]> granicus.if.org Git - apache/blob - support/suexec.c
suexec: Pass the SERVER_SIGNATURE envvar through to CGIs.
[apache] / support / suexec.c
1 /* Copyright 1999-2004 The Apache Software Foundation
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 /*
17  * suexec.c -- "Wrapper" support program for suEXEC behaviour for Apache
18  *
19  ***********************************************************************
20  *
21  * NOTE! : DO NOT edit this code!!!  Unless you know what you are doing,
22  *         editing this code might open up your system in unexpected 
23  *         ways to would-be crackers.  Every precaution has been taken 
24  *         to make this code as safe as possible; alter it at your own
25  *         risk.
26  *
27  ***********************************************************************
28  *
29  *
30  */
31
32 #include "apr.h"
33 #include "ap_config.h"
34 #include "suexec.h"
35
36 #include <sys/param.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <string.h>
40 #include <time.h>
41 #if APR_HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44
45 #include <stdio.h>
46 #include <stdarg.h>
47 #include <stdlib.h>
48
49 #ifdef HAVE_PWD_H
50 #include <pwd.h>
51 #endif
52
53 #ifdef HAVE_GRP_H
54 #include <grp.h>
55 #endif
56
57 /*
58  ***********************************************************************
59  * There is no initgroups() in QNX, so I believe this is safe :-)
60  * Use cc -osuexec -3 -O -mf -DQNX suexec.c to compile.
61  *
62  * May 17, 1997.
63  * Igor N. Kovalenko -- infoh mail.wplus.net
64  ***********************************************************************
65  */
66
67 #if defined(NEED_INITGROUPS)
68 int initgroups(const char *name, gid_t basegid)
69 {
70     /* QNX and MPE do not appear to support supplementary groups. */
71     return 0;
72 }
73 #endif
74
75 #if defined(SUNOS4)
76 extern char *sys_errlist[];
77 #define strerror(x) sys_errlist[(x)]
78 #endif
79
80 #if defined(PATH_MAX)
81 #define AP_MAXPATH PATH_MAX
82 #elif defined(MAXPATHLEN)
83 #define AP_MAXPATH MAXPATHLEN
84 #else
85 #define AP_MAXPATH 8192
86 #endif
87
88 #define AP_ENVBUF 256
89
90 extern char **environ;
91 static FILE *log = NULL;
92
93 char *safe_env_lst[] =
94 {
95     /* variable name starts with */
96     "HTTP_",
97     "SSL_",
98
99     /* variable name is */
100     "AUTH_TYPE=",
101     "CONTENT_LENGTH=",
102     "CONTENT_TYPE=",
103     "DATE_GMT=",
104     "DATE_LOCAL=",
105     "DOCUMENT_NAME=",
106     "DOCUMENT_PATH_INFO=",
107     "DOCUMENT_ROOT=",
108     "DOCUMENT_URI=",
109     "GATEWAY_INTERFACE=",
110     "HTTPS=",
111     "LAST_MODIFIED=",
112     "PATH_INFO=",
113     "PATH_TRANSLATED=",
114     "QUERY_STRING=",
115     "QUERY_STRING_UNESCAPED=",
116     "REMOTE_ADDR=",
117     "REMOTE_HOST=",
118     "REMOTE_IDENT=",
119     "REMOTE_PORT=",
120     "REMOTE_USER=",
121     "REDIRECT_HANDLER=",
122     "REDIRECT_QUERY_STRING=",
123     "REDIRECT_REMOTE_USER=",
124     "REDIRECT_STATUS=",
125     "REDIRECT_URL=",
126     "REQUEST_METHOD=",
127     "REQUEST_URI=",
128     "SCRIPT_FILENAME=",
129     "SCRIPT_NAME=",
130     "SCRIPT_URI=",
131     "SCRIPT_URL=",
132     "SERVER_ADMIN=",
133     "SERVER_NAME=",
134     "SERVER_ADDR=",
135     "SERVER_PORT=",
136     "SERVER_PROTOCOL=",
137     "SERVER_SIGNATURE=",
138     "SERVER_SOFTWARE=",
139     "UNIQUE_ID=",
140     "USER_NAME=",
141     "TZ=",
142     NULL
143 };
144
145
146 static void err_output(int is_error, const char *fmt, va_list ap)
147 {
148 #ifdef AP_LOG_EXEC
149     time_t timevar;
150     struct tm *lt;
151
152     if (!log) {
153         if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
154             fprintf(stderr, "suexec failure: could not open log file\n");
155             perror("fopen");
156             exit(1);
157         }
158     }
159
160     if (is_error) {
161         fprintf(stderr, "suexec policy violation: see suexec log for more "
162                         "details\n");
163     }
164
165     time(&timevar);
166     lt = localtime(&timevar);
167
168     fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
169             lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
170             lt->tm_hour, lt->tm_min, lt->tm_sec);
171
172     vfprintf(log, fmt, ap);
173
174     fflush(log);
175 #endif /* AP_LOG_EXEC */
176     return;
177 }
178
179 static void log_err(const char *fmt,...)
180 {
181 #ifdef AP_LOG_EXEC
182     va_list ap;
183
184     va_start(ap, fmt);
185     err_output(1, fmt, ap); /* 1 == is_error */
186     va_end(ap);
187 #endif /* AP_LOG_EXEC */
188     return;
189 }
190
191 static void log_no_err(const char *fmt,...)
192 {
193 #ifdef AP_LOG_EXEC
194     va_list ap;
195
196     va_start(ap, fmt);
197     err_output(0, fmt, ap); /* 0 == !is_error */
198     va_end(ap);
199 #endif /* AP_LOG_EXEC */
200     return;
201 }
202
203 static void clean_env(void)
204 {
205     char pathbuf[512];
206     char **cleanenv;
207     char **ep;
208     int cidx = 0;
209     int idx;
210
211     /* While cleaning the environment, the environment should be clean.
212      * (e.g. malloc() may get the name of a file for writing debugging info.
213      * Bad news if MALLOC_DEBUG_FILE is set to /etc/passwd.  Sprintf() may be
214      * susceptible to bad locale settings....)
215      * (from PR 2790)
216      */
217     char **envp = environ;
218     char *empty_ptr = NULL;
219  
220     environ = &empty_ptr; /* VERY safe environment */
221     
222     if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
223         log_err("failed to malloc memory for environment\n");
224         exit(120);
225     }
226
227     sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
228     cleanenv[cidx] = strdup(pathbuf);
229     cidx++;
230
231     for (ep = envp; *ep && cidx < AP_ENVBUF-1; ep++) {
232         for (idx = 0; safe_env_lst[idx]; idx++) {
233             if (!strncmp(*ep, safe_env_lst[idx],
234                          strlen(safe_env_lst[idx]))) {
235                 cleanenv[cidx] = *ep;
236                 cidx++;
237                 break;
238             }
239         }
240     }
241
242     cleanenv[cidx] = NULL;
243
244     environ = cleanenv;
245 }
246
247 int main(int argc, char *argv[])
248 {
249     int userdir = 0;        /* ~userdir flag             */
250     uid_t uid;              /* user information          */
251     gid_t gid;              /* target group placeholder  */
252     char *target_uname;     /* target user name          */
253     char *target_gname;     /* target group name         */
254     char *target_homedir;   /* target home directory     */
255     char *actual_uname;     /* actual user name          */
256     char *actual_gname;     /* actual group name         */
257     char *prog;             /* name of this program      */
258     char *cmd;              /* command to be executed    */
259     char cwd[AP_MAXPATH];   /* current working directory */
260     char dwd[AP_MAXPATH];   /* docroot working directory */
261     struct passwd *pw;      /* password entry holder     */
262     struct group *gr;       /* group entry holder        */
263     struct stat dir_info;   /* directory info holder     */
264     struct stat prg_info;   /* program info holder       */
265
266     /*
267      * Start with a "clean" environment
268      */
269     clean_env();
270
271     prog = argv[0];
272     /*
273      * Check existence/validity of the UID of the user
274      * running this program.  Error out if invalid.
275      */
276     uid = getuid();
277     if ((pw = getpwuid(uid)) == NULL) {
278         log_err("crit: invalid uid: (%ld)\n", uid);
279         exit(102);
280     }
281     /*
282      * See if this is a 'how were you compiled' request, and
283      * comply if so.
284      */
285     if ((argc > 1)
286         && (! strcmp(argv[1], "-V"))
287         && ((uid == 0)
288 #ifdef _OSD_POSIX
289         /* User name comparisons are case insensitive on BS2000/OSD */
290             || (! strcasecmp(AP_HTTPD_USER, pw->pw_name)))
291 #else  /* _OSD_POSIX */
292             || (! strcmp(AP_HTTPD_USER, pw->pw_name)))
293 #endif /* _OSD_POSIX */
294         ) {
295 #ifdef AP_DOC_ROOT
296         fprintf(stderr, " -D AP_DOC_ROOT=\"%s\"\n", AP_DOC_ROOT);
297 #endif
298 #ifdef AP_GID_MIN
299         fprintf(stderr, " -D AP_GID_MIN=%d\n", AP_GID_MIN);
300 #endif
301 #ifdef AP_HTTPD_USER
302         fprintf(stderr, " -D AP_HTTPD_USER=\"%s\"\n", AP_HTTPD_USER);
303 #endif
304 #ifdef AP_LOG_EXEC
305         fprintf(stderr, " -D AP_LOG_EXEC=\"%s\"\n", AP_LOG_EXEC);
306 #endif
307 #ifdef AP_SAFE_PATH
308         fprintf(stderr, " -D AP_SAFE_PATH=\"%s\"\n", AP_SAFE_PATH);
309 #endif
310 #ifdef AP_SUEXEC_UMASK
311         fprintf(stderr, " -D AP_SUEXEC_UMASK=%03o\n", AP_SUEXEC_UMASK);
312 #endif
313 #ifdef AP_UID_MIN
314         fprintf(stderr, " -D AP_UID_MIN=%d\n", AP_UID_MIN);
315 #endif
316 #ifdef AP_USERDIR_SUFFIX
317         fprintf(stderr, " -D AP_USERDIR_SUFFIX=\"%s\"\n", AP_USERDIR_SUFFIX);
318 #endif
319         exit(0);
320     }
321     /*
322      * If there are a proper number of arguments, set
323      * all of them to variables.  Otherwise, error out.
324      */
325     if (argc < 4) {
326         log_err("too few arguments\n");
327         exit(101);
328     }
329     target_uname = argv[1];
330     target_gname = argv[2];
331     cmd = argv[3];
332
333     /*
334      * Check to see if the user running this program
335      * is the user allowed to do so as defined in
336      * suexec.h.  If not the allowed user, error out.
337      */
338 #ifdef _OSD_POSIX
339     /* User name comparisons are case insensitive on BS2000/OSD */
340     if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
341         log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
342         exit(103);
343     }
344 #else  /*_OSD_POSIX*/
345     if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
346         log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
347         exit(103);
348     }
349 #endif /*_OSD_POSIX*/
350
351     /*
352      * Check for a leading '/' (absolute path) in the command to be executed,
353      * or attempts to back up out of the current directory,
354      * to protect against attacks.  If any are
355      * found, error out.  Naughty naughty crackers.
356      */
357     if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
358         || (strstr(cmd, "/../") != NULL)) {
359         log_err("invalid command (%s)\n", cmd);
360         exit(104);
361     }
362
363     /*
364      * Check to see if this is a ~userdir request.  If
365      * so, set the flag, and remove the '~' from the
366      * target username.
367      */
368     if (!strncmp("~", target_uname, 1)) {
369         target_uname++;
370         userdir = 1;
371     }
372
373     /*
374      * Error out if the target username is invalid.
375      */
376     if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
377         if ((pw = getpwnam(target_uname)) == NULL) {
378             log_err("invalid target user name: (%s)\n", target_uname);
379             exit(105);
380         }
381     }
382     else {
383         if ((pw = getpwuid(atoi(target_uname))) == NULL) {
384             log_err("invalid target user id: (%s)\n", target_uname);
385             exit(121);
386         }
387     }
388
389     /*
390      * Error out if the target group name is invalid.
391      */
392     if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
393         if ((gr = getgrnam(target_gname)) == NULL) {
394             log_err("invalid target group name: (%s)\n", target_gname);
395             exit(106);
396         }
397         gid = gr->gr_gid;
398         actual_gname = strdup(gr->gr_name);
399     }
400     else {
401         gid = atoi(target_gname);
402         actual_gname = strdup(target_gname);
403     }
404
405 #ifdef _OSD_POSIX
406     /*
407      * Initialize BS2000 user environment
408      */
409     {
410         pid_t pid;
411         int status;
412
413         switch (pid = ufork(target_uname)) {
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             }
427             exit(WEXITSTATUS(status));
428         }
429     }
430 #endif /*_OSD_POSIX*/
431     
432     /*
433      * Save these for later since initgroups will hose the struct
434      */
435     uid = pw->pw_uid;
436     actual_uname = strdup(pw->pw_name);
437     target_homedir = strdup(pw->pw_dir);
438
439     /*
440      * Log the transaction here to be sure we have an open log 
441      * before we setuid().
442      */
443     log_no_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
444                target_uname, actual_uname,
445                target_gname, actual_gname,
446                cmd);
447
448     /*
449      * Error out if attempt is made to execute as root or as
450      * a UID less than AP_UID_MIN.  Tsk tsk.
451      */
452     if ((uid == 0) || (uid < AP_UID_MIN)) {
453         log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
454         exit(107);
455     }
456
457     /*
458      * Error out if attempt is made to execute as root group
459      * or as a GID less than AP_GID_MIN.  Tsk tsk.
460      */
461     if ((gid == 0) || (gid < AP_GID_MIN)) {
462         log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
463         exit(108);
464     }
465
466     /*
467      * Change UID/GID here so that the following tests work over NFS.
468      *
469      * Initialize the group access list for the target user,
470      * and setgid() to the target group. If unsuccessful, error out.
471      */
472     if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
473         log_err("failed to setgid (%ld: %s)\n", gid, cmd);
474         exit(109);
475     }
476
477     /*
478      * setuid() to the target user.  Error out on fail.
479      */
480     if ((setuid(uid)) != 0) {
481         log_err("failed to setuid (%ld: %s)\n", uid, cmd);
482         exit(110);
483     }
484
485     /*
486      * Get the current working directory, as well as the proper
487      * document root (dependant upon whether or not it is a
488      * ~userdir request).  Error out if we cannot get either one,
489      * or if the current working directory is not in the docroot.
490      * Use chdir()s and getcwd()s to avoid problems with symlinked
491      * directories.  Yuck.
492      */
493     if (getcwd(cwd, AP_MAXPATH) == NULL) {
494         log_err("cannot get current working directory\n");
495         exit(111);
496     }
497
498     if (userdir) {
499         if (((chdir(target_homedir)) != 0) ||
500             ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
501             ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
502             ((chdir(cwd)) != 0)) {
503             log_err("cannot get docroot information (%s)\n", target_homedir);
504             exit(112);
505         }
506     }
507     else {
508         if (((chdir(AP_DOC_ROOT)) != 0) ||
509             ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
510             ((chdir(cwd)) != 0)) {
511             log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
512             exit(113);
513         }
514     }
515
516     if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
517         log_err("command not in docroot (%s/%s)\n", cwd, cmd);
518         exit(114);
519     }
520
521     /*
522      * Stat the cwd and verify it is a directory, or error out.
523      */
524     if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
525         log_err("cannot stat directory: (%s)\n", cwd);
526         exit(115);
527     }
528
529     /*
530      * Error out if cwd is writable by others.
531      */
532     if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
533         log_err("directory is writable by others: (%s)\n", cwd);
534         exit(116);
535     }
536
537     /*
538      * Error out if we cannot stat the program.
539      */
540     if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
541         log_err("cannot stat program: (%s)\n", cmd);
542         exit(117);
543     }
544
545     /*
546      * Error out if the program is writable by others.
547      */
548     if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
549         log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
550         exit(118);
551     }
552
553     /*
554      * Error out if the file is setuid or setgid.
555      */
556     if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
557         log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
558         exit(119);
559     }
560
561     /*
562      * Error out if the target name/group is different from
563      * the name/group of the cwd or the program.
564      */
565     if ((uid != dir_info.st_uid) ||
566         (gid != dir_info.st_gid) ||
567         (uid != prg_info.st_uid) ||
568         (gid != prg_info.st_gid)) {
569         log_err("target uid/gid (%ld/%ld) mismatch "
570                 "with directory (%ld/%ld) or program (%ld/%ld)\n",
571                 uid, gid,
572                 dir_info.st_uid, dir_info.st_gid,
573                 prg_info.st_uid, prg_info.st_gid);
574         exit(120);
575     }
576     /*
577      * Error out if the program is not executable for the user.
578      * Otherwise, she won't find any error in the logs except for
579      * "[error] Premature end of script headers: ..."
580      */
581     if (!(prg_info.st_mode & S_IXUSR)) {
582         log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
583         exit(121);
584     }
585
586 #ifdef AP_SUEXEC_UMASK
587     /*
588      * umask() uses inverse logic; bits are CLEAR for allowed access.
589      */
590     if ((~AP_SUEXEC_UMASK) & 0022) {
591         log_err("notice: AP_SUEXEC_UMASK of %03o allows "
592                 "write permission to group and/or other\n", AP_SUEXEC_UMASK);
593     }
594     umask(AP_SUEXEC_UMASK);
595 #endif /* AP_SUEXEC_UMASK */
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, strerror(errno), cmd);
634     exit(255);
635 }