2 * Bouncer -- A Daemon for Turning Away Mischievous Guests
4 * (c) 2016 Martin Mares <mj@ucw.cz>
6 * FIXME: ipset create bouncer4 hash:ip family inet
7 * FIXME: ipset create bouncer6 hash:ip family inet6
8 * FIXME: sshd_config: UseDNS no
9 * FIXME: PAM module names should be made configurable
10 * FIXME: Parse "N more failures" messages
16 #include <ucw/clists.h>
19 #include <ucw/mainloop.h>
21 #include <ucw/string.h>
24 #include <arpa/inet.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
34 #include <libipset/data.h>
35 #include <libipset/session.h>
36 #include <libipset/types.h>
38 /*** Internal representation of IPv4/IPv6 addresses ***/
40 // In network byte order, IPv4 represented as ::ffff:1.2.3.4
45 #define ADDR_BUFSIZE 64
46 #define AFMT(_a) ({ char *_buf = alloca(ADDR_BUFSIZE); addr_format(_buf, _a); _buf; })
48 static bool addr_is_v4(struct addr addr)
50 return !addr.a[0] && !addr.a[1] && addr.a[2] == htonl(0xffff);
53 static void addr_format(char *buf, struct addr addr)
59 in4.s_addr = addr.a[3];
60 ok = inet_ntop(AF_INET, &in4, buf, ADDR_BUFSIZE);
65 memcpy(&in6, &addr, sizeof(addr));
66 ok = inet_ntop(AF_INET6, &in6, buf, ADDR_BUFSIZE);
69 snprintf(buf, ADDR_BUFSIZE, "<error %d>", errno);
72 static bool addr_parse(struct addr *addr, const char *src)
77 if (inet_pton(AF_INET, src, &a4))
79 addr->a[0] = addr->a[1] = 0;
80 addr->a[2] = htonl(0xffff);
81 addr->a[3] = a4.s_addr;
84 else if (inet_pton(AF_INET6, src, &a6))
86 memcpy(&addr, &a6, 16);
93 /*** Configuration ***/
95 static char *listen_on = "/var/run/bouncer.sock";
96 static uns max_failures = ~0U;
97 static uns max_suspect_time = 86400;
98 static uns max_banned_time = 86400;
99 static uns max_suspects = ~0U;
100 static uns max_banned = ~0U;
101 static char *ipv4_set;
102 static char *ipv6_set;
103 static char *config_log_stream;
105 static struct cf_section bouncer_cf = {
107 CF_STRING("ListenOn", &listen_on),
108 CF_UNS("MaxSuspects", &max_suspects),
109 CF_UNS("MaxBanned", &max_banned),
110 CF_UNS("MaxSuspectTime", &max_suspect_time),
111 CF_UNS("MaxBannedTime", &max_banned_time),
112 CF_UNS("MaxFailures", &max_failures),
113 CF_STRING("IPv4Set", &ipv4_set),
114 CF_STRING("IPv6Set", &ipv6_set),
115 CF_STRING("LogStream", &config_log_stream),
120 /*** An interface to IP sets ***/
122 static struct ipset_session *is_sess;
124 static const char *trim_eol(const char *msg)
126 int len = strlen(msg);
127 if (!len || msg[len-1] != '\n')
131 char *x = xstrdup(msg);
137 static void is_die(const char *when)
139 const char *warn = ipset_session_warning(is_sess);
141 msg(L_WARN, "%s: %s", when, trim_eol(warn));
143 const char *err = ipset_session_error(is_sess);
144 die("%s: %s", when, err ? trim_eol(err) : "Unknown error");
147 static void is_err(const char *when)
149 const char *warn = ipset_session_warning(is_sess);
151 msg(L_WARN, "%s: %s", when, trim_eol(warn));
153 const char *err = ipset_session_error(is_sess);
154 msg(L_ERROR, "%s: %s", when, err ? trim_eol(err) : "Unknown error");
156 ipset_session_report_reset(is_sess);
159 static void is_init(void)
163 is_sess = ipset_session_init(printf);
165 die("Unable to initialize ipset session");
168 static bool is_setup(char *set)
173 if (ipset_parse_setname(is_sess, IPSET_SETNAME, set) < 0)
174 is_die("ipset_parse_setname");
178 static void is_flush(char *set)
183 if (ipset_cmd(is_sess, IPSET_CMD_FLUSH, 0) < 0)
184 return is_err("IPSET_CMD_FLUSH");
187 static bool is_modify(bool add, struct addr addr)
189 int cmd = add ? IPSET_CMD_ADD : IPSET_CMD_DEL;
190 char *set = addr_is_v4(addr) ? ipv4_set : ipv6_set;
194 if (ipset_envopt_parse(is_sess, IPSET_ENV_EXIST, NULL) < 0)
195 is_die("IPSET_ENV_EXIST");
197 const struct ipset_type *is_type = ipset_type_get(is_sess, cmd);
199 is_die("ipset_type_get");
201 if (is_type->dimension != 1)
202 die("Invalid ipset dimension %d", is_type->dimension);
204 char buf[ADDR_BUFSIZE];
205 addr_format(buf, addr);
206 if (ipset_parse_elem(is_sess, 0, buf) < 0)
208 is_err("ipset_parse_elem");
212 if (ipset_cmd(is_sess, cmd, 0) < 0)
214 is_err(add ? "IPSET_CMD_ADD" : "IPSET_CMD_DEL");
221 /*** Handling of login failures ***/
223 struct culprit_node {
224 cnode n; // In either suspect_list or banned_list
231 timestamp_t last_fail; // Not updated when banned
234 #define HASH_NODE struct culprit_node
235 #define HASH_PREFIX(x) culprit_##x
236 #define HASH_KEY_MEMORY addr_bytes
237 #define HASH_KEY_SIZE 16
238 #define HASH_WANT_LOOKUP
239 #define HASH_WANT_REMOVE
240 #define HASH_USE_AUTO_ELTPOOL 1000
241 #define HASH_ZERO_FILL
242 #define HASH_LOOKUP_DETECT_NEW
243 #include <ucw/hashtable.h>
245 static clist suspect_list, banned_list;
246 static uns num_suspects, num_banned;
247 static struct main_timer cleanup_timer;
249 static void cleanup_list(clist *list, uns *counter, timestamp_t max_time, uns max_count, timestamp_t *next)
251 timestamp_t now = main_get_now();
255 struct culprit_node *c = clist_head(list);
259 timestamp_t expire_in = c->last_fail + max_time;
260 if (*counter > max_count)
262 static timestamp_t last_overflow_warning;
263 if (last_overflow_warning + 60000 < now)
265 last_overflow_warning = now;
267 msg(L_WARN, "Too many bans, dropping some. Try increasing MaxBanned.");
269 msg(L_WARN, "Too many suspects, dropping some. Try increasing MaxSuspects.");
276 *next = MIN(*next, expire_in);
282 msg(L_INFO, "Unbanning %s", AFMT(c->addr));
283 is_modify(0, c->addr);
286 msg(L_DEBUG, "Suspect %s: acquitted", AFMT(c->addr));
294 static void culprit_cleanup(void)
296 timestamp_t next_cleanup = main_get_now() + (timestamp_t)3600 * 1000;
297 cleanup_list(&suspect_list, &num_suspects, (timestamp_t)max_suspect_time * 1000, max_suspects, &next_cleanup);
298 cleanup_list(&banned_list, &num_banned, (timestamp_t)max_banned_time * 1000, max_banned, &next_cleanup);
299 timer_add(&cleanup_timer, next_cleanup);
302 static void handle_failed_login(struct addr addr)
305 timestamp_t now = main_get_now();
307 struct culprit_node *c = culprit_lookup((byte *) &addr, &is_new);
313 clist_add_tail(&suspect_list, &c->n);
315 msg(L_DEBUG, "Suspect %s: new", AFMT(addr));
322 clist_add_tail(&suspect_list, &c->n);
323 msg(L_DEBUG, "Suspect %s: failures=%u", AFMT(addr), c->fail_count);
326 if (!c->banned && c->fail_count >= max_failures)
328 msg(L_INFO, "Banning %s: failures=%u", AFMT(addr), c->fail_count);
332 clist_add_tail(&banned_list, &c->n);
334 is_modify(1, c->addr);
340 static void culprit_timer(struct main_timer *tm UNUSED)
345 static void fail_init(void)
348 clist_init(&suspect_list);
349 clist_init(&banned_list);
350 cleanup_timer.handler = culprit_timer;
353 /*** Parsing of log messages ***/
355 static bool check_next(char **pp, char *want)
367 static void process_msg(char *line)
369 DBG("Parse: <%s>", line);
373 // 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
375 // We shall start with 32 non-spaces
376 for (int i=0; i<32; i++)
382 DBG("Parse 1: <%s>", p);
384 // Space, something, colon, space
387 while (*p && *p != ' ' && *p != ':')
389 if (!check_next(&p, ": "))
391 DBG("Parse 2: <%s>", p);
393 // pam_unix(something), colon, space
394 if (!check_next(&p, "pam_unix("))
403 if (!check_next(&p, ": "))
405 DBG("Parse 3: <%s>", p);
407 // "authentication failure;"
408 if (!check_next(&p, "authentication failure; "))
410 DBG("Parse 4: <%s>", p);
423 while (*p && *p != ' ' && *p != '=')
430 while (*p && *p != ' ')
437 DBG("Parse KV: %s=<%s>", key, val);
438 if (!strcmp(key, "rhost"))
442 // Act on the message
444 if (addr_parse(&addr, rhost))
445 handle_failed_login(addr);
447 msg(L_WARN, "Unable to parse address %s", rhost);
450 /*** Socket for receiving messages from rsyslog ***/
452 struct main_file sk_file;
454 static int sk_read(struct main_file *mf)
457 int len = recv(mf->fd, line, sizeof(line), MSG_TRUNC);
460 if (errno == EINTR || errno == EAGAIN)
465 if (len >= (int) sizeof(line))
467 msg(L_WARN, "Truncated message received (length=%d)", len);
468 len = sizeof(line) - 1;
472 if (len > 0 && line[len-1] == '\n')
474 if (len > 0 && line[len-1] == '\r')
481 static void sk_init(void)
484 mode_t old_umask = umask(0077);
487 if ((fd = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0)
488 die("Cannot create PF_UNIX socket: %m");
490 struct sockaddr_un sa = { .sun_family = AF_UNIX };
491 strcpy(sa.sun_path, listen_on);
492 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0)
493 die("Cannot bind socket %s: %m", listen_on);
496 sk_file.read_handler = sk_read;
504 static struct opt_section options = {
506 OPT_HELP("Bouncer -- A Daemon for Turning Away Mischievous Guests"),
508 OPT_HELP("Options:"),
515 int main(int argc UNUSED, char **argv)
517 cf_def_file = "config"; // FIXME
518 cf_declare_section("Bouncer", &bouncer_cf, 0);
519 opt_parse(&options, argv+1);
521 if (config_log_stream)
522 log_configured(config_log_stream);
532 msg(L_INFO, "Starting");