Fix key reloading core dumps. Change advice on keys.
[become] / src / daemon.c
CommitLineData
c4f2d992 1/* -*-c-*-
2 *
8fc4c5cd 3 * $Id: daemon.c,v 1.15 2003/10/26 11:57:46 mdw Exp $
c4f2d992 4 *
5 * Running a `become' daemon
6 *
c758e654 7 * (c) 1998 EBI
c4f2d992 8 */
9
03f996bd 10/*----- Licensing notice --------------------------------------------------*
c4f2d992 11 *
12 * This file is part of `become'
13 *
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.
18 *
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.
23 *
24 * You should have received a copy of the GNU General Public License
03f996bd 25 * along with `become'; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
c4f2d992 27 */
28
29/*----- Revision history --------------------------------------------------*
30 *
31 * $Log: daemon.c,v $
8fc4c5cd 32 * Revision 1.15 2003/10/26 11:57:46 mdw
33 * Fix key reloading core dumps. Change advice on keys.
34 *
030c25b7 35 * Revision 1.14 2003/10/17 16:30:22 mdw
36 * Reload keys and config files automatically.
37 *
4c37c6af 38 * Revision 1.13 2003/10/12 10:00:06 mdw
39 * Fix for daemon mode. Oops.
40 *
f60a3434 41 * Revision 1.12 2003/10/12 00:14:55 mdw
42 * Major overhaul. Now uses DSA signatures rather than the bogus symmetric
43 * encrypt-and-hope thing. Integrated with mLib and Catacomb.
44 *
79fae27d 45 * Revision 1.11 1999/05/04 16:17:12 mdw
46 * Change to header file name for parser. See log for `parse.h' for
47 * details.
48 *
49 * Revision 1.10 1998/04/23 13:23:09 mdw
8702965d 50 * Support new interface to configuration file parser.
51 *
c758e654 52 * Revision 1.9 1998/01/12 16:45:59 mdw
53 * Fix copyright date.
54 *
9e5602f0 55 * Revision 1.8 1997/09/26 09:14:58 mdw
56 * Merged blowfish branch into trunk.
57 *
58 * Revision 1.7.2.1 1997/09/26 09:08:05 mdw
59 * Use the Blowfish encryption algorithm instead of IDEA. This is partly
60 * because I prefer Blowfish (without any particularly strong evidence) but
61 * mainly because IDEA is patented and Blowfish isn't.
62 *
0c6c5a97 63 * Revision 1.7 1997/09/17 10:23:23 mdw
64 * Fix a typo. Port numbers are in network order now, so don't change them.
65 *
f3debbd8 66 * Revision 1.6 1997/09/09 18:17:06 mdw
67 * Allow default port to be given as a service name or port number.
68 *
69 * Revision 1.5 1997/08/20 16:17:10 mdw
ffdb9474 70 * More sensible restart routine: `_reinit' functions replaced by `_end' and
71 * `_init' functions.
72 *
a63eaefc 73 * Revision 1.4 1997/08/07 10:00:37 mdw
74 * (Log entry for previous version is bogus.) Read netgroups database.
75 * Give up privileges permanently on startup.
607937a4 76 *
03f996bd 77 * Revision 1.2 1997/08/04 10:24:21 mdw
78 * Sources placed under CVS control.
79 *
80 * Revision 1.1 1997/07/21 13:47:50 mdw
c4f2d992 81 * Initial revision
82 *
83 */
84
85/*----- Header files ------------------------------------------------------*/
86
87/* --- ANSI headers --- */
88
89#include <errno.h>
90#include <signal.h>
c4f2d992 91#include <stdio.h>
92#include <stdlib.h>
93#include <string.h>
94
95/* --- Unix headers --- */
96
97#include <sys/types.h>
98#include <sys/time.h>
99#include <sys/socket.h>
100
101#include <netinet/in.h>
102
103#include <arpa/inet.h>
104
105#include <netdb.h>
106#include <syslog.h>
107#include <unistd.h>
108
f60a3434 109/* --- mLib headers --- */
110
111#include <mLib/fwatch.h>
112#include <mLib/quis.h>
113#include <mLib/report.h>
114#include <mLib/sel.h>
115#include <mLib/sig.h>
116#include <mLib/sym.h>
117#include <mLib/trace.h>
118
119/* --- Catacomb headers --- */
120
121#include <catacomb/buf.h>
122#include <catacomb/dsa.h>
123#include <catacomb/key.h>
124#include <catacomb/mp.h>
125#include <catacomb/noise.h>
126#include <catacomb/paranoia.h>
127#include <catacomb/rand.h>
128#include <catacomb/sha.h>
129
c4f2d992 130/* --- Local headers --- */
131
132#include "become.h"
133#include "config.h"
c4f2d992 134#include "daemon.h"
c4f2d992 135#include "lexer.h"
136#include "name.h"
607937a4 137#include "netg.h"
79fae27d 138#include "parse.h"
c4f2d992 139#include "rule.h"
c4f2d992 140#include "userdb.h"
c4f2d992 141
142/*----- Arbitrary constants -----------------------------------------------*/
143
030c25b7 144#define daemon__awakeEvery (10) /* Awaken this often to rescan */
c4f2d992 145
146/*----- Static variables --------------------------------------------------*/
147
c4f2d992 148static int daemon__port = -1; /* No particular port yet */
030c25b7 149static fwatch daemon__cwatch, daemon__kwatch; /* Watching key / config files */
f60a3434 150static sel_timer daemon__timer; /* Timer for reading */
151static sel_state daemon__sel; /* Select context */
152static sel_file daemon__listen; /* Listening socket selector */
153static const char *daemon__config; /* Configuration file for daemon */
030c25b7 154static const char *daemon__keyfile; /* Keyring file for daemon */
f60a3434 155static dsa_priv daemon__key; /* The key data */
c4f2d992 156
157/*----- Main code ---------------------------------------------------------*/
158
159/* --- @daemon_usePort@ --- *
160 *
161 * Arguments: @int port@ = port to use, please
162 *
163 * Returns: ---
164 *
165 * Use: Instructs the daemon to listen to the given port.
166 */
167
168void daemon_usePort(int port)
169{
170 daemon__port = port;
171}
172
f60a3434 173/* --- @daemon__moan@ --- *
174 *
175 * Arguments: @const char *f@ = offending file name
176 * @int line@ = offending line of the file
177 * @const char *msg@ = message
178 * @void *p@ = ignored
179 *
180 * Returns: ---
181 *
182 * Use: Reports an error message about a key file.
183 */
184
185static void daemon__moan(const char *f, int line, const char *msg, void *p)
186{
187 syslog(LOG_ERR, "key file error: %s: %d: %s", f, line, msg);
030c25b7 188 T( trace(TRACE_DAEMON, "daemon: key file error: %s: %d: %s",
189 f, line, msg); )
f60a3434 190}
191
c4f2d992 192/* --- @daemon_readKey@ --- *
193 *
f60a3434 194 * Arguments: @const char *kf@ = pointer to key file name to use
c4f2d992 195 *
196 * Returns: ---
197 *
f60a3434 198 * Use: Loads the private key from the key file.
c4f2d992 199 */
200
201void daemon_readKey(const char *kf)
202{
f60a3434 203 key_packstruct kps[DSA_PRIVFETCHSZ];
204 key_packdef *kp;
205 key_file f;
206 key *k;
207 int err;
c4f2d992 208
030c25b7 209 if (daemon__keyfile)
c4f2d992 210 return;
030c25b7 211 T( trace(TRACE_DAEMON, "daemon: reading key from `%s'", kf); )
f60a3434 212 if (key_open(&f, kf, KOPEN_READ, daemon__moan, 0))
c4f2d992 213 return;
f60a3434 214 kp = key_fetchinit(dsa_privfetch, kps, &daemon__key);
215 if ((k = key_bytype(&f, "become-dsa")) == 0)
216 err = KERR_NOTFOUND;
217 else
218 err = key_fetch(kp, k);
219 if (err)
220 syslog(LOG_ERR, "couldn't load key: %s", key_strerror(err));
221 else {
222 mp_copy(daemon__key.dp.p);
223 mp_copy(daemon__key.dp.q);
224 mp_copy(daemon__key.dp.g);
225 mp_copy(daemon__key.x);
226 mp_copy(daemon__key.y);
8fc4c5cd 227 daemon__keyfile = kf;
c4f2d992 228 }
f60a3434 229 key_fetchdone(kp);
230 key_close(&f);
c4f2d992 231}
232
233/* --- @daemon__readConfig@ --- *
234 *
235 * Arguments: @const char *cf@ = pointer to configuration file to use
236 *
237 * Returns: Zero if it worked, nonzero if it hurt...
238 *
239 * Use: Reads the configuration file, and other things.
240 */
241
242static int daemon__readConfig(const char *cf)
243{
244 FILE *fp;
245
030c25b7 246 daemon__keyfile = 0;
c4f2d992 247 if ((fp = fopen(cf, "r")) == 0)
248 return (-1);
249 lexer_scan(fp);
8702965d 250 parse();
c4f2d992 251 fclose(fp);
030c25b7 252 if (!daemon__keyfile)
c4f2d992 253 daemon_readKey(file_KEY);
03f996bd 254 T( trace(TRACE_DAEMON, "daemon: read config file"); )
c4f2d992 255 return (0);
256}
257
c4f2d992 258/* --- @daemon__read@ --- *
259 *
260 * Arguments: @int fd@ = socket handle
f60a3434 261 * @unsigned mode@ = ignored
262 * @void *p@ = ignored
c4f2d992 263 *
264 * Returns: ---
265 *
266 * Use: Examines a buffer, and returns a response.
267 */
268
f60a3434 269void daemon__read(int fd, unsigned mode, void *p)
c4f2d992 270{
271 unsigned char buff[65536]; /* Buffer for incoming packets */
c4f2d992 272 struct sockaddr_in sin; /* Address of packet sender */
273 char sender[64]; /* Sender's hostname (resolved) */
f60a3434 274 octet h[SHA_HASHSZ]; /* Hash of the transmission buffer */
275 sha_ctx hc; /* Hashing context */
c4f2d992 276 request rq; /* Request buffer for verification */
f60a3434 277 ssize_t sz; /* Length of incoming message */
278 socklen_t slen; /* Length of incoming address */
279 uint32 u; /* Scratch integer */
280 uint16 ul; /* And another */
281 struct hostent *he; /* Resolve structure */
282 mp *m, *k, *r, *s; /* Integers for signing */
283 int ans; /* Answer from the check */
284 buf b; /* Buffer for parsing request */
c4f2d992 285
f60a3434 286 /* --- Kick some randomness in the pot --- */
c4f2d992 287
f60a3434 288 noise_timer(RAND_GLOBAL);
c4f2d992 289
f60a3434 290 /* --- Read the message --- */
291
292 slen = sizeof(sin);
293 if ((sz = recvfrom(fd, (char *)buff, sizeof(buff), 0,
294 (struct sockaddr *)&sin, &slen)) < 0) {
295 T( trace(TRACE_DAEMON, "daemon: error reading packet: %s",
296 strerror(errno)); )
297 syslog(LOG_INFO, "duff packet received: %e");
298 return;
c4f2d992 299 }
300
301 /* --- Resolve the host name --- */
302
f60a3434 303 he = gethostbyaddr((char *)&sin.sin_addr, sizeof(sin.sin_addr), AF_INET);
304 sender[0] = 0;
305 strncat(sender, he ? he->h_name : inet_ntoa(sin.sin_addr),
306 sizeof(sender) - 1);
307 syslog(LOG_DEBUG, "packet received from %s", sender);
308 T( trace(TRACE_DAEMON, "daemon: received request from %s", sender); )
c4f2d992 309
030c25b7 310 /* --- Sanity check --- */
311
312 if (!daemon__keyfile) {
313 syslog(LOG_NOTICE, "no key file: ignoring request");
314 T( trace(TRACE_DAEMON, "daemon: no key file: ignoring request"); )
315 return;
316 }
317
c4f2d992 318 /* --- Unpack the block --- */
319
c4f2d992 320 rq.host = sin.sin_addr;
f60a3434 321 buf_init(&b, buff, sz);
322 if (buf_ensure(&b, SHA_HASHSZ)) goto fail; BSTEP(&b, SHA_HASHSZ);
323 if (buf_getu32(&b, &u)) goto fail; rq.from = u;
324 if (buf_getu32(&b, &u)) goto fail; rq.to = u;
325 if (buf_getu16(&b, &ul) || buf_ensure(&b, ul) || ul >= sizeof(rq.cmd))
326 goto fail;
327 memcpy(rq.cmd, BCUR(&b), ul);
328 rq.cmd[ul] = 0;
329 BSTEP(&b, ul);
330 if (BLEFT(&b)) goto fail;
331
332 /* --- Hash the request block --- */
333
334 sha_init(&hc);
335 sha_hash(&hc, buff, sz);
336 sha_done(&hc, h);
c4f2d992 337
338 /* --- Build a reply block --- */
339
f60a3434 340 ans = rule_check(&rq);
341 syslog(LOG_INFO, "request from %s for %i to become %i to run %s %s",
342 sender, rq.from, rq.to, rq.cmd, ans ? "granted" : "denied");
343 buf_init(&b, buff, sizeof(buff));
344 if (buf_put(&b, h, sizeof(h)) || buf_putbyte(&b, ans))
345 goto fail;
346
347 /* --- Sign the reply block --- */
348
349 sha_init(&hc);
350 sha_hash(&hc, BBASE(&b), BLEN(&b));
351 sha_done(&hc, h);
352 m = mp_loadb(MP_NEW, h, sizeof(h));
353 rand_get(RAND_GLOBAL, h, sizeof(h));
354 k = mp_loadb(MP_NEWSEC, h, sizeof(h));
355 r = s = MP_NEW;
356 dsa_mksig(&daemon__key.dp, daemon__key.x, m, k, &r, &s);
357 buf_putmp(&b, r);
358 buf_putmp(&b, s);
359 mp_drop(m);
360 mp_drop(k);
361 mp_drop(r);
362 mp_drop(s);
363 if (BBAD(&b))
364 goto fail;
c4f2d992 365
366 /* --- Send the reply off --- */
367
f60a3434 368 sendto(fd, BBASE(&b), BLEN(&b), 0, (struct sockaddr *)&sin, sizeof(sin));
03f996bd 369 T( trace(TRACE_DAEMON, "daemon: reply sent"); )
f60a3434 370 return;
371
372fail:
373 syslog(LOG_ERR, "couldn't respond to query");
374 T( trace(TRACE_DAEMON, "daemon: failed to answer query"); )
375}
376
377/* --- @daemon__die@ --- *
378 *
379 * Arguments: @int n@ = signal number
380 * @void *p@ = ignored
381 *
382 * Returns: Doesn't.
383 *
384 * Use: Exits the daemon.
385 */
386
387static void daemon__die(int n, void *p)
388{
389 T( trace(TRACE_DAEMON, "daemon: killed by signal %i", n); )
390 syslog(LOG_NOTICE, "killed by signal type %i", n);
391 remove(file_PID);
392 exit(0);
393}
394
395/* --- @daemon__setTimer@ --- *
396 *
397 * Arguments: ---
398 *
399 * Returns: ---
400 *
401 * Use: Sets the interval timer up.
402 */
403
404static void daemon__wakeUp(struct timeval *tv, void *p);
405
406static void daemon__setTimer(void)
407{
408 struct timeval tv;
409
410 gettimeofday(&tv, 0);
411 tv.tv_sec += daemon__awakeEvery;
412 sel_addtimer(&daemon__sel, &daemon__timer, &tv, daemon__wakeUp, 0);
413}
414
415/* --- @daemon__rescan@ --- *
416 *
417 * Arguments: @int n@ = signal number
418 * @void *p@ = ignored
419 *
420 * Returns: ---
421 *
422 * Use: Forces a rescan of the daemon's configuration.
423 */
424
425static void daemon__rescan(int n, void *p)
426{
427 syslog(LOG_INFO, "rescanning configuration file");
428 name_end();
429 rule_end();
430 netg_end();
431 userdb_end();
432 dsa_privfree(&daemon__key);
433 userdb_init();
434 userdb_local();
435 userdb_yp();
436 netg_init();
437 rule_init();
438 name_init();
439 if (daemon__readConfig(daemon__config))
440 syslog(LOG_ERR, "error reading configuration file");
441 sel_rmtimer(&daemon__timer);
442 daemon__setTimer();
030c25b7 443 fwatch_update(&daemon__cwatch, daemon__config);
444 fwatch_update(&daemon__kwatch, daemon__keyfile);
f60a3434 445}
446
447/* --- @daemon__wakeUp@ --- *
448 *
449 * Arguments: @struct timeval *tv@ = ignored
450 * @void *p@ = ignored
451 *
452 * Returns: ---
453 *
454 * Use: Wakes up periodically to check the configuration file.
455 */
456
457static void daemon__wakeUp(struct timeval *tv, void *p)
458{
030c25b7 459 T( trace(TRACE_DAEMON, "daemon: interval timer"); )
f60a3434 460 rand_seed(RAND_GLOBAL, 160);
030c25b7 461 daemon__setTimer();
462 if (fwatch_update(&daemon__cwatch, daemon__config))
f60a3434 463 daemon__rescan(0, 0);
030c25b7 464 else if (fwatch_update(&daemon__kwatch, daemon__keyfile)) {
465 const char *kf = daemon__keyfile;
466 daemon__keyfile = 0;
467 daemon_readKey(kf);
468 }
c4f2d992 469}
470
471/* --- @daemon_init@ --- *
472 *
473 * Arguments: @const char *cf@ = pointer to name of configuration file
474 * @int port@ = port to listen to, or %$-1$% for default
4c37c6af 475 * @unsigned f@ = various flags
c4f2d992 476 *
477 * Returns: Never.
478 *
479 * Use: Starts `become' up in daemon mode.
480 */
481
4c37c6af 482void daemon_init(const char *cf, int port, unsigned f)
c4f2d992 483{
484 int s;
f60a3434 485 int i;
486
487 static struct sigvec {
488 int sig;
489 void (*proc)(int n, void *p);
490 sig s;
491 } sigs[] = {
492 { SIGHUP, daemon__rescan },
493 { SIGINT, daemon__die },
494 { SIGTERM, daemon__die },
495 { SIGQUIT, daemon__die },
496 { 0, 0 }
497 };
c4f2d992 498
499 /* --- Remove my root privileges --- *
500 *
501 * Just in case there's anything dodgy in my configuration file, or the
502 * user wants me to start on a funny port.
503 */
504
607937a4 505 setuid(getuid());
c4f2d992 506
f60a3434 507 /* --- Initialize the random number generator --- */
508
509 rand_noisesrc(RAND_GLOBAL, &noise_source);
510 rand_seed(RAND_GLOBAL, 160);
511
c4f2d992 512 /* --- Initialise bits of the program --- */
513
f60a3434 514 daemon__config = cf;
c4f2d992 515 daemon__port = port;
f60a3434 516 sel_init(&daemon__sel);
517 sig_init(&daemon__sel);
c4f2d992 518 userdb_init();
519 userdb_local();
520 userdb_yp();
607937a4 521 netg_init();
c4f2d992 522 name_init();
523 rule_init();
524 openlog(quis(), 0, LOG_DAEMON);
525 syslog(LOG_NOTICE, "starting up");
526
f60a3434 527 if (daemon__readConfig(daemon__config))
528 die(1, "couldn't read configuration file");
030c25b7 529 fwatch_init(&daemon__cwatch, daemon__config);
530 fwatch_init(&daemon__kwatch, daemon__keyfile);
c4f2d992 531
532 /* --- Decide on a port to use --- *
533 *
534 * If I don't have a port yet (e.g., from the configuration file) then
535 * look it up in /etc/services under whatever name I was started as.
536 */
537
0c6c5a97 538 if (daemon__port == 0) {
c4f2d992 539 struct servent *se = getservbyname(quis(), "udp");
540 if (!se)
f60a3434 541 die(1, "no idea which port to listen to");
f3debbd8 542 daemon__port = se->s_port;
c4f2d992 543 }
544
545 /* --- Now set up a socket --- */
546
547 {
548 struct sockaddr_in sin;
549
550 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
f60a3434 551 die(1, "couldn't create socket: %s", strerror(errno));
c4f2d992 552 sin.sin_family = AF_INET;
0c6c5a97 553 sin.sin_port = daemon__port;
c4f2d992 554 sin.sin_addr.s_addr = htonl(INADDR_ANY);
0c6c5a97 555 if (bind(s, (struct sockaddr *)&sin, sizeof(sin))) {
f60a3434 556 die(1, "couldn't bind socket to port %i: %s",
0c6c5a97 557 ntohs(daemon__port), strerror(errno));
558 }
c4f2d992 559 }
560
561 /* --- Fork off into the sunset --- */
562
4c37c6af 563 if (!(f & df_nofork)) {
c4f2d992 564 int pid = fork();
565 FILE *fp;
566
567 /* --- Make a background process --- */
568
569 if (pid == -1)
f60a3434 570 die(1, "couldn't fork daemon: %s", strerror(errno));
c4f2d992 571 else if (pid != 0)
572 return;
573
574 /* --- Disconnect from the terminal --- */
575
576 setsid();
577
578 /* --- Write my process id to a file --- */
579
580 if ((fp = fopen(file_PID, "w")) != 0) {
581 fprintf(fp, "%lu\n", (unsigned long)getpid());
582 fclose(fp);
583 }
03f996bd 584 T( trace(TRACE_DAEMON, "daemon: forked to pid %li", (long)getpid()); )
c4f2d992 585 }
c4f2d992 586
f60a3434 587 /* --- Set signal handlers --- */
c4f2d992 588
f60a3434 589 for (i = 0; sigs[i].proc; i++)
590 sig_add(&sigs[i].s, sigs[i].sig, sigs[i].proc, 0);
c4f2d992 591
f60a3434 592 /* --- Set the timer for rescanning the file --- */
c4f2d992 593
f60a3434 594 daemon__setTimer();
c4f2d992 595
f60a3434 596 /* --- Watch for input --- */
c4f2d992 597
f60a3434 598 sel_initfile(&daemon__sel, &daemon__listen, s, SEL_READ,
599 daemon__read, 0);
600 sel_addfile(&daemon__listen);
c4f2d992 601
f60a3434 602 /* --- Now wait for something exciting to happen --- */
c4f2d992 603
f60a3434 604 for (;;) {
605 if (sel_select(&daemon__sel)) {
606 if (errno == EINTR || errno == EAGAIN)
607 continue;
608 syslog(LOG_ERR, "error from select: %s", strerror(errno));
609 exit(1);
c4f2d992 610 }
611 }
612}
613
614/*----- That's all, folks -------------------------------------------------*/