[mod_proxy] move data_fastcgi into mod_proxy.c
[lighttpd.git] / src / mod_auth.c
blobabfdf2d99d89a47bea9d88e16f81b3112fdc73b5
1 #include "first.h"
3 #include "plugin.h"
4 #include "http_auth.h"
5 #include "log.h"
7 #include <stdlib.h>
8 #include <string.h>
10 /**
11 * auth framework
14 typedef struct {
15 /* auth */
16 array *auth_require;
17 buffer *auth_backend_conf;
18 unsigned short auth_extern_authn;
20 /* generated */
21 const http_auth_backend_t *auth_backend;
22 } plugin_config;
24 typedef struct {
25 PLUGIN_DATA;
27 plugin_config **config_storage;
29 plugin_config conf;
30 } plugin_data;
32 static handler_t mod_auth_check_basic(server *srv, connection *con, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend);
33 static handler_t mod_auth_check_digest(server *srv, connection *con, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend);
34 static handler_t mod_auth_check_extern(server *srv, connection *con, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend);
36 INIT_FUNC(mod_auth_init) {
37 static const http_auth_scheme_t http_auth_scheme_basic = { "basic", mod_auth_check_basic, NULL };
38 static const http_auth_scheme_t http_auth_scheme_digest = { "digest", mod_auth_check_digest, NULL };
39 static const http_auth_scheme_t http_auth_scheme_extern = { "extern", mod_auth_check_extern, NULL };
40 plugin_data *p;
42 /* register http_auth_scheme_* */
43 http_auth_scheme_set(&http_auth_scheme_basic);
44 http_auth_scheme_set(&http_auth_scheme_digest);
45 http_auth_scheme_set(&http_auth_scheme_extern);
47 p = calloc(1, sizeof(*p));
49 return p;
52 FREE_FUNC(mod_auth_free) {
53 plugin_data *p = p_d;
55 UNUSED(srv);
57 if (!p) return HANDLER_GO_ON;
59 if (p->config_storage) {
60 size_t i;
61 for (i = 0; i < srv->config_context->used; i++) {
62 plugin_config *s = p->config_storage[i];
64 if (NULL == s) continue;
66 array_free(s->auth_require);
67 buffer_free(s->auth_backend_conf);
69 free(s);
71 free(p->config_storage);
74 free(p);
76 return HANDLER_GO_ON;
79 /* data type for mod_auth structured data
80 * (parsed from auth.require array of strings) */
81 typedef struct {
82 DATA_UNSET;
83 http_auth_require_t *require;
84 } data_auth;
86 static void data_auth_free(data_unset *d)
88 data_auth * const dauth = (data_auth *)d;
89 buffer_free(dauth->key);
90 http_auth_require_free(dauth->require);
91 free(dauth);
94 static data_auth *data_auth_init(void)
96 data_auth * const dauth = calloc(1, sizeof(*dauth));
97 force_assert(NULL != dauth);
98 dauth->copy = NULL; /* must not be called on this data */
99 dauth->free = data_auth_free;
100 dauth->reset = NULL; /* must not be called on this data */
101 dauth->insert_dup = NULL; /* must not be called on this data */
102 dauth->print = NULL; /* must not be called on this data */
103 dauth->type = TYPE_OTHER;
105 dauth->key = buffer_init();
106 dauth->require = http_auth_require_init();
108 return dauth;
111 static int mod_auth_require_parse (server *srv, http_auth_require_t * const require, const buffer *b)
113 /* user=name1|user=name2|group=name3|host=name4 */
115 const char *str = b->ptr;
116 const char *p;
118 if (buffer_is_equal_string(b, CONST_STR_LEN("valid-user"))) {
119 require->valid_user = 1;
120 return 1; /* success */
123 do {
124 const char *eq;
125 size_t len;
126 p = strchr(str, '|');
127 len = NULL != p ? (size_t)(p - str) : strlen(str);
128 eq = memchr(str, '=', len);
129 if (NULL == eq) {
130 log_error_write(srv, __FILE__, __LINE__, "sssbss",
131 "error parsing auth.require 'require' field: missing '='",
132 "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\").",
133 "error value:", b, "error near:", str);
134 return 0;
136 if (p-1 == eq) {
137 log_error_write(srv, __FILE__, __LINE__, "sssbss",
138 "error parsing auth.require 'require' field: missing token after '='",
139 "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\").",
140 "error value:", b, "error near:", str);
141 return 0;
144 switch ((int)(eq - str)) {
145 case 4:
146 if (0 == memcmp(str, CONST_STR_LEN("user"))) {
147 data_string *ds = data_string_init();
148 buffer_copy_string_len(ds->key,str+5,len-5); /*("user=" is 5)*/
149 array_insert_unique(require->user, (data_unset *)ds);
150 continue;
152 else if (0 == memcmp(str, CONST_STR_LEN("host"))) {
153 data_string *ds = data_string_init();
154 buffer_copy_string_len(ds->key,str+5,len-5); /*("host=" is 5)*/
155 array_insert_unique(require->host, (data_unset *)ds);
156 log_error_write(srv, __FILE__, __LINE__, "ssb",
157 "warning parsing auth.require 'require' field: 'host' not implemented;",
158 "field value:", b);
159 continue;
161 break; /* to error */
162 case 5:
163 if (0 == memcmp(str, CONST_STR_LEN("group"))) {
164 data_string *ds = data_string_init();
165 buffer_copy_string_len(ds->key,str+6,len-6); /*("group=" is 6)*/
166 array_insert_unique(require->group, (data_unset *)ds);
167 #if 0/*(supported by mod_authn_ldap, but not all other backends)*/
168 log_error_write(srv, __FILE__, __LINE__, "ssb",
169 "warning parsing auth.require 'require' field: 'group' not implemented;",
170 "field value:", b);
171 #endif
172 continue;
174 break; /* to error */
175 case 10:
176 if (0 == memcmp(str, CONST_STR_LEN("valid-user"))) {
177 log_error_write(srv, __FILE__, __LINE__, "sssb",
178 "error parsing auth.require 'require' field: valid user can not be combined with other require rules",
179 "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\").",
180 "error value:", b);
181 return 0;
183 break; /* to error */
184 default:
185 break; /* to error */
188 log_error_write(srv, __FILE__, __LINE__, "sssbss",
189 "error parsing auth.require 'require' field: invalid/unsupported token",
190 "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\").",
191 "error value:", b, "error near:", str);
192 return 0;
194 } while (p && *((str = p+1)));
196 return 1; /* success */
199 SETDEFAULTS_FUNC(mod_auth_set_defaults) {
200 plugin_data *p = p_d;
201 size_t i;
203 config_values_t cv[] = {
204 { "auth.backend", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
205 { "auth.require", NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
206 { "auth.extern-authn", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION },/* 2 */
207 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
210 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
212 for (i = 0; i < srv->config_context->used; i++) {
213 data_config const* config = (data_config const*)srv->config_context->data[i];
214 plugin_config *s;
215 size_t n;
216 data_array *da;
218 s = calloc(1, sizeof(plugin_config));
219 s->auth_backend_conf = buffer_init();
221 s->auth_require = array_init();
223 cv[0].destination = s->auth_backend_conf;
224 cv[1].destination = s->auth_require; /* T_CONFIG_LOCAL; not modified by config_insert_values_global() */
225 cv[2].destination = &s->auth_extern_authn;
227 p->config_storage[i] = s;
229 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
230 return HANDLER_ERROR;
233 if (!buffer_string_is_empty(s->auth_backend_conf)) {
234 s->auth_backend = http_auth_backend_get(s->auth_backend_conf);
235 if (NULL == s->auth_backend) {
236 log_error_write(srv, __FILE__, __LINE__, "sb", "auth.backend not supported:", s->auth_backend_conf);
238 return HANDLER_ERROR;
242 /* no auth.require for this section */
243 if (NULL == (da = (data_array *)array_get_element(config->value, "auth.require"))) continue;
245 if (da->type != TYPE_ARRAY || !array_is_kvarray(da->value)) {
246 log_error_write(srv, __FILE__, __LINE__, "ss",
247 "unexpected value for auth.require; expected ",
248 "auth.require = ( \"urlpath\" => ( \"option\" => \"value\" ) )");
249 return HANDLER_ERROR;
253 for (n = 0; n < da->value->used; n++) {
254 size_t m;
255 data_array *da_file = (data_array *)da->value->data[n];
256 const buffer *method = NULL, *realm = NULL, *require = NULL;
257 const http_auth_scheme_t *auth_scheme;
259 if (!array_is_kvstring(da_file->value)) {
260 log_error_write(srv, __FILE__, __LINE__, "ss",
261 "unexpected value for auth.require; expected ",
262 "auth.require = ( \"urlpath\" => ( \"option\" => \"value\" ) )");
264 return HANDLER_ERROR;
267 for (m = 0; m < da_file->value->used; m++) {
268 if (da_file->value->data[m]->type == TYPE_STRING) {
269 data_string *ds = (data_string *)da_file->value->data[m];
270 if (buffer_is_equal_string(ds->key, CONST_STR_LEN("method"))) {
271 method = ds->value;
272 } else if (buffer_is_equal_string(ds->key, CONST_STR_LEN("realm"))) {
273 realm = ds->value;
274 } else if (buffer_is_equal_string(ds->key, CONST_STR_LEN("require"))) {
275 require = ds->value;
276 } else {
277 log_error_write(srv, __FILE__, __LINE__, "ssbs",
278 "the field is unknown in:",
279 "auth.require = ( \"...\" => ( ..., -> \"",
280 da_file->value->data[m]->key,
281 "\" <- => \"...\" ) )");
283 return HANDLER_ERROR;
285 } else {
286 log_error_write(srv, __FILE__, __LINE__, "ssbs",
287 "a string was expected for:",
288 "auth.require = ( \"...\" => ( ..., -> \"",
289 da_file->value->data[m]->key,
290 "\" <- => \"...\" ) )");
292 return HANDLER_ERROR;
296 if (buffer_string_is_empty(method)) {
297 log_error_write(srv, __FILE__, __LINE__, "ss",
298 "the method field is missing or blank in:",
299 "auth.require = ( \"...\" => ( ..., \"method\" => \"...\" ) )");
300 return HANDLER_ERROR;
301 } else {
302 auth_scheme = http_auth_scheme_get(method);
303 if (NULL == auth_scheme) {
304 log_error_write(srv, __FILE__, __LINE__, "sbss",
305 "unknown method", method, "(e.g. \"basic\", \"digest\" or \"extern\") in",
306 "auth.require = ( \"...\" => ( ..., \"method\" => \"...\") )");
307 return HANDLER_ERROR;
311 if (buffer_is_empty(realm)) {
312 log_error_write(srv, __FILE__, __LINE__, "ss",
313 "the realm field is missing in:",
314 "auth.require = ( \"...\" => ( ..., \"realm\" => \"...\" ) )");
315 return HANDLER_ERROR;
318 if (buffer_string_is_empty(require)) {
319 log_error_write(srv, __FILE__, __LINE__, "ss",
320 "the require field is missing or blank in:",
321 "auth.require = ( \"...\" => ( ..., \"require\" => \"...\" ) )");
322 return HANDLER_ERROR;
325 if (require) { /*(always true at this point)*/
326 data_auth * const dauth = data_auth_init();
327 buffer_copy_buffer(dauth->key, da_file->key);
328 dauth->require->scheme = auth_scheme;
329 buffer_copy_buffer(dauth->require->realm, realm);
330 if (!mod_auth_require_parse(srv, dauth->require, require)) {
331 dauth->free((data_unset *)dauth);
332 return HANDLER_ERROR;
334 array_insert_unique(s->auth_require, (data_unset *)dauth);
339 return HANDLER_GO_ON;
342 #define PATCH(x) \
343 p->conf.x = s->x;
344 static int mod_auth_patch_connection(server *srv, connection *con, plugin_data *p) {
345 size_t i, j;
346 plugin_config *s = p->config_storage[0];
348 PATCH(auth_backend);
349 PATCH(auth_require);
350 PATCH(auth_extern_authn);
352 /* skip the first, the global context */
353 for (i = 1; i < srv->config_context->used; i++) {
354 data_config *dc = (data_config *)srv->config_context->data[i];
355 s = p->config_storage[i];
357 /* condition didn't match */
358 if (!config_check_cond(srv, con, dc)) continue;
360 /* merge config */
361 for (j = 0; j < dc->value->used; j++) {
362 data_unset *du = dc->value->data[j];
364 if (buffer_is_equal_string(du->key, CONST_STR_LEN("auth.backend"))) {
365 PATCH(auth_backend);
366 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("auth.require"))) {
367 PATCH(auth_require);
368 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("auth.extern-authn"))) {
369 PATCH(auth_extern_authn);
374 return 0;
376 #undef PATCH
378 static handler_t mod_auth_uri_handler(server *srv, connection *con, void *p_d) {
379 size_t k;
380 plugin_data *p = p_d;
382 mod_auth_patch_connection(srv, con, p);
384 if (p->conf.auth_require == NULL) return HANDLER_GO_ON;
386 /* search auth directives for first prefix match against URL path */
387 for (k = 0; k < p->conf.auth_require->used; k++) {
388 const data_auth * const dauth = (data_auth *)p->conf.auth_require->data[k];
389 const buffer *path = dauth->key;
391 if (buffer_string_length(con->uri.path) < buffer_string_length(path)) continue;
393 /* if we have a case-insensitive FS we have to lower-case the URI here too */
395 if (!con->conf.force_lowercase_filenames
396 ? 0 == strncmp(con->uri.path->ptr, path->ptr, buffer_string_length(path))
397 : 0 == strncasecmp(con->uri.path->ptr, path->ptr, buffer_string_length(path))) {
398 const http_auth_scheme_t * const scheme = dauth->require->scheme;
399 if (p->conf.auth_extern_authn) {
400 data_string *ds = (data_string *)array_get_element(con->environment, "REMOTE_USER");
401 if (NULL != ds && http_auth_match_rules(dauth->require, ds->value->ptr, NULL, NULL)) {
402 return HANDLER_GO_ON;
405 return scheme->checkfn(srv, con, scheme->p_d, dauth->require, p->conf.auth_backend);
409 /* nothing to do for us */
410 return HANDLER_GO_ON;
413 int mod_auth_plugin_init(plugin *p);
414 int mod_auth_plugin_init(plugin *p) {
415 p->version = LIGHTTPD_VERSION_ID;
416 p->name = buffer_init_string("auth");
417 p->init = mod_auth_init;
418 p->set_defaults = mod_auth_set_defaults;
419 p->handle_uri_clean = mod_auth_uri_handler;
420 p->cleanup = mod_auth_free;
422 p->data = NULL;
424 return 0;
431 * auth schemes (basic, digest, extern)
433 * (could be in separate file from mod_auth.c as long as registration occurs)
436 #include "response.h"
437 #include "base64.h"
438 #include "md5.h"
439 #include "rand.h"
441 static handler_t mod_auth_send_400_bad_request(server *srv, connection *con) {
442 UNUSED(srv);
444 /* a field was missing or invalid */
445 con->http_status = 400; /* Bad Request */
446 con->mode = DIRECT;
448 return HANDLER_FINISHED;
451 static handler_t mod_auth_send_401_unauthorized_basic(server *srv, connection *con, buffer *realm) {
452 con->http_status = 401;
453 con->mode = DIRECT;
455 buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("Basic realm=\""));
456 buffer_append_string_buffer(srv->tmp_buf, realm);
457 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\", charset=\"UTF-8\""));
459 response_header_insert(srv, con, CONST_STR_LEN("WWW-Authenticate"), CONST_BUF_LEN(srv->tmp_buf));
461 return HANDLER_FINISHED;
464 static handler_t mod_auth_check_basic(server *srv, connection *con, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend) {
465 data_string *ds = (data_string *)array_get_element(con->request.headers, "Authorization");
466 buffer *username;
467 buffer *b;
468 char *pw;
469 handler_t rc = HANDLER_UNSET;
471 UNUSED(p_d);
473 if (NULL == backend) {
474 log_error_write(srv, __FILE__, __LINE__, "sb", "auth.backend not configured for", con->uri.path);
475 con->http_status = 500;
476 con->mode = DIRECT;
477 return HANDLER_FINISHED;
480 if (NULL == ds || buffer_is_empty(ds->value)) {
481 return mod_auth_send_401_unauthorized_basic(srv, con, require->realm);
484 if (0 != strncasecmp(ds->value->ptr, "Basic ", sizeof("Basic ")-1)) {
485 return mod_auth_send_400_bad_request(srv, con);
488 username = buffer_init();
490 b = ds->value;
491 /* coverity[overflow_sink : FALSE] */
492 if (!buffer_append_base64_decode(username, b->ptr+sizeof("Basic ")-1, buffer_string_length(b)-(sizeof("Basic ")-1), BASE64_STANDARD)) {
493 log_error_write(srv, __FILE__, __LINE__, "sb", "decoding base64-string failed", username);
495 buffer_free(username);
496 return mod_auth_send_400_bad_request(srv, con);
499 /* r2 == user:password */
500 if (NULL == (pw = strchr(username->ptr, ':'))) {
501 log_error_write(srv, __FILE__, __LINE__, "sb", "missing ':' in", username);
503 buffer_free(username);
504 return mod_auth_send_400_bad_request(srv, con);
507 buffer_string_set_length(username, pw - username->ptr);
508 pw++;
510 rc = backend->basic(srv, con, backend->p_d, require, username, pw);
511 switch (rc) {
512 case HANDLER_GO_ON:
513 http_auth_setenv(con->environment, CONST_BUF_LEN(username), CONST_STR_LEN("Basic"));
514 break;
515 case HANDLER_WAIT_FOR_EVENT:
516 case HANDLER_FINISHED:
517 break;
518 case HANDLER_ERROR:
519 default:
520 log_error_write(srv, __FILE__, __LINE__, "sbsBsB", "password doesn't match for", con->uri.path, "username:", username, ", IP:", con->dst_addr_buf);
521 rc = HANDLER_UNSET;
522 break;
525 buffer_free(username);
526 return (HANDLER_UNSET != rc) ? rc : mod_auth_send_401_unauthorized_basic(srv, con, require->realm);
529 #define HASHLEN 16
530 #define HASHHEXLEN 32
531 typedef unsigned char HASH[HASHLEN];
532 typedef char HASHHEX[HASHHEXLEN+1];
534 static void CvtHex(const HASH Bin, char (*Hex)[33]) {
535 li_tohex(*Hex, sizeof(*Hex), (const char*) Bin, 16);
538 typedef struct {
539 const char *key;
540 int key_len;
541 char **ptr;
542 } digest_kv;
544 static handler_t mod_auth_send_401_unauthorized_digest(server *srv, connection *con, buffer *realm, int nonce_stale);
546 static handler_t mod_auth_check_digest(server *srv, connection *con, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend) {
547 data_string *ds = (data_string *)array_get_element(con->request.headers, "Authorization");
549 char a1[33];
550 char a2[33];
552 char *username = NULL;
553 char *realm = NULL;
554 char *nonce = NULL;
555 char *uri = NULL;
556 char *algorithm = NULL;
557 char *qop = NULL;
558 char *cnonce = NULL;
559 char *nc = NULL;
560 char *respons = NULL;
562 char *e, *c;
563 const char *m = NULL;
564 int i;
565 buffer *b;
567 li_MD5_CTX Md5Ctx;
568 HASH HA1;
569 HASH HA2;
570 HASH RespHash;
571 HASHHEX HA2Hex;
574 /* init pointers */
575 #define S(x) \
576 x, sizeof(x)-1, NULL
577 digest_kv dkv[10] = {
578 { S("username=") },
579 { S("realm=") },
580 { S("nonce=") },
581 { S("uri=") },
582 { S("algorithm=") },
583 { S("qop=") },
584 { S("cnonce=") },
585 { S("nc=") },
586 { S("response=") },
588 { NULL, 0, NULL }
590 #undef S
592 dkv[0].ptr = &username;
593 dkv[1].ptr = &realm;
594 dkv[2].ptr = &nonce;
595 dkv[3].ptr = &uri;
596 dkv[4].ptr = &algorithm;
597 dkv[5].ptr = &qop;
598 dkv[6].ptr = &cnonce;
599 dkv[7].ptr = &nc;
600 dkv[8].ptr = &respons;
602 UNUSED(p_d);
604 if (NULL == backend) {
605 log_error_write(srv, __FILE__, __LINE__, "sb", "auth.backend not configured for", con->uri.path);
606 con->http_status = 500;
607 con->mode = DIRECT;
608 return HANDLER_FINISHED;
611 if (NULL == ds || buffer_is_empty(ds->value)) {
612 return mod_auth_send_401_unauthorized_digest(srv, con, require->realm, 0);
615 if (0 != strncasecmp(ds->value->ptr, "Digest ", sizeof("Digest ")-1)) {
616 return mod_auth_send_400_bad_request(srv, con);
619 b = buffer_init();
620 /* coverity[overflow_sink : FALSE] */
621 buffer_copy_string_len(b, ds->value->ptr+sizeof("Digest ")-1, buffer_string_length(ds->value)-(sizeof("Digest ")-1));
623 /* parse credentials from client */
624 for (c = b->ptr; *c; c++) {
625 /* skip whitespaces */
626 while (*c == ' ' || *c == '\t') c++;
627 if (!*c) break;
629 for (i = 0; dkv[i].key; i++) {
630 if ((0 == strncmp(c, dkv[i].key, dkv[i].key_len))) {
631 if ((c[dkv[i].key_len] == '"') &&
632 (NULL != (e = strchr(c + dkv[i].key_len + 1, '"')))) {
633 /* value with "..." */
634 *(dkv[i].ptr) = c + dkv[i].key_len + 1;
635 c = e;
637 *e = '\0';
638 } else if (NULL != (e = strchr(c + dkv[i].key_len, ','))) {
639 /* value without "...", terminated by ',' */
640 *(dkv[i].ptr) = c + dkv[i].key_len;
641 c = e;
643 *e = '\0';
644 } else {
645 /* value without "...", terminated by EOL */
646 *(dkv[i].ptr) = c + dkv[i].key_len;
647 c += strlen(c) - 1;
649 break;
654 /* check if everything is transmitted */
655 if (!username ||
656 !realm ||
657 !nonce ||
658 !uri ||
659 (qop && (!nc || !cnonce)) ||
660 !respons ) {
661 /* missing field */
663 log_error_write(srv, __FILE__, __LINE__, "s",
664 "digest: missing field");
666 buffer_free(b);
667 return mod_auth_send_400_bad_request(srv, con);
671 * protect the md5-sess against missing cnonce and nonce
673 if (algorithm &&
674 0 == strcasecmp(algorithm, "md5-sess") &&
675 (!nonce || !cnonce)) {
676 log_error_write(srv, __FILE__, __LINE__, "s",
677 "digest: (md5-sess: missing field");
679 buffer_free(b);
680 return mod_auth_send_400_bad_request(srv, con);
683 if (qop && strcasecmp(qop, "auth-int") == 0) {
684 log_error_write(srv, __FILE__, __LINE__, "s",
685 "digest: qop=auth-int not supported");
687 buffer_free(b);
688 return mod_auth_send_400_bad_request(srv, con);
691 m = get_http_method_name(con->request.http_method);
692 force_assert(m);
694 /* detect if attacker is attempting to reuse valid digest for one uri
695 * on a different request uri. Might also happen if intermediate proxy
696 * altered client request line. (Altered request would not result in
697 * the same digest as that calculated by the client.)
698 * Internal redirects such as with mod_rewrite will modify request uri.
699 * Reauthentication is done to detect crossing auth realms, but this
700 * uri validation step is bypassed. con->request.orig_uri is original
701 * uri sent in client request. */
703 const size_t ulen = strlen(uri);
704 const size_t rlen = buffer_string_length(con->request.orig_uri);
705 if (!buffer_is_equal_string(con->request.orig_uri, uri, ulen)
706 && !(rlen < ulen && 0 == memcmp(con->request.orig_uri->ptr, uri, rlen) && uri[rlen] == '?')) {
707 log_error_write(srv, __FILE__, __LINE__, "sbsssB",
708 "digest: auth failed: uri mismatch (", con->request.orig_uri, "!=", uri, "), IP:", con->dst_addr_buf);
709 buffer_free(b);
710 return mod_auth_send_400_bad_request(srv, con);
714 /* password-string == HA1 */
715 switch (backend->digest(srv, con, backend->p_d, username, realm, HA1)) {
716 case HANDLER_GO_ON:
717 break;
718 case HANDLER_WAIT_FOR_EVENT:
719 buffer_free(b);
720 return HANDLER_WAIT_FOR_EVENT;
721 case HANDLER_FINISHED:
722 buffer_free(b);
723 return HANDLER_FINISHED;
724 case HANDLER_ERROR:
725 default:
726 buffer_free(b);
727 return mod_auth_send_401_unauthorized_digest(srv, con, require->realm, 0);
730 if (algorithm &&
731 strcasecmp(algorithm, "md5-sess") == 0) {
732 li_MD5_Init(&Md5Ctx);
733 /* Errata ID 1649: http://www.rfc-editor.org/errata_search.php?rfc=2617 */
734 CvtHex(HA1, &a1);
735 li_MD5_Update(&Md5Ctx, (unsigned char *)a1, HASHHEXLEN);
736 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
737 li_MD5_Update(&Md5Ctx, (unsigned char *)nonce, strlen(nonce));
738 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
739 li_MD5_Update(&Md5Ctx, (unsigned char *)cnonce, strlen(cnonce));
740 li_MD5_Final(HA1, &Md5Ctx);
743 CvtHex(HA1, &a1);
745 /* calculate H(A2) */
746 li_MD5_Init(&Md5Ctx);
747 li_MD5_Update(&Md5Ctx, (unsigned char *)m, strlen(m));
748 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
749 li_MD5_Update(&Md5Ctx, (unsigned char *)uri, strlen(uri));
750 /* qop=auth-int not supported, already checked above */
752 if (qop && strcasecmp(qop, "auth-int") == 0) {
753 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
754 li_MD5_Update(&Md5Ctx, (unsigned char *) [body checksum], HASHHEXLEN);
757 li_MD5_Final(HA2, &Md5Ctx);
758 CvtHex(HA2, &HA2Hex);
760 /* calculate response */
761 li_MD5_Init(&Md5Ctx);
762 li_MD5_Update(&Md5Ctx, (unsigned char *)a1, HASHHEXLEN);
763 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
764 li_MD5_Update(&Md5Ctx, (unsigned char *)nonce, strlen(nonce));
765 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
766 if (qop && *qop) {
767 li_MD5_Update(&Md5Ctx, (unsigned char *)nc, strlen(nc));
768 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
769 li_MD5_Update(&Md5Ctx, (unsigned char *)cnonce, strlen(cnonce));
770 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
771 li_MD5_Update(&Md5Ctx, (unsigned char *)qop, strlen(qop));
772 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
774 li_MD5_Update(&Md5Ctx, (unsigned char *)HA2Hex, HASHHEXLEN);
775 li_MD5_Final(RespHash, &Md5Ctx);
776 CvtHex(RespHash, &a2);
778 if (0 != strcmp(a2, respons)) {
779 /* digest not ok */
780 log_error_write(srv, __FILE__, __LINE__, "sssB",
781 "digest: auth failed for ", username, ": wrong password, IP:", con->dst_addr_buf);
783 buffer_free(b);
784 return mod_auth_send_401_unauthorized_digest(srv, con, require->realm, 0);
787 /* value is our allow-rules */
788 if (!http_auth_match_rules(require, username, NULL, NULL)) {
789 buffer_free(b);
790 return mod_auth_send_401_unauthorized_digest(srv, con, require->realm, 0);
793 /* check age of nonce. Note, random data is used in nonce generation
794 * in mod_auth_send_401_unauthorized_digest(). If that were replaced
795 * with nanosecond time, then nonce secret would remain unique enough
796 * for the purposes of Digest auth, and would be reproducible (and
797 * verifiable) if nanoseconds were inclued with seconds as part of the
798 * nonce "timestamp:secret". Since that is not done, timestamp in
799 * nonce could theoretically be modified and still produce same md5sum,
800 * but that is highly unlikely within a 10 min (moving) window of valid
801 * time relative to current time (now) */
803 time_t ts = 0;
804 const unsigned char * const nonce_uns = (unsigned char *)nonce;
805 for (i = 0; i < 8 && light_isxdigit(nonce_uns[i]); ++i) {
806 ts = (ts << 4) + hex2int(nonce_uns[i]);
808 if (nonce[i] != ':'
809 || ts > srv->cur_ts || srv->cur_ts - ts > 600) { /*(10 mins)*/
810 /* nonce is stale; have client regenerate digest */
811 buffer_free(b);
812 return mod_auth_send_401_unauthorized_digest(srv, con, require->realm, 1);
813 } /*(future: might send nextnonce when expiration is imminent)*/
816 http_auth_setenv(con->environment, username, strlen(username), CONST_STR_LEN("Digest"));
818 buffer_free(b);
820 return HANDLER_GO_ON;
823 static handler_t mod_auth_send_401_unauthorized_digest(server *srv, connection *con, buffer *realm, int nonce_stale) {
824 li_MD5_CTX Md5Ctx;
825 HASH h;
826 char hh[33];
828 force_assert(33 >= LI_ITOSTRING_LENGTH); /*(buffer used for both li_itostrn() and CvtHex())*/
830 /* generate nonce */
832 /* generate shared-secret */
833 li_MD5_Init(&Md5Ctx);
835 li_itostrn(hh, sizeof(hh), srv->cur_ts);
836 li_MD5_Update(&Md5Ctx, (unsigned char *)hh, strlen(hh));
837 li_itostrn(hh, sizeof(hh), li_rand_pseudo_bytes());
838 li_MD5_Update(&Md5Ctx, (unsigned char *)hh, strlen(hh));
840 li_MD5_Final(h, &Md5Ctx);
842 CvtHex(h, &hh);
844 /* generate WWW-Authenticate */
846 con->http_status = 401;
847 con->mode = DIRECT;
849 buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("Digest realm=\""));
850 buffer_append_string_buffer(srv->tmp_buf, realm);
851 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\", charset=\"UTF-8\", nonce=\""));
852 buffer_append_uint_hex(srv->tmp_buf, (uintmax_t)srv->cur_ts);
853 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN(":"));
854 buffer_append_string(srv->tmp_buf, hh);
855 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\", qop=\"auth\""));
856 if (nonce_stale) {
857 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN(", stale=true"));
860 response_header_insert(srv, con, CONST_STR_LEN("WWW-Authenticate"), CONST_BUF_LEN(srv->tmp_buf));
862 return HANDLER_FINISHED;
865 static handler_t mod_auth_check_extern(server *srv, connection *con, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend) {
866 /* require REMOTE_USER already set */
867 data_string *ds = (data_string *)array_get_element(con->environment, "REMOTE_USER");
868 UNUSED(srv);
869 UNUSED(p_d);
870 UNUSED(backend);
871 if (NULL != ds && http_auth_match_rules(require, ds->value->ptr, NULL, NULL)) {
872 return HANDLER_GO_ON;
873 } else {
874 con->http_status = 401;
875 con->mode = DIRECT;
876 return HANDLER_FINISHED;