]> granicus.if.org Git - apache/blob - modules/aaa/mod_auth_basic.c
Fix a comment similar to r1638072
[apache] / modules / aaa / mod_auth_basic.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "apr_strings.h"
18 #include "apr_lib.h"            /* for apr_isspace */
19 #include "apr_base64.h"         /* for apr_base64_decode et al */
20 #define APR_WANT_STRFUNC        /* for strcasecmp */
21 #include "apr_want.h"
22
23 #include "ap_config.h"
24 #include "httpd.h"
25 #include "http_config.h"
26 #include "http_core.h"
27 #include "http_log.h"
28 #include "http_protocol.h"
29 #include "http_request.h"
30 #include "util_md5.h"
31 #include "ap_provider.h"
32 #include "ap_expr.h"
33
34 #include "mod_auth.h"
35
36 typedef struct {
37     authn_provider_list *providers;
38     char *dir; /* unused variable */
39     int authoritative;
40     ap_expr_info_t *fakeuser;
41     ap_expr_info_t *fakepass;
42     const char *use_digest_algorithm;
43     unsigned int fake_set:1,
44                  use_digest_algorithm_set:1,
45                  authoritative_set:1;
46 } auth_basic_config_rec;
47
48 static void *create_auth_basic_dir_config(apr_pool_t *p, char *d)
49 {
50     auth_basic_config_rec *conf = apr_pcalloc(p, sizeof(*conf));
51
52     /* Any failures are fatal. */
53     conf->authoritative = 1;
54
55     return conf;
56 }
57
58 static void *merge_auth_basic_dir_config(apr_pool_t *p, void *basev, void *overridesv)
59 {
60     auth_basic_config_rec *newconf = apr_pcalloc(p, sizeof(*newconf));
61     auth_basic_config_rec *base = basev;
62     auth_basic_config_rec *overrides = overridesv;
63
64     newconf->authoritative =
65             overrides->authoritative_set ? overrides->authoritative :
66                     base->authoritative;
67     newconf->authoritative_set = overrides->authoritative_set
68             || base->authoritative_set;
69
70     newconf->fakeuser =
71             overrides->fake_set ? overrides->fakeuser : base->fakeuser;
72     newconf->fakepass =
73             overrides->fake_set ? overrides->fakepass : base->fakepass;
74     newconf->fake_set = overrides->fake_set || base->fake_set;
75
76     newconf->use_digest_algorithm =
77         overrides->use_digest_algorithm_set ? overrides->use_digest_algorithm
78                                             : base->use_digest_algorithm;
79     newconf->use_digest_algorithm_set =
80         overrides->use_digest_algorithm_set || base->use_digest_algorithm_set;
81
82     newconf->providers = overrides->providers ? overrides->providers : base->providers;
83
84     return newconf;
85 }
86
87 static const char *add_authn_provider(cmd_parms *cmd, void *config,
88                                       const char *arg)
89 {
90     auth_basic_config_rec *conf = (auth_basic_config_rec*)config;
91     authn_provider_list *newp;
92
93     newp = apr_pcalloc(cmd->pool, sizeof(authn_provider_list));
94     newp->provider_name = arg;
95
96     /* lookup and cache the actual provider now */
97     newp->provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
98                                         newp->provider_name,
99                                         AUTHN_PROVIDER_VERSION);
100
101     if (newp->provider == NULL) {
102         /* by the time they use it, the provider should be loaded and
103            registered with us. */
104         return apr_psprintf(cmd->pool,
105                             "Unknown Authn provider: %s",
106                             newp->provider_name);
107     }
108
109     if (!newp->provider->check_password) {
110         /* if it doesn't provide the appropriate function, reject it */
111         return apr_psprintf(cmd->pool,
112                             "The '%s' Authn provider doesn't support "
113                             "Basic Authentication", newp->provider_name);
114     }
115
116     /* Add it to the list now. */
117     if (!conf->providers) {
118         conf->providers = newp;
119     }
120     else {
121         authn_provider_list *last = conf->providers;
122
123         while (last->next) {
124             last = last->next;
125         }
126         last->next = newp;
127     }
128
129     return NULL;
130 }
131
132 static const char *set_authoritative(cmd_parms * cmd, void *config, int flag)
133 {
134     auth_basic_config_rec *conf = (auth_basic_config_rec *) config;
135
136     conf->authoritative = flag;
137     conf->authoritative_set = 1;
138
139     return NULL;
140 }
141
142 static const char *add_basic_fake(cmd_parms * cmd, void *config,
143         const char *user, const char *pass)
144 {
145     auth_basic_config_rec *conf = (auth_basic_config_rec *) config;
146     const char *err;
147
148     if (!strcasecmp(user, "off")) {
149         conf->fakeuser = NULL;
150         conf->fakepass = NULL;
151         conf->fake_set = 1;
152     }
153     else {
154         /* if password is unspecified, set it to the fixed string "password" to
155          * be compatible with the behaviour of mod_ssl.
156          */
157         if (!pass) {
158             pass = "password";
159         }
160
161         conf->fakeuser =
162                 ap_expr_parse_cmd(cmd, user, AP_EXPR_FLAG_STRING_RESULT,
163                         &err, NULL);
164         if (err) {
165             return apr_psprintf(cmd->pool,
166                     "Could not parse fake username expression '%s': %s", user,
167                     err);
168         }
169         conf->fakepass =
170                 ap_expr_parse_cmd(cmd, pass, AP_EXPR_FLAG_STRING_RESULT,
171                         &err, NULL);
172         if (err) {
173             return apr_psprintf(cmd->pool,
174                     "Could not parse fake password expression '%s': %s", pass,
175                     err);
176         }
177         conf->fake_set = 1;
178     }
179
180     return NULL;
181 }
182
183 static const char *set_use_digest_algorithm(cmd_parms *cmd, void *config,
184                                             const char *alg)
185 {
186     auth_basic_config_rec *conf = (auth_basic_config_rec *)config;
187
188     if (strcasecmp(alg, "Off") && strcasecmp(alg, "MD5")) {
189         return apr_pstrcat(cmd->pool,
190                            "Invalid algorithm in "
191                            "AuthBasicUseDigestAlgorithm: ", alg, NULL);
192     }
193
194     conf->use_digest_algorithm = alg;
195     conf->use_digest_algorithm_set = 1;
196
197     return NULL;
198 }
199
200 static const command_rec auth_basic_cmds[] =
201 {
202     AP_INIT_ITERATE("AuthBasicProvider", add_authn_provider, NULL, OR_AUTHCFG,
203                     "specify the auth providers for a directory or location"),
204     AP_INIT_FLAG("AuthBasicAuthoritative", set_authoritative, NULL, OR_AUTHCFG,
205                  "Set to 'Off' to allow access control to be passed along to "
206                  "lower modules if the UserID is not known to this module"),
207     AP_INIT_TAKE12("AuthBasicFake", add_basic_fake, NULL, OR_AUTHCFG,
208                   "Fake basic authentication using the given expressions for "
209                   "username and password, 'off' to disable. Password defaults "
210                   "to 'password' if missing."),
211     AP_INIT_TAKE1("AuthBasicUseDigestAlgorithm", set_use_digest_algorithm,
212                   NULL, OR_AUTHCFG,
213                   "Set to 'MD5' to use the auth provider's authentication "
214                   "check for digest auth, using a hash of 'user:realm:pass'"),
215     {NULL}
216 };
217
218 module AP_MODULE_DECLARE_DATA auth_basic_module;
219
220 /* These functions return 0 if client is OK, and proper error status
221  * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
222  * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
223  * couldn't figure out how to tell if the client is authorized or not.
224  *
225  * If they return DECLINED, and all other modules also decline, that's
226  * treated by the server core as a configuration error, logged and
227  * reported as such.
228  */
229
230 static void note_basic_auth_failure(request_rec *r)
231 {
232     apr_table_setn(r->err_headers_out,
233                    (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate"
234                                                    : "WWW-Authenticate",
235                    apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r),
236                                "\"", NULL));
237 }
238
239 static int hook_note_basic_auth_failure(request_rec *r, const char *auth_type)
240 {
241     if (ap_casecmpstr(auth_type, "Basic"))
242         return DECLINED;
243
244     note_basic_auth_failure(r);
245     return OK;
246 }
247
248 static int get_basic_auth(request_rec *r, const char **user,
249                           const char **pw)
250 {
251     const char *auth_line;
252     char *decoded_line;
253
254     /* Get the appropriate header */
255     auth_line = apr_table_get(r->headers_in, (PROXYREQ_PROXY == r->proxyreq)
256                                               ? "Proxy-Authorization"
257                                               : "Authorization");
258
259     if (!auth_line) {
260         note_basic_auth_failure(r);
261         return HTTP_UNAUTHORIZED;
262     }
263
264     if (ap_casecmpstr(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
265         /* Client tried to authenticate using wrong auth scheme */
266         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01614)
267                       "client used wrong authentication scheme: %s", r->uri);
268         note_basic_auth_failure(r);
269         return HTTP_UNAUTHORIZED;
270     }
271
272     /* Skip leading spaces. */
273     while (apr_isspace(*auth_line)) {
274         auth_line++;
275     }
276
277     decoded_line = ap_pbase64decode(r->pool, auth_line);
278
279     *user = ap_getword_nulls(r->pool, (const char**)&decoded_line, ':');
280     *pw = decoded_line;
281
282     /* set the user, even though the user is unauthenticated at this point */
283     r->user = (char *) *user;
284
285     return OK;
286 }
287
288 /* Determine user ID, and check if it really is that user, for HTTP
289  * basic authentication...
290  */
291 static int authenticate_basic_user(request_rec *r)
292 {
293     auth_basic_config_rec *conf = ap_get_module_config(r->per_dir_config,
294                                                        &auth_basic_module);
295     const char *sent_user, *sent_pw, *current_auth;
296     const char *realm = NULL;
297     const char *digest = NULL;
298     int res;
299     authn_status auth_result;
300     authn_provider_list *current_provider;
301
302     /* Are we configured to be Basic auth? */
303     current_auth = ap_auth_type(r);
304     if (!current_auth || ap_casecmpstr(current_auth, "Basic")) {
305         return DECLINED;
306     }
307
308     /* We need an authentication realm. */
309     if (!ap_auth_name(r)) {
310         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01615)
311                       "need AuthName: %s", r->uri);
312         return HTTP_INTERNAL_SERVER_ERROR;
313     }
314
315     r->ap_auth_type = (char*)current_auth;
316
317     res = get_basic_auth(r, &sent_user, &sent_pw);
318     if (res) {
319         return res;
320     }
321
322     if (conf->use_digest_algorithm
323         && !strcasecmp(conf->use_digest_algorithm, "MD5")) {
324         realm = ap_auth_name(r);
325         digest = ap_md5(r->pool,
326                         (unsigned char *)apr_pstrcat(r->pool, sent_user, ":",
327                                                      realm, ":",
328                                                      sent_pw, NULL));
329     }
330
331     current_provider = conf->providers;
332     do {
333         const authn_provider *provider;
334
335         /* For now, if a provider isn't set, we'll be nice and use the file
336          * provider.
337          */
338         if (!current_provider) {
339             provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
340                                           AUTHN_DEFAULT_PROVIDER,
341                                           AUTHN_PROVIDER_VERSION);
342
343             if (!provider || !provider->check_password) {
344                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01616)
345                               "No Authn provider configured");
346                 auth_result = AUTH_GENERAL_ERROR;
347                 break;
348             }
349             apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, AUTHN_DEFAULT_PROVIDER);
350         }
351         else {
352             provider = current_provider->provider;
353             apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, current_provider->provider_name);
354         }
355
356         if (digest) {
357             char *password;
358
359             if (!provider->get_realm_hash) {
360                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02493)
361                               "Authn provider does not support "
362                               "AuthBasicUseDigestAlgorithm");
363                 auth_result = AUTH_GENERAL_ERROR;
364                 break;
365             }
366             /* We expect the password to be hash of user:realm:password */
367             auth_result = provider->get_realm_hash(r, sent_user, realm,
368                                                    &password);
369             if (auth_result == AUTH_USER_FOUND) {
370                 auth_result = strcmp(digest, password) ? AUTH_DENIED
371                                                        : AUTH_GRANTED;
372             }
373         }
374         else {
375             auth_result = provider->check_password(r, sent_user, sent_pw);
376         }
377
378         apr_table_unset(r->notes, AUTHN_PROVIDER_NAME_NOTE);
379
380         /* Something occured. Stop checking. */
381         if (auth_result != AUTH_USER_NOT_FOUND) {
382             break;
383         }
384
385         /* If we're not really configured for providers, stop now. */
386         if (!conf->providers) {
387             break;
388         }
389
390         current_provider = current_provider->next;
391     } while (current_provider);
392
393     if (auth_result != AUTH_GRANTED) {
394         int return_code;
395
396         /* If we're not authoritative, then any error is ignored. */
397         if (!(conf->authoritative) && auth_result != AUTH_DENIED) {
398             return DECLINED;
399         }
400
401         switch (auth_result) {
402         case AUTH_DENIED:
403             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01617)
404                       "user %s: authentication failure for \"%s\": "
405                       "Password Mismatch",
406                       sent_user, r->uri);
407             return_code = HTTP_UNAUTHORIZED;
408             break;
409         case AUTH_USER_NOT_FOUND:
410             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01618)
411                       "user %s not found: %s", sent_user, r->uri);
412             return_code = HTTP_UNAUTHORIZED;
413             break;
414         case AUTH_HANDLED:
415             return_code = r->status;
416             break;
417         case AUTH_GENERAL_ERROR:
418         default:
419             /* We'll assume that the module has already said what its error
420              * was in the logs.
421              */
422             return_code = HTTP_INTERNAL_SERVER_ERROR;
423             break;
424         }
425
426         /* If we're returning 401, tell them to try again. */
427         if (return_code == HTTP_UNAUTHORIZED) {
428             note_basic_auth_failure(r);
429         }
430         return return_code;
431     }
432
433     return OK;
434 }
435
436 /* If requested, create a fake basic authentication header for the benefit
437  * of a proxy or application running behind this server.
438  */
439 static int authenticate_basic_fake(request_rec *r)
440 {
441     const char *auth_line, *user, *pass, *err;
442     auth_basic_config_rec *conf = ap_get_module_config(r->per_dir_config,
443                                                        &auth_basic_module);
444
445     if (!conf->fakeuser) {
446         return DECLINED;
447     }
448
449     user = ap_expr_str_exec(r, conf->fakeuser, &err);
450     if (err) {
451         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02455)
452                       "AuthBasicFake: could not evaluate user expression for URI '%s': %s", r->uri, err);
453         return HTTP_INTERNAL_SERVER_ERROR;
454     }
455     if (!user || !*user) {
456         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02458)
457                       "AuthBasicFake: empty username expression for URI '%s', ignoring", r->uri);
458
459         apr_table_unset(r->headers_in, "Authorization");
460
461         return DECLINED;
462     }
463
464     pass = ap_expr_str_exec(r, conf->fakepass, &err);
465     if (err) {
466         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02456)
467                       "AuthBasicFake: could not evaluate password expression for URI '%s': %s", r->uri, err);
468         return HTTP_INTERNAL_SERVER_ERROR;
469     }
470     if (!pass || !*pass) {
471         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02459)
472                       "AuthBasicFake: empty password expression for URI '%s', ignoring", r->uri);
473
474         apr_table_unset(r->headers_in, "Authorization");
475
476         return DECLINED;
477     }
478
479     auth_line = apr_pstrcat(r->pool, "Basic ",
480                             ap_pbase64encode(r->pool,
481                                              apr_pstrcat(r->pool, user,
482                                                          ":", pass, NULL)),
483                             NULL);
484     apr_table_setn(r->headers_in, "Authorization", auth_line);
485
486     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02457)
487                   "AuthBasicFake: \"Authorization: %s\"",
488                   auth_line);
489
490     return OK;
491 }
492
493 static void register_hooks(apr_pool_t *p)
494 {
495     ap_hook_check_authn(authenticate_basic_user, NULL, NULL, APR_HOOK_MIDDLE,
496                         AP_AUTH_INTERNAL_PER_CONF);
497     ap_hook_fixups(authenticate_basic_fake, NULL, NULL, APR_HOOK_LAST);
498     ap_hook_note_auth_failure(hook_note_basic_auth_failure, NULL, NULL,
499                               APR_HOOK_MIDDLE);
500 }
501
502 AP_DECLARE_MODULE(auth_basic) =
503 {
504     STANDARD20_MODULE_STUFF,
505     create_auth_basic_dir_config,  /* dir config creater */
506     merge_auth_basic_dir_config,   /* dir merger --- default is to override */
507     NULL,                          /* server config */
508     NULL,                          /* merge server config */
509     auth_basic_cmds,               /* command apr_table_t */
510     register_hooks                 /* register hooks */
511 };