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