summaryrefslogtreecommitdiff
path: root/apps/chttpd/src/chttpd_auth.erl
blob: ac4679c5c150ef30562e9529870ab15666275d35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
% Licensed under the Apache License, Version 2.0 (the "License"); you may not
% use this file except in compliance with the License.  You may obtain a copy of
% the License at
%
%   http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
% License for the specific language governing permissions and limitations under
% the License.

-module(chttpd_auth).
-include_lib("couch/include/couch_db.hrl").

-export([special_test_authentication_handler/1, null_authentication_handler/1,
    cookie_authentication_handler/1, default_authentication_handler/1,
    handle_session_req/1, handle_user_req/1, cookie_auth_header/2]).
    
% used by OAuth handler
-export([get_user/1, ensure_users_db_exists/1]).

-import(chttpd, [send_json/2, send_json/4, send_method_not_allowed/2]).

special_test_authentication_handler(Req) ->
    case chttpd:header_value(Req, "WWW-Authenticate") of
    "X-Couch-Test-Auth " ++ NamePass ->
        % NamePass is a colon separated string: "joe schmoe:a password".
        [Name, Pass] = re:split(NamePass, ":", [{return, list}]),
        case {Name, Pass} of
        {"Jan Lehnardt", "apple"} -> ok;
        {"Christopher Lenz", "dog food"} -> ok;
        {"Noah Slater", "biggiesmalls endian"} -> ok;
        {"Chris Anderson", "mp3"} -> ok;
        {"Damien Katz", "pecan pie"} -> ok;
        {_, _} ->
            throw({unauthorized, <<"Name or password is incorrect.">>})
        end,
        Req#httpd{user_ctx=#user_ctx{name=?l2b(Name)}};
    _ ->
        % No X-Couch-Test-Auth credentials sent, give admin access so the
        % previous authentication can be restored after the test
        Req#httpd{user_ctx=#user_ctx{roles=[<<"_admin">>]}}
    end.

null_authentication_handler(Req) ->
    Ctx = #user_ctx{roles=[<<"_reader">>, <<"writer">>, <<"_admin">>]},
    Req#httpd{user_ctx=Ctx}.

default_authentication_handler(Req) ->
    case basic_username_pw(Req) of
    {Username, Password} ->
        case get_user(Username) of
        nil ->
            throw({unauthorized, <<"unknown username">>});
        Props ->
            ExpectedHash = couch_util:get_value(<<"password_sha">>, Props),
            Salt = couch_util:get_value(<<"salt">>, Props),
            PasswordHash = hash_password(?l2b(Password), Salt),
            case couch_util:verify(ExpectedHash, PasswordHash) of
            true ->
                Ctx = #user_ctx{
                    name = couch_util:get_value(<<"username">>, Props),
                    roles = couch_util:get_value(<<"roles">>, Props)
                },
                Req#httpd{user_ctx=Ctx};
            _ ->
                throw({unauthorized, <<"password is incorrect">>})
            end
        end;
    nil ->
        Req
    end.

cookie_authentication_handler(#httpd{path_parts=[<<"_session">>],
        method='POST'} = Req) ->
    % ignore any cookies sent with login request
    Req;
cookie_authentication_handler(Req) ->
    try cookie_auth_user(Req) of
    nil ->
        Req;
    {cookie_auth_failed, _} = X ->
        Req#httpd{auth=X};
    Req2 ->
        Req2
    catch error:_ ->
        Req#httpd{auth={cookie_auth_failed, {invalid_cookie, null}}}
    end.

