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