]> Sergey Matveev's repositories - public-inbox.git/blob - t/nntpd-tls.t
t/nntpd-tls: sometimes SSL_connect succeeds quickly
[public-inbox.git] / t / nntpd-tls.t
1 # Copyright (C) 2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 use strict;
4 use warnings;
5 use Test::More;
6 use File::Temp qw(tempdir);
7 use Socket qw(SOCK_STREAM IPPROTO_TCP SOL_SOCKET);
8 # IO::Poll and Net::NNTP are part of the standard library, but
9 # distros may split them off...
10 foreach my $mod (qw(DBD::SQLite IO::Socket::SSL Net::NNTP IO::Poll)) {
11         eval "require $mod";
12         plan skip_all => "$mod missing for $0" if $@;
13 }
14 Net::NNTP->can('starttls') or
15         plan skip_all => 'Net::NNTP does not support TLS';
16 IO::Socket::SSL->VERSION(2.007) or
17         plan skip_all => 'IO::Socket::SSL <2.007 not supported by Net::NNTP';
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
26 use_ok 'PublicInbox::TLS';
27 use_ok 'IO::Socket::SSL';
28 require './t/common.perl';
29 require PublicInbox::InboxWritable;
30 require PublicInbox::MIME;
31 require PublicInbox::SearchIdx;
32 my $need_zlib;
33 eval { require Compress::Raw::Zlib } or
34         $need_zlib = 'Compress::Raw::Zlib missing';
35 my $version = 2; # v2 needs newer git
36 require_git('2.6') if $version >= 2;
37 my $tmpdir = tempdir('pi-nntpd-tls-XXXXXX', TMPDIR => 1, CLEANUP => 1);
38 my $err = "$tmpdir/stderr.log";
39 my $out = "$tmpdir/stdout.log";
40 my $inboxdir = "$tmpdir";
41 my $pi_config = "$tmpdir/pi_config";
42 my $group = 'test-nntpd-tls';
43 my $addr = $group . '@example.com';
44 my $nntpd = 'blib/script/public-inbox-nntpd';
45 my $starttls = tcp_server();
46 my $nntps = tcp_server();
47 my ($pid, $tail_pid);
48 END {
49         foreach ($pid, $tail_pid) {
50                 kill 'TERM', $_ if defined $_;
51         }
52 };
53
54 my $ibx = PublicInbox::Inbox->new({
55         inboxdir => $inboxdir,
56         name => 'nntpd-tls',
57         version => $version,
58         -primary_address => $addr,
59         indexlevel => 'basic',
60 });
61 $ibx = PublicInbox::InboxWritable->new($ibx, {nproc=>1});
62 $ibx->init_inbox(0);
63 {
64         open my $fh, '>', $pi_config or die "open: $!\n";
65         print $fh <<EOF
66 [publicinbox "nntpd-tls"]
67         inboxdir = $inboxdir
68         address = $addr
69         indexlevel = basic
70         newsgroup = $group
71 EOF
72         ;
73         close $fh or die "close: $!\n";
74 }
75
76 {
77         my $im = $ibx->importer(0);
78         my $mime = PublicInbox::MIME->new(do {
79                 open my $fh, '<', 't/data/0001.patch' or die;
80                 local $/;
81                 <$fh>
82         });
83         ok($im->add($mime), 'message added');
84         $im->done;
85         if ($version == 1) {
86                 my $s = PublicInbox::SearchIdx->new($ibx, 1);
87                 $s->index_sync;
88         }
89 }
90
91 my $nntps_addr = $nntps->sockhost . ':' . $nntps->sockport;
92 my $starttls_addr = $starttls->sockhost . ':' . $starttls->sockport;
93 my $env = { PI_CONFIG => $pi_config };
94
95 for my $args (
96         [ "--cert=$cert", "--key=$key",
97                 "-lnntps://$nntps_addr",
98                 "-lnntp://$starttls_addr" ],
99 ) {
100         for ($out, $err) {
101                 open my $fh, '>', $_ or die "truncate: $!";
102         }
103         if (my $tail_cmd = $ENV{TAIL}) { # don't assume GNU tail
104                 $tail_pid = fork;
105                 if (defined $tail_pid && $tail_pid == 0) {
106                         exec(split(' ', $tail_cmd), $out, $err);
107                 }
108         }
109         my $cmd = [ $nntpd, '-W0', @$args, "--stdout=$out", "--stderr=$err" ];
110         $pid = spawn_listener($env, $cmd, [ $starttls, $nntps ]);
111         my %o = (
112                 SSL_hostname => 'server.local',
113                 SSL_verifycn_name => 'server.local',
114                 SSL_verify_mode => SSL_VERIFY_PEER(),
115                 SSL_ca_file => 'certs/test-ca.pem',
116         );
117         my $expect = { $group => [qw(1 1 n)] };
118
119         # start negotiating a slow TLS connection
120         my $slow = tcp_connect($nntps, Blocking => 0);
121         $slow = IO::Socket::SSL->start_SSL($slow, SSL_startHandshake => 0, %o);
122         my $slow_done = $slow->connect_SSL;
123         my @poll;
124         if ($slow_done) {
125                 diag('W: connect_SSL early OK, slow client test invalid');
126                 use PublicInbox::Syscall qw(EPOLLIN EPOLLOUT);
127                 @poll = (fileno($slow), EPOLLIN | EPOLLOUT);
128         } else {
129                 @poll = (fileno($slow), PublicInbox::TLS::epollbit());
130         }
131         # we should call connect_SSL much later...
132
133         # NNTPS
134         my $c = Net::NNTP->new($nntps_addr, %o, SSL => 1);
135         my $list = $c->list;
136         is_deeply($list, $expect, 'NNTPS LIST works');
137         unlike(get_capa($c), qr/\bSTARTTLS\r\n/,
138                 'STARTTLS not advertised for NNTPS');
139         is($c->command('QUIT')->response(), Net::Cmd::CMD_OK(), 'QUIT works');
140         is(0, sysread($c, my $buf, 1), 'got EOF after QUIT');
141
142         # STARTTLS
143         $c = Net::NNTP->new($starttls_addr, %o);
144         $list = $c->list;
145         is_deeply($list, $expect, 'plain LIST works');
146         ok($c->starttls, 'STARTTLS succeeds');
147         is($c->code, 382, 'got 382 for STARTTLS');
148         $list = $c->list;
149         is_deeply($list, $expect, 'LIST works after STARTTLS');
150         unlike(get_capa($c), qr/\bSTARTTLS\r\n/,
151                 'STARTTLS not advertised after STARTTLS');
152
153         # Net::NNTP won't let us do dumb things, but we need to test
154         # dumb things, so use Net::Cmd directly:
155         my $n = $c->command('STARTTLS')->response();
156         is($n, Net::Cmd::CMD_ERROR(), 'error attempting STARTTLS again');
157         is($c->code, 502, '502 according to RFC 4642 sec#2.2.1');
158
159         # STARTTLS with bad hostname
160         $o{SSL_hostname} = $o{SSL_verifycn_name} = 'server.invalid';
161         $c = Net::NNTP->new($starttls_addr, %o);
162         like(get_capa($c), qr/\bSTARTTLS\r\n/, 'STARTTLS advertised');
163         $list = $c->list;
164         is_deeply($list, $expect, 'plain LIST works again');
165         ok(!$c->starttls, 'STARTTLS fails with bad hostname');
166         $c = Net::NNTP->new($starttls_addr, %o);
167         $list = $c->list;
168         is_deeply($list, $expect, 'not broken after bad negotiation');
169
170         # NNTPS with bad hostname
171         $c = Net::NNTP->new($nntps_addr, %o, SSL => 1);
172         is($c, undef, 'NNTPS fails with bad hostname');
173         $o{SSL_hostname} = $o{SSL_verifycn_name} = 'server.local';
174         $c = Net::NNTP->new($nntps_addr, %o, SSL => 1);
175         ok($c, 'NNTPS succeeds again with valid hostname');
176
177         # slow TLS connection did not block the other fast clients while
178         # connecting, finish it off:
179         until ($slow_done) {
180                 IO::Poll::_poll(-1, @poll);
181                 $slow_done = $slow->connect_SSL and last;
182                 @poll = (fileno($slow), PublicInbox::TLS::epollbit());
183         }
184         $slow->blocking(1);
185         ok(sysread($slow, my $greet, 4096) > 0, 'slow got greeting');
186         like($greet, qr/\A201 /, 'got expected greeting');
187         is(syswrite($slow, "QUIT\r\n"), 6, 'slow wrote QUIT');
188         ok(sysread($slow, my $end, 4096) > 0, 'got EOF');
189         is(sysread($slow, my $eof, 4096), 0, 'got EOF');
190         $slow = undef;
191
192         SKIP: {
193                 skip 'TCP_DEFER_ACCEPT is Linux-only', 2 if $^O ne 'linux';
194                 my $var = Socket::TCP_DEFER_ACCEPT();
195                 defined(my $x = getsockopt($nntps, IPPROTO_TCP, $var)) or die;
196                 ok(unpack('i', $x) > 0, 'TCP_DEFER_ACCEPT set on NNTPS');
197                 defined($x = getsockopt($starttls, IPPROTO_TCP, $var)) or die;
198                 is(unpack('i', $x), 0, 'TCP_DEFER_ACCEPT is 0 on plain NNTP');
199         };
200         SKIP: {
201                 skip 'SO_ACCEPTFILTER is FreeBSD-only', 2 if $^O ne 'freebsd';
202                 if (system('kldstat -m accf_data >/dev/null')) {
203                         skip 'accf_data not loaded? kldload accf_data', 2;
204                 }
205                 require PublicInbox::Daemon;
206                 my $var = PublicInbox::Daemon::SO_ACCEPTFILTER();
207                 my $x = getsockopt($nntps, SOL_SOCKET, $var);
208                 like($x, qr/\Adataready\0+\z/, 'got dataready accf for NNTPS');
209                 $x = getsockopt($starttls, IPPROTO_TCP, $var);
210                 is($x, undef, 'no BSD accept filter for plain NNTP');
211         };
212
213         $c = undef;
214         kill('TERM', $pid);
215         is($pid, waitpid($pid, 0), 'nntpd exited successfully');
216         is($?, 0, 'no error in exited process');
217         $pid = undef;
218         my $eout = eval {
219                 open my $fh, '<', $err or die "open $err failed: $!";
220                 local $/;
221                 <$fh>;
222         };
223         unlike($eout, qr/wide/i, 'no Wide character warnings');
224         if (defined $tail_pid) {
225                 kill 'TERM', $tail_pid;
226                 waitpid($tail_pid, 0);
227                 $tail_pid = undef;
228         }
229 }
230 done_testing();
231
232 sub get_capa {
233         my ($sock) = @_;
234         syswrite($sock, "CAPABILITIES\r\n");
235         my $capa = '';
236         do {
237                 my $r = sysread($sock, $capa, 8192, length($capa));
238                 die "unexpected: $!" unless defined($r);
239                 die 'unexpected EOF' if $r == 0;
240         } until $capa =~ /\.\r\n\z/;
241
242         my $deflate_capa = qr/\r\nCOMPRESS DEFLATE\r\n/;
243         if ($need_zlib) {
244                 unlike($capa, $deflate_capa,
245                         'COMPRESS DEFLATE NOT advertised '.$need_zlib);
246         } else {
247                 like($capa, $deflate_capa, 'COMPRESS DEFLATE advertised');
248         }
249         $capa;
250 }
251
252 1;