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