forked from fladd/py-fishcrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fishcrypt.py
2065 lines (1807 loc) · 74.6 KB
/
fishcrypt.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 -*-
#
# FiSH/Mircryption clone for XChat/HexChat in 100% Python
#
# Requirements: PyCrypto, and Python 2 (>=2.5)
#
# Copyright 2011 Nam T. Nguyen ( http://www.vithon.org/forum/Thread/show/54 )
# Released under the BSD license
#
# rewritten by trubo/segfault for irc.prooops.eu #py-fishcrypt trubo00@gmail.com
#
# fixes by fladd <fladd@fladd.de>
#
# irccrypt module is copyright 2009 Bjorn Edstrom ( http://www.bjrn.se/ircsrp )
# with modification from Nam T. Nguyen and trubo
#
# Changelog:
# * 5.31
# + Minor bugfix when sending messages
#
# * 5.30
# + Decrypt own messages (for https://github.com/TingPing/plugins/blob/master/HexChat/mymsg.py)
#
# * 5.20
# + Added authentification hash for DH key exchange
#
# * 5.10
# + Plugin will now load correctly on Windows
# + Fixed bug that crashed the plugin in some cases
# * 5.00
# + Fixed compatibility for networks with identify-msg (e.g. freenode) in key exchange (fladd)
# + Added FiSHLiM unload (fladd)
# + Changed /ME+ to be compatibile with FiSHLiM (fladd)
#
# * 4.21
# + Fixed Empty Action /me
# * 4.20
# + Added support for Stealth mode >> no KeyExchange possible [/SET FISHSTEALTH True/False]
# * 4.19
# + Added support for mIRC CBC KeyExchange, https://github.com/flakes/mirc_fish_10/
# * 4.18
# + Buffix Topic use key from channel not context
# * 4.17
# + CBC Default
# * 4.16
# + Bugfix Topic
# + config plaintextmarker in keyprotection
# + config parameter DEFAULTPROTECT and DEFAULTCBC
# * 4.15
# + Destroy object
# * 4.14
# + Stable
# * 4.13
# + new NickTrace
# + wildcard /KEY search
# + msg send to other target are marked with "Message Send"
# + Tab Completion for udpate command
# + using strxor from the pyCrypto packages if available
# + some performance enhancements
# + Pseudo Threading for Windows
# * 4.12
# + Beta Support
# * 4.11
# + BugFix /UPDATE
# * 4.10
# + BugFix /FISHSETUP
# * 4.09
# + BugFix again /FISHSETUP /UPDATE
# * 4.08
# + BugFix settings are not saved
# * 4.07
# + new Update function
# * 4.06
# + Small BugFixes
# * 4.05
# + BugFix Windows has no full xchatdir now using scriptpath for fish3.pickle
# * 4.04
# + BugFix notices
# * 4.03
# + BugFix /FISHSETUP
# * 4.02
# + noproxy oprions for /FISHSETUP
# * 4.01
# + BugFix pyBlowfish
# * 4.00
# + Windows Support with pyBlowfish.py and irccrypt now included
# * 3.31
# + BugFix unpack large messages
# * 3.30
# + Added chksum for irccrypt with __module_name__ tags http://pastebin.com/vTrWyBKv
# * 3.29
# + BugFix Update and Threaded Update
# * 3.28
# + /SET [fishcrypt]
# * 3.27
# + BugFix /ME+ in Query
# * 3.26
# + Updates over Proxy
# * 3.25
# + crypted /ME+
# * 3.24
# + BugFix topic 332
# * 3.23
# + BugFix notice send
# * 3.22
# + BugFix
# * 3.21
# + BugFix
# * 3.20
# + partly show incomplete messages
# * 3.19
# + /FISHUPDATE update switch
# * 3.18
# + AUTO CBC Mode only in querys
# * 3.17
# + Highlight Bugfix
# * 3.16
# + Highlight
# * 3.15
# + Bugfixes
# * 3.13
# + split lines if longer then 334 Chars
#
# * 3.12
# + add PROTECTKEY to block dh1080 keyexchange on known Keys ( thx ^V^ )
#
# * 3.11
# + add Keystorage encryption
#to
# * 3.10
# + Fix Path for Windows and provide download URL for pycrypto
#
# * 3.09
# + Bugfixes
#
# * 3.08:
# + some docu added
#
# * 3.07:
# + fixed notice in channel not send to user
#
# * 3.06:
# + support for /msg /msg+ /notice /notice+ (trubo)
#
# * 3.04:
# + new lock design (by target) (trubo)
#
# * 3.01:
# + change switches to be compatible with fish.secure.la/xchat/FiSH-XChat.txt (trubo)
#
# * 3.0:
# + rewritten to class XChatCrypt (trubo)
#
# * 2.0:
# + Suport network mask in /key command
# + Alias key_exchange to keyx
# + Support plaintext marker '+p '
# + Support encrypted key store
#
# * 1.0:
# + Initial release
#
###
__module_name__ = 'fishcrypt'
__module_version__ = '5.31'
__module_description__ = 'fish encryption in pure python'
ISBETA = ""
UPDATEURL = 'https://raw.githubusercontent.com/fladd/py-fishcrypt/master/fishcrypt.py'
BETAUPDATEURL = 'https://raw.githubusercontent.com/fladd/py-fishcrypt/master/fishcrypt.py'
PYBLOWFISHURL = "https://raw.githubusercontent.com/fladd/py-fishcrypt/master/pyBlowfish.py"
SOCKSIPYURL = 'http://socksipy-branch.googlecode.com/svn/trunk/socks.py'
ONMODES = ["Y","y","j","J","1","yes","on","ON","Yes","True","true"]
YESNO = lambda x: (x==0 and "N") or "Y"
import sys
import os
import re
import base64
import hashlib
import struct
import time
from math import log
try:
import xchat
except ImportError:
sys.exit("should be run from xchat plugin with python enabled")
try:
import cPickle as pickle
except ImportError:
import pickle
## check for Windows
import platform
sep = "/"
isWindows = (platform.system() == "Windows")
if isWindows:
sep = "\\"
## append current path
if isWindows:
# Try XChat
scriptname = os.getenv('APPDATA')+"\\XChat\\addons\\fishcrypt.py"
if not os.path.exists(scriptname):
# Try HexChat
scriptname = os.getenv('APPDATA')+"\\HexChat\\addons\\fishcrypt.py"
if not os.path.exists(scriptname):
# Try portable install
scriptname = sys.path[0]+"\\addons\\fishcrypt.py"
else:
import inspect
scriptname = inspect.currentframe().f_code.co_filename
script = "".join(scriptname.split(sep)[-1:])
path = sep.join(scriptname.split(sep)[:-1])
sys.path.insert(1,path)
SCRIPTCHKSUM = hashlib.sha1(open(scriptname,'rb').read()).hexdigest()
REQUIRESETUP = False
try:
import Crypto.Cipher.Blowfish as cBlowfish
except ImportError:
try:
import pyBlowfish as cBlowfish
pyBlowfishlocation = "%s.py" % str(cBlowfish)[str(cBlowfish).find("from '")+6:str(cBlowfish).find(".py")]
chksum = hashlib.sha1(open(pyBlowfishlocation,'rb').read()).hexdigest()
validVersion = {'35c1b6cd5af14add86dc0cf3f0309a185c308dcd':0.4,'877ae9de309685c975a6d120760c1ff9b4c55719':0.5, '57117e7c9c7649bf490589b7ae06a140e82664c6':0.5}.get(chksum,-1)
if validVersion == -1:
print "\0034** Loaded pyBlowfish.py with checksum: %s is untrusted" % (chksum)
else:
if validVersion < 0.5:
print "\0034** Loaded pyBlowfish.py (%.1f) with checksum: %s is too old" % (validVersion,chksum)
REQUIRESETUP = True
else:
print "\0033** Loaded pyBlowfish.py Version %.1f with checksum: %s" % (validVersion,chksum)
except ImportError:
import platform
print "\002\0034No Blowfish implementation"
if not isWindows:
print "This module requires PyCrypto / The Python Cryptographic Toolkit."
print "Get it from http://www.dlitz.net/software/pycrypto/. or"
else:
path = path.replace(sep,sep*2)
print "Download Python only Blowfish at %s" % PYBLOWFISHURL
print "or type \002/FISHSETUP\002 for automatic install of that"
REQUIRESETUP = True
try:
xchat.command("UNLOAD FiSHLiM")
except:
pass
try:
from Crypto.Util.strxor import strxor as xorstring
except ImportError:
## use slower python only xor
def xorstring(a, b): # Slow.
"""xor string a and b, both of length blocksize."""
xored = []
for i in xrange(8):
xored.append( chr(ord(a[i]) ^ ord(b[i])) )
return "".join(xored)
if not isWindows:
from threading import Thread
else:
class Thread:
def __init__(self,target=None,args=[],kwargs={},name='Thread*'):
self.__target = target
self.__args = args
self.__kwargs = kwargs
self.__name = name
self.__hook = None
def start(self):
print "-Starting Pseudo Thread"
self.__hook = xchat.hook_timer(1,self.__thread,(self.__target,self.__args,self.__kwargs))
def __thread(self,userdata):
try:
_thread,args,kwargs = userdata
_thread(*args,**kwargs)
finally:
xchat.unhook(self.__hook)
self.__hook = None
return False
import socket
REALSOCKET = socket.socket
def makedict(**kwargs):
return kwargs
COLOR = makedict(white="\0030", black="\0031", blue="\0032", red="\0034",
dred="\0035", purple="\0036", dyellow="\0037", yellow="\0038", bgreen="\0039",
dgreen="\00310", green="\00311", bpurple="\00313", dgrey="\00314",
lgrey="\00315", close="\003")
class SecretKey(object):
def __init__(self, dh, key=None,protectmode=False,cbcmode=False):
self.dh = dh
self.key = key
self.cbc_mode = cbcmode
self.protect_mode = protectmode
self.active = True
self.cipher = 0
self.keyname = (None,None)
def __str__(self):
return "%s@%s" % self.keyname
def proxyload(_thread,_useproxy,doExtra):
socket.socket = REALSOCKET
if xchat.get_prefs('net_proxy_type') > 0 and _useproxy:
try:
import socks
except ImportError:
print "\0034python-socksipy not installed"
print "sudo apt-get install python-socksipy"
print "or install %s" % SOCKSIPYURL
print "or just use the noproxy option with /FISHUPDATE and /FISHSETUP"
return xchat.EAT_ALL
proxytype = [0,-1,socks.PROXY_TYPE_SOCKS4,socks.PROXY_TYPE_SOCKS5,socks.PROXY_TYPE_HTTP,-1][xchat.get_prefs('net_proxy_type')]
nameproxytype = ['','Socks4a','Socks5','HTTP','']
if proxytype < 0:
print "\0034Proxytype not suported for updates"
return xchat.EAT_ALL
proxyuser = xchat.get_prefs('net_proxy_user')
proxypass = xchat.get_prefs('net_proxy_pass')
if len(proxyuser) < 1 or len(proxypass) < 1:
proyxuser = proxypass = None
socks.setdefaultproxy(proxytype,xchat.get_prefs('net_proxy_host'),xchat.get_prefs('net_proxy_port'),rdns=True,username=proxyuser,password=proxypass)
print "\00310using xchat proxy settings \0037Type: %s Host: %s Port: %s" % (nameproxytype[proxytype],xchat.get_prefs('net_proxy_host'),xchat.get_prefs('net_proxy_port'))
## Replace default socket
socket.socket = socks.socksocket
import urllib2
_thread(urllib2,doExtra)
def destroyObject(userdata):
global loadObj
del loadObj
return False
class XChatCrypt:
def __init__(self):
print "%sFishcrypt Version %s %s\003" % (COLOR['blue'],__module_version__,ISBETA)
print "SHA1 checksum: %r" % SCRIPTCHKSUM
self.active = True
self.__KeyMap = {}
self.__TargetMap = {}
self.__lockMAP = {}
self.config = {
'PLAINTEXTMARKER' : '+p',
'DEFAULTCBC' : True,
'DEFAULTPROTECT' : False,
'FISHUPDATETIMEOUT' : 30,
'MAXMESSAGELENGTH' : 300,
'USEPROXYUPDATE' : True,
'FISHBETAVERSION': True,
'FISHDEVELOPDEBUG': False,
'AUTOBACKUP': True,
'FISHSTEALTH': False,
}
self.status = {
'CHKPW': None,
'DBPASSWD' : None,
'CRYPTDB' : False,
'LOADED' : True
}
self.__update_thread = None
self._updatedSource = None
self.__hooks = []
self.__hooks.append(xchat.hook_command('SETKEY', self.set_key, help='set a new key for a nick or channel /SETKEY <nick>/#chan [new_key]'))
self.__hooks.append(xchat.hook_command('KEYX', self.key_exchange, help='exchange a new pub key, /KEYX <nick>'))
self.__hooks.append(xchat.hook_command('KEY', self.show_key, help='list key of a nick or channel or all (*), /KEY [nick/#chan/*]' ))
self.__hooks.append(xchat.hook_command('DELKEY', self.del_key, help='remove key, /DELKEY <nick>/#chan/*'))
self.__hooks.append(xchat.hook_command('CBCMODE', self.set_cbc, help='set or shows cbc mode for (current) channel/nick , /CBCMODE [<nick>] <0|1>'))
self.__hooks.append(xchat.hook_command('PROTECTKEY', self.set_protect, help='sets or shows key protection mode for (current) nick, /PROTECTKEY [<nick>] <0|1>'))
self.__hooks.append(xchat.hook_command('ENCRYPT', self.set_act, help='set or shows encryption on for (current) channel/nick , /ENCRYPT [<nick>] <0|1>'))
self.__hooks.append(xchat.hook_command('PRNCRYPT', self.prn_crypt, help='print msg encrpyted localy , /PRNCRYPT <msg>'))
self.__hooks.append(xchat.hook_command('PRNDECRYPT', self.prn_decrypt, help='print msg decrpyted localy , /PRNDECRYPT <msg>'))
self.__hooks.append(xchat.hook_command('UPDATE', self.update, help='Update this Script'))
self.__hooks.append(xchat.hook_command('FISHUPDATE', self.fishupdate, help='Update this Script'))
## check for password sets
self.__hooks.append(xchat.hook_command('SET',self.settings))
self.__hooks.append(xchat.hook_command('DBPASS',self.set_dbpass))
self.__hooks.append(xchat.hook_command('DBLOAD',self.set_dbload))
self.__hooks.append(xchat.hook_command('HELP',self.get_help))
self.__hooks.append(xchat.hook_command('', self.outMessage))
self.__hooks.append(xchat.hook_command('ME+', self.outMessageCmd))
self.__hooks.append(xchat.hook_command('MSG', self.outMessageCmd))
self.__hooks.append(xchat.hook_command('MSG+', self.outMessageForce))
self.__hooks.append(xchat.hook_command('NOTICE', self.outMessageCmd))
self.__hooks.append(xchat.hook_command('NOTICE+', self.outMessageForce))
self.__hooks.append(xchat.hook_server('notice', self.on_notice,priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_server('332', self.server_332_topic,priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_print('Key Press',self.tabComplete))
self.__hooks.append(xchat.hook_print('Notice Send',self.on_notice_send, 'Notice',priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_print('Change Nick', self.nick_trace))
self.__hooks.append(xchat.hook_print('Channel Action', self.inMessage, 'Channel Action',priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_print('Private Action to Dialog', self.inMessage, 'Private Action to Dialog',priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_print('Private Action ', self.inMessage, 'Private Action',priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_print('Channel Message', self.inMessage, 'Channel Message',priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_print('Private Message to Dialog', self.inMessage, 'Private Message to Dialog',priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_print('Private Message', self.inMessage, 'Private Message',priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_print('Your Message', self.inMessage, 'Your Message',priority=xchat.PRI_HIGHEST))
self.__hooks.append(xchat.hook_unload(self.__destroy))
self.loadDB()
def __destroy(self,userdata):
for hook in self.__hooks:
xchat.unhook(hook)
destroyObject(None)
def __del__(self):
print "\00311fishcrypt.py successful unloaded"
def get_help(self,word, word_eol, userdata):
if len(word) < 2:
print "\n\0033 For fishcrypt.py help type /HELP FISHCRYPT"
return xchat.EAT_NONE
if word[1].upper() == "FISHCRYPT":
print ""
print "\002\0032 **** fishcrypt.py Version: %s %s ****" % (__module_version__,ISBETA)
if self.config['FISHBETAVERSION']:
print "\0036Beta download %s" % (BETAUPDATEURL)
print "\0036 %s" % UPDATEURL
print "\n"
print " \002\00314***************** Fishcrypt Help ********************"
print " -----------------------------------------------------"
print "/MSG+ \00314send crypted msg regardless of /ENCRYPT setting"
print "/NOTICE+ \00314send crypted notice regardless of /ENCRYPT setting"
print "/ME+ \00314send crypted CTCP ACTION"
print "/SETKEY \00314set a new key for a nick or channel"
print "/KEYX \00314exchange pubkey for dialog"
print "/KEY \00314show Keys"
print "/DELKEY \00314delete Keys"
print "/CBCMODE \00314enable/disable CBC Mode for this Key"
print "/ENCRYPT \00314enable/disable encryption for this Key"
print "/PROTECTKEY \00314enable/disable protection for keyx key exchange"
print "/DBPASS \00314set/change the passphrase for the Key Storage"
print "/DBLOAD \00314loads the Key Storage"
print "/PRNDECRYPT \00314decrypts messages localy"
print "/PRNCRYPT \00314encrypts messages localy"
print "/FISHUPDATE \00314check online for new Version and update"
print "/SET [fishcrypt] \00314show/set fishcrypt settings"
return xchat.EAT_ALL
def tabComplete(self,word, word_eol, userdata):
if word[0] not in ["65289","65056"]:
return xchat.EAT_NONE
input = xchat.get_info('inputbox')
if input.upper().startswith("/UPDATE FISHCRYPT I"):
newinput = "/UPDATE FISHCRYPT INSTALL"
elif input.upper().startswith("/UPDATE FISHCRYPT D"):
newinput = "/UPDATE FISHCRYPT DIFF"
elif input.upper().startswith("/UPDATE FISHCRYPT C"):
newinput = "/UPDATE FISHCRYPT CHANGES"
elif input.upper().startswith("/UPDATE FISHCRYPT L"):
newinput = "/UPDATE FISHCRYPT LOAD"
elif input.upper() == "/UPDATE FISHCRYPT ":
print "LOAD INSTALL DIFF CHANGES"
return xchat.EAT_NONE
elif input.upper().startswith("/UPDATE F"):
newinput = "/UPDATE FISHCRYPT "
elif input.upper().startswith("/HELP F"):
newinput = "/HELP FISHCRYPT "
elif input.upper().startswith("/SET F"):
newinput = "/SET FISHCRYPT "
else:
return xchat.EAT_NONE
xchat.command("SETTEXT %s" % newinput)
xchat.command("SETCURSOR %d" % len(newinput))
return xchat.EAT_PLUGIN
def fishupdate(self,word, word_eol, userdata):
return self.update(["UPDATE","FISHCRYPT","INSTALL"],None,None)
def update(self,word, word_eol, userdata):
useproxy = self.config['USEPROXYUPDATE']
if len(word) <3:
print "\00313Fishcrypt.py Updater"
print "\00313/UPDATE FISHCRYPT [LOAD,CHANGES,DIFF,INSTALL]"
return xchat.EAT_XCHAT
if word[1].upper() != "FISHCRYPT":
return xchat.EAT_NONE
if self.__update_thread:
print "\0034Update Thread already running"
return xchat.EAT_ALL
_doExtra = None
if word[2].lower() == "diff":
if self._updatedSource:
self._updateDiff(xchat.get_context())
else:
_doExtra = self._updateDiff
if word[2].lower() == "changes":
if self._updatedSource:
self._updateChanges(xchat.get_context())
else:
_doExtra = self._updateChanges
if word[2].lower() == "install":
if self._updatedSource:
self._updateInstall(xchat.get_context())
else:
_doExtra = self._updateInstall
if word[2].lower() == "load" or _doExtra:
proxyload(self._update,useproxy,_doExtra)
return xchat.EAT_ALL
def _update(self,urllib2,doExtra):
self.__update_thread = Thread(target=self.__update,kwargs={'urllib2':urllib2,'context':xchat.get_context(),'doExtra':doExtra},name='fishcrypt_update')
self.__update_thread.start()
def _updateInstall(self,context):
try:
try:
__fd = open(scriptname,"wb")
__fd.write(self._updatedSource)
finally:
__fd.close()
context.prnt( "\00310UPDATE Complete \r\nplease reload the script (/py reload %s)" % (script,) )
except:
context.prnt( "\002\0034UPDATE FAILED" )
raise
def _updateDiff(self,context):
currentscript = open(scriptname,"rb").read()
import difflib
for line in difflib.unified_diff(currentscript.splitlines(1),self._updatedSource.splitlines(1)):
context.prnt( line)
def _updateChanges(self,context):
currentscript = open(scriptname,"rb").read()
import difflib
for line in difflib.ndiff(currentscript[currentscript.find("# Changelog:"):currentscript.find("__module_name__")].splitlines(1),self._updatedSource[self._updatedSource.find("# Changelog:"):self._updatedSource.find("__module_name__")].splitlines(1)):
if len(line) > 2:
if line[0] in ["+","-"]:
context.prnt( line[2:])
def __update(self,urllib2,context,doExtra):
url = UPDATEURL
if self.config['FISHBETAVERSION']:
url = BETAUPDATEURL
context.prnt("\0038.....checking for updates at %r... please wait ...." % url)
try:
try:
__updatescript = urllib2.urlopen(url,timeout=self.config['FISHUPDATETIMEOUT']).read()
__updateversion = re.search("__module_version__ = '([0-9]+\.[0-9]+)'",__updatescript)
if __updateversion:
if float(__module_version__) < float(__updateversion.group(1)) or ISBETA != "":
updatechksum = hashlib.sha1(__updatescript).hexdigest()
if SCRIPTCHKSUM <> updatechksum:
self._updatedSource = __updatescript
context.prnt( "\00310Download Version %s with checksum %r complete" % (__updateversion.group(1),updatechksum))
else:
context.prnt( "\00310No new version available - checksums match")
else:
context.prnt( "\0032%sVersion %s is up to date (found Version %s)" % (__module_name__,__module_version__,__updateversion.group(1)) )
else:
context.prnt( "\0034NO VALID PLUGIN FOUND AT %s" % (url,) )
except urllib2.URLError,err:
context.prnt( "\002\0034LOAD FAILED" )
context.prnt( "%r" % (err,) )
except:
context.prnt( "\002\0034LOAD FAILED" )
context.prnt("%r" % (sys.exc_info(),))
finally:
self.__update_thread = None
context.prnt( "\00310Update Thread finished" )
if doExtra and self._updatedSource:
doExtra(context)
## Load key storage
def loadDB(self):
data = db = None
try:
try:
hnd = open(os.path.join(path,'fish3.pickle'),'rb')
data = hnd.read()
## set DB loaded to False as we have a file we don't want to create a new
self.status['LOADED'] = False
except:
return
finally:
try:
hnd.close()
except:
pass
if data:
try:
db = pickle.loads(data)
print "%sUnencrypted Key Storage loaded" % (COLOR['bpurple'],)
except pickle.UnpicklingError:
## ignore if file is invalid
if data.startswith("+OK *"):
self.status['CRYPTDB'] = True
if self.status['DBPASSWD']:
try:
algo = BlowfishCBC(self.status['DBPASSWD'])
decrypted = mircryption_cbc_unpack(data,algo)
db = pickle.loads(decrypted)
print "%sEncrypted Key Storage loaded" % (COLOR['green'],)
except pickle.UnpicklingError:
self.status['DBPASSWD'] = None
print "%sKey Storage can't be loaded with this password" % (COLOR['dred'],)
print "use /DBLOAD to load it later"
else:
xchat.command('GETSTR "" "SET fishcrypt_passload" "Enter your Key Storage Password"')
pass
if type(db) == dict:
self.status['LOADED'] = True
## save temp keymap
oldKeyMap = self.__KeyMap
oldTargetMap = self.__TargetMap
## fill dict with the loaded Keymap
self.__KeyMap = db.get("KeyMap",{})
self.__TargetMap = db.get("TargetMap",{})
self.__KeyMap.update(oldKeyMap)
self.__TargetMap.update(oldTargetMap)
for key in self.__KeyMap.keys():
self.__KeyMap[key].keyname = key
if not hasattr(self.__KeyMap[key],'protect_mode'):
self.__KeyMap[key].protect_mode = False
self.cleanUpTargetMap()
## only import valid config values
for key in self.config.keys():
try:
self.config[key] = db["Config"][key]
except KeyError:
pass
if self.config['FISHDEVELOPDEBUG']:
self.__hooks.append(xchat.hook_command('FISHEVAL',self.__evaldebug))
def cleanUpTargetMap(self):
## DB Cleanup
for network in self.__TargetMap.values():
for target,value in network.items():
if type(value[1]) <> SecretKey or value[0] < time.time() - 60*60*24*7 or value[1] not in self.__KeyMap.values():
del network[target]
print "Expired: %r %r" % (target,value)
## save keys to storage
def saveDB(self):
self.cleanUpTargetMap()
if not self.status['LOADED']:
print "Key Storage not loaded, no save. use /DBLOAD to load it"
return
try:
data = pickle.dumps({
'KeyMap': self.__KeyMap,
'TargetMap': self.__TargetMap,
'Config': self.config,
'Version': __module_version__
})
hnd = open(os.path.join(path,'fish3.pickle'),'wb')
if self.status['DBPASSWD']:
algo = BlowfishCBC(self.status['DBPASSWD'])
encrypted = mircryption_cbc_pack(data,algo)
data = encrypted
self.status['CRYPTDB'] = True
else:
self.status['CRYPTDB'] = False
hnd.write(data)
finally:
hnd.close()
def __evaldebug(self,word, word_eol, userdata):
eval(compile(word_eol[1],'develeval','exec'))
return xchat.EAT_ALL
def set_dbload(self,word, word_eol, userdata):
self.loadDB()
return xchat.EAT_ALL
def set_dbpass(self,word, word_eol, userdata):
xchat.command('GETSTR "" "SET fishcrypt_passpre" "New Password"')
return xchat.EAT_ALL
## set keydb passwd
def settings(self,word, word_eol, userdata):
fishonly = False
if len(word) == 2:
if word[1].upper() == "FISHCRYPT":
fishonly = True
if len(word) < 2 or fishonly:
## not for us
#print "fishcrypt_pass%s%s%s: \003%r" % (COLOR['blue'],"."*16,COLOR['green'],self.status['DBPASSWD'])
for key in self.config:
keyname = "%s%s" % (key,"."*20)
print "\00312%.29s: %s" % (keyname,str(self.config[key]))
if fishonly:
return xchat.EAT_ALL
return xchat.EAT_NONE
if word[1] == "fishcrypt_passpre":
if len(word) == 2:
self.status['CHKPW'] = ""
else:
self.status['CHKPW'] = word_eol[2]
xchat.command('GETSTR "" "SET fishcrypt_pass" "Repeat the Password"')
return xchat.EAT_ALL
if word[1] == "fishcrypt_pass":
if len(word) == 2:
if self.status['CHKPW'] <> "" and self.status['CHKPW'] <> None:
print "Passwords don't match"
self.status['CHKPW'] = None
return xchat.EAT_ALL
self.status['DBPASSWD'] = None
print "%sPassword removed and Key Storage decrypted" % (COLOR['dred'],)
print "%sWarning Keys are plaintext" % (COLOR['dred'],)
else:
if self.status['CHKPW'] <> None and self.status['CHKPW'] <> word_eol[2]:
print "Passwords don't match"
self.status['CHKPW'] = None
return xchat.EAT_ALL
if len(word_eol[2]) < 8 or len(word_eol[2]) > 56:
print "Passwords must be between 8 and 56 chars"
self.status['CHKPW'] = None
return xchat.EAT_ALL
self.status['DBPASSWD'] = word_eol[2]
## don't show the pw on console if set per GETSTR
if self.status['CHKPW'] == None:
print "%sPassword for Key Storage encryption set to %r" % (COLOR['dred'],self.status['DBPASSWD'])
else:
print "%sKey Storage encrypted" % (COLOR['dred'])
self.status['CHKPW'] = None
self.saveDB()
return xchat.EAT_ALL
if word[1] == "fishcrypt_passload":
if len(word) > 2:
if len(word_eol[2]) < 8 or len(word_eol[2]) > 56:
print "Password not between 8 and 56 chars"
else:
self.status['DBPASSWD'] = word_eol[2]
self.loadDB()
else:
print "Key Storage Not loaded"
self.status['DBPASSWD'] = None
return xchat.EAT_ALL
key = word[1].upper()
if key in self.config.keys():
if len(word) <3:
keyname = "%s%s" % (key,"."*20)
print "\00312%.29s: %s" % (keyname,str(self.config[key]))
else:
try:
if type(self.config[key]) == bool:
self.config[key] = bool(word[2] in ONMODES)
else:
self.config[key] = type(self.config[key])(word_eol[2])
print "\0035Set %r to %r" % (key,word_eol[2])
self.saveDB()
except ValueError:
print "\0034Invalid Config Value %r for %s" % (word_eol[2],key)
return xchat.EAT_ALL
return xchat.EAT_NONE
## incoming notice received
def on_notice(self,word, word_eol, userdata):
## check if this is not allready processed
if self.__chk_proc():
return xchat.EAT_NONE
## check if DH Key Exchange
if word[3].startswith(":") and word[3].endswith('DH1080_FINISH'):
return self.dh1080_finish(word, word_eol, userdata)
elif word[3].startswith(":") and word[3].endswith('DH1080_INIT'):
return self.dh1080_init(word, word_eol, userdata)
## check for encrypted Notice
elif word[3].startswith(':') and (word[3].endswith(':+OK') or word[3].startswith(':mcps')):
## rewrite data to pass to default inMessage function
## change full ident to nick only
nick = self.get_nick(word[0])
target = word[2]
speaker = nick
## strip :: from message
if word[3].endswith("+OK"):
idx = len(word[3]) - len("+OK")
elif word[3].endswith("mcps"):
idx = len(word[3]) - len("mcps")
message = word_eol[3][idx:]
if target.startswith("#"):
id = self.get_id()
speaker = "## %s" % speaker
else:
id = self.get_id(nick=nick)
#print "DEBUG(crypt): key: %r word: %r" % (id,word,)
key = self.find_key(id)
## if no key found exit
if not key:
return xchat.EAT_NONE
## decrypt the message
try:
sndmessage = self.decrypt(key,message)
except:
sndmessage = None
isCBC=0
if message.startswith("+OK *"):
isCBC=1
failcol = ""
## if decryption was possible check for invalid chars
if sndmessage:
try:
message = sndmessage.decode("UTF8").encode("UTF8")
## mark nick for encrypted msgg
speaker = "%s %s" % ("°"*(1+isCBC),speaker)
except UnicodeError:
try:
message = unicode(sndmessage,encoding='iso8859-1',errors='ignore').encode('UTF8')
## mark nick for encrypted msgg
speaker = "%s %s" % ("°"*(1+isCBC),speaker)
except:
raise
## send the message to local xchat
#self.emit_print(userdata,speaker,message)
#return xchat.EAT_XCHAT
except:
## mark nick with a question mark
speaker = "?%s" % (speaker)
failcol = "\003"
else:
failcol = "\003"
## mark the message with \003, it failed to be processed and there for the \003+OK will no longer be excepted as encrypted so it wont loop
self.emit_print(userdata,speaker,"%s%s" % (failcol,message))
return xchat.EAT_XCHAT
# return self.inMessage([nick,msg], ["%s %s" % (nick,msg),msg], userdata)
## ignore everything else
else:
#print "DEBUG: %r %r %r" % (word, word_eol, userdata)
return xchat.EAT_NONE
## local notice send messages
def on_notice_send(self,word, word_eol, userdata):
## get current nick
target = xchat.get_context().get_info('nick')
#print "DEBUG_notice_send: %r - %r - %r %r" % (word,word_eol,userdata,nick)
## check if this is not allready processed
if self.__chk_proc(target=target):
return xchat.EAT_NONE
## get the speakers nick only from full ident
speaker = self.get_nick(word[0])
## strip first : from notice
message = word_eol[1][1:]
if message.startswith('+OK ') or message.startswith('mcps '):
## get the key id from the speaker
id = self.get_id(nick=speaker)
key = self.find_key(id)
## if no key available for the speaker exit
if not key:
return xchat.EAT_NONE
## decrypt the message
sndmessage = self.decrypt(key,message)
isCBC = 0
if message.startswith("+OK *"):
isCBC = 1
if not target.startswith("#"):
## if we receive a messge with CBC enabled we asume the partner can also except it so activate it
key.cbc_mode = True
## if decryption was possible check for invalid chars
if sndmessage:
try:
message = sndmessage.decode("UTF8").encode("UTF8")
## mark nick for encrypted msgg
speaker = "%s %s" % ("°"*(1+isCBC),speaker)
except:
## mark nick with a question mark
speaker = "?%s" % (speaker)
## send original message because invalid chars
message = message
## send the message back to incoming notice but with locked target status so it will not be processed again
self.emit_print("Notice Send",speaker,message,target=target)
return xchat.EAT_XCHAT
return xchat.EAT_NONE
## incoming messages
def inMessage(self,word, word_eol, userdata):
## if message is allready processed ignore
if self.__chk_proc() or len(word_eol) < 2:
return xchat.EAT_PLUGIN
speaker = word[0]
message = word_eol[1]
#print "DEBUG(INMsg): %r - %r - %r" % (word,word_eol,userdata)
# if there is mode char, remove it from the message
if len(word_eol) >= 3:
#message = message[ : -(len(word_eol[2]) + 1)]
message = message[:-2]
## check if message is crypted
if message.startswith('+OK ') or message.startswith('mcps '):
target = None
if userdata == "Private Message":
target = speaker
id = self.get_id(nick=target)
target,network = id
key = self.find_key(id)
## if no key found exit
if not key:
return xchat.EAT_NONE
## decrypt the message
try:
sndmessage = self.decrypt(key,message)
except:
sndmessage = None
isCBC=0
if message.startswith("+OK *"):
isCBC=1
if not target.startswith("#"):
## if we receive a messge with CBC enabled we asume the partner can also except it so activate it
key.cbc_mode = True
failcol = ""
## if decryption was possible check for invalid chars
action = False
if sndmessage: