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