Commit 3c78b09f authored by Philipp Hörist's avatar Philipp Hörist
Browse files

[omemo] Refactor Plugin

- Adapt to nbxmpp supporting OMEMO
- Move python-axolotl code into backend folder
parent a6ed3149
from .omemoplugin import OmemoPlugin
from omemo.plugin import OmemoPlugin
# -*- coding: utf-8 -*-
#
# Copyright 2015 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
#
# This file is part of python-omemo library.
#
# The python-omemo library 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.
#
# python-omemo 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
# the python-omemo library. If not, see <http://www.gnu.org/licenses/>.
#
import os
import logging
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers.modes import GCM
# On Windows we have to import a specific backend because the
# default_backend() mechanism doesn't work in Gajim for Windows.
# Its because of how Gajim is build with cx_freeze
if os.name == 'nt':
from cryptography.hazmat.backends.openssl import backend
else:
from cryptography.hazmat.backends import default_backend
log = logging.getLogger('gajim.plugin_system.omemo')
def aes_decrypt(_key, iv, payload):
""" Use AES128 GCM with the given key and iv to decrypt the payload. """
if len(_key) >= 32:
# XEP-0384
log.debug('XEP Compliant Key/Tag')
data = payload
key = _key[:16]
tag = _key[16:]
else:
# Legacy
log.debug('Legacy Key/Tag')
data = payload[:-16]
key = _key
tag = payload[-16:]
if os.name == 'nt':
_backend = backend
else:
_backend = default_backend()
decryptor = Cipher(
algorithms.AES(key),
GCM(iv, tag=tag),
backend=_backend).decryptor()
return decryptor.update(data) + decryptor.finalize()
def aes_encrypt(key, iv, plaintext):
""" Use AES128 GCM with the given key and iv to encrypt the plaintext. """
if os.name == 'nt':
_backend = backend
else:
_backend = default_backend()
encryptor = Cipher(
algorithms.AES(key),
GCM(iv),
backend=_backend).encryptor()
return encryptor.update(plaintext) + encryptor.finalize(), encryptor.tag
# Copyright (C) 2019 Philipp Hörist <philipp AT hoerist.com>
#
# This file is part of OMEMO Gajim Plugin.
#
# OMEMO Gajim Plugin 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; version 3 only.
#
# OMEMO Gajim Plugin 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 OMEMO Gajim Plugin. If not, see <http://www.gnu.org/licenses/>.
import os
import logging
from collections import namedtuple
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers.modes import GCM
from cryptography.hazmat.backends import default_backend
log = logging.getLogger('gajim.plugin_system.omemo')
EncryptionResult = namedtuple('EncryptionResult', 'payload key iv')
def _decrypt(key, iv, tag, data):
decryptor = Cipher(
algorithms.AES(key),
GCM(iv, tag=tag),
backend=default_backend()).decryptor()
return decryptor.update(data) + decryptor.finalize()
def aes_decrypt(_key, iv, payload):
if len(_key) >= 32:
# XEP-0384
log.debug('XEP Compliant Key/Tag')
data = payload
key = _key[:16]
tag = _key[16:]
else:
# Legacy
log.debug('Legacy Key/Tag')
data = payload[:-16]
key = _key
tag = payload[-16:]
return _decrypt(key, iv, tag, data).decode()
def aes_decrypt_file(key, iv, payload):
data = payload[:-16]
tag = payload[-16:]
return _decrypt(key, iv, tag, data)
def _encrypt(data, key_size, iv_size):
if isinstance(data, str):
data = data.encode()
key = os.urandom(key_size)
iv = os.urandom(iv_size)
encryptor = Cipher(
algorithms.AES(key),
GCM(iv),
backend=default_backend()).encryptor()
payload = encryptor.update(data) + encryptor.finalize()
return key, iv, encryptor.tag, payload
def aes_encrypt(plaintext):
key, iv, tag, payload = _encrypt(plaintext, 16, 16)
key += tag
return EncryptionResult(payload=payload, key=key, iv=iv)
def aes_encrypt_file(data):
key, iv, tag, payload, = _encrypt(data, 32, 16)
payload += tag
return EncryptionResult(payload=payload, key=key, iv=iv)
''' Database helper functions '''
def table_exists(db, name):
""" Check if the specified table exists in the db. """
query = """ SELECT name FROM sqlite_master
WHERE type='table' AND name=?;
"""
return db.execute(query, (name, )).fetchone() is not None
def user_version(db):
""" Return the value of PRAGMA user_version. """
return db.execute('PRAGMA user_version').fetchone()[0]
''' Database helper functions '''
def table_exists(db, name):
""" Check if the specified table exists in the db. """
query = """ SELECT name FROM sqlite_master
WHERE type='table' AND name=?;
"""
return db.execute(query, (name, )).fetchone() is not None
def user_version(db):
""" Return the value of PRAGMA user_version. """
return db.execute('PRAGMA user_version').fetchone()[0]
# -*- coding: utf-8 -*-
#
# Copyright 2015 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
# Copyright 2015 Daniel Gultsch <daniel@cgultsch.de>
#
# This file is part of Gajim-OMEMO plugin.
#
# The Gajim-OMEMO plugin 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.
#
# Gajim-OMEMO 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
# the Gajim-OMEMO plugin. If not, see <http://www.gnu.org/licenses/>.
#
class EncryptionState():
""" Used to store if OMEMO is enabled or not between gajim restarts """
def __init__(self, dbConn):
"""
:type dbConn: Connection
"""
self.dbConn = dbConn
def activate(self, jid):
q = """INSERT OR REPLACE INTO encryption_state (jid, encryption)
VALUES (?, 1) """
c = self.dbConn.cursor()
c.execute(q, (jid, ))
self.dbConn.commit()
def deactivate(self, jid):
q = """INSERT OR REPLACE INTO encryption_state (jid, encryption)
VALUES (?, 0)"""
c = self.dbConn.cursor()
c.execute(q, (jid, ))
self.dbConn.commit()
def is_active(self, jid):
q = 'SELECT encryption FROM encryption_state where jid = ?;'
c = self.dbConn.cursor()
c.execute(q, (jid, ))
result = c.fetchone()
if result is None:
return False
return result[0]
def exist(self, jid):
q = 'SELECT encryption FROM encryption_state where jid = ?;'
c = self.dbConn.cursor()
c.execute(q, (jid, ))
result = c.fetchone()
if result is None:
return False
else:
return True
# -*- coding: utf-8 -*-
#
# Copyright 2015 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
# Copyright 2015 Daniel Gultsch <daniel@cgultsch.de>
#
# This file is part of Gajim-OMEMO plugin.
#
# The Gajim-OMEMO plugin 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.
#
# Gajim-OMEMO 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
# the Gajim-OMEMO plugin. If not, see <http://www.gnu.org/licenses/>.
#
class EncryptionState():
""" Used to store if OMEMO is enabled or not between gajim restarts """
def __init__(self, dbConn):
"""
:type dbConn: Connection
"""
self.dbConn = dbConn
def activate(self, jid):
q = """INSERT OR REPLACE INTO encryption_state (jid, encryption)
VALUES (?, 1) """
c = self.dbConn.cursor()
c.execute(q, (jid, ))
self.dbConn.commit()
def deactivate(self, jid):
q = """INSERT OR REPLACE INTO encryption_state (jid, encryption)
VALUES (?, 0)"""
c = self.dbConn.cursor()
c.execute(q, (jid, ))
self.dbConn.commit()
def is_active(self, jid):
q = 'SELECT encryption FROM encryption_state where jid = ?;'
c = self.dbConn.cursor()
c.execute(q, (jid, ))
result = c.fetchone()
if result is None:
return False
return result[0]
def exist(self, jid):
q = 'SELECT encryption FROM encryption_state where jid = ?;'
c = self.dbConn.cursor()
c.execute(q, (jid, ))
result = c.fetchone()
if result is None:
return False
else:
return True
# -*- coding: utf-8 -*-
#
# Copyright 2015 Tarek Galal <tare2.galal@gmail.com>
#
# This file is part of Gajim-OMEMO plugin.
#
# The Gajim-OMEMO plugin 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.
#
# Gajim-OMEMO 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
# the Gajim-OMEMO plugin. If not, see <http://www.gnu.org/licenses/>.
#
import logging
from axolotl.state.axolotlstore import AxolotlStore
from axolotl.util.keyhelper import KeyHelper
from .liteidentitykeystore import LiteIdentityKeyStore
from .liteprekeystore import LitePreKeyStore
from .litesessionstore import LiteSessionStore
from .litesignedprekeystore import LiteSignedPreKeyStore
from .encryption import EncryptionState
from .sql import SQLDatabase
log = logging.getLogger('gajim.plugin_system.omemo')
DEFAULT_PREKEY_AMOUNT = 100
MIN_PREKEY_AMOUNT = 80
SPK_ARCHIVE_TIME = 86400 * 15 # 15 Days
SPK_CYCLE_TIME = 86400 # 24 Hours
class LiteAxolotlStore(AxolotlStore):
def __init__(self, connection):
try:
connection.text_factory = bytes
except(AttributeError):
raise AssertionError('Expected a sqlite3.Connection got ' +
str(connection))
self.sql = SQLDatabase(connection)
self.identityKeyStore = LiteIdentityKeyStore(connection)
self.preKeyStore = LitePreKeyStore(connection)
self.signedPreKeyStore = LiteSignedPreKeyStore(connection)
self.sessionStore = LiteSessionStore(connection)
self.encryptionStore = EncryptionState(connection)
if not self.getLocalRegistrationId():
log.info("Generating Axolotl keys")
self._generate_axolotl_keys()
def _generate_axolotl_keys(self):
identityKeyPair = KeyHelper.generateIdentityKeyPair()
registrationId = KeyHelper.generateRegistrationId()
preKeys = KeyHelper.generatePreKeys(KeyHelper.getRandomSequence(),
DEFAULT_PREKEY_AMOUNT)
self.storeLocalData(registrationId, identityKeyPair)
signedPreKey = KeyHelper.generateSignedPreKey(
identityKeyPair, KeyHelper.getRandomSequence(65536))
self.storeSignedPreKey(signedPreKey.getId(), signedPreKey)
for preKey in preKeys:
self.storePreKey(preKey.getId(), preKey)
def getIdentityKeyPair(self):
return self.identityKeyStore.getIdentityKeyPair()
def storeLocalData(self, registrationId, identityKeyPair):
self.identityKeyStore.storeLocalData(registrationId, identityKeyPair)
def getLocalRegistrationId(self):
return self.identityKeyStore.getLocalRegistrationId()
def saveIdentity(self, recepientId, identityKey):
self.identityKeyStore.saveIdentity(recepientId, identityKey)
def deleteIdentity(self, recipientId, identityKey):
self.identityKeyStore.deleteIdentity(recipientId, identityKey)
def isTrustedIdentity(self, recepientId, identityKey):
return self.identityKeyStore.isTrustedIdentity(recepientId,
identityKey)
def setTrust(self, identityKey, trust):
return self.identityKeyStore.setTrust(identityKey, trust)
def getTrustedFingerprints(self, jid):
return self.identityKeyStore.getTrustedFingerprints(jid)
def getUndecidedFingerprints(self, jid):
return self.identityKeyStore.getUndecidedFingerprints(jid)
def setShownFingerprints(self, jid):
return self.identityKeyStore.setShownFingerprints(jid)
def getNewFingerprints(self, jid):
return self.identityKeyStore.getNewFingerprints(jid)
def loadPreKey(self, preKeyId):
return self.preKeyStore.loadPreKey(preKeyId)
def loadPreKeys(self):
return self.preKeyStore.loadPendingPreKeys()
def storePreKey(self, preKeyId, preKeyRecord):
self.preKeyStore.storePreKey(preKeyId, preKeyRecord)
def containsPreKey(self, preKeyId):
return self.preKeyStore.containsPreKey(preKeyId)
def removePreKey(self, preKeyId):
self.preKeyStore.removePreKey(preKeyId)
def loadSession(self, recepientId, deviceId):
return self.sessionStore.loadSession(recepientId, deviceId)
def getActiveDeviceTuples(self):
return self.sessionStore.getActiveDeviceTuples()
def getInactiveSessionsKeys(self, recipientId):
return self.sessionStore.getInactiveSessionsKeys(recipientId)
def getSubDeviceSessions(self, recepientId):
# TODO Reuse this
return self.sessionStore.getSubDeviceSessions(recepientId)
def getJidFromDevice(self, device_id):
return self.sessionStore.getJidFromDevice(device_id)
def storeSession(self, recepientId, deviceId, sessionRecord):
self.sessionStore.storeSession(recepientId, deviceId, sessionRecord)
def containsSession(self, recepientId, deviceId):
return self.sessionStore.containsSession(recepientId, deviceId)
def deleteSession(self, recepientId, deviceId):
self.sessionStore.deleteSession(recepientId, deviceId)
def deleteAllSessions(self, recepientId):
self.sessionStore.deleteAllSessions(recepientId)
def getSessionsFromJid(self, recipientId):
return self.sessionStore.getSessionsFromJid(recipientId)
def getSessionsFromJids(self, recipientId):
return self.sessionStore.getSessionsFromJids(recipientId)
def getAllSessions(self):
return self.sessionStore.getAllSessions()
def loadSignedPreKey(self, signedPreKeyId):
return self.signedPreKeyStore.loadSignedPreKey(signedPreKeyId)
def loadSignedPreKeys(self):
return self.signedPreKeyStore.loadSignedPreKeys()
def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):
self.signedPreKeyStore.storeSignedPreKey(signedPreKeyId,
signedPreKeyRecord)
def containsSignedPreKey(self, signedPreKeyId):
return self.signedPreKeyStore.containsSignedPreKey(signedPreKeyId)
def removeSignedPreKey(self, signedPreKeyId):
self.signedPreKeyStore.removeSignedPreKey(signedPreKeyId)
def getNextSignedPreKeyId(self):
return self.signedPreKeyStore.getNextSignedPreKeyId()
def getCurrentSignedPreKeyId(self):
return self.signedPreKeyStore.getCurrentSignedPreKeyId()
def getSignedPreKeyTimestamp(self, signedPreKeyId):
return self.signedPreKeyStore.getSignedPreKeyTimestamp(signedPreKeyId)
def removeOldSignedPreKeys(self, timestamp):
self.signedPreKeyStore.removeOldSignedPreKeys(timestamp)
# -*- coding: utf-8 -*-
#
# Copyright 2015 Tarek Galal <tare2.galal@gmail.com>
#
# This file is part of Gajim-OMEMO plugin.
#
# The Gajim-OMEMO plugin 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.
#
# Gajim-OMEMO 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
# the Gajim-OMEMO plugin. If not, see <http://www.gnu.org/licenses/>.
#
import logging
from axolotl.state.axolotlstore import AxolotlStore
from axolotl.util.keyhelper import KeyHelper
from .liteidentitykeystore import LiteIdentityKeyStore
from .liteprekeystore import LitePreKeyStore
from .litesessionstore import LiteSessionStore
from .litesignedprekeystore import LiteSignedPreKeyStore
from .encryption import EncryptionState
from .sql import SQLDatabase
log = logging.getLogger('gajim.plugin_system.omemo')
DEFAULT_PREKEY_AMOUNT = 100
MIN_PREKEY_AMOUNT = 80
SPK_ARCHIVE_TIME = 86400 * 15 # 15 Days
SPK_CYCLE_TIME = 86400 # 24 Hours
class LiteAxolotlStore(AxolotlStore):
def __init__(self, connection):
try:
connection.text_factory = bytes
except(AttributeError):
raise AssertionError('Expected a sqlite3.Connection got ' +
str(connection))
self.sql = SQLDatabase(connection)
self.identityKeyStore = LiteIdentityKeyStore(connection)
self.preKeyStore = LitePreKeyStore(connection)
self.signedPreKeyStore = LiteSignedPreKeyStore(connection)
self.sessionStore = LiteSessionStore(connection)
self.encryptionStore = EncryptionState(connection)
if not self.getLocalRegistrationId():
log.info("Generating Axolotl keys")
self._generate_axolotl_keys()
def _generate_axolotl_keys(self):
identityKeyPair = KeyHelper.generateIdentityKeyPair()
registrationId = KeyHelper.generateRegistrationId()
preKeys = KeyHelper.generatePreKeys(KeyHelper.getRandomSequence(),
DEFAULT_PREKEY_AMOUNT)
self.storeLocalData(registrationId, identityKeyPair)
signedPreKey = KeyHelper.generateSignedPreKey(
identityKeyPair, KeyHelper.getRandomSequence(65536))
self.storeSignedPreKey(signedPreKey.getId(), signedPreKey)
for preKey in preKeys:
self.storePreKey(preKey.getId(), preKey)
def getIdentityKeyPair(self):
return self.identityKeyStore.getIdentityKeyPair()
def storeLocalData(self, registrationId, identityKeyPair):
self.identityKeyStore.storeLocalData(registrationId, identityKeyPair)
def getLocalRegistrationId(self):
return self.identityKeyStore.getLocalRegistrationId()
def saveIdentity(self, recepientId, identityKey):
self.identityKeyStore.saveIdentity(recepientId, identityKey)
def deleteIdentity(self, recipientId, identityKey):
self.identityKeyStore.deleteIdentity(recipientId, identityKey)