Samba 3: security updates CVE-2011-2522 and CVE-2011-2694 (unused in Tomato)
[tomato.git] / release / src / router / samba3 / source / web / cgi.c
blob9b5220cf5c5e0daa260ef87eacc53989a441159f
1 /*
2 some simple CGI helper routines
3 Copyright (C) Andrew Tridgell 1997-1998
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 #include "includes.h"
22 #include "web/swat_proto.h"
23 #include "secrets.h"
25 #define MAX_VARIABLES 10000
27 /* set the expiry on fixed pages */
28 #define EXPIRY_TIME (60*60*24*7)
30 #ifdef DEBUG_COMMENTS
31 extern void print_title(char *fmt, ...);
32 #endif
34 struct cgi_var {
35 char *name;
36 char *value;
39 static struct cgi_var variables[MAX_VARIABLES];
40 static int num_variables;
41 static int content_length;
42 static int request_post;
43 static char *query_string;
44 static const char *baseurl;
45 static char *pathinfo;
46 static char *C_user;
47 static char *C_pass;
48 static BOOL inetd_server;
49 static BOOL got_request;
51 static char *grab_line(FILE *f, int *cl)
53 char *ret = NULL;
54 int i = 0;
55 int len = 0;
57 while ((*cl)) {
58 int c;
60 if (i == len) {
61 char *ret2;
62 if (len == 0) len = 1024;
63 else len *= 2;
64 ret2 = (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret, len);
65 if (!ret2) return ret;
66 ret = ret2;
69 c = fgetc(f);
70 (*cl)--;
72 if (c == EOF) {
73 (*cl) = 0;
74 break;
77 if (c == '\r') continue;
79 if (strchr_m("\n&", c)) break;
81 ret[i++] = c;
85 if (ret) {
86 ret[i] = 0;
88 return ret;
91 /**
92 URL encoded strings can have a '+', which should be replaced with a space
94 (This was in rfc1738_unescape(), but that broke the squid helper)
95 **/
97 static void plus_to_space_unescape(char *buf)
99 char *p=buf;
101 while ((p=strchr_m(p,'+')))
102 *p = ' ';
105 /***************************************************************************
106 load all the variables passed to the CGI program. May have multiple variables
107 with the same name and the same or different values. Takes a file parameter
108 for simulating CGI invocation eg loading saved preferences.
109 ***************************************************************************/
110 void cgi_load_variables(void)
112 static char *line;
113 char *p, *s, *tok;
114 int len, i;
115 FILE *f = stdin;
117 #ifdef DEBUG_COMMENTS
118 char dummy[100]="";
119 print_title(dummy);
120 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
121 #endif
123 if (!content_length) {
124 p = getenv("CONTENT_LENGTH");
125 len = p?atoi(p):0;
126 } else {
127 len = content_length;
131 if (len > 0 &&
132 (request_post ||
133 ((s=getenv("REQUEST_METHOD")) &&
134 strequal(s,"POST")))) {
135 while (len && (line=grab_line(f, &len))) {
136 p = strchr_m(line,'=');
137 if (!p) continue;
139 *p = 0;
141 variables[num_variables].name = SMB_STRDUP(line);
142 variables[num_variables].value = SMB_STRDUP(p+1);
144 SAFE_FREE(line);
146 if (!variables[num_variables].name ||
147 !variables[num_variables].value)
148 continue;
150 plus_to_space_unescape(variables[num_variables].value);
151 rfc1738_unescape(variables[num_variables].value);
152 plus_to_space_unescape(variables[num_variables].name);
153 rfc1738_unescape(variables[num_variables].name);
155 #ifdef DEBUG_COMMENTS
156 printf("<!== POST var %s has value \"%s\" ==>\n",
157 variables[num_variables].name,
158 variables[num_variables].value);
159 #endif
161 num_variables++;
162 if (num_variables == MAX_VARIABLES) break;
166 fclose(stdin);
167 open("/dev/null", O_RDWR);
169 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
170 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
171 p = strchr_m(tok,'=');
172 if (!p) continue;
174 *p = 0;
176 variables[num_variables].name = SMB_STRDUP(tok);
177 variables[num_variables].value = SMB_STRDUP(p+1);
179 if (!variables[num_variables].name ||
180 !variables[num_variables].value)
181 continue;
183 plus_to_space_unescape(variables[num_variables].value);
184 rfc1738_unescape(variables[num_variables].value);
185 plus_to_space_unescape(variables[num_variables].name);
186 rfc1738_unescape(variables[num_variables].name);
188 #ifdef DEBUG_COMMENTS
189 printf("<!== Commandline var %s has value \"%s\" ==>\n",
190 variables[num_variables].name,
191 variables[num_variables].value);
192 #endif
193 num_variables++;
194 if (num_variables == MAX_VARIABLES) break;
198 #ifdef DEBUG_COMMENTS
199 printf("<!== End dump in cgi_load_variables() ==>\n");
200 #endif
202 /* variables from the client are in UTF-8 - convert them
203 to our internal unix charset before use */
204 for (i=0;i<num_variables;i++) {
205 pstring dest;
207 convert_string(CH_UTF8, CH_UNIX,
208 variables[i].name, -1,
209 dest, sizeof(dest), True);
210 free(variables[i].name);
211 variables[i].name = SMB_STRDUP(dest);
213 convert_string(CH_UTF8, CH_UNIX,
214 variables[i].value, -1,
215 dest, sizeof(dest), True);
216 free(variables[i].value);
217 variables[i].value = SMB_STRDUP(dest);
222 /***************************************************************************
223 find a variable passed via CGI
224 Doesn't quite do what you think in the case of POST text variables, because
225 if they exist they might have a value of "" or even " ", depending on the
226 browser. Also doesn't allow for variables[] containing multiple variables
227 with the same name and the same or different values.
228 ***************************************************************************/
230 const char *cgi_variable(const char *name)
232 int i;
234 for (i=0;i<num_variables;i++)
235 if (strcmp(variables[i].name, name) == 0)
236 return variables[i].value;
237 return NULL;
240 /***************************************************************************
241 Version of the above that can't return a NULL pointer.
242 ***************************************************************************/
244 const char *cgi_variable_nonull(const char *name)
246 const char *var = cgi_variable(name);
247 if (var) {
248 return var;
249 } else {
250 return "";
254 /***************************************************************************
255 tell a browser about a fatal error in the http processing
256 ***************************************************************************/
257 static void cgi_setup_error(const char *err, const char *header, const char *info)
259 if (!got_request) {
260 /* damn browsers don't like getting cut off before they give a request */
261 char line[1024];
262 while (fgets(line, sizeof(line)-1, stdin)) {
263 if (strnequal(line,"GET ", 4) ||
264 strnequal(line,"POST ", 5) ||
265 strnequal(line,"PUT ", 4)) {
266 break;
271 d_printf("HTTP/1.0 %s\r\n%sConnection: close\r\nContent-Type: text/html\r\n\r\n<HTML><HEAD><TITLE>%s</TITLE></HEAD><BODY><H1>%s</H1>%s<p></BODY></HTML>\r\n\r\n", err, header, err, err, info);
272 fclose(stdin);
273 fclose(stdout);
274 exit(0);
278 /***************************************************************************
279 tell a browser about a fatal authentication error
280 ***************************************************************************/
281 static void cgi_auth_error(void)
283 if (inetd_server) {
284 cgi_setup_error("401 Authorization Required",
285 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
286 "You must be authenticated to use this service");
287 } else {
288 printf("Content-Type: text/html\r\n");
290 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
291 printf("<BODY><H1>Installation Error</H1>\n");
292 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
293 printf("</BODY></HTML>\r\n");
295 exit(0);
298 /***************************************************************************
299 authenticate when we are running as a CGI
300 ***************************************************************************/
301 static void cgi_web_auth(void)
303 const char *user = getenv("REMOTE_USER");
304 struct passwd *pwd;
305 const char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
306 const char *tail = "</BODY></HTML>\r\n";
308 if (!user) {
309 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
310 head, tail);
311 exit(0);
314 pwd = getpwnam_alloc(NULL, user);
315 if (!pwd) {
316 printf("%sCannot find user %s<br>%s\n", head, user, tail);
317 exit(0);
320 C_user = SMB_STRDUP(user);
322 if (!setuid(0)) {
323 C_pass = secrets_fetch_generic("root", "SWAT");
324 if (C_pass == NULL) {
325 char *tmp_pass = NULL;
326 tmp_pass = generate_random_str(16);
327 if (tmp_pass == NULL) {
328 printf("%sFailed to create random nonce for "
329 "SWAT session\n<br>%s\n", head, tail);
330 exit(0);
332 secrets_store_generic("root", "SWAT", tmp_pass);
333 C_pass = SMB_STRDUP(tmp_pass);
336 setuid(pwd->pw_uid);
337 if (geteuid() != pwd->pw_uid || getuid() != pwd->pw_uid) {
338 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
339 head, user, (int)geteuid(), (int)getuid(), tail);
340 exit(0);
342 TALLOC_FREE(pwd);
346 /***************************************************************************
347 handle a http authentication line
348 ***************************************************************************/
349 static BOOL cgi_handle_authorization(char *line)
351 char *p;
352 fstring user, user_pass;
353 struct passwd *pass = NULL;
355 if (!strnequal(line,"Basic ", 6)) {
356 goto err;
358 line += 6;
359 while (line[0] == ' ') line++;
360 base64_decode_inplace(line);
361 if (!(p=strchr_m(line,':'))) {
363 * Always give the same error so a cracker
364 * cannot tell why we fail.
366 goto err;
368 *p = 0;
370 convert_string(CH_UTF8, CH_UNIX,
371 line, -1,
372 user, sizeof(user), True);
374 convert_string(CH_UTF8, CH_UNIX,
375 p+1, -1,
376 user_pass, sizeof(user_pass), True);
379 * Try and get the user from the UNIX password file.
382 pass = getpwnam_alloc(NULL, user);
385 * Validate the password they have given.
388 if NT_STATUS_IS_OK(pass_check(pass, user, user_pass,
389 strlen(user_pass), NULL, False)) {
391 if (pass) {
393 * Password was ok.
396 if ( initgroups(pass->pw_name, pass->pw_gid) != 0 )
397 goto err;
399 become_user_permanently(pass->pw_uid, pass->pw_gid);
401 /* Save the users name */
402 C_user = SMB_STRDUP(user);
403 C_pass = SMB_STRDUP(user_pass);
404 TALLOC_FREE(pass);
405 return True;
409 err:
410 cgi_setup_error("401 Bad Authorization",
411 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
412 "username or password incorrect");
414 TALLOC_FREE(pass);
415 return False;
418 /***************************************************************************
419 is this root?
420 ***************************************************************************/
421 BOOL am_root(void)
423 if (geteuid() == 0) {
424 return( True);
425 } else {
426 return( False);
430 /***************************************************************************
431 return a ptr to the users name
432 ***************************************************************************/
433 char *cgi_user_name(void)
435 return(C_user);
438 /***************************************************************************
439 return a ptr to the users password
440 ***************************************************************************/
441 char *cgi_user_pass(void)
443 return(C_pass);
446 /***************************************************************************
447 handle a file download
448 ***************************************************************************/
449 static void cgi_download(char *file)
451 SMB_STRUCT_STAT st;
452 char buf[1024];
453 int fd, l, i;
454 char *p;
455 char *lang;
457 /* sanitise the filename */
458 for (i=0;file[i];i++) {
459 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
460 cgi_setup_error("404 File Not Found","",
461 "Illegal character in filename");
465 if (sys_stat(file, &st) != 0)
467 cgi_setup_error("404 File Not Found","",
468 "The requested file was not found");
471 if (S_ISDIR(st.st_mode))
473 snprintf(buf, sizeof(buf), "%s/index.html", file);
474 if (!file_exist(buf, &st) || !S_ISREG(st.st_mode))
476 cgi_setup_error("404 File Not Found","",
477 "The requested file was not found");
480 else if (S_ISREG(st.st_mode))
482 snprintf(buf, sizeof(buf), "%s", file);
484 else
486 cgi_setup_error("404 File Not Found","",
487 "The requested file was not found");
490 fd = web_open(buf,O_RDONLY,0);
491 if (fd == -1) {
492 cgi_setup_error("404 File Not Found","",
493 "The requested file was not found");
495 printf("HTTP/1.0 200 OK\r\n");
496 if ((p=strrchr_m(buf, '.'))) {
497 if (strcmp(p,".gif")==0) {
498 printf("Content-Type: image/gif\r\n");
499 } else if (strcmp(p,".jpg")==0) {
500 printf("Content-Type: image/jpeg\r\n");
501 } else if (strcmp(p,".png")==0) {
502 printf("Content-Type: image/png\r\n");
503 } else if (strcmp(p,".css")==0) {
504 printf("Content-Type: text/css\r\n");
505 } else if (strcmp(p,".txt")==0) {
506 printf("Content-Type: text/plain\r\n");
507 } else {
508 printf("Content-Type: text/html\r\n");
511 printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
513 lang = lang_tdb_current();
514 if (lang) {
515 printf("Content-Language: %s\r\n", lang);
518 printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
519 while ((l=read(fd,buf,sizeof(buf)))>0) {
520 fwrite(buf, 1, l, stdout);
522 close(fd);
523 exit(0);
530 * @brief Setup the CGI framework.
532 * Setup the cgi framework, handling the possibility that this program
533 * is either run as a true CGI program with a gateway to a web server, or
534 * is itself a mini web server.
536 void cgi_setup(const char *rootdir, int auth_required)
538 BOOL authenticated = False;
539 char line[1024];
540 char *url=NULL;
541 char *p;
542 char *lang;
544 if (chdir(rootdir)) {
545 cgi_setup_error("500 Server Error", "",
546 "chdir failed - the server is not configured correctly");
549 /* Handle the possibility we might be running as non-root */
550 sec_init();
552 if ((lang=getenv("HTTP_ACCEPT_LANGUAGE"))) {
553 /* if running as a cgi program */
554 web_set_lang(lang);
557 /* maybe we are running under a web server */
558 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
559 if (auth_required) {
560 cgi_web_auth();
562 return;
565 inetd_server = True;
567 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
568 cgi_setup_error("403 Forbidden", "",
569 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
572 /* we are a mini-web server. We need to read the request from stdin
573 and handle authentication etc */
574 while (fgets(line, sizeof(line)-1, stdin)) {
575 if (line[0] == '\r' || line[0] == '\n') break;
576 if (strnequal(line,"GET ", 4)) {
577 got_request = True;
578 url = SMB_STRDUP(&line[4]);
579 } else if (strnequal(line,"POST ", 5)) {
580 got_request = True;
581 request_post = 1;
582 url = SMB_STRDUP(&line[5]);
583 } else if (strnequal(line,"PUT ", 4)) {
584 got_request = True;
585 cgi_setup_error("400 Bad Request", "",
586 "This server does not accept PUT requests");
587 } else if (strnequal(line,"Authorization: ", 15)) {
588 authenticated = cgi_handle_authorization(&line[15]);
589 } else if (strnequal(line,"Content-Length: ", 16)) {
590 content_length = atoi(&line[16]);
591 } else if (strnequal(line,"Accept-Language: ", 17)) {
592 web_set_lang(&line[17]);
594 /* ignore all other requests! */
597 if (auth_required && !authenticated) {
598 cgi_auth_error();
601 if (!url) {
602 cgi_setup_error("400 Bad Request", "",
603 "You must specify a GET or POST request");
606 /* trim the URL */
607 if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
608 *p = 0;
610 while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
611 url[strlen(url)-1] = 0;
614 /* anything following a ? in the URL is part of the query string */
615 if ((p=strchr_m(url,'?'))) {
616 query_string = p+1;
617 *p = 0;
620 string_sub(url, "/swat/", "", 0);
622 if (url[0] != '/' && strstr(url,"..")==0) {
623 cgi_download(url);
626 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
627 printf("Date: %s\r\n", http_timestring(time(NULL)));
628 baseurl = "";
629 pathinfo = url+1;
633 /***************************************************************************
634 return the current pages URL
635 ***************************************************************************/
636 const char *cgi_baseurl(void)
638 if (inetd_server) {
639 return baseurl;
641 return getenv("SCRIPT_NAME");
644 /***************************************************************************
645 return the current pages path info
646 ***************************************************************************/
647 const char *cgi_pathinfo(void)
649 char *r;
650 if (inetd_server) {
651 return pathinfo;
653 r = getenv("PATH_INFO");
654 if (!r) return "";
655 if (*r == '/') r++;
656 return r;
659 /***************************************************************************
660 return the hostname of the client
661 ***************************************************************************/
662 char *cgi_remote_host(void)
664 if (inetd_server) {
665 return get_peer_name(1,False);
667 return getenv("REMOTE_HOST");
670 /***************************************************************************
671 return the hostname of the client
672 ***************************************************************************/
673 char *cgi_remote_addr(void)
675 if (inetd_server) {
676 return get_peer_addr(1);
678 return getenv("REMOTE_ADDR");
682 /***************************************************************************
683 return True if the request was a POST
684 ***************************************************************************/
685 BOOL cgi_waspost(void)
687 if (inetd_server) {
688 return request_post;
690 return strequal(getenv("REQUEST_METHOD"), "POST");