xref: /freebsd/libexec/atrun/atrun.c (revision 724b4bfdf1306e4f2c451b6d146fe0fe0353b2c8)
1 /*
2  *  atrun.c - run jobs queued by at; run with root privileges.
3  *  Copyright (C) 1993, 1994 Thomas Koenig
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. The name of the author(s) may not be used to endorse or promote
11  *    products derived from this software without specific prior written
12  *    permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #ifndef lint
27 static const char rcsid[] =
28   "$FreeBSD$";
29 #endif /* not lint */
30 
31 /* System Headers */
32 
33 #include <sys/fcntl.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <sys/param.h>
38 #include <ctype.h>
39 #include <dirent.h>
40 #include <err.h>
41 #include <grp.h>
42 #include <pwd.h>
43 #include <signal.h>
44 #include <stdarg.h>
45 #include <stddef.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <syslog.h>
50 #include <time.h>
51 #include <unistd.h>
52 #ifdef __FreeBSD__
53 #include <paths.h>
54 #else
55 #include <getopt.h>
56 #endif
57 #ifdef LOGIN_CAP
58 #include <login_cap.h>
59 #endif
60 #ifdef PAM
61 #include <security/pam_appl.h>
62 #include <security/openpam.h>
63 #endif
64 
65 /* Local headers */
66 
67 #include "gloadavg.h"
68 #define MAIN
69 #include "privs.h"
70 
71 /* Macros */
72 
73 #ifndef ATJOB_DIR
74 #define ATJOB_DIR "/usr/spool/atjobs/"
75 #endif
76 
77 #ifndef ATSPOOL_DIR
78 #define ATSPOOL_DIR "/usr/spool/atspool/"
79 #endif
80 
81 #ifndef LOADAVG_MX
82 #define LOADAVG_MX 1.5
83 #endif
84 
85 /* File scope variables */
86 
87 static const char * const atrun = "atrun"; /* service name for syslog etc. */
88 static int debug = 0;
89 
90 void perr(const char *fmt, ...);
91 void perrx(const char *fmt, ...);
92 static void usage(void);
93 
94 /* Local functions */
95 static int
96 write_string(int fd, const char* a)
97 {
98     return write(fd, a, strlen(a));
99 }
100 
101 #undef DEBUG_FORK
102 #ifdef DEBUG_FORK
103 static pid_t
104 myfork(void)
105 {
106 	pid_t res;
107 	res = fork();
108 	if (res == 0)
109 	    kill(getpid(),SIGSTOP);
110 	return res;
111 }
112 
113 #define fork myfork
114 #endif
115 
116 static void
117 run_file(const char *filename, uid_t uid, gid_t gid)
118 {
119 /* Run a file by spawning off a process which redirects I/O,
120  * spawns a subshell, then waits for it to complete and sends
121  * mail to the user.
122  */
123     pid_t pid;
124     int fd_out, fd_in;
125     int queue;
126     char mailbuf[MAXLOGNAME], fmt[64];
127     char *mailname = NULL;
128     FILE *stream;
129     int send_mail = 0;
130     struct stat buf, lbuf;
131     off_t size;
132     struct passwd *pentry;
133     int fflags;
134     long nuid;
135     long ngid;
136 #ifdef PAM
137     pam_handle_t *pamh = NULL;
138     int pam_err;
139     struct pam_conv pamc = {
140 	.conv = openpam_nullconv,
141 	.appdata_ptr = NULL
142     };
143 #endif
144 
145     PRIV_START
146 
147     if (chmod(filename, S_IRUSR) != 0)
148     {
149 	perr("cannot change file permissions");
150     }
151 
152     PRIV_END
153 
154     pid = fork();
155     if (pid == -1)
156 	perr("cannot fork");
157 
158     else if (pid != 0)
159 	return;
160 
161     /* Let's see who we mail to.  Hopefully, we can read it from
162      * the command file; if not, send it to the owner, or, failing that,
163      * to root.
164      */
165 
166     pentry = getpwuid(uid);
167     if (pentry == NULL)
168 	perrx("Userid %lu not found - aborting job %s",
169 		(unsigned long) uid, filename);
170 
171 #ifdef PAM
172     PRIV_START
173 
174     pam_err = pam_start(atrun, pentry->pw_name, &pamc, &pamh);
175     if (pam_err != PAM_SUCCESS)
176 	perrx("cannot start PAM: %s", pam_strerror(pamh, pam_err));
177 
178     pam_err = pam_acct_mgmt(pamh, PAM_SILENT);
179     /* Expired password shouldn't prevent the job from running. */
180     if (pam_err != PAM_SUCCESS && pam_err != PAM_NEW_AUTHTOK_REQD)
181 	perrx("Account %s (userid %lu) unavailable for job %s: %s",
182 	    pentry->pw_name, (unsigned long)uid,
183 	    filename, pam_strerror(pamh, pam_err));
184 
185     pam_end(pamh, pam_err);
186 
187     PRIV_END
188 #endif /* PAM */
189 
190     PRIV_START
191 
192     stream=fopen(filename, "r");
193 
194     PRIV_END
195 
196     if (stream == NULL)
197 	perr("cannot open input file");
198 
199     if ((fd_in = dup(fileno(stream))) <0)
200 	perr("error duplicating input file descriptor");
201 
202     if (fstat(fd_in, &buf) == -1)
203 	perr("error in fstat of input file descriptor");
204 
205     if (lstat(filename, &lbuf) == -1)
206 	perr("error in fstat of input file");
207 
208     if (S_ISLNK(lbuf.st_mode))
209 	perrx("Symbolic link encountered in job %s - aborting", filename);
210 
211     if ((lbuf.st_dev != buf.st_dev) || (lbuf.st_ino != buf.st_ino) ||
212         (lbuf.st_uid != buf.st_uid) || (lbuf.st_gid != buf.st_gid) ||
213         (lbuf.st_size!=buf.st_size))
214 	perrx("Somebody changed files from under us for job %s - aborting",
215 		filename);
216 
217     if (buf.st_nlink > 1)
218 	perrx("Somebody is trying to run a linked script for job %s", filename);
219 
220     if ((fflags = fcntl(fd_in, F_GETFD)) <0)
221 	perr("error in fcntl");
222 
223     fcntl(fd_in, F_SETFD, fflags & ~FD_CLOEXEC);
224 
225     snprintf(fmt, sizeof(fmt),
226 	"#!/bin/sh\n# atrun uid=%%ld gid=%%ld\n# mail %%%ds %%d",
227                           MAXLOGNAME - 1);
228 
229     if (fscanf(stream, fmt, &nuid, &ngid, mailbuf, &send_mail) != 4)
230 	perrx("File %s is in wrong format - aborting", filename);
231 
232     if (mailbuf[0] == '-')
233 	perrx("Illegal mail name %s in %s", mailbuf, filename);
234 
235     mailname = mailbuf;
236 
237     if (nuid != uid)
238 	perrx("Job %s - userid %ld does not match file uid %lu",
239 		filename, nuid, (unsigned long)uid);
240 
241     if (ngid != gid)
242 	perrx("Job %s - groupid %ld does not match file gid %lu",
243 		filename, ngid, (unsigned long)gid);
244 
245     fclose(stream);
246 
247     if (chdir(ATSPOOL_DIR) < 0)
248 	perr("cannot chdir to %s", ATSPOOL_DIR);
249 
250     /* Create a file to hold the output of the job we are about to run.
251      * Write the mail header.
252      */
253     if((fd_out=open(filename,
254 		O_WRONLY | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) < 0)
255 	perr("cannot create output file");
256 
257     write_string(fd_out, "Subject: Output from your job ");
258     write_string(fd_out, filename);
259     write_string(fd_out, "\n\n");
260     fstat(fd_out, &buf);
261     size = buf.st_size;
262 
263     close(STDIN_FILENO);
264     close(STDOUT_FILENO);
265     close(STDERR_FILENO);
266 
267     pid = fork();
268     if (pid < 0)
269 	perr("error in fork");
270 
271     else if (pid == 0)
272     {
273 	char *nul = NULL;
274 	char **nenvp = &nul;
275 
276 	/* Set up things for the child; we want standard input from the input file,
277 	 * and standard output and error sent to our output file.
278 	 */
279 
280 	if (lseek(fd_in, (off_t) 0, SEEK_SET) < 0)
281 	    perr("error in lseek");
282 
283 	if (dup(fd_in) != STDIN_FILENO)
284 	    perr("error in I/O redirection");
285 
286 	if (dup(fd_out) != STDOUT_FILENO)
287 	    perr("error in I/O redirection");
288 
289 	if (dup(fd_out) != STDERR_FILENO)
290 	    perr("error in I/O redirection");
291 
292 	close(fd_in);
293 	close(fd_out);
294 	if (chdir(ATJOB_DIR) < 0)
295 	    perr("cannot chdir to %s", ATJOB_DIR);
296 
297 	queue = *filename;
298 
299 	PRIV_START
300 
301         nice(tolower(queue) - 'a');
302 
303 #ifdef LOGIN_CAP
304 	/*
305 	 * For simplicity and safety, set all aspects of the user context
306 	 * except for a selected subset:  Don't set priority, which was
307 	 * set based on the queue file name according to the tradition.
308 	 * Don't bother to set environment, including path vars, either
309 	 * because it will be discarded anyway.  Although the job file
310 	 * should set umask, preset it here just in case.
311 	 */
312 	if (setusercontext(NULL, pentry, uid, LOGIN_SETALL &
313 		~(LOGIN_SETPRIORITY | LOGIN_SETPATH | LOGIN_SETENV)) != 0)
314 	    exit(EXIT_FAILURE);	/* setusercontext() logged the error */
315 #else /* LOGIN_CAP */
316 	if (initgroups(pentry->pw_name,pentry->pw_gid))
317 	    perr("cannot init group access list");
318 
319 	if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
320 	    perr("cannot change group");
321 
322 	if (setlogin(pentry->pw_name))
323 	    perr("cannot set login name");
324 
325 	if (setuid(uid) < 0 || seteuid(uid) < 0)
326 	    perr("cannot set user id");
327 #endif /* LOGIN_CAP */
328 
329 	if (chdir(pentry->pw_dir))
330 		chdir("/");
331 
332 	if(execle("/bin/sh","sh",(char *) NULL, nenvp) != 0)
333 	    perr("exec failed for /bin/sh");
334 
335 	PRIV_END
336     }
337     /* We're the parent.  Let's wait.
338      */
339     close(fd_in);
340     close(fd_out);
341     waitpid(pid, (int *) NULL, 0);
342 
343     /* Send mail.  Unlink the output file first, so it is deleted after
344      * the run.
345      */
346     stat(filename, &buf);
347     if (open(filename, O_RDONLY) != STDIN_FILENO)
348         perr("open of jobfile failed");
349 
350     unlink(filename);
351     if ((buf.st_size != size) || send_mail)
352     {
353 	PRIV_START
354 
355 #ifdef LOGIN_CAP
356 	/*
357 	 * This time set full context to run the mailer.
358 	 */
359 	if (setusercontext(NULL, pentry, uid, LOGIN_SETALL) != 0)
360 	    exit(EXIT_FAILURE);	/* setusercontext() logged the error */
361 #else /* LOGIN_CAP */
362 	if (initgroups(pentry->pw_name,pentry->pw_gid))
363 	    perr("cannot init group access list");
364 
365 	if (setgid(gid) < 0 || setegid(pentry->pw_gid) < 0)
366 	    perr("cannot change group");
367 
368 	if (setlogin(pentry->pw_name))
369 	    perr("cannot set login name");
370 
371 	if (setuid(uid) < 0 || seteuid(uid) < 0)
372 	    perr("cannot set user id");
373 #endif /* LOGIN_CAP */
374 
375 	if (chdir(pentry->pw_dir))
376 		chdir("/");
377 
378 #ifdef __FreeBSD__
379 	execl(_PATH_SENDMAIL, "sendmail", "-F", "Atrun Service",
380 			"-odi", "-oem",
381 			mailname, (char *) NULL);
382 #else
383         execl(MAIL_CMD, MAIL_CMD, mailname, (char *) NULL);
384 #endif
385 	    perr("exec failed for mail command");
386 
387 	PRIV_END
388     }
389     exit(EXIT_SUCCESS);
390 }
391 
392 /* Global functions */
393 
394 /* Needed in gloadavg.c */
395 void
396 perr(const char *fmt, ...)
397 {
398     const char * const fmtadd = ": %m";
399     char nfmt[strlen(fmt) + strlen(fmtadd) + 1];
400     va_list ap;
401 
402     va_start(ap, fmt);
403     if (debug)
404     {
405 	vwarn(fmt, ap);
406     }
407     else
408     {
409 	snprintf(nfmt, sizeof(nfmt), "%s%s", fmt, fmtadd);
410 	vsyslog(LOG_ERR, nfmt, ap);
411     }
412     va_end(ap);
413 
414     exit(EXIT_FAILURE);
415 }
416 
417 void
418 perrx(const char *fmt, ...)
419 {
420     va_list ap;
421 
422     va_start(ap, fmt);
423     if (debug)
424 	vwarnx(fmt, ap);
425     else
426 	vsyslog(LOG_ERR, fmt, ap);
427     va_end(ap);
428 
429     exit(EXIT_FAILURE);
430 }
431 
432 int
433 main(int argc, char *argv[])
434 {
435 /* Browse through  ATJOB_DIR, checking all the jobfiles wether they should
436  * be executed and or deleted. The queue is coded into the first byte of
437  * the job filename, the date (in minutes since Eon) as a hex number in the
438  * following eight bytes, followed by a dot and a serial number.  A file
439  * which has not been executed yet is denoted by its execute - bit set.
440  * For those files which are to be executed, run_file() is called, which forks
441  * off a child which takes care of I/O redirection, forks off another child
442  * for execution and yet another one, optionally, for sending mail.
443  * Files which already have run are removed during the next invocation.
444  */
445     DIR *spool;
446     struct dirent *dirent;
447     struct stat buf;
448     unsigned long ctm;
449     unsigned long jobno;
450     char queue;
451     time_t now, run_time;
452     char batch_name[] = "Z2345678901234";
453     uid_t batch_uid;
454     gid_t batch_gid;
455     int c;
456     int run_batch;
457     double load_avg = LOADAVG_MX;
458 
459 /* We don't need root privileges all the time; running under uid and gid daemon
460  * is fine.
461  */
462 
463     RELINQUISH_PRIVS_ROOT(DAEMON_UID, DAEMON_GID)
464 
465     openlog(atrun, LOG_PID, LOG_CRON);
466 
467     opterr = 0;
468     while((c=getopt(argc, argv, "dl:"))!= -1)
469     {
470 	switch (c)
471 	{
472 	case 'l':
473 	    if (sscanf(optarg, "%lf", &load_avg) != 1)
474 		perr("garbled option -l");
475 	    if (load_avg <= 0.)
476 		load_avg = LOADAVG_MX;
477 	    break;
478 
479 	case 'd':
480 	    debug ++;
481 	    break;
482 
483 	case '?':
484 	default:
485 	    usage();
486 	}
487     }
488 
489     if (chdir(ATJOB_DIR) != 0)
490 	perr("cannot change to %s", ATJOB_DIR);
491 
492     /* Main loop. Open spool directory for reading and look over all the
493      * files in there. If the filename indicates that the job should be run
494      * and the x bit is set, fork off a child which sets its user and group
495      * id to that of the files and exec a /bin/sh which executes the shell
496      * script. Unlink older files if they should no longer be run.  For
497      * deletion, their r bit has to be turned on.
498      *
499      * Also, pick the oldest batch job to run, at most one per invocation of
500      * atrun.
501      */
502     if ((spool = opendir(".")) == NULL)
503 	perr("cannot read %s", ATJOB_DIR);
504 
505     now = time(NULL);
506     run_batch = 0;
507     batch_uid = (uid_t) -1;
508     batch_gid = (gid_t) -1;
509 
510     while ((dirent = readdir(spool)) != NULL) {
511 	if (stat(dirent->d_name,&buf) != 0)
512 	    perr("cannot stat in %s", ATJOB_DIR);
513 
514 	/* We don't want directories
515 	 */
516 	if (!S_ISREG(buf.st_mode))
517 	    continue;
518 
519 	if (sscanf(dirent->d_name,"%c%5lx%8lx",&queue,&jobno,&ctm) != 3)
520 	    continue;
521 
522 	run_time = (time_t) ctm*60;
523 
524 	if ((S_IXUSR & buf.st_mode) && (run_time <=now)) {
525 	    if (isupper(queue) && (strcmp(batch_name,dirent->d_name) > 0)) {
526 		run_batch = 1;
527 		strlcpy(batch_name, dirent->d_name, sizeof(batch_name));
528 		batch_uid = buf.st_uid;
529 		batch_gid = buf.st_gid;
530 	    }
531 
532 	/* The file is executable and old enough
533 	 */
534 	    if (islower(queue))
535 		run_file(dirent->d_name, buf.st_uid, buf.st_gid);
536 	}
537 	/*  Delete older files
538 	 */
539 	if ((run_time < now) && !(S_IXUSR & buf.st_mode) && (S_IRUSR & buf.st_mode))
540 	    unlink(dirent->d_name);
541     }
542     /* run the single batch file, if any
543     */
544     if (run_batch && (gloadavg() < load_avg))
545 	run_file(batch_name, batch_uid, batch_gid);
546 
547     closelog();
548     exit(EXIT_SUCCESS);
549 }
550 
551 static void
552 usage(void)
553 {
554     if (debug)
555 	fprintf(stderr, "usage: atrun [-l load_avg] [-d]\n");
556     else
557 	syslog(LOG_ERR, "usage: atrun [-l load_avg] [-d]");
558 
559     exit(EXIT_FAILURE);
560 }
561