3 * $Id: daemon.c,v 1.17 2004/04/08 01:36:20 mdw Exp $
5 * Running a `become' daemon
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of `become'
14 * `Become' is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * `Become' is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with `become'; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 /*----- Header files ------------------------------------------------------*/
31 /* --- ANSI headers --- */
39 /* --- Unix headers --- */
41 #include <sys/types.h>
43 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #include <arpa/inet.h>
53 /* --- mLib headers --- */
55 #include <mLib/fwatch.h>
56 #include <mLib/quis.h>
57 #include <mLib/report.h>
61 #include <mLib/trace.h>
63 /* --- Catacomb headers --- */
65 #include <catacomb/buf.h>
66 #include <catacomb/dsa.h>
67 #include <catacomb/key.h>
68 #include <catacomb/mp.h>
69 #include <catacomb/noise.h>
70 #include <catacomb/paranoia.h>
71 #include <catacomb/rand.h>
72 #include <catacomb/sha.h>
74 /* --- Local headers --- */
86 /*----- Arbitrary constants -----------------------------------------------*/
88 #define daemon__awakeEvery (10) /* Awaken this often to rescan */
90 /*----- Static variables --------------------------------------------------*/
92 static int daemon__port = -1; /* No particular port yet */
93 static fwatch daemon__cwatch, daemon__kwatch; /* Watching key/config files */
94 static sel_timer daemon__timer; /* Timer for reading */
95 static sel_state daemon__sel; /* Select context */
96 static sel_file daemon__listen; /* Listening socket selector */
97 static const char *daemon__config; /* Configuration file for daemon */
98 static const char *daemon__keyfile; /* Keyring file for daemon */
99 static dsa_priv daemon__key; /* The key data */
101 /*----- Main code ---------------------------------------------------------*/
103 /* --- @daemon_usePort@ --- *
105 * Arguments: @int port@ = port to use, please
109 * Use: Instructs the daemon to listen to the given port.
112 void daemon_usePort(int port)
117 /* --- @daemon__moan@ --- *
119 * Arguments: @const char *f@ = offending file name
120 * @int line@ = offending line of the file
121 * @const char *msg@ = message
122 * @void *p@ = ignored
126 * Use: Reports an error message about a key file.
129 static void daemon__moan(const char *f, int line, const char *msg, void *p)
131 syslog(LOG_ERR, "key file error: %s: %d: %s", f, line, msg);
132 T( trace(TRACE_DAEMON, "daemon: key file error: %s: %d: %s",
136 /* --- @daemon_readKey@ --- *
138 * Arguments: @const char *kf@ = pointer to key file name to use
142 * Use: Loads the private key from the key file.
145 void daemon_readKey(const char *kf)
147 key_packstruct kps[DSA_PRIVFETCHSZ];
155 T( trace(TRACE_DAEMON, "daemon: reading key from `%s'", kf); )
156 if (key_open(&f, kf, KOPEN_READ, daemon__moan, 0))
158 kp = key_fetchinit(dsa_privfetch, kps, &daemon__key);
159 if ((k = key_bytype(&f, "become-dsa")) == 0)
162 err = key_fetch(kp, k);
164 syslog(LOG_ERR, "couldn't load key: %s", key_strerror(err));
166 mp_copy(daemon__key.dp.p);
167 mp_copy(daemon__key.dp.q);
168 mp_copy(daemon__key.dp.g);
169 mp_copy(daemon__key.x);
170 mp_copy(daemon__key.y);
171 daemon__keyfile = kf;
177 /* --- @daemon__readConfig@ --- *
179 * Arguments: @const char *cf@ = pointer to configuration file to use
181 * Returns: Zero if it worked, nonzero if it hurt...
183 * Use: Reads the configuration file, and other things.
186 static int daemon__readConfig(const char *cf)
191 if ((fp = fopen(cf, "r")) == 0)
196 if (!daemon__keyfile)
197 daemon_readKey(file_KEY);
198 T( trace(TRACE_DAEMON, "daemon: read config file"); )
202 /* --- @daemon__read@ --- *
204 * Arguments: @int fd@ = socket handle
205 * @unsigned mode@ = ignored
206 * @void *p@ = ignored
210 * Use: Examines a buffer, and returns a response.
213 void daemon__read(int fd, unsigned mode, void *p)
215 unsigned char buff[65536]; /* Buffer for incoming packets */
216 struct sockaddr_in sin; /* Address of packet sender */
217 char sender[64]; /* Sender's hostname (resolved) */
218 octet h[SHA_HASHSZ]; /* Hash of the transmission buffer */
219 sha_ctx hc; /* Hashing context */
220 request rq; /* Request buffer for verification */
221 ssize_t sz; /* Length of incoming message */
222 socklen_t slen; /* Length of incoming address */
223 uint32 u; /* Scratch integer */
224 uint16 ul; /* And another */
225 struct hostent *he; /* Resolve structure */
226 mp *m, *k, *r, *s; /* Integers for signing */
227 int ans; /* Answer from the check */
228 buf b; /* Buffer for parsing request */
230 /* --- Kick some randomness in the pot --- */
232 noise_timer(RAND_GLOBAL);
234 /* --- Read the message --- */
237 if ((sz = recvfrom(fd, (char *)buff, sizeof(buff), 0,
238 (struct sockaddr *)&sin, &slen)) < 0) {
239 T( trace(TRACE_DAEMON, "daemon: error reading packet: %s",
241 syslog(LOG_INFO, "duff packet received: %e");
245 /* --- Resolve the host name --- */
247 he = gethostbyaddr((char *)&sin.sin_addr, sizeof(sin.sin_addr), AF_INET);
249 strncat(sender, he ? he->h_name : inet_ntoa(sin.sin_addr),
251 syslog(LOG_DEBUG, "packet received from %s", sender);
252 T( trace(TRACE_DAEMON, "daemon: received request from %s", sender); )
254 /* --- Sanity check --- */
256 if (!daemon__keyfile) {
257 syslog(LOG_NOTICE, "no key file: ignoring request");
258 T( trace(TRACE_DAEMON, "daemon: no key file: ignoring request"); )
262 /* --- Unpack the block --- */
264 rq.host = sin.sin_addr;
265 buf_init(&b, buff, sz);
266 if (buf_ensure(&b, SHA_HASHSZ)) goto fail; BSTEP(&b, SHA_HASHSZ);
267 if (buf_getu32(&b, &u)) goto fail; rq.from = u;
268 if (buf_getu32(&b, &u)) goto fail; rq.to = u;
269 if (buf_getu16(&b, &ul) || buf_ensure(&b, ul) || ul >= sizeof(rq.cmd))
271 memcpy(rq.cmd, BCUR(&b), ul);
274 if (BLEFT(&b)) goto fail;
276 /* --- Hash the request block --- */
279 sha_hash(&hc, buff, sz);
282 /* --- Build a reply block --- */
284 ans = rule_check(&rq);
285 syslog(LOG_INFO, "request from %s for %i to become %i to run %s %s",
286 sender, rq.from, rq.to, rq.cmd, ans ? "granted" : "denied");
287 buf_init(&b, buff, sizeof(buff));
288 if (buf_put(&b, h, sizeof(h)) || buf_putbyte(&b, ans))
291 /* --- Sign the reply block --- */
294 sha_hash(&hc, BBASE(&b), BLEN(&b));
296 m = mp_loadb(MP_NEW, h, sizeof(h));
297 rand_get(RAND_GLOBAL, h, sizeof(h));
298 k = mp_loadb(MP_NEWSEC, h, sizeof(h));
300 dsa_mksig(&daemon__key.dp, daemon__key.x, m, k, &r, &s);
310 /* --- Send the reply off --- */
312 sendto(fd, BBASE(&b), BLEN(&b), 0, (struct sockaddr *)&sin, sizeof(sin));
313 T( trace(TRACE_DAEMON, "daemon: reply sent"); )
317 syslog(LOG_ERR, "couldn't respond to query");
318 T( trace(TRACE_DAEMON, "daemon: failed to answer query"); )
321 /* --- @daemon__die@ --- *
323 * Arguments: @int n@ = signal number
324 * @void *p@ = ignored
328 * Use: Exits the daemon.
331 static void daemon__die(int n, void *p)
333 T( trace(TRACE_DAEMON, "daemon: killed by signal %i", n); )
334 syslog(LOG_NOTICE, "killed by signal type %i", n);
339 /* --- @daemon__setTimer@ --- *
345 * Use: Sets the interval timer up.
348 static void daemon__wakeUp(struct timeval *tv, void *p);
350 static void daemon__setTimer(void)
354 gettimeofday(&tv, 0);
355 tv.tv_sec += daemon__awakeEvery;
356 sel_addtimer(&daemon__sel, &daemon__timer, &tv, daemon__wakeUp, 0);
359 /* --- @daemon__rescan@ --- *
361 * Arguments: @int n@ = signal number
362 * @void *p@ = ignored
366 * Use: Forces a rescan of the daemon's configuration.
369 static void daemon__rescan(int n, void *p)
371 syslog(LOG_INFO, "rescanning configuration file");
376 dsa_privfree(&daemon__key);
383 if (daemon__readConfig(daemon__config))
384 syslog(LOG_ERR, "error reading configuration file");
385 sel_rmtimer(&daemon__timer);
387 fwatch_update(&daemon__cwatch, daemon__config);
388 fwatch_update(&daemon__kwatch, daemon__keyfile);
391 /* --- @daemon__wakeUp@ --- *
393 * Arguments: @struct timeval *tv@ = ignored
394 * @void *p@ = ignored
398 * Use: Wakes up periodically to check the configuration file.
401 static void daemon__wakeUp(struct timeval *tv, void *p)
403 T( trace(TRACE_DAEMON, "daemon: interval timer"); )
404 rand_seed(RAND_GLOBAL, 160);
406 if (fwatch_update(&daemon__cwatch, daemon__config))
407 daemon__rescan(0, 0);
408 else if (fwatch_update(&daemon__kwatch, daemon__keyfile)) {
409 const char *kf = daemon__keyfile;
415 /* --- @daemon_init@ --- *
417 * Arguments: @const char *cf@ = pointer to name of configuration file
418 * @int port@ = port to listen to, or %$-1$% for default
419 * @unsigned f@ = various flags
423 * Use: Starts `become' up in daemon mode.
426 void daemon_init(const char *cf, int port, unsigned f)
431 static struct sigvec {
433 void (*proc)(int n, void *p);
436 { SIGHUP, daemon__rescan },
437 { SIGINT, daemon__die },
438 { SIGTERM, daemon__die },
439 { SIGQUIT, daemon__die },
443 /* --- Remove my root privileges --- *
445 * Just in case there's anything dodgy in my configuration file, or the
446 * user wants me to start on a funny port.
451 /* --- Initialize the random number generator --- */
453 rand_noisesrc(RAND_GLOBAL, &noise_source);
454 rand_seed(RAND_GLOBAL, 160);
456 /* --- Initialise bits of the program --- */
460 sel_init(&daemon__sel);
461 sig_init(&daemon__sel);
468 openlog(quis(), 0, LOG_DAEMON);
469 syslog(LOG_NOTICE, "starting up");
471 if (daemon__readConfig(daemon__config))
472 die(1, "couldn't read configuration file");
473 fwatch_init(&daemon__cwatch, daemon__config);
474 fwatch_init(&daemon__kwatch, daemon__keyfile);
476 /* --- Decide on a port to use --- *
478 * If I don't have a port yet (e.g., from the configuration file) then
479 * look it up in /etc/services under whatever name I was started as.
482 if (daemon__port == 0) {
483 struct servent *se = getservbyname(quis(), "udp");
485 daemon__port = se->s_port;
487 daemon__port = htons(SERVER_PORT);
490 /* --- Now set up a socket --- */
493 struct sockaddr_in sin;
495 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
496 die(1, "couldn't create socket: %s", strerror(errno));
497 sin.sin_family = AF_INET;
498 sin.sin_port = daemon__port;
499 sin.sin_addr.s_addr = htonl(INADDR_ANY);
500 if (bind(s, (struct sockaddr *)&sin, sizeof(sin))) {
501 die(1, "couldn't bind socket to port %i: %s",
502 ntohs(daemon__port), strerror(errno));
506 /* --- Fork off into the sunset --- */
508 if (!(f & df_nofork)) {
512 /* --- Make a background process --- */
515 die(1, "couldn't fork daemon: %s", strerror(errno));
519 /* --- Disconnect from the terminal --- */
523 /* --- Write my process id to a file --- */
525 if ((fp = fopen(file_PID, "w")) != 0) {
526 fprintf(fp, "%lu\n", (unsigned long)getpid());
529 T( trace(TRACE_DAEMON, "daemon: forked to pid %li", (long)getpid()); )
532 /* --- Set signal handlers --- */
534 for (i = 0; sigs[i].proc; i++)
535 sig_add(&sigs[i].s, sigs[i].sig, sigs[i].proc, 0);
537 /* --- Set the timer for rescanning the file --- */
541 /* --- Watch for input --- */
543 sel_initfile(&daemon__sel, &daemon__listen, s, SEL_READ,
545 sel_addfile(&daemon__listen);
547 /* --- Now wait for something exciting to happen --- */
550 if (sel_select(&daemon__sel)) {
551 if (errno == EINTR || errno == EAGAIN)
553 syslog(LOG_ERR, "error from select: %s", strerror(errno));
559 /*----- That's all, folks -------------------------------------------------*/