xref: /lighttpd1.4/src/mod_auth.c (revision 20c56cec)
13538f8f2SGlenn Strauss /*
23538f8f2SGlenn Strauss  * http_auth - HTTP authentication and authorization
33538f8f2SGlenn Strauss  *
43538f8f2SGlenn Strauss  * Largely-rewritten from original
53538f8f2SGlenn Strauss  * Copyright(c) 2016,2021 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
63538f8f2SGlenn Strauss  * License: BSD 3-clause (same as lighttpd)
73538f8f2SGlenn Strauss  */
88abd06a7SGlenn Strauss #include "first.h"
98abd06a7SGlenn Strauss 
101fc8a3e1SGlenn Strauss #include <stdlib.h>
111fc8a3e1SGlenn Strauss #include <string.h>
121fc8a3e1SGlenn Strauss 
133538f8f2SGlenn Strauss #include "mod_auth_api.h"
141fc8a3e1SGlenn Strauss #include "sys-crypto-md.h" /* USE_LIB_CRYPTO */
151fc8a3e1SGlenn Strauss 
1604d76e7aSGlenn Strauss #include "base.h"
1762ccda85SGlenn Strauss #include "ck.h"
183dd3cde9SGlenn Strauss #include "http_header.h"
1922e8b456SStefan Bühler #include "log.h"
20156e1da2SGlenn Strauss #include "algo_splaytree.h"
213538f8f2SGlenn Strauss #include "plugin.h"
223538f8f2SGlenn Strauss #include "plugin_config.h"
23bcdc6a3bSJan Kneschke 
24bcdc6a3bSJan Kneschke /**
257ba06c71SGlenn Strauss  * auth framework
26bcdc6a3bSJan Kneschke  */
27bcdc6a3bSJan Kneschke 
284b3a91e6SGlenn Strauss typedef struct {
29e11514b0SGlenn Strauss     splay_tree *sptree; /* data in nodes of tree are (http_auth_cache_entry *)*/
30e11514b0SGlenn Strauss     time_t max_age;
31e11514b0SGlenn Strauss } http_auth_cache;
32e11514b0SGlenn Strauss 
33e11514b0SGlenn Strauss typedef struct {
344b3a91e6SGlenn Strauss     const http_auth_backend_t *auth_backend;
358e713130SGlenn Strauss     const array *auth_require;
36e11514b0SGlenn Strauss     http_auth_cache *auth_cache;
378e713130SGlenn Strauss     unsigned int auth_extern_authn;
387ba06c71SGlenn Strauss } plugin_config;
394b3a91e6SGlenn Strauss 
404b3a91e6SGlenn Strauss typedef struct {
414b3a91e6SGlenn Strauss     PLUGIN_DATA;
428e713130SGlenn Strauss     plugin_config defaults;
437ba06c71SGlenn Strauss     plugin_config conf;
447ba06c71SGlenn Strauss } plugin_data;
457ba06c71SGlenn Strauss 
46e11514b0SGlenn Strauss typedef struct {
47e11514b0SGlenn Strauss     const struct http_auth_require_t *require;
48e11514b0SGlenn Strauss     time_t ctime;
49e11514b0SGlenn Strauss     int dalgo;
50e11514b0SGlenn Strauss     uint32_t dlen;
51e11514b0SGlenn Strauss     uint32_t ulen;
52e11514b0SGlenn Strauss     char *username;
53e11514b0SGlenn Strauss     char *pwdigest;
54e11514b0SGlenn Strauss } http_auth_cache_entry;
55e11514b0SGlenn Strauss 
56e11514b0SGlenn Strauss static http_auth_cache_entry *
57e11514b0SGlenn Strauss 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)
58e11514b0SGlenn Strauss {
59e11514b0SGlenn Strauss     /*(similar to buffer_copy_string_len() for each element,
60e11514b0SGlenn Strauss      * but allocate exact lengths in single chunk of memory
61e11514b0SGlenn Strauss      * for cache to avoid wasting space and for memory locality)*/
62e11514b0SGlenn Strauss     /* http_auth_require_t is stored instead of copying realm
63e11514b0SGlenn Strauss      *(store pointer to http_auth_require_t, which is persistent
64e11514b0SGlenn Strauss      * and will be different for each realm + permissions combo)*/
65e11514b0SGlenn Strauss     http_auth_cache_entry * const ae =
66e11514b0SGlenn Strauss       malloc(sizeof(http_auth_cache_entry) + ulen + pwlen);
67e11514b0SGlenn Strauss     force_assert(ae);
68e11514b0SGlenn Strauss     ae->require = require;
69dbe3e236SGlenn Strauss     ae->ctime = log_monotonic_secs;
70e11514b0SGlenn Strauss     ae->dalgo = dalgo;
71e11514b0SGlenn Strauss     ae->ulen = ulen;
72e11514b0SGlenn Strauss     ae->dlen = pwlen;
73e11514b0SGlenn Strauss     ae->username = (char *)(ae + 1);
74e11514b0SGlenn Strauss     ae->pwdigest = ae->username + ulen;
75e11514b0SGlenn Strauss     memcpy(ae->username, username, ulen);
76e11514b0SGlenn Strauss     memcpy(ae->pwdigest, pw, pwlen);
77e11514b0SGlenn Strauss     return ae;
78e11514b0SGlenn Strauss }
79e11514b0SGlenn Strauss 
80e11514b0SGlenn Strauss static void
81e11514b0SGlenn Strauss http_auth_cache_entry_free (void *data)
82e11514b0SGlenn Strauss {
83e11514b0SGlenn Strauss     http_auth_cache_entry * const ae = data;
8408c03cd4SGlenn Strauss     ck_memzero(ae->pwdigest, ae->dlen);
85e11514b0SGlenn Strauss     free(ae);
86e11514b0SGlenn Strauss }
87e11514b0SGlenn Strauss 
88e11514b0SGlenn Strauss static void
89e11514b0SGlenn Strauss http_auth_cache_free (http_auth_cache *ac)
90e11514b0SGlenn Strauss {
91e11514b0SGlenn Strauss     splay_tree *sptree = ac->sptree;
92e11514b0SGlenn Strauss     while (sptree) {
93e11514b0SGlenn Strauss         http_auth_cache_entry_free(sptree->data);
94e11514b0SGlenn Strauss         sptree = splaytree_delete(sptree, sptree->key);
95e11514b0SGlenn Strauss     }
96e11514b0SGlenn Strauss     free(ac);
97e11514b0SGlenn Strauss }
98e11514b0SGlenn Strauss 
99e11514b0SGlenn Strauss static http_auth_cache *
100e11514b0SGlenn Strauss http_auth_cache_init (const array *opts)
101e11514b0SGlenn Strauss {
102e11514b0SGlenn Strauss     http_auth_cache *ac = malloc(sizeof(http_auth_cache));
103e11514b0SGlenn Strauss     force_assert(ac);
104e11514b0SGlenn Strauss     ac->sptree = NULL;
105e11514b0SGlenn Strauss     ac->max_age = 600; /* 10 mins */
106e11514b0SGlenn Strauss     for (uint32_t i = 0, used = opts->used; i < used; ++i) {
107d6f692f1SGlenn Strauss         data_unset *du = opts->data[i];
108d6f692f1SGlenn Strauss         if (buffer_is_equal_string(&du->key, CONST_STR_LEN("max-age")))
109d6f692f1SGlenn Strauss             ac->max_age = (time_t)config_plugin_value_to_int32(du, ac->max_age);
110e11514b0SGlenn Strauss     }
111e11514b0SGlenn Strauss     return ac;
112e11514b0SGlenn Strauss }
113e11514b0SGlenn Strauss 
114e11514b0SGlenn Strauss static int
115e11514b0SGlenn Strauss http_auth_cache_hash (const struct http_auth_require_t * const require, const char *username, const uint32_t ulen)
116e11514b0SGlenn Strauss {
117e11514b0SGlenn Strauss     uint32_t h = /*(hash pointer value, which includes realm and permissions)*/
118e11514b0SGlenn Strauss       djbhash((char *)(intptr_t)require, sizeof(intptr_t), DJBHASH_INIT);
119e11514b0SGlenn Strauss     h = djbhash(username, ulen, h);
120e11514b0SGlenn Strauss     /* strip highest bit of hash value for splaytree (see splaytree_djbhash())*/
121e11514b0SGlenn Strauss     return (int32_t)(h & ~(((uint32_t)1) << 31));
122e11514b0SGlenn Strauss }
123e11514b0SGlenn Strauss 
124e11514b0SGlenn Strauss static http_auth_cache_entry *
125e11514b0SGlenn Strauss http_auth_cache_query (splay_tree ** const sptree, const int ndx)
126e11514b0SGlenn Strauss {
127e11514b0SGlenn Strauss     *sptree = splaytree_splay(*sptree, ndx);
128e11514b0SGlenn Strauss     return (*sptree && (*sptree)->key == ndx) ? (*sptree)->data : NULL;
129e11514b0SGlenn Strauss }
130e11514b0SGlenn Strauss 
131e11514b0SGlenn Strauss static void
132e11514b0SGlenn Strauss http_auth_cache_insert (splay_tree ** const sptree, const int ndx, void * const data, void(data_free_fn)(void *))
133e11514b0SGlenn Strauss {
134e11514b0SGlenn Strauss     /*(not necessary to re-splay (with current usage) since single-threaded
135e11514b0SGlenn Strauss      * and splaytree has not been modified since http_auth_cache_query())*/
136e11514b0SGlenn Strauss     /* *sptree = splaytree_splay(*sptree, ndx); */
137e11514b0SGlenn Strauss     if (NULL == *sptree || (*sptree)->key != ndx)
138e11514b0SGlenn Strauss         *sptree = splaytree_insert(*sptree, ndx, data);
139e11514b0SGlenn Strauss     else { /* collision; replace old entry */
140e11514b0SGlenn Strauss         data_free_fn((*sptree)->data);
141e11514b0SGlenn Strauss         (*sptree)->data = data;
142e11514b0SGlenn Strauss     }
143e11514b0SGlenn Strauss }
144e11514b0SGlenn Strauss 
145e11514b0SGlenn Strauss /* walk though cache, collect expired ids, and remove them in a second loop */
146e11514b0SGlenn Strauss static void
147e11514b0SGlenn Strauss 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)
148e11514b0SGlenn Strauss {
149e11514b0SGlenn Strauss     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
150e11514b0SGlenn Strauss     if (t->left)
151e11514b0SGlenn Strauss         mod_auth_tag_old_entries(t->left, keys, ndx, max_age, cur_ts);
152e11514b0SGlenn Strauss     if (t->right)
153e11514b0SGlenn Strauss         mod_auth_tag_old_entries(t->right, keys, ndx, max_age, cur_ts);
154e11514b0SGlenn Strauss     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
155e11514b0SGlenn Strauss 
156e11514b0SGlenn Strauss     const http_auth_cache_entry * const ae = t->data;
157e11514b0SGlenn Strauss     if (cur_ts - ae->ctime > max_age)
158e11514b0SGlenn Strauss         keys[(*ndx)++] = t->key;
159e11514b0SGlenn Strauss }
160e11514b0SGlenn Strauss 
161e11514b0SGlenn Strauss __attribute_noinline__
162e11514b0SGlenn Strauss static void
163e11514b0SGlenn Strauss mod_auth_periodic_cleanup(splay_tree **sptree_ptr, const time_t max_age, const time_t cur_ts)
164e11514b0SGlenn Strauss {
165e11514b0SGlenn Strauss     splay_tree *sptree = *sptree_ptr;
166e11514b0SGlenn Strauss     int max_ndx, i;
167e11514b0SGlenn Strauss     int keys[8192]; /* 32k size on stack */
168e11514b0SGlenn Strauss     do {
169e11514b0SGlenn Strauss         if (!sptree) break;
170e11514b0SGlenn Strauss         max_ndx = 0;
171e11514b0SGlenn Strauss         mod_auth_tag_old_entries(sptree, keys, &max_ndx, max_age, cur_ts);
172e11514b0SGlenn Strauss         for (i = 0; i < max_ndx; ++i) {
173e11514b0SGlenn Strauss             int ndx = keys[i];
174e11514b0SGlenn Strauss             sptree = splaytree_splay(sptree, ndx);
175e11514b0SGlenn Strauss             if (sptree && sptree->key == ndx) {
176e11514b0SGlenn Strauss                 http_auth_cache_entry_free(sptree->data);
177e11514b0SGlenn Strauss                 sptree = splaytree_delete(sptree, ndx);
178e11514b0SGlenn Strauss             }
179e11514b0SGlenn Strauss         }
180e11514b0SGlenn Strauss     } while (max_ndx == sizeof(keys)/sizeof(int));
181e11514b0SGlenn Strauss     *sptree_ptr = sptree;
182e11514b0SGlenn Strauss }
183e11514b0SGlenn Strauss 
184e11514b0SGlenn Strauss TRIGGER_FUNC(mod_auth_periodic)
185e11514b0SGlenn Strauss {
186e11514b0SGlenn Strauss     const plugin_data * const p = p_d;
187dbe3e236SGlenn Strauss     const time_t cur_ts = log_monotonic_secs;
188e11514b0SGlenn Strauss     if (cur_ts & 0x7) return HANDLER_GO_ON; /*(continue once each 8 sec)*/
189e11514b0SGlenn Strauss     UNUSED(srv);
190e11514b0SGlenn Strauss 
191e11514b0SGlenn Strauss     /* future: might construct array of (http_auth_cache *) at startup
192e11514b0SGlenn Strauss      *         to avoid the need to search for them here */
19333e400b4SGlenn Strauss     /* (init i to 0 if global context; to 1 to skip empty global context) */
19433e400b4SGlenn Strauss     if (NULL == p->cvlist) return HANDLER_GO_ON;
19533e400b4SGlenn Strauss     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
196e11514b0SGlenn Strauss         const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
197e11514b0SGlenn Strauss         for (; cpv->k_id != -1; ++cpv) {
198e11514b0SGlenn Strauss             if (cpv->k_id != 3) continue; /* k_id == 3 for auth.cache */
199e11514b0SGlenn Strauss             if (cpv->vtype != T_CONFIG_LOCAL) continue;
200e11514b0SGlenn Strauss             http_auth_cache *ac = cpv->v.v;
201e11514b0SGlenn Strauss             mod_auth_periodic_cleanup(&ac->sptree, ac->max_age, cur_ts);
202e11514b0SGlenn Strauss         }
203e11514b0SGlenn Strauss     }
204e11514b0SGlenn Strauss 
205e11514b0SGlenn Strauss     return HANDLER_GO_ON;
206e11514b0SGlenn Strauss }
207e11514b0SGlenn Strauss 
208e11514b0SGlenn Strauss 
209e11514b0SGlenn Strauss 
210e11514b0SGlenn Strauss 
2117c7f8c46SGlenn Strauss 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);
2127c7f8c46SGlenn Strauss 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);
2137c7f8c46SGlenn Strauss 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);
2144b3a91e6SGlenn Strauss 
215bcdc6a3bSJan Kneschke INIT_FUNC(mod_auth_init) {
216e11514b0SGlenn Strauss 	static http_auth_scheme_t http_auth_scheme_basic  = { "basic",  mod_auth_check_basic,  NULL };
217e11514b0SGlenn Strauss 	static http_auth_scheme_t http_auth_scheme_digest = { "digest", mod_auth_check_digest, NULL };
2187ba06c71SGlenn Strauss 	static const http_auth_scheme_t http_auth_scheme_extern = { "extern", mod_auth_check_extern, NULL };
219e11514b0SGlenn Strauss 	plugin_data *p = calloc(1, sizeof(*p));
220e11514b0SGlenn Strauss 	force_assert(p);
2217ba06c71SGlenn Strauss 
2227ba06c71SGlenn Strauss 	/* register http_auth_scheme_* */
223e11514b0SGlenn Strauss 	http_auth_scheme_basic.p_d = p;
2247ba06c71SGlenn Strauss 	http_auth_scheme_set(&http_auth_scheme_basic);
225e11514b0SGlenn Strauss 	http_auth_scheme_digest.p_d = p;
2267ba06c71SGlenn Strauss 	http_auth_scheme_set(&http_auth_scheme_digest);
2277ba06c71SGlenn Strauss 	http_auth_scheme_set(&http_auth_scheme_extern);
228bcdc6a3bSJan Kneschke 
229bcdc6a3bSJan Kneschke 	return p;
230bcdc6a3bSJan Kneschke }
231bcdc6a3bSJan Kneschke 
232b73949e0SGlenn Strauss FREE_FUNC(mod_auth_free) {
233b73949e0SGlenn Strauss     plugin_data * const p = p_d;
2348e713130SGlenn Strauss     if (NULL == p->cvlist) return;
2358e713130SGlenn Strauss     /* (init i to 0 if global context; to 1 to skip empty global context) */
2368e713130SGlenn Strauss     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
2378e713130SGlenn Strauss         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
2388e713130SGlenn Strauss         for (; -1 != cpv->k_id; ++cpv) {
2398e713130SGlenn Strauss             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
2408e713130SGlenn Strauss             switch (cpv->k_id) {
2418e713130SGlenn Strauss               case 1: /* auth.require */
2428e713130SGlenn Strauss                 array_free(cpv->v.v);
2438e713130SGlenn Strauss                 break;
244e11514b0SGlenn Strauss               case 3: /* auth.cache */
245e11514b0SGlenn Strauss                 http_auth_cache_free(cpv->v.v);
246e11514b0SGlenn Strauss                 break;
2478e713130SGlenn Strauss               default:
2488e713130SGlenn Strauss                 break;
2498e713130SGlenn Strauss             }
2508e713130SGlenn Strauss         }
2518e713130SGlenn Strauss     }
2521a8ac120SGlenn Strauss 
2531a8ac120SGlenn Strauss     http_auth_dumbdata_reset();
2548e713130SGlenn Strauss }
2558e713130SGlenn Strauss 
2567ba06c71SGlenn Strauss /* data type for mod_auth structured data
2577ba06c71SGlenn Strauss  * (parsed from auth.require array of strings) */
2587ba06c71SGlenn Strauss typedef struct {
2597ba06c71SGlenn Strauss     DATA_UNSET;
2607ba06c71SGlenn Strauss     http_auth_require_t *require;
2617ba06c71SGlenn Strauss } data_auth;
2627ba06c71SGlenn Strauss 
2637ba06c71SGlenn Strauss static void data_auth_free(data_unset *d)
2647ba06c71SGlenn Strauss {
2657ba06c71SGlenn Strauss     data_auth * const dauth = (data_auth *)d;
266ad9b7e00SGlenn Strauss     free(dauth->key.ptr);
2677ba06c71SGlenn Strauss     http_auth_require_free(dauth->require);
2687ba06c71SGlenn Strauss     free(dauth);
2697ba06c71SGlenn Strauss }
2707ba06c71SGlenn Strauss 
2717ba06c71SGlenn Strauss static data_auth *data_auth_init(void)
2727ba06c71SGlenn Strauss {
2738c7f1dfbSGlenn Strauss     static const struct data_methods fn = {
2748c7f1dfbSGlenn Strauss       NULL, /* copy must not be called on this data */
2758c7f1dfbSGlenn Strauss       data_auth_free,
2768c7f1dfbSGlenn Strauss       NULL, /* insert_dup must not be called on this data */
2778c7f1dfbSGlenn Strauss     };
2787ba06c71SGlenn Strauss     data_auth * const dauth = calloc(1, sizeof(*dauth));
2797ba06c71SGlenn Strauss     force_assert(NULL != dauth);
2807ba06c71SGlenn Strauss     dauth->type       = TYPE_OTHER;
2818c7f1dfbSGlenn Strauss     dauth->fn         = &fn;
2827ba06c71SGlenn Strauss 
2837ba06c71SGlenn Strauss     dauth->require = http_auth_require_init();
2847ba06c71SGlenn Strauss 
2857ba06c71SGlenn Strauss     return dauth;
2867ba06c71SGlenn Strauss }
2877ba06c71SGlenn Strauss 
288870b0c13SGlenn Strauss static int mod_auth_algorithm_parse(http_auth_info_t *ai, const char *s, size_t len) {
289870b0c13SGlenn Strauss     if (0 == len) {
290b9e2be50SGlenn Strauss         ai->dalgo = HTTP_AUTH_DIGEST_MD5;
291b9e2be50SGlenn Strauss         ai->dlen  = HTTP_AUTH_DIGEST_MD5_BINLEN;
292b9e2be50SGlenn Strauss         return 1;
293b9e2be50SGlenn Strauss     }
294b9e2be50SGlenn Strauss 
295b9e2be50SGlenn Strauss     if (len > 5
296b9e2be50SGlenn Strauss         && (s[len-5]       ) == '-'
297b9e2be50SGlenn Strauss         && (s[len-4] | 0x20) == 's'
298b9e2be50SGlenn Strauss         && (s[len-3] | 0x20) == 'e'
299b9e2be50SGlenn Strauss         && (s[len-2] | 0x20) == 's'
300b9e2be50SGlenn Strauss         && (s[len-1] | 0x20) == 's') {
301b9e2be50SGlenn Strauss         ai->dalgo = HTTP_AUTH_DIGEST_SESS;
302b9e2be50SGlenn Strauss         len -= 5;
303b9e2be50SGlenn Strauss     }
304b9e2be50SGlenn Strauss     else {
305b9e2be50SGlenn Strauss         ai->dalgo = HTTP_AUTH_DIGEST_NONE;
306b9e2be50SGlenn Strauss     }
307b9e2be50SGlenn Strauss 
308b9e2be50SGlenn Strauss     if (3 == len
309b9e2be50SGlenn Strauss         && 'm' == (s[0] | 0x20)
310b9e2be50SGlenn Strauss         && 'd' == (s[1] | 0x20)
311b9e2be50SGlenn Strauss         && '5' == (s[2]       )) {
312b9e2be50SGlenn Strauss         ai->dalgo |= HTTP_AUTH_DIGEST_MD5;
313b9e2be50SGlenn Strauss         ai->dlen   = HTTP_AUTH_DIGEST_MD5_BINLEN;
314b9e2be50SGlenn Strauss         return 1;
315b9e2be50SGlenn Strauss     }
316b28a3714SGlenn Strauss   #ifdef USE_LIB_CRYPTO
317b9e2be50SGlenn Strauss     else if (len >= 7
318b9e2be50SGlenn Strauss              && 's' == (s[0] | 0x20)
319b9e2be50SGlenn Strauss              && 'h' == (s[1] | 0x20)
320b9e2be50SGlenn Strauss              && 'a' == (s[2] | 0x20)
321b9e2be50SGlenn Strauss              && '-' == (s[3]       )) {
322b9e2be50SGlenn Strauss         if (len == 7 && s[4] == '2' && s[5] == '5' && s[6] == '6') {
323b9e2be50SGlenn Strauss             ai->dalgo |= HTTP_AUTH_DIGEST_SHA256;
324b9e2be50SGlenn Strauss             ai->dlen   = HTTP_AUTH_DIGEST_SHA256_BINLEN;
325b9e2be50SGlenn Strauss             return 1;
326b9e2be50SGlenn Strauss         }
3271fc8a3e1SGlenn Strauss       #ifdef USE_LIB_CRYPTO_SHA512_256
328b9e2be50SGlenn Strauss         if (len == 11 && 0 == memcmp(s+4, "512-256", 7)) {
329b9e2be50SGlenn Strauss             ai->dalgo |= HTTP_AUTH_DIGEST_SHA512_256;
330b9e2be50SGlenn Strauss             ai->dlen   = HTTP_AUTH_DIGEST_SHA512_256_BINLEN;
331b9e2be50SGlenn Strauss             return 1;
332b9e2be50SGlenn Strauss         }
333b9e2be50SGlenn Strauss       #endif
334b9e2be50SGlenn Strauss     }
335b9e2be50SGlenn Strauss   #endif
336b9e2be50SGlenn Strauss     return 0; /*(error)*/
337b9e2be50SGlenn Strauss }
338b9e2be50SGlenn Strauss 
339b9e2be50SGlenn Strauss static int mod_auth_algorithms_parse(int *algorithm, buffer *algos) {
340870b0c13SGlenn Strauss     for (const char *s = algos->ptr, *p; s; s = p ? p+1 : NULL) {
341b9e2be50SGlenn Strauss         http_auth_info_t ai;
342b9e2be50SGlenn Strauss         p = strchr(s, '|');
343870b0c13SGlenn Strauss         if (!mod_auth_algorithm_parse(&ai, s, p ? (size_t)(p - s) : strlen(s)))
344870b0c13SGlenn Strauss             return 0;
345b9e2be50SGlenn Strauss         *algorithm |= ai.dalgo;
346b9e2be50SGlenn Strauss     }
347b9e2be50SGlenn Strauss     return 1;
348b9e2be50SGlenn Strauss }
349b9e2be50SGlenn Strauss 
350b5775b99SGlenn Strauss static int mod_auth_require_parse (http_auth_require_t * const require, const buffer *b, log_error_st *errh)
3517ba06c71SGlenn Strauss {
3527ba06c71SGlenn Strauss     /* user=name1|user=name2|group=name3|host=name4 */
3537ba06c71SGlenn Strauss 
3547ba06c71SGlenn Strauss     const char *str = b->ptr;
3557ba06c71SGlenn Strauss     const char *p;
3567ba06c71SGlenn Strauss 
3577ba06c71SGlenn Strauss     if (buffer_is_equal_string(b, CONST_STR_LEN("valid-user"))) {
3587ba06c71SGlenn Strauss         require->valid_user = 1;
3597ba06c71SGlenn Strauss         return 1; /* success */
3607ba06c71SGlenn Strauss     }
3617ba06c71SGlenn Strauss 
3627ba06c71SGlenn Strauss     do {
3637ba06c71SGlenn Strauss         const char *eq;
3647ba06c71SGlenn Strauss         size_t len;
3657ba06c71SGlenn Strauss         p = strchr(str, '|');
3667ba06c71SGlenn Strauss         len = NULL != p ? (size_t)(p - str) : strlen(str);
3677ba06c71SGlenn Strauss         eq = memchr(str, '=', len);
3687ba06c71SGlenn Strauss         if (NULL == eq) {
369b5775b99SGlenn Strauss             log_error(errh, __FILE__, __LINE__,
370010c2894SGlenn Strauss               "error parsing auth.require 'require' field: missing '=' "
371010c2894SGlenn Strauss               "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\"). "
372010c2894SGlenn Strauss               "error value: %s error near: %s", b->ptr, str);
3737ba06c71SGlenn Strauss             return 0;
3747ba06c71SGlenn Strauss         }
375b2c18f48SGlenn Strauss         if (eq[1] == '|' || eq[1] == '\0') {
376b5775b99SGlenn Strauss             log_error(errh, __FILE__, __LINE__,
377010c2894SGlenn Strauss               "error parsing auth.require 'require' field: "
378010c2894SGlenn Strauss               "missing token after '=' "
379010c2894SGlenn Strauss               "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\"). "
380010c2894SGlenn Strauss               "error value: %s error near: %s", b->ptr, str);
3817ba06c71SGlenn Strauss             return 0;
3827ba06c71SGlenn Strauss         }
3837ba06c71SGlenn Strauss 
3847ba06c71SGlenn Strauss         switch ((int)(eq - str)) {
3857ba06c71SGlenn Strauss           case 4:
3867ba06c71SGlenn Strauss             if (0 == memcmp(str, CONST_STR_LEN("user"))) {
387810109ccSGlenn Strauss                 /*("user=" is 5)*/
388a03afc90SGlenn Strauss                 array_set_key_value(&require->user, str+5, len-5, CONST_STR_LEN(""));
3897ba06c71SGlenn Strauss                 continue;
3907ba06c71SGlenn Strauss             }
3917ba06c71SGlenn Strauss             else if (0 == memcmp(str, CONST_STR_LEN("host"))) {
392810109ccSGlenn Strauss                 /*("host=" is 5)*/
393a03afc90SGlenn Strauss                 array_set_key_value(&require->host, str+5, len-5, CONST_STR_LEN(""));
394b5775b99SGlenn Strauss                 log_error(errh, __FILE__, __LINE__,
395010c2894SGlenn Strauss                   "warning parsing auth.require 'require' field: "
396010c2894SGlenn Strauss                   "'host' not implemented; field value: %s", b->ptr);
3977ba06c71SGlenn Strauss                 continue;
3987ba06c71SGlenn Strauss             }
3997ba06c71SGlenn Strauss             break; /* to error */
4007ba06c71SGlenn Strauss           case 5:
4017ba06c71SGlenn Strauss             if (0 == memcmp(str, CONST_STR_LEN("group"))) {
402810109ccSGlenn Strauss                 /*("group=" is 6)*/
403a03afc90SGlenn Strauss                 array_set_key_value(&require->group, str+6, len-6, CONST_STR_LEN(""));
4049c91af0cSGlenn Strauss               #if 0/*(supported by mod_authn_ldap, but not all other backends)*/
405b5775b99SGlenn Strauss                 log_error(errh, __FILE__, __LINE__,
406010c2894SGlenn Strauss                   "warning parsing auth.require 'require' field: "
407010c2894SGlenn Strauss                   "'group' not implemented; field value: %s", b->ptr);
4089c91af0cSGlenn Strauss               #endif
4097ba06c71SGlenn Strauss                 continue;
4107ba06c71SGlenn Strauss             }
4117ba06c71SGlenn Strauss             break; /* to error */
4127ba06c71SGlenn Strauss           case 10:
4137ba06c71SGlenn Strauss             if (0 == memcmp(str, CONST_STR_LEN("valid-user"))) {
414b5775b99SGlenn Strauss                 log_error(errh, __FILE__, __LINE__,
415010c2894SGlenn Strauss                   "error parsing auth.require 'require' field: "
416010c2894SGlenn Strauss                   "valid user can not be combined with other require rules "
417010c2894SGlenn Strauss                   "(expecting \"valid-user\" or "
418010c2894SGlenn Strauss                   "\"user=a|user=b|group=g|host=h\"). error value: %s", b->ptr);
4197ba06c71SGlenn Strauss                 return 0;
4207ba06c71SGlenn Strauss             }
4217ba06c71SGlenn Strauss             break; /* to error */
4227ba06c71SGlenn Strauss           default:
4237ba06c71SGlenn Strauss             break; /* to error */
4247ba06c71SGlenn Strauss         }
4257ba06c71SGlenn Strauss 
426b5775b99SGlenn Strauss         log_error(errh, __FILE__, __LINE__,
427010c2894SGlenn Strauss           "error parsing auth.require 'require' field: "
428010c2894SGlenn Strauss           "invalid/unsupported token "
429010c2894SGlenn Strauss           "(expecting \"valid-user\" or \"user=a|user=b|group=g|host=h\"). "
430010c2894SGlenn Strauss           "error value: %s error near: %s", b->ptr, str);
4317ba06c71SGlenn Strauss         return 0;
4327ba06c71SGlenn Strauss 
4337ba06c71SGlenn Strauss     } while (p && *((str = p+1)));
4347ba06c71SGlenn Strauss 
4357ba06c71SGlenn Strauss     return 1; /* success */
4367ba06c71SGlenn Strauss }
4377ba06c71SGlenn Strauss 
438b5775b99SGlenn Strauss static handler_t mod_auth_require_parse_array(const array *value, array * const auth_require, log_error_st *errh)
4398e713130SGlenn Strauss {
4408e713130SGlenn Strauss 		for (uint32_t n = 0; n < value->used; ++n) {
4417ba06c71SGlenn Strauss 			size_t m;
4428e713130SGlenn Strauss 			data_array *da_file = (data_array *)value->data[n];
4437ba06c71SGlenn Strauss 			const buffer *method = NULL, *realm = NULL, *require = NULL;
444e1188e77SGlenn Strauss 			const buffer *nonce_secret = NULL;
4457ba06c71SGlenn Strauss 			const http_auth_scheme_t *auth_scheme;
446b9e2be50SGlenn Strauss 			buffer *algos = NULL;
447b9e2be50SGlenn Strauss 			int algorithm = HTTP_AUTH_DIGEST_SESS;
4487ba06c71SGlenn Strauss 
449c2238256SGlenn Strauss 			if (!array_is_kvstring(&da_file->value)) {
450b5775b99SGlenn Strauss 				log_error(errh, __FILE__, __LINE__,
451010c2894SGlenn Strauss 				  "unexpected value for auth.require; expected "
452bd77abe0SGlenn Strauss 				  "auth.require = ( \"urlpath\" => ( \"option\" => \"value\" ) )");
4537ba06c71SGlenn Strauss 
4547ba06c71SGlenn Strauss 				return HANDLER_ERROR;
4557ba06c71SGlenn Strauss 			}
4567ba06c71SGlenn Strauss 
457c2238256SGlenn Strauss 			for (m = 0; m < da_file->value.used; m++) {
458c2238256SGlenn Strauss 				if (da_file->value.data[m]->type == TYPE_STRING) {
459c2238256SGlenn Strauss 					data_string *ds = (data_string *)da_file->value.data[m];
460ad9b7e00SGlenn Strauss 					if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("method"))) {
461601c572cSGlenn Strauss 						method = &ds->value;
462ad9b7e00SGlenn Strauss 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("realm"))) {
463601c572cSGlenn Strauss 						realm = &ds->value;
464ad9b7e00SGlenn Strauss 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("require"))) {
465601c572cSGlenn Strauss 						require = &ds->value;
466ad9b7e00SGlenn Strauss 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("algorithm"))) {
467601c572cSGlenn Strauss 						algos = &ds->value;
46833ae8302SGlenn Strauss 					} else if (buffer_is_equal_string(&ds->key, CONST_STR_LEN("nonce_secret"))
46933ae8302SGlenn Strauss 					           || buffer_is_equal_string(&ds->key, CONST_STR_LEN("nonce-secret"))) {
470e1188e77SGlenn Strauss 						nonce_secret = &ds->value;
4717ba06c71SGlenn Strauss 					} else {
472b5775b99SGlenn Strauss 						log_error(errh, __FILE__, __LINE__,
473010c2894SGlenn Strauss 						  "the field is unknown in: "
474010c2894SGlenn Strauss 						  "auth.require = ( \"...\" => ( ..., -> \"%s\" <- => \"...\" ) )",
475010c2894SGlenn Strauss 						  da_file->value.data[m]->key.ptr);
4767ba06c71SGlenn Strauss 
4777ba06c71SGlenn Strauss 						return HANDLER_ERROR;
4787ba06c71SGlenn Strauss 					}
4797ba06c71SGlenn Strauss 				} else {
480b5775b99SGlenn Strauss 					log_error(errh, __FILE__, __LINE__,
481010c2894SGlenn Strauss 					  "a string was expected for: "
482010c2894SGlenn Strauss 					  "auth.require = ( \"...\" => ( ..., -> \"%s\" <- => \"...\" ) )",
483010c2894SGlenn Strauss 					  da_file->value.data[m]->key.ptr);
4847ba06c71SGlenn Strauss 
4857ba06c71SGlenn Strauss 					return HANDLER_ERROR;
4867ba06c71SGlenn Strauss 				}
4877ba06c71SGlenn Strauss 			}
4887ba06c71SGlenn Strauss 
489af3df29aSGlenn Strauss 			if (!method || buffer_is_blank(method)) {
490b5775b99SGlenn Strauss 				log_error(errh, __FILE__, __LINE__,
491010c2894SGlenn Strauss 				  "the method field is missing or blank in: "
4927ba06c71SGlenn Strauss 				  "auth.require = ( \"...\" => ( ..., \"method\" => \"...\" ) )");
4937ba06c71SGlenn Strauss 				return HANDLER_ERROR;
4947ba06c71SGlenn Strauss 			} else {
4957ba06c71SGlenn Strauss 				auth_scheme = http_auth_scheme_get(method);
4967ba06c71SGlenn Strauss 				if (NULL == auth_scheme) {
497b5775b99SGlenn Strauss 					log_error(errh, __FILE__, __LINE__,
498010c2894SGlenn Strauss 					  "unknown method %s (e.g. \"basic\", \"digest\" or \"extern\") in "
499010c2894SGlenn Strauss 					  "auth.require = ( \"...\" => ( ..., \"method\" => \"...\") )", method->ptr);
5007ba06c71SGlenn Strauss 					return HANDLER_ERROR;
5017ba06c71SGlenn Strauss 				}
5027ba06c71SGlenn Strauss 			}
5037ba06c71SGlenn Strauss 
504af3df29aSGlenn Strauss 			if (!realm) {
505b5775b99SGlenn Strauss 				log_error(errh, __FILE__, __LINE__,
506010c2894SGlenn Strauss 				  "the realm field is missing in: "
5077ba06c71SGlenn Strauss 				  "auth.require = ( \"...\" => ( ..., \"realm\" => \"...\" ) )");
5087ba06c71SGlenn Strauss 				return HANDLER_ERROR;
5097ba06c71SGlenn Strauss 			}
5107ba06c71SGlenn Strauss 
511af3df29aSGlenn Strauss 			if (!require || buffer_is_blank(require)) {
512b5775b99SGlenn Strauss 				log_error(errh, __FILE__, __LINE__,
513010c2894SGlenn Strauss 				  "the require field is missing or blank in: "
5147ba06c71SGlenn Strauss 				  "auth.require = ( \"...\" => ( ..., \"require\" => \"...\" ) )");
5157ba06c71SGlenn Strauss 				return HANDLER_ERROR;
5167ba06c71SGlenn Strauss 			}
5177ba06c71SGlenn Strauss 
518af3df29aSGlenn Strauss 			if (!algos || buffer_is_blank(algos)) {
519b9e2be50SGlenn Strauss 				algorithm |= HTTP_AUTH_DIGEST_MD5;
520b9e2be50SGlenn Strauss 			} else if (!mod_auth_algorithms_parse(&algorithm, algos)) {
521b5775b99SGlenn Strauss 				log_error(errh, __FILE__, __LINE__,
522010c2894SGlenn Strauss 				  "invalid algorithm in: "
523b9e2be50SGlenn Strauss 				  "auth.require = ( \"...\" => ( ..., \"algorithm\" => \"...\" ) )");
524b9e2be50SGlenn Strauss 				return HANDLER_ERROR;
525b9e2be50SGlenn Strauss 			}
526b9e2be50SGlenn Strauss 
527609e9a50SGlenn Strauss 			if (require) { /*(always true at this point)*/
5287ba06c71SGlenn Strauss 				data_auth * const dauth = data_auth_init();
529ad9b7e00SGlenn Strauss 				buffer_copy_buffer(&dauth->key, &da_file->key);
5307ba06c71SGlenn Strauss 				dauth->require->scheme = auth_scheme;
531b9e2be50SGlenn Strauss 				dauth->require->algorithm = algorithm;
532a03afc90SGlenn Strauss 				dauth->require->realm = realm;
533e1188e77SGlenn Strauss 				dauth->require->nonce_secret = nonce_secret; /*(NULL is ok)*/
534b5775b99SGlenn Strauss 				if (!mod_auth_require_parse(dauth->require, require, errh)) {
5358c7f1dfbSGlenn Strauss 					dauth->fn->free((data_unset *)dauth);
5367ba06c71SGlenn Strauss 					return HANDLER_ERROR;
5377ba06c71SGlenn Strauss 				}
5388e713130SGlenn Strauss 				array_insert_unique(auth_require, (data_unset *)dauth);
5397ba06c71SGlenn Strauss 			}
5407ba06c71SGlenn Strauss 		}
5417ba06c71SGlenn Strauss 
5427ba06c71SGlenn Strauss 	return HANDLER_GO_ON;
5437ba06c71SGlenn Strauss }
5447ba06c71SGlenn Strauss 
5458e713130SGlenn Strauss static void mod_auth_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
5468e713130SGlenn Strauss     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
5478e713130SGlenn Strauss       case 0: /* auth.backend */
5488e713130SGlenn Strauss         if (cpv->vtype == T_CONFIG_LOCAL)
5498e713130SGlenn Strauss             pconf->auth_backend = cpv->v.v;
5508e713130SGlenn Strauss         break;
5518e713130SGlenn Strauss       case 1: /* auth.require */
5528e713130SGlenn Strauss         if (cpv->vtype == T_CONFIG_LOCAL)
5538e713130SGlenn Strauss             pconf->auth_require = cpv->v.v;
5548e713130SGlenn Strauss         break;
5558e713130SGlenn Strauss       case 2: /* auth.extern-authn */
5568e713130SGlenn Strauss         pconf->auth_extern_authn = cpv->v.u;
557e11514b0SGlenn Strauss         break;
558e11514b0SGlenn Strauss       case 3: /* auth.cache */
559e11514b0SGlenn Strauss         if (cpv->vtype == T_CONFIG_LOCAL)
560e11514b0SGlenn Strauss             pconf->auth_cache = cpv->v.v;
561e11514b0SGlenn Strauss         break;
5628e713130SGlenn Strauss       default:/* should not happen */
5638e713130SGlenn Strauss         return;
5648e713130SGlenn Strauss     }
5658e713130SGlenn Strauss }
5664a6ce4aeSJan Kneschke 
5678e713130SGlenn Strauss static void mod_auth_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
5688e713130SGlenn Strauss     do {
5698e713130SGlenn Strauss         mod_auth_merge_config_cpv(pconf, cpv);
5708e713130SGlenn Strauss     } while ((++cpv)->k_id != -1);
5718e713130SGlenn Strauss }
572bcdc6a3bSJan Kneschke 
5737c7f8c46SGlenn Strauss static void mod_auth_patch_config(request_st * const r, plugin_data * const p) {
574cc2134c8SGlenn Strauss     p->conf = p->defaults; /* copy small struct instead of memcpy() */
575cc2134c8SGlenn Strauss     /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/
5768e713130SGlenn Strauss     for (int i = 1, used = p->nconfig; i < used; ++i) {
5777c7f8c46SGlenn Strauss         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
5788e713130SGlenn Strauss             mod_auth_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
5798e713130SGlenn Strauss     }
5808e713130SGlenn Strauss }
58136f64b26SGlenn Strauss 
5828e713130SGlenn Strauss SETDEFAULTS_FUNC(mod_auth_set_defaults) {
5838e713130SGlenn Strauss     static const config_plugin_keys_t cpk[] = {
5848e713130SGlenn Strauss       { CONST_STR_LEN("auth.backend"),
5858e713130SGlenn Strauss         T_CONFIG_STRING,
5868e713130SGlenn Strauss         T_CONFIG_SCOPE_CONNECTION }
5878e713130SGlenn Strauss      ,{ CONST_STR_LEN("auth.require"),
58803b4c993SGlenn Strauss         T_CONFIG_ARRAY_KVARRAY,
5898e713130SGlenn Strauss         T_CONFIG_SCOPE_CONNECTION }
5908e713130SGlenn Strauss      ,{ CONST_STR_LEN("auth.extern-authn"),
5918e713130SGlenn Strauss         T_CONFIG_BOOL,
5928e713130SGlenn Strauss         T_CONFIG_SCOPE_CONNECTION }
593e11514b0SGlenn Strauss      ,{ CONST_STR_LEN("auth.cache"),
594e11514b0SGlenn Strauss         T_CONFIG_ARRAY,
595e11514b0SGlenn Strauss         T_CONFIG_SCOPE_CONNECTION }
5968e713130SGlenn Strauss      ,{ NULL, 0,
5978e713130SGlenn Strauss         T_CONFIG_UNSET,
5988e713130SGlenn Strauss         T_CONFIG_SCOPE_UNSET }
5998e713130SGlenn Strauss     };
600bcdc6a3bSJan Kneschke 
6018e713130SGlenn Strauss     plugin_data * const p = p_d;
6028e713130SGlenn Strauss     if (!config_plugin_values_init(srv, p, cpk, "mod_auth"))
6038e713130SGlenn Strauss         return HANDLER_ERROR;
604bcdc6a3bSJan Kneschke 
6058e713130SGlenn Strauss     /* process and validate config directives
6068e713130SGlenn Strauss      * (init i to 0 if global context; to 1 to skip empty global context) */
6078e713130SGlenn Strauss     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
6088e713130SGlenn Strauss         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
6098e713130SGlenn Strauss         for (; -1 != cpv->k_id; ++cpv) {
6108e713130SGlenn Strauss             switch (cpv->k_id) {
6118e713130SGlenn Strauss               case 0: /* auth.backend */
612af3df29aSGlenn Strauss                 if (!buffer_is_blank(cpv->v.b)) {
6138e713130SGlenn Strauss                     const http_auth_backend_t * const auth_backend =
6148e713130SGlenn Strauss                       http_auth_backend_get(cpv->v.b);
6158e713130SGlenn Strauss                     if (NULL == auth_backend) {
6168e713130SGlenn Strauss                         log_error(srv->errh, __FILE__, __LINE__,
6178e713130SGlenn Strauss                           "auth.backend not supported: %s", cpv->v.b->ptr);
6188e713130SGlenn Strauss                         return HANDLER_ERROR;
6198e713130SGlenn Strauss                     }
6208e713130SGlenn Strauss                     *(const http_auth_backend_t **)&cpv->v.v = auth_backend;
6218e713130SGlenn Strauss                     cpv->vtype = T_CONFIG_LOCAL;
6228e713130SGlenn Strauss                 }
6238e713130SGlenn Strauss                 break;
6248e713130SGlenn Strauss               case 1: /* auth.require */
62503b4c993SGlenn Strauss                 {
62624680a91SGlenn Strauss                     array * const a = array_init(4);
6278e713130SGlenn Strauss                     if (HANDLER_GO_ON !=
628b5775b99SGlenn Strauss                         mod_auth_require_parse_array(cpv->v.a, a, srv->errh)) {
6298e713130SGlenn Strauss                         array_free(a);
6308e713130SGlenn Strauss                         return HANDLER_ERROR;
6318e713130SGlenn Strauss                     }
6328e713130SGlenn Strauss                     cpv->v.a = a;
6338e713130SGlenn Strauss                     cpv->vtype = T_CONFIG_LOCAL;
6348e713130SGlenn Strauss                 }
6358e713130SGlenn Strauss                 break;
6368e713130SGlenn Strauss               case 2: /* auth.extern-authn */
6378e713130SGlenn Strauss                 break;
638e11514b0SGlenn Strauss               case 3: /* auth.cache */
639e11514b0SGlenn Strauss                 cpv->v.v = http_auth_cache_init(cpv->v.a);
640e11514b0SGlenn Strauss                 cpv->vtype = T_CONFIG_LOCAL;
641e11514b0SGlenn Strauss                 break;
6428e713130SGlenn Strauss               default:/* should not happen */
6438e713130SGlenn Strauss                 break;
644bcdc6a3bSJan Kneschke             }
645bcdc6a3bSJan Kneschke         }
646bcdc6a3bSJan Kneschke     }
647bcdc6a3bSJan Kneschke 
6488e713130SGlenn Strauss     /* initialize p->defaults from global config context */
6498e713130SGlenn Strauss     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
6508e713130SGlenn Strauss         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
6518e713130SGlenn Strauss         if (-1 != cpv->k_id)
6528e713130SGlenn Strauss             mod_auth_merge_config(&p->defaults, cpv);
653bcdc6a3bSJan Kneschke     }
6548e713130SGlenn Strauss 
6558e713130SGlenn Strauss     return HANDLER_GO_ON;
6568e713130SGlenn Strauss }
657bcdc6a3bSJan Kneschke 
6587c7f8c46SGlenn Strauss static handler_t mod_auth_uri_handler(request_st * const r, void *p_d) {
6597ba06c71SGlenn Strauss 	plugin_data *p = p_d;
660d61f3381SGlenn Strauss 	data_auth *dauth;
66181b2d1f0SGlenn Strauss 
6627c7f8c46SGlenn Strauss 	mod_auth_patch_config(r, p);
66381b2d1f0SGlenn Strauss 
6647ba06c71SGlenn Strauss 	if (p->conf.auth_require == NULL) return HANDLER_GO_ON;
66581b2d1f0SGlenn Strauss 
6667ba06c71SGlenn Strauss 	/* search auth directives for first prefix match against URL path */
6677ba06c71SGlenn Strauss 	/* if we have a case-insensitive FS we have to lower-case the URI here too */
6687c7f8c46SGlenn Strauss 	dauth = (!r->conf.force_lowercase_filenames)
6697c7f8c46SGlenn Strauss 	   ? (data_auth *)array_match_key_prefix(p->conf.auth_require, &r->uri.path)
6707c7f8c46SGlenn Strauss 	   : (data_auth *)array_match_key_prefix_nc(p->conf.auth_require, &r->uri.path);
671d61f3381SGlenn Strauss 	if (NULL == dauth) return HANDLER_GO_ON;
6727ba06c71SGlenn Strauss 
673d61f3381SGlenn Strauss 	{
6747ba06c71SGlenn Strauss 			const http_auth_scheme_t * const scheme = dauth->require->scheme;
675f54d628cSGlenn Strauss 			if (p->conf.auth_extern_authn) {
6767c7f8c46SGlenn Strauss 				const buffer *vb = http_header_env_get(r, CONST_STR_LEN("REMOTE_USER"));
6773dd3cde9SGlenn Strauss 				if (NULL != vb && http_auth_match_rules(dauth->require, vb->ptr, NULL, NULL)) {
678f54d628cSGlenn Strauss 					return HANDLER_GO_ON;
679f54d628cSGlenn Strauss 				}
680f54d628cSGlenn Strauss 			}
6817c7f8c46SGlenn Strauss 			return scheme->checkfn(r, scheme->p_d, dauth->require, p->conf.auth_backend);
6827ba06c71SGlenn Strauss 	}
6837ba06c71SGlenn Strauss }
6847ba06c71SGlenn Strauss 
685e11514b0SGlenn Strauss 
6867ba06c71SGlenn Strauss int mod_auth_plugin_init(plugin *p);
6877ba06c71SGlenn Strauss int mod_auth_plugin_init(plugin *p) {
6887ba06c71SGlenn Strauss 	p->version     = LIGHTTPD_VERSION_ID;
689e2de4e58SGlenn Strauss 	p->name        = "auth";
6907ba06c71SGlenn Strauss 	p->init        = mod_auth_init;
6917ba06c71SGlenn Strauss 	p->set_defaults = mod_auth_set_defaults;
692e11514b0SGlenn Strauss 	p->handle_trigger = mod_auth_periodic;
6937ba06c71SGlenn Strauss 	p->handle_uri_clean = mod_auth_uri_handler;
6947ba06c71SGlenn Strauss 	p->cleanup     = mod_auth_free;
6957ba06c71SGlenn Strauss 
69681b2d1f0SGlenn Strauss 	return 0;
69781b2d1f0SGlenn Strauss }
69881b2d1f0SGlenn Strauss 
69981b2d1f0SGlenn Strauss 
70081b2d1f0SGlenn Strauss 
70181b2d1f0SGlenn Strauss 
7027ba06c71SGlenn Strauss /*
7037ba06c71SGlenn Strauss  * auth schemes (basic, digest, extern)
7047ba06c71SGlenn Strauss  *
7057ba06c71SGlenn Strauss  * (could be in separate file from mod_auth.c as long as registration occurs)
7067ba06c71SGlenn Strauss  */
70781b2d1f0SGlenn Strauss 
7081fc8a3e1SGlenn Strauss #include "sys-crypto-md.h"
7097ba06c71SGlenn Strauss #include "base64.h"
7107f4e156eSGlenn Strauss #include "rand.h"
7113dd3cde9SGlenn Strauss #include "http_header.h"
71281b2d1f0SGlenn Strauss 
713010c2894SGlenn Strauss __attribute_cold__
714ffc7a0bfSGlenn Strauss __attribute_noinline__
7157c7f8c46SGlenn Strauss static handler_t mod_auth_send_400_bad_request(request_st * const r) {
7164b3a91e6SGlenn Strauss 
7174b3a91e6SGlenn Strauss 	/* a field was missing or invalid */
7187c7f8c46SGlenn Strauss 	r->http_status = 400; /* Bad Request */
7197c7f8c46SGlenn Strauss 	r->handler_module = NULL;
7204b3a91e6SGlenn Strauss 
7214b3a91e6SGlenn Strauss 	return HANDLER_FINISHED;
7224b3a91e6SGlenn Strauss }
7234b3a91e6SGlenn Strauss 
724*20c56cecSGlenn Strauss 
725*20c56cecSGlenn Strauss 
726ffc7a0bfSGlenn Strauss __attribute_noinline__
7277c7f8c46SGlenn Strauss static handler_t mod_auth_send_401_unauthorized_basic(request_st * const r, const buffer * const realm) {
7287c7f8c46SGlenn Strauss     r->http_status = 401;
7297c7f8c46SGlenn Strauss     r->handler_module = NULL;
730dc01487eSGlenn Strauss     buffer_append_str3(
73126f354cbSGlenn Strauss       http_header_response_set_ptr(r, HTTP_HEADER_WWW_AUTHENTICATE,
732dc01487eSGlenn Strauss                                    CONST_STR_LEN("WWW-Authenticate")),
733dc01487eSGlenn Strauss       CONST_STR_LEN("Basic realm=\""),
734af3df29aSGlenn Strauss       BUF_PTR_LEN(realm),
735dc01487eSGlenn Strauss       CONST_STR_LEN("\", charset=\"UTF-8\""));
7364b3a91e6SGlenn Strauss     return HANDLER_FINISHED;
7374b3a91e6SGlenn Strauss }
7384b3a91e6SGlenn Strauss 
7397c7f8c46SGlenn Strauss 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) {
74081b2d1f0SGlenn Strauss 	buffer *username;
74181b2d1f0SGlenn Strauss 	char *pw;
74281b2d1f0SGlenn Strauss 
743cf0098eaSGlenn Strauss 	if (NULL == backend || NULL == backend->basic) {
744cf0098eaSGlenn Strauss 		if (NULL == backend)
745cf0098eaSGlenn Strauss 			log_error(r->conf.errh, __FILE__, __LINE__,
746cf0098eaSGlenn Strauss 			  "auth.backend not configured for %s", r->uri.path.ptr);
747cf0098eaSGlenn Strauss 		else
748cf0098eaSGlenn Strauss 			log_error(r->conf.errh, __FILE__, __LINE__,
749cf0098eaSGlenn Strauss 			  "auth.require \"method\" => \"basic\" invalid "
750cf0098eaSGlenn Strauss 			  "(try \"digest\"?) for %s",
751cf0098eaSGlenn Strauss 			  r->uri.path.ptr);
7527c7f8c46SGlenn Strauss 		r->http_status = 500;
7537c7f8c46SGlenn Strauss 		r->handler_module = NULL;
7547ba06c71SGlenn Strauss 		return HANDLER_FINISHED;
7557ba06c71SGlenn Strauss 	}
7567ba06c71SGlenn Strauss 
757ffc7a0bfSGlenn Strauss 	const buffer * const b =
758ffc7a0bfSGlenn Strauss 	  http_header_request_get(r, HTTP_HEADER_AUTHORIZATION,
759ffc7a0bfSGlenn Strauss 	                          CONST_STR_LEN("Authorization"));
7607ba06c71SGlenn Strauss 
761ffc7a0bfSGlenn Strauss 	if (NULL == b || !buffer_eq_icase_ssn(b->ptr, CONST_STR_LEN("Basic "))) {
7627c7f8c46SGlenn Strauss 		return mod_auth_send_401_unauthorized_basic(r, require->realm);
7634b3a91e6SGlenn Strauss 	}
7649bc61f16SGlenn Strauss       #ifdef __COVERITY__
765af3df29aSGlenn Strauss 	if (buffer_clen(b) < sizeof("Basic ")-1) {
7667c7f8c46SGlenn Strauss 		return mod_auth_send_400_bad_request(r);
7679bc61f16SGlenn Strauss 	}
7689bc61f16SGlenn Strauss       #endif
76981b2d1f0SGlenn Strauss 
77081b2d1f0SGlenn Strauss 	username = buffer_init();
77181b2d1f0SGlenn Strauss 
7728047c2f4SGlenn Strauss 	/* coverity[overflow_sink : FALSE] */
773af3df29aSGlenn Strauss 	if (!buffer_append_base64_decode(username, b->ptr+sizeof("Basic ")-1, buffer_clen(b)-(sizeof("Basic ")-1), BASE64_STANDARD)) {
7747c7f8c46SGlenn Strauss 		log_error(r->conf.errh, __FILE__, __LINE__, "decoding base64-string failed %s", b->ptr+sizeof("Basic ")-1);
77581b2d1f0SGlenn Strauss 
77681b2d1f0SGlenn Strauss 		buffer_free(username);
7777c7f8c46SGlenn Strauss 		return mod_auth_send_400_bad_request(r);
77881b2d1f0SGlenn Strauss 	}
77981b2d1f0SGlenn Strauss 
78081b2d1f0SGlenn Strauss 	/* r2 == user:password */
78181b2d1f0SGlenn Strauss 	if (NULL == (pw = strchr(username->ptr, ':'))) {
7827c7f8c46SGlenn Strauss 		log_error(r->conf.errh, __FILE__, __LINE__, "missing ':' in %s", username->ptr);
78381b2d1f0SGlenn Strauss 
78481b2d1f0SGlenn Strauss 		buffer_free(username);
7857c7f8c46SGlenn Strauss 		return mod_auth_send_400_bad_request(r);
78681b2d1f0SGlenn Strauss 	}
78781b2d1f0SGlenn Strauss 
788af3df29aSGlenn Strauss 	uint32_t pwlen = buffer_clen(username);
789af3df29aSGlenn Strauss 	buffer_truncate(username, pw - username->ptr);
79081b2d1f0SGlenn Strauss 	pw++;
791e11514b0SGlenn Strauss 	pwlen -= (pw - username->ptr);
79281b2d1f0SGlenn Strauss 
793e11514b0SGlenn Strauss 	plugin_data * const p = p_d;
794e11514b0SGlenn Strauss 	splay_tree ** sptree = p->conf.auth_cache
795e11514b0SGlenn Strauss 	  ? &p->conf.auth_cache->sptree
796e11514b0SGlenn Strauss 	  : NULL;
797e11514b0SGlenn Strauss 	http_auth_cache_entry *ae = NULL;
798fd0cc468SGlenn Strauss 	handler_t rc = HANDLER_ERROR;
799e11514b0SGlenn Strauss 	int ndx = -1;
800e11514b0SGlenn Strauss 	if (sptree) {
801af3df29aSGlenn Strauss 		ndx = http_auth_cache_hash(require, BUF_PTR_LEN(username));
802e11514b0SGlenn Strauss 		ae = http_auth_cache_query(sptree, ndx);
803e11514b0SGlenn Strauss 		if (ae && ae->require == require
804e11514b0SGlenn Strauss 		    && buffer_is_equal_string(username, ae->username, ae->ulen))
80562ccda85SGlenn Strauss 			rc = ck_memeq_const_time(ae->pwdigest, ae->dlen, pw, pwlen)
806e11514b0SGlenn Strauss 			  ? HANDLER_GO_ON
807e11514b0SGlenn Strauss 			  : HANDLER_ERROR;
808e11514b0SGlenn Strauss 		else /*(not found or hash collision)*/
809e11514b0SGlenn Strauss 			ae = NULL;
810e11514b0SGlenn Strauss 	}
811e11514b0SGlenn Strauss 
812fd0cc468SGlenn Strauss 	if (NULL == ae)
8137c7f8c46SGlenn Strauss 		rc = backend->basic(r, backend->p_d, require, username, pw);
814e11514b0SGlenn Strauss 
8157ba06c71SGlenn Strauss 	switch (rc) {
8164b3a91e6SGlenn Strauss 	case HANDLER_GO_ON:
817af3df29aSGlenn Strauss 		http_auth_setenv(r, BUF_PTR_LEN(username), CONST_STR_LEN("Basic"));
818e11514b0SGlenn Strauss 		if (sptree && NULL == ae) { /*(cache (new) successful result)*/
819af3df29aSGlenn Strauss 			ae = http_auth_cache_entry_init(require, 0, BUF_PTR_LEN(username),
820e11514b0SGlenn Strauss 			                                pw, pwlen);
821e11514b0SGlenn Strauss 			http_auth_cache_insert(sptree, ndx, ae, http_auth_cache_entry_free);
822e11514b0SGlenn Strauss 		}
8234b3a91e6SGlenn Strauss 		break;
8244b3a91e6SGlenn Strauss 	case HANDLER_WAIT_FOR_EVENT:
8254b3a91e6SGlenn Strauss 	case HANDLER_FINISHED:
8267ba06c71SGlenn Strauss 		break;
8274b3a91e6SGlenn Strauss 	case HANDLER_ERROR:
8284b3a91e6SGlenn Strauss 	default:
8297c7f8c46SGlenn Strauss 		log_error(r->conf.errh, __FILE__, __LINE__,
830010c2894SGlenn Strauss 		  "password doesn't match for %s username: %s IP: %s",
8317c7f8c46SGlenn Strauss 		  r->uri.path.ptr, username->ptr, r->con->dst_addr_buf->ptr);
8324a600dabSGlenn Strauss 		r->keep_alive = -1; /*(disable keep-alive if bad password)*/
833fd0cc468SGlenn Strauss 		rc = mod_auth_send_401_unauthorized_basic(r, require->realm);
8347ba06c71SGlenn Strauss 		break;
83581b2d1f0SGlenn Strauss 	}
83681b2d1f0SGlenn Strauss 
83708c03cd4SGlenn Strauss 	ck_memzero(pw, pwlen);
8384b3a91e6SGlenn Strauss 	buffer_free(username);
839fd0cc468SGlenn Strauss 	return rc;
84081b2d1f0SGlenn Strauss }
84181b2d1f0SGlenn Strauss 
84281b2d1f0SGlenn Strauss 
843*20c56cecSGlenn Strauss 
844*20c56cecSGlenn Strauss enum http_auth_digest_params_e {
845*20c56cecSGlenn Strauss   e_username = 0
846*20c56cecSGlenn Strauss  ,e_realm
847*20c56cecSGlenn Strauss  ,e_nonce
848*20c56cecSGlenn Strauss  ,e_uri
849*20c56cecSGlenn Strauss  ,e_algorithm
850*20c56cecSGlenn Strauss  ,e_qop
851*20c56cecSGlenn Strauss  ,e_cnonce
852*20c56cecSGlenn Strauss  ,e_nc
853*20c56cecSGlenn Strauss  ,e_response
854*20c56cecSGlenn Strauss  ,http_auth_digest_params_sz /*(last item)*/
855*20c56cecSGlenn Strauss };
856*20c56cecSGlenn Strauss 
857*20c56cecSGlenn Strauss typedef struct http_auth_digest_params_t {
858*20c56cecSGlenn Strauss     const char *ptr[http_auth_digest_params_sz];
859*20c56cecSGlenn Strauss     uint16_t len[http_auth_digest_params_sz];
860*20c56cecSGlenn Strauss     time_t send_nextnonce_ts;
861*20c56cecSGlenn Strauss     unsigned char rdigest[MD_DIGEST_LENGTH_MAX]; /*(last member)*/
862*20c56cecSGlenn Strauss } http_auth_digest_params_t;
863*20c56cecSGlenn Strauss 
864*20c56cecSGlenn Strauss 
865*20c56cecSGlenn Strauss static void
866*20c56cecSGlenn Strauss mod_auth_digest_mutate (http_auth_info_t * const ai, const http_auth_digest_params_t * const dp, const char * const method)
867*20c56cecSGlenn Strauss {
868*20c56cecSGlenn Strauss     force_assert(method);
869c987bec1SGlenn Strauss     li_md_iov_fn digest_iov = MD5_iov;
870c987bec1SGlenn Strauss     /* (ai->dalgo & HTTP_AUTH_DIGEST_MD5) default */
871b28a3714SGlenn Strauss   #ifdef USE_LIB_CRYPTO
872c987bec1SGlenn Strauss     if (ai->dalgo & HTTP_AUTH_DIGEST_SHA256)
873c987bec1SGlenn Strauss         digest_iov = SHA256_iov;
8741fc8a3e1SGlenn Strauss    #ifdef USE_LIB_CRYPTO_SHA512_256
875b9e2be50SGlenn Strauss     else if (ai->dalgo & HTTP_AUTH_DIGEST_SHA512_256)
876c987bec1SGlenn Strauss         digest_iov = SHA512_256_iov;
877b9e2be50SGlenn Strauss    #endif
878b9e2be50SGlenn Strauss   #endif
879c987bec1SGlenn Strauss     size_t n;
880c987bec1SGlenn Strauss     struct const_iovec iov[11];
881c987bec1SGlenn Strauss     char a1[MD_DIGEST_LENGTH_MAX*2+8]; /*(+1 for li_tohex(); +8 for align)*/
882c987bec1SGlenn Strauss     char a2[MD_DIGEST_LENGTH_MAX*2+8]; /*(+1 for li_tohex(); +8 for align)*/
883c987bec1SGlenn Strauss 
884c987bec1SGlenn Strauss     li_tohex(a1, sizeof(a1), (const char *)ai->digest, ai->dlen);
885c987bec1SGlenn Strauss 
886c987bec1SGlenn Strauss     if (ai->dalgo & HTTP_AUTH_DIGEST_SESS) {
887c987bec1SGlenn Strauss         /* http://www.rfc-editor.org/errata_search.php?rfc=2617
888c987bec1SGlenn Strauss          * Errata ID: 1649 */
889c987bec1SGlenn Strauss         iov[0].iov_base = a1;
890c987bec1SGlenn Strauss         iov[0].iov_len  = ai->dlen*2;
891c987bec1SGlenn Strauss         iov[1].iov_base = ":";
892c987bec1SGlenn Strauss         iov[1].iov_len  = 1;
893*20c56cecSGlenn Strauss         iov[2].iov_base = dp->ptr[e_nonce];
894*20c56cecSGlenn Strauss         iov[2].iov_len  = dp->len[e_nonce];
895c987bec1SGlenn Strauss         iov[3].iov_base = ":";
896c987bec1SGlenn Strauss         iov[3].iov_len  = 1;
897*20c56cecSGlenn Strauss         iov[4].iov_base = dp->ptr[e_cnonce];
898*20c56cecSGlenn Strauss         iov[4].iov_len  = dp->len[e_cnonce];
899c987bec1SGlenn Strauss         digest_iov(ai->digest, iov, 5);
900c987bec1SGlenn Strauss         li_tohex(a1, sizeof(a1), (const char *)ai->digest, ai->dlen);
901c987bec1SGlenn Strauss     }
902c987bec1SGlenn Strauss 
903c987bec1SGlenn Strauss     /* calculate H(A2) */
904*20c56cecSGlenn Strauss     iov[0].iov_base = method;
905*20c56cecSGlenn Strauss     iov[0].iov_len  = strlen(method);
906c987bec1SGlenn Strauss     iov[1].iov_base = ":";
907c987bec1SGlenn Strauss     iov[1].iov_len  = 1;
908*20c56cecSGlenn Strauss     iov[2].iov_base = dp->ptr[e_uri];
909*20c56cecSGlenn Strauss     iov[2].iov_len  = dp->len[e_uri];
910c987bec1SGlenn Strauss     n = 3;
911c987bec1SGlenn Strauss   #if 0
912c987bec1SGlenn Strauss     /* qop=auth-int not supported, already checked in caller */
913*20c56cecSGlenn Strauss     if (dp->ptr[e_qop] && buffer_eq_icase_ss(dp->ptr[e_qop], dp->len[e_qop],
914*20c56cecSGlenn Strauss                                              CONST_STR_LEN("auth-int"))) {
915c987bec1SGlenn Strauss         iov[3].iov_base = ":";
916c987bec1SGlenn Strauss         iov[3].iov_len  = 1;
917c987bec1SGlenn Strauss         iov[4].iov_base = [body checksum];
918c987bec1SGlenn Strauss         iov[4].iov_len  = ai->dlen*2;
919c987bec1SGlenn Strauss         n = 5;
920c987bec1SGlenn Strauss     }
921c987bec1SGlenn Strauss   #endif
922c987bec1SGlenn Strauss     digest_iov(ai->digest, iov, n);
923c987bec1SGlenn Strauss     li_tohex(a2, sizeof(a2), (const char *)ai->digest, ai->dlen);
924c987bec1SGlenn Strauss 
925c987bec1SGlenn Strauss     /* calculate response */
926c987bec1SGlenn Strauss     iov[0].iov_base = a1;
927c987bec1SGlenn Strauss     iov[0].iov_len  = ai->dlen*2;
928c987bec1SGlenn Strauss     iov[1].iov_base = ":";
929c987bec1SGlenn Strauss     iov[1].iov_len  = 1;
930*20c56cecSGlenn Strauss     iov[2].iov_base = dp->ptr[e_nonce];
931*20c56cecSGlenn Strauss     iov[2].iov_len  = dp->len[e_nonce];
932c987bec1SGlenn Strauss     iov[3].iov_base = ":";
933c987bec1SGlenn Strauss     iov[3].iov_len  = 1;
934c987bec1SGlenn Strauss     n = 4;
935*20c56cecSGlenn Strauss     if (dp->len[e_qop]) {
936*20c56cecSGlenn Strauss         iov[4].iov_base = dp->ptr[e_nc];
937*20c56cecSGlenn Strauss         iov[4].iov_len  = dp->len[e_nc];
938c987bec1SGlenn Strauss         iov[5].iov_base = ":";
939c987bec1SGlenn Strauss         iov[5].iov_len  = 1;
940*20c56cecSGlenn Strauss         iov[6].iov_base = dp->ptr[e_cnonce];
941*20c56cecSGlenn Strauss         iov[6].iov_len  = dp->len[e_cnonce];
942c987bec1SGlenn Strauss         iov[7].iov_base = ":";
943c987bec1SGlenn Strauss         iov[7].iov_len  = 1;
944*20c56cecSGlenn Strauss         iov[8].iov_base = dp->ptr[e_qop];
945*20c56cecSGlenn Strauss         iov[8].iov_len  = dp->len[e_qop];
946c987bec1SGlenn Strauss         iov[9].iov_base = ":";
947c987bec1SGlenn Strauss         iov[9].iov_len  = 1;
948c987bec1SGlenn Strauss         n = 10;
949c987bec1SGlenn Strauss     }
950c987bec1SGlenn Strauss     iov[n].iov_base = a2;
951c987bec1SGlenn Strauss     iov[n].iov_len  = ai->dlen*2;
952c987bec1SGlenn Strauss     digest_iov(ai->digest, iov, n+1);
953b9e2be50SGlenn Strauss }
954b9e2be50SGlenn Strauss 
955*20c56cecSGlenn Strauss 
956*20c56cecSGlenn Strauss static void
957*20c56cecSGlenn Strauss mod_auth_append_nonce (buffer *b, time_t cur_ts, const struct http_auth_require_t *require, int dalgo, int *rndptr)
958*20c56cecSGlenn Strauss {
959e1188e77SGlenn Strauss     buffer_append_uint_hex(b, (uintmax_t)cur_ts);
960e1188e77SGlenn Strauss     buffer_append_string_len(b, CONST_STR_LEN(":"));
961e1188e77SGlenn Strauss     const buffer * const nonce_secret = require->nonce_secret;
962e1188e77SGlenn Strauss     int rnd;
963e1188e77SGlenn Strauss     if (NULL == nonce_secret)
964e1188e77SGlenn Strauss         rnd = rndptr ? *rndptr : li_rand_pseudo();
965e1188e77SGlenn Strauss     else { /*(do not directly expose random number generator single value)*/
966e1188e77SGlenn Strauss         rndptr
967e1188e77SGlenn Strauss           ? (void)(rnd = *rndptr)
968e1188e77SGlenn Strauss           : li_rand_pseudo_bytes((unsigned char *)&rnd, sizeof(rnd));
969e1188e77SGlenn Strauss         buffer_append_uint_hex(b, (uintmax_t)rnd);
970e1188e77SGlenn Strauss         buffer_append_string_len(b, CONST_STR_LEN(":"));
971e1188e77SGlenn Strauss     }
972c987bec1SGlenn Strauss 
973c987bec1SGlenn Strauss     size_t n;
974c987bec1SGlenn Strauss     struct const_iovec iov[3];
975c987bec1SGlenn Strauss 
976c987bec1SGlenn Strauss   #if 0
977c987bec1SGlenn Strauss     char a1[LI_ITOSTRING_LENGTH];
978c987bec1SGlenn Strauss     char a2[LI_ITOSTRING_LENGTH];
979c987bec1SGlenn Strauss     iov[0].iov_base = a1;
980c987bec1SGlenn Strauss     iov[0].iov_len  = li_itostrn(a1, sizeof(a1), cur_ts);
981c987bec1SGlenn Strauss     iov[1].iov_base = a2;
982c987bec1SGlenn Strauss     iov[1].iov_len  = li_itostrn(a2, sizeof(a2), rnd);
983c987bec1SGlenn Strauss   #else
984c987bec1SGlenn Strauss     iov[0].iov_base = &cur_ts;
985c987bec1SGlenn Strauss     iov[0].iov_len  = sizeof(cur_ts);
986c987bec1SGlenn Strauss     iov[1].iov_base = &rnd;
987c987bec1SGlenn Strauss     iov[1].iov_len  = sizeof(rnd);
988c987bec1SGlenn Strauss   #endif
989c987bec1SGlenn Strauss     n = 2;
990c987bec1SGlenn Strauss     if (nonce_secret) {
991c987bec1SGlenn Strauss         iov[2].iov_base = nonce_secret->ptr;
992c987bec1SGlenn Strauss         iov[2].iov_len  = buffer_clen(nonce_secret);
993c987bec1SGlenn Strauss         n = 3;
994c987bec1SGlenn Strauss     }
995c987bec1SGlenn Strauss 
996c987bec1SGlenn Strauss     unsigned char h[MD_DIGEST_LENGTH_MAX];
997e1188e77SGlenn Strauss     switch (dalgo) {
998b28a3714SGlenn Strauss      #ifdef USE_LIB_CRYPTO
9991fc8a3e1SGlenn Strauss       #ifdef USE_LIB_CRYPTO_SHA512_256
1000e1188e77SGlenn Strauss       case HTTP_AUTH_DIGEST_SHA512_256:
1001c987bec1SGlenn Strauss         SHA512_256_iov(h, iov, n);
1002c987bec1SGlenn Strauss         n = HTTP_AUTH_DIGEST_SHA512_256_BINLEN;
1003e1188e77SGlenn Strauss         break;
1004e1188e77SGlenn Strauss       #endif
1005e1188e77SGlenn Strauss       case HTTP_AUTH_DIGEST_SHA256:
1006c987bec1SGlenn Strauss         SHA256_iov(h, iov, n);
1007c987bec1SGlenn Strauss         n = HTTP_AUTH_DIGEST_SHA256_BINLEN;
1008e1188e77SGlenn Strauss         break;
1009e1188e77SGlenn Strauss      #endif
1010e1188e77SGlenn Strauss       /*case HTTP_AUTH_DIGEST_MD5:*/
1011e1188e77SGlenn Strauss       default:
1012c987bec1SGlenn Strauss         MD5_iov(h, iov, n);
1013c987bec1SGlenn Strauss         n = HTTP_AUTH_DIGEST_MD5_BINLEN;
1014e1188e77SGlenn Strauss         break;
1015e1188e77SGlenn Strauss     }
1016c987bec1SGlenn Strauss     li_tohex(buffer_extend(b, n*2), n*2+1, (const char *)h, n);
1017e1188e77SGlenn Strauss }
1018e1188e77SGlenn Strauss 
1019*20c56cecSGlenn Strauss 
1020*20c56cecSGlenn Strauss static void
1021*20c56cecSGlenn Strauss mod_auth_digest_www_authenticate (buffer *b, time_t cur_ts, const struct http_auth_require_t *require, int nonce_stale)
1022*20c56cecSGlenn Strauss {
1023b9e2be50SGlenn Strauss     int algos = nonce_stale ? nonce_stale : require->algorithm;
1024b9e2be50SGlenn Strauss     int n = 0;
1025e1188e77SGlenn Strauss     int algoid[3];
1026b9e2be50SGlenn Strauss     unsigned int algolen[3];
1027b9e2be50SGlenn Strauss     const char *algoname[3];
1028b28a3714SGlenn Strauss   #ifdef USE_LIB_CRYPTO
10291fc8a3e1SGlenn Strauss    #ifdef USE_LIB_CRYPTO_SHA512_256
1030b9e2be50SGlenn Strauss     if (algos & HTTP_AUTH_DIGEST_SHA512_256) {
1031e1188e77SGlenn Strauss         algoid[n] = HTTP_AUTH_DIGEST_SHA512_256;
1032b9e2be50SGlenn Strauss         algoname[n] = "SHA-512-256";
1033b9e2be50SGlenn Strauss         algolen[n] = sizeof("SHA-512-256")-1;
1034b9e2be50SGlenn Strauss         ++n;
1035b9e2be50SGlenn Strauss     }
1036b9e2be50SGlenn Strauss    #endif
1037b9e2be50SGlenn Strauss     if (algos & HTTP_AUTH_DIGEST_SHA256) {
1038e1188e77SGlenn Strauss         algoid[n] = HTTP_AUTH_DIGEST_SHA256;
1039b9e2be50SGlenn Strauss         algoname[n] = "SHA-256";
1040b9e2be50SGlenn Strauss         algolen[n] = sizeof("SHA-256")-1;
1041b9e2be50SGlenn Strauss         ++n;
1042b9e2be50SGlenn Strauss     }
1043b9e2be50SGlenn Strauss   #endif
1044b9e2be50SGlenn Strauss     if (algos & HTTP_AUTH_DIGEST_MD5) {
1045e1188e77SGlenn Strauss         algoid[n] = HTTP_AUTH_DIGEST_MD5;
1046b9e2be50SGlenn Strauss         algoname[n] = "MD5";
1047b9e2be50SGlenn Strauss         algolen[n] = sizeof("MD5")-1;
1048b9e2be50SGlenn Strauss         ++n;
1049b9e2be50SGlenn Strauss     }
1050b9e2be50SGlenn Strauss 
1051b9e2be50SGlenn Strauss     buffer_clear(b);
1052b9e2be50SGlenn Strauss     for (int i = 0; i < n; ++i) {
1053dc01487eSGlenn Strauss         struct const_iovec iov[] = {
1054dc01487eSGlenn Strauss           { CONST_STR_LEN("\r\nWWW-Authenticate: ") }
1055dc01487eSGlenn Strauss          ,{ CONST_STR_LEN("Digest realm=\"") }
1056af3df29aSGlenn Strauss          ,{ BUF_PTR_LEN(require->realm) }
1057dc01487eSGlenn Strauss          ,{ CONST_STR_LEN("\", charset=\"UTF-8\", algorithm=") }
1058dc01487eSGlenn Strauss          ,{ algoname[i], algolen[i] }
1059dc01487eSGlenn Strauss          ,{ CONST_STR_LEN(", nonce=\"") }
1060dc01487eSGlenn Strauss         };
1061dc01487eSGlenn Strauss         buffer_append_iovec(b, iov+(0==i), sizeof(iov)/sizeof(*iov)-(0==i));
1062e1188e77SGlenn Strauss         mod_auth_append_nonce(b, cur_ts, require, algoid[i], NULL);
1063b9e2be50SGlenn Strauss         buffer_append_string_len(b, CONST_STR_LEN("\", qop=\"auth\""));
1064b9e2be50SGlenn Strauss         if (nonce_stale) {
1065b9e2be50SGlenn Strauss             buffer_append_string_len(b, CONST_STR_LEN(", stale=true"));
1066b9e2be50SGlenn Strauss         }
1067b9e2be50SGlenn Strauss     }
106881b2d1f0SGlenn Strauss }
106981b2d1f0SGlenn Strauss 
1070c841ce3bSGlenn Strauss 
1071*20c56cecSGlenn Strauss __attribute_noinline__
1072*20c56cecSGlenn Strauss static handler_t
1073*20c56cecSGlenn Strauss mod_auth_send_401_unauthorized_digest(request_st * const r, const struct http_auth_require_t * const require, int nonce_stale)
1074*20c56cecSGlenn Strauss {
1075*20c56cecSGlenn Strauss     r->http_status = 401;
1076*20c56cecSGlenn Strauss     r->handler_module = NULL;
1077*20c56cecSGlenn Strauss     mod_auth_digest_www_authenticate(
1078*20c56cecSGlenn Strauss       http_header_response_set_ptr(r, HTTP_HEADER_WWW_AUTHENTICATE,
1079*20c56cecSGlenn Strauss                                    CONST_STR_LEN("WWW-Authenticate")),
1080*20c56cecSGlenn Strauss       log_epoch_secs, require, nonce_stale);
1081*20c56cecSGlenn Strauss     return HANDLER_FINISHED;
1082*20c56cecSGlenn Strauss }
1083*20c56cecSGlenn Strauss 
1084*20c56cecSGlenn Strauss 
1085*20c56cecSGlenn Strauss static void
1086*20c56cecSGlenn Strauss mod_auth_digest_authentication_info (buffer *b, time_t cur_ts, const struct http_auth_require_t *require, int dalgo)
1087*20c56cecSGlenn Strauss {
10886ad325c6SGlenn Strauss     buffer_clear(b);
10896ad325c6SGlenn Strauss     buffer_append_string_len(b, CONST_STR_LEN("nextnonce=\""));
1090e1188e77SGlenn Strauss     mod_auth_append_nonce(b, cur_ts, require, dalgo, NULL);
10916ad325c6SGlenn Strauss     buffer_append_string_len(b, CONST_STR_LEN("\""));
10926ad325c6SGlenn Strauss }
10936ad325c6SGlenn Strauss 
1094*20c56cecSGlenn Strauss 
1095c841ce3bSGlenn Strauss static handler_t
1096c841ce3bSGlenn Strauss 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)
1097c841ce3bSGlenn Strauss {
1098c841ce3bSGlenn Strauss     plugin_data * const p = p_d;
1099c841ce3bSGlenn Strauss     splay_tree **sptree = p->conf.auth_cache
1100c841ce3bSGlenn Strauss       ? &p->conf.auth_cache->sptree
1101c841ce3bSGlenn Strauss       : NULL;
1102c841ce3bSGlenn Strauss     http_auth_cache_entry *ae = NULL;
1103c841ce3bSGlenn Strauss     handler_t rc = HANDLER_GO_ON;
1104c841ce3bSGlenn Strauss     int ndx = -1;
1105c841ce3bSGlenn Strauss     if (sptree) {
1106c841ce3bSGlenn Strauss         ndx = http_auth_cache_hash(require, ai->username, ai->ulen);
1107c841ce3bSGlenn Strauss         ae = http_auth_cache_query(sptree, ndx);
1108c841ce3bSGlenn Strauss         if (ae && ae->require == require
1109c841ce3bSGlenn Strauss             && ae->dalgo == ai->dalgo
1110c841ce3bSGlenn Strauss             && ae->dlen == ai->dlen
1111c841ce3bSGlenn Strauss             && ae->ulen == ai->ulen
1112c841ce3bSGlenn Strauss             && 0 == memcmp(ae->username, ai->username, ai->ulen)) {
1113c841ce3bSGlenn Strauss             memcpy(ai->digest, ae->pwdigest, ai->dlen);
1114c841ce3bSGlenn Strauss         }
1115c841ce3bSGlenn Strauss         else /*(not found or hash collision)*/
1116c841ce3bSGlenn Strauss             ae = NULL;
1117c841ce3bSGlenn Strauss     }
1118c841ce3bSGlenn Strauss 
1119c841ce3bSGlenn Strauss     if (NULL == ae)
1120c841ce3bSGlenn Strauss         rc = backend->digest(r, backend->p_d, ai);
1121c841ce3bSGlenn Strauss 
1122c841ce3bSGlenn Strauss     switch (rc) {
1123c841ce3bSGlenn Strauss     case HANDLER_GO_ON:
1124c841ce3bSGlenn Strauss         break;
1125c841ce3bSGlenn Strauss     case HANDLER_WAIT_FOR_EVENT:
1126c841ce3bSGlenn Strauss         return HANDLER_WAIT_FOR_EVENT;
1127c841ce3bSGlenn Strauss     case HANDLER_FINISHED:
1128c841ce3bSGlenn Strauss         return HANDLER_FINISHED;
1129c841ce3bSGlenn Strauss     case HANDLER_ERROR:
1130c841ce3bSGlenn Strauss     default:
1131c841ce3bSGlenn Strauss         r->keep_alive = -1; /*(disable keep-alive if unknown user)*/
1132c841ce3bSGlenn Strauss         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1133c841ce3bSGlenn Strauss     }
1134c841ce3bSGlenn Strauss 
1135c841ce3bSGlenn Strauss     if (sptree && NULL == ae) { /*(cache digest from backend)*/
1136c841ce3bSGlenn Strauss         ae = http_auth_cache_entry_init(require, ai->dalgo, ai->username,
1137c841ce3bSGlenn Strauss                                         ai->ulen, (char *)ai->digest, ai->dlen);
1138c841ce3bSGlenn Strauss         http_auth_cache_insert(sptree, ndx, ae, http_auth_cache_entry_free);
1139c841ce3bSGlenn Strauss     }
1140c841ce3bSGlenn Strauss 
1141c841ce3bSGlenn Strauss     return rc;
1142c841ce3bSGlenn Strauss }
1143c841ce3bSGlenn Strauss 
114481b2d1f0SGlenn Strauss 
1145*20c56cecSGlenn Strauss __attribute_cold__
1146*20c56cecSGlenn Strauss static handler_t
1147*20c56cecSGlenn Strauss mod_auth_digest_misconfigured (request_st * const r, const struct http_auth_backend_t * const backend)
1148*20c56cecSGlenn Strauss {
1149cf0098eaSGlenn Strauss     if (NULL == backend)
11507c7f8c46SGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
11517c7f8c46SGlenn Strauss           "auth.backend not configured for %s", r->uri.path.ptr);
1152cf0098eaSGlenn Strauss     else
1153cf0098eaSGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
1154cf0098eaSGlenn Strauss           "auth.require \"method\" => \"digest\" invalid "
1155*20c56cecSGlenn Strauss           "(try \"basic\"?) for %s", r->uri.path.ptr);
1156*20c56cecSGlenn Strauss 
11577c7f8c46SGlenn Strauss     r->http_status = 500;
11587c7f8c46SGlenn Strauss     r->handler_module = NULL;
11597ba06c71SGlenn Strauss     return HANDLER_FINISHED;
11607ba06c71SGlenn Strauss }
11617ba06c71SGlenn Strauss 
11627ba06c71SGlenn Strauss 
1163*20c56cecSGlenn Strauss static void
1164*20c56cecSGlenn Strauss mod_auth_digest_parse_authorization (http_auth_digest_params_t * const dp, const buffer * const vb)
1165*20c56cecSGlenn Strauss {
1166*20c56cecSGlenn Strauss     struct digest_kv {
1167*20c56cecSGlenn Strauss         const char *key;
1168*20c56cecSGlenn Strauss         uint32_t klen;
1169*20c56cecSGlenn Strauss         enum http_auth_digest_params_e id;
1170*20c56cecSGlenn Strauss     };
1171*20c56cecSGlenn Strauss 
1172*20c56cecSGlenn Strauss     static const struct digest_kv dkv[] = {
1173*20c56cecSGlenn Strauss         { CONST_STR_LEN("username="),  e_username },
1174*20c56cecSGlenn Strauss         { CONST_STR_LEN("realm="),     e_realm },
1175*20c56cecSGlenn Strauss         { CONST_STR_LEN("nonce="),     e_nonce },
1176*20c56cecSGlenn Strauss         { CONST_STR_LEN("uri="),       e_uri },
1177*20c56cecSGlenn Strauss         { CONST_STR_LEN("algorithm="), e_algorithm },
1178*20c56cecSGlenn Strauss         { CONST_STR_LEN("qop="),       e_qop },
1179*20c56cecSGlenn Strauss         { CONST_STR_LEN("cnonce="),    e_cnonce },
1180*20c56cecSGlenn Strauss         { CONST_STR_LEN("nc="),        e_nc },
1181*20c56cecSGlenn Strauss         { CONST_STR_LEN("response="),  e_response },
1182*20c56cecSGlenn Strauss 
1183*20c56cecSGlenn Strauss         { NULL, 0, http_auth_digest_params_sz }
1184*20c56cecSGlenn Strauss     };
118581b2d1f0SGlenn Strauss 
118681b2d1f0SGlenn Strauss     /* parse credentials from client */
1187*20c56cecSGlenn Strauss     /* note: parsing does not recognize and handle BWS (bad whitespace) */
1188*20c56cecSGlenn Strauss     /* XXX: might find end of token and strncmp() only when len matches */
1189*20c56cecSGlenn Strauss     /* (caller already checked that vb->ptr begins with "Digest ") */
1190*20c56cecSGlenn Strauss     /* coverity[overflow_sink : FALSE] */
1191*20c56cecSGlenn Strauss     for (const char *c = vb->ptr+sizeof("Digest ")-1, *e; *c; c++) {
119281b2d1f0SGlenn Strauss         /* skip whitespaces */
119381b2d1f0SGlenn Strauss         while (*c == ' ' || *c == '\t') c++;
119481b2d1f0SGlenn Strauss         if (!*c) break;
119581b2d1f0SGlenn Strauss 
1196*20c56cecSGlenn Strauss         for (int i = 0; dkv[i].key; ++i) {
1197*20c56cecSGlenn Strauss             if (0 != strncmp(c, dkv[i].key, dkv[i].klen))
1198*20c56cecSGlenn Strauss                 continue;
1199*20c56cecSGlenn Strauss 
1200*20c56cecSGlenn Strauss             if ((c[dkv[i].klen] == '"') &&
1201*20c56cecSGlenn Strauss                 (NULL != (e = strchr(c + dkv[i].klen + 1, '"')))) {
120281b2d1f0SGlenn Strauss                 /* value with "..." */
1203*20c56cecSGlenn Strauss                 c += dkv[i].klen + 1;
1204*20c56cecSGlenn Strauss                 dp->ptr[dkv[i].id] = c;
1205*20c56cecSGlenn Strauss                 dp->len[dkv[i].id] = (uint16_t)(e - c);
120681b2d1f0SGlenn Strauss                 c = e;
1207*20c56cecSGlenn Strauss             }
1208*20c56cecSGlenn Strauss             else if (NULL != (e = strchr(c + dkv[i].klen, ','))) {
120981b2d1f0SGlenn Strauss                 /* value without "...", terminated by ',' */
1210*20c56cecSGlenn Strauss                 c += dkv[i].klen;
1211*20c56cecSGlenn Strauss                 dp->ptr[dkv[i].id] = c;
1212*20c56cecSGlenn Strauss                 dp->len[dkv[i].id] = (uint16_t)(e - c);
121381b2d1f0SGlenn Strauss                 c = e;
1214*20c56cecSGlenn Strauss             }
1215*20c56cecSGlenn Strauss             else {
121681b2d1f0SGlenn Strauss                 /* value without "...", terminated by EOL */
1217*20c56cecSGlenn Strauss                 c += dkv[i].klen;
1218*20c56cecSGlenn Strauss                 dp->ptr[dkv[i].id] = c;
1219*20c56cecSGlenn Strauss                 c += (dp->len[dkv[i].id] = (uint16_t)strlen(c)) - 1;
122081b2d1f0SGlenn Strauss             }
122181b2d1f0SGlenn Strauss             break;
122281b2d1f0SGlenn Strauss         }
122381b2d1f0SGlenn Strauss     }
122481b2d1f0SGlenn Strauss }
122581b2d1f0SGlenn Strauss 
122681b2d1f0SGlenn Strauss 
1227*20c56cecSGlenn Strauss static handler_t
1228*20c56cecSGlenn Strauss 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)
1229*20c56cecSGlenn Strauss {
1230*20c56cecSGlenn Strauss     /* check for required parameters */
1231*20c56cecSGlenn Strauss     if ((!dp->ptr[e_qop] || (dp->ptr[e_nc] && dp->ptr[e_cnonce]))
1232*20c56cecSGlenn Strauss         && dp->ptr[e_username]
1233*20c56cecSGlenn Strauss         && dp->ptr[e_realm]
1234*20c56cecSGlenn Strauss         && dp->ptr[e_nonce]
1235*20c56cecSGlenn Strauss         && dp->ptr[e_uri]
1236*20c56cecSGlenn Strauss         && dp->ptr[e_response]) {
1237*20c56cecSGlenn Strauss         ai->username = dp->ptr[e_username];
1238*20c56cecSGlenn Strauss         ai->ulen     = dp->len[e_username];
1239*20c56cecSGlenn Strauss         ai->realm    = dp->ptr[e_realm];
1240*20c56cecSGlenn Strauss         ai->rlen     = dp->len[e_realm];
1241*20c56cecSGlenn Strauss     }
1242*20c56cecSGlenn Strauss     else {
12437c7f8c46SGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
124481b2d1f0SGlenn Strauss           "digest: missing field");
12457c7f8c46SGlenn Strauss         return mod_auth_send_400_bad_request(r);
124681b2d1f0SGlenn Strauss     }
124781b2d1f0SGlenn Strauss 
1248*20c56cecSGlenn Strauss     if (!buffer_eq_slen(require->realm, ai->realm, ai->rlen)) {
12497c7f8c46SGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
12505a6e4df8SGlenn Strauss           "digest: realm mismatch");
12517c7f8c46SGlenn Strauss         return mod_auth_send_401_unauthorized_digest(r, require, 0);
12525a6e4df8SGlenn Strauss     }
12535a6e4df8SGlenn Strauss 
1254*20c56cecSGlenn Strauss     if (!mod_auth_algorithm_parse(ai,dp->ptr[e_algorithm],dp->len[e_algorithm])
1255*20c56cecSGlenn Strauss         || !(require->algorithm & ai->dalgo & ~HTTP_AUTH_DIGEST_SESS)) {
12567c7f8c46SGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
1257*20c56cecSGlenn Strauss           "digest: (%.*s): invalid",
1258*20c56cecSGlenn Strauss           (int)dp->len[e_algorithm], dp->ptr[e_algorithm]);
125912ac70d0SGlenn Strauss         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1260b9e2be50SGlenn Strauss     }
1261b9e2be50SGlenn Strauss 
1262*20c56cecSGlenn Strauss     /* *-sess requires nonce and cnonce */
1263*20c56cecSGlenn Strauss     if ((ai->dalgo & HTTP_AUTH_DIGEST_SESS)
1264*20c56cecSGlenn Strauss         && (!dp->ptr[e_nonce] || !dp->ptr[e_cnonce])) {
12657c7f8c46SGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
1266*20c56cecSGlenn Strauss           "digest: (%.*s): missing field",
1267*20c56cecSGlenn Strauss           (int)dp->len[e_algorithm], dp->ptr[e_algorithm]);
12687c7f8c46SGlenn Strauss         return mod_auth_send_400_bad_request(r);
126981b2d1f0SGlenn Strauss     }
127081b2d1f0SGlenn Strauss 
1271*20c56cecSGlenn Strauss     if (0 != li_hex2bin(dp->rdigest, sizeof(dp->rdigest),
1272*20c56cecSGlenn Strauss                         dp->ptr[e_response], dp->len[e_response])
1273*20c56cecSGlenn Strauss         || dp->len[e_response] != (ai->dlen << 1)) {
12747c7f8c46SGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
1275*20c56cecSGlenn Strauss           "digest: (%s): invalid format", dp->ptr[e_response]);
12767c7f8c46SGlenn Strauss         return mod_auth_send_400_bad_request(r);
1277b9e2be50SGlenn Strauss     }
1278b9e2be50SGlenn Strauss 
1279*20c56cecSGlenn Strauss     if (dp->ptr[e_qop]&& buffer_eq_icase_ss(dp->ptr[e_qop], dp->len[e_qop],
1280*20c56cecSGlenn Strauss                                             CONST_STR_LEN("auth-int"))) {
12817c7f8c46SGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
128281b2d1f0SGlenn Strauss           "digest: qop=auth-int not supported");
12837c7f8c46SGlenn Strauss         return mod_auth_send_400_bad_request(r);
128481b2d1f0SGlenn Strauss     }
128581b2d1f0SGlenn Strauss 
128681b2d1f0SGlenn Strauss     /* detect if attacker is attempting to reuse valid digest for one uri
128781b2d1f0SGlenn Strauss      * on a different request uri.  Might also happen if intermediate proxy
128881b2d1f0SGlenn Strauss      * altered client request line.  (Altered request would not result in
128981b2d1f0SGlenn Strauss      * the same digest as that calculated by the client.)
129081b2d1f0SGlenn Strauss      * Internal redirects such as with mod_rewrite will modify request uri.
129181b2d1f0SGlenn Strauss      * Reauthentication is done to detect crossing auth realms, but this
12927c7f8c46SGlenn Strauss      * uri validation step is bypassed.  r->target_orig is
12938131e439SGlenn Strauss      * original request-target sent in client request. */
1294*20c56cecSGlenn Strauss     if (!buffer_eq_slen(&r->target_orig, dp->ptr[e_uri], dp->len[e_uri])) {
12957c7f8c46SGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
1296*20c56cecSGlenn Strauss           "digest: auth failed: uri mismatch (%s != %.*s), IP: %s",
1297*20c56cecSGlenn Strauss           r->target_orig.ptr, (int)dp->len[e_uri], dp->ptr[e_uri],
1298*20c56cecSGlenn Strauss           r->con->dst_addr_buf->ptr);
12997c7f8c46SGlenn Strauss         return mod_auth_send_400_bad_request(r);
130081b2d1f0SGlenn Strauss     }
1301*20c56cecSGlenn Strauss 
1302*20c56cecSGlenn Strauss     return HANDLER_GO_ON;
130381b2d1f0SGlenn Strauss }
130481b2d1f0SGlenn Strauss 
1305*20c56cecSGlenn Strauss 
1306*20c56cecSGlenn Strauss static handler_t
1307*20c56cecSGlenn Strauss 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)
1308*20c56cecSGlenn Strauss {
1309e1188e77SGlenn Strauss     /* check age of nonce.  Note, random data is used in nonce generation
1310e1188e77SGlenn Strauss      * in mod_auth_send_401_unauthorized_digest().  If that were replaced
1311e1188e77SGlenn Strauss      * with nanosecond time, then nonce secret would remain unique enough
1312e1188e77SGlenn Strauss      * for the purposes of Digest auth, and would be reproducible (and
1313e1188e77SGlenn Strauss      * verifiable) if nanoseconds were included with seconds as part of the
1314e1188e77SGlenn Strauss      * nonce "timestamp:secret".  However, doing so would expose a high
1315e1188e77SGlenn Strauss      * precision timestamp of the system to attackers.  timestamp in nonce
1316e1188e77SGlenn Strauss      * could theoretically be modified and still produce same md5sum, but
1317e1188e77SGlenn Strauss      * that is highly unlikely within a 10 min (moving) window of valid
1318e1188e77SGlenn Strauss      * time relative to current time (now).
1319e1188e77SGlenn Strauss      * If it is desired to validate that nonces were generated by server,
1320e1188e77SGlenn Strauss      * then specify auth.require = ( ... => ( "secret" => "..." ) )
1321e1188e77SGlenn Strauss      * When secret is specified, then instead of nanoseconds, the random
1322e1188e77SGlenn Strauss      * data value (included for unique nonces) will be exposed in the nonce
1323e1188e77SGlenn Strauss      * along with the timestamp, and the additional secret will be used to
1324e1188e77SGlenn Strauss      * validate that the server generated the nonce using that secret. */
1325e1188e77SGlenn Strauss     time_t ts = 0;
1326*20c56cecSGlenn Strauss     const unsigned char * const nonce = (unsigned char *)dp->ptr[e_nonce];
1327*20c56cecSGlenn Strauss     int i;
1328*20c56cecSGlenn Strauss     for (i = 0; i < 8 && light_isxdigit(nonce[i]); ++i)
1329*20c56cecSGlenn Strauss         ts =(time_t)((uint32_t)ts << 4) | hex2int(nonce[i]);
1330*20c56cecSGlenn Strauss 
1331e1188e77SGlenn Strauss     const time_t cur_ts = log_epoch_secs;
1332*20c56cecSGlenn Strauss     if (nonce[i] != ':' || ts > cur_ts || cur_ts - ts > 600) { /*(10 mins)*/
1333e1188e77SGlenn Strauss         /* nonce is stale; have client regenerate digest */
1334*20c56cecSGlenn Strauss         return mod_auth_send_401_unauthorized_digest(r, require, ai->dalgo);
1335e1188e77SGlenn Strauss     }
1336e1188e77SGlenn Strauss 
1337*20c56cecSGlenn Strauss     if (cur_ts - ts > 540)  /*(9 mins)*/
1338*20c56cecSGlenn Strauss         dp->send_nextnonce_ts = cur_ts;
1339e1188e77SGlenn Strauss 
1340e1188e77SGlenn Strauss     if (require->nonce_secret) {
1341e1188e77SGlenn Strauss         unsigned int rnd = 0;
1342*20c56cecSGlenn Strauss         for (int j = i+8; i < j && light_isxdigit(nonce[i]); ++i) {
1343*20c56cecSGlenn Strauss             rnd = (rnd << 4) + hex2int(nonce[i]);
1344e1188e77SGlenn Strauss         }
1345e1188e77SGlenn Strauss         if (nonce[i] != ':') {
1346e1188e77SGlenn Strauss             /* nonce is invalid;
1347e1188e77SGlenn Strauss              * expect extra field w/ require->nonce_secret */
1348e1188e77SGlenn Strauss             log_error(r->conf.errh, __FILE__, __LINE__,
1349e1188e77SGlenn Strauss               "digest: nonce invalid");
1350e1188e77SGlenn Strauss             return mod_auth_send_400_bad_request(r);
1351e1188e77SGlenn Strauss         }
1352e1188e77SGlenn Strauss         buffer * const tb = r->tmp_buf;
1353e1188e77SGlenn Strauss         buffer_clear(tb);
1354*20c56cecSGlenn Strauss         mod_auth_append_nonce(tb, cur_ts, require, ai->dalgo, (int *)&rnd);
1355*20c56cecSGlenn Strauss         if (!buffer_eq_slen(tb, dp->ptr[e_nonce], dp->len[e_nonce])) {
1356e1188e77SGlenn Strauss             /* nonce not generated using current require->nonce_secret */
1357e1188e77SGlenn Strauss             log_error(r->conf.errh, __FILE__, __LINE__,
1358e1188e77SGlenn Strauss               "digest: nonce mismatch");
1359e1188e77SGlenn Strauss             return mod_auth_send_401_unauthorized_digest(r, require, 0);
1360e1188e77SGlenn Strauss         }
1361e1188e77SGlenn Strauss     }
136281b2d1f0SGlenn Strauss 
13634b3a91e6SGlenn Strauss     return HANDLER_GO_ON;
136481b2d1f0SGlenn Strauss }
136581b2d1f0SGlenn Strauss 
1366*20c56cecSGlenn Strauss 
1367*20c56cecSGlenn Strauss static handler_t
1368*20c56cecSGlenn Strauss 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)
1369*20c56cecSGlenn Strauss {
1370*20c56cecSGlenn Strauss     if (NULL == backend || NULL == backend->digest)
1371*20c56cecSGlenn Strauss         return mod_auth_digest_misconfigured(r, backend);
1372*20c56cecSGlenn Strauss 
1373*20c56cecSGlenn Strauss     const buffer * const vb =
1374*20c56cecSGlenn Strauss       http_header_request_get(r, HTTP_HEADER_AUTHORIZATION,
1375*20c56cecSGlenn Strauss                               CONST_STR_LEN("Authorization"));
1376*20c56cecSGlenn Strauss     if (NULL == vb || !buffer_eq_icase_ssn(vb->ptr, CONST_STR_LEN("Digest ")))
1377*20c56cecSGlenn Strauss         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1378*20c56cecSGlenn Strauss   #ifdef __COVERITY__
1379*20c56cecSGlenn Strauss     if (buffer_clen(vb) < sizeof("Digest ")-1)
1380*20c56cecSGlenn Strauss         return mod_auth_send_400_bad_request(r);
1381*20c56cecSGlenn Strauss   #endif
1382*20c56cecSGlenn Strauss 
1383*20c56cecSGlenn Strauss     http_auth_digest_params_t dp;
1384*20c56cecSGlenn Strauss     http_auth_info_t ai;
1385*20c56cecSGlenn Strauss     handler_t rc;
1386*20c56cecSGlenn Strauss 
1387*20c56cecSGlenn Strauss     memset(&dp, 0, sizeof(dp) - sizeof(dp.rdigest));
1388*20c56cecSGlenn Strauss 
1389*20c56cecSGlenn Strauss     mod_auth_digest_parse_authorization(&dp, vb);
1390*20c56cecSGlenn Strauss 
1391*20c56cecSGlenn Strauss     rc = mod_auth_digest_validate_params(r, require, &dp, &ai);
1392*20c56cecSGlenn Strauss     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1393*20c56cecSGlenn Strauss         return rc;
1394*20c56cecSGlenn Strauss 
1395*20c56cecSGlenn Strauss     rc = mod_auth_digest_validate_nonce(r, require, &dp, &ai);
1396*20c56cecSGlenn Strauss     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1397*20c56cecSGlenn Strauss         return rc;
1398*20c56cecSGlenn Strauss 
1399*20c56cecSGlenn Strauss     rc = mod_auth_digest_get(r, p_d, require, backend, &ai);
1400*20c56cecSGlenn Strauss     if (__builtin_expect( (HANDLER_GO_ON != rc), 0))
1401*20c56cecSGlenn Strauss         return rc;
1402*20c56cecSGlenn Strauss 
1403*20c56cecSGlenn Strauss     mod_auth_digest_mutate(&ai, &dp, get_http_method_name(r->http_method));
1404*20c56cecSGlenn Strauss 
1405*20c56cecSGlenn Strauss     if (!ck_memeq_const_time_fixed_len(dp.rdigest, ai.digest, ai.dlen)) {
1406*20c56cecSGlenn Strauss         /*ck_memzero(ai.digest, ai.dlen);*//*skip clear since mutated*/
1407*20c56cecSGlenn Strauss         /* digest not ok */
1408*20c56cecSGlenn Strauss         log_error(r->conf.errh, __FILE__, __LINE__,
1409*20c56cecSGlenn Strauss           "digest: auth failed for %.*s: wrong password, IP: %s",
1410*20c56cecSGlenn Strauss           (int)ai.ulen, ai.username, r->con->dst_addr_buf->ptr);
1411*20c56cecSGlenn Strauss         r->keep_alive = -1; /*(disable keep-alive if bad password)*/
1412*20c56cecSGlenn Strauss         return mod_auth_send_401_unauthorized_digest(r, require, 0);
14137ba06c71SGlenn Strauss     }
1414*20c56cecSGlenn Strauss     /*ck_memzero(ai.digest, ai.dlen);*//* skip clear since mutated */
1415*20c56cecSGlenn Strauss 
1416*20c56cecSGlenn Strauss     /* check authorization (authz); string args must be '\0'-terminated) */
1417*20c56cecSGlenn Strauss     buffer * const tb = r->tmp_buf;
1418*20c56cecSGlenn Strauss     buffer_copy_string_len(tb, ai.username, ai.ulen);
1419*20c56cecSGlenn Strauss     if (!http_auth_match_rules(require, tb->ptr, NULL, NULL))
1420*20c56cecSGlenn Strauss         return mod_auth_send_401_unauthorized_digest(r, require, 0);
1421*20c56cecSGlenn Strauss 
1422*20c56cecSGlenn Strauss     if (dp.send_nextnonce_ts) {
1423*20c56cecSGlenn Strauss         /*(send nextnonce when expiration is approaching)*/
1424*20c56cecSGlenn Strauss         mod_auth_digest_authentication_info(
1425*20c56cecSGlenn Strauss           http_header_response_set_ptr(r, HTTP_HEADER_OTHER,
1426*20c56cecSGlenn Strauss                                        CONST_STR_LEN("Authentication-Info")),
1427*20c56cecSGlenn Strauss           dp.send_nextnonce_ts /*(cur_ts)*/, require, ai.dalgo);
1428*20c56cecSGlenn Strauss     }
1429*20c56cecSGlenn Strauss 
1430*20c56cecSGlenn Strauss     http_auth_setenv(r, ai.username, ai.ulen, CONST_STR_LEN("Digest"));
1431*20c56cecSGlenn Strauss     return HANDLER_GO_ON;
1432*20c56cecSGlenn Strauss }
1433*20c56cecSGlenn Strauss 
1434*20c56cecSGlenn Strauss 
14357ba06c71SGlenn Strauss 
14367c7f8c46SGlenn Strauss 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) {
14377ba06c71SGlenn Strauss 	/* require REMOTE_USER already set */
14387c7f8c46SGlenn Strauss 	const buffer *vb = http_header_env_get(r, CONST_STR_LEN("REMOTE_USER"));
14397ba06c71SGlenn Strauss 	UNUSED(p_d);
14407ba06c71SGlenn Strauss 	UNUSED(backend);
14413dd3cde9SGlenn Strauss 	if (NULL != vb && http_auth_match_rules(require, vb->ptr, NULL, NULL)) {
1442f9d58670SStefan Bühler 		return HANDLER_GO_ON;
1443bcdc6a3bSJan Kneschke 	} else {
14447c7f8c46SGlenn Strauss 		r->http_status = 401;
14457c7f8c46SGlenn Strauss 		r->handler_module = NULL;
1446bcdc6a3bSJan Kneschke 		return HANDLER_FINISHED;
14477187271fSStefan Bühler 	}
1448bcdc6a3bSJan Kneschke }
1449