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