cookie_auth_header(#httpd{auth={cookie_auth_failed, _}}, Headers) ->
    % check for an AuthSession cookie from login handler
    CookieHeader = couch_util:get_value("Set-Cookie", Headers, ""),
    Cookies = mochiweb_cookies:parse_cookie(CookieHeader),
    AuthSession = couch_util:get_value("AuthSession", Cookies),
    if AuthSession == undefined ->
        [generate_cookie_buster()];
    true ->
        []
    end;
cookie_auth_header(#httpd{user_ctx=#user_ctx{name=null}}, _Headers) ->
    [];
cookie_auth_header(#httpd{user_ctx=Ctx, auth={Secret,true}}, Headers) ->
    % Note: we only set the AuthSession cookie if:
    %  * a valid AuthSession cookie has been received
    %  * we are outside a 10% timeout window
    %  * and if an AuthSession cookie hasn't already been set e.g. by a login
    %    or logout handler.
    % The login and logout handlers set the AuthSession cookie themselves.
    CookieHeader = couch_util:get_value("Set-Cookie", Headers, ""),
    Cookies = mochiweb_cookies:parse_cookie(CookieHeader),
    AuthSession = couch_util:get_value("AuthSession", Cookies),
    if AuthSession == undefined ->
        [generate_cookie(Ctx#user_ctx.name, Secret, timestamp())];
    true ->
        []
    end;
cookie_auth_header(_Req, _Headers) ->
    [].

handle_session_req(#httpd{method='POST', mochi_req=MochiReq, user_ctx=Ctx}=Req) ->
    % login
    Form = parse_form(MochiReq),
    UserName = extract_username(Form),
    case get_user(UserName) of
    nil ->
        throw({forbidden, <<"unknown username">>});
    User ->
        UserSalt = couch_util:get_value(<<"salt">>, User),
        case lists:member(<<"_admin">>, Ctx#user_ctx.roles) of
        true ->
            ok;
        false ->
            Password = extract_password(Form),
            ExpectedHash = couch_util:get_value(<<"password_sha">>, User),
            PasswordHash = hash_password(Password, UserSalt),
            case couch_util:verify(ExpectedHash, PasswordHash) of
            true ->
                ok;
            _Else ->
                throw({forbidden, <<"Name or password is incorrect.">>})
            end
        end,
        Secret = ?l2b(couch_config:get("couch_httpd_auth", "secret")),
        SecretAndSalt = <<Secret/binary, UserSalt/binary>>,
        Cookie = generate_cookie(UserName, SecretAndSalt, timestamp()),
        send_response(Req, [Cookie])
    end;
handle_session_req(#httpd{method='GET', user_ctx=UserCtx}=Req) ->
    % whoami
    #user_ctx{name = Name, roles = Roles} = UserCtx,
    ForceLogin = chttpd:qs_value(Req, "basic", "false"),
    case {Name, ForceLogin} of
    {null, "true"} ->
        throw({unauthorized, <<"Please login.">>});
    _False -> 
        Props = [{name,Name}, {roles,Roles}],
        send_json(Req, {[{ok,true}, {userCtx, {Props}} | Props]})
    end;
handle_session_req(#httpd{method='DELETE'}=Req) ->
    % logout
    send_response(Req, [generate_cookie_buster()]);
handle_session_req(Req) ->
    send_method_not_allowed(Req, "GET,HEAD,POST,DELETE").

handle_user_req(#httpd{method='POST'}=Req) ->
    DbName = couch_config:get("couch_httpd_auth", "authentication_db", "users"),
    ensure_users_db_exists(DbName),
    create_user(Req, DbName);
handle_user_req(#httpd{method=Method, path_parts=[_]}=_Req) when
        Method == 'PUT' orelse Method == 'DELETE' ->
    throw({bad_request, <<"Username is missing">>});
handle_user_req(#httpd{method='PUT', path_parts=[_, UserName]}=Req) ->
    DbName = couch_config:get("couch_httpd_auth", "authentication_db", "users"),
    ensure_users_db_exists(DbName),
    update_user(Req, DbName, UserName);
handle_user_req(#httpd{method='DELETE', path_parts=[_, UserName]}=Req) ->
    DbName = couch_config:get("couch_httpd_auth", "authentication_db", "users"),
    ensure_users_db_exists(DbName),
    delete_user(Req, DbName, UserName);
handle_user_req(Req) ->
    send_method_not_allowed(Req, "DELETE,POST,PUT").

get_user(UserName) when is_list(UserName) ->
    get_user(?l2b(UserName));
get_user(UserName) ->
    case couch_config:get("admins", ?b2l(UserName)) of
    "-hashed-" ++ HashedPwdAndSalt ->
        [HashedPwd, Salt] = string:tokens(HashedPwdAndSalt, ","),
        [
            {<<"username">>, UserName},
            {<<"roles">>, [<<"_reader">>, <<"_writer">>, <<"_admin">>]},
            {<<"salt">>, ?l2b(Salt)},
            {<<"password_sha">>, ?l2b(HashedPwd)}
        ];
    _ ->
        try ets:lookup(users_cache, UserName) of
        [{UserName, Props}] ->
            Props;
        [] ->
            load_user_from_db(UserName)
        catch error:badarg ->
            load_user_from_db(UserName)
        end
    end.

load_user_from_db(UserName) ->
    DbName = couch_config:get("couch_httpd_auth", "authentication_db", "users"),
    try fabric:open_doc(DbName, UserName, []) of
    {ok, Doc} ->
        ?LOG_INFO("cache miss on username ~s", [UserName]),
        {Props} = couch_doc:to_json_obj(Doc, []),
        Props;
    _Else ->
        ?LOG_INFO("no record of user ~s", [UserName]),
        nil
    catch error:database_does_not_exist ->
        nil
    end.

ensure_users_db_exists(DbName) ->
    try fabric:get_doc_count(DbName) of
    {ok, N} when is_integer(N) ->
        ok;
    {error, _} ->
        fabric:create_db(DbName, [])
    catch error:database_does_not_exist ->
        fabric:create_db(DbName, [])
    end.

% internal functions

basic_username_pw(Req) ->
    case chttpd:header_value(Req, "Authorization") of
    "Basic " ++ Base64Value ->
        case string:tokens(?b2l(base64:decode(Base64Value)),":") of
        [User, Pass] ->
            {User, Pass};
        [User] ->
            {User, ""};
        _ ->
            nil
        end;
    _ ->
        nil
    end.

cookie_auth_user(#httpd{mochi_req=MochiReq}=Req) ->
    case MochiReq:get_cookie_value("AuthSession") of
    undefined ->
        nil;
    Cookie -> 
        AuthSession = couch_util:decodeBase64Url(Cookie),
        [User, TimeStr | HashParts] = string:tokens(?b2l(AuthSession), ":"),
        % Verify expiry and hash
        case couch_config:get("couch_httpd_auth", "secret") of
        undefined ->
            ?LOG_DEBUG("AuthSession cookie, but no secret in config!", []),
            {cookie_auth_failed, {internal_server_error, null}};
        SecretStr ->
            case get_user(User) of
            nil ->
                Msg = io_lib:format("no record of user ~s", [User]),
                {cookie_auth_failed, {bad_user, ?l2b(Msg)}};
            Result ->
                Secret = ?l2b(SecretStr),
                UserSalt = couch_util:get_value(<<"salt">>, Result),
                FullSecret = <<Secret/binary, UserSalt/binary>>,
                ExpectedHash = crypto:sha_mac(FullSecret, [User, ":", TimeStr]),
                PasswordHash = ?l2b(string:join(HashParts, ":")),
                case couch_util:verify(ExpectedHash, PasswordHash) of
                true ->
                    TimeStamp = erlang:list_to_integer(TimeStr, 16),
                    Timeout = erlang:list_to_integer(couch_config:get(
                        "couch_httpd_auth", "timeout", "600")),
                    CurrentTime = timestamp(),
                    if CurrentTime < TimeStamp + Timeout ->
                        TimeLeft = TimeStamp + Timeout - CurrentTime,
                        Req#httpd{user_ctx=#user_ctx{
                            name=?l2b(User),
                            roles=couch_util:get_value(<<"roles">>, Result, [])
                        }, auth={FullSecret, TimeLeft < Timeout*0.9}};
                    true ->
                        ?LOG_DEBUG("cookie for ~s was expired", [User]),
                        Msg = lists:concat(["Your session has expired after ",
                            Timeout div 60, " minutes of inactivity"]),
                        {cookie_auth_failed, {credentials_expired, ?l2b(Msg)}}
                    end;
                _Else ->
                    Msg = <<"cookie password hash was incorrect">>,
                    {cookie_auth_failed, {bad_password, Msg}}
                end
            end
        end
    end.

create_user(#httpd{method='POST', mochi_req=MochiReq}=Req, Db) ->
    Form = parse_form(MochiReq),
    {UserName, Password} = extract_username_password(Form),
    case get_user(UserName) of
    nil -> 
        Roles = [?l2b(R) || R <- proplists:get_all_values("roles", Form)],
        if Roles /= [] ->
            chttpd:verify_is_server_admin(Req);
        true -> ok end,
        Active = chttpd_view:parse_bool_param(couch_util:get_value("active",
            Form, "true")),
        UserSalt = couch_uuids:random(),
        UserDoc = #doc{
            id = UserName,
            body = {[
                {<<"active">>, Active},
                {<<"email">>, ?l2b(couch_util:get_value("email", Form, ""))},
                {<<"password_sha">>, hash_password(Password, UserSalt)},
                {<<"roles">>, Roles},
                {<<"salt">>, UserSalt},
                {<<"type">>, <<"user">>},
                {<<"username">>, UserName}
            ]}
        },
        {ok, _Rev} = fabric:update_doc(Db, UserDoc, []),
        ?LOG_DEBUG("User ~s (~s) with password, ~s created.", [UserName,
            UserName, Password]),
        send_response(Req);
    _Result -> 
        ?LOG_DEBUG("Can't create ~s: already exists", [UserName]),
         throw({forbidden, <<"User already exists.">>})
    end.

delete_user(#httpd{user_ctx=UserCtx}=Req, Db, UserName) ->
    case get_user(UserName) of
    nil ->
        throw({not_found, <<"User doesn't exist">>});
    User ->
        case lists:member(<<"_admin">>,UserCtx#user_ctx.roles) of
        true ->
            ok;
        false when UserCtx#user_ctx.name == UserName ->
            ok;
        false ->
            throw({forbidden, <<"You aren't allowed to delete the user">>})
        end,
        {Pos,Rev} = couch_doc:parse_rev(couch_util:get_value(<<"_rev">>,User)),
        UserDoc = #doc{
            id = UserName,
            revs = {Pos, [Rev]},
            deleted = true
        },
        {ok, _Rev} = fabric:update_doc(Db, UserDoc, []),
        send_response(Req)
    end.

extract_username(Form) ->
    try ?l2b(couch_util:get_value("username", Form))
    catch error:badarg ->
        throw({bad_request, <<"user accounts must have a username">>})
    end.

extract_password(Form) ->
    try ?l2b(couch_util:get_value("password", Form))
    catch error:badarg ->
        throw({bad_request, <<"user accounts must have a password">>})
    end.

extract_username_password(Form) ->
    try
        {?l2b(couch_util:get_value("username", Form)),
         ?l2b(couch_util:get_value("password", Form))}
    catch error:badarg ->
        Msg = <<"user accounts must have a username and password">>,
        throw({bad_request, Msg})
    end.

generate_cookie_buster() ->
    T0 = calendar:now_to_datetime({0,86400,0}),
    Opts = [{max_age,0}, {path,"/"}, {local_time,T0}],
    mochiweb_cookies:cookie("AuthSession", "", Opts).

generate_cookie(User, Secret, TimeStamp) ->
    SessionData = ?b2l(User) ++ ":" ++ erlang:integer_to_list(TimeStamp, 16),
    Hash = crypto:sha_mac(Secret, SessionData),
    Cookie = couch_util:encodeBase64Url(SessionData ++ ":" ++ ?b2l(Hash)),
    % TODO add {secure, true} to options when SSL is detected
    mochiweb_cookies:cookie("AuthSession", Cookie, [{path, "/"}]).

hash_password(Password, Salt) ->
    ?l2b(couch_util:to_hex(crypto:sha(<<Password/binary, Salt/binary>>))).

parse_form(MochiReq) ->
    case MochiReq:get_primary_header_value("content-type") of
    "application/x-www-form-urlencoded" ++ _ ->
        ReqBody = MochiReq:recv_body(),
        mochiweb_util:parse_qs(ReqBody);
    _ ->
        throw({bad_request, <<"you must specify "
            "application/x-www-form-urlencoded as the primary content-type">>})
    end.

send_response(Req) ->
    send_response(Req, []).

send_response(Req, ExtraHeaders) ->
    {Code, Headers} = case chttpd:qs_value(Req, "next", nil) of
    nil -> {200, []};
    Redirect ->
        {302, [{"Location", chttpd:absolute_uri(Req, Redirect)}]}
    end,
    send_json(Req, Code, Headers ++ ExtraHeaders, {[{ok, true}]}).

timestamp() ->
    {MegaSeconds, Seconds, _} = erlang:now(),
    MegaSeconds * 1000000 + Seconds.

update_user(#httpd{mochi_req=MochiReq, user_ctx=UserCtx}=Req, Db, UserName) ->
    case get_user(UserName) of
    nil ->
        throw({not_found, <<"User doesn't exist">>});
    User ->
        Form = parse_form(MochiReq),
        NewPassword = ?l2b(couch_util:get_value("password", Form, "")),
        OldPassword = ?l2b(couch_util:get_value("old_password", Form, "")),

        UserSalt = couch_util:get_value(<<"salt">>, User),
        CurrentPasswordHash = couch_util:get_value(<<"password_sha">>, User),

        Roles = [?l2b(R) || R <- proplists:get_all_values("roles", Form)],
        if Roles /= [] ->
            chttpd:verify_is_server_admin(Req);
        true -> ok end,

        PasswordHash = case NewPassword of
        <<>> ->
            CurrentPasswordHash;
        _Else ->
            case lists:member(<<"_admin">>,UserCtx#user_ctx.roles) of
            true ->
                hash_password(NewPassword, UserSalt);
            false when UserCtx#user_ctx.name == UserName ->
                %% for user we test old password before allowing change
                case hash_password(OldPassword, UserSalt) of
                CurrentPasswordHash ->
                    hash_password(NewPassword, UserSalt);
                _ ->
                    throw({forbidden, <<"Old password is incorrect.">>})
                end;
            _ ->
                Msg = <<"You aren't allowed to change this password.">>,
                throw({forbidden, Msg})
            end
        end,

        Active = chttpd_view:parse_bool_param(couch_util:get_value("active",
            Form, "true")),
        {Pos,Rev} = couch_doc:parse_rev(couch_util:get_value(<<"_rev">>,User)),
        UserDoc = #doc{
            id = UserName,
            revs = {Pos,[Rev]},
            body = {[
                {<<"active">>, Active},
                {<<"email">>, ?l2b(couch_util:get_value("email", Form, ""))},
                {<<"password_sha">>, PasswordHash},
                {<<"roles">>, Roles},
                {<<"salt">>, UserSalt},
                {<<"type">>, <<"user">>},
                {<<"username">>, UserName}
            ]}
        },
        {ok, _Rev} = fabric:update_doc(Db, UserDoc, []),
        ?LOG_DEBUG("User ~s updated.", [UserName]),
        send_response(Req)
    end.