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