1 /* Copyright 1999-2004 The Apache Software Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 * suexec.c -- "Wrapper" support program for suEXEC behaviour for Apache
19 ***********************************************************************
21 * NOTE! : DO NOT edit this code!!! Unless you know what you are doing,
22 * editing this code might open up your system in unexpected
23 * ways to would-be crackers. Every precaution has been taken
24 * to make this code as safe as possible; alter it at your own
27 ***********************************************************************
33 #include "ap_config.h"
36 #include <sys/param.h>
38 #include <sys/types.h>
58 ***********************************************************************
59 * There is no initgroups() in QNX, so I believe this is safe :-)
60 * Use cc -osuexec -3 -O -mf -DQNX suexec.c to compile.
63 * Igor N. Kovalenko -- infoh mail.wplus.net
64 ***********************************************************************
67 #if defined(NEED_INITGROUPS)
68 int initgroups(const char *name, gid_t basegid)
70 /* QNX and MPE do not appear to support supplementary groups. */
76 extern char *sys_errlist[];
77 #define strerror(x) sys_errlist[(x)]
81 #define AP_MAXPATH PATH_MAX
82 #elif defined(MAXPATHLEN)
83 #define AP_MAXPATH MAXPATHLEN
85 #define AP_MAXPATH 8192
90 extern char **environ;
91 static FILE *log = NULL;
93 char *safe_env_lst[] =
95 /* variable name starts with */
99 /* variable name is */
106 "DOCUMENT_PATH_INFO=",
110 "GATEWAY_INTERFACE=",
116 "QUERY_STRING_UNESCAPED=",
123 "REDIRECT_QUERY_STRING=",
124 "REDIRECT_REMOTE_USER=",
146 static void err_output(int is_error, const char *fmt, va_list ap)
153 if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
154 fprintf(stderr, "suexec failure: could not open log file\n");
161 fprintf(stderr, "suexec policy violation: see suexec log for more "
166 lt = localtime(&timevar);
168 fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
169 lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
170 lt->tm_hour, lt->tm_min, lt->tm_sec);
172 vfprintf(log, fmt, ap);
175 #endif /* AP_LOG_EXEC */
179 static void log_err(const char *fmt,...)
185 err_output(1, fmt, ap); /* 1 == is_error */
187 #endif /* AP_LOG_EXEC */
191 static void log_no_err(const char *fmt,...)
197 err_output(0, fmt, ap); /* 0 == !is_error */
199 #endif /* AP_LOG_EXEC */
203 static void clean_env(void)
211 /* While cleaning the environment, the environment should be clean.
212 * (e.g. malloc() may get the name of a file for writing debugging info.
213 * Bad news if MALLOC_DEBUG_FILE is set to /etc/passwd. Sprintf() may be
214 * susceptible to bad locale settings....)
217 char **envp = environ;
218 char *empty_ptr = NULL;
220 environ = &empty_ptr; /* VERY safe environment */
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 = envp; *ep && cidx < AP_ENVBUF-1; ep++) {
232 for (idx = 0; safe_env_lst[idx]; idx++) {
233 if (!strncmp(*ep, safe_env_lst[idx],
234 strlen(safe_env_lst[idx]))) {
235 cleanenv[cidx] = *ep;
242 cleanenv[cidx] = NULL;
247 int main(int argc, char *argv[])
249 int userdir = 0; /* ~userdir flag */
250 uid_t uid; /* user information */
251 gid_t gid; /* target group placeholder */
252 char *target_uname; /* target user name */
253 char *target_gname; /* target group name */
254 char *target_homedir; /* target home directory */
255 char *actual_uname; /* actual user name */
256 char *actual_gname; /* actual group name */
257 char *prog; /* name of this program */
258 char *cmd; /* command to be executed */
259 char cwd[AP_MAXPATH]; /* current working directory */
260 char dwd[AP_MAXPATH]; /* docroot working directory */
261 struct passwd *pw; /* password entry holder */
262 struct group *gr; /* group entry holder */
263 struct stat dir_info; /* directory info holder */
264 struct stat prg_info; /* program info holder */
267 * Start with a "clean" environment
273 * Check existence/validity of the UID of the user
274 * running this program. Error out if invalid.
277 if ((pw = getpwuid(uid)) == NULL) {
278 log_err("crit: invalid uid: (%ld)\n", uid);
282 * See if this is a 'how were you compiled' request, and
286 && (! strcmp(argv[1], "-V"))
289 /* User name comparisons are case insensitive on BS2000/OSD */
290 || (! strcasecmp(AP_HTTPD_USER, pw->pw_name)))
291 #else /* _OSD_POSIX */
292 || (! strcmp(AP_HTTPD_USER, pw->pw_name)))
293 #endif /* _OSD_POSIX */
296 fprintf(stderr, " -D AP_DOC_ROOT=\"%s\"\n", AP_DOC_ROOT);
299 fprintf(stderr, " -D AP_GID_MIN=%d\n", AP_GID_MIN);
302 fprintf(stderr, " -D AP_HTTPD_USER=\"%s\"\n", AP_HTTPD_USER);
305 fprintf(stderr, " -D AP_LOG_EXEC=\"%s\"\n", AP_LOG_EXEC);
308 fprintf(stderr, " -D AP_SAFE_PATH=\"%s\"\n", AP_SAFE_PATH);
310 #ifdef AP_SUEXEC_UMASK
311 fprintf(stderr, " -D AP_SUEXEC_UMASK=%03o\n", AP_SUEXEC_UMASK);
314 fprintf(stderr, " -D AP_UID_MIN=%d\n", AP_UID_MIN);
316 #ifdef AP_USERDIR_SUFFIX
317 fprintf(stderr, " -D AP_USERDIR_SUFFIX=\"%s\"\n", AP_USERDIR_SUFFIX);
322 * If there are a proper number of arguments, set
323 * all of them to variables. Otherwise, error out.
326 log_err("too few arguments\n");
329 target_uname = argv[1];
330 target_gname = argv[2];
334 * Check to see if the user running this program
335 * is the user allowed to do so as defined in
336 * suexec.h. If not the allowed user, error out.
339 /* User name comparisons are case insensitive on BS2000/OSD */
340 if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
341 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
345 if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
346 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
349 #endif /*_OSD_POSIX*/
352 * Check for a leading '/' (absolute path) in the command to be executed,
353 * or attempts to back up out of the current directory,
354 * to protect against attacks. If any are
355 * found, error out. Naughty naughty crackers.
357 if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
358 || (strstr(cmd, "/../") != NULL)) {
359 log_err("invalid command (%s)\n", cmd);
364 * Check to see if this is a ~userdir request. If
365 * so, set the flag, and remove the '~' from the
368 if (!strncmp("~", target_uname, 1)) {
374 * Error out if the target username is invalid.
376 if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
377 if ((pw = getpwnam(target_uname)) == NULL) {
378 log_err("invalid target user name: (%s)\n", target_uname);
383 if ((pw = getpwuid(atoi(target_uname))) == NULL) {
384 log_err("invalid target user id: (%s)\n", target_uname);
390 * Error out if the target group name is invalid.
392 if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
393 if ((gr = getgrnam(target_gname)) == NULL) {
394 log_err("invalid target group name: (%s)\n", target_gname);
398 actual_gname = strdup(gr->gr_name);
401 gid = atoi(target_gname);
402 actual_gname = strdup(target_gname);
407 * Initialize BS2000 user environment
413 switch (pid = ufork(target_uname)) {
415 log_err("failed to setup bs2000 environment for user %s: %s\n",
416 target_uname, strerror(errno));
420 default: /* Father */
421 while (pid != waitpid(pid, &status, 0))
423 /* @@@ FIXME: should we deal with STOP signals as well? */
424 if (WIFSIGNALED(status)) {
425 kill (getpid(), WTERMSIG(status));
427 exit(WEXITSTATUS(status));
430 #endif /*_OSD_POSIX*/
433 * Save these for later since initgroups will hose the struct
436 actual_uname = strdup(pw->pw_name);
437 target_homedir = strdup(pw->pw_dir);
440 * Log the transaction here to be sure we have an open log
441 * before we setuid().
443 log_no_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
444 target_uname, actual_uname,
445 target_gname, actual_gname,
449 * Error out if attempt is made to execute as root or as
450 * a UID less than AP_UID_MIN. Tsk tsk.
452 if ((uid == 0) || (uid < AP_UID_MIN)) {
453 log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
458 * Error out if attempt is made to execute as root group
459 * or as a GID less than AP_GID_MIN. Tsk tsk.
461 if ((gid == 0) || (gid < AP_GID_MIN)) {
462 log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
467 * Change UID/GID here so that the following tests work over NFS.
469 * Initialize the group access list for the target user,
470 * and setgid() to the target group. If unsuccessful, error out.
472 if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
473 log_err("failed to setgid (%ld: %s)\n", gid, cmd);
478 * setuid() to the target user. Error out on fail.
480 if ((setuid(uid)) != 0) {
481 log_err("failed to setuid (%ld: %s)\n", uid, cmd);
486 * Get the current working directory, as well as the proper
487 * document root (dependant upon whether or not it is a
488 * ~userdir request). Error out if we cannot get either one,
489 * or if the current working directory is not in the docroot.
490 * Use chdir()s and getcwd()s to avoid problems with symlinked
493 if (getcwd(cwd, AP_MAXPATH) == NULL) {
494 log_err("cannot get current working directory\n");
499 if (((chdir(target_homedir)) != 0) ||
500 ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
501 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
502 ((chdir(cwd)) != 0)) {
503 log_err("cannot get docroot information (%s)\n", target_homedir);
508 if (((chdir(AP_DOC_ROOT)) != 0) ||
509 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
510 ((chdir(cwd)) != 0)) {
511 log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
516 if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
517 log_err("command not in docroot (%s/%s)\n", cwd, cmd);
522 * Stat the cwd and verify it is a directory, or error out.
524 if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
525 log_err("cannot stat directory: (%s)\n", cwd);
530 * Error out if cwd is writable by others.
532 if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
533 log_err("directory is writable by others: (%s)\n", cwd);
538 * Error out if we cannot stat the program.
540 if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
541 log_err("cannot stat program: (%s)\n", cmd);
546 * Error out if the program is writable by others.
548 if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
549 log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
554 * Error out if the file is setuid or setgid.
556 if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
557 log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
562 * Error out if the target name/group is different from
563 * the name/group of the cwd or the program.
565 if ((uid != dir_info.st_uid) ||
566 (gid != dir_info.st_gid) ||
567 (uid != prg_info.st_uid) ||
568 (gid != prg_info.st_gid)) {
569 log_err("target uid/gid (%ld/%ld) mismatch "
570 "with directory (%ld/%ld) or program (%ld/%ld)\n",
572 dir_info.st_uid, dir_info.st_gid,
573 prg_info.st_uid, prg_info.st_gid);
577 * Error out if the program is not executable for the user.
578 * Otherwise, she won't find any error in the logs except for
579 * "[error] Premature end of script headers: ..."
581 if (!(prg_info.st_mode & S_IXUSR)) {
582 log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
586 #ifdef AP_SUEXEC_UMASK
588 * umask() uses inverse logic; bits are CLEAR for allowed access.
590 if ((~AP_SUEXEC_UMASK) & 0022) {
591 log_err("notice: AP_SUEXEC_UMASK of %03o allows "
592 "write permission to group and/or other\n", AP_SUEXEC_UMASK);
594 umask(AP_SUEXEC_UMASK);
595 #endif /* AP_SUEXEC_UMASK */
598 * Be sure to close the log file so the CGI can't
599 * mess with it. If the exec fails, it will be reopened
600 * automatically when log_err is called. Note that the log
601 * might not actually be open if AP_LOG_EXEC isn't defined.
602 * However, the "log" cell isn't ifdef'd so let's be defensive
603 * and assume someone might have done something with it
604 * outside an ifdef'd AP_LOG_EXEC block.
612 * Execute the command, replacing our image with its own.
614 #ifdef NEED_HASHBANG_EMUL
615 /* We need the #! emulation when we want to execute scripts */
617 extern char **environ;
619 ap_execve(cmd, &argv[3], environ);
621 #else /*NEED_HASHBANG_EMUL*/
622 execv(cmd, &argv[3]);
623 #endif /*NEED_HASHBANG_EMUL*/
626 * (I can't help myself...sorry.)
628 * Uh oh. Still here. Where's the kaboom? There was supposed to be an
629 * EARTH-shattering kaboom!
631 * Oh well, log the failure and error out.
633 log_err("(%d)%s: exec failed (%s)\n", errno, strerror(errno), cmd);