forked from cms-sw/cmsdist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bigcouch_cms_auth.erl.file
336 lines (318 loc) · 12.5 KB
/
bigcouch_cms_auth.erl.file
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
% 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.
%
% --------------------------------------------------------------------
%
% This module implements two authentication handlers for the CMS CounchDB
% cluster:
%
% * cms_backend_authentication_handler
% Uses header information set by the WebTool front end to validate
% the source, and then create a user context based on the passed
% header values
%
% * cms_host_authentication_handler
% Authenticates requests against a whitelist specified in the config
% file, resultsing in a user context also defined in the config. If
% not specified, defaults to admin rights.
%
% To use either, specify one of the following in the CouchDB instance config file:
%
% [httpd]
% ; Production handler
% authentication_handlers = {couch_cms_auth, cms_backend_authentication_handler}
% ; Host handler
% authentication_handlers = {couch_cms_auth, cms_host_authentication_hander}
%
% In usual operation, we require two handlers, the backend to handle user
% requests, and the host-based to handle cluster replication. Configure as:
%
% [httpd]
% authentication_handlers = {couch_cms_auth, cms_backend_authentication_hander},
% {couch_cms_auth, cms_host_authentication_handler}
%
% Configuration options have sensible defaults, but they can be overriden
% in the configuration file:
%
% [couch_cms_auth]
% ; For production handler
% authn_dn_header = new-dn-header-name
% authn_login_header = new-login-header-name
% authn_method_header = new-method-header-name
% authn_name_header = new-name-header-name
% authn_hmac_header = new-hmac-header-name
% authz_header_prefix = new-authz-prefix
% validate_hmac = false
% hmac_secret = HEXHEXHEXHEX
% allow_backend_passthrough = true
%
%
% ; For host handler
% allowed_hosts = {www.myhost.com, username1, Role1:Role2},{www.anotherhost.org, name2, Role3}
% allow_host_passthrough = false
%
% For normal CMS WebTools authentication, allow_backend_passthrough should be set
% to true - replicators will authenticate against this, and requests from
% the front ends will fall through to the backend handler
%
% The suggested configuration for CMS deployment is simply:
%
% [httpd]
% authentication_handlers = {couch_httpd_auth, default_authentication_handler},
% {couch_cms_auth, cms_backend_authentication_hander},
% {couch_cms_auth, cms_host_authentication_handler}
%
% [couch_cms_auth]
% hmac_secret = whatever_hex_we_need
% allow_backend_passthrough = true
% allowed_hosts = {backend1.cern.ch, _admin, _admin},
% {backend2.cern.ch, _admin, _admin},
% {backend3.cern.ch, _admin, _admin}
%
% [admins]
% deployment = password
%
% Note that the password for the deployment user will be securely hashed
% when CouchDB is first started. It must be used in the URL to push
% the couchapp locally, for example http://deployment:password@backend1.cern.ch/db
% Also, the hmac_secret can be in another chained
% configuration file (CouchDB can take multiple -a options, I believe) if we
% want to keep it separate
%
-module(couch_cms_auth).
% TODO: can I try/catch this to make it work under standard couch too?`
-include_lib("couch/include/couch_db.hrl").
-export([cms_backend_authentication_handler/1,
cms_host_authentication_handler/1]).
-import(couch_httpd, [header_value/2, host_for_request/1, make_fun_spec_strs/1]).
-import(mochiweb_headers, [to_list/1]).
-import(couch_util, [to_hex/1]).
-import(proplists, [get_value/2]).
-import(lists).
%% @doc CMS WebTools authentication failed
%
% Called in case of auth failure
%
auth_failed() ->
throw({unauthorized, <<"Authorisation failed">>}).
%% @doc CMS WebTools hex / binary helpers
%
% Used to convert keys and hashes to / from hex / binary
% Note that bin_to_hexstr is optimised and will only work
% with 20 byte hashes
%
hexstr_to_bin(S) ->
hexstr_to_bin(lists:reverse(S), []).
hexstr_to_bin([], Acc) ->
list_to_binary(Acc);
hexstr_to_bin([X,Y|T], Acc) ->
{ok, [V], []} = io_lib:fread("~16u", [X,Y]),
hexstr_to_bin(T, [V | Acc]).
bin_to_hexstr(<<X:160/big-unsigned-integer>>) ->
lists:flatten(io_lib:format("~40.16.0b", [X])).
%% @doc CMS WebTools HMAC verification
%
% Verifies a cmsweb HMAC signature
%
cms_verify_hmac(HeaderAuthNDN, ClientAuthNDN,
HeaderAuthNLogin, ClientAuthNLogin,
HeaderAuthNMethod, ClientAuthNMethod,
HeaderAuthNName, ClientAuthNName,
ClientAuthZ, ClientHMAC) ->
% Check validation is required
case couch_config:get("couch_cms_auth", "validate_hmac", "true") of
"false" ->
true;
_ ->
% Construct the AuthN header list
AuthNHeaders = [{HeaderAuthNDN, ClientAuthNDN},
{HeaderAuthNLogin, ClientAuthNLogin},
{HeaderAuthNMethod, ClientAuthNMethod},
{HeaderAuthNName, ClientAuthNName}],
% Check that all headers are present
CheckFun = fun({_, H}) ->
case H of
undefined -> true;
_ -> false
end
end,
case lists:any(CheckFun, AuthNHeaders) of
true ->
% At least one header value was undefined - fail check
false;
false ->
% Convert the AuthZ headers into canonical format and sort
CanonicalMapFun = fun({K, V}) ->
{string:to_lower(K), V}
end,
ClientCanonicalAuthZ = lists:map(CanonicalMapFun, ClientAuthZ),
SortFun = fun({A, _}, {B, _}) ->
A =< B
end,
ClientAuthZSorted = lists:sort(SortFun, ClientCanonicalAuthZ),
AllAuthHeaders = AuthNHeaders ++ ClientAuthZSorted,
% Now convert to expected HMAC signature
FoldFun = fun({H, V}, {Acc1, Acc2}) ->
{Acc1 ++ lists:flatten(io_lib:format("h~.16bv~.16b", [length(H), length(V)])),
Acc2 ++ lists:flatten(io_lib:format("~s~s", [H, V]))}
end,
{Auth1, Auth2} = lists:foldl(FoldFun, {"", ""}, AllAuthHeaders),
Auth = lists:flatten(io_lib:format("~s#~s", [Auth1, Auth2])),
% Get the shared secret
HMACSecretHex = couch_config:get("couch_cms_auth", "hmac_secret", ""),
HMACSecret = hexstr_to_bin(HMACSecretHex),
% Compute the hash
Hash = crypto:sha_mac(HMACSecret, Auth),
HashHex = bin_to_hexstr(Hash),
% Run the comparison
case HashHex of
ClientHMAC ->
true;
_ ->
false
end
end
end.
%% @doc CMS WebTools proxy authentication handler
%
% This handler forwards a validated request from the CMS WebTools front end to couch.
% All requests at this stage are considered authenticated, the auth handler simply
% performs an HMAC check, and then re-formats the authentication headers into the
% CouchDB user context document. If any validation (HMAC, User or Role) fails, a
% user context is not granted. Header names can be specified in the couch configuration
% section [couch_cms_auth]. See documentation at top of file. The resulting user
% context looks like:
%
% {"db":"t1_ch_cern",
% "name":"MyLogin",
% "roles":[["admin",["T1_UK_RAL"]],["role1",["T1_UK_RAL","T1_CH_CERN"]]]
% }
%
cms_backend_authentication_handler(Req) ->
AllowPass = couch_config:get("couch_cms_auth", "allow_backend_passthrough", "false"),
case cms_backend_authentication_handler_worker(Req) of
nil ->
?LOG_DEBUG("Failed backend auth", []),
case AllowPass of
"true" ->
Req;
_ ->
auth_failed()
end;
Req2 ->
?LOG_DEBUG("Passed backend auth", []),
Req2
end.
%% @doc CMS WebTools proxy authentication handler worker
%
% Main worker for CMS backend authentication
%
cms_backend_authentication_handler_worker(#httpd{mochi_req=MochiReq} = Req) ->
% Get the header names from config (or assign defaults)
HeaderAuthNDN = couch_config:get("couch_cms_auth", "authn_dn_header", "cms-authn-dn"),
HeaderAuthNLogin = couch_config:get("couch_cms_auth", "authn_login_header", "cms-authn-login"),
HeaderAuthNMethod = couch_config:get("couch_cms_auth", "authn_method_header", "cms-authn-method"),
HeaderAuthNName = couch_config:get("couch_cms_auth", "authn_name_header", "cms-authn-name"),
HeaderAuthNHMAC = couch_config:get("couch_cms_auth", "authn_hmac_header", "cms-authn-hmac"),
HeaderAuthZPrefix = couch_config:get("couch_cms_auth", "authz_header_prefix", "cms-authz-"),
% Get the AuthN / HMAC headers
ClientAuthNDN = header_value(Req, HeaderAuthNDN),
ClientAuthNLogin = header_value(Req, HeaderAuthNLogin),
ClientAuthNMethod = header_value(Req, HeaderAuthNMethod),
ClientAuthNName = header_value(Req, HeaderAuthNName),
ClientHMAC = header_value(Req, HeaderAuthNHMAC),
% Get all the roles
Headers = MochiReq:get(headers),
HeadersList = mochiweb_headers:to_list(Headers),
FilterFun = fun({K, _V}) when is_atom(K) ->
false;
({K, _V}) ->
lists:prefix(HeaderAuthZPrefix, string:to_lower(K))
end,
ClientAuthZUnsorted = lists:filter(FilterFun, HeadersList),
% Parse the roles
MapFun = fun({K, V}) ->
Groups = string:tokens(V, " "),
[?l2b(string:to_lower(lists:nthtail(length(HeaderAuthZPrefix), K))),
[?l2b(Group) || Group <- Groups]]
end,
ClientRoles = lists:map(MapFun, ClientAuthZUnsorted),
% Now run the authentication
case cms_verify_hmac(HeaderAuthNDN, ClientAuthNDN,
HeaderAuthNLogin, ClientAuthNLogin,
HeaderAuthNMethod, ClientAuthNMethod,
HeaderAuthNName, ClientAuthNName,
ClientAuthZUnsorted, ClientHMAC) of
false -> nil;
true ->
% Authenticate the user
case ClientAuthNLogin of
undefined -> nil;
_ ->
% All validated
Req#httpd{user_ctx=#user_ctx{name=?l2b(ClientAuthNLogin), roles=ClientRoles}}
end
end.
%% @doc CMS WebTools host-based authentication handler
%
% This handler only allows specified hosts
%
% * allowed_hosts : a list of allowed hosts, usernames and roles
% {127.0.0.1, Replicator1, Role}
% * allow_host_passthrough : if true, allows auth to fall through
% to the next handler. For CMS WebTools we want this, as
% replicators will authenticate here, but the front-end
% requests need to fall through to the JSON header auth
%
cms_host_authentication_handler(Req) ->
AllowPass = couch_config:get("couch_cms_auth", "allow_host_passthrough", "falsee"),
case cms_host_authentication_handler_worker(Req) of
nil ->
?LOG_DEBUG("Failed host auth", []),
case AllowPass of
"true" ->
Req;
_ ->
auth_failed()
end;
Req2 ->
?LOG_DEBUG("Passed host auth", []),
Req2
end.
%% @doc CMS WebTools host-based authentication handler
%
% Main worker for cms_host_authentication_hander
%
cms_host_authentication_handler_worker(Req) ->
% Parse the host / permissions list
HostList = couch_httpd:make_fun_spec_strs(couch_config:get("couch_cms_auth", "allowed_hosts", "")),
case length(HostList) of
0 ->
nil;
_ ->
HTTmp = [list_to_tuple(element(2, re:run(X, "{\\s*(.*),\\s*(.*),\\s*(.*)\\s*}",
[{capture, all_but_first, list}]))) || X <- HostList],
HostPermissions = [{?l2b(element(1, X)), [?l2b(element(2, X)),
[?l2b(R) || R <- string:tokens(element(3, X), ":")]]} || X <- HTTmp],
% Check for a match in the host list
Host = ?l2b(Req#httpd.peer),
case proplists:get_value(Host, HostPermissions) of
undefined ->
nil;
[Username, Roles] ->
% Prepare the user context
?LOG_DEBUG("Authenticated host ~s as ~s", [Host, Username]),
?LOG_DEBUG("Authenticated roles:", []),
[?LOG_DEBUG(" Role: ~s", [R]) || R <- Roles],
Req#httpd{user_ctx=#user_ctx{name=Username, roles=Roles}}
end
end.