2 * Bouncer -- A Daemon for Turning Away Mischievous Guests
4 * (c) 2016 Martin Mares <mj@ucw.cz>
10 #include <ucw/clists.h>
13 #include <ucw/mainloop.h>
15 #include <ucw/string.h>
18 #include <arpa/inet.h>
21 #include <sys/types.h>
22 #include <sys/socket.h>
28 #include <libipset/data.h>
29 #include <libipset/session.h>
30 #include <libipset/types.h>
32 /*** Internal representation of IPv4/IPv6 addresses ***/
34 // In network byte order, IPv4 represented as ::ffff:1.2.3.4
39 #define ADDR_BUFSIZE 64
40 #define AFMT(_a) ({ char *_buf = alloca(ADDR_BUFSIZE); addr_format(_buf, _a); _buf; })
42 static bool addr_is_v4(struct addr addr)
44 return !addr.a[0] && !addr.a[1] && addr.a[2] == htonl(0xffff);
47 static void addr_format(char *buf, struct addr addr)
53 in4.s_addr = addr.a[3];
54 ok = inet_ntop(AF_INET, &in4, buf, ADDR_BUFSIZE);
59 memcpy(&in6, &addr, sizeof(addr));
60 ok = inet_ntop(AF_INET6, &in6, buf, ADDR_BUFSIZE);
63 snprintf(buf, ADDR_BUFSIZE, "<error %d>", errno);
66 static bool addr_parse(struct addr *addr, const char *src)
71 if (inet_pton(AF_INET, src, &a4))
73 addr->a[0] = addr->a[1] = 0;
74 addr->a[2] = htonl(0xffff);
75 addr->a[3] = a4.s_addr;
78 else if (inet_pton(AF_INET6, src, &a6))
80 memcpy(addr, &a6, 16);
87 /*** Configuration ***/
89 static char *listen_on = "/var/run/bouncer.sock";
90 static uns max_failures = ~0U;
91 static uns max_suspect_time = 86400;
92 static uns max_banned_time = 86400;
93 static uns max_suspects = ~0U;
94 static uns max_banned = ~0U;
96 static char *ipv4_set;
97 static char *ipv6_set;
98 static char *config_log_stream;
100 static struct cf_section bouncer_cf = {
102 CF_STRING("ListenOn", &listen_on),
103 CF_UNS("MaxSuspects", &max_suspects),
104 CF_UNS("MaxBanned", &max_banned),
105 CF_UNS("MaxSuspectTime", &max_suspect_time),
106 CF_UNS("MaxBannedTime", &max_banned_time),
107 CF_UNS("MaxFailures", &max_failures),
108 CF_UNS("Probation", &probation),
109 CF_STRING("IPv4Set", &ipv4_set),
110 CF_STRING("IPv6Set", &ipv6_set),
111 CF_STRING("LogStream", &config_log_stream),
116 /*** An interface to IP sets ***/
118 static struct ipset_session *is_sess;
120 static const char *trim_eol(const char *msg)
122 int len = strlen(msg);
123 if (!len || msg[len-1] != '\n')
127 char *x = xstrdup(msg);
133 static void is_die(const char *when)
135 const char *warn = ipset_session_warning(is_sess);
137 msg(L_WARN, "%s: %s", when, trim_eol(warn));
139 const char *err = ipset_session_error(is_sess);
140 die("%s: %s", when, err ? trim_eol(err) : "Unknown error");
143 static void is_err(const char *when)
145 const char *warn = ipset_session_warning(is_sess);
147 msg(L_WARN, "%s: %s", when, trim_eol(warn));
149 const char *err = ipset_session_error(is_sess);
150 msg(L_ERROR, "%s: %s", when, err ? trim_eol(err) : "Unknown error");
152 ipset_session_report_reset(is_sess);
155 static void is_init(void)
159 is_sess = ipset_session_init(printf);
161 die("Unable to initialize ipset session");
164 static bool is_setup(char *set)
169 if (ipset_parse_setname(is_sess, IPSET_SETNAME, set) < 0)
170 is_die("ipset_parse_setname");
174 static void is_flush(char *set)
179 if (ipset_cmd(is_sess, IPSET_CMD_FLUSH, 0) < 0)
180 return is_err("IPSET_CMD_FLUSH");
183 static bool is_modify(bool add, struct addr addr)
185 int cmd = add ? IPSET_CMD_ADD : IPSET_CMD_DEL;
186 char *set = addr_is_v4(addr) ? ipv4_set : ipv6_set;
190 if (ipset_envopt_parse(is_sess, IPSET_ENV_EXIST, NULL) < 0)
191 is_die("IPSET_ENV_EXIST");
193 const struct ipset_type *is_type = ipset_type_get(is_sess, cmd);
195 is_die("ipset_type_get");
197 if (is_type->dimension != 1)
198 die("Invalid ipset dimension %d", is_type->dimension);
200 char buf[ADDR_BUFSIZE];
201 addr_format(buf, addr);
202 if (ipset_parse_elem(is_sess, 0, buf) < 0)
204 is_err("ipset_parse_elem");
208 if (ipset_cmd(is_sess, cmd, 0) < 0)
210 is_err(add ? "IPSET_CMD_ADD" : "IPSET_CMD_DEL");
217 /*** Handling of login failures ***/
219 struct culprit_node {
220 cnode n; // In either suspect_list or banned_list
227 timestamp_t last_fail; // Not updated when banned
230 #define HASH_NODE struct culprit_node
231 #define HASH_PREFIX(x) culprit_##x
232 #define HASH_KEY_MEMORY addr_bytes
233 #define HASH_KEY_SIZE 16
234 #define HASH_WANT_LOOKUP
235 #define HASH_WANT_REMOVE
236 #define HASH_USE_AUTO_ELTPOOL 1000
237 #define HASH_ZERO_FILL
238 #define HASH_LOOKUP_DETECT_NEW
239 #include <ucw/hashtable.h>
241 static clist suspect_list, banned_list;
242 static uns num_suspects, num_banned;
243 static struct main_timer cleanup_timer;
245 static void cleanup_list(clist *list, uns *counter, timestamp_t max_time, uns max_count, timestamp_t *next)
247 timestamp_t now = main_get_now();
251 struct culprit_node *c = clist_head(list);
255 timestamp_t expire_in = c->last_fail + max_time;
256 if (*counter > max_count)
258 static timestamp_t last_overflow_warning;
259 if (last_overflow_warning + 60000 < now)
261 last_overflow_warning = now;
263 msg(L_WARN, "Too many bans, dropping some. Try increasing MaxBanned.");
265 msg(L_WARN, "Too many suspects, dropping some. Try increasing MaxSuspects.");
272 *next = MIN(*next, expire_in);
281 msg(L_INFO, "Unbanning %s", AFMT(c->addr));
282 is_modify(0, c->addr);
287 c->fail_count = max_failures - probation;
288 clist_add_tail(&suspect_list, &c->n);
290 msg(L_DEBUG, "Suspect %s: probation, failures=%u", AFMT(c->addr), c->fail_count);
297 msg(L_DEBUG, "Suspect %s: acquitted", AFMT(c->addr));
303 static void culprit_cleanup(void)
305 timestamp_t next_cleanup = main_get_now() + (timestamp_t)3600 * 1000;
306 cleanup_list(&banned_list, &num_banned, (timestamp_t)max_banned_time * 1000, max_banned, &next_cleanup);
307 cleanup_list(&suspect_list, &num_suspects, (timestamp_t)max_suspect_time * 1000, max_suspects, &next_cleanup);
308 timer_add(&cleanup_timer, next_cleanup);
311 static void handle_failed_login(struct addr addr, int cnt)
314 timestamp_t now = main_get_now();
316 struct culprit_node *c = culprit_lookup((byte *) &addr, &is_new);
322 clist_add_tail(&suspect_list, &c->n);
324 msg(L_DEBUG, "Suspect %s: new, failures=%u", AFMT(addr), c->fail_count);
329 c->fail_count += cnt;
331 clist_add_tail(&suspect_list, &c->n);
332 msg(L_DEBUG, "Suspect %s: failures=%u", AFMT(addr), c->fail_count);
335 if (!c->banned && c->fail_count >= max_failures)
337 msg(L_INFO, "Banning %s: failures=%u", AFMT(addr), c->fail_count);
341 clist_add_tail(&banned_list, &c->n);
343 is_modify(1, c->addr);
349 static void culprit_timer(struct main_timer *tm UNUSED)
354 static void fail_init(void)
357 clist_init(&suspect_list);
358 clist_init(&banned_list);
359 cleanup_timer.handler = culprit_timer;
362 /*** Parsing of log messages ***/
364 static bool check_next(char **pp, char *want)
376 static void parse_failure(char *p, int cnt)
378 DBG("Parse 4: <%s> cnt=%d", p, cnt);
391 while (*p && *p != ' ' && *p != '=')
398 while (*p && *p != ' ')
405 DBG("Parse KV: %s=<%s>", key, val);
406 if (!strcmp(key, "rhost"))
410 // Act on the message
412 if (addr_parse(&addr, rhost))
413 handle_failed_login(addr, cnt);
415 msg(L_WARN, "Unable to parse address %s", rhost);
418 static void process_msg(char *line)
420 DBG("Parse: <%s>", line);
424 // 2016-11-04T17:18:54.825821+01:00 sshd[6733]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=1.2.3.4
425 // 2016-11-05T12:49:52.418880+01:00 sshd[16271]: PAM 2 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=116.31.116.26 user=root
427 // We shall start with 32 non-spaces
428 for (int i=0; i<32; i++)
434 DBG("Parse 1: <%s>", p);
436 // Space, something, colon, space
439 while (*p && *p != ' ' && *p != ':')
441 if (!check_next(&p, ": "))
443 DBG("Parse 2: <%s>", p);
445 // pam_unix(something), colon, space
446 if (check_next(&p, "pam_unix("))
455 if (!check_next(&p, ": "))
457 DBG("Parse 3: <%s>", p);
459 if (!check_next(&p, "authentication failure; "))
465 // "PAM <n> more authentication failures;"
466 if (check_next(&p, "PAM "))
468 if (!(*p >= '0' && *p <= '9'))
471 while (*p >= '0' && *p <= '9')
474 if (!check_next(&p, " more authentication failures; "))
477 parse_failure(p, cnt);
481 /*** Socket for receiving messages from rsyslog ***/
483 struct main_file sk_file;
485 static int sk_read(struct main_file *mf)
488 int len = recv(mf->fd, line, sizeof(line), MSG_TRUNC);
491 if (errno == EINTR || errno == EAGAIN)
496 if (len >= (int) sizeof(line))
498 msg(L_WARN, "Truncated message received (length=%d)", len);
499 len = sizeof(line) - 1;
503 if (len > 0 && line[len-1] == '\n')
505 if (len > 0 && line[len-1] == '\r')
512 static void sk_init(void)
515 mode_t old_umask = umask(0077);
518 if ((fd = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0)
519 die("Cannot create PF_UNIX socket: %m");
521 struct sockaddr_un sa = { .sun_family = AF_UNIX };
522 strcpy(sa.sun_path, listen_on);
523 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0)
524 die("Cannot bind socket %s: %m", listen_on);
527 sk_file.read_handler = sk_read;
535 static struct opt_section options = {
537 OPT_HELP("Bouncer -- A Daemon for Turning Away Mischievous Guests"),
539 OPT_HELP("Options:"),
546 int main(int argc UNUSED, char **argv)
548 cf_def_file = "/etc/bouncer";
549 cf_declare_section("Bouncer", &bouncer_cf, 0);
550 opt_parse(&options, argv+1);
552 if (config_log_stream)
553 log_configured(config_log_stream);
563 msg(L_INFO, "Starting");