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