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