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