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