OTR plugin for Gajim 1.0+
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

otr.py 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. ## Copyright (C) 2008-2012 Kjell Braden <afflux@pentabarf.de>
  2. ## Copyright (C) 2019 Pavel R. <pd at narayana dot im>
  3. #
  4. # This file is part of Gajim OTR Plugin.
  5. #
  6. # Gajim OTR Plugin is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published
  8. # by the Free Software Foundation; version 3 only.
  9. #
  10. # This software is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You can always obtain full license text at <http://www.gnu.org/licenses/>.
  16. import os
  17. from inspect import signature
  18. from gajim.common import const, app, helpers, configpaths
  19. from gajim.session import ChatControlSession
  20. from nbxmpp.protocol import Message, JID
  21. from potr import context, crypt, proto
  22. from .keystore import Keystore
  23. # Prototype of OTR Channel (secure conversations between Gajim user (Alice) and Gajim peer (Bob)
  24. class OTRChannel(context.Context):
  25. # this method may be called self.sendMessage() when we need to send some data to our <peer> via XMPP
  26. def inject(self,msg,appdata=None):
  27. stanza = Message(to=self.peer, body=msg.decode(), typ='chat')
  28. stanza.setThread(appdata or ChatControlSession.generate_thread_id(None))
  29. self.user.stream.send_stanza(stanza)
  30. # this method called on channel state change
  31. def setState(self,state=0):
  32. if state and state != self.state:
  33. self.getCurrentTrust() is None and self.setCurrentTrust(0) != 0 and self.printl(OTR.TRUSTED[None].format(fprint=self.getCurrentKey())) # new fingerprint
  34. self.printl(OTR.STATUS[state].format(peer=self.peer,trust=OTR.TRUSTED[self.getCurrentTrust()],fprint=self.getCurrentKey())) # state is changed
  35. self.state = state
  36. # print some text to chat window
  37. def printl(self,line):
  38. println = self.user.getControl(self.peer) and self.user.getControl(self.peer).conv_textview.print_conversation_line
  39. println and println("OTR: "+line,kind='status',name='',tim='',**('jid' in signature(println).parameters and {'jid':None} or {}))
  40. @staticmethod
  41. def getPolicy(policy): return OTR.DEFAULT_POLICY.get(policy)
  42. # OTR instance for Gajim user (Alice)
  43. class OTR(context.Account):
  44. PROTO = ('XMPP', 1024)
  45. ENCRYPTION_NAME = ('OTR')
  46. DEFAULT_POLICY = {
  47. 'REQUIRE_ENCRYPTION': True,
  48. 'ALLOW_V1': False,
  49. 'ALLOW_V2': True,
  50. 'SEND_TAG': True,
  51. 'WHITESPACE_START_AKE': True,
  52. 'ERROR_START_AKE': True,
  53. }
  54. TRUSTED = {None:"new fingerprint received: *{fprint}*", 0:"untrusted", 1:"trusted", 2:"authenticated"}
  55. STATUS = {
  56. context.STATE_PLAINTEXT: "(re-)starting encrypted conversation with {peer}..",
  57. context.STATE_ENCRYPTED: "{trust} encrypted conversation started (fingerprint: {fprint})",
  58. context.STATE_FINISHED: "encrypted conversation with {peer} closed (fingerprint: {fprint})",
  59. context.UnencryptedMessage: "this message is *not encrypted*: {msg}",
  60. context.NotEncryptedError: "unable to process message (channel lost)",
  61. context.ErrorReceived: "received error message: {err}",
  62. crypt.InvalidParameterError: "unable to decrypt message (key/signature mismatch)",
  63. }
  64. def __init__(self,plugin,account):
  65. super(OTR,self).__init__(account,*OTR.PROTO)
  66. self.plugin = plugin
  67. self.log = plugin.log
  68. self.account = account
  69. self.stream = app.connections[account]
  70. self.jid = self.stream.get_own_jid()
  71. self.keystore = Keystore(os.path.join(configpaths.get('MY_DATA'), 'otr_' + self.jid.getStripped() + '.db'))
  72. self.loadTrusts()
  73. # get chat control
  74. def getControl(self,peer):
  75. ctl = app.interface.msg_win_mgr.get_control(peer.getStripped(),self.account)
  76. return ctl
  77. # get OTR context (encrypted dialog between Alice and Bob)
  78. def getContext(self,peer):
  79. peer in self.ctxs and self.ctxs[peer].state == context.STATE_FINISHED and self.ctxs.pop(peer).disconnect() # close dead channels
  80. self.ctxs[peer] = self.ctxs.get(peer) or OTRChannel(self,peer)
  81. return self.ctxs[peer]
  82. # load my private key
  83. def loadPrivkey(self):
  84. my = self.keystore.load(jid=self.jid)
  85. return (my and my.privatekey) and crypt.PK.parsePrivateKey(bytes.fromhex(my.privatekey))[0] or None
  86. # save my privatekey
  87. def savePrivkey(self):
  88. self.keystore.save(jid=self.jid,privatekey=self.getPrivkey().serializePrivateKey().hex())
  89. # load known fingerprints
  90. def loadTrusts(self):
  91. for peer in self.keystore.load(): self.setTrust(peer.jid,peer.fingerprint,peer.trust)
  92. # save known fingerprints
  93. def saveTrusts(self):
  94. for peer,fingerprints in self.trusts.items():
  95. for fingerprint,trust in fingerprints.items(): self.keystore.save(jid=peer,fingerprint=fingerprint,trust=trust)
  96. # decrypt message
  97. def decrypt(self,event,callback):
  98. peer = event.stanza.getFrom()
  99. channel, ctl = self.getContext(peer), self.getControl(peer)
  100. try:
  101. text, tlvs = channel.receiveMessage(event.msgtxt.encode(),appdata=event.stanza.getThread()) or b''
  102. except (context.UnencryptedMessage,context.NotEncryptedError,context.ErrorReceived,crypt.InvalidParameterError) as e:
  103. self.log.error("** got exception while decrypting message: %s" % e)
  104. channel.printl(OTR.STATUS[e].format(msg=event.msgtxt,err=e.args[0].error))
  105. else:
  106. event.msgtxt = text and text.decode() or ""
  107. event.encrypted = OTR.ENCRYPTION_NAME
  108. event.additional_data["encrypted"] = {"name":OTR.ENCRYPTION_NAME}
  109. callback(event)
  110. finally:
  111. if channel.mayRetransmit and channel.state and ctl: channel.mayRetransmit = ctl.send_message(channel.lastMessage.decode())
  112. # encrypt message
  113. def encrypt(self,event,callback):
  114. peer = event.msg_iq.getTo()
  115. channel, ctl = self.getContext(peer), event.control
  116. if event.xhtml: return ctl.send_message(event.message) # skip xhtml messages
  117. try:
  118. encrypted = channel.sendMessage(context.FRAGMENT_SEND_ALL_BUT_LAST,event.message.encode(),appdata=event.msg_iq.getThread()) or b''
  119. message = (encrypted != self.getDefaultQueryMessage(OTR.DEFAULT_POLICY.get)) and event.message or ""
  120. except context.NotEncryptedError as e:
  121. self.log.error("** got exception while encrypting message: %s" % e)
  122. channel.printl(peer,OTR.STATUS[e])
  123. else:
  124. event.msg_iq.setBody(encrypted.decode()) # encrypted data goes here
  125. event.message = message # message that will be displayed in our chat goes here
  126. event.encrypted, event.additional_data["encrypted"] = OTR.ENCRYPTION_NAME, {"name":OTR.ENCRYPTION_NAME} # some mandatory encryption flags
  127. callback(event)