xref: /lighttpd1.4/src/mod_auth.c (revision 463c60ce)
1 /*
2  * http_auth - HTTP authentication and authorization
3  *
4  * Largely-rewritten from original
5  * Copyright(c) 2016,2021 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
6  * License: BSD 3-clause (same as lighttpd)
7  */
8 #include "first.h"
9 
10 #include <stdlib.h>
11 #include <string.h>
12 
13 #include "mod_auth_api.h"
14 #include "sys-crypto-md.h" /* USE_LIB_CRYPTO */
15 
16 #include "base.h"
17 #include "ck.h"
18 #include "http_header.h"
19 #include "log.h"
20 #include "algo_splaytree.h"
21 #include "plugin.h"
22 #include "plugin_config.h"
23 
24 /**
25  * auth framework
26  */
27 
28 typedef struct {
29     splay_tree *sptree; /* data in nodes of tree are (http_auth_cache_entry *)*/
30     time_t max_age;
31 } http_auth_cache;
32 
33 typedef struct {
34     const http_auth_backend_t *auth_backend;
35     const array *auth_require;
36     http_auth_cache *auth_cache;
37     unsigned int auth_extern_authn;
38 } plugin_config;
39 
40 typedef struct {
41     PLUGIN_DATA;
42     plugin_config defaults;
43     plugin_config conf;
44 } plugin_data;
45 
46 typedef struct {
47     const struct http_auth_require_t *require;
48     unix_time64_t ctime;
49     int dalgo;
50     uint32_t dlen;
51     uint32_t ulen;
52     uint32_t klen;
53     char *k;
54     char *username;
55     char *pwdigest;
56 } http_auth_cache_entry;
57 
58 static http_auth_cache_entry *
59 http_auth_cache_entry_init (const struct http_auth_require_t * const require, const int dalgo, const char *k, const uint32_t klen, const char *username, const uint32_t ulen, const char *pw, const uint32_t pwlen)
60 {
61     /*(similar to buffer_copy_string_len() for each element,
62      * but allocate exact lengths in single chunk of memory
63      * for cache to avoid wasting space and for memory locality)*/
64     /* http_auth_require_t is stored instead of copying realm
65      *(store pointer to http_auth_require_t, which is persistent
66      * and will be different for each realm + permissions combo)*/
67     http_auth_cache_entry * const ae =
68       malloc(sizeof(http_auth_cache_entry) + ulen + pwlen
69              + (k == username ? 0 : klen));
70     force_assert(ae);
71     ae->require = require;
72     ae->ctime = log_monotonic_secs;
73     ae->dalgo = dalgo;
74     ae->ulen = ulen;
75     ae->dlen = pwlen;
76     ae->klen = klen;
77     ae->username = (char *)(ae + 1);
78     ae->pwdigest = ae->username + ulen;
79     ae->k = (k == username)
80       ? ae->username
81       : memcpy(ae->pwdigest + pwlen, k, klen);
82     memcpy(ae->username, username, ulen);
83     memcpy(ae->pwdigest, pw, pwlen);
84     return ae;
85 }
86 
87 static void
88 http_auth_cache_entry_free (void *data)
89 {
90     http_auth_cache_entry * const ae = data;
91     ck_memzero(ae->pwdigest, ae->dlen);
92     free(ae);
93 }
94 
95 static void
96 http_auth_cache_free (http_auth_cache *ac)
97 {
98     splay_tree *sptree = ac->sptree;
99     while (sptree) {
100         http_auth_cache_entry_free(sptree->data);
101         sptree = splaytree_delete(sptree, sptree->key);
102     }
103     free(ac);
104 }
105 
106 static http_auth_cache *
107 http_auth_cache_init (const array *opts)
108 {
109     http_auth_cache *ac = malloc(sizeof(http_auth_cache));
110     force_assert(ac);
111     ac->sptree = NULL;
112     ac->max_age = 600; /* 10 mins */
113     for (uint32_t i = 0, used = opts->used; i < used; ++i) {
114         data_unset *du = opts->data[i];
115         if (buffer_is_equal_string(&du->key, CONST_STR_LEN("max-age")))
116             ac->max_age = (time_t)
117               config_plugin_value_to_int32(du, (int32_t)ac->max_age);
118     }
119     return ac;
120 }
121 
122 static int
123 http_auth_cache_hash (const struct http_auth_require_t * const require, const char *username, const uint32_t ulen)
124 {
125     uint32_t h = /*(hash pointer value, which includes realm and permissions)*/
126       djbhash((char *)(intptr_t)require, sizeof(intptr_t), DJBHASH_INIT);
127     h = djbhash(username, ulen, h);
128     /* strip highest bit of hash value for splaytree (see splaytree_djbhash())*/
129     return (int32_t)(h & ~(((uint32_t)1) << 31));
130 }
131 
132 static http_auth_cache_entry *
133 http_auth_cache_query (splay_tree ** const sptree, const int ndx)
134 {
135     *sptree = splaytree_splay(*sptree, ndx);
136     return (*sptree && (*sptree)->key == ndx) ? (*sptree)->data : NULL;
137 }
138 
139 static void
140 http_auth_cache_insert (splay_tree ** const sptree, const int ndx, void * const data, void(data_free_fn)(void *))
141 {
142     /*(not necessary to re-splay (with current usage) since single-threaded
143      * and splaytree has not been modified since http_auth_cache_query())*/
144     /* *sptree = splaytree_splay(*sptree, ndx); */
145     if (NULL == *sptree || (*sptree)->key != ndx)
146         *sptree = splaytree_insert(*sptree, ndx, data);
147     else { /* collision; replace old entry */
148         data_free_fn((*sptree)->data);
149         (*sptree)->data = data;
150     }
151 }
152 
153 /* walk though cache, collect expired ids, and remove them in a second loop */
154 static void
155 mod_auth_tag_old_entries (splay_tree * const t, int * const keys, int * const ndx, const time_t max_age, const unix_time64_t cur_ts)
156 {
157     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
158     if (t->left)
159         mod_auth_tag_old_entries(t->left, keys, ndx, max_age, cur_ts);
160     if (t->right)
161         mod_auth_tag_old_entries(t->right, keys, ndx, max_age, cur_ts);
162     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
163 
164     const http_auth_cache_entry * const ae = t->data;
165     if (cur_ts - ae->ctime > max_age)
166         keys[(*ndx)++] = t->key;
167 }
168 
169 __attribute_noinline__
170 static void
171 mod_auth_periodic_cleanup(splay_tree **sptree_ptr, const time_t max_age, const unix_time64_t cur_ts)
172 {
173     splay_tree *sptree = *sptree_ptr;
174     int max_ndx, i;
175     int keys[8192]; /* 32k size on stack */
176     do {
177         if (!sptree) break;
178         max_ndx = 0;
179         mod_auth_tag_old_entries(sptree, keys, &max_ndx, max_age, cur_ts);
180         for (i = 0; i < max_ndx; ++i) {
181             int ndx = keys[i];
182             sptree = splaytree_splay(sptree, ndx);
183             if (sptree && sptree->key == ndx) {
184                 http_auth_cache_entry_free(sptree->data);
185                 sptree = splaytree_delete(sptree, ndx);
186             }
187         }
188     } while (max_ndx == sizeof(keys)/sizeof(int));
189     *sptree_ptr = sptree;
190 }
191 
192 TRIGGER_FUNC(mod_auth_periodic)
193 {
194     const plugin_data * const p = p_d;
195     const unix_time64_t cur_ts = log_monotonic_secs;
196     if (cur_ts & 0x7) return HANDLER_GO_ON; /*(continue once each 8 sec)*/
197     UNUSED(srv);
198 
199     /* future: might construct array of (http_auth_cache *) at startup
200      *         to avoid the need to search for them here */
201     /* (init i to 0 if global context; to 1 to skip empty global context) */
202     if (NULL == p->cvlist) return HANDLER_GO_ON;
203     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
204         const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
205         for (; cpv->k_id != -1; ++cpv) {
206             if (cpv->k_id != 3) continue; /* k_id == 3 for auth.cache */
207             if (cpv->vtype != T_CONFIG_LOCAL) continue;
208             http_auth_cache *ac = cpv->v.v;
209             mod_auth_periodic_cleanup(&ac->sptree, ac->max_age, cur_ts);
210         }
211     }
212 
213     return HANDLER_GO_ON;
214 }
215 
216 
217 
218 
219 static handler_t mod_auth_check_basic(request_st *r, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend);
220 static handler_t mod_auth_check_digest(request_st *r, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend);
221 static handler_t mod_auth_check_extern(request_st *r, void *p_d, const struct http_auth_require_t *require, const struct http_auth_backend_t *backend);
222 
223 INIT_FUNC(mod_auth_init) {
224 	static http_auth_scheme_t http_auth_scheme_basic  = { "basic",  mod_auth_check_basic,  NULL };
225 	static http_auth_scheme_t http_auth_scheme_digest = { "digest", mod_auth_check_digest, NULL };
226 	static const http_auth_scheme_t http_auth_scheme_extern = { "extern", mod_auth_check_extern, NULL };
227 	plugin_data *p = calloc(1, sizeof(*p));
228 	force_assert(p);
229 
230 	/* register http_auth_scheme_* */
231 	http_auth_scheme_basic.p_d = p;
232 	http_auth_scheme_set(&http_auth_scheme_basic);
233 	http_auth_scheme_digest.p_d = p;
234 	http_auth_scheme_set(&http_auth_scheme_digest);
235 	http_auth_scheme_set(&http_auth_scheme_extern);
236 
237 	return p;
238 }
239 
240 FREE_FUNC(mod_auth_free) {
241     plugin_data * const p = p_d;
242     if (NULL == p->cvlist) return;
243     /* (init i to 0 if global context; to 1 to skip empty global context) */
244     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
245         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
246         for (; -1 != cpv->k_id; ++cpv) {
247             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
248             switch (cpv->k_id) {
249               case 1: /* auth.require */
250                 array_free(cpv->v.v);
251                 break;
252               case 3: /* auth.cache */
253                 http_auth_cache_free(cpv->v.v);
254                 break;
255               default:
256                 break;
257             }
258         }
259     }
260 
261     http_auth_dumbdata_reset();
262 }
263 
264 /* data type for mod_auth structured data
265  * (parsed from auth.require array of strings) */
266 typedef struct {
267     DATA_UNSET;
268     http_auth_require_t *require;
269 } data_auth;
270 
271 static void data_auth_free(data_unset *d)
272 {
273     data_auth * const dauth = (data_auth *)d;
274     free(dauth->key.ptr);
275     http_auth_require_free(dauth->require);
276     free(dauth);
277 }
278 
279 static data_auth *data_auth_init(void)
280 {
281     static const struct data_methods fn = {
282       NULL, /* copy must not be called on this data */
283       data_auth_free,
284       NULL, /* insert_dup must not be called on this data */
285     };
286     data_auth * const dauth = calloc(1, sizeof(*dauth));
287     force_assert(NULL != dauth);
288     dauth->type       = TYPE_OTHER;
289     dauth->fn         = &fn;
290 
291     dauth->require = http_auth_require_init();
292 
293     return dauth;
294 }
295 
296 static int mod_auth_algorithm_parse(http_auth_info_t *ai, const char *s, size_t len) {
297     if (0 == len) {
298         ai->dalgo = HTTP_AUTH_DIGEST_MD5;
299         ai->dlen  = HTTP_AUTH_DIGEST_MD5_BINLEN;
300         return 1;
301     }
302 
303     if (len > 5
304         && (s[len-5]       ) == '-'
305         && (s[len-4] | 0x20) == 's'
306         && (s[len-3] | 0x20) == 'e'
307         && (s[len-2] | 0x20) == 's'
308         && (s[len-1] | 0x20) == 's') {
309         ai->dalgo = HTTP_AUTH_DIGEST_SESS;
310         len -= 5;
311     }
312     else {
313         ai->dalgo = HTTP_AUTH_DIGEST_NONE;
314     }
315 
316     if (3 == len
317         && 'm' == (s[0] | 0x20)
318         && 'd' == (s[1] | 0x20)
319         && '5' == (s[2]       )) {
320         ai->dalgo |= HTTP_AUTH_DIGEST_MD5;
321         ai->dlen   = HTTP_AUTH_DIGEST_MD5_BINLEN;
322         return 1;
323     }
324   #ifdef USE_LIB_CRYPTO
325     else if (len >= 7
326              && 's' == (s[0] | 0x20)
327              && 'h' == (s[1] | 0x20)
328              && 'a' == (s[2] | 0x20)
329              && '-' == (s[3]       )) {
330         if (len == 7 && s[4] == '2' && s[5] == '5' && s[6] == '6') {
331             ai->dalgo |= HTTP_AUTH_DIGEST_SHA256;
332             ai->dlen   = HTTP_AUTH_DIGEST_SHA256_BINLEN;
333             return 1;
334         }
335       #ifdef USE_LIB_CRYPTO_SHA512_256
336         if (len == 11 && 0 == memcmp(s+4, "512-256", 7)) {
337             ai->dalgo |= HTTP_AUTH_DIGEST_SHA512_256;
338             ai->dlen   = HTTP_AUTH_DIGEST_SHA512_256_BINLEN;
339             return 1;
340         }
341       #endif
342     }
343   #endif
344     return 0; /*(error)*/
345 }
346 
347 static int mod_auth_algorithms_parse(int *algorithm, buffer *algos) {
348     for (const char *s = algos->ptr, *p; s; s = p ? p+1 : NULL) {
349         http_auth_info_t ai;
350         p = strchr(s, '|');
351         if (!mod_auth_algorithm_parse(&ai, s, p ? (size_t)(p - s) : strlen(s)))
352             return 0;
353         *algorithm |= ai.dalgo;
354     }
355     return 1;
356 }
357 
358 static int mod_auth_require_parse (http_auth_require_t * const require, const buffer *b, log_error_st *errh)
359 {
360     /* user=name1|user=name2|group=name3|host=name4 */
361 
362     const char *str = b->ptr;
363     const char *p;
364 
365     if (buffer_is_equal_string(b, CONST_STR_LEN("valid-user"))) {
366         require->valid_user = 1;
367         return 1; /* success */
368     }
369 
370     do {
371         const char *eq;
372         size_t len;
373         p = strchr(str, '|');
374         len = NULL != p ? (size_t)(p - str) : strlen(str);
375         eq = memchr(str, '=', len);
376         if (NULL == eq) {
377             log_error(errh, __FILE__, __LINE__,
378               "error parsing auth.require 'require' field: missing '=' "
379               "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\"). "
380               "error value: %s error near: %s", b->ptr, str);
381             return 0;
382         }
383         if (eq[1] == '|' || eq[1] == '\0') {
384             log_error(errh, __FILE__, __LINE__,
385               "error parsing auth.require 'require' field: "
386               "missing token after '=' "
387               "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\"). "
388               "error value: %s error near: %s", b->ptr, str);
389             return 0;
390         }
391 
392         switch ((int)(eq - str)) {
393           case 4:
394             if (0 == memcmp(str, CONST_STR_LEN("user"))) {
395                 /*("user=" is 5)*/
396                 array_insert_value(&require->user, str+5, len-5);
397                 continue;
398             }
399             else if (0 == memcmp(str, CONST_STR_LEN("host"))) {
400                 /*("host=" is 5)*/
401                 array_insert_value(&require->host, str+5, len-5);
402                 log_error(errh, __FILE__, __LINE__,
403                   "warning parsing auth.require 'require' field: "
404                   "'host' not implemented; field value: %s", b->ptr);
405                 continue;
406             }
407             break; /* to error */
408           case 5:
409             if (0 == memcmp(str, CONST_STR_LEN("group"))) {
410                 /*("group=" is 6)*/
411                 array_insert_value(&require->group, str+6, len-6);
412               #if 0/*(supported by mod_authn_ldap, but not all other backends)*/
413                 log_error(errh, __FILE__, __LINE__,
414                   "warning parsing auth.require 'require' field: "
415                   "'group' not implemented; field value: %s", b->ptr);
416               #endif
417                 continue;
418             }
419             break; /* to error */
420           case 10:
421             if (0 == memcmp(str, CONST_STR_LEN("valid-user"))) {
422                 log_error(errh, __FILE__, __LINE__,
423                   "error parsing auth.require 'require' field: "
424                   "valid user can not be combined with other require rules "
425                   "(expecting \"valid-user\" or "
426                   "\"user=a|user=b|group=g|host=h\"). error value: %s", b->ptr);
427                 return 0;
428             }
429             break; /* to error */
430           default:
431             break; /* to error */
432         }
433 
434         log_error(errh, __FILE__, __LINE__,
435           "error parsing auth.require 'require' field: "
436           "invalid/unsupported token "
437           "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\"). "
438           "error value: %s error near: %s", b->ptr, str);
439         return 0;
440 
441     } while (p && *((str = p+1)));
442 
443     return 1; /* success */
444 }
445 
446 static handler_t mod_auth_require_parse_array(const array *value, array * const auth_require, log_error_st *errh)
447 {
448 		for (uint32_t n = 0; n < value->used; ++n) {
449 			size_t m;
450 			data_array *da_file = (data_array *)value->data[n];
451 			const buffer *method = NULL, *realm = NULL, *require = NULL;
452 			const buffer *nonce_secret = NULL;
453 			data_unset *userhash = NULL;
454 			const http_auth_scheme_t *auth_scheme;
455 			buffer *algos = NULL;
456 			int algorithm = HTTP_AUTH_DIGEST_SESS;
457 
458 			if (!array_is_kvstring(&da_file->value)) {
459 				log_error(errh, __FILE__, __LINE__,
460 				  "unexpected value for auth.require; expected "
461 				  "auth.require = ( \"urlpath\" => ( \"option\" => \"value\" ) )");
462 
463 				return HANDLER_ERROR;
464 			}
465 
466 			for (m = 0; m < da_file->value.used; m++) {
467 				if (da_file->value.data[m]->type == TYPE_STRING) {
468 					data_string *ds = (data_string *)da_file->value.data[m];
469 					if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("method"))) {
470 						method = &ds->value;
471 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("realm"))) {
472 						realm = &ds->value;
473 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("require"))) {
474 						require = &ds->value;
475 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("algorithm"))) {
476 						algos = &ds->value;
477 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("nonce_secret"))
478 					           || buffer_is_equal_string(&ds->key, CONST_STR_LEN("nonce-secret"))) {
479 						nonce_secret = &ds->value;
480 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("userhash"))) {
481 						userhash = (data_unset *)ds;
482 					} else {
483 						log_error(errh, __FILE__, __LINE__,
484 						  "the field is unknown in: "
485 						  "auth.require = ( \"...\" => ( ..., -> \"%s\" <- => \"...\" ) )",
486 						  da_file->value.data[m]->key.ptr);
487 
488 						return HANDLER_ERROR;
489 					}
490 				} else {
491 					log_error(errh, __FILE__, __LINE__,
492 					  "a string was expected for: "
493 					  "auth.require = ( \"...\" => ( ..., -> \"%s\" <- => \"...\" ) )",
494 					  da_file->value.data[m]->key.ptr);
495 
496 					return HANDLER_ERROR;
497 				}
498 			}
499 
500 			if (!method || buffer_is_blank(method)) {
501 				log_error(errh, __FILE__, __LINE__,
502 				  "the method field is missing or blank in: "
503 				  "auth.require = ( \"...\" => ( ..., \"method\" => \"...\" ) )");
504 				return HANDLER_ERROR;
505 			} else {
506 				auth_scheme = http_auth_scheme_get(method);
507 				if (NULL == auth_scheme) {
508 					log_error(errh, __FILE__, __LINE__,
509 					  "unknown method %s (e.g. \"basic\", \"digest\" or \"extern\") in "
510 					  "auth.require = ( \"...\" => ( ..., \"method\" => \"...\") )", method->ptr);
511 					return HANDLER_ERROR;
512 				}
513 			}
514 
515 			if (!realm) {
516 				log_error(errh, __FILE__, __LINE__,
517 				  "the realm field is missing in: "
518 				  "auth.require = ( \"...\" => ( ..., \"realm\" => \"...\" ) )");
519 				return HANDLER_ERROR;
520 			}
521 
522 			if (!require || buffer_is_blank(require)) {
523 				log_error(errh, __FILE__, __LINE__,
524 				  "the require field is missing or blank in: "
525 				  "auth.require = ( \"...\" => ( ..., \"require\" => \"...\" ) )");
526 				return HANDLER_ERROR;
527 			}
528 
529 			if (!algos || buffer_is_blank(algos)) {
530 				algorithm |= HTTP_AUTH_DIGEST_MD5;
531 			} else if (!mod_auth_algorithms_parse(&algorithm, algos)) {
532 				log_error(errh, __FILE__, __LINE__,
533 				  "invalid algorithm in: "
534 				  "auth.require = ( \"...\" => ( ..., \"algorithm\" => \"...\" ) )");
535 				return HANDLER_ERROR;
536 			}
537 
538 			if (require) { /*(always true at this point)*/
539 				data_auth * const dauth = data_auth_init();
540 				buffer_copy_buffer(&dauth->key, &da_file->key);
541 				dauth->require->scheme = auth_scheme;
542 				dauth->require->algorithm = algorithm;
543 				dauth->require->realm = realm;
544 				dauth->require->nonce_secret = nonce_secret; /*(NULL is ok)*/
545 				dauth->require->userhash = config_plugin_value_tobool(userhash, 0);
546 				if (!mod_auth_require_parse(dauth->require, require, errh)) {
547 					dauth->fn->free((data_unset *)dauth);
548 					return HANDLER_ERROR;
549 				}
550 				array_insert_unique(auth_require, (data_unset *)dauth);
551 			}
552 		}
553 
554 	return HANDLER_GO_ON;
555 }
556 
557 static void mod_auth_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
558     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
559       case 0: /* auth.backend */
560         if (cpv->vtype == T_CONFIG_LOCAL)
561             pconf->auth_backend = cpv->v.v;
562         break;
563       case 1: /* auth.require */
564         if (cpv->vtype == T_CONFIG_LOCAL)
565             pconf->auth_require = cpv->v.v;
566         break;
567       case 2: /* auth.extern-authn */
568         pconf->auth_extern_authn = cpv->v.u;
569         break;
570       case 3: /* auth.cache */
571         if (cpv->vtype == T_CONFIG_LOCAL)
572             pconf->auth_cache = cpv->v.v;
573         break;
574       default:/* should not happen */
575         return;
576     }
577 }
578 
579 static void mod_auth_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
580     do {
581         mod_auth_merge_config_cpv(pconf, cpv);
582     } while ((++cpv)->k_id != -1);
583 }
584 
585 static void mod_auth_patch_config(request_st * const r, plugin_data * const p) {
586     p->conf = p->defaults; /* copy small struct instead of memcpy() */
587     /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/
588     for (int i = 1, used = p->nconfig; i < used; ++i) {
589         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
590             mod_auth_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
591     }
592 }
593 
594 SETDEFAULTS_FUNC(mod_auth_set_defaults) {
595     static const config_plugin_keys_t cpk[] = {
596       { CONST_STR_LEN("auth.backend"),
597         T_CONFIG_STRING,
598         T_CONFIG_SCOPE_CONNECTION }
599      ,{ CONST_STR_LEN("auth.require"),
600         T_CONFIG_ARRAY_KVARRAY,
601         T_CONFIG_SCOPE_CONNECTION }
602      ,{ CONST_STR_LEN("auth.extern-authn"),
603         T_CONFIG_BOOL,
604         T_CONFIG_SCOPE_CONNECTION }
605      ,{ CONST_STR_LEN("auth.cache"),
606         T_CONFIG_ARRAY,
607         T_CONFIG_SCOPE_CONNECTION }
608      ,{ NULL, 0,
609         T_CONFIG_UNSET,
610         T_CONFIG_SCOPE_UNSET }
611     };
612 
613     plugin_data * const p = p_d;
614     if (!config_plugin_values_init(srv, p, cpk, "mod_auth"))
615         return HANDLER_ERROR;
616 
617     /* process and validate config directives
618      * (init i to 0 if global context; to 1 to skip empty global context) */
619     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
620         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
621         for (; -1 != cpv->k_id; ++cpv) {
622             switch (cpv->k_id) {
623               case 0: /* auth.backend */
624                 if (!buffer_is_blank(cpv->v.b)) {
625                     const http_auth_backend_t * const auth_backend =
626                       http_auth_backend_get(cpv->v.b);
627                     if (NULL == auth_backend) {
628                         log_error(srv->errh, __FILE__, __LINE__,
629                           "auth.backend not supported: %s", cpv->v.b->ptr);
630                         return HANDLER_ERROR;
631                     }
632                     *(const http_auth_backend_t **)&cpv->v.v = auth_backend;
633                     cpv->vtype = T_CONFIG_LOCAL;
634                 }
635                 break;
636               case 1: /* auth.require */
637                 {
638                     array * const a = array_init(4);
639                     if (HANDLER_GO_ON !=
640                         mod_auth_require_parse_array(cpv->v.a, a, srv->errh)) {
641                         array_free(a);
642                         return HANDLER_ERROR;
643                     }
644                     cpv->v.a = a;
645                     cpv->vtype = T_CONFIG_LOCAL;
646                 }
647                 break;
648               case 2: /* auth.extern-authn */
649                 break;
650               case 3: /* auth.cache */
651                 cpv->v.v = http_auth_cache_init(cpv->v.a);
652                 cpv->vtype = T_CONFIG_LOCAL;
653                 break;
654               default:/* should not happen */
655                 break;
656             }
657         }
658     }
659 
660     /* initialize p->defaults from global config context */
661     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
662         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
663         if (-1 != cpv->k_id)
664             mod_auth_merge_config(&p->defaults, cpv);
665     }
666 
667     return HANDLER_GO_ON;
668 }
669 
670 static handler_t mod_auth_uri_handler(request_st * const r, void *p_d) {
671 	plugin_data *p = p_d;
672 	data_auth *dauth;
673 
674 	mod_auth_patch_config(r, p);
675 
676 	if (p->conf.auth_require == NULL) return HANDLER_GO_ON;
677 
678 	/* search auth directives for first prefix match against URL path */
679 	/* if we have a case-insensitive FS we have to lower-case the URI here too */
680 	dauth = (!r->conf.force_lowercase_filenames)
681 	   ? (data_auth *)array_match_key_prefix(p->conf.auth_require, &r->uri.path)
682 	   : (data_auth *)array_match_key_prefix_nc(p->conf.auth_require, &r->uri.path);
683 	if (NULL == dauth) return HANDLER_GO_ON;
684 
685 	{
686 			const http_auth_scheme_t * const scheme = dauth->require->scheme;
687 			if (p->conf.auth_extern_authn) {
688 				const buffer *vb = http_header_env_get(r, CONST_STR_LEN("REMOTE_USER"));
689 				if (NULL != vb && http_auth_match_rules(dauth->require, vb->ptr, NULL, NULL)) {
690 					return HANDLER_GO_ON;
691 				}
692 			}
693 			return scheme->checkfn(r, scheme->p_d, dauth->require, p->conf.auth_backend);
694 	}
695 }
696 
697 
698 __attribute_cold__
699 int mod_auth_plugin_init(plugin *p);
700 int mod_auth_plugin_init(plugin *p) {
701 	p->version     = LIGHTTPD_VERSION_ID;
702 	p->name        = "auth";
703 	p->init        = mod_auth_init;
704 	p->set_defaults = mod_auth_set_defaults;
705 	p->handle_trigger = mod_auth_periodic;
706 	p->handle_uri_clean = mod_auth_uri_handler;
707 	p->cleanup     = mod_auth_free;
708 
709 	return 0;
710 }
711 
712 
713 
714 
715 /*
716  * auth schemes (basic, digest, extern)
717  *
718  * (could be in separate file from mod_auth.c as long as registration occurs)
719  */
720 
721 #include "sys-crypto-md.h"
722 #include "base64.h"
723 #include "rand.h"
724 #include "http_header.h"
725 
726 __attribute_cold__
727 __attribute_noinline__
728 static handler_t
729 mod_auth_send_400_bad_request (request_st * const r)
730 {
731     /* a field was missing or invalid */
732     r->http_status = 400; /* Bad Request */
733     r->handler_module = NULL;
734     return HANDLER_FINISHED;
735 }
736 
737 
738 
739 __attribute_noinline__
740 static handler_t
741 mod_auth_send_401_unauthorized_basic (request_st * const r, const buffer * const realm)
742 {
743     r->http_status = 401;
744     r->handler_module = NULL;
745     buffer_append_str3(
746       http_header_response_set_ptr(r, HTTP_HEADER_WWW_AUTHENTICATE,
747                                    CONST_STR_LEN("WWW-Authenticate")),
748       CONST_STR_LEN("Basic realm=\""),
749       BUF_PTR_LEN(realm),
750       CONST_STR_LEN("\", charset=\"UTF-8\""));
751     return HANDLER_FINISHED;
752 }
753 
754 
755 __attribute_cold__
756 static handler_t
757 mod_auth_basic_misconfigured (request_st * const r, const struct http_auth_backend_t * const backend)
758 {
759     if (NULL == backend)
760         log_error(r->conf.errh, __FILE__, __LINE__,
761           "auth.backend not configured for %s", r->uri.path.ptr);
762     else
763         log_error(r->conf.errh, __FILE__, __LINE__,
764           "auth.require \"method\" => \"basic\" invalid "
765           "(try \"digest\"?) for %s", r->uri.path.ptr);
766 
767     r->http_status = 500;
768     r->handler_module = NULL;
769     return HANDLER_FINISHED;
770 }
771 
772 
773 static handler_t
774 mod_auth_check_basic(request_st * const r, void *p_d, const struct http_auth_require_t * const require, const struct http_auth_backend_t * const backend)
775 {
776     if (NULL == backend || NULL == backend->basic)
777         return mod_auth_basic_misconfigured(r, backend);
778 
779     const buffer * const vb =
780       http_header_request_get(r, HTTP_HEADER_AUTHORIZATION,
781                               CONST_STR_LEN("Authorization"));
782     if (NULL == vb || !buffer_eq_icase_ssn(vb->ptr, CONST_STR_LEN("Basic ")))
783         return mod_auth_send_401_unauthorized_basic(r, require->realm);
784   #ifdef __COVERITY__
785     if (buffer_clen(vb) < sizeof("Basic ")-1)
786         return mod_auth_send_400_bad_request(r);
787   #endif
788 
789     size_t ulen = buffer_clen(vb) - (sizeof("Basic ")-1);
790     size_t pwlen;
791     char *pw;
792     char user[1024];
793 
794     /* base64-decode Authorization into username:password string;
795      * limit base64-decoded username:password string to fit into 1k buf */
796     if (ulen > 1363) /*(1363/4*3+3 = 1023)*/
797         return mod_auth_send_401_unauthorized_basic(r, require->realm);
798     /* coverity[overflow_sink : FALSE] */
799     ulen = li_base64_dec((unsigned char *)user, sizeof(user),
800                          vb->ptr+sizeof("Basic ")-1, ulen, BASE64_STANDARD);
801     if (0 == ulen) {
802         log_error(r->conf.errh, __FILE__, __LINE__,
803           "decoding base64-string failed %s", vb->ptr+sizeof("Basic ")-1);
804         return mod_auth_send_400_bad_request(r);
805     }
806     user[ulen] = '\0';
807     pw = memchr(user, ':', ulen);
808     if (NULL == pw) {
809         log_error(r->conf.errh, __FILE__, __LINE__, "missing ':' in %s", user);
810         return mod_auth_send_400_bad_request(r);
811     }
812     *pw++ = '\0';
813     pwlen = (size_t)(user + ulen - pw);
814     ulen  = (size_t)(pw - 1 - user);
815 
816     plugin_data * const p = p_d;
817     splay_tree ** sptree = p->conf.auth_cache
818       ? &p->conf.auth_cache->sptree
819       : NULL;
820     http_auth_cache_entry *ae = NULL;
821     handler_t rc = HANDLER_ERROR;
822     int ndx = -1;
823     if (sptree) {
824         ndx = http_auth_cache_hash(require, user, ulen);
825         ae = http_auth_cache_query(sptree, ndx);
826         if (ae && ae->require == require
827             && ulen == ae->ulen && 0 == memcmp(user, ae->username, ulen))
828             rc = ck_memeq_const_time(ae->pwdigest, ae->dlen, pw, pwlen)
829               ? HANDLER_GO_ON
830               : HANDLER_ERROR;
831         else /*(not found or hash collision)*/
832             ae = NULL;
833     }
834 
835     if (NULL == ae) {
836         const buffer userb = { user, ulen+1, 0 };
837         rc = backend->basic(r, backend->p_d, require, &userb, pw);
838     }
839 
840     switch (rc) {
841     case HANDLER_GO_ON:
842         http_auth_setenv(r, user, ulen, CONST_STR_LEN("Basic"));
843         if (sptree && NULL == ae) { /*(cache (new) successful result)*/
844             ae = http_auth_cache_entry_init(require, 0, user, ulen, user, ulen,
845                                             pw, pwlen);
846             http_auth_cache_insert(sptree, ndx, ae, http_auth_cache_entry_free);
847         }
848         break;
849     case HANDLER_WAIT_FOR_EVENT:
850     case HANDLER_FINISHED:
851         break;
852     case HANDLER_ERROR:
853     default:
854         log_error(r->conf.errh, __FILE__, __LINE__,
855           "password doesn't match for %s username: %s IP: %s",
856           r->uri.path.ptr, user, r->con->dst_addr_buf.ptr);
857         r->keep_alive = -1; /*(disable keep-alive if bad password)*/
858         rc = mod_auth_send_401_unauthorized_basic(r, require->realm);
859         break;
860     }
861 
862     ck_memzero(pw, pwlen);
863     return rc;
864 }
865 
866 
867 
868 enum http_auth_digest_params_e {
869   e_username = 0
870  ,e_realm
871  ,e_nonce
872  ,e_uri
873  ,e_algorithm
874  ,e_qop
875  ,e_cnonce
876  ,e_nc
877  ,e_response
878  ,e_userstar
879  ,e_userhash
880  ,http_auth_digest_params_sz /*(last item)*/
881 };
882 
883 typedef struct http_auth_digest_params_t {
884     const char *ptr[http_auth_digest_params_sz];
885     uint16_t len[http_auth_digest_params_sz];
886     unix_time64_t send_nextnonce_ts;
887     unsigned char rdigest[MD_DIGEST_LENGTH_MAX];/*(earlier members get 0-init)*/
888 } http_auth_digest_params_t;
889 
890 
891 static void
892 mod_auth_digest_mutate (http_auth_info_t * const ai, const http_auth_digest_params_t * const dp, const buffer * const method)
893 {
894     force_assert(method);
895     li_md_iov_fn digest_iov = MD5_iov;
896     /* (ai->dalgo & HTTP_AUTH_DIGEST_MD5) default */
897   #ifdef USE_LIB_CRYPTO
898     if (ai->dalgo & HTTP_AUTH_DIGEST_SHA256)
899         digest_iov = SHA256_iov;
900    #ifdef USE_LIB_CRYPTO_SHA512_256
901     else if (ai->dalgo & HTTP_AUTH_DIGEST_SHA512_256)
902         digest_iov = SHA512_256_iov;
903    #endif
904   #endif
905     size_t n;
906     struct const_iovec iov[11];
907     char a1[MD_DIGEST_LENGTH_MAX*2+8]; /*(+1 for li_tohex(); +8 for align)*/
908     char a2[MD_DIGEST_LENGTH_MAX*2+8]; /*(+1 for li_tohex(); +8 for align)*/
909 
910     li_tohex(a1, sizeof(a1), (const char *)ai->digest, ai->dlen);
911 
912     if (ai->dalgo & HTTP_AUTH_DIGEST_SESS) {
913         /* http://www.rfc-editor.org/errata_search.php?rfc=2617
914          * Errata ID: 1649 */
915         iov[0].iov_base = a1;
916         iov[0].iov_len  = ai->dlen*2;
917         iov[1].iov_base = ":";
918         iov[1].iov_len  = 1;
919         iov[2].iov_base = dp->ptr[e_nonce];
920         iov[2].iov_len  = dp->len[e_nonce];
921         iov[3].iov_base = ":";
922         iov[3].iov_len  = 1;
923         iov[4].iov_base = dp->ptr[e_cnonce];
924         iov[4].iov_len  = dp->len[e_cnonce];
925         digest_iov(ai->digest, iov, 5);
926         li_tohex(a1, sizeof(a1), (const char *)ai->digest, ai->dlen);
927     }
928 
929     /* calculate H(A2) */
930     iov[0].iov_base = method->ptr;
931     iov[0].iov_len  = buffer_clen(method);
932     iov[1].iov_base = ":";
933     iov[1].iov_len  = 1;
934     iov[2].iov_base = dp->ptr[e_uri];
935     iov[2].iov_len  = dp->len[e_uri];
936     n = 3;
937   #if 0
938     /* qop=auth-int not supported, already checked in caller */
939     if (dp->ptr[e_qop] && buffer_eq_icase_ss(dp->ptr[e_qop], dp->len[e_qop],
940                                              CONST_STR_LEN("auth-int"))) {
941         iov[3].iov_base = ":";
942         iov[3].iov_len  = 1;
943         iov[4].iov_base = [body checksum];
944         iov[4].iov_len  = ai->dlen*2;
945         n = 5;
946     }
947   #endif
948     digest_iov(ai->digest, iov, n);
949     li_tohex(a2, sizeof(a2), (const char *)ai->digest, ai->dlen);
950 
951     /* calculate response */
952     iov[0].iov_base = a1;
953     iov[0].iov_len  = ai->dlen*2;
954     iov[1].iov_base = ":";
955     iov[1].iov_len  = 1;
956     iov[2].iov_base = dp->ptr[e_nonce];
957     iov[2].iov_len  = dp->len[e_nonce];
958     iov[3].iov_base = ":";
959     iov[3].iov_len  = 1;
960     n = 4;
961     if (dp->len[e_qop]) {
962         iov[4].iov_base = dp->ptr[e_nc];
963         iov[4].iov_len  = dp->len[e_nc];
964         iov[5].iov_base = ":";
965         iov[5].iov_len  = 1;
966         iov[6].iov_base = dp->ptr[e_cnonce];
967         iov[6].iov_len  = dp->len[e_cnonce];
968         iov[7].iov_base = ":";
969         iov[7].iov_len  = 1;
970         iov[8].iov_base = dp->ptr[e_qop];
971         iov[8].iov_len  = dp->len[e_qop];
972         iov[9].iov_base = ":";
973         iov[9].iov_len  = 1;
974         n = 10;
975     }
976     iov[n].iov_base = a2;
977     iov[n].iov_len  = ai->dlen*2;
978     digest_iov(ai->digest, iov, n+1);
979 }
980 
981 
982 static void
983 mod_auth_append_nonce (buffer *b, unix_time64_t cur_ts, const struct http_auth_require_t *require, int dalgo, int *rndptr)
984 {
985     buffer_append_uint_hex(b, (uintmax_t)cur_ts);
986     buffer_append_char(b, ':');
987     const buffer * const nonce_secret = require->nonce_secret;
988     int rnd;
989     if (NULL == nonce_secret)
990         rnd = rndptr ? *rndptr : li_rand_pseudo();
991     else { /*(do not directly expose random number generator single value)*/
992         rndptr
993           ? (void)(rnd = *rndptr)
994           : li_rand_pseudo_bytes((unsigned char *)&rnd, sizeof(rnd));
995         buffer_append_uint_hex(b, (uintmax_t)rnd);
996         buffer_append_char(b, ':');
997     }
998 
999     size_t n;
1000     struct const_iovec iov[3];
1001 
1002   #if 0
1003     char a1[LI_ITOSTRING_LENGTH];
1004     char a2[LI_ITOSTRING_LENGTH];
1005     iov[0].iov_base = a1;
1006     iov[0].iov_len  = li_itostrn(a1, sizeof(a1), cur_ts);
1007     iov[1].iov_base = a2;
1008     iov[1].iov_len  = li_itostrn(a2, sizeof(a2), rnd);
1009   #else
1010     iov[0].iov_base = &cur_ts;
1011     iov[0].iov_len  = sizeof(cur_ts);
1012     iov[1].iov_base = &rnd;
1013     iov[1].iov_len  = sizeof(rnd);
1014   #endif
1015     n = 2;
1016     if (nonce_secret) {
1017         iov[2].iov_base = nonce_secret->ptr;
1018         iov[2].iov_len  = buffer_clen(nonce_secret);
1019         n = 3;
1020     }
1021 
1022     unsigned char h[MD_DIGEST_LENGTH_MAX];
1023     switch (dalgo) {
1024      #ifdef USE_LIB_CRYPTO
1025       #ifdef USE_LIB_CRYPTO_SHA512_256
1026       case HTTP_AUTH_DIGEST_SHA512_256:
1027         SHA512_256_iov(h, iov, n);
1028         n = HTTP_AUTH_DIGEST_SHA512_256_BINLEN;
1029         break;
1030       #endif
1031       case HTTP_AUTH_DIGEST_SHA256:
1032         SHA256_iov(h, iov, n);
1033         n = HTTP_AUTH_DIGEST_SHA256_BINLEN;
1034         break;
1035      #endif
1036       /*case HTTP_AUTH_DIGEST_MD5:*/
1037       default:
1038         MD5_iov(h, iov, n);
1039         n = HTTP_AUTH_DIGEST_MD5_BINLEN;
1040         break;
1041     }
1042     li_tohex(buffer_extend(b, n*2), n*2+1, (const char *)h, n);
1043 }
1044 
1045 
1046 static void
1047 mod_auth_digest_www_authenticate (buffer *b, unix_time64_t cur_ts, const struct http_auth_require_t *require, int nonce_stale)
1048 {
1049     int algos = nonce_stale ? nonce_stale : require->algorithm;
1050     int n = 0;
1051     int algoid[3];
1052     unsigned int algolen[3];
1053     const char *algoname[3];
1054   #ifdef USE_LIB_CRYPTO
1055    #ifdef USE_LIB_CRYPTO_SHA512_256
1056     if (algos & HTTP_AUTH_DIGEST_SHA512_256) {
1057         algoid[n] = HTTP_AUTH_DIGEST_SHA512_256;
1058         algoname[n] = "SHA-512-256";
1059         algolen[n] = sizeof("SHA-512-256")-1;
1060         ++n;
1061     }
1062    #endif
1063     if (algos & HTTP_AUTH_DIGEST_SHA256) {
1064         algoid[n] = HTTP_AUTH_DIGEST_SHA256;
1065         algoname[n] = "SHA-256";
1066         algolen[n] = sizeof("SHA-256")-1;
1067         ++n;
1068     }
1069   #endif
1070     if (algos & HTTP_AUTH_DIGEST_MD5) {
1071         algoid[n] = HTTP_AUTH_DIGEST_MD5;
1072         algoname[n] = "MD5";
1073         algolen[n] = sizeof("MD5")-1;
1074         ++n;
1075     }
1076 
1077     buffer_clear(b);
1078     for (int i = 0; i < n; ++i) {
1079         struct const_iovec iov[] = {
1080           { CONST_STR_LEN("\r\nWWW-Authenticate: ") }
1081          ,{ CONST_STR_LEN("Digest realm=\"") }
1082          ,{ BUF_PTR_LEN(require->realm) }
1083          ,{ CONST_STR_LEN("\", charset=\"UTF-8\", algorithm=") }
1084          ,{ algoname[i], algolen[i] }
1085          ,{ CONST_STR_LEN(", nonce=\"") }
1086         };
1087         buffer_append_iovec(b, iov+(0==i), sizeof(iov)/sizeof(*iov)-(0==i));
1088         mod_auth_append_nonce(b, cur_ts, require, algoid[i], NULL);
1089         buffer_append_string_len(b, CONST_STR_LEN("\", qop=\"auth\""));
1090         if (require->userhash) {
1091             buffer_append_string_len(b, CONST_STR_LEN(", userhash=true"));
1092         }
1093         if (nonce_stale) {
1094             buffer_append_string_len(b, CONST_STR_LEN(", stale=true"));
1095         }
1096     }
1097 }
1098 
1099 
1100 __attribute_noinline__
1101 static handler_t
1102 mod_auth_send_401_unauthorized_digest(request_st * const r, const struct http_auth_require_t * const require, int nonce_stale)
1103 {
1104     r->http_status = 401;
1105     r->handler_module = NULL;
1106     mod_auth_digest_www_authenticate(
1107       http_header_response_set_ptr(r, HTTP_HEADER_WWW_AUTHENTICATE,
1108                                    CONST_STR_LEN("WWW-Authenticate")),
1109       log_epoch_secs, require, nonce_stale);
1110     return HANDLER_FINISHED;
1111 }
1112 
1113 
1114 static void
1115 mod_auth_digest_authentication_info (buffer *b, unix_time64_t cur_ts, const struct http_auth_require_t *require, int dalgo)
1116 {
1117     buffer_clear(b);
1118     buffer_append_string_len(b, CONST_STR_LEN("nextnonce=\""));
1119     mod_auth_append_nonce(b, cur_ts, require, dalgo, NULL);
1120     buffer_append_char(b, '"');
1121 }
1122 
1123 
1124 static handler_t
1125 mod_auth_digest_get (request_st * const r, void *p_d, const struct http_auth_require_t * const require, const struct http_auth_backend_t * const backend, http_auth_info_t * const ai)
1126 {
1127     plugin_data * const p = p_d;
1128     splay_tree **sptree = p->conf.auth_cache
1129       ? &p->conf.auth_cache->sptree
1130       : NULL;
1131     http_auth_cache_entry *ae = NULL;
1132     handler_t rc = HANDLER_GO_ON;
1133     int ndx = -1;
1134 
1135     const char *user = ai->username;
1136     const uint32_t ulen = ai->ulen;
1137     char userbuf[sizeof(ai->userbuf)];
1138     if (ai->userhash && ulen <= sizeof(userbuf)) {
1139         /*(lowercase hex in userhash for consistency)*/
1140         const char * const restrict s = ai->username;
1141         for (uint_fast32_t i = 0; i < ulen; ++i)
1142             userbuf[i] = !light_isupper(s[i]) ? s[i] : (s[i] | 0x20);
1143         user = userbuf;
1144     }
1145 
1146     if (sptree) {
1147         ndx = http_auth_cache_hash(require, user, ulen);
1148         ae = http_auth_cache_query(sptree, ndx);
1149         if (ae && ae->require == require
1150             && ae->dalgo == ai->dalgo
1151             && ae->dlen == ai->dlen
1152             && ae->klen == ulen
1153             && 0 == memcmp(ae->k, user, ulen)
1154             && (ae->k == ae->username || ai->userhash)) {
1155             memcpy(ai->digest, ae->pwdigest, ai->dlen);
1156             if (ae->k != ae->username) { /*(userhash was key; copy username)*/
1157                 if (__builtin_expect( (ae->ulen <= sizeof(ai->userbuf)), 1)) {
1158                     ai->ulen = ae->ulen;
1159                     ai->username = memcpy(ai->userbuf, ae->username, ae->ulen);
1160                 }
1161             }
1162         }
1163         else /*(not found or hash collision)*/
1164             ae = NULL;
1165     }
1166 
1167     if (NULL == ae) {
1168         if (ai->userhash && ulen <= sizeof(ai->userbuf))
1169             ai->username = memcpy(ai->userbuf, userbuf, ulen);
1170             /* ai->username (lowercase userhash) will be replaced by username */
1171         rc = backend->digest(r, backend->p_d, ai);
1172     }
1173 
1174     switch (rc) {
1175     case HANDLER_GO_ON:
1176         break;
1177     case HANDLER_WAIT_FOR_EVENT:
1178         return HANDLER_WAIT_FOR_EVENT;
1179     case HANDLER_FINISHED:
1180         return HANDLER_FINISHED;
1181     case HANDLER_ERROR:
1182     default:
1183         r->keep_alive = -1; /*(disable keep-alive if unknown user)*/
1184         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1185     }
1186 
1187     if (sptree && NULL == ae) { /*(cache digest from backend)*/
1188         ae = http_auth_cache_entry_init(require, ai->dalgo, user, ulen,
1189                                         ai->username, ai->ulen,
1190                                         (char *)ai->digest, ai->dlen);
1191         http_auth_cache_insert(sptree, ndx, ae, http_auth_cache_entry_free);
1192     }
1193 
1194     return rc;
1195 }
1196 
1197 
1198 __attribute_cold__
1199 static handler_t
1200 mod_auth_digest_misconfigured (request_st * const r, const struct http_auth_backend_t * const backend)
1201 {
1202     if (NULL == backend)
1203         log_error(r->conf.errh, __FILE__, __LINE__,
1204           "auth.backend not configured for %s", r->uri.path.ptr);
1205     else
1206         log_error(r->conf.errh, __FILE__, __LINE__,
1207           "auth.require \"method\" => \"digest\" invalid "
1208           "(try \"basic\"?) for %s", r->uri.path.ptr);
1209 
1210     r->http_status = 500;
1211     r->handler_module = NULL;
1212     return HANDLER_FINISHED;
1213 }
1214 
1215 
1216 static void
1217 mod_auth_digest_parse_authorization (http_auth_digest_params_t * const dp, const char *c)
1218 {
1219     struct digest_kv {
1220         const char *key;
1221         uint32_t klen;
1222         enum http_auth_digest_params_e id;
1223     };
1224 
1225     static const struct digest_kv dkv[] = {
1226         { CONST_STR_LEN("username"),  e_username },
1227         { CONST_STR_LEN("realm"),     e_realm },
1228         { CONST_STR_LEN("nonce"),     e_nonce },
1229         { CONST_STR_LEN("uri"),       e_uri },
1230         { CONST_STR_LEN("algorithm"), e_algorithm },
1231         { CONST_STR_LEN("qop"),       e_qop },
1232         { CONST_STR_LEN("cnonce"),    e_cnonce },
1233         { CONST_STR_LEN("nc"),        e_nc },
1234         { CONST_STR_LEN("response"),  e_response },
1235         { CONST_STR_LEN("username*"), e_userstar },
1236         { CONST_STR_LEN("userhash"),  e_userhash },
1237 
1238         { NULL, 0, http_auth_digest_params_sz }
1239     };
1240 
1241     /* parse credentials from client */
1242     /* (caller must pass c pointing to string after "Digest ") */
1243     for (const char *e; *c; c++) {
1244         /* skip whitespaces */
1245         while (*c == ' ' || *c == '\t' || *c == ',') ++c;
1246         if (!*c) break;
1247         for (e = c; *e!='=' && *e!=' ' && *e!='\t' && *e!='\0'; ++e) ;
1248         const uint32_t tlen = (uint32_t)(e - c);
1249 
1250         for (int i = 0; dkv[i].key; ++i) {
1251             if (tlen != dkv[i].klen || 0 != memcmp(c, dkv[i].key, tlen))
1252                 continue;
1253             c += tlen;
1254             /* detect and step over '='; ignore BWS (bad whitespace) */
1255             if (__builtin_expect( (*c != '='), 0)) {
1256                 while (*c == ' ' || *c == '\t') ++c;
1257                 if (*c != '=') return; /*(including '\0')*/
1258             }
1259             do { ++c; } while (*c == ' ' || *c == '\t');
1260 
1261             if (*c == '"') {
1262                 for (e = ++c; *e != '"' && *e != '\0'; ++e) {
1263                     if (*e == '\\' && *++e == '\0') return;
1264                 }
1265                 if (*e != '"') return;
1266                 /* value with "..." *//*(XXX: quoted value not unescaped)*/
1267             }
1268             else {
1269                 for (e = c; *e!=',' && *e!=' ' && *e!='\t' && *e!='\0'; ++e) ;
1270                 /* value without "..." */
1271             }
1272             dp->ptr[dkv[i].id] = c;
1273             dp->len[dkv[i].id] = (uint16_t)(e - c);
1274             c = e;
1275             if (*c != ',') {
1276                 /*(could more strictly check for linear whitespace)*/
1277                 c = strchr(c, ',');
1278                 if (!c) return;
1279             }
1280             break;
1281         }
1282     }
1283 }
1284 
1285 
1286 static handler_t
1287 mod_auth_digest_validate_userstar (request_st * const r, http_auth_digest_params_t * const dp, http_auth_info_t * const ai)
1288 {
1289     /*assert(dp->ptr[e_userstar]);*/
1290 
1291     if (dp->len[e_userhash] == 4) { /*("true")*/
1292         log_error(r->conf.errh, __FILE__, __LINE__,
1293           "digest: invalid \"username*\" with \"userhash\" = true");
1294         return mod_auth_send_400_bad_request(r);
1295     }
1296 
1297     /* "username*" RFC5987 ext-value
1298      * ext-value = charset  "'" [ language ] "'" value-chars */
1299     const char *ptr = dp->ptr[e_userstar];
1300     uint32_t len    = dp->len[e_userstar];
1301     /* validate and step over charset... */
1302     if ((*ptr | 0x20) == 'u' && len > 5
1303         && buffer_eq_icase_ssn(ptr, "utf-8", 5))
1304         ptr += 5;
1305     else if ((*ptr | 0x20) == 'i' && len > 10
1306              && buffer_eq_icase_ssn(ptr, "iso-8859-1", 10))
1307         ptr += 10;
1308     else
1309         ptr = "\n"; /*(invalid char; (not '\''); error below)*/
1310     /* step over ...'language'... */
1311     if (*ptr++ != '\''
1312         || !(ptr = memchr(ptr, '\'',
1313                           len - (uint32_t)(ptr - dp->ptr[e_userstar])))) {
1314         log_error(r->conf.errh, __FILE__, __LINE__,
1315           "digest: invalid \"username*\" ext-value");
1316         return mod_auth_send_400_bad_request(r);
1317     }
1318     ++ptr;
1319 
1320     /* decode %XX encodings (could be more efficient by combining tests) */
1321     buffer * const tb = r->tmp_buf;
1322     buffer_copy_string_len(tb, ptr, len-(uint32_t)(ptr - dp->ptr[e_userstar]));
1323     buffer_urldecode_path(tb);
1324     if (dp->ptr[e_userstar][0] == 'u' && !buffer_is_valid_UTF8(tb)) {
1325         log_error(r->conf.errh, __FILE__, __LINE__,
1326           "digest: invalid \"username*\" invalid UTF-8");
1327         return mod_auth_send_400_bad_request(r);
1328     }
1329     len = buffer_clen(tb);
1330     if (len > sizeof(ai->userbuf)) {
1331         log_error(r->conf.errh, __FILE__, __LINE__,
1332           "digest: invalid \"username*\" too long");
1333         return mod_auth_send_400_bad_request(r);
1334     }
1335     for (ptr = tb->ptr; *ptr; ++ptr) {
1336         /* prohibit decoded control chars, including '\0','\r','\n' */
1337         /* (theoretically could permit '\t', but not currently done) */
1338         if (*(unsigned char *)ptr < 0x20 || *ptr == 127) { /* iscntrl() */
1339             log_error(r->conf.errh, __FILE__, __LINE__,
1340               "digest: invalid \"username*\" contains ctrl chars");
1341             return mod_auth_send_400_bad_request(r);
1342         }
1343     }
1344 
1345     ai->ulen     = len;
1346     ai->username = memcpy(ai->userbuf, tb->ptr, len);
1347     return HANDLER_GO_ON;
1348 }
1349 
1350 
1351 static handler_t
1352 mod_auth_digest_validate_params (request_st * const r, const struct http_auth_require_t * const require, http_auth_digest_params_t * const dp, http_auth_info_t * const ai)
1353 {
1354     /* check for required parameters */
1355     if ((!dp->ptr[e_qop] || (dp->ptr[e_nc] && dp->ptr[e_cnonce]))
1356         && ((NULL != dp->ptr[e_username]) ^ (NULL != dp->ptr[e_userstar]))
1357         && dp->ptr[e_realm]
1358         && dp->ptr[e_nonce]
1359         && dp->ptr[e_uri]
1360         && dp->ptr[e_response]) {
1361         ai->username = dp->ptr[e_username];
1362         ai->ulen     = dp->len[e_username];
1363         ai->realm    = dp->ptr[e_realm];
1364         ai->rlen     = dp->len[e_realm];
1365         ai->userhash = (dp->len[e_userhash]==4);/*("true", not "false",absent)*/
1366         if (!ai->username) { /* (dp->ptr[e_userstar]) */
1367             if (HANDLER_GO_ON != mod_auth_digest_validate_userstar(r, dp, ai))
1368                 return HANDLER_FINISHED;
1369         }
1370     }
1371     else {
1372         log_error(r->conf.errh, __FILE__, __LINE__,
1373           "digest: missing field");
1374         return mod_auth_send_400_bad_request(r);
1375     }
1376 
1377     if (!buffer_eq_slen(require->realm, ai->realm, ai->rlen)) {
1378         log_error(r->conf.errh, __FILE__, __LINE__,
1379           "digest: realm mismatch");
1380         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1381     }
1382 
1383     if (!mod_auth_algorithm_parse(ai,dp->ptr[e_algorithm],dp->len[e_algorithm])
1384         || !(require->algorithm & ai->dalgo & ~HTTP_AUTH_DIGEST_SESS)) {
1385         log_error(r->conf.errh, __FILE__, __LINE__,
1386           "digest: (%.*s): invalid",
1387           (int)dp->len[e_algorithm], dp->ptr[e_algorithm]);
1388         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1389     }
1390 
1391     /* *-sess requires nonce and cnonce */
1392     if ((ai->dalgo & HTTP_AUTH_DIGEST_SESS)
1393         && (!dp->ptr[e_nonce] || !dp->ptr[e_cnonce])) {
1394         log_error(r->conf.errh, __FILE__, __LINE__,
1395           "digest: (%.*s): missing field",
1396           (int)dp->len[e_algorithm], dp->ptr[e_algorithm]);
1397         return mod_auth_send_400_bad_request(r);
1398     }
1399 
1400     if (0 != li_hex2bin(dp->rdigest, sizeof(dp->rdigest),
1401                         dp->ptr[e_response], dp->len[e_response])
1402         || dp->len[e_response] != (ai->dlen << 1)) {
1403         log_error(r->conf.errh, __FILE__, __LINE__,
1404           "digest: (%s): invalid format", dp->ptr[e_response]);
1405         return mod_auth_send_400_bad_request(r);
1406     }
1407 
1408     if (dp->ptr[e_qop]&& buffer_eq_icase_ss(dp->ptr[e_qop], dp->len[e_qop],
1409                                             CONST_STR_LEN("auth-int"))) {
1410         log_error(r->conf.errh, __FILE__, __LINE__,
1411           "digest: qop=auth-int not supported");
1412         return mod_auth_send_400_bad_request(r);
1413     }
1414 
1415     /* detect if attacker is attempting to reuse valid digest for one uri
1416      * on a different request uri.  Might also happen if intermediate proxy
1417      * altered client request line.  (Altered request would not result in
1418      * the same digest as that calculated by the client.)
1419      * Internal redirects such as with mod_rewrite will modify request uri.
1420      * Reauthentication is done to detect crossing auth realms, but this
1421      * uri validation step is bypassed.  r->target_orig is
1422      * original request-target sent in client request. */
1423     if (!buffer_eq_slen(&r->target_orig, dp->ptr[e_uri], dp->len[e_uri])) {
1424         log_error(r->conf.errh, __FILE__, __LINE__,
1425           "digest: auth failed: uri mismatch (%s != %.*s), IP: %s",
1426           r->target_orig.ptr, (int)dp->len[e_uri], dp->ptr[e_uri],
1427           r->con->dst_addr_buf.ptr);
1428         return mod_auth_send_400_bad_request(r);
1429     }
1430 
1431     return HANDLER_GO_ON;
1432 }
1433 
1434 
1435 static handler_t
1436 mod_auth_digest_validate_nonce (request_st * const r, const struct http_auth_require_t * const require, http_auth_digest_params_t * const dp, http_auth_info_t * const ai)
1437 {
1438     /* check age of nonce.  Note, random data is used in nonce generation
1439      * in mod_auth_send_401_unauthorized_digest().  If that were replaced
1440      * with nanosecond time, then nonce secret would remain unique enough
1441      * for the purposes of Digest auth, and would be reproducible (and
1442      * verifiable) if nanoseconds were included with seconds as part of the
1443      * nonce "timestamp:secret".  However, doing so would expose a high
1444      * precision timestamp of the system to attackers.  timestamp in nonce
1445      * could theoretically be modified and still produce same md5sum, but
1446      * that is highly unlikely within a 10 min (moving) window of valid
1447      * time relative to current time (now).
1448      * If it is desired to validate that nonces were generated by server,
1449      * then specify auth.require = ( ... => ( "secret" => "..." ) )
1450      * When secret is specified, then instead of nanoseconds, the random
1451      * data value (included for unique nonces) will be exposed in the nonce
1452      * along with the timestamp, and the additional secret will be used to
1453      * validate that the server generated the nonce using that secret. */
1454     unix_time64_t ts = 0;
1455     const unsigned char * const nonce = (unsigned char *)dp->ptr[e_nonce];
1456     int i;
1457     for (i = 0; i < 16 && light_isxdigit(nonce[i]); ++i)
1458         ts = (unix_time64_t)((uint64_t)ts << 4) | hex2int(nonce[i]);
1459 
1460     const unix_time64_t cur_ts = log_epoch_secs;
1461     if (nonce[i] != ':' || ts > cur_ts || cur_ts - ts > 600) { /*(10 mins)*/
1462         /* nonce is stale; have client regenerate digest */
1463         return mod_auth_send_401_unauthorized_digest(r, require, ai->dalgo);
1464     }
1465 
1466     if (cur_ts - ts > 540)  /*(9 mins)*/
1467         dp->send_nextnonce_ts = cur_ts;
1468 
1469     if (require->nonce_secret) {
1470         unsigned int rnd = 0;
1471         for (int j = i+8; i < j && light_isxdigit(nonce[i]); ++i) {
1472             rnd = (rnd << 4) + hex2int(nonce[i]);
1473         }
1474         if (nonce[i] != ':') {
1475             /* nonce is invalid;
1476              * expect extra field w/ require->nonce_secret */
1477             log_error(r->conf.errh, __FILE__, __LINE__,
1478               "digest: nonce invalid");
1479             return mod_auth_send_400_bad_request(r);
1480         }
1481         buffer * const tb = r->tmp_buf;
1482         buffer_clear(tb);
1483         mod_auth_append_nonce(tb, cur_ts, require, ai->dalgo, (int *)&rnd);
1484         if (!buffer_eq_slen(tb, dp->ptr[e_nonce], dp->len[e_nonce])) {
1485             /* nonce not generated using current require->nonce_secret */
1486             log_error(r->conf.errh, __FILE__, __LINE__,
1487               "digest: nonce mismatch");
1488             return mod_auth_send_401_unauthorized_digest(r, require, 0);
1489         }
1490     }
1491 
1492     return HANDLER_GO_ON;
1493 }
1494 
1495 
1496 static handler_t
1497 mod_auth_check_digest (request_st * const r, void *p_d, const struct http_auth_require_t * const require, const struct http_auth_backend_t * const backend)
1498 {
1499     if (NULL == backend || NULL == backend->digest)
1500         return mod_auth_digest_misconfigured(r, backend);
1501 
1502     const buffer * const vb =
1503       http_header_request_get(r, HTTP_HEADER_AUTHORIZATION,
1504                               CONST_STR_LEN("Authorization"));
1505     if (NULL == vb || !buffer_eq_icase_ssn(vb->ptr, CONST_STR_LEN("Digest ")))
1506         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1507   #ifdef __COVERITY__
1508     if (buffer_clen(vb) < sizeof("Digest ")-1)
1509         return mod_auth_send_400_bad_request(r);
1510   #endif
1511 
1512     http_auth_digest_params_t dp;
1513     http_auth_info_t ai;
1514     handler_t rc;
1515 
1516     /* XXX: should use offsetof() (if portable enough) */
1517     memset(&dp, 0, sizeof(dp) - sizeof(dp.rdigest));
1518 
1519     mod_auth_digest_parse_authorization(&dp, vb->ptr + sizeof("Digest ")-1);
1520 
1521     rc = mod_auth_digest_validate_params(r, require, &dp, &ai);
1522     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1523         return rc;
1524 
1525     rc = mod_auth_digest_validate_nonce(r, require, &dp, &ai);
1526     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1527         return rc;
1528 
1529     rc = mod_auth_digest_get(r, p_d, require, backend, &ai);
1530     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1531         return rc;
1532 
1533     mod_auth_digest_mutate(&ai, &dp, http_method_buf(r->http_method));
1534 
1535     if (!ck_memeq_const_time_fixed_len(dp.rdigest, ai.digest, ai.dlen)) {
1536         /*ck_memzero(ai.digest, ai.dlen);*//*skip clear since mutated*/
1537         /* digest not ok */
1538         log_error(r->conf.errh, __FILE__, __LINE__,
1539           "digest: auth failed for %.*s: wrong password, IP: %s",
1540           (int)ai.ulen, ai.username, r->con->dst_addr_buf.ptr);
1541         r->keep_alive = -1; /*(disable keep-alive if bad password)*/
1542         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1543     }
1544     /*ck_memzero(ai.digest, ai.dlen);*//* skip clear since mutated */
1545 
1546     /* check authorization (authz); string args must be '\0'-terminated) */
1547     buffer * const tb = r->tmp_buf;
1548     buffer_copy_string_len(tb, ai.username, ai.ulen);
1549     if (!http_auth_match_rules(require, tb->ptr, NULL, NULL))
1550         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1551 
1552     if (dp.send_nextnonce_ts) {
1553         /*(send nextnonce when expiration is approaching)*/
1554         mod_auth_digest_authentication_info(
1555           http_header_response_set_ptr(r, HTTP_HEADER_OTHER,
1556                                        CONST_STR_LEN("Authentication-Info")),
1557           dp.send_nextnonce_ts /*(cur_ts)*/, require, ai.dalgo);
1558     }
1559 
1560     http_auth_setenv(r, ai.username, ai.ulen, CONST_STR_LEN("Digest"));
1561     return HANDLER_GO_ON;
1562 }
1563 
1564 
1565 
1566 static handler_t mod_auth_check_extern(request_st * const r, void *p_d, const struct http_auth_require_t * const require, const struct http_auth_backend_t * const backend) {
1567     /* require REMOTE_USER already set */
1568     const buffer *vb = http_header_env_get(r, CONST_STR_LEN("REMOTE_USER"));
1569     UNUSED(p_d);
1570     UNUSED(backend);
1571     if (NULL != vb && http_auth_match_rules(require, vb->ptr, NULL, NULL)) {
1572         return HANDLER_GO_ON;
1573     } else {
1574         r->http_status = 401;
1575         r->handler_module = NULL;
1576         return HANDLER_FINISHED;
1577     }
1578 }
1579