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