2 some simple CGI helper routines
3 Copyright (C) Andrew Tridgell 1997-1998
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.
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.
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/>.
21 #include "system/passwd.h"
22 #include "system/filesys.h"
23 #include "web/swat_proto.h"
24 #include "intl/lang_tdb.h"
27 #include "../lib/util/setid.h"
29 #define MAX_VARIABLES 10000
31 /* set the expiry on fixed pages */
32 #define EXPIRY_TIME (60*60*24*7)
35 extern void print_title(char *fmt
, ...);
43 static struct cgi_var variables
[MAX_VARIABLES
];
44 static int num_variables
;
45 static int content_length
;
46 static int request_post
;
47 static char *query_string
;
48 static const char *baseurl
;
49 static char *pathinfo
;
52 static bool inetd_server
;
53 static bool got_request
;
55 static char *grab_line(FILE *f
, int *cl
)
66 if (len
== 0) len
= 1024;
68 ret2
= (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret
, len
);
69 if (!ret2
) return ret
;
81 if (c
== '\r') continue;
83 if (strchr_m("\n&", c
)) break;
96 URL encoded strings can have a '+', which should be replaced with a space
98 (This was in rfc1738_unescape(), but that broke the squid helper)
101 static void plus_to_space_unescape(char *buf
)
105 while ((p
=strchr_m(p
,'+')))
109 /***************************************************************************
110 load all the variables passed to the CGI program. May have multiple variables
111 with the same name and the same or different values. Takes a file parameter
112 for simulating CGI invocation eg loading saved preferences.
113 ***************************************************************************/
114 void cgi_load_variables(void)
121 #ifdef DEBUG_COMMENTS
124 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__
);
127 if (!content_length
) {
128 p
= getenv("CONTENT_LENGTH");
131 len
= content_length
;
137 ((s
=getenv("REQUEST_METHOD")) &&
138 strequal(s
,"POST")))) {
139 while (len
&& (line
=grab_line(f
, &len
))) {
140 p
= strchr_m(line
,'=');
145 variables
[num_variables
].name
= SMB_STRDUP(line
);
146 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
150 if (!variables
[num_variables
].name
||
151 !variables
[num_variables
].value
)
154 plus_to_space_unescape(variables
[num_variables
].value
);
155 rfc1738_unescape(variables
[num_variables
].value
);
156 plus_to_space_unescape(variables
[num_variables
].name
);
157 rfc1738_unescape(variables
[num_variables
].name
);
159 #ifdef DEBUG_COMMENTS
160 printf("<!== POST var %s has value \"%s\" ==>\n",
161 variables
[num_variables
].name
,
162 variables
[num_variables
].value
);
166 if (num_variables
== MAX_VARIABLES
) break;
171 open("/dev/null", O_RDWR
);
173 if ((s
=query_string
) || (s
=getenv("QUERY_STRING"))) {
175 for (tok
=strtok_r(s
, "&;", &saveptr
); tok
;
176 tok
=strtok_r(NULL
, "&;", &saveptr
)) {
177 p
= strchr_m(tok
,'=');
182 variables
[num_variables
].name
= SMB_STRDUP(tok
);
183 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
185 if (!variables
[num_variables
].name
||
186 !variables
[num_variables
].value
)
189 plus_to_space_unescape(variables
[num_variables
].value
);
190 rfc1738_unescape(variables
[num_variables
].value
);
191 plus_to_space_unescape(variables
[num_variables
].name
);
192 rfc1738_unescape(variables
[num_variables
].name
);
194 #ifdef DEBUG_COMMENTS
195 printf("<!== Commandline var %s has value \"%s\" ==>\n",
196 variables
[num_variables
].name
,
197 variables
[num_variables
].value
);
200 if (num_variables
== MAX_VARIABLES
) break;
204 #ifdef DEBUG_COMMENTS
205 printf("<!== End dump in cgi_load_variables() ==>\n");
208 /* variables from the client are in UTF-8 - convert them
209 to our internal unix charset before use */
210 for (i
=0;i
<num_variables
;i
++) {
211 TALLOC_CTX
*frame
= talloc_stackframe();
215 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
216 variables
[i
].name
, strlen(variables
[i
].name
),
218 SAFE_FREE(variables
[i
].name
);
219 variables
[i
].name
= SMB_STRDUP(dest
? dest
: "");
222 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
223 variables
[i
].value
, strlen(variables
[i
].value
),
225 SAFE_FREE(variables
[i
].value
);
226 variables
[i
].value
= SMB_STRDUP(dest
? dest
: "");
232 /***************************************************************************
233 find a variable passed via CGI
234 Doesn't quite do what you think in the case of POST text variables, because
235 if they exist they might have a value of "" or even " ", depending on the
236 browser. Also doesn't allow for variables[] containing multiple variables
237 with the same name and the same or different values.
238 ***************************************************************************/
240 const char *cgi_variable(const char *name
)
244 for (i
=0;i
<num_variables
;i
++)
245 if (strcmp(variables
[i
].name
, name
) == 0)
246 return variables
[i
].value
;
250 /***************************************************************************
251 Version of the above that can't return a NULL pointer.
252 ***************************************************************************/
254 const char *cgi_variable_nonull(const char *name
)
256 const char *var
= cgi_variable(name
);
264 /***************************************************************************
265 tell a browser about a fatal error in the http processing
266 ***************************************************************************/
267 static void cgi_setup_error(const char *err
, const char *header
, const char *info
)
270 /* damn browsers don't like getting cut off before they give a request */
272 while (fgets(line
, sizeof(line
)-1, stdin
)) {
273 if (strnequal(line
,"GET ", 4) ||
274 strnequal(line
,"POST ", 5) ||
275 strnequal(line
,"PUT ", 4)) {
281 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
);
288 /***************************************************************************
289 tell a browser about a fatal authentication error
290 ***************************************************************************/
291 static void cgi_auth_error(void)
294 cgi_setup_error("401 Authorization Required",
295 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
296 "You must be authenticated to use this service");
298 printf("Content-Type: text/html\r\n");
300 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
301 printf("<BODY><H1>Installation Error</H1>\n");
302 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
303 printf("</BODY></HTML>\r\n");
308 /***************************************************************************
309 authenticate when we are running as a CGI
310 ***************************************************************************/
311 static void cgi_web_auth(void)
313 const char *user
= getenv("REMOTE_USER");
315 const char *head
= "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
316 const char *tail
= "</BODY></HTML>\r\n";
319 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
324 pwd
= Get_Pwnam_alloc(talloc_tos(), user
);
326 printf("%sCannot find user %s<br>%s\n", head
, user
, tail
);
330 C_user
= SMB_STRDUP(user
);
332 if (!samba_setuid(0)) {
333 C_pass
= secrets_fetch_generic("root", "SWAT");
334 if (C_pass
== NULL
) {
335 char *tmp_pass
= NULL
;
336 tmp_pass
= generate_random_password(talloc_tos(),
338 if (tmp_pass
== NULL
) {
339 printf("%sFailed to create random nonce for "
340 "SWAT session\n<br>%s\n", head
, tail
);
343 secrets_store_generic("root", "SWAT", tmp_pass
);
344 C_pass
= SMB_STRDUP(tmp_pass
);
345 TALLOC_FREE(tmp_pass
);
348 samba_setuid(pwd
->pw_uid
);
349 if (geteuid() != pwd
->pw_uid
|| getuid() != pwd
->pw_uid
) {
350 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
351 head
, user
, (int)geteuid(), (int)getuid(), tail
);
358 /***************************************************************************
359 handle a http authentication line
360 ***************************************************************************/
361 static bool cgi_handle_authorization(char *line
)
364 fstring user
, user_pass
;
365 struct passwd
*pass
= NULL
;
367 char addr
[INET6_ADDRSTRLEN
];
370 if (!strnequal(line
,"Basic ", 6)) {
374 while (line
[0] == ' ') line
++;
375 base64_decode_inplace(line
);
376 if (!(p
=strchr_m(line
,':'))) {
378 * Always give the same error so a cracker
379 * cannot tell why we fail.
385 if (!convert_string(CH_UTF8
, CH_UNIX
,
387 user
, sizeof(user
), &size
)) {
391 if (!convert_string(CH_UTF8
, CH_UNIX
,
393 user_pass
, sizeof(user_pass
), &size
)) {
398 * Try and get the user from the UNIX password file.
401 pass
= Get_Pwnam_alloc(talloc_tos(), user
);
403 rhost
= client_name(1);
404 if (strequal(rhost
,"UNKNOWN"))
405 rhost
= client_addr(1, addr
, sizeof(addr
));
408 * Validate the password they have given.
411 if NT_STATUS_IS_OK(pass_check(pass
, user
, rhost
, user_pass
, false)) {
417 if ( initgroups(pass
->pw_name
, pass
->pw_gid
) != 0 )
420 become_user_permanently(pass
->pw_uid
, pass
->pw_gid
);
422 /* Save the users name */
423 C_user
= SMB_STRDUP(user
);
424 C_pass
= SMB_STRDUP(user_pass
);
431 cgi_setup_error("401 Bad Authorization",
432 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
433 "username or password incorrect");
439 /***************************************************************************
441 ***************************************************************************/
444 if (geteuid() == 0) {
451 /***************************************************************************
452 return a ptr to the users name
453 ***************************************************************************/
454 char *cgi_user_name(void)
459 /***************************************************************************
460 return a ptr to the users password
461 ***************************************************************************/
462 char *cgi_user_pass(void)
467 /***************************************************************************
468 handle a file download
469 ***************************************************************************/
470 static void cgi_download(char *file
)
478 /* sanitise the filename */
479 for (i
=0;file
[i
];i
++) {
480 if (!isalnum((int)file
[i
]) && !strchr_m("/.-_", file
[i
])) {
481 cgi_setup_error("404 File Not Found","",
482 "Illegal character in filename");
486 if (sys_stat(file
, &st
, false) != 0) {
487 cgi_setup_error("404 File Not Found","",
488 "The requested file was not found");
491 if (S_ISDIR(st
.st_ex_mode
))
493 snprintf(buf
, sizeof(buf
), "%s/index.html", file
);
494 if (!file_exist_stat(buf
, &st
, false)
495 || !S_ISREG(st
.st_ex_mode
))
497 cgi_setup_error("404 File Not Found","",
498 "The requested file was not found");
501 else if (S_ISREG(st
.st_ex_mode
))
503 snprintf(buf
, sizeof(buf
), "%s", file
);
507 cgi_setup_error("404 File Not Found","",
508 "The requested file was not found");
511 fd
= web_open(buf
,O_RDONLY
,0);
513 cgi_setup_error("404 File Not Found","",
514 "The requested file was not found");
516 printf("HTTP/1.0 200 OK\r\n");
517 if ((p
=strrchr_m(buf
, '.'))) {
518 if (strcmp(p
,".gif")==0) {
519 printf("Content-Type: image/gif\r\n");
520 } else if (strcmp(p
,".jpg")==0) {
521 printf("Content-Type: image/jpeg\r\n");
522 } else if (strcmp(p
,".png")==0) {
523 printf("Content-Type: image/png\r\n");
524 } else if (strcmp(p
,".css")==0) {
525 printf("Content-Type: text/css\r\n");
526 } else if (strcmp(p
,".txt")==0) {
527 printf("Content-Type: text/plain\r\n");
529 printf("Content-Type: text/html\r\n");
532 printf("Expires: %s\r\n",
533 http_timestring(talloc_tos(), time(NULL
)+EXPIRY_TIME
));
535 lang
= lang_tdb_current();
537 printf("Content-Language: %s\r\n", lang
);
540 printf("Content-Length: %d\r\n\r\n", (int)st
.st_ex_size
);
541 while ((l
=read(fd
,buf
,sizeof(buf
)))>0) {
542 if (fwrite(buf
, 1, l
, stdout
) != l
) {
552 /* return true if the char* contains ip addrs only. Used to avoid
555 static bool only_ipaddrs_in_list(const char **list
)
563 for (; *list
; list
++) {
564 /* factor out the special strings */
565 if (strequal(*list
, "ALL") || strequal(*list
, "FAIL") ||
566 strequal(*list
, "EXCEPT")) {
570 if (!is_ipaddress(*list
)) {
572 * If we failed, make sure that it was not because
573 * the token was a network/netmask pair. Only
574 * network/netmask pairs have a '/' in them.
576 if ((strchr_m(*list
, '/')) == NULL
) {
578 DEBUG(3,("only_ipaddrs_in_list: list has "
579 "non-ip address (%s)\n",
589 /* return true if access should be allowed to a service for a socket */
590 static bool check_access(int sock
, const char **allow_list
,
591 const char **deny_list
)
594 bool only_ip
= false;
595 char addr
[INET6_ADDRSTRLEN
];
597 if ((!deny_list
|| *deny_list
==0) && (!allow_list
|| *allow_list
==0)) {
601 /* Bypass name resolution calls if the lists
602 * only contain IP addrs */
603 if (only_ipaddrs_in_list(allow_list
) &&
604 only_ipaddrs_in_list(deny_list
)) {
606 DEBUG (3, ("check_access: no hostnames "
607 "in host allow/deny list.\n"));
608 ret
= allow_access(deny_list
,
611 get_peer_addr(sock
,addr
,sizeof(addr
)));
613 DEBUG (3, ("check_access: hostnames in "
614 "host allow/deny list.\n"));
615 ret
= allow_access(deny_list
,
617 get_peer_name(sock
,true),
618 get_peer_addr(sock
,addr
,sizeof(addr
)));
622 DEBUG(2,("Allowed connection from %s (%s)\n",
623 only_ip
? "" : get_peer_name(sock
,true),
624 get_peer_addr(sock
,addr
,sizeof(addr
))));
626 DEBUG(0,("Denied connection from %s (%s)\n",
627 only_ip
? "" : get_peer_name(sock
,true),
628 get_peer_addr(sock
,addr
,sizeof(addr
))));
635 * @brief Setup the CGI framework.
637 * Setup the cgi framework, handling the possibility that this program
638 * is either run as a true CGI program with a gateway to a web server, or
639 * is itself a mini web server.
641 void cgi_setup(const char *rootdir
, int auth_required
)
643 bool authenticated
= False
;
649 if (chdir(rootdir
)) {
650 cgi_setup_error("500 Server Error", "",
651 "chdir failed - the server is not configured correctly");
654 /* Handle the possibility we might be running as non-root */
657 if ((lang
=getenv("HTTP_ACCEPT_LANGUAGE"))) {
658 /* if running as a cgi program */
662 /* maybe we are running under a web server */
663 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
672 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
673 cgi_setup_error("403 Forbidden", "",
674 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
677 /* we are a mini-web server. We need to read the request from stdin
678 and handle authentication etc */
679 while (fgets(line
, sizeof(line
)-1, stdin
)) {
680 if (line
[0] == '\r' || line
[0] == '\n') break;
681 if (strnequal(line
,"GET ", 4)) {
683 url
= SMB_STRDUP(&line
[4]);
684 } else if (strnequal(line
,"POST ", 5)) {
687 url
= SMB_STRDUP(&line
[5]);
688 } else if (strnequal(line
,"PUT ", 4)) {
690 cgi_setup_error("400 Bad Request", "",
691 "This server does not accept PUT requests");
692 } else if (strnequal(line
,"Authorization: ", 15)) {
693 authenticated
= cgi_handle_authorization(&line
[15]);
694 } else if (strnequal(line
,"Content-Length: ", 16)) {
695 content_length
= atoi(&line
[16]);
696 } else if (strnequal(line
,"Accept-Language: ", 17)) {
697 web_set_lang(&line
[17]);
699 /* ignore all other requests! */
702 if (auth_required
&& !authenticated
) {
707 cgi_setup_error("400 Bad Request", "",
708 "You must specify a GET or POST request");
712 if ((p
= strchr_m(url
,' ')) || (p
=strchr_m(url
,'\t'))) {
715 while (*url
&& strchr_m("\r\n",url
[strlen(url
)-1])) {
716 url
[strlen(url
)-1] = 0;
719 /* anything following a ? in the URL is part of the query string */
720 if ((p
=strchr_m(url
,'?'))) {
725 string_sub(url
, "/swat/", "", 0);
727 if (url
[0] != '/' && strstr(url
,"..")==0) {
731 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
732 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL
)));
738 /***************************************************************************
739 return the current pages URL
740 ***************************************************************************/
741 const char *cgi_baseurl(void)
746 return getenv("SCRIPT_NAME");
749 /***************************************************************************
750 return the current pages path info
751 ***************************************************************************/
752 const char *cgi_pathinfo(void)
758 r
= getenv("PATH_INFO");
764 /***************************************************************************
765 return the hostname of the client
766 ***************************************************************************/
767 const char *cgi_remote_host(void)
770 return get_peer_name(1,False
);
772 return getenv("REMOTE_HOST");
775 /***************************************************************************
776 return the hostname of the client
777 ***************************************************************************/
778 const char *cgi_remote_addr(void)
781 char addr
[INET6_ADDRSTRLEN
];
782 get_peer_addr(1,addr
,sizeof(addr
));
783 return talloc_strdup(talloc_tos(), addr
);
785 return getenv("REMOTE_ADDR");
789 /***************************************************************************
790 return True if the request was a POST
791 ***************************************************************************/
792 bool cgi_waspost(void)
797 return strequal(getenv("REQUEST_METHOD"), "POST");