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