Support elliptic curves, and bigger hashes.
[become] / src / daemon.c
1 /* -*-c-*-
2 *
3 * $Id: daemon.c,v 1.18 2004/04/17 10:46:08 mdw Exp $
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 #include <catacomb/sha.h>
75
76 /* --- Local headers --- */
77
78 #include "become.h"
79 #include "config.h"
80 #include "daemon.h"
81 #include "lexer.h"
82 #include "name.h"
83 #include "netg.h"
84 #include "parse.h"
85 #include "rule.h"
86 #include "userdb.h"
87
88 /*----- Arbitrary constants -----------------------------------------------*/
89
90 #define daemon__awakeEvery (10) /* Awaken this often to rescan */
91
92 /*----- Static variables --------------------------------------------------*/
93
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 */
102
103 /*----- Main code ---------------------------------------------------------*/
104
105 /* --- @daemon_usePort@ --- *
106 *
107 * Arguments: @int port@ = port to use, please
108 *
109 * Returns: ---
110 *
111 * Use: Instructs the daemon to listen to the given port.
112 */
113
114 void daemon_usePort(int port)
115 {
116 daemon__port = port;
117 }
118
119 /* --- @daemon__moan@ --- *
120 *
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
125 *
126 * Returns: ---
127 *
128 * Use: Reports an error message about a key file.
129 */
130
131 static void daemon__moan(const char *f, int line, const char *msg, void *p)
132 {
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",
135 f, line, msg); )
136 }
137
138 /* --- @daemon_readKey@ --- *
139 *
140 * Arguments: @const char *kf@ = pointer to key file name to use
141 *
142 * Returns: ---
143 *
144 * Use: Loads the private key from the key file.
145 */
146
147 void daemon_readKey(const char *kf)
148 {
149 key_packdef *kp;
150 key_file f;
151 key *k;
152 int err;
153 const char *sn;
154 const char *hn;
155 const char *errmsg;
156 gdsa g;
157
158 if (daemon__keyfile)
159 return;
160 T( trace(TRACE_DAEMON, "daemon: reading key from `%s'", kf); )
161 if (key_open(&f, kf, KOPEN_READ, daemon__moan, 0))
162 goto fail_0;
163 if ((k = key_bytype(&f, "become")) == 0) {
164 syslog(LOG_ERR, "no key of type `become' found");
165 goto fail_1;
166 }
167 if ((hn = key_getattr(&f, k, "hash")) == 0)
168 hn = "sha";
169 sn = key_getattr(&f, k, "sig");
170 g.r = &rand_global;
171 if ((g.h = ghash_byname(hn)) == 0) {
172 syslog(LOG_ERR, "key uses unknown hash algorithm `%s'", hn);
173 goto fail_1;
174 }
175 if (!sn || strcmp(sn, "dsa") == 0) {
176 dh_priv dp;
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));
180 goto fail_2;
181 }
182 if ((g.g = group_prime(&dp.dp)) == 0) {
183 syslog(LOG_ERR, "bad prime group in key");
184 goto fail_3;
185 }
186 g.p = G_CREATE(g.g);
187 if (G_FROMINT(g.g, g.p, dp.y)) {
188 syslog(LOG_ERR, "bad public key");
189 goto fail_4;
190 }
191 g.u = mp_copy(dp.x);
192 } else if (strcmp(sn, "ecdsa") == 0) {
193 ec_priv ep;
194 ec_info ei;
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));
198 goto fail_2;
199 }
200 if ((errmsg = ec_getinfo(&ei, ep.cstr)) != 0) {
201 syslog(LOG_ERR, "bad curve in key: %s", errmsg);
202 goto fail_3;
203 }
204 g.g = group_ec(&ei);
205 g.p = G_CREATE(g.g);
206 if (G_FROMEC(g.g, g.p, &ep.p)) {
207 syslog(LOG_ERR, "bad public point");
208 goto fail_4;
209 }
210 g.u = mp_copy(ep.x);
211 } else {
212 syslog(LOG_ERR, "key uses unknown signature scheme `%s'", sn);
213 goto fail_1;
214 }
215 key_fetchdone(kp);
216 daemon__keyfile = kf;
217 key_close(&f);
218 if (daemon__key.g) {
219 mp_drop(daemon__key.u);
220 G_DESTROY(daemon__key.g, daemon__key.p);
221 G_DESTROYGROUP(daemon__key.g);
222 }
223 daemon__key = g;
224 T( trace(TRACE_DAEMON, "daemon: key read ok"); )
225 return;
226
227 fail_4:
228 G_DESTROY(g.g, g.p);
229 fail_3:
230 G_DESTROYGROUP(g.g);
231 fail_2:
232 key_fetchdone(kp);
233 fail_1:
234 key_close(&f);
235 fail_0:
236 T( trace(TRACE_DAEMON, "daemon: failed to read key"); )
237 return;
238 }
239
240 /* --- @daemon__readConfig@ --- *
241 *
242 * Arguments: @const char *cf@ = pointer to configuration file to use
243 *
244 * Returns: Zero if it worked, nonzero if it hurt...
245 *
246 * Use: Reads the configuration file, and other things.
247 */
248
249 static int daemon__readConfig(const char *cf)
250 {
251 FILE *fp;
252
253 daemon__keyfile = 0;
254 if ((fp = fopen(cf, "r")) == 0)
255 return (-1);
256 lexer_scan(fp);
257 parse();
258 fclose(fp);
259 if (!daemon__keyfile)
260 daemon_readKey(file_KEY);
261 T( trace(TRACE_DAEMON, "daemon: read config file"); )
262 return (0);
263 }
264
265 /* --- @daemon__read@ --- *
266 *
267 * Arguments: @int fd@ = socket handle
268 * @unsigned mode@ = ignored
269 * @void *p@ = ignored
270 *
271 * Returns: ---
272 *
273 * Use: Examines a buffer, and returns a response.
274 */
275
276 void daemon__read(int fd, unsigned mode, void *p)
277 {
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 */
291
292 /* --- Kick some randomness in the pot --- */
293
294 noise_timer(RAND_GLOBAL);
295
296 /* --- Read the message --- */
297
298 slen = sizeof(sin);
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",
302 strerror(errno)); )
303 syslog(LOG_INFO, "duff packet received: %e");
304 return;
305 }
306
307 /* --- Resolve the host name --- */
308
309 he = gethostbyaddr((char *)&sin.sin_addr, sizeof(sin.sin_addr), AF_INET);
310 sender[0] = 0;
311 strncat(sender, he ? he->h_name : inet_ntoa(sin.sin_addr),
312 sizeof(sender) - 1);
313 syslog(LOG_DEBUG, "packet received from %s", sender);
314 T( trace(TRACE_DAEMON, "daemon: received request from %s", sender); )
315
316 /* --- Sanity check --- */
317
318 if (!daemon__keyfile) {
319 syslog(LOG_NOTICE, "no key file: ignoring request");
320 T( trace(TRACE_DAEMON, "daemon: no key file: ignoring request"); )
321 return;
322 }
323
324 /* --- Unpack the block --- */
325
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))
332 goto fail;
333 memcpy(rq.cmd, BCUR(&b), ul);
334 rq.cmd[ul] = 0;
335 BSTEP(&b, ul);
336 if (BLEFT(&b)) goto fail;
337
338 /* --- Hash the request block --- */
339
340 h = GH_INIT(daemon__key.h);
341 GH_HASH(h, buff, sz);
342
343 /* --- Build a reply block --- */
344
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;
352
353 /* --- Sign the reply block --- */
354
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);
359 GH_DESTROY(h);
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;
363
364 /* --- Send the reply off --- */
365
366 sendto(fd, BBASE(&b), BLEN(&b), 0, (struct sockaddr *)&sin, sizeof(sin));
367 T( trace(TRACE_DAEMON, "daemon: reply sent"); )
368 return;
369
370 fail:
371 syslog(LOG_ERR, "couldn't respond to query");
372 T( trace(TRACE_DAEMON, "daemon: failed to answer query"); )
373 }
374
375 /* --- @daemon__die@ --- *
376 *
377 * Arguments: @int n@ = signal number
378 * @void *p@ = ignored
379 *
380 * Returns: Doesn't.
381 *
382 * Use: Exits the daemon.
383 */
384
385 static void daemon__die(int n, void *p)
386 {
387 T( trace(TRACE_DAEMON, "daemon: killed by signal %i", n); )
388 syslog(LOG_NOTICE, "killed by signal type %i", n);
389 remove(file_PID);
390 exit(0);
391 }
392
393 /* --- @daemon__setTimer@ --- *
394 *
395 * Arguments: ---
396 *
397 * Returns: ---
398 *
399 * Use: Sets the interval timer up.
400 */
401
402 static void daemon__wakeUp(struct timeval *tv, void *p);
403
404 static void daemon__setTimer(void)
405 {
406 struct timeval tv;
407
408 gettimeofday(&tv, 0);
409 tv.tv_sec += daemon__awakeEvery;
410 sel_addtimer(&daemon__sel, &daemon__timer, &tv, daemon__wakeUp, 0);
411 }
412
413 /* --- @daemon__rescan@ --- *
414 *
415 * Arguments: @int n@ = signal number
416 * @void *p@ = ignored
417 *
418 * Returns: ---
419 *
420 * Use: Forces a rescan of the daemon's configuration.
421 */
422
423 static void daemon__rescan(int n, void *p)
424 {
425 syslog(LOG_INFO, "rescanning configuration file");
426 name_end();
427 rule_end();
428 netg_end();
429 userdb_end();
430 userdb_init();
431 userdb_local();
432 userdb_yp();
433 netg_init();
434 rule_init();
435 name_init();
436 if (daemon__readConfig(daemon__config))
437 syslog(LOG_ERR, "error reading configuration file");
438 sel_rmtimer(&daemon__timer);
439 daemon__setTimer();
440 fwatch_update(&daemon__cwatch, daemon__config);
441 fwatch_update(&daemon__kwatch, daemon__keyfile);
442 }
443
444 /* --- @daemon__wakeUp@ --- *
445 *
446 * Arguments: @struct timeval *tv@ = ignored
447 * @void *p@ = ignored
448 *
449 * Returns: ---
450 *
451 * Use: Wakes up periodically to check the configuration file.
452 */
453
454 static void daemon__wakeUp(struct timeval *tv, void *p)
455 {
456 T( trace(TRACE_DAEMON, "daemon: interval timer"); )
457 rand_seed(RAND_GLOBAL, 160);
458 daemon__setTimer();
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;
463 daemon__keyfile = 0;
464 daemon_readKey(kf);
465 }
466 }
467
468 /* --- @daemon_init@ --- *
469 *
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
473 *
474 * Returns: Never.
475 *
476 * Use: Starts `become' up in daemon mode.
477 */
478
479 void daemon_init(const char *cf, int port, unsigned f)
480 {
481 int s;
482 int i;
483
484 static struct sigvec {
485 int sig;
486 void (*proc)(int n, void *p);
487 sig s;
488 } sigs[] = {
489 { SIGHUP, daemon__rescan },
490 { SIGINT, daemon__die },
491 { SIGTERM, daemon__die },
492 { SIGQUIT, daemon__die },
493 { 0, 0 }
494 };
495
496 /* --- Remove my root privileges --- *
497 *
498 * Just in case there's anything dodgy in my configuration file, or the
499 * user wants me to start on a funny port.
500 */
501
502 setuid(getuid());
503
504 /* --- Initialize the random number generator --- */
505
506 rand_noisesrc(RAND_GLOBAL, &noise_source);
507 rand_seed(RAND_GLOBAL, 160);
508
509 /* --- Initialise bits of the program --- */
510
511 daemon__config = cf;
512 daemon__port = port;
513 sel_init(&daemon__sel);
514 sig_init(&daemon__sel);
515 userdb_init();
516 userdb_local();
517 userdb_yp();
518 netg_init();
519 name_init();
520 rule_init();
521 openlog(quis(), 0, LOG_DAEMON);
522 syslog(LOG_NOTICE, "starting up");
523
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);
528
529 /* --- Decide on a port to use --- *
530 *
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.
533 */
534
535 if (daemon__port == 0) {
536 struct servent *se = getservbyname(quis(), "udp");
537 if (se)
538 daemon__port = se->s_port;
539 else
540 daemon__port = htons(SERVER_PORT);
541 }
542
543 /* --- Now set up a socket --- */
544
545 {
546 struct sockaddr_in sin;
547
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));
556 }
557 }
558
559 /* --- Fork off into the sunset --- */
560
561 if (!(f & df_nofork)) {
562 int pid = fork();
563 FILE *fp;
564
565 /* --- Make a background process --- */
566
567 if (pid == -1)
568 die(1, "couldn't fork daemon: %s", strerror(errno));
569 else if (pid != 0)
570 return;
571
572 /* --- Disconnect from the terminal --- */
573
574 setsid();
575
576 /* --- Write my process id to a file --- */
577
578 if ((fp = fopen(file_PID, "w")) != 0) {
579 fprintf(fp, "%lu\n", (unsigned long)getpid());
580 fclose(fp);
581 }
582 T( trace(TRACE_DAEMON, "daemon: forked to pid %li", (long)getpid()); )
583 }
584
585 /* --- Set signal handlers --- */
586
587 for (i = 0; sigs[i].proc; i++)
588 sig_add(&sigs[i].s, sigs[i].sig, sigs[i].proc, 0);
589
590 /* --- Set the timer for rescanning the file --- */
591
592 daemon__setTimer();
593
594 /* --- Watch for input --- */
595
596 sel_initfile(&daemon__sel, &daemon__listen, s, SEL_READ,
597 daemon__read, 0);
598 sel_addfile(&daemon__listen);
599
600 /* --- Now wait for something exciting to happen --- */
601
602 for (;;) {
603 if (sel_select(&daemon__sel)) {
604 if (errno == EINTR || errno == EAGAIN)
605 continue;
606 syslog(LOG_ERR, "error from select: %s", strerror(errno));
607 exit(1);
608 }
609 }
610 }
611
612 /*----- That's all, folks -------------------------------------------------*/