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