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