]> Sergey Matveev's repositories - public-inbox.git/blob - t/httpd-corner.t
http: reject excessive headers
[public-inbox.git] / t / httpd-corner.t
1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # note: our HTTP server should be standalone and capable of running
4 # generic Rack apps.
5 use strict;
6 use warnings;
7 use Test::More;
8
9 foreach my $mod (qw(Plack::Util Plack::Request Plack::Builder Danga::Socket
10                         HTTP::Parser::XS HTTP::Date HTTP::Status)) {
11         eval "require $mod";
12         plan skip_all => "$mod missing for httpd-corner.t" if $@;
13 }
14
15 use Digest::SHA qw(sha1_hex);
16 use File::Temp qw/tempdir/;
17 use Cwd qw/getcwd/;
18 use IO::Socket;
19 use IO::Socket::UNIX;
20 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
21 use Socket qw(SO_KEEPALIVE IPPROTO_TCP TCP_NODELAY);
22 use POSIX qw(dup2 mkfifo :sys_wait_h);
23 my $tmpdir = tempdir('httpd-corner-XXXXXX', TMPDIR => 1, CLEANUP => 1);
24 my $fifo = "$tmpdir/fifo";
25 ok(defined mkfifo($fifo, 0777), 'created FIFO');
26 my $err = "$tmpdir/stderr.log";
27 my $out = "$tmpdir/stdout.log";
28 my $httpd = 'blib/script/public-inbox-httpd';
29 my $psgi = getcwd()."/t/httpd-corner.psgi";
30 my %opts = (
31         LocalAddr => '127.0.0.1',
32         ReuseAddr => 1,
33         Proto => 'tcp',
34         Type => SOCK_STREAM,
35         Listen => 1024,
36 );
37 my $sock = IO::Socket::INET->new(%opts);
38 my $upath = "$tmpdir/s";
39 my $unix = IO::Socket::UNIX->new(
40         Listen => 1024,
41         Type => SOCK_STREAM,
42         Local => $upath
43 );
44 ok($unix, 'UNIX socket created');
45 my $pid;
46 END { kill 'TERM', $pid if defined $pid };
47 my $spawn_httpd = sub {
48         my (@args) = @_;
49         $! = 0;
50         my $fl = fcntl($sock, F_GETFD, 0);
51         ok(! $!, 'no error from fcntl(F_GETFD)');
52         is($fl, FD_CLOEXEC, 'cloexec set by default (Perl behavior)');
53         $pid = fork;
54         if ($pid == 0) {
55                 # pretend to be systemd
56                 dup2(fileno($sock), 3) or die "dup2 failed: $!\n";
57                 dup2(fileno($unix), 4) or die "dup2 failed: $!\n";
58                 my $t = IO::Handle->new_from_fd(3, 'r');
59                 $t->fcntl(F_SETFD, 0);
60                 my $u = IO::Handle->new_from_fd(4, 'r');
61                 $u->fcntl(F_SETFD, 0);
62                 $ENV{LISTEN_PID} = $$;
63                 $ENV{LISTEN_FDS} = 2;
64                 exec $httpd, @args, "--stdout=$out", "--stderr=$err", $psgi;
65                 die "FAIL: $!\n";
66         }
67         ok(defined $pid, 'forked httpd process successfully');
68 };
69
70 {
71         ok($sock, 'sock created');
72         $! = 0;
73         my $fl = fcntl($sock, F_GETFD, 0);
74         ok(! $!, 'no error from fcntl(F_GETFD)');
75         is($fl, FD_CLOEXEC, 'cloexec set by default (Perl behavior)');
76         $spawn_httpd->('-W0');
77 }
78
79 {
80         my $conn = conn_for($sock, 'streaming callback');
81         $conn->write("GET /callback HTTP/1.0\r\n\r\n");
82         ok($conn->read(my $buf, 8192), 'read response');
83         my ($head, $body) = split(/\r\n\r\n/, $buf);
84         is($body, "hello world\n", 'callback body matches expected');
85 }
86
87 {
88         my $conn = conn_for($sock, 'excessive header');
89         $SIG{PIPE} = 'IGNORE';
90         $conn->write("GET /callback HTTP/1.0\r\n");
91         foreach my $i (1..500000) {
92                 last unless $conn->write("X-xxxxxJunk-$i: omg\r\n");
93         }
94         ok(!$conn->write("\r\n"), 'broken request');
95         ok($conn->read(my $buf, 8192), 'read response');
96         my ($head, $body) = split(/\r\n\r\n/, $buf);
97         like($head, qr/\b400\b/, 'got 400 response');
98 }
99
100 # Unix domain sockets
101 {
102         my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
103         ok($u, 'unix socket connected');
104         $u->write("GET /host-port HTTP/1.0\r\n\r\n");
105         $u->read(my $buf, 4096);
106         like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
107                 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
108 }
109
110 sub conn_for {
111         my ($sock, $msg) = @_;
112         my $conn = IO::Socket::INET->new(
113                                 PeerAddr => $sock->sockhost,
114                                 PeerPort => $sock->sockport,
115                                 Proto => 'tcp',
116                                 Type => SOCK_STREAM);
117         ok($conn, "connected for $msg");
118         $conn->autoflush(1);
119         setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
120         return $conn;
121 }
122
123 {
124         my $conn = conn_for($sock, 'host-port');
125         $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
126         $conn->read(my $buf, 4096);
127         my ($head, $body) = split(/\r\n\r\n/, $buf);
128         my ($addr, $port) = split(/:/, $body);
129         is($addr, $conn->sockhost, 'host matches addr');
130         is($port, $conn->sockport, 'port matches');
131 }
132
133 # graceful termination
134 {
135         my $conn = conn_for($sock, 'graceful termination via slow header');
136         $conn->write("GET /slow-header HTTP/1.0\r\n" .
137                         "X-Check-Fifo: $fifo\r\n\r\n");
138         open my $f, '>', $fifo or die "open $fifo: $!\n";
139         $f->autoflush(1);
140         ok(print($f "hello\n"), 'wrote something to fifo');
141         my $kpid = $pid;
142         $pid = undef;
143         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
144         ok(print($f "world\n"), 'wrote else to fifo');
145         close $f or die "close fifo: $!\n";
146         $conn->read(my $buf, 8192);
147         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
148         like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
149         is($body, "hello\nworld\n", 'read expected body');
150         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
151         is($?, 0, 'no error');
152         $spawn_httpd->('-W0');
153 }
154
155 {
156         my $conn = conn_for($sock, 'graceful termination via slow-body');
157         $conn->write("GET /slow-body HTTP/1.0\r\n" .
158                         "X-Check-Fifo: $fifo\r\n\r\n");
159         open my $f, '>', $fifo or die "open $fifo: $!\n";
160         $f->autoflush(1);
161         my $buf;
162         $conn->sysread($buf, 8192);
163         like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
164         like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
165
166         foreach my $c ('a'..'c') {
167                 $c .= "\n";
168                 ok(print($f $c), 'wrote line to fifo');
169                 $conn->sysread($buf, 8192);
170                 is($buf, $c, 'got trickle for reading');
171         }
172         my $kpid = $pid;
173         $pid = undef;
174         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
175         ok(print($f "world\n"), 'wrote else to fifo');
176         close $f or die "close fifo: $!\n";
177         $conn->sysread($buf, 8192);
178         is($buf, "world\n", 'read expected body');
179         is($conn->sysread($buf, 8192), 0, 'got EOF from server');
180         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
181         is($?, 0, 'no error');
182         $spawn_httpd->('-W0');
183 }
184
185 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
186
187 my $str = 'abcdefghijklmnopqrstuvwxyz';
188 my $len = length $str;
189 is($len, 26, 'got the alphabet');
190 my $check_self = sub {
191         my ($conn) = @_;
192         $conn->read(my $buf, 4096);
193         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
194         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
195         is($body, sha1_hex($str), 'read expected body');
196 };
197
198 SKIP: {
199         use POSIX qw(dup2);
200         use IO::File;
201         my $have_curl = 0;
202         foreach my $p (split(':', $ENV{PATH})) {
203                 -x "$p/curl" or next;
204                 $have_curl = 1;
205                 last;
206         }
207         my $ntest = 2;
208         $have_curl or skip('curl(1) missing', $ntest);
209         my $url = 'http://' . $sock->sockhost . ':' . $sock->sockport . '/sha1';
210         my ($r, $w);
211         pipe($r, $w) or die "pipe: $!";
212         my $tout = IO::File->new_tmpfile or die "new_tmpfile: $!";
213         my $pid = fork;
214         defined $pid or die "fork: $!";
215         my @cmd = (qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url);
216         if ($pid == 0) {
217                 dup2(fileno($r), 0) or die "redirect stdin failed: $!\n";
218                 dup2(fileno($tout), 1) or die "redirect stdout failed: $!\n";
219                 exec(@cmd) or die 'exec `' . join(' '). "' failed: $!\n";
220         }
221         $w->autoflush(1);
222         foreach my $c ('a'..'z') {
223                 print $w $c or die "failed to write to curl: $!";
224                 delay();
225         }
226         close $w or die "close write pipe: $!";
227         close $r or die "close read pipe: $!";
228         my $kid = waitpid $pid, 0;
229         is($?, 0, 'curl exited successfully');
230         $tout->sysseek(0, SEEK_SET);
231         $tout->sysread(my $buf, 100);
232         is($buf, sha1_hex($str), 'read expected body');
233 }
234
235 {
236         my $conn = conn_for($sock, '1.1 pipeline together');
237         $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
238                         "PUT /sha1 HTTP/1.1\r\n\r\n");
239         my $buf = '';
240         my @r;
241         until (scalar(@r) >= 2) {
242                 my $r = $conn->sysread(my $tmp, 4096);
243                 die $! unless defined $r;
244                 die "EOF <$buf>" unless $r;
245                 $buf .= $tmp;
246                 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
247         }
248         is(2, scalar @r, 'got 2 responses');
249         my $i = 3;
250         foreach my $hex (@r) {
251                 is($hex, sha1_hex(''), "read expected body $i");
252                 $i++;
253         }
254 }
255
256 {
257         my $conn = conn_for($sock, 'graceful termination during slow request');
258         $conn->write("PUT /sha1 HTTP/1.0\r\n");
259         delay();
260         $conn->write("Content-Length: $len\r\n");
261         delay();
262         $conn->write("\r\n");
263         my $kpid = $pid;
264         $pid = undef;
265         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
266         delay();
267         my $n = 0;
268         foreach my $c ('a'..'z') {
269                 $n += $conn->write($c);
270         }
271         is($n, $len, 'wrote alphabet');
272         $check_self->($conn);
273         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
274         is($?, 0, 'no error');
275         $spawn_httpd->('-W0');
276 }
277
278 # various DoS attacks against the chunk parser:
279 {
280         local $SIG{PIPE} = 'IGNORE';
281         my $conn = conn_for($sock, '1.1 chunk header excessive');
282         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
283         my $n = 0;
284         my $w;
285         while ($w = $conn->write('ffffffff')) {
286                 $n += $w;
287         }
288         ok($!, 'got error set in $!');
289         is($w, undef, 'write error happened');
290         ok($n > 0, 'was able to write');
291         my $r = $conn->read(my $buf, 66666);
292         ok($r > 0, 'got non-empty response');
293         like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
294
295         $conn = conn_for($sock, '1.1 chunk trailer excessive');
296         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
297         is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
298         delay();
299         $n = 0;
300         while ($w = $conn->write("\r")) {
301                 $n += $w;
302         }
303         ok($!, 'got error set in $!');
304         ok($n > 0, 'wrote part of chunk end (\r)');
305         $r = $conn->read($buf, 66666);
306         ok($r > 0, 'got non-empty response');
307         like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
308 }
309
310 {
311         my $conn = conn_for($sock, '1.1 chunked close trickle');
312         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
313         $conn->write("Transfer-encoding: chunked\r\n\r\n");
314         foreach my $x ('a'..'z') {
315                 delay();
316                 $conn->write('1');
317                 delay();
318                 $conn->write("\r");
319                 delay();
320                 $conn->write("\n");
321                 delay();
322                 $conn->write($x);
323                 delay();
324                 $conn->write("\r");
325                 delay();
326                 $conn->write("\n");
327         }
328         $conn->write('0');
329         delay();
330         $conn->write("\r");
331         delay();
332         $conn->write("\n");
333         delay();
334         $conn->write("\r");
335         delay();
336         $conn->write("\n");
337         delay();
338         $check_self->($conn);
339 }
340
341 {
342         my $conn = conn_for($sock, '1.1 chunked close');
343         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
344         my $xlen = sprintf('%x', $len);
345         $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
346                 "$str\r\n0\r\n\r\n");
347         $check_self->($conn);
348 }
349
350 {
351         my $conn = conn_for($sock, 'chunked body + pipeline');
352         $conn->write("PUT /sha1 HTTP/1.1\r\n" .
353                         "Transfer-Encoding: chunked\r\n");
354         delay();
355         $conn->write("\r\n1\r\n");
356         delay();
357         $conn->write('a');
358         delay();
359         $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
360         delay();
361
362         my $buf = '';
363         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
364                 $conn->sysread(my $tmp, 4096);
365                 $buf .= $tmp;
366         }
367         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
368         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
369         is($body, sha1_hex('a'), 'read expected body');
370
371         $conn->write("Connection: close\r\n");
372         $conn->write("Content-Length: $len\r\n\r\n$str");
373         $check_self->($conn);
374 }
375
376 {
377         my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
378         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
379                         "Connection: keep-alive\r\n");
380         delay();
381         $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
382         my $buf = '';
383         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
384                 $conn->sysread(my $tmp, 4096);
385                 $buf .= $tmp;
386         }
387         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
388         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
389         is($body, sha1_hex($str), 'read expected body');
390
391         $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
392         $check_self->($conn);
393 }
394
395 {
396         my $conn = conn_for($sock, 'trickle body');
397         $conn->write("PUT /sha1 HTTP/1.0\r\n");
398         $conn->write("Content-Length: $len\r\n\r\n");
399         my $beg = substr($str, 0, 10);
400         my $end = substr($str, 10);
401         is($beg . $end, $str, 'substr setup correct');
402         delay();
403         $conn->write($beg);
404         delay();
405         $conn->write($end);
406         $check_self->($conn);
407 }
408
409 {
410         my $conn = conn_for($sock, 'one-shot write');
411         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
412                         "Content-Length: $len\r\n\r\n$str");
413         $check_self->($conn);
414 }
415
416 {
417         my $conn = conn_for($sock, 'trickle header, one-shot body');
418         $conn->write("PUT /sha1 HTTP/1.0\r\n");
419         delay();
420         $conn->write("Content-Length: $len\r\n\r\n$str");
421         $check_self->($conn);
422 }
423
424 {
425         my $conn = conn_for($sock, '1.1 Connnection: close');
426         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
427         delay();
428         $conn->write("Content-Length: $len\r\n\r\n$str");
429         $check_self->($conn);
430 }
431
432 {
433         my $conn = conn_for($sock, '1.1 pipeline start');
434         $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
435         my $buf = '';
436         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
437                 $conn->sysread(my $tmp, 4096);
438                 $buf .= $tmp;
439         }
440         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
441         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
442         is($body, sha1_hex(''), 'read expected body');
443
444         # 2nd request
445         $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
446         $buf = '';
447         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
448                 $conn->sysread(my $tmp, 4096);
449                 $buf .= $tmp;
450         }
451         ($head, $body) = split(/\r\n\r\n/, $buf, 2);
452         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
453         is($body, sha1_hex(''), 'read expected body #2');
454 }
455
456 done_testing();
457
458 1;