2 * uhttpd - Tiny single-threaded httpd
4 * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #define _XOPEN_SOURCE 700
28 static LIST_HEAD(auth_realms
);
30 void uh_auth_add(const char *path
, const char *user
, const char *pass
)
32 struct auth_realm
*new = NULL
;
34 const char *new_pass
= NULL
;
35 char *dest_path
, *dest_user
, *dest_pass
;
41 /* given password refers to a passwd entry */
42 if ((strlen(pass
) > 3) && !strncmp(pass
, "$p$", 3)) {
44 /* try to resolve shadow entry */
45 spwd
= getspnam(&pass
[3]);
47 new_pass
= spwd
->sp_pwdp
;
50 pwd
= getpwnam(&pass
[3]);
51 if (pwd
&& pwd
->pw_passwd
&& pwd
->pw_passwd
[0] &&
52 pwd
->pw_passwd
[0] != '!')
53 new_pass
= pwd
->pw_passwd
;
59 if (!new_pass
|| !new_pass
[0])
62 new = calloc_a(sizeof(*new),
63 &dest_path
, strlen(path
) + 1,
64 &dest_user
, strlen(user
) + 1,
65 &dest_pass
, strlen(new_pass
) + 1);
70 new->path
= strcpy(dest_path
, path
);
71 new->user
= strcpy(dest_user
, user
);
72 new->pass
= strcpy(dest_pass
, new_pass
);
73 list_add(&new->list
, &auth_realms
);
76 bool uh_auth_check(struct client
*cl
, struct path_info
*pi
)
78 struct http_request
*req
= &cl
->request
;
79 struct auth_realm
*realm
;
80 bool user_match
= false;
85 if (pi
->auth
&& !strncasecmp(pi
->auth
, "Basic ", 6)) {
86 const char *auth
= pi
->auth
+ 6;
88 uh_b64decode(uh_buf
, sizeof(uh_buf
), auth
, strlen(auth
));
89 pass
= strchr(uh_buf
, ':');
97 plen
= strlen(pi
->name
);
98 list_for_each_entry(realm
, &auth_realms
, list
) {
99 int rlen
= strlen(realm
->path
);
104 if (strncasecmp(pi
->name
, realm
->path
, rlen
) != 0)
111 if (strcmp(user
, realm
->user
) != 0)
122 (!strcmp(pass
, realm
->pass
) ||
123 !strcmp(crypt(pass
, realm
->pass
), realm
->pass
)))
126 uh_http_header(cl
, 401, "Authorization Required");
127 ustream_printf(cl
->us
,
128 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
129 "Content-Type: text/plain\r\n\r\n",
131 uh_chunk_printf(cl
, "Authorization Required\n");