s3-auth: use auth.h where needed.
[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 "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
27 #define MAX_VARIABLES 10000
28
29 /* set the expiry on fixed pages */
30 #define EXPIRY_TIME (60*60*24*7)
31
32 #ifdef DEBUG_COMMENTS
33 extern void print_title(char *fmt, ...);
34 #endif
35
36 struct cgi_var {
37         char *name;
38         char *value;
39 };
40
41 static struct cgi_var variables[MAX_VARIABLES];
42 static int num_variables;
43 static int content_length;
44 static int request_post;
45 static char *query_string;
46 static const char *baseurl;
47 static char *pathinfo;
48 static char *C_user;
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);
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);
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_tos(), user);
322         if (!pwd) {
323                 printf("%sCannot find user %s<br>%s\n", head, user, tail);
324                 exit(0);
325         }
326
327         setuid(0);
328         setuid(pwd->pw_uid);
329         if (geteuid() != pwd->pw_uid || getuid() != pwd->pw_uid) {
330                 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n", 
331                        head, user, (int)geteuid(), (int)getuid(), tail);
332                 exit(0);
333         }
334         TALLOC_FREE(pwd);
335 }
336
337
338 /***************************************************************************
339 handle a http authentication line
340   ***************************************************************************/
341 static bool cgi_handle_authorization(char *line)
342 {
343         char *p;
344         fstring user, user_pass;
345         struct passwd *pass = NULL;
346         const char *rhost;
347         char addr[INET6_ADDRSTRLEN];
348
349         if (!strnequal(line,"Basic ", 6)) {
350                 goto err;
351         }
352         line += 6;
353         while (line[0] == ' ') line++;
354         base64_decode_inplace(line);
355         if (!(p=strchr_m(line,':'))) {
356                 /*
357                  * Always give the same error so a cracker
358                  * cannot tell why we fail.
359                  */
360                 goto err;
361         }
362         *p = 0;
363
364         convert_string(CH_UTF8, CH_UNIX, 
365                        line, -1, 
366                        user, sizeof(user));
367
368         convert_string(CH_UTF8, CH_UNIX, 
369                        p+1, -1, 
370                        user_pass, sizeof(user_pass));
371
372         /*
373          * Try and get the user from the UNIX password file.
374          */
375
376         pass = Get_Pwnam_alloc(talloc_tos(), user);
377
378         rhost = client_name(1);
379         if (strequal(rhost,"UNKNOWN"))
380                 rhost = client_addr(1, addr, sizeof(addr));
381
382         /*
383          * Validate the password they have given.
384          */
385
386         if NT_STATUS_IS_OK(pass_check(pass, user, rhost, user_pass, false)) {
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                         TALLOC_FREE(pass);
400                         return True;
401                 }
402         }
403
404 err:
405         cgi_setup_error("401 Bad Authorization", 
406                         "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
407                         "username or password incorrect");
408
409         TALLOC_FREE(pass);
410         return False;
411 }
412
413 /***************************************************************************
414 is this root?
415   ***************************************************************************/
416 bool am_root(void)
417 {
418         if (geteuid() == 0) {
419                 return( True);
420         } else {
421                 return( False);
422         }
423 }
424
425 /***************************************************************************
426 return a ptr to the users name
427   ***************************************************************************/
428 char *cgi_user_name(void)
429 {
430         return(C_user);
431 }
432
433
434 /***************************************************************************
435 handle a file download
436   ***************************************************************************/
437 static void cgi_download(char *file)
438 {
439         SMB_STRUCT_STAT st;
440         char buf[1024];
441         int fd, l, i;
442         char *p;
443         char *lang;
444
445         /* sanitise the filename */
446         for (i=0;file[i];i++) {
447                 if (!isalnum((int)file[i]) && !strchr_m("/.-_", file[i])) {
448                         cgi_setup_error("404 File Not Found","",
449                                         "Illegal character in filename");
450                 }
451         }
452
453         if (sys_stat(file, &st, false) != 0)    {
454                 cgi_setup_error("404 File Not Found","",
455                                 "The requested file was not found");
456         }
457
458         if (S_ISDIR(st.st_ex_mode))
459         {
460                 snprintf(buf, sizeof(buf), "%s/index.html", file);
461                 if (!file_exist_stat(buf, &st, false)
462                     || !S_ISREG(st.st_ex_mode))
463                 {
464                         cgi_setup_error("404 File Not Found","",
465                                         "The requested file was not found");
466                 }
467         }
468         else if (S_ISREG(st.st_ex_mode))
469         {
470                 snprintf(buf, sizeof(buf), "%s", file);
471         }
472         else
473         {
474                 cgi_setup_error("404 File Not Found","",
475                                 "The requested file was not found");
476         }
477
478         fd = web_open(buf,O_RDONLY,0);
479         if (fd == -1) {
480                 cgi_setup_error("404 File Not Found","",
481                                 "The requested file was not found");
482         }
483         printf("HTTP/1.0 200 OK\r\n");
484         if ((p=strrchr_m(buf, '.'))) {
485                 if (strcmp(p,".gif")==0) {
486                         printf("Content-Type: image/gif\r\n");
487                 } else if (strcmp(p,".jpg")==0) {
488                         printf("Content-Type: image/jpeg\r\n");
489                 } else if (strcmp(p,".png")==0) {
490                         printf("Content-Type: image/png\r\n");
491                 } else if (strcmp(p,".css")==0) {
492                         printf("Content-Type: text/css\r\n");
493                 } else if (strcmp(p,".txt")==0) {
494                         printf("Content-Type: text/plain\r\n");
495                 } else {
496                         printf("Content-Type: text/html\r\n");
497                 }
498         }
499         printf("Expires: %s\r\n", 
500                    http_timestring(talloc_tos(), time(NULL)+EXPIRY_TIME));
501
502         lang = lang_tdb_current();
503         if (lang) {
504                 printf("Content-Language: %s\r\n", lang);
505         }
506
507         printf("Content-Length: %d\r\n\r\n", (int)st.st_ex_size);
508         while ((l=read(fd,buf,sizeof(buf)))>0) {
509                 if (fwrite(buf, 1, l, stdout) != l) {
510                         break;
511                 }
512         }
513         close(fd);
514         exit(0);
515 }
516
517
518
519 /* return true if the char* contains ip addrs only.  Used to avoid
520 name lookup calls */
521
522 static bool only_ipaddrs_in_list(const char **list)
523 {
524         bool only_ip = true;
525
526         if (!list) {
527                 return true;
528         }
529
530         for (; *list ; list++) {
531                 /* factor out the special strings */
532                 if (strequal(*list, "ALL") || strequal(*list, "FAIL") ||
533                     strequal(*list, "EXCEPT")) {
534                         continue;
535                 }
536
537                 if (!is_ipaddress(*list)) {
538                         /*
539                          * If we failed, make sure that it was not because
540                          * the token was a network/netmask pair. Only
541                          * network/netmask pairs have a '/' in them.
542                          */
543                         if ((strchr_m(*list, '/')) == NULL) {
544                                 only_ip = false;
545                                 DEBUG(3,("only_ipaddrs_in_list: list has "
546                                         "non-ip address (%s)\n",
547                                         *list));
548                                 break;
549                         }
550                 }
551         }
552
553         return only_ip;
554 }
555
556 /* return true if access should be allowed to a service for a socket */
557 static bool check_access(int sock, const char **allow_list,
558                          const char **deny_list)
559 {
560         bool ret = false;
561         bool only_ip = false;
562         char addr[INET6_ADDRSTRLEN];
563
564         if ((!deny_list || *deny_list==0) && (!allow_list || *allow_list==0)) {
565                 return true;
566         }
567
568         /* Bypass name resolution calls if the lists
569          * only contain IP addrs */
570         if (only_ipaddrs_in_list(allow_list) &&
571             only_ipaddrs_in_list(deny_list)) {
572                 only_ip = true;
573                 DEBUG (3, ("check_access: no hostnames "
574                            "in host allow/deny list.\n"));
575                 ret = allow_access(deny_list,
576                                    allow_list,
577                                    "",
578                                    get_peer_addr(sock,addr,sizeof(addr)));
579         } else {
580                 DEBUG (3, ("check_access: hostnames in "
581                            "host allow/deny list.\n"));
582                 ret = allow_access(deny_list,
583                                    allow_list,
584                                    get_peer_name(sock,true),
585                                    get_peer_addr(sock,addr,sizeof(addr)));
586         }
587
588         if (ret) {
589                 DEBUG(2,("Allowed connection from %s (%s)\n",
590                          only_ip ? "" : get_peer_name(sock,true),
591                          get_peer_addr(sock,addr,sizeof(addr))));
592         } else {
593                 DEBUG(0,("Denied connection from %s (%s)\n",
594                          only_ip ? "" : get_peer_name(sock,true),
595                          get_peer_addr(sock,addr,sizeof(addr))));
596         }
597
598         return(ret);
599 }
600
601 /**
602  * @brief Setup the CGI framework.
603  *
604  * Setup the cgi framework, handling the possibility that this program
605  * is either run as a true CGI program with a gateway to a web server, or
606  * is itself a mini web server.
607  **/
608 void cgi_setup(const char *rootdir, int auth_required)
609 {
610         bool authenticated = False;
611         char line[1024];
612         char *url=NULL;
613         char *p;
614         char *lang;
615
616         if (chdir(rootdir)) {
617                 cgi_setup_error("500 Server Error", "",
618                                 "chdir failed - the server is not configured correctly");
619         }
620
621         /* Handle the possibility we might be running as non-root */
622         sec_init();
623
624         if ((lang=getenv("HTTP_ACCEPT_LANGUAGE"))) {
625                 /* if running as a cgi program */
626                 web_set_lang(lang);
627         }
628
629         /* maybe we are running under a web server */
630         if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
631                 if (auth_required) {
632                         cgi_web_auth();
633                 }
634                 return;
635         }
636
637         inetd_server = True;
638
639         if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
640                 cgi_setup_error("403 Forbidden", "",
641                                 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
642         }
643
644         /* we are a mini-web server. We need to read the request from stdin
645            and handle authentication etc */
646         while (fgets(line, sizeof(line)-1, stdin)) {
647                 if (line[0] == '\r' || line[0] == '\n') break;
648                 if (strnequal(line,"GET ", 4)) {
649                         got_request = True;
650                         url = SMB_STRDUP(&line[4]);
651                 } else if (strnequal(line,"POST ", 5)) {
652                         got_request = True;
653                         request_post = 1;
654                         url = SMB_STRDUP(&line[5]);
655                 } else if (strnequal(line,"PUT ", 4)) {
656                         got_request = True;
657                         cgi_setup_error("400 Bad Request", "",
658                                         "This server does not accept PUT requests");
659                 } else if (strnequal(line,"Authorization: ", 15)) {
660                         authenticated = cgi_handle_authorization(&line[15]);
661                 } else if (strnequal(line,"Content-Length: ", 16)) {
662                         content_length = atoi(&line[16]);
663                 } else if (strnequal(line,"Accept-Language: ", 17)) {
664                         web_set_lang(&line[17]);
665                 }
666                 /* ignore all other requests! */
667         }
668
669         if (auth_required && !authenticated) {
670                 cgi_auth_error();
671         }
672
673         if (!url) {
674                 cgi_setup_error("400 Bad Request", "",
675                                 "You must specify a GET or POST request");
676         }
677
678         /* trim the URL */
679         if ((p = strchr_m(url,' ')) || (p=strchr_m(url,'\t'))) {
680                 *p = 0;
681         }
682         while (*url && strchr_m("\r\n",url[strlen(url)-1])) {
683                 url[strlen(url)-1] = 0;
684         }
685
686         /* anything following a ? in the URL is part of the query string */
687         if ((p=strchr_m(url,'?'))) {
688                 query_string = p+1;
689                 *p = 0;
690         }
691
692         string_sub(url, "/swat/", "", 0);
693
694         if (url[0] != '/' && strstr(url,"..")==0) {
695                 cgi_download(url);
696         }
697
698         printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
699         printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL)));
700         baseurl = "";
701         pathinfo = url+1;
702 }
703
704
705 /***************************************************************************
706 return the current pages URL
707   ***************************************************************************/
708 const char *cgi_baseurl(void)
709 {
710         if (inetd_server) {
711                 return baseurl;
712         }
713         return getenv("SCRIPT_NAME");
714 }
715
716 /***************************************************************************
717 return the current pages path info
718   ***************************************************************************/
719 const char *cgi_pathinfo(void)
720 {
721         char *r;
722         if (inetd_server) {
723                 return pathinfo;
724         }
725         r = getenv("PATH_INFO");
726         if (!r) return "";
727         if (*r == '/') r++;
728         return r;
729 }
730
731 /***************************************************************************
732 return the hostname of the client
733   ***************************************************************************/
734 const char *cgi_remote_host(void)
735 {
736         if (inetd_server) {
737                 return get_peer_name(1,False);
738         }
739         return getenv("REMOTE_HOST");
740 }
741
742 /***************************************************************************
743 return the hostname of the client
744   ***************************************************************************/
745 const char *cgi_remote_addr(void)
746 {
747         if (inetd_server) {
748                 char addr[INET6_ADDRSTRLEN];
749                 get_peer_addr(1,addr,sizeof(addr));
750                 return talloc_strdup(talloc_tos(), addr);
751         }
752         return getenv("REMOTE_ADDR");
753 }
754
755
756 /***************************************************************************
757 return True if the request was a POST
758   ***************************************************************************/
759 bool cgi_waspost(void)
760 {
761         if (inetd_server) {
762                 return request_post;
763         }
764         return strequal(getenv("REQUEST_METHOD"), "POST");
765 }