xref: /netbsd-src/libexec/atrun/atrun.c (revision 4472dbe5e3bd91ef2540bada7a7ca7384627ff9b)
1 /*	$NetBSD: atrun.c,v 1.7 1999/08/16 03:08:33 simonb Exp $	*/
2 
3 /*
4  *  atrun.c - run jobs queued by at; run with root privileges.
5  *  Copyright (C) 1993, 1994 Thomas Koenig
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. The name of the author(s) may not be used to endorse or promote
13  *    products derived from this software without specific prior written
14  *    permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 /* System Headers */
29 
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <sys/param.h>
34 #include <ctype.h>
35 #include <dirent.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <signal.h>
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46 #include <unistd.h>
47 #include <syslog.h>
48 #include <utmp.h>
49 
50 #include <paths.h>
51 
52 /* Local headers */
53 
54 #define MAIN
55 #include "privs.h"
56 #include "pathnames.h"
57 #include "atrun.h"
58 
59 /* File scope defines */
60 
61 #if (MAXLOGNAME-1) > UT_NAMESIZE
62 #define LOGNAMESIZE UT_NAMESIZE
63 #else
64 #define LOGNAMESIZE (MAXLOGNAME-1)
65 #endif
66 
67 /* File scope variables */
68 
69 static char *namep;
70 #if 0
71 static char rcsid[] = "$OpenBSD: atrun.c,v 1.7 1997/09/08 22:12:10 millert Exp $";
72 #else
73 __RCSID("$NetBSD: atrun.c,v 1.7 1999/08/16 03:08:33 simonb Exp $");
74 #endif
75 
76 static int debug = 0;
77 
78 /* Local functions */
79 static void perr __P((const char *));
80 static void perr2 __P((char *, char *));
81 static int write_string __P((int, const char *));
82 static void run_file __P((const char *, uid_t, gid_t));
83 static void become_user __P((struct passwd *, uid_t));
84 
85 int main __P((int, char *[]));
86 
87 static void
88 perr(a)
89 	const char *a;
90 {
91 	if (debug)
92 		perror(a);
93 	else
94 		syslog(LOG_ERR, "%s: %m", a);
95 
96 	exit(EXIT_FAILURE);
97 }
98 
99 static void
100 perr2(a, b)
101 	char *a, *b;
102 {
103 	if (debug) {
104 		(void)fputs(a, stderr);
105 		perror(b);
106 	} else
107 		syslog(LOG_ERR, "%s%s: %m", a, b);
108 
109 	exit(EXIT_FAILURE);
110 }
111 
112 static int
113 write_string(fd, a)
114 	int fd;
115 	const char *a;
116 {
117 	return(write(fd, a, strlen(a)));
118 }
119 
120 static void
121 become_user(pentry, uid)
122 	struct passwd *pentry;
123 	uid_t uid;
124 {
125 	if (initgroups(pentry->pw_name, pentry->pw_gid) < 0)
126 		perr("Cannot init group list");
127 
128 	if (setegid(pentry->pw_gid) < 0 || setgid(pentry->pw_gid) < 0)
129 		perr("Cannot change primary group");
130 
131 	if (setlogin(pentry->pw_name) < 0)
132 		perr("Cannot set login name");
133 
134 	if (setuid(uid) < 0 || seteuid(uid) < 0)
135 		perr("Cannot set user id");
136 
137 	if (chdir(pentry->pw_dir) < 0)
138 		chdir("/");
139 }
140 
141 static void
142 run_file(filename, uid, gid)
143 	const char *filename;
144 	uid_t uid;
145 	gid_t gid;
146 {
147 	/*
148 	 * Run a file by by spawning off a process which redirects I/O,
149 	 * spawns a subshell, then waits for it to complete and spawns another
150 	 * process to send mail to the user.
151 	 */
152 	pid_t pid;
153 	int fd_out, fd_in;
154 	int queue;
155 	char mailbuf[LOGNAMESIZE + 1], fmt[49];
156 	char *mailname = NULL;
157 	FILE *stream;
158 	int send_mail = 0;
159 	struct stat buf, lbuf;
160 	off_t size;
161 	struct passwd *pentry;
162 	int fflags;
163 	uid_t nuid;
164 	gid_t ngid;
165 
166 	PRIV_START
167 
168 	if (chmod(filename, S_IRUSR) != 0)
169 		perr("Cannot change file permissions");
170 
171 	PRIV_END
172 
173 	pid = fork();
174 	if (pid == -1)
175 		perr("Cannot fork");
176 	else if (pid != 0)
177 		return;
178 
179 	/*
180 	 * Let's see who we mail to.  Hopefully, we can read it from the
181 	 * command file; if not, send it to the owner, or, failing that, to
182 	 * root.
183 	 */
184 
185 	pentry = getpwuid(uid);
186 	if (pentry == NULL) {
187 		syslog(LOG_ERR,"Userid %u not found - aborting job %s",
188 		    uid, filename);
189 		exit(EXIT_FAILURE);
190 	}
191 	PRIV_START
192 
193 	stream = fopen(filename, "r");
194 
195 	PRIV_END
196 
197 	if (pentry->pw_expire && time(NULL) >= pentry->pw_expire) {
198 		syslog(LOG_ERR, "Userid %u has expired - aborting job %s",
199 		    uid, filename);
200 		exit(EXIT_FAILURE);
201 	}
202 
203 	if (stream == NULL)
204 		perr("Cannot open input file");
205 
206 	if ((fd_in = dup(fileno(stream))) < 0)
207 		perr("Error duplicating input file descriptor");
208 
209 	if (fstat(fd_in, &buf) == -1)
210 		perr("Error in fstat of input file descriptor");
211 
212 	PRIV_START
213 
214 	if (lstat(filename, &lbuf) == -1)
215 		perr("Error in lstat of input file");
216 
217 	PRIV_END
218 
219 	if (S_ISLNK(lbuf.st_mode)) {
220 		syslog(LOG_ERR, "Symbolic link encountered in job %s - aborting",
221 		    filename);
222 		exit(EXIT_FAILURE);
223 	}
224 	if ((lbuf.st_dev != buf.st_dev) || (lbuf.st_ino != buf.st_ino) ||
225 	    (lbuf.st_uid != buf.st_uid) || (lbuf.st_gid != buf.st_gid) ||
226 	    (lbuf.st_size!=buf.st_size)) {
227 		syslog(LOG_ERR, "Somebody changed files from under us for job %s - aborting", filename);
228 		exit(EXIT_FAILURE);
229 	}
230 	if (buf.st_nlink > 1) {
231 		syslog(LOG_ERR, "Somebody is trying to run a linked script for job %s",
232 		    filename);
233 		exit(EXIT_FAILURE);
234 	}
235 	if ((fflags = fcntl(fd_in, F_GETFD)) < 0)
236 		perr("Error in fcntl");
237 
238 	(void)fcntl(fd_in, F_SETFD, fflags & ~FD_CLOEXEC);
239 
240 	(void)snprintf(fmt, sizeof(fmt),
241 	    "#!/bin/sh\n# atrun uid=%%ld gid=%%ld\n# mail %%%ds %%d",
242 	    LOGNAMESIZE);
243 	if (fscanf(stream, fmt, &nuid, &ngid, mailbuf, &send_mail) != 4) {
244 		syslog(LOG_ERR, "File %s is in wrong format - aborting",
245 		    filename);
246 		exit(EXIT_FAILURE);
247 	}
248 	if (mailbuf[0] == '-') {
249 		syslog(LOG_ERR, "illegal mail name %s in %s", mailbuf, filename);
250 		exit(EXIT_FAILURE);
251 	}
252 	mailname = mailbuf;
253 	if (nuid != uid) {
254 		syslog(LOG_ERR, "Job %s - userid %u does not match file uid %u",
255 		    filename, nuid, uid);
256 		exit(EXIT_FAILURE);
257 	}
258 	if (ngid != gid) {
259 		syslog(LOG_ERR, "Job %s - groupid %u does not match file gid %u",
260 		    filename, ngid, gid);
261 		exit(EXIT_FAILURE);
262 	}
263 	(void)fclose(stream);
264 
265 	PRIV_START
266 
267 	if (chdir(_PATH_ATSPOOL) < 0)
268 		perr2("Cannot chdir to ", _PATH_ATSPOOL);
269 
270 	/*
271 	 * Create a file to hold the output of the job we are  about to
272 	 * run. Write the mail header.
273 	 */
274 
275 	if ((fd_out = open(filename,
276 		    O_WRONLY | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) < 0)
277 		perr("Cannot create output file");
278 
279 	PRIV_END
280 
281 	write_string(fd_out, "To: ");
282 	write_string(fd_out, mailname);
283 	write_string(fd_out, "\nSubject: Output from your job ");
284 	write_string(fd_out, filename);
285 	write_string(fd_out, "\n\n");
286 	if (fstat(fd_out, &buf) == -1)
287 		perr("Error in fstat of output file descriptor");
288 	size = buf.st_size;
289 
290 	(void)close(STDIN_FILENO);
291 	(void)close(STDOUT_FILENO);
292 	(void)close(STDERR_FILENO);
293 
294 	pid = fork();
295 	if (pid < 0)
296 		perr("Error in fork");
297 	else if (pid == 0) {
298 		char *nul = NULL;
299 		char **nenvp = &nul;
300 
301 		/*
302 		 * Set up things for the child; we want standard input from
303 		 * the input file, and standard output and error sent to
304 		 * our output file.
305 		 */
306 		if (lseek(fd_in, (off_t) 0, SEEK_SET) < 0)
307 			perr("Error in lseek");
308 
309 		if (dup(fd_in) != STDIN_FILENO)
310 			perr("Error in I/O redirection");
311 
312 		if (dup(fd_out) != STDOUT_FILENO)
313 			perr("Error in I/O redirection");
314 
315 		if (dup(fd_out) != STDERR_FILENO)
316 			perr("Error in I/O redirection");
317 
318 		(void)close(fd_in);
319 		(void)close(fd_out);
320 
321 		PRIV_START
322 
323 		if (chdir(_PATH_ATJOBS) < 0)
324 			perr2("Cannot chdir to ", _PATH_ATJOBS);
325 
326 		queue = *filename;
327 
328 		if (queue > 'b')
329 		    nice(queue - 'b');
330 
331 		become_user(pentry, uid);
332 
333 		if (execle("/bin/sh", "sh", (char *)NULL, nenvp) != 0)
334 			perr("Exec failed for /bin/sh");
335 
336 		PRIV_END
337 	}
338 	/* We're the parent.  Let's wait. */
339 	(void)close(fd_in);
340 	(void)close(fd_out);
341 	waitpid(pid, (int *)NULL, 0);
342 
343 	/*
344 	 * Send mail.  Unlink the output file first, so it is deleted
345 	 * after the run.
346 	 */
347 	PRIV_START
348 
349 	if (stat(filename, &buf) == -1)
350 		perr("Error in stat of output file");
351 	if (open(filename, O_RDONLY) != STDIN_FILENO)
352 		perr("Open of jobfile failed");
353 
354 	(void)unlink(filename);
355 
356 	PRIV_END
357 
358 	if ((buf.st_size != size) || send_mail) {
359 		/* Fork off a child for sending mail */
360 
361 		PRIV_START
362 
363 		become_user(pentry, uid);
364 
365 		execl(_PATH_SENDMAIL, "sendmail", "-F", "Atrun Service",
366 		    "-odi", "-oem", "-t", (char *) NULL);
367 		perr("Exec failed for mail command");
368 
369 		PRIV_END
370 	}
371 	exit(EXIT_SUCCESS);
372 }
373 
374 /* Global functions */
375 
376 int
377 main(argc, argv)
378 	int argc;
379 	char *argv[];
380 {
381 	/*
382 	 * Browse through  _PATH_ATJOBS, checking all the jobfiles wether
383 	 * they should be executed and or deleted. The queue is coded into
384 	 * the first byte of the job filename, the date (in minutes since
385 	 * Eon) as a hex number in the following eight bytes, followed by
386 	 * a dot and a serial number.  A file which has not been executed
387 	 * yet is denoted by its execute - bit set.  For those files which
388 	 * are to be executed, run_file() is called, which forks off a
389 	 * child which takes care of I/O redirection, forks off another
390 	 * child for execution and yet another one, optionally, for sending
391 	 * mail.  Files which already have run are removed during the
392 	 * next invocation.
393 	 */
394 	DIR *spool;
395 	struct dirent *dirent;
396 	struct stat buf;
397 	unsigned long ctm;
398 	int jobno;
399 	char queue;
400 	time_t now, run_time;
401 	char batch_name[] = "Z2345678901234";
402 	uid_t batch_uid;
403 	gid_t batch_gid;
404 	int c;
405 	int run_batch;
406 	double la, load_avg = ATRUN_MAXLOAD;
407 
408 	/*
409 	 * We don't need root privileges all the time; running under uid
410 	 * and gid nobody is fine except for privileged operations.
411 	 */
412 	RELINQUISH_PRIVS_ROOT(NOBODY_UID, NOBODY_GID)
413 
414 	openlog("atrun", LOG_PID, LOG_CRON);
415 
416 	opterr = 0;
417 	errno = 0;
418 	while ((c = getopt(argc, argv, "dl:")) != -1) {
419 		switch (c) {
420 		case 'l':
421 			if (sscanf(optarg, "%lf", &load_avg) != 1)
422 				perr("garbled option -l");
423 			if (load_avg <= 0.)
424 				load_avg = ATRUN_MAXLOAD;
425 			break;
426 
427 		case 'd':
428 			debug++;
429 			break;
430 
431 		case '?':
432 			perr("unknown option");
433 			break;
434 
435 		default:
436 			perr("idiotic option - aborted");
437 			break;
438 		}
439 	}
440 
441 	namep = argv[0];
442 
443 	PRIV_START
444 
445 	if (chdir(_PATH_ATJOBS) != 0)
446 		perr2("Cannot change to ", _PATH_ATJOBS);
447 
448 
449 	/*
450 	 * Main loop. Open spool directory for reading and look over all
451 	 * the files in there. If the filename indicates that the job
452 	 * should be run and the x bit is set, fork off a child which sets
453 	 * its user and group id to that of the files and exec a /bin/sh
454 	 * which executes the shell script. Unlink older files if they
455 	 * should no longer be run.  For deletion, their r bit has to be
456 	 * turned on.
457 	 *
458 	 * Also, pick the oldest batch job to run, at most one per
459 	 * invocation of atrun.
460 	 */
461 	if ((spool = opendir(".")) == NULL)
462 		perr2("Cannot read ", _PATH_ATJOBS);
463 
464 	PRIV_END
465 
466 	now = time(NULL);
467 	run_batch = 0;
468 	batch_uid = (uid_t) -1;
469 	batch_gid = (gid_t) -1;
470 
471 	while ((dirent = readdir(spool)) != NULL) {
472 		PRIV_START
473 
474 		if (stat(dirent->d_name, &buf) != 0)
475 			perr2("Cannot stat in ", _PATH_ATJOBS);
476 
477 		PRIV_END
478 
479 		/* We don't want directories */
480 		if (!S_ISREG(buf.st_mode))
481 			continue;
482 
483 		if (sscanf(dirent->d_name, "%c%5x%8lx", &queue, &jobno, &ctm) != 3)
484 			continue;
485 
486 		run_time = (time_t) ctm * 60;
487 
488 		if ((S_IXUSR & buf.st_mode) && (run_time <= now)) {
489 			if (isupper(queue) &&
490 			    (strcmp(batch_name, dirent->d_name) > 0)) {
491 				run_batch = 1;
492 				(void)strncpy(batch_name, dirent->d_name,
493 				    sizeof(batch_name));
494 				batch_uid = buf.st_uid;
495 				batch_gid = buf.st_gid;
496 			}
497 
498 			/* The file is executable and old enough */
499 			if (islower(queue))
500 				run_file(dirent->d_name, buf.st_uid, buf.st_gid);
501 		}
502 
503 		/* Delete older files */
504 		if ((run_time < now) && !(S_IXUSR & buf.st_mode) &&
505 		    (S_IRUSR & buf.st_mode)) {
506 			PRIV_START
507 
508 			(void)unlink(dirent->d_name);
509 
510 			PRIV_END
511 		}
512 	}
513 
514 	/* Run the single batch file, if any */
515 	if (run_batch && ((getloadavg(&la, 1) == 1) && la < load_avg))
516 		run_file(batch_name, batch_uid, batch_gid);
517 
518 	closelog();
519 	exit(EXIT_SUCCESS);
520 }
521