chiark / gitweb /
Use the Blowfish encryption algorithm instead of IDEA. This is partly
[become] / src / daemon.c
1 /* -*-c-*-
2  *
3  * $Id: daemon.c,v 1.7.2.1 1997/09/26 09:08:05 mdw Exp $
4  *
5  * Running a `become' daemon
6  *
7  * (c) 1997 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: daemon.c,v $
32  * Revision 1.7.2.1  1997/09/26 09:08:05  mdw
33  * Use the Blowfish encryption algorithm instead of IDEA.  This is partly
34  * because I prefer Blowfish (without any particularly strong evidence) but
35  * mainly because IDEA is patented and Blowfish isn't.
36  *
37  * Revision 1.7  1997/09/17 10:23:23  mdw
38  * Fix a typo.  Port numbers are in network order now, so don't change them.
39  *
40  * Revision 1.6  1997/09/09 18:17:06  mdw
41  * Allow default port to be given as a service name or port number.
42  *
43  * Revision 1.5  1997/08/20  16:17:10  mdw
44  * More sensible restart routine: `_reinit' functions replaced by `_end' and
45  * `_init' functions.
46  *
47  * Revision 1.4  1997/08/07 10:00:37  mdw
48  * (Log entry for previous version is bogus.)  Read netgroups database.
49  * Give up privileges permanently on startup.
50  *
51  * Revision 1.2  1997/08/04 10:24:21  mdw
52  * Sources placed under CVS control.
53  *
54  * Revision 1.1  1997/07/21  13:47:50  mdw
55  * Initial revision
56  *
57  */
58
59 /*----- Header files ------------------------------------------------------*/
60
61 /* --- ANSI headers --- */
62
63 #include <errno.h>
64 #include <signal.h>
65 #include <setjmp.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69
70 /* --- Unix headers --- */
71
72 #include <sys/types.h>
73 #include <sys/time.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 <syslog.h>
82 #include <unistd.h>
83
84 /* --- Local headers --- */
85
86 #include "become.h"
87 #include "blowfish.h"
88 #include "config.h"
89 #include "crypt.h"
90 #include "daemon.h"
91 #include "lexer.h"
92 #include "name.h"
93 #include "netg.h"
94 #include "parser.h"
95 #include "rule.h"
96 #include "tx.h"
97 #include "userdb.h"
98 #include "utils.h"
99
100 /*----- Arbitrary constants -----------------------------------------------*/
101
102 #define daemon__awakeEvery (30 * 60)    /* Awaken this often to rescan */
103
104 /*----- Static variables --------------------------------------------------*/
105
106 static int daemon__running = 0;         /* Am I running as a daemon? */
107 static int daemon__port = -1;           /* No particular port yet */
108 static volatile sig_atomic_t daemon__rescan = 0; /* Rescan as soon as poss */
109 #define daemon__signum daemon__rescan   /* Alias for readbility */
110 static int daemon__readKey = 0;         /* Have I read a key? */
111 static unsigned char daemon__key[BLOWFISH_KEYSIZE]; /* Encryption key */
112 static jmp_buf daemon__dieBuf;          /* Jump here to kill the daemon */
113
114 /*----- Main code ---------------------------------------------------------*/
115
116 /* --- @daemon_usePort@ --- *
117  *
118  * Arguments:   @int port@ = port to use, please
119  *
120  * Returns:     ---
121  *
122  * Use:         Instructs the daemon to listen to the given port.
123  */
124
125 void daemon_usePort(int port)
126 {
127   daemon__port = port;
128 }
129
130 /* --- @daemon_readKey@ --- *
131  *
132  * Arguments:   @const char *kf@ = name of file containing key
133  *
134  * Returns:     ---
135  *
136  * Use:         Instructs the daemon to read the named key file.
137  */
138
139 void daemon_readKey(const char *kf)
140 {
141   FILE *fp;
142
143   if (!daemon__running)
144     return;
145
146   if ((fp = fopen(kf, "r")) == 0) {
147     syslog(LOG_WARNING, "couldn't read key file: %e");
148     return;
149   }
150   tx_getBits(daemon__key, 128, fp);
151   fclose(fp);
152   daemon__readKey = 1;
153   return;
154 }
155
156 /* --- @daemon__readConfig@ --- *
157  *
158  * Arguments:   @const char *cf@ = pointer to configuration file to use
159  *
160  * Returns:     Zero if it worked, nonzero if it hurt...
161  *
162  * Use:         Reads the configuration file, and other things.
163  */
164
165 static int daemon__readConfig(const char *cf)
166 {
167   FILE *fp;
168
169   daemon__readKey = 0;
170   if ((fp = fopen(cf, "r")) == 0)
171     return (-1);
172   lexer_scan(fp);
173   yyparse();
174   fclose(fp);
175   if (!daemon__readKey)
176     daemon_readKey(file_KEY);
177   daemon__rescan = 0;
178   T( trace(TRACE_DAEMON, "daemon: read config file"); )
179   return (0);
180 }
181
182 /* --- @daemon__restart@ --- *
183  *
184  * Arguments:   @int sig@ = the signal number
185  *
186  * Returns:     ---
187  *
188  * Use:         Handles signals.  Causes the configuration file to be reread.
189  */
190
191 static void daemon__restart(int sig)
192 {
193   daemon__rescan = 1;
194   signal(sig, daemon__restart);
195 }
196
197 /* --- @daemon__die@ --- *
198  *
199  * Arguments:   @int sig@ = the signal number
200  *
201  * Returns:     via @longjmp@
202  *
203  * Use:         Handles other signals.  Causes the daemon to die.
204  */
205
206 static void daemon__die(int sig)
207 {
208   daemon__signum = sig;
209   longjmp(daemon__dieBuf, 1);
210 }
211
212 /* --- @daemon__read@ --- *
213  *
214  * Arguments:   @int fd@ = socket handle
215  *
216  * Returns:     ---
217  *
218  * Use:         Examines a buffer, and returns a response.
219  */
220
221 void daemon__read(int fd)
222 {
223   unsigned char buff[65536];            /* Buffer for incoming packets */
224   unsigned char rpl[crp_size];          /* Buffer for outgoing replies */
225   struct sockaddr_in sin;               /* Address of packet sender */
226   char sender[64];                      /* Sender's hostname (resolved) */
227   unsigned char sk[BLOWFISH_KEYSIZE];   /* Session key for reply */
228   request rq;                           /* Request buffer for verification */
229
230   /* --- Read the message --- */
231
232   {
233     int slen = sizeof(sin);
234
235     if (recvfrom(fd, (char *)buff, sizeof(buff), 0,
236                  (struct sockaddr *)&sin, &slen) < 0) {
237       T( trace(TRACE_DAEMON, "daemon: error reading packet: %s",
238                strerror(errno)); )
239       syslog(LOG_INFO, "duff packet received: %e");
240       return;
241     }
242   }
243
244   /* --- Resolve the host name --- */
245
246   {
247     struct hostent *he = gethostbyaddr((char *)&sin.sin_addr,
248                                        sizeof(sin.sin_addr),
249                                        AF_INET);
250     sender[0] = 0;
251     strncat(sender,
252             he ? he->h_name : inet_ntoa(sin.sin_addr),
253             sizeof(sender));
254     syslog(LOG_DEBUG, "packet received from %s", sender);
255     T( trace(TRACE_DAEMON, "daemon: received request from %s", sender); )
256   }
257
258   /* --- Unpack the block --- */
259
260   if (crypt_unpackRequest(&rq, buff, daemon__key, sk, rpl) == 0) {
261     burn(buff);
262     T( trace(TRACE_DAEMON, "daemon: received corrupt or invalid request"); )
263     syslog(LOG_INFO, "packet from %s rejected", sender);
264     return;
265   }
266   burn(buff);
267
268   /* --- Fill in the sender's address in the request block --- */
269
270   rq.host = sin.sin_addr;
271
272   /* --- Build a reply block --- */
273
274   {
275     int answer = rule_check(&rq);
276     syslog(LOG_INFO, "request from %s for %i to become %i to run %s %s",
277            sender, rq.from, rq.to, rq.cmd, answer ? "granted" : "denied");
278     crypt_packReply(rpl, sk, answer);
279     burn(sk);
280   }
281
282   /* --- Send the reply off --- */
283
284   sendto(fd, (char *)rpl, crp_size, 0, (struct sockaddr *)&sin, sizeof(sin));
285   T( trace(TRACE_DAEMON, "daemon: reply sent"); )
286   burn(rpl);
287 }
288
289 /* --- @daemon_init@ --- *
290  *
291  * Arguments:   @const char *cf@ = pointer to name of configuration file
292  *              @int port@ = port to listen to, or %$-1$% for default
293  *
294  * Returns:     Never.
295  *
296  * Use:         Starts `become' up in daemon mode.
297  */
298
299 void daemon_init(const char *cf, int port)
300 {
301   int s;
302
303   /* --- Remove my root privileges --- *
304    *
305    * Just in case there's anything dodgy in my configuration file, or the
306    * user wants me to start on a funny port.
307    */
308
309   setuid(getuid());
310
311   /* --- Initialise bits of the program --- */
312
313   daemon__running = 1;
314   daemon__port = port;
315   userdb_init();
316   userdb_local();
317   userdb_yp();
318   netg_init();
319   name_init();
320   rule_init();
321   openlog(quis(), 0, LOG_DAEMON);
322   syslog(LOG_NOTICE, "starting up");
323
324   if (daemon__readConfig(cf))
325     die("couldn't read configuration file");
326
327   /* --- Decide on a port to use --- *
328    *
329    * If I don't have a port yet (e.g., from the configuration file) then
330    * look it up in /etc/services under whatever name I was started as.
331    */
332
333   if (daemon__port == 0) {
334     struct servent *se = getservbyname(quis(), "udp");
335     if (!se)
336       die("no idea which port to listen to");
337     daemon__port = se->s_port;
338   }
339
340   /* --- Now set up a socket --- */
341
342   {
343     struct sockaddr_in sin;
344
345     if ((s = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
346       die("couldn't create socket: %s", strerror(errno));
347     sin.sin_family = AF_INET;
348     sin.sin_port = daemon__port;
349     sin.sin_addr.s_addr = htonl(INADDR_ANY);
350     if (bind(s, (struct sockaddr *)&sin, sizeof(sin))) {
351       die("couldn't bind socket to port %i: %s",
352           ntohs(daemon__port), strerror(errno));
353     }
354   }
355
356   /* --- Fork off into the sunset --- */
357
358 #ifdef NDEBUG
359   {
360     int pid = fork();
361     FILE *fp;
362
363     /* --- Make a background process --- */
364
365     if (pid == -1)
366       die("couldn't fork daemon: %s", strerror(errno));
367     else if (pid != 0)
368       return;
369
370     /* --- Disconnect from the terminal --- */
371
372     setsid();
373
374     /* --- Write my process id to a file --- */
375
376     if ((fp = fopen(file_PID, "w")) != 0) {
377       fprintf(fp, "%lu\n", (unsigned long)getpid());
378       fclose(fp);
379     }
380     T( trace(TRACE_DAEMON, "daemon: forked to pid %li", (long)getpid()); )
381   }
382 #endif
383
384   /* --- Program in daemon death mode --- */
385
386   if (setjmp(daemon__dieBuf)) {
387 #ifdef TRACING
388     if (daemon__signum == SIGQUIT && tracing() & TRACE_RULE) {
389       T( rule_dump(); )
390       signal(SIGQUIT, daemon__die);
391     } else
392 #endif
393     {
394       T( trace(TRACE_DAEMON, "daemon: killed by signal %i",
395                daemon__signum); )
396       syslog(LOG_NOTICE, "killed by signal type %i", daemon__signum);
397       remove(file_PID);
398       exit(0);
399     }
400   } else {
401
402     /* --- Set signal handlers --- */
403
404     signal(SIGHUP, daemon__restart);
405     signal(SIGQUIT, daemon__die);
406     signal(SIGINT, daemon__die);
407     signal(SIGTERM, daemon__die);
408     signal(SIGSEGV, daemon__die);
409     signal(SIGFPE, daemon__die);
410     signal(SIGBUS, daemon__die);
411   }
412
413   /* --- Now wait for something exciting to happen --- *
414    *
415    * Actually, every so often (5 minutes, perhaps) I need to wake up and
416    * rescan the users to see whether they've changed.  Time to play with
417    * @select@.
418    */
419
420   {
421     time_t when;
422
423     /* --- Find when I am, and thus when I need to be awoken again --- */
424
425     when = time(0) + daemon__awakeEvery;
426
427     for (;;) {
428       fd_set fds;
429       int i;
430
431       /* --- Set up the file descriptor tables --- */
432
433       FD_ZERO(&fds);
434       FD_SET(s, &fds);
435
436       /* --- Now wait for something interesting --- */
437
438       T( trace(TRACE_DAEMON, "daemon: waiting for requests"); )
439       i = select(FD_SETSIZE, &fds, 0, 0, 0);
440
441       /* --- Now, see if I need to rescan the config --- */
442
443       if (daemon__rescan || time(0) - when > 0) {
444         daemon__rescan = 0;
445         syslog(LOG_INFO, "rescanning configuration file");
446         name_end();
447         rule_end();
448         netg_end();
449         userdb_end();
450         userdb_init();
451         userdb_local();
452         userdb_yp();
453         netg_init();
454         rule_init();
455         name_init();
456         if (daemon__readConfig(cf))
457           syslog(LOG_ERR, "error reading configuration file");
458         when = time(0) + daemon__awakeEvery;
459       }
460
461       /* --- Read the data from the request --- */
462
463       if (i > 0)
464         daemon__read(s);
465     }
466   }
467 }
468
469 /*----- That's all, folks -------------------------------------------------*/