fix errors detected by Coverity Scan
[lighttpd.git] / src / http_auth.c
blob8dfe9a6b1d321ab44b92c0fba0de14499ccf2dd0
1 #include "first.h"
3 #include "server.h"
4 #include "log.h"
5 #include "http_auth.h"
6 #include "inet_ntop_cache.h"
7 #include "stream.h"
8 #include "base64.h"
10 #ifdef HAVE_CRYPT_H
11 # include <crypt.h>
12 #elif defined(__linux__)
13 /* linux needs _XOPEN_SOURCE */
14 # define _XOPEN_SOURCE
15 #endif
17 #if defined(HAVE_LIBCRYPT) && !defined(HAVE_CRYPT)
18 /* always assume crypt() is present if we have -lcrypt */
19 # define HAVE_CRYPT
20 #endif
22 #include <sys/types.h>
23 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <ctype.h>
34 #include "md5.h"
36 #ifdef USE_OPENSSL
37 #include <openssl/sha.h>
38 #endif
40 #include "safe_memclear.h"
42 #define HASHLEN 16
43 #define HASHHEXLEN 32
44 typedef unsigned char HASH[HASHLEN];
45 typedef char HASHHEX[HASHHEXLEN+1];
47 static void CvtHex(const HASH Bin, char (*Hex)[33]) {
48 li_tohex(*Hex, sizeof(*Hex), (const char*) Bin, 16);
52 /**
53 * the $apr1$ handling is taken from apache 1.3.x
57 * The apr_md5_encode() routine uses much code obtained from the FreeBSD 3.0
58 * MD5 crypt() function, which is licenced as follows:
59 * ----------------------------------------------------------------------------
60 * "THE BEER-WARE LICENSE" (Revision 42):
61 * <phk@login.dknet.dk> wrote this file. As long as you retain this notice you
62 * can do whatever you want with this stuff. If we meet some day, and you think
63 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
64 * ----------------------------------------------------------------------------
67 handler_t auth_ldap_init(server *srv, mod_auth_plugin_config *s);
69 static int http_auth_get_password(server *srv, mod_auth_plugin_data *p, buffer *username, buffer *realm, buffer *password) {
70 if (buffer_is_empty(username) || buffer_is_empty(realm)) return -1;
72 if (p->conf.auth_backend == AUTH_BACKEND_HTDIGEST) {
73 FILE *fp;
74 char f_user[1024];
76 if (buffer_string_is_empty(p->conf.auth_htdigest_userfile)) return -1;
78 fp = fopen(p->conf.auth_htdigest_userfile->ptr, "r");
79 if (NULL == fp) {
80 log_error_write(srv, __FILE__, __LINE__, "sbss", "opening digest-userfile", p->conf.auth_htdigest_userfile, "failed:", strerror(errno));
82 return -1;
85 while (NULL != fgets(f_user, sizeof(f_user), fp)) {
86 char *f_pwd, *f_realm;
87 size_t u_len, r_len;
89 /* skip blank lines and comment lines (beginning '#') */
90 if (f_user[0] == '#' || f_user[0] == '\n' || f_user[0] == '\0') continue;
93 * htdigest format
95 * user:realm:md5(user:realm:password)
98 if (NULL == (f_realm = strchr(f_user, ':'))) {
99 log_error_write(srv, __FILE__, __LINE__, "sbs",
100 "parsed error in", p->conf.auth_htdigest_userfile,
101 "expected 'username:realm:hashed password'");
103 continue; /* skip bad lines */
106 if (NULL == (f_pwd = strchr(f_realm + 1, ':'))) {
107 log_error_write(srv, __FILE__, __LINE__, "sbs",
108 "parsed error in", p->conf.auth_plain_userfile,
109 "expected 'username:realm:hashed password'");
111 continue; /* skip bad lines */
114 /* get pointers to the fields */
115 u_len = f_realm - f_user;
116 f_realm++;
117 r_len = f_pwd - f_realm;
118 f_pwd++;
120 if (buffer_string_length(username) == u_len &&
121 (buffer_string_length(realm) == r_len) &&
122 (0 == strncmp(username->ptr, f_user, u_len)) &&
123 (0 == strncmp(realm->ptr, f_realm, r_len))) {
124 /* found */
126 size_t pwd_len = strlen(f_pwd);
127 if (f_pwd[pwd_len-1] == '\n') --pwd_len;
129 buffer_copy_string_len(password, f_pwd, pwd_len);
131 fclose(fp);
132 return 0;
136 fclose(fp);
137 } else if (p->conf.auth_backend == AUTH_BACKEND_HTPASSWD ||
138 p->conf.auth_backend == AUTH_BACKEND_PLAIN) {
139 FILE *fp;
140 char f_user[1024];
141 buffer *auth_fn;
143 auth_fn = (p->conf.auth_backend == AUTH_BACKEND_HTPASSWD) ? p->conf.auth_htpasswd_userfile : p->conf.auth_plain_userfile;
145 if (buffer_string_is_empty(auth_fn)) return -1;
147 fp = fopen(auth_fn->ptr, "r");
148 if (NULL == fp) {
149 log_error_write(srv, __FILE__, __LINE__, "sbss",
150 "opening plain-userfile", auth_fn, "failed:", strerror(errno));
152 return -1;
155 while (NULL != fgets(f_user, sizeof(f_user), fp)) {
156 char *f_pwd;
157 size_t u_len;
159 /* skip blank lines and comment lines (beginning '#') */
160 if (f_user[0] == '#' || f_user[0] == '\n' || f_user[0] == '\0') continue;
163 * htpasswd format
165 * user:crypted passwd
168 if (NULL == (f_pwd = strchr(f_user, ':'))) {
169 log_error_write(srv, __FILE__, __LINE__, "sbs",
170 "parsed error in", auth_fn,
171 "expected 'username:hashed password'");
173 continue; /* skip bad lines */
176 /* get pointers to the fields */
177 u_len = f_pwd - f_user;
178 f_pwd++;
180 if (buffer_string_length(username) == u_len &&
181 (0 == strncmp(username->ptr, f_user, u_len))) {
182 /* found */
184 size_t pwd_len = strlen(f_pwd);
185 if (f_pwd[pwd_len-1] == '\n') --pwd_len;
187 buffer_copy_string_len(password, f_pwd, pwd_len);
189 fclose(fp);
190 return 0;
194 fclose(fp);
195 } else if (p->conf.auth_backend == AUTH_BACKEND_LDAP) {
196 return 0;
199 return -1;
202 int http_auth_match_rules(server *srv, array *req, const char *username, const char *group, const char *host) {
203 const char *r = NULL, *rules = NULL;
204 int username_len;
205 data_string *require;
207 UNUSED(group);
208 UNUSED(host);
210 require = (data_string *)array_get_element(req, "require");
211 if (!require) return -1; /*(should not happen; config is validated at startup)*/
213 /* if we get here, the user we got a authed user */
214 if (0 == strcmp(require->value->ptr, "valid-user")) {
215 return 0;
218 /* user=name1|group=name3|host=name4 */
220 /* seperate the string by | */
221 #if 0
222 log_error_write(srv, __FILE__, __LINE__, "sb", "rules", require->value);
223 #endif
225 username_len = username ? strlen(username) : 0;
227 r = rules = require->value->ptr;
229 while (1) {
230 const char *eq;
231 const char *k, *v, *e;
232 int k_len, v_len, r_len;
234 e = strchr(r, '|');
236 if (e) {
237 r_len = e - r;
238 } else {
239 r_len = strlen(rules) - (r - rules);
242 /* from r to r + r_len is a rule */
244 if (0 == strncmp(r, "valid-user", r_len)) {
245 log_error_write(srv, __FILE__, __LINE__, "sb",
246 "parsing the 'require' section in 'auth.require' failed: valid-user cannot be combined with other require rules",
247 require->value);
248 return -1;
251 /* search for = in the rules */
252 if (NULL == (eq = strchr(r, '='))) {
253 log_error_write(srv, __FILE__, __LINE__, "sb",
254 "parsing the 'require' section in 'auth.require' failed: a = is missing",
255 require->value);
256 return -1;
259 /* = out of range */
260 if (eq > r + r_len) {
261 log_error_write(srv, __FILE__, __LINE__, "sb",
262 "parsing the 'require' section in 'auth.require' failed: = out of range",
263 require->value);
265 return -1;
268 /* the part before the = is user|group|host */
270 k = r;
271 k_len = eq - r;
272 v = eq + 1;
273 v_len = r_len - k_len - 1;
275 if (k_len == 4) {
276 if (0 == strncmp(k, "user", k_len)) {
277 if (username &&
278 username_len == v_len &&
279 0 == strncmp(username, v, v_len)) {
280 return 0;
282 } else if (0 == strncmp(k, "host", k_len)) {
283 log_error_write(srv, __FILE__, __LINE__, "s", "host ... (not implemented)");
284 } else {
285 log_error_write(srv, __FILE__, __LINE__, "s", "unknown key");
286 return -1;
288 } else if (k_len == 5) {
289 if (0 == strncmp(k, "group", k_len)) {
290 log_error_write(srv, __FILE__, __LINE__, "s", "group ... (not implemented)");
291 } else {
292 log_error_write(srv, __FILE__, __LINE__, "ss", "unknown key", k);
293 return -1;
295 } else {
296 log_error_write(srv, __FILE__, __LINE__, "s", "unknown key");
297 return -1;
300 if (!e) break;
301 r = e + 1;
304 log_error_write(srv, __FILE__, __LINE__, "s", "nothing matched");
306 return -1;
309 #define APR_MD5_DIGESTSIZE 16
310 #define APR1_ID "$apr1$"
313 * The following MD5 password encryption code was largely borrowed from
314 * the FreeBSD 3.0 /usr/src/lib/libcrypt/crypt.c file, which is
315 * licenced as stated at the top of this file.
318 static void to64(char *s, unsigned long v, int n)
320 static const unsigned char itoa64[] = /* 0 ... 63 => ASCII - 64 */
321 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
323 while (--n >= 0) {
324 *s++ = itoa64[v&0x3f];
325 v >>= 6;
329 static void apr_md5_encode(const char *pw, const char *salt, char *result, size_t nbytes) {
331 * Minimum size is 8 bytes for salt, plus 1 for the trailing NUL,
332 * plus 4 for the '$' separators, plus the password hash itself.
333 * Let's leave a goodly amount of leeway.
336 char passwd[120], *p;
337 const char *sp, *ep;
338 unsigned char final[APR_MD5_DIGESTSIZE];
339 ssize_t sl, pl, i;
340 li_MD5_CTX ctx, ctx1;
341 unsigned long l;
344 * Refine the salt first. It's possible we were given an already-hashed
345 * string as the salt argument, so extract the actual salt value from it
346 * if so. Otherwise just use the string up to the first '$' as the salt.
348 sp = salt;
351 * If it starts with the magic string, then skip that.
353 if (!strncmp(sp, APR1_ID, strlen(APR1_ID))) {
354 sp += strlen(APR1_ID);
358 * It stops at the first '$' or 8 chars, whichever comes first
360 for (ep = sp; (*ep != '\0') && (*ep != '$') && (ep < (sp + 8)); ep++) {
361 continue;
365 * Get the length of the true salt
367 sl = ep - sp;
370 * 'Time to make the doughnuts..'
372 li_MD5_Init(&ctx);
375 * The password first, since that is what is most unknown
377 li_MD5_Update(&ctx, pw, strlen(pw));
380 * Then our magic string
382 li_MD5_Update(&ctx, APR1_ID, strlen(APR1_ID));
385 * Then the raw salt
387 li_MD5_Update(&ctx, sp, sl);
390 * Then just as many characters of the MD5(pw, salt, pw)
392 li_MD5_Init(&ctx1);
393 li_MD5_Update(&ctx1, pw, strlen(pw));
394 li_MD5_Update(&ctx1, sp, sl);
395 li_MD5_Update(&ctx1, pw, strlen(pw));
396 li_MD5_Final(final, &ctx1);
397 for (pl = strlen(pw); pl > 0; pl -= APR_MD5_DIGESTSIZE) {
398 li_MD5_Update(
399 &ctx, final,
400 (pl > APR_MD5_DIGESTSIZE) ? APR_MD5_DIGESTSIZE : pl);
404 * Don't leave anything around in vm they could use.
406 memset(final, 0, sizeof(final));
409 * Then something really weird...
411 for (i = strlen(pw); i != 0; i >>= 1) {
412 if (i & 1) {
413 li_MD5_Update(&ctx, final, 1);
415 else {
416 li_MD5_Update(&ctx, pw, 1);
421 * Now make the output string. We know our limitations, so we
422 * can use the string routines without bounds checking.
424 strcpy(passwd, APR1_ID);
425 strncat(passwd, sp, sl);
426 strcat(passwd, "$");
428 li_MD5_Final(final, &ctx);
431 * And now, just to make sure things don't run too fast..
432 * On a 60 Mhz Pentium this takes 34 msec, so you would
433 * need 30 seconds to build a 1000 entry dictionary...
435 for (i = 0; i < 1000; i++) {
436 li_MD5_Init(&ctx1);
437 if (i & 1) {
438 li_MD5_Update(&ctx1, pw, strlen(pw));
440 else {
441 li_MD5_Update(&ctx1, final, APR_MD5_DIGESTSIZE);
443 if (i % 3) {
444 li_MD5_Update(&ctx1, sp, sl);
447 if (i % 7) {
448 li_MD5_Update(&ctx1, pw, strlen(pw));
451 if (i & 1) {
452 li_MD5_Update(&ctx1, final, APR_MD5_DIGESTSIZE);
454 else {
455 li_MD5_Update(&ctx1, pw, strlen(pw));
457 li_MD5_Final(final,&ctx1);
460 p = passwd + strlen(passwd);
462 l = (final[ 0]<<16) | (final[ 6]<<8) | final[12]; to64(p, l, 4); p += 4;
463 l = (final[ 1]<<16) | (final[ 7]<<8) | final[13]; to64(p, l, 4); p += 4;
464 l = (final[ 2]<<16) | (final[ 8]<<8) | final[14]; to64(p, l, 4); p += 4;
465 l = (final[ 3]<<16) | (final[ 9]<<8) | final[15]; to64(p, l, 4); p += 4;
466 l = (final[ 4]<<16) | (final[10]<<8) | final[ 5]; to64(p, l, 4); p += 4;
467 l = final[11] ; to64(p, l, 2); p += 2;
468 *p = '\0';
471 * Don't leave anything around in vm they could use.
473 safe_memclear(final, sizeof(final));
475 /* FIXME
477 #define apr_cpystrn strncpy
478 apr_cpystrn(result, passwd, nbytes - 1);
481 #ifdef USE_OPENSSL
482 static void apr_sha_encode(const char *pw, char *result, size_t nbytes) {
483 unsigned char digest[20];
484 size_t base64_written;
486 SHA1((const unsigned char*) pw, strlen(pw), digest);
488 memset(result, 0, nbytes);
490 /* need 5 bytes for "{SHA}", 28 for base64 (3 bytes -> 4 bytes) of SHA1 (20 bytes), 1 terminating */
491 if (nbytes < 5 + 28 + 1) return;
493 memcpy(result, "{SHA}", 5);
494 base64_written = li_to_base64(result + 5, nbytes - 5, digest, 20, BASE64_STANDARD);
495 force_assert(base64_written == 28);
496 result[5 + base64_written] = '\0'; /* terminate string */
498 #endif
503 * @param password password-string from the auth-backend
504 * @param pw password-string from the client
507 static int http_auth_basic_password_compare(server *srv, mod_auth_plugin_data *p, array *req, buffer *username, buffer *realm, buffer *password, const char *pw) {
508 UNUSED(srv);
509 UNUSED(req);
511 if (p->conf.auth_backend == AUTH_BACKEND_HTDIGEST) {
513 * htdigest format
515 * user:realm:md5(user:realm:password)
518 li_MD5_CTX Md5Ctx;
519 HASH HA1;
520 char a1[33];
522 li_MD5_Init(&Md5Ctx);
523 li_MD5_Update(&Md5Ctx, CONST_BUF_LEN(username));
524 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
525 li_MD5_Update(&Md5Ctx, CONST_BUF_LEN(realm));
526 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
527 li_MD5_Update(&Md5Ctx, (unsigned char *)pw, strlen(pw));
528 li_MD5_Final(HA1, &Md5Ctx);
530 CvtHex(HA1, &a1);
532 if (0 == strcmp(password->ptr, a1)) {
533 return 0;
535 } else if (p->conf.auth_backend == AUTH_BACKEND_HTPASSWD) {
536 char sample[120];
537 if (!strncmp(password->ptr, APR1_ID, strlen(APR1_ID))) {
539 * The hash was created using $apr1$ custom algorithm.
541 apr_md5_encode(pw, password->ptr, sample, sizeof(sample));
542 return (strcmp(sample, password->ptr) == 0) ? 0 : 1;
543 #ifdef USE_OPENSSL
544 } else if (0 == strncmp(password->ptr, "{SHA}", 5)) {
545 apr_sha_encode(pw, sample, sizeof(sample));
546 return (strcmp(sample, password->ptr) == 0) ? 0 : 1;
547 #endif
548 } else {
549 #if defined(HAVE_CRYPT_R) || defined(HAVE_CRYPT)
550 char *crypted;
551 #if defined(HAVE_CRYPT_R)
552 struct crypt_data crypt_tmp_data;
553 crypt_tmp_data.initialized = 0;
554 #endif
556 /* a simple DES password is 2 + 11 characters. everything else should be longer. */
557 if (buffer_string_length(password) < 13) {
558 return -1;
561 #if defined(HAVE_CRYPT_R)
562 if (0 == (crypted = crypt_r(pw, password->ptr, &crypt_tmp_data))) {
563 #else
564 if (0 == (crypted = crypt(pw, password->ptr))) {
565 #endif
566 /* crypt failed. */
567 return -1;
570 if (0 == strcmp(password->ptr, crypted)) {
571 return 0;
573 #endif
575 } else if (p->conf.auth_backend == AUTH_BACKEND_PLAIN) {
576 if (0 == strcmp(password->ptr, pw)) {
577 return 0;
579 } else if (p->conf.auth_backend == AUTH_BACKEND_LDAP) {
580 #ifdef USE_LDAP
581 LDAP *ldap;
582 LDAPMessage *lm, *first;
583 char *dn;
584 int ret;
585 char *attrs[] = { LDAP_NO_ATTRS, NULL };
586 size_t i, len;
588 /* for now we stay synchronous */
591 * 1. connect anonymously (done in plugin init)
592 * 2. get DN for uid = username
593 * 3. auth against ldap server
594 * 4. (optional) check a field
595 * 5. disconnect
599 /* check username
601 * we have to protect us againt username which modifies out filter in
602 * a unpleasant way
605 len = buffer_string_length(username);
606 for (i = 0; i < len; i++) {
607 char c = username->ptr[i];
609 if (!isalpha(c) &&
610 !isdigit(c) &&
611 (c != ' ') &&
612 (c != '@') &&
613 (c != '-') &&
614 (c != '_') &&
615 (c != '.') ) {
617 log_error_write(srv, __FILE__, __LINE__, "sbd",
618 "ldap: invalid character (- _.@a-zA-Z0-9 allowed) in username:", username, i);
620 return -1;
624 if (p->conf.auth_ldap_allow_empty_pw != 1 && pw[0] == '\0')
625 return -1;
627 /* build filter */
628 buffer_copy_buffer(p->ldap_filter, p->conf.ldap_filter_pre);
629 buffer_append_string_buffer(p->ldap_filter, username);
630 buffer_append_string_buffer(p->ldap_filter, p->conf.ldap_filter_post);
633 /* 2. */
634 if (p->anon_conf->ldap == NULL ||
635 LDAP_SUCCESS != (ret = ldap_search_s(p->anon_conf->ldap, p->conf.auth_ldap_basedn->ptr, LDAP_SCOPE_SUBTREE, p->ldap_filter->ptr, attrs, 0, &lm))) {
637 /* try again; the ldap library sometimes fails for the first call but reconnects */
638 if (p->anon_conf->ldap == NULL || ret != LDAP_SERVER_DOWN ||
639 LDAP_SUCCESS != (ret = ldap_search_s(p->anon_conf->ldap, p->conf.auth_ldap_basedn->ptr, LDAP_SCOPE_SUBTREE, p->ldap_filter->ptr, attrs, 0, &lm))) {
641 if (auth_ldap_init(srv, p->anon_conf) != HANDLER_GO_ON)
642 return -1;
644 if (NULL == p->anon_conf->ldap) return -1;
646 if (LDAP_SUCCESS != (ret = ldap_search_s(p->anon_conf->ldap, p->conf.auth_ldap_basedn->ptr, LDAP_SCOPE_SUBTREE, p->ldap_filter->ptr, attrs, 0, &lm))) {
647 log_error_write(srv, __FILE__, __LINE__, "sssb",
648 "ldap:", ldap_err2string(ret), "filter:", p->ldap_filter);
649 return -1;
654 if (NULL == (first = ldap_first_entry(p->anon_conf->ldap, lm))) {
655 log_error_write(srv, __FILE__, __LINE__, "s", "ldap ...");
657 ldap_msgfree(lm);
659 return -1;
662 if (NULL == (dn = ldap_get_dn(p->anon_conf->ldap, first))) {
663 log_error_write(srv, __FILE__, __LINE__, "s", "ldap ...");
665 ldap_msgfree(lm);
667 return -1;
670 ldap_msgfree(lm);
673 /* 3. */
674 if (NULL == (ldap = ldap_init(p->conf.auth_ldap_hostname->ptr, LDAP_PORT))) {
675 log_error_write(srv, __FILE__, __LINE__, "ss", "ldap ...", strerror(errno));
676 return -1;
679 ret = LDAP_VERSION3;
680 if (LDAP_OPT_SUCCESS != (ret = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, &ret))) {
681 log_error_write(srv, __FILE__, __LINE__, "ss", "ldap:", ldap_err2string(ret));
683 ldap_unbind_s(ldap);
685 return -1;
688 if (p->conf.auth_ldap_starttls == 1) {
689 if (LDAP_OPT_SUCCESS != (ret = ldap_start_tls_s(ldap, NULL, NULL))) {
690 log_error_write(srv, __FILE__, __LINE__, "ss", "ldap startTLS failed:", ldap_err2string(ret));
692 ldap_unbind_s(ldap);
694 return -1;
699 if (LDAP_SUCCESS != (ret = ldap_simple_bind_s(ldap, dn, pw))) {
700 log_error_write(srv, __FILE__, __LINE__, "ss", "ldap:", ldap_err2string(ret));
702 ldap_unbind_s(ldap);
704 return -1;
707 /* 5. */
708 ldap_unbind_s(ldap);
710 /* everything worked, good, access granted */
712 return 0;
713 #endif
715 return -1;
718 int http_auth_basic_check(server *srv, connection *con, mod_auth_plugin_data *p, array *req, const char *realm_str) {
719 buffer *username, *password;
720 char *pw;
722 data_string *realm;
724 realm = (data_string *)array_get_element(req, "realm");
725 if (!realm) return 0; /*(should not happen; config is validated at startup)*/
727 username = buffer_init();
729 if (!buffer_append_base64_decode(username, realm_str, strlen(realm_str), BASE64_STANDARD)) {
730 log_error_write(srv, __FILE__, __LINE__, "sb", "decodeing base64-string failed", username);
732 buffer_free(username);
733 return 0;
736 /* r2 == user:password */
737 if (NULL == (pw = strchr(username->ptr, ':'))) {
738 log_error_write(srv, __FILE__, __LINE__, "sb", ": is missing in", username);
740 buffer_free(username);
741 return 0;
744 buffer_string_set_length(username, pw - username->ptr);
745 pw++;
747 password = buffer_init();
748 /* copy password to r1 */
749 if (http_auth_get_password(srv, p, username, realm->value, password)) {
750 buffer_free(username);
751 buffer_free(password);
753 if (AUTH_BACKEND_UNSET == p->conf.auth_backend) {
754 log_error_write(srv, __FILE__, __LINE__, "s", "auth.backend is not set");
755 } else {
756 log_error_write(srv, __FILE__, __LINE__, "ss", "get_password failed, IP:", inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
759 return 0;
762 /* password doesn't match */
763 if (http_auth_basic_password_compare(srv, p, req, username, realm->value, password, pw)) {
764 log_error_write(srv, __FILE__, __LINE__, "sbsBss", "password doesn't match for", con->uri.path, "username:", username, ", IP:", inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
766 buffer_free(username);
767 buffer_free(password);
769 return 0;
772 /* value is our allow-rules */
773 if (http_auth_match_rules(srv, req, username->ptr, NULL, NULL)) {
774 buffer_free(username);
775 buffer_free(password);
777 log_error_write(srv, __FILE__, __LINE__, "s", "rules didn't match");
779 return 0;
782 /* remember the username */
783 buffer_copy_buffer(p->auth_user, username);
785 buffer_free(username);
786 buffer_free(password);
788 return 1;
791 typedef struct {
792 const char *key;
793 int key_len;
794 char **ptr;
795 } digest_kv;
797 /* return values: -1: error/bad request, 0: failed, 1: success */
798 int http_auth_digest_check(server *srv, connection *con, mod_auth_plugin_data *p, array *req, const char *realm_str) {
799 char a1[33];
800 char a2[33];
802 char *username = NULL;
803 char *realm = NULL;
804 char *nonce = NULL;
805 char *uri = NULL;
806 char *algorithm = NULL;
807 char *qop = NULL;
808 char *cnonce = NULL;
809 char *nc = NULL;
810 char *respons = NULL;
812 char *e, *c;
813 const char *m = NULL;
814 int i;
815 buffer *password, *b, *username_buf, *realm_buf;
817 li_MD5_CTX Md5Ctx;
818 HASH HA1;
819 HASH HA2;
820 HASH RespHash;
821 HASHHEX HA2Hex;
824 /* init pointers */
825 #define S(x) \
826 x, sizeof(x)-1, NULL
827 digest_kv dkv[10] = {
828 { S("username=") },
829 { S("realm=") },
830 { S("nonce=") },
831 { S("uri=") },
832 { S("algorithm=") },
833 { S("qop=") },
834 { S("cnonce=") },
835 { S("nc=") },
836 { S("response=") },
838 { NULL, 0, NULL }
840 #undef S
842 dkv[0].ptr = &username;
843 dkv[1].ptr = &realm;
844 dkv[2].ptr = &nonce;
845 dkv[3].ptr = &uri;
846 dkv[4].ptr = &algorithm;
847 dkv[5].ptr = &qop;
848 dkv[6].ptr = &cnonce;
849 dkv[7].ptr = &nc;
850 dkv[8].ptr = &respons;
852 UNUSED(req);
854 if (p->conf.auth_backend != AUTH_BACKEND_HTDIGEST &&
855 p->conf.auth_backend != AUTH_BACKEND_PLAIN) {
856 log_error_write(srv, __FILE__, __LINE__, "s",
857 "digest: unsupported backend (only htdigest or plain)");
859 return -1;
862 b = buffer_init_string(realm_str);
864 /* parse credentials from client */
865 for (c = b->ptr; *c; c++) {
866 /* skip whitespaces */
867 while (*c == ' ' || *c == '\t') c++;
868 if (!*c) break;
870 for (i = 0; dkv[i].key; i++) {
871 if ((0 == strncmp(c, dkv[i].key, dkv[i].key_len))) {
872 if ((c[dkv[i].key_len] == '"') &&
873 (NULL != (e = strchr(c + dkv[i].key_len + 1, '"')))) {
874 /* value with "..." */
875 *(dkv[i].ptr) = c + dkv[i].key_len + 1;
876 c = e;
878 *e = '\0';
879 } else if (NULL != (e = strchr(c + dkv[i].key_len, ','))) {
880 /* value without "...", terminated by ',' */
881 *(dkv[i].ptr) = c + dkv[i].key_len;
882 c = e;
884 *e = '\0';
885 } else {
886 /* value without "...", terminated by EOL */
887 *(dkv[i].ptr) = c + dkv[i].key_len;
888 c += strlen(c) - 1;
894 if (p->conf.auth_debug > 1) {
895 log_error_write(srv, __FILE__, __LINE__, "ss", "username", username);
896 log_error_write(srv, __FILE__, __LINE__, "ss", "realm", realm);
897 log_error_write(srv, __FILE__, __LINE__, "ss", "nonce", nonce);
898 log_error_write(srv, __FILE__, __LINE__, "ss", "uri", uri);
899 log_error_write(srv, __FILE__, __LINE__, "ss", "algorithm", algorithm);
900 log_error_write(srv, __FILE__, __LINE__, "ss", "qop", qop);
901 log_error_write(srv, __FILE__, __LINE__, "ss", "cnonce", cnonce);
902 log_error_write(srv, __FILE__, __LINE__, "ss", "nc", nc);
903 log_error_write(srv, __FILE__, __LINE__, "ss", "response", respons);
906 /* check if everything is transmitted */
907 if (!username ||
908 !realm ||
909 !nonce ||
910 !uri ||
911 (qop && (!nc || !cnonce)) ||
912 !respons ) {
913 /* missing field */
915 log_error_write(srv, __FILE__, __LINE__, "s",
916 "digest: missing field");
918 buffer_free(b);
919 return -1;
923 * protect the md5-sess against missing cnonce and nonce
925 if (algorithm &&
926 0 == strcasecmp(algorithm, "md5-sess") &&
927 (!nonce || !cnonce)) {
928 log_error_write(srv, __FILE__, __LINE__, "s",
929 "digest: (md5-sess: missing field");
931 buffer_free(b);
932 return -1;
935 if (qop && strcasecmp(qop, "auth-int") == 0) {
936 log_error_write(srv, __FILE__, __LINE__, "s",
937 "digest: qop=auth-int not supported");
939 buffer_free(b);
940 return -1;
943 m = get_http_method_name(con->request.http_method);
944 force_assert(m);
946 /* password-string == HA1 */
947 password = buffer_init();
948 username_buf = buffer_init_string(username);
949 realm_buf = buffer_init_string(realm);
950 if (http_auth_get_password(srv, p, username_buf, realm_buf, password)) {
951 buffer_free(password);
952 buffer_free(b);
953 buffer_free(username_buf);
954 buffer_free(realm_buf);
955 return 0;
958 buffer_free(username_buf);
959 buffer_free(realm_buf);
961 if (p->conf.auth_backend == AUTH_BACKEND_PLAIN) {
962 /* generate password from plain-text */
963 li_MD5_Init(&Md5Ctx);
964 li_MD5_Update(&Md5Ctx, (unsigned char *)username, strlen(username));
965 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
966 li_MD5_Update(&Md5Ctx, (unsigned char *)realm, strlen(realm));
967 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
968 li_MD5_Update(&Md5Ctx, CONST_BUF_LEN(password));
969 li_MD5_Final(HA1, &Md5Ctx);
970 } else if (p->conf.auth_backend == AUTH_BACKEND_HTDIGEST) {
971 /* HA1 */
972 /* transform the 32-byte-hex-md5 to a 16-byte-md5 */
973 for (i = 0; i < HASHLEN; i++) {
974 HA1[i] = hex2int(password->ptr[i*2]) << 4;
975 HA1[i] |= hex2int(password->ptr[i*2+1]);
977 } else {
978 /* we already check that above */
979 SEGFAULT();
982 buffer_free(password);
984 if (algorithm &&
985 strcasecmp(algorithm, "md5-sess") == 0) {
986 li_MD5_Init(&Md5Ctx);
987 /* Errata ID 1649: http://www.rfc-editor.org/errata_search.php?rfc=2617 */
988 CvtHex(HA1, &a1);
989 li_MD5_Update(&Md5Ctx, (unsigned char *)a1, HASHHEXLEN);
990 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
991 li_MD5_Update(&Md5Ctx, (unsigned char *)nonce, strlen(nonce));
992 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
993 li_MD5_Update(&Md5Ctx, (unsigned char *)cnonce, strlen(cnonce));
994 li_MD5_Final(HA1, &Md5Ctx);
997 CvtHex(HA1, &a1);
999 /* calculate H(A2) */
1000 li_MD5_Init(&Md5Ctx);
1001 li_MD5_Update(&Md5Ctx, (unsigned char *)m, strlen(m));
1002 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
1003 li_MD5_Update(&Md5Ctx, (unsigned char *)uri, strlen(uri));
1004 /* qop=auth-int not supported, already checked above */
1006 if (qop && strcasecmp(qop, "auth-int") == 0) {
1007 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
1008 li_MD5_Update(&Md5Ctx, (unsigned char *) [body checksum], HASHHEXLEN);
1011 li_MD5_Final(HA2, &Md5Ctx);
1012 CvtHex(HA2, &HA2Hex);
1014 /* calculate response */
1015 li_MD5_Init(&Md5Ctx);
1016 li_MD5_Update(&Md5Ctx, (unsigned char *)a1, HASHHEXLEN);
1017 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
1018 li_MD5_Update(&Md5Ctx, (unsigned char *)nonce, strlen(nonce));
1019 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
1020 if (qop && *qop) {
1021 li_MD5_Update(&Md5Ctx, (unsigned char *)nc, strlen(nc));
1022 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
1023 li_MD5_Update(&Md5Ctx, (unsigned char *)cnonce, strlen(cnonce));
1024 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
1025 li_MD5_Update(&Md5Ctx, (unsigned char *)qop, strlen(qop));
1026 li_MD5_Update(&Md5Ctx, CONST_STR_LEN(":"));
1028 li_MD5_Update(&Md5Ctx, (unsigned char *)HA2Hex, HASHHEXLEN);
1029 li_MD5_Final(RespHash, &Md5Ctx);
1030 CvtHex(RespHash, &a2);
1032 if (0 != strcmp(a2, respons)) {
1033 /* digest not ok */
1035 if (p->conf.auth_debug) {
1036 log_error_write(srv, __FILE__, __LINE__, "sss",
1037 "digest: digest mismatch", a2, respons);
1040 log_error_write(srv, __FILE__, __LINE__, "ssss",
1041 "digest: auth failed for ", username, ": wrong password, IP:", inet_ntop_cache_get_ip(srv, &(con->dst_addr)));
1043 buffer_free(b);
1044 return 0;
1047 /* value is our allow-rules */
1048 if (http_auth_match_rules(srv, req, username, NULL, NULL)) {
1049 buffer_free(b);
1051 log_error_write(srv, __FILE__, __LINE__, "s",
1052 "digest: rules did match");
1054 return 0;
1057 /* remember the username */
1058 buffer_copy_string(p->auth_user, username);
1060 buffer_free(b);
1062 if (p->conf.auth_debug) {
1063 log_error_write(srv, __FILE__, __LINE__, "s",
1064 "digest: auth ok");
1066 return 1;
1070 int http_auth_digest_generate_nonce(server *srv, mod_auth_plugin_data *p, buffer *fn, char (*out)[33]) {
1071 HASH h;
1072 li_MD5_CTX Md5Ctx;
1073 char hh[LI_ITOSTRING_LENGTH];
1075 UNUSED(p);
1077 /* generate shared-secret */
1078 li_MD5_Init(&Md5Ctx);
1079 li_MD5_Update(&Md5Ctx, CONST_BUF_LEN(fn));
1080 li_MD5_Update(&Md5Ctx, CONST_STR_LEN("+"));
1082 /* we assume sizeof(time_t) == 4 here, but if not it ain't a problem at all */
1083 li_itostrn(hh, sizeof(hh), srv->cur_ts);
1084 li_MD5_Update(&Md5Ctx, (unsigned char *)hh, strlen(hh));
1085 li_MD5_Update(&Md5Ctx, (unsigned char *)srv->entropy, sizeof(srv->entropy));
1086 li_itostrn(hh, sizeof(hh), rand());
1087 li_MD5_Update(&Md5Ctx, (unsigned char *)hh, strlen(hh));
1089 li_MD5_Final(h, &Md5Ctx);
1091 CvtHex(h, out);
1093 return 0;