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