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>
59 #define AP_MAXPATH PATH_MAX
60 #elif defined(MAXPATHLEN)
61 #define AP_MAXPATH MAXPATHLEN
63 #define AP_MAXPATH 8192
68 extern char **environ;
69 static FILE *log = NULL;
71 static const char *const safe_env_lst[] =
73 /* variable name starts with */
77 /* variable name is */
84 "DOCUMENT_PATH_INFO=",
93 "QUERY_STRING_UNESCAPED=",
100 "REDIRECT_QUERY_STRING=",
101 "REDIRECT_REMOTE_USER=",
124 static void err_output(int is_error, const char *fmt, va_list ap)
131 if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
132 fprintf(stderr, "suexec failure: could not open log file\n");
139 fprintf(stderr, "suexec policy violation: see suexec log for more "
144 lt = localtime(&timevar);
146 fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
147 lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
148 lt->tm_hour, lt->tm_min, lt->tm_sec);
150 vfprintf(log, fmt, ap);
153 #endif /* AP_LOG_EXEC */
157 static void log_err(const char *fmt,...)
163 err_output(1, fmt, ap); /* 1 == is_error */
165 #endif /* AP_LOG_EXEC */
169 static void log_no_err(const char *fmt,...)
175 err_output(0, fmt, ap); /* 0 == !is_error */
177 #endif /* AP_LOG_EXEC */
181 static void clean_env(void)
189 /* While cleaning the environment, the environment should be clean.
190 * (e.g. malloc() may get the name of a file for writing debugging info.
191 * Bad news if MALLOC_DEBUG_FILE is set to /etc/passwd. Sprintf() may be
192 * susceptible to bad locale settings....)
195 char **envp = environ;
196 char *empty_ptr = NULL;
198 environ = &empty_ptr; /* VERY safe environment */
200 if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
201 log_err("failed to malloc memory for environment\n");
205 sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
206 cleanenv[cidx] = strdup(pathbuf);
209 for (ep = envp; *ep && cidx < AP_ENVBUF-1; ep++) {
210 for (idx = 0; safe_env_lst[idx]; idx++) {
211 if (!strncmp(*ep, safe_env_lst[idx],
212 strlen(safe_env_lst[idx]))) {
213 cleanenv[cidx] = *ep;
220 cleanenv[cidx] = NULL;
225 int main(int argc, char *argv[])
227 int userdir = 0; /* ~userdir flag */
228 uid_t uid; /* user information */
229 gid_t gid; /* target group placeholder */
230 char *target_uname; /* target user name */
231 char *target_gname; /* target group name */
232 char *target_homedir; /* target home directory */
233 char *actual_uname; /* actual user name */
234 char *actual_gname; /* actual group name */
235 char *prog; /* name of this program */
236 char *cmd; /* command to be executed */
237 char cwd[AP_MAXPATH]; /* current working directory */
238 char dwd[AP_MAXPATH]; /* docroot working directory */
239 struct passwd *pw; /* password entry holder */
240 struct group *gr; /* group entry holder */
241 struct stat dir_info; /* directory info holder */
242 struct stat prg_info; /* program info holder */
245 * Start with a "clean" environment
251 * Check existence/validity of the UID of the user
252 * running this program. Error out if invalid.
255 if ((pw = getpwuid(uid)) == NULL) {
256 log_err("crit: invalid uid: (%ld)\n", uid);
260 * See if this is a 'how were you compiled' request, and
264 && (! strcmp(argv[1], "-V"))
267 /* User name comparisons are case insensitive on BS2000/OSD */
268 || (! strcasecmp(AP_HTTPD_USER, pw->pw_name)))
269 #else /* _OSD_POSIX */
270 || (! strcmp(AP_HTTPD_USER, pw->pw_name)))
271 #endif /* _OSD_POSIX */
274 fprintf(stderr, " -D AP_DOC_ROOT=\"%s\"\n", AP_DOC_ROOT);
277 fprintf(stderr, " -D AP_GID_MIN=%d\n", AP_GID_MIN);
280 fprintf(stderr, " -D AP_HTTPD_USER=\"%s\"\n", AP_HTTPD_USER);
283 fprintf(stderr, " -D AP_LOG_EXEC=\"%s\"\n", AP_LOG_EXEC);
286 fprintf(stderr, " -D AP_SAFE_PATH=\"%s\"\n", AP_SAFE_PATH);
288 #ifdef AP_SUEXEC_UMASK
289 fprintf(stderr, " -D AP_SUEXEC_UMASK=%03o\n", AP_SUEXEC_UMASK);
292 fprintf(stderr, " -D AP_UID_MIN=%d\n", AP_UID_MIN);
294 #ifdef AP_USERDIR_SUFFIX
295 fprintf(stderr, " -D AP_USERDIR_SUFFIX=\"%s\"\n", AP_USERDIR_SUFFIX);
300 * If there are a proper number of arguments, set
301 * all of them to variables. Otherwise, error out.
304 log_err("too few arguments\n");
307 target_uname = argv[1];
308 target_gname = argv[2];
312 * Check to see if the user running this program
313 * is the user allowed to do so as defined in
314 * suexec.h. If not the allowed user, error out.
317 /* User name comparisons are case insensitive on BS2000/OSD */
318 if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
319 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
323 if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
324 log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
327 #endif /*_OSD_POSIX*/
330 * Check for a leading '/' (absolute path) in the command to be executed,
331 * or attempts to back up out of the current directory,
332 * to protect against attacks. If any are
333 * found, error out. Naughty naughty crackers.
335 if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
336 || (strstr(cmd, "/../") != NULL)) {
337 log_err("invalid command (%s)\n", cmd);
342 * Check to see if this is a ~userdir request. If
343 * so, set the flag, and remove the '~' from the
346 if (!strncmp("~", target_uname, 1)) {
352 * Error out if the target username is invalid.
354 if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
355 if ((pw = getpwnam(target_uname)) == NULL) {
356 log_err("invalid target user name: (%s)\n", target_uname);
361 if ((pw = getpwuid(atoi(target_uname))) == NULL) {
362 log_err("invalid target user id: (%s)\n", target_uname);
368 * Error out if the target group name is invalid.
370 if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
371 if ((gr = getgrnam(target_gname)) == NULL) {
372 log_err("invalid target group name: (%s)\n", target_gname);
377 if ((gr = getgrgid(atoi(target_gname))) == NULL) {
378 log_err("invalid target group id: (%s)\n", target_gname);
383 actual_gname = strdup(gr->gr_name);
387 * Initialize BS2000 user environment
393 switch (pid = ufork(target_uname)) {
395 log_err("failed to setup bs2000 environment for user %s: %s\n",
396 target_uname, strerror(errno));
400 default: /* Father */
401 while (pid != waitpid(pid, &status, 0))
403 /* @@@ FIXME: should we deal with STOP signals as well? */
404 if (WIFSIGNALED(status)) {
405 kill (getpid(), WTERMSIG(status));
407 exit(WEXITSTATUS(status));
410 #endif /*_OSD_POSIX*/
413 * Save these for later since initgroups will hose the struct
416 actual_uname = strdup(pw->pw_name);
417 target_homedir = strdup(pw->pw_dir);
420 * Log the transaction here to be sure we have an open log
421 * before we setuid().
423 log_no_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
424 target_uname, actual_uname,
425 target_gname, actual_gname,
429 * Error out if attempt is made to execute as root or as
430 * a UID less than AP_UID_MIN. Tsk tsk.
432 if ((uid == 0) || (uid < AP_UID_MIN)) {
433 log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
438 * Error out if attempt is made to execute as root group
439 * or as a GID less than AP_GID_MIN. Tsk tsk.
441 if ((gid == 0) || (gid < AP_GID_MIN)) {
442 log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
447 * Change UID/GID here so that the following tests work over NFS.
449 * Initialize the group access list for the target user,
450 * and setgid() to the target group. If unsuccessful, error out.
452 if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
453 log_err("failed to setgid (%ld: %s)\n", gid, cmd);
458 * setuid() to the target user. Error out on fail.
460 if ((setuid(uid)) != 0) {
461 log_err("failed to setuid (%ld: %s)\n", uid, cmd);
466 * Get the current working directory, as well as the proper
467 * document root (dependant upon whether or not it is a
468 * ~userdir request). Error out if we cannot get either one,
469 * or if the current working directory is not in the docroot.
470 * Use chdir()s and getcwd()s to avoid problems with symlinked
473 if (getcwd(cwd, AP_MAXPATH) == NULL) {
474 log_err("cannot get current working directory\n");
479 if (((chdir(target_homedir)) != 0) ||
480 ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
481 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
482 ((chdir(cwd)) != 0)) {
483 log_err("cannot get docroot information (%s)\n", target_homedir);
488 if (((chdir(AP_DOC_ROOT)) != 0) ||
489 ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
490 ((chdir(cwd)) != 0)) {
491 log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
496 if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
497 log_err("command not in docroot (%s/%s)\n", cwd, cmd);
502 * Stat the cwd and verify it is a directory, or error out.
504 if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
505 log_err("cannot stat directory: (%s)\n", cwd);
510 * Error out if cwd is writable by others.
512 if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
513 log_err("directory is writable by others: (%s)\n", cwd);
518 * Error out if we cannot stat the program.
520 if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
521 log_err("cannot stat program: (%s)\n", cmd);
526 * Error out if the program is writable by others.
528 if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
529 log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
534 * Error out if the file is setuid or setgid.
536 if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
537 log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
542 * Error out if the target name/group is different from
543 * the name/group of the cwd or the program.
545 if ((uid != dir_info.st_uid) ||
546 (gid != dir_info.st_gid) ||
547 (uid != prg_info.st_uid) ||
548 (gid != prg_info.st_gid)) {
549 log_err("target uid/gid (%ld/%ld) mismatch "
550 "with directory (%ld/%ld) or program (%ld/%ld)\n",
552 dir_info.st_uid, dir_info.st_gid,
553 prg_info.st_uid, prg_info.st_gid);
557 * Error out if the program is not executable for the user.
558 * Otherwise, she won't find any error in the logs except for
559 * "[error] Premature end of script headers: ..."
561 if (!(prg_info.st_mode & S_IXUSR)) {
562 log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
566 #ifdef AP_SUEXEC_UMASK
568 * umask() uses inverse logic; bits are CLEAR for allowed access.
570 if ((~AP_SUEXEC_UMASK) & 0022) {
571 log_err("notice: AP_SUEXEC_UMASK of %03o allows "
572 "write permission to group and/or other\n", AP_SUEXEC_UMASK);
574 umask(AP_SUEXEC_UMASK);
575 #endif /* AP_SUEXEC_UMASK */
578 * Be sure to close the log file so the CGI can't
579 * mess with it. If the exec fails, it will be reopened
580 * automatically when log_err is called. Note that the log
581 * might not actually be open if AP_LOG_EXEC isn't defined.
582 * However, the "log" cell isn't ifdef'd so let's be defensive
583 * and assume someone might have done something with it
584 * outside an ifdef'd AP_LOG_EXEC block.
592 * Execute the command, replacing our image with its own.
594 #ifdef NEED_HASHBANG_EMUL
595 /* We need the #! emulation when we want to execute scripts */
597 extern char **environ;
599 ap_execve(cmd, &argv[3], environ);
601 #else /*NEED_HASHBANG_EMUL*/
602 execv(cmd, &argv[3]);
603 #endif /*NEED_HASHBANG_EMUL*/
606 * (I can't help myself...sorry.)
608 * Uh oh. Still here. Where's the kaboom? There was supposed to be an
609 * EARTH-shattering kaboom!
611 * Oh well, log the failure and error out.
613 log_err("(%d)%s: exec failed (%s)\n", errno, strerror(errno), cmd);