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