1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * suexec.c -- "Wrapper" support program for suEXEC behaviour for Apache
20 ***********************************************************************
22 * NOTE! : DO NOT edit this code!!! Unless you know what you are doing,
23 * editing this code might open up your system in unexpected
24 * ways to would-be crackers. Every precaution has been taken
25 * to make this code as safe as possible; alter it at your own
28 ***********************************************************************
34 #include "ap_config.h"
37 #include <sys/param.h>
39 #include <sys/types.h>
62 #define AP_MAXPATH PATH_MAX
63 #elif defined(MAXPATHLEN)
64 #define AP_MAXPATH MAXPATHLEN
66 #define AP_MAXPATH 8192
71 extern char **environ;
72 static FILE *log = NULL;
74 static const char *const safe_env_lst[] =
76 /* variable name starts with */
80 /* variable name is */
84 "CONTEXT_DOCUMENT_ROOT=",
90 "DOCUMENT_PATH_INFO=",
99 "QUERY_STRING_UNESCAPED=",
105 "REDIRECT_ERROR_NOTES=",
107 "REDIRECT_QUERY_STRING=",
108 "REDIRECT_REMOTE_USER=",
109 "REDIRECT_SCRIPT_FILENAME=",
132 static void log_err(const char *fmt,...)
133 __attribute__((format(printf,1,2)));
134 static void log_no_err(const char *fmt,...)
135 __attribute__((format(printf,1,2)));
136 static void err_output(int is_error, const char *fmt, va_list ap)
137 __attribute__((format(printf,2,0)));
139 static void err_output(int is_error, const char *fmt, va_list ap)
146 #if defined(_LARGEFILE64_SOURCE) && HAVE_FOPEN64
147 if ((log = fopen64(AP_LOG_EXEC, "a")) == NULL) {
149 if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
151 fprintf(stderr, "suexec failure: could not open log file\n");
158 fprintf(stderr, "suexec policy violation: see suexec log for more "
163 lt = localtime(&timevar);
165 fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
166 lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
167 lt->tm_hour, lt->tm_min, lt->tm_sec);
169 vfprintf(log, fmt, ap);
172 #endif /* AP_LOG_EXEC */
176 static void log_err(const char *fmt,...)
182 err_output(1, fmt, ap); /* 1 == is_error */
184 #endif /* AP_LOG_EXEC */
188 static void log_no_err(const char *fmt,...)
194 err_output(0, fmt, ap); /* 0 == !is_error */
196 #endif /* AP_LOG_EXEC */
200 static void clean_env(void)
208 /* While cleaning the environment, the environment should be clean.
209 * (e.g. malloc() may get the name of a file for writing debugging info.
210 * Bad news if MALLOC_DEBUG_FILE is set to /etc/passwd. Sprintf() may be
211 * susceptible to bad locale settings....)
214 char **envp = environ;
215 char *empty_ptr = NULL;
217 environ = &empty_ptr; /* VERY safe environment */
219 if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
220 log_err("failed to malloc memory for environment\n");
224 sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
225 cleanenv[cidx] = strdup(pathbuf);
226 if (cleanenv[cidx] == NULL) {
227 log_err("failed to malloc memory for environment\n");
232 for (ep = envp; *ep && cidx < AP_ENVBUF-1; ep++) {
233 for (idx = 0; safe_env_lst[idx]; idx++) {
234 if (!strncmp(*ep, safe_env_lst[idx],
235 strlen(safe_env_lst[idx]))) {
236 cleanenv[cidx] = *ep;
243 cleanenv[cidx] = NULL;
248 int main(int argc, char *argv[])
250 int userdir = 0; /* ~userdir flag */
251 uid_t uid; /* user information */
252 gid_t gid; /* target group placeholder */
253 char *target_uname; /* target user name */
254 char *target_gname; /* target group name */
255 char *target_homedir; /* target home directory */
256 char *actual_uname; /* actual user name */
257 char *actual_gname; /* actual group name */
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
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: (%lu)\n", (unsigned long)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);
398 if ((gr = getgrgid(atoi(target_gname))) == NULL) {
399 log_err("invalid target group id: (%s)\n", target_gname);
404 if ((actual_gname = strdup(gr->gr_name)) == NULL) {
405 log_err("failed to alloc memory\n");
411 * Initialize BS2000 user environment
417 switch (pid = ufork(target_uname)) {
419 log_err("failed to setup bs2000 environment for user %s: %s\n",
420 target_uname, strerror(errno));
424 default: /* Father */
425 while (pid != waitpid(pid, &status, 0))
427 /* @@@ FIXME: should we deal with STOP signals as well? */
428 if (WIFSIGNALED(status)) {
429 kill (getpid(), WTERMSIG(status));
431 exit(WEXITSTATUS(status));
434 #endif /*_OSD_POSIX*/
437 * Save these for later since initgroups will hose the struct
440 actual_uname = strdup(pw->pw_name);
441 target_homedir = strdup(pw->pw_dir);
442 if (actual_uname == NULL || target_homedir == NULL) {
443 log_err("failed to alloc memory\n");
448 * Log the transaction here to be sure we have an open log
449 * before we setuid().
451 log_no_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
452 target_uname, actual_uname,
453 target_gname, actual_gname,
457 * Error out if attempt is made to execute as root or as
458 * a UID less than AP_UID_MIN. Tsk tsk.
460 if ((uid == 0) || (uid < AP_UID_MIN)) {
461 log_err("cannot run as forbidden uid (%lu/%s)\n", (unsigned long)uid, cmd);
466 * Error out if attempt is made to execute as root group
467 * or as a GID less than AP_GID_MIN. Tsk tsk.
469 if ((gid == 0) || (gid < AP_GID_MIN)) {
470 log_err("cannot run as forbidden gid (%lu/%s)\n", (unsigned long)gid, cmd);
475 * Change UID/GID here so that the following tests work over NFS.
477 * Initialize the group access list for the target user,
478 * and setgid() to the target group. If unsuccessful, error out.
480 if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
481 log_err("failed to setgid (%lu: %s)\n", (unsigned long)gid, cmd);
486 * setuid() to the target user. Error out on fail.
488 if ((setuid(uid)) != 0) {
489 log_err("failed to setuid (%lu: %s)\n", (unsigned long)uid, cmd);
494 * Get the current working directory, as well as the proper
495 * document root (dependant upon whether or not it is a
496 * ~userdir request). Error out if we cannot get either one,
497 * or if the current working directory is not in the docroot.
498 * Use chdir()s and getcwd()s to avoid problems with symlinked
501 if (getcwd(cwd, AP_MAXPATH) == NULL) {
502 log_err("cannot get current working directory\n");
507 if (((chdir(target_homedir)) != 0) ||
508 ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
509 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
510 ((chdir(cwd)) != 0)) {
511 log_err("cannot get docroot information (%s)\n", target_homedir);
516 if (((chdir(AP_DOC_ROOT)) != 0) ||
517 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
518 ((chdir(cwd)) != 0)) {
519 log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
524 if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
525 log_err("command not in docroot (%s/%s)\n", cwd, cmd);
530 * Stat the cwd and verify it is a directory, or error out.
532 if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
533 log_err("cannot stat directory: (%s)\n", cwd);
538 * Error out if cwd is writable by others.
540 if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
541 log_err("directory is writable by others: (%s)\n", cwd);
546 * Error out if we cannot stat the program.
548 if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
549 log_err("cannot stat program: (%s)\n", cmd);
554 * Error out if the program is writable by others.
556 if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
557 log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
562 * Error out if the file is setuid or setgid.
564 if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
565 log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
570 * Error out if the target name/group is different from
571 * the name/group of the cwd or the program.
573 if ((uid != dir_info.st_uid) ||
574 (gid != dir_info.st_gid) ||
575 (uid != prg_info.st_uid) ||
576 (gid != prg_info.st_gid)) {
577 log_err("target uid/gid (%lu/%lu) mismatch "
578 "with directory (%lu/%lu) or program (%lu/%lu)\n",
579 (unsigned long)uid, (unsigned long)gid,
580 (unsigned long)dir_info.st_uid, (unsigned long)dir_info.st_gid,
581 (unsigned long)prg_info.st_uid, (unsigned long)prg_info.st_gid);
585 * Error out if the program is not executable for the user.
586 * Otherwise, she won't find any error in the logs except for
587 * "[error] Premature end of script headers: ..."
589 if (!(prg_info.st_mode & S_IXUSR)) {
590 log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
594 #ifdef AP_SUEXEC_UMASK
596 * umask() uses inverse logic; bits are CLEAR for allowed access.
598 if ((~AP_SUEXEC_UMASK) & 0022) {
599 log_err("notice: AP_SUEXEC_UMASK of %03o allows "
600 "write permission to group and/or other\n", AP_SUEXEC_UMASK);
602 umask(AP_SUEXEC_UMASK);
603 #endif /* AP_SUEXEC_UMASK */
605 /* Be sure to close the log file so the CGI can't mess with it. */
609 * ask fcntl(2) to set the FD_CLOEXEC flag on the log file,
610 * so it'll be automagically closed if the exec() call succeeds.
614 if ((fcntl(fileno(log), F_SETFD, FD_CLOEXEC) == -1)) {
615 log_err("error: can't set close-on-exec flag");
620 * In this case, exec() errors won't be logged because we have already
621 * dropped privileges and won't be able to reopen the log file.
629 * Execute the command, replacing our image with its own.
631 #ifdef NEED_HASHBANG_EMUL
632 /* We need the #! emulation when we want to execute scripts */
634 extern char **environ;
636 ap_execve(cmd, &argv[3], environ);
638 #else /*NEED_HASHBANG_EMUL*/
639 execv(cmd, &argv[3]);
640 #endif /*NEED_HASHBANG_EMUL*/
643 * (I can't help myself...sorry.)
645 * Uh oh. Still here. Where's the kaboom? There was supposed to be an
646 * EARTH-shattering kaboom!
648 * Oh well, log the failure and error out.
650 log_err("(%d)%s: exec failed (%s)\n", errno, strerror(errno), cmd);