Debian Codegraph @

t/integration/handler/file.t

raw
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Plack::Test;
6 use HTTP::Request;
7 use HTTP::Request::Common;
8 use Path::Tiny ();
9
10 # Dancer2 serves files from disk by three different code paths, and they do
11 # not agree with each other. This file pins all three:
12 #
13 # 1. send_file - Dancer2::Core::App::send_file, called from a route.
14 # 2. the static handler - on by default; Plack::App::File wrapped in
15 # Plack::Middleware::Conditional by App::to_app,
16 # so it runs *before* the application.
17 # 3. Dancer2::Handler::File - off by default; a real route (/**) registered
18 # into the application when config asks for it.
19 #
20 # Where they disagree, the disagreement is asserted rather than smoothed over.
21 # One of those disagreements was a security hole - Dancer2::Handler::File
22 # serving files outside public_dir - and is pinned by the ../ subtests below.
23
24 # --- fixture tree ---------------------------------------------------------
25 #
26 # Built in a BEGIN block: the third application needs a config.yml on disk
27 # before its own 'use Dancer2' runs, because route_handlers is read once when
28 # the application object is constructed at import time. A later 'set' is too
29 # late, which is why this is a config file and not a setting.
30 #
31 # $ROOT/secret.txt <- outside the public directory, must stay unreachable
32 # $ROOT/public/hello.txt
33 # $ROOT/public/locked.txt <- mode 0000
34 # $ROOT/public/shadowed.txt <- a route of the same name also exists
35 # $ROOT/conf/config.yml <- enables Dancer2::Handler::File
36
37 my ( $ROOT, $PUBLIC, $CONFDIR, $LOCKED_IS_UNREADABLE );
38
39 BEGIN {
40 $ROOT = Path::Tiny->tempdir; # kept in scope so it outlives the tests
41 $PUBLIC = $ROOT->child('public');
42 $PUBLIC->mkpath;
43 $CONFDIR = $ROOT->child('conf');
44 $CONFDIR->mkpath;
45
46 $ROOT->child('secret.txt')->spew_utf8('SECRET');
47 $PUBLIC->child('hello.txt')->spew_utf8('HELLO');
48 $PUBLIC->child('shadowed.txt')->spew_utf8('FILE-CONTENT');
49
50 my $locked = $PUBLIC->child('locked.txt');
51 $locked->spew_utf8('LOCKED');
52 chmod 0000, "$locked";
53
54 # Running as root, or on a filesystem that ignores the mode, leaves the
55 # file readable and the 403 assertions below meaningless. Ask the
56 # filesystem rather than guessing.
57 $LOCKED_IS_UNREADABLE = !-r "$locked";
58
59 $CONFDIR->child('config.yml')->spew_utf8( <<"YML" );
60 logger: "null"
61 public_dir: "$PUBLIC"
62 static_handler: 0
63 route_handlers:
64 - - File
65 - public_dir: "$PUBLIC"
66 YML
67 }
68
69 # --- 1. send_file ---------------------------------------------------------
70
71 {
72 package SendFileApp;
73 use Dancer2;
74 set logger => 'null';
75 set public_dir => "$PUBLIC";
76 set static_handler => 0; # keep path 2 out of the way of path 1
77
78 get '/ok' => sub { send_file('hello.txt') };
79 get '/missing' => sub { send_file('nope.txt') };
80 get '/locked' => sub { send_file('locked.txt') };
81
82 # Two flavours of escape. The second one names a file that does not exist
83 # either, which is what makes it interesting: containment has to be
84 # decided before existence, or this answers 404 and quietly confirms the
85 # path was resolved outside the public directory.
86 get '/escape' => sub { send_file('../secret.txt') };
87 get '/escape-missing' => sub { send_file('../no-such-file.txt') };
88
89 get '/absolute' => sub { send_file("$ROOT/secret.txt") };
90 get '/system-absolute' => sub {
91 send_file( "$ROOT/secret.txt", system_path => 1 );
92 };
93
94 get '/named' => sub { send_file( 'hello.txt', filename => 'renamed.txt' ) };
95 get '/inline' => sub {
96 send_file(
97 'hello.txt',
98 filename => 'r.txt',
99 content_disposition => 'inline',
100 );
101 };
102
103 get '/in-memory' => sub {
104 send_file(
105 \'IN-MEMORY',
106 content_type => 'text/plain',
107 filename => 'mem.txt',
108 );
109 };
110
111 get '/after' => sub { send_file('hello.txt'); return 'NEVER-REACHED' };
112 }
113
114 subtest 'send_file will not serve a file outside the public directory' => sub {
115 my $test = Plack::Test->create( SendFileApp->to_app );
116
117 # The control: the very same call does serve a file that is inside.
118 my $ok = $test->request( GET '/ok' );
119 is( $ok->code, 200, 'a file inside the public directory is served' );
120 is( $ok->content, 'HELLO', 'and its content is what is on disk' );
121
122 my $escape = $test->request( GET '/escape' );
123 is( $escape->code, 403,
124 'a ../ path pointing outside the public directory is refused' );
125 is( $escape->content, 'Forbidden', 'with the standard 403 body' );
126 unlike( $escape->content, qr/SECRET/,
127 'and no part of the target file is disclosed' );
128
129 is( $test->request( GET '/escape-missing' )->code, 403,
130 'containment is decided before existence, so an escape to a missing file is still 403, not 404' );
131
132 is( $test->request( GET '/absolute' )->code, 403,
133 'an absolute path is refused too, unless system_path says otherwise' );
134
135 my $system = $test->request( GET '/system-absolute' );
136 is( $system->code, 200,
137 'system_path => 1 is the documented way out and still works' );
138 is( $system->content, 'SECRET', 'and it does read the requested file' );
139 };
140
141 subtest 'send_file distinguishes missing from unreadable' => sub {
142 my $test = Plack::Test->create( SendFileApp->to_app );
143
144 my $missing = $test->request( GET '/missing' );
145 is( $missing->code, 404, 'a missing file is a 404' );
146 is( $missing->content, 'Not Found', 'with the standard 404 body' );
147
148 SKIP: {
149 skip 'cannot make a file unreadable here', 2
150 if !$LOCKED_IS_UNREADABLE;
151
152 my $locked = $test->request( GET '/locked' );
153 is( $locked->code, 403,
154 'a file that exists but cannot be read is a 403, not a 404' );
155 is( $locked->content, 'Forbidden', 'with the standard 403 body' );
156 }
157 };
158
159 subtest 'send_file sets Content-Disposition and ends the route' => sub {
160 my $test = Plack::Test->create( SendFileApp->to_app );
161
162 is( $test->request( GET '/ok' )->header('Content-Disposition'), undef,
163 'no Content-Disposition unless a filename was asked for' );
164
165 is(
166 $test->request( GET '/named' )->header('Content-Disposition'),
167 'attachment; filename="renamed.txt"',
168 'a filename produces an attachment disposition under the given name',
169 );
170
171 is(
172 $test->request( GET '/inline' )->header('Content-Disposition'),
173 'inline; filename="r.txt"',
174 'content_disposition overrides the attachment default',
175 );
176
177 my $mem = $test->request( GET '/in-memory' );
178 is( $mem->code, 200, 'a scalar reference is served as content' );
179 is( $mem->content, 'IN-MEMORY', 'and the content is the referenced string' );
180 is(
181 $mem->header('Content-Disposition'),
182 'attachment; filename="mem.txt"',
183 'an in-memory body can still be given a download filename',
184 );
185
186 # send_file longjmps out of the route. If it ever stops doing that, the
187 # return value below wins instead.
188 is( $test->request( GET '/after' )->content, 'HELLO',
189 'send_file exits the route immediately; code after it does not run' );
190 };
191
192 # --- 2. the default static handler ---------------------------------------
193
194 {
195 package StaticApp;
196 use Dancer2;
197 set logger => 'null';
198 set public_dir => "$PUBLIC";
199
200 # Both of these are shadowed by a file on disk / by nothing on disk.
201 # Which one wins is the behavior being pinned.
202 get '/shadowed.txt' => sub { 'ROUTE-CONTENT' };
203 get '/nothere.txt' => sub { 'ROUTE-SERVED-INSTEAD' };
204 }
205
206 subtest 'the default static handler runs ahead of the application' => sub {
207 my $test = Plack::Test->create( StaticApp->to_app );
208
209 my $hello = $test->request( GET '/hello.txt' );
210 is( $hello->code, 200, 'an existing file is served' );
211 is( $hello->content, 'HELLO', 'straight off disk' );
212 like( $hello->header('Content-Type'), qr{^text/plain\b},
213 'with a content type derived from the extension' );
214 like( $hello->header('Content-Type'), qr/charset=utf-8/i,
215 'and a charset, because it is a text type' );
216
217 # This is the ordering assertion: the static handler is middleware, so it
218 # wins over a route of the same path.
219 is( $test->request( GET '/shadowed.txt' )->content, 'FILE-CONTENT',
220 'a file on disk beats a route of the same path' );
221
222 # And this is the fall-through: no file, so the request reaches the app.
223 my $fell = $test->request( GET '/nothere.txt' );
224 is( $fell->code, 200,
225 'a missing file does not 404 on the spot' );
226 is( $fell->content, 'ROUTE-SERVED-INSTEAD',
227 'it falls through to the route that does match' );
228
229 my $escape = $test->request( HTTP::Request->new( GET => '/../secret.txt' ) );
230 is( $escape->code, 403,
231 'a ../ path is refused by Plack::App::File before Dancer2 sees it' );
232 unlike( $escape->content, qr/SECRET/,
233 'and the file outside the public directory is not disclosed' );
234
235 SKIP: {
236 skip 'cannot make a file unreadable here', 1
237 if !$LOCKED_IS_UNREADABLE;
238 is( $test->request( GET '/locked.txt' )->code, 403,
239 'an unreadable file is a 403 here too' );
240 }
241 };
242
243 subtest 'a null byte in a static path is refused quietly (fixed)' => sub {
244 my $test = Plack::Test->create( StaticApp->to_app );
245
246 my @warnings;
247 my $res = do {
248 local $SIG{__WARN__} = sub { push @warnings, $_[0] };
249 $test->request( HTTP::Request->new( GET => "/hello.txt\0.png" ) );
250 };
251
252 is( $res->code, 404, 'the request is answered, not aborted' );
253 unlike( $res->content, qr/HELLO/,
254 'and the file whose name was the prefix is not served' );
255
256 # The static handler's file-existence condition used to hand the raw
257 # PATH_INFO to Path::Tiny, which warned "Invalid \0 character in pathname"
258 # on every such request -- an attacker-supplied path reaching the log once
259 # per request. The condition now refuses a NUL-bearing path before
260 # Path::Tiny is asked about it, so the request falls through to the
261 # application and 404s exactly as it did, but in silence.
262 is( scalar @warnings, 0, 'no warning reaches the log' )
263 or diag "unexpected warnings:\n@warnings";
264 };
265
266 # --- 3. Dancer2::Handler::File ------------------------------------------
267 #
268 # DANCER_CONFDIR has to be in place while the application below is being
269 # constructed, and gone again afterwards so nothing else in this file reads
270 # that config. Both BEGIN blocks run at compile time, in the order written,
271 # and 'use Dancer2' between them builds the application.
272
273 BEGIN { $ENV{DANCER_CONFDIR} = "$CONFDIR" }
274
275 {
276 package HandlerFileApp;
277 use Dancer2;
278
279 # Registered before the handler's own /** route, so this one matches
280 # first - the opposite of the middleware case above.
281 get '/shadowed.txt' => sub { 'ROUTE-CONTENT' };
282 }
283
284 BEGIN { delete $ENV{DANCER_CONFDIR} }
285
286 subtest 'Dancer2::Handler::File serves files as an ordinary route' => sub {
287 my $test = Plack::Test->create( HandlerFileApp->to_app );
288
289 my $hello = $test->request( GET '/hello.txt' );
290 is( $hello->code, 200, 'the handler serves a file under public_dir' );
291 is( $hello->content, 'HELLO', 'with the content from disk' );
292
293 is( $test->request( HTTP::Request->new( HEAD => '/hello.txt' ) )->code,
294 200, 'and answers HEAD as well as GET' );
295
296 # It is a route, not middleware, and it is registered last - so a route
297 # the developer declared wins even when a file of that name exists.
298 is( $test->request( GET '/shadowed.txt' )->content, 'ROUTE-CONTENT',
299 'a declared route beats a file of the same name here' );
300
301 # The handler passes rather than answering, which is why this reaches the
302 # application's own 404 instead of an empty 200.
303 is( $test->request( GET '/nothere.txt' )->code, 404,
304 'a missing file is passed on and 404s through the application' );
305
306 is( $test->request( HTTP::Request->new( GET => "/hello.txt\0.png" ) )->code,
307 400, 'a NUL in the path is rejected outright' );
308
309 SKIP: {
310 skip 'cannot make a file unreadable here', 1
311 if !$LOCKED_IS_UNREADABLE;
312 is( $test->request( GET '/locked.txt' )->code, 403,
313 'an unreadable file is a 403' );
314 }
315 };
316
317 subtest 'Dancer2::Handler::File refuses a ../ path outside public_dir (fixed)' => sub {
318
319 # This used to be a security hole: Dancer2::Handler::File joined
320 # public_dir with the request path and never checked that the result was
321 # still inside public_dir. It now resolves the joined path with realpath
322 # and applies the same containment check send_file already used at
323 # Dancer2/Core/App.pm:1180-1182 ($dir->realpath->subsumes($file_path)),
324 # so it agrees with send_file and with Plack::App::File on the default
325 # static path, both of which answer 403 for the same request.
326
327 my $test = Plack::Test->create( HandlerFileApp->to_app );
328
329 my $res = $test->request( HTTP::Request->new( GET => '/../secret.txt' ) );
330
331 is( $res->code, 403,
332 'a ../ path escaping public_dir is refused' );
333 unlike( $res->content, qr/SECRET/,
334 'and the content of the file outside public_dir is not disclosed' );
335 };
336
337 subtest 'the ../ escape is refused at any depth (fixed)' => sub {
338
339 # The subtest above pins that a single ../ is refused. This one pins that
340 # the containment check holds regardless of how many ../ segments are
341 # used - including a surplus that would collapse at the filesystem root -
342 # so there is no depth an attacker can use to get back in.
343 #
344 # Same fix as above - $dir->realpath->subsumes($file_path), the check
345 # send_file already makes at Dancer2/Core/App.pm:1182.
346 #
347 # Note this matters only where the default static handler is off: with it
348 # on, Plack::App::File refuses the same request with a 403 before Dancer2
349 # ever sees it, which the StaticApp subtest above pins. HandlerFileApp
350 # sets static_handler: 0.
351
352 my $test = Plack::Test->create( HandlerFileApp->to_app );
353
354 # Two levels up and back down again, rather than the single ../ above:
355 # public_dir/../../<tempdir name>/secret.txt resolves to the same file.
356 my $updown = $test->request( HTTP::Request->new(
357 GET => '/../../' . $ROOT->basename . '/secret.txt' ) );
358 is( $updown->code, 403,
359 'a two-level ../../ path is refused just as well as one' );
360 unlike( $updown->content, qr/SECRET/,
361 'and the file outside public_dir is not disclosed' );
362
363 # More ../ than there are directories: the surplus would otherwise
364 # collapse at the filesystem root instead of failing, so this checks the
365 # containment guard holds even when an attacker has no knowledge of how
366 # deep public_dir happens to sit. $ROOT->relative('/') then walks back
367 # down to the fixture from /.
368 my $deep = $test->request( HTTP::Request->new(
369 GET => '/' . ( '../' x 20 ) . $ROOT->relative('/') . '/secret.txt' ) );
370 is( $deep->code, 403,
371 'surplus ../ segments are refused rather than collapsing at /' );
372 unlike( $deep->content, qr/SECRET/,
373 'so the escape does not work regardless of the depth used' );
374
375 # The reason the two assertions above matter: the same shape would
376 # otherwise reach a real file outside the application entirely. Guarded,
377 # because a readable /etc/passwd is a Unix assumption and this suite also
378 # runs on Windows.
379 SKIP: {
380 skip 'no readable /etc/passwd on this platform', 2
381 if !-r '/etc/passwd';
382
383 my $passwd = $test->request( HTTP::Request->new(
384 GET => '/' . ( '../' x 20 ) . 'etc/passwd' ) );
385 is( $passwd->code, 403,
386 '/etc/passwd is refused, not served, through Dancer2::Handler::File' );
387 unlike( $passwd->content, qr/^root:/m,
388 'and the response is not the system password file' );
389 }
390 };
391
392 done_testing();