]> granicus.if.org Git - apache/blob - support/suexec.c
Update copyright to 2001
[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 #include "ap_config_auto.h"
85
86 #if HAVE_PWD_H
87 #include <pwd.h>
88 #endif
89
90 #if HAVE_GRP_H
91 #include <grp.h>
92 #endif
93
94 /*
95  ***********************************************************************
96  * There is no initgroups() in QNX, so I believe this is safe :-)
97  * Use cc -osuexec -3 -O -mf -DQNX suexec.c to compile.
98  *
99  * May 17, 1997.
100  * Igor N. Kovalenko -- infoh@mail.wplus.net
101  ***********************************************************************
102  */
103
104 #if defined(NEED_INITGROUPS)
105 int initgroups(const char *name, gid_t basegid)
106 {
107 /* QNX and MPE do not appear to support supplementary groups. */
108     return 0;
109 }
110 #endif
111
112 #if defined(PATH_MAX)
113 #define AP_MAXPATH PATH_MAX
114 #elif defined(MAXPATHLEN)
115 #define AP_MAXPATH MAXPATHLEN
116 #else
117 #define AP_MAXPATH 8192
118 #endif
119
120 #define AP_ENVBUF 256
121
122 extern char **environ;
123 static FILE *log = NULL;
124
125 char *safe_env_lst[] =
126 {
127     "AUTH_TYPE",
128     "CONTENT_LENGTH",
129     "CONTENT_TYPE",
130     "DATE_GMT",
131     "DATE_LOCAL",
132     "DOCUMENT_NAME",
133     "DOCUMENT_PATH_INFO",
134     "DOCUMENT_ROOT",
135     "DOCUMENT_URI",
136     "FILEPATH_INFO",
137     "GATEWAY_INTERFACE",
138     "LAST_MODIFIED",
139     "PATH_INFO",
140     "PATH_TRANSLATED",
141     "QUERY_STRING",
142     "QUERY_STRING_UNESCAPED",
143     "REMOTE_ADDR",
144     "REMOTE_HOST",
145     "REMOTE_IDENT",
146     "REMOTE_PORT",
147     "REMOTE_USER",
148     "REDIRECT_QUERY_STRING",
149     "REDIRECT_STATUS",
150     "REDIRECT_URL",
151     "REQUEST_METHOD",
152     "REQUEST_URI",
153     "SCRIPT_FILENAME",
154     "SCRIPT_NAME",
155     "SCRIPT_URI",
156     "SCRIPT_URL",
157     "SERVER_ADMIN",
158     "SERVER_NAME",
159     "SERVER_ADDR",
160     "SERVER_PORT",
161     "SERVER_PROTOCOL",
162     "SERVER_SOFTWARE",
163     "UNIQUE_ID",
164     "USER_NAME",
165     "TZ",
166     NULL
167 };
168
169
170 static void err_output(const char *fmt, va_list ap)
171 {
172 #ifdef AP_LOG_EXEC
173     time_t timevar;
174     struct tm *lt;
175
176     if (!log) {
177         if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
178             fprintf(stderr, "failed to open log file\n");
179             perror("fopen");
180             exit(1);
181         }
182     }
183
184     time(&timevar);
185     lt = localtime(&timevar);
186
187     fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
188             lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
189             lt->tm_hour, lt->tm_min, lt->tm_sec);
190
191     vfprintf(log, fmt, ap);
192
193     fflush(log);
194 #endif /* AP_LOG_EXEC */
195     return;
196 }
197
198 static void log_err(const char *fmt,...)
199 {
200 #ifdef AP_LOG_EXEC
201     va_list ap;
202
203     va_start(ap, fmt);
204     err_output(fmt, ap);
205     va_end(ap);
206 #endif /* AP_LOG_EXEC */
207     return;
208 }
209
210 static void clean_env(void)
211 {
212     char pathbuf[512];
213     char **cleanenv;
214     char **ep;
215     int cidx = 0;
216     int idx;
217
218
219     if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
220         log_err("failed to malloc memory for environment\n");
221         exit(120);
222     }
223
224     sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
225     cleanenv[cidx] = strdup(pathbuf);
226     cidx++;
227
228     for (ep = environ; *ep && cidx < AP_ENVBUF-1; ep++) {
229         if (!strncmp(*ep, "HTTP_", 5)) {
230             cleanenv[cidx] = *ep;
231             cidx++;
232         }
233         else {
234             for (idx = 0; safe_env_lst[idx]; idx++) {
235                 if (!strncmp(*ep, safe_env_lst[idx],
236                              strlen(safe_env_lst[idx]))) {
237                     cleanenv[cidx] = *ep;
238                     cidx++;
239                     break;
240                 }
241             }
242         }
243     }
244
245     cleanenv[cidx] = NULL;
246
247     environ = cleanenv;
248 }
249
250 int main(int argc, char *argv[])
251 {
252     int userdir = 0;            /* ~userdir flag             */
253     uid_t uid;                  /* user information          */
254     gid_t gid;                  /* target group placeholder  */
255     char *target_uname;         /* target user name          */
256     char *target_gname;         /* target group name         */
257     char *target_homedir;       /* target home directory     */
258     char *actual_uname;         /* actual user name          */
259     char *actual_gname;         /* actual group name         */
260     char *prog;                 /* name of this program      */
261     char *cmd;                  /* command to be executed    */
262     char cwd[AP_MAXPATH];       /* current working directory */
263     char dwd[AP_MAXPATH];       /* docroot working directory */
264     struct passwd *pw;          /* password entry holder     */
265     struct group *gr;           /* group entry holder        */
266     struct stat dir_info;       /* directory info holder     */
267     struct stat prg_info;       /* program info holder       */
268
269     /*
270      * If there are a proper number of arguments, set
271      * all of them to variables.  Otherwise, error out.
272      */
273     prog = argv[0];
274     if (argc < 4) {
275         log_err("too few arguments\n");
276         exit(101);
277     }
278     target_uname = argv[1];
279     target_gname = argv[2];
280     cmd = argv[3];
281
282     /*
283      * Check existence/validity of the UID of the user
284      * running this program.  Error out if invalid.
285      */
286     uid = getuid();
287     if ((pw = getpwuid(uid)) == NULL) {
288         log_err("invalid uid: (%ld)\n", uid);
289         exit(102);
290     }
291
292     /*
293      * Check to see if the user running this program
294      * is the user allowed to do so as defined in
295      * suexec.h.  If not the allowed user, error out.
296      */
297 #ifdef _OSD_POSIX
298     /* User name comparisons are case insensitive on BS2000/OSD */
299     if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
300         log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
301         exit(103);
302     }
303 #else  /*_OSD_POSIX*/
304     if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
305         log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
306         exit(103);
307     }
308 #endif /*_OSD_POSIX*/
309
310     /*
311      * Check for a leading '/' (absolute path) in the command to be executed,
312      * or attempts to back up out of the current directory,
313      * to protect against attacks.  If any are
314      * found, error out.  Naughty naughty crackers.
315      */
316     if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
317         || (strstr(cmd, "/../") != NULL)) {
318         log_err("invalid command (%s)\n", cmd);
319         exit(104);
320     }
321
322     /*
323      * Check to see if this is a ~userdir request.  If
324      * so, set the flag, and remove the '~' from the
325      * target username.
326      */
327     if (!strncmp("~", target_uname, 1)) {
328         target_uname++;
329         userdir = 1;
330     }
331
332     /*
333      * Error out if the target username is invalid.
334      */
335     if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
336         if ((pw = getpwnam(target_uname)) == NULL) {
337             log_err("invalid target user name: (%s)\n", target_uname);
338             exit(105);
339         }
340     }
341     else {
342         if ((pw = getpwuid(atoi(target_uname))) == NULL) {
343             log_err("invalud target user id: (%s)\n", target_uname);
344             exit(121);
345         }
346     }
347
348     /*
349      * Error out if the target group name is invalid.
350      */
351     if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
352         if ((gr = getgrnam(target_gname)) == NULL) {
353             log_err("invalid target group name: (%s)\n", target_gname);
354             exit(106);
355         }
356         gid = gr->gr_gid;
357         actual_gname = strdup(gr->gr_name);
358     }
359     else {
360         gid = atoi(target_gname);
361         actual_gname = strdup(target_gname);
362     }
363
364 #ifdef _OSD_POSIX
365     /*
366      * Initialize BS2000 user environment
367      */
368     {
369         pid_t pid;
370         int status;
371
372         switch (pid = ufork(target_uname))
373         {
374         case -1:        /* Error */
375             log_err("failed to setup bs2000 environment for user %s: %s\n",
376                     target_uname, strerror(errno));
377             exit(150);
378         case 0: /* Child */
379             break;
380         default:        /* Father */
381             while (pid != waitpid(pid, &status, 0))
382                 ;
383             /* @@@ FIXME: should we deal with STOP signals as well? */
384             if (WIFSIGNALED(status))
385                 kill (getpid(), WTERMSIG(status));
386             exit(WEXITSTATUS(status));
387         }
388     }
389 #endif /*_OSD_POSIX*/
390
391     /*
392      * Save these for later since initgroups will hose the struct
393      */
394     uid = pw->pw_uid;
395     actual_uname = strdup(pw->pw_name);
396     target_homedir = strdup(pw->pw_dir);
397
398     /*
399      * Log the transaction here to be sure we have an open log 
400      * before we setuid().
401      */
402     log_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
403             target_uname, actual_uname,
404             target_gname, actual_gname,
405             cmd);
406
407     /*
408      * Error out if attempt is made to execute as root or as
409      * a UID less than AP_UID_MIN.  Tsk tsk.
410      */
411     if ((uid == 0) || (uid < AP_UID_MIN)) {
412         log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
413         exit(107);
414     }
415
416     /*
417      * Error out if attempt is made to execute as root group
418      * or as a GID less than AP_GID_MIN.  Tsk tsk.
419      */
420     if ((gid == 0) || (gid < AP_GID_MIN)) {
421         log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
422         exit(108);
423     }
424
425     /*
426      * Change UID/GID here so that the following tests work over NFS.
427      *
428      * Initialize the group access list for the target user,
429      * and setgid() to the target group. If unsuccessful, error out.
430      */
431     if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
432         log_err("failed to setgid (%ld: %s)\n", gid, cmd);
433         exit(109);
434     }
435
436     /*
437      * setuid() to the target user.  Error out on fail.
438      */
439     if ((setuid(uid)) != 0) {
440         log_err("failed to setuid (%ld: %s)\n", uid, cmd);
441         exit(110);
442     }
443
444     /*
445      * Get the current working directory, as well as the proper
446      * document root (dependant upon whether or not it is a
447      * ~userdir request).  Error out if we cannot get either one,
448      * or if the current working directory is not in the docroot.
449      * Use chdir()s and getcwd()s to avoid problems with symlinked
450      * directories.  Yuck.
451      */
452     if (getcwd(cwd, AP_MAXPATH) == NULL) {
453         log_err("cannot get current working directory\n");
454         exit(111);
455     }
456
457     if (userdir) {
458         if (((chdir(target_homedir)) != 0) ||
459             ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
460             ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
461             ((chdir(cwd)) != 0)) {
462             log_err("cannot get docroot information (%s)\n", target_homedir);
463             exit(112);
464         }
465     }
466     else {
467         if (((chdir(AP_DOC_ROOT)) != 0) ||
468             ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
469             ((chdir(cwd)) != 0)) {
470             log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
471             exit(113);
472         }
473     }
474
475     if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
476         log_err("command not in docroot (%s/%s)\n", cwd, cmd);
477         exit(114);
478     }
479
480     /*
481      * Stat the cwd and verify it is a directory, or error out.
482      */
483     if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
484         log_err("cannot stat directory: (%s)\n", cwd);
485         exit(115);
486     }
487
488     /*
489      * Error out if cwd is writable by others.
490      */
491     if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
492         log_err("directory is writable by others: (%s)\n", cwd);
493         exit(116);
494     }
495
496     /*
497      * Error out if we cannot stat the program.
498      */
499     if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
500         log_err("cannot stat program: (%s)\n", cmd);
501         exit(117);
502     }
503
504     /*
505      * Error out if the program is writable by others.
506      */
507     if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
508         log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
509         exit(118);
510     }
511
512     /*
513      * Error out if the file is setuid or setgid.
514      */
515     if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
516         log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
517         exit(119);
518     }
519
520     /*
521      * Error out if the target name/group is different from
522      * the name/group of the cwd or the program.
523      */
524     if ((uid != dir_info.st_uid) ||
525         (gid != dir_info.st_gid) ||
526         (uid != prg_info.st_uid) ||
527         (gid != prg_info.st_gid)) {
528         log_err("target uid/gid (%ld/%ld) mismatch "
529                 "with directory (%ld/%ld) or program (%ld/%ld)\n",
530                 uid, gid,
531                 dir_info.st_uid, dir_info.st_gid,
532                 prg_info.st_uid, prg_info.st_gid);
533         exit(120);
534     }
535     /*
536      * Error out if the program is not executable for the user.
537      * Otherwise, she won't find any error in the logs except for
538      * "[error] Premature end of script headers: ..."
539      */
540     if (!(prg_info.st_mode & S_IXUSR)) {
541         log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
542         exit(121);
543     }
544
545     clean_env();
546
547     /* 
548      * Be sure to close the log file so the CGI can't
549      * mess with it.  If the exec fails, it will be reopened 
550      * automatically when log_err is called.  Note that the log
551      * might not actually be open if AP_LOG_EXEC isn't defined.
552      * However, the "log" cell isn't ifdef'd so let's be defensive
553      * and assume someone might have done something with it
554      * outside an ifdef'd AP_LOG_EXEC block.
555      */
556     if (log != NULL) {
557         fclose(log);
558         log = NULL;
559     }
560
561     /*
562      * Execute the command, replacing our image with its own.
563      */
564 #ifdef NEED_HASHBANG_EMUL
565     /* We need the #! emulation when we want to execute scripts */
566     {
567         extern char **environ;
568
569         ap_execve(cmd, &argv[3], environ);
570     }
571 #else /*NEED_HASHBANG_EMUL*/
572     execv(cmd, &argv[3]);
573 #endif /*NEED_HASHBANG_EMUL*/
574
575     /*
576      * (I can't help myself...sorry.)
577      *
578      * Uh oh.  Still here.  Where's the kaboom?  There was supposed to be an
579      * EARTH-shattering kaboom!
580      *
581      * Oh well, log the failure and error out.
582      */
583     log_err("(%d)%s: exec failed (%s)\n", errno, 
584             strerror(errno), cmd);
585     exit(255);
586 }