xref: /illumos-gate/usr/src/cmd/cron/crontab.c (revision c211fc479225fa54805cf480633bf6689ca9a2db)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
26 /*	  All Rights Reserved  	*/
27 
28 
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <sys/wait.h>
33 #include <errno.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <fcntl.h>
39 #include <ctype.h>
40 #include <pwd.h>
41 #include <unistd.h>
42 #include <locale.h>
43 #include <nl_types.h>
44 #include <langinfo.h>
45 #include <libintl.h>
46 #include <spawn.h>
47 #include <security/pam_appl.h>
48 #include <limits.h>
49 #include <libzoneinfo.h>
50 #include "cron.h"
51 #include "getresponse.h"
52 
53 #if defined(XPG4)
54 #define	VIPATH	"/usr/xpg4/bin/vi"
55 #elif defined(XPG6)
56 #define	VIPATH	"/usr/xpg6/bin/vi"
57 #else
58 #define	_XPG_NOTDEFINED
59 #define	VIPATH	"vi"
60 #endif
61 
62 #define	TMPFILE		"_cron"		/* prefix for tmp file */
63 #define	CRMODE		0600	/* mode for creating crontabs */
64 
65 #define	BADCREATE	\
66 	"can't create your crontab file in the crontab directory."
67 #define	BADOPEN		"can't open your crontab file."
68 #define	BADSHELL	\
69 	"because your login shell isn't /usr/bin/sh, you can't use cron."
70 #define	WARNSHELL	"warning: commands will be executed using /usr/bin/sh\n"
71 #define	BADUSAGE	\
72 	"usage:\n"			\
73 	"\tcrontab [file]\n"		\
74 	"\tcrontab -e [username]\n"	\
75 	"\tcrontab -l [username]\n"	\
76 	"\tcrontab -r [username]"
77 #define	INVALIDUSER	"you are not a valid user (no entry in /etc/passwd)."
78 #define	NOTALLOWED	"you are not authorized to use cron.  Sorry."
79 #define	NOTROOT		\
80 	"you must be super-user to access another user's crontab file"
81 #define	AUDITREJECT	"The audit context for your shell has not been set."
82 #define	EOLN		"unexpected end of line."
83 #define	UNEXPECT	"unexpected character found in line."
84 #define	OUTOFBOUND	"number out of bounds."
85 #define	ERRSFND		"errors detected in input, no crontab file generated."
86 #define	ED_ERROR	\
87 	"     The editor indicates that an error occurred while you were\n"\
88 	"     editing the crontab data - usually a minor typing error.\n\n"
89 #define	BADREAD		"error reading your crontab file"
90 #define	ED_PROMPT	\
91 	"     Edit again, to ensure crontab information is intact (%s/%s)?\n"\
92 	"     ('%s' will discard edits.)"
93 #define	NAMETOOLONG	"login name too long"
94 #define	BAD_TZ	"Timezone unrecognized in: %s"
95 #define	BAD_SHELL	"Invalid shell specified: %s"
96 #define	BAD_HOME	"Unable to access directory: %s\t%s\n"
97 
98 extern int	per_errno;
99 extern char 	**environ;
100 
101 extern int	audit_crontab_modify(char *, char *, int);
102 extern int	audit_crontab_delete(char *, int);
103 extern int	audit_crontab_not_allowed(uid_t, char *);
104 
105 int		err;
106 int		cursor;
107 char		*cf;
108 char		*tnam;
109 char		edtemp[5+13+1];
110 char		line[CTLINESIZE];
111 static		char	login[UNAMESIZE];
112 
113 static int	next_field(int, int);
114 static void	catch(int);
115 static void	crabort(char *);
116 static void	cerror(char *);
117 static void	copycron(FILE *);
118 
119 int
120 main(int argc, char **argv)
121 {
122 	int	c, r;
123 	int	rflag	= 0;
124 	int	lflag	= 0;
125 	int	eflag	= 0;
126 	int	errflg	= 0;
127 	char *pp;
128 	FILE *fp, *tmpfp;
129 	struct stat stbuf;
130 	struct passwd *pwp;
131 	time_t omodtime;
132 	char *editor;
133 	uid_t ruid;
134 	pid_t pid;
135 	int stat_loc;
136 	int ret;
137 	char real_login[UNAMESIZE];
138 	int tmpfd = -1;
139 	pam_handle_t *pamh;
140 	int pam_error;
141 	pid_t cpid;
142 	int cstatus;
143 	char *argvec[3];
144 
145 	(void) setlocale(LC_ALL, "");
146 #if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
147 #define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
148 #endif
149 	(void) textdomain(TEXT_DOMAIN);
150 
151 	if (init_yes() < 0) {
152 		(void) fprintf(stderr, gettext(ERR_MSG_INIT_YES),
153 		    strerror(errno));
154 		exit(1);
155 	}
156 
157 	while ((c = getopt(argc, argv, "elr")) != EOF)
158 		switch (c) {
159 			case 'e':
160 				eflag++;
161 				break;
162 			case 'l':
163 				lflag++;
164 				break;
165 			case 'r':
166 				rflag++;
167 				break;
168 			case '?':
169 				errflg++;
170 				break;
171 		}
172 
173 	if (eflag + lflag + rflag > 1)
174 		errflg++;
175 
176 	argc -= optind;
177 	argv += optind;
178 	if (errflg || argc > 1)
179 		crabort(BADUSAGE);
180 
181 	ruid = getuid();
182 	if ((pwp = getpwuid(ruid)) == NULL)
183 		crabort(INVALIDUSER);
184 
185 	if (strlcpy(real_login, pwp->pw_name, sizeof (real_login))
186 	    >= sizeof (real_login))
187 		crabort(NAMETOOLONG);
188 
189 	if ((eflag || lflag || rflag) && argc == 1) {
190 		if ((pwp = getpwnam(*argv)) == NULL)
191 			crabort(INVALIDUSER);
192 
193 		if (!chkauthattr(CRONADMIN_AUTH, real_login)) {
194 			if (pwp->pw_uid != ruid)
195 				crabort(NOTROOT);
196 			else
197 				pp = getuser(ruid);
198 		} else
199 			pp = *argv++;
200 	} else {
201 		pp = getuser(ruid);
202 	}
203 
204 	if (pp == NULL) {
205 		if (per_errno == 2)
206 			crabort(BADSHELL);
207 		else
208 			crabort(INVALIDUSER);
209 	}
210 	if (strlcpy(login, pp, sizeof (login)) >= sizeof (login))
211 		crabort(NAMETOOLONG);
212 	if (!allowed(login, CRONALLOW, CRONDENY))
213 		crabort(NOTALLOWED);
214 
215 	/* Do account validation check */
216 	pam_error = pam_start("cron", pp, NULL, &pamh);
217 	if (pam_error != PAM_SUCCESS) {
218 		crabort((char *)pam_strerror(pamh, pam_error));
219 	}
220 	pam_error = pam_acct_mgmt(pamh, PAM_SILENT);
221 	if (pam_error != PAM_SUCCESS) {
222 		(void) fprintf(stderr, gettext("Warning - Invalid account: "
223 		    "'%s' not allowed to execute cronjobs\n"), pp);
224 	}
225 	(void) pam_end(pamh, PAM_SUCCESS);
226 
227 
228 	/* check for unaudited shell */
229 	if (audit_crontab_not_allowed(ruid, pp))
230 		crabort(AUDITREJECT);
231 
232 	cf = xmalloc(strlen(CRONDIR)+strlen(login)+2);
233 	strcat(strcat(strcpy(cf, CRONDIR), "/"), login);
234 
235 	if (rflag) {
236 		r = unlink(cf);
237 		cron_sendmsg(DELETE, login, login, CRON);
238 		audit_crontab_delete(cf, r);
239 		exit(0);
240 	}
241 	if (lflag) {
242 		if ((fp = fopen(cf, "r")) == NULL)
243 			crabort(BADOPEN);
244 		while (fgets(line, CTLINESIZE, fp) != NULL)
245 			fputs(line, stdout);
246 		fclose(fp);
247 		exit(0);
248 	}
249 	if (eflag) {
250 		if ((fp = fopen(cf, "r")) == NULL) {
251 			if (errno != ENOENT)
252 				crabort(BADOPEN);
253 		}
254 		(void) strcpy(edtemp, "/tmp/crontabXXXXXX");
255 		tmpfd = mkstemp(edtemp);
256 		if (fchown(tmpfd, ruid, -1) == -1) {
257 			(void) close(tmpfd);
258 			crabort("fchown of temporary file failed");
259 		}
260 		(void) close(tmpfd);
261 		/*
262 		 * Fork off a child with user's permissions,
263 		 * to edit the crontab file
264 		 */
265 		if ((pid = fork()) == (pid_t)-1)
266 			crabort("fork failed");
267 		if (pid == 0) {		/* child process */
268 			/* give up super-user privileges. */
269 			setuid(ruid);
270 			if ((tmpfp = fopen(edtemp, "w")) == NULL)
271 				crabort("can't create temporary file");
272 			if (fp != NULL) {
273 				/*
274 				 * Copy user's crontab file to temporary file.
275 				 */
276 				while (fgets(line, CTLINESIZE, fp) != NULL) {
277 					fputs(line, tmpfp);
278 					if (ferror(tmpfp)) {
279 						fclose(fp);
280 						fclose(tmpfp);
281 						crabort("write error on"
282 						    "temporary file");
283 					}
284 				}
285 				if (ferror(fp)) {
286 					fclose(fp);
287 					fclose(tmpfp);
288 					crabort(BADREAD);
289 				}
290 				fclose(fp);
291 			}
292 			if (fclose(tmpfp) == EOF)
293 				crabort("write error on temporary file");
294 			if (stat(edtemp, &stbuf) < 0)
295 				crabort("can't stat temporary file");
296 			omodtime = stbuf.st_mtime;
297 #ifdef _XPG_NOTDEFINED
298 			editor = getenv("VISUAL");
299 			if (editor == NULL) {
300 #endif
301 				editor = getenv("EDITOR");
302 				if (editor == NULL)
303 					editor = VIPATH;
304 #ifdef _XPG_NOTDEFINED
305 			}
306 #endif
307 			argvec[0] = strdup(editor);
308 			argvec[1] = strdup(edtemp);
309 			argvec[2] = NULL;
310 
311 			if (argvec[0] == NULL || argvec[1] == NULL)
312 				crabort("Insufficient memory");
313 
314 			sleep(1);
315 
316 			while (1) {
317 				/*
318 				 * posix_spawnp() allows the file pointed to
319 				 * by the 'EDITOR' variable to be searched in
320 				 * the PATH environment variable
321 				 */
322 
323 				ret = posix_spawnp(&cpid, editor, NULL, NULL,
324 				    (char *const *)argvec,
325 				    (char *const *)environ);
326 				if (ret) {
327 					(void) fprintf(stderr,
328 					    gettext("crontab: %s: %s\n"),
329 					    editor, strerror(errno));
330 					cstatus = -1;
331 				} else {
332 					pid_t wpid = 0;
333 					while ((wpid = waitpid(cpid, &cstatus,
334 					    0)) == -1 && errno == EINTR)
335 						;
336 					if (wpid  == -1)
337 						cstatus = -1;
338 				}
339 
340 				/* sanity checks */
341 				if ((tmpfp = fopen(edtemp, "r")) == NULL)
342 					crabort("can't open temporary file");
343 				if (fstat(fileno(tmpfp), &stbuf) < 0)
344 					crabort("can't stat temporary file");
345 				if (stbuf.st_size == 0)
346 					crabort("temporary file empty");
347 				if (omodtime == stbuf.st_mtime) {
348 					(void) unlink(edtemp);
349 					fprintf(stderr, gettext(
350 					    "The crontab file was not"
351 					    " changed.\n"));
352 					exit(1);
353 				}
354 				if ((cstatus) && (errno != EINTR)) {
355 					/*
356 					 * Some editors (like 'vi') can return
357 					 * a non-zero exit status even though
358 					 * everything is okay. Need to check.
359 					 */
360 					fprintf(stderr, gettext(ED_ERROR));
361 					fflush(stderr);
362 					if (isatty(fileno(stdin))) {
363 						/* Interactive */
364 						fprintf(stdout,
365 						    gettext(ED_PROMPT),
366 						    yesstr, nostr, nostr);
367 						fflush(stdout);
368 
369 						if (yes()) {
370 							/* Edit again */
371 							continue;
372 						} else {
373 							/* Dump changes */
374 							(void) unlink(edtemp);
375 							exit(1);
376 						}
377 					} else {
378 						/*
379 						 * Non-interactive, dump changes
380 						 */
381 						(void) unlink(edtemp);
382 						exit(1);
383 					}
384 				}
385 				exit(0);
386 			} /* while (1) */
387 		}
388 
389 		/* fix for 1125555 - ignore common signals while waiting */
390 		(void) signal(SIGINT, SIG_IGN);
391 		(void) signal(SIGHUP, SIG_IGN);
392 		(void) signal(SIGQUIT, SIG_IGN);
393 		(void) signal(SIGTERM, SIG_IGN);
394 		wait(&stat_loc);
395 		if ((stat_loc & 0xFF00) != 0)
396 			exit(1);
397 
398 		/*
399 		 * unlink edtemp as 'ruid'. The file contents will be held
400 		 * since we open the file descriptor 'tmpfp' before calling
401 		 * unlink.
402 		 */
403 		if (((ret = seteuid(ruid)) < 0) ||
404 		    ((tmpfp = fopen(edtemp, "r")) == NULL) ||
405 		    (unlink(edtemp) == -1)) {
406 			fprintf(stderr, "crontab: %s: %s\n",
407 			    edtemp, errmsg(errno));
408 			if ((ret < 0) || (tmpfp == NULL))
409 				(void) unlink(edtemp);
410 			exit(1);
411 		} else
412 			seteuid(0);
413 
414 		copycron(tmpfp);
415 	} else {
416 		if (argc == 0)
417 			copycron(stdin);
418 		else if (seteuid(getuid()) != 0 || (fp = fopen(argv[0], "r"))
419 		    == NULL)
420 			crabort(BADOPEN);
421 		else {
422 			seteuid(0);
423 			copycron(fp);
424 		}
425 	}
426 	cron_sendmsg(ADD, login, login, CRON);
427 /*
428  *	if (per_errno == 2)
429  *		fprintf(stderr, gettext(WARNSHELL));
430  */
431 	return (0);
432 }
433 
434 static void
435 copycron(fp)
436 FILE *fp;
437 {
438 	FILE *tfp;
439 	char pid[6], *tnam_end;
440 	int t;
441 	char buf[LINE_MAX];
442 
443 	sprintf(pid, "%-5d", getpid());
444 	tnam = xmalloc(strlen(CRONDIR)+strlen(TMPFILE)+7);
445 	strcat(strcat(strcat(strcpy(tnam, CRONDIR), "/"), TMPFILE), pid);
446 	/* cut trailing blanks */
447 	tnam_end = strchr(tnam, ' ');
448 	if (tnam_end != NULL)
449 		*tnam_end = 0;
450 	/* catch SIGINT, SIGHUP, SIGQUIT signals */
451 	if (signal(SIGINT, catch) == SIG_IGN)
452 		signal(SIGINT, SIG_IGN);
453 	if (signal(SIGHUP, catch) == SIG_IGN) signal(SIGHUP, SIG_IGN);
454 	if (signal(SIGQUIT, catch) == SIG_IGN) signal(SIGQUIT, SIG_IGN);
455 	if (signal(SIGTERM, catch) == SIG_IGN) signal(SIGTERM, SIG_IGN);
456 	if ((t = creat(tnam, CRMODE)) == -1) crabort(BADCREATE);
457 	if ((tfp = fdopen(t, "w")) == NULL) {
458 		unlink(tnam);
459 		crabort(BADCREATE);
460 	}
461 	err = 0;	/* if errors found, err set to 1 */
462 	while (fgets(line, CTLINESIZE, fp) != NULL) {
463 		cursor = 0;
464 		while (line[cursor] == ' ' || line[cursor] == '\t')
465 			cursor++;
466 		/* fix for 1039689 - treat blank line like a comment */
467 		if (line[cursor] == '#' || line[cursor] == '\n')
468 			goto cont;
469 
470 		if (strncmp(&line[cursor], ENV_TZ, strlen(ENV_TZ)) == 0) {
471 			char *x;
472 
473 			strncpy(buf, &line[cursor + strlen(ENV_TZ)],
474 			    sizeof (buf));
475 			if ((x = strchr(buf, '\n')) != NULL)
476 				*x = NULL;
477 
478 			if (isvalid_tz(buf, NULL, _VTZ_ALL)) {
479 				goto cont;
480 			} else {
481 				err = 1;
482 				fprintf(stderr, BAD_TZ, &line[cursor]);
483 				continue;
484 			}
485 		} else if (strncmp(&line[cursor], ENV_SHELL,
486 		    strlen(ENV_SHELL)) == 0) {
487 			char *x;
488 
489 			strncpy(buf, &line[cursor + strlen(ENV_SHELL)],
490 			    sizeof (buf));
491 			if ((x = strchr(buf, '\n')) != NULL)
492 				*x = NULL;
493 
494 			if (isvalid_shell(buf)) {
495 				goto cont;
496 			} else {
497 				err = 1;
498 				fprintf(stderr, BAD_SHELL, &line[cursor]);
499 				continue;
500 			}
501 		} else if (strncmp(&line[cursor], ENV_HOME,
502 		    strlen(ENV_HOME)) == 0) {
503 			char *x;
504 
505 			strncpy(buf, &line[cursor + strlen(ENV_HOME)],
506 			    sizeof (buf));
507 			if ((x = strchr(buf, '\n')) != NULL)
508 				*x = NULL;
509 			if (chdir(buf) == 0) {
510 				goto cont;
511 			} else {
512 				err = 1;
513 				fprintf(stderr, BAD_HOME, &line[cursor],
514 				    strerror(errno));
515 				continue;
516 			}
517 		}
518 
519 		if (next_field(0, 59)) continue;
520 		if (next_field(0, 23)) continue;
521 		if (next_field(1, 31)) continue;
522 		if (next_field(1, 12)) continue;
523 		if (next_field(0, 06)) continue;
524 		if (line[++cursor] == '\0') {
525 			cerror(EOLN);
526 			continue;
527 		}
528 cont:
529 		if (fputs(line, tfp) == EOF) {
530 			unlink(tnam);
531 			crabort(BADCREATE);
532 		}
533 	}
534 	fclose(fp);
535 	fclose(tfp);
536 
537 	/* audit differences between old and new crontabs */
538 	audit_crontab_modify(cf, tnam, err);
539 
540 	if (!err) {
541 		/* make file tfp the new crontab */
542 		unlink(cf);
543 		if (link(tnam, cf) == -1) {
544 			unlink(tnam);
545 			crabort(BADCREATE);
546 		}
547 	} else {
548 		crabort(ERRSFND);
549 	}
550 	unlink(tnam);
551 }
552 
553 static int
554 next_field(lower, upper)
555 int lower, upper;
556 {
557 	int num, num2;
558 
559 	while ((line[cursor] == ' ') || (line[cursor] == '\t')) cursor++;
560 	if (line[cursor] == '\0') {
561 		cerror(EOLN);
562 		return (1);
563 	}
564 	if (line[cursor] == '*') {
565 		cursor++;
566 		if ((line[cursor] != ' ') && (line[cursor] != '\t')) {
567 			cerror(UNEXPECT);
568 			return (1);
569 		}
570 		return (0);
571 	}
572 	while (TRUE) {
573 		if (!isdigit(line[cursor])) {
574 			cerror(UNEXPECT);
575 			return (1);
576 		}
577 		num = 0;
578 		do {
579 			num = num*10 + (line[cursor]-'0');
580 		} while (isdigit(line[++cursor]));
581 		if ((num < lower) || (num > upper)) {
582 			cerror(OUTOFBOUND);
583 			return (1);
584 		}
585 		if (line[cursor] == '-') {
586 			if (!isdigit(line[++cursor])) {
587 				cerror(UNEXPECT);
588 				return (1);
589 			}
590 			num2 = 0;
591 			do {
592 				num2 = num2*10 + (line[cursor]-'0');
593 			} while (isdigit(line[++cursor]));
594 			if ((num2 < lower) || (num2 > upper)) {
595 				cerror(OUTOFBOUND);
596 				return (1);
597 			}
598 		}
599 		if ((line[cursor] == ' ') || (line[cursor] == '\t')) break;
600 		if (line[cursor] == '\0') {
601 			cerror(EOLN);
602 			return (1);
603 		}
604 		if (line[cursor++] != ',') {
605 			cerror(UNEXPECT);
606 			return (1);
607 		}
608 	}
609 	return (0);
610 }
611 
612 static void
613 cerror(msg)
614 char *msg;
615 {
616 	fprintf(stderr, gettext("%scrontab: error on previous line; %s\n"),
617 	    line, msg);
618 	err = 1;
619 }
620 
621 
622 static void
623 catch(int x)
624 {
625 	unlink(tnam);
626 	exit(1);
627 }
628 
629 static void
630 crabort(msg)
631 char *msg;
632 {
633 	int sverrno;
634 
635 	if (strcmp(edtemp, "") != 0) {
636 		sverrno = errno;
637 		(void) unlink(edtemp);
638 		errno = sverrno;
639 	}
640 	if (tnam != NULL) {
641 		sverrno = errno;
642 		(void) unlink(tnam);
643 		errno = sverrno;
644 	}
645 	fprintf(stderr, "crontab: %s\n", gettext(msg));
646 	exit(1);
647 }
648