f6560d59a59246cc90d5ca7b3fa79d444f1a793c
[become] / src / check.c
1 /* -*-c-*-
2 *
3 * $Id: check.c,v 1.14 2004/04/17 10:46:08 mdw Exp $
4 *
5 * Check validity of requests
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 <ctype.h>
34 #include <errno.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39
40 /* --- Unix headers --- */
41
42 #include <sys/time.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
45
46 #include <netinet/in.h>
47
48 #include <arpa/inet.h>
49
50 #include <fcntl.h>
51 #include <netdb.h>
52 #include <unistd.h>
53
54 /* --- mLib headers --- */
55
56 #include <mLib/alloc.h>
57 #include <mLib/quis.h>
58 #include <mLib/report.h>
59 #include <mLib/sym.h>
60 #include <mLib/trace.h>
61
62 /* --- Catacomb headers --- */
63
64 #include <catacomb/buf.h>
65 #include <catacomb/gdsa.h>
66 #include <catacomb/key.h>
67 #include <catacomb/dh.h>
68 #include <catacomb/ec-keys.h>
69 #include <catacomb/mp.h>
70 #include <catacomb/noise.h>
71 #include <catacomb/rand.h>
72
73 /* --- Local headers --- */
74
75 #include "become.h"
76 #include "config.h"
77 #include "lexer.h"
78 #include "name.h"
79 #include "netg.h"
80 #include "rule.h"
81 #include "parse.h"
82 #include "userdb.h"
83
84 /*----- Client-end network support ----------------------------------------*/
85
86 #ifndef NONETWORK
87
88 /* --- @check__send@ --- *
89 *
90 * Arguments: @char *buf@ = pointer to encrypted request
91 * @size_t sz@ = size of request
92 * @int fd@ = socket to send from
93 * @struct sockaddr_in *serv@ = pointer to table of servers
94 * @size_t n_serv@ = number of servers
95 *
96 * Returns: ---
97 *
98 * Use: Sends the request packet to the list of servers. If the
99 * message couldn't be sent to any of them, an error is
100 * reported.
101 */
102
103 static void check__send(char *buf, size_t sz, int fd,
104 struct sockaddr_in *serv, size_t n_serv)
105 {
106 size_t i;
107 int ok = 0;
108 int err = 0;
109
110 for (i = 0; i < n_serv; i++) {
111 if (sendto(fd, buf, sz, 0,
112 (struct sockaddr *)(serv + i), sizeof(serv[i])) < 0) {
113 T( trace(TRACE_CLIENT, "client: send to %s failed: %s",
114 inet_ntoa(serv[i].sin_addr), strerror(errno)); )
115 err = errno;
116 } else
117 ok = 1;
118 }
119
120 if (!ok)
121 die(1, "couldn't send request to server: %s", strerror(err));
122 }
123
124 /* --- @check__ask@ --- *
125 *
126 * Arguments: @request *rq@ = pointer to request buffer
127 * @struct sockaddr_in *serv@ = pointer to table of servers
128 * @size_t n_serv@ = number of servers
129 *
130 * Returns: Nonzero if OK, zero if forbidden
131 *
132 * Use: Contacts a number of servers to decide whether the request
133 * is OK.
134 */
135
136 static int check__ask(request *rq, struct sockaddr_in *serv, size_t n_serv)
137 {
138 static int tbl[] = { 0, 5, 10, 20, -1 };
139
140 char buff[2048], rbuff[2048];
141 size_t rqlen;
142 gdsa g;
143 const char *p;
144 ghash *h;
145 key_packdef *kp;
146 buf b;
147 int fd;
148 struct sockaddr_in sin;
149 socklen_t slen;
150 ssize_t sz;
151 int ans;
152 fd_set fds;
153 struct timeval start, now, tv;
154 gdsa_sig s;
155 key_file f;
156 key *k;
157 key_iter ki;
158 int ind;
159 size_t i;
160
161 /* --- Open the public keyring --- */
162
163 if ((key_open(&f, file_PUBKEY, KOPEN_READ, key_moan, 0)) != 0)
164 die(1, "couldn't open public keyring");
165
166 /* --- Build the request packet --- */
167
168 rand_noisesrc(RAND_GLOBAL, &noise_source);
169 rand_seed(RAND_GLOBAL, 160);
170 buf_init(&b, buff, sizeof(buff));
171 rand_get(RAND_GLOBAL, buf_get(&b, 64), 64);
172 buf_putu32(&b, rq->from);
173 buf_putu32(&b, rq->to);
174 buf_putu16(&b, strlen(rq->cmd));
175 buf_put(&b, rq->cmd, strlen(rq->cmd));
176 rqlen = BLEN(&b);
177
178 /* --- Create my socket --- */
179
180 if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
181 die(1, "couldn't create socket: %s", strerror(errno));
182 if (fcntl(fd, F_SETFD, 1) < 0)
183 die(1, "couldn't set close-on-exec flag for socket: %s", strerror(errno));
184
185 /* --- Bind myself to some address --- */
186
187 sin.sin_family = AF_INET;
188 sin.sin_port = 0;
189 sin.sin_addr.s_addr = htonl(INADDR_ANY);
190
191 if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0)
192 die(1, "couldn't bind socket to address: %s", strerror(errno));
193
194 /* --- Find out when we are --- */
195
196 gettimeofday(&start, 0);
197 ind = 0;
198
199 /* --- Now loop until everything's done --- */
200
201 for (;;) {
202 gettimeofday(&now, 0);
203
204 /* --- If the current timer has expired, find one that hasn't --- *
205 *
206 * Also resend the request after I've found a timer which is still
207 * extant. If there aren't any, report an error.
208 */
209
210 if (now.tv_sec >= start.tv_sec + tbl[ind] &&
211 now.tv_usec >= start.tv_usec) {
212 do {
213 ind++;
214 if (tbl[ind] < 0)
215 die(1, "no reply from servers");
216 } while (now.tv_sec >= start.tv_sec + tbl[ind] &&
217 now.tv_usec >= start.tv_usec);
218 check__send(buff, rqlen, fd, serv, n_serv);
219 T( trace(TRACE_CLIENT, "client: send request to servers"); )
220 }
221
222 /* --- Now wait for a packet to arrive --- */
223
224 if (now.tv_usec > start.tv_usec) {
225 now.tv_usec -= 1000000;
226 now.tv_sec += 1;
227 }
228 tv.tv_sec = start.tv_sec + tbl[ind] - now.tv_sec;
229 tv.tv_usec = start.tv_usec - now.tv_usec;
230
231 /* --- Sort out file descriptors to watch --- */
232
233 FD_ZERO(&fds);
234 FD_SET(fd, &fds);
235
236 /* --- Wait for them --- */
237
238 i = select(FD_SETSIZE, &fds, 0, 0, &tv);
239 if (i == 0 || (i < 0 && errno == EINTR))
240 continue;
241 if (i < 0)
242 die(1, "error waiting for reply: %s", strerror(errno));
243
244 /* --- Read the reply data --- */
245
246 slen = sizeof(sin);
247 if ((sz = recvfrom(fd, (char *)rbuff, sizeof(rbuff), 0,
248 (struct sockaddr *)&sin, &slen)) < 0)
249 die(1, "error reading server's reply: %s", strerror(errno));
250
251 IF_TRACING(TRACE_CLIENT, {
252 struct hostent *h = gethostbyaddr((char *)&sin.sin_addr,
253 sizeof(sin.sin_addr), AF_INET);
254 trace(TRACE_CLIENT, "client: reply received from %s port %i",
255 h ? h->h_name : inet_ntoa(sin.sin_addr),
256 ntohs(sin.sin_port));
257 })
258
259 /* --- Verify the sender --- *
260 *
261 * This is more to avoid confusion than for security: an active
262 * attacker is quite capable of forging the source address. We rely
263 * on the signature in the reply packet for authentication.
264 */
265
266 for (i = 0; i < n_serv; i++) {
267 if (sin.sin_addr.s_addr == serv[i].sin_addr.s_addr &&
268 sin.sin_port == serv[i].sin_port)
269 break;
270 }
271 if (i >= n_serv) {
272 T( trace(TRACE_CLIENT, "client: reply from unknown host"); )
273 continue;
274 }
275
276 /* --- The hash length varies with the key --- *
277 *
278 * So we have to unpack once for each key. This isn't too bad.
279 */
280
281 g.r = &rand_global;
282 g.u = 0;
283 key_mkiter(&ki, &f);
284 while ((k = key_next(&ki)) != 0) {
285 if (key_expired(k)) continue;
286 if (strcmp(k->type, "become") != 0) continue;
287
288 /* --- Get a hash function --- */
289
290 if ((p = key_getattr(&f, k, "hash")) == 0)
291 p = "sha";
292 if ((g.h = ghash_byname(p)) == 0)
293 continue;
294
295 /* --- Unpack the key --- */
296
297 p = key_getattr(&f, k, "sig");
298 if (!p || strcmp(p, "dsa") == 0) {
299 dh_pub dp;
300 kp = key_fetchinit(dh_pubfetch, 0, &dp);
301 if (key_fetch(kp, k)) goto fail_1;
302 if ((g.g = group_prime(&dp.dp)) == 0) goto fail_1;
303 g.p = G_CREATE(g.g);
304 if (G_FROMINT(g.g, g.p, dp.y)) goto fail_2;
305 } else if (strcmp(p, "ecdsa") == 0) {
306 ec_pub ep;
307 ec_info ei;
308 kp = key_fetchinit(ec_pubfetch, 0, &ep);
309 if (key_fetch(kp, k)) goto fail_1;
310 if (ec_getinfo(&ei, ep.cstr)) goto fail_1;
311 g.g = group_ec(&ei);
312 g.p = G_CREATE(g.g);
313 if (G_FROMEC(g.g, g.p, &ep.p)) goto fail_2;
314 } else
315 goto fail_0;
316
317 /* --- Unpack the response --- */
318
319 h = GH_INIT(g.h);
320 GH_HASH(h, buff, rqlen);
321 buf_init(&b, rbuff, sz);
322 if (buf_ensure(&b, g.h->hashsz)) goto fail_3;
323 if (memcmp(BCUR(&b), GH_DONE(h, 0), g.h->hashsz) != 0) goto fail_3;
324 BSTEP(&b, g.h->hashsz);
325 if ((ans = buf_getbyte(&b)) < 0) goto fail_3;
326 GH_DESTROY(h);
327
328 /* --- Verify the signature --- */
329
330 h = gdsa_beginhash(&g);
331 GH_HASH(h, BBASE(&b), BLEN(&b));
332 gdsa_endhash(&g, h);
333 s.r = s.s = 0;
334 if ((s.r = buf_getmp(&b)) == 0 ||
335 (s.s = buf_getmp(&b)) == 0)
336 goto fail_4;
337 if (gdsa_verify(&g, &s, GH_DONE(h, 0)))
338 goto fail_4;
339
340 mp_drop(s.r); mp_drop(s.s);
341 GH_DESTROY(h);
342 G_DESTROY(g.g, g.p);
343 G_DESTROYGROUP(g.g);
344 key_fetchdone(kp);
345 key_close(&f);
346 return (ans);
347
348 /* --- Tidy up and try again --- */
349
350 fail_4:
351 mp_drop(s.r); mp_drop(s.s);
352 fail_3:
353 GH_DESTROY(h);
354 G_DESTROY(g.g, g.p);
355 fail_2:
356 G_DESTROYGROUP(g.g);
357 fail_1:
358 key_fetchdone(kp);
359 fail_0:
360 continue;
361 }
362
363 T( trace(TRACE_CLIENT,
364 "client: invalid or corrupt reply packet"); )
365 }
366
367 die(1, "internal error: can't get here in check__ask");
368 return (0);
369 }
370
371 /* --- @check__client@ --- *
372 *
373 * Arguments: @request *rq@ = pointer to a request block
374 * @FILE *fp@ = file containing server configuration
375 *
376 * Returns: Nonzero if OK, zero if forbidden
377 *
378 * Use: Asks one or several servers whether a request is acceptable.
379 */
380
381 int check__client(request *rq, FILE *fp)
382 {
383 /* --- Format of the file --- *
384 *
385 * The `servers' file contains entries of the form
386 *
387 * %%\syntax{<host> [`:' <port>]}%%
388 *
389 * separates by whitespace. I build them all into an array of socket
390 * addresses and pass the whole lot to another function.
391 */
392
393 struct sockaddr_in *serv; /* Array of servers */
394 size_t n_serv, max_serv; /* Number and maximum number */
395
396 /* --- Initialise the server array --- */
397
398 T( trace(TRACE_CLIENT, "client: reading server definitions"); )
399 n_serv = 0; max_serv = 4; /* Four seems reasonable */
400 serv = xmalloc(sizeof(*serv) * max_serv);
401
402 /* --- Start reading the file --- */
403
404 {
405 char buff[256], *p, *l; /* A buffer and pointers for it */
406 int port; /* Default port for servers */
407 int state; /* Current parser state */
408 struct in_addr t_host; /* Temp place for an address*/
409 int t_port; /* Temp place for a port */
410 int ch; /* The current character */
411
412 /* --- Parser states --- */
413
414 enum {
415 st_start, /* Waiting to begin */
416 st_host, /* Reading a new hostname */
417 st_colon, /* Expecting a colon, maybe */
418 st_preport, /* Waiting before reading port */
419 st_port, /* Reading a port number */
420 st_commit, /* Commit a newly read server */
421 st_done /* Finished reading the file */
422 };
423
424 /* --- Find a default port --- */
425
426 {
427 struct servent *s = getservbyname(quis(), "udp");
428 port = (s ? s->s_port : htons(SERVER_PORT));
429 }
430
431 /* --- Initialise for scanning the file --- */
432
433 state = st_host;
434 p = buff;
435 l = buff + sizeof(buff);
436 t_port = port;
437 ch = getc(fp);
438
439 /* --- Go for it --- */
440
441 while (state != st_done) {
442 switch (state) {
443
444 /* --- Initial whitespace before hostname --- */
445
446 case st_start:
447 if (ch == EOF)
448 state = st_done;
449 else if (isspace((unsigned char)ch))
450 ch = getc(fp);
451 else
452 state = st_host;
453 break;
454
455 /* --- Read a host name --- */
456
457 case st_host:
458 if (p == l)
459 die(1, "string too long in `" file_SERVER "'");
460 if (ch != EOF && !isspace((unsigned char)ch) && ch != ':') {
461 *p++ = ch;
462 ch = getc(fp);
463 } else {
464 struct hostent *h;
465
466 *p++ = 0;
467 if ((h = gethostbyname(buff)) == 0)
468 die(1, "unknown host `%s' in `" file_SERVER "'", buff);
469 memcpy(&t_host, h->h_addr, sizeof(t_host));
470 state = st_colon;
471 }
472 break;
473
474 /* --- Waiting for a colon coming up --- */
475
476 case st_colon:
477 if (ch == EOF)
478 state = st_commit;
479 else if (isspace((unsigned char)ch))
480 ch = getc(fp);
481 else if (ch == ':') {
482 state = st_preport;
483 ch = getc(fp);
484 }
485 else
486 state = st_commit;
487 break;
488
489 /* --- Clearing whitespace before a port number --- */
490
491 case st_preport:
492 if (ch == EOF)
493 state = st_commit;
494 else if (isspace((unsigned char)ch))
495 ch = getc(fp);
496 else {
497 state = st_port;
498 p = buff;
499 }
500 break;
501
502 /* --- Read a port number --- */
503
504 case st_port:
505 if (p == l)
506 die(1, "string too long in `" file_SERVER "'");
507 if (ch != EOF && !isspace((unsigned char)ch) && ch != ':') {
508 *p++ = ch;
509 ch = getc(fp);
510 } else {
511 struct servent *s;
512
513 *p++ = 0;
514 s = getservbyname(buff, "udp");
515 if (!s && isdigit((unsigned char)buff[0]))
516 t_port = htons(atoi(buff));
517 else if (!s)
518 die(1, "unknown service `%s' in `" file_SERVER "'", buff);
519 else
520 t_port = s->s_port;
521 state = st_commit;
522 }
523 break;
524
525 /* --- A server has been read successfully --- */
526
527 case st_commit:
528 if (n_serv == max_serv) {
529 max_serv *= 2;
530 serv = xrealloc(serv, n_serv * sizeof(*serv),
531 max_serv * sizeof(*serv));
532 }
533 serv[n_serv].sin_family = AF_INET;
534 serv[n_serv].sin_addr = t_host;
535 serv[n_serv].sin_port = t_port;
536 n_serv++;
537 state = st_start;
538 p = buff;
539 t_port = port;
540 break;
541
542 /* --- A safety net for a broken parser --- */
543
544 default:
545 die(1, "internal error: can't get here in check__client");
546 break;
547 }
548 }
549 }
550
551 fclose(fp);
552
553 /* --- Now start sending requests --- */
554
555 if (!n_serv)
556 die(1, "no servers specified in `" file_SERVER "'");
557
558 IF_TRACING(TRACE_CLIENT, {
559 size_t i;
560
561 for (i = 0; i < n_serv; i++) {
562 trace(TRACE_CLIENT, "client: server %s port %i",
563 inet_ntoa(serv[i].sin_addr), ntohs(serv[i].sin_port));
564 }
565 })
566 return (check__ask(rq, serv, n_serv));
567 }
568
569 #endif
570
571 /*----- Main checking function --------------------------------------------*/
572
573 /* --- @check@ --- *
574 *
575 * Arguments: @request *rq@ = pointer to request buffer
576 *
577 * Returns: Nonzero if OK, zero if forbidden
578 *
579 * Use: Checks to see if the request is acceptable.
580 */
581
582 int check(request *rq)
583 {
584 FILE *fp;
585
586 /* --- Check if we need to talk to a server --- */
587
588 #ifndef NONETWORK
589 if ((fp = fopen(file_SERVER, "r")) != 0)
590 return (check__client(rq, fp));
591 #endif
592
593 /* --- Otherwise do this all the old-fashioned way --- */
594
595 if ((fp = fopen(file_RULES, "r")) == 0) {
596 die(1, "couldn't read configuration file `%s': %s",
597 file_RULES, strerror(errno));
598 }
599
600 userdb_init();
601 userdb_local();
602 userdb_yp();
603 netg_init();
604 name_init();
605 rule_init();
606 lexer_scan(fp);
607 parse();
608 fclose(fp);
609
610 return (rule_check(rq));
611 }
612
613 /*----- That's all, folks -------------------------------------------------*/