Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsafe directory traversal #3

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 60 additions & 4 deletions src/elli_static.erl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
-include_lib("kernel/include/file.hrl").

-define(TABLE, elli_static_table).

-define(NOT_FOUND, {404, [], <<"Not Found">>}).

%% elli_handler callbacks
-export([handle/2, handle_event/3]).
Expand Down Expand Up @@ -81,16 +81,72 @@ file_info(Filename) ->
{error, Reason} -> throw(Reason)
end.


maybe_file(Req, Prefix, Dir) ->
%% all paths start with a slash which `safe_relative_path/1' interprets as
%% unsafe (absolute path), so temporarily remove it
<<"/", RawPath/binary>> = elli_request:raw_path(Req),

%% santize the path ensuring the request doesn't access any parent
%% directories ... and reattach the slash if deemed safe
SafePath = case safe_relative_path(RawPath) of
unsafe ->
throw(?NOT_FOUND);
%% return type quirk work around
[] ->
<<"/">>;
Sanitized ->
<<"/", Sanitized/binary>>
end,

Size = byte_size(Prefix),
case elli_request:raw_path(Req) of
case SafePath of
%% ensure that `SafePath' starts with the correct prefix
<<Prefix:Size/binary,"/",Path/binary>> ->
Filename = filename:join(Dir, Path),
case filelib:is_regular(Filename) of
true -> {just, Filename};
false -> throw({404, [], <<"Not Found">>})
false -> throw(?NOT_FOUND)
end;
_ ->
nothing
end.


%% OTP_RELEASE macro was introduced in 21, `filename:safe_relative_path/1' in
%% 19.3, so the code below is safe
-ifdef(OTP_RELEASE).
-ifdef(?OTP_RELEASE >= 21).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think I've seen this sort of ifdef before, but it appears to work as desired.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My preference would be to defer to filename:safe_relative_path/1 if available. However, checking this at runtime (via module_info(exports)) caused lots of coverall coverage complaints.

Xref and dialyzer are run under the test profile, so in-module eunit tests ended up failing xref right out of the gate (elli_static:safe_relative_path_test/0 is unused export). Doh!

I didn't want to introduce a new module, but I suppose I could create something like elli_static_utils, place safe_relative_path/1 in there, and test independently of the OTP version. The utils module would be a cleaner approach IMO.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 to a utils module, if you're up for it.

safe_relative_path(Path) ->
filename:safe_relative_path(Path).
-endif.
-else.

%% @doc Backport of `filename:safe_relative_path/1' from 19.3. This code was
%% lifted from:
%% https://github.com/erlang/otp/blob/master/lib/stdlib/src/filename.erl#L811
-spec safe_relative_path(binary()) -> unsafe | file:name_all().
safe_relative_path(Path) ->
case filename:pathtype(Path) of
relative ->
Cs0 = filename:split(Path),
safe_relative_path_1(Cs0, []);
_ ->
unsafe
end.

safe_relative_path_1([<<".">>|T], Acc) ->
safe_relative_path_1(T, Acc);
safe_relative_path_1([<<"..">>|T], Acc) ->
climb(T, Acc);
safe_relative_path_1([H|T], Acc) ->
safe_relative_path_1(T, [H|Acc]);
safe_relative_path_1([], []) ->
[];
safe_relative_path_1([], Acc) ->
filename:join(lists:reverse(Acc)).

climb(_, []) ->
unsafe;
climb(T, [_|Acc]) ->
safe_relative_path_1(T, Acc).
-endif.
33 changes: 32 additions & 1 deletion test/elli_static_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ elli_static_test_() ->
fun setup/0, fun teardown/1,
[?_test(readme()),
?_test(no_file()),
?_test(not_found())]}.
?_test(not_found()),
?_test(safe_traversal()),
?_test(unsafe_traversal()),
?_test(invalid_path_separator())]}.


readme() ->
Expand All @@ -28,6 +31,34 @@ not_found() ->
{ok, Response} = httpc:request("http://localhost:3000/not_found"),
?assertMatch({{"HTTP/1.1",404,"Not Found"}, _Headers, "Not Found"}, Response).

safe_traversal() ->
{ok, File} = file:read_file("README.md"),
Expected = binary_to_list(File),

{ok, Response} = httpc:request("http://localhost:3000/elli_static/"
"../elli_static/README.md"),
?assertEqual([integer_to_list(iolist_size(Expected))],
proplists:get_all_values("content-length", element(2, Response))),
?assertMatch({_Status, _Headers, Expected}, Response),


%% `Response' should match the same request above
{ok, Response} = httpc:request("http://localhost:3000/elli_static/./README.md").

unsafe_traversal() ->
%% compute the relative path to /etc/passwd
{ok, Cwd} = file:get_cwd(),
PasswdPath = [".." || _ <- filename:split(Cwd)] ++ ["etc", "passwd"],
Path = filename:join(PasswdPath),

{ok, Response} = httpc:request("http://localhost:3000/elli_static/" ++ Path),
?assertMatch({{"HTTP/1.1",404,"Not Found"}, _Headers, "Not Found"}, Response).

invalid_path_separator() ->
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call.

%% https://www.ietf.org/rfc/rfc2396.txt defines a path separator to be a
%% single slash
{ok, Response} = httpc:request("http://localhost:3000////elli_static/README.md"),
?assertMatch({{"HTTP/1.1",404,"Not Found"}, _Headers, "Not Found"}, Response).

setup() ->
{ok, Dir} = file:get_cwd(),
Expand Down