xref: /netbsd-src/external/bsd/cron/dist/do_command.c (revision 796c32c94f6e154afc9de0f63da35c91bb739b45)
1 /*	$NetBSD: do_command.c,v 1.11 2017/09/28 02:32:51 christos Exp $	*/
2 
3 /* Copyright 1988,1990,1993,1994 by Paul Vixie
4  * All rights reserved
5  */
6 
7 /*
8  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
9  * Copyright (c) 1997,2000 by Internet Software Consortium, Inc.
10  *
11  * Permission to use, copy, modify, and distribute this software for any
12  * purpose with or without fee is hereby granted, provided that the above
13  * copyright notice and this permission notice appear in all copies.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
16  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17  * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
18  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  */
23 #include <sys/cdefs.h>
24 #if !defined(lint) && !defined(LINT)
25 #if 0
26 static char rcsid[] = "Id: do_command.c,v 1.9 2004/01/23 18:56:42 vixie Exp";
27 #else
28 __RCSID("$NetBSD: do_command.c,v 1.11 2017/09/28 02:32:51 christos Exp $");
29 #endif
30 #endif
31 
32 #include "cron.h"
33 #include <unistd.h>
34 
35 static int		child_process(entry *);
36 static int		safe_p(const char *, const char *);
37 
38 void
39 do_command(entry *e, user *u) {
40 	int retval;
41 
42 	Debug(DPROC, ("[%ld] do_command(%s, (%s,%ld,%ld))\n",
43 		      (long)getpid(), e->cmd, u->name,
44 		      (long)e->pwd->pw_uid, (long)e->pwd->pw_gid));
45 
46 	/* fork to become asynchronous -- parent process is done immediately,
47 	 * and continues to run the normal cron code, which means return to
48 	 * tick().  the child and grandchild don't leave this function, alive.
49 	 *
50 	 * vfork() is unsuitable, since we have much to do, and the parent
51 	 * needs to be able to run off and fork other processes.
52 	 */
53 	switch (fork()) {
54 	case -1:
55 		log_it("CRON", getpid(), "error", "can't fork");
56 		break;
57 	case 0:
58 		/* child process */
59 		acquire_daemonlock(1);
60 		retval = child_process(e);
61 		Debug(DPROC, ("[%ld] child process done (rc=%d), exiting\n",
62 			      (long)getpid(), retval));
63 		_exit(retval);
64 		break;
65 	default:
66 		/* parent process */
67 		break;
68 	}
69 	Debug(DPROC, ("[%ld] main process returning to work\n",(long)getpid()));
70 }
71 
72 static void
73 sigchld_handler(int signo) {
74 	for (;;) {
75 		WAIT_T waiter;
76 		PID_T pid = waitpid(-1, &waiter, WNOHANG);
77 
78 		switch (pid) {
79 		case -1:
80 			if (errno == EINTR)
81 				continue;
82 		case 0:
83 			return;
84 		default:
85 			break;
86 		}
87 	}
88 }
89 
90 static void
91 write_data(char *volatile input_data, int *stdin_pipe, int *stdout_pipe)
92 {
93 	FILE *out = fdopen(stdin_pipe[WRITE_PIPE], "w");
94 	int need_newline = FALSE;
95 	int escaped = FALSE;
96 	int ch;
97 
98 	Debug(DPROC, ("[%ld] child2 sending data to grandchild\n",
99 		      (long)getpid()));
100 
101 #ifdef USE_PAM
102 	cron_pam_child_close();
103 #else
104 	log_close();
105 #endif
106 
107 	/* close the pipe we don't use, since we inherited it and
108 	 * are part of its reference count now.
109 	 */
110 	(void)close(stdout_pipe[READ_PIPE]);
111 
112 	/* translation:
113 	 *	\% -> %
114 	 *	%  -> \n
115 	 *	\x -> \x	for all x != %
116 	 */
117 	while ((ch = *input_data++) != '\0') {
118 		if (escaped) {
119 			if (ch != '%')
120 				(void)putc('\\', out);
121 		} else {
122 			if (ch == '%')
123 				ch = '\n';
124 		}
125 
126 		if (!(escaped = (ch == '\\'))) {
127 			(void)putc(ch, out);
128 			need_newline = (ch != '\n');
129 		}
130 	}
131 	if (escaped)
132 		(void)putc('\\', out);
133 	if (need_newline)
134 		(void)putc('\n', out);
135 
136 	/* close the pipe, causing an EOF condition.  fclose causes
137 	 * stdin_pipe[WRITE_PIPE] to be closed, too.
138 	 */
139 	(void)fclose(out);
140 
141 	Debug(DPROC, ("[%ld] child2 done sending to grandchild\n",
142 		      (long)getpid()));
143 }
144 
145 static int
146 read_data(entry *e, const char *mailto, const char *usernm, char **envp,
147     int *stdout_pipe)
148 {
149 	FILE	*in = fdopen(stdout_pipe[READ_PIPE], "r");
150 	FILE	*mail = NULL;
151 	int	bytes = 1;
152 	int	status = 0;
153 	int	ch = getc(in);
154 	int	retval = 0;
155 	sig_t	oldchld = NULL;
156 
157 	if (ch == EOF)
158 		goto out;
159 
160 	Debug(DPROC|DEXT, ("[%ld] got data (%x:%c) from grandchild\n",
161 	    (long)getpid(), ch, ch));
162 
163 	/* get name of recipient.  this is MAILTO if set to a
164 	 * valid local username; USER otherwise.
165 	 */
166 	if (mailto) {
167 		/* MAILTO was present in the environment
168 		 */
169 		if (!*mailto) {
170 			/* ... but it's empty. set to NULL
171 			 */
172 			mailto = NULL;
173 		}
174 	} else {
175 		/* MAILTO not present, set to USER.
176 		 */
177 		mailto = usernm;
178 	}
179 
180 	/*
181 	 * Unsafe, disable mailing.
182 	 */
183 	if (!safe_p(usernm, mailto))
184 		mailto = NULL;
185 
186 	/* if we are supposed to be mailing, MAILTO will
187 	 * be non-NULL.  only in this case should we set
188 	 * up the mail command and subjects and stuff...
189 	 */
190 
191 	if (mailto) {
192 		char	**env;
193 		char	mailcmd[MAX_COMMAND];
194 		char	hostname[MAXHOSTNAMELEN + 1];
195 
196 		(void)gethostname(hostname, MAXHOSTNAMELEN);
197 		if (strlens(MAILFMT, MAILARG, NULL) + 1 >= sizeof mailcmd) {
198 			log_it(usernm, getpid(), "MAIL", "mailcmd too long");
199 			retval = ERROR_EXIT;
200 			goto out;
201 		}
202 		(void)snprintf(mailcmd, sizeof(mailcmd), MAILFMT, MAILARG);
203 		oldchld = signal(SIGCHLD, SIG_DFL);
204 		if (!(mail = cron_popen(mailcmd, "w", e->pwd))) {
205 			log_itx(usernm, getpid(), "MAIL",
206 			    "cannot run `%s'", mailcmd);
207 			(void) signal(SIGCHLD, oldchld);
208 			retval = ERROR_EXIT;
209 			goto out;
210 		}
211 		(void)fprintf(mail, "From: root (Cron Daemon)\n");
212 		(void)fprintf(mail, "To: %s\n", mailto);
213 		(void)fprintf(mail, "Subject: Cron <%s@%s> %s\n",
214 		    usernm, hostname, e->cmd);
215 		(void)fprintf(mail, "Auto-Submitted: auto-generated\n");
216 #ifdef MAIL_DATE
217 		(void)fprintf(mail, "Date: %s\n", arpadate(&StartTime));
218 #endif /*MAIL_DATE*/
219 		for (env = envp;  *env;  env++)
220 			(void)fprintf(mail, "X-Cron-Env: <%s>\n", *env);
221 		(void)fprintf(mail, "\n");
222 
223 		/* this was the first char from the pipe
224 		 */
225 		(void)putc(ch, mail);
226 	}
227 
228 	/* we have to read the input pipe no matter whether
229 	 * we mail or not, but obviously we only write to
230 	 * mail pipe if we ARE mailing.
231 	 */
232 
233 	while (EOF != (ch = getc(in))) {
234 		bytes++;
235 		if (mailto)
236 			(void)putc(ch, mail);
237 	}
238 
239 	/* only close pipe if we opened it -- i.e., we're
240 	 * mailing...
241 	 */
242 
243 	if (mailto) {
244 		Debug(DPROC, ("[%ld] closing pipe to mail\n", (long)getpid()));
245 		/* Note: the pclose will probably see
246 		 * the termination of the grandchild
247 		 * in addition to the mail process, since
248 		 * it (the grandchild) is likely to exit
249 		 * after closing its stdout.
250 		 */
251 		status = cron_pclose(mail);
252 		(void) signal(SIGCHLD, oldchld);
253 	}
254 
255 	/* if there was output and we could not mail it,
256 	 * log the facts so the poor user can figure out
257 	 * what's going on.
258 	 */
259 	if (mailto && status) {
260 		log_itx(usernm, getpid(), "MAIL",
261 		    "mailed %d byte%s of output to `%s' but"
262 		    " got status %#04x", bytes,
263 		    bytes == 1 ? "" : "s", mailto, status);
264 	}
265 
266 out:
267 	Debug(DPROC, ("[%ld] got EOF from grandchild\n", (long)getpid()));
268 
269 	(void)fclose(in);	/* also closes stdout_pipe[READ_PIPE] */
270 	return retval;
271 }
272 
273 extern char **environ;
274 static int
275 child_process(entry *e) {
276 	int stdin_pipe[2], stdout_pipe[2];
277 	char * volatile input_data;
278 	char *homedir, *usernm, * volatile mailto;
279 	struct sigaction sact;
280 	char **envp = e->envp;
281 	int retval = OK_EXIT;
282 
283 	Debug(DPROC, ("[%ld] child_process('%s')\n", (long)getpid(), e->cmd));
284 
285 	setproctitle("running job");
286 
287 	/* discover some useful and important environment settings
288 	 */
289 	usernm = e->pwd->pw_name;
290 	mailto = env_get("MAILTO", envp);
291 
292 	memset(&sact, 0, sizeof(sact));
293 	sigemptyset(&sact.sa_mask);
294 	sact.sa_flags = 0;
295 #ifdef SA_RESTART
296 	sact.sa_flags |= SA_RESTART;
297 #endif
298 	sact.sa_handler = sigchld_handler;
299 	(void) sigaction(SIGCHLD, &sact, NULL);
300 
301 	/* create some pipes to talk to our future child
302 	 */
303 	if (pipe(stdin_pipe) == -1) 	/* child's stdin */
304 		log_it("CRON", getpid(), "error", "create child stdin pipe");
305 	if (pipe(stdout_pipe) == -1)	/* child's stdout */
306 		log_it("CRON", getpid(), "error", "create child stdout pipe");
307 
308 	/* since we are a forked process, we can diddle the command string
309 	 * we were passed -- nobody else is going to use it again, right?
310 	 *
311 	 * if a % is present in the command, previous characters are the
312 	 * command, and subsequent characters are the additional input to
313 	 * the command.  An escaped % will have the escape character stripped
314 	 * from it.  Subsequent %'s will be transformed into newlines,
315 	 * but that happens later.
316 	 */
317 	/*local*/{
318 		int escaped = FALSE;
319 		int ch;
320 		char *p;
321 
322 		/* translation:
323 		 *	\% -> %
324 		 *	%  -> end of command, following is command input.
325 		 *	\x -> \x	for all x != %
326 		 */
327 		input_data = p = e->cmd;
328 		while ((ch = *input_data++) != '\0') {
329  			if (escaped) {
330 				if (ch != '%')
331 					*p++ = '\\';
332 			} else {
333 				if (ch == '%') {
334 					break;
335 				}
336 			}
337 
338 			if (!(escaped = (ch == '\\'))) {
339 				*p++ = (char)ch;
340 			}
341 		}
342 		if (ch == '\0') {
343 			/* move pointer back, so that code below
344 			 * won't think we encountered % sequence */
345 			input_data--;
346 		}
347 		if (escaped)
348 			*p++ = '\\';
349 
350 		*p = '\0';
351 	}
352 
353 #ifdef USE_PAM
354 	if (!cron_pam_start(usernm))
355 		return ERROR_EXIT;
356 
357 	if (!(envp = cron_pam_getenvlist(envp))) {
358 		retval = ERROR_EXIT;
359 		goto child_process_end;
360 	}
361 #endif
362 
363 	/* fork again, this time so we can exec the user's command.
364 	 */
365 	switch (vfork()) {
366 	case -1:
367 		retval = ERROR_EXIT;
368 		goto child_process_end;
369 		/*NOTREACHED*/
370 	case 0:
371 		Debug(DPROC, ("[%ld] grandchild process vfork()'ed\n",
372 			      (long)getpid()));
373 
374 		/* write a log message.  we've waited this long to do it
375 		 * because it was not until now that we knew the PID that
376 		 * the actual user command shell was going to get and the
377 		 * PID is part of the log message.
378 		 */
379 		if ((e->flags & DONT_LOG) == 0) {
380 			char *x = mkprints(e->cmd, strlen(e->cmd));
381 
382 			log_it(usernm, getpid(), "CMD START", x);
383 			free(x);
384 		}
385 
386 		/* that's the last thing we'll log.  close the log files.
387 		 */
388 		log_close();
389 
390 		/* get new pgrp, void tty, etc.
391 		 */
392 		if (setsid() == -1)
393 			syslog(LOG_ERR, "setsid() failure: %m");
394 
395 		/* close the pipe ends that we won't use.  this doesn't affect
396 		 * the parent, who has to read and write them; it keeps the
397 		 * kernel from recording us as a potential client TWICE --
398 		 * which would keep it from sending SIGPIPE in otherwise
399 		 * appropriate circumstances.
400 		 */
401 		(void)close(stdin_pipe[WRITE_PIPE]);
402 		(void)close(stdout_pipe[READ_PIPE]);
403 
404 		/* grandchild process.  make std{in,out} be the ends of
405 		 * pipes opened by our daddy; make stderr go to stdout.
406 		 */
407 		if (stdin_pipe[READ_PIPE] != STDIN) {
408 			(void)dup2(stdin_pipe[READ_PIPE], STDIN);
409 			(void)close(stdin_pipe[READ_PIPE]);
410 		}
411 		if (stdout_pipe[WRITE_PIPE] != STDOUT) {
412 			(void)dup2(stdout_pipe[WRITE_PIPE], STDOUT);
413 			(void)close(stdout_pipe[WRITE_PIPE]);
414 		}
415 		(void)dup2(STDOUT, STDERR);
416 
417 		/* set our directory, uid and gid.  Set gid first, since once
418 		 * we set uid, we've lost root privledges.
419 		 */
420 #ifdef LOGIN_CAP
421 		{
422 #ifdef BSD_AUTH
423 			auth_session_t *as;
424 #endif
425 			login_cap_t *lc;
426 			char *p;
427 
428 			if ((lc = login_getclass(e->pwd->pw_class)) == NULL) {
429 				warnx("unable to get login class for `%s'",
430 				    e->pwd->pw_name);
431 				_exit(ERROR_EXIT);
432 			}
433 			if (setusercontext(lc, e->pwd, e->pwd->pw_uid, LOGIN_SETALL) < 0) {
434 				warnx("setusercontext failed for `%s'",
435 				    e->pwd->pw_name);
436 				_exit(ERROR_EXIT);
437 			}
438 #ifdef BSD_AUTH
439 			as = auth_open();
440 			if (as == NULL || auth_setpwd(as, e->pwd) != 0) {
441 				warn("can't malloc");
442 				_exit(ERROR_EXIT);
443 			}
444 			if (auth_approval(as, lc, usernm, "cron") <= 0) {
445 				warnx("approval failed for `%s'",
446 				    e->pwd->pw_name);
447 				_exit(ERROR_EXIT);
448 			}
449 			auth_close(as);
450 #endif /* BSD_AUTH */
451 			login_close(lc);
452 
453 			/* If no PATH specified in crontab file but
454 			 * we just added one via login.conf, add it to
455 			 * the crontab environment.
456 			 */
457 			if (env_get("PATH", envp) == NULL && environ != NULL) {
458 				if ((p = getenv("PATH")) != NULL)
459 					envp = env_set(envp, p);
460 			}
461 		}
462 #else
463 		if (setgid(e->pwd->pw_gid) != 0) {
464 			syslog(LOG_ERR, "setgid(%d) failed for %s: %m",
465 			    e->pwd->pw_gid, e->pwd->pw_name);
466 			_exit(ERROR_EXIT);
467 		}
468 		if (initgroups(usernm, e->pwd->pw_gid) != 0) {
469 			syslog(LOG_ERR, "initgroups(%s, %d) failed for %s: %m",
470 			    usernm, e->pwd->pw_gid, e->pwd->pw_name);
471 			_exit(ERROR_EXIT);
472 		}
473 #if (defined(BSD)) && (BSD >= 199103)
474 		if (setlogin(usernm) < 0) {
475 			syslog(LOG_ERR, "setlogin(%s) failure for %s: %m",
476 			    usernm, e->pwd->pw_name);
477 			_exit(ERROR_EXIT);
478 		}
479 #endif /* BSD */
480 #ifdef USE_PAM
481 		if (!cron_pam_setcred())
482 			_exit(ERROR_EXIT);
483 		cron_pam_child_close();
484 #endif
485 		if (setuid(e->pwd->pw_uid) != 0) {
486 			syslog(LOG_ERR, "setuid(%d) failed for %s: %m",
487 			    e->pwd->pw_uid, e->pwd->pw_name);
488 			_exit(ERROR_EXIT);
489 		}
490 		/* we aren't root after this... */
491 #endif /* LOGIN_CAP */
492 		homedir = env_get("HOME", envp);
493 		if (chdir(homedir) != 0) {
494 			syslog(LOG_ERR, "chdir(%s) $HOME failed for %s: %m",
495 			    homedir, e->pwd->pw_name);
496 			_exit(ERROR_EXIT);
497 		}
498 
499 #ifdef USE_SIGCHLD
500 		/* our grandparent is watching for our death by catching
501 		 * SIGCHLD.  the parent is ignoring SIGCHLD's; we want
502 		 * to restore default behaviour.
503 		 */
504 		(void) signal(SIGCHLD, SIG_DFL);
505 #endif
506 		(void) signal(SIGPIPE, SIG_DFL);
507 		(void) signal(SIGUSR1, SIG_DFL);
508 		(void) signal(SIGHUP, SIG_DFL);
509 
510 		/*
511 		 * Exec the command.
512 		 */
513 		{
514 			char	*shell = env_get("SHELL", envp);
515 
516 # if DEBUGGING
517 			if (DebugFlags & DTEST) {
518 				(void)fprintf(stderr,
519 				"debug DTEST is on, not exec'ing command.\n");
520 				(void)fprintf(stderr,
521 				"\tcmd='%s' shell='%s'\n", e->cmd, shell);
522 				_exit(OK_EXIT);
523 			}
524 # endif /*DEBUGGING*/
525 			(void)execle(shell, shell, "-c", e->cmd, NULL, envp);
526 			warn("execl: couldn't exec `%s'", shell);
527 			_exit(ERROR_EXIT);
528 		}
529 		break;
530 	default:
531 		/* parent process */
532 		break;
533 	}
534 
535 	/* middle process, child of original cron, parent of process running
536 	 * the user's command.
537 	 */
538 
539 	Debug(DPROC, ("[%ld] child continues, closing pipes\n",(long)getpid()));
540 
541 	/* close the ends of the pipe that will only be referenced in the
542 	 * grandchild process...
543 	 */
544 	(void)close(stdin_pipe[READ_PIPE]);
545 	(void)close(stdout_pipe[WRITE_PIPE]);
546 
547 	/*
548 	 * write, to the pipe connected to child's stdin, any input specified
549 	 * after a % in the crontab entry.  while we copy, convert any
550 	 * additional %'s to newlines.  when done, if some characters were
551 	 * written and the last one wasn't a newline, write a newline.
552 	 *
553 	 * Note that if the input data won't fit into one pipe buffer (2K
554 	 * or 4K on most BSD systems), and the child doesn't read its stdin,
555 	 * we would block here.  thus we must fork again.
556 	 */
557 
558 	if (*input_data) {
559 		switch (fork()) {
560 		case 0:
561 			write_data(input_data, stdin_pipe, stdout_pipe);
562 			exit(EXIT_SUCCESS);
563 		case -1:
564 			retval = ERROR_EXIT;
565 			goto child_process_end;
566 		default:
567 			break;
568 		}
569 	}
570 
571 	/* close the pipe to the grandkiddie's stdin, since its wicked uncle
572 	 * ernie back there has it open and will close it when he's done.
573 	 */
574 	(void)close(stdin_pipe[WRITE_PIPE]);
575 
576 	/*
577 	 * read output from the grandchild.  it's stderr has been redirected to
578 	 * it's stdout, which has been redirected to our pipe.  if there is any
579 	 * output, we'll be mailing it to the user whose crontab this is...
580 	 * when the grandchild exits, we'll get EOF.
581 	 */
582 
583 	Debug(DPROC, ("[%ld] child reading output from grandchild\n",
584 		      (long)getpid()));
585 
586 	retval = read_data(e, mailto, usernm, envp, stdout_pipe);
587 	if (retval)
588 		goto child_process_end;
589 
590 
591 	/* wait for children to die.
592 	 */
593 	sigchld_handler(0);
594 
595 	/* Log the time when we finished deadling with the job */
596 	/*local*/{
597 		char *x = mkprints(e->cmd, strlen(e->cmd));
598 
599 		log_it(usernm, getpid(), "CMD FINISH", x);
600 		free(x);
601 	}
602 
603 child_process_end:
604 #ifdef USE_PAM
605 	cron_pam_finish();
606 #endif
607 	return retval;
608 }
609 
610 static int
611 safe_p(const char *usernm, const char *s) {
612 	static const char safe_delim[] = "@!:%-.,";     /* conservative! */
613 	const char *t;
614 	int ch, first;
615 
616 	for (t = s, first = 1; (ch = *t++) != '\0'; first = 0) {
617 		if (isascii(ch) && isprint(ch) &&
618 		    (isalnum(ch) || (!first && strchr(safe_delim, ch))))
619 			continue;
620 		log_it(usernm, getpid(), "UNSAFE", s);
621 		return (FALSE);
622 	}
623 	return (TRUE);
624 }
625