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