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