1 /* mod-sockcheck.c - insecure proxy checking
2 * Copyright 2000-2006 srvx Development Team
4 * This file is part of srvx.
6 * srvx is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with srvx; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
27 #ifdef HAVE_SYS_SOCKET_H
28 #include <sys/socket.h>
30 #ifdef HAVE_NETINET_IN_H
31 #include <netinet/in.h>
33 #ifdef HAVE_ARPA_INET_H
34 #include <arpa/inet.h>
37 /* TODO, 1.3 or later: allow rules like "27374:" "reject:Subseven detected";
38 * (For convenience; right now it assumes that there will be a state
39 * rather than an immediate response upon connection.)
42 #if !defined(SOCKCHECK_DEBUG)
43 #define SOCKCHECK_DEBUG 0
45 #define SOCKCHECK_TEST_DB "sockcheck.conf"
47 enum sockcheck_decision {
57 enum sockcheck_decision decision;
58 char hostname[IRC_NTOP_MAX_SIZE]; /* acts as key for checked_ip_dict */
59 } *sockcheck_cache_info;
61 DECLARE_LIST(sci_list, sockcheck_cache_info);
62 DEFINE_LIST(sci_list, sockcheck_cache_info)
64 /* Here's the list of hosts that need to be started on.
66 static struct sci_list pending_sci_list;
68 /* Map of previously checked IPs state (if we've accepted the address yet).
69 * The data for each entry is a pointer to a sockcheck_cache_info.
71 static dict_t checked_ip_dict;
73 /* Each sockcheck template is formed as a Mealy state machine (that is,
74 * the output on a state transition is a function of both the current
75 * state and the input). Mealy state machines require fewer states to
76 * match the same input than Moore machines (where the output is only
77 * a function of the current state).
79 * A state is characterized by sending some data (possibly nothing),
80 * waiting a certain amount of time to receive one of zero or more
81 * responses, and a decision (accept, reject, continue to another
82 * state) based on the received response.
85 struct sockcheck_response {
87 struct sockcheck_state *next;
90 DECLARE_LIST(response_list, struct sockcheck_response *);
91 DEFINE_LIST(response_list, struct sockcheck_response *)
92 static unsigned int max_responses;
94 struct sockcheck_state {
96 unsigned short timeout;
98 enum sockcheck_decision type;
100 struct response_list responses;
103 struct sockcheck_list {
104 unsigned int size, used, refs;
105 struct sockcheck_state **list;
111 static struct sockcheck_list *tests;
113 /* Stuff to track client state, one instance per open connection. */
114 struct sockcheck_client {
116 struct sockcheck_list *tests;
117 sockcheck_cache_info addr;
118 unsigned int client_index;
119 unsigned int test_index;
120 unsigned short test_rep;
121 struct sockcheck_state *state;
122 unsigned int read_size, read_used, read_pos;
124 const char **resp_state;
128 unsigned int max_clients;
129 unsigned int max_read;
130 unsigned int gline_duration;
131 unsigned int max_cache_age;
132 struct sockaddr *local_addr;
136 static unsigned int sockcheck_num_clients;
137 static struct sockcheck_client **client_list;
138 static unsigned int proxies_detected, checked_ip_count;
139 static struct module *sockcheck_module;
140 static struct log_type *PC_LOG;
141 const char *sockcheck_module_deps[] = { NULL };
143 static const struct message_entry msgtab[] = {
144 { "PCMSG_PROXY_DEFINITION_FAILED", "Proxy definition failed: %s" },
145 { "PCMSG_PROXY_DEFINITION_SUCCEEDED", "New proxy type defined." },
146 { "PCMSG_UNSCANNABLE_IP", "%s has a spoofed, hidden or localnet IP." },
147 { "PCMSG_ADDRESS_QUEUED", "$b%s$b is now queued to be proxy-checked." },
148 { "PCMSG_ADDRESS_UNRESOLVED", "Unable to resolve $b%s$b to an IP address." },
149 { "PCMSG_CHECKING_ADDRESS", "$b%s$b is currently being checked; unable to clear it." },
150 { "PCMSG_NOT_REMOVED_FROM_CACHE", "$b%s$b was not cached and therefore was not cleared." },
151 { "PCMSG_REMOVED_FROM_CACHE", "$b%s$b was cleared from the cached hosts list." },
152 { "PCMSG_DISABLED", "Proxy scanning is $bdisabled$b." },
153 { "PCMSG_NOT_CACHED", "No proxycheck records exist for IP %s." },
154 { "PCMSG_STATUS_CHECKING", "IP %s proxycheck state: last touched %s ago, still checking" },
155 { "PCMSG_STATUS_ACCEPTED", "IP %s proxycheck state: last touched %s ago, accepted" },
156 { "PCMSG_STATUS_REJECTED", "IP %s proxycheck state: last touched %s ago, rejected: %s" },
157 { "PCMSG_STATUS_UNKNOWN", "IP %s proxycheck state: last touched %s ago, invalid status" },
158 { "PCMSG_STATISTICS", "Since booting, I have checked %d clients for illicit proxies, and detected %d proxy hosts.\nI am currently checking %d clients (out of %d max) and have a backlog of %d more to start on.\nI currently have %d hosts cached.\nI know how to detect %d kinds of proxies." },
162 static struct sockcheck_list *
163 sockcheck_list_alloc(unsigned int size)
165 struct sockcheck_list *list = malloc(sizeof(*list));
169 list->list = malloc(list->size*sizeof(list->list[0]));
174 sockcheck_list_append(struct sockcheck_list *list, struct sockcheck_state *new_item)
176 if (list->used == list->size) {
178 list->list = realloc(list->list, list->size*sizeof(list->list[0]));
180 list->list[list->used++] = new_item;
183 static struct sockcheck_list *
184 sockcheck_list_clone(struct sockcheck_list *old_list)
186 struct sockcheck_list *new_list = malloc(sizeof(*new_list));
187 new_list->used = old_list->used;
189 new_list->size = old_list->size;
190 new_list->list = malloc(new_list->size*sizeof(new_list->list[0]));
191 memcpy(new_list->list, old_list->list, new_list->used*sizeof(new_list->list[0]));
196 sockcheck_list_unref(struct sockcheck_list *list)
198 if (!list || --list->refs > 0) return;
204 sockcheck_issue_gline(sockcheck_cache_info sci)
206 char addr[IRC_NTOP_MAX_SIZE + 2] = {'*', '@', '\0'};
207 irc_ntop(addr + 2, sizeof(addr) - 2, &sci->addr);
208 log_module(PC_LOG, LOG_INFO, "Issuing gline for client at %s: %s", addr + 2, sci->reason);
209 gline_add("ProxyCheck", addr, sockcheck_conf.gline_duration, sci->reason, now, now, 1);
212 static struct sockcheck_client *
213 sockcheck_alloc_client(sockcheck_cache_info sci)
215 struct sockcheck_client *client;
216 client = calloc(1, sizeof(*client));
217 client->tests = tests;
218 client->tests->refs++;
220 client->read_size = sockcheck_conf.max_read;
221 client->read = malloc(client->read_size);
222 client->resp_state = malloc(max_responses * sizeof(client->resp_state[0]));
227 sockcheck_free_client(struct sockcheck_client *client)
229 if (SOCKCHECK_DEBUG) {
230 log_module(PC_LOG, LOG_INFO, "Goodbye %s (%p)! I set you free!", client->addr->hostname, client);
233 ioset_close(client->fd, 1);
235 sockcheck_list_unref(client->tests);
237 free(client->resp_state);
241 static void sockcheck_start_client(unsigned int idx);
242 static void sockcheck_begin_test(struct sockcheck_client *client);
243 static void sockcheck_advance(struct sockcheck_client *client, unsigned int next_state);
246 sockcheck_timeout_client(void *data)
248 struct sockcheck_client *client = data;
249 if (SOCKCHECK_DEBUG) {
250 log_module(PC_LOG, LOG_INFO, "Client %s timed out.", client->addr->hostname);
253 sockcheck_advance(client, client->state->responses.used-1);
257 sockcheck_print_client(const struct sockcheck_client *client)
259 static const char *decs[] = {"CHECKING", "ACCEPT", "REJECT"};
260 log_module(PC_LOG, LOG_INFO, "client %p: { addr = %p { decision = %s; last_touched = "FMT_TIME_T"; reason = %s; hostname = \"%s\" }; "
261 "test_index = %d; state = %p { port = %d; type = %s; template = \"%s\"; ... }; "
262 "fd = %p(%d); read = %p; read_size = %d; read_used = %d; read_pos = %d; }",
263 client, client->addr, decs[client->addr->decision], client->addr->last_touched,
264 client->addr->reason, client->addr->hostname,
265 client->test_index, client->state,
266 (client->state ? client->state->port : 0),
267 (client->state ? decs[client->state->type] : "N/A"),
268 (client->state ? client->state->template : "N/A"),
269 client->fd, (client->fd ? client->fd->fd : 0),
270 client->read, client->read_size, client->read_used, client->read_pos);
273 static char hexvals[256] = {
274 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 */
275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */
276 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */
277 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, /* 48 */
278 0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 */
279 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 */
280 0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 96 */
281 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* 112 */
285 expand_var(const struct sockcheck_client *client, char var, char **p_expansion, unsigned int *p_exp_length)
287 extern struct cManagerNode cManager;
288 const char *expansion;
289 unsigned int exp_length;
293 /* expand variable */
296 expansion = client->addr->hostname;
297 exp_length = strlen(expansion);
300 exp4 = client->addr->addr.in6_32[3];
301 exp_length = sizeof(exp4);
302 expansion = (char*)&exp4;
305 exp2 = htons(client->state->port);
306 exp_length = sizeof(exp2);
307 expansion = (char*)&exp2;
310 expansion = cManager.uplink->host;
311 exp_length = strlen(expansion);
314 log_module(PC_LOG, LOG_WARNING, "Request to expand unknown sockcheck variable $%c, using empty expansion.", var);
319 *p_expansion = malloc(exp_length);
320 memcpy(*p_expansion, expansion, exp_length);
323 *p_exp_length = exp_length;
328 sockcheck_check_template(const char *template, int is_input)
331 if (is_input && !strcmp(template, "other")) return 1;
332 for (nn=0; template[nn]; nn += 2) {
333 switch (template[nn]) {
335 if (!template[nn+1]) {
336 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s had = at end of template; needs a second character.", template);
341 switch (template[nn+1]) {
342 case 'c': case 'i': case 'p': case 'u': break;
344 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s refers to unknown variable %c (pos %d).", template, template[nn+1], nn);
350 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s: . is only valid in input templates.", template);
353 if (template[nn+1] != '.') {
354 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s expects .. to come in twos (pos %d).", template, nn);
358 case '0': case '1': case '2': case '3': case '4':
359 case '5': case '6': case '7': case '8': case '9':
360 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
361 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
362 if (!hexvals[(unsigned char)template[nn+1]] && (template[nn+1] != '0')) {
363 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s expects hex characters to come in twos (pos %d).", template, nn);
368 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s: unrecognized character '%c' (pos %d).", template, template[nn], nn);
376 sockcheck_elaborate_state(struct sockcheck_client *client)
378 const char *template;
381 for (template = client->state->template, nn = 0; template[nn]; nn += 2) {
382 switch (template[nn]) {
383 case '=': ioset_write(client->fd, template+nn+1, 1); break;
384 case '0': case '1': case '2': case '3': case '4':
385 case '5': case '6': case '7': case '8': case '9':
386 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
387 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': {
388 char ch = hexvals[(unsigned char)template[nn]] << 4
389 | hexvals[(unsigned char)template[nn+1]];
390 ioset_write(client->fd, &ch, 1);
395 unsigned int exp_length;
396 expand_var(client, template[nn+1], &expansion, &exp_length);
397 ioset_write(client->fd, expansion, exp_length);
403 for (nn=0; nn<client->state->responses.used; nn++) {
404 /* Set their resp_state to the start of the response. */
405 client->resp_state[nn] = client->state->responses.list[nn]->template;
406 /* If it doesn't require reading, take it now. */
407 if (client->resp_state[nn] && !*client->resp_state[nn]) {
408 if (SOCKCHECK_DEBUG) {
409 log_module(PC_LOG, LOG_INFO, "Skipping straight to easy option %d for %p.", nn, client);
411 sockcheck_advance(client, nn);
415 timeq_add(now + client->state->timeout, sockcheck_timeout_client, client);
416 if (SOCKCHECK_DEBUG) {
417 log_module(PC_LOG, LOG_INFO, "Elaborated state for %s:", client->addr->hostname);
418 sockcheck_print_client(client);
423 sockcheck_decide(struct sockcheck_client *client, enum sockcheck_decision decision)
428 client->addr->decision = decision;
429 client->addr->last_touched = now;
433 if (SOCKCHECK_DEBUG) {
434 log_module(PC_LOG, LOG_INFO, "Proxy check passed for client at %s.", client->addr->hostname);
438 client->addr->reason = client->state->template;
440 sockcheck_issue_gline(client->addr);
441 if (SOCKCHECK_DEBUG) {
442 log_module(PC_LOG, LOG_INFO, "Proxy check rejects client at %s (%s)", client->addr->hostname, client->addr->reason);
444 /* Don't compare test_index != 0 directly, because somebody
445 * else may have reordered the tests already. */
446 if (client->tests->list[client->test_index] != tests->list[0]) {
447 struct sockcheck_list *new_tests = sockcheck_list_clone(tests);
448 struct sockcheck_state *new_first = client->tests->list[client->test_index];
449 for (n=0; (n<tests->used) && (tests->list[n] != new_first); n++) ;
450 for (; n>0; n--) new_tests->list[n] = new_tests->list[n-1];
451 new_tests->list[0] = new_first;
452 sockcheck_list_unref(tests);
457 log_module(PC_LOG, LOG_ERROR, "BUG: sockcheck_decide(\"%s\", %d): unrecognized decision.", client->addr->hostname, decision);
459 n = client->client_index;
460 sockcheck_free_client(client);
461 if ((--sockcheck_num_clients < sockcheck_conf.max_clients)
462 && (pending_sci_list.used > 0)) {
463 sockcheck_start_client(n);
470 sockcheck_advance(struct sockcheck_client *client, unsigned int next_state)
472 struct sockcheck_state *ns;
475 timeq_del(0, sockcheck_timeout_client, client, TIMEQ_IGNORE_WHEN);
476 if (SOCKCHECK_DEBUG) {
479 static const char *hexmap = "0123456789ABCDEF";
480 log_module(PC_LOG, LOG_INFO, "sockcheck_advance(%s) following response %d (type %d) of %d.", client->addr->hostname, next_state, client->state->responses.list[next_state]->next->type, client->state->responses.used);
481 for (n=0; n<client->read_used; n++) {
482 for (m=0; (m<(sizeof(buffer)-1)>>1) && ((n+m) < client->read_used); m++) {
483 buffer[m << 1] = hexmap[client->read[n+m] >> 4];
484 buffer[m << 1 | 1] = hexmap[client->read[n+m] & 15];
487 log_module(PC_LOG, LOG_INFO, " .. read data: %s", buffer);
490 sockcheck_print_client(client);
493 ns = client->state = client->state->responses.list[next_state]->next;
496 sockcheck_elaborate_state(client);
499 sockcheck_decide(client, REJECT);
502 if (++client->test_rep < client->tests->list[client->test_index]->reps) {
503 sockcheck_begin_test(client);
504 } else if (++client->test_index < client->tests->used) {
505 client->test_rep = 0;
506 sockcheck_begin_test(client);
508 sockcheck_decide(client, ACCEPT);
512 log_module(PC_LOG, LOG_ERROR, "BUG: unknown next-state type %d (after %p).", ns->type, client->state);
518 sockcheck_readable(struct io_fd *fd)
520 /* read what we can from the fd */
521 struct sockcheck_client *client = fd->data;
526 res = read(fd->fd, client->read + client->read_used, client->read_size - client->read_used);
528 switch (res = errno) {
530 log_module(PC_LOG, LOG_ERROR, "BUG: sockcheck_readable(%d/%s): read() returned errno %d (%s)", fd->fd, client->addr->hostname, errno, strerror(errno));
534 sockcheck_advance(client, client->state->responses.used - 1);
537 } else if (res == 0) {
538 sockcheck_advance(client, client->state->responses.used - 1);
541 client->read_used += res;
543 if (SOCKCHECK_DEBUG) {
546 static const char *hexmap = "0123456789ABCDEF";
547 for (n=0; n<client->read_used; n++) {
548 for (m=0; (m<(sizeof(buffer)-1)>>1) && ((n+m) < client->read_used); m++) {
549 buffer[m << 1] = hexmap[client->read[n+m] >> 4];
550 buffer[m << 1 | 1] = hexmap[client->read[n+m] & 15];
553 log_module(PC_LOG, LOG_INFO, "read %d bytes data: %s", client->read_used, buffer);
558 /* See if what's been read matches any of the expected responses */
559 while (client->read_pos < client->read_used) {
560 unsigned int last_pos = client->read_pos;
562 const char *resp_state;
564 for (nn=0; nn<(client->state->responses.used-1); nn++) {
566 unsigned int exp_length = 1, free_exp = 0;
567 /* compare against possible target */
568 resp_state = client->resp_state[nn];
569 if (resp_state == NULL) continue;
570 switch (*resp_state) {
572 bleh = resp_state[1];
576 /* any character passes */
580 case '0': case '1': case '2': case '3': case '4':
581 case '5': case '6': case '7': case '8': case '9':
582 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
583 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
584 bleh = hexvals[(unsigned char)resp_state[0]] << 4
585 | hexvals[(unsigned char)resp_state[1]];
589 expand_var(client, resp_state[1], &expected, &exp_length);
593 if (client->read_pos+exp_length <= client->read_used) {
594 if (exp_length && memcmp(client->read+client->read_pos, expected, exp_length)) {
597 client->read_pos += exp_length;
600 /* can't check the variable yet, so come back later */
603 if (free_exp) free(expected);
605 client->resp_state[nn] = resp_state = resp_state + 2;
607 sockcheck_advance(client, nn);
611 client->resp_state[nn] = NULL;
614 if (last_pos == client->read_pos) break;
617 /* nothing seemed to match. what now? */
618 if (client->read_used >= client->read_size) {
619 /* we got more data than we expected to get .. don't read any more */
620 if (SOCKCHECK_DEBUG) {
621 log_module(PC_LOG, LOG_INFO, "Buffer filled (unmatched) for client %s", client->addr->hostname);
623 sockcheck_advance(client, client->state->responses.used-1);
629 sockcheck_connected(struct io_fd *fd, int rc)
631 struct sockcheck_client *client = fd->data;
636 log_module(PC_LOG, LOG_ERROR, "BUG: connect() got error %d (%s) for client at %s.", rc, strerror(rc), client->addr->hostname);
640 if (SOCKCHECK_DEBUG) {
641 log_module(PC_LOG, LOG_INFO, "Client %s gave us errno %d (%s)", client->addr->hostname, rc, strerror(rc));
643 sockcheck_advance(client, client->state->responses.used-1);
647 if (SOCKCHECK_DEBUG) {
648 log_module(PC_LOG, LOG_INFO, "Connected: to %s port %d.", client->addr->hostname, client->state->port);
650 sockcheck_elaborate_state(client);
654 sockcheck_begin_test(struct sockcheck_client *client)
659 ioset_close(client->fd, 1);
662 client->state = client->tests->list[client->test_index];
663 client->read_pos = 0;
664 client->read_used = 0;
665 io_fd = ioset_connect(sockcheck_conf.local_addr, sockcheck_conf.local_addr_len, client->addr->hostname, client->state->port, 0, client, sockcheck_connected);
668 client->test_index++;
671 io_fd->readable_cb = sockcheck_readable;
672 timeq_add(now + client->state->timeout, sockcheck_timeout_client, client);
673 if (SOCKCHECK_DEBUG) {
674 log_module(PC_LOG, LOG_INFO, "Starting proxy check on %s:%d (test %d) with fd %d (%p).", client->addr->hostname, client->state->port, client->test_index, io_fd->fd, io_fd);
677 } while (client->test_index < client->tests->used);
678 /* Ran out of tests to run; accept this client. */
679 sockcheck_decide(client, ACCEPT);
683 sockcheck_start_client(unsigned int idx)
685 sockcheck_cache_info sci;
686 struct sockcheck_client *client;
688 if (pending_sci_list.used == 0) return;
689 if (!(sci = pending_sci_list.list[0])) {
690 log_module(PC_LOG, LOG_ERROR, "BUG: sockcheck_start_client(%d) found null pointer in pending_sci_list.", idx);
693 memmove(pending_sci_list.list, pending_sci_list.list+1,
694 (--pending_sci_list.used)*sizeof(pending_sci_list.list[0]));
695 sockcheck_num_clients++;
697 client = client_list[idx] = sockcheck_alloc_client(sci);
698 log_module(PC_LOG, LOG_INFO, "Proxy-checking client at %s as client %d (%p) of %d.", sci->hostname, idx, client, sockcheck_num_clients);
699 client->test_rep = 0;
700 client->client_index = idx;
701 sockcheck_begin_test(client);
705 sockcheck_queue_address(irc_in_addr_t addr)
707 sockcheck_cache_info sci;
708 const char *ipstr = irc_ntoa(&addr);
710 sci = dict_find(checked_ip_dict, ipstr, NULL);
713 switch (sci->decision) {
715 /* We are already checking this host. */
718 if ((sci->last_touched + sockcheck_conf.max_cache_age) >= (unsigned)now) return;
721 if ((sci->last_touched + sockcheck_conf.gline_duration) >= (unsigned)now) {
722 sockcheck_issue_gline(sci);
727 dict_remove(checked_ip_dict, sci->hostname);
729 sci = calloc(1, sizeof(*sci));
730 sci->decision = CHECKING;
731 sci->last_touched = now;
734 strncpy(sci->hostname, ipstr, sizeof(sci->hostname));
735 dict_insert(checked_ip_dict, sci->hostname, sci);
736 sci_list_append(&pending_sci_list, sci);
737 if (sockcheck_num_clients < sockcheck_conf.max_clients)
738 sockcheck_start_client(sockcheck_num_clients);
742 sockcheck_uncache_host(const char *name)
744 sockcheck_cache_info sci;
745 if ((sci = dict_find(checked_ip_dict, name, NULL))
746 && (sci->decision == CHECKING)) {
749 return dict_remove(checked_ip_dict, name);
753 sockcheck_create_response(const char *key, void *data, void *extra)
755 const char *str, *end;
756 struct record_data *rd = data;
757 struct sockcheck_state *parent = extra;
758 struct sockcheck_response *resp;
762 /* allocate memory and tack it onto parent->responses */
763 resp = malloc(sizeof(*resp));
764 for (end = key; *end != ':' && *end != 0; end += 2 && end) ;
765 templ = malloc(end - key + 1);
766 memcpy(templ, key, end - key);
767 templ[end - key] = 0;
768 resp->template = templ;
769 if (!sockcheck_check_template(resp->template, 1)) _exit(1);
770 resp->next = malloc(sizeof(*resp->next));
771 resp->next->port = parent->port;
772 response_list_append(&parent->responses, resp);
773 /* now figure out how to create resp->next */
774 if ((str = GET_RECORD_QSTRING(rd))) {
775 if (!ircncasecmp(str, "reject", 6)) {
776 resp->next->type = REJECT;
777 } else if (!ircncasecmp(str, "accept", 6)) {
778 resp->next->type = ACCEPT;
780 log_module(PC_LOG, LOG_ERROR, "Error: unknown sockcheck decision `%s', defaulting to accept.", str);
781 resp->next->type = ACCEPT;
784 resp->next->template = strdup(str+7);
786 resp->next->template = strdup("No explanation given");
788 } else if ((resps = GET_RECORD_OBJECT(rd))) {
789 resp->next->type = CHECKING;
790 response_list_init(&resp->next->responses);
792 resp->next->template = strdup(end+1);
793 if (!sockcheck_check_template(resp->next->template, 0)) _exit(1);
795 resp->next->template = strdup("");
797 dict_foreach(resps, sockcheck_create_response, resp->next);
802 /* key: PORT:send-pattern, as in keys of sockcheck.conf.example
803 * data: recdb record_data containing response
804 * extra: struct sockcheck_list* to append test to
807 sockcheck_create_test(const char *key, void *data, void *extra)
810 struct record_data *rd;
812 struct sockcheck_state *new_test;
816 new_test = malloc(sizeof(*new_test));
817 new_test->template = NULL;
819 new_test->port = strtoul(key, &end, 0);
820 new_test->timeout = 5;
821 new_test->type = CHECKING;
822 response_list_init(&new_test->responses);
823 if (!(object = GET_RECORD_OBJECT(rd))) {
824 log_module(PC_LOG, LOG_ERROR, "Error: misformed sockcheck test `%s', skipping it.", key);
830 case '@': new_test->timeout = strtoul(end+1, &end, 0); break;
831 case '*': new_test->reps = strtoul(end+1, &end, 0); break;
833 new_test->template = strdup(end+1);
835 if (!sockcheck_check_template(new_test->template, 0)) _exit(1);
838 log_module(PC_LOG, LOG_ERROR, "Error: misformed sockcheck test `%s', skipping it.", key);
843 if (!new_test->template) {
844 log_module(PC_LOG, LOG_ERROR, "Error: misformed sockcheck test `%s', skipping it.", key);
848 dict_foreach(object, sockcheck_create_response, new_test);
849 /* If none of the responses have template "other", create a
850 * default response that goes to accept. */
851 for (n=0; n<new_test->responses.used; n++) {
852 if (!strcmp(new_test->responses.list[n]->template, "other")) break;
854 if (n == new_test->responses.used) {
855 rd = alloc_record_data_qstring("accept");
856 sockcheck_create_response("other", rd, new_test);
857 free_record_data(rd);
858 } else if (n != (new_test->responses.used - 1)) {
859 struct sockcheck_response *tmp;
860 /* switch the response for "other" to the end */
861 tmp = new_test->responses.list[new_test->responses.used - 1];
862 new_test->responses.list[new_test->responses.used - 1] = new_test->responses.list[n];
863 new_test->responses.list[n] = tmp;
865 if (new_test->responses.used > max_responses) {
866 max_responses = new_test->responses.used;
868 sockcheck_list_append(extra, new_test);
873 sockcheck_read_tests(void)
876 struct sockcheck_list *new_tests;
877 test_db = parse_database(SOCKCHECK_TEST_DB);
880 if (dict_size(test_db) > 0) {
881 new_tests = sockcheck_list_alloc(dict_size(test_db));
882 dict_foreach(test_db, sockcheck_create_test, new_tests);
883 if (tests) sockcheck_list_unref(tests);
886 log_module(PC_LOG, LOG_ERROR, "%s was empty - disabling sockcheck.", SOCKCHECK_TEST_DB);
888 free_database(test_db);
892 sockcheck_free_state(struct sockcheck_state *state)
895 if (state->type == CHECKING) {
896 for (n=0; n<state->responses.used; n++) {
897 free((char*)state->responses.list[n]->template);
898 sockcheck_free_state(state->responses.list[n]->next);
899 free(state->responses.list[n]);
901 response_list_clean(&state->responses);
903 free((char*)state->template);
908 sockcheck_add_test(const char *desc)
910 struct sockcheck_list *new_tests;
913 struct record_data *rd;
915 if ((reason = parse_record(desc, &name, &rd)))
917 new_tests = sockcheck_list_clone(tests);
918 if (sockcheck_create_test(name, rd, new_tests)) {
919 sockcheck_list_unref(new_tests);
920 return "Sockcheck test parse error";
922 sockcheck_list_unref(tests);
928 sockcheck_shutdown(void)
933 for (n=0; n<sockcheck_conf.max_clients; n++) {
935 sockcheck_free_client(client_list[n]);
939 sockcheck_num_clients = 0;
940 dict_delete(checked_ip_dict);
941 sci_list_clean(&pending_sci_list);
943 for (n=0; n<tests->used; n++)
944 sockcheck_free_state(tests->list[n]);
945 sockcheck_list_unref(tests);
946 if (sockcheck_conf.local_addr) {
947 free(sockcheck_conf.local_addr);
948 sockcheck_conf.local_addr_len = 0;
953 sockcheck_clean_cache(UNUSED_ARG(void *data))
956 dict_iterator_t it, next;
957 sockcheck_cache_info sci;
961 if (SOCKCHECK_DEBUG) {
962 struct string_buffer sb;
963 string_buffer_init(&sb);
964 /* Remember which clients we're still checking; we're not allowed to remove them. */
965 for (curr_clients = dict_new(), nn=0; nn < sockcheck_conf.max_clients; nn++) {
966 if (!client_list[nn])
968 dict_insert(curr_clients, client_list[nn]->addr->hostname, client_list[nn]);
969 string_buffer_append(&sb, ' ');
970 string_buffer_append_string(&sb, client_list[nn]->addr->hostname);
972 string_buffer_append(&sb, '\0');
973 log_module(PC_LOG, LOG_INFO, "Cleaning sockcheck cache at "FMT_TIME_T"; current clients: %s.", now, sb.list);
974 string_buffer_clean(&sb);
976 for (curr_clients = dict_new(), nn=0; nn < sockcheck_conf.max_clients; nn++) {
977 if (!client_list[nn])
979 dict_insert(curr_clients, client_list[nn]->addr->hostname, client_list[nn]);
983 for (it=dict_first(checked_ip_dict); it; it=next) {
984 next = iter_next(it);
986 max_age = (sci->decision == REJECT) ? sockcheck_conf.gline_duration : sockcheck_conf.max_cache_age;
987 if (((sci->last_touched + max_age) < now)
988 && !dict_find(curr_clients, sci->hostname, NULL)) {
989 if (SOCKCHECK_DEBUG) {
990 log_module(PC_LOG, LOG_INFO, " .. nuking %s (last touched "FMT_TIME_T").", sci->hostname, sci->last_touched);
992 dict_remove(checked_ip_dict, sci->hostname);
995 dict_delete(curr_clients);
996 timeq_add(now+sockcheck_conf.max_cache_age, sockcheck_clean_cache, 0);
999 static MODCMD_FUNC(cmd_defproxy)
1003 if ((reason = sockcheck_add_test(unsplit_string(argv+1, argc-1, NULL)))) {
1004 reply("PCMSG_PROXY_DEFINITION_FAILED", reason);
1007 reply("PCMSG_PROXY_DEFINITION_SUCCEEDED");
1011 static MODCMD_FUNC(cmd_hostscan)
1014 irc_in_addr_t ipaddr;
1015 char hnamebuf[IRC_NTOP_MAX_SIZE];
1017 for (n=1; n<argc; n++) {
1018 struct userNode *un = GetUserH(argv[n]);
1021 if (!irc_in_addr_is_valid(un->ip)
1022 || irc_in_addr_is_loopback(un->ip)) {
1023 reply("PCMSG_UNSCANNABLE_IP", un->nick);
1025 irc_ntop(hnamebuf, sizeof(hnamebuf), &un->ip);
1026 sockcheck_queue_address(un->ip);
1027 reply("PCMSG_ADDRESS_QUEUED", hnamebuf);
1030 char *scanhost = argv[n];
1031 if (irc_pton(&ipaddr, NULL, scanhost)) {
1032 sockcheck_queue_address(ipaddr);
1033 reply("PCMSG_ADDRESS_QUEUED", scanhost);
1035 reply("PCMSG_ADDRESS_UNRESOLVED", scanhost);
1042 static MODCMD_FUNC(cmd_clearhost)
1045 char hnamebuf[IRC_NTOP_MAX_SIZE];
1047 for (n=1; n<argc; n++) {
1048 struct userNode *un = GetUserH(argv[n]);
1049 const char *scanhost;
1052 irc_ntop(hnamebuf, sizeof(hnamebuf), &un->ip);
1053 scanhost = hnamebuf;
1057 switch (sockcheck_uncache_host(scanhost)) {
1059 reply("PCMSG_CHECKING_ADDRESS", scanhost);
1062 reply("PCMSG_NOT_REMOVED_FROM_CACHE", scanhost);
1065 reply("PCMSG_REMOVED_FROM_CACHE", scanhost);
1072 static MODCMD_FUNC(cmd_stats_proxycheck)
1075 const char *hostname = argv[1];
1076 char elapse_buf[INTERVALLEN];
1079 sockcheck_cache_info sci = dict_find(checked_ip_dict, hostname, NULL);
1081 reply("PCMSG_NOT_CACHED", hostname);
1084 intervalString(elapse_buf, now - sci->last_touched, user->handle_info);
1085 switch (sci->decision) {
1086 case CHECKING: msg = "PCMSG_STATUS_CHECKING"; break;
1087 case ACCEPT: msg = "PCMSG_STATUS_ACCEPTED"; break;
1088 case REJECT: msg = "PCMSG_STATUS_REJECTED"; break;
1089 default: msg = "PCMSG_STATUS_UNKNOWN"; break;
1091 reply(msg, sci->hostname, elapse_buf, sci->reason);
1094 reply("PCMSG_STATISTICS", checked_ip_count, proxies_detected, sockcheck_num_clients, sockcheck_conf.max_clients, pending_sci_list.used, dict_size(checked_ip_dict), (tests ? tests->used : 0));
1100 sockcheck_new_user(struct userNode *user) {
1101 /* If they have a bum IP, or are bursting in, don't proxy-check or G-line them. */
1102 if (irc_in_addr_is_valid(user->ip)
1103 && !irc_in_addr_is_loopback(user->ip)
1104 && !user->uplink->burst)
1105 sockcheck_queue_address(user->ip);
1110 _sockcheck_init(void)
1112 checked_ip_dict = dict_new();
1113 dict_set_free_data(checked_ip_dict, free);
1114 sci_list_init(&pending_sci_list);
1115 sockcheck_num_clients = 0;
1116 sockcheck_read_tests();
1117 timeq_del(0, sockcheck_clean_cache, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
1118 client_list = calloc(sockcheck_conf.max_clients, sizeof(client_list[0]));
1119 timeq_add(now+sockcheck_conf.max_cache_age, sockcheck_clean_cache, 0);
1123 sockcheck_read_conf(void)
1126 struct addrinfo *ai;
1129 /* set the defaults here in case the entire record is missing */
1130 sockcheck_conf.max_clients = 32;
1131 sockcheck_conf.max_read = 1024;
1132 sockcheck_conf.gline_duration = 3600;
1133 sockcheck_conf.max_cache_age = 60;
1134 if (sockcheck_conf.local_addr) {
1135 free(sockcheck_conf.local_addr);
1136 sockcheck_conf.local_addr = NULL;
1138 /* now try to read from the conf database */
1139 if ((my_node = conf_get_data("modules/sockcheck", RECDB_OBJECT))) {
1140 str = database_get_data(my_node, "max_sockets", RECDB_QSTRING);
1141 if (str) sockcheck_conf.max_clients = strtoul(str, NULL, 0);
1142 str = database_get_data(my_node, "max_clients", RECDB_QSTRING);
1143 if (str) sockcheck_conf.max_clients = strtoul(str, NULL, 0);
1144 str = database_get_data(my_node, "max_read", RECDB_QSTRING);
1145 if (str) sockcheck_conf.max_read = strtoul(str, NULL, 0);
1146 str = database_get_data(my_node, "max_cache_age", RECDB_QSTRING);
1147 if (str) sockcheck_conf.max_cache_age = ParseInterval(str);
1148 str = database_get_data(my_node, "gline_duration", RECDB_QSTRING);
1149 if (str) sockcheck_conf.gline_duration = ParseInterval(str);
1150 str = database_get_data(my_node, "address", RECDB_QSTRING);
1151 if (!getaddrinfo(str, NULL, NULL, &ai)) {
1152 sockcheck_conf.local_addr_len = ai->ai_addrlen;
1153 sockcheck_conf.local_addr = calloc(1, ai->ai_addrlen);
1154 memcpy(sockcheck_conf.local_addr, ai->ai_addr, ai->ai_addrlen);
1157 sockcheck_conf.local_addr_len = 0;
1158 sockcheck_conf.local_addr = NULL;
1160 log_module(PC_LOG, LOG_ERROR, "Error: Unable to get host named `%s', not checking from a specific address.", str);
1166 sockcheck_init(void)
1168 PC_LOG = log_register_type("ProxyCheck", "file:proxycheck.log");
1169 conf_register_reload(sockcheck_read_conf);
1170 reg_exit_func(sockcheck_shutdown);
1172 message_register_table(msgtab);
1174 sockcheck_module = module_register("ProxyCheck", PC_LOG, "mod-sockcheck.help", NULL);
1175 modcmd_register(sockcheck_module, "defproxy", cmd_defproxy, 2, 0, "level", "999", NULL);
1176 modcmd_register(sockcheck_module, "hostscan", cmd_hostscan, 2, 0, "level", "650", NULL);
1177 modcmd_register(sockcheck_module, "clearhost", cmd_clearhost, 2, 0, "level", "650", NULL);
1178 modcmd_register(sockcheck_module, "stats proxycheck", cmd_stats_proxycheck, 0, 0, NULL);
1179 reg_new_user_func(sockcheck_new_user);
1184 sockcheck_finalize(void)