forked from mmb/weechat-otr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weechat_otr.py
2062 lines (1654 loc) · 73.8 KB
/
weechat_otr.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
# -*- coding: utf-8 -*-
# otr - WeeChat script for Off-the-Record IRC messaging
#
# DISCLAIMER: To the best of my knowledge this script securely provides OTR
# messaging in WeeChat, but I offer no guarantee. Please report any security
# holes you find.
#
# Copyright (c) 2012-2015 Matthew M. Boedicker <[email protected]>
# Nils Görs <[email protected]>
# Daniel "koolfy" Faucon <[email protected]>
# Felix Eckhofer <[email protected]>
#
# Report issues at https://github.com/mmb/weechat-otr
#
# 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, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import collections
import glob
import io
import os
import platform
import re
import traceback
import shlex
import shutil
import sys
class PythonVersion2(object):
"""Python 2 version of code that must differ between Python 2 and 3."""
def __init__(self):
import cgi
self.cgi = cgi
import HTMLParser
self.html_parser = HTMLParser
self.html_parser_init_kwargs = {}
import htmlentitydefs
self.html_entities = htmlentitydefs
def html_escape(self, strng):
"""Escape HTML characters in a string."""
return self.cgi.escape(strng)
def unicode(self, *args, **kwargs):
"""Return the Unicode version of a string."""
return unicode(*args, **kwargs)
def unichr(self, *args, **kwargs):
"""Return the one character string of a Unicode character number."""
return unichr(*args, **kwargs)
def to_unicode(self, strng):
"""Convert a utf-8 encoded string to a Unicode."""
if isinstance(strng, unicode):
return strng
else:
return strng.decode('utf-8', 'replace')
def to_str(self, strng):
"""Convert a Unicode to a utf-8 encoded string."""
return strng.encode('utf-8', 'replace')
class PythonVersion3(object):
"""Python 3 version of code that must differ between Python 2 and 3."""
def __init__(self, minor):
self.minor = minor
import html
self.html = html
import html.parser
self.html_parser = html.parser
if self.minor >= 4:
self.html_parser_init_kwargs = { 'convert_charrefs' : True }
else:
self.html_parser_init_kwargs = {}
import html.entities
self.html_entities = html.entities
def html_escape(self, strng):
"""Escape HTML characters in a string."""
return self.html.escape(strng, quote=False)
def unicode(self, *args, **kwargs):
"""Return the Unicode version of a string."""
return str(*args, **kwargs)
def unichr(self, *args, **kwargs):
"""Return the one character string of a Unicode character number."""
return chr(*args, **kwargs)
def to_unicode(self, strng):
"""Convert a utf-8 encoded string to unicode."""
if isinstance(strng, bytes):
return strng.decode('utf-8', 'replace')
else:
return strng
def to_str(self, strng):
"""Convert a Unicode to a utf-8 encoded string."""
return strng
if sys.version_info.major >= 3:
PYVER = PythonVersion3(sys.version_info.minor)
else:
PYVER = PythonVersion2()
import weechat
import potr
SCRIPT_NAME = 'otr'
SCRIPT_DESC = 'Off-the-Record messaging for IRC'
SCRIPT_HELP = """{description}
Quick start:
Add an OTR item to the status bar by adding '[otr]' to the config setting
weechat.bar.status.items. This will show you whether your current conversation
is encrypted, authenticated and logged. /set otr.* for OTR status bar
customization options.
Start a private conversation with a friend who has OTR: /query yourpeer hi
In the private chat buffer: /otr start
If you have not authenticated your peer yet, follow the instructions for
authentication.
You can, at any time, see the current OTR session status and fingerprints with:
/otr status
View OTR policies for your peer: /otr policy
View default OTR policies: /otr policy default
Start/Stop log recording for the current OTR session: /otr log [start|stop]
This will be reverted back to the previous log setting at the end of the session.
To refresh the OTR session: /otr refresh
To end your private conversation: /otr finish
This script supports only OTR protocol version 2.
""".format(description=SCRIPT_DESC)
SCRIPT_AUTHOR = 'Matthew M. Boedicker'
SCRIPT_LICENCE = 'GPL3'
SCRIPT_VERSION = '1.8.0'
OTR_DIR_NAME = 'otr'
OTR_QUERY_RE = re.compile(r'\?OTR(\?|\??v[a-z\d]*\?)')
POLICIES = {
'allow_v2' : 'allow OTR protocol version 2, effectively enable OTR '
'since v2 is the only supported version',
'require_encryption' : 'refuse to send unencrypted messages when OTR is '
'enabled',
'log' : 'enable logging of OTR conversations',
'send_tag' : 'advertise your OTR capability using the whitespace tag',
'html_escape' : 'escape HTML special characters in outbound messages',
'html_filter' : 'filter HTML in incoming messages',
}
READ_ONLY_POLICIES = {
'allow_v1' : False,
}
ACTION_PREFIX = '/me '
IRC_ACTION_RE = re.compile('^\x01ACTION (?P<text>.*)\x01$')
PLAIN_ACTION_RE = re.compile('^'+ACTION_PREFIX+'(?P<text>.*)$')
IRC_SANITIZE_TABLE = dict((ord(char), None) for char in '\n\r\x00')
global otr_debug_buffer
otr_debug_buffer = None
# Patch potr.proto.TaggedPlaintext to not end plaintext tags in a space.
#
# When POTR adds OTR tags to plaintext it puts them at the end of the message.
# The tags end in a space which gets stripped off by WeeChat because it
# strips trailing spaces from commands. This causes OTR initiation to fail so
# the following code adds an extra tab at the end of the plaintext tags if
# they end in a space.
#
# The patched version also skips OTR tagging for CTCP messages because it
# breaks the CTCP format.
def patched__bytes__(self):
# Do not tag CTCP messages.
if self.msg.startswith(b'\x01') and \
self.msg.endswith(b'\x01'):
return self.msg
data = self.msg + potr.proto.MESSAGE_TAG_BASE
for v in self.versions:
data += potr.proto.MESSAGE_TAGS[v]
if data.endswith(b' '):
data += b'\t'
return data
potr.proto.TaggedPlaintext.__bytes__ = patched__bytes__
def command(buf, command_str):
"""Wrap weechat.command() with utf-8 encode."""
debug(command_str)
weechat.command(buf, PYVER.to_str(command_str))
def privmsg(server, nick, message):
"""Send a private message to a nick."""
for line in message.splitlines():
command('', '/quote -server {server} PRIVMSG {nick} :{line}'.format(
server=irc_sanitize(server),
nick=irc_sanitize(nick),
line=irc_sanitize(line)))
def build_privmsg_in(fromm, target, msg):
"""Build inbound IRC PRIVMSG command."""
return ':{user} PRIVMSG {target} :{msg}'.format(
user=irc_sanitize(fromm),
target=irc_sanitize(target),
msg=irc_sanitize(msg))
def build_privmsgs_in(fromm, target, msg, prefix=''):
"""Build an inbound IRC PRIVMSG command for each line in msg.
If prefix is supplied, prefix each line of msg with it."""
cmd = []
for line in msg.splitlines():
cmd.append(build_privmsg_in(fromm, target, prefix+line))
return '\r\n'.join(cmd)
def build_privmsg_out(target, msg):
"""Build outbound IRC PRIVMSG command(s)."""
cmd = []
for line in msg.splitlines():
cmd.append('PRIVMSG {target} :{line}'.format(
target=irc_sanitize(target),
line=irc_sanitize(line)))
return '\r\n'.join(cmd)
def irc_sanitize(msg):
"""Remove NUL, CR and LF characters from msg.
The (utf-8 encoded version of a) string returned from this function
should be safe to use as an argument in an irc command."""
return PYVER.unicode(msg).translate(IRC_SANITIZE_TABLE)
def prnt(buf, message):
"""Wrap weechat.prnt() with utf-8 encode."""
weechat.prnt(buf, PYVER.to_str(message))
def print_buffer(buf, message, level='info'):
"""Print message to buf with prefix,
using color according to level."""
prnt(buf, '{prefix}\t{msg}'.format(
prefix=get_prefix(),
msg=colorize(message, 'buffer.{}'.format(level))))
def get_prefix():
"""Returns configured message prefix."""
return weechat.string_eval_expression(
config_string('look.prefix'),
{}, {}, {})
def debug(msg):
"""Send a debug message to the OTR debug buffer."""
debug_option = weechat.config_get(config_prefix('general.debug'))
global otr_debug_buffer
if weechat.config_boolean(debug_option):
if not otr_debug_buffer:
otr_debug_buffer = weechat.buffer_new("OTR Debug", "", "",
"debug_buffer_close_cb", "")
weechat.buffer_set(otr_debug_buffer, 'title', 'OTR Debug')
weechat.buffer_set(otr_debug_buffer, 'localvar_set_no_log', '1')
prnt(otr_debug_buffer, ('{script} debug\t{text}'.format(
script=SCRIPT_NAME,
text=PYVER.unicode(msg)
)))
def debug_buffer_close_cb(data, buf):
"""Set the OTR debug buffer to None."""
global otr_debug_buffer
otr_debug_buffer = None
return weechat.WEECHAT_RC_OK
def current_user(server_name):
"""Get the nick and server of the current user on a server."""
return irc_user(info_get('irc_nick', server_name), server_name)
def irc_user(nick, server):
"""Build an IRC user string from a nick and server."""
return '{nick}@{server}'.format(
nick=nick.lower(),
server=server)
def isupport_value(server, feature):
"""Get the value of an IRC server feature."""
args = '{server},{feature}'.format(server=server, feature=feature)
return info_get('irc_server_isupport_value', args)
def is_a_channel(channel, server):
"""Return true if a string has an IRC channel prefix."""
prefixes = \
tuple(isupport_value(server, 'CHANTYPES')) + \
tuple(isupport_value(server, 'STATUSMSG'))
# If the server returns nothing for CHANTYPES and STATUSMSG use
# default prefixes.
if not prefixes:
prefixes = ('#', '&', '+', '!', '@')
return channel.startswith(prefixes)
# Exception class for PRIVMSG parsing exceptions.
class PrivmsgParseException(Exception):
pass
def parse_irc_privmsg(message, server):
"""Parse an IRC PRIVMSG command and return a dictionary.
Either the to_channel key or the to_nick key will be set depending on
whether the message is to a nick or a channel. The other will be None.
Example input:
:nick!user@host PRIVMSG #weechat :message here
Output:
{'from': 'nick!user@host',
'from_nick': 'nick',
'to': '#weechat',
'to_channel': '#weechat',
'to_nick': None,
'text': 'message here'}
"""
weechat_result = weechat.info_get_hashtable(
'irc_message_parse', dict(message=message))
if weechat_result['command'].upper() == 'PRIVMSG':
target, text = PYVER.to_unicode(
weechat_result['arguments']).split(' ', 1)
if text.startswith(':'):
text = text[1:]
result = {
'from': PYVER.to_unicode(weechat_result['host']),
'to' : target,
'text': text,
}
if weechat_result['host']:
result['from_nick'] = PYVER.to_unicode(weechat_result['nick'])
else:
result['from_nick'] = ''
if is_a_channel(target, server):
result['to_channel'] = target
result['to_nick'] = None
else:
result['to_channel'] = None
result['to_nick'] = target
return result
else:
raise PrivmsgParseException(message)
def has_otr_end(msg):
"""Return True if the message is the end of an OTR message."""
return msg.endswith('.') or msg.endswith(',')
def first_instance(objs, klass):
"""Return the first object in the list that is an instance of a class."""
for obj in objs:
if isinstance(obj, klass):
return obj
def config_prefix(option):
"""Add the config prefix to an option and return the full option name."""
return '{script}.{option}'.format(
script=SCRIPT_NAME,
option=option)
def config_color(option):
"""Get the color of a color config option."""
return weechat.color(weechat.config_color(weechat.config_get(
config_prefix('color.{}'.format(option)))))
def config_string(option):
"""Get the string value of a config option with utf-8 decode."""
return PYVER.to_unicode(weechat.config_string(
weechat.config_get(config_prefix(option))))
def buffer_get_string(buf, prop):
"""Wrap weechat.buffer_get_string() with utf-8 encode/decode."""
if buf is not None:
encoded_buf = PYVER.to_str(buf)
else:
encoded_buf = None
return PYVER.to_unicode(weechat.buffer_get_string(
encoded_buf, PYVER.to_str(prop)))
def buffer_is_private(buf):
"""Return True if a buffer is private."""
return buffer_get_string(buf, 'localvar_type') == 'private'
def info_get(info_name, arguments):
"""Wrap weechat.info_get() with utf-8 encode/decode."""
return PYVER.to_unicode(weechat.info_get(
PYVER.to_str(info_name), PYVER.to_str(arguments)))
def msg_irc_from_plain(msg):
"""Transform a plain-text message to irc format.
This will replace lines that start with /me with the respective
irc command."""
return PLAIN_ACTION_RE.sub('\x01ACTION \g<text>\x01', msg)
def msg_plain_from_irc(msg):
"""Transform an irc message to plain-text.
Any ACTION found will be rewritten as /me <text>."""
return IRC_ACTION_RE.sub(ACTION_PREFIX + r'\g<text>', msg)
def default_peer_args(args, buf):
"""Get the nick and server of a remote peer from command arguments or
a buffer.
args is the [nick, server] slice of arguments from a command.
If these are present, return them. If args is empty and the buffer buf
is private, return the remote nick and server of buf."""
result = None, None
if len(args) == 2:
result = tuple(args)
else:
if buffer_is_private(buf):
result = (
buffer_get_string(buf, 'localvar_channel'),
buffer_get_string(buf, 'localvar_server'))
return result
def format_default_policies():
"""Return current default policies formatted as a string for the user."""
buf = io.StringIO()
buf.write('Current default OTR policies:\n')
for policy, desc in sorted(POLICIES.items()):
buf.write(' {policy} ({desc}) : {value}\n'.format(
policy=policy,
desc=desc,
value=config_string('policy.default.{}'.format(policy))))
buf.write('Change default policies with: /otr policy default NAME on|off')
return buf.getvalue()
def to_bytes(strng):
"""Convert a python str or unicode to bytes."""
return strng.encode('utf-8', 'replace')
def colorize(msg, color):
"""Colorize each line of msg using color."""
result = []
colorstr = config_color(color)
for line in msg.splitlines():
result.append('{color}{msg}'.format(
color=colorstr,
msg=line))
return '\r\n'.join(result)
def accounts():
"""Return a list of all IrcOtrAccounts sorted by name."""
result = []
for key_path in glob.iglob(os.path.join(OTR_DIR, '*.key3')):
key_name, _ = os.path.splitext(os.path.basename(key_path))
result.append(ACCOUNTS[key_name])
return sorted(result, key=lambda account: account.name)
def show_account_fingerprints():
"""Print all account names and their fingerprints to the core buffer."""
table_formatter = TableFormatter()
for account in accounts():
table_formatter.add_row([
account.name,
str(account.getPrivkey())])
print_buffer('', table_formatter.format())
def show_peer_fingerprints(grep=None):
"""Print peer names and their fingerprints to the core buffer.
If grep is passed in, show all peer names containing that substring."""
trust_descs = {
'' : 'unverified',
'smp' : 'SMP verified',
'verified' : 'verified',
}
table_formatter = TableFormatter()
for account in accounts():
for peer, peer_data in sorted(account.trusts.items()):
for fingerprint, trust in sorted(peer_data.items()):
if grep is None or grep in peer:
table_formatter.add_row([
peer,
account.name,
potr.human_hash(fingerprint),
trust_descs[trust],
])
print_buffer('', table_formatter.format())
def private_key_file_path(account_name):
"""Return the private key file path for an account."""
return os.path.join(OTR_DIR, '{}.key3'.format(account_name))
def read_private_key(key_file_path):
"""Return the private key in a private key file."""
debug(('read private key', key_file_path))
with open(key_file_path, 'rb') as key_file:
return potr.crypt.PK.parsePrivateKey(key_file.read())[0]
class AccountDict(collections.defaultdict):
"""Dictionary that adds missing keys as IrcOtrAccount instances."""
def __missing__(self, key):
debug(('add account', key))
self[key] = IrcOtrAccount(key)
return self[key]
class Assembler(object):
"""Reassemble fragmented OTR messages.
This does not deal with OTR fragmentation, which is handled by potr, but
fragmentation of received OTR messages that are too large for IRC.
"""
def __init__(self):
self.clear()
def add(self, data):
"""Add data to the buffer."""
self.value += data
def clear(self):
"""Empty the buffer."""
self.value = ''
def is_done(self):
"""Return True if the buffer is a complete message."""
return self.is_query() or \
not to_bytes(self.value).startswith(potr.proto.OTRTAG) or \
has_otr_end(self.value)
def get(self):
"""Return the current value of the buffer and empty it."""
result = self.value
self.clear()
return result
def is_query(self):
"""Return true if the buffer is an OTR query."""
return OTR_QUERY_RE.search(self.value)
class IrcContext(potr.context.Context):
"""Context class for OTR over IRC."""
def __init__(self, account, peername):
super(IrcContext, self).__init__(account, peername)
self.peer_nick, self.peer_server = peername.split('@', 1)
self.in_assembler = Assembler()
self.in_otr_message = False
self.in_smp = False
self.smp_question = False
def policy_config_option(self, policy):
"""Get the option name of a policy option for this context."""
return config_prefix('.'.join([
'policy', self.peer_server, self.user.nick, self.peer_nick,
policy.lower()]))
def getPolicy(self, key):
"""Get the value of a policy option for this context."""
key_lower = key.lower()
if key_lower in READ_ONLY_POLICIES:
result = READ_ONLY_POLICIES[key_lower]
elif key_lower == 'send_tag' and self.no_send_tag():
result = False
else:
option = weechat.config_get(
PYVER.to_str(self.policy_config_option(key)))
if option == '':
option = weechat.config_get(
PYVER.to_str(self.user.policy_config_option(key)))
if option == '':
option = weechat.config_get(config_prefix('.'.join(
['policy', self.peer_server, key_lower])))
if option == '':
option = weechat.config_get(
config_prefix('policy.default.{}'.format(key_lower)))
result = bool(weechat.config_boolean(option))
debug(('getPolicy', key, result))
return result
def inject(self, msg, appdata=None):
"""Send a message to the remote peer."""
if isinstance(msg, potr.proto.OTRMessage):
msg = PYVER.unicode(msg)
else:
msg = PYVER.to_unicode(msg)
debug(('inject', msg, 'len {}'.format(len(msg)), appdata))
privmsg(self.peer_server, self.peer_nick, msg)
def setState(self, newstate):
"""Handle state transition."""
debug(('state', self.state, newstate))
if self.is_encrypted():
if newstate == potr.context.STATE_ENCRYPTED:
self.print_buffer(
'Private conversation has been refreshed.', 'success')
elif newstate == potr.context.STATE_FINISHED:
self.print_buffer(
'{peer} has ended the private conversation. You should do '
'the same:\n/otr finish'.format(peer=self.peer_nick))
elif newstate == potr.context.STATE_ENCRYPTED:
# unencrypted => encrypted
trust = self.getCurrentTrust()
# Disable logging before any proof of OTR activity is generated.
# This is necessary when the session is started automatically, and
# not by /otr start.
if not self.getPolicy('log'):
self.previous_log_level = self.disable_logging()
else:
self.previous_log_level = self.get_log_level()
if self.is_logged():
self.hint(
'You have enabled the recording to disk of OTR '
'conversations. By doing this you are potentially '
'putting yourself and your correspondent in danger. '
'Please consider disabling this policy with '
'"/otr policy default log off". To disable logging '
'for this OTR session, use "/otr log stop"')
if trust is None:
fpr = str(self.getCurrentKey())
self.print_buffer('New fingerprint: {}'.format(fpr), 'warning')
self.setCurrentTrust('')
if bool(trust):
self.print_buffer(
'Authenticated secured OTR conversation started.',
'success')
else:
self.print_buffer(
'Unauthenticated secured OTR conversation started.',
'warning')
self.hint(self.verify_instructions())
if self.state != potr.context.STATE_PLAINTEXT and \
newstate == potr.context.STATE_PLAINTEXT:
self.print_buffer('Private conversation ended.')
# If we altered the logging value, restore it.
if self.previous_log_level is not None:
self.restore_logging(self.previous_log_level)
super(IrcContext, self).setState(newstate)
def maxMessageSize(self, appdata=None):
"""Return the max message size for this context."""
# remove 'PRIVMSG <nick> :' from max message size
result = self.user.maxMessageSize - 10 - len(self.peer_nick)
debug('max message size {}'.format(result))
return result
def buffer(self):
"""Get the buffer for this context."""
return info_get(
'irc_buffer', '{server},{nick}'.format(
server=self.peer_server,
nick=self.peer_nick
))
def print_buffer(self, msg, level='info'):
"""Print a message to the buffer for this context.
level is used to colorize the message."""
buf = self.buffer()
# add [nick] prefix if we have only a server buffer for the query
if self.peer_nick and not buffer_is_private(buf):
msg = '[{nick}] {msg}'.format(
nick=self.peer_nick,
msg=msg)
print_buffer(buf, msg, level)
def hint(self, msg):
"""Print a message to the buffer but only when hints are enabled."""
hints_option = weechat.config_get(config_prefix('general.hints'))
if weechat.config_boolean(hints_option):
self.print_buffer(msg, 'hint')
def smp_finish(self, message=False, level='info'):
"""Reset SMP state and send a message to the user."""
self.in_smp = False
self.smp_question = False
self.user.saveTrusts()
if message:
self.print_buffer(message, level)
def handle_tlvs(self, tlvs):
"""Handle SMP states."""
if tlvs:
smp1q = first_instance(tlvs, potr.proto.SMP1QTLV)
smp3 = first_instance(tlvs, potr.proto.SMP3TLV)
smp4 = first_instance(tlvs, potr.proto.SMP4TLV)
if first_instance(tlvs, potr.proto.SMPABORTTLV):
debug('SMP aborted by peer')
self.smp_finish('SMP aborted by peer.', 'warning')
elif self.in_smp and not self.smpIsValid():
debug('SMP aborted')
self.smp_finish('SMP aborted.', 'error')
elif first_instance(tlvs, potr.proto.SMP1TLV):
debug('SMP1')
self.in_smp = True
self.print_buffer(
"""Peer has requested SMP verification.
Respond with: /otr smp respond <secret>""")
elif smp1q:
debug(('SMP1Q', smp1q.msg))
self.in_smp = True
self.smp_question = True
self.print_buffer(
"""Peer has requested SMP verification: {msg}
Respond with: /otr smp respond <answer>""".format(
msg=PYVER.to_unicode(smp1q.msg)))
elif first_instance(tlvs, potr.proto.SMP2TLV):
if not self.in_smp:
debug('Received unexpected SMP2')
self.smp_finish()
else:
debug('SMP2')
self.print_buffer('SMP progressing.')
elif smp3 or smp4:
if smp3:
debug('SMP3')
elif smp4:
debug('SMP4')
if self.smpIsSuccess():
if self.smp_question:
self.smp_finish('SMP verification succeeded.',
'success')
if not self.is_verified:
self.print_buffer(
"""You may want to authenticate your peer by asking your own question:
/otr smp ask <'question'> 'secret'""")
else:
self.smp_finish('SMP verification succeeded.',
'success')
else:
self.smp_finish('SMP verification failed.', 'error')
def verify_instructions(self):
"""Generate verification instructions for user."""
return """You can verify that this contact is who they claim to be in one of the following ways:
1) Verify each other's fingerprints using a secure channel:
Your fingerprint : {your_fp}
{peer}'s fingerprint : {peer_fp}
then use the command: /otr trust {peer_nick} {peer_server}
2) SMP pre-shared secret that you both know:
/otr smp ask {peer_nick} {peer_server} 'secret'
3) SMP pre-shared secret that you both know with a question:
/otr smp ask {peer_nick} {peer_server} <'question'> 'secret'
Note: You can safely omit specifying the peer and server when
executing these commands from the appropriate conversation
buffer
""".format(
your_fp=self.user.getPrivkey(),
peer=self.peer,
peer_nick=self.peer_nick,
peer_server=self.peer_server,
peer_fp=potr.human_hash(
self.crypto.theirPubkey.cfingerprint()),
)
def is_encrypted(self):
"""Return True if the conversation with this context's peer is
currently encrypted."""
return self.state == potr.context.STATE_ENCRYPTED
def is_verified(self):
"""Return True if this context's peer is verified."""
return bool(self.getCurrentTrust())
def format_policies(self):
"""Return current policies for this context formatted as a string for
the user."""
buf = io.StringIO()
buf.write('Current OTR policies for {peer}:\n'.format(
peer=self.peer))
for policy, desc in sorted(POLICIES.items()):
buf.write(' {policy} ({desc}) : {value}\n'.format(
policy=policy,
desc=desc,
value='on' if self.getPolicy(policy) else 'off'))
buf.write('Change policies with: /otr policy NAME on|off')
return buf.getvalue()
def is_logged(self):
"""Return True if conversations with this context's peer are currently
being logged to disk."""
infolist = weechat.infolist_get('logger_buffer', '', '')
buf = self.buffer()
result = False
while weechat.infolist_next(infolist):
if weechat.infolist_pointer(infolist, 'buffer') == buf:
result = bool(weechat.infolist_integer(infolist, 'log_enabled'))
break
weechat.infolist_free(infolist)
return result
def get_log_level(self):
"""Return the current logging level for this context's peer
or -1 if the buffer uses the default log level of weechat."""
infolist = weechat.infolist_get('logger_buffer', '', '')
buf = self.buffer()
if not weechat.config_get(self.get_logger_option_name(buf)):
result = -1
else:
result = 0
while weechat.infolist_next(infolist):
if weechat.infolist_pointer(infolist, 'buffer') == buf:
result = weechat.infolist_integer(infolist, 'log_level')
break
weechat.infolist_free(infolist)
return result
def get_logger_option_name(self, buf):
"""Returns the logger config option for the specified buffer."""
name = buffer_get_string(buf, 'name')
plugin = buffer_get_string(buf, 'plugin')
return 'logger.level.{plugin}.{name}'.format(
plugin=plugin, name=name)
def disable_logging(self):
"""Return the previous logger level and set the buffer logger level
to 0. If it was already 0, return None."""
# If previous_log_level has not been previously set, return the level
# we detect now.
if not hasattr(self, 'previous_log_level'):
previous_log_level = self.get_log_level()
if self.is_logged():
weechat.command(self.buffer(), '/mute logger disable')
self.print_buffer(
'Logs have been temporarily disabled for the session. They will be restored upon finishing the OTR session.')
return previous_log_level
# If previous_log_level was already set, it means we already altered it
# and that we just detected an already modified logging level.
# Return the pre-existing value so it doesn't get lost, and we can
# restore it later.
else:
return self.previous_log_level
def restore_logging(self, previous_log_level):
"""Restore the log level of the buffer."""
buf = self.buffer()
if (previous_log_level >= 0) and (previous_log_level < 10):
self.print_buffer(
'Restoring buffer logging value to: {}'.format(
previous_log_level), 'warning')
weechat.command(buf, '/mute logger set {}'.format(
previous_log_level))
if previous_log_level == -1:
logger_option_name = self.get_logger_option_name(buf)
self.print_buffer(
'Restoring buffer logging value to default', 'warning')
weechat.command(buf, '/mute unset {}'.format(
logger_option_name))
del self.previous_log_level
def msg_convert_in(self, msg):
"""Transform incoming OTR message to IRC format.
This includes stripping html, converting plain-text ACTIONs
and character encoding conversion.
Only character encoding is changed if context is unencrypted."""
msg = PYVER.to_unicode(msg)
if not self.is_encrypted():
return msg
if self.getPolicy('html_filter'):
try:
msg = IrcHTMLParser.parse(msg)
except PYVER.html_parser.HTMLParseError:
pass
return msg_irc_from_plain(msg)
def msg_convert_out(self, msg):
"""Convert an outgoing IRC message to be sent over OTR.
This includes escaping html, converting ACTIONs to plain-text
and character encoding conversion
Only character encoding is changed if context is unencrypted."""
if self.is_encrypted():
msg = msg_plain_from_irc(msg)
if self.getPolicy('html_escape'):
msg = PYVER.html_escape(msg)
# potr expects bytes to be returned
return to_bytes(msg)
def no_send_tag(self):
"""Skip OTR whitespace tagging to bots and services.
Any nicks matching the otr.general.no_send_tag_regex config setting
will not be tagged.
"""
no_send_tag_regex = config_string('general.no_send_tag_regex')
debug(('no_send_tag', no_send_tag_regex, self.peer_nick))
if no_send_tag_regex:
return re.match(no_send_tag_regex, self.peer_nick, re.IGNORECASE)
def __repr__(self):
return PYVER.to_str(('<{} {:x} peer_nick={c.peer_nick} '
'peer_server={c.peer_server}>').format(
self.__class__.__name__, id(self), c=self))
class IrcOtrAccount(potr.context.Account):
"""Account class for OTR over IRC."""