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>
66 #define AP_MAXPATH PATH_MAX
67 #elif defined(MAXPATHLEN)
68 #define AP_MAXPATH MAXPATHLEN
70 #define AP_MAXPATH 8192
75 extern char **environ;
79 #if !defined(AP_LOG_FACILITY) && defined(LOG_AUTHPRIV)
80 #define AP_LOG_FACILITY LOG_AUTHPRIV
81 #elif !defined(AP_LOG_FACILITY)
82 #define AP_LOG_FACILITY LOG_AUTH
87 /* Non-syslog support. */
88 static FILE *log = NULL;
91 static const char *const safe_env_lst[] =
93 /* variable name starts with */
97 /* variable name is */
101 "CONTEXT_DOCUMENT_ROOT=",
106 "DOCUMENT_PATH_INFO=",
109 "GATEWAY_INTERFACE=",
115 "QUERY_STRING_UNESCAPED=",
121 "REDIRECT_ERROR_NOTES=",
123 "REDIRECT_QUERY_STRING=",
124 "REDIRECT_REMOTE_USER=",
125 "REDIRECT_SCRIPT_FILENAME=",
148 static void log_err(const char *fmt,...)
149 __attribute__((format(printf,1,2)));
150 static void log_no_err(const char *fmt,...)
151 __attribute__((format(printf,1,2)));
152 static void err_output(int is_error, const char *fmt, va_list ap)
153 __attribute__((format(printf,2,0)));
155 static void err_output(int is_error, const char *fmt, va_list ap)
157 #if defined(AP_LOG_SYSLOG)
159 openlog("suexec", LOG_PID, AP_LOG_FACILITY);
163 vsyslog(is_error ? LOG_ERR : LOG_INFO, fmt, ap);
164 #elif defined(AP_LOG_EXEC)
169 #if defined(_LARGEFILE64_SOURCE) && HAVE_FOPEN64
170 if ((log = fopen64(AP_LOG_EXEC, "a")) == NULL) {
172 if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
174 fprintf(stderr, "suexec failure: could not open log file\n");
181 fprintf(stderr, "suexec policy violation: see suexec log for more "
186 lt = localtime(&timevar);
188 fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
189 lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
190 lt->tm_hour, lt->tm_min, lt->tm_sec);
192 vfprintf(log, fmt, ap);
195 #endif /* AP_LOG_EXEC */
199 static void log_err(const char *fmt,...)
205 err_output(1, fmt, ap); /* 1 == is_error */
207 #endif /* AP_LOG_EXEC */
211 static void log_no_err(const char *fmt,...)
217 err_output(0, fmt, ap); /* 0 == !is_error */
219 #endif /* AP_LOG_EXEC */
223 static void clean_env(void)
231 /* While cleaning the environment, the environment should be clean.
232 * (e.g. malloc() may get the name of a file for writing debugging info.
233 * Bad news if MALLOC_DEBUG_FILE is set to /etc/passwd. Sprintf() may be
234 * susceptible to bad locale settings....)
237 char **envp = environ;
238 char *empty_ptr = NULL;
240 environ = &empty_ptr; /* VERY safe environment */
242 if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
243 log_err("failed to malloc memory for environment\n");
247 sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
248 cleanenv[cidx] = strdup(pathbuf);
249 if (cleanenv[cidx] == NULL) {
250 log_err("failed to malloc memory for environment\n");
255 for (ep = envp; *ep && cidx < AP_ENVBUF-1; ep++) {
256 for (idx = 0; safe_env_lst[idx]; idx++) {
257 if (!strncmp(*ep, safe_env_lst[idx],
258 strlen(safe_env_lst[idx]))) {
259 cleanenv[cidx] = *ep;
266 cleanenv[cidx] = NULL;
271 int main(int argc, char *argv[])
273 int userdir = 0; /* ~userdir flag */
274 uid_t uid; /* user information */
275 gid_t gid; /* target group placeholder */
276 char *target_uname; /* target user name */
277 char *target_gname; /* target group name */
278 char *target_homedir; /* target home directory */
279 char *actual_uname; /* actual user name */
280 char *actual_gname; /* actual group name */
281 char *cmd; /* command to be executed */
282 char cwd[AP_MAXPATH]; /* current working directory */
283 char dwd[AP_MAXPATH]; /* docroot working directory */
284 struct passwd *pw; /* password entry holder */
285 struct group *gr; /* group entry holder */
286 struct stat dir_info; /* directory info holder */
287 struct stat prg_info; /* program info holder */
290 * Start with a "clean" environment
295 * Check existence/validity of the UID of the user
296 * running this program. Error out if invalid.
299 if ((pw = getpwuid(uid)) == NULL) {
300 log_err("crit: invalid uid: (%lu)\n", (unsigned long)uid);
304 * See if this is a 'how were you compiled' request, and
308 && (! strcmp(argv[1], "-V"))
311 /* User name comparisons are case insensitive on BS2000/OSD */
312 || (! strcasecmp(AP_HTTPD_USER, pw->pw_name)))
313 #else /* _OSD_POSIX */
314 || (! strcmp(AP_HTTPD_USER, pw->pw_name)))
315 #endif /* _OSD_POSIX */
318 fprintf(stderr, " -D AP_DOC_ROOT=\"%s\"\n", AP_DOC_ROOT);
321 fprintf(stderr, " -D AP_GID_MIN=%d\n", AP_GID_MIN);
324 fprintf(stderr, " -D AP_HTTPD_USER=\"%s\"\n", AP_HTTPD_USER);
326 #if defined(AP_LOG_SYSLOG)
327 fprintf(stderr, " -D AP_LOG_SYSLOG\n");
328 #elif defined(AP_LOG_EXEC)
329 fprintf(stderr, " -D AP_LOG_EXEC=\"%s\"\n", AP_LOG_EXEC);
332 fprintf(stderr, " -D AP_SAFE_PATH=\"%s\"\n", AP_SAFE_PATH);
334 #ifdef AP_SUEXEC_UMASK
335 fprintf(stderr, " -D AP_SUEXEC_UMASK=%03o\n", AP_SUEXEC_UMASK);
338 fprintf(stderr, " -D AP_UID_MIN=%d\n", AP_UID_MIN);
340 #ifdef AP_USERDIR_SUFFIX
341 fprintf(stderr, " -D AP_USERDIR_SUFFIX=\"%s\"\n", AP_USERDIR_SUFFIX);
346 * If there are a proper number of arguments, set
347 * all of them to variables. Otherwise, error out.
350 log_err("too few arguments\n");
353 target_uname = argv[1];
354 target_gname = argv[2];
358 * Check to see if the user running this program
359 * is the user allowed to do so as defined in
360 * suexec.h. If not the allowed user, error out.
363 /* User name comparisons are case insensitive on BS2000/OSD */
364 if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
365 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
369 if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
370 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
373 #endif /*_OSD_POSIX*/
376 * Check for a leading '/' (absolute path) in the command to be executed,
377 * or attempts to back up out of the current directory,
378 * to protect against attacks. If any are
379 * found, error out. Naughty naughty crackers.
381 if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
382 || (strstr(cmd, "/../") != NULL)) {
383 log_err("invalid command (%s)\n", cmd);
388 * Check to see if this is a ~userdir request. If
389 * so, set the flag, and remove the '~' from the
392 if (!strncmp("~", target_uname, 1)) {
398 * Error out if the target username is invalid.
400 if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
401 if ((pw = getpwnam(target_uname)) == NULL) {
402 log_err("invalid target user name: (%s)\n", target_uname);
407 if ((pw = getpwuid(atoi(target_uname))) == NULL) {
408 log_err("invalid target user id: (%s)\n", target_uname);
414 * Error out if the target group name is invalid.
416 if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
417 if ((gr = getgrnam(target_gname)) == NULL) {
418 log_err("invalid target group name: (%s)\n", target_gname);
423 if ((gr = getgrgid(atoi(target_gname))) == NULL) {
424 log_err("invalid target group id: (%s)\n", target_gname);
429 if ((actual_gname = strdup(gr->gr_name)) == NULL) {
430 log_err("failed to alloc memory\n");
436 * Initialize BS2000 user environment
442 switch (pid = ufork(target_uname)) {
444 log_err("failed to setup bs2000 environment for user %s: %s\n",
445 target_uname, strerror(errno));
449 default: /* Father */
450 while (pid != waitpid(pid, &status, 0))
452 /* @@@ FIXME: should we deal with STOP signals as well? */
453 if (WIFSIGNALED(status)) {
454 kill (getpid(), WTERMSIG(status));
456 exit(WEXITSTATUS(status));
459 #endif /*_OSD_POSIX*/
462 * Save these for later since initgroups will hose the struct
465 actual_uname = strdup(pw->pw_name);
466 target_homedir = strdup(pw->pw_dir);
467 if (actual_uname == NULL || target_homedir == NULL) {
468 log_err("failed to alloc memory\n");
473 * Log the transaction here to be sure we have an open log
474 * before we setuid().
476 log_no_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
477 target_uname, actual_uname,
478 target_gname, actual_gname,
482 * Error out if attempt is made to execute as root or as
483 * a UID less than AP_UID_MIN. Tsk tsk.
485 if ((uid == 0) || (uid < AP_UID_MIN)) {
486 log_err("cannot run as forbidden uid (%lu/%s)\n", (unsigned long)uid, cmd);
491 * Error out if attempt is made to execute as root group
492 * or as a GID less than AP_GID_MIN. Tsk tsk.
494 if ((gid == 0) || (gid < AP_GID_MIN)) {
495 log_err("cannot run as forbidden gid (%lu/%s)\n", (unsigned long)gid, cmd);
500 * Change UID/GID here so that the following tests work over NFS.
502 * Initialize the group access list for the target user,
503 * and setgid() to the target group. If unsuccessful, error out.
505 if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
506 log_err("failed to setgid (%lu: %s)\n", (unsigned long)gid, cmd);
511 * setuid() to the target user. Error out on fail.
513 if ((setuid(uid)) != 0) {
514 log_err("failed to setuid (%lu: %s)\n", (unsigned long)uid, cmd);
519 * Get the current working directory, as well as the proper
520 * document root (dependant upon whether or not it is a
521 * ~userdir request). Error out if we cannot get either one,
522 * or if the current working directory is not in the docroot.
523 * Use chdir()s and getcwd()s to avoid problems with symlinked
526 if (getcwd(cwd, AP_MAXPATH) == NULL) {
527 log_err("cannot get current working directory\n");
532 if (((chdir(target_homedir)) != 0) ||
533 ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
534 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
535 ((chdir(cwd)) != 0)) {
536 log_err("cannot get docroot information (%s)\n", target_homedir);
541 if (((chdir(AP_DOC_ROOT)) != 0) ||
542 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
543 ((chdir(cwd)) != 0)) {
544 log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
549 if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
550 log_err("command not in docroot (%s/%s)\n", cwd, cmd);
555 * Stat the cwd and verify it is a directory, or error out.
557 if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
558 log_err("cannot stat directory: (%s)\n", cwd);
563 * Error out if cwd is writable by others.
565 if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
566 log_err("directory is writable by others: (%s)\n", cwd);
571 * Error out if we cannot stat the program.
573 if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
574 log_err("cannot stat program: (%s)\n", cmd);
579 * Error out if the program is writable by others.
581 if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
582 log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
587 * Error out if the file is setuid or setgid.
589 if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
590 log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
595 * Error out if the target name/group is different from
596 * the name/group of the cwd or the program.
598 if ((uid != dir_info.st_uid) ||
599 (gid != dir_info.st_gid) ||
600 (uid != prg_info.st_uid) ||
601 (gid != prg_info.st_gid)) {
602 log_err("target uid/gid (%lu/%lu) mismatch "
603 "with directory (%lu/%lu) or program (%lu/%lu)\n",
604 (unsigned long)uid, (unsigned long)gid,
605 (unsigned long)dir_info.st_uid, (unsigned long)dir_info.st_gid,
606 (unsigned long)prg_info.st_uid, (unsigned long)prg_info.st_gid);
610 * Error out if the program is not executable for the user.
611 * Otherwise, she won't find any error in the logs except for
612 * "[error] Premature end of script headers: ..."
614 if (!(prg_info.st_mode & S_IXUSR)) {
615 log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
619 #ifdef AP_SUEXEC_UMASK
621 * umask() uses inverse logic; bits are CLEAR for allowed access.
623 if ((~AP_SUEXEC_UMASK) & 0022) {
624 log_err("notice: AP_SUEXEC_UMASK of %03o allows "
625 "write permission to group and/or other\n", AP_SUEXEC_UMASK);
627 umask(AP_SUEXEC_UMASK);
628 #endif /* AP_SUEXEC_UMASK */
630 /* Be sure to close the log file so the CGI can't mess with it. */
640 * ask fcntl(2) to set the FD_CLOEXEC flag on the log file,
641 * so it'll be automagically closed if the exec() call succeeds.
645 if ((fcntl(fileno(log), F_SETFD, FD_CLOEXEC) == -1)) {
646 log_err("error: can't set close-on-exec flag");
651 * In this case, exec() errors won't be logged because we have already
652 * dropped privileges and won't be able to reopen the log file.
661 * Execute the command, replacing our image with its own.
663 #ifdef NEED_HASHBANG_EMUL
664 /* We need the #! emulation when we want to execute scripts */
666 extern char **environ;
668 ap_execve(cmd, &argv[3], environ);
670 #else /*NEED_HASHBANG_EMUL*/
671 execv(cmd, &argv[3]);
672 #endif /*NEED_HASHBANG_EMUL*/
675 * (I can't help myself...sorry.)
677 * Uh oh. Still here. Where's the kaboom? There was supposed to be an
678 * EARTH-shattering kaboom!
680 * Oh well, log the failure and error out.
682 log_err("(%d)%s: exec failed (%s)\n", errno, strerror(errno), cmd);