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