]> Sergey Matveev's repositories - public-inbox.git/blob - t/httpd-corner.t
http: reject excessively large HTTP request bodies
[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 {
101         my $conn = conn_for($sock, 'excessive body Content-Length');
102         $SIG{PIPE} = 'IGNORE';
103         my $n = (10 * 1024 * 1024) + 1;
104         $conn->write("PUT /sha1 HTTP/1.0\r\nContent-Length: $n\r\n\r\n");
105         ok($conn->read(my $buf, 8192), 'read response');
106         my ($head, $body) = split(/\r\n\r\n/, $buf);
107         like($head, qr/\b413\b/, 'got 413 response');
108 }
109
110 {
111         my $conn = conn_for($sock, 'excessive body chunked');
112         $SIG{PIPE} = 'IGNORE';
113         my $n = (10 * 1024 * 1024) + 1;
114         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n");
115         $conn->write("\r\n".sprintf("%x\r\n", $n));
116         ok($conn->read(my $buf, 8192), 'read response');
117         my ($head, $body) = split(/\r\n\r\n/, $buf);
118         like($head, qr/\b413\b/, 'got 413 response');
119 }
120
121 # Unix domain sockets
122 {
123         my $u = IO::Socket::UNIX->new(Type => SOCK_STREAM, Peer => $upath);
124         ok($u, 'unix socket connected');
125         $u->write("GET /host-port HTTP/1.0\r\n\r\n");
126         $u->read(my $buf, 4096);
127         like($buf, qr!\r\n\r\n127\.0\.0\.1:0\z!,
128                 'set REMOTE_ADDR and REMOTE_PORT for Unix socket');
129 }
130
131 sub conn_for {
132         my ($sock, $msg) = @_;
133         my $conn = IO::Socket::INET->new(
134                                 PeerAddr => $sock->sockhost,
135                                 PeerPort => $sock->sockport,
136                                 Proto => 'tcp',
137                                 Type => SOCK_STREAM);
138         ok($conn, "connected for $msg");
139         $conn->autoflush(1);
140         setsockopt($conn, IPPROTO_TCP, TCP_NODELAY, 1);
141         return $conn;
142 }
143
144 {
145         my $conn = conn_for($sock, 'host-port');
146         $conn->write("GET /host-port HTTP/1.0\r\n\r\n");
147         $conn->read(my $buf, 4096);
148         my ($head, $body) = split(/\r\n\r\n/, $buf);
149         my ($addr, $port) = split(/:/, $body);
150         is($addr, $conn->sockhost, 'host matches addr');
151         is($port, $conn->sockport, 'port matches');
152 }
153
154 # graceful termination
155 {
156         my $conn = conn_for($sock, 'graceful termination via slow header');
157         $conn->write("GET /slow-header 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         ok(print($f "hello\n"), 'wrote something to fifo');
162         my $kpid = $pid;
163         $pid = undef;
164         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
165         ok(print($f "world\n"), 'wrote else to fifo');
166         close $f or die "close fifo: $!\n";
167         $conn->read(my $buf, 8192);
168         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
169         like($head, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-header');
170         is($body, "hello\nworld\n", 'read expected body');
171         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
172         is($?, 0, 'no error');
173         $spawn_httpd->('-W0');
174 }
175
176 {
177         my $conn = conn_for($sock, 'graceful termination via slow-body');
178         $conn->write("GET /slow-body HTTP/1.0\r\n" .
179                         "X-Check-Fifo: $fifo\r\n\r\n");
180         open my $f, '>', $fifo or die "open $fifo: $!\n";
181         $f->autoflush(1);
182         my $buf;
183         $conn->sysread($buf, 8192);
184         like($buf, qr!\AHTTP/1\.[01] 200 OK!, 'got 200 for slow-body');
185         like($buf, qr!\r\n\r\n!, 'finished HTTP response header');
186
187         foreach my $c ('a'..'c') {
188                 $c .= "\n";
189                 ok(print($f $c), 'wrote line to fifo');
190                 $conn->sysread($buf, 8192);
191                 is($buf, $c, 'got trickle for reading');
192         }
193         my $kpid = $pid;
194         $pid = undef;
195         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
196         ok(print($f "world\n"), 'wrote else to fifo');
197         close $f or die "close fifo: $!\n";
198         $conn->sysread($buf, 8192);
199         is($buf, "world\n", 'read expected body');
200         is($conn->sysread($buf, 8192), 0, 'got EOF from server');
201         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
202         is($?, 0, 'no error');
203         $spawn_httpd->('-W0');
204 }
205
206 sub delay { select(undef, undef, undef, shift || rand(0.02)) }
207
208 my $str = 'abcdefghijklmnopqrstuvwxyz';
209 my $len = length $str;
210 is($len, 26, 'got the alphabet');
211 my $check_self = sub {
212         my ($conn) = @_;
213         $conn->read(my $buf, 4096);
214         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
215         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
216         is($body, sha1_hex($str), 'read expected body');
217 };
218
219 SKIP: {
220         use POSIX qw(dup2);
221         use IO::File;
222         my $have_curl = 0;
223         foreach my $p (split(':', $ENV{PATH})) {
224                 -x "$p/curl" or next;
225                 $have_curl = 1;
226                 last;
227         }
228         my $ntest = 2;
229         $have_curl or skip('curl(1) missing', $ntest);
230         my $url = 'http://' . $sock->sockhost . ':' . $sock->sockport . '/sha1';
231         my ($r, $w);
232         pipe($r, $w) or die "pipe: $!";
233         my $tout = IO::File->new_tmpfile or die "new_tmpfile: $!";
234         my $pid = fork;
235         defined $pid or die "fork: $!";
236         my @cmd = (qw(curl --tcp-nodelay --no-buffer -T- -HExpect: -sS), $url);
237         if ($pid == 0) {
238                 dup2(fileno($r), 0) or die "redirect stdin failed: $!\n";
239                 dup2(fileno($tout), 1) or die "redirect stdout failed: $!\n";
240                 exec(@cmd) or die 'exec `' . join(' '). "' failed: $!\n";
241         }
242         $w->autoflush(1);
243         foreach my $c ('a'..'z') {
244                 print $w $c or die "failed to write to curl: $!";
245                 delay();
246         }
247         close $w or die "close write pipe: $!";
248         close $r or die "close read pipe: $!";
249         my $kid = waitpid $pid, 0;
250         is($?, 0, 'curl exited successfully');
251         $tout->sysseek(0, SEEK_SET);
252         $tout->sysread(my $buf, 100);
253         is($buf, sha1_hex($str), 'read expected body');
254 }
255
256 {
257         my $conn = conn_for($sock, '1.1 pipeline together');
258         $conn->write("PUT /sha1 HTTP/1.1\r\nUser-agent: hello\r\n\r\n" .
259                         "PUT /sha1 HTTP/1.1\r\n\r\n");
260         my $buf = '';
261         my @r;
262         until (scalar(@r) >= 2) {
263                 my $r = $conn->sysread(my $tmp, 4096);
264                 die $! unless defined $r;
265                 die "EOF <$buf>" unless $r;
266                 $buf .= $tmp;
267                 @r = ($buf =~ /\r\n\r\n([a-f0-9]{40})/g);
268         }
269         is(2, scalar @r, 'got 2 responses');
270         my $i = 3;
271         foreach my $hex (@r) {
272                 is($hex, sha1_hex(''), "read expected body $i");
273                 $i++;
274         }
275 }
276
277 {
278         my $conn = conn_for($sock, 'graceful termination during slow request');
279         $conn->write("PUT /sha1 HTTP/1.0\r\n");
280         delay();
281         $conn->write("Content-Length: $len\r\n");
282         delay();
283         $conn->write("\r\n");
284         my $kpid = $pid;
285         $pid = undef;
286         is(kill('TERM', $kpid), 1, 'started graceful shutdown');
287         delay();
288         my $n = 0;
289         foreach my $c ('a'..'z') {
290                 $n += $conn->write($c);
291         }
292         is($n, $len, 'wrote alphabet');
293         $check_self->($conn);
294         is(waitpid($kpid, 0), $kpid, 'reaped httpd');
295         is($?, 0, 'no error');
296         $spawn_httpd->('-W0');
297 }
298
299 # various DoS attacks against the chunk parser:
300 {
301         local $SIG{PIPE} = 'IGNORE';
302         my $conn = conn_for($sock, '1.1 chunk header excessive');
303         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
304         my $n = 0;
305         my $w;
306         while ($w = $conn->write('ffffffff')) {
307                 $n += $w;
308         }
309         ok($!, 'got error set in $!');
310         is($w, undef, 'write error happened');
311         ok($n > 0, 'was able to write');
312         my $r = $conn->read(my $buf, 66666);
313         ok($r > 0, 'got non-empty response');
314         like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
315
316         $conn = conn_for($sock, '1.1 chunk trailer excessive');
317         $conn->write("PUT /sha1 HTTP/1.1\r\nTransfer-Encoding:chunked\r\n\r\n");
318         is($conn->syswrite("1\r\na"), 4, 'wrote first header + chunk');
319         delay();
320         $n = 0;
321         while ($w = $conn->write("\r")) {
322                 $n += $w;
323         }
324         ok($!, 'got error set in $!');
325         ok($n > 0, 'wrote part of chunk end (\r)');
326         $r = $conn->read($buf, 66666);
327         ok($r > 0, 'got non-empty response');
328         like($buf, qr!HTTP/1\.\d 400 !, 'got 400 response');
329 }
330
331 {
332         my $conn = conn_for($sock, '1.1 chunked close trickle');
333         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
334         $conn->write("Transfer-encoding: chunked\r\n\r\n");
335         foreach my $x ('a'..'z') {
336                 delay();
337                 $conn->write('1');
338                 delay();
339                 $conn->write("\r");
340                 delay();
341                 $conn->write("\n");
342                 delay();
343                 $conn->write($x);
344                 delay();
345                 $conn->write("\r");
346                 delay();
347                 $conn->write("\n");
348         }
349         $conn->write('0');
350         delay();
351         $conn->write("\r");
352         delay();
353         $conn->write("\n");
354         delay();
355         $conn->write("\r");
356         delay();
357         $conn->write("\n");
358         delay();
359         $check_self->($conn);
360 }
361
362 {
363         my $conn = conn_for($sock, '1.1 chunked close');
364         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
365         my $xlen = sprintf('%x', $len);
366         $conn->write("Transfer-Encoding: chunked\r\n\r\n$xlen\r\n" .
367                 "$str\r\n0\r\n\r\n");
368         $check_self->($conn);
369 }
370
371 {
372         my $conn = conn_for($sock, 'chunked body + pipeline');
373         $conn->write("PUT /sha1 HTTP/1.1\r\n" .
374                         "Transfer-Encoding: chunked\r\n");
375         delay();
376         $conn->write("\r\n1\r\n");
377         delay();
378         $conn->write('a');
379         delay();
380         $conn->write("\r\n0\r\n\r\nPUT /sha1 HTTP/1.1\r\n");
381         delay();
382
383         my $buf = '';
384         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
385                 $conn->sysread(my $tmp, 4096);
386                 $buf .= $tmp;
387         }
388         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
389         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
390         is($body, sha1_hex('a'), 'read expected body');
391
392         $conn->write("Connection: close\r\n");
393         $conn->write("Content-Length: $len\r\n\r\n$str");
394         $check_self->($conn);
395 }
396
397 {
398         my $conn = conn_for($sock, 'trickle header, one-shot body + pipeline');
399         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
400                         "Connection: keep-alive\r\n");
401         delay();
402         $conn->write("Content-Length: $len\r\n\r\n${str}PUT");
403         my $buf = '';
404         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
405                 $conn->sysread(my $tmp, 4096);
406                 $buf .= $tmp;
407         }
408         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
409         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
410         is($body, sha1_hex($str), 'read expected body');
411
412         $conn->write(" /sha1 HTTP/1.0\r\nContent-Length: $len\r\n\r\n$str");
413         $check_self->($conn);
414 }
415
416 {
417         my $conn = conn_for($sock, 'trickle body');
418         $conn->write("PUT /sha1 HTTP/1.0\r\n");
419         $conn->write("Content-Length: $len\r\n\r\n");
420         my $beg = substr($str, 0, 10);
421         my $end = substr($str, 10);
422         is($beg . $end, $str, 'substr setup correct');
423         delay();
424         $conn->write($beg);
425         delay();
426         $conn->write($end);
427         $check_self->($conn);
428 }
429
430 {
431         my $conn = conn_for($sock, 'one-shot write');
432         $conn->write("PUT /sha1 HTTP/1.0\r\n" .
433                         "Content-Length: $len\r\n\r\n$str");
434         $check_self->($conn);
435 }
436
437 {
438         my $conn = conn_for($sock, 'trickle header, one-shot body');
439         $conn->write("PUT /sha1 HTTP/1.0\r\n");
440         delay();
441         $conn->write("Content-Length: $len\r\n\r\n$str");
442         $check_self->($conn);
443 }
444
445 {
446         my $conn = conn_for($sock, '1.1 Connnection: close');
447         $conn->write("PUT /sha1 HTTP/1.1\r\nConnection:close\r\n");
448         delay();
449         $conn->write("Content-Length: $len\r\n\r\n$str");
450         $check_self->($conn);
451 }
452
453 {
454         my $conn = conn_for($sock, '1.1 pipeline start');
455         $conn->write("PUT /sha1 HTTP/1.1\r\n\r\nPUT");
456         my $buf = '';
457         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
458                 $conn->sysread(my $tmp, 4096);
459                 $buf .= $tmp;
460         }
461         my ($head, $body) = split(/\r\n\r\n/, $buf, 2);
462         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
463         is($body, sha1_hex(''), 'read expected body');
464
465         # 2nd request
466         $conn->write(" /sha1 HTTP/1.1\r\n\r\n");
467         $buf = '';
468         until ($buf =~ /\r\n\r\n[a-f0-9]{40}\z/) {
469                 $conn->sysread(my $tmp, 4096);
470                 $buf .= $tmp;
471         }
472         ($head, $body) = split(/\r\n\r\n/, $buf, 2);
473         like($head, qr/\r\nContent-Length: 40\r\n/s, 'got expected length');
474         is($body, sha1_hex(''), 'read expected body #2');
475 }
476
477 done_testing();
478
479 1;