xref: /lighttpd1.4/src/mod_auth.c (revision 18bbdbbe)
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 int mod_auth_plugin_init(plugin *p);
699 int mod_auth_plugin_init(plugin *p) {
700 	p->version     = LIGHTTPD_VERSION_ID;
701 	p->name        = "auth";
702 	p->init        = mod_auth_init;
703 	p->set_defaults = mod_auth_set_defaults;
704 	p->handle_trigger = mod_auth_periodic;
705 	p->handle_uri_clean = mod_auth_uri_handler;
706 	p->cleanup     = mod_auth_free;
707 
708 	return 0;
709 }
710 
711 
712 
713 
714 /*
715  * auth schemes (basic, digest, extern)
716  *
717  * (could be in separate file from mod_auth.c as long as registration occurs)
718  */
719 
720 #include "sys-crypto-md.h"
721 #include "base64.h"
722 #include "rand.h"
723 #include "http_header.h"
724 
725 __attribute_cold__
726 __attribute_noinline__
727 static handler_t
728 mod_auth_send_400_bad_request (request_st * const r)
729 {
730     /* a field was missing or invalid */
731     r->http_status = 400; /* Bad Request */
732     r->handler_module = NULL;
733     return HANDLER_FINISHED;
734 }
735 
736 
737 
738 __attribute_noinline__
739 static handler_t
740 mod_auth_send_401_unauthorized_basic (request_st * const r, const buffer * const realm)
741 {
742     r->http_status = 401;
743     r->handler_module = NULL;
744     buffer_append_str3(
745       http_header_response_set_ptr(r, HTTP_HEADER_WWW_AUTHENTICATE,
746                                    CONST_STR_LEN("WWW-Authenticate")),
747       CONST_STR_LEN("Basic realm=\""),
748       BUF_PTR_LEN(realm),
749       CONST_STR_LEN("\", charset=\"UTF-8\""));
750     return HANDLER_FINISHED;
751 }
752 
753 
754 __attribute_cold__
755 static handler_t
756 mod_auth_basic_misconfigured (request_st * const r, const struct http_auth_backend_t * const backend)
757 {
758     if (NULL == backend)
759         log_error(r->conf.errh, __FILE__, __LINE__,
760           "auth.backend not configured for %s", r->uri.path.ptr);
761     else
762         log_error(r->conf.errh, __FILE__, __LINE__,
763           "auth.require \"method\" => \"basic\" invalid "
764           "(try \"digest\"?) for %s", r->uri.path.ptr);
765 
766     r->http_status = 500;
767     r->handler_module = NULL;
768     return HANDLER_FINISHED;
769 }
770 
771 
772 static handler_t
773 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)
774 {
775     if (NULL == backend || NULL == backend->basic)
776         return mod_auth_basic_misconfigured(r, backend);
777 
778     const buffer * const vb =
779       http_header_request_get(r, HTTP_HEADER_AUTHORIZATION,
780                               CONST_STR_LEN("Authorization"));
781     if (NULL == vb || !buffer_eq_icase_ssn(vb->ptr, CONST_STR_LEN("Basic ")))
782         return mod_auth_send_401_unauthorized_basic(r, require->realm);
783   #ifdef __COVERITY__
784     if (buffer_clen(vb) < sizeof("Basic ")-1)
785         return mod_auth_send_400_bad_request(r);
786   #endif
787 
788     size_t ulen = buffer_clen(vb) - (sizeof("Basic ")-1);
789     size_t pwlen;
790     char *pw;
791     char user[1024];
792 
793     /* base64-decode Authorization into username:password string;
794      * limit base64-decoded username:password string to fit into 1k buf */
795     if (ulen > 1363) /*(1363/4*3+3 = 1023)*/
796         return mod_auth_send_401_unauthorized_basic(r, require->realm);
797     /* coverity[overflow_sink : FALSE] */
798     ulen = li_base64_dec((unsigned char *)user, sizeof(user),
799                          vb->ptr+sizeof("Basic ")-1, ulen, BASE64_STANDARD);
800     if (0 == ulen) {
801         log_error(r->conf.errh, __FILE__, __LINE__,
802           "decoding base64-string failed %s", vb->ptr+sizeof("Basic ")-1);
803         return mod_auth_send_400_bad_request(r);
804     }
805     user[ulen] = '\0';
806     pw = memchr(user, ':', ulen);
807     if (NULL == pw) {
808         log_error(r->conf.errh, __FILE__, __LINE__, "missing ':' in %s", user);
809         return mod_auth_send_400_bad_request(r);
810     }
811     *pw++ = '\0';
812     pwlen = (size_t)(user + ulen - pw);
813     ulen  = (size_t)(pw - 1 - user);
814 
815     plugin_data * const p = p_d;
816     splay_tree ** sptree = p->conf.auth_cache
817       ? &p->conf.auth_cache->sptree
818       : NULL;
819     http_auth_cache_entry *ae = NULL;
820     handler_t rc = HANDLER_ERROR;
821     int ndx = -1;
822     if (sptree) {
823         ndx = http_auth_cache_hash(require, user, ulen);
824         ae = http_auth_cache_query(sptree, ndx);
825         if (ae && ae->require == require
826             && ulen == ae->ulen && 0 == memcmp(user, ae->username, ulen))
827             rc = ck_memeq_const_time(ae->pwdigest, ae->dlen, pw, pwlen)
828               ? HANDLER_GO_ON
829               : HANDLER_ERROR;
830         else /*(not found or hash collision)*/
831             ae = NULL;
832     }
833 
834     if (NULL == ae) {
835         const buffer userb = { user, ulen+1, 0 };
836         rc = backend->basic(r, backend->p_d, require, &userb, pw);
837     }
838 
839     switch (rc) {
840     case HANDLER_GO_ON:
841         http_auth_setenv(r, user, ulen, CONST_STR_LEN("Basic"));
842         if (sptree && NULL == ae) { /*(cache (new) successful result)*/
843             ae = http_auth_cache_entry_init(require, 0, user, ulen, user, ulen,
844                                             pw, pwlen);
845             http_auth_cache_insert(sptree, ndx, ae, http_auth_cache_entry_free);
846         }
847         break;
848     case HANDLER_WAIT_FOR_EVENT:
849     case HANDLER_FINISHED:
850         break;
851     case HANDLER_ERROR:
852     default:
853         log_error(r->conf.errh, __FILE__, __LINE__,
854           "password doesn't match for %s username: %s IP: %s",
855           r->uri.path.ptr, user, r->con->dst_addr_buf.ptr);
856         r->keep_alive = -1; /*(disable keep-alive if bad password)*/
857         rc = mod_auth_send_401_unauthorized_basic(r, require->realm);
858         break;
859     }
860 
861     ck_memzero(pw, pwlen);
862     return rc;
863 }
864 
865 
866 
867 enum http_auth_digest_params_e {
868   e_username = 0
869  ,e_realm
870  ,e_nonce
871  ,e_uri
872  ,e_algorithm
873  ,e_qop
874  ,e_cnonce
875  ,e_nc
876  ,e_response
877  ,e_userstar
878  ,e_userhash
879  ,http_auth_digest_params_sz /*(last item)*/
880 };
881 
882 typedef struct http_auth_digest_params_t {
883     const char *ptr[http_auth_digest_params_sz];
884     uint16_t len[http_auth_digest_params_sz];
885     unix_time64_t send_nextnonce_ts;
886     unsigned char rdigest[MD_DIGEST_LENGTH_MAX];/*(earlier members get 0-init)*/
887 } http_auth_digest_params_t;
888 
889 
890 static void
891 mod_auth_digest_mutate (http_auth_info_t * const ai, const http_auth_digest_params_t * const dp, const buffer * const method)
892 {
893     force_assert(method);
894     li_md_iov_fn digest_iov = MD5_iov;
895     /* (ai->dalgo & HTTP_AUTH_DIGEST_MD5) default */
896   #ifdef USE_LIB_CRYPTO
897     if (ai->dalgo & HTTP_AUTH_DIGEST_SHA256)
898         digest_iov = SHA256_iov;
899    #ifdef USE_LIB_CRYPTO_SHA512_256
900     else if (ai->dalgo & HTTP_AUTH_DIGEST_SHA512_256)
901         digest_iov = SHA512_256_iov;
902    #endif
903   #endif
904     size_t n;
905     struct const_iovec iov[11];
906     char a1[MD_DIGEST_LENGTH_MAX*2+8]; /*(+1 for li_tohex(); +8 for align)*/
907     char a2[MD_DIGEST_LENGTH_MAX*2+8]; /*(+1 for li_tohex(); +8 for align)*/
908 
909     li_tohex(a1, sizeof(a1), (const char *)ai->digest, ai->dlen);
910 
911     if (ai->dalgo & HTTP_AUTH_DIGEST_SESS) {
912         /* http://www.rfc-editor.org/errata_search.php?rfc=2617
913          * Errata ID: 1649 */
914         iov[0].iov_base = a1;
915         iov[0].iov_len  = ai->dlen*2;
916         iov[1].iov_base = ":";
917         iov[1].iov_len  = 1;
918         iov[2].iov_base = dp->ptr[e_nonce];
919         iov[2].iov_len  = dp->len[e_nonce];
920         iov[3].iov_base = ":";
921         iov[3].iov_len  = 1;
922         iov[4].iov_base = dp->ptr[e_cnonce];
923         iov[4].iov_len  = dp->len[e_cnonce];
924         digest_iov(ai->digest, iov, 5);
925         li_tohex(a1, sizeof(a1), (const char *)ai->digest, ai->dlen);
926     }
927 
928     /* calculate H(A2) */
929     iov[0].iov_base = method->ptr;
930     iov[0].iov_len  = buffer_clen(method);
931     iov[1].iov_base = ":";
932     iov[1].iov_len  = 1;
933     iov[2].iov_base = dp->ptr[e_uri];
934     iov[2].iov_len  = dp->len[e_uri];
935     n = 3;
936   #if 0
937     /* qop=auth-int not supported, already checked in caller */
938     if (dp->ptr[e_qop] && buffer_eq_icase_ss(dp->ptr[e_qop], dp->len[e_qop],
939                                              CONST_STR_LEN("auth-int"))) {
940         iov[3].iov_base = ":";
941         iov[3].iov_len  = 1;
942         iov[4].iov_base = [body checksum];
943         iov[4].iov_len  = ai->dlen*2;
944         n = 5;
945     }
946   #endif
947     digest_iov(ai->digest, iov, n);
948     li_tohex(a2, sizeof(a2), (const char *)ai->digest, ai->dlen);
949 
950     /* calculate response */
951     iov[0].iov_base = a1;
952     iov[0].iov_len  = ai->dlen*2;
953     iov[1].iov_base = ":";
954     iov[1].iov_len  = 1;
955     iov[2].iov_base = dp->ptr[e_nonce];
956     iov[2].iov_len  = dp->len[e_nonce];
957     iov[3].iov_base = ":";
958     iov[3].iov_len  = 1;
959     n = 4;
960     if (dp->len[e_qop]) {
961         iov[4].iov_base = dp->ptr[e_nc];
962         iov[4].iov_len  = dp->len[e_nc];
963         iov[5].iov_base = ":";
964         iov[5].iov_len  = 1;
965         iov[6].iov_base = dp->ptr[e_cnonce];
966         iov[6].iov_len  = dp->len[e_cnonce];
967         iov[7].iov_base = ":";
968         iov[7].iov_len  = 1;
969         iov[8].iov_base = dp->ptr[e_qop];
970         iov[8].iov_len  = dp->len[e_qop];
971         iov[9].iov_base = ":";
972         iov[9].iov_len  = 1;
973         n = 10;
974     }
975     iov[n].iov_base = a2;
976     iov[n].iov_len  = ai->dlen*2;
977     digest_iov(ai->digest, iov, n+1);
978 }
979 
980 
981 static void
982 mod_auth_append_nonce (buffer *b, unix_time64_t cur_ts, const struct http_auth_require_t *require, int dalgo, int *rndptr)
983 {
984     buffer_append_uint_hex(b, (uintmax_t)cur_ts);
985     buffer_append_char(b, ':');
986     const buffer * const nonce_secret = require->nonce_secret;
987     int rnd;
988     if (NULL == nonce_secret)
989         rnd = rndptr ? *rndptr : li_rand_pseudo();
990     else { /*(do not directly expose random number generator single value)*/
991         rndptr
992           ? (void)(rnd = *rndptr)
993           : li_rand_pseudo_bytes((unsigned char *)&rnd, sizeof(rnd));
994         buffer_append_uint_hex(b, (uintmax_t)rnd);
995         buffer_append_char(b, ':');
996     }
997 
998     size_t n;
999     struct const_iovec iov[3];
1000 
1001   #if 0
1002     char a1[LI_ITOSTRING_LENGTH];
1003     char a2[LI_ITOSTRING_LENGTH];
1004     iov[0].iov_base = a1;
1005     iov[0].iov_len  = li_itostrn(a1, sizeof(a1), cur_ts);
1006     iov[1].iov_base = a2;
1007     iov[1].iov_len  = li_itostrn(a2, sizeof(a2), rnd);
1008   #else
1009     iov[0].iov_base = &cur_ts;
1010     iov[0].iov_len  = sizeof(cur_ts);
1011     iov[1].iov_base = &rnd;
1012     iov[1].iov_len  = sizeof(rnd);
1013   #endif
1014     n = 2;
1015     if (nonce_secret) {
1016         iov[2].iov_base = nonce_secret->ptr;
1017         iov[2].iov_len  = buffer_clen(nonce_secret);
1018         n = 3;
1019     }
1020 
1021     unsigned char h[MD_DIGEST_LENGTH_MAX];
1022     switch (dalgo) {
1023      #ifdef USE_LIB_CRYPTO
1024       #ifdef USE_LIB_CRYPTO_SHA512_256
1025       case HTTP_AUTH_DIGEST_SHA512_256:
1026         SHA512_256_iov(h, iov, n);
1027         n = HTTP_AUTH_DIGEST_SHA512_256_BINLEN;
1028         break;
1029       #endif
1030       case HTTP_AUTH_DIGEST_SHA256:
1031         SHA256_iov(h, iov, n);
1032         n = HTTP_AUTH_DIGEST_SHA256_BINLEN;
1033         break;
1034      #endif
1035       /*case HTTP_AUTH_DIGEST_MD5:*/
1036       default:
1037         MD5_iov(h, iov, n);
1038         n = HTTP_AUTH_DIGEST_MD5_BINLEN;
1039         break;
1040     }
1041     li_tohex(buffer_extend(b, n*2), n*2+1, (const char *)h, n);
1042 }
1043 
1044 
1045 static void
1046 mod_auth_digest_www_authenticate (buffer *b, unix_time64_t cur_ts, const struct http_auth_require_t *require, int nonce_stale)
1047 {
1048     int algos = nonce_stale ? nonce_stale : require->algorithm;
1049     int n = 0;
1050     int algoid[3];
1051     unsigned int algolen[3];
1052     const char *algoname[3];
1053   #ifdef USE_LIB_CRYPTO
1054    #ifdef USE_LIB_CRYPTO_SHA512_256
1055     if (algos & HTTP_AUTH_DIGEST_SHA512_256) {
1056         algoid[n] = HTTP_AUTH_DIGEST_SHA512_256;
1057         algoname[n] = "SHA-512-256";
1058         algolen[n] = sizeof("SHA-512-256")-1;
1059         ++n;
1060     }
1061    #endif
1062     if (algos & HTTP_AUTH_DIGEST_SHA256) {
1063         algoid[n] = HTTP_AUTH_DIGEST_SHA256;
1064         algoname[n] = "SHA-256";
1065         algolen[n] = sizeof("SHA-256")-1;
1066         ++n;
1067     }
1068   #endif
1069     if (algos & HTTP_AUTH_DIGEST_MD5) {
1070         algoid[n] = HTTP_AUTH_DIGEST_MD5;
1071         algoname[n] = "MD5";
1072         algolen[n] = sizeof("MD5")-1;
1073         ++n;
1074     }
1075 
1076     buffer_clear(b);
1077     for (int i = 0; i < n; ++i) {
1078         struct const_iovec iov[] = {
1079           { CONST_STR_LEN("\r\nWWW-Authenticate: ") }
1080          ,{ CONST_STR_LEN("Digest realm=\"") }
1081          ,{ BUF_PTR_LEN(require->realm) }
1082          ,{ CONST_STR_LEN("\", charset=\"UTF-8\", algorithm=") }
1083          ,{ algoname[i], algolen[i] }
1084          ,{ CONST_STR_LEN(", nonce=\"") }
1085         };
1086         buffer_append_iovec(b, iov+(0==i), sizeof(iov)/sizeof(*iov)-(0==i));
1087         mod_auth_append_nonce(b, cur_ts, require, algoid[i], NULL);
1088         buffer_append_string_len(b, CONST_STR_LEN("\", qop=\"auth\""));
1089         if (require->userhash) {
1090             buffer_append_string_len(b, CONST_STR_LEN(", userhash=true"));
1091         }
1092         if (nonce_stale) {
1093             buffer_append_string_len(b, CONST_STR_LEN(", stale=true"));
1094         }
1095     }
1096 }
1097 
1098 
1099 __attribute_noinline__
1100 static handler_t
1101 mod_auth_send_401_unauthorized_digest(request_st * const r, const struct http_auth_require_t * const require, int nonce_stale)
1102 {
1103     r->http_status = 401;
1104     r->handler_module = NULL;
1105     mod_auth_digest_www_authenticate(
1106       http_header_response_set_ptr(r, HTTP_HEADER_WWW_AUTHENTICATE,
1107                                    CONST_STR_LEN("WWW-Authenticate")),
1108       log_epoch_secs, require, nonce_stale);
1109     return HANDLER_FINISHED;
1110 }
1111 
1112 
1113 static void
1114 mod_auth_digest_authentication_info (buffer *b, unix_time64_t cur_ts, const struct http_auth_require_t *require, int dalgo)
1115 {
1116     buffer_clear(b);
1117     buffer_append_string_len(b, CONST_STR_LEN("nextnonce=\""));
1118     mod_auth_append_nonce(b, cur_ts, require, dalgo, NULL);
1119     buffer_append_char(b, '"');
1120 }
1121 
1122 
1123 static handler_t
1124 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)
1125 {
1126     plugin_data * const p = p_d;
1127     splay_tree **sptree = p->conf.auth_cache
1128       ? &p->conf.auth_cache->sptree
1129       : NULL;
1130     http_auth_cache_entry *ae = NULL;
1131     handler_t rc = HANDLER_GO_ON;
1132     int ndx = -1;
1133 
1134     const char *user = ai->username;
1135     const uint32_t ulen = ai->ulen;
1136     char userbuf[sizeof(ai->userbuf)];
1137     if (ai->userhash && ulen <= sizeof(userbuf)) {
1138         /*(lowercase hex in userhash for consistency)*/
1139         const char * const restrict s = ai->username;
1140         for (uint_fast32_t i = 0; i < ulen; ++i)
1141             userbuf[i] = !light_isupper(s[i]) ? s[i] : (s[i] | 0x20);
1142         user = userbuf;
1143     }
1144 
1145     if (sptree) {
1146         ndx = http_auth_cache_hash(require, user, ulen);
1147         ae = http_auth_cache_query(sptree, ndx);
1148         if (ae && ae->require == require
1149             && ae->dalgo == ai->dalgo
1150             && ae->dlen == ai->dlen
1151             && ae->klen == ulen
1152             && 0 == memcmp(ae->k, user, ulen)
1153             && (ae->k == ae->username || ai->userhash)) {
1154             memcpy(ai->digest, ae->pwdigest, ai->dlen);
1155             if (ae->k != ae->username) { /*(userhash was key; copy username)*/
1156                 if (__builtin_expect( (ae->ulen <= sizeof(ai->userbuf)), 1)) {
1157                     ai->ulen = ae->ulen;
1158                     ai->username = memcpy(ai->userbuf, ae->username, ae->ulen);
1159                 }
1160             }
1161         }
1162         else /*(not found or hash collision)*/
1163             ae = NULL;
1164     }
1165 
1166     if (NULL == ae) {
1167         if (ai->userhash && ulen <= sizeof(ai->userbuf))
1168             ai->username = memcpy(ai->userbuf, userbuf, ulen);
1169             /* ai->username (lowercase userhash) will be replaced by username */
1170         rc = backend->digest(r, backend->p_d, ai);
1171     }
1172 
1173     switch (rc) {
1174     case HANDLER_GO_ON:
1175         break;
1176     case HANDLER_WAIT_FOR_EVENT:
1177         return HANDLER_WAIT_FOR_EVENT;
1178     case HANDLER_FINISHED:
1179         return HANDLER_FINISHED;
1180     case HANDLER_ERROR:
1181     default:
1182         r->keep_alive = -1; /*(disable keep-alive if unknown user)*/
1183         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1184     }
1185 
1186     if (sptree && NULL == ae) { /*(cache digest from backend)*/
1187         ae = http_auth_cache_entry_init(require, ai->dalgo, user, ulen,
1188                                         ai->username, ai->ulen,
1189                                         (char *)ai->digest, ai->dlen);
1190         http_auth_cache_insert(sptree, ndx, ae, http_auth_cache_entry_free);
1191     }
1192 
1193     return rc;
1194 }
1195 
1196 
1197 __attribute_cold__
1198 static handler_t
1199 mod_auth_digest_misconfigured (request_st * const r, const struct http_auth_backend_t * const backend)
1200 {
1201     if (NULL == backend)
1202         log_error(r->conf.errh, __FILE__, __LINE__,
1203           "auth.backend not configured for %s", r->uri.path.ptr);
1204     else
1205         log_error(r->conf.errh, __FILE__, __LINE__,
1206           "auth.require \"method\" => \"digest\" invalid "
1207           "(try \"basic\"?) for %s", r->uri.path.ptr);
1208 
1209     r->http_status = 500;
1210     r->handler_module = NULL;
1211     return HANDLER_FINISHED;
1212 }
1213 
1214 
1215 static void
1216 mod_auth_digest_parse_authorization (http_auth_digest_params_t * const dp, const char *c)
1217 {
1218     struct digest_kv {
1219         const char *key;
1220         uint32_t klen;
1221         enum http_auth_digest_params_e id;
1222     };
1223 
1224     static const struct digest_kv dkv[] = {
1225         { CONST_STR_LEN("username"),  e_username },
1226         { CONST_STR_LEN("realm"),     e_realm },
1227         { CONST_STR_LEN("nonce"),     e_nonce },
1228         { CONST_STR_LEN("uri"),       e_uri },
1229         { CONST_STR_LEN("algorithm"), e_algorithm },
1230         { CONST_STR_LEN("qop"),       e_qop },
1231         { CONST_STR_LEN("cnonce"),    e_cnonce },
1232         { CONST_STR_LEN("nc"),        e_nc },
1233         { CONST_STR_LEN("response"),  e_response },
1234         { CONST_STR_LEN("username*"), e_userstar },
1235         { CONST_STR_LEN("userhash"),  e_userhash },
1236 
1237         { NULL, 0, http_auth_digest_params_sz }
1238     };
1239 
1240     /* parse credentials from client */
1241     /* (caller must pass c pointing to string after "Digest ") */
1242     for (const char *e; *c; c++) {
1243         /* skip whitespaces */
1244         while (*c == ' ' || *c == '\t' || *c == ',') ++c;
1245         if (!*c) break;
1246         for (e = c; *e!='=' && *e!=' ' && *e!='\t' && *e!='\0'; ++e) ;
1247         const uint32_t tlen = (uint32_t)(e - c);
1248 
1249         for (int i = 0; dkv[i].key; ++i) {
1250             if (tlen != dkv[i].klen || 0 != memcmp(c, dkv[i].key, tlen))
1251                 continue;
1252             c += tlen;
1253             /* detect and step over '='; ignore BWS (bad whitespace) */
1254             if (__builtin_expect( (*c != '='), 0)) {
1255                 while (*c == ' ' || *c == '\t') ++c;
1256                 if (*c != '=') return; /*(including '\0')*/
1257             }
1258             do { ++c; } while (*c == ' ' || *c == '\t');
1259 
1260             if (*c == '"') {
1261                 for (e = ++c; *e != '"' && *e != '\0'; ++e) {
1262                     if (*e == '\\' && *++e == '\0') return;
1263                 }
1264                 if (*e != '"') return;
1265                 /* value with "..." *//*(XXX: quoted value not unescaped)*/
1266             }
1267             else {
1268                 for (e = c; *e!=',' && *e!=' ' && *e!='\t' && *e!='\0'; ++e) ;
1269                 /* value without "..." */
1270             }
1271             dp->ptr[dkv[i].id] = c;
1272             dp->len[dkv[i].id] = (uint16_t)(e - c);
1273             c = e;
1274             if (*c != ',') {
1275                 /*(could more strictly check for linear whitespace)*/
1276                 c = strchr(c, ',');
1277                 if (!c) return;
1278             }
1279             break;
1280         }
1281     }
1282 }
1283 
1284 
1285 static handler_t
1286 mod_auth_digest_validate_userstar (request_st * const r, http_auth_digest_params_t * const dp, http_auth_info_t * const ai)
1287 {
1288     /*assert(dp->ptr[e_userstar]);*/
1289 
1290     if (dp->len[e_userhash] == 4) { /*("true")*/
1291         log_error(r->conf.errh, __FILE__, __LINE__,
1292           "digest: invalid \"username*\" with \"userhash\" = true");
1293         return mod_auth_send_400_bad_request(r);
1294     }
1295 
1296     /* "username*" RFC5987 ext-value
1297      * ext-value = charset  "'" [ language ] "'" value-chars */
1298     const char *ptr = dp->ptr[e_userstar];
1299     uint32_t len    = dp->len[e_userstar];
1300     /* validate and step over charset... */
1301     if ((*ptr | 0x20) == 'u' && len > 5
1302         && buffer_eq_icase_ssn(ptr, "utf-8", 5))
1303         ptr += 5;
1304     else if ((*ptr | 0x20) == 'i' && len > 10
1305              && buffer_eq_icase_ssn(ptr, "iso-8859-1", 10))
1306         ptr += 10;
1307     else
1308         ptr = "\n"; /*(invalid char; (not '\''); error below)*/
1309     /* step over ...'language'... */
1310     if (*ptr++ != '\''
1311         || !(ptr = memchr(ptr, '\'',
1312                           len - (uint32_t)(ptr - dp->ptr[e_userstar])))) {
1313         log_error(r->conf.errh, __FILE__, __LINE__,
1314           "digest: invalid \"username*\" ext-value");
1315         return mod_auth_send_400_bad_request(r);
1316     }
1317     ++ptr;
1318 
1319     /* decode %XX encodings (could be more efficient by combining tests) */
1320     buffer * const tb = r->tmp_buf;
1321     buffer_copy_string_len(tb, ptr, len-(uint32_t)(ptr - dp->ptr[e_userstar]));
1322     buffer_urldecode_path(tb);
1323     if (dp->ptr[e_userstar][0] == 'u' && !buffer_is_valid_UTF8(tb)) {
1324         log_error(r->conf.errh, __FILE__, __LINE__,
1325           "digest: invalid \"username*\" invalid UTF-8");
1326         return mod_auth_send_400_bad_request(r);
1327     }
1328     len = buffer_clen(tb);
1329     if (len > sizeof(ai->userbuf)) {
1330         log_error(r->conf.errh, __FILE__, __LINE__,
1331           "digest: invalid \"username*\" too long");
1332         return mod_auth_send_400_bad_request(r);
1333     }
1334     for (ptr = tb->ptr; *ptr; ++ptr) {
1335         /* prohibit decoded control chars, including '\0','\r','\n' */
1336         /* (theoretically could permit '\t', but not currently done) */
1337         if (*(unsigned char *)ptr < 0x20 || *ptr == 127) { /* iscntrl() */
1338             log_error(r->conf.errh, __FILE__, __LINE__,
1339               "digest: invalid \"username*\" contains ctrl chars");
1340             return mod_auth_send_400_bad_request(r);
1341         }
1342     }
1343 
1344     ai->ulen     = len;
1345     ai->username = memcpy(ai->userbuf, tb->ptr, len);
1346     return HANDLER_GO_ON;
1347 }
1348 
1349 
1350 static handler_t
1351 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)
1352 {
1353     /* check for required parameters */
1354     if ((!dp->ptr[e_qop] || (dp->ptr[e_nc] && dp->ptr[e_cnonce]))
1355         && ((NULL != dp->ptr[e_username]) ^ (NULL != dp->ptr[e_userstar]))
1356         && dp->ptr[e_realm]
1357         && dp->ptr[e_nonce]
1358         && dp->ptr[e_uri]
1359         && dp->ptr[e_response]) {
1360         ai->username = dp->ptr[e_username];
1361         ai->ulen     = dp->len[e_username];
1362         ai->realm    = dp->ptr[e_realm];
1363         ai->rlen     = dp->len[e_realm];
1364         ai->userhash = (dp->len[e_userhash]==4);/*("true", not "false",absent)*/
1365         if (!ai->username) { /* (dp->ptr[e_userstar]) */
1366             if (HANDLER_GO_ON != mod_auth_digest_validate_userstar(r, dp, ai))
1367                 return HANDLER_FINISHED;
1368         }
1369     }
1370     else {
1371         log_error(r->conf.errh, __FILE__, __LINE__,
1372           "digest: missing field");
1373         return mod_auth_send_400_bad_request(r);
1374     }
1375 
1376     if (!buffer_eq_slen(require->realm, ai->realm, ai->rlen)) {
1377         log_error(r->conf.errh, __FILE__, __LINE__,
1378           "digest: realm mismatch");
1379         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1380     }
1381 
1382     if (!mod_auth_algorithm_parse(ai,dp->ptr[e_algorithm],dp->len[e_algorithm])
1383         || !(require->algorithm & ai->dalgo & ~HTTP_AUTH_DIGEST_SESS)) {
1384         log_error(r->conf.errh, __FILE__, __LINE__,
1385           "digest: (%.*s): invalid",
1386           (int)dp->len[e_algorithm], dp->ptr[e_algorithm]);
1387         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1388     }
1389 
1390     /* *-sess requires nonce and cnonce */
1391     if ((ai->dalgo & HTTP_AUTH_DIGEST_SESS)
1392         && (!dp->ptr[e_nonce] || !dp->ptr[e_cnonce])) {
1393         log_error(r->conf.errh, __FILE__, __LINE__,
1394           "digest: (%.*s): missing field",
1395           (int)dp->len[e_algorithm], dp->ptr[e_algorithm]);
1396         return mod_auth_send_400_bad_request(r);
1397     }
1398 
1399     if (0 != li_hex2bin(dp->rdigest, sizeof(dp->rdigest),
1400                         dp->ptr[e_response], dp->len[e_response])
1401         || dp->len[e_response] != (ai->dlen << 1)) {
1402         log_error(r->conf.errh, __FILE__, __LINE__,
1403           "digest: (%s): invalid format", dp->ptr[e_response]);
1404         return mod_auth_send_400_bad_request(r);
1405     }
1406 
1407     if (dp->ptr[e_qop]&& buffer_eq_icase_ss(dp->ptr[e_qop], dp->len[e_qop],
1408                                             CONST_STR_LEN("auth-int"))) {
1409         log_error(r->conf.errh, __FILE__, __LINE__,
1410           "digest: qop=auth-int not supported");
1411         return mod_auth_send_400_bad_request(r);
1412     }
1413 
1414     /* detect if attacker is attempting to reuse valid digest for one uri
1415      * on a different request uri.  Might also happen if intermediate proxy
1416      * altered client request line.  (Altered request would not result in
1417      * the same digest as that calculated by the client.)
1418      * Internal redirects such as with mod_rewrite will modify request uri.
1419      * Reauthentication is done to detect crossing auth realms, but this
1420      * uri validation step is bypassed.  r->target_orig is
1421      * original request-target sent in client request. */
1422     if (!buffer_eq_slen(&r->target_orig, dp->ptr[e_uri], dp->len[e_uri])) {
1423         log_error(r->conf.errh, __FILE__, __LINE__,
1424           "digest: auth failed: uri mismatch (%s != %.*s), IP: %s",
1425           r->target_orig.ptr, (int)dp->len[e_uri], dp->ptr[e_uri],
1426           r->con->dst_addr_buf.ptr);
1427         return mod_auth_send_400_bad_request(r);
1428     }
1429 
1430     return HANDLER_GO_ON;
1431 }
1432 
1433 
1434 static handler_t
1435 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)
1436 {
1437     /* check age of nonce.  Note, random data is used in nonce generation
1438      * in mod_auth_send_401_unauthorized_digest().  If that were replaced
1439      * with nanosecond time, then nonce secret would remain unique enough
1440      * for the purposes of Digest auth, and would be reproducible (and
1441      * verifiable) if nanoseconds were included with seconds as part of the
1442      * nonce "timestamp:secret".  However, doing so would expose a high
1443      * precision timestamp of the system to attackers.  timestamp in nonce
1444      * could theoretically be modified and still produce same md5sum, but
1445      * that is highly unlikely within a 10 min (moving) window of valid
1446      * time relative to current time (now).
1447      * If it is desired to validate that nonces were generated by server,
1448      * then specify auth.require = ( ... => ( "secret" => "..." ) )
1449      * When secret is specified, then instead of nanoseconds, the random
1450      * data value (included for unique nonces) will be exposed in the nonce
1451      * along with the timestamp, and the additional secret will be used to
1452      * validate that the server generated the nonce using that secret. */
1453     unix_time64_t ts = 0;
1454     const unsigned char * const nonce = (unsigned char *)dp->ptr[e_nonce];
1455     int i;
1456     for (i = 0; i < 16 && light_isxdigit(nonce[i]); ++i)
1457         ts = (unix_time64_t)((uint64_t)ts << 4) | hex2int(nonce[i]);
1458 
1459     const unix_time64_t cur_ts = log_epoch_secs;
1460     if (nonce[i] != ':' || ts > cur_ts || cur_ts - ts > 600) { /*(10 mins)*/
1461         /* nonce is stale; have client regenerate digest */
1462         return mod_auth_send_401_unauthorized_digest(r, require, ai->dalgo);
1463     }
1464 
1465     if (cur_ts - ts > 540)  /*(9 mins)*/
1466         dp->send_nextnonce_ts = cur_ts;
1467 
1468     if (require->nonce_secret) {
1469         unsigned int rnd = 0;
1470         for (int j = i+8; i < j && light_isxdigit(nonce[i]); ++i) {
1471             rnd = (rnd << 4) + hex2int(nonce[i]);
1472         }
1473         if (nonce[i] != ':') {
1474             /* nonce is invalid;
1475              * expect extra field w/ require->nonce_secret */
1476             log_error(r->conf.errh, __FILE__, __LINE__,
1477               "digest: nonce invalid");
1478             return mod_auth_send_400_bad_request(r);
1479         }
1480         buffer * const tb = r->tmp_buf;
1481         buffer_clear(tb);
1482         mod_auth_append_nonce(tb, cur_ts, require, ai->dalgo, (int *)&rnd);
1483         if (!buffer_eq_slen(tb, dp->ptr[e_nonce], dp->len[e_nonce])) {
1484             /* nonce not generated using current require->nonce_secret */
1485             log_error(r->conf.errh, __FILE__, __LINE__,
1486               "digest: nonce mismatch");
1487             return mod_auth_send_401_unauthorized_digest(r, require, 0);
1488         }
1489     }
1490 
1491     return HANDLER_GO_ON;
1492 }
1493 
1494 
1495 static handler_t
1496 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)
1497 {
1498     if (NULL == backend || NULL == backend->digest)
1499         return mod_auth_digest_misconfigured(r, backend);
1500 
1501     const buffer * const vb =
1502       http_header_request_get(r, HTTP_HEADER_AUTHORIZATION,
1503                               CONST_STR_LEN("Authorization"));
1504     if (NULL == vb || !buffer_eq_icase_ssn(vb->ptr, CONST_STR_LEN("Digest ")))
1505         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1506   #ifdef __COVERITY__
1507     if (buffer_clen(vb) < sizeof("Digest ")-1)
1508         return mod_auth_send_400_bad_request(r);
1509   #endif
1510 
1511     http_auth_digest_params_t dp;
1512     http_auth_info_t ai;
1513     handler_t rc;
1514 
1515     /* XXX: should use offsetof() (if portable enough) */
1516     memset(&dp, 0, sizeof(dp) - sizeof(dp.rdigest));
1517 
1518     mod_auth_digest_parse_authorization(&dp, vb->ptr + sizeof("Digest ")-1);
1519 
1520     rc = mod_auth_digest_validate_params(r, require, &dp, &ai);
1521     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1522         return rc;
1523 
1524     rc = mod_auth_digest_validate_nonce(r, require, &dp, &ai);
1525     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1526         return rc;
1527 
1528     rc = mod_auth_digest_get(r, p_d, require, backend, &ai);
1529     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1530         return rc;
1531 
1532     mod_auth_digest_mutate(&ai, &dp, http_method_buf(r->http_method));
1533 
1534     if (!ck_memeq_const_time_fixed_len(dp.rdigest, ai.digest, ai.dlen)) {
1535         /*ck_memzero(ai.digest, ai.dlen);*//*skip clear since mutated*/
1536         /* digest not ok */
1537         log_error(r->conf.errh, __FILE__, __LINE__,
1538           "digest: auth failed for %.*s: wrong password, IP: %s",
1539           (int)ai.ulen, ai.username, r->con->dst_addr_buf.ptr);
1540         r->keep_alive = -1; /*(disable keep-alive if bad password)*/
1541         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1542     }
1543     /*ck_memzero(ai.digest, ai.dlen);*//* skip clear since mutated */
1544 
1545     /* check authorization (authz); string args must be '\0'-terminated) */
1546     buffer * const tb = r->tmp_buf;
1547     buffer_copy_string_len(tb, ai.username, ai.ulen);
1548     if (!http_auth_match_rules(require, tb->ptr, NULL, NULL))
1549         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1550 
1551     if (dp.send_nextnonce_ts) {
1552         /*(send nextnonce when expiration is approaching)*/
1553         mod_auth_digest_authentication_info(
1554           http_header_response_set_ptr(r, HTTP_HEADER_OTHER,
1555                                        CONST_STR_LEN("Authentication-Info")),
1556           dp.send_nextnonce_ts /*(cur_ts)*/, require, ai.dalgo);
1557     }
1558 
1559     http_auth_setenv(r, ai.username, ai.ulen, CONST_STR_LEN("Digest"));
1560     return HANDLER_GO_ON;
1561 }
1562 
1563 
1564 
1565 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) {
1566     /* require REMOTE_USER already set */
1567     const buffer *vb = http_header_env_get(r, CONST_STR_LEN("REMOTE_USER"));
1568     UNUSED(p_d);
1569     UNUSED(backend);
1570     if (NULL != vb && http_auth_match_rules(require, vb->ptr, NULL, NULL)) {
1571         return HANDLER_GO_ON;
1572     } else {
1573         r->http_status = 401;
1574         r->handler_module = NULL;
1575         return HANDLER_FINISHED;
1576     }
1577 }
1578