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