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
;
53 static bool inetd_server
;
54 static bool got_request
;
56 static char *grab_line(FILE *f
, int *cl
)
67 if (len
== 0) len
= 1024;
69 ret2
= (char *)SMB_REALLOC_KEEP_OLD_ON_ERROR(ret
, len
);
70 if (!ret2
) return ret
;
82 if (c
== '\r') continue;
84 if (strchr_m("\n&", c
)) break;
97 URL encoded strings can have a '+', which should be replaced with a space
99 (This was in rfc1738_unescape(), but that broke the squid helper)
102 static void plus_to_space_unescape(char *buf
)
106 while ((p
=strchr_m(p
,'+')))
110 /***************************************************************************
111 load all the variables passed to the CGI program. May have multiple variables
112 with the same name and the same or different values. Takes a file parameter
113 for simulating CGI invocation eg loading saved preferences.
114 ***************************************************************************/
115 void cgi_load_variables(void)
122 #ifdef DEBUG_COMMENTS
125 printf("<!== Start dump in cgi_load_variables() %s ==>\n",__FILE__
);
128 if (!content_length
) {
129 p
= getenv("CONTENT_LENGTH");
132 len
= content_length
;
138 ((s
=getenv("REQUEST_METHOD")) &&
139 strequal(s
,"POST")))) {
140 while (len
&& (line
=grab_line(f
, &len
))) {
141 p
= strchr_m(line
,'=');
146 variables
[num_variables
].name
= SMB_STRDUP(line
);
147 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
151 if (!variables
[num_variables
].name
||
152 !variables
[num_variables
].value
)
155 plus_to_space_unescape(variables
[num_variables
].value
);
156 rfc1738_unescape(variables
[num_variables
].value
);
157 plus_to_space_unescape(variables
[num_variables
].name
);
158 rfc1738_unescape(variables
[num_variables
].name
);
160 #ifdef DEBUG_COMMENTS
161 printf("<!== POST var %s has value \"%s\" ==>\n",
162 variables
[num_variables
].name
,
163 variables
[num_variables
].value
);
167 if (num_variables
== MAX_VARIABLES
) break;
172 open("/dev/null", O_RDWR
);
174 if ((s
=query_string
) || (s
=getenv("QUERY_STRING"))) {
176 for (tok
=strtok_r(s
, "&;", &saveptr
); tok
;
177 tok
=strtok_r(NULL
, "&;", &saveptr
)) {
178 p
= strchr_m(tok
,'=');
183 variables
[num_variables
].name
= SMB_STRDUP(tok
);
184 variables
[num_variables
].value
= SMB_STRDUP(p
+1);
186 if (!variables
[num_variables
].name
||
187 !variables
[num_variables
].value
)
190 plus_to_space_unescape(variables
[num_variables
].value
);
191 rfc1738_unescape(variables
[num_variables
].value
);
192 plus_to_space_unescape(variables
[num_variables
].name
);
193 rfc1738_unescape(variables
[num_variables
].name
);
195 #ifdef DEBUG_COMMENTS
196 printf("<!== Commandline var %s has value \"%s\" ==>\n",
197 variables
[num_variables
].name
,
198 variables
[num_variables
].value
);
201 if (num_variables
== MAX_VARIABLES
) break;
205 #ifdef DEBUG_COMMENTS
206 printf("<!== End dump in cgi_load_variables() ==>\n");
209 /* variables from the client are in UTF-8 - convert them
210 to our internal unix charset before use */
211 for (i
=0;i
<num_variables
;i
++) {
212 TALLOC_CTX
*frame
= talloc_stackframe();
216 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
217 variables
[i
].name
, strlen(variables
[i
].name
),
219 SAFE_FREE(variables
[i
].name
);
220 variables
[i
].name
= SMB_STRDUP(dest
? dest
: "");
223 convert_string_talloc(frame
, CH_UTF8
, CH_UNIX
,
224 variables
[i
].value
, strlen(variables
[i
].value
),
226 SAFE_FREE(variables
[i
].value
);
227 variables
[i
].value
= SMB_STRDUP(dest
? dest
: "");
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 ***************************************************************************/
241 const char *cgi_variable(const char *name
)
245 for (i
=0;i
<num_variables
;i
++)
246 if (strcmp(variables
[i
].name
, name
) == 0)
247 return variables
[i
].value
;
251 /***************************************************************************
252 Version of the above that can't return a NULL pointer.
253 ***************************************************************************/
255 const char *cgi_variable_nonull(const char *name
)
257 const char *var
= cgi_variable(name
);
265 /***************************************************************************
266 tell a browser about a fatal error in the http processing
267 ***************************************************************************/
268 static void cgi_setup_error(const char *err
, const char *header
, const char *info
)
271 /* damn browsers don't like getting cut off before they give a request */
273 while (fgets(line
, sizeof(line
)-1, stdin
)) {
274 if (strnequal(line
,"GET ", 4) ||
275 strnequal(line
,"POST ", 5) ||
276 strnequal(line
,"PUT ", 4)) {
282 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
);
289 /***************************************************************************
290 tell a browser about a fatal authentication error
291 ***************************************************************************/
292 static void cgi_auth_error(void)
295 cgi_setup_error("401 Authorization Required",
296 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
297 "You must be authenticated to use this service");
299 printf("Content-Type: text/html\r\n");
301 printf("\r\n<HTML><HEAD><TITLE>SWAT</TITLE></HEAD>\n");
302 printf("<BODY><H1>Installation Error</H1>\n");
303 printf("SWAT must be installed via inetd. It cannot be run as a CGI script<p>\n");
304 printf("</BODY></HTML>\r\n");
309 /***************************************************************************
310 authenticate when we are running as a CGI
311 ***************************************************************************/
312 static void cgi_web_auth(void)
314 const char *user
= getenv("REMOTE_USER");
316 const char *head
= "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
317 const char *tail
= "</BODY></HTML>\r\n";
320 printf("%sREMOTE_USER not set. Not authenticated by web server.<br>%s\n",
325 pwd
= Get_Pwnam_alloc(talloc_tos(), user
);
327 printf("%sCannot find user %s<br>%s\n", head
, user
, tail
);
331 C_user
= SMB_STRDUP(user
);
333 if (!samba_setuid(0)) {
334 C_pass
= SMB_STRDUP(cgi_nonce());
336 samba_setuid(pwd
->pw_uid
);
337 if (geteuid() != pwd
->pw_uid
|| getuid() != pwd
->pw_uid
) {
338 printf("%sFailed to become user %s - uid=%d/%d<br>%s\n",
339 head
, user
, (int)geteuid(), (int)getuid(), tail
);
346 /***************************************************************************
347 handle a http authentication line
348 ***************************************************************************/
349 static bool cgi_handle_authorization(char *line
)
352 fstring user
, user_pass
;
353 struct passwd
*pass
= NULL
;
355 char addr
[INET6_ADDRSTRLEN
];
358 if (!strnequal(line
,"Basic ", 6)) {
362 while (line
[0] == ' ') line
++;
363 base64_decode_inplace(line
);
364 if (!(p
=strchr_m(line
,':'))) {
366 * Always give the same error so a cracker
367 * cannot tell why we fail.
373 if (!convert_string(CH_UTF8
, CH_UNIX
,
375 user
, sizeof(user
), &size
)) {
379 if (!convert_string(CH_UTF8
, CH_UNIX
,
381 user_pass
, sizeof(user_pass
), &size
)) {
386 * Try and get the user from the UNIX password file.
389 pass
= Get_Pwnam_alloc(talloc_tos(), user
);
391 rhost
= client_name(1);
392 if (strequal(rhost
,"UNKNOWN"))
393 rhost
= client_addr(1, addr
, sizeof(addr
));
396 * Validate the password they have given.
399 if NT_STATUS_IS_OK(pass_check(pass
, user
, rhost
, user_pass
, false)) {
405 if ( initgroups(pass
->pw_name
, pass
->pw_gid
) != 0 )
408 become_user_permanently(pass
->pw_uid
, pass
->pw_gid
);
410 /* Save the users name */
411 C_user
= SMB_STRDUP(user
);
412 C_pass
= SMB_STRDUP(user_pass
);
419 cgi_setup_error("401 Bad Authorization",
420 "WWW-Authenticate: Basic realm=\"SWAT\"\r\n",
421 "username or password incorrect");
427 /***************************************************************************
429 ***************************************************************************/
432 if (geteuid() == 0) {
439 /***************************************************************************
440 return a ptr to the users name
441 ***************************************************************************/
442 char *cgi_user_name(void)
447 /***************************************************************************
448 return a ptr to the users password
449 ***************************************************************************/
450 char *cgi_user_pass(void)
455 /***************************************************************************
456 return a ptr to the nonce
457 ***************************************************************************/
458 char *cgi_nonce(void)
460 const char *head
= "Content-Type: text/html\r\n\r\n<HTML><BODY><H1>SWAT installation Error</H1>\n";
461 const char *tail
= "</BODY></HTML>\r\n";
462 C_nonce
= secrets_fetch_generic("root", "SWAT");
463 if (C_nonce
== NULL
) {
464 char *tmp_pass
= NULL
;
465 tmp_pass
= generate_random_password(talloc_tos(), 16, 16);
466 if (tmp_pass
== NULL
) {
467 printf("%sFailed to create random nonce for "
468 "SWAT session\n<br>%s\n", head
, tail
);
471 secrets_store_generic("root", "SWAT", tmp_pass
);
472 C_nonce
= SMB_STRDUP(tmp_pass
);
473 TALLOC_FREE(tmp_pass
);
478 /***************************************************************************
479 handle a file download
480 ***************************************************************************/
481 static void cgi_download(char *file
)
489 /* sanitise the filename */
490 for (i
=0;file
[i
];i
++) {
491 if (!isalnum((int)file
[i
]) && !strchr_m("/.-_", file
[i
])) {
492 cgi_setup_error("404 File Not Found","",
493 "Illegal character in filename");
497 if (sys_stat(file
, &st
, false) != 0) {
498 cgi_setup_error("404 File Not Found","",
499 "The requested file was not found");
502 if (S_ISDIR(st
.st_ex_mode
))
504 snprintf(buf
, sizeof(buf
), "%s/index.html", file
);
505 if (!file_exist_stat(buf
, &st
, false)
506 || !S_ISREG(st
.st_ex_mode
))
508 cgi_setup_error("404 File Not Found","",
509 "The requested file was not found");
512 else if (S_ISREG(st
.st_ex_mode
))
514 snprintf(buf
, sizeof(buf
), "%s", file
);
518 cgi_setup_error("404 File Not Found","",
519 "The requested file was not found");
522 fd
= web_open(buf
,O_RDONLY
,0);
524 cgi_setup_error("404 File Not Found","",
525 "The requested file was not found");
527 printf("HTTP/1.0 200 OK\r\n");
528 if ((p
=strrchr_m(buf
, '.'))) {
529 if (strcmp(p
,".gif")==0) {
530 printf("Content-Type: image/gif\r\n");
531 } else if (strcmp(p
,".jpg")==0) {
532 printf("Content-Type: image/jpeg\r\n");
533 } else if (strcmp(p
,".png")==0) {
534 printf("Content-Type: image/png\r\n");
535 } else if (strcmp(p
,".css")==0) {
536 printf("Content-Type: text/css\r\n");
537 } else if (strcmp(p
,".txt")==0) {
538 printf("Content-Type: text/plain\r\n");
540 printf("Content-Type: text/html\r\n");
543 printf("Expires: %s\r\n",
544 http_timestring(talloc_tos(), time(NULL
)+EXPIRY_TIME
));
546 lang
= lang_tdb_current();
548 printf("Content-Language: %s\r\n", lang
);
551 printf("Content-Length: %d\r\n\r\n", (int)st
.st_ex_size
);
552 while ((l
=read(fd
,buf
,sizeof(buf
)))>0) {
553 if (fwrite(buf
, 1, l
, stdout
) != l
) {
563 /* return true if the char* contains ip addrs only. Used to avoid
566 static bool only_ipaddrs_in_list(const char **list
)
574 for (; *list
; list
++) {
575 /* factor out the special strings */
576 if (strequal(*list
, "ALL") || strequal(*list
, "FAIL") ||
577 strequal(*list
, "EXCEPT")) {
581 if (!is_ipaddress(*list
)) {
583 * If we failed, make sure that it was not because
584 * the token was a network/netmask pair. Only
585 * network/netmask pairs have a '/' in them.
587 if ((strchr_m(*list
, '/')) == NULL
) {
589 DEBUG(3,("only_ipaddrs_in_list: list has "
590 "non-ip address (%s)\n",
600 /* return true if access should be allowed to a service for a socket */
601 static bool check_access(int sock
, const char **allow_list
,
602 const char **deny_list
)
605 bool only_ip
= false;
606 char addr
[INET6_ADDRSTRLEN
];
608 if ((!deny_list
|| *deny_list
==0) && (!allow_list
|| *allow_list
==0)) {
612 /* Bypass name resolution calls if the lists
613 * only contain IP addrs */
614 if (only_ipaddrs_in_list(allow_list
) &&
615 only_ipaddrs_in_list(deny_list
)) {
617 DEBUG (3, ("check_access: no hostnames "
618 "in host allow/deny list.\n"));
619 ret
= allow_access(deny_list
,
622 get_peer_addr(sock
,addr
,sizeof(addr
)));
624 DEBUG (3, ("check_access: hostnames in "
625 "host allow/deny list.\n"));
626 ret
= allow_access(deny_list
,
628 get_peer_name(sock
,true),
629 get_peer_addr(sock
,addr
,sizeof(addr
)));
633 DEBUG(2,("Allowed connection from %s (%s)\n",
634 only_ip
? "" : get_peer_name(sock
,true),
635 get_peer_addr(sock
,addr
,sizeof(addr
))));
637 DEBUG(0,("Denied connection from %s (%s)\n",
638 only_ip
? "" : get_peer_name(sock
,true),
639 get_peer_addr(sock
,addr
,sizeof(addr
))));
646 * @brief Setup the CGI framework.
648 * Setup the cgi framework, handling the possibility that this program
649 * is either run as a true CGI program with a gateway to a web server, or
650 * is itself a mini web server.
652 void cgi_setup(const char *rootdir
, int auth_required
)
654 bool authenticated
= False
;
660 if (chdir(rootdir
)) {
661 cgi_setup_error("500 Server Error", "",
662 "chdir failed - the server is not configured correctly");
665 /* Handle the possibility we might be running as non-root */
668 if ((lang
=getenv("HTTP_ACCEPT_LANGUAGE"))) {
669 /* if running as a cgi program */
673 /* maybe we are running under a web server */
674 if (getenv("CONTENT_LENGTH") || getenv("REQUEST_METHOD")) {
683 if (!check_access(1, lp_hostsallow(-1), lp_hostsdeny(-1))) {
684 cgi_setup_error("403 Forbidden", "",
685 "Samba is configured to deny access from this client\n<br>Check your \"hosts allow\" and \"hosts deny\" options in smb.conf ");
688 /* we are a mini-web server. We need to read the request from stdin
689 and handle authentication etc */
690 while (fgets(line
, sizeof(line
)-1, stdin
)) {
691 if (line
[0] == '\r' || line
[0] == '\n') break;
692 if (strnequal(line
,"GET ", 4)) {
694 url
= SMB_STRDUP(&line
[4]);
695 } else if (strnequal(line
,"POST ", 5)) {
698 url
= SMB_STRDUP(&line
[5]);
699 } else if (strnequal(line
,"PUT ", 4)) {
701 cgi_setup_error("400 Bad Request", "",
702 "This server does not accept PUT requests");
703 } else if (strnequal(line
,"Authorization: ", 15)) {
704 authenticated
= cgi_handle_authorization(&line
[15]);
705 } else if (strnequal(line
,"Content-Length: ", 16)) {
706 content_length
= atoi(&line
[16]);
707 } else if (strnequal(line
,"Accept-Language: ", 17)) {
708 web_set_lang(&line
[17]);
710 /* ignore all other requests! */
713 if (auth_required
&& !authenticated
) {
718 cgi_setup_error("400 Bad Request", "",
719 "You must specify a GET or POST request");
723 if ((p
= strchr_m(url
,' ')) || (p
=strchr_m(url
,'\t'))) {
726 while (*url
&& strchr_m("\r\n",url
[strlen(url
)-1])) {
727 url
[strlen(url
)-1] = 0;
730 /* anything following a ? in the URL is part of the query string */
731 if ((p
=strchr_m(url
,'?'))) {
736 string_sub(url
, "/swat/", "", 0);
738 if (url
[0] != '/' && strstr(url
,"..")==0) {
742 printf("HTTP/1.0 200 OK\r\nConnection: close\r\n");
743 printf("Date: %s\r\n", http_timestring(talloc_tos(), time(NULL
)));
749 /***************************************************************************
750 return the current pages URL
751 ***************************************************************************/
752 const char *cgi_baseurl(void)
757 return getenv("SCRIPT_NAME");
760 /***************************************************************************
761 return the current pages path info
762 ***************************************************************************/
763 const char *cgi_pathinfo(void)
769 r
= getenv("PATH_INFO");
775 /***************************************************************************
776 return the hostname of the client
777 ***************************************************************************/
778 const char *cgi_remote_host(void)
781 return get_peer_name(1,False
);
783 return getenv("REMOTE_HOST");
786 /***************************************************************************
787 return the hostname of the client
788 ***************************************************************************/
789 const char *cgi_remote_addr(void)
792 char addr
[INET6_ADDRSTRLEN
];
793 get_peer_addr(1,addr
,sizeof(addr
));
794 return talloc_strdup(talloc_tos(), addr
);
796 return getenv("REMOTE_ADDR");
800 /***************************************************************************
801 return True if the request was a POST
802 ***************************************************************************/
803 bool cgi_waspost(void)
808 return strequal(getenv("REQUEST_METHOD"), "POST");