]> granicus.if.org Git - apache/blob - support/suexec.c
Don't directly include ap_config_auto.h directly. It isn't available on
[apache] / support / suexec.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  */
54
55 /*
56  * suexec.c -- "Wrapper" support program for suEXEC behaviour for Apache
57  *
58  ***********************************************************************
59  *
60  * NOTE! : DO NOT edit this code!!!  Unless you know what you are doing,
61  *         editing this code might open up your system in unexpected 
62  *         ways to would-be crackers.  Every precaution has been taken 
63  *         to make this code as safe as possible; alter it at your own
64  *         risk.
65  *
66  ***********************************************************************
67  *
68  *
69  */
70
71 #include "ap_config.h"
72 #include <sys/param.h>
73 #include <sys/stat.h>
74 #include <sys/types.h>
75 #include <string.h>
76 #include <time.h>
77 #include <unistd.h>
78
79 #include <stdio.h>
80 #include <stdarg.h>
81 #include <stdlib.h>
82
83 #include "suexec.h"
84
85 #ifdef HAVE_PWD_H
86 #include <pwd.h>
87 #endif
88
89 #ifdef HAVE_GRP_H
90 #include <grp.h>
91 #endif
92
93 /*
94  ***********************************************************************
95  * There is no initgroups() in QNX, so I believe this is safe :-)
96  * Use cc -osuexec -3 -O -mf -DQNX suexec.c to compile.
97  *
98  * May 17, 1997.
99  * Igor N. Kovalenko -- infoh@mail.wplus.net
100  ***********************************************************************
101  */
102
103 #if defined(NEED_INITGROUPS)
104 int initgroups(const char *name, gid_t basegid)
105 {
106 /* QNX and MPE do not appear to support supplementary groups. */
107     return 0;
108 }
109 #endif
110
111 #if defined(PATH_MAX)
112 #define AP_MAXPATH PATH_MAX
113 #elif defined(MAXPATHLEN)
114 #define AP_MAXPATH MAXPATHLEN
115 #else
116 #define AP_MAXPATH 8192
117 #endif
118
119 #define AP_ENVBUF 256
120
121 extern char **environ;
122 static FILE *log = NULL;
123
124 char *safe_env_lst[] =
125 {
126     "AUTH_TYPE",
127     "CONTENT_LENGTH",
128     "CONTENT_TYPE",
129     "DATE_GMT",
130     "DATE_LOCAL",
131     "DOCUMENT_NAME",
132     "DOCUMENT_PATH_INFO",
133     "DOCUMENT_ROOT",
134     "DOCUMENT_URI",
135     "FILEPATH_INFO",
136     "GATEWAY_INTERFACE",
137     "LAST_MODIFIED",
138     "PATH_INFO",
139     "PATH_TRANSLATED",
140     "QUERY_STRING",
141     "QUERY_STRING_UNESCAPED",
142     "REMOTE_ADDR",
143     "REMOTE_HOST",
144     "REMOTE_IDENT",
145     "REMOTE_PORT",
146     "REMOTE_USER",
147     "REDIRECT_QUERY_STRING",
148     "REDIRECT_STATUS",
149     "REDIRECT_URL",
150     "REQUEST_METHOD",
151     "REQUEST_URI",
152     "SCRIPT_FILENAME",
153     "SCRIPT_NAME",
154     "SCRIPT_URI",
155     "SCRIPT_URL",
156     "SERVER_ADMIN",
157     "SERVER_NAME",
158     "SERVER_ADDR",
159     "SERVER_PORT",
160     "SERVER_PROTOCOL",
161     "SERVER_SOFTWARE",
162     "UNIQUE_ID",
163     "USER_NAME",
164     "TZ",
165     NULL
166 };
167
168
169 static void err_output(const char *fmt, va_list ap)
170 {
171 #ifdef AP_LOG_EXEC
172     time_t timevar;
173     struct tm *lt;
174
175     if (!log) {
176         if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
177             fprintf(stderr, "failed to open log file\n");
178             perror("fopen");
179             exit(1);
180         }
181     }
182
183     time(&timevar);
184     lt = localtime(&timevar);
185
186     fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
187             lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
188             lt->tm_hour, lt->tm_min, lt->tm_sec);
189
190     vfprintf(log, fmt, ap);
191
192     fflush(log);
193 #endif /* AP_LOG_EXEC */
194     return;
195 }
196
197 static void log_err(const char *fmt,...)
198 {
199 #ifdef AP_LOG_EXEC
200     va_list ap;
201
202     va_start(ap, fmt);
203     err_output(fmt, ap);
204     va_end(ap);
205 #endif /* AP_LOG_EXEC */
206     return;
207 }
208
209 static void clean_env(void)
210 {
211     char pathbuf[512];
212     char **cleanenv;
213     char **ep;
214     int cidx = 0;
215     int idx;
216
217
218     if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
219         log_err("failed to malloc memory for environment\n");
220         exit(120);
221     }
222
223     sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
224     cleanenv[cidx] = strdup(pathbuf);
225     cidx++;
226
227     for (ep = environ; *ep && cidx < AP_ENVBUF-1; ep++) {
228         if (!strncmp(*ep, "HTTP_", 5)) {
229             cleanenv[cidx] = *ep;
230             cidx++;
231         }
232         else {
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;
237                     cidx++;
238                     break;
239                 }
240             }
241         }
242     }
243
244     cleanenv[cidx] = NULL;
245
246     environ = cleanenv;
247 }
248
249 int main(int argc, char *argv[])
250 {
251     int userdir = 0;            /* ~userdir flag             */
252     uid_t uid;                  /* user information          */
253     gid_t gid;                  /* target group placeholder  */
254     char *target_uname;         /* target user name          */
255     char *target_gname;         /* target group name         */
256     char *target_homedir;       /* target home directory     */
257     char *actual_uname;         /* actual user name          */
258     char *actual_gname;         /* actual group name         */
259     char *prog;                 /* name of this program      */
260     char *cmd;                  /* command to be executed    */
261     char cwd[AP_MAXPATH];       /* current working directory */
262     char dwd[AP_MAXPATH];       /* docroot working directory */
263     struct passwd *pw;          /* password entry holder     */
264     struct group *gr;           /* group entry holder        */
265     struct stat dir_info;       /* directory info holder     */
266     struct stat prg_info;       /* program info holder       */
267
268     /*
269      * If there are a proper number of arguments, set
270      * all of them to variables.  Otherwise, error out.
271      */
272     prog = argv[0];
273     if (argc < 4) {
274         log_err("too few arguments\n");
275         exit(101);
276     }
277     target_uname = argv[1];
278     target_gname = argv[2];
279     cmd = argv[3];
280
281     /*
282      * Check existence/validity of the UID of the user
283      * running this program.  Error out if invalid.
284      */
285     uid = getuid();
286     if ((pw = getpwuid(uid)) == NULL) {
287         log_err("invalid uid: (%ld)\n", uid);
288         exit(102);
289     }
290
291     /*
292      * Check to see if the user running this program
293      * is the user allowed to do so as defined in
294      * suexec.h.  If not the allowed user, error out.
295      */
296 #ifdef _OSD_POSIX
297     /* User name comparisons are case insensitive on BS2000/OSD */
298     if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
299         log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
300         exit(103);
301     }
302 #else  /*_OSD_POSIX*/
303     if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
304         log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
305         exit(103);
306     }
307 #endif /*_OSD_POSIX*/
308
309     /*
310      * Check for a leading '/' (absolute path) in the command to be executed,
311      * or attempts to back up out of the current directory,
312      * to protect against attacks.  If any are
313      * found, error out.  Naughty naughty crackers.
314      */
315     if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
316         || (strstr(cmd, "/../") != NULL)) {
317         log_err("invalid command (%s)\n", cmd);
318         exit(104);
319     }
320
321     /*
322      * Check to see if this is a ~userdir request.  If
323      * so, set the flag, and remove the '~' from the
324      * target username.
325      */
326     if (!strncmp("~", target_uname, 1)) {
327         target_uname++;
328         userdir = 1;
329     }
330
331     /*
332      * Error out if the target username is invalid.
333      */
334     if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
335         if ((pw = getpwnam(target_uname)) == NULL) {
336             log_err("invalid target user name: (%s)\n", target_uname);
337             exit(105);
338         }
339     }
340     else {
341         if ((pw = getpwuid(atoi(target_uname))) == NULL) {
342             log_err("invalud target user id: (%s)\n", target_uname);
343             exit(121);
344         }
345     }
346
347     /*
348      * Error out if the target group name is invalid.
349      */
350     if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
351         if ((gr = getgrnam(target_gname)) == NULL) {
352             log_err("invalid target group name: (%s)\n", target_gname);
353             exit(106);
354         }
355         gid = gr->gr_gid;
356         actual_gname = strdup(gr->gr_name);
357     }
358     else {
359         gid = atoi(target_gname);
360         actual_gname = strdup(target_gname);
361     }
362
363 #ifdef _OSD_POSIX
364     /*
365      * Initialize BS2000 user environment
366      */
367     {
368         pid_t pid;
369         int status;
370
371         switch (pid = ufork(target_uname))
372         {
373         case -1:        /* Error */
374             log_err("failed to setup bs2000 environment for user %s: %s\n",
375                     target_uname, strerror(errno));
376             exit(150);
377         case 0: /* Child */
378             break;
379         default:        /* Father */
380             while (pid != waitpid(pid, &status, 0))
381                 ;
382             /* @@@ FIXME: should we deal with STOP signals as well? */
383             if (WIFSIGNALED(status))
384                 kill (getpid(), WTERMSIG(status));
385             exit(WEXITSTATUS(status));
386         }
387     }
388 #endif /*_OSD_POSIX*/
389
390     /*
391      * Save these for later since initgroups will hose the struct
392      */
393     uid = pw->pw_uid;
394     actual_uname = strdup(pw->pw_name);
395     target_homedir = strdup(pw->pw_dir);
396
397     /*
398      * Log the transaction here to be sure we have an open log 
399      * before we setuid().
400      */
401     log_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
402             target_uname, actual_uname,
403             target_gname, actual_gname,
404             cmd);
405
406     /*
407      * Error out if attempt is made to execute as root or as
408      * a UID less than AP_UID_MIN.  Tsk tsk.
409      */
410     if ((uid == 0) || (uid < AP_UID_MIN)) {
411         log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
412         exit(107);
413     }
414
415     /*
416      * Error out if attempt is made to execute as root group
417      * or as a GID less than AP_GID_MIN.  Tsk tsk.
418      */
419     if ((gid == 0) || (gid < AP_GID_MIN)) {
420         log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
421         exit(108);
422     }
423
424     /*
425      * Change UID/GID here so that the following tests work over NFS.
426      *
427      * Initialize the group access list for the target user,
428      * and setgid() to the target group. If unsuccessful, error out.
429      */
430     if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
431         log_err("failed to setgid (%ld: %s)\n", gid, cmd);
432         exit(109);
433     }
434
435     /*
436      * setuid() to the target user.  Error out on fail.
437      */
438     if ((setuid(uid)) != 0) {
439         log_err("failed to setuid (%ld: %s)\n", uid, cmd);
440         exit(110);
441     }
442
443     /*
444      * Get the current working directory, as well as the proper
445      * document root (dependant upon whether or not it is a
446      * ~userdir request).  Error out if we cannot get either one,
447      * or if the current working directory is not in the docroot.
448      * Use chdir()s and getcwd()s to avoid problems with symlinked
449      * directories.  Yuck.
450      */
451     if (getcwd(cwd, AP_MAXPATH) == NULL) {
452         log_err("cannot get current working directory\n");
453         exit(111);
454     }
455
456     if (userdir) {
457         if (((chdir(target_homedir)) != 0) ||
458             ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
459             ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
460             ((chdir(cwd)) != 0)) {
461             log_err("cannot get docroot information (%s)\n", target_homedir);
462             exit(112);
463         }
464     }
465     else {
466         if (((chdir(AP_DOC_ROOT)) != 0) ||
467             ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
468             ((chdir(cwd)) != 0)) {
469             log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
470             exit(113);
471         }
472     }
473
474     if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
475         log_err("command not in docroot (%s/%s)\n", cwd, cmd);
476         exit(114);
477     }
478
479     /*
480      * Stat the cwd and verify it is a directory, or error out.
481      */
482     if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
483         log_err("cannot stat directory: (%s)\n", cwd);
484         exit(115);
485     }
486
487     /*
488      * Error out if cwd is writable by others.
489      */
490     if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
491         log_err("directory is writable by others: (%s)\n", cwd);
492         exit(116);
493     }
494
495     /*
496      * Error out if we cannot stat the program.
497      */
498     if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
499         log_err("cannot stat program: (%s)\n", cmd);
500         exit(117);
501     }
502
503     /*
504      * Error out if the program is writable by others.
505      */
506     if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
507         log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
508         exit(118);
509     }
510
511     /*
512      * Error out if the file is setuid or setgid.
513      */
514     if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
515         log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
516         exit(119);
517     }
518
519     /*
520      * Error out if the target name/group is different from
521      * the name/group of the cwd or the program.
522      */
523     if ((uid != dir_info.st_uid) ||
524         (gid != dir_info.st_gid) ||
525         (uid != prg_info.st_uid) ||
526         (gid != prg_info.st_gid)) {
527         log_err("target uid/gid (%ld/%ld) mismatch "
528                 "with directory (%ld/%ld) or program (%ld/%ld)\n",
529                 uid, gid,
530                 dir_info.st_uid, dir_info.st_gid,
531                 prg_info.st_uid, prg_info.st_gid);
532         exit(120);
533     }
534     /*
535      * Error out if the program is not executable for the user.
536      * Otherwise, she won't find any error in the logs except for
537      * "[error] Premature end of script headers: ..."
538      */
539     if (!(prg_info.st_mode & S_IXUSR)) {
540         log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
541         exit(121);
542     }
543
544     clean_env();
545
546     /* 
547      * Be sure to close the log file so the CGI can't
548      * mess with it.  If the exec fails, it will be reopened 
549      * automatically when log_err is called.  Note that the log
550      * might not actually be open if AP_LOG_EXEC isn't defined.
551      * However, the "log" cell isn't ifdef'd so let's be defensive
552      * and assume someone might have done something with it
553      * outside an ifdef'd AP_LOG_EXEC block.
554      */
555     if (log != NULL) {
556         fclose(log);
557         log = NULL;
558     }
559
560     /*
561      * Execute the command, replacing our image with its own.
562      */
563 #ifdef NEED_HASHBANG_EMUL
564     /* We need the #! emulation when we want to execute scripts */
565     {
566         extern char **environ;
567
568         ap_execve(cmd, &argv[3], environ);
569     }
570 #else /*NEED_HASHBANG_EMUL*/
571     execv(cmd, &argv[3]);
572 #endif /*NEED_HASHBANG_EMUL*/
573
574     /*
575      * (I can't help myself...sorry.)
576      *
577      * Uh oh.  Still here.  Where's the kaboom?  There was supposed to be an
578      * EARTH-shattering kaboom!
579      *
580      * Oh well, log the failure and error out.
581      */
582     log_err("(%d)%s: exec failed (%s)\n", errno, 
583             strerror(errno), cmd);
584     exit(255);
585 }