-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathircrypt-keyex.py
More file actions
1022 lines (840 loc) · 33.8 KB
/
ircrypt-keyex.py
File metadata and controls
1022 lines (840 loc) · 33.8 KB
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
# -*- coding: utf-8 -*-
#
# IRCrypt: Addon for IRCrypt to enable key exchange via public key authentication
# ===============================================================================
#
# Copyright (C) 2013-2014
# Lars Kiesow <lkiesow@uos.de>
# Sven Haardiek <sven@haardiek.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
#
# == About ======================================================================
# The weechat IRCrypt-KeyEx plug-in is an addon for the weechat IRCrypt
# plug-in to enable key exchange via public key exchange. The plug-in will
# create a RSA keypair and use this to do plublic key authentication with
# other users and to exchange symmetric keys.
#
# == Project ====================================================================
#
# This plug-in is part of the IRCrypt project. For mor information or to
# participate, please visit
#
# https://github.com/IRCrypt
#
#
# To report bugs, make suggestions, etc. for this particular plug-in, please
# have a look at:
#
# https://github.com/IRCrypt/ircrypt-weechat
#
import weechat, string, os, subprocess, base64, time, imp, sys
# Dont create .pyc file
sys.dont_write_bytecode = True
# Constants used in this script
SCRIPT_NAME = 'ircrypt-keyex'
SCRIPT_AUTHOR = 'Sven Haardiek <sven@haardiek.de>, Lars Kiesow <lkiesow@uos.de>'
SCRIPT_VERSION = 'SNAPSHOT'
SCRIPT_LICENSE = 'GPL3'
SCRIPT_DESC = 'IRCrypt-KeyEx: Addon for IRCrypt to enable key exchange via public key authentication'
SCRIPT_HELP_TEXT = '''%(bold)sIRCrypt-KeyEx command options: %(normal)s
list List public key fingerprints
start [-server <server>] <nick> Start key exchange with nick
remove-public-key [-server <server>] <nick> Remove public key id for nick
%(bold)sExamples: %(normal)s
Start key exchange with a user
/ircrypt-keyex start nick
Remove public key identifier for a user:
/ircrypt-keyex remove-public-key nick
%(bold)sConfiguration: %(normal)s
Tip: You can list all options and what they are currently set to by executing:
/set ircrypt-keyex.*
%(bold)sircrypt-keyex.general.binary %(normal)s
This will set the GnuPG binary used for encryption and decryption. IRCrypt-keyex
will try to set this automatically.
''' % {'bold':weechat.color('bold'), 'normal':weechat.color('-bold')}
MAX_PART_LEN = 300
MSG_PART_TIMEOUT = 300 # 5min
# Global variables and memory used to store message parts, pending requests,
# configuration options, keys, etc.
ircrypt = None
ircrypt_sym_key_memory = {}
ircrypt_config_file = None
ircrypt_config_section = {}
ircrypt_config_option = {}
ircrypt_asym_id = {}
ircrypt_pub_keys_memory = {}
ircrypt_key_ex_memory = {}
ircrypt_gpg_homedir = None
ircrypt_gpg_id = None
class MeassageParts:
'''Class used for storing parts of messages which were split after
encryption due to their length.'''
modified = 0
last_id = None
message = ''
def update(self, id, msg):
'''This method updates an already existing message part by adding a new
part to the old ones and updating the identifier of the latest received
message part.
'''
# Check if id is correct. If not, throw away old parts:
if self.last_id and self.last_id != id+1:
self.message = ''
# Check if the are old message parts which belong due to their old age
# probably not to this message:
if time.time() - self.modified > MSG_PART_TIMEOUT:
self.message = ''
self.last_id = id
self.message = msg + self.message
self.modified = time.time()
class KeyExchange:
'''Class used for key exchange
@pub_key_receive indicates wether the public key has not yet received
@pub_key_send indicates wether the public key has not yet been send
@parts specify the number of keyparts
@sym_key is the symmetric key
@sym_received incicates wether the symmetric key is completed
'''
pub_key_receive = False
pub_key_send = False
parts = 0
sym_key = ''
sym_received = False
def __init__(self, pub_key_receive, pub_key_send):
'''This function initialize the instance'''
self.pub_key_receive = pub_key_receive
self.pub_key_send = pub_key_send
def update(self, keypart):
'''This function update the symmetric key and do the XOR operation'''
if self.sym_key == '':
self.sym_key = keypart
else:
self.sym_key = ''.join(chr(ord(x) ^ ord(y)) for x, y in
zip(self.sym_key, keypart))
self.parts = self.parts + 1
def ircrypt_gpg_init():
'''Initialize GnuPG'''
global ircrypt_gpg_homedir, ircrypt_gpg_id
# This should usually be ~/.weechat/ircrypt
ircrypt_gpg_homedir = '%s/ircrypt' % weechat.info_get("weechat_dir", "")
try:
os.mkdir(ircrypt_gpg_homedir, 0o700)
except OSError:
pass
# Probe for GPG key
(ret, out, err) = ircrypt.ircrypt_gnupg(b'', '--homedir', ircrypt_gpg_homedir,
'--list-secret-keys', '--with-fingerprint', '--with-colon')
# GnuPG returncode
if ret:
ircrypt.ircrypt_error(err.decode('utf-8'), weechat.current_buffer())
return weechat.WEECHAT_RC_ERROR
elif err:
ircrypt.ircrypt_warn(err.decode('utf-8'), '')
# There is a secret key
if out:
try:
ircrypt_gpg_id = out.decode('utf-8').split('fpr')[-1].split('\n')[0].strip(':')
ircrypt.ircrypt_info('Found private gpg key with fingerprint %s' %
ircrypt_gpg_id, '')
return weechat.WEECHAT_RC_OK
except:
ircrypt.ircrypt_error('Unable to get key id', '')
# Try to generate a key
ircrypt.ircrypt_warn('No private key for assymetric encryption was found in the '
+ 'IRCrypt GPG keyring. IRCrypt will now try to automatically generate a '
+ 'new key. This might take quite some time as this procedure depends on '
+ 'the gathering of enough entropy for generating cryptographically '
+ 'strong random numbers. You cannot use the key exchange (public key'
+ 'authentication) until this process is done. However, it does not'
+ 'affect the symmetric encryption which can already be used. You '
+ 'will be notified once the process is done.')
binary = weechat.config_string(weechat.config_get('ircrypt.general.binary'))
hook = weechat.hook_process_hashtable(binary, {
'stdin': '1',
'arg1': '--batch',
'arg2': '--no-tty',
'arg3': '--quiet',
'arg4': '--homedir',
'arg5': ircrypt_gpg_homedir,
'arg6': '--gen-key'},
0, 'ircrypt_key_generated_cb', '')
gen_command = 'Key-Type: RSA\n' \
+ 'Key-Length: 2048\n' \
+ 'Subkey-Type: RSA\n' \
+ 'Subkey-Length: 2048\n' \
+ 'Name-comment: ircrypt\n' \
+ 'Expire-Date: 0\n' \
+ '%commit'
weechat.hook_set(hook, 'stdin', gen_command)
weechat.hook_set(hook, 'stdin_close', '')
return weechat.WEECHAT_RC_OK
def ircrypt_key_generated_cb(data, command, errorcode, out, err):
'''Callback for process hook to generate key'''
# Error
if errorcode:
ircrypt.ircrypt_error(err, '')
return weechat.WEECHAT_RC_ERROR
elif err:
ircrypt.ircrypt_warn(err)
ircrypt.ircrypt_info('A private key for asymmetric encryption was successfully'
+ 'generated and can now be used for communication.')
return ircrypt_gpg_init()
def ircrypt_receive_key_ex_ping(server, args, info):
'''This function handles incomming >KEY-EX-PING notices'''
global ircrypt_gpg_id, ircrypt_key_ex_memory
# Check for ircrypt plugin
if not ircrypt_check_ircrypt:
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
return ''
# Check if own gpg key exists
if not ircrypt_gpg_id:
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
return ''
# Get fingerprint from message
try:
fingerprint = args.split('>KEY-EX-PING')[-1].split(' (')[0].lstrip(' ')
except:
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
return ''
# Wrong fingerprint: Error
if fingerprint and fingerprint != ircrypt_gpg_id:
ircrypt.ircrypt_error('%s tries key exchange with wrong fingerprint' \
% info['nick'], weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-PING-WITH-INVALID-FINGERPRINT' % (server, info['nick']))
return ''
# Send back a >KEY-EX-PONG with optional fingerprint and create an instance
# of the class KeyExchange
target = ('%s/%s' % (server, info['nick'])).lower()
gpg_id = ircrypt_asym_id.get(target)
if gpg_id:
weechat.command('','/mute -all notice -server %s %s >KEY-EX-PONG %s' \
% (server, info['nick'], gpg_id))
if fingerprint:
ircrypt_key_ex_memory[target] = KeyExchange(False, False)
else:
ircrypt_key_ex_memory[target] = KeyExchange(False, True)
else:
weechat.command('','/mute -all notice -server %s %s >KEY-EX-PONG' \
% (server, info['nick']))
if fingerprint:
ircrypt_key_ex_memory[target] = KeyExchange(True, False)
else:
ircrypt_key_ex_memory[target] = KeyExchange(True, True)
return ''
def ircrypt_receive_key_ex_pong(server, args, info):
'''This function handles incomming >KEY-EX-PONG notices'''
global ircrypt_gpg_id, ircrypt_key_ex_memory
target = ('%s/%s' % (server, info['nick'])).lower()
# No instance of KeyExchange: Error
if not ircrypt_key_ex_memory.get(target):
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-NO-KEY-EXCHANGE' % (server, info['nick']))
return ''
fingerprint = args.split('>KEY-EX-PONG')[-1].lstrip(' ')
# Wrong fingerprint: Error and try to delete instance of KeyExchange
if fingerprint and fingerprint != ircrypt_gpg_id:
ircrypt.ircrypt_error('%s tries key exchange with wrong fingerprint' \
% info['nick'], weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-PING-WITH-INVALID-FINGERPRINT' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# If correct fingerprint, the public key must not been sent
if fingerprint:
ircrypt_key_ex_memory[target].pub_key_send = False
# Notice to start next phase
weechat.command('','/mute -all notice -server %s %s >KEY-EX-NEXT-PHASE' \
% (server, info['nick']))
# If no public key must be sent, start symmetric key exchange. Otherwise
# send public key, if necessary
if (ircrypt_key_ex_memory[target].pub_key_send,
ircrypt_key_ex_memory[target].pub_key_receive) == (False, False):
ircrypt_sym_key_send(server, info['nick'])
elif ircrypt_key_ex_memory[target].pub_key_send:
ircrypt_public_key_send(server, info['nick'])
return ''
def ircrypt_receive_next_phase(server, args, info):
'''This function handles incomming >KEY-EX-NEXT-PHASE notices'''
global ircrypt_gpg_id, ircrypt_key_ex_memory
target = ('%s/%s' % (server, info['nick'])).lower()
# No instance of KeyExchange: Error
if not ircrypt_key_ex_memory.get(target):
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-NO-KEY-EXCHANGE' % (server, info['nick']))
return ''
# If no public key must be sent, start symmetric key exchange. Otherwise
# send public key, if necessary
if (ircrypt_key_ex_memory[target].pub_key_send,
ircrypt_key_ex_memory[target].pub_key_receive) == (False,False):
ircrypt_sym_key_send(server, info['nick'])
elif ircrypt_key_ex_memory[target].pub_key_send:
ircrypt_public_key_send(server, info['nick'])
return ''
def ircrypt_public_key_send(server, nick):
'''This function sends away own public key'''
global ircrypt_gpg_homedir, ircrypt_gpg_id, ircrypt_key_ex_memory
# Export own public key and b64encode the public key. Print error if
# necessary.
if not ircrypt_gpg_id:
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
return ''
(ret, out, err) = ircrypt.ircrypt_gnupg(b'', '--homedir', ircrypt_gpg_homedir,
'--export', ircrypt_gpg_id)
if ret:
ircrypt.ircrypt_error(err.decode('utf-8'), weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
# TODO: This will never work. There is no target
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
elif err:
ircrypt.ircrypt_warn(err.decode('utf-8'))
pub_key = base64.b64encode(out)
# Partition the public key and send it away
for i in range(1 + (len(pub_key) // MAX_PART_LEN))[::-1]:
msg = '>PUB-EX-%i %s' % (i, pub_key[i*MAX_PART_LEN:(i+1)*MAX_PART_LEN])
weechat.command('','/mute -all notice -server %s %s %s' % (server, nick, msg))
return ''
def ircrypt_public_key_get(server, args, info):
'''This function handles incomming >PUB-EX- messages'''
global ircrypt_pub_keys_memory, ircrypt_asym_id, ircrypt_key_ex_memory
# Get prefix, number and message
pre, message = args.split('>PUB-EX-', 1)
number, message = message.split(' ', 1)
target = ('%s/%s' % (server, info['nick'])).lower()
# Check if we got the last part of the message otherwise put the message
# into a global memory and quit
if int(number):
if not target in ircrypt_pub_keys_memory:
# - First element is list of requests
# - Second element is currently received request
ircrypt_pub_keys_memory[target] = ircrypt.MessageParts()
# Add parts to current request
ircrypt_pub_keys_memory[target].update(int(number), message)
return ''
# No instance of KeyExchange: Error
if not ircrypt_key_ex_memory.get(target):
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-NO-KEY-EXCHANGE' % (server, info['nick']))
return ''
# If no request for a public key: Error and try to delete instance of
# KeyExchange
if not ircrypt_key_ex_memory[target].pub_key_receive:
ircrypt.ircrypt_error('%s sends his public key without inquiry' % info['nick'],
weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-NO-REQUEST-FOR-PUBLIC-KEY' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# If there is a public identifier: Error and try to delete instance of
# KeyExchange
key_id = ircrypt_asym_id.get(target)
if key_id:
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Get whole message
try:
message = message + ircrypt_pub_keys_memory[target].message
del ircrypt_pub_keys_memory[target]
except KeyError:
pass
# Decode base64 encoded message
try:
message = base64.b64decode(message)
except:
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Import public key
(ret, out, err) = ircrypt.ircrypt_gnupg(message, '--homedir', ircrypt_gpg_homedir,
'--keyid-format', '0xlong', '--import')
# Print error (There are the information about the imported public key)
# and quit key exchange if necessary
if ret:
ircrypt.ircrypt_error(err.decode('utf-8'), weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Try to get public key identifier contained in the stderr output.
try:
gpg_id = err.decode('utf-8').split('0x',1)[1].split(':',1)[0]
except:
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Probe for GPG fingerprint
(ret, out, err) = ircrypt.ircrypt_gnupg(b'', '--homedir', ircrypt_gpg_homedir,
'--fingerprint', '--with-colon')
# Print error (There are the information about the imported public key)
# and quit key exchange if necessary
if ret:
ircrypt.ircrypt_error(err.decode('utf-8'), weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
elif err:
ircrypt.ircrypt_warn(err.decode('utf-8'))
# There is a secret key
try:
out = [ line for line in out.decode('utf-8').split('\n') \
if (gpg_id + ':') in line and line.startswith('fpr:') ][-1]
gpg_id = out.split('fpr')[-1].strip(':')
except:
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Set asymmetric identifier and remember that the public key was received
ircrypt_asym_id[target] = gpg_id
ircrypt_key_ex_memory[target].pub_key_receive = False
# Send status back
weechat.command('','/mute -all notice -server %s %s '
'>KEY-EX-PUB-RECEIVED' % (server, info['nick']))
# Start symmetic key exchange if public key exchange is closed
if (ircrypt_key_ex_memory[target].pub_key_send,
ircrypt_key_ex_memory[target].pub_key_receive) == (False,False):
ircrypt_sym_key_send(server, info['nick'])
return ''
def ircrypt_receive_key_ex_pub_received(server, args, info):
'''This function handles incomming >PUB-KEY-RECEIVED notices'''
global ircrypt_gpg_id, ircrypt_key_ex_memory
target = ('%s/%s' % (server, info['nick'])).lower()
# No instance of KeyExchange: Error
if not ircrypt_key_ex_memory.get(target):
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-NO-KEY-EXCHANGE' % (server, info['nick']))
return ''
# Set asymmetric identifier and remember that the public key was sent
ircrypt_key_ex_memory[target].pub_key_send = False
# Start symmetic key exchange if public key exchange is closed
if (ircrypt_key_ex_memory[target].pub_key_send,
ircrypt_key_ex_memory[target].pub_key_receive) == (False,False):
ircrypt_sym_key_send(server, info['nick'])
return ''
def ircrypt_sym_key_send(server, nick):
'''This function create a part of a symmetric key and send it away'''
global ircrypt_asym_id, ircrypt_key_ex_memory, ircrypt_sym_keys_memory
# Create part of key
keypart = os.urandom(64)
target = ('%s/%s' % (server, nick)).lower()
(ret, out, err) = ircrypt.ircrypt_gnupg(keypart, '--homedir', ircrypt_gpg_homedir,
'-s', '--trust-model', 'always', '-e', '-r', ircrypt_asym_id[target])
# Print error and quit key exchange if necessary
if ret:
ircrypt.ircrypt_error(err.decode('utf-8'), weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
elif err:
ircrypt.ircrypt_warn(err.decode('utf-8'))
# Update symmetric key
ircrypt_key_ex_memory[target].update(keypart)
# If symmetric key is complete, send status back
if ircrypt_key_ex_memory[target].parts == 2:
weechat.command('','/mute -all notice -server %s %s '
'>KEY-EX-SYM-RECEIVED' % (server, nick))
# If the symmetric key is also complete by the counterpart set symmetric
# key
if ircrypt_key_ex_memory[target].sym_received:
weechat.command('','/ircrypt set-key -server %s %s %s' \
% (server, info['nick'],
base64.b64encode(ircrypt_key_ex_memory[target].sym_key)))
# Print encrypted part of the symmetric key in multiple notices
out = base64.b64encode(out)
for i in range(1 + (len(out) / MAX_PART_LEN))[::-1]:
msg = '>SYM-EX-%i %s' % (i, out[i*MAX_PART_LEN:(i+1)*MAX_PART_LEN])
weechat.command('','/mute -all notice -server %s %s %s' % (server, nick, msg))
def ircrypt_sym_key_get(server, args, info):
global ircrypt_pub_keys_memory, ircrypt_asym_id, ircrypt_key_ex_memory
# Get prefix, number and message
pre, message = args.split('>SYM-EX-', 1)
number, message = message.split(' ', 1)
catchword = (server, info['channel'], info['nick'])
# Decrypt only if we got last part of the message
# otherwise put the message into a global memory and quit
if int(number) != 0:
if not catchword in ircrypt_sym_key_memory:
ircrypt_sym_key_memory[catchword] = ircrypt.MessageParts()
ircrypt_sym_key_memory[catchword].update(int(number), message)
return ''
# Get whole message
try:
message = message + ircrypt_sym_key_memory[catchword].message
except KeyError:
pass
target = ('%s/%s' % (server, info['nick'])).lower()
# No instance of KeyExchange: Error
if not ircrypt_key_ex_memory.get(target):
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-NO-KEY-EXCHANGE' % (server, info['nick']))
return ''
# No request for symmtric key exchange: Error and try to delete instance
if (ircrypt_key_ex_memory[target].pub_key_send or
ircrypt_key_ex_memory[target].pub_key_receive):
ircrypt.ircrypt_error('%s sends symmetric key without inquiry' % info['nick'],
weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-NO-REQUEST-FOR-SYMMETRIC-KEY' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Decode base64 encoded message
try:
message = base64.b64decode(message)
except TypeError:
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Decrypt
(ret, out, err) = ircrypt.ircrypt_gnupg(message, '--homedir',
ircrypt_gpg_homedir, '-d')
# Print error and quit key exchange if necessary
if ret:
ircrypt.ircrypt_error(err.decode('utf-8'), weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-INTERNAL-ERROR' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Remove old messages from memory
try:
del ircrypt_sym_key_memory[catchword]
except KeyError:
pass
target = ('%s/%s' % (server, info['nick'])).lower() # TODO: Necessary?
# Update symmetric key
ircrypt_key_ex_memory[target].update(out)
# If symmetric key is complete, send status back
if ircrypt_key_ex_memory[target].parts == 2:
weechat.command('','/mute -all notice -server %s %s '
'>KEY-EX-SYM-RECEIVED' % (server, info['nick']))
# If the symmetric key is also complete by the counterpart set symmetric
# key
if ircrypt_key_ex_memory[target].sym_received:
weechat.command('','/ircrypt set-key -server %s %s %s' \
% (server, info['nick'],
base64.b64encode(ircrypt_key_ex_memory[target].sym_key)))
return ''
def ircrypt_receive_key_ex_sym_received(server, args, info):
'''This functions handles incomming >KEY-EX-SYM-RECEIVED notices'''
global ircrypt_gpg_id, ircrypt_key_ex_memory
target = ('%s/%s' % (server, info['nick'])).lower()
# No instance of KeyExchange: Error
if not ircrypt_key_ex_memory.get(target):
weechat.command('','/mute -all notice -server %s %s '
'>UCRY-NO-KEY-EXCHANGE' % (server, info['nick']))
return ''
# No request for symmetric key exchange: Error and try to delete instance
if (ircrypt_key_ex_memory[target].pub_key_send or
ircrypt_key_ex_memory[target].pub_key_receive):
ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer())
weechat.command('','/mute -all notice -server %s %s'
'>UCRY-NO-REQUEST-FOR-SYMMETRIC-KEY' % (server, info['nick']))
try:
del ircrypt_key_ex_memory[target]
except KeyError:
pass
return ''
# Remember that the counterpart has received the symmetric key
ircrypt_key_ex_memory[target].sym_received = True
# If the symmetric key is also complete by the counterpart set symmetric
# key
if ircrypt_key_ex_memory[target].parts == 2:
weechat.command('','/ircrypt set-key -server %s %s %s' \
% (server, info['nick'],
base64.b64encode(ircrypt_key_ex_memory[target].sym_key)))
return ''
def ircrypt_config_init():
''' This method initializes the configuration file. It creates sections and
options in memory and prepares the handling of key sections.
'''
global ircrypt_config_file, ircrypt_config_section, ircrypt_config_option
ircrypt_config_file = weechat.config_new('ircrypt-keyex', 'ircrypt_config_reload_cb', '')
if not ircrypt_config_file:
return
# public key identifier
ircrypt_config_section['asym_id'] = weechat.config_new_section(
ircrypt_config_file, 'asym_id', 0, 0,
'ircrypt_config_asym_id_read_cb', '',
'ircrypt_config_asym_id_write_cb', '', '', '', '', '', '', '')
if not ircrypt_config_section['asym_id']:
weechat.config_free(ircrypt_config_file)
def ircrypt_config_reload_cb(data, config_file):
'''Handle a reload of the configuration file.
'''
return weechat.WEECHAT_CONFIG_READ_OK
def ircrypt_config_read():
''' Read IRCrypt configuration file (ircrypt.conf).
'''
global ircrypt_config_file
return weechat.config_read(ircrypt_config_file)
def ircrypt_config_write():
''' Write IRCrypt configuration file (ircrypt.conf) to disk.
'''
global ircrypt_config_file
return weechat.config_write(ircrypt_config_file)
def ircrypt_config_asym_id_read_cb(data, config_file, section_name, option_name,
value):
'''Read elements of the key section from the configuration file.
'''
global ircrypt_asym_id
ircrypt_asym_id[option_name.lower()] = value
return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED
def ircrypt_config_asym_id_write_cb(data, config_file, section_name):
'''Write passphrases to the key section of the configuration file.
'''
global ircrypt_asym_id
weechat.config_write_line(config_file, section_name, '')
for target, asym_id in sorted(list(ircrypt_asym_id.items())):
weechat.config_write_line(config_file, target.lower(), asym_id)
return weechat.WEECHAT_RC_OK
def ircrypt_command_list():
'''ircrypt command to list fingerprints'''
out = '\n'.join([' %s : %s' % x for x in ircrypt_asym_id.items()])
ircrypt.ircrypt_info('Fingerprint:\n' + out if out else 'No known Fingerprints')
return weechat.WEECHAT_RC_OK
def ircrypt_command_start(server, nick):
'''This function is called when the user starts a key exchange'''
global ircrypt_asym_id, ircrypt_key_ex_memory, ircrypt_gpg_id
# Check for ircrypt plugin
if not ircrypt_check_ircrypt:
return weechat.WEECHAT_RC_OK
# Check if own gpg key exists
if not ircrypt_gpg_id:
ircrypt.ircrypt_error('No GPG key generated')
return weechat.WEECHAT_RC_ERROR
# Send >KEY-EX-PING with optional gpg fingerprint and create instance of
# KeyExchange
target = ('%s/%s' % (server, nick)).lower()
gpg_id = ircrypt_asym_id.get(target)
text = '(Trying to initialte key exchange via IRCrypt-KeyEx)'
if gpg_id:
weechat.command('','/mute -all notice -server %s %s >KEY-EX-PING %s %s' \
% (server, nick, gpg_id, text))
ircrypt_key_ex_memory[target] = KeyExchange(False, True)
else:
weechat.command('','/mute -all notice -server %s %s >KEY-EX-PING %s' \
% (server, nick, text))
ircrypt_key_ex_memory[target] = KeyExchange(True, True)
# print information
ircrypt.ircrypt_info('Start key exchange with %s on server %s. This may take some '
'time. The exchange will be ignored if %s has no IRCrypt-KeyEx.' \
% (nick, server, nick))
return weechat.WEECHAT_RC_OK
def ircrypt_command_remove_public_key(target):
'''ircrypt command to remove public key for target (target is a server/channel combination)'''
global ircrypt_asym_id
# Check if public key is set and print error in current buffer otherwise
if target.lower() not in ircrypt_asym_id:
ircrypt.ircrypt_error('No existing public key for %s.' % target, weechat.current_buffer())
return weechat.WEECHAT_RC_ERROR
# Delete public key (first in gpg then in config file) and print status
# message in current buffer
(ret, out, err) = ircrypt.ircrypt_gnupg(b'', '--yes', '--homedir',
ircrypt_gpg_homedir,'--delete-key', ircrypt_asym_id[target.lower()])
if ret:
ircrypt.ircrypt_error('Could not delete public key in gpg', weechat.current_buffer())
return weechat.WEECHAT_RC_ERROR
elif err:
ircrypt.ircrypt_warn(err.decode('utf-8'))
del ircrypt_asym_id[target.lower()]
ircrypt.ircrypt_info('Removed asymmetric identifier for %s' % target)
return weechat.WEECHAT_RC_OK
def ircrypt_command(data, buffer, args):
'''Hook to handle the /ircrypt-keyex weechat command.'''
global ircrypt_asym_id
argv = [a for a in args.split(' ') if a]
if argv and not argv[0] in ['list', 'remove-public-key', 'start']:
ircrypt.ircrypt_error('%sUnknown command. Try /help ircrypt-keyex', buffer)
return weechat.WEECHAT_RC_ERROR
# list
if not argv or argv == ['list']:
return ircrypt_command_list()
# Check if a server was set
if (len(argv) > 2 and argv[1] == '-server'):
server = argv[2]
del argv[2]
del argv[1]
args = args.split(' ', 2)[-1]
else:
# Try to determine the server automatically
server = weechat.buffer_get_string(buffer, 'localvar_server')
# All remaining commands need a server name
if not server:
# if no server was set print message in ircrypt buffer and throw error
ircrypt.ircrypt_error('Unknown Server. Please use -server to specify server', buffer)
return weechat.WEECHAT_RC_ERROR
# For the remaining commands we need at least one additional argument
if len(argv) < 2:
return weechat.WEECHAT_RC_ERROR
target = ('%s/%s' % (server, argv[1])).lower()
if argv[0] == 'start':
if len(argv) == 2:
return ircrypt_command_start(server, argv[1])
return weechat.WEECHAT_RC_ERROR
# Remove public key from another user
if argv[0] == 'remove-public-key':
if len(argv) != 2:
return weechat.WEECHAT_RC_ERROR
return ircrypt_command_remove_public_key(target)
# Error if command was unknown
return weechat.WEECHAT_RC_ERROR
def ircrypt_notice_hook(data, msgtype, server, args):
info = weechat.info_get_hashtable('irc_message_parse', { 'message': args })
if '>UCRY-INTERNAL-ERROR' in args:
ircrypt.ircrypt_error('%s on server %s reported an error during the key exchange' \
% (info['nick'], server), weechat.current_buffer())
return ''
elif '>UCRY-NO-KEY-EXCHANGE' in args:
ircrypt.ircrypt_error('%s on server %s reported an error during the key exchange' \
% (info['nick'], server), weechat.current_buffer())
return ''
elif '>UCRY-PING-WITH-INVALID-FINGERPRINT' in args:
ircrypt.ircrypt_error('%s on server %s reported that your fingerprint known does'
'not match his own fingerprint' % (info['nick'], server),
weechat.current_buffer())
return ''
elif '>UCRY-NO-REQUEST-FOR-PUBLIC-KEY' in args:
ircrypt.ircrypt_error('%s on server %s reported an error during the key exchange' \
% (info['nick'], server), weechat.current_buffer())
return ''
elif '>UCRY-NO-REQUEST-FOR-SYMMETRIC-KEY' in args:
ircrypt.ircrypt_error('%s on server %s reported an error during the key exchange' \
% (info['nick'], server), weechat.current_buffer())
return ''
# Different hooks
elif '>KEY-EX-PING' in args:
return ircrypt_receive_key_ex_ping(server, args, info)
elif '>KEY-EX-PONG' in args:
return ircrypt_receive_key_ex_pong(server, args, info)
elif '>KEY-EX-NEXT-PHASE' in args:
return ircrypt_receive_next_phase(server, args, info)
elif '>KEY-EX-PUB-RECEIVED' in args:
return ircrypt_receive_key_ex_pub_received(server, args, info)
elif '>SYM-EX-' in args:
return ircrypt_sym_key_get(server, args, info)
elif '>KEY-EX-SYM-RECEIVED' in args:
return ircrypt_receive_key_ex_sym_received(server, args, info)
elif '>PUB-EX-' in args:
return ircrypt_public_key_get(server, args, info)
return args
def ircrypt_load(data, signal, ircrypt_path):
global ircrypt
if ircrypt_path.endswith('ircrypt.py'):
ircrypt = imp.load_source('ircrypt', ircrypt_path)
ircrypt_init()
return weechat.WEECHAT_RC_OK
def ircrypt_check_ircrypt():
infolist = weechat.infolist_get('python_script', '', 'ircrypt')
weechat.infolist_next(infolist)
ircrypt_path = weechat.infolist_string(infolist, 'filename')
weechat.infolist_free(infolist)
return ircrypt_path
def ircrypt_init():
# Initialize configuration
ircrypt_config_init()
ircrypt_config_read()
# Look for GnuPG binary
if weechat.config_string(weechat.config_get('ircrypt.general.binary')):
# Initialize public key authentification
ircrypt_gpg_init()
# Register Hooks
weechat.hook_modifier('irc_in_notice', 'ircrypt_notice_hook', '')
weechat.hook_command('ircrypt-keyex', 'Commands of the Addon IRCrypt-keyex',
'[list] '
'| remove-public-key [-server <server>] <nick> '
'| start [-server <server>] <nick> ',
SCRIPT_HELP_TEXT,
'list '
'|| remove-public-key %(nicks)|-server %(irc_servers) %- '
'|| start %(nicks)|-server %(irc_servers) %- ',
'ircrypt_command', '')