s3:registry/regfio read SD from the correct location
[Samba.git] / source3 / web / cgi.c
blob0192e7db20f07f93284845e2aa816d54426d451e
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 3 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, see <http://www.gnu.org/licenses/>.
20 #include "includes.h"
21 #include "system/passwd.h"
22 #include "system/filesys.h"
23 #include "web/swat_proto.h"
24 #include "intl/lang_tdb.h"
25 #include "auth.h"
26 #include "secrets.h"
27 #include "../lib/util/setid.h"
29 #define MAX_VARIABLES 10000
31 /* set the expiry on fixed pages */
32 #define EXPIRY_TIME (60*60*24*7)
34 #ifdef DEBUG_COMMENTS
35 extern void print_title(char *fmt, ...);
36 #endif
38 struct cgi_var {
39 char *name;
40 char *value;
43 static struct cgi_var variables[MAX_VARIABLES];
44 static int num_variables;
45 static int content_length;
46 static int request_post;
47 static char *query_string;
48 static const char *baseurl;
49 static char *pathinfo;
50 static char *C_user;
51 static char *C_pass;
52 static char *C_nonce;
53 static bool inetd_server;
54 static bool got_request;
56 static char *grab_line(FILE *f, int *cl)
58 char *ret = NULL;
59 int i = 0;
60 int len = 0;
62 while ((*cl)) {
63 int c;
65 if (i == len) {
66 char *ret2;
67 if (len == 0) len = 1024;
68 else len *= 2;
69 ret2 = (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret, len);
70 if (!ret2) return ret;
71 ret = ret2;
74 c = fgetc(f);
75 (*cl)--;
77 if (c == EOF) {
78 (*cl) = 0;
79 break;
82 if (c == '\r') continue;
84 if (strchr_m("\n&", c)) break;
86 ret[i++] = c;
90 if (ret) {
91 ret[i] = 0;
93 return ret;
96 /**
97 URL encoded strings can have a '+', which should be replaced with a space
99 (This was in rfc1738_unescape(), but that broke the squid helper)
102 static void plus_to_space_unescape(char *buf)
104 char *p=buf;
106 while ((p=strchr_m(p,'+')))
107 *p = ' ';
110 /***************************************************************************
111 load all the variables passed to the CGI program. May have multiple variables
112 with the same name and the same or different values. Takes a file parameter
113 for simulating CGI invocation eg loading saved preferences.
114 ***************************************************************************/
115 void cgi_load_variables(void)
117 static char *line;
118 char *p, *s, *tok;
119 int len, i;
120 FILE *f = stdin;
122 #ifdef DEBUG_COMMENTS
123 char dummy[100]="";
124 print_title(dummy);
125 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
126 #endif
128 if (!content_length) {
129 p = getenv("CONTENT_LENGTH");
130 len = p?atoi(p):0;
131 } else {
132 len = content_length;
136 if (len > 0 &&
137 (request_post ||
138 ((s=getenv("REQUEST_METHOD")) &&
139 strequal(s,"POST")))) {
140 while (len && (line=grab_line(f, &len))) {
141 p = strchr_m(line,'=');
142 if (!p) continue;
144 *p = 0;
146 variables[num_variables].name = SMB_STRDUP(line);
147 variables[num_variables].value = SMB_STRDUP(p+1);
149 SAFE_FREE(line);
151 if (!variables[num_variables].name ||
152 !variables[num_variables].value)
153 continue;
155 plus_to_space_unescape(variables[num_variables].value);
156 rfc1738_unescape(variables[num_variables].value);
157 plus_to_space_unescape(variables[num_variables].name);
158 rfc1738_unescape(variables[num_variables].name);
160 #ifdef DEBUG_COMMENTS
161 printf("<!== POST var %s has value \"%s\" ==>\n",
162 variables[num_variables].name,
163 variables[num_variables].value);
164 #endif
166 num_variables++;
167 if (num_variables == MAX_VARIABLES) break;
171 fclose(stdin);
172 open("/dev/null", O_RDWR);
174 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
175 char *saveptr;
176 for (tok=strtok_r(s, "&;", &saveptr); tok;
177 tok=strtok_r(NULL, "&;", &saveptr)) {
178 p = strchr_m(tok,'=');
179 if (!p) continue;
181 *p = 0;
183 variables[num_variables].name = SMB_STRDUP(tok);
184 variables[num_variables].value = SMB_STRDUP(p+1);
186 if (!variables[num_variables].name ||
187 !variables[num_variables].value)
188 continue;
190 plus_to_space_unescape(variables[num_variables].value);
191 rfc1738_unescape(variables[num_variables].value);
192 plus_to_space_unescape(variables[num_variables].name);
193 rfc1738_unescape(variables[num_variables].name);
195 #ifdef DEBUG_COMMENTS
196 printf("<!== Commandline var %s has value \"%s\" ==>\n",
197 variables[num_variables].name,
198 variables[num_variables].value);
199 #endif
200 num_variables++;
201 if (num_variables == MAX_VARIABLES) break;
205 #ifdef DEBUG_COMMENTS
206 printf("<!== End dump in cgi_load_variables() ==>\n");
207 #endif
209 /* variables from the client are in UTF-8 - convert them
210 to our internal unix charset before use */
211 for (i=0;i<num_variables;i++) {
212 TALLOC_CTX *frame = talloc_stackframe();
213 char *dest = NULL;
214 size_t dest_len;
216 convert_string_talloc(frame, CH_UTF8, CH_UNIX,
217 variables[i].name, strlen(variables[i].name),
218 &dest, &dest_len);
219 SAFE_FREE(variables[i].name);
220 variables[i].name = SMB_STRDUP(dest ? dest : "");
222 dest = NULL;
223 convert_string_talloc(frame, CH_UTF8, CH_UNIX,
224 variables[i].value, strlen(variables[i].value),
225 &dest, &dest_len);
226 SAFE_FREE(variables[i].value);
227 variables[i].value = SMB_STRDUP(dest ? dest : "");
228 TALLOC_FREE(frame);
233 /***************************************************************************
234 find a variable passed via CGI
235 Doesn't quite do what you think in the case of POST text variables, because
236 if they exist they might have a value of "" or even " ", depending on the
237 browser. Also doesn't allow for variables[] containing multiple variables
238 with the same name and the same or different values.
239 ***************************************************************************/
241 const char *cgi_variable(const char *name)
243 int i;
245 for (i=0;i<num_variables;i++)
246 if (strcmp(variables[i].name, name) == 0)
247 return variables[i].value;
248 return NULL;
251 /***************************************************************************
252 Version of the above that can't return a NULL pointer.
253 ***************************************************************************/
255 const char *cgi_variable_nonull(const char *name)
257 const char *var = cgi_variable(name);
258 if (var) {
259 return var;
260 } else {
261 return "";
265 /***************************************************************************
266 tell a browser about a fatal error in the http processing
267 ***************************************************************************/
268 static void cgi_setup_error(const char *err, const char *header, const char *info)
270 if (!got_request) {
271 /* damn browsers don't like getting cut off before they give a request */
272 char line[1024];
273 while (fgets(line, sizeof(line)-1, stdin)) {
274 if (strnequal(line,"GET ", 4) ||
275 strnequal(line,"POST ", 5) ||
276 strnequal(line,"PUT ", 4)) {
277 break;
282 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);
283 fclose(stdin);
284 fclose(stdout);
285 exit(0);
289 /***************************************************************************
290 tell a browser about a fatal authentication error
291 ***************************************************************************/
292 static void cgi_auth_error(void)
294 if (inetd_server) {
295 cgi_setup_error("401 Authorization Required",
296 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
297 "You must be authenticated to use this service");
298 } else {
299 printf("Content-Type: text/html\r\n");
301 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
302 printf("<BODY><H1>Installation Error</H1>\n");
303 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
304 printf("</BODY></HTML>\r\n");
306 exit(0);
309 /***************************************************************************
310 authenticate when we are running as a CGI
311 ***************************************************************************/
312 static void cgi_web_auth(void)
314 const char *user = getenv("REMOTE_USER");
315 struct passwd *pwd;
316 const char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
317 const char *tail = "</BODY></HTML>\r\n";
319 if (!user) {
320 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
321 head, tail);
322 exit(0);
325 pwd = Get_Pwnam_alloc(talloc_tos(), user);
326 if (!pwd) {
327 printf("%sCannot find user %s<br>%s\n", head, user, tail);
328 exit(0);
331 C_user = SMB_STRDUP(user);
333 if (!samba_setuid(0)) {
334 C_pass = SMB_STRDUP(cgi_nonce());
336 samba_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;
354 const char *rhost;
355 char addr[INET6_ADDRSTRLEN];
356 size_t size = 0;
358 if (!strnequal(line,"Basic ", 6)) {
359 goto err;
361 line += 6;
362 while (line[0] == ' ') line++;
363 base64_decode_inplace(line);
364 if (!(p=strchr_m(line,':'))) {
366 * Always give the same error so a cracker
367 * cannot tell why we fail.
369 goto err;
371 *p = 0;
373 if (!convert_string(CH_UTF8, CH_UNIX,
374 line, -1,
375 user, sizeof(user), &size)) {
376 goto err;
379 if (!convert_string(CH_UTF8, CH_UNIX,
380 p+1, -1,
381 user_pass, sizeof(user_pass), &size)) {
382 goto err;
386 * Try and get the user from the UNIX password file.
389 pass = Get_Pwnam_alloc(talloc_tos(), user);
391 rhost = client_name(1);
392 if (strequal(rhost,"UNKNOWN"))
393 rhost = client_addr(1, addr, sizeof(addr));
396 * Validate the password they have given.
399 if NT_STATUS_IS_OK(pass_check(pass, user, rhost, user_pass, false)) {
400 if (pass) {
402 * Password was ok.
405 if ( initgroups(pass->pw_name, pass->pw_gid) != 0 )
406 goto err;
408 become_user_permanently(pass->pw_uid, pass->pw_gid);
410 /* Save the users name */
411 C_user = SMB_STRDUP(user);
412 C_pass = SMB_STRDUP(user_pass);
413 TALLOC_FREE(pass);
414 return True;
418 err:
419 cgi_setup_error("401 Bad Authorization",
420 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
421 "username or password incorrect");
423 TALLOC_FREE(pass);
424 return False;
427 /***************************************************************************
428 is this root?
429 ***************************************************************************/
430 bool am_root(void)
432 if (geteuid() == 0) {
433 return( True);
434 } else {
435 return( False);
439 /***************************************************************************
440 return a ptr to the users name
441 ***************************************************************************/
442 char *cgi_user_name(void)
444 return(C_user);
447 /***************************************************************************
448 return a ptr to the users password
449 ***************************************************************************/
450 char *cgi_user_pass(void)
452 return(C_pass);
455 /***************************************************************************
456 return a ptr to the nonce
457 ***************************************************************************/
458 char *cgi_nonce(void)
460 const char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
461 const char *tail = "</BODY></HTML>\r\n";
462 C_nonce = secrets_fetch_generic("root", "SWAT");
463 if (C_nonce == NULL) {
464 char *tmp_pass = NULL;
465 tmp_pass = generate_random_password(talloc_tos(), 16, 16);
466 if (tmp_pass == NULL) {
467 printf("%sFailed to create random nonce for "
468 "SWAT session\n<br>%s\n", head, tail);
469 exit(0);
471 secrets_store_generic("root", "SWAT", tmp_pass);
472 C_nonce = SMB_STRDUP(tmp_pass);
473 TALLOC_FREE(tmp_pass);
475 return(C_nonce);
478 /***************************************************************************
479 handle a file download
480 ***************************************************************************/
481 static void cgi_download(char *file)
483 SMB_STRUCT_STAT st;
484 char buf[1024];
485 int fd, l, i;
486 char *p;
487 char *lang;
489 /* sanitise the filename */
490 for (i=0;file[i];i++) {
491 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
492 cgi_setup_error("404 File Not Found","",
493 "Illegal character in filename");
497 if (sys_stat(file, &st, false) != 0) {
498 cgi_setup_error("404 File Not Found","",
499 "The requested file was not found");
502 if (S_ISDIR(st.st_ex_mode))
504 snprintf(buf, sizeof(buf), "%s/index.html", file);
505 if (!file_exist_stat(buf, &st, false)
506 || !S_ISREG(st.st_ex_mode))
508 cgi_setup_error("404 File Not Found","",
509 "The requested file was not found");
512 else if (S_ISREG(st.st_ex_mode))
514 snprintf(buf, sizeof(buf), "%s", file);
516 else
518 cgi_setup_error("404 File Not Found","",
519 "The requested file was not found");
522 fd = web_open(buf,O_RDONLY,0);
523 if (fd == -1) {
524 cgi_setup_error("404 File Not Found","",
525 "The requested file was not found");
527 printf("HTTP/1.0 200 OK\r\n");
528 if ((p=strrchr_m(buf, '.'))) {
529 if (strcmp(p,".gif")==0) {
530 printf("Content-Type: image/gif\r\n");
531 } else if (strcmp(p,".jpg")==0) {
532 printf("Content-Type: image/jpeg\r\n");
533 } else if (strcmp(p,".png")==0) {
534 printf("Content-Type: image/png\r\n");
535 } else if (strcmp(p,".css")==0) {
536 printf("Content-Type: text/css\r\n");
537 } else if (strcmp(p,".txt")==0) {
538 printf("Content-Type: text/plain\r\n");
539 } else {
540 printf("Content-Type: text/html\r\n");
543 printf("Expires: %s\r\n",
544 http_timestring(talloc_tos(), time(NULL)+EXPIRY_TIME));
546 lang = lang_tdb_current();
547 if (lang) {
548 printf("Content-Language: %s\r\n", lang);
551 printf("Content-Length: %d\r\n\r\n", (int)st.st_ex_size);
552 while ((l=read(fd,buf,sizeof(buf)))>0) {
553 if (fwrite(buf, 1, l, stdout) != l) {
554 break;
557 close(fd);
558 exit(0);
563 /* return true if the char* contains ip addrs only. Used to avoid
564 name lookup calls */
566 static bool only_ipaddrs_in_list(const char **list)
568 bool only_ip = true;
570 if (!list) {
571 return true;
574 for (; *list ; list++) {
575 /* factor out the special strings */
576 if (strequal(*list, "ALL") || strequal(*list, "FAIL") ||
577 strequal(*list, "EXCEPT")) {
578 continue;
581 if (!is_ipaddress(*list)) {
583 * If we failed, make sure that it was not because
584 * the token was a network/netmask pair. Only
585 * network/netmask pairs have a '/' in them.
587 if ((strchr_m(*list, '/')) == NULL) {
588 only_ip = false;
589 DEBUG(3,("only_ipaddrs_in_list: list has "
590 "non-ip address (%s)\n",
591 *list));
592 break;
597 return only_ip;
600 /* return true if access should be allowed to a service for a socket */
601 static bool check_access(int sock, const char **allow_list,
602 const char **deny_list)
604 bool ret = false;
605 bool only_ip = false;
606 char addr[INET6_ADDRSTRLEN];
608 if ((!deny_list || *deny_list==0) && (!allow_list || *allow_list==0)) {
609 return true;
612 /* Bypass name resolution calls if the lists
613 * only contain IP addrs */
614 if (only_ipaddrs_in_list(allow_list) &&
615 only_ipaddrs_in_list(deny_list)) {
616 only_ip = true;
617 DEBUG (3, ("check_access: no hostnames "
618 "in host allow/deny list.\n"));
619 ret = allow_access(deny_list,
620 allow_list,
622 get_peer_addr(sock,addr,sizeof(addr)));
623 } else {
624 DEBUG (3, ("check_access: hostnames in "
625 "host allow/deny list.\n"));
626 ret = allow_access(deny_list,
627 allow_list,
628 get_peer_name(sock,true),
629 get_peer_addr(sock,addr,sizeof(addr)));
632 if (ret) {
633 DEBUG(2,("Allowed connection from %s (%s)\n",
634 only_ip ? "" : get_peer_name(sock,true),
635 get_peer_addr(sock,addr,sizeof(addr))));
636 } else {
637 DEBUG(0,("Denied connection from %s (%s)\n",
638 only_ip ? "" : get_peer_name(sock,true),
639 get_peer_addr(sock,addr,sizeof(addr))));
642 return(ret);
646 * @brief Setup the CGI framework.
648 * Setup the cgi framework, handling the possibility that this program
649 * is either run as a true CGI program with a gateway to a web server, or
650 * is itself a mini web server.
652 void cgi_setup(const char *rootdir, int auth_required)
654 bool authenticated = False;
655 char line[1024];
656 char *url=NULL;
657 char *p;
658 char *lang;
660 if (chdir(rootdir)) {
661 cgi_setup_error("500 Server Error", "",
662 "chdir failed - the server is not configured correctly");
665 /* Handle the possibility we might be running as non-root */
666 sec_init();
668 if ((lang=getenv("HTTP_ACCEPT_LANGUAGE"))) {
669 /* if running as a cgi program */
670 web_set_lang(lang);
673 /* maybe we are running under a web server */
674 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
675 if (auth_required) {
676 cgi_web_auth();
678 return;
681 inetd_server = True;
683 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
684 cgi_setup_error("403 Forbidden", "",
685 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
688 /* we are a mini-web server. We need to read the request from stdin
689 and handle authentication etc */
690 while (fgets(line, sizeof(line)-1, stdin)) {
691 if (line[0] == '\r' || line[0] == '\n') break;
692 if (strnequal(line,"GET ", 4)) {
693 got_request = True;
694 url = SMB_STRDUP(&line[4]);
695 } else if (strnequal(line,"POST ", 5)) {
696 got_request = True;
697 request_post = 1;
698 url = SMB_STRDUP(&line[5]);
699 } else if (strnequal(line,"PUT ", 4)) {
700 got_request = True;
701 cgi_setup_error("400 Bad Request", "",
702 "This server does not accept PUT requests");
703 } else if (strnequal(line,"Authorization: ", 15)) {
704 authenticated = cgi_handle_authorization(&line[15]);
705 } else if (strnequal(line,"Content-Length: ", 16)) {
706 content_length = atoi(&line[16]);
707 } else if (strnequal(line,"Accept-Language: ", 17)) {
708 web_set_lang(&line[17]);
710 /* ignore all other requests! */
713 if (auth_required && !authenticated) {
714 cgi_auth_error();
717 if (!url) {
718 cgi_setup_error("400 Bad Request", "",
719 "You must specify a GET or POST request");
722 /* trim the URL */
723 if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
724 *p = 0;
726 while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
727 url[strlen(url)-1] = 0;
730 /* anything following a ? in the URL is part of the query string */
731 if ((p=strchr_m(url,'?'))) {
732 query_string = p+1;
733 *p = 0;
736 string_sub(url, "/swat/", "", 0);
738 if (url[0] != '/' && strstr(url,"..")==0) {
739 cgi_download(url);
742 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
743 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL)));
744 baseurl = "";
745 pathinfo = url+1;
749 /***************************************************************************
750 return the current pages URL
751 ***************************************************************************/
752 const char *cgi_baseurl(void)
754 if (inetd_server) {
755 return baseurl;
757 return getenv("SCRIPT_NAME");
760 /***************************************************************************
761 return the current pages path info
762 ***************************************************************************/
763 const char *cgi_pathinfo(void)
765 char *r;
766 if (inetd_server) {
767 return pathinfo;
769 r = getenv("PATH_INFO");
770 if (!r) return "";
771 if (*r == '/') r++;
772 return r;
775 /***************************************************************************
776 return the hostname of the client
777 ***************************************************************************/
778 const char *cgi_remote_host(void)
780 if (inetd_server) {
781 return get_peer_name(1,False);
783 return getenv("REMOTE_HOST");
786 /***************************************************************************
787 return the hostname of the client
788 ***************************************************************************/
789 const char *cgi_remote_addr(void)
791 if (inetd_server) {
792 char addr[INET6_ADDRSTRLEN];
793 get_peer_addr(1,addr,sizeof(addr));
794 return talloc_strdup(talloc_tos(), addr);
796 return getenv("REMOTE_ADDR");
800 /***************************************************************************
801 return True if the request was a POST
802 ***************************************************************************/
803 bool cgi_waspost(void)
805 if (inetd_server) {
806 return request_post;
808 return strequal(getenv("REQUEST_METHOD"), "POST");