Added the security changes suggested by Andrew - become the
[kai/samba.git] / source / 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 2 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, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20
21 #include "includes.h"
22 #include "smb.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 #define CGI_LOGGING 0
30
31 #ifdef DEBUG_COMMENTS
32 extern void print_title(char *fmt, ...);
33 #endif
34
35 struct var {
36         char *name;
37         char *value;
38 };
39
40 static struct var variables[MAX_VARIABLES];
41 static int num_variables;
42 static int content_length;
43 static int request_post;
44 static char *query_string;
45 static char *baseurl;
46 static char *pathinfo;
47 static char *C_user;
48
49 static void unescape(char *buf)
50 {
51         char *p=buf;
52
53         while ((p=strchr(p,'+')))
54                 *p = ' ';
55
56         p = buf;
57
58         while (p && *p && (p=strchr(p,'%'))) {
59                 int c1 = p[1];
60                 int c2 = p[2];
61
62                 if (c1 >= '0' && c1 <= '9')
63                         c1 = c1 - '0';
64                 else if (c1 >= 'A' && c1 <= 'F')
65                         c1 = 10 + c1 - 'A';
66                 else if (c1 >= 'a' && c1 <= 'f')
67                         c1 = 10 + c1 - 'a';
68                 else {p++; continue;}
69
70                 if (c2 >= '0' && c2 <= '9')
71                         c2 = c2 - '0';
72                 else if (c2 >= 'A' && c2 <= 'F')
73                         c2 = 10 + c2 - 'A';
74                 else if (c2 >= 'a' && c2 <= 'f')
75                         c2 = 10 + c2 - 'a';
76                 else {p++; continue;}
77                         
78                 *p = (c1<<4) | c2;
79
80                 memcpy(p+1, p+3, strlen(p+3)+1);
81                 p++;
82         }
83 }
84
85
86 static char *grab_line(FILE *f, int *cl)
87 {
88         char *ret;
89         int i = 0;
90         int len = 1024;
91
92         ret = (char *)malloc(len);
93         if (!ret) return NULL;
94         
95
96         while ((*cl)) {
97                 int c = fgetc(f);
98                 (*cl)--;
99
100                 if (c == EOF) {
101                         (*cl) = 0;
102                         break;
103                 }
104                 
105                 if (c == '\r') continue;
106
107                 if (strchr("\n&", c)) break;
108
109                 ret[i++] = c;
110
111                 if (i == len-1) {
112                         char *ret2;
113                         ret2 = (char *)realloc(ret, len*2);
114                         if (!ret2) return ret;
115                         len *= 2;
116                         ret = ret2;
117                 }
118         }
119         
120
121         ret[i] = 0;
122         return ret;
123 }
124
125 /***************************************************************************
126   load all the variables passed to the CGI program. May have multiple variables
127   with the same name and the same or different values. Takes a file parameter
128   for simulating CGI invocation eg loading saved preferences.
129   ***************************************************************************/
130 void cgi_load_variables(FILE *f1)
131 {
132         FILE *f = f1;
133         static char *line;
134         char *p, *s, *tok;
135         int len;
136
137 #ifdef DEBUG_COMMENTS
138         char dummy[100]="";
139         print_title(dummy);
140         printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__);
141 #endif
142
143         if (!f1) {
144                 f = stdin;
145                 if (!content_length) {
146                         p = getenv("CONTENT_LENGTH");
147                         len = p?atoi(p):0;
148                 } else {
149                         len = content_length;
150                 }
151         } else {
152                 fseek(f, 0, SEEK_END);
153                 len = ftell(f);
154                 fseek(f, 0, SEEK_SET);
155         }
156
157
158         if (len > 0 && 
159             (f1 || request_post ||
160              ((s=getenv("REQUEST_METHOD")) && 
161               strcasecmp(s,"POST")==0))) {
162                 while (len && (line=grab_line(f, &len))) {
163                         p = strchr(line,'=');
164                         if (!p) continue;
165                         
166                         *p = 0;
167                         
168                         variables[num_variables].name = strdup(line);
169                         variables[num_variables].value = strdup(p+1);
170
171                         free(line);
172                         
173                         if (!variables[num_variables].name || 
174                             !variables[num_variables].value)
175                                 continue;
176
177                         unescape(variables[num_variables].value);
178                         unescape(variables[num_variables].name);
179
180 #ifdef DEBUG_COMMENTS
181                         printf("<!== POST var %s has value \"%s\"  ==>\n",
182                                variables[num_variables].name,
183                                variables[num_variables].value);
184 #endif
185                         
186                         num_variables++;
187                         if (num_variables == MAX_VARIABLES) break;
188                 }
189         }
190
191         if (f1) {
192 #ifdef DEBUG_COMMENTS
193                 printf("<!== End dump in cgi_load_variables() ==>\n"); 
194 #endif
195                 return;
196         }
197
198         fclose(stdin);
199
200         if ((s=query_string) || (s=getenv("QUERY_STRING"))) {
201                 for (tok=strtok(s,"&;");tok;tok=strtok(NULL,"&;")) {
202                         p = strchr(tok,'=');
203                         if (!p) continue;
204                         
205                         *p = 0;
206                         
207                         variables[num_variables].name = strdup(tok);
208                         variables[num_variables].value = strdup(p+1);
209
210                         if (!variables[num_variables].name || 
211                             !variables[num_variables].value)
212                                 continue;
213
214                         unescape(variables[num_variables].value);
215                         unescape(variables[num_variables].name);
216
217 #ifdef DEBUG_COMMENTS
218                         printf("<!== Commandline var %s has value \"%s\"  ==>\n",
219                                variables[num_variables].name,
220                                variables[num_variables].value);
221 #endif                                          
222                         num_variables++;
223                         if (num_variables == MAX_VARIABLES) break;
224                 }
225
226         }
227 #ifdef DEBUG_COMMENTS
228         printf("<!== End dump in cgi_load_variables() ==>\n");   
229 #endif
230 }
231
232
233 /***************************************************************************
234   find a variable passed via CGI
235   Doesn't quite do what you think in the case of POST text variables, because
236   if they exist they might have a value of "" or even " ", depending on the 
237   browser. Also doesn't allow for variables[] containing multiple variables
238   with the same name and the same or different values.
239   ***************************************************************************/
240 char *cgi_variable(char *name)
241 {
242         int i;
243
244         for (i=0;i<num_variables;i++)
245                 if (strcmp(variables[i].name, name) == 0)
246                         return variables[i].value;
247         return NULL;
248 }
249
250 /***************************************************************************
251 tell a browser about a fatal error in the http processing
252   ***************************************************************************/
253 static void cgi_setup_error(char *err, char *header, char *info)
254 {
255         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", err, header, err, err, info);
256         exit(0);
257 }
258
259
260 /***************************************************************************
261 decode a base64 string in-place - simple and slow algorithm
262   ***************************************************************************/
263 static void base64_decode(char *s)
264 {
265         char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
266         int bit_offset, byte_offset, idx, i, n;
267         unsigned char *d = (unsigned char *)s;
268         char *p;
269
270         n=i=0;
271
272         while (*s && (p=strchr(b64,*s))) {
273                 idx = (int)(p - b64);
274                 byte_offset = (i*6)/8;
275                 bit_offset = (i*6)%8;
276                 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
277                 if (bit_offset < 3) {
278                         d[byte_offset] |= (idx << (2-bit_offset));
279                         n = byte_offset+1;
280                 } else {
281                         d[byte_offset] |= (idx >> (bit_offset-2));
282                         d[byte_offset+1] = 0;
283                         d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
284                         n = byte_offset+2;
285                 }
286                 s++; i++;
287         }
288         /* null terminate */
289         d[n] = 0;
290 }
291
292
293 /***************************************************************************
294 handle a http authentication line
295   ***************************************************************************/
296 static BOOL cgi_handle_authorization(char *line)
297 {
298         char *p, *user, *user_pass;
299         struct passwd *pass = NULL;
300         int ret = False;
301
302         if (strncasecmp(line,"Basic ", 6)) {
303                 cgi_setup_error("401 Bad Authorization", "", 
304                                 "Only basic authorization is understood");
305                 return False;
306         }
307         line += 6;
308         while (line[0] == ' ') line++;
309         base64_decode(line);
310         if (!(p=strchr(line,':'))) {
311                 /*
312                  * Always give the same error so a cracker
313                  * cannot tell why we fail.
314                  */
315                 cgi_setup_error("401 Bad Authorization", "", 
316                                 "username/password must be supplied");
317                 return False;
318         }
319         *p = 0;
320         user = line;
321         user_pass = p+1;
322
323         /*
324          * Try and get the user from the UNIX password file.
325          */
326
327         if(!(pass = Get_Pwnam(user,False))) {
328                 /*
329                  * Always give the same error so a cracker
330                  * cannot tell why we fail.
331                  */
332                 cgi_setup_error("401 Bad Authorization", "",
333                                 "username/password must be supplied");
334                 return False;
335         }
336
337         /*
338          * Validate the password they have given.
339          */
340
341         if((ret = pass_check(user, user_pass, strlen(user_pass), NULL, NULL)) == True) {
342
343                 /*
344                  * Password was ok.
345                  */
346
347                 if(pass->pw_uid != 0) {
348                         /*
349                          * We have not authenticated as root,
350                          * become the user *permanently*.
351                          */
352                         if(!become_user_permanently(pass->pw_uid, pass->pw_gid)) {
353                                 /*
354                                  * Always give the same error so a cracker
355                                  * cannot tell why we fail.
356                                  */
357                                 cgi_setup_error("401 Bad Authorization", "",
358                         "username/password must be supplied");
359                         return False;
360                         }
361
362                         /*
363                          * On exit from here we are the authenticated
364                          * user - no way back.
365                          */
366                 }
367
368                 /* Save the users name */
369                 C_user = strdup(user);
370         }
371
372         return ret;
373 }
374
375 /***************************************************************************
376 is this root?
377   ***************************************************************************/
378 BOOL am_root(void)
379 {
380         if (geteuid() == 0) {
381                 return( True);
382         } else {
383                 return( False);
384         }
385 }
386
387 /***************************************************************************
388 return a ptr to the users name
389   ***************************************************************************/
390 char *get_user_name(void)
391 {
392         return(C_user);
393 }
394
395
396 /***************************************************************************
397 handle a file download
398   ***************************************************************************/
399 static void cgi_download(char *file)
400 {
401         SMB_STRUCT_STAT st;
402         char buf[1024];
403         int fd, l, i;
404         char *p;
405
406         /* sanitise the filename */
407         for (i=0;file[i];i++) {
408                 if (!isalnum((int)file[i]) && !strchr("/.-_", file[i])) {
409                         cgi_setup_error("404 File Not Found","",
410                                         "Illegal character in filename");
411                 }
412         }
413
414         if (!file_exist(file, &st)) {
415                 cgi_setup_error("404 File Not Found","",
416                                 "The requested file was not found");
417         }
418         fd = open(file,O_RDONLY);
419         if (fd == -1) {
420                 cgi_setup_error("404 File Not Found","",
421                                 "The requested file was not found");
422         }
423         printf("HTTP/1.0 200 OK\r\n");
424         if ((p=strrchr(file,'.'))) {
425                 if (strcmp(p,".gif")==0) {
426                         printf("Content-Type: image/gif\r\n");
427                 } else if (strcmp(p,".jpg")==0) {
428                         printf("Content-Type: image/jpeg\r\n");
429                 } else {
430                         printf("Content-Type: text/html\r\n");
431                 }
432         }
433         printf("Expires: %s\r\n", http_timestring(time(NULL)+EXPIRY_TIME));
434
435         printf("Content-Length: %d\r\n\r\n", (int)st.st_size);
436         while ((l=read(fd,buf,sizeof(buf)))>0) {
437                 fwrite(buf, 1, l, stdout);
438         }
439         close(fd);
440         exit(0);
441 }
442
443
444 /***************************************************************************
445 setup the cgi framework, handling the possability that this program is either
446 run as a true cgi program by a web browser or is itself a mini web server
447   ***************************************************************************/
448 void cgi_setup(char *rootdir, int auth_required)
449 {
450         BOOL authenticated = False;
451         char line[1024];
452         char *url=NULL;
453         char *p;
454 #if CGI_LOGGING
455         FILE *f;
456 #endif
457
458         if (chdir(rootdir)) {
459                 cgi_setup_error("400 Server Error", "",
460                                 "chdir failed - the server is not configured correctly");
461         }
462
463         if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
464
465                 char *x;
466
467                 /* Save the users name if available */
468                 if ((x = getenv("REMOTE_USER"))) {
469                         C_user = strdup(x);
470                 } else {
471                         C_user = "";
472                 }
473
474                 /* assume we are running under a real web server */
475                 return;
476         }
477
478 #if CGI_LOGGING
479         f = fopen("/tmp/cgi.log", "a");
480         if (f) fprintf(f,"\n[Date: %s   %s (%s)]\n", 
481                        http_timestring(time(NULL)),
482                        client_name(1), client_addr(1));
483 #endif
484
485         /* we are a mini-web server. We need to read the request from stdin
486            and handle authentication etc */
487         while (fgets(line, sizeof(line)-1, stdin)) {
488 #if CGI_LOGGING
489                 if (f) fputs(line, f);
490 #endif
491                 if (line[0] == '\r' || line[0] == '\n') break;
492                 if (strncasecmp(line,"GET ", 4)==0) {
493                         url = strdup(&line[4]);
494                 } else if (strncasecmp(line,"POST ", 5)==0) {
495                         request_post = 1;
496                         url = strdup(&line[5]);
497                 } else if (strncasecmp(line,"PUT ", 4)==0) {
498                         cgi_setup_error("400 Bad Request", "",
499                                         "This server does not accept PUT requests");
500                 } else if (strncasecmp(line,"Authorization: ", 15)==0) {
501                         authenticated = cgi_handle_authorization(&line[15]);
502                 } else if (strncasecmp(line,"Content-Length: ", 16)==0) {
503                         content_length = atoi(&line[16]);
504                 }
505                 /* ignore all other requests! */
506         }
507 #if CGI_LOGGING
508         if (f) fclose(f);
509 #endif
510
511         if (auth_required && !authenticated) {
512                 cgi_setup_error("401 Authorization Required", 
513                                 "WWW-Authenticate: Basic realm=\"root\"\r\n",
514                                 "You must be authenticated to use this service");
515         }
516
517         if (!url) {
518                 cgi_setup_error("400 Bad Request", "",
519                                 "You must specify a GET or POST request");
520         }
521
522         /* trim the URL */
523         if ((p = strchr(url,' ')) || (p=strchr(url,'\t'))) {
524                 *p = 0;
525         }
526         while (*url && strchr("\r\n",url[strlen(url)-1])) {
527                 url[strlen(url)-1] = 0;
528         }
529
530         /* anything following a ? in the URL is part of the query string */
531         if ((p=strchr(url,'?'))) {
532                 query_string = p+1;
533                 *p = 0;
534         }
535
536         string_sub(url, "/swat/", "");
537
538         if (strstr(url,"..")==0 && file_exist(url, NULL)) {
539                 cgi_download(url);
540         }
541
542         printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
543         printf("Date: %s\r\n", http_timestring(time(NULL)));
544         baseurl = "";
545         pathinfo = url+1;
546 }
547
548
549 /***************************************************************************
550 return the current pages URL
551   ***************************************************************************/
552 char *cgi_baseurl(void)
553 {
554         if (baseurl) {
555                 return baseurl;
556         }
557         return getenv("SCRIPT_NAME");
558 }
559
560 /***************************************************************************
561 return the current pages path info
562   ***************************************************************************/
563 char *cgi_pathinfo(void)
564 {
565         char *r;
566         if (pathinfo) {
567                 return pathinfo;
568         }
569         r = getenv("PATH_INFO");
570         if (!r) return "";
571         if (*r == '/') r++;
572         return r;
573 }
574
575 /***************************************************************************
576 return the hostname of the client
577   ***************************************************************************/
578 char *cgi_remote_host(void)
579 {
580         if (baseurl) {
581                 return client_name(1);
582         }
583         return getenv("REMOTE_HOST");
584 }
585
586 /***************************************************************************
587 return the hostname of the client
588   ***************************************************************************/
589 char *cgi_remote_addr(void)
590 {
591         if (baseurl) {
592                 return client_addr(1);
593         }
594         return getenv("REMOTE_ADDR");
595 }
596
597
598 /***************************************************************************
599 return True if the request was a POST
600   ***************************************************************************/
601 BOOL cgi_waspost(void)
602 {
603         if (baseurl) {
604                 return request_post;
605         }
606         return strequal(getenv("REQUEST_METHOD"), "POST");
607 }