Add backstop check for taint of executable name when calling exec()
[exim.git] / src / src / child.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2015 */
6 /* Copyright (c) The Exim Maintainers 2020 - 2021 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9
10 #include "exim.h"
11
12 static void (*oldsignal)(int);
13
14
15 /*************************************************
16 *          Ensure an fd has a given value        *
17 *************************************************/
18
19 /* This function is called when we want to ensure that a certain fd has a
20 specific value (one of 0, 1, 2). If it hasn't got it already, close the value
21 we want, duplicate the fd, then close the old one.
22
23 Arguments:
24   oldfd        original fd
25   newfd        the fd we want
26
27 Returns:       nothing
28 */
29
30 void
31 force_fd(int oldfd, int newfd)
32 {
33 if (oldfd == newfd) return;
34 (void)close(newfd);
35 (void)dup2(oldfd, newfd);
36 (void)close(oldfd);
37 }
38
39
40 #ifndef STAND_ALONE
41 /*************************************************
42 *   Build argv list and optionally re-exec Exim  *
43 *************************************************/
44
45 /* This function is called when Exim wants to re-exec (overlay) itself in the
46 current process. This is different to child_open_exim(), which runs another
47 Exim process in parallel (but it then calls this function). The function's
48 basic job is to build the argv list according to the values of current options
49 settings. There is a basic list that all calls require, and an additional list
50 that some do not require. Further additions can be given as additional
51 arguments. An option specifies whether the exec() is actually to happen, and if
52 so, what is to be done if it fails.
53
54 Arguments:
55   exec_type      CEE_RETURN_ARGV => don't exec; return the argv list
56                  CEE_EXEC_EXIT   => just exit() on exec failure
57                  CEE_EXEC_PANIC  => panic-die on exec failure
58   kill_v         if TRUE, don't pass on the D_v flag
59   pcount         if not NULL, points to extra size of argv required, and if
60                    CEE_RETURN_ARGV is specified, it is updated to give the
61                    number of slots used
62   minimal        TRUE if only minimal argv is required
63   acount         number of additional arguments
64   ...            further values to add to argv
65
66 Returns:         if CEE_RETURN_ARGV is given, returns a pointer to argv;
67                  otherwise, does not return
68 */
69
70 uschar **
71 child_exec_exim(int exec_type, BOOL kill_v, int *pcount, BOOL minimal,
72   int acount, ...)
73 {
74 int first_special = -1;
75 int n = 0;
76 int extra = pcount ? *pcount : 0;
77 uschar **argv;
78
79 argv = store_get((extra + acount + MAX_CLMACROS + 24) * sizeof(char *), GET_UNTAINTED);
80
81 /* In all case, the list starts out with the path, any macros, and a changed
82 config file. */
83
84 argv[n++] = exim_path;          /* assume untainted */
85 if (clmacro_count > 0)
86   {
87   memcpy(argv + n, clmacros, clmacro_count * sizeof(uschar *));
88   n += clmacro_count;
89   }
90 if (f.config_changed)
91   { argv[n++] = US"-C"; argv[n++] = config_main_filename; }
92
93 /* These values are added only for non-minimal cases. If debug_selector is
94 precisely D_v, we have to assume this was started by a non-admin user, and
95 we suppress the flag when requested. (This happens when passing on an SMTP
96 connection, and after ETRN.) If there's more debugging going on, an admin user
97 was involved, so we do pass it on. */
98
99 if (!minimal)
100   {
101   if (debug_selector == D_v)
102     {
103     if (!kill_v) argv[n++] = US"-v";
104     }
105   else
106     {
107     if (debug_selector != 0)
108       {
109       argv[n++] = string_sprintf("-d=0x%x", debug_selector);
110       if (debug_fd > 2)
111         {
112         int flags = fcntl(debug_fd, F_GETFD);
113         if (flags != -1) (void)fcntl(debug_fd, F_SETFD, flags & ~FD_CLOEXEC);
114         close(2);
115         dup2(debug_fd, 2);
116         close(debug_fd);
117         }
118       }
119     }
120   if (debug_pretrigger_buf)
121     { argv[n++] = US"-dp"; argv[n++] = string_sprintf("0x%x", debug_pretrigger_bsize); }
122   if (dtrigger_selector != 0)
123     argv[n++] = string_sprintf("-dt=0x%x", dtrigger_selector);
124   DEBUG(D_any)
125     {
126     argv[n++] = US"-MCd";
127     argv[n++] = US process_purpose;
128     }
129   if (!f.testsuite_delays)      argv[n++] = US"-odd";
130   if (f.dont_deliver)           argv[n++] = US"-N";
131   if (f.queue_smtp)             argv[n++] = US"-odqs";
132   if (f.synchronous_delivery)   argv[n++] = US"-odi";
133   if (connection_max_messages >= 0)
134     argv[n++] = string_sprintf("-oB%d", connection_max_messages);
135   if (*queue_name)
136     { argv[n++] = US"-MCG"; argv[n++] = queue_name; }
137   }
138
139 /* Now add in any others that are in the call. Remember which they were,
140 for more helpful diagnosis on failure. */
141
142 if (acount > 0)
143   {
144   va_list ap;
145   va_start(ap, acount);
146   first_special = n;
147   while (acount-- > 0)
148     argv[n++] = va_arg(ap, uschar *);
149   va_end(ap);
150   }
151
152 /* Terminate the list, and return it, if that is what is wanted. */
153
154 argv[n] = NULL;
155 if (exec_type == CEE_RETURN_ARGV)
156   {
157   if (pcount) *pcount = n;
158   return argv;
159   }
160
161 /* Otherwise, do the exec() here, and handle the consequences of an unexpected
162 failure. We know that there will always be at least one extra option in the
163 call when exec() is done here, so it can be used to add to the panic data. */
164
165 DEBUG(D_exec) debug_print_argv(CUSS argv);
166 exim_nullstd();                            /* Make sure std{in,out,err} exist */
167 execv(CS argv[0], (char *const *)argv);
168
169 log_write(0,
170   LOG_MAIN | (exec_type == CEE_EXEC_EXIT ? LOG_PANIC : LOG_PANIC_DIE),
171   "re-exec of exim (%s) with %s failed: %s", exim_path, argv[first_special],
172   strerror(errno));
173
174 /* Get here if exec_type == CEE_EXEC_EXIT.
175 Note: this must be _exit(), not exit(). */
176
177 _exit(EX_EXECFAILED);
178
179 return NULL;   /* To keep compilers happy */
180 }
181
182
183
184
185 /*************************************************
186 *          Create a child Exim process           *
187 *************************************************/
188
189 /* This function is called when Exim wants to run a parallel instance of itself
190 in order to inject a message via the standard input. The function creates a
191 child process and runs Exim in it. It sets up a pipe to the standard input of
192 the new process, and returns that to the caller via fdptr. The function returns
193 the pid of the new process, or -1 if things go wrong. If debug_fd is
194 non-negative, it is passed as stderr.
195
196 This interface is now a just wrapper for the more complicated function
197 child_open_exim2(), which has additional arguments. The wrapper must continue
198 to exist, even if all calls from within Exim are changed, because it is
199 documented for use from local_scan().
200
201 Argument: fdptr   pointer to int for the stdin fd
202           purpose of the child process, for debug
203 Returns:          pid of the created process or -1 if anything has gone wrong
204 */
205
206 pid_t
207 child_open_exim_function(int * fdptr, const uschar * purpose)
208 {
209 return child_open_exim2_function(fdptr, US"<>", bounce_sender_authentication,
210   purpose);
211 }
212
213
214 /* This is a more complicated function for creating a child Exim process, with
215 more arguments.
216
217 Arguments:
218   fdptr                   pointer to int for the stdin fd
219   sender                  for a sender address (data for -f)
220   sender_authentication   authenticated sender address or NULL
221   purpose                 of the child process, for debug
222
223 Returns:          pid of the created process or -1 if anything has gone wrong
224 */
225
226 pid_t
227 child_open_exim2_function(int * fdptr, uschar * sender,
228   uschar * sender_authentication, const uschar * purpose)
229 {
230 int pfd[2];
231 int save_errno;
232 pid_t pid;
233
234 /* Create the pipe and fork the process. Ensure that SIGCHLD is set to
235 SIG_DFL before forking, so that the child process can be waited for. We
236 sometimes get here with it set otherwise. Save the old state for resetting
237 on the wait. */
238
239 if (pipe(pfd) != 0) return (pid_t)(-1);
240 oldsignal = signal(SIGCHLD, SIG_DFL);
241 pid = exim_fork(purpose);
242
243 /* Child process: make the reading end of the pipe into the standard input and
244 close the writing end. If debugging, pass debug_fd as stderr. Then re-exec
245 Exim with appropriate options. In the test harness, use -odi unless queue_only
246 is set, so that the bounce is fully delivered before returning. Failure is
247 signalled with EX_EXECFAILED (specified by CEE_EXEC_EXIT), but this shouldn't
248 occur. */
249
250 if (pid == 0)
251   {
252   force_fd(pfd[pipe_read], 0);
253   (void)close(pfd[pipe_write]);
254   if (debug_fd > 0) force_fd(debug_fd, 2);
255   if (f.running_in_test_harness && !queue_only)
256     {
257     if (sender_authentication)
258       child_exec_exim(CEE_EXEC_EXIT, FALSE, NULL, FALSE, 9,
259         US "-odi", US"-t", US"-oem", US"-oi", US"-f", sender, US"-oMas",
260         sender_authentication, message_id_option);
261     else
262       child_exec_exim(CEE_EXEC_EXIT, FALSE, NULL, FALSE, 7,
263         US "-odi", US"-t", US"-oem", US"-oi", US"-f", sender,
264         message_id_option);
265     /* Control does not return here. */
266     }
267   else   /* Not test harness */
268     {
269     if (sender_authentication)
270       child_exec_exim(CEE_EXEC_EXIT, FALSE, NULL, FALSE, 8,
271         US"-t", US"-oem", US"-oi", US"-f", sender, US"-oMas",
272         sender_authentication, message_id_option);
273     else
274       child_exec_exim(CEE_EXEC_EXIT, FALSE, NULL, FALSE, 6,
275         US"-t", US"-oem", US"-oi", US"-f", sender, message_id_option);
276     /* Control does not return here. */
277     }
278   }
279
280 testharness_pause_ms(100); /* let child work even longer, for exec */
281
282 /* Parent process. Save fork() errno and close the reading end of the stdin
283 pipe. */
284
285 save_errno = errno;
286 (void)close(pfd[pipe_read]);
287
288 /* Fork succeeded */
289
290 if (pid > 0)
291   {
292   *fdptr = pfd[pipe_write];   /* return writing end of stdin pipe */
293   return pid;                 /* and pid of new process */
294   }
295
296 /* Fork failed */
297
298 (void)close(pfd[pipe_write]);
299 errno = save_errno;
300 return (pid_t)(-1);
301 }
302 #endif   /* STAND_ALONE */
303
304
305
306 /*************************************************
307 *         Create a non-Exim child process        *
308 *************************************************/
309
310 /* This function creates a child process and runs the given command in it. It
311 sets up pipes to the standard input and output of the new process, and returns
312 them to the caller. The standard error is cloned to the output. If there are
313 any file descriptors "in the way" in the new process, they are closed. A new
314 umask is supplied for the process, and an optional new uid and gid are also
315 available. These are used by the queryprogram router to set an unprivileged id.
316 SIGUSR1 is always disabled in the new process, as it is not going to be running
317 Exim (the function child_open_exim() is provided for that). This function
318 returns the pid of the new process, or -1 if things go wrong.
319
320 Arguments:
321   argv        the argv for exec in the new process
322   envp        the envp for exec in the new process
323   newumask    umask to set in the new process
324   newuid      point to uid for the new process or NULL for no change
325   newgid      point to gid for the new process or NULL for no change
326   infdptr     pointer to int into which the fd of the stdin of the new process
327                 is placed
328   outfdptr    pointer to int into which the fd of the stdout/stderr of the new
329                 process is placed
330   wd          if not NULL, a path to be handed to chdir() in the new process
331   make_leader if TRUE, make the new process a process group leader
332   purpose     for debug: reason for running the task
333
334 Returns:      the pid of the created process or -1 if anything has gone wrong
335 */
336
337 pid_t
338 child_open_uid(const uschar **argv, const uschar **envp, int newumask,
339   uid_t *newuid, gid_t *newgid, int *infdptr, int *outfdptr, uschar *wd,
340   BOOL make_leader, const uschar * purpose)
341 {
342 int save_errno;
343 int inpfd[2], outpfd[2];
344 pid_t pid;
345
346 if (is_tainted(argv[0]))
347   {
348   log_write(0, LOG_MAIN | LOG_PANIC, "Attempt to exec tainted path: '%s'", argv[0]);
349   return (pid_t)(-1);
350   }
351
352 /* Create the pipes. */
353
354 if (pipe(inpfd) != 0) return (pid_t)(-1);
355 if (pipe(outpfd) != 0)
356   {
357   (void)close(inpfd[pipe_read]);
358   (void)close(inpfd[pipe_write]);
359   return (pid_t)(-1);
360   }
361
362 /* Fork the process. Ensure that SIGCHLD is set to SIG_DFL before forking, so
363 that the child process can be waited for. We sometimes get here with it set
364 otherwise. Save the old state for resetting on the wait. */
365
366 oldsignal = signal(SIGCHLD, SIG_DFL);
367 pid = exim_fork(purpose);
368
369 /* Handle the child process. First, set the required environment. We must do
370 this before messing with the pipes, in order to be able to write debugging
371 output when things go wrong. */
372
373 if (pid == 0)
374   {
375   signal(SIGUSR1, SIG_IGN);
376   signal(SIGPIPE, SIG_DFL);
377
378   if (newgid && setgid(*newgid) < 0)
379     {
380     DEBUG(D_any) debug_printf("failed to set gid=%ld in subprocess: %s\n",
381       (long int)(*newgid), strerror(errno));
382     goto CHILD_FAILED;
383     }
384
385   if (newuid && setuid(*newuid) < 0)
386     {
387     DEBUG(D_any) debug_printf("failed to set uid=%ld in subprocess: %s\n",
388       (long int)(*newuid), strerror(errno));
389     goto CHILD_FAILED;
390     }
391
392   (void)umask(newumask);
393
394   if (wd && Uchdir(wd) < 0)
395     {
396     DEBUG(D_any) debug_printf("failed to chdir to %s: %s\n", wd,
397       strerror(errno));
398     goto CHILD_FAILED;
399     }
400
401   /* Becomes a process group leader if requested, and then organize the pipes.
402   Any unexpected failure is signalled with EX_EXECFAILED; these are all "should
403   never occur" failures, except for exec failing because the command doesn't
404   exist. */
405
406   if (make_leader && setpgid(0,0) < 0)
407     {
408     DEBUG(D_any) debug_printf("failed to set group leader in subprocess: %s\n",
409       strerror(errno));
410     goto CHILD_FAILED;
411     }
412
413   (void)close(inpfd[pipe_write]);
414   force_fd(inpfd[pipe_read], 0);
415
416   (void)close(outpfd[pipe_read]);
417   force_fd(outpfd[pipe_write], 1);
418
419   (void)close(2);
420   (void)dup2(1, 2);
421
422   /* Now do the exec */
423
424   if (envp) execve(CS argv[0], (char *const *)argv, (char *const *)envp);
425   else execv(CS argv[0], (char *const *)argv);
426
427   /* Failed to execv. Signal this failure using EX_EXECFAILED. We are
428   losing the actual errno we got back, because there is no way to return
429   this information. */
430
431   CHILD_FAILED:
432   _exit(EX_EXECFAILED);      /* Note: must be _exit(), NOT exit() */
433   }
434
435 /* Parent process. Save any fork failure code, and close the reading end of the
436 stdin pipe, and the writing end of the stdout pipe. */
437
438 save_errno = errno;
439 (void)close(inpfd[pipe_read]);
440 (void)close(outpfd[pipe_write]);
441
442 /* Fork succeeded; return the input/output pipes and the pid */
443
444 if (pid > 0)
445   {
446   *infdptr = inpfd[pipe_write];
447   *outfdptr = outpfd[pipe_read];
448   return pid;
449   }
450
451 /* Fork failed; reset fork errno before returning */
452
453 (void)close(inpfd[pipe_write]);
454 (void)close(outpfd[pipe_read]);
455 errno = save_errno;
456 return (pid_t)(-1);
457 }
458
459
460
461
462 /*************************************************
463 *    Create child process without uid change     *
464 *************************************************/
465
466 /* This function is a wrapper for child_open_uid() that doesn't have the uid,
467 gid and working directory changing arguments. The function is provided so as to
468 have a clean interface for use from local_scan(), but also saves writing NULL
469 arguments several calls that would otherwise use child_open_uid().
470
471 Arguments:
472   argv        the argv for exec in the new process
473   envp        the envp for exec in the new process
474   newumask    umask to set in the new process
475   infdptr     pointer to int into which the fd of the stdin of the new process
476                 is placed
477   outfdptr    pointer to int into which the fd of the stdout/stderr of the new
478                 process is placed
479   make_leader if TRUE, make the new process a process group leader
480   purpose     for debug: reason for running the task
481
482 Returns:      the pid of the created process or -1 if anything has gone wrong
483 */
484
485 pid_t
486 child_open_function(uschar **argv, uschar **envp, int newumask, int *infdptr,
487   int *outfdptr, BOOL make_leader, const uschar * purpose)
488 {
489 return child_open_uid(CUSS argv, CUSS envp, newumask, NULL, NULL,
490   infdptr, outfdptr, NULL, make_leader, purpose);
491 }
492
493
494
495
496 /*************************************************
497 *           Close down child process             *
498 *************************************************/
499
500 /* Wait for the given process to finish, with optional timeout.
501
502 Arguments
503   pid:      the pid to wait for
504   timeout:  maximum time to wait; 0 means for as long as it takes
505
506 Returns:    >= 0          process terminated by exiting; value is process
507                             ending status; if an execve() failed, the value
508                             is typically 127 (defined as EX_EXECFAILED)
509             < 0 & > -256  process was terminated by a signal; value is the
510                             negation of the signal number
511             -256          timed out
512             -257          other error in wait(); errno still set
513 */
514
515 int
516 child_close(pid_t pid, int timeout)
517 {
518 int yield;
519
520 if (timeout > 0)
521   {
522   sigalrm_seen = FALSE;
523   ALARM(timeout);
524   }
525
526 for(;;)
527   {
528   int status;
529   pid_t rc = waitpid(pid, &status, 0);
530   if (rc == pid)
531     {
532     int lowbyte = status & 255;
533     yield = lowbyte == 0 ? (status >> 8) & 255 : -lowbyte;
534     break;
535     }
536   if (rc < 0)
537     {
538     /* This "shouldn't happen" test does happen on MacOS: for some reason
539     I do not understand we seems to get an alarm signal despite not having
540     an active alarm set. There seems to be only one, so just go round again. */
541
542     if (errno == EINTR && sigalrm_seen && timeout <= 0) continue;
543
544     yield = (errno == EINTR && sigalrm_seen) ? -256 : -257;
545     break;
546     }
547   }
548
549 if (timeout > 0) ALARM_CLR(0);
550
551 signal(SIGCHLD, oldsignal);   /* restore */
552 return yield;
553 }
554
555 /* End of child.c */