]> jfr.im git - irc/evilnet/x3.git/blame - src/mod-sockcheck.c
Fixed header comments
[irc/evilnet/x3.git] / src / mod-sockcheck.c
CommitLineData
d76ed9a9 1/* mod-sockcheck.c - insecure proxy checking
2 * Copyright 2000-2004 srvx Development Team
3 *
83ff05c3 4 * This file is part of x3.
d76ed9a9 5 *
d0f04f71 6 * x3 is free software; you can redistribute it and/or modify
d76ed9a9 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.
10 *
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.
15 *
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.
19 */
20
21#include "conf.h"
22#include "gline.h"
23#include "ioset.h"
24#include "modcmd.h"
25#include "timeq.h"
26
27#ifdef HAVE_SYS_SOCKET_H
28#include <sys/socket.h>
29#endif
30#ifdef HAVE_NETINET_IN_H
31#include <netinet/in.h>
32#endif
33#ifdef HAVE_ARPA_INET_H
34#include <arpa/inet.h>
35#endif
36
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.)
40 */
41
42#if !defined(SOCKCHECK_DEBUG)
43#define SOCKCHECK_DEBUG 0
44#endif
45#define SOCKCHECK_TEST_DB "sockcheck.conf"
46
47enum sockcheck_decision {
48 CHECKING,
49 ACCEPT,
50 REJECT
51};
52
53typedef struct {
2f61d1d7 54 irc_in_addr_t addr;
d76ed9a9 55 const char *reason;
2f61d1d7 56 time_t last_touched;
57 enum sockcheck_decision decision;
58 char hostname[IRC_NTOP_MAX_SIZE]; /* acts as key for checked_ip_dict */
d76ed9a9 59} *sockcheck_cache_info;
60
61DECLARE_LIST(sci_list, sockcheck_cache_info);
62DEFINE_LIST(sci_list, sockcheck_cache_info)
63
64/* Here's the list of hosts that need to be started on.
65 */
66static struct sci_list pending_sci_list;
67
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.
70 */
71static dict_t checked_ip_dict;
72
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).
78 *
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.
83 */
84
85struct sockcheck_response {
86 const char *template;
87 struct sockcheck_state *next;
88};
89
90DECLARE_LIST(response_list, struct sockcheck_response *);
91DEFINE_LIST(response_list, struct sockcheck_response *)
92static unsigned int max_responses;
93
94struct sockcheck_state {
95 unsigned short port;
96 unsigned short timeout;
97 unsigned short reps;
98 enum sockcheck_decision type;
99 const char *template;
100 struct response_list responses;
101};
102
103struct sockcheck_list {
104 unsigned int size, used, refs;
105 struct sockcheck_state **list;
106};
107
108/*
109 * List of tests.
110 */
111static struct sockcheck_list *tests;
112
113/* Stuff to track client state, one instance per open connection. */
114struct sockcheck_client {
115 struct io_fd *fd;
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;
123 char *read;
124 const char **resp_state;
125};
126
127static struct {
128 unsigned int max_clients;
129 unsigned int max_read;
130 unsigned int gline_duration;
131 unsigned int max_cache_age;
2f61d1d7 132 struct sockaddr *local_addr;
d76ed9a9 133 int local_addr_len;
134} sockcheck_conf;
135
136static unsigned int sockcheck_num_clients;
137static struct sockcheck_client **client_list;
138static unsigned int proxies_detected, checked_ip_count;
139static struct module *sockcheck_module;
140static struct log_type *PC_LOG;
141const char *sockcheck_module_deps[] = { NULL };
142
143static 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, acepted" },
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." },
159 { NULL, NULL }
160};
161
162static struct sockcheck_list *
163sockcheck_list_alloc(unsigned int size)
164{
165 struct sockcheck_list *list = malloc(sizeof(*list));
166 list->used = 0;
167 list->refs = 1;
168 list->size = size;
169 list->list = malloc(list->size*sizeof(list->list[0]));
170 return list;
171}
172
173static void
174sockcheck_list_append(struct sockcheck_list *list, struct sockcheck_state *new_item)
175{
176 if (list->used == list->size) {
177 list->size <<= 1;
178 list->list = realloc(list->list, list->size*sizeof(list->list[0]));
179 }
180 list->list[list->used++] = new_item;
181}
182
183static struct sockcheck_list *
184sockcheck_list_clone(struct sockcheck_list *old_list)
185{
186 struct sockcheck_list *new_list = malloc(sizeof(*new_list));
187 new_list->used = old_list->used;
188 new_list->refs = 1;
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]));
192 return new_list;
193}
194
195static void
196sockcheck_list_unref(struct sockcheck_list *list)
197{
198 if (!list || --list->refs > 0) return;
199 free(list->list);
200 free(list);
201}
202
203static void
204sockcheck_issue_gline(sockcheck_cache_info sci)
205{
2f61d1d7 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, 1, 1);
210
d76ed9a9 211}
212
213static struct sockcheck_client *
214sockcheck_alloc_client(sockcheck_cache_info sci)
215{
216 struct sockcheck_client *client;
217 client = calloc(1, sizeof(*client));
218 client->tests = tests;
219 client->tests->refs++;
220 client->addr = sci;
221 client->read_size = sockcheck_conf.max_read;
222 client->read = malloc(client->read_size);
223 client->resp_state = malloc(max_responses * sizeof(client->resp_state[0]));
224 return client;
225}
226
227static void
228sockcheck_free_client(struct sockcheck_client *client)
229{
230 if (SOCKCHECK_DEBUG) {
231 log_module(PC_LOG, LOG_INFO, "Goodbye %s (%p)! I set you free!", client->addr->hostname, client);
232 }
ec1a68c8 233 verify(client);
234 if (client->fd)
235 ioset_close(client->fd->fd, 1);
d76ed9a9 236 sockcheck_list_unref(client->tests);
237 free(client->read);
238 free(client->resp_state);
239 free(client);
240}
241
242static void sockcheck_start_client(unsigned int idx);
243static void sockcheck_begin_test(struct sockcheck_client *client);
244static void sockcheck_advance(struct sockcheck_client *client, unsigned int next_state);
245
246static void
247sockcheck_timeout_client(void *data)
248{
249 struct sockcheck_client *client = data;
250 if (SOCKCHECK_DEBUG) {
251 log_module(PC_LOG, LOG_INFO, "Client %s timed out.", client->addr->hostname);
252 }
ec1a68c8 253 verify(client);
d76ed9a9 254 sockcheck_advance(client, client->state->responses.used-1);
255}
256
257static void
258sockcheck_print_client(const struct sockcheck_client *client)
259{
260 static const char *decs[] = {"CHECKING", "ACCEPT", "REJECT"};
261 log_module(PC_LOG, LOG_INFO, "client %p: { addr = %p { decision = %s; last_touched = "FMT_TIME_T"; reason = %s; hostname = \"%s\" }; "
262 "test_index = %d; state = %p { port = %d; type = %s; template = \"%s\"; ... }; "
263 "fd = %p(%d); read = %p; read_size = %d; read_used = %d; read_pos = %d; }",
2f61d1d7 264 client, client->addr, decs[client->addr->decision], client->addr->last_touched,
265 client->addr->reason, client->addr->hostname,
d76ed9a9 266 client->test_index, client->state,
267 (client->state ? client->state->port : 0),
268 (client->state ? decs[client->state->type] : "N/A"),
269 (client->state ? client->state->template : "N/A"),
270 client->fd, (client->fd ? client->fd->fd : 0),
271 client->read, client->read_size, client->read_used, client->read_pos);
272}
273
274static char hexvals[256] = {
275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 */
276 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 */
277 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 */
278 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, /* 48 */
279 0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 */
280 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 */
281 0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 96 */
282 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* 112 */
283};
284
285static void
286expand_var(const struct sockcheck_client *client, char var, char **p_expansion, unsigned int *p_exp_length)
287{
288 extern struct cManagerNode cManager;
289 const char *expansion;
290 unsigned int exp_length;
291#ifndef __SOLARIS__
292 u_int32_t exp4;
293 u_int16_t exp2;
294#else
295 uint32_t exp4;
296 uint16_t exp2;
297#endif
298 /* expand variable */
299 switch (var) {
300 case 'c':
301 expansion = client->addr->hostname;
302 exp_length = strlen(expansion);
303 break;
304 case 'i':
2f61d1d7 305 exp4 = client->addr->addr.in6_32[3];
d76ed9a9 306 exp_length = sizeof(exp4);
307 expansion = (char*)&exp4;
308 break;
309 case 'p':
310 exp2 = htons(client->state->port);
311 exp_length = sizeof(exp2);
312 expansion = (char*)&exp2;
313 break;
314 case 'u':
315 expansion = cManager.uplink->host;
316 exp_length = strlen(expansion);
317 break;
318 default:
319 log_module(PC_LOG, LOG_WARNING, "Request to expand unknown sockcheck variable $%c, using empty expansion.", var);
320 expansion = "";
321 exp_length = 0;
322 }
323 if (p_expansion) {
324 *p_expansion = malloc(exp_length);
325 memcpy(*p_expansion, expansion, exp_length);
326 }
327 if (p_exp_length) {
328 *p_exp_length = exp_length;
329 }
330}
331
332static int
333sockcheck_check_template(const char *template, int is_input)
334{
335 unsigned int nn;
336 if (is_input && !strcmp(template, "other")) return 1;
337 for (nn=0; template[nn]; nn += 2) {
338 switch (template[nn]) {
339 case '=':
340 if (!template[nn+1]) {
341 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s had = at end of template; needs a second character.", template);
342 return 0;
343 }
344 break;
345 case '$':
346 switch (template[nn+1]) {
347 case 'c': case 'i': case 'p': case 'u': break;
348 default:
349 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s refers to unknown variable %c (pos %d).", template, template[nn+1], nn);
350 return 0;
351 }
352 break;
353 case '.':
354 if (!is_input) {
355 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s: . is only valid in input templates.", template);
356 return 0;
357 }
358 if (template[nn+1] != '.') {
359 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s expects .. to come in twos (pos %d).", template, nn);
360 return 0;
361 }
362 break;
363 case '0': case '1': case '2': case '3': case '4':
364 case '5': case '6': case '7': case '8': case '9':
365 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
366 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
367 if (!hexvals[(unsigned char)template[nn+1]] && (template[nn+1] != '0')) {
368 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s expects hex characters to come in twos (pos %d).", template, nn);
369 return 0;
370 }
371 break;
372 default:
373 log_module(MAIN_LOG, LOG_ERROR, "ProxyCheck template %s: unrecognized character '%c' (pos %d).", template, template[nn], nn);
374 return 0;
375 }
376 }
377 return 1;
378}
379
380static void
381sockcheck_elaborate_state(struct sockcheck_client *client)
382{
383 const char *template;
384 unsigned int nn;
385
386 for (template = client->state->template, nn = 0; template[nn]; nn += 2) {
387 switch (template[nn]) {
388 case '=': ioset_write(client->fd, template+nn+1, 1); break;
389 case '0': case '1': case '2': case '3': case '4':
390 case '5': case '6': case '7': case '8': case '9':
391 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
392 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': {
393 char ch = hexvals[(unsigned char)template[nn]] << 4
394 | hexvals[(unsigned char)template[nn+1]];
395 ioset_write(client->fd, &ch, 1);
396 break;
397 }
398 case '$': {
399 char *expansion;
400 unsigned int exp_length;
401 expand_var(client, template[nn+1], &expansion, &exp_length);
402 ioset_write(client->fd, expansion, exp_length);
403 free(expansion);
404 break;
405 }
406 }
407 }
408 for (nn=0; nn<client->state->responses.used; nn++) {
409 /* Set their resp_state to the start of the response. */
410 client->resp_state[nn] = client->state->responses.list[nn]->template;
411 /* If it doesn't require reading, take it now. */
412 if (client->resp_state[nn] && !*client->resp_state[nn]) {
413 if (SOCKCHECK_DEBUG) {
414 log_module(PC_LOG, LOG_INFO, "Skipping straight to easy option %d for %p.", nn, client);
415 }
416 sockcheck_advance(client, nn);
417 return;
418 }
419 }
420 timeq_add(now + client->state->timeout, sockcheck_timeout_client, client);
421 if (SOCKCHECK_DEBUG) {
422 log_module(PC_LOG, LOG_INFO, "Elaborated state for %s:", client->addr->hostname);
423 sockcheck_print_client(client);
424 }
425}
426
427static void
428sockcheck_decide(struct sockcheck_client *client, enum sockcheck_decision decision)
429{
430 unsigned int n;
431
432 checked_ip_count++;
433 client->addr->decision = decision;
434 client->addr->last_touched = now;
435 switch (decision) {
436 case ACCEPT:
437 /* do nothing */
438 if (SOCKCHECK_DEBUG) {
2f61d1d7 439 log_module(PC_LOG, LOG_INFO, "Proxy check passed for client at %s.", client->addr->hostname);
d76ed9a9 440 }
441 break;
442 case REJECT:
443 client->addr->reason = client->state->template;
444 proxies_detected++;
445 sockcheck_issue_gline(client->addr);
446 if (SOCKCHECK_DEBUG) {
2f61d1d7 447 log_module(PC_LOG, LOG_INFO, "Proxy check rejects client at %s (%s)", client->addr->hostname, client->addr->reason);
d76ed9a9 448 }
449 /* Don't compare test_index != 0 directly, because somebody
450 * else may have reordered the tests already. */
451 if (client->tests->list[client->test_index] != tests->list[0]) {
452 struct sockcheck_list *new_tests = sockcheck_list_clone(tests);
453 struct sockcheck_state *new_first = client->tests->list[client->test_index];
454 for (n=0; (n<tests->used) && (tests->list[n] != new_first); n++) ;
455 for (; n>0; n--) new_tests->list[n] = new_tests->list[n-1];
456 new_tests->list[0] = new_first;
457 sockcheck_list_unref(tests);
458 tests = new_tests;
459 }
460 break;
461 default:
462 log_module(PC_LOG, LOG_ERROR, "BUG: sockcheck_decide(\"%s\", %d): unrecognized decision.", client->addr->hostname, decision);
463 }
464 n = client->client_index;
465 sockcheck_free_client(client);
466 if ((--sockcheck_num_clients < sockcheck_conf.max_clients)
467 && (pending_sci_list.used > 0)) {
468 sockcheck_start_client(n);
469 } else {
470 client_list[n] = 0;
471 }
472}
473
474static void
475sockcheck_advance(struct sockcheck_client *client, unsigned int next_state)
476{
477 struct sockcheck_state *ns;
478
ec1a68c8 479 verify(client);
d76ed9a9 480 timeq_del(0, sockcheck_timeout_client, client, TIMEQ_IGNORE_WHEN);
481 if (SOCKCHECK_DEBUG) {
482 unsigned int n, m;
483 char buffer[201];
484 static const char *hexmap = "0123456789ABCDEF";
485 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);
486 for (n=0; n<client->read_used; n++) {
487 for (m=0; (m<(sizeof(buffer)-1)>>1) && ((n+m) < client->read_used); m++) {
488 buffer[m << 1] = hexmap[client->read[n+m] >> 4];
489 buffer[m << 1 | 1] = hexmap[client->read[n+m] & 15];
490 }
491 buffer[m<<1] = 0;
492 log_module(PC_LOG, LOG_INFO, " .. read data: %s", buffer);
493 n += m;
494 }
495 sockcheck_print_client(client);
496 }
497
498 ns = client->state = client->state->responses.list[next_state]->next;
499 switch (ns->type) {
500 case CHECKING:
501 sockcheck_elaborate_state(client);
502 break;
503 case REJECT:
504 sockcheck_decide(client, REJECT);
505 break;
506 case ACCEPT:
507 if (++client->test_rep < client->tests->list[client->test_index]->reps) {
508 sockcheck_begin_test(client);
509 } else if (++client->test_index < client->tests->used) {
510 client->test_rep = 0;
511 sockcheck_begin_test(client);
512 } else {
513 sockcheck_decide(client, ACCEPT);
514 }
515 break;
516 default:
517 log_module(PC_LOG, LOG_ERROR, "BUG: unknown next-state type %d (after %p).", ns->type, client->state);
518 break;
519 }
520}
521
522static void
523sockcheck_readable(struct io_fd *fd)
524{
525 /* read what we can from the fd */
526 struct sockcheck_client *client = fd->data;
527 unsigned int nn;
528 int res;
529
ec1a68c8 530 verify(client);
d76ed9a9 531 res = read(fd->fd, client->read + client->read_used, client->read_size - client->read_used);
532 if (res < 0) {
533 switch (res = errno) {
534 default:
535 log_module(PC_LOG, LOG_ERROR, "BUG: sockcheck_readable(%d/%s): read() returned errno %d (%s)", fd->fd, client->addr->hostname, errno, strerror(errno));
536 case EAGAIN:
537 return;
538 case ECONNRESET:
539 sockcheck_advance(client, client->state->responses.used - 1);
540 return;
541 }
542 } else if (res == 0) {
543 sockcheck_advance(client, client->state->responses.used - 1);
544 return;
545 } else {
546 client->read_used += res;
547 }
548 if (SOCKCHECK_DEBUG) {
549 unsigned int n, m;
550 char buffer[201];
551 static const char *hexmap = "0123456789ABCDEF";
552 for (n=0; n<client->read_used; n++) {
553 for (m=0; (m<(sizeof(buffer)-1)>>1) && ((n+m) < client->read_used); m++) {
554 buffer[m << 1] = hexmap[client->read[n+m] >> 4];
555 buffer[m << 1 | 1] = hexmap[client->read[n+m] & 15];
556 }
557 buffer[m<<1] = 0;
558 log_module(PC_LOG, LOG_INFO, "read %d bytes data: %s", client->read_used, buffer);
559 n += m;
560 }
561 }
562
563 /* See if what's been read matches any of the expected responses */
564 while (client->read_pos < client->read_used) {
565 unsigned int last_pos = client->read_pos;
566 char bleh;
567 const char *resp_state;
568
569 for (nn=0; nn<(client->state->responses.used-1); nn++) {
570 char *expected;
571 unsigned int exp_length = 1, free_exp = 0;
572 /* compare against possible target */
573 resp_state = client->resp_state[nn];
574 if (resp_state == NULL) continue;
575 switch (*resp_state) {
576 case '=':
577 bleh = resp_state[1];
578 expected = &bleh;
579 break;
580 case '.':
581 /* any character passes */
582 client->read_pos++;
583 exp_length = 0;
584 break;
585 case '0': case '1': case '2': case '3': case '4':
586 case '5': case '6': case '7': case '8': case '9':
587 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
588 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
589 bleh = hexvals[(unsigned char)resp_state[0]] << 4
590 | hexvals[(unsigned char)resp_state[1]];
591 expected = &bleh;
592 break;
593 case '$':
594 expand_var(client, resp_state[1], &expected, &exp_length);
595 free_exp = 1;
596 break;
597 }
598 if (client->read_pos+exp_length <= client->read_used) {
599 if (exp_length && memcmp(client->read+client->read_pos, expected, exp_length)) {
600 resp_state = NULL;
601 } else {
602 client->read_pos += exp_length;
603 }
604 } else {
605 /* can't check the variable yet, so come back later */
606 resp_state -= 2;
607 }
608 if (free_exp) free(expected);
609 if (resp_state) {
610 client->resp_state[nn] = resp_state = resp_state + 2;
611 if (!*resp_state) {
612 sockcheck_advance(client, nn);
613 return;
614 }
615 } else {
616 client->resp_state[nn] = NULL;
617 }
618 }
619 if (last_pos == client->read_pos) break;
620 }
621
622 /* nothing seemed to match. what now? */
623 if (client->read_used >= client->read_size) {
624 /* we got more data than we expected to get .. don't read any more */
625 if (SOCKCHECK_DEBUG) {
626 log_module(PC_LOG, LOG_INFO, "Buffer filled (unmatched) for client %s", client->addr->hostname);
627 }
628 sockcheck_advance(client, client->state->responses.used-1);
629 return;
630 }
631}
632
633static void
634sockcheck_connected(struct io_fd *fd, int rc)
635{
636 struct sockcheck_client *client = fd->data;
ec1a68c8 637 verify(client);
d76ed9a9 638 client->fd = fd;
639 switch (rc) {
640 default:
641 log_module(PC_LOG, LOG_ERROR, "BUG: connect() got error %d (%s) for client at %s.", rc, strerror(rc), client->addr->hostname);
642 case EHOSTUNREACH:
643 case ECONNREFUSED:
644 case ETIMEDOUT:
645 if (SOCKCHECK_DEBUG) {
646 log_module(PC_LOG, LOG_INFO, "Client %s gave us errno %d (%s)", client->addr->hostname, rc, strerror(rc));
647 }
648 sockcheck_advance(client, client->state->responses.used-1);
649 return;
650 case 0: break;
651 }
652 fd->wants_reads = 1;
653 if (SOCKCHECK_DEBUG) {
654 log_module(PC_LOG, LOG_INFO, "Connected: to %s port %d.", client->addr->hostname, client->state->port);
655 }
656 sockcheck_elaborate_state(client);
657}
658
659static void
660sockcheck_begin_test(struct sockcheck_client *client)
661{
662 struct io_fd *io_fd;
663
ec1a68c8 664 verify(client);
d76ed9a9 665 if (client->fd) {
666 ioset_close(client->fd->fd, 1);
667 client->fd = NULL;
668 }
669 do {
670 client->state = client->tests->list[client->test_index];
671 client->read_pos = 0;
672 client->read_used = 0;
2f61d1d7 673 client->fd = io_fd = ioset_connect(sockcheck_conf.local_addr, sockcheck_conf.local_addr_len, client->addr->hostname, client->state->port, 0, client, sockcheck_connected);
d76ed9a9 674 if (!io_fd) {
675 client->test_index++;
676 continue;
677 }
678 io_fd->readable_cb = sockcheck_readable;
679 timeq_add(now + client->state->timeout, sockcheck_timeout_client, client);
680 if (SOCKCHECK_DEBUG) {
681 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);
682 }
683 return;
684 } while (client->test_index < client->tests->used);
685 /* Ran out of tests to run; accept this client. */
686 sockcheck_decide(client, ACCEPT);
687}
688
689static void
690sockcheck_start_client(unsigned int idx)
691{
692 sockcheck_cache_info sci;
693 struct sockcheck_client *client;
694
695 if (pending_sci_list.used == 0) return;
696 if (!(sci = pending_sci_list.list[0])) {
697 log_module(PC_LOG, LOG_ERROR, "BUG: sockcheck_start_client(%d) found null pointer in pending_sci_list.", idx);
698 return;
699 }
700 memmove(pending_sci_list.list, pending_sci_list.list+1,
701 (--pending_sci_list.used)*sizeof(pending_sci_list.list[0]));
702 sockcheck_num_clients++;
703 if (!tests) return;
704 client = client_list[idx] = sockcheck_alloc_client(sci);
2f61d1d7 705 log_module(PC_LOG, LOG_INFO, "Proxy-checking client at %s as client %d (%p) of %d.", sci->hostname, idx, client, sockcheck_num_clients);
d76ed9a9 706 client->test_rep = 0;
707 client->client_index = idx;
708 sockcheck_begin_test(client);
709}
710
711void
2f61d1d7 712sockcheck_queue_address(irc_in_addr_t addr)
d76ed9a9 713{
714 sockcheck_cache_info sci;
2f61d1d7 715 const char *ipstr = irc_ntoa(&addr);
d76ed9a9 716
717 sci = dict_find(checked_ip_dict, ipstr, NULL);
718 if (sci) {
ec1a68c8 719 verify(sci);
d76ed9a9 720 switch (sci->decision) {
721 case CHECKING:
722 /* We are already checking this host. */
723 return;
724 case ACCEPT:
725 if ((sci->last_touched + sockcheck_conf.max_cache_age) >= (unsigned)now) return;
726 break;
727 case REJECT:
728 if ((sci->last_touched + sockcheck_conf.gline_duration) >= (unsigned)now) {
729 sockcheck_issue_gline(sci);
730 return;
731 }
732 break;
733 }
734 dict_remove(checked_ip_dict, sci->hostname);
735 }
736 sci = calloc(1, sizeof(*sci));
737 sci->decision = CHECKING;
738 sci->last_touched = now;
739 sci->reason = NULL;
740 sci->addr = addr;
741 strncpy(sci->hostname, ipstr, sizeof(sci->hostname));
742 dict_insert(checked_ip_dict, sci->hostname, sci);
743 sci_list_append(&pending_sci_list, sci);
744 if (sockcheck_num_clients < sockcheck_conf.max_clients)
745 sockcheck_start_client(sockcheck_num_clients);
746}
747
748int
749sockcheck_uncache_host(const char *name)
750{
751 sockcheck_cache_info sci;
752 if ((sci = dict_find(checked_ip_dict, name, NULL))
753 && (sci->decision == CHECKING)) {
754 return -1;
755 }
756 return dict_remove(checked_ip_dict, name);
757}
758
759static int
760sockcheck_create_response(const char *key, void *data, void *extra)
761{
762 const char *str, *end;
763 struct record_data *rd = data;
764 struct sockcheck_state *parent = extra;
765 struct sockcheck_response *resp;
766 dict_t resps;
767 char *templ;
768
769 /* allocate memory and tack it onto parent->responses */
770 resp = malloc(sizeof(*resp));
771 for (end = key; *end != ':' && *end != 0; end += 2 && end) ;
772 templ = malloc(end - key + 1);
773 memcpy(templ, key, end - key);
774 templ[end - key] = 0;
775 resp->template = templ;
776 if (!sockcheck_check_template(resp->template, 1)) _exit(1);
777 resp->next = malloc(sizeof(*resp->next));
778 resp->next->port = parent->port;
779 response_list_append(&parent->responses, resp);
780 /* now figure out how to create resp->next */
781 if ((str = GET_RECORD_QSTRING(rd))) {
782 if (!ircncasecmp(str, "reject", 6)) {
783 resp->next->type = REJECT;
784 } else if (!ircncasecmp(str, "accept", 6)) {
785 resp->next->type = ACCEPT;
786 } else {
787 log_module(PC_LOG, LOG_ERROR, "Error: unknown sockcheck decision `%s', defaulting to accept.", str);
788 resp->next->type = ACCEPT;
789 }
790 if (str[6]) {
791 resp->next->template = strdup(str+7);
792 } else {
793 resp->next->template = strdup("No explanation given");
794 }
795 } else if ((resps = GET_RECORD_OBJECT(rd))) {
796 resp->next->type = CHECKING;
797 response_list_init(&resp->next->responses);
798 if (*end == ':') {
799 resp->next->template = strdup(end+1);
800 if (!sockcheck_check_template(resp->next->template, 0)) _exit(1);
801 } else {
802 resp->next->template = strdup("");
803 }
804 dict_foreach(resps, sockcheck_create_response, resp->next);
805 }
806 return 0;
807}
808
809/* key: PORT:send-pattern, as in keys of sockcheck.conf.example
810 * data: recdb record_data containing response
811 * extra: struct sockcheck_list* to append test to
812 */
813static int
814sockcheck_create_test(const char *key, void *data, void *extra)
815{
816 char *end;
817 struct record_data *rd;
818 dict_t object;
819 struct sockcheck_state *new_test;
820 unsigned int n;
821
822 rd = data;
823 new_test = malloc(sizeof(*new_test));
824 new_test->template = NULL;
825 new_test->reps = 1;
826 new_test->port = strtoul(key, &end, 0);
827 new_test->timeout = 5;
828 new_test->type = CHECKING;
829 response_list_init(&new_test->responses);
830 if (!(object = GET_RECORD_OBJECT(rd))) {
831 log_module(PC_LOG, LOG_ERROR, "Error: misformed sockcheck test `%s', skipping it.", key);
832 free(new_test);
833 return 1;
834 }
835 while (*end) {
836 switch (*end) {
837 case '@': new_test->timeout = strtoul(end+1, &end, 0); break;
838 case '*': new_test->reps = strtoul(end+1, &end, 0); break;
839 case ':':
840 new_test->template = strdup(end+1);
841 end += strlen(end);
842 if (!sockcheck_check_template(new_test->template, 0)) _exit(1);
843 break;
844 default:
845 log_module(PC_LOG, LOG_ERROR, "Error: misformed sockcheck test `%s', skipping it.", key);
846 free(new_test);
847 return 1;
848 }
849 }
850 if (!new_test->template) {
851 log_module(PC_LOG, LOG_ERROR, "Error: misformed sockcheck test `%s', skipping it.", key);
852 free(new_test);
853 return 1;
854 }
855 dict_foreach(object, sockcheck_create_response, new_test);
856 /* If none of the responses have template "other", create a
857 * default response that goes to accept. */
858 for (n=0; n<new_test->responses.used; n++) {
859 if (!strcmp(new_test->responses.list[n]->template, "other")) break;
860 }
861 if (n == new_test->responses.used) {
862 rd = alloc_record_data_qstring("accept");
863 sockcheck_create_response("other", rd, new_test);
864 free_record_data(rd);
865 } else if (n != (new_test->responses.used - 1)) {
866 struct sockcheck_response *tmp;
867 /* switch the response for "other" to the end */
868 tmp = new_test->responses.list[new_test->responses.used - 1];
869 new_test->responses.list[new_test->responses.used - 1] = new_test->responses.list[n];
870 new_test->responses.list[n] = tmp;
871 }
872 if (new_test->responses.used > max_responses) {
873 max_responses = new_test->responses.used;
874 }
875 sockcheck_list_append(extra, new_test);
876 return 0;
877}
878
879static void
880sockcheck_read_tests(void)
881{
882 dict_t test_db;
883 struct sockcheck_list *new_tests;
884 test_db = parse_database(SOCKCHECK_TEST_DB);
885 if (!test_db)
886 return;
887 if (dict_size(test_db) > 0) {
888 new_tests = sockcheck_list_alloc(dict_size(test_db));
889 dict_foreach(test_db, sockcheck_create_test, new_tests);
890 if (tests) sockcheck_list_unref(tests);
891 tests = new_tests;
892 } else {
893 log_module(PC_LOG, LOG_ERROR, "%s was empty - disabling sockcheck.", SOCKCHECK_TEST_DB);
894 }
895 free_database(test_db);
896}
897
898void
899sockcheck_free_state(struct sockcheck_state *state)
900{
901 unsigned int n;
902 if (state->type == CHECKING) {
903 for (n=0; n<state->responses.used; n++) {
904 free((char*)state->responses.list[n]->template);
905 sockcheck_free_state(state->responses.list[n]->next);
906 free(state->responses.list[n]);
907 }
908 response_list_clean(&state->responses);
909 }
910 free((char*)state->template);
911 free(state);
912}
913
914const char *
915sockcheck_add_test(const char *desc)
916{
917 struct sockcheck_list *new_tests;
918 const char *reason;
919 char *name;
920 struct record_data *rd;
921
922 if ((reason = parse_record(desc, &name, &rd)))
923 return reason;
924 new_tests = sockcheck_list_clone(tests);
925 if (sockcheck_create_test(name, rd, new_tests)) {
926 sockcheck_list_unref(new_tests);
927 return "Sockcheck test parse error";
928 }
929 sockcheck_list_unref(tests);
930 tests = new_tests;
931 return 0;
932}
933
934static void
935sockcheck_shutdown(void)
936{
937 unsigned int n;
938
939 if (client_list) {
940 for (n=0; n<sockcheck_conf.max_clients; n++) {
941 if (client_list[n])
942 sockcheck_free_client(client_list[n]);
943 }
944 free(client_list);
945 }
946 sockcheck_num_clients = 0;
947 dict_delete(checked_ip_dict);
948 sci_list_clean(&pending_sci_list);
949 if (tests)
950 for (n=0; n<tests->used; n++)
951 sockcheck_free_state(tests->list[n]);
952 sockcheck_list_unref(tests);
953 if (sockcheck_conf.local_addr) {
954 free(sockcheck_conf.local_addr);
955 sockcheck_conf.local_addr_len = 0;
956 }
957}
958
959static void
960sockcheck_clean_cache(UNUSED_ARG(void *data))
961{
962 dict_t curr_clients;
963 dict_iterator_t it, next;
964 sockcheck_cache_info sci;
965 unsigned int nn;
966 int max_age;
967
968 if (SOCKCHECK_DEBUG) {
969 struct string_buffer sb;
970 string_buffer_init(&sb);
971 /* Remember which clients we're still checking; we're not allowed to remove them. */
972 for (curr_clients = dict_new(), nn=0; nn < sockcheck_conf.max_clients; nn++) {
973 if (!client_list[nn])
974 continue;
975 dict_insert(curr_clients, client_list[nn]->addr->hostname, client_list[nn]);
976 string_buffer_append(&sb, ' ');
977 string_buffer_append_string(&sb, client_list[nn]->addr->hostname);
978 }
979 string_buffer_append(&sb, '\0');
980 log_module(PC_LOG, LOG_INFO, "Cleaning sockcheck cache at "FMT_TIME_T"; current clients: %s.", now, sb.list);
981 string_buffer_clean(&sb);
982 } else {
983 for (curr_clients = dict_new(), nn=0; nn < sockcheck_conf.max_clients; nn++) {
984 if (!client_list[nn])
985 continue;
986 dict_insert(curr_clients, client_list[nn]->addr->hostname, client_list[nn]);
987 }
988 }
989
990 for (it=dict_first(checked_ip_dict); it; it=next) {
991 next = iter_next(it);
992 sci = iter_data(it);
993 max_age = (sci->decision == REJECT) ? sockcheck_conf.gline_duration : sockcheck_conf.max_cache_age;
994 if (((sci->last_touched + max_age) < now)
995 && !dict_find(curr_clients, sci->hostname, NULL)) {
996 if (SOCKCHECK_DEBUG) {
997 log_module(PC_LOG, LOG_INFO, " .. nuking %s (last touched "FMT_TIME_T").", sci->hostname, sci->last_touched);
998 }
999 dict_remove(checked_ip_dict, sci->hostname);
1000 }
1001 }
1002 dict_delete(curr_clients);
1003 timeq_add(now+sockcheck_conf.max_cache_age, sockcheck_clean_cache, 0);
1004}
1005
1006static MODCMD_FUNC(cmd_defproxy)
1007{
1008 const char *reason;
1009
1010 if ((reason = sockcheck_add_test(unsplit_string(argv+1, argc-1, NULL)))) {
1011 reply("PCMSG_PROXY_DEFINITION_FAILED", reason);
1012 return 0;
1013 }
1014 reply("PCMSG_PROXY_DEFINITION_SUCCEEDED");
1015 return 1;
1016}
1017
1018static MODCMD_FUNC(cmd_hostscan)
1019{
1020 unsigned int n;
2f61d1d7 1021 irc_in_addr_t ipaddr;
1022 char hnamebuf[IRC_NTOP_MAX_SIZE];
d76ed9a9 1023
1024 for (n=1; n<argc; n++) {
1025 struct userNode *un = GetUserH(argv[n]);
1026
1027 if (un) {
2f61d1d7 1028 if (!irc_in_addr_is_valid(un->ip)
1029 || irc_in_addr_is_loopback(un->ip)) {
d76ed9a9 1030 reply("PCMSG_UNSCANNABLE_IP", un->nick);
1031 } else {
2f61d1d7 1032 irc_ntop(hnamebuf, sizeof(hnamebuf), &un->ip);
d76ed9a9 1033 sockcheck_queue_address(un->ip);
1034 reply("PCMSG_ADDRESS_QUEUED", hnamebuf);
1035 }
1036 } else {
1037 char *scanhost = argv[n];
2f61d1d7 1038 if (!irc_pton(&ipaddr, NULL, scanhost)) {
d76ed9a9 1039 sockcheck_queue_address(ipaddr);
1040 reply("PCMSG_ADDRESS_QUEUED", scanhost);
1041 } else {
1042 reply("PCMSG_ADDRESS_UNRESOLVED", scanhost);
1043 }
1044 }
1045 }
1046 return 1;
1047}
1048
1049static MODCMD_FUNC(cmd_clearhost)
1050{
1051 unsigned int n;
2f61d1d7 1052 char hnamebuf[IRC_NTOP_MAX_SIZE];
d76ed9a9 1053
1054 for (n=1; n<argc; n++) {
1055 struct userNode *un = GetUserH(argv[n]);
1056 const char *scanhost;
1057
1058 if (un) {
2f61d1d7 1059 irc_ntop(hnamebuf, sizeof(hnamebuf), &un->ip);
d76ed9a9 1060 scanhost = hnamebuf;
1061 } else {
1062 scanhost = argv[n];
1063 }
1064 switch (sockcheck_uncache_host(scanhost)) {
1065 case -1:
1066 reply("PCMSG_CHECKING_ADDRESS", scanhost);
1067 break;
1068 case 0:
1069 reply("PCMSG_NOT_REMOVED_FROM_CACHE", scanhost);
1070 break;
1071 default:
1072 reply("PCMSG_REMOVED_FROM_CACHE", scanhost);
1073 break;
1074 }
1075 }
1076 return 1;
1077}
1078
1079static MODCMD_FUNC(cmd_stats_proxycheck)
1080{
1081 if (argc > 1) {
1082 const char *hostname = argv[1];
1083 char elapse_buf[INTERVALLEN];
1084 const char *msg;
1085
1086 sockcheck_cache_info sci = dict_find(checked_ip_dict, hostname, NULL);
1087 if (!sci) {
1088 reply("PCMSG_NOT_CACHED", hostname);
1089 return 0;
1090 }
1091 intervalString(elapse_buf, now - sci->last_touched, user->handle_info);
1092 switch (sci->decision) {
1093 case CHECKING: msg = "PCMSG_STATUS_CHECKING"; break;
1094 case ACCEPT: msg = "PCMSG_STATUS_ACCEPTED"; break;
1095 case REJECT: msg = "PCMSG_STATUS_REJECTED"; break;
1096 default: msg = "PCMSG_STATUS_UNKNOWN"; break;
1097 }
1098 reply(msg, sci->hostname, elapse_buf, sci->reason);
1099 return 1;
1100 } else {
1101 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));
1102 return 1;
1103 }
1104}
1105
1106static int
1107sockcheck_new_user(struct userNode *user) {
1108 /* If they have a bum IP, or are bursting in, don't proxy-check or G-line them. */
2f61d1d7 1109 if (irc_in_addr_is_valid(user->ip)
1110 && !irc_in_addr_is_loopback(user->ip)
d76ed9a9 1111 && !user->uplink->burst)
1112 sockcheck_queue_address(user->ip);
1113 return 0;
1114}
1115
1116static void
1117_sockcheck_init(void)
1118{
1119 checked_ip_dict = dict_new();
1120 dict_set_free_data(checked_ip_dict, free);
1121 sci_list_init(&pending_sci_list);
1122 sockcheck_num_clients = 0;
1123 sockcheck_read_tests();
1124 timeq_del(0, sockcheck_clean_cache, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
1125 client_list = calloc(sockcheck_conf.max_clients, sizeof(client_list[0]));
1126 timeq_add(now+sockcheck_conf.max_cache_age, sockcheck_clean_cache, 0);
1127}
1128
1129static void
1130sockcheck_read_conf(void)
1131{
1132 dict_t my_node;
2f61d1d7 1133 struct addrinfo *ai;
d76ed9a9 1134 const char *str;
1135
1136 /* set the defaults here in case the entire record is missing */
1137 sockcheck_conf.max_clients = 32;
1138 sockcheck_conf.max_read = 1024;
1139 sockcheck_conf.gline_duration = 3600;
1140 sockcheck_conf.max_cache_age = 60;
1141 if (sockcheck_conf.local_addr) {
1142 free(sockcheck_conf.local_addr);
1143 sockcheck_conf.local_addr = NULL;
1144 }
1145 /* now try to read from the conf database */
1146 if ((my_node = conf_get_data("modules/sockcheck", RECDB_OBJECT))) {
1147 str = database_get_data(my_node, "max_sockets", RECDB_QSTRING);
1148 if (str) sockcheck_conf.max_clients = strtoul(str, NULL, 0);
1149 str = database_get_data(my_node, "max_clients", RECDB_QSTRING);
1150 if (str) sockcheck_conf.max_clients = strtoul(str, NULL, 0);
1151 str = database_get_data(my_node, "max_read", RECDB_QSTRING);
1152 if (str) sockcheck_conf.max_read = strtoul(str, NULL, 0);
1153 str = database_get_data(my_node, "max_cache_age", RECDB_QSTRING);
1154 if (str) sockcheck_conf.max_cache_age = ParseInterval(str);
1155 str = database_get_data(my_node, "gline_duration", RECDB_QSTRING);
1156 if (str) sockcheck_conf.gline_duration = ParseInterval(str);
1157 str = database_get_data(my_node, "address", RECDB_QSTRING);
2f61d1d7 1158 if (!getaddrinfo(str, NULL, NULL, &ai)) {
1159 sockcheck_conf.local_addr_len = ai->ai_addrlen;
1160 sockcheck_conf.local_addr = calloc(1, ai->ai_addrlen);
1161 memcpy(sockcheck_conf.local_addr, ai->ai_addr, ai->ai_addrlen);
1162 } else {
1163 sockcheck_conf.local_addr_len = 0;
1164 sockcheck_conf.local_addr = NULL;
1165 log_module(PC_LOG, LOG_ERROR, "Error: Unable to get host named `%s', not checking a specific address.", str);
d76ed9a9 1166 }
1167 }
1168}
1169
1170int
1171sockcheck_init(void)
1172{
1173 PC_LOG = log_register_type("ProxyCheck", "file:proxycheck.log");
1174 conf_register_reload(sockcheck_read_conf);
1175 reg_exit_func(sockcheck_shutdown);
1176 _sockcheck_init();
1177 message_register_table(msgtab);
1178
1179 sockcheck_module = module_register("ProxyCheck", PC_LOG, "mod-sockcheck.help", NULL);
1180 modcmd_register(sockcheck_module, "defproxy", cmd_defproxy, 2, 0, "level", "999", NULL);
1181 modcmd_register(sockcheck_module, "hostscan", cmd_hostscan, 2, 0, "level", "650", NULL);
1182 modcmd_register(sockcheck_module, "clearhost", cmd_clearhost, 2, 0, "level", "650", NULL);
1183 modcmd_register(sockcheck_module, "stats proxycheck", cmd_stats_proxycheck, 0, 0, NULL);
1184 reg_new_user_func(sockcheck_new_user);
1185 return 1;
1186}
1187
1188int
1189sockcheck_finalize(void)
1190{
1191 return 1;
1192}