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