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
14 #include <ucw/clists.h>
16 #include <ucw/mainloop.h>
18 #include <ucw/string.h>
21 #include <arpa/inet.h>
24 #include <sys/socket.h>
29 #include <libipset/data.h>
30 #include <libipset/session.h>
31 #include <libipset/types.h>
33 /*** Internal representation of IPv4/IPv6 addresses ***/
35 // In network byte order, IPv4 represented as ::ffff:1.2.3.4
40 #define ADDR_BUFSIZE 64
41 #define AFMT(_a) ({ char *_buf = alloca(ADDR_BUFSIZE); addr_format(_buf, _a); _buf; })
43 static bool addr_is_v4(struct addr addr)
45 return !addr.a[0] && !addr.a[1] && addr.a[2] == htonl(0xffff);
48 static void addr_format(char *buf, struct addr addr)
54 in4.s_addr = addr.a[3];
55 ok = inet_ntop(AF_INET, &in4, buf, ADDR_BUFSIZE);
60 memcpy(&in6, &addr, sizeof(addr));
61 ok = inet_ntop(AF_INET6, &in6, buf, ADDR_BUFSIZE);
64 snprintf(buf, ADDR_BUFSIZE, "<error %d>", errno);
67 static bool addr_parse(struct addr *addr, const char *src)
72 if (inet_pton(AF_INET, src, &a4))
74 addr->a[0] = addr->a[1] = 0;
75 addr->a[2] = htonl(0xffff);
76 addr->a[3] = a4.s_addr;
79 else if (inet_pton(AF_INET6, src, &a6))
81 memcpy(&addr, &a6, 16);
88 /*** Configuration ***/
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;
101 * - PAM module name(s) to match
104 static struct cf_section bouncer_cf = {
106 CF_UNS("MaxSuspects", &max_suspects),
107 CF_UNS("MaxBanned", &max_banned),
108 CF_UNS("MaxSuspectTime", &max_suspect_time),
109 CF_UNS("MaxBannedTime", &max_banned_time),
110 CF_UNS("MaxFailures", &max_failures),
115 /*** An interface to IP sets ***/
117 static struct ipset_session *is_sess;
124 static const char * const is_names[] = {
129 static const char *trim_eol(const char *msg)
131 int len = strlen(msg);
132 if (!len || msg[len-1] != '\n')
136 char *x = xstrdup(msg);
142 static void is_die(const char *when)
144 const char *warn = ipset_session_warning(is_sess);
146 msg(L_WARN, "%s: %s", when, trim_eol(warn));
148 const char *err = ipset_session_error(is_sess);
149 die("%s: %s", when, err ? trim_eol(err) : "Unknown error");
152 static void is_err(const char *when)
154 const char *warn = ipset_session_warning(is_sess);
156 msg(L_WARN, "%s: %s", when, trim_eol(warn));
158 const char *err = ipset_session_error(is_sess);
159 msg(L_ERROR, "%s: %s", when, err ? trim_eol(err) : "Unknown error");
161 ipset_session_report_reset(is_sess);
164 static void is_init(void)
168 is_sess = ipset_session_init(printf);
170 die("Unable to initialize ipset session");
173 static void is_setup(int set)
175 if (ipset_parse_setname(is_sess, IPSET_SETNAME, is_names[set]) < 0)
176 is_die("ipset_parse_setname");
179 static void is_flush(int set)
183 if (ipset_cmd(is_sess, IPSET_CMD_FLUSH, 0) < 0)
184 return is_err("IPSET_CMD_FLUSH");
187 static void is_modify(bool add, struct addr addr)
189 is_setup(addr_is_v4(addr) ? IS_IPV4 : IS_IPV6);
190 int cmd = add ? IPSET_CMD_ADD : IPSET_CMD_DEL;
192 if (ipset_envopt_parse(is_sess, IPSET_ENV_EXIST, NULL) < 0)
193 is_die("IPSET_ENV_EXIST");
195 const struct ipset_type *is_type = ipset_type_get(is_sess, cmd);
197 is_die("ipset_type_get");
199 if (is_type->dimension != 1)
200 die("Invalid ipset dimension %d", is_type->dimension);
202 char buf[ADDR_BUFSIZE];
203 addr_format(buf, addr);
204 if (ipset_parse_elem(is_sess, 0, buf) < 0)
205 return is_err("ipset_parse_elem");
207 if (ipset_cmd(is_sess, cmd, 0) < 0)
208 return is_err(add ? "IPSET_CMD_ADD" : "IPSET_CMD_DEL");
211 /*** Handling of login failures ***/
213 struct culprit_node {
214 cnode n; // In either suspect_list or banned_list
221 timestamp_t last_fail; // Not updated when banned
224 #define HASH_NODE struct culprit_node
225 #define HASH_PREFIX(x) culprit_##x
226 #define HASH_KEY_MEMORY addr_bytes
227 #define HASH_KEY_SIZE 16
228 #define HASH_WANT_LOOKUP
229 #define HASH_WANT_REMOVE
230 #define HASH_USE_AUTO_ELTPOOL 1000
231 #define HASH_ZERO_FILL
232 #define HASH_LOOKUP_DETECT_NEW
233 #include <ucw/hashtable.h>
235 static clist suspect_list, banned_list;
236 static uns num_suspects, num_banned;
237 static struct main_timer cleanup_timer;
239 static void cleanup_list(clist *list, uns *counter, timestamp_t max_time, uns max_count, timestamp_t *next)
241 timestamp_t now = main_get_now();
245 struct culprit_node *c = clist_head(list);
249 timestamp_t expire_in = c->last_fail + max_time - now;
250 if (*counter > max_count)
252 // FIXME: Warn with rate limit
258 *next = MIN(*next, expire_in);
264 DBG("%s: unbanned", AFMT(c->addr));
265 is_modify(0, c->addr);
269 DBG("%s: removed from LRU", AFMT(c->addr));
278 static void culprit_cleanup(void)
280 timestamp_t next_cleanup = main_get_now() + (timestamp_t)3600 * 1000;
281 cleanup_list(&suspect_list, &num_suspects, (timestamp_t)max_suspect_time * 1000, max_suspects, &next_cleanup);
282 cleanup_list(&banned_list, &num_banned, (timestamp_t)max_banned_time * 1000, max_banned, &next_cleanup);
283 timer_add(&cleanup_timer, next_cleanup);
286 static void handle_failed_login(struct addr addr)
289 timestamp_t now = main_get_now();
291 struct culprit_node *c = culprit_lookup((byte *) &addr, &is_new);
297 clist_add_tail(&suspect_list, &c->n);
299 DBG("%s: first fail", AFMT(addr));
306 clist_add_tail(&suspect_list, &c->n);
307 DBG("%s: next fail, cnt=%u", AFMT(addr), c->fail_count);
310 if (!c->banned && c->fail_count >= max_failures)
312 DBG("%s: banned", AFMT(addr));
316 clist_add_tail(&banned_list, &c->n);
318 is_modify(1, c->addr);
324 static void culprit_timer(struct main_timer *tm UNUSED)
329 static void fail_init(void)
332 clist_init(&suspect_list);
333 clist_init(&banned_list);
334 cleanup_timer.handler = culprit_timer;
337 /*** Parsing of log messages ***/
339 static bool check_next(char **pp, char *want)
351 static void process_msg(char *line)
353 DBG("Parse: <%s>", line);
357 // 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
359 // We shall start with 32 non-spaces
360 for (int i=0; i<32; i++)
366 DBG("Parse 1: <%s>", p);
368 // Space, something, colon, space
371 while (*p && *p != ' ' && *p != ':')
373 if (!check_next(&p, ": "))
375 DBG("Parse 2: <%s>", p);
377 // pam_unix(something), colon, space (FIXME: make configurable)
378 if (!check_next(&p, "pam_unix("))
387 if (!check_next(&p, ": "))
389 DBG("Parse 3: <%s>", p);
391 // "authentication failure;"
392 if (!check_next(&p, "authentication failure; "))
394 DBG("Parse 4: <%s>", p);
407 while (*p && *p != ' ' && *p != '=')
414 while (*p && *p != ' ')
421 DBG("Parse KV: %s=<%s>", key, val);
422 if (!strcmp(key, "rhost"))
426 // Act on the message
428 if (addr_parse(&addr, rhost))
429 handle_failed_login(addr);
431 msg(L_WARN, "Unable to parse address %s", rhost);
434 /*** Socket for receiving messages from rsyslog ***/
436 static const char sk_name[] = "/var/run/bouncer.sock";
437 struct main_file sk_file;
439 static int sk_read(struct main_file *mf)
442 int len = recv(mf->fd, line, sizeof(line), MSG_TRUNC);
445 if (errno == EINTR || errno == EAGAIN)
450 if (len >= (int) sizeof(line))
452 msg(L_WARN, "Truncated message received (length=%d)", len);
453 len = sizeof(line) - 1;
457 if (len > 0 && line[len-1] == '\n')
459 if (len > 0 && line[len-1] == '\r')
466 static void sk_init(void)
471 if ((fd = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0)
472 die("Cannot create PF_UNIX socket: %m");
474 struct sockaddr_un sa = { .sun_family = AF_UNIX };
475 strcpy(sa.sun_path, sk_name);
476 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0)
477 die("Cannot bind socket %s: %m", sk_name);
479 // FIXME: Permissions
482 sk_file.read_handler = sk_read;
488 static struct opt_section options = {
490 OPT_HELP("Bouncer -- A Daemon for Turning Away Mischievous Guests"),
492 OPT_HELP("Options:"),
499 int main(int argc UNUSED, char **argv)
501 cf_def_file = "config"; // FIXME
502 cf_declare_section("Bouncer", &bouncer_cf, 0);
503 opt_parse(&options, argv+1);
509 // FIXME msg(L_INFO, "Clearing previous state");