3 * $Id: daemon.c,v 1.18 2004/04/17 10:46:08 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/gdsa.h>
67 #include <catacomb/key.h>
68 #include <catacomb/dh.h>
69 #include <catacomb/ec-keys.h>
70 #include <catacomb/mp.h>
71 #include <catacomb/noise.h>
72 #include <catacomb/paranoia.h>
73 #include <catacomb/rand.h>
74 #include <catacomb/sha.h>
76 /* --- Local headers --- */
88 /*----- Arbitrary constants -----------------------------------------------*/
90 #define daemon__awakeEvery (10) /* Awaken this often to rescan */
92 /*----- Static variables --------------------------------------------------*/
94 static int daemon__port = -1; /* No particular port yet */
95 static fwatch daemon__cwatch, daemon__kwatch; /* Watching key/config files */
96 static sel_timer daemon__timer; /* Timer for reading */
97 static sel_state daemon__sel; /* Select context */
98 static sel_file daemon__listen; /* Listening socket selector */
99 static const char *daemon__config; /* Configuration file for daemon */
100 static const char *daemon__keyfile; /* Keyring file for daemon */
101 static gdsa daemon__key; /* The key data */
103 /*----- Main code ---------------------------------------------------------*/
105 /* --- @daemon_usePort@ --- *
107 * Arguments: @int port@ = port to use, please
111 * Use: Instructs the daemon to listen to the given port.
114 void daemon_usePort(int port)
119 /* --- @daemon__moan@ --- *
121 * Arguments: @const char *f@ = offending file name
122 * @int line@ = offending line of the file
123 * @const char *msg@ = message
124 * @void *p@ = ignored
128 * Use: Reports an error message about a key file.
131 static void daemon__moan(const char *f, int line, const char *msg, void *p)
133 syslog(LOG_ERR, "key file error: %s: %d: %s", f, line, msg);
134 T( trace(TRACE_DAEMON, "daemon: key file error: %s: %d: %s",
138 /* --- @daemon_readKey@ --- *
140 * Arguments: @const char *kf@ = pointer to key file name to use
144 * Use: Loads the private key from the key file.
147 void daemon_readKey(const char *kf)
160 T( trace(TRACE_DAEMON, "daemon: reading key from `%s'", kf); )
161 if (key_open(&f, kf, KOPEN_READ, daemon__moan, 0))
163 if ((k = key_bytype(&f, "become")) == 0) {
164 syslog(LOG_ERR, "no key of type `become' found");
167 if ((hn = key_getattr(&f, k, "hash")) == 0)
169 sn = key_getattr(&f, k, "sig");
171 if ((g.h = ghash_byname(hn)) == 0) {
172 syslog(LOG_ERR, "key uses unknown hash algorithm `%s'", hn);
175 if (!sn || strcmp(sn, "dsa") == 0) {
177 kp = key_fetchinit(dh_privfetch, 0, &dp);
178 if ((err = key_fetch(kp, k)) != 0) {
179 syslog(LOG_ERR, "error loading key: %s", key_strerror(err));
182 if ((g.g = group_prime(&dp.dp)) == 0) {
183 syslog(LOG_ERR, "bad prime group in key");
187 if (G_FROMINT(g.g, g.p, dp.y)) {
188 syslog(LOG_ERR, "bad public key");
192 } else if (strcmp(sn, "ecdsa") == 0) {
195 kp = key_fetchinit(ec_privfetch, 0, &ep);
196 if ((err = key_fetch(kp, k)) != 0) {
197 syslog(LOG_ERR, "error loading key: %s", key_strerror(err));
200 if ((errmsg = ec_getinfo(&ei, ep.cstr)) != 0) {
201 syslog(LOG_ERR, "bad curve in key: %s", errmsg);
206 if (G_FROMEC(g.g, g.p, &ep.p)) {
207 syslog(LOG_ERR, "bad public point");
212 syslog(LOG_ERR, "key uses unknown signature scheme `%s'", sn);
216 daemon__keyfile = kf;
219 mp_drop(daemon__key.u);
220 G_DESTROY(daemon__key.g, daemon__key.p);
221 G_DESTROYGROUP(daemon__key.g);
224 T( trace(TRACE_DAEMON, "daemon: key read ok"); )
236 T( trace(TRACE_DAEMON, "daemon: failed to read key"); )
240 /* --- @daemon__readConfig@ --- *
242 * Arguments: @const char *cf@ = pointer to configuration file to use
244 * Returns: Zero if it worked, nonzero if it hurt...
246 * Use: Reads the configuration file, and other things.
249 static int daemon__readConfig(const char *cf)
254 if ((fp = fopen(cf, "r")) == 0)
259 if (!daemon__keyfile)
260 daemon_readKey(file_KEY);
261 T( trace(TRACE_DAEMON, "daemon: read config file"); )
265 /* --- @daemon__read@ --- *
267 * Arguments: @int fd@ = socket handle
268 * @unsigned mode@ = ignored
269 * @void *p@ = ignored
273 * Use: Examines a buffer, and returns a response.
276 void daemon__read(int fd, unsigned mode, void *p)
278 unsigned char buff[65536]; /* Buffer for incoming packets */
279 struct sockaddr_in sin; /* Address of packet sender */
280 char sender[64]; /* Sender's hostname (resolved) */
281 ghash *h; /* Hash context */
282 request rq; /* Request buffer for verification */
283 ssize_t sz; /* Length of incoming message */
284 socklen_t slen; /* Length of incoming address */
285 uint32 u; /* Scratch integer */
286 uint16 ul; /* And another */
287 struct hostent *he; /* Resolve structure */
288 gdsa_sig s = GDSA_SIG_INIT; /* Signature block */
289 int ans; /* Answer from the check */
290 buf b; /* Buffer for parsing request */
292 /* --- Kick some randomness in the pot --- */
294 noise_timer(RAND_GLOBAL);
296 /* --- Read the message --- */
299 if ((sz = recvfrom(fd, (char *)buff, sizeof(buff), 0,
300 (struct sockaddr *)&sin, &slen)) < 0) {
301 T( trace(TRACE_DAEMON, "daemon: error reading packet: %s",
303 syslog(LOG_INFO, "duff packet received: %e");
307 /* --- Resolve the host name --- */
309 he = gethostbyaddr((char *)&sin.sin_addr, sizeof(sin.sin_addr), AF_INET);
311 strncat(sender, he ? he->h_name : inet_ntoa(sin.sin_addr),
313 syslog(LOG_DEBUG, "packet received from %s", sender);
314 T( trace(TRACE_DAEMON, "daemon: received request from %s", sender); )
316 /* --- Sanity check --- */
318 if (!daemon__keyfile) {
319 syslog(LOG_NOTICE, "no key file: ignoring request");
320 T( trace(TRACE_DAEMON, "daemon: no key file: ignoring request"); )
324 /* --- Unpack the block --- */
326 rq.host = sin.sin_addr;
327 buf_init(&b, buff, sz);
328 if (buf_ensure(&b, 64)) goto fail; BSTEP(&b, 64);
329 if (buf_getu32(&b, &u)) goto fail; rq.from = u;
330 if (buf_getu32(&b, &u)) goto fail; rq.to = u;
331 if (buf_getu16(&b, &ul) || buf_ensure(&b, ul) || ul >= sizeof(rq.cmd))
333 memcpy(rq.cmd, BCUR(&b), ul);
336 if (BLEFT(&b)) goto fail;
338 /* --- Hash the request block --- */
340 h = GH_INIT(daemon__key.h);
341 GH_HASH(h, buff, sz);
343 /* --- Build a reply block --- */
345 ans = rule_check(&rq);
346 syslog(LOG_INFO, "request from %s for %i to become %i to run %s %s",
347 sender, rq.from, rq.to, rq.cmd, ans ? "granted" : "denied");
348 buf_init(&b, buff, sizeof(buff));
349 buf_put(&b, GH_DONE(h, 0), GH_CLASS(h)->hashsz);
350 buf_putbyte(&b, ans);
351 if (BBAD(&b)) goto fail;
353 /* --- Sign the reply block --- */
355 h = gdsa_beginhash(&daemon__key);
356 GH_HASH(h, BBASE(&b), BLEN(&b));
357 gdsa_endhash(&daemon__key, h);
358 gdsa_sign(&daemon__key, &s, GH_DONE(h, 0), 0);
360 buf_putmp(&b, s.r); buf_putmp(&b, s.s);
361 mp_drop(s.r); mp_drop(s.s);
362 if (BBAD(&b)) goto fail;
364 /* --- Send the reply off --- */
366 sendto(fd, BBASE(&b), BLEN(&b), 0, (struct sockaddr *)&sin, sizeof(sin));
367 T( trace(TRACE_DAEMON, "daemon: reply sent"); )
371 syslog(LOG_ERR, "couldn't respond to query");
372 T( trace(TRACE_DAEMON, "daemon: failed to answer query"); )
375 /* --- @daemon__die@ --- *
377 * Arguments: @int n@ = signal number
378 * @void *p@ = ignored
382 * Use: Exits the daemon.
385 static void daemon__die(int n, void *p)
387 T( trace(TRACE_DAEMON, "daemon: killed by signal %i", n); )
388 syslog(LOG_NOTICE, "killed by signal type %i", n);
393 /* --- @daemon__setTimer@ --- *
399 * Use: Sets the interval timer up.
402 static void daemon__wakeUp(struct timeval *tv, void *p);
404 static void daemon__setTimer(void)
408 gettimeofday(&tv, 0);
409 tv.tv_sec += daemon__awakeEvery;
410 sel_addtimer(&daemon__sel, &daemon__timer, &tv, daemon__wakeUp, 0);
413 /* --- @daemon__rescan@ --- *
415 * Arguments: @int n@ = signal number
416 * @void *p@ = ignored
420 * Use: Forces a rescan of the daemon's configuration.
423 static void daemon__rescan(int n, void *p)
425 syslog(LOG_INFO, "rescanning configuration file");
436 if (daemon__readConfig(daemon__config))
437 syslog(LOG_ERR, "error reading configuration file");
438 sel_rmtimer(&daemon__timer);
440 fwatch_update(&daemon__cwatch, daemon__config);
441 fwatch_update(&daemon__kwatch, daemon__keyfile);
444 /* --- @daemon__wakeUp@ --- *
446 * Arguments: @struct timeval *tv@ = ignored
447 * @void *p@ = ignored
451 * Use: Wakes up periodically to check the configuration file.
454 static void daemon__wakeUp(struct timeval *tv, void *p)
456 T( trace(TRACE_DAEMON, "daemon: interval timer"); )
457 rand_seed(RAND_GLOBAL, 160);
459 if (fwatch_update(&daemon__cwatch, daemon__config))
460 daemon__rescan(0, 0);
461 else if (fwatch_update(&daemon__kwatch, daemon__keyfile)) {
462 const char *kf = daemon__keyfile;
468 /* --- @daemon_init@ --- *
470 * Arguments: @const char *cf@ = pointer to name of configuration file
471 * @int port@ = port to listen to, or %$-1$% for default
472 * @unsigned f@ = various flags
476 * Use: Starts `become' up in daemon mode.
479 void daemon_init(const char *cf, int port, unsigned f)
484 static struct sigvec {
486 void (*proc)(int n, void *p);
489 { SIGHUP, daemon__rescan },
490 { SIGINT, daemon__die },
491 { SIGTERM, daemon__die },
492 { SIGQUIT, daemon__die },
496 /* --- Remove my root privileges --- *
498 * Just in case there's anything dodgy in my configuration file, or the
499 * user wants me to start on a funny port.
504 /* --- Initialize the random number generator --- */
506 rand_noisesrc(RAND_GLOBAL, &noise_source);
507 rand_seed(RAND_GLOBAL, 160);
509 /* --- Initialise bits of the program --- */
513 sel_init(&daemon__sel);
514 sig_init(&daemon__sel);
521 openlog(quis(), 0, LOG_DAEMON);
522 syslog(LOG_NOTICE, "starting up");
524 if (daemon__readConfig(daemon__config))
525 die(1, "couldn't read configuration file");
526 fwatch_init(&daemon__cwatch, daemon__config);
527 fwatch_init(&daemon__kwatch, daemon__keyfile);
529 /* --- Decide on a port to use --- *
531 * If I don't have a port yet (e.g., from the configuration file) then
532 * look it up in /etc/services under whatever name I was started as.
535 if (daemon__port == 0) {
536 struct servent *se = getservbyname(quis(), "udp");
538 daemon__port = se->s_port;
540 daemon__port = htons(SERVER_PORT);
543 /* --- Now set up a socket --- */
546 struct sockaddr_in sin;
548 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
549 die(1, "couldn't create socket: %s", strerror(errno));
550 sin.sin_family = AF_INET;
551 sin.sin_port = daemon__port;
552 sin.sin_addr.s_addr = htonl(INADDR_ANY);
553 if (bind(s, (struct sockaddr *)&sin, sizeof(sin))) {
554 die(1, "couldn't bind socket to port %i: %s",
555 ntohs(daemon__port), strerror(errno));
559 /* --- Fork off into the sunset --- */
561 if (!(f & df_nofork)) {
565 /* --- Make a background process --- */
568 die(1, "couldn't fork daemon: %s", strerror(errno));
572 /* --- Disconnect from the terminal --- */
576 /* --- Write my process id to a file --- */
578 if ((fp = fopen(file_PID, "w")) != 0) {
579 fprintf(fp, "%lu\n", (unsigned long)getpid());
582 T( trace(TRACE_DAEMON, "daemon: forked to pid %li", (long)getpid()); )
585 /* --- Set signal handlers --- */
587 for (i = 0; sigs[i].proc; i++)
588 sig_add(&sigs[i].s, sigs[i].sig, sigs[i].proc, 0);
590 /* --- Set the timer for rescanning the file --- */
594 /* --- Watch for input --- */
596 sel_initfile(&daemon__sel, &daemon__listen, s, SEL_READ,
598 sel_addfile(&daemon__listen);
600 /* --- Now wait for something exciting to happen --- */
603 if (sel_select(&daemon__sel)) {
604 if (errno == EINTR || errno == EAGAIN)
606 syslog(LOG_ERR, "error from select: %s", strerror(errno));
612 /*----- That's all, folks -------------------------------------------------*/