forked from freenode/Sigyn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.py
3821 lines (3638 loc) · 185 KB
/
plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env/python
#
# -*- coding: utf-8 -*-
###
# Copyright (c) 2016, Nicolas Coevoet
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import os
import re
import sys
import time
import urllib
import sqlite3
import httplib
import threading
import dns.resolver
import json
import ipaddress
import random
import supybot.log as log
import supybot.conf as conf
import supybot.utils as utils
import supybot.ircdb as ircdb
import supybot.world as world
from supybot.commands import *
import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins
import supybot.commands as commands
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
import supybot.schedule as schedule
import supybot.registry as registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Sigyn')
except:
_ = lambda x:x
def repetitions(s):
# returns a list of (pattern,count), used to detect a repeated pattern inside a single string.
r = re.compile(r"(.+?)\1+")
for match in r.finditer(s):
yield (match.group(1), len(match.group(0))/len(match.group(1)))
def isCloaked (prefix,sig):
if sig.registryValue('useWhoWas'):
return False
if not ircutils.isUserHostmask(prefix):
return False
(nick,ident,host) = ircutils.splitHostmask(prefix)
if '/' in host:
if host.startswith('gateway/') or host.startswith('nat/'):
return False
return True
return False
def compareString (a,b):
"""return 0 to 1 float percent of similarity ( 0.85 seems to be a good average )"""
if a == b:
return 1
sa, sb = set(a), set(b)
n = len(sa.intersection(sb))
if float(len(sa) + len(sb) - n) == 0:
return 0
jacc = n / float(len(sa) + len(sb) - n)
return jacc
def largestString (s1,s2):
"""return largest pattern available in 2 strings"""
# From https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python2
# License: CC BY-SA
m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]
longest, x_longest = 0, 0
for x in xrange(1, 1 + len(s1)):
for y in xrange(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
m[x][y] = m[x - 1][y - 1] + 1
if m[x][y] > longest:
longest = m[x][y]
x_longest = x
else:
m[x][y] = 0
return s1[x_longest - longest: x_longest]
def floatToGMT (t):
f = None
try:
f = float(t)
except:
return None
return time.strftime('%Y-%m-%d %H:%M:%S GMT',time.gmtime(f))
def _getRe(f):
def get(irc, msg, args, state):
original = args[:]
s = args.pop(0)
def isRe(s):
try:
foo = f(s)
return True
except ValueError:
return False
try:
while len(s) < 512 and not isRe(s):
s += ' ' + args.pop(0)
if len(s) < 512:
state.args.append([s,f(s)])
else:
state.errorInvalid('regular expression', s)
except IndexError:
args[:] = original
state.errorInvalid('regular expression', s)
return get
getPatternAndMatcher = _getRe(utils.str.perlReToPythonRe)
addConverter('getPatternAndMatcher', getPatternAndMatcher)
class Ircd (object):
__slots__ = ('irc', 'channels','whowas','klines','queues','opered','defcon','pending','logs','limits','netsplit','ping','servers','resolving','stats','patterns','throttled','lastDefcon','god','mx','tokline','toklineresults','dlines', 'invites', 'nicks')
def __init__(self,irc):
self.irc = irc
# contains Chan instances
self.channels = {}
# contains Pattern instances
self.patterns = {}
# contains whowas requested for a short period of time
self.whowas = {}
# contains klines requested for a short period of time
self.klines = {}
# contains various TimeoutQueue for detection purpose
# often it's [host] { with various TimeOutQueue and others elements }
self.queues = {}
# flag or time
self.opered = False
# flag or time
self.defcon = False
# used for temporary storage of outgoing actions
self.pending = {}
self.logs = {}
# contains servers notices when full or in bad state
# [servername] = time.time()
self.limits = {}
# flag or time
self.netsplit = False
self.ping = None
self.servers = {}
self.resolving = {}
self.stats = {}
self.throttled = False
self.lastDefcon = False
self.god = False
self.mx = {}
self.tokline = {}
self.toklineresults = {}
self.dlines = []
self.invites = {}
self.nicks = {}
def __repr__(self):
return '%s(patterns=%r, queues=%r, channels=%r, pending=%r, logs=%r, limits=%r, whowas=%r, klines=%r)' % (self.__class__.__name__,
self.patterns, self.queues, self.channels, self.pending, self.logs, self.limits, self.whowas, self.klines)
def restore (self,db):
c = db.cursor()
c.execute("""SELECT id, pattern, regexp, mini, life FROM patterns WHERE removed_at is NULL""")
items = c.fetchall()
if len(items):
for item in items:
(uid,pattern,regexp,limit,life) = item
regexp = int(regexp)
if regexp == 1:
regexp = True
else:
regexp = False
self.patterns[uid] = Pattern(uid,pattern,regexp,limit,life)
c.close()
def add (self,db,prefix,pattern,limit,life,regexp):
c = db.cursor()
t = 0
if regexp:
t = 1
c.execute("""INSERT INTO patterns VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)""", (pattern,t,limit,life,prefix,'',0,float(time.time())))
uid = int(c.lastrowid)
self.patterns[uid] = Pattern(uid,pattern,regexp,limit,life)
db.commit()
c.close()
return uid
def count(self,db,uid):
uid = int(uid)
if uid in self.patterns:
c = db.cursor()
c.execute("""SELECT id, triggered FROM patterns WHERE id=? LIMIT 1""",(uid,))
items = c.fetchall()
if len(items):
(uid,triggered) = items[0]
triggered = int(triggered + 1)
c.execute("""UPDATE patterns SET triggered=? WHERE id=?""",(triggered,uid))
db.commit()
c.close()
def ls (self,db,pattern,deep=False):
c = db.cursor()
glob = '*%s*' % pattern
like = '%'+pattern+'%'
i = None
try:
i = int(pattern)
except:
i = None
if i:
c.execute("""SELECT id, pattern, regexp, operator, at, triggered, removed_at, removed_by, comment, mini, life FROM patterns WHERE id=? LIMIT 1""",(i,))
else:
if deep:
c.execute("""SELECT id, pattern, regexp, operator, at, triggered, removed_at, removed_by, comment, mini, life FROM patterns WHERE id GLOB ? OR id LIKE ? OR pattern GLOB ? OR pattern LIKE ? OR comment GLOB ? OR comment LIKE ? ORDER BY id DESC""",(glob,like,glob,like,glob,like))
else:
c.execute("""SELECT id, pattern, regexp, operator, at, triggered, removed_at, removed_by, comment, mini, life FROM patterns WHERE (id GLOB ? OR id LIKE ? OR pattern GLOB ? OR pattern LIKE ? OR comment GLOB ? OR comment LIKE ?) and removed_at is NULL ORDER BY id DESC""",(glob,like,glob,like,glob,like))
items = c.fetchall()
c.close()
if len(items):
results = []
for item in items:
(uid,pattern,regexp,operator,at,triggered,removed_at,removed_by,comment,limit,life) = item
end = ''
if i:
if removed_by:
end = ' - disabled on %s by %s - ' % (floatToGMT(removed_at),removed_by.split('!')[0])
regexp = int(regexp)
reg = 'not case sensitive'
if regexp == 1:
reg = 'regexp pattern'
results.append('#%s "%s" by %s on %s (%s calls) %s/%ss%s %s - %s' % (uid,pattern,operator.split('!')[0],floatToGMT(at),triggered,limit,life,end,comment,reg))
else:
if removed_by:
end = ' (disabled)'
results.append('[#%s "%s" (%s calls) %s/%ss%s]' % (uid,pattern,triggered,limit,life,end))
return results
return []
def edit (self,db,uid,limit,life,comment):
c = db.cursor()
uid = int(uid)
c.execute("""SELECT id, life FROM patterns WHERE id=? LIMIT 1""",(uid,))
items = c.fetchall()
if len(items):
if comment:
c.execute("""UPDATE patterns SET life=?, mini=?, comment=? WHERE id=? LIMIT 1""",(life,limit,comment,uid))
else:
c.execute("""UPDATE patterns SET life=?, mini=? WHERE id=? LIMIT 1""",(life,limit,uid))
db.commit()
if uid in self.patterns:
self.patterns[uid].life = life
self.patterns[uid].limit = limit
found = True
c.close()
return (len(items))
def toggle (self,db,uid,prefix,active):
c = db.cursor()
uid = int(uid)
c.execute("""SELECT id, pattern, regexp, mini, life, removed_at, removed_by FROM patterns WHERE id=? LIMIT 1""",(uid,))
items = c.fetchall()
updated = False
if len(items):
(id,pattern,regexp,limit,life,removed_at,removed_by) = items[0]
regexp = int(regexp)
if active and removed_at:
c.execute("""UPDATE patterns SET removed_at=NULL, removed_by=NULL WHERE id=? LIMIT 1""",(uid,))
self.patterns[uid] = Pattern(uid,pattern,regexp == 1,limit,life)
updated = True
elif not removed_at and not active:
c.execute("""UPDATE patterns SET removed_at=?, removed_by=? WHERE id=? LIMIT 1""",(float(time.time()),prefix,uid))
if uid in self.patterns:
del self.patterns[uid]
updated = True
db.commit()
c.close()
return updated
def remove (self, db, uid):
c = db.cursor()
uid = int(uid)
c.execute("""SELECT id, pattern, regexp, mini, life, removed_at, removed_by FROM patterns WHERE id=? LIMIT 1""",(uid,))
items = c.fetchall()
updated = False
if len(items):
(id,pattern,regexp,limit,life,removed_at,removed_by) = items[0]
c.execute("""DELETE FROM patterns WHERE id=? LIMIT 1""",(uid,))
if not removed_at:
if uid in self.patterns:
del self.patterns[uid]
updated = True
db.commit()
c.close()
return updated
class Chan (object):
__slots__ = ('channel', 'patterns', 'buffers', 'logs', 'nicks', 'called', 'klines', 'requestedBySpam')
def __init__(self,channel):
self.channel = channel
self.patterns = None
self.buffers = {}
self.logs = {}
self.nicks = {}
self.called = False
self.klines = utils.structures.TimeoutQueue(900)
self.requestedBySpam = False
def __repr__(self):
return '%s(channel=%r, patterns=%r, buffers=%r, logs=%r, nicks=%r)' % (self.__class__.__name__,
self.channel, self.patterns, self.buffers, self.logs, self.nicks)
class Pattern (object):
__slots__ = ('uid', 'pattern', 'limit', 'life', '_match')
def __init__(self,uid,pattern,regexp,limit,life):
self.uid = uid
self.pattern = pattern
self.limit = limit
self.life = life
self._match = False
if regexp:
self._match = utils.str.perlReToPythonRe(pattern)
def match (self,text):
s = False
try:
if self._match:
s = self._match.search (text) != None
else:
s = self.pattern in text
except:
s = False
return s
def __repr__(self):
return '%s(uid=%r, pattern=%r, limit=%r, life=%r, _match=%r)' % (self.__class__.__name__,
self.uid, self.pattern, self.limit, self.life, self._match)
class Sigyn(callbacks.Plugin,plugins.ChannelDBHandler):
"""Network and Channels Spam protections"""
threaded = True
noIgnore = True
def __init__(self, irc):
callbacks.Plugin.__init__(self, irc)
plugins.ChannelDBHandler.__init__(self)
self._ircs = ircutils.IrcDict()
self.cache = {}
self.getIrc(irc)
self.addDnsblQueue = []
self.pendingAddDnsbl = False
self.rmDnsblQueue = []
self.pendingRmDnsbl = False
self.words = []
self.channelCreationPattern = re.compile(r"^[#a-z]{6,9}$")
self.collect = {}
self.collecting = False
self.starting = world.starting
self.recaps = re.compile("[A-Z]")
if len(self.registryValue('wordsList')):
for item in self.registryValue('wordsList'):
try:
with open(item, 'r') as content_file:
file = content_file.read()
for line in file.split('\n'):
for word in line.split(' '):
w = word.strip()
if len(w) > self.registryValue('wordMinimum'):
self.words.append(w)
except:
continue
def collectnick (self,irc,msg,args):
"""
collect nicks during bot wave for analyze later, first call to start recording, second call to show results
"""
if self.collecting:
L = []
for w in self.collect:
L.append('%s(%s)' % (w,self.collect[w]))
self.collect = {}
self.collecting = False
irc.reply('%s nicks: %s' % (len(L),' '.join(L)))
else:
self.collecting = True
irc.replySuccess()
collectnick = wrap(collectnick,['owner'])
def lswords (self,irc,msg,args,word):
"""<word>
return if word is in list"""
irc.reply('%s in list ? %s' % (word,word in self.words))
lswords = wrap(lswords,['owner','text'])
def rmwords (self,irc,msg,args,words):
"""<word> [<word>]
remove <word> from wordsList files"""
newList = []
for item in self.registryValue('wordsList'):
try:
f = open(item,'r')
wol = f.read().split('\n')
wnl = []
for line in wol:
for word in line.split(' '):
w = word.strip()
if len(w) > self.registryValue('wordMinimum'):
found = False
for nw in words:
if w == nw:
found = True
break
if not found:
wnl.append(w)
f.close()
f = open(item,'w')
f.write('\n'.join(wnl))
f.close()
newList = newList + wnl
except:
continue
oldList = len(self.words)
self.words = newList
irc.reply('words list updated: %s words before, %s words after' % (oldList,len(newList)))
rmwords = wrap(rmwords,['owner',many('something')])
def removeDnsbl (self,irc,ip,droneblHost,droneblKey):
def check(answer):
self.pendingRmDnsbl = False
if len(self.rmDnsblQueue) > 0:
item = self.rmDnsblQueue.pop()
self.removeDnsbl(item[0],item[1],item[2],item[3])
for line in answer.split('\n'):
if line.find('listed="1"') != -1:
if line.find('type="18"') != -1:
self.logChannel(irc,'RMDNSBL: %s type 18 found, not removed.' % ip)
continue
id = line.split('id="')[1]
id = id.split('"')[0]
add = "<?xml version=\"1.0\"?><request key='"+droneblKey+"'><remove id='"+id+"' /></request>"
type, uri = urllib.splittype(droneblHost)
host, handler = urllib.splithost(uri)
connection = httplib.HTTPConnection(host)
connection.putrequest("POST",handler)
connection.putheader("Content-Type", "text/xml")
connection.putheader("Content-Length", str(int(len(add))))
connection.endheaders()
connection.send(add)
response = connection.getresponse().read().replace('\n','')
if "You are not authorized to remove this incident" in response:
self.logChannel(irc,'RMDNSBL: You are not authorized to remove this incident %s (%s)' % (ip,id))
else:
self.logChannel(irc,'RMDNSBL: %s (%s)' % (ip,id))
if len(self.rmDnsblQueue) == 0 and not self.pendingRmDnsbl:
request = "<?xml version=\"1.0\"?><request key='"+droneblKey+"'><lookup ip='"+ip+"' /></request>"
type, uri = urllib.splittype(droneblHost)
host, handler = urllib.splithost(uri)
connection = httplib.HTTPConnection(host,80,timeout=40)
connection.putrequest("POST",handler)
connection.putheader("Content-Type", "text/xml")
connection.putheader("Content-Length", str(int(len(request))))
connection.endheaders()
connection.send(request)
self.pendingRmDnsbl = True
try:
check(connection.getresponse().read())
except:
self.logChannel(irc,'RMDNSBL: TimeOut for %s' % ip)
else:
self.rmDnsblQueue.append([irc, ip, droneblHost, droneblKey])
def fillDnsbl (self,irc,ip,droneblHost,droneblKey,comment=None):
def check(answer):
self.pendingAddDnsbl = False
if len(self.addDnsblQueue) > 0:
item = self.addDnsblQueue.pop()
self.fillDnsbl(item[0],item[1],item[2],item[3],item[4])
if 'listed="1"' in answer:
return
add = "<?xml version=\"1.0\"?><request key='"+droneblKey+"'><add ip='"+ip+"' type='3' comment='used by irc spam bot' /></request>"
type, uri = urllib.splittype(droneblHost)
host, handler = urllib.splithost(uri)
connection = httplib.HTTPConnection(host)
connection.putrequest("POST",handler)
connection.putheader("Content-Type", "text/xml")
connection.putheader("Content-Length", str(int(len(add))))
connection.endheaders()
connection.send(add)
if comment:
self.logChannel(irc,'DNSBL: %s (%s)' % (ip,comment))
else:
self.logChannel(irc,'DNSBL: %s' % ip)
if len(self.addDnsblQueue) == 0 or not self.pendingAddDnsbl:
self.pendingAddDnsbl = True
request = "<?xml version=\"1.0\"?><request key='"+droneblKey+"'><lookup ip='"+ip+"' /></request>"
type, uri = urllib.splittype(droneblHost)
host, handler = urllib.splithost(uri)
connection = httplib.HTTPConnection(host,80,timeout=40)
connection.putrequest("POST",handler)
connection.putheader("Content-Type", "text/xml")
connection.putheader("Content-Length", str(int(len(request))))
connection.endheaders()
connection.send(request)
try:
check(connection.getresponse().read())
except:
self.logChannel(irc,'DNSBL: TimeOut for %s' % ip)
else:
self.addDnsblQueue.append([irc, ip, droneblHost, droneblKey,comment])
def state (self,irc,msg,args,channel):
"""[<channel>]
returns state of the plugin, for optional <channel>"""
self.cleanup(irc)
i = self.getIrc(irc)
if not channel:
irc.queueMsg(ircmsgs.privmsg(msg.nick,'Opered %s, enable %s, defcon %s, netsplit %s' % (i.opered,self.registryValue('enable'),(i.defcon),i.netsplit)))
irc.queueMsg(ircmsgs.privmsg(msg.nick,'There are %s permanent patterns and %s channels directly monitored' % (len(i.patterns),len(i.channels))))
channels = 0
prefixs = 0
for k in i.queues:
if irc.isChannel(k):
channels += 1
elif ircutils.isUserHostmask(k):
prefixs += 1
irc.queueMsg(ircmsgs.privmsg(msg.nick,"Via server's notices: %s channels and %s users monitored" % (channels,prefixs)))
for chan in i.channels:
if channel == chan:
ch = self.getChan(irc,chan)
if not self.registryValue('ignoreChannel',channel=chan):
called = ""
if ch.called:
called = 'currently in defcon'
irc.queueMsg(ircmsgs.privmsg(msg.nick,'On %s (%s users) %s:' % (chan,len(ch.nicks),called)))
protections = ['flood','lowFlood','repeat','lowRepeat','massRepeat','lowMassRepeat','hilight','nick','ctcp']
for protection in protections:
if self.registryValue('%sPermit' % protection,channel=chan) > -1:
permit = self.registryValue('%sPermit' % protection,channel=chan)
life = self.registryValue('%sLife' % protection,channel=chan)
abuse = self.hasAbuseOnChannel(irc,chan,protection)
if abuse:
abuse = ' (ongoing abuses) '
else:
abuse = ''
count = 0
if protection == 'repeat':
for b in ch.buffers:
if ircutils.isUserHostmask('n!%s' % b):
count += 1
else:
for b in ch.buffers:
if protection in b:
count += len(ch.buffers[b])
if count:
count = " - %s user's buffers" % count
else:
count = ""
irc.queueMsg(ircmsgs.privmsg(msg.nick," - %s : %s/%ss %s%s" % (protection,permit,life,abuse,count)))
irc.replySuccess()
state = wrap(state,['owner',optional('channel')])
def defcon (self,irc,msg,args,channel):
"""[<channel>]
limits are lowered, globally or for a specific <channel>"""
i = self.getIrc(irc)
if channel and channel != self.registryValue('logChannel'):
if channel in i.channels and self.registryValue('abuseDuration',channel=channel) > 0:
chan = self.getChan(irc,channel)
if chan.called:
self.logChannel(irc,'INFO: [%s] rescheduled ignores lifted, limits lowered (by %s) for %ss' % (channel,msg.nick,self.registryValue('abuseDuration',channel=channel)))
chan.called = time.time()
else:
self.logChannel(irc,'INFO: [%s] ignores lifted, limits lowered (by %s) for %ss' % (channel,msg.nick,self.registryValue('abuseDuration',channel=channel)))
chan.called = time.time()
else:
if i.defcon:
i.defcon = time.time()
irc.reply('Already in defcon mode, reset, %ss more' % self.registryValue('defcon'))
else:
i.defcon = time.time()
self.logChannel(irc,"INFO: ignores lifted and abuses end to klines for %ss by %s" % (self.registryValue('defcon'),msg.nick))
# todo check current bot's umode
if not i.god:
irc.sendMsg(ircmsgs.IrcMsg('MODE %s +p' % irc.nick))
else:
for channel in irc.state.channels:
if irc.isChannel(channel) and self.registryValue('defconMode',channel=channel):
if not 'z' in irc.state.channels[channel].modes:
if irc.nick in list(irc.state.channels[channel].ops):
irc.sendMsg(ircmsgs.IrcMsg('MODE %s +qz $~a' % channel))
else:
irc.sendMsg(ircmsgs.IrcMsg('MODE %s +oqz %s $~a' % (channel,irc.nick)))
irc.replySuccess()
defcon = wrap(defcon,['owner',optional('channel')])
def vacuum (self,irc,msg,args):
"""takes no arguments
VACUUM the permanent patterns's database"""
db = self.getDb(irc.network)
c = db.cursor()
c.execute('VACUUM')
c.close()
irc.replySuccess()
vacuum = wrap(vacuum,['owner'])
def leave (self,irc,msg,args,channel):
"""<channel>
force the bot to part <channel> and won't rejoin even if invited
"""
if channel in irc.state.channels:
reason = conf.supybot.plugins.channel.partMsg.getValue()
irc.queueMsg(ircmsgs.part(channel,reason))
try:
network = conf.supybot.networks.get(irc.network)
network.channels().remove(channel)
except:
pass
self.setRegistryValue('lastActionTaken',-1.0,channel=channel)
irc.replySuccess()
leave = wrap(leave,['owner','channel'])
def stay (self,irc,msg,args,channel):
"""<channel>
force bot to stay in <channel>
"""
self.setRegistryValue('leaveChannelIfNoActivity',-1,channel=channel)
if not channel in irc.state.channels:
self.setRegistryValue('lastActionTaken',time.time(),channel=channel)
irc.queueMsg(ircmsgs.join(channel))
try:
network = conf.supybot.networks.get(irc.network)
network.channels().add(channel)
except KeyError:
pass
irc.replySuccess()
stay = wrap(stay,['owner','channel'])
def isprotected (self,irc,msg,args,hostmask,channel):
"""<hostmask> [<channel>]
returns true if <hostmask> is protected, in optional <channel>"""
if ircdb.checkCapability(hostmask, 'protected'):
irc.reply('%s is globally protected' % hostmask)
else:
if channel:
protected = ircdb.makeChannelCapability(channel, 'protected')
if ircdb.checkCapability(hostmask, protected):
irc.reply('%s is protected in %s' % (hostmask,channel))
else:
irc.reply('%s is not protected in %s' % (hostmask,channel))
else:
irc.reply('%s is not protected' % hostmask);
isprotected = wrap(isprotected,['owner','hostmask',optional('channel')])
def checkactions (self,irc,msg,args,duration):
"""<duration> in days
return channels where last action taken is older than <duration>"""
channels = []
duration = duration * 24 * 3600
for channel in irc.state.channels:
if irc.isChannel(channel):
if self.registryValue('mainChannel') in channel or channel == self.registryValue('reportChannel') or self.registryValue('snoopChannel') == channel or self.registryValue('secretChannel') == channel:
continue
if self.registryValue('ignoreChannel',channel):
continue
action = self.registryValue('lastActionTaken',channel=channel)
if action > 0:
if time.time()-action > duration:
channels.append('%s: %s' % (channel,time.strftime('%Y-%m-%d %H:%M:%S GMT',time.gmtime(action))))
else:
channels.append(channel)
irc.replies(channels,None,None,False)
checkactions = wrap(checkactions,['owner','positiveInt'])
def netsplit (self,irc,msg,args,duration):
"""<duration>
entering netsplit mode for <duration> (in seconds)"""
i = self.getIrc(irc)
if i.netsplit:
i.netsplit = time.time()+duration
irc.reply('Already in netsplit mode, reset, %ss more' % duration)
else:
i.netsplit = time.time()+duration
self.logChannel(irc,"INFO: netsplit activated for %ss by %s: some abuses are ignored" % (duration,msg.nick))
irc.replySuccess()
netsplit = wrap(netsplit,['owner','positiveInt'])
def checkpattern (self,irc,msg,args,text):
""" <text>
returns permanents patterns triggered by <text>"""
i = self.getIrc(irc)
patterns = []
for k in i.patterns:
pattern = i.patterns[k]
if pattern.match(text):
patterns.append('#%s' % pattern.uid)
if len(patterns):
irc.queueMsg(ircmsgs.privmsg(msg.nick,'%s matches: %s' % (len(patterns),', '.join(patterns))))
else:
irc.reply('No matches')
checkpattern = wrap(checkpattern,['owner','text'])
def lspattern (self,irc,msg,args,optlist,pattern):
"""[--deep] <id|pattern>
returns patterns which matches pattern or info about pattern #id, use --deep to search on deactivated patterns, * to return all pattern"""
i = self.getIrc(irc)
deep = pattern == '*'
for (option, arg) in optlist:
if option == 'deep':
deep = True
results = i.ls(self.getDb(irc.network),pattern,deep)
if len(results):
if deep or pattern == '*':
for r in results:
irc.queueMsg(ircmsgs.privmsg(msg.nick,r))
else:
irc.replies(results,None,None,False)
else:
irc.reply('no pattern found')
lspattern = wrap(lspattern,['owner',getopts({'deep': ''}),'text'])
def rmpattern (self,irc,msg,args,ids):
"""<id> [<id>]
remove permanent pattern by id"""
i = self.getIrc(irc)
results = []
for id in ids:
result = i.remove(self.getDb(irc.network),id)
if result:
results.append('#%s' % id)
self.logChannel(irc,'PATTERN: %s deleted %s' % (msg.nick,','.join(results)))
irc.replySuccess()
rmpattern = wrap(rmpattern,['owner',many('positiveInt')])
def addpattern (self,irc,msg,args,limit,life,pattern):
"""<limit> <life> <pattern>
add a permanent <pattern> : kline after <limit> calls raised during <life> seconds,
for immediate kline use limit 0"""
i = self.getIrc(irc)
pattern = pattern.lower()
result = i.add(self.getDb(irc.network),msg.prefix,pattern,limit,life,False)
self.logChannel(irc,'PATTERN: %s added #%s : "%s" %s/%ss' % (msg.nick,result,pattern,limit,life))
irc.reply('#%s added' % result)
addpattern = wrap(addpattern,['owner','nonNegativeInt','positiveInt','text'])
def addregexpattern (self,irc,msg,args,limit,life,pattern):
"""<limit> <life> /<pattern>/
add a permanent /<pattern>/ to kline after <limit> calls raised during <life> seconds,
for immediate kline use limit 0"""
i = self.getIrc(irc)
result = i.add(self.getDb(irc.network),msg.prefix,pattern[0],limit,life,True)
self.logChannel(irc,'PATTERN: %s added #%s : "%s" %s/%ss' % (msg.nick,result,pattern[0],limit,life))
irc.reply('#%s added' % result)
addregexpattern = wrap(addregexpattern,['owner','nonNegativeInt','positiveInt','getPatternAndMatcher'])
def editpattern (self,irc,msg,args,uid,limit,life,comment):
"""<id> <limit> <life> [<comment>]
edit #<id> with new <limit> <life> and <comment>"""
i = self.getIrc(irc)
result = i.edit(self.getDb(irc.network),uid,limit,life,comment)
if result:
if comment:
self.logChannel(irc,'PATTERN: %s edited #%s with %s/%ss (%s)' % (msg.nick,uid,limit,life,comment))
else:
self.logChannel(irc,'PATTERN: %s edited #%s with %s/%ss' % (msg.nick,uid,limit,life))
irc.replySuccess()
else:
irc.reply("#%s doesn't exist")
editpattern = wrap(editpattern,['owner','positiveInt','nonNegativeInt','positiveInt',optional('text')])
def togglepattern (self,irc,msg,args,uid,toggle):
"""<id> <boolean>
activate or deactivate #<id>"""
i = self.getIrc(irc)
result = i.toggle(self.getDb(irc.network),uid,msg.prefix,toggle)
if result:
if toggle:
self.logChannel(irc,'PATTERN: %s enabled #%s' % (msg.nick,uid))
else:
self.logChannel(irc,'PATTERN: %s disabled #%s' % (msg.nick,uid))
irc.replySuccess()
else:
irc.reply("#%s doesn't exist or is already in requested state" % uid)
togglepattern = wrap(togglepattern,['owner','positiveInt','boolean'])
def lstmp (self,irc,msg,args,channel):
"""[<channel>]
returns temporary patterns for given channel"""
i = self.getIrc(irc)
if channel in i.channels:
chan = self.getChan(irc,channel)
if chan.patterns:
patterns = list(chan.patterns)
if len(patterns):
irc.reply('[%s] %s patterns : %s' % (channel,len(patterns),', '.join(patterns)))
else:
irc.reply('[%s] no active pattern' % channel)
else:
irc.reply('[%s] no active pattern' % channel)
else:
irc.reply('[%s] is unknown' % channel)
lstmp = wrap(lstmp,['op'])
def dnsbl (self,irc,msg,args,ips,comment):
"""<ip> [,<ip>] [<comment>]
add <ips> on dronebl"""
for ip in ips:
if utils.net.isIPV4(ip):
t = world.SupyThread(target=self.fillDnsbl,name=format('fillDnsbl %s', ip),args=(irc,ip,self.registryValue('droneblHost'),self.registryValue('droneblKey'),comment))
t.setDaemon(True)
t.start()
irc.replySuccess()
dnsbl = wrap(dnsbl,['owner',commalist('ip'),rest('text')])
def rmdnsbl (self,irc,msg,args,ips):
"""<ip> [<ip>]
remove <ips> from dronebl"""
for ip in ips:
if utils.net.isIPV4(ip):
t = world.SupyThread(target=self.removeDnsbl,name=format('rmDnsbl %s', ip),args=(irc,ip,self.registryValue('droneblHost'),self.registryValue('droneblKey')))
t.setDaemon(True)
t.start()
irc.replySuccess()
rmdnsbl = wrap(rmdnsbl,['owner',many('ip')])
def checkRegistar (self,irc,nick,ip):
try:
j = urllib.urlopen('http://legacy.iphub.info/api.php?ip=%s&showtype=4' % ip)
r = j.read()
data = json.loads(r)
self.log.debug('%s registar is %s' % (ip,r))
if 'asn' in data and len(data['asn']):
a = data['asn'].split(' ')
asn = a.pop(0)
detail = ' '.join(a)
irc.queueMsg(ircmsgs.privmsg(nick,"%s: http://bgp.he.net/%s#_prefixes (%s)" % (ip,asn,detail)))
except:
j = ''
def registar (self,irc,msg,args,ips):
"""<ip> [<ip>]
returns registar of ips provided"""
for ip in ips:
if utils.net.isIPV4(ip):
t = world.SupyThread(target=self.checkRegistar,name=format('checkRegistar %s', ip),args=(irc,msg.nick,ip))
t.setDaemon(True)
t.start()
irc.replySuccess()
registar = wrap(registar,['owner',many('ip')])
def addtmp (self,irc,msg,args,channel,text):
"""[<channel>] <message>
add a string in channel's temporary patterns"""
text = text.lower()
i = self.getIrc(irc)
if channel in i.channels:
chan = self.getChan(irc,channel)
shareID = self.registryValue('shareComputedPatternID',channel=channel)
if shareID == -1:
life = self.registryValue('computedPatternLife',channel=channel)
if not chan.patterns:
chan.patterns = utils.structures.TimeoutQueue(life)
elif chan.patterns.timeout != life:
chan.patterns.setTimeout(life)
chan.patterns.enqueue(text)
self.logChannel(irc,'PATTERN: [%s] added tmp "%s" for %ss by %s' % (channel,text,life,msg.nick))
irc.replySuccess()
else:
n = 0
l = self.registryValue('computedPatternLife',channel=channel)
for channel in i.channels:
chan = self.getChan(irc,channel)
id = self.registryValue('shareComputedPatternID',channel=channel)
if id == shareID:
life = self.registryValue('computedPatternLife',channel=channel)
if not chan.patterns:
chan.patterns = utils.structures.TimeoutQueue(life)
elif chan.patterns.timeout != life:
chan.patterns.setTimeout(life)
chan.patterns.enqueue(text)
n = n + 1
self.logChannel(irc,'PATTERN: added tmp "%s" for %ss by %s in %s channels' % (text,l,msg.nick,n))
irc.replySuccess()
else:
irc.reply('unknown channel')
addtmp = wrap(addtmp,['op','text'])
def addglobaltmp (self,irc,msg,args,text):
"""<text>
add <text> to temporary patterns in all channels"""
text = text.lower()
i = self.getIrc(irc)
n = 0
for channel in i.channels:
chan = self.getChan(irc,channel)
life = self.registryValue('computedPatternLife',channel=channel)
if not chan.patterns:
chan.patterns = utils.structures.TimeoutQueue(life)
elif chan.patterns.timeout != life:
chan.patterns.setTimeout(life)
chan.patterns.enqueue(text)
n = n + 1
self.logChannel(irc,'PATTERN: added tmp "%s" for %ss by %s in %s channels' % (text,life,msg.nick,n))
irc.replySuccess()
addglobaltmp = wrap(addglobaltmp,['owner','text'])
def rmtmp (self,irc,msg,args,channel):
"""[<channel>]
remove temporary patterns for given channel"""
i = self.getIrc(irc)
if channel in i.channels:
chan = self.getChan(irc,channel)
shareID = self.registryValue('shareComputedPatternID',channel=channel)
if shareID != -1:
n = 0
for channel in i.channels:
id = self.registryValue('shareComputedPatternID',channel=channel)
if id == shareID:
if i.channels[channel].patterns:
i.channels[channel].patterns.reset()
n = n + 1
self.logChannel(irc,'PATTERN: removed tmp patterns in %s channels by %s' % (n,msg.nick))
elif chan.patterns:
l = len(chan.patterns)
chan.patterns.reset()
if l:
self.logChannel(irc,'PATTERN: [%s] removed %s tmp pattern by %s' % (channel,l,msg.nick))
irc.replySuccess()
else:
irc.reply('[%s] no active pattern' % channel)
else:
irc.reply('[%s] no active pattern' % channel)
else:
irc.reply('unknown channel')
rmtmp = wrap(rmtmp,['op'])
def unkline (self,irc,msg,args,nick):
"""<nick>
request unkline of <nick>, klined recently from your channel
"""
channels = []
ops = []