xref: /illumos-gate/usr/src/cmd/cron/crontab.c (revision 8b80e8cb6855118d46f605e91b5ed4ce83417395)
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 2008 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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
30 
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <errno.h>
36 #include <signal.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <fcntl.h>
41 #include <ctype.h>
42 #include <pwd.h>
43 #include <unistd.h>
44 #include <locale.h>
45 #include <nl_types.h>
46 #include <langinfo.h>
47 #include <libintl.h>
48 #include <spawn.h>
49 #include <security/pam_appl.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 
95 extern int	per_errno;
96 extern char 	**environ;
97 
98 extern int	audit_crontab_modify(char *, char *, int);
99 extern int	audit_crontab_delete(char *, int);
100 extern int	audit_crontab_not_allowed(uid_t, char *);
101 
102 int		err;
103 int		cursor;
104 char		*cf;
105 char		*tnam;
106 char		edtemp[5+13+1];
107 char		line[CTLINESIZE];
108 static		char	login[UNAMESIZE];
109 
110 static int	next_field(int, int);
111 static void	catch(int);
112 static void	crabort(char *);
113 static void	cerror(char *);
114 static void	copycron(FILE *);
115 
116 int
117 main(int argc, char **argv)
118 {
119 	int	c, r;
120 	int	rflag	= 0;
121 	int	lflag	= 0;
122 	int	eflag	= 0;
123 	int	errflg	= 0;
124 	char *pp;
125 	FILE *fp, *tmpfp;
126 	struct stat stbuf;
127 	struct passwd *pwp;
128 	time_t omodtime;
129 	char *editor;
130 	uid_t ruid;
131 	pid_t pid;
132 	int stat_loc;
133 	int ret;
134 	char real_login[UNAMESIZE];
135 	int tmpfd = -1;
136 	pam_handle_t *pamh;
137 	int pam_error;
138 	pid_t cpid;
139 	int cstatus;
140 	char *argvec[3];
141 
142 	(void) setlocale(LC_ALL, "");
143 #if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
144 #define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
145 #endif
146 	(void) textdomain(TEXT_DOMAIN);
147 
148 	if (init_yes() < 0) {
149 		(void) fprintf(stderr, gettext(ERR_MSG_INIT_YES),
150 		    strerror(errno));
151 		exit(1);
152 	}
153 
154 	while ((c = getopt(argc, argv, "elr")) != EOF)
155 		switch (c) {
156 			case 'e':
157 				eflag++;
158 				break;
159 			case 'l':
160 				lflag++;
161 				break;
162 			case 'r':
163 				rflag++;
164 				break;
165 			case '?':
166 				errflg++;
167 				break;
168 		}
169 
170 	if (eflag + lflag + rflag > 1)
171 		errflg++;
172 
173 	argc -= optind;
174 	argv += optind;
175 	if (errflg || argc > 1)
176 		crabort(BADUSAGE);
177 
178 	ruid = getuid();
179 	if ((pwp = getpwuid(ruid)) == NULL)
180 		crabort(INVALIDUSER);
181 
182 	if (strlcpy(real_login, pwp->pw_name, sizeof (real_login))
183 	    >= sizeof (real_login))
184 		crabort(NAMETOOLONG);
185 
186 	if ((eflag || lflag || rflag) && argc == 1) {
187 		if ((pwp = getpwnam(*argv)) == NULL)
188 			crabort(INVALIDUSER);
189 
190 		if (!chkauthattr(CRONADMIN_AUTH, real_login)) {
191 			if (pwp->pw_uid != ruid)
192 				crabort(NOTROOT);
193 			else
194 				pp = getuser(ruid);
195 		} else
196 			pp = *argv++;
197 	} else {
198 		pp = getuser(ruid);
199 	}
200 
201 	if (pp == NULL) {
202 		if (per_errno == 2)
203 			crabort(BADSHELL);
204 		else
205 			crabort(INVALIDUSER);
206 	}
207 	if (strlcpy(login, pp, sizeof (login)) >= sizeof (login))
208 		crabort(NAMETOOLONG);
209 	if (!allowed(login, CRONALLOW, CRONDENY))
210 		crabort(NOTALLOWED);
211 
212 	/* Do account validation check */
213 	pam_error = pam_start("cron", pp, NULL, &pamh);
214 	if (pam_error != PAM_SUCCESS) {
215 		crabort((char *)pam_strerror(pamh, pam_error));
216 	}
217 	pam_error = pam_acct_mgmt(pamh, PAM_SILENT);
218 	if (pam_error != PAM_SUCCESS) {
219 		(void) fprintf(stderr, gettext("Warning - Invalid account: "
220 		    "'%s' not allowed to execute cronjobs\n"), pp);
221 	}
222 	(void) pam_end(pamh, PAM_SUCCESS);
223 
224 
225 	/* check for unaudited shell */
226 	if (audit_crontab_not_allowed(ruid, pp))
227 		crabort(AUDITREJECT);
228 
229 	cf = xmalloc(strlen(CRONDIR)+strlen(login)+2);
230 	strcat(strcat(strcpy(cf, CRONDIR), "/"), login);
231 
232 	if (rflag) {
233 		r = unlink(cf);
234 		cron_sendmsg(DELETE, login, login, CRON);
235 		audit_crontab_delete(cf, r);
236 		exit(0);
237 	}
238 	if (lflag) {
239 		if ((fp = fopen(cf, "r")) == NULL)
240 			crabort(BADOPEN);
241 		while (fgets(line, CTLINESIZE, fp) != NULL)
242 			fputs(line, stdout);
243 		fclose(fp);
244 		exit(0);
245 	}
246 	if (eflag) {
247 		if ((fp = fopen(cf, "r")) == NULL) {
248 			if (errno != ENOENT)
249 				crabort(BADOPEN);
250 		}
251 		(void) strcpy(edtemp, "/tmp/crontabXXXXXX");
252 		tmpfd = mkstemp(edtemp);
253 		if (fchown(tmpfd, ruid, -1) == -1) {
254 			(void) close(tmpfd);
255 			crabort("fchown of temporary file failed");
256 		}
257 		(void) close(tmpfd);
258 		/*
259 		 * Fork off a child with user's permissions,
260 		 * to edit the crontab file
261 		 */
262 		if ((pid = fork()) == (pid_t)-1)
263 			crabort("fork failed");
264 		if (pid == 0) {		/* child process */
265 			/* give up super-user privileges. */
266 			setuid(ruid);
267 			if ((tmpfp = fopen(edtemp, "w")) == NULL)
268 				crabort("can't create temporary file");
269 			if (fp != NULL) {
270 				/*
271 				 * Copy user's crontab file to temporary file.
272 				 */
273 				while (fgets(line, CTLINESIZE, fp) != NULL) {
274 					fputs(line, tmpfp);
275 					if (ferror(tmpfp)) {
276 						fclose(fp);
277 						fclose(tmpfp);
278 						crabort("write error on"
279 						    "temporary file");
280 					}
281 				}
282 				if (ferror(fp)) {
283 					fclose(fp);
284 					fclose(tmpfp);
285 					crabort(BADREAD);
286 				}
287 				fclose(fp);
288 			}
289 			if (fclose(tmpfp) == EOF)
290 				crabort("write error on temporary file");
291 			if (stat(edtemp, &stbuf) < 0)
292 				crabort("can't stat temporary file");
293 			omodtime = stbuf.st_mtime;
294 #ifdef _XPG_NOTDEFINED
295 			editor = getenv("VISUAL");
296 			if (editor == NULL) {
297 #endif
298 				editor = getenv("EDITOR");
299 				if (editor == NULL)
300 					editor = VIPATH;
301 #ifdef _XPG_NOTDEFINED
302 			}
303 #endif
304 			argvec[0] = strdup(editor);
305 			argvec[1] = strdup(edtemp);
306 			argvec[2] = NULL;
307 
308 			if (argvec[0] == NULL || argvec[1] == NULL)
309 				crabort("Insufficient memory");
310 
311 			sleep(1);
312 
313 			while (1) {
314 				/*
315 				 * posix_spawnp() allows the file pointed to
316 				 * by the 'EDITOR' variable to be searched in
317 				 * the PATH environment variable
318 				 */
319 
320 				ret = posix_spawnp(&cpid, editor, NULL, NULL,
321 				    (char *const *)argvec,
322 				    (char *const *)environ);
323 				if (ret) {
324 					(void) fprintf(stderr,
325 					    gettext("crontab: %s: %s\n"),
326 					    editor, strerror(errno));
327 					cstatus = -1;
328 				} else {
329 					pid_t wpid = 0;
330 					while ((wpid = waitpid(cpid, &cstatus,
331 					    0)) == -1 && errno == EINTR)
332 						;
333 					if (wpid  == -1)
334 						cstatus = -1;
335 				}
336 
337 				/* sanity checks */
338 				if ((tmpfp = fopen(edtemp, "r")) == NULL)
339 					crabort("can't open temporary file");
340 				if (fstat(fileno(tmpfp), &stbuf) < 0)
341 					crabort("can't stat temporary file");
342 				if (stbuf.st_size == 0)
343 					crabort("temporary file empty");
344 				if (omodtime == stbuf.st_mtime) {
345 					(void) unlink(edtemp);
346 					fprintf(stderr, gettext(
347 					    "The crontab file was not"
348 					    " changed.\n"));
349 					exit(1);
350 				}
351 				if ((cstatus) && (errno != EINTR)) {
352 					/*
353 					 * Some editors (like 'vi') can return
354 					 * a non-zero exit status even though
355 					 * everything is okay. Need to check.
356 					 */
357 					fprintf(stderr, gettext(ED_ERROR));
358 					fflush(stderr);
359 					if (isatty(fileno(stdin))) {
360 						/* Interactive */
361 						fprintf(stdout,
362 						    gettext(ED_PROMPT),
363 						    yesstr, nostr, nostr);
364 						fflush(stdout);
365 
366 						if (yes()) {
367 							/* Edit again */
368 							continue;
369 						} else {
370 							/* Dump changes */
371 							(void) unlink(edtemp);
372 							exit(1);
373 						}
374 					} else {
375 						/*
376 						 * Non-interactive, dump changes
377 						 */
378 						(void) unlink(edtemp);
379 						exit(1);
380 					}
381 				}
382 				exit(0);
383 			} /* while (1) */
384 		}
385 
386 		/* fix for 1125555 - ignore common signals while waiting */
387 		(void) signal(SIGINT, SIG_IGN);
388 		(void) signal(SIGHUP, SIG_IGN);
389 		(void) signal(SIGQUIT, SIG_IGN);
390 		(void) signal(SIGTERM, SIG_IGN);
391 		wait(&stat_loc);
392 		if ((stat_loc & 0xFF00) != 0)
393 			exit(1);
394 
395 		/*
396 		 * unlink edtemp as 'ruid'. The file contents will be held
397 		 * since we open the file descriptor 'tmpfp' before calling
398 		 * unlink.
399 		 */
400 		if (((ret = seteuid(ruid)) < 0) ||
401 		    ((tmpfp = fopen(edtemp, "r")) == NULL) ||
402 		    (unlink(edtemp) == -1)) {
403 			fprintf(stderr, "crontab: %s: %s\n",
404 			    edtemp, errmsg(errno));
405 			if ((ret < 0) || (tmpfp == NULL))
406 				(void) unlink(edtemp);
407 			exit(1);
408 		} else
409 			seteuid(0);
410 
411 		copycron(tmpfp);
412 	} else {
413 		if (argc == 0)
414 			copycron(stdin);
415 		else if (seteuid(getuid()) != 0 || (fp = fopen(argv[0], "r"))
416 		    == NULL)
417 			crabort(BADOPEN);
418 		else {
419 			seteuid(0);
420 			copycron(fp);
421 		}
422 	}
423 	cron_sendmsg(ADD, login, login, CRON);
424 /*
425  *	if (per_errno == 2)
426  *		fprintf(stderr, gettext(WARNSHELL));
427  */
428 	return (0);
429 }
430 
431 static void
432 copycron(fp)
433 FILE *fp;
434 {
435 	FILE *tfp;
436 	char pid[6], *tnam_end;
437 	int t;
438 
439 	sprintf(pid, "%-5d", getpid());
440 	tnam = xmalloc(strlen(CRONDIR)+strlen(TMPFILE)+7);
441 	strcat(strcat(strcat(strcpy(tnam, CRONDIR), "/"), TMPFILE), pid);
442 	/* cut trailing blanks */
443 	tnam_end = strchr(tnam, ' ');
444 	if (tnam_end != NULL)
445 		*tnam_end = 0;
446 	/* catch SIGINT, SIGHUP, SIGQUIT signals */
447 	if (signal(SIGINT, catch) == SIG_IGN)
448 		signal(SIGINT, SIG_IGN);
449 	if (signal(SIGHUP, catch) == SIG_IGN) signal(SIGHUP, SIG_IGN);
450 	if (signal(SIGQUIT, catch) == SIG_IGN) signal(SIGQUIT, SIG_IGN);
451 	if (signal(SIGTERM, catch) == SIG_IGN) signal(SIGTERM, SIG_IGN);
452 	if ((t = creat(tnam, CRMODE)) == -1) crabort(BADCREATE);
453 	if ((tfp = fdopen(t, "w")) == NULL) {
454 		unlink(tnam);
455 		crabort(BADCREATE);
456 	}
457 	err = 0;	/* if errors found, err set to 1 */
458 	while (fgets(line, CTLINESIZE, fp) != NULL) {
459 		cursor = 0;
460 		while (line[cursor] == ' ' || line[cursor] == '\t')
461 			cursor++;
462 		/* fix for 1039689 - treat blank line like a comment */
463 		if (line[cursor] == '#' || line[cursor] == '\n')
464 			goto cont;
465 		if (next_field(0, 59)) continue;
466 		if (next_field(0, 23)) continue;
467 		if (next_field(1, 31)) continue;
468 		if (next_field(1, 12)) continue;
469 		if (next_field(0, 06)) continue;
470 		if (line[++cursor] == '\0') {
471 			cerror(EOLN);
472 			continue;
473 		}
474 cont:
475 		if (fputs(line, tfp) == EOF) {
476 			unlink(tnam);
477 			crabort(BADCREATE);
478 		}
479 	}
480 	fclose(fp);
481 	fclose(tfp);
482 
483 	/* audit differences between old and new crontabs */
484 	audit_crontab_modify(cf, tnam, err);
485 
486 	if (!err) {
487 		/* make file tfp the new crontab */
488 		unlink(cf);
489 		if (link(tnam, cf) == -1) {
490 			unlink(tnam);
491 			crabort(BADCREATE);
492 		}
493 	} else
494 		fprintf(stderr, "crontab: %s\n", gettext(ERRSFND));
495 	unlink(tnam);
496 }
497 
498 static int
499 next_field(lower, upper)
500 int lower, upper;
501 {
502 	int num, num2;
503 
504 	while ((line[cursor] == ' ') || (line[cursor] == '\t')) cursor++;
505 	if (line[cursor] == '\0') {
506 		cerror(EOLN);
507 		return (1);
508 	}
509 	if (line[cursor] == '*') {
510 		cursor++;
511 		if ((line[cursor] != ' ') && (line[cursor] != '\t')) {
512 			cerror(UNEXPECT);
513 			return (1);
514 		}
515 		return (0);
516 	}
517 	while (TRUE) {
518 		if (!isdigit(line[cursor])) {
519 			cerror(UNEXPECT);
520 			return (1);
521 		}
522 		num = 0;
523 		do {
524 			num = num*10 + (line[cursor]-'0');
525 		} while (isdigit(line[++cursor]));
526 		if ((num < lower) || (num > upper)) {
527 			cerror(OUTOFBOUND);
528 			return (1);
529 		}
530 		if (line[cursor] == '-') {
531 			if (!isdigit(line[++cursor])) {
532 				cerror(UNEXPECT);
533 				return (1);
534 			}
535 			num2 = 0;
536 			do {
537 				num2 = num2*10 + (line[cursor]-'0');
538 			} while (isdigit(line[++cursor]));
539 			if ((num2 < lower) || (num2 > upper)) {
540 				cerror(OUTOFBOUND);
541 				return (1);
542 			}
543 		}
544 		if ((line[cursor] == ' ') || (line[cursor] == '\t')) break;
545 		if (line[cursor] == '\0') {
546 			cerror(EOLN);
547 			return (1);
548 		}
549 		if (line[cursor++] != ',') {
550 			cerror(UNEXPECT);
551 			return (1);
552 		}
553 	}
554 	return (0);
555 }
556 
557 static void
558 cerror(msg)
559 char *msg;
560 {
561 	fprintf(stderr, gettext("%scrontab: error on previous line; %s\n"),
562 	    line, msg);
563 	err = 1;
564 }
565 
566 
567 static void
568 catch(int x)
569 {
570 	unlink(tnam);
571 	exit(1);
572 }
573 
574 static void
575 crabort(msg)
576 char *msg;
577 {
578 	int sverrno;
579 
580 	if (strcmp(edtemp, "") != 0) {
581 		sverrno = errno;
582 		(void) unlink(edtemp);
583 		errno = sverrno;
584 	}
585 	if (tnam != NULL) {
586 		sverrno = errno;
587 		(void) unlink(tnam);
588 		errno = sverrno;
589 	}
590 	fprintf(stderr, "crontab: %s\n", gettext(msg));
591 	exit(1);
592 }
593