]> Sergey Matveev's repositories - public-inbox.git/blob - t/imapd-tls.t
No ext_urls
[public-inbox.git] / t / imapd-tls.t
1 #!perl -w
2 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 use strict;
5 use v5.10.1;
6 use Socket qw(IPPROTO_TCP SOL_SOCKET);
7 use PublicInbox::TestCommon;
8 # IO::Poll is part of the standard library, but distros may split it off...
9 require_mods(qw(-imapd IO::Socket::SSL Mail::IMAPClient IO::Poll));
10 my $imap_client = 'Mail::IMAPClient';
11 $imap_client->can('starttls') or
12         plan skip_all => 'Mail::IMAPClient does not support TLS';
13 my $can_compress = $imap_client->can('compress');
14 if ($can_compress) { # hope this gets fixed upstream, soon
15         require PublicInbox::IMAPClient;
16         $imap_client = 'PublicInbox::IMAPClient';
17 }
18
19 my $cert = 'certs/server-cert.pem';
20 my $key = 'certs/server-key.pem';
21 unless (-r $key && -r $cert) {
22         plan skip_all =>
23                 "certs/ missing for $0, run $^X ./create-certs.perl in certs/";
24 }
25 use_ok 'PublicInbox::TLS';
26 use_ok 'IO::Socket::SSL';
27 my $version = 1; # v2 needs newer git
28 require_git('2.6') if $version >= 2;
29 my ($tmpdir, $for_destroy) = tmpdir();
30 my $err = "$tmpdir/stderr.log";
31 my $out = "$tmpdir/stdout.log";
32 my $pi_config;
33 my $group = 'test-imapd-tls';
34 my $addr = $group . '@example.com';
35 my $starttls = tcp_server();
36 my $imaps = tcp_server();
37 my $ibx = create_inbox 'imapd-tls', version => $version,
38                         -primary_address => $addr, indexlevel => 'basic', sub {
39         my ($im, $ibx) = @_;
40         $im->add(eml_load('t/data/0001.patch')) or BAIL_OUT '->add';
41         $pi_config = "$ibx->{inboxdir}/pi_config";
42         open my $fh, '>', $pi_config or BAIL_OUT "open: $!";
43         print $fh <<EOF or BAIL_OUT "print: $!";
44 [publicinbox "imapd-tls"]
45         inboxdir = $ibx->{inboxdir}
46         address = $addr
47         indexlevel = basic
48         newsgroup = $group
49 EOF
50         close $fh or BAIL_OUT "close: $!\n";
51 };
52 $pi_config //= "$ibx->{inboxdir}/pi_config";
53
54 my $imaps_addr = tcp_host_port($imaps);
55 my $starttls_addr = tcp_host_port($starttls);
56 my $env = { PI_CONFIG => $pi_config };
57 my $td;
58
59 for my $args (
60         [ "--cert=$cert", "--key=$key",
61                 "-limaps://$imaps_addr",
62                 "-limap://$starttls_addr" ],
63 ) {
64         for ($out, $err) {
65                 open my $fh, '>', $_ or BAIL_OUT "truncate: $!";
66         }
67         my $cmd = [ '-imapd', '-W0', @$args, "--stdout=$out", "--stderr=$err" ];
68         $td = start_script($cmd, $env, { 3 => $starttls, 4 => $imaps });
69         my %o = (
70                 SSL_hostname => 'server.local',
71                 SSL_verifycn_name => 'server.local',
72                 SSL_verify_mode => SSL_VERIFY_PEER(),
73                 SSL_ca_file => 'certs/test-ca.pem',
74         );
75         # start negotiating a slow TLS connection
76         my $slow = tcp_connect($imaps, Blocking => 0);
77         $slow = IO::Socket::SSL->start_SSL($slow, SSL_startHandshake => 0, %o);
78         my $slow_done = $slow->connect_SSL;
79         my @poll;
80         if ($slow_done) {
81                 diag('W: connect_SSL early OK, slow client test invalid');
82                 use PublicInbox::Syscall qw(EPOLLIN EPOLLOUT);
83                 @poll = (fileno($slow), EPOLLIN | EPOLLOUT);
84         } else {
85                 @poll = (fileno($slow), PublicInbox::TLS::epollbit());
86         }
87         # we should call connect_SSL much later...
88         my %imaps_opt = (User => 'a', Password => 'b',
89                         Server => $imaps->sockhost,
90                         Port => $imaps->sockport);
91         # IMAPS
92         my $c = $imap_client->new(%imaps_opt, Ssl => [ %o ]);
93         ok($c && $c->IsAuthenticated, 'authenticated');
94         ok($c->select($group), 'SELECT works');
95         ok(!(scalar $c->has_capability('STARTTLS')),
96                 'starttls not advertised with IMAPS');
97         ok(!$c->starttls, "starttls fails");
98         ok($c->has_capability('COMPRESS') ||
99                 $c->has_capability('COMPRESS=DEFLATE'),
100                 'compress advertised');
101         ok($c->compress, 'compression enabled with IMAPS');
102         ok(!$c->starttls, 'starttls still fails');
103         ok($c->noop, 'noop succeeds');
104         ok($c->logout, 'logout succeeds');
105
106         # STARTTLS
107         my %imap_opt = (Server => $starttls->sockhost,
108                         Port => $starttls->sockport);
109         $c = $imap_client->new(%imap_opt);
110         ok(scalar $c->has_capability('STARTTLS'),
111                 'starttls advertised');
112         ok($c->Starttls([ %o ]), 'set starttls options');
113         ok($c->starttls, '->starttls works');
114         ok(!(scalar($c->has_capability('STARTTLS'))),
115                 'starttls not advertised');
116         ok(!$c->starttls, '->starttls again fails');
117         ok(!(scalar($c->has_capability('STARTTLS'))),
118                 'starttls still not advertised');
119         ok($c->examine($group), 'EXAMINE works');
120         ok($c->noop, 'NOOP works');
121         ok($c->compress, 'compression enabled with IMAPS');
122         ok($c->noop, 'NOOP works after compress');
123         ok($c->logout, 'logout succeeds after compress');
124
125         # STARTTLS with bad hostname
126         $o{SSL_hostname} = $o{SSL_verifycn_name} = 'server.invalid';
127         $c = $imap_client->new(%imap_opt);
128         ok(scalar $c->has_capability('STARTTLS'), 'starttls advertised');
129         ok($c->Starttls([ %o ]), 'set starttls options');
130         ok(!$c->starttls, '->starttls fails with bad hostname');
131
132         $c = $imap_client->new(%imap_opt);
133         ok($c->noop, 'NOOP still works from plain IMAP');
134
135         # IMAPS with bad hostname
136         $c = $imap_client->new(%imaps_opt, Ssl => [ %o ]);
137         is($c, undef, 'IMAPS fails with bad hostname');
138
139         # make hostname valid
140         $o{SSL_hostname} = $o{SSL_verifycn_name} = 'server.local';
141         $c = $imap_client->new(%imaps_opt, Ssl => [ %o ]);
142         ok($c, 'IMAPS succeeds again with valid hostname');
143
144         # slow TLS connection did not block the other fast clients while
145         # connecting, finish it off:
146         until ($slow_done) {
147                 IO::Poll::_poll(-1, @poll);
148                 $slow_done = $slow->connect_SSL and last;
149                 @poll = (fileno($slow), PublicInbox::TLS::epollbit());
150         }
151         $slow->blocking(1);
152         ok(sysread($slow, my $greet, 4096) > 0, 'slow got a greeting');
153         like($greet, qr/\A\* OK \[CAPABILITY IMAP4rev1 /, 'got greeting');
154         is(syswrite($slow, "1 LOGOUT\r\n"), 10, 'slow wrote LOGOUT');
155         ok(sysread($slow, my $end, 4096) > 0, 'got end');
156         is(sysread($slow, my $eof, 4096), 0, 'got EOF');
157
158         test_lei(sub {
159                 lei_ok qw(ls-mail-source), "imap://$starttls_addr",
160                         \'STARTTLS not used by default';
161                 ok(!lei(qw(ls-mail-source -c imap.starttls=true),
162                         "imap://$starttls_addr"), 'STARTTLS verify fails');
163         });
164
165         SKIP: {
166                 skip 'TCP_DEFER_ACCEPT is Linux-only', 2 if $^O ne 'linux';
167                 my $var = eval { Socket::TCP_DEFER_ACCEPT() } // 9;
168                 defined(my $x = getsockopt($imaps, IPPROTO_TCP, $var)) or die;
169                 ok(unpack('i', $x) > 0, 'TCP_DEFER_ACCEPT set on IMAPS');
170                 defined($x = getsockopt($starttls, IPPROTO_TCP, $var)) or die;
171                 is(unpack('i', $x), 0, 'TCP_DEFER_ACCEPT is 0 on plain IMAP');
172         };
173         SKIP: {
174                 skip 'SO_ACCEPTFILTER is FreeBSD-only', 2 if $^O ne 'freebsd';
175                 if (system('kldstat -m accf_data >/dev/null')) {
176                         skip 'accf_data not loaded? kldload accf_data', 2;
177                 }
178                 require PublicInbox::Daemon;
179                 my $x = getsockopt($imaps, SOL_SOCKET,
180                                 $PublicInbox::Daemon::SO_ACCEPTFILTER);
181                 like($x, qr/\Adataready\0+\z/, 'got dataready accf for IMAPS');
182                 $x = getsockopt($starttls, IPPROTO_TCP,
183                                 $PublicInbox::Daemon::SO_ACCEPTFILTER);
184                 is($x, undef, 'no BSD accept filter for plain IMAP');
185         };
186
187         $c = undef;
188         $td->kill;
189         $td->join;
190         is($?, 0, 'no error in exited process');
191         open my $fh, '<', $err or BAIL_OUT "open $err failed: $!";
192         my $eout = do { local $/; <$fh> };
193         unlike($eout, qr/wide/i, 'no Wide character warnings');
194 }
195
196 done_testing;