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