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