1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
56 * suexec.c -- "Wrapper" support program for suEXEC behaviour for Apache
58 ***********************************************************************
60 * NOTE! : DO NOT edit this code!!! Unless you know what you are doing,
61 * editing this code might open up your system in unexpected
62 * ways to would-be crackers. Every precaution has been taken
63 * to make this code as safe as possible; alter it at your own
66 ***********************************************************************
72 #include "ap_config.h"
75 #include <sys/param.h>
77 #include <sys/types.h>
97 ***********************************************************************
98 * There is no initgroups() in QNX, so I believe this is safe :-)
99 * Use cc -osuexec -3 -O -mf -DQNX suexec.c to compile.
102 * Igor N. Kovalenko -- infoh@mail.wplus.net
103 ***********************************************************************
106 #if defined(NEED_INITGROUPS)
107 int initgroups(const char *name, gid_t basegid)
109 /* QNX and MPE do not appear to support supplementary groups. */
114 #if defined(PATH_MAX)
115 #define AP_MAXPATH PATH_MAX
116 #elif defined(MAXPATHLEN)
117 #define AP_MAXPATH MAXPATHLEN
119 #define AP_MAXPATH 8192
122 #define AP_ENVBUF 256
124 extern char **environ;
125 static FILE *log = NULL;
127 char *safe_env_lst[] =
135 "DOCUMENT_PATH_INFO",
145 "QUERY_STRING_UNESCAPED",
151 "REDIRECT_QUERY_STRING",
173 static void err_output(const char *fmt, va_list ap)
180 if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
181 fprintf(stderr, "failed to open log file\n");
188 lt = localtime(&timevar);
190 fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
191 lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
192 lt->tm_hour, lt->tm_min, lt->tm_sec);
194 vfprintf(log, fmt, ap);
197 #endif /* AP_LOG_EXEC */
201 static void log_err(const char *fmt,...)
209 #endif /* AP_LOG_EXEC */
213 static void clean_env(void)
222 if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
223 log_err("failed to malloc memory for environment\n");
227 sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
228 cleanenv[cidx] = strdup(pathbuf);
231 for (ep = environ; *ep && cidx < AP_ENVBUF-1; ep++) {
232 if (!strncmp(*ep, "HTTP_", 5) || !strncmp(*ep, "SSL_", 4)) {
233 cleanenv[cidx] = *ep;
237 for (idx = 0; safe_env_lst[idx]; idx++) {
238 if (!strncmp(*ep, safe_env_lst[idx],
239 strlen(safe_env_lst[idx]))) {
240 cleanenv[cidx] = *ep;
248 cleanenv[cidx] = NULL;
253 int main(int argc, char *argv[])
255 int userdir = 0; /* ~userdir flag */
256 uid_t uid; /* user information */
257 gid_t gid; /* target group placeholder */
258 char *target_uname; /* target user name */
259 char *target_gname; /* target group name */
260 char *target_homedir; /* target home directory */
261 char *actual_uname; /* actual user name */
262 char *actual_gname; /* actual group name */
263 char *prog; /* name of this program */
264 char *cmd; /* command to be executed */
265 char cwd[AP_MAXPATH]; /* current working directory */
266 char dwd[AP_MAXPATH]; /* docroot working directory */
267 struct passwd *pw; /* password entry holder */
268 struct group *gr; /* group entry holder */
269 struct stat dir_info; /* directory info holder */
270 struct stat prg_info; /* program info holder */
274 * Check existence/validity of the UID of the user
275 * running this program. Error out if invalid.
278 if ((pw = getpwuid(uid)) == NULL) {
279 log_err("crit: invalid uid: (%ld)\n", uid);
283 * See if this is a 'how were you compiled' request, and
287 && (! strcmp(argv[1], "-V"))
290 /* User name comparisons are case insensitive on BS2000/OSD */
291 || (! strcasecmp(AP_HTTPD_USER, pw->pw_name)))
292 #else /* _OSD_POSIX */
293 || (! strcmp(AP_HTTPD_USER, pw->pw_name)))
294 #endif /* _OSD_POSIX */
297 fprintf(stderr, " -D AP_DOC_ROOT=\"%s\"\n", AP_DOC_ROOT);
300 fprintf(stderr, " -D AP_GID_MIN=%d\n", AP_GID_MIN);
303 fprintf(stderr, " -D AP_HTTPD_USER=\"%s\"\n", AP_HTTPD_USER);
306 fprintf(stderr, " -D AP_LOG_EXEC=\"%s\"\n", AP_LOG_EXEC);
309 fprintf(stderr, " -D AP_SAFE_PATH=\"%s\"\n", AP_SAFE_PATH);
311 #ifdef AP_SUEXEC_UMASK
312 fprintf(stderr, " -D AP_SUEXEC_UMASK=%03o\n", AP_SUEXEC_UMASK);
315 fprintf(stderr, " -D AP_UID_MIN=%d\n", AP_UID_MIN);
317 #ifdef AP_USERDIR_SUFFIX
318 fprintf(stderr, " -D AP_USERDIR_SUFFIX=\"%s\"\n", AP_USERDIR_SUFFIX);
323 * If there are a proper number of arguments, set
324 * all of them to variables. Otherwise, error out.
327 log_err("too few arguments\n");
330 target_uname = argv[1];
331 target_gname = argv[2];
335 * Check to see if the user running this program
336 * is the user allowed to do so as defined in
337 * suexec.h. If not the allowed user, error out.
340 /* User name comparisons are case insensitive on BS2000/OSD */
341 if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
342 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
346 if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
347 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
350 #endif /*_OSD_POSIX*/
353 * Check for a leading '/' (absolute path) in the command to be executed,
354 * or attempts to back up out of the current directory,
355 * to protect against attacks. If any are
356 * found, error out. Naughty naughty crackers.
358 if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
359 || (strstr(cmd, "/../") != NULL)) {
360 log_err("invalid command (%s)\n", cmd);
365 * Check to see if this is a ~userdir request. If
366 * so, set the flag, and remove the '~' from the
369 if (!strncmp("~", target_uname, 1)) {
375 * Error out if the target username is invalid.
377 if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
378 if ((pw = getpwnam(target_uname)) == NULL) {
379 log_err("invalid target user name: (%s)\n", target_uname);
384 if ((pw = getpwuid(atoi(target_uname))) == NULL) {
385 log_err("invalid target user id: (%s)\n", target_uname);
391 * Error out if the target group name is invalid.
393 if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
394 if ((gr = getgrnam(target_gname)) == NULL) {
395 log_err("invalid target group name: (%s)\n", target_gname);
399 actual_gname = strdup(gr->gr_name);
402 gid = atoi(target_gname);
403 actual_gname = strdup(target_gname);
408 * Initialize BS2000 user environment
414 switch (pid = ufork(target_uname)) {
416 log_err("failed to setup bs2000 environment for user %s: %s\n",
417 target_uname, strerror(errno));
421 default: /* Father */
422 while (pid != waitpid(pid, &status, 0))
424 /* @@@ FIXME: should we deal with STOP signals as well? */
425 if (WIFSIGNALED(status)) {
426 kill (getpid(), WTERMSIG(status));
428 exit(WEXITSTATUS(status));
431 #endif /*_OSD_POSIX*/
434 * Save these for later since initgroups will hose the struct
437 actual_uname = strdup(pw->pw_name);
438 target_homedir = strdup(pw->pw_dir);
441 * Log the transaction here to be sure we have an open log
442 * before we setuid().
444 log_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
445 target_uname, actual_uname,
446 target_gname, actual_gname,
450 * Error out if attempt is made to execute as root or as
451 * a UID less than AP_UID_MIN. Tsk tsk.
453 if ((uid == 0) || (uid < AP_UID_MIN)) {
454 log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
459 * Error out if attempt is made to execute as root group
460 * or as a GID less than AP_GID_MIN. Tsk tsk.
462 if ((gid == 0) || (gid < AP_GID_MIN)) {
463 log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
468 * Change UID/GID here so that the following tests work over NFS.
470 * Initialize the group access list for the target user,
471 * and setgid() to the target group. If unsuccessful, error out.
473 if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
474 log_err("failed to setgid (%ld: %s)\n", gid, cmd);
479 * setuid() to the target user. Error out on fail.
481 if ((setuid(uid)) != 0) {
482 log_err("failed to setuid (%ld: %s)\n", uid, cmd);
487 * Get the current working directory, as well as the proper
488 * document root (dependant upon whether or not it is a
489 * ~userdir request). Error out if we cannot get either one,
490 * or if the current working directory is not in the docroot.
491 * Use chdir()s and getcwd()s to avoid problems with symlinked
494 if (getcwd(cwd, AP_MAXPATH) == NULL) {
495 log_err("cannot get current working directory\n");
500 if (((chdir(target_homedir)) != 0) ||
501 ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
502 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
503 ((chdir(cwd)) != 0)) {
504 log_err("cannot get docroot information (%s)\n", target_homedir);
509 if (((chdir(AP_DOC_ROOT)) != 0) ||
510 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
511 ((chdir(cwd)) != 0)) {
512 log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
517 if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
518 log_err("command not in docroot (%s/%s)\n", cwd, cmd);
523 * Stat the cwd and verify it is a directory, or error out.
525 if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
526 log_err("cannot stat directory: (%s)\n", cwd);
531 * Error out if cwd is writable by others.
533 if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
534 log_err("directory is writable by others: (%s)\n", cwd);
539 * Error out if we cannot stat the program.
541 if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
542 log_err("cannot stat program: (%s)\n", cmd);
547 * Error out if the program is writable by others.
549 if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
550 log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
555 * Error out if the file is setuid or setgid.
557 if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
558 log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
563 * Error out if the target name/group is different from
564 * the name/group of the cwd or the program.
566 if ((uid != dir_info.st_uid) ||
567 (gid != dir_info.st_gid) ||
568 (uid != prg_info.st_uid) ||
569 (gid != prg_info.st_gid)) {
570 log_err("target uid/gid (%ld/%ld) mismatch "
571 "with directory (%ld/%ld) or program (%ld/%ld)\n",
573 dir_info.st_uid, dir_info.st_gid,
574 prg_info.st_uid, prg_info.st_gid);
578 * Error out if the program is not executable for the user.
579 * Otherwise, she won't find any error in the logs except for
580 * "[error] Premature end of script headers: ..."
582 if (!(prg_info.st_mode & S_IXUSR)) {
583 log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
587 #ifdef AP_SUEXEC_UMASK
589 * umask() uses inverse logic; bits are CLEAR for allowed access.
591 if ((~AP_SUEXEC_UMASK) & 0022) {
592 log_err("notice: AP_SUEXEC_UMASK of %03o allows "
593 "write permission to group and/or other\n", AP_SUEXEC_UMASK);
595 umask(AP_SUEXEC_UMASK);
596 #endif /* AP_SUEXEC_UMASK */
600 * Be sure to close the log file so the CGI can't
601 * mess with it. If the exec fails, it will be reopened
602 * automatically when log_err is called. Note that the log
603 * might not actually be open if AP_LOG_EXEC isn't defined.
604 * However, the "log" cell isn't ifdef'd so let's be defensive
605 * and assume someone might have done something with it
606 * outside an ifdef'd AP_LOG_EXEC block.
614 * Execute the command, replacing our image with its own.
616 #ifdef NEED_HASHBANG_EMUL
617 /* We need the #! emulation when we want to execute scripts */
619 extern char **environ;
621 ap_execve(cmd, &argv[3], environ);
623 #else /*NEED_HASHBANG_EMUL*/
624 execv(cmd, &argv[3]);
625 #endif /*NEED_HASHBANG_EMUL*/
628 * (I can't help myself...sorry.)
630 * Uh oh. Still here. Where's the kaboom? There was supposed to be an
631 * EARTH-shattering kaboom!
633 * Oh well, log the failure and error out.
635 log_err("(%d)%s: exec failed (%s)\n", errno, strerror(errno), cmd);