]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/blacklist/bin/blacklistd.c
Import NetBSD's blacklist source from vendor tree
[FreeBSD/FreeBSD.git] / contrib / blacklist / bin / blacklistd.c
1 /*      $NetBSD: blacklistd.c,v 1.34 2016/04/04 15:52:56 christos Exp $ */
2
3 /*-
4  * Copyright (c) 2015 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Christos Zoulas.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34 #include <sys/cdefs.h>
35 __RCSID("$NetBSD: blacklistd.c,v 1.34 2016/04/04 15:52:56 christos Exp $");
36
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/queue.h>
40
41 #ifdef HAVE_LIBUTIL_H
42 #include <libutil.h>
43 #endif
44 #ifdef HAVE_UTIL_H
45 #include <util.h>
46 #endif
47 #include <string.h>
48 #include <signal.h>
49 #include <netdb.h>
50 #include <stdio.h>
51 #include <stdbool.h>
52 #include <string.h>
53 #include <inttypes.h>
54 #include <syslog.h>
55 #include <ctype.h>
56 #include <limits.h>
57 #include <errno.h>
58 #include <poll.h>
59 #include <fcntl.h>
60 #include <err.h>
61 #include <stdlib.h>
62 #include <unistd.h>
63 #include <time.h>
64 #include <ifaddrs.h>
65 #include <netinet/in.h>
66
67 #include "bl.h"
68 #include "internal.h"
69 #include "conf.h"
70 #include "run.h"
71 #include "state.h"
72 #include "support.h"
73
74 static const char *configfile = _PATH_BLCONF;
75 static DB *state;
76 static const char *dbfile = _PATH_BLSTATE;
77 static sig_atomic_t readconf;
78 static sig_atomic_t done;
79 static int vflag;
80
81 static void
82 sigusr1(int n __unused)
83 {
84         debug++;
85 }
86
87 static void
88 sigusr2(int n __unused)
89 {
90         debug--;
91 }
92
93 static void
94 sighup(int n __unused)
95 {
96         readconf++;
97 }
98
99 static void
100 sigdone(int n __unused)
101 {
102         done++;
103 }
104
105 static __dead void
106 usage(int c)
107 {
108         if (c)
109                 warnx("Unknown option `%c'", (char)c);
110         fprintf(stderr, "Usage: %s [-vdfr] [-c <config>] [-R <rulename>] "
111             "[-P <sockpathsfile>] [-C <controlprog>] [-D <dbfile>] "
112             "[-s <sockpath>] [-t <timeout>]\n", getprogname());
113         exit(EXIT_FAILURE);
114 }
115
116 static int
117 getremoteaddress(bl_info_t *bi, struct sockaddr_storage *rss, socklen_t *rsl)
118 {
119         *rsl = sizeof(*rss);
120         memset(rss, 0, *rsl);
121
122         if (getpeername(bi->bi_fd, (void *)rss, rsl) != -1)
123                 return 0;
124
125         if (errno != ENOTCONN) {
126                 (*lfun)(LOG_ERR, "getpeername failed (%m)"); 
127                 return -1;
128         }
129
130         if (bi->bi_slen == 0) {
131                 (*lfun)(LOG_ERR, "unconnected socket with no peer in message");
132                 return -1;
133         }
134
135         switch (bi->bi_ss.ss_family) {
136         case AF_INET:
137                 *rsl = sizeof(struct sockaddr_in);
138                 break;
139         case AF_INET6:
140                 *rsl = sizeof(struct sockaddr_in6);
141                 break;
142         default:
143                 (*lfun)(LOG_ERR, "bad client passed socket family %u",
144                     (unsigned)bi->bi_ss.ss_family); 
145                 return -1;
146         }
147
148         if (*rsl != bi->bi_slen) {
149                 (*lfun)(LOG_ERR, "bad client passed socket length %u != %u",
150                     (unsigned)*rsl, (unsigned)bi->bi_slen); 
151                 return -1;
152         }
153
154         memcpy(rss, &bi->bi_ss, *rsl);
155
156 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
157         if (*rsl != rss->ss_len) {
158                 (*lfun)(LOG_ERR,
159                     "bad client passed socket internal length %u != %u",
160                     (unsigned)*rsl, (unsigned)rss->ss_len); 
161                 return -1;
162         }
163 #endif
164         return 0;
165 }
166
167 static void
168 process(bl_t bl)
169 {
170         struct sockaddr_storage rss;
171         socklen_t rsl;
172         char rbuf[BUFSIZ];
173         bl_info_t *bi;
174         struct conf c;
175         struct dbinfo dbi;
176         struct timespec ts;
177
178         if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
179                 (*lfun)(LOG_ERR, "clock_gettime failed (%m)"); 
180                 return;
181         }
182
183         if ((bi = bl_recv(bl)) == NULL) {
184                 (*lfun)(LOG_ERR, "no message (%m)"); 
185                 return;
186         }
187
188         if (getremoteaddress(bi, &rss, &rsl) == -1)
189                 goto out;
190
191         if (debug) {
192                 sockaddr_snprintf(rbuf, sizeof(rbuf), "%a:%p", (void *)&rss);
193                 (*lfun)(LOG_DEBUG, "processing type=%d fd=%d remote=%s msg=%s"
194                     " uid=%lu gid=%lu", bi->bi_type, bi->bi_fd, rbuf,
195                     bi->bi_msg, (unsigned long)bi->bi_uid,
196                     (unsigned long)bi->bi_gid);
197         }
198
199         if (conf_find(bi->bi_fd, bi->bi_uid, &rss, &c) == NULL) {
200                 (*lfun)(LOG_DEBUG, "no rule matched");
201                 goto out;
202         }
203
204
205         if (state_get(state, &c, &dbi) == -1)
206                 goto out;
207
208         if (debug) {
209                 char b1[128], b2[128];
210                 (*lfun)(LOG_DEBUG, "%s: db state info for %s: count=%d/%d "
211                     "last=%s now=%s", __func__, rbuf, dbi.count, c.c_nfail,
212                     fmttime(b1, sizeof(b1), dbi.last),
213                     fmttime(b2, sizeof(b2), ts.tv_sec));
214         }
215
216         switch (bi->bi_type) {
217         case BL_ADD:
218                 dbi.count++;
219                 dbi.last = ts.tv_sec;
220                 if (dbi.id[0]) {
221                         /*
222                          * We should not be getting this since the rule
223                          * should have blocked the address. A possible
224                          * explanation is that someone removed that rule,
225                          * and another would be that we got another attempt
226                          * before we added the rule. In anycase, we remove
227                          * and re-add the rule because we don't want to add
228                          * it twice, because then we'd lose track of it.
229                          */
230                         (*lfun)(LOG_DEBUG, "rule exists %s", dbi.id);
231                         (void)run_change("rem", &c, dbi.id, 0);
232                         dbi.id[0] = '\0';
233                 }
234                 if (c.c_nfail != -1 && dbi.count >= c.c_nfail) {
235                         int res = run_change("add", &c, dbi.id, sizeof(dbi.id));
236                         if (res == -1)
237                                 goto out;
238                         sockaddr_snprintf(rbuf, sizeof(rbuf), "%a",
239                             (void *)&rss);
240                         (*lfun)(LOG_INFO,
241                             "blocked %s/%d:%d for %d seconds",
242                             rbuf, c.c_lmask, c.c_port, c.c_duration);
243                                 
244                 }
245                 break;
246         case BL_DELETE:
247                 if (dbi.last == 0)
248                         goto out;
249                 dbi.last = 0;
250                 break;
251         default:
252                 (*lfun)(LOG_ERR, "unknown message %d", bi->bi_type); 
253         }
254         if (state_put(state, &c, &dbi) == -1)
255                 goto out;
256 out:
257         close(bi->bi_fd);
258 }
259
260 static void
261 update_interfaces(void)
262 {
263         struct ifaddrs *oifas, *nifas;
264
265         if (getifaddrs(&nifas) == -1)
266                 return;
267
268         oifas = ifas;
269         ifas = nifas;
270
271         if (oifas)
272                 freeifaddrs(oifas);
273 }
274
275 static void
276 update(void)
277 {
278         struct timespec ts;
279         struct conf c;
280         struct dbinfo dbi;
281         unsigned int f, n;
282         char buf[128];
283         void *ss = &c.c_ss;
284
285         if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
286                 (*lfun)(LOG_ERR, "clock_gettime failed (%m)"); 
287                 return;
288         }
289
290 again:
291         for (n = 0, f = 1; state_iterate(state, &c, &dbi, f) == 1;
292             f = 0, n++)
293         {
294                 time_t when = c.c_duration + dbi.last;
295                 if (debug > 1) {
296                         char b1[64], b2[64];
297                         sockaddr_snprintf(buf, sizeof(buf), "%a:%p", ss);
298                         (*lfun)(LOG_DEBUG, "%s:[%u] %s count=%d duration=%d "
299                             "last=%s " "now=%s", __func__, n, buf, dbi.count,
300                             c.c_duration, fmttime(b1, sizeof(b1), dbi.last),
301                             fmttime(b2, sizeof(b2), ts.tv_sec));
302                 }
303                 if (c.c_duration == -1 || when >= ts.tv_sec)
304                         continue;
305                 if (dbi.id[0]) {
306                         run_change("rem", &c, dbi.id, 0);
307                         sockaddr_snprintf(buf, sizeof(buf), "%a", ss);
308                         syslog(LOG_INFO, "released %s/%d:%d after %d seconds",
309                             buf, c.c_lmask, c.c_port, c.c_duration);
310                 }
311                 state_del(state, &c);
312                 goto again;
313         }
314 }
315
316 static void
317 addfd(struct pollfd **pfdp, bl_t **blp, size_t *nfd, size_t *maxfd,
318     const char *path)
319 {
320         bl_t bl = bl_create(true, path, vflag ? vdlog : vsyslog);
321         if (bl == NULL || !bl_isconnected(bl))
322                 exit(EXIT_FAILURE);
323         if (*nfd >= *maxfd) {
324                 *maxfd += 10;
325                 *blp = realloc(*blp, sizeof(**blp) * *maxfd);
326                 if (*blp == NULL)
327                         err(EXIT_FAILURE, "malloc");
328                 *pfdp = realloc(*pfdp, sizeof(**pfdp) * *maxfd);
329                 if (*pfdp == NULL)
330                         err(EXIT_FAILURE, "malloc");
331         }
332
333         (*pfdp)[*nfd].fd = bl_getfd(bl);
334         (*pfdp)[*nfd].events = POLLIN;
335         (*blp)[*nfd] = bl;
336         *nfd += 1;
337 }
338
339 static void
340 uniqueadd(struct conf ***listp, size_t *nlist, size_t *mlist, struct conf *c)
341 {
342         struct conf **list = *listp;
343
344         if (c->c_name[0] == '\0')
345                 return;
346         for (size_t i = 0; i < *nlist; i++) {
347                 if (strcmp(list[i]->c_name, c->c_name) == 0)
348                         return;
349         }
350         if (*nlist == *mlist) {
351                 *mlist += 10;
352                 void *p = realloc(*listp, *mlist * sizeof(*list));
353                 if (p == NULL)
354                         err(EXIT_FAILURE, "Can't allocate for rule list");
355                 list = *listp = p;
356         }
357         list[(*nlist)++] = c;
358 }
359
360 static void
361 rules_flush(void)
362 {
363         struct conf **list;
364         size_t nlist, mlist;
365
366         list = NULL;
367         mlist = nlist = 0;
368         for (size_t i = 0; i < rconf.cs_n; i++)
369                 uniqueadd(&list, &nlist, &mlist, &rconf.cs_c[i]);
370         for (size_t i = 0; i < lconf.cs_n; i++)
371                 uniqueadd(&list, &nlist, &mlist, &lconf.cs_c[i]);
372
373         for (size_t i = 0; i < nlist; i++)
374                 run_flush(list[i]);
375         free(list);
376 }
377
378 static void
379 rules_restore(void)
380 {
381         struct conf c;
382         struct dbinfo dbi;
383         unsigned int f;
384
385         for (f = 1; state_iterate(state, &c, &dbi, f) == 1; f = 0) {
386                 if (dbi.id[0] == '\0')
387                         continue;
388                 (void)run_change("rem", &c, dbi.id, 0);
389                 (void)run_change("add", &c, dbi.id, sizeof(dbi.id));
390         }
391 }
392
393 int
394 main(int argc, char *argv[])
395 {
396         int c, tout, flags, flush, restore;
397         const char *spath, *blsock;
398
399         setprogname(argv[0]);
400
401         spath = NULL;
402         blsock = _PATH_BLSOCK;
403         flush = 0;
404         restore = 0;
405         tout = 0;
406         flags = O_RDWR|O_EXCL|O_CLOEXEC;
407         while ((c = getopt(argc, argv, "C:c:D:dfP:rR:s:t:v")) != -1) {
408                 switch (c) {
409                 case 'C':
410                         controlprog = optarg;
411                         break;
412                 case 'c':
413                         configfile = optarg;
414                         break;
415                 case 'D':
416                         dbfile = optarg;
417                         break;
418                 case 'd':
419                         debug++;
420                         break;
421                 case 'f':
422                         flush++;
423                         break;
424                 case 'P':
425                         spath = optarg;
426                         break;
427                 case 'R':
428                         rulename = optarg;
429                         break;
430                 case 'r':
431                         restore++;
432                         break;
433                 case 's':
434                         blsock = optarg;
435                         break;
436                 case 't':
437                         tout = atoi(optarg) * 1000;
438                         break;
439                 case 'v':
440                         vflag++;
441                         break;
442                 default:
443                         usage(c);
444                 }
445         }
446
447         argc -= optind;
448         if (argc)
449                 usage(0);
450
451         signal(SIGHUP, sighup);
452         signal(SIGINT, sigdone);
453         signal(SIGQUIT, sigdone);
454         signal(SIGTERM, sigdone);
455         signal(SIGUSR1, sigusr1);
456         signal(SIGUSR2, sigusr2);
457
458         openlog(getprogname(), LOG_PID, LOG_DAEMON);
459
460         if (debug) {
461                 lfun = dlog;
462                 if (tout == 0)
463                         tout = 5000;
464         } else {
465                 if (tout == 0)
466                         tout = 15000;
467         }
468
469         update_interfaces();
470         conf_parse(configfile);
471         if (flush) {
472                 rules_flush();
473                 flags |= O_TRUNC;
474         }
475
476         if (restore)
477                 rules_restore();
478
479         struct pollfd *pfd = NULL;
480         bl_t *bl = NULL;
481         size_t nfd = 0;
482         size_t maxfd = 0;
483
484         if (spath == NULL)
485                 addfd(&pfd, &bl, &nfd, &maxfd, blsock);
486         else {
487                 FILE *fp = fopen(spath, "r");
488                 char *line;
489                 if (fp == NULL)
490                         err(EXIT_FAILURE, "Can't open `%s'", spath);
491                 for (; (line = fparseln(fp, NULL, NULL, NULL, 0)) != NULL;
492                     free(line))
493                         addfd(&pfd, &bl, &nfd, &maxfd, line);
494                 fclose(fp);
495         }
496
497         state = state_open(dbfile, flags, 0600);
498         if (state == NULL)
499                 state = state_open(dbfile,  flags | O_CREAT, 0600);
500         if (state == NULL)
501                 return EXIT_FAILURE;
502
503         if (!debug) {
504                 if (daemon(0, 0) == -1)
505                         err(EXIT_FAILURE, "daemon failed");
506                 if (pidfile(NULL) == -1)
507                         err(EXIT_FAILURE, "Can't create pidfile");
508         }
509
510         for (size_t t = 0; !done; t++) {
511                 if (readconf) {
512                         readconf = 0;
513                         conf_parse(configfile);
514                 }
515                 switch (poll(pfd, (nfds_t)nfd, tout)) {
516                 case -1:
517                         if (errno == EINTR)
518                                 continue;
519                         (*lfun)(LOG_ERR, "poll (%m)");
520                         return EXIT_FAILURE;
521                 case 0:
522                         state_sync(state);
523                         break;
524                 default:
525                         for (size_t i = 0; i < nfd; i++)
526                                 if (pfd[i].revents & POLLIN)
527                                         process(bl[i]);
528                 }
529                 if (t % 100 == 0)
530                         state_sync(state);
531                 if (t % 10000 == 0)
532                         update_interfaces();
533                 update();
534         }
535         state_close(state);
536         return 0;
537 }