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=",
109 "GATEWAY_INTERFACE=",
115 "QUERY_STRING_UNESCAPED=",
122 "REDIRECT_QUERY_STRING=",
123 "REDIRECT_REMOTE_USER=",
145 static void err_output(int is_error, const char *fmt, va_list ap)
152 if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
153 fprintf(stderr, "suexec failure: could not open log file\n");
160 fprintf(stderr, "suexec policy violation: see suexec log for more "
165 lt = localtime(&timevar);
167 fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
168 lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
169 lt->tm_hour, lt->tm_min, lt->tm_sec);
171 vfprintf(log, fmt, ap);
174 #endif /* AP_LOG_EXEC */
178 static void log_err(const char *fmt,...)
184 err_output(1, fmt, ap); /* 1 == is_error */
186 #endif /* AP_LOG_EXEC */
190 static void log_no_err(const char *fmt,...)
196 err_output(0, fmt, ap); /* 0 == !is_error */
198 #endif /* AP_LOG_EXEC */
202 static void clean_env(void)
210 /* While cleaning the environment, the environment should be clean.
211 * (e.g. malloc() may get the name of a file for writing debugging info.
212 * Bad news if MALLOC_DEBUG_FILE is set to /etc/passwd. Sprintf() may be
213 * susceptible to bad locale settings....)
216 char **envp = environ;
217 char *empty_ptr = NULL;
219 environ = &empty_ptr; /* VERY safe environment */
221 if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
222 log_err("failed to malloc memory for environment\n");
226 sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
227 cleanenv[cidx] = strdup(pathbuf);
230 for (ep = envp; *ep && cidx < AP_ENVBUF-1; ep++) {
231 for (idx = 0; safe_env_lst[idx]; idx++) {
232 if (!strncmp(*ep, safe_env_lst[idx],
233 strlen(safe_env_lst[idx]))) {
234 cleanenv[cidx] = *ep;
241 cleanenv[cidx] = NULL;
246 int main(int argc, char *argv[])
248 int userdir = 0; /* ~userdir flag */
249 uid_t uid; /* user information */
250 gid_t gid; /* target group placeholder */
251 char *target_uname; /* target user name */
252 char *target_gname; /* target group name */
253 char *target_homedir; /* target home directory */
254 char *actual_uname; /* actual user name */
255 char *actual_gname; /* actual group name */
256 char *prog; /* name of this program */
257 char *cmd; /* command to be executed */
258 char cwd[AP_MAXPATH]; /* current working directory */
259 char dwd[AP_MAXPATH]; /* docroot working directory */
260 struct passwd *pw; /* password entry holder */
261 struct group *gr; /* group entry holder */
262 struct stat dir_info; /* directory info holder */
263 struct stat prg_info; /* program info holder */
266 * Start with a "clean" environment
272 * Check existence/validity of the UID of the user
273 * running this program. Error out if invalid.
276 if ((pw = getpwuid(uid)) == NULL) {
277 log_err("crit: invalid uid: (%ld)\n", uid);
281 * See if this is a 'how were you compiled' request, and
285 && (! strcmp(argv[1], "-V"))
288 /* User name comparisons are case insensitive on BS2000/OSD */
289 || (! strcasecmp(AP_HTTPD_USER, pw->pw_name)))
290 #else /* _OSD_POSIX */
291 || (! strcmp(AP_HTTPD_USER, pw->pw_name)))
292 #endif /* _OSD_POSIX */
295 fprintf(stderr, " -D AP_DOC_ROOT=\"%s\"\n", AP_DOC_ROOT);
298 fprintf(stderr, " -D AP_GID_MIN=%d\n", AP_GID_MIN);
301 fprintf(stderr, " -D AP_HTTPD_USER=\"%s\"\n", AP_HTTPD_USER);
304 fprintf(stderr, " -D AP_LOG_EXEC=\"%s\"\n", AP_LOG_EXEC);
307 fprintf(stderr, " -D AP_SAFE_PATH=\"%s\"\n", AP_SAFE_PATH);
309 #ifdef AP_SUEXEC_UMASK
310 fprintf(stderr, " -D AP_SUEXEC_UMASK=%03o\n", AP_SUEXEC_UMASK);
313 fprintf(stderr, " -D AP_UID_MIN=%d\n", AP_UID_MIN);
315 #ifdef AP_USERDIR_SUFFIX
316 fprintf(stderr, " -D AP_USERDIR_SUFFIX=\"%s\"\n", AP_USERDIR_SUFFIX);
321 * If there are a proper number of arguments, set
322 * all of them to variables. Otherwise, error out.
325 log_err("too few arguments\n");
328 target_uname = argv[1];
329 target_gname = argv[2];
333 * Check to see if the user running this program
334 * is the user allowed to do so as defined in
335 * suexec.h. If not the allowed user, error out.
338 /* User name comparisons are case insensitive on BS2000/OSD */
339 if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
340 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
344 if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
345 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
348 #endif /*_OSD_POSIX*/
351 * Check for a leading '/' (absolute path) in the command to be executed,
352 * or attempts to back up out of the current directory,
353 * to protect against attacks. If any are
354 * found, error out. Naughty naughty crackers.
356 if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
357 || (strstr(cmd, "/../") != NULL)) {
358 log_err("invalid command (%s)\n", cmd);
363 * Check to see if this is a ~userdir request. If
364 * so, set the flag, and remove the '~' from the
367 if (!strncmp("~", target_uname, 1)) {
373 * Error out if the target username is invalid.
375 if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
376 if ((pw = getpwnam(target_uname)) == NULL) {
377 log_err("invalid target user name: (%s)\n", target_uname);
382 if ((pw = getpwuid(atoi(target_uname))) == NULL) {
383 log_err("invalid target user id: (%s)\n", target_uname);
389 * Error out if the target group name is invalid.
391 if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
392 if ((gr = getgrnam(target_gname)) == NULL) {
393 log_err("invalid target group name: (%s)\n", target_gname);
397 actual_gname = strdup(gr->gr_name);
400 gid = atoi(target_gname);
401 actual_gname = strdup(target_gname);
406 * Initialize BS2000 user environment
412 switch (pid = ufork(target_uname)) {
414 log_err("failed to setup bs2000 environment for user %s: %s\n",
415 target_uname, strerror(errno));
419 default: /* Father */
420 while (pid != waitpid(pid, &status, 0))
422 /* @@@ FIXME: should we deal with STOP signals as well? */
423 if (WIFSIGNALED(status)) {
424 kill (getpid(), WTERMSIG(status));
426 exit(WEXITSTATUS(status));
429 #endif /*_OSD_POSIX*/
432 * Save these for later since initgroups will hose the struct
435 actual_uname = strdup(pw->pw_name);
436 target_homedir = strdup(pw->pw_dir);
439 * Log the transaction here to be sure we have an open log
440 * before we setuid().
442 log_no_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
443 target_uname, actual_uname,
444 target_gname, actual_gname,
448 * Error out if attempt is made to execute as root or as
449 * a UID less than AP_UID_MIN. Tsk tsk.
451 if ((uid == 0) || (uid < AP_UID_MIN)) {
452 log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
457 * Error out if attempt is made to execute as root group
458 * or as a GID less than AP_GID_MIN. Tsk tsk.
460 if ((gid == 0) || (gid < AP_GID_MIN)) {
461 log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
466 * Change UID/GID here so that the following tests work over NFS.
468 * Initialize the group access list for the target user,
469 * and setgid() to the target group. If unsuccessful, error out.
471 if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
472 log_err("failed to setgid (%ld: %s)\n", gid, cmd);
477 * setuid() to the target user. Error out on fail.
479 if ((setuid(uid)) != 0) {
480 log_err("failed to setuid (%ld: %s)\n", uid, cmd);
485 * Get the current working directory, as well as the proper
486 * document root (dependant upon whether or not it is a
487 * ~userdir request). Error out if we cannot get either one,
488 * or if the current working directory is not in the docroot.
489 * Use chdir()s and getcwd()s to avoid problems with symlinked
492 if (getcwd(cwd, AP_MAXPATH) == NULL) {
493 log_err("cannot get current working directory\n");
498 if (((chdir(target_homedir)) != 0) ||
499 ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
500 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
501 ((chdir(cwd)) != 0)) {
502 log_err("cannot get docroot information (%s)\n", target_homedir);
507 if (((chdir(AP_DOC_ROOT)) != 0) ||
508 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
509 ((chdir(cwd)) != 0)) {
510 log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
515 if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
516 log_err("command not in docroot (%s/%s)\n", cwd, cmd);
521 * Stat the cwd and verify it is a directory, or error out.
523 if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
524 log_err("cannot stat directory: (%s)\n", cwd);
529 * Error out if cwd is writable by others.
531 if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
532 log_err("directory is writable by others: (%s)\n", cwd);
537 * Error out if we cannot stat the program.
539 if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
540 log_err("cannot stat program: (%s)\n", cmd);
545 * Error out if the program is writable by others.
547 if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
548 log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
553 * Error out if the file is setuid or setgid.
555 if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
556 log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
561 * Error out if the target name/group is different from
562 * the name/group of the cwd or the program.
564 if ((uid != dir_info.st_uid) ||
565 (gid != dir_info.st_gid) ||
566 (uid != prg_info.st_uid) ||
567 (gid != prg_info.st_gid)) {
568 log_err("target uid/gid (%ld/%ld) mismatch "
569 "with directory (%ld/%ld) or program (%ld/%ld)\n",
571 dir_info.st_uid, dir_info.st_gid,
572 prg_info.st_uid, prg_info.st_gid);
576 * Error out if the program is not executable for the user.
577 * Otherwise, she won't find any error in the logs except for
578 * "[error] Premature end of script headers: ..."
580 if (!(prg_info.st_mode & S_IXUSR)) {
581 log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
585 #ifdef AP_SUEXEC_UMASK
587 * umask() uses inverse logic; bits are CLEAR for allowed access.
589 if ((~AP_SUEXEC_UMASK) & 0022) {
590 log_err("notice: AP_SUEXEC_UMASK of %03o allows "
591 "write permission to group and/or other\n", AP_SUEXEC_UMASK);
593 umask(AP_SUEXEC_UMASK);
594 #endif /* AP_SUEXEC_UMASK */
597 * Be sure to close the log file so the CGI can't
598 * mess with it. If the exec fails, it will be reopened
599 * automatically when log_err is called. Note that the log
600 * might not actually be open if AP_LOG_EXEC isn't defined.
601 * However, the "log" cell isn't ifdef'd so let's be defensive
602 * and assume someone might have done something with it
603 * outside an ifdef'd AP_LOG_EXEC block.
611 * Execute the command, replacing our image with its own.
613 #ifdef NEED_HASHBANG_EMUL
614 /* We need the #! emulation when we want to execute scripts */
616 extern char **environ;
618 ap_execve(cmd, &argv[3], environ);
620 #else /*NEED_HASHBANG_EMUL*/
621 execv(cmd, &argv[3]);
622 #endif /*NEED_HASHBANG_EMUL*/
625 * (I can't help myself...sorry.)
627 * Uh oh. Still here. Where's the kaboom? There was supposed to be an
628 * EARTH-shattering kaboom!
630 * Oh well, log the failure and error out.
632 log_err("(%d)%s: exec failed (%s)\n", errno, strerror(errno), cmd);