]> granicus.if.org Git - apache/blob - modules/aaa/mod_auth_basic.c
move a temporary table from r->pool to a temporary
[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     int fake_set:1;
44     int use_digest_algorithm_set:1;
45     int 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
150         conf->fakeuser = NULL;
151         conf->fakepass = NULL;
152         conf->fake_set = 1;
153
154     }
155     else {
156
157         /* if password is unspecified, set it to the fixed string "password" to
158          * be compatible with the behaviour of mod_ssl.
159          */
160         if (!pass) {
161             pass = "password";
162         }
163
164         conf->fakeuser =
165                 ap_expr_parse_cmd(cmd, user, AP_EXPR_FLAG_STRING_RESULT,
166                         &err, NULL);
167         if (err) {
168             return apr_psprintf(cmd->pool,
169                     "Could not parse fake username expression '%s': %s", user,
170                     err);
171         }
172         conf->fakepass =
173                 ap_expr_parse_cmd(cmd, pass, AP_EXPR_FLAG_STRING_RESULT,
174                         &err, NULL);
175         if (err) {
176             return apr_psprintf(cmd->pool,
177                     "Could not parse fake password expression '%s': %s", user,
178                     err);
179         }
180         conf->fake_set = 1;
181
182     }
183
184     return NULL;
185 }
186
187 static const char *set_use_digest_algorithm(cmd_parms *cmd, void *config,
188                                             const char *alg)
189 {
190     auth_basic_config_rec *conf = (auth_basic_config_rec *)config;
191
192     if (strcasecmp(alg, "Off") && strcasecmp(alg, "MD5")) {
193         return apr_pstrcat(cmd->pool,
194                            "Invalid algorithm in "
195                            "AuthBasicUseDigestAlgorithm: ", alg, NULL);
196     }
197
198     conf->use_digest_algorithm = apr_pstrdup(cmd->pool, alg);
199     conf->use_digest_algorithm_set = 1;
200
201     return NULL;
202 }
203
204 static const command_rec auth_basic_cmds[] =
205 {
206     AP_INIT_ITERATE("AuthBasicProvider", add_authn_provider, NULL, OR_AUTHCFG,
207                     "specify the auth providers for a directory or location"),
208     AP_INIT_FLAG("AuthBasicAuthoritative", set_authoritative, NULL, OR_AUTHCFG,
209                  "Set to 'Off' to allow access control to be passed along to "
210                  "lower modules if the UserID is not known to this module"),
211     AP_INIT_TAKE12("AuthBasicFake", add_basic_fake, NULL, OR_AUTHCFG,
212                   "Fake basic authentication using the given expressions for "
213                   "username and password, 'off' to disable. Password defaults "
214                   "to 'password' if missing."),
215     AP_INIT_TAKE1("AuthBasicUseDigestAlgorithm", set_use_digest_algorithm,
216                   NULL, OR_AUTHCFG,
217                   "Set to 'MD5' to use the auth provider's authentication "
218                   "check for digest auth, using a hash of 'user:realm:pass'"),
219     {NULL}
220 };
221
222 module AP_MODULE_DECLARE_DATA auth_basic_module;
223
224 /* These functions return 0 if client is OK, and proper error status
225  * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
226  * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
227  * couldn't figure out how to tell if the client is authorized or not.
228  *
229  * If they return DECLINED, and all other modules also decline, that's
230  * treated by the server core as a configuration error, logged and
231  * reported as such.
232  */
233
234 static void note_basic_auth_failure(request_rec *r)
235 {
236     apr_table_setn(r->err_headers_out,
237                    (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate"
238                                                    : "WWW-Authenticate",
239                    apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r),
240                                "\"", NULL));
241 }
242
243 static int hook_note_basic_auth_failure(request_rec *r, const char *auth_type)
244 {
245     if (strcasecmp(auth_type, "Basic"))
246         return DECLINED;
247
248     note_basic_auth_failure(r);
249     return OK;
250 }
251
252 static int get_basic_auth(request_rec *r, const char **user,
253                           const char **pw)
254 {
255     const char *auth_line;
256     char *decoded_line;
257     int length;
258
259     /* Get the appropriate header */
260     auth_line = apr_table_get(r->headers_in, (PROXYREQ_PROXY == r->proxyreq)
261                                               ? "Proxy-Authorization"
262                                               : "Authorization");
263
264     if (!auth_line) {
265         note_basic_auth_failure(r);
266         return HTTP_UNAUTHORIZED;
267     }
268
269     if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
270         /* Client tried to authenticate using wrong auth scheme */
271         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01614)
272                       "client used wrong authentication scheme: %s", r->uri);
273         note_basic_auth_failure(r);
274         return HTTP_UNAUTHORIZED;
275     }
276
277     /* Skip leading spaces. */
278     while (apr_isspace(*auth_line)) {
279         auth_line++;
280     }
281
282     decoded_line = apr_palloc(r->pool, apr_base64_decode_len(auth_line) + 1);
283     length = apr_base64_decode(decoded_line, auth_line);
284     /* Null-terminate the string. */
285     decoded_line[length] = '\0';
286
287     *user = ap_getword_nulls(r->pool, (const char**)&decoded_line, ':');
288     *pw = decoded_line;
289
290     /* set the user, even though the user is unauthenticated at this point */
291     r->user = (char *) *user;
292
293     return OK;
294 }
295
296 /* Determine user ID, and check if it really is that user, for HTTP
297  * basic authentication...
298  */
299 static int authenticate_basic_user(request_rec *r)
300 {
301     auth_basic_config_rec *conf = ap_get_module_config(r->per_dir_config,
302                                                        &auth_basic_module);
303     const char *sent_user, *sent_pw, *current_auth;
304     const char *realm = NULL;
305     const char *digest = NULL;
306     int res;
307     authn_status auth_result;
308     authn_provider_list *current_provider;
309
310     /* Are we configured to be Basic auth? */
311     current_auth = ap_auth_type(r);
312     if (!current_auth || strcasecmp(current_auth, "Basic")) {
313         return DECLINED;
314     }
315
316     /* We need an authentication realm. */
317     if (!ap_auth_name(r)) {
318         ap_log_rerror(APLOG_MARK, APLOG_ERR,
319                       0, r, APLOGNO(01615) "need AuthName: %s", r->uri);
320         return HTTP_INTERNAL_SERVER_ERROR;
321     }
322
323     r->ap_auth_type = (char*)current_auth;
324
325     res = get_basic_auth(r, &sent_user, &sent_pw);
326     if (res) {
327         return res;
328     }
329
330     if (conf->use_digest_algorithm
331         && !strcasecmp(conf->use_digest_algorithm, "MD5")) {
332         realm = ap_auth_name(r);
333         digest = ap_md5(r->pool,
334                         (unsigned char *)apr_pstrcat(r->pool, sent_user, ":",
335                                                      realm, ":",
336                                                      sent_pw, NULL));
337     }
338
339     current_provider = conf->providers;
340     do {
341         const authn_provider *provider;
342
343         /* For now, if a provider isn't set, we'll be nice and use the file
344          * provider.
345          */
346         if (!current_provider) {
347             provider = ap_lookup_provider(AUTHN_PROVIDER_GROUP,
348                                           AUTHN_DEFAULT_PROVIDER,
349                                           AUTHN_PROVIDER_VERSION);
350
351             if (!provider || !provider->check_password) {
352                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01616)
353                               "No Authn provider configured");
354                 auth_result = AUTH_GENERAL_ERROR;
355                 break;
356             }
357             apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, AUTHN_DEFAULT_PROVIDER);
358         }
359         else {
360             provider = current_provider->provider;
361             apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, current_provider->provider_name);
362         }
363
364         if (digest) {
365             char *password;
366
367             if (!provider->get_realm_hash) {
368                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02493)
369                               "Authn provider does not support "
370                               "AuthBasicUseDigestAlgorithm");
371                 auth_result = AUTH_GENERAL_ERROR;
372                 break;
373             }
374             /* We expect the password to be hash of user:realm:password */
375             auth_result = provider->get_realm_hash(r, sent_user, realm,
376                                                    &password);
377             if (auth_result == AUTH_USER_FOUND) {
378                 auth_result = strcmp(digest, password) ? AUTH_DENIED
379                                                        : AUTH_GRANTED;
380             }
381         }
382         else {
383             auth_result = provider->check_password(r, sent_user, sent_pw);
384         }
385
386         apr_table_unset(r->notes, AUTHN_PROVIDER_NAME_NOTE);
387
388         /* Something occured. Stop checking. */
389         if (auth_result != AUTH_USER_NOT_FOUND) {
390             break;
391         }
392
393         /* If we're not really configured for providers, stop now. */
394         if (!conf->providers) {
395             break;
396         }
397
398         current_provider = current_provider->next;
399     } while (current_provider);
400
401     if (auth_result != AUTH_GRANTED) {
402         int return_code;
403
404         /* If we're not authoritative, then any error is ignored. */
405         if (!(conf->authoritative) && auth_result != AUTH_DENIED) {
406             return DECLINED;
407         }
408
409         switch (auth_result) {
410         case AUTH_DENIED:
411             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01617)
412                       "user %s: authentication failure for \"%s\": "
413                       "Password Mismatch",
414                       sent_user, r->uri);
415             return_code = HTTP_UNAUTHORIZED;
416             break;
417         case AUTH_USER_NOT_FOUND:
418             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01618)
419                       "user %s not found: %s", sent_user, r->uri);
420             return_code = HTTP_UNAUTHORIZED;
421             break;
422         case AUTH_HANDLED:
423             return_code = r->status;
424             break;
425         case AUTH_GENERAL_ERROR:
426         default:
427             /* We'll assume that the module has already said what its error
428              * was in the logs.
429              */
430             return_code = HTTP_INTERNAL_SERVER_ERROR;
431             break;
432         }
433
434         /* If we're returning 403, tell them to try again. */
435         if (return_code == HTTP_UNAUTHORIZED) {
436             note_basic_auth_failure(r);
437         }
438         return return_code;
439     }
440
441     return OK;
442 }
443
444 /* If requested, create a fake basic authentication header for the benefit
445  * of a proxy or application running behind this server.
446  */
447 static int authenticate_basic_fake(request_rec *r)
448 {
449     const char *auth_line, *user, *pass, *err;
450     auth_basic_config_rec *conf = ap_get_module_config(r->per_dir_config,
451                                                        &auth_basic_module);
452
453     if (!conf->fakeuser) {
454         return DECLINED;
455     }
456
457     user = ap_expr_str_exec(r, conf->fakeuser, &err);
458     if (err) {
459         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02455)
460                       "AuthBasicFake: could not evaluate user expression for URI '%s': %s", r->uri, err);
461         return HTTP_INTERNAL_SERVER_ERROR;
462     }
463     if (!user || !*user) {
464         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02458)
465                       "AuthBasicFake: empty username expression for URI '%s', ignoring", r->uri);
466
467         apr_table_unset(r->headers_in, "Authorization");
468
469         return DECLINED;
470     }
471
472     pass = ap_expr_str_exec(r, conf->fakepass, &err);
473     if (err) {
474         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02456)
475                       "AuthBasicFake: could not evaluate password expression for URI '%s': %s", r->uri, err);
476         return HTTP_INTERNAL_SERVER_ERROR;
477     }
478     if (!pass || !*pass) {
479         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02459)
480                       "AuthBasicFake: empty password expression for URI '%s', ignoring", r->uri);
481
482         apr_table_unset(r->headers_in, "Authorization");
483
484         return DECLINED;
485     }
486
487     auth_line = apr_pstrcat(r->pool, "Basic ",
488                             ap_pbase64encode(r->pool,
489                                              apr_pstrcat(r->pool, user,
490                                                          ":", pass, NULL)),
491                             NULL);
492     apr_table_setn(r->headers_in, "Authorization", auth_line);
493
494     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02457)
495                   "AuthBasicFake: \"Authorization: %s\"",
496                   auth_line);
497
498     return OK;
499 }
500
501 static void register_hooks(apr_pool_t *p)
502 {
503     ap_hook_check_authn(authenticate_basic_user, NULL, NULL, APR_HOOK_MIDDLE,
504                         AP_AUTH_INTERNAL_PER_CONF);
505     ap_hook_fixups(authenticate_basic_fake, NULL, NULL, APR_HOOK_LAST);
506     ap_hook_note_auth_failure(hook_note_basic_auth_failure, NULL, NULL,
507                               APR_HOOK_MIDDLE);
508 }
509
510 AP_DECLARE_MODULE(auth_basic) =
511 {
512     STANDARD20_MODULE_STUFF,
513     create_auth_basic_dir_config,  /* dir config creater */
514     merge_auth_basic_dir_config,   /* dir merger --- default is to override */
515     NULL,                          /* server config */
516     NULL,                          /* merge server config */
517     auth_basic_cmds,               /* command apr_table_t */
518     register_hooks                 /* register hooks */
519 };