xref: /netbsd-src/external/bsd/cron/dist/do_command.c (revision 16dce51364ebe8aeafbae46bc5aa167b8115bc45)
1 /*	$NetBSD: do_command.c,v 1.12 2018/02/04 03:37:59 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.12 2018/02/04 03:37:59 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 exec_user_command(entry *e, char **envp, char *usernm, int *stdin_pipe,
276     int *stdout_pipe)
277 {
278 	char *homedir;
279 	char * volatile *ep = envp;
280 
281 	switch (vfork()) {
282 	case -1:
283 		return -1;
284 	case 0:
285 		Debug(DPROC, ("[%ld] grandchild process vfork()'ed\n",
286 			      (long)getpid()));
287 
288 		/* write a log message.  we've waited this long to do it
289 		 * because it was not until now that we knew the PID that
290 		 * the actual user command shell was going to get and the
291 		 * PID is part of the log message.
292 		 */
293 		if ((e->flags & DONT_LOG) == 0) {
294 			char *x = mkprints(e->cmd, strlen(e->cmd));
295 
296 			log_it(usernm, getpid(), "CMD START", x);
297 			free(x);
298 		}
299 
300 		/* that's the last thing we'll log.  close the log files.
301 		 */
302 		log_close();
303 
304 		/* get new pgrp, void tty, etc.
305 		 */
306 		if (setsid() == -1)
307 			syslog(LOG_ERR, "setsid() failure: %m");
308 
309 		/* close the pipe ends that we won't use.  this doesn't affect
310 		 * the parent, who has to read and write them; it keeps the
311 		 * kernel from recording us as a potential client TWICE --
312 		 * which would keep it from sending SIGPIPE in otherwise
313 		 * appropriate circumstances.
314 		 */
315 		(void)close(stdin_pipe[WRITE_PIPE]);
316 		(void)close(stdout_pipe[READ_PIPE]);
317 
318 		/* grandchild process.  make std{in,out} be the ends of
319 		 * pipes opened by our daddy; make stderr go to stdout.
320 		 */
321 		if (stdin_pipe[READ_PIPE] != STDIN) {
322 			(void)dup2(stdin_pipe[READ_PIPE], STDIN);
323 			(void)close(stdin_pipe[READ_PIPE]);
324 		}
325 		if (stdout_pipe[WRITE_PIPE] != STDOUT) {
326 			(void)dup2(stdout_pipe[WRITE_PIPE], STDOUT);
327 			(void)close(stdout_pipe[WRITE_PIPE]);
328 		}
329 		(void)dup2(STDOUT, STDERR);
330 
331 		/* set our directory, uid and gid.  Set gid first, since once
332 		 * we set uid, we've lost root privledges.
333 		 */
334 #ifdef LOGIN_CAP
335 		{
336 #ifdef BSD_AUTH
337 			auth_session_t *as;
338 #endif
339 			login_cap_t *lc;
340 			char *p;
341 
342 			if ((lc = login_getclass(e->pwd->pw_class)) == NULL) {
343 				warnx("unable to get login class for `%s'",
344 				    e->pwd->pw_name);
345 				_exit(ERROR_EXIT);
346 			}
347 			if (setusercontext(lc, e->pwd, e->pwd->pw_uid, LOGIN_SETALL) < 0) {
348 				warnx("setusercontext failed for `%s'",
349 				    e->pwd->pw_name);
350 				_exit(ERROR_EXIT);
351 			}
352 #ifdef BSD_AUTH
353 			as = auth_open();
354 			if (as == NULL || auth_setpwd(as, e->pwd) != 0) {
355 				warn("can't malloc");
356 				_exit(ERROR_EXIT);
357 			}
358 			if (auth_approval(as, lc, usernm, "cron") <= 0) {
359 				warnx("approval failed for `%s'",
360 				    e->pwd->pw_name);
361 				_exit(ERROR_EXIT);
362 			}
363 			auth_close(as);
364 #endif /* BSD_AUTH */
365 			login_close(lc);
366 
367 			/* If no PATH specified in crontab file but
368 			 * we just added one via login.conf, add it to
369 			 * the crontab environment.
370 			 */
371 			if (env_get("PATH", envp) == NULL && environ != NULL) {
372 				if ((p = getenv("PATH")) != NULL)
373 					ep = env_set(envp, p);
374 			}
375 		}
376 #else
377 		if (setgid(e->pwd->pw_gid) != 0) {
378 			syslog(LOG_ERR, "setgid(%d) failed for %s: %m",
379 			    e->pwd->pw_gid, e->pwd->pw_name);
380 			_exit(ERROR_EXIT);
381 		}
382 		if (initgroups(usernm, e->pwd->pw_gid) != 0) {
383 			syslog(LOG_ERR, "initgroups(%s, %d) failed for %s: %m",
384 			    usernm, e->pwd->pw_gid, e->pwd->pw_name);
385 			_exit(ERROR_EXIT);
386 		}
387 #if (defined(BSD)) && (BSD >= 199103)
388 		if (setlogin(usernm) < 0) {
389 			syslog(LOG_ERR, "setlogin(%s) failure for %s: %m",
390 			    usernm, e->pwd->pw_name);
391 			_exit(ERROR_EXIT);
392 		}
393 #endif /* BSD */
394 #ifdef USE_PAM
395 		if (!cron_pam_setcred())
396 			_exit(ERROR_EXIT);
397 		cron_pam_child_close();
398 #endif
399 		if (setuid(e->pwd->pw_uid) != 0) {
400 			syslog(LOG_ERR, "setuid(%d) failed for %s: %m",
401 			    e->pwd->pw_uid, e->pwd->pw_name);
402 			_exit(ERROR_EXIT);
403 		}
404 		/* we aren't root after this... */
405 #endif /* LOGIN_CAP */
406 		homedir = env_get("HOME", __UNVOLATILE(ep));
407 		if (chdir(homedir) != 0) {
408 			syslog(LOG_ERR, "chdir(%s) $HOME failed for %s: %m",
409 			    homedir, e->pwd->pw_name);
410 			_exit(ERROR_EXIT);
411 		}
412 
413 #ifdef USE_SIGCHLD
414 		/* our grandparent is watching for our death by catching
415 		 * SIGCHLD.  the parent is ignoring SIGCHLD's; we want
416 		 * to restore default behaviour.
417 		 */
418 		(void) signal(SIGCHLD, SIG_DFL);
419 #endif
420 		(void) signal(SIGPIPE, SIG_DFL);
421 		(void) signal(SIGUSR1, SIG_DFL);
422 		(void) signal(SIGHUP, SIG_DFL);
423 
424 		/*
425 		 * Exec the command.
426 		 */
427 		{
428 			char	*shell = env_get("SHELL", __UNVOLATILE(ep));
429 
430 # if DEBUGGING
431 			if (DebugFlags & DTEST) {
432 				(void)fprintf(stderr,
433 				"debug DTEST is on, not exec'ing command.\n");
434 				(void)fprintf(stderr,
435 				"\tcmd='%s' shell='%s'\n", e->cmd, shell);
436 				_exit(OK_EXIT);
437 			}
438 # endif /*DEBUGGING*/
439 			(void)execle(shell, shell, "-c", e->cmd, NULL, envp);
440 			warn("execl: couldn't exec `%s'", shell);
441 			_exit(ERROR_EXIT);
442 		}
443 		return 0;
444 	default:
445 		/* parent process */
446 		return 0;
447 	}
448 }
449 
450 static int
451 child_process(entry *e) {
452 	int stdin_pipe[2], stdout_pipe[2];
453 	char * volatile input_data;
454 	char *usernm, * volatile mailto;
455 	struct sigaction sact;
456 	char **envp = e->envp;
457 	int retval = OK_EXIT;
458 
459 	Debug(DPROC, ("[%ld] child_process('%s')\n", (long)getpid(), e->cmd));
460 
461 	setproctitle("running job");
462 
463 	/* discover some useful and important environment settings
464 	 */
465 	usernm = e->pwd->pw_name;
466 	mailto = env_get("MAILTO", envp);
467 
468 	memset(&sact, 0, sizeof(sact));
469 	sigemptyset(&sact.sa_mask);
470 	sact.sa_flags = 0;
471 #ifdef SA_RESTART
472 	sact.sa_flags |= SA_RESTART;
473 #endif
474 	sact.sa_handler = sigchld_handler;
475 	(void) sigaction(SIGCHLD, &sact, NULL);
476 
477 	/* create some pipes to talk to our future child
478 	 */
479 	if (pipe(stdin_pipe) == -1) 	/* child's stdin */
480 		log_it("CRON", getpid(), "error", "create child stdin pipe");
481 	if (pipe(stdout_pipe) == -1)	/* child's stdout */
482 		log_it("CRON", getpid(), "error", "create child stdout pipe");
483 
484 	/* since we are a forked process, we can diddle the command string
485 	 * we were passed -- nobody else is going to use it again, right?
486 	 *
487 	 * if a % is present in the command, previous characters are the
488 	 * command, and subsequent characters are the additional input to
489 	 * the command.  An escaped % will have the escape character stripped
490 	 * from it.  Subsequent %'s will be transformed into newlines,
491 	 * but that happens later.
492 	 */
493 	/*local*/{
494 		int escaped = FALSE;
495 		int ch;
496 		char *p;
497 
498 		/* translation:
499 		 *	\% -> %
500 		 *	%  -> end of command, following is command input.
501 		 *	\x -> \x	for all x != %
502 		 */
503 		input_data = p = e->cmd;
504 		while ((ch = *input_data++) != '\0') {
505  			if (escaped) {
506 				if (ch != '%')
507 					*p++ = '\\';
508 			} else {
509 				if (ch == '%') {
510 					break;
511 				}
512 			}
513 
514 			if (!(escaped = (ch == '\\'))) {
515 				*p++ = (char)ch;
516 			}
517 		}
518 		if (ch == '\0') {
519 			/* move pointer back, so that code below
520 			 * won't think we encountered % sequence */
521 			input_data--;
522 		}
523 		if (escaped)
524 			*p++ = '\\';
525 
526 		*p = '\0';
527 	}
528 
529 #ifdef USE_PAM
530 	if (!cron_pam_start(usernm))
531 		return ERROR_EXIT;
532 
533 	if (!(envp = cron_pam_getenvlist(envp))) {
534 		retval = ERROR_EXIT;
535 		goto child_process_end;
536 	}
537 #endif
538 
539 	/* fork again, this time so we can exec the user's command.
540 	 */
541 	if (exec_user_command(e, envp, usernm, stdin_pipe, stdout_pipe) == -1) {
542 		retval = ERROR_EXIT;
543 		goto child_process_end;
544 	}
545 
546 
547 	/* middle process, child of original cron, parent of process running
548 	 * the user's command.
549 	 */
550 
551 	Debug(DPROC, ("[%ld] child continues, closing pipes\n",(long)getpid()));
552 
553 	/* close the ends of the pipe that will only be referenced in the
554 	 * grandchild process...
555 	 */
556 	(void)close(stdin_pipe[READ_PIPE]);
557 	(void)close(stdout_pipe[WRITE_PIPE]);
558 
559 	/*
560 	 * write, to the pipe connected to child's stdin, any input specified
561 	 * after a % in the crontab entry.  while we copy, convert any
562 	 * additional %'s to newlines.  when done, if some characters were
563 	 * written and the last one wasn't a newline, write a newline.
564 	 *
565 	 * Note that if the input data won't fit into one pipe buffer (2K
566 	 * or 4K on most BSD systems), and the child doesn't read its stdin,
567 	 * we would block here.  thus we must fork again.
568 	 */
569 
570 	if (*input_data) {
571 		switch (fork()) {
572 		case 0:
573 			write_data(input_data, stdin_pipe, stdout_pipe);
574 			exit(EXIT_SUCCESS);
575 		case -1:
576 			retval = ERROR_EXIT;
577 			goto child_process_end;
578 		default:
579 			break;
580 		}
581 	}
582 
583 	/* close the pipe to the grandkiddie's stdin, since its wicked uncle
584 	 * ernie back there has it open and will close it when he's done.
585 	 */
586 	(void)close(stdin_pipe[WRITE_PIPE]);
587 
588 	/*
589 	 * read output from the grandchild.  it's stderr has been redirected to
590 	 * it's stdout, which has been redirected to our pipe.  if there is any
591 	 * output, we'll be mailing it to the user whose crontab this is...
592 	 * when the grandchild exits, we'll get EOF.
593 	 */
594 
595 	Debug(DPROC, ("[%ld] child reading output from grandchild\n",
596 		      (long)getpid()));
597 
598 	retval = read_data(e, mailto, usernm, envp, stdout_pipe);
599 	if (retval)
600 		goto child_process_end;
601 
602 
603 	/* wait for children to die.
604 	 */
605 	sigchld_handler(0);
606 
607 	/* Log the time when we finished deadling with the job */
608 	/*local*/{
609 		char *x = mkprints(e->cmd, strlen(e->cmd));
610 
611 		log_it(usernm, getpid(), "CMD FINISH", x);
612 		free(x);
613 	}
614 
615 child_process_end:
616 #ifdef USE_PAM
617 	cron_pam_finish();
618 #endif
619 	return retval;
620 }
621 
622 static int
623 safe_p(const char *usernm, const char *s) {
624 	static const char safe_delim[] = "@!:%-.,";     /* conservative! */
625 	const char *t;
626 	int ch, first;
627 
628 	for (t = s, first = 1; (ch = *t++) != '\0'; first = 0) {
629 		if (isascii(ch) && isprint(ch) &&
630 		    (isalnum(ch) || (!first && strchr(safe_delim, ch))))
631 			continue;
632 		log_it(usernm, getpid(), "UNSAFE", s);
633 		return (FALSE);
634 	}
635 	return (TRUE);
636 }
637