]> jfr.im git - irc/quakenet/newserv.git/blame - proxyscan/proxyscan.c
merge
[irc/quakenet/newserv.git] / proxyscan / proxyscan.c
CommitLineData
c86edd1d
Q
1
2#include "proxyscan.h"
3
4#include <sys/poll.h>
5#include <sys/types.h>
6#include <sys/socket.h>
7#include <netdb.h>
8#include "../core/error.h"
9#include "../core/events.h"
10#include <stdlib.h>
11#include <stdio.h>
12#include <errno.h>
13#include "../nick/nick.h"
14#include "../core/hooks.h"
15#include "../lib/sstring.h"
16#include "../irc/irc_config.h"
17#include "../localuser/localuser.h"
18#include "../core/config.h"
19#include <unistd.h>
20#include "../core/schedule.h"
21#include <string.h>
22#include "../irc/irc.h"
23#include "../lib/irc_string.h"
cfd3214b
CP
24#include "../lib/version.h"
25#include "../channel/channel.h"
26#include "../localuser/localuserchannel.h"
818e3d5f 27#include "../core/nsmalloc.h"
557c8cb2 28#include "../lib/irc_ipv6.h"
cfd3214b
CP
29
30MODULE_VERSION("")
c86edd1d
Q
31
32#define SCANTIMEOUT 60
33
34#define SCANHOSTHASHSIZE 1000
35#define SCANHASHSIZE 400
36
37/* It's unlikely you'll get 100k of preamble before a connect... */
38#define READ_SANITY_LIMIT 102400
39
40scan *scantable[SCANHASHSIZE];
41
7ab80d0c
P
42CommandTree *ps_commands;
43
c86edd1d
Q
44int listenfd;
45int activescans;
46int maxscans;
47int queuedhosts;
48int scansdone;
49int rescaninterval;
50int warningsent;
51int glinedhosts;
2220c058 52time_t ps_starttime;
557c8cb2
P
53int ps_cache_ext;
54int ps_extscan_ext;
7ab80d0c 55int ps_ready;
c86edd1d
Q
56
57int numscans; /* number of scan types currently valid */
58scantype thescans[PSCAN_MAXSCANS];
59
60unsigned int hitsbyclass[10];
61unsigned int scansbyclass[10];
62
63unsigned int myip;
64sstring *myipstr;
65unsigned short listenport;
66int brokendb;
67
68unsigned int ps_mailip;
69unsigned int ps_mailport;
70sstring *ps_mailname;
71
92f1d9e3
D
72unsigned long scanspermin;
73unsigned long tempscanspermin=0;
74unsigned long lastscants=0;
75
761a4596
P
76unsigned int ps_start_ts=0;
77
c86edd1d
Q
78nick *proxyscannick;
79
80FILE *ps_logfile;
81
82/* Local functions */
83void handlescansock(int fd, short events);
84void timeoutscansock(void *arg);
85void proxyscan_newnick(int hooknum, void *arg);
86void proxyscan_lostnick(int hooknum, void *arg);
7ab80d0c 87void proxyscan_onconnect(int hooknum, void *arg);
c86edd1d
Q
88void proxyscanuserhandler(nick *target, int message, void **params);
89void registerproxyscannick();
90void killsock(scan *sp, int outcome);
91void killallscans();
92void proxyscanstats(int hooknum, void *arg);
93void sendlagwarning();
c86edd1d
Q
94void proxyscan_newip(nick *np, unsigned long ip);
95int proxyscan_addscantype(int type, int port);
96int proxyscan_delscantype(int type, int port);
97
7ab80d0c
P
98int proxyscandostatus(void *sender, int cargc, char **cargv);
99int proxyscandebug(void *sender, int cargc, char **cargv);
100int proxyscandosave(void *sender, int cargc, char **cargv);
101int proxyscandospew(void *sender, int cargc, char **cargv);
102int proxyscandoshowkill(void *sender, int cargc, char **cargv);
103int proxyscandoscan(void *sender, int cargc, char **cargv);
104int proxyscandoaddscan(void *sender, int cargc, char **cargv);
105int proxyscandodelscan(void *sender, int cargc, char **cargv);
106int proxyscandoshowcommands(void *sender, int cargc, char **cargv);
107
c86edd1d
Q
108int proxyscan_addscantype(int type, int port) {
109 /* Check we have a spare scan slot */
110
111 if (numscans>=PSCAN_MAXSCANS)
112 return 1;
113
114 thescans[numscans].type=type;
115 thescans[numscans].port=port;
116 thescans[numscans].hits=0;
117
118 numscans++;
119
120 return 0;
121}
122
123int proxyscan_delscantype(int type, int port) {
124 int i;
125
126 for (i=0;i<numscans;i++)
127 if (thescans[i].type==type && thescans[i].port==port)
128 break;
129
130 if (i>=numscans)
131 return 1;
132
133 memmove(thescans+i, thescans+(i+1), (PSCAN_MAXSCANS-(i+1)) * sizeof(scantype));
134 numscans--;
135
136 return 0;
137}
138
139void _init(void) {
140 sstring *cfgstr;
141 int ipbits[4];
142
761a4596 143 ps_start_ts = time(NULL);
7ab80d0c
P
144 ps_ready = 0;
145 ps_commands = NULL;
761a4596 146
557c8cb2 147 ps_cache_ext = registernodeext("proxyscancache");
a8ba1373
P
148 if( ps_cache_ext == -1 ) {
149 Error("proxyscan",ERR_INFO,"failed to reg node ext");
150 return;
557c8cb2
P
151 }
152 ps_extscan_ext = registernodeext("proxyscanextscan");
a8ba1373
P
153 if ( ps_extscan_ext == -1) {
154 Error("proxyscan",ERR_INFO,"failed to reg node ext");
155 return;
557c8cb2 156 }
a8ba1373 157
c86edd1d
Q
158 memset(scantable,0,sizeof(scantable));
159 maxscans=200;
160 activescans=0;
161 queuedhosts=0;
162 scansdone=0;
163 warningsent=0;
2220c058 164 ps_starttime=time(NULL);
c86edd1d 165 glinedhosts=0;
7ab80d0c 166
92f1d9e3
D
167 scanspermin=0;
168 lastscants=time(NULL);
169
c86edd1d
Q
170 /* Listen port */
171 cfgstr=getcopyconfigitem("proxyscan","port","9999",6);
172 listenport=strtol(cfgstr->content,NULL,10);
173 freesstring(cfgstr);
174
175 /* Max concurrent scans */
176 cfgstr=getcopyconfigitem("proxyscan","maxscans","200",5);
177 maxscans=strtol(cfgstr->content,NULL,10);
178 freesstring(cfgstr);
179
180 /* Clean host timeout */
181 cfgstr=getcopyconfigitem("proxyscan","rescaninterval","3600",7);
182 rescaninterval=strtol(cfgstr->content,NULL,10);
183 cachehostinit(rescaninterval);
184 freesstring(cfgstr);
185
186 /* this default will NOT work well */
187 myipstr=getcopyconfigitem("proxyscan","ip","127.0.0.1",16);
188
189 sscanf(myipstr->content,"%d.%d.%d.%d",&ipbits[0],&ipbits[1],&ipbits[2],&ipbits[3]);
190
191 myip=((ipbits[0]&0xFF)<<24)+((ipbits[1]&0xFF)<<16)+
192 ((ipbits[2]&0xFF)<<8)+(ipbits[3]&0xFF);
193
f94f9cec 194#if defined(PROXYSCAN_MAIL)
c86edd1d
Q
195 /* Mailer host */
196 cfgstr=getcopyconfigitem("proxyscan","mailerip","",16);
197
c86edd1d
Q
198 psm_mailerfd=-1;
199 if (cfgstr) {
200 sscanf(cfgstr->content,"%d.%d.%d.%d",&ipbits[0],&ipbits[1],&ipbits[2],&ipbits[3]);
201 ps_mailip = ((ipbits[0]&0xFF)<<24)+((ipbits[1]&0xFF)<<16)+
202 ((ipbits[2]&0xFF)<<8)+(ipbits[3]&0xFF);
203 ps_mailport=25;
204 freesstring(cfgstr);
205
206 ps_mailname=getcopyconfigitem("proxyscan","mailname","some.mail.server",HOSTLEN);
c9db668b 207 Error("proxyscan",ERR_INFO,"Proxyscan mailer enabled; mailing to %s as %s.",IPlongtostr(ps_mailip),ps_mailname->content);
c86edd1d
Q
208 } else {
209 ps_mailport=0;
210 ps_mailname=NULL;
211 }
212#endif
213
214 proxyscannick=NULL;
215 /* Set up our nick on the network */
216 scheduleoneshot(time(NULL),&registerproxyscannick,NULL);
217
7ab80d0c
P
218 registerhook(HOOK_SERVER_END_OF_BURST, &proxyscan_onconnect);
219
c86edd1d
Q
220 registerhook(HOOK_NICK_NEWNICK,&proxyscan_newnick);
221
222 registerhook(HOOK_CORE_STATSREQUEST,&proxyscanstats);
223
224 /* Read in the clean hosts */
225 loadcachehosts();
226
557c8cb2
P
227 /* Read in any custom ports to scan */
228 loadextrascans();
229
c86edd1d
Q
230 /* Set up the database */
231 if ((proxyscandbinit())!=0) {
232 brokendb=1;
233 } else {
234 brokendb=0;
235 }
236
7ab80d0c
P
237 ps_commands = newcommandtree();
238 addcommandtotree(ps_commands, "showcommands", 0, 0, &proxyscandoshowcommands);
239 addcommandtotree(ps_commands, "status", 0, 0, &proxyscandostatus);
240 addcommandtotree(ps_commands, "listopen", 0, 0, &proxyscandolistopen);
241 addcommandtotree(ps_commands, "save", 0, 0, &proxyscandosave);
242 addcommandtotree(ps_commands, "spew", 0, 0, &proxyscandospew);
243 addcommandtotree(ps_commands, "showkill", 0, 0, &proxyscandoshowkill);
244 addcommandtotree(ps_commands, "scan", 0, 0, &proxyscandoscan);
245 addcommandtotree(ps_commands, "addscan", 0, 0, &proxyscandoaddscan);
246 addcommandtotree(ps_commands, "delscan", 0, 0, &proxyscandodelscan);
247
c86edd1d
Q
248 /* Default scan types */
249 proxyscan_addscantype(STYPE_HTTP, 8080);
7a91c1d0 250 proxyscan_addscantype(STYPE_HTTP, 8118);
c86edd1d
Q
251 proxyscan_addscantype(STYPE_HTTP, 80);
252 proxyscan_addscantype(STYPE_HTTP, 6588);
253 proxyscan_addscantype(STYPE_HTTP, 8000);
254 proxyscan_addscantype(STYPE_HTTP, 3128);
255 proxyscan_addscantype(STYPE_HTTP, 3802);
256 proxyscan_addscantype(STYPE_HTTP, 5490);
257 proxyscan_addscantype(STYPE_HTTP, 7441);
258 proxyscan_addscantype(STYPE_HTTP, 808);
259 proxyscan_addscantype(STYPE_HTTP, 3332);
260 proxyscan_addscantype(STYPE_HTTP, 2282);
0a85c6ba 261 proxyscan_addscantype(STYPE_SOCKS4, 559);
c86edd1d
Q
262 proxyscan_addscantype(STYPE_SOCKS4, 1080);
263 proxyscan_addscantype(STYPE_SOCKS5, 1080);
264 proxyscan_addscantype(STYPE_SOCKS4, 1075);
265 proxyscan_addscantype(STYPE_SOCKS5, 1075);
266 proxyscan_addscantype(STYPE_SOCKS4, 2280);
267 proxyscan_addscantype(STYPE_SOCKS5, 2280);
268 proxyscan_addscantype(STYPE_SOCKS4, 1180);
269 proxyscan_addscantype(STYPE_SOCKS5, 1180);
0a85c6ba
P
270 proxyscan_addscantype(STYPE_SOCKS4, 9999);
271 proxyscan_addscantype(STYPE_SOCKS5, 9999);
c86edd1d
Q
272 proxyscan_addscantype(STYPE_WINGATE, 23);
273 proxyscan_addscantype(STYPE_CISCO, 23);
274 proxyscan_addscantype(STYPE_WINGATE, 1181);
275 proxyscan_addscantype(STYPE_SOCKS5, 1978);
276 proxyscan_addscantype(STYPE_SOCKS5, 1029);
277 proxyscan_addscantype(STYPE_SOCKS5, 3801);
278 proxyscan_addscantype(STYPE_SOCKS5, 3331);
279 proxyscan_addscantype(STYPE_HTTP, 65506);
280 proxyscan_addscantype(STYPE_HTTP, 63809);
905c2ba2 281 proxyscan_addscantype(STYPE_HTTP, 63000);
92f1d9e3 282 proxyscan_addscantype(STYPE_SOCKS4, 29992);
468b83b2 283 proxyscan_addscantype(STYPE_DIRECT_IRC, 6666);
c7be40f8
CP
284 proxyscan_addscantype(STYPE_DIRECT_IRC, 6667);
285 proxyscan_addscantype(STYPE_DIRECT_IRC, 6668);
286 proxyscan_addscantype(STYPE_DIRECT_IRC, 6669);
287 proxyscan_addscantype(STYPE_DIRECT_IRC, 6670);
e95140be 288 proxyscan_addscantype(STYPE_ROUTER, 3128);
7ab80d0c 289
c86edd1d
Q
290 /* Schedule saves */
291 schedulerecurring(time(NULL)+3600,0,3600,&dumpcachehosts,NULL);
7ab80d0c
P
292
293 ps_logfile=fopen("logs/proxyscan.log","a");
c86edd1d 294
7ab80d0c
P
295 if (connected) {
296 /* if we're already connected, assume we're just reloading module (i.e. have a completed burst) */
297 ps_ready = 1;
298 startqueuedscans();
299 }
c86edd1d
Q
300}
301
302void registerproxyscannick(void *arg) {
303 sstring *psnick,*psuser,*pshost,*psrealname;
304 /* Set up our nick on the network */
cfd3214b 305 channel *cp;
c86edd1d
Q
306
307 psnick=getcopyconfigitem("proxyscan","nick","P",NICKLEN);
308 psuser=getcopyconfigitem("proxyscan","user","proxyscan",USERLEN);
309 pshost=getcopyconfigitem("proxyscan","host","some.host",HOSTLEN);
310 psrealname=getcopyconfigitem("proxyscan","realname","Proxyscan",REALLEN);
311
312 proxyscannick=registerlocaluser(psnick->content,psuser->content,pshost->content,
313 psrealname->content,
314 NULL,UMODE_OPER|UMODE_SERVICE|UMODE_DEAF,
315 &proxyscanuserhandler);
316
317 freesstring(psnick);
318 freesstring(psuser);
319 freesstring(pshost);
320 freesstring(psrealname);
cfd3214b
CP
321
322 cp=findchannel("#twilightzone");
323 if (!cp) {
324 localcreatechannel(proxyscannick,"#twilightzone");
325 } else {
326 localjoinchannel(proxyscannick,cp);
327 localgetops(proxyscannick,cp);
328 }
c86edd1d
Q
329}
330
331void _fini(void) {
332
333 deregisterlocaluser(proxyscannick,NULL);
557c8cb2 334
7ab80d0c 335 deregisterhook(HOOK_SERVER_END_OF_BURST, &proxyscan_onconnect);
c86edd1d
Q
336
337 deregisterhook(HOOK_NICK_NEWNICK,&proxyscan_newnick);
338
339 deregisterhook(HOOK_CORE_STATSREQUEST,&proxyscanstats);
340
341 deleteschedule(NULL,&dumpcachehosts,NULL);
7ab80d0c
P
342
343 destroycommandtree(ps_commands);
344
c86edd1d
Q
345 /* Kill any scans in progress */
346 killallscans();
347
348 /* Dump the database - AFTER killallscans() which prunes it */
349 dumpcachehosts(NULL);
350
7ab80d0c
P
351 /* dump any cached hosts before deleting the extensions */
352 releasenodeext(ps_cache_ext);
353 releasenodeext(ps_extscan_ext);
354
c86edd1d 355 /* free() all our structures */
818e3d5f 356 nsfreeall(POOL_PROXYSCAN);
c86edd1d 357
6e228f06 358 freesstring(myipstr);
c86edd1d
Q
359 freesstring(ps_mailname);
360#if defined(PROXYSCAN_MAIL)
361 if (psm_mailerfd!=-1)
362 deregisterhandler(psm_mailerfd,1);
363#endif
364
365 if (ps_logfile)
366 fclose(ps_logfile);
367}
368
369void proxyscanuserhandler(nick *target, int message, void **params) {
370 nick *sender;
7ab80d0c
P
371 Command *ps_command;
372 char *cargv[20];
373 int cargc;
c86edd1d
Q
374
375 switch(message) {
376 case LU_KILLED:
377 scheduleoneshot(time(NULL)+1,&registerproxyscannick,NULL);
378 proxyscannick=NULL;
379 break;
380
381 case LU_PRIVMSG:
382 case LU_SECUREMSG:
383 sender=(nick *)params[0];
c86edd1d
Q
384
385 if (IsOper(sender)) {
7ab80d0c 386 cargc = splitline((char *)params[1], cargv, 20, 0);
7d228b1d 387
7ab80d0c
P
388 if ( cargc == 0 )
389 return;
7d228b1d 390
7ab80d0c 391 ps_command = findcommandintree(ps_commands, cargv[0], 1);
7d228b1d 392
7ab80d0c
P
393 if ( !ps_command ) {
394 sendnoticetouser(proxyscannick,sender, "Unknown command.");
395 return;
c86edd1d
Q
396 }
397
7ab80d0c
P
398 if ( ps_command->maxparams < (cargc-1) ) {
399 rejoinline(cargv[ps_command->maxparams], cargc - (ps_command->maxparams));
400 cargc = (ps_command->maxparams) + 1;
c86edd1d
Q
401 }
402
7ab80d0c
P
403 (ps_command->handler)((void *)sender, cargc - 1, &(cargv[1]));
404 break;
c86edd1d
Q
405 }
406
407 default:
408 break;
409 }
410}
411
412void addscantohash(scan *sp) {
413 int hash;
414 hash=(sp->fd)%SCANHASHSIZE;
415
416 sp->next=scantable[hash];
417 scantable[hash]=sp;
418
419 activescans++;
420}
421
422void delscanfromhash(scan *sp) {
423 int hash;
424 scan **sh;
425
426 hash=(sp->fd)%SCANHASHSIZE;
427
428 for (sh=&(scantable[hash]);*sh;sh=&((*sh)->next)) {
429 if (*sh==sp) {
430 (*sh)=sp->next;
431 break;
432 }
433 }
434
435 activescans--;
436}
437
438scan *findscan(int fd) {
439 int hash;
440 scan *sp;
441
442 hash=fd%SCANHASHSIZE;
443
444 for (sp=scantable[hash];sp;sp=sp->next)
445 if (sp->fd==fd)
446 return sp;
447
448 return NULL;
449}
450
557c8cb2 451void startscan(patricia_node_t *node, int type, int port, int class) {
c86edd1d 452 scan *sp;
92f1d9e3
D
453 float scantmp;
454
455 if (scansdone>maxscans)
456 {
457 /* ignore the first maxscans as this will skew our scans per second! */
458 tempscanspermin++;
459 if ((lastscants+60) <= time(NULL))
460 {
461 /* ok, at least 60 seconds has passed, calculate the scans per minute figure */
462 scantmp = time(NULL) - lastscants;
463 scantmp = tempscanspermin / scantmp;
464 scantmp = (scantmp * 60);
465 scanspermin = scantmp;
466 lastscants = time(NULL);
467 tempscanspermin = 0;
468 }
469 }
c86edd1d
Q
470
471 sp=getscan();
472
473 sp->outcome=SOUTCOME_INPROGRESS;
474 sp->port=port;
557c8cb2 475 sp->node=node;
c86edd1d
Q
476 sp->type=type;
477 sp->class=class;
478 sp->bytesread=0;
479 sp->totalbytesread=0;
480 memset(sp->readbuf, '\0', PSCAN_READBUFSIZE);
481
557c8cb2 482 sp->fd=createconnectsocket(irc_in_addr_v4_to_int(&((patricia_node_t *)sp->node)->prefix->sin),sp->port);
c86edd1d
Q
483 sp->state=SSTATE_CONNECTING;
484 if (sp->fd<0) {
485 /* Couldn't set up the socket? */
919fa66b 486 derefnode(iptree,sp->node);
c86edd1d
Q
487 freescan(sp);
488 return;
489 }
490 /* Wait until it is writeable */
491 registerhandler(sp->fd,POLLERR|POLLHUP|POLLOUT,&handlescansock);
492 /* And set a timeout */
493 sp->sch=scheduleoneshot(time(NULL)+SCANTIMEOUT,&timeoutscansock,(void *)sp);
494 addscantohash(sp);
495}
496
497void timeoutscansock(void *arg) {
498 scan *sp=(scan *)arg;
499
500 killsock(sp, SOUTCOME_CLOSED);
501}
502
503void killsock(scan *sp, int outcome) {
504 int i;
505 cachehost *chp;
506 foundproxy *fpp;
bef1f120 507 time_t now;
c86edd1d
Q
508
509 scansdone++;
510 scansbyclass[sp->class]++;
511
512 /* Remove the socket from the schedule/event lists */
513 deregisterhandler(sp->fd,1); /* this will close the fd for us */
514 deleteschedule(sp->sch,&timeoutscansock,(void *)sp);
515
516 sp->outcome=outcome;
517 delscanfromhash(sp);
518
519 /* See if we need to queue another scan.. */
520 if (sp->outcome==SOUTCOME_CLOSED &&
521 ((sp->class==SCLASS_CHECK) ||
522 (sp->class==SCLASS_NORMAL && (sp->state==SSTATE_SENTREQUEST || sp->state==SSTATE_GOTRESPONSE))))
557c8cb2 523 queuescan(sp->node, sp->type, sp->port, SCLASS_PASS2, time(NULL)+300);
c86edd1d
Q
524
525 if (sp->outcome==SOUTCOME_CLOSED && sp->class==SCLASS_PASS2)
557c8cb2 526 queuescan(sp->node, sp->type, sp->port, SCLASS_PASS3, time(NULL)+300);
c86edd1d
Q
527
528 if (sp->outcome==SOUTCOME_CLOSED && sp->class==SCLASS_PASS3)
557c8cb2 529 queuescan(sp->node, sp->type, sp->port, SCLASS_PASS4, time(NULL)+300);
c86edd1d
Q
530
531 if (sp->outcome==SOUTCOME_OPEN) {
532 hitsbyclass[sp->class]++;
533
534 /* Lets try and get the cache record. If there isn't one, make a new one. */
557c8cb2
P
535 if (!(chp=findcachehost(sp->node))) {
536 chp=addcleanhost(time(NULL));
537 patricia_ref_prefix(sp->node->prefix);
a8ba1373 538 sp->node->exts[ps_cache_ext] = chp;
557c8cb2 539 }
c86edd1d
Q
540 /* Stick it on the cache's list of proxies, if necessary */
541 for (fpp=chp->proxies;fpp;fpp=fpp->next)
542 if (fpp->type==sp->type && fpp->port==sp->port)
543 break;
544
545 if (!fpp) {
546 fpp=getfoundproxy();
547 fpp->type=sp->type;
548 fpp->port=sp->port;
549 fpp->next=chp->proxies;
550 chp->proxies=fpp;
551 }
bef1f120
CP
552
553 now=time(NULL);
554 /* the purpose of this lastgline stuff is to stop gline spam from one scan */
555 if (!chp->glineid || (now>=chp->lastgline+SCANTIMEOUT)) {
556 chp->lastgline=now;
c86edd1d 557 glinedhosts++;
bef1f120 558 loggline(chp, sp->node);
68e41288
P
559 irc_send("%s GL * +*@%s 1800 %jd :Open Proxy, see http://www.quakenet.org/openproxies.html - ID: %d",
560 mynumeric->content,IPtostr(((patricia_node_t *)sp->node)->prefix->sin),(intmax_t)getnettime(), chp->glineid);
557c8cb2 561 Error("proxyscan",ERR_DEBUG,"Found open proxy on host %s",IPtostr(((patricia_node_t *)sp->node)->prefix->sin));
c86edd1d 562 } else {
557c8cb2 563 loggline(chp, sp->node); /* Update log only */
c86edd1d
Q
564 }
565
566 /* Update counter */
567 for(i=0;i<numscans;i++) {
568 if (thescans[i].type==sp->type && thescans[i].port==sp->port) {
569 thescans[i].hits++;
570 break;
571 }
572 }
573 }
574
9ae689d8
P
575 /* deref prefix (referenced in queuescan) */
576 derefnode(iptree,sp->node);
c86edd1d
Q
577 freescan(sp);
578
579 /* kick the queue.. */
580 startqueuedscans();
581}
582
583void handlescansock(int fd, short events) {
584 scan *sp;
585 char buf[512];
586 int res;
587 int i;
588 unsigned long netip;
589 unsigned short netport;
590
591 if ((sp=findscan(fd))==NULL) {
592 /* Not found; return and hope it goes away */
593 Error("proxyscan",ERR_ERROR,"Unexpected message from fd %d",fd);
594 return;
595 }
596
597 /* It woke up, delete the alarm call.. */
598 deleteschedule(sp->sch,&timeoutscansock,(void *)sp);
599
600 if (events & (POLLERR|POLLHUP)) {
601 /* Some kind of error; give up on this socket */
602 if (sp->state==SSTATE_GOTRESPONSE) {
603 /* If the error occured while we were waiting for a response, we might have
604 * received the "OPEN PROXY!" message and the EOF at the same time, so continue
605 * processing */
606/* Error("proxyscan",ERR_DEBUG,"Got error in GOTRESPONSE state for %s, continuing.",IPtostr(sp->host->IP)); */
607 } else {
608 killsock(sp, SOUTCOME_CLOSED);
609 return;
610 }
611 }
612
613 /* Otherwise, we got what we wanted.. */
614
615 switch(sp->state) {
616 case SSTATE_CONNECTING:
617 /* OK, we got activity while connecting, so we're going to send some
618 * request depending on scan type. However, we can reregister everything
619 * here to save duplicate code: This code is common for all handlers */
620
621 /* Delete the old handler */
622 deregisterhandler(fd,0);
623 /* Set the new one */
624 registerhandler(fd,POLLERR|POLLHUP|POLLIN,&handlescansock);
625 sp->sch=scheduleoneshot(time(NULL)+SCANTIMEOUT,&timeoutscansock,(void *)sp);
626 /* Update state */
627 sp->state=SSTATE_SENTREQUEST;
628
629 switch(sp->type) {
630 case STYPE_HTTP:
631 sprintf(buf,"CONNECT %s:%d HTTP/1.0\r\n\r\n",myipstr->content,listenport);
632 if ((write(fd,buf,strlen(buf)))<strlen(buf)) {
633 /* We didn't write the full amount, DIE */
634 killsock(sp,SOUTCOME_CLOSED);
635 return;
636 }
637 break;
638
639 case STYPE_SOCKS4:
640 /* set up the buffer */
641 netip=htonl(myip);
642 netport=htons(listenport);
643 memcpy(&buf[4],&netip,4);
644 memcpy(&buf[2],&netport,2);
645 buf[0]=4;
646 buf[1]=1;
647 buf[8]=0;
648 if ((write(fd,buf,9))<9) {
649 /* Didn't write enough, give up */
650 killsock(sp,SOUTCOME_CLOSED);
651 return;
652 }
653 break;
654
655 case STYPE_SOCKS5:
656 /* Set up initial request buffer */
657 buf[0]=5;
658 buf[1]=1;
659 buf[2]=0;
660 if ((write(fd,buf,3))>3) {
661 /* Didn't write enough, give up */
662 killsock(sp,SOUTCOME_CLOSED);
663 return;
664 }
665
666 /* Now the actual connect request */
667 buf[0]=5;
668 buf[1]=1;
669 buf[2]=0;
670 buf[3]=1;
671 netip=htonl(myip);
672 netport=htons(listenport);
673 memcpy(&buf[4],&netip,4);
674 memcpy(&buf[8],&netport,2);
675 res=write(fd,buf,10);
676 if (res<10) {
677 killsock(sp,SOUTCOME_CLOSED);
678 return;
679 }
680 break;
681
682 case STYPE_WINGATE:
683 /* Send wingate request */
684 sprintf(buf,"%s:%d\r\n",myipstr->content,listenport);
685 if((write(fd,buf,strlen(buf)))<strlen(buf)) {
686 killsock(sp,SOUTCOME_CLOSED);
687 return;
688 }
689 break;
690
691 case STYPE_CISCO:
692 /* Send cisco request */
693 sprintf(buf,"cisco\r\n");
694 if ((write(fd,buf,strlen(buf)))<strlen(buf)) {
695 killsock(sp, SOUTCOME_CLOSED);
696 return;
697 }
698
699 sprintf(buf,"telnet %s %d\r\n",myipstr->content,listenport);
700 if ((write(fd,buf,strlen(buf)))<strlen(buf)) {
701 killsock(sp, SOUTCOME_CLOSED);
702 return;
703 }
704
905c2ba2 705 break;
706
707 case STYPE_DIRECT:
708 /* Do nothing */
c86edd1d 709 break;
c7be40f8
CP
710
711 case STYPE_DIRECT_IRC:
712 sprintf(buf,"PRIVMSG\r\n");
713 if ((write(fd,buf,strlen(buf)))<strlen(buf)) {
714 killsock(sp, SOUTCOME_CLOSED);
715 return;
716 }
717
e95140be
CP
718 /* Do nothing */
719 break;
720
721 case STYPE_ROUTER:
722 sprintf(buf,"GET /nonexistent HTTP/1.0\r\n\r\n");
723 if ((write(fd,buf,strlen(buf)))<strlen(buf)) {
724 killsock(sp, SOUTCOME_CLOSED);
725 return;
726 }
727
c7be40f8
CP
728 /* Do nothing */
729 break;
c86edd1d
Q
730 }
731 break;
732
733 case SSTATE_SENTREQUEST:
734 res=read(fd, sp->readbuf+sp->bytesread, PSCAN_READBUFSIZE-sp->bytesread);
735
736 if (res<=0) {
737 if ((errno!=EINTR && errno!=EWOULDBLOCK) || res==0) {
738 /* EOF, forget it */
739 killsock(sp, SOUTCOME_CLOSED);
740 return;
741 }
742 }
743
744 sp->bytesread+=res;
745 sp->totalbytesread+=res;
c7be40f8
CP
746
747 {
748 char *magicstring;
749 int magicstringlength;
750
e95140be 751 if(sp->type == STYPE_DIRECT_IRC) {
c7be40f8
CP
752 magicstring = MAGICIRCSTRING;
753 magicstringlength = MAGICIRCSTRINGLENGTH;
e95140be
CP
754 } else if(sp->type == STYPE_ROUTER) {
755 magicstring = MAGICROUTERSTRING;
756 magicstringlength = MAGICROUTERSTRINGLENGTH;
757 } else {
758 magicstring = MAGICSTRING;
759 magicstringlength = MAGICSTRINGLENGTH;
c7be40f8
CP
760 }
761
762 for (i=0;i<sp->bytesread - magicstringlength;i++) {
763 if (!strncmp(sp->readbuf+i, magicstring, magicstringlength)) {
764 /* Found the magic string */
765 /* If the offset is 0, this means it was the first thing we got from the socket,
766 * so it's an actual IRCD (sheesh). Note that when the buffer is full and moved,
767 * the thing moved to offset 0 would previously have been tested as offset
768 * PSCAN_READBUFSIZE/2.
769 *
770 * Skip this checking for STYPE_DIRECT scans, which are used to detect trojans setting
771 * up portforwards (which will therefore show up as ircds, we rely on the port being
772 * strange enough to avoid false positives */
773 if (i==0 && (sp->type != STYPE_DIRECT)) {
774 killsock(sp, SOUTCOME_CLOSED);
775 return;
776 }
777
778 killsock(sp, SOUTCOME_OPEN);
c86edd1d
Q
779 return;
780 }
c86edd1d
Q
781 }
782 }
783
784 /* If the buffer is full, move half of it along to make room */
785 if (sp->bytesread == PSCAN_READBUFSIZE) {
786 memcpy(sp->readbuf, sp->readbuf + (PSCAN_READBUFSIZE)/2, PSCAN_READBUFSIZE/2);
787 sp->bytesread = PSCAN_READBUFSIZE/2;
788 }
789
790 /* Don't read data forever.. */
791 if (sp->totalbytesread > READ_SANITY_LIMIT) {
792 killsock(sp, SOUTCOME_CLOSED);
793 return;
794 }
795
796 /* No magic string yet, we schedule another timeout in case it comes later. */
797 sp->sch=scheduleoneshot(time(NULL)+SCANTIMEOUT,&timeoutscansock,(void *)sp);
798 return;
799 }
800}
801
802void killallscans() {
803 int i;
804 scan *sp;
805 cachehost *chp;
806
807 for(i=0;i<SCANHASHSIZE;i++) {
808 for(sp=scantable[i];sp;sp=sp->next) {
809 /* If there is a pending scan, delete it's clean host record.. */
a8ba1373
P
810 if ((chp=findcachehost(sp->node)) && !chp->proxies) {
811 sp->node->exts[ps_cache_ext] = NULL;
812 derefnode(iptree,sp->node);
c86edd1d 813 delcachehost(chp);
a8ba1373 814 }
c86edd1d
Q
815
816 if (sp->fd!=-1) {
817 deregisterhandler(sp->fd,1);
818 deleteschedule(sp->sch,&timeoutscansock,(void *)(sp));
819 }
820 }
821 }
822}
823
824void proxyscanstats(int hooknum, void *arg) {
825 char buf[512];
826
827 sprintf(buf, "Proxyscn: %6d/%4d scans complete/in progress. %d hosts queued.",
828 scansdone,activescans,queuedhosts);
829 triggerhook(HOOK_CORE_STATSREPLY,buf);
830 sprintf(buf, "Proxyscn: %6u known clean hosts",cleancount());
831 triggerhook(HOOK_CORE_STATSREPLY,buf);
832}
833
834void sendlagwarning() {
835 int i,j;
836 nick *np;
837
838 for (i=0;i<MAXSERVERS;i++) {
839 if (serverlist[i].maxusernum>0) {
840 for(j=0;j<serverlist[i].maxusernum;j++) {
841 np=servernicks[i][j];
842 if (np!=NULL && IsOper(np)) {
843 sendnoticetouser(proxyscannick,np,"Warning: More than 20,000 hosts to scan - I'm lagging behind badly!");
844 }
845 }
846 }
847 }
848}
849
905c2ba2 850int pscansort(const void *a, const void *b) {
851 int ra = *((const int *)a);
852 int rb = *((const int *)b);
853
854 return thescans[ra].hits - thescans[rb].hits;
855}
856
7ab80d0c
P
857int proxyscandostatus(void *sender, int cargc, char **cargv) {
858 nick *np = (nick *) sender;
c86edd1d
Q
859 int i;
860 int totaldetects=0;
905c2ba2 861 int ord[PSCAN_MAXSCANS];
c86edd1d 862
2220c058 863 sendnoticetouser(proxyscannick,np,"Service uptime: %s",longtoduration(time(NULL)-ps_starttime, 1));
c86edd1d
Q
864 sendnoticetouser(proxyscannick,np,"Total scans completed: %d",scansdone);
865 sendnoticetouser(proxyscannick,np,"Total hosts glined: %d",glinedhosts);
866
c651da74 867 sendnoticetouser(proxyscannick,np,"pendingscan structures: %lu x %lu bytes = %lu bytes total",countpendingscan,
92f1d9e3
D
868 sizeof(pendingscan), (countpendingscan * sizeof(pendingscan)));
869
c86edd1d 870 sendnoticetouser(proxyscannick,np,"Currently active scans: %d/%d",activescans,maxscans);
92f1d9e3 871 sendnoticetouser(proxyscannick,np,"Processing speed: %lu scans per minute",scanspermin);
c86edd1d
Q
872 sendnoticetouser(proxyscannick,np,"Normal queued scans: %d",normalqueuedscans);
873 sendnoticetouser(proxyscannick,np,"Timed queued scans: %d",prioqueuedscans);
874 sendnoticetouser(proxyscannick,np,"'Clean' cached hosts: %d",cleancount());
875 sendnoticetouser(proxyscannick,np,"'Dirty' cached hosts: %d",dirtycount());
557c8cb2
P
876
877 sendnoticetouser(proxyscannick,np,"Extra scans: %d", extrascancount());
c86edd1d
Q
878 for (i=0;i<5;i++)
879 sendnoticetouser(proxyscannick,np,"Open proxies, class %1d: %d/%d (%.2f%%)",i,hitsbyclass[i],scansbyclass[i],((float)hitsbyclass[i]*100)/scansbyclass[i]);
880
881 for (i=0;i<numscans;i++)
882 totaldetects+=thescans[i].hits;
883
905c2ba2 884 for (i=0;i<numscans;i++)
885 ord[i]=i;
886
887 qsort(ord,numscans,sizeof(int),pscansort);
888
c86edd1d
Q
889 sendnoticetouser(proxyscannick,np,"Scan type Port Detections");
890 for (i=0;i<numscans;i++)
891 sendnoticetouser(proxyscannick,np,"%-9s %-5d %d (%.2f%%)",
905c2ba2 892 scantostr(thescans[ord[i]].type), thescans[ord[i]].port, thescans[ord[i]].hits, ((float)thescans[ord[i]].hits*100)/totaldetects);
c86edd1d
Q
893
894 sendnoticetouser(proxyscannick,np,"End of list.");
7ab80d0c 895 return CMD_OK;
c86edd1d
Q
896}
897
7ab80d0c 898int proxyscandebug(void *sender, int cargc, char **cargv) {
c86edd1d
Q
899 /* Dump all scans.. */
900 int i;
901 int activescansfound=0;
902 int totalscansfound=0;
903 scan *sp;
7ab80d0c 904 nick *np = (nick *)sender;
c86edd1d
Q
905
906 sendnoticetouser(proxyscannick,np,"Active scans : %d",activescans);
907
908 for (i=0;i<SCANHASHSIZE;i++) {
909 for (sp=scantable[i];sp;sp=sp->next) {
910 if (sp->outcome==SOUTCOME_INPROGRESS) {
911 activescansfound++;
912 }
913 totalscansfound++;
914 sendnoticetouser(proxyscannick,np,"fd: %d type: %d port: %d state: %d outcome: %d IP: %s",
557c8cb2 915 sp->fd,sp->type,sp->port,sp->state,sp->outcome,IPtostr(((patricia_node_t *)sp->node)->prefix->sin));
c86edd1d
Q
916 }
917 }
918
7ab80d0c
P
919 sendnoticetouser(proxyscannick,np,"Total %d scans actually found (%d active)",totalscansfound,activescansfound);
920 return CMD_OK;
921}
922
923void proxyscan_onconnect(int hooknum, void *arg) {
924 ps_ready = 1;
925
926 /* kick the queue.. */
927 startqueuedscans();
928}
929
930int proxyscandosave(void *sender, int cargc, char **cargv) {
931 nick *np = (nick *)sender;
932
933 sendnoticetouser(proxyscannick,np,"Saving cached hosts...");
934 dumpcachehosts(NULL);
935 sendnoticetouser(proxyscannick,np,"Done.");
936 return CMD_OK;
937}
938
939int proxyscandospew(void *sender, int cargc, char **cargv) {
940 nick *np = (nick *)sender;
941
942 /* check our database for the ip supplied */
943 unsigned long a,b,c,d;
944 if (4 != sscanf(cargv[0],"%lu.%lu.%lu.%lu",&a,&b,&c,&d)) {
945 sendnoticetouser(proxyscannick,np,"Usage: spew x.x.x.x");
946 } else {
947 /* check db */
948 proxyscanspewip(proxyscannick,np,a,b,c,d);
949 }
950 return CMD_OK;
951}
952
953int proxyscandoshowkill(void *sender, int cargc, char **cargv) {
954 nick *np = (nick *)sender;
955
956 /* check our database for the id supplied */
957 unsigned long a;
958 if (1 != sscanf(cargv[0],"%lu",&a)) {
959 sendnoticetouser(proxyscannick,np,"Usage: showkill <id>");
960 } else {
961 /* check db */
962 proxyscanshowkill(proxyscannick,np,a);
963 }
964 return CMD_OK;
965}
966
883d13a2
CP
967void startnickscan(nick *np) {
968 time_t t = time(NULL);
969 int i;
970 for(i=0;i<numscans;i++) {
971 /* @@@TODO: we allow a forced scan to scan the same IP multiple times atm */
972 queuescan(np->ipnode,thescans[i].type,thescans[i].port,SCLASS_NORMAL,t);
973 }
974}
975
7ab80d0c
P
976int proxyscandoscan(void *sender, int cargc, char **cargv) {
977 nick *np = (nick *)sender;
978 patricia_node_t *node;
979 struct irc_in_addr sin;
980 unsigned char bits;
981 int i;
982
983 if (0 == ipmask_parse(cargv[0],&sin, &bits)) {
984 sendnoticetouser(proxyscannick,np,"Usage: scan <ip>");
985 } else {
9ae689d8
P
986 if (bits != 128 || !irc_in_addr_is_ipv4(&sin) || irc_in_addr_is_loopback(&sin)) {
987 sendnoticetouser(proxyscannick,np,"You may only scan single IPv4 IP's");
988 return CMD_OK;
989 }
990
883d13a2 991 time_t t;
7ab80d0c
P
992 sendnoticetouser(proxyscannick,np,"Forcing scan of %s",IPtostr(sin));
993 // * Just queue the scans directly here.. plonk them on the priority queue * /
994 node = refnode(iptree, &sin, bits); /* node leaks node here - should only allow to scan a nick? */
883d13a2 995 t = time(NULL);
7ab80d0c
P
996 for(i=0;i<numscans;i++) {
997 /* @@@TODO: we allow a forced scan to scan the same IP multiple times atm */
883d13a2 998 queuescan(node,thescans[i].type,thescans[i].port,SCLASS_NORMAL,t);
557c8cb2 999 }
7ab80d0c
P
1000 }
1001 return CMD_OK;
1002}
557c8cb2 1003
7ab80d0c
P
1004int proxyscandoaddscan(void *sender, int cargc, char **cargv) {
1005 nick *np = (nick *)sender;
1006
1007 unsigned int a,b;
1008 if (sscanf(cargv[0],"%u %u",&a,&b) != 2) {
1009 sendnoticetouser(proxyscannick,np,"Usage: addscan <type> <port>");
1010 } else {
1011 sendnoticetouser(proxyscannick,np,"Added scan type %u port %u",a,b);
1012 proxyscan_addscantype(a,b);
1013 scanall(a,b);
1014 }
1015 return CMD_OK;
1016}
1017
1018int proxyscandodelscan(void *sender, int cargc, char **cargv) {
1019 nick *np = (nick *)sender;
1020
1021 unsigned int a,b;
1022 if (sscanf(cargv[0],"%u %u",&a,&b) != 2) {
1023 sendnoticetouser(proxyscannick,np,"Usage: delscan <type> <port>");
1024 } else {
1025 sendnoticetouser(proxyscannick,np,"Delete scan type %u port %u",a,b);
1026 proxyscan_delscantype(a,b);
1027 }
1028 return CMD_OK;
1029}
1030
1031int proxyscandoshowcommands(void *sender, int cargc, char **cargv) {
1032 nick *np = (nick *)sender;
1033 Command *cmdlist[100];
1034 int i,n;
1035
1036 n=getcommandlist(ps_commands,cmdlist,100);
1037
1038 sendnoticetouser(proxyscannick,np,"The following commands are registered at present:");
1039 for(i=0;i<n;i++) {
1040 sendnoticetouser(proxyscannick,np,"%s",cmdlist[i]->command->content);
1041 }
1042 sendnoticetouser(proxyscannick,np,"End of list.");
1043 return CMD_OK;
c86edd1d 1044}