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