source: branches/samba-3.3.x/source/web/cgi.c@ 614

Last change on this file since 614 was 614, checked in by Herwig Bauernfeind, 14 years ago

Update Samba 3.3 to 3.3.16 (security update)

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