]> granicus.if.org Git - apache/blob - os/unix/unixd.c
Use apr-2 object perms setter
[apache] / os / unix / unixd.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 #include "ap_config.h"
18 #include "httpd.h"
19 #include "http_config.h"
20 #include "http_main.h"
21 #include "http_log.h"
22 #include "unixd.h"
23 #include "mpm_common.h"
24 #include "os.h"
25 #include "ap_mpm.h"
26 #include "apr_thread_proc.h"
27 #include "apr_strings.h"
28 #include "apr_portable.h"
29 #include "apr_perms_set.h"
30 #ifdef HAVE_PWD_H
31 #include <pwd.h>
32 #endif
33 #ifdef HAVE_SYS_RESOURCE_H
34 #include <sys/resource.h>
35 #endif
36 /* XXX */
37 #include <sys/stat.h>
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41 #ifdef HAVE_GRP_H
42 #include <grp.h>
43 #endif
44 #ifdef HAVE_STRINGS_H
45 #include <strings.h>
46 #endif
47 #ifdef HAVE_SYS_SEM_H
48 #include <sys/sem.h>
49 #endif
50 #ifdef HAVE_SYS_PRCTL_H
51 #include <sys/prctl.h>
52 #endif
53
54 unixd_config_rec ap_unixd_config;
55
56
57 AP_DECLARE(void) ap_unixd_set_rlimit(cmd_parms *cmd, struct rlimit **plimit,
58                                      const char *arg,
59                                      const char * arg2, int type)
60 {
61 #if (defined(RLIMIT_CPU) || defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_NPROC) || defined(RLIMIT_AS)) && APR_HAVE_STRUCT_RLIMIT && APR_HAVE_GETRLIMIT
62     char *str;
63     struct rlimit *limit;
64     /* If your platform doesn't define rlim_t then typedef it in ap_config.h */
65     rlim_t cur = 0;
66     rlim_t max = 0;
67
68     *plimit = (struct rlimit *)apr_pcalloc(cmd->pool, sizeof(**plimit));
69     limit = *plimit;
70     if ((getrlimit(type, limit)) != 0)  {
71         *plimit = NULL;
72         ap_log_error(APLOG_MARK, APLOG_ERR, errno, cmd->server,
73                      "%s: getrlimit failed", cmd->cmd->name);
74         return;
75     }
76
77     if ((str = ap_getword_conf(cmd->pool, &arg))) {
78         if (!strcasecmp(str, "max")) {
79             cur = limit->rlim_max;
80         }
81         else {
82             cur = atol(str);
83         }
84     }
85     else {
86         ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server,
87                      "Invalid parameters for %s", cmd->cmd->name);
88         return;
89     }
90
91     if (arg2 && (str = ap_getword_conf(cmd->pool, &arg2))) {
92         max = atol(str);
93     }
94
95     /* if we aren't running as root, cannot increase max */
96     if (geteuid()) {
97         limit->rlim_cur = cur;
98         if (max) {
99             ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server,
100                          "Must be uid 0 to raise maximum %s", cmd->cmd->name);
101         }
102     }
103     else {
104         if (cur) {
105             limit->rlim_cur = cur;
106         }
107         if (max) {
108             limit->rlim_max = max;
109         }
110     }
111 #else
112
113     ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server,
114                  "Platform does not support rlimit for %s", cmd->cmd->name);
115 #endif
116 }
117
118 APR_HOOK_STRUCT(
119                APR_HOOK_LINK(get_suexec_identity)
120 )
121
122 AP_IMPLEMENT_HOOK_RUN_FIRST(ap_unix_identity_t *, get_suexec_identity,
123                          (const request_rec *r), (r), NULL)
124
125 static apr_status_t ap_unix_create_privileged_process(
126                               apr_proc_t *newproc, const char *progname,
127                               const char * const *args,
128                               const char * const *env,
129                               apr_procattr_t *attr, ap_unix_identity_t *ugid,
130                               apr_pool_t *p)
131 {
132     int i = 0;
133     const char **newargs;
134     char *newprogname;
135     char *execuser, *execgroup;
136     const char *argv0;
137
138     if (!ap_unixd_config.suexec_enabled) {
139         return apr_proc_create(newproc, progname, args, env, attr, p);
140     }
141
142     argv0 = ap_strrchr_c(progname, '/');
143     /* Allow suexec's "/" check to succeed */
144     if (argv0 != NULL) {
145         argv0++;
146     }
147     else {
148         argv0 = progname;
149     }
150
151
152     if (ugid->userdir) {
153         execuser = apr_psprintf(p, "~%ld", (long) ugid->uid);
154     }
155     else {
156         execuser = apr_psprintf(p, "%ld", (long) ugid->uid);
157     }
158     execgroup = apr_psprintf(p, "%ld", (long) ugid->gid);
159
160     if (!execuser || !execgroup) {
161         return APR_ENOMEM;
162     }
163
164     i = 0;
165     if (args) {
166         while (args[i]) {
167             i++;
168             }
169     }
170     /* allocate space for 4 new args, the input args, and a null terminator */
171     newargs = apr_palloc(p, sizeof(char *) * (i + 4));
172     newprogname = SUEXEC_BIN;
173     newargs[0] = SUEXEC_BIN;
174     newargs[1] = execuser;
175     newargs[2] = execgroup;
176     newargs[3] = apr_pstrdup(p, argv0);
177
178     /*
179     ** using a shell to execute suexec makes no sense thus
180     ** we force everything to be APR_PROGRAM, and never
181     ** APR_SHELLCMD
182     */
183     if(apr_procattr_cmdtype_set(attr, APR_PROGRAM) != APR_SUCCESS) {
184         return APR_EGENERAL;
185     }
186
187     i = 1;
188     do {
189         newargs[i + 3] = args[i];
190     } while (args[i++]);
191
192     return apr_proc_create(newproc, newprogname, newargs, env, attr, p);
193 }
194
195 AP_DECLARE(apr_status_t) ap_os_create_privileged_process(
196     const request_rec *r,
197     apr_proc_t *newproc, const char *progname,
198     const char * const *args,
199     const char * const *env,
200     apr_procattr_t *attr, apr_pool_t *p)
201 {
202     ap_unix_identity_t *ugid = ap_run_get_suexec_identity(r);
203
204     if (ugid == NULL) {
205         return apr_proc_create(newproc, progname, args, env, attr, p);
206     }
207
208     return ap_unix_create_privileged_process(newproc, progname, args, env,
209                                               attr, ugid, p);
210 }
211
212 AP_DECLARE(apr_status_t) ap_unixd_set_proc_mutex_perms(apr_proc_mutex_t *pmutex)
213 {
214     apr_status_t rv = APR_SUCCESS;
215     if (!geteuid()) {
216         rv = APR_PERMS_SET_FN(proc_mutex)(pmutex,
217                                           APR_FPROT_GWRITE | APR_FPROT_UWRITE,
218                                           ap_unixd_config.user_id,
219                                           ap_unixd_config.group_id);
220         if (rv == APR_ENOTIMPL) {
221             rv = APR_SUCCESS;
222         }
223     }
224     return rv;
225 }
226
227 AP_DECLARE(apr_status_t) ap_unixd_set_global_mutex_perms(apr_global_mutex_t *gmutex)
228 {
229 #if !APR_PROC_MUTEX_IS_GLOBAL
230     apr_os_global_mutex_t osgmutex;
231     apr_os_global_mutex_get(&osgmutex, gmutex);
232     return ap_unixd_set_proc_mutex_perms(osgmutex.proc_mutex);
233 #else  /* APR_PROC_MUTEX_IS_GLOBAL */
234     /* In this case, apr_proc_mutex_t and apr_global_mutex_t are the same. */
235     return ap_unixd_set_proc_mutex_perms(gmutex);
236 #endif /* APR_PROC_MUTEX_IS_GLOBAL */
237 }
238
239 AP_DECLARE(apr_status_t) ap_unixd_accept(void **accepted, ap_listen_rec *lr,
240                                          apr_pool_t *ptrans)
241 {
242     apr_socket_t *csd;
243     apr_status_t status;
244 #ifdef _OSD_POSIX
245     int sockdes;
246 #endif
247
248     *accepted = NULL;
249     status = apr_socket_accept(&csd, lr->sd, ptrans);
250     if (status == APR_SUCCESS) {
251         *accepted = csd;
252 #ifdef _OSD_POSIX
253         apr_os_sock_get(&sockdes, csd);
254         if (sockdes >= FD_SETSIZE) {
255             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
256                          "new file descriptor %d is too large; you probably need "
257                          "to rebuild Apache with a larger FD_SETSIZE "
258                          "(currently %d)",
259                          sockdes, FD_SETSIZE);
260             apr_socket_close(csd);
261             return APR_EINTR;
262         }
263 #endif
264         return APR_SUCCESS;
265     }
266
267     if (APR_STATUS_IS_EINTR(status)) {
268         return status;
269     }
270     /* Our old behaviour here was to continue after accept()
271      * errors.  But this leads us into lots of troubles
272      * because most of the errors are quite fatal.  For
273      * example, EMFILE can be caused by slow descriptor
274      * leaks (say in a 3rd party module, or libc).  It's
275      * foolish for us to continue after an EMFILE.  We also
276      * seem to tickle kernel bugs on some platforms which
277      * lead to never-ending loops here.  So it seems best
278      * to just exit in most cases.
279      */
280     switch (status) {
281 #if defined(HPUX11) && defined(ENOBUFS)
282         /* On HPUX 11.x, the 'ENOBUFS, No buffer space available'
283          * error occurs because the accept() cannot complete.
284          * You will not see ENOBUFS with 10.20 because the kernel
285          * hides any occurrence from being returned to user space.
286          * ENOBUFS with 11.x's TCP/IP stack is possible, and could
287          * occur intermittently. As a work-around, we are going to
288          * ignore ENOBUFS.
289          */
290         case ENOBUFS:
291 #endif
292
293 #ifdef EPROTO
294         /* EPROTO on certain older kernels really means
295          * ECONNABORTED, so we need to ignore it for them.
296          * See discussion in new-httpd archives nh.9701
297          * search for EPROTO.
298          *
299          * Also see nh.9603, search for EPROTO:
300          * There is potentially a bug in Solaris 2.x x<6,
301          * and other boxes that implement tcp sockets in
302          * userland (i.e. on top of STREAMS).  On these
303          * systems, EPROTO can actually result in a fatal
304          * loop.  See PR#981 for example.  It's hard to
305          * handle both uses of EPROTO.
306          */
307         case EPROTO:
308 #endif
309 #ifdef ECONNABORTED
310         case ECONNABORTED:
311 #endif
312         /* Linux generates the rest of these, other tcp
313          * stacks (i.e. bsd) tend to hide them behind
314          * getsockopt() interfaces.  They occur when
315          * the net goes sour or the client disconnects
316          * after the three-way handshake has been done
317          * in the kernel but before userland has picked
318          * up the socket.
319          */
320 #ifdef ECONNRESET
321         case ECONNRESET:
322 #endif
323 #ifdef ETIMEDOUT
324         case ETIMEDOUT:
325 #endif
326 #ifdef EHOSTUNREACH
327         case EHOSTUNREACH:
328 #endif
329 #ifdef ENETUNREACH
330         case ENETUNREACH:
331 #endif
332         /* EAGAIN/EWOULDBLOCK can be returned on BSD-derived
333          * TCP stacks when the connection is aborted before
334          * we call connect, but only because our listener
335          * sockets are non-blocking (AP_NONBLOCK_WHEN_MULTI_LISTEN)
336          */
337 #ifdef EAGAIN
338         case EAGAIN:
339 #endif
340 #ifdef EWOULDBLOCK
341 #if !defined(EAGAIN) || EAGAIN != EWOULDBLOCK
342         case EWOULDBLOCK:
343 #endif
344 #endif
345             break;
346 #ifdef ENETDOWN
347         case ENETDOWN:
348             /*
349              * When the network layer has been shut down, there
350              * is not much use in simply exiting: the parent
351              * would simply re-create us (and we'd fail again).
352              * Use the CHILDFATAL code to tear the server down.
353              * @@@ Martin's idea for possible improvement:
354              * A different approach would be to define
355              * a new APEXIT_NETDOWN exit code, the reception
356              * of which would make the parent shutdown all
357              * children, then idle-loop until it detected that
358              * the network is up again, and restart the children.
359              * Ben Hyde noted that temporary ENETDOWN situations
360              * occur in mobile IP.
361              */
362             ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf,
363                          "apr_socket_accept: giving up.");
364             return APR_EGENERAL;
365 #endif /*ENETDOWN*/
366
367         default:
368 #ifdef _OSD_POSIX /* Possibly on other platforms too */
369             /* If the socket has been closed in ap_close_listeners()
370              * by the restart/stop action, we may get EBADF.
371              * Do not print an error in this case.
372              */
373             if (!lr->active && status == EBADF)
374                 return status;
375 #endif
376             ap_log_error(APLOG_MARK, APLOG_ERR, status, ap_server_conf,
377                          "apr_socket_accept: (client socket)");
378             return APR_EGENERAL;
379     }
380     return status;
381 }
382
383
384 #ifdef _OSD_POSIX
385
386 #include "apr_lib.h"
387
388 #define USER_LEN 8
389
390 typedef enum
391 {
392     bs2_unknown,     /* not initialized yet. */
393     bs2_noFORK,      /* no fork() because -X flag was specified */
394     bs2_FORK,        /* only fork() because uid != 0 */
395     bs2_UFORK        /* Normally, ufork() is used to switch identities. */
396 } bs2_ForkType;
397
398 static bs2_ForkType forktype = bs2_unknown;
399
400
401 static void ap_str_toupper(char *str)
402 {
403     while (*str) {
404         *str = apr_toupper(*str);
405         ++str;
406     }
407 }
408
409 /* Determine the method for forking off a child in such a way as to
410  * set both the POSIX and BS2000 user id's to the unprivileged user.
411  */
412 static bs2_ForkType os_forktype(int one_process)
413 {
414     /* have we checked the OS version before? If yes return the previous
415      * result - the OS release isn't going to change suddenly!
416      */
417     if (forktype == bs2_unknown) {
418         /* not initialized yet */
419
420         /* No fork if the one_process option was set */
421         if (one_process) {
422             forktype = bs2_noFORK;
423         }
424         /* If the user is unprivileged, use the normal fork() only. */
425         else if (getuid() != 0) {
426             forktype = bs2_FORK;
427         }
428         else
429             forktype = bs2_UFORK;
430     }
431     return forktype;
432 }
433
434
435
436 /* This routine complements the setuid() call: it causes the BS2000 job
437  * environment to be switched to the target user's user id.
438  * That is important if CGI scripts try to execute native BS2000 commands.
439  */
440 int os_init_job_environment(server_rec *server, const char *user_name, int one_process)
441 {
442     bs2_ForkType            type = os_forktype(one_process);
443
444     /* We can be sure that no change to uid==0 is possible because of
445      * the checks in http_core.c:set_user()
446      */
447
448     if (one_process) {
449
450         type = forktype = bs2_noFORK;
451
452         ap_log_error(APLOG_MARK, APLOG_ERR, 0, server,
453                      "The debug mode of Apache should only "
454                      "be started by an unprivileged user!");
455         return 0;
456     }
457
458     return 0;
459 }
460
461 /* BS2000 requires a "special" version of fork() before a setuid() call */
462 pid_t os_fork(const char *user)
463 {
464     pid_t pid;
465     char  username[USER_LEN+1];
466
467     switch (os_forktype(0)) {
468
469       case bs2_FORK:
470         pid = fork();
471         break;
472
473       case bs2_UFORK:
474         apr_cpystrn(username, user, sizeof username);
475
476         /* Make user name all upper case - for some versions of ufork() */
477         ap_str_toupper(username);
478
479         pid = ufork(username);
480         if (pid == -1 && errno == EPERM) {
481             ap_log_error(APLOG_MARK, APLOG_EMERG, errno,
482                          NULL, "ufork: Possible mis-configuration "
483                          "for user %s - Aborting.", user);
484             exit(1);
485         }
486         break;
487
488       default:
489         pid = 0;
490         break;
491     }
492
493     return pid;
494 }
495
496 #endif /* _OSD_POSIX */
497