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