source: trunk/server/source3/web/cgi.c@ 745

Last change on this file since 745 was 745, checked in by Silvan Scherrer, 13 years ago

Samba Server: updated trunk to 3.6.0

File size: 20.9 KB
Line 
1/*
2 some simple CGI helper routines
3 Copyright (C) Andrew Tridgell 1997-1998
4
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.
9
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.
14
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/>.
17*/
18
19
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
28#define MAX_VARIABLES 10000
29
30/* set the expiry on fixed pages */
31#define EXPIRY_TIME (60*60*24*7)
32
33#ifdef DEBUG_COMMENTS
34extern void print_title(char *fmt, ...);
35#endif
36
37struct cgi_var {
38 char *name;
39 char *value;
40};
41
42static struct cgi_var variables[MAX_VARIABLES];
43static int num_variables;
44static int content_length;
45static int request_post;
46static char *query_string;
47static const char *baseurl;
48static char *pathinfo;
49static char *C_user;
50static char *C_pass;
51static bool inetd_server;
52static bool got_request;
53
54static char *grab_line(FILE *f, int *cl)
55{
56 char *ret = NULL;
57 int i = 0;
58 int len = 0;
59
60 while ((*cl)) {
61 int c;
62
63 if (i == len) {
64 char *ret2;
65 if (len == 0) len = 1024;
66 else len *= 2;
67 ret2 = (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret, len);
68 if (!ret2) return ret;
69 ret = ret2;
70 }
71
72 c = fgetc(f);
73 (*cl)--;
74
75 if (c == EOF) {
76 (*cl) = 0;
77 break;
78 }
79
80 if (c == '\r') continue;
81
82 if (strchr_m("\n&", c)) break;
83
84 ret[i++] = c;
85
86 }
87
88 if (ret) {
89 ret[i] = 0;
90 }
91 return ret;
92}
93
94/**
95 URL encoded strings can have a '+', which should be replaced with a space
96
97 (This was in rfc1738_unescape(), but that broke the squid helper)
98**/
99
100static void plus_to_space_unescape(char *buf)
101{
102 char *p=buf;
103
104 while ((p=strchr_m(p,'+')))
105 *p = ' ';
106}
107
108/***************************************************************************
109 load all the variables passed to the CGI program. May have multiple variables
110 with the same name and the same or different values. Takes a file parameter
111 for simulating CGI invocation eg loading saved preferences.
112 ***************************************************************************/
113void cgi_load_variables(void)
114{
115 static char *line;
116 char *p, *s, *tok;
117 int len, i;
118 FILE *f = stdin;
119
120#ifdef DEBUG_COMMENTS
121 char dummy[100]="";
122 print_title(dummy);
123 d_printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
124#endif
125
126 if (!content_length) {
127 p = getenv("CONTENT_LENGTH");
128 len = p?atoi(p):0;
129 } else {
130 len = content_length;
131 }
132
133
134 if (len > 0 &&
135 (request_post ||
136 ((s=getenv("REQUEST_METHOD")) &&
137 strequal(s,"POST")))) {
138 while (len && (line=grab_line(f, &len))) {
139 p = strchr_m(line,'=');
140 if (!p) continue;
141
142 *p = 0;
143
144 variables[num_variables].name = SMB_STRDUP(line);
145 variables[num_variables].value = SMB_STRDUP(p+1);
146
147 SAFE_FREE(line);
148
149 if (!variables[num_variables].name ||
150 !variables[num_variables].value)
151 continue;
152
153 plus_to_space_unescape(variables[num_variables].value);
154 rfc1738_unescape(variables[num_variables].value);
155 plus_to_space_unescape(variables[num_variables].name);
156 rfc1738_unescape(variables[num_variables].name);
157
158#ifdef DEBUG_COMMENTS
159 printf("<!== POST var %s has value \"%s\" ==>\n",
160 variables[num_variables].name,
161 variables[num_variables].value);
162#endif
163
164 num_variables++;
165 if (num_variables == MAX_VARIABLES) break;
166 }
167 }
168
169 fclose(stdin);
170 open("/dev/null", O_RDWR);
171
172 if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
173 char *saveptr;
174 for (tok=strtok_r(s, "&;", &saveptr); tok;
175 tok=strtok_r(NULL, "&;", &saveptr)) {
176 p = strchr_m(tok,'=');
177 if (!p) continue;
178
179 *p = 0;
180
181 variables[num_variables].name = SMB_STRDUP(tok);
182 variables[num_variables].value = SMB_STRDUP(p+1);
183
184 if (!variables[num_variables].name ||
185 !variables[num_variables].value)
186 continue;
187
188 plus_to_space_unescape(variables[num_variables].value);
189 rfc1738_unescape(variables[num_variables].value);
190 plus_to_space_unescape(variables[num_variables].name);
191 rfc1738_unescape(variables[num_variables].name);
192
193#ifdef DEBUG_COMMENTS
194 printf("<!== Commandline var %s has value \"%s\" ==>\n",
195 variables[num_variables].name,
196 variables[num_variables].value);
197#endif
198 num_variables++;
199 if (num_variables == MAX_VARIABLES) break;
200 }
201
202 }
203#ifdef DEBUG_COMMENTS
204 printf("<!== End dump in cgi_load_variables() ==>\n");
205#endif
206
207 /* variables from the client are in UTF-8 - convert them
208 to our internal unix charset before use */
209 for (i=0;i<num_variables;i++) {
210 TALLOC_CTX *frame = talloc_stackframe();
211 char *dest = NULL;
212 size_t dest_len;
213
214 convert_string_talloc(frame, CH_UTF8, CH_UNIX,
215 variables[i].name, strlen(variables[i].name),
216 &dest, &dest_len, True);
217 SAFE_FREE(variables[i].name);
218 variables[i].name = SMB_STRDUP(dest ? dest : "");
219
220 dest = NULL;
221 convert_string_talloc(frame, CH_UTF8, CH_UNIX,
222 variables[i].value, strlen(variables[i].value),
223 &dest, &dest_len, True);
224 SAFE_FREE(variables[i].value);
225 variables[i].value = SMB_STRDUP(dest ? dest : "");
226 TALLOC_FREE(frame);
227 }
228}
229
230
231/***************************************************************************
232 find a variable passed via CGI
233 Doesn't quite do what you think in the case of POST text variables, because
234 if they exist they might have a value of "" or even " ", depending on the
235 browser. Also doesn't allow for variables[] containing multiple variables
236 with the same name and the same or different values.
237 ***************************************************************************/
238
239const char *cgi_variable(const char *name)
240{
241 int i;
242
243 for (i=0;i<num_variables;i++)
244 if (strcmp(variables[i].name, name) == 0)
245 return variables[i].value;
246 return NULL;
247}
248
249/***************************************************************************
250 Version of the above that can't return a NULL pointer.
251***************************************************************************/
252
253const char *cgi_variable_nonull(const char *name)
254{
255 const char *var = cgi_variable(name);
256 if (var) {
257 return var;
258 } else {
259 return "";
260 }
261}
262
263/***************************************************************************
264tell a browser about a fatal error in the http processing
265 ***************************************************************************/
266static void cgi_setup_error(const char *err, const char *header, const char *info)
267{
268 if (!got_request) {
269 /* damn browsers don't like getting cut off before they give a request */
270 char line[1024];
271 while (fgets(line, sizeof(line)-1, stdin)) {
272 if (strnequal(line,"GET ", 4) ||
273 strnequal(line,"POST ", 5) ||
274 strnequal(line,"PUT ", 4)) {
275 break;
276 }
277 }
278 }
279
280 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);
281 fclose(stdin);
282 fclose(stdout);
283 exit(0);
284}
285
286
287/***************************************************************************
288tell a browser about a fatal authentication error
289 ***************************************************************************/
290static void cgi_auth_error(void)
291{
292 if (inetd_server) {
293 cgi_setup_error("401 Authorization Required",
294 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
295 "You must be authenticated to use this service");
296 } else {
297 printf("Content-Type: text/html\r\n");
298
299 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
300 printf("<BODY><H1>Installation Error</H1>\n");
301 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
302 printf("</BODY></HTML>\r\n");
303 }
304 exit(0);
305}
306
307/***************************************************************************
308authenticate when we are running as a CGI
309 ***************************************************************************/
310static void cgi_web_auth(void)
311{
312 const char *user = getenv("REMOTE_USER");
313 struct passwd *pwd;
314 const char *head = "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
315 const char *tail = "</BODY></HTML>\r\n";
316
317 if (!user) {
318 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
319 head, tail);
320 exit(0);
321 }
322
323#ifndef __OS2__
324 pwd = Get_Pwnam_alloc(talloc_tos(), user);
325 if (!pwd) {
326 printf("%sCannot find user %s<br>%s\n", head, user, tail);
327 exit(0);
328 }
329
330 C_user = SMB_STRDUP(user);
331
332 if (!setuid(0)) {
333 C_pass = secrets_fetch_generic("root", "SWAT");
334 if (C_pass == NULL) {
335 char *tmp_pass = NULL;
336 tmp_pass = generate_random_password(talloc_tos(),
337 16, 16);
338 if (tmp_pass == NULL) {
339 printf("%sFailed to create random nonce for "
340 "SWAT session\n<br>%s\n", head, tail);
341 exit(0);
342 }
343 secrets_store_generic("root", "SWAT", tmp_pass);
344 C_pass = SMB_STRDUP(tmp_pass);
345 TALLOC_FREE(tmp_pass);
346 }
347 }
348 setuid(pwd->pw_uid);
349 if (geteuid() != pwd->pw_uid || getuid() != pwd->pw_uid) {
350 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
351 head, user, (int)geteuid(), (int)getuid(), tail);
352 exit(0);
353 }
354 TALLOC_FREE(pwd);
355#endif
356}
357
358
359/***************************************************************************
360handle a http authentication line
361 ***************************************************************************/
362static bool cgi_handle_authorization(char *line)
363{
364 char *p;
365 fstring user, user_pass;
366 struct passwd *pass = NULL;
367 const char *rhost;
368 char addr[INET6_ADDRSTRLEN];
369
370 if (!strnequal(line,"Basic ", 6)) {
371 goto err;
372 }
373 line += 6;
374 while (line[0] == ' ') line++;
375 base64_decode_inplace(line);
376 if (!(p=strchr_m(line,':'))) {
377 /*
378 * Always give the same error so a cracker
379 * cannot tell why we fail.
380 */
381 goto err;
382 }
383 *p = 0;
384
385 convert_string(CH_UTF8, CH_UNIX,
386 line, -1,
387 user, sizeof(user), True);
388
389 convert_string(CH_UTF8, CH_UNIX,
390 p+1, -1,
391 user_pass, sizeof(user_pass), True);
392
393 /*
394 * Try and get the user from the UNIX password file.
395 */
396
397 pass = Get_Pwnam_alloc(talloc_tos(), user);
398
399 rhost = client_name(1);
400 if (strequal(rhost,"UNKNOWN"))
401 rhost = client_addr(1, addr, sizeof(addr));
402
403 /*
404 * Validate the password they have given.
405 */
406
407 if NT_STATUS_IS_OK(pass_check(pass, user, rhost, user_pass, false)) {
408 if (pass) {
409 /*
410 * Password was ok.
411 */
412
413 if ( initgroups(pass->pw_name, pass->pw_gid) != 0 )
414 goto err;
415
416 become_user_permanently(pass->pw_uid, pass->pw_gid);
417
418 /* Save the users name */
419 C_user = SMB_STRDUP(user);
420 C_pass = SMB_STRDUP(user_pass);
421 TALLOC_FREE(pass);
422 return True;
423 }
424 }
425
426err:
427 cgi_setup_error("401 Bad Authorization",
428 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
429 "username or password incorrect");
430
431 TALLOC_FREE(pass);
432 return False;
433}
434
435/***************************************************************************
436is this root?
437 ***************************************************************************/
438bool am_root(void)
439{
440 if (geteuid() == 0) {
441 return( True);
442 } else {
443 return( False);
444 }
445}
446
447/***************************************************************************
448return a ptr to the users name
449 ***************************************************************************/
450char *cgi_user_name(void)
451{
452 return(C_user);
453}
454
455/***************************************************************************
456return a ptr to the users password
457 ***************************************************************************/
458char *cgi_user_pass(void)
459{
460 return(C_pass);
461}
462
463/***************************************************************************
464handle a file download
465 ***************************************************************************/
466static void cgi_download(char *file)
467{
468 SMB_STRUCT_STAT st;
469 char buf[1024];
470 int fd, l, i;
471 char *p;
472 char *lang;
473
474 /* sanitise the filename */
475 for (i=0;file[i];i++) {
476 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
477 cgi_setup_error("404 File Not Found","",
478 "Illegal character in filename");
479 }
480 }
481
482 if (sys_stat(file, &st, false) != 0) {
483 cgi_setup_error("404 File Not Found","",
484 "The requested file was not found");
485 }
486
487 if (S_ISDIR(st.st_ex_mode))
488 {
489 snprintf(buf, sizeof(buf), "%s/index.html", file);
490 if (!file_exist_stat(buf, &st, false)
491 || !S_ISREG(st.st_ex_mode))
492 {
493 cgi_setup_error("404 File Not Found","",
494 "The requested file was not found");
495 }
496 }
497 else if (S_ISREG(st.st_ex_mode))
498 {
499 snprintf(buf, sizeof(buf), "%s", file);
500 }
501 else
502 {
503 cgi_setup_error("404 File Not Found","",
504 "The requested file was not found");
505 }
506
507 fd = web_open(buf,O_RDONLY,0);
508 if (fd == -1) {
509 cgi_setup_error("404 File Not Found","",
510 "The requested file was not found");
511 }
512 printf("HTTP/1.0 200 OK\r\n");
513 if ((p=strrchr_m(buf, '.'))) {
514 if (strcmp(p,".gif")==0) {
515 printf("Content-Type: image/gif\r\n");
516 } else if (strcmp(p,".jpg")==0) {
517 printf("Content-Type: image/jpeg\r\n");
518 } else if (strcmp(p,".png")==0) {
519 printf("Content-Type: image/png\r\n");
520 } else if (strcmp(p,".css")==0) {
521 printf("Content-Type: text/css\r\n");
522 } else if (strcmp(p,".txt")==0) {
523 printf("Content-Type: text/plain\r\n");
524 } else {
525 printf("Content-Type: text/html\r\n");
526 }
527 }
528 printf("Expires: %s\r\n",
529 http_timestring(talloc_tos(), time(NULL)+EXPIRY_TIME));
530
531 lang = lang_tdb_current();
532 if (lang) {
533 printf("Content-Language: %s\r\n", lang);
534 }
535
536 printf("Content-Length: %d\r\n\r\n", (int)st.st_ex_size);
537 while ((l=read(fd,buf,sizeof(buf)))>0) {
538 if (fwrite(buf, 1, l, stdout) != l) {
539 break;
540 }
541 }
542 close(fd);
543 exit(0);
544}
545
546
547
548/* return true if the char* contains ip addrs only. Used to avoid
549name lookup calls */
550
551static bool only_ipaddrs_in_list(const char **list)
552{
553 bool only_ip = true;
554
555 if (!list) {
556 return true;
557 }
558
559 for (; *list ; list++) {
560 /* factor out the special strings */
561 if (strequal(*list, "ALL") || strequal(*list, "FAIL") ||
562 strequal(*list, "EXCEPT")) {
563 continue;
564 }
565
566 if (!is_ipaddress(*list)) {
567 /*
568 * If we failed, make sure that it was not because
569 * the token was a network/netmask pair. Only
570 * network/netmask pairs have a '/' in them.
571 */
572 if ((strchr_m(*list, '/')) == NULL) {
573 only_ip = false;
574 DEBUG(3,("only_ipaddrs_in_list: list has "
575 "non-ip address (%s)\n",
576 *list));
577 break;
578 }
579 }
580 }
581
582 return only_ip;
583}
584
585/* return true if access should be allowed to a service for a socket */
586static bool check_access(int sock, const char **allow_list,
587 const char **deny_list)
588{
589 bool ret = false;
590 bool only_ip = false;
591 char addr[INET6_ADDRSTRLEN];
592
593 if ((!deny_list || *deny_list==0) && (!allow_list || *allow_list==0)) {
594 return true;
595 }
596
597 /* Bypass name resolution calls if the lists
598 * only contain IP addrs */
599 if (only_ipaddrs_in_list(allow_list) &&
600 only_ipaddrs_in_list(deny_list)) {
601 only_ip = true;
602 DEBUG (3, ("check_access: no hostnames "
603 "in host allow/deny list.\n"));
604 ret = allow_access(deny_list,
605 allow_list,
606 "",
607 get_peer_addr(sock,addr,sizeof(addr)));
608 } else {
609 DEBUG (3, ("check_access: hostnames in "
610 "host allow/deny list.\n"));
611 ret = allow_access(deny_list,
612 allow_list,
613 get_peer_name(sock,true),
614 get_peer_addr(sock,addr,sizeof(addr)));
615 }
616
617 if (ret) {
618 DEBUG(2,("Allowed connection from %s (%s)\n",
619 only_ip ? "" : get_peer_name(sock,true),
620 get_peer_addr(sock,addr,sizeof(addr))));
621 } else {
622 DEBUG(0,("Denied connection from %s (%s)\n",
623 only_ip ? "" : get_peer_name(sock,true),
624 get_peer_addr(sock,addr,sizeof(addr))));
625 }
626
627 return(ret);
628}
629
630/**
631 * @brief Setup the CGI framework.
632 *
633 * Setup the cgi framework, handling the possibility that this program
634 * is either run as a true CGI program with a gateway to a web server, or
635 * is itself a mini web server.
636 **/
637void cgi_setup(const char *rootdir, int auth_required)
638{
639 bool authenticated = False;
640 char line[1024];
641 char *url=NULL;
642 char *p;
643 char *lang;
644
645 if (chdir(rootdir)) {
646 cgi_setup_error("500 Server Error", "",
647 "chdir failed - the server is not configured correctly");
648 }
649
650 /* Handle the possibility we might be running as non-root */
651 sec_init();
652
653 if ((lang=getenv("HTTP_ACCEPT_LANGUAGE"))) {
654 /* if running as a cgi program */
655 web_set_lang(lang);
656 }
657
658 /* maybe we are running under a web server */
659 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
660 if (auth_required) {
661 cgi_web_auth();
662 }
663 return;
664 }
665
666 inetd_server = True;
667
668 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
669 cgi_setup_error("403 Forbidden", "",
670 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
671 }
672
673 /* we are a mini-web server. We need to read the request from stdin
674 and handle authentication etc */
675 while (fgets(line, sizeof(line)-1, stdin)) {
676 if (line[0] == '\r' || line[0] == '\n') break;
677 if (strnequal(line,"GET ", 4)) {
678 got_request = True;
679 url = SMB_STRDUP(&line[4]);
680 } else if (strnequal(line,"POST ", 5)) {
681 got_request = True;
682 request_post = 1;
683 url = SMB_STRDUP(&line[5]);
684 } else if (strnequal(line,"PUT ", 4)) {
685 got_request = True;
686 cgi_setup_error("400 Bad Request", "",
687 "This server does not accept PUT requests");
688 } else if (strnequal(line,"Authorization: ", 15)) {
689 authenticated = cgi_handle_authorization(&line[15]);
690 } else if (strnequal(line,"Content-Length: ", 16)) {
691 content_length = atoi(&line[16]);
692 } else if (strnequal(line,"Accept-Language: ", 17)) {
693 web_set_lang(&line[17]);
694 }
695 /* ignore all other requests! */
696 }
697
698 if (auth_required && !authenticated) {
699 cgi_auth_error();
700 }
701
702 if (!url) {
703 cgi_setup_error("400 Bad Request", "",
704 "You must specify a GET or POST request");
705 }
706
707 /* trim the URL */
708 if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
709 *p = 0;
710 }
711 while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
712 url[strlen(url)-1] = 0;
713 }
714
715 /* anything following a ? in the URL is part of the query string */
716 if ((p=strchr_m(url,'?'))) {
717 query_string = p+1;
718 *p = 0;
719 }
720
721 string_sub(url, "/swat/", "", 0);
722
723 if (url[0] != '/' && strstr(url,"..")==0) {
724 cgi_download(url);
725 }
726
727 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
728 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL)));
729 baseurl = "";
730 pathinfo = url+1;
731}
732
733
734/***************************************************************************
735return the current pages URL
736 ***************************************************************************/
737const char *cgi_baseurl(void)
738{
739 if (inetd_server) {
740 return baseurl;
741 }
742 return getenv("SCRIPT_NAME");
743}
744
745/***************************************************************************
746return the current pages path info
747 ***************************************************************************/
748const char *cgi_pathinfo(void)
749{
750 char *r;
751 if (inetd_server) {
752 return pathinfo;
753 }
754 r = getenv("PATH_INFO");
755 if (!r) return "";
756 if (*r == '/') r++;
757 return r;
758}
759
760/***************************************************************************
761return the hostname of the client
762 ***************************************************************************/
763const char *cgi_remote_host(void)
764{
765 if (inetd_server) {
766 return get_peer_name(1,False);
767 }
768 return getenv("REMOTE_HOST");
769}
770
771/***************************************************************************
772return the hostname of the client
773 ***************************************************************************/
774const char *cgi_remote_addr(void)
775{
776 if (inetd_server) {
777 char addr[INET6_ADDRSTRLEN];
778 get_peer_addr(1,addr,sizeof(addr));
779 return talloc_strdup(talloc_tos(), addr);
780 }
781 return getenv("REMOTE_ADDR");
782}
783
784
785/***************************************************************************
786return True if the request was a POST
787 ***************************************************************************/
788bool cgi_waspost(void)
789{
790 if (inetd_server) {
791 return request_post;
792 }
793 return strequal(getenv("REQUEST_METHOD"), "POST");
794}
Note: See TracBrowser for help on using the repository browser.