diff options
| author | Marvin W <git@larma.de> | 2026-10-04 14:42:16 +0200 |
|---|---|---|
| committer | Marvin W <git@larma.de> | 2026-10-23 16:59:59 +0200 |
| commit | dba577f39c489b9db29960f2bf5cc78ac4f29d7b (patch) | |
| tree | a8354c9fc328c1442d5e8c5c2adec4b428c92f44 /main/src/plugins/omemo | |
| parent | 2413442905e31f34cb0f77c9167003b3725760fe (diff) | |
Move OMEMO, OpenPGP and RTP plugins into main/libdino
Diffstat (limited to 'main/src/plugins/omemo')
27 files changed, 3515 insertions, 0 deletions
diff --git a/main/src/plugins/omemo/dtls_srtp_verification_draft.vala b/main/src/plugins/omemo/dtls_srtp_verification_draft.vala new file mode 100644 index 00000000..09617a2a --- /dev/null +++ b/main/src/plugins/omemo/dtls_srtp_verification_draft.vala @@ -0,0 +1,268 @@ +using Omemo; +using Gee; +using Xmpp; + +namespace Dino.Plugins.Omemo.DtlsSrtpVerificationDraft { + public const string NS_URI = "http://gultsch.de/xmpp/drafts/omemo/dlts-srtp-verification"; + + public class StreamModule : XmppStreamModule { + + public static Xmpp.ModuleIdentity<StreamModule> IDENTITY = new Xmpp.ModuleIdentity<StreamModule>(NS_URI, "dtls_srtp_omemo_verification_draft"); + + private VerificationSendListener send_listener = new VerificationSendListener(); + private HashMap<string, int> device_id_by_jingle_sid = new HashMap<string, int>(); + private HashMap<string, int> device_id_by_muji_member = new HashMap<string, int>(); + private HashMap<string, Gee.List<string>> content_names_by_jingle_sid = new HashMap<string, Gee.List<string>>(); + + private void on_preprocess_incoming_iq_set_get(XmppStream stream, Xmpp.Iq.Stanza iq) { + if (iq.type_ != Iq.Stanza.TYPE_SET) return; + + Gee.List<StanzaNode> content_nodes = iq.stanza.get_deep_subnodes(Xep.Jingle.NS_URI + ":jingle", Xep.Jingle.NS_URI + ":content"); + if (content_nodes.size == 0) return; + + string? jingle_sid = iq.stanza.get_deep_attribute(Xep.Jingle.NS_URI + ":jingle", "sid"); + if (jingle_sid == null) return; + + Xep.Omemo.OmemoDecryptor decryptor = stream.get_module(Xep.Omemo.OmemoDecryptor.IDENTITY); + + foreach (StanzaNode content_node in content_nodes) { + string? content_name = content_node.get_attribute("name"); + if (content_name == null) continue; + StanzaNode? transport_node = content_node.get_subnode("transport", Xep.JingleIceUdp.NS_URI); + if (transport_node == null) continue; + StanzaNode? fingerprint_node = transport_node.get_subnode("fingerprint", NS_URI); + if (fingerprint_node == null) continue; + StanzaNode? encrypted_node = fingerprint_node.get_subnode("encrypted", Omemo.NS_URI); + if (encrypted_node == null) continue; + + Xep.Omemo.ParsedData? parsed_data = decryptor.parse_node(encrypted_node); + if (parsed_data == null || parsed_data.ciphertext == null) continue; + + if (device_id_by_jingle_sid.has_key(jingle_sid) && device_id_by_jingle_sid[jingle_sid] != parsed_data.sid) { + warning("Expected DTLS fingerprint to be OMEMO encrypted from %s %d, but it was from %d", iq.from.to_string(), device_id_by_jingle_sid[jingle_sid], parsed_data.sid); + } + + foreach (Bytes encr_key in parsed_data.our_potential_encrypted_keys.keys) { + parsed_data.is_prekey = parsed_data.our_potential_encrypted_keys[encr_key]; + parsed_data.encrypted_key = encr_key.get_data(); + + try { + uint8[] key = decryptor.decrypt_key(parsed_data, iq.from.bare_jid); + string cleartext = decryptor.decrypt(parsed_data.ciphertext, key, parsed_data.iv); + + StanzaNode new_fingerprint_node = new StanzaNode.build("fingerprint", Xep.JingleIceUdp.DTLS_NS_URI).add_self_xmlns() + .put_node(new StanzaNode.text(cleartext)); + string? hash_attr = fingerprint_node.get_attribute("hash", NS_URI); + string? setup_attr = fingerprint_node.get_attribute("setup", NS_URI); + if (hash_attr != null) new_fingerprint_node.put_attribute("hash", hash_attr); + if (setup_attr != null) new_fingerprint_node.put_attribute("setup", setup_attr); + transport_node.put_node(new_fingerprint_node); + + device_id_by_jingle_sid[jingle_sid] = parsed_data.sid; + if (!content_names_by_jingle_sid.has_key(content_name)) { + content_names_by_jingle_sid[content_name] = new ArrayList<string>(); + } + content_names_by_jingle_sid[content_name].add(content_name); + + stream.get_flag(Xep.Jingle.Flag.IDENTITY).get_session.begin(jingle_sid, (_, res) => { + Xep.Jingle.Session? session = stream.get_flag(Xep.Jingle.Flag.IDENTITY).get_session.end(res); + if (session == null || !session.contents_map.has_key(content_name)) return; + var encryption = new OmemoContentEncryption(NS_URI, "OMEMO", iq.from.bare_jid, device_id_by_jingle_sid[jingle_sid]); + session.contents_map[content_name].encryptions[NS_URI] = encryption; + + if (iq.stanza.get_deep_attribute(Xep.Jingle.NS_URI + ":jingle", "action") == "session-accept") { + session.additional_content_add_incoming.connect(on_content_add_received); + } + }); + + break; + } catch (Error e) { + debug("Decrypting message from %s/%d failed: %s", iq.from.bare_jid.to_string(), parsed_data.sid, e.message); + } + } + } + } + + private void on_preprocess_outgoing_iq_set_get(XmppStream stream, Xmpp.Iq.Stanza iq) { + if (iq.type_ != Iq.Stanza.TYPE_SET) return; + + StanzaNode? jingle_node = iq.stanza.get_subnode("jingle", Xep.Jingle.NS_URI); + if (jingle_node == null) return; + + int device_id = -1; + string? sid = jingle_node.get_attribute("sid", Xep.Jingle.NS_URI); + if (sid != null && device_id_by_jingle_sid.has_key(sid)) { + device_id = device_id_by_jingle_sid[sid]; + } + + StanzaNode? muji_node = jingle_node.get_subnode("muji", Xep.Muji.NS_URI); + if (muji_node != null) { + string muji_room = muji_node.get_attribute("room"); + try { + Jid muji_jid = Jid.from_string(muji_room); + if (device_id_by_muji_member.has_key(@"$(muji_jid.bare_jid)/$(iq.to)")) { + device_id = device_id_by_muji_member[@"$(muji_jid.bare_jid)/$(iq.to)"]; + } + } catch (InvalidJidError e) { + // Ignore + } + } + + if (device_id == -1) return; + + Gee.List<StanzaNode> content_nodes = jingle_node.get_subnodes("content", Xep.Jingle.NS_URI); + if (content_nodes.size == 0) return; + + foreach (StanzaNode content_node in content_nodes) { + StanzaNode? transport_node = content_node.get_subnode("transport", Xep.JingleIceUdp.NS_URI); + if (transport_node == null) continue; + StanzaNode? fingerprint_node = transport_node.get_subnode("fingerprint", Xep.JingleIceUdp.DTLS_NS_URI); + if (fingerprint_node == null) continue; + string fingerprint = fingerprint_node.get_deep_string_content(); + + StanzaNode? encrypted_node = null; + try { + Xep.Omemo.OmemoEncryptor encryptor = stream.get_module(Xep.Omemo.OmemoEncryptor.IDENTITY); + Xep.Omemo.EncryptionData enc_data = encryptor.encrypt_plaintext(fingerprint); + encryptor.encrypt_key(enc_data, iq.to.bare_jid, device_id); + encrypted_node = enc_data.get_encrypted_node(); + } catch (Error e) { + warning("Error while OMEMO-encrypting call keys: %s", e.message); + return; + } + + StanzaNode new_fingerprint_node = new StanzaNode.build("fingerprint", NS_URI).add_self_xmlns().put_node(encrypted_node); + string? hash_attr = fingerprint_node.get_attribute("hash", Xep.JingleIceUdp.DTLS_NS_URI); + string? setup_attr = fingerprint_node.get_attribute("setup", Xep.JingleIceUdp.DTLS_NS_URI); + if (hash_attr != null) new_fingerprint_node.put_attribute("hash", hash_attr); + if (setup_attr != null) new_fingerprint_node.put_attribute("setup", setup_attr); + transport_node.put_node(new_fingerprint_node); + + transport_node.sub_nodes.remove(fingerprint_node); + } + } + + private void on_message_received(XmppStream stream, Xmpp.MessageStanza message) { + StanzaNode? proceed_node = message.stanza.get_subnode("proceed", Xep.JingleMessageInitiation.NS_URI); + if (proceed_node == null) return; + + string? jingle_sid = proceed_node.get_attribute("id"); + if (jingle_sid == null) return; + + StanzaNode? device_node = proceed_node.get_subnode("device", NS_URI); + if (device_node == null) return; + + int device_id = device_node.get_attribute_int("id", -1); + if (device_id == -1) return; + + device_id_by_jingle_sid[jingle_sid] = device_id; + } + + private void on_session_initiate_received(XmppStream stream, Xep.Jingle.Session session) { + if (device_id_by_jingle_sid.has_key(session.sid)) { + foreach (Xep.Jingle.Content content in session.contents) { + on_content_add_received(stream, content); + } + } + session.additional_content_add_incoming.connect(on_content_add_received); + } + + private void on_content_add_received(XmppStream stream, Xep.Jingle.Content content) { + if (!content_names_by_jingle_sid.has_key(content.session.sid) || content_names_by_jingle_sid[content.session.sid].contains(content.content_name)) { + var encryption = new OmemoContentEncryption(NS_URI, "OMEMO", content.peer_full_jid.bare_jid, device_id_by_jingle_sid[content.session.sid]); + content.encryptions[encryption.encryption_ns] = encryption; + } + } + + private void on_pre_send_presence_stanza(XmppStream stream, Presence.Stanza presence) { + StanzaNode? muji_node = presence.stanza.get_subnode("muji", Xep.Muji.NS_URI); + if (muji_node == null) return; + + StanzaNode device_node = new StanzaNode.build("device", NS_URI).add_self_xmlns() + .put_attribute("id", stream.get_module(Omemo.StreamModule.IDENTITY).store.local_registration_id.to_string()); + muji_node.put_node(device_node); + } + + private void on_received_available(XmppStream stream, Presence.Stanza presence) { + StanzaNode? muji_node = presence.stanza.get_subnode("muji", Xep.Muji.NS_URI); + if (muji_node == null) return; + + StanzaNode? device_node = muji_node.get_subnode("device", NS_URI); + if (device_node == null) return; + + int device_id = device_node.get_attribute_int("id", -1); + if (device_id == -1) return; + + StanzaNode? muc_x_node = presence.stanza.get_subnode("x", "http://jabber.org/protocol/muc#user"); + if (muc_x_node == null) return; + + StanzaNode? item_node = muc_x_node.get_subnode("item"); + if (item_node == null) return; + + Jid? real_jid = null; + try { + string jid_attribute = item_node.get_attribute("jid"); + if (jid_attribute == null) return; + real_jid = Jid.from_string(jid_attribute); + } catch (InvalidJidError e) { + // Ignore + return; + } + + device_id_by_muji_member[@"$(presence.from.bare_jid)/$(real_jid)"] = device_id; + } + + public override void attach(XmppStream stream) { + stream.get_module(Xmpp.MessageModule.IDENTITY).received_message.connect(on_message_received); + stream.get_module(Xmpp.MessageModule.IDENTITY).send_pipeline.connect(send_listener); + stream.get_module(Xmpp.Iq.Module.IDENTITY).preprocess_incoming_iq_set_get.connect(on_preprocess_incoming_iq_set_get); + stream.get_module(Xmpp.Iq.Module.IDENTITY).preprocess_outgoing_iq_set_get.connect(on_preprocess_outgoing_iq_set_get); + stream.get_module(Xep.Jingle.Module.IDENTITY).session_initiate_received.connect(on_session_initiate_received); + stream.get_module(Xmpp.Presence.Module.IDENTITY).pre_send_presence_stanza.connect(on_pre_send_presence_stanza); + stream.get_module(Xmpp.Presence.Module.IDENTITY).received_available.connect(on_received_available); + } + + public override void detach(XmppStream stream) { + stream.get_module(Xmpp.MessageModule.IDENTITY).received_message.disconnect(on_message_received); + stream.get_module(Xmpp.MessageModule.IDENTITY).send_pipeline.disconnect(send_listener); + stream.get_module(Xmpp.Iq.Module.IDENTITY).preprocess_incoming_iq_set_get.disconnect(on_preprocess_incoming_iq_set_get); + stream.get_module(Xmpp.Iq.Module.IDENTITY).preprocess_outgoing_iq_set_get.disconnect(on_preprocess_outgoing_iq_set_get); + stream.get_module(Xep.Jingle.Module.IDENTITY).session_initiate_received.disconnect(on_session_initiate_received); + stream.get_module(Xmpp.Presence.Module.IDENTITY).received_available.disconnect(on_received_available); + } + + public override string get_ns() { return NS_URI; } + + public override string get_id() { return IDENTITY.id; } + } + + public class VerificationSendListener : StanzaListener<MessageStanza> { + + private string[] after_actions_const = {}; + + public override string action_group { get { return "REWRITE_NODES"; } } + public override string[] after_actions { get { return after_actions_const; } } + + public override async bool run(XmppStream stream, MessageStanza message) { + StanzaNode? proceed_node = message.stanza.get_subnode("proceed", Xep.JingleMessageInitiation.NS_URI); + if (proceed_node == null) return false; + + StanzaNode device_node = new StanzaNode.build("device", NS_URI).add_self_xmlns() + .put_attribute("id", stream.get_module(Omemo.StreamModule.IDENTITY).store.local_registration_id.to_string()); + proceed_node.put_node(device_node); + return false; + } + } + + public class OmemoContentEncryption : Xep.Jingle.ContentEncryption { + public Jid jid { get; set; } + public int sid { get; set; } + + public OmemoContentEncryption(string encryption_ns, string encryption_name, Jid jid, int sid) { + base(encryption_ns, encryption_name); + this.jid = jid; + this.sid = sid; + } + } +} + diff --git a/main/src/plugins/omemo/file_transfer/file_decryptor.vala b/main/src/plugins/omemo/file_transfer/file_decryptor.vala new file mode 100644 index 00000000..8ae0b96b --- /dev/null +++ b/main/src/plugins/omemo/file_transfer/file_decryptor.vala @@ -0,0 +1,90 @@ +using Dino.Entities; + +using Dino.Crypto; +using Omemo; + +namespace Dino.Plugins.Omemo { + +public class OmemoHttpFileReceiveData : HttpFileReceiveData { + public string original_url; +} + +public class OmemoFileDecryptor : FileDecryptor, Object { + + private Regex url_regex = /^aesgcm:\/\/(.*)#(([A-Fa-f0-9]{2}){48}|([A-Fa-f0-9]{2}){44})$/; + + public Encryption get_encryption() { + return Encryption.OMEMO; + } + + public FileReceiveData prepare_get_meta_info(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) { + HttpFileReceiveData? http_receive_data = receive_data as HttpFileReceiveData; + if (http_receive_data == null) assert(false); + if ((receive_data as OmemoHttpFileReceiveData) != null) return receive_data; + + var omemo_http_receive_data = new OmemoHttpFileReceiveData(); + omemo_http_receive_data.url = aesgcm_to_https_link(http_receive_data.url); + omemo_http_receive_data.original_url = http_receive_data.url; + + return omemo_http_receive_data; + } + + public FileMeta prepare_download_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) { + if (file_meta.file_name != null) { + file_meta.file_name = file_meta.file_name.split("#")[0]; + } + return file_meta; + } + + public bool can_decrypt_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) { + HttpFileReceiveData? http_file_receive = receive_data as HttpFileReceiveData; + if (http_file_receive == null) return false; + + return this.url_regex.match(http_file_receive.url) || (receive_data as OmemoHttpFileReceiveData) != null; + } + + public async InputStream decrypt_file(InputStream encrypted_stream, Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) throws FileReceiveError { + const uint KEY_SIZE = 32; + try { + OmemoHttpFileReceiveData? omemo_http_receive_data = receive_data as OmemoHttpFileReceiveData; + if (omemo_http_receive_data == null) assert(false); + + // Decode IV and key + MatchInfo match_info; + this.url_regex.match(omemo_http_receive_data.original_url, 0, out match_info); + uint8[] iv_and_key = hex_to_bin(match_info.fetch(2).up()); + uint8[] iv = iv_and_key[0:iv_and_key.length-KEY_SIZE]; + uint8[] key = iv_and_key[iv_and_key.length-KEY_SIZE:iv_and_key.length]; + + file_transfer.encryption = Encryption.OMEMO; + debug("Decrypting file %s from %s", file_transfer.file_name, file_transfer.server_file_name); + + SymmetricCipherDecryption cipher = create_symmetric_cipher_decryption("AES-GCM"); + cipher.set_key(key); + cipher.set_iv(iv); + return new ConverterInputStream(encrypted_stream, new SymmetricCipherDecrypter((owned) cipher, 16)); + + } catch (Crypto.Error e) { + throw new FileReceiveError.DECRYPTION_FAILED("OMEMO file decryption error: %s".printf(e.message)); + } catch (GLib.Error e) { + throw new FileReceiveError.DECRYPTION_FAILED("OMEMO file decryption error: %s".printf(e.message)); + } + } + + private uint8[] hex_to_bin(string hex) { + uint8[] bin = new uint8[hex.length / 2]; + const string HEX = "0123456789ABCDEF"; + for (int i = 0; i < hex.length / 2; i++) { + bin[i] = (uint8) (HEX.index_of_char(hex[i*2]) << 4) | HEX.index_of_char(hex[i*2+1]); + } + return bin; + } + + private string aesgcm_to_https_link(string aesgcm_link) { + MatchInfo match_info; + this.url_regex.match(aesgcm_link, 0, out match_info); + return "https://" + match_info.fetch(1); + } +} + +} diff --git a/main/src/plugins/omemo/file_transfer/file_encryptor.vala b/main/src/plugins/omemo/file_transfer/file_encryptor.vala new file mode 100644 index 00000000..5f1d6e69 --- /dev/null +++ b/main/src/plugins/omemo/file_transfer/file_encryptor.vala @@ -0,0 +1,76 @@ +using Gee; +using Gtk; + +using Dino.Crypto; +using Dino.Entities; +using Xmpp; +using Omemo; + +namespace Dino.Plugins.Omemo { + +public class OmemoHttpFileMeta : HttpFileMeta { + public uint8[] iv; + public uint8[] key; +} + +public class OmemoFileEncryptor : Dino.FileEncryptor, Object { + + public bool can_encrypt_file(Conversation conversation, FileTransfer file_transfer) { + return file_transfer.encryption == Encryption.OMEMO; + } + + public FileMeta encrypt_file(Conversation conversation, FileTransfer file_transfer) throws FileSendError { + const uint KEY_SIZE = 32; + const uint IV_SIZE = 12; + var omemo_http_file_meta = new OmemoHttpFileMeta(); + + try { + //Create a key and use it to encrypt the file + uint8[] iv = new uint8[IV_SIZE]; + Crypto.randomize(iv); + uint8[] key = new uint8[KEY_SIZE]; + Crypto.randomize(key); + + SymmetricCipherEncryption cipher = create_symmetric_cipher_encryption("AES-GCM"); + cipher.set_key(key); + cipher.set_iv(iv); + + omemo_http_file_meta.iv = iv; + omemo_http_file_meta.key = key; + omemo_http_file_meta.size = file_transfer.size + 16; + omemo_http_file_meta.content_type = new FileContentType.from_mime_type("application/octet-stream"); + file_transfer.input_stream = new ConverterInputStream(file_transfer.input_stream, new SymmetricCipherEncrypter((owned) cipher, 16)); + } catch (Crypto.Error error) { + throw new FileSendError.ENCRYPTION_FAILED("OMEMO file encryption error: %s".printf(error.message)); + } catch (GLib.Error error) { + throw new FileSendError.ENCRYPTION_FAILED("OMEMO file encryption error: %s".printf(error.message)); + } + + debug("Encrypting file %s as %s", file_transfer.file_name, file_transfer.server_file_name); + + return omemo_http_file_meta; + } + + public FileSendData? preprocess_send_file(Conversation conversation, FileTransfer file_transfer, FileSendData file_send_data, FileMeta file_meta) { + HttpFileSendData? send_data = file_send_data as HttpFileSendData; + if (send_data == null) return null; + + OmemoHttpFileMeta? omemo_http_file_meta = file_meta as OmemoHttpFileMeta; + if (omemo_http_file_meta == null) return null; + + // Convert iv and key to hex + string iv_and_key = ""; + foreach (uint8 byte in omemo_http_file_meta.iv) iv_and_key += byte.to_string("%02x"); + foreach (uint8 byte in omemo_http_file_meta.key) iv_and_key += byte.to_string("%02x"); + + string aesgcm_link = send_data.url_down + "#" + iv_and_key; + aesgcm_link = "aesgcm://" + aesgcm_link.substring(8); // replace https:// by aesgcm:// + + send_data.url_down = aesgcm_link; + send_data.encrypt_message = true; + + return file_send_data; + } +} + +} diff --git a/main/src/plugins/omemo/jingle/jet_omemo.vala b/main/src/plugins/omemo/jingle/jet_omemo.vala new file mode 100644 index 00000000..07d03f64 --- /dev/null +++ b/main/src/plugins/omemo/jingle/jet_omemo.vala @@ -0,0 +1,115 @@ +using Dino.Crypto; +using Dino.Crypto.Omemo; +using Dino; +using Dino.Entities; +using Gee; +using Omemo; +using Xmpp; +using Xmpp.Xep; + +namespace Dino.Plugins.JetOmemo { + +private const string NS_URI = "urn:xmpp:jingle:jet-omemo:0"; +private const string AES_128_GCM_URI = "urn:xmpp:ciphers:aes-128-gcm-nopadding"; + +public class Module : XmppStreamModule, Jet.EnvelopEncoding { + public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0396_jet_omemo"); + const uint KEY_SIZE = 16; + const uint IV_SIZE = 12; + + public override void attach(XmppStream stream) { + if (stream.get_module(Jet.Module.IDENTITY) != null) { + stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI); + stream.get_module(Jet.Module.IDENTITY).register_envelop_encoding(this); + stream.get_module(Jet.Module.IDENTITY).register_cipher(new AesGcmCipher(KEY_SIZE, IV_SIZE, AES_128_GCM_URI)); + } + } + + public override void detach(XmppStream stream) { + stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI); + } + + public async bool is_available(XmppStream stream, Jid full_jid) { + bool? has_feature = yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI); + if (has_feature == null || !(!)has_feature) { + return false; + } + return yield stream.get_module(Xep.Jet.Module.IDENTITY).is_available(stream, full_jid); + } + + public string get_type_uri() { + return Omemo.NS_URI; + } + + public Jet.TransportSecret decode_envolop(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, StanzaNode security) throws Jingle.IqError { + StanzaNode? encrypted = security.get_subnode("encrypted", Omemo.NS_URI); + if (encrypted == null) throw new Jingle.IqError.BAD_REQUEST("Invalid JET-OMEMO envelop: missing encrypted element"); + + Xep.Omemo.OmemoDecryptor decryptor = stream.get_module(Xep.Omemo.OmemoDecryptor.IDENTITY); + + Xmpp.Xep.Omemo.ParsedData? data = decryptor.parse_node(encrypted); + if (data == null) throw new Jingle.IqError.BAD_REQUEST("Invalid JET-OMEMO envelop: bad encrypted element"); + + foreach (Bytes encr_key in data.our_potential_encrypted_keys.keys) { + data.is_prekey = data.our_potential_encrypted_keys[encr_key]; + data.encrypted_key = encr_key.get_data(); + + try { + uint8[] key = decryptor.decrypt_key(data, peer_full_jid.bare_jid); + return new Jet.TransportSecret(key, data.iv); + } catch (GLib.Error e) { + debug("Decrypting JET key from %s/%d failed: %s", peer_full_jid.bare_jid.to_string(), data.sid, e.message); + } + } + throw new Jingle.IqError.NOT_ACCEPTABLE("Not encrypted for targeted device"); + } + + public void encode_envelop(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, Jet.SecurityParameters security_params, StanzaNode security) { + Store store = stream.get_module(Omemo.StreamModule.IDENTITY).store; + + var encryption_data = new Xep.Omemo.EncryptionData(store.local_registration_id); + encryption_data.iv = security_params.secret.initialization_vector; + encryption_data.keytag = security_params.secret.transport_key; + Xep.Omemo.OmemoEncryptor encryptor = stream.get_module(Xep.Omemo.OmemoEncryptor.IDENTITY); + encryptor.encrypt_key_to_recipient(stream, encryption_data, peer_full_jid.bare_jid); + + security.put_node(encryption_data.get_encrypted_node()); + } + + public override string get_ns() { return NS_URI; } + public override string get_id() { return IDENTITY.id; } +} + +public class AesGcmCipher : Jet.Cipher, Object { + private uint key_size; + private uint default_iv_size; + private string uri; + public AesGcmCipher(uint key_size, uint default_iv_size, string uri) { + this.key_size = key_size; + this.default_iv_size = default_iv_size; + this.uri = uri; + } + public string get_cipher_uri() { + return uri; + } + public Jet.TransportSecret generate_random_secret() { + uint8[] iv = new uint8[default_iv_size]; + Crypto.randomize(iv); + uint8[] key = new uint8[key_size]; + Crypto.randomize(key); + return new Jet.TransportSecret(key, iv); + } + public InputStream wrap_input_stream(InputStream input, Jet.TransportSecret secret) requires (secret.transport_key.length == key_size) { + SymmetricCipherDecryption cipher = create_symmetric_cipher_decryption("AES-GCM"); + cipher.set_key(secret.transport_key); + cipher.set_iv(secret.initialization_vector); + return new ConverterInputStream(input, new SymmetricCipherDecrypter((owned) cipher, 16)); + } + public OutputStream wrap_output_stream(OutputStream output, Jet.TransportSecret secret) requires (secret.transport_key.length == key_size) { + SymmetricCipherEncryption cipher = create_symmetric_cipher_encryption("AES-GCM"); + cipher.set_key(secret.transport_key); + cipher.set_iv(secret.initialization_vector); + return new ConverterOutputStream(output, new SymmetricCipherEncrypter((owned) cipher, 16)); + } +} +} diff --git a/main/src/plugins/omemo/jingle/jingle_helper.vala b/main/src/plugins/omemo/jingle/jingle_helper.vala new file mode 100644 index 00000000..ec6c0eca --- /dev/null +++ b/main/src/plugins/omemo/jingle/jingle_helper.vala @@ -0,0 +1,53 @@ +using Dino.Entities; +using Xmpp; + +namespace Dino.Plugins.JetOmemo { +public class EncryptionHelper : JingleFileEncryptionHelper, Object { + private StreamInteractor stream_interactor; + + public EncryptionHelper(StreamInteractor stream_interactor) { + this.stream_interactor = stream_interactor; + } + + public bool can_transfer(Conversation conversation) { + return true; + } + + public async bool can_encrypt(Conversation conversation, FileTransfer file_transfer, Jid? full_jid) { + XmppStream? stream = stream_interactor.get_stream(conversation.account); + if (stream == null) return false; + + Gee.List<Jid>? resources = stream.get_flag(Presence.Flag.IDENTITY).get_resources(conversation.counterpart); + if (resources == null) return false; + + if (full_jid == null) { + foreach (Jid test_jid in resources) { + if (yield stream.get_module(Module.IDENTITY).is_available(stream, test_jid)) { + return true; + } + } + } else { + if (yield stream.get_module(Module.IDENTITY).is_available(stream, full_jid)) { + return true; + } + } + return false; + } + + public string? get_precondition_name(Conversation conversation, FileTransfer file_transfer) { + return Xep.Jet.NS_URI; + } + + public Object? get_precondition_options(Conversation conversation, FileTransfer file_transfer) { + return new Xep.Jet.Options(Omemo.NS_URI, AES_128_GCM_URI); + } + + public Encryption get_encryption(Xmpp.Xep.JingleFileTransfer.FileTransfer jingle_transfer) { + Xep.Jet.SecurityParameters? security = jingle_transfer.security as Xep.Jet.SecurityParameters; + if (security != null && security.encoding.get_type_uri() == Omemo.NS_URI) { + return Encryption.OMEMO; + } + return Encryption.NONE; + } +} +} diff --git a/main/src/plugins/omemo/logic/database.vala b/main/src/plugins/omemo/logic/database.vala new file mode 100644 index 00000000..f2a92259 --- /dev/null +++ b/main/src/plugins/omemo/logic/database.vala @@ -0,0 +1,284 @@ +using Gee; + +using Dino.Entities; +using Dino.Qlite; + +namespace Dino.Plugins.Omemo { + +public class Database : Qlite.Database { + private const int VERSION = 5; + + public class IdentityMetaTable : Table { + //Default to provide backwards compatability + public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true, min_version = 2, default = "-1" }; + public Column<string> address_name = new Column.Text("address_name") { not_null = true }; + public Column<int> device_id = new Column.Integer("device_id") { not_null = true }; + public Column<string?> identity_key_public_base64 = new Column.Text("identity_key_public_base64"); + public Column<bool> trusted_identity = new Column.BoolInt("trusted_identity") { default = "0", max_version = 1 }; + public Column<int> trust_level = new Column.Integer("trust_level") { default = TrustLevel.UNKNOWN.to_string(), min_version = 2 }; + public Column<bool> now_active = new Column.BoolInt("now_active") { default = "1" }; + public Column<long> last_active = new Column.Long("last_active"); + public Column<long> last_message_untrusted = new Column.Long("last_message_untrusted") { min_version = 5 }; + public Column<long> last_message_undecryptable = new Column.Long("last_message_undecryptable") { min_version = 5 }; + + internal IdentityMetaTable(Database db) { + base(db, "identity_meta"); + init({identity_id, address_name, device_id, identity_key_public_base64, trusted_identity, trust_level, now_active, last_active, last_message_untrusted, last_message_undecryptable}); + index("identity_meta_idx", {identity_id, address_name, device_id}, true); + index("identity_meta_list_idx", {identity_id, address_name}); + } + + public QueryBuilder with_address(int identity_id, string address_name) { + return select().with(this.identity_id, "=", identity_id).with(this.address_name, "=", address_name); + } + + public QueryBuilder get_with_device_id(int identity_id, int device_id) { + return select().with(this.identity_id, "=", identity_id).with(this.device_id, "=", device_id); + } + + public void insert_device_list(int32 identity_id, string address_name, ArrayList<int32> devices) { + update().with(this.identity_id, "=", identity_id).with(this.address_name, "=", address_name).set(now_active, false).perform(); + foreach (int32 device_id in devices) { + upsert() + .value(this.identity_id, identity_id, true) + .value(this.address_name, address_name, true) + .value(this.device_id, device_id, true) + .value(this.now_active, true) + .value(this.last_active, (long) new DateTime.now_utc().to_unix()) + .perform(); + } + } + + public int64 insert_device_bundle(int32 identity_id, string address_name, int device_id, Bundle bundle, TrustLevel trust) { + if (bundle == null || bundle.identity_key == null) return -1; + // Do not replace identity_key if it was known before, it should never change! + string identity_key = Base64.encode(bundle.identity_key.serialize()); + RowOption row = with_address(identity_id, address_name).with(this.device_id, "=", device_id).single().row(); + if (row.is_present() && row[identity_key_public_base64] != null && row[identity_key_public_base64] != identity_key) { + critical("Tried to change the identity key for a known device id. Likely an attack."); + return -1; + } + return upsert() + .value(this.identity_id, identity_id, true) + .value(this.address_name, address_name, true) + .value(this.device_id, device_id, true) + .value(this.identity_key_public_base64, identity_key) + .value(this.trust_level, trust).perform(); + } + + public int64 insert_device_session(int32 identity_id, string address_name, int device_id, string identity_key, TrustLevel trust) { + RowOption row = with_address(identity_id, address_name).with(this.device_id, "=", device_id).single().row(); + if (row.is_present() && row[identity_key_public_base64] != null && row[identity_key_public_base64] != identity_key) { + critical("Tried to change the identity key for a known device id. Likely an attack."); + return -1; + } + return upsert() + .value(this.identity_id, identity_id, true) + .value(this.address_name, address_name, true) + .value(this.device_id, device_id, true) + .value(this.identity_key_public_base64, identity_key) + .value(this.trust_level, trust).perform(); + } + + public void update_last_message_untrusted(int identity_id, int device_id, DateTime? time) { + var stmt = update() + .with(this.identity_id, "=", identity_id) + .with(this.device_id, "=", device_id); + if (time != null) { + stmt.set(last_message_untrusted, (long)time.to_unix()); + } else { + stmt.set_null(last_message_untrusted); + } + stmt.perform(); + } + + public void update_last_message_undecryptable(int identity_id, int device_id, DateTime? time) { + var stmt = update() + .with(this.identity_id, "=", identity_id) + .with(this.device_id, "=", device_id); + if (time != null) { + stmt.set(last_message_undecryptable, (long)time.to_unix()); + } else { + stmt.set_null(last_message_undecryptable); + } + stmt.perform(); + } + + public QueryBuilder get_trusted_devices(int identity_id, string address_name) { + return this.with_address(identity_id, address_name) + .with(this.trust_level, "!=", TrustLevel.UNTRUSTED) + .with(this.now_active, "=", true); + } + + public QueryBuilder get_known_devices(int identity_id, string address_name) { + return this.with_address(identity_id, address_name) + .with(this.trust_level, "!=", TrustLevel.UNKNOWN) + .without_null(this.identity_key_public_base64); + } + + public QueryBuilder get_unknown_devices(int identity_id, string address_name) { + return this.with_address(identity_id, address_name) + .with_null(this.identity_key_public_base64); + } + + public QueryBuilder get_new_devices(int identity_id, string address_name) { + return this.with_address(identity_id, address_name) + .with(this.trust_level, "=", TrustLevel.UNKNOWN) + .without_null(this.identity_key_public_base64); + } + + public Row? get_device(int identity_id, string address_name, int device_id) { + return this.with_address(identity_id, address_name) + .with(this.device_id, "=", device_id).single().row().inner; + } + } + + + public class TrustTable : Table { + public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true }; + public Column<string> address_name = new Column.Text("address_name"); + public Column<bool> blind_trust = new Column.BoolInt("blind_trust") { default = "1" } ; + + internal TrustTable(Database db) { + base(db, "trust"); + init({identity_id, address_name, blind_trust}); + index("trust_idx", {identity_id, address_name}, true); + } + + public bool get_blind_trust(int32 identity_id, string address_name, bool def = false) { + RowOption row = this.select().with(this.identity_id, "=", identity_id) + .with(this.address_name, "=", address_name).single().row(); + if (row.is_present()) return row[blind_trust]; + return def; + } + } + + public class IdentityTable : Table { + public Column<int> id = new Column.Integer("id") { primary_key = true, auto_increment = true }; + public Column<int> account_id = new Column.Integer("account_id") { unique = true, not_null = true }; + public Column<int> device_id = new Column.Integer("device_id") { not_null = true }; + public Column<string> identity_key_private_base64 = new Column.NonNullText("identity_key_private_base64"); + public Column<string> identity_key_public_base64 = new Column.NonNullText("identity_key_public_base64"); + + internal IdentityTable(Database db) { + base(db, "identity"); + init({id, account_id, device_id, identity_key_private_base64, identity_key_public_base64}); + } + + public int get_id(int account_id) { + int id = -1; + Row? row = this.row_with(this.account_id, account_id).inner; + if (row != null) id = ((!)row)[this.id]; + return id; + } + } + + public class SignedPreKeyTable : Table { + public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true }; + public Column<int> signed_pre_key_id = new Column.Integer("signed_pre_key_id") { not_null = true }; + public Column<string> record_base64 = new Column.NonNullText("record_base64"); + + internal SignedPreKeyTable(Database db) { + base(db, "signed_pre_key"); + init({identity_id, signed_pre_key_id, record_base64}); + unique({identity_id, signed_pre_key_id}); + index("signed_pre_key_idx", {identity_id, signed_pre_key_id}, true); + } + } + + public class PreKeyTable : Table { + public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true }; + public Column<int> pre_key_id = new Column.Integer("pre_key_id") { not_null = true }; + public Column<string> record_base64 = new Column.NonNullText("record_base64"); + + internal PreKeyTable(Database db) { + base(db, "pre_key"); + init({identity_id, pre_key_id, record_base64}); + unique({identity_id, pre_key_id}); + index("pre_key_idx", {identity_id, pre_key_id}, true); + } + } + + public class SessionTable : Table { + public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true }; + public Column<string> address_name = new Column.NonNullText("name"); + public Column<int> device_id = new Column.Integer("device_id") { not_null = true }; + public Column<string> record_base64 = new Column.NonNullText("record_base64"); + + internal SessionTable(Database db) { + base(db, "session"); + init({identity_id, address_name, device_id, record_base64}); + unique({identity_id, address_name, device_id}); + index("session_idx", {identity_id, address_name, device_id}, true); + } + } + + public class ContentItemMetaTable : Table { + public Column<int> content_item_id = new Column.Integer("message_id") { primary_key = true }; + public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true }; + public Column<string> address_name = new Column.Text("address_name") { not_null = true }; + public Column<int> device_id = new Column.Integer("device_id") { not_null = true }; + public Column<bool> trusted_when_received = new Column.BoolInt("trusted_when_received") { not_null = true, default = "1" }; + + internal ContentItemMetaTable(Database db) { + base(db, "content_item_meta"); + init({content_item_id, identity_id, address_name, device_id, trusted_when_received}); + index("content_item_meta_device_idx", {identity_id, device_id, address_name}); + } + + public RowOption with_content_item(ContentItem item) { + return row_with(content_item_id, item.id); + } + + public QueryBuilder with_device(int identity_id, string address_name, int device_id) { + return select() + .with(this.identity_id, "=", identity_id) + .with(this.address_name, "=", address_name) + .with(this.device_id, "=", device_id); + } + } + + public IdentityMetaTable identity_meta { get; private set; } + public TrustTable trust { get; private set; } + public IdentityTable identity { get; private set; } + public SignedPreKeyTable signed_pre_key { get; private set; } + public PreKeyTable pre_key { get; private set; } + public SessionTable session { get; private set; } + public ContentItemMetaTable content_item_meta { get; private set; } + + public Database(string fileName) { + base(fileName, VERSION); + identity_meta = new IdentityMetaTable(this); + trust = new TrustTable(this); + identity = new IdentityTable(this); + signed_pre_key = new SignedPreKeyTable(this); + pre_key = new PreKeyTable(this); + session = new SessionTable(this); + content_item_meta = new ContentItemMetaTable(this); + init({identity_meta, trust, identity, signed_pre_key, pre_key, session, content_item_meta}); + + try { + exec("PRAGMA journal_mode = WAL"); + exec("PRAGMA synchronous = NORMAL"); + exec("PRAGMA secure_delete = ON"); + } catch (Error e) { + error("Failed to set OMEMO database properties: %s", e.message); + } + } + + public override void migrate(long oldVersion) { + if(oldVersion == 1) { + try { + exec("DROP INDEX identity_meta_idx"); + exec("DROP INDEX identity_meta_list_idx"); + exec("CREATE UNIQUE INDEX identity_meta_idx ON identity_meta (identity_id, address_name, device_id)"); + exec("CREATE INDEX identity_meta_list_idx ON identity_meta (identity_id, address_name)"); + } catch (Error e) { + stderr.printf("Failed to migrate OMEMO database\n"); + Process.exit(-1); + } + } + } +} + +} diff --git a/main/src/plugins/omemo/logic/decrypt.vala b/main/src/plugins/omemo/logic/decrypt.vala new file mode 100644 index 00000000..135ac42c --- /dev/null +++ b/main/src/plugins/omemo/logic/decrypt.vala @@ -0,0 +1,212 @@ +using Gee; + +using Dino.Crypto.Omemo; +using Dino.Entities; +using Dino.Qlite; +using Omemo; +using Xmpp; + +namespace Dino.Plugins.Omemo { + + public class OmemoDecryptor : Xep.Omemo.OmemoDecryptor { + + private Account account; + private Store store; + private Database db; + private StreamInteractor stream_interactor; + private TrustManager trust_manager; + + public override uint32 own_device_id { get { return store.local_registration_id; }} + + public OmemoDecryptor(Account account, StreamInteractor stream_interactor, TrustManager trust_manager, Database db, Store store) { + this.account = account; + this.stream_interactor = stream_interactor; + this.trust_manager = trust_manager; + this.db = db; + this.store = store; + } + + public bool decrypt_message(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) { + StanzaNode? encrypted_node = stanza.stanza.get_subnode("encrypted", NS_URI); + if (encrypted_node == null || MessageFlag.get_flag(stanza) != null || stanza.from == null) return false; + + if (!Plugin.ensure_context()) return false; + int identity_id = db.identity.get_id(conversation.account.id); + + MessageFlag flag = new MessageFlag(); + stanza.add_flag(flag); + + Xep.Omemo.ParsedData? data = parse_node(encrypted_node); + if (data == null) return false; + + + foreach (Bytes encr_key in data.our_potential_encrypted_keys.keys) { + data.is_prekey = data.our_potential_encrypted_keys[encr_key]; + data.encrypted_key = encr_key.get_data(); + Gee.List<Jid> possible_jids = get_potential_message_jids(message, data, identity_id); + if (possible_jids.size == 0) { + debug("Received message from unknown entity with device id %d", data.sid); + } + + foreach (Jid possible_jid in possible_jids) { + try { + uint8[] key = decrypt_key(data, possible_jid); + if (data.ciphertext != null) { + string cleartext = arr_to_str(aes_decrypt(Cipher.AES_GCM_NOPADDING, key, data.iv, data.ciphertext)); + message.body = cleartext; + } + + // If we figured out which real jid a message comes from due to decryption working, save it + if (conversation.type_ == Conversation.Type.GROUPCHAT && message.real_jid == null) { + message.real_jid = possible_jid; + } + + message.encryption = Encryption.OMEMO; + + trust_manager.message_device_id_map[message] = data.sid; + return true; + } catch (Error e) { + debug("Decrypting message from %s/%d failed: %s", possible_jid.to_string(), data.sid, e.message); + } + } + } + + if ( + data.ciphertext != null && // Ratchet forwarding doesn't contain payload and might not include us, which is ok + data.our_potential_encrypted_keys.size == 0 && // The message was not encrypted to us + stream_interactor.module_manager.get_module(message.account, StreamModule.IDENTITY).store.local_registration_id != data.sid // Message from this device. Never encrypted to itself. + ) { + db.identity_meta.update_last_message_undecryptable(identity_id, data.sid, message.time); + trust_manager.bad_message_state_updated(conversation.account, message.from, data.sid); + } + + debug("Received OMEMO encryped message that could not be decrypted."); + return false; + } + + public Gee.List<Jid> get_potential_message_jids(Entities.Message message, Xmpp.Xep.Omemo.ParsedData data, int identity_id) { + Gee.List<Jid> possible_jids = new ArrayList<Jid>(); + if (message.type_ == Message.Type.CHAT) { + possible_jids.add(message.from.bare_jid); + } else { + if (message.real_jid != null) { + possible_jids.add(message.real_jid.bare_jid); + } else if (data.is_prekey) { + // pre key messages do store the identity key, so we can use that to find the real jid + PreKeyOmemoMessage msg = Plugin.get_context().deserialize_signal_pre_key_message(data.encrypted_key); + string identity_key = Base64.encode(msg.identity_key.serialize()); + foreach (Row row in db.identity_meta.get_with_device_id(identity_id, data.sid).with(db.identity_meta.identity_key_public_base64, "=", identity_key)) { + try { + possible_jids.add(Jid.from_string(row[db.identity_meta.address_name])); + } catch (InvalidJidError e) { + warning("Ignoring invalid jid from database: %s", e.message); + } + } + } else { + // If we don't know the device name (MUC history w/o MAM), test decryption with all keys with fitting device id + foreach (Row row in db.identity_meta.get_with_device_id(identity_id, data.sid)) { + try { + possible_jids.add(Jid.from_string(row[db.identity_meta.address_name])); + } catch (InvalidJidError e) { + warning("Ignoring invalid jid from database: %s", e.message); + } + } + } + } + return possible_jids; + } + + public override uint8[] decrypt_key(Xmpp.Xep.Omemo.ParsedData data, Jid from_jid) throws GLib.Error { + int sid = data.sid; + uint8[] ciphertext = data.ciphertext; + uint8[] encrypted_key = data.encrypted_key; + + Address address = new Address(from_jid.to_string(), sid); + uint8[] key; + + if (data.is_prekey) { + int identity_id = db.identity.get_id(account.id); + PreKeyOmemoMessage msg = Plugin.get_context().deserialize_signal_pre_key_message(encrypted_key); + string identity_key = Base64.encode(msg.identity_key.serialize()); + + bool ok = update_db_for_prekey(identity_id, identity_key, from_jid, sid); + if (!ok) throw new GLib.Error(-1, 0, "Failed updating db for prekey"); + + debug("Starting new session for decryption with device from %s/%d", from_jid.to_string(), sid); + SessionCipher cipher = store.create_session_cipher(address); + key = cipher.decrypt_pre_key_message(msg); + // TODO: Finish session + } else { + debug("Continuing session for decryption with device from %s/%d", from_jid.to_string(), sid); + OmemoMessage msg = Plugin.get_context().deserialize_signal_message(encrypted_key); + SessionCipher cipher = store.create_session_cipher(address); + key = cipher.decrypt_message(msg); + } + + if (key.length >= 32) { + int authtaglength = key.length - 16; + uint8[] new_ciphertext = new uint8[ciphertext.length + authtaglength]; + uint8[] new_key = new uint8[16]; + Memory.copy(new_ciphertext, ciphertext, ciphertext.length); + Memory.copy((uint8*)new_ciphertext + ciphertext.length, (uint8*)key + 16, authtaglength); + Memory.copy(new_key, key, 16); + data.ciphertext = new_ciphertext; + key = new_key; + } + + return key; + } + + public override string decrypt(uint8[] ciphertext, uint8[] key, uint8[] iv) throws GLib.Error { + return arr_to_str(aes_decrypt(Cipher.AES_GCM_NOPADDING, key, iv, ciphertext)); + } + + private bool update_db_for_prekey(int identity_id, string identity_key, Jid from_jid, int sid) { + Row? device = db.identity_meta.get_device(identity_id, from_jid.to_string(), sid); + if (device != null && device[db.identity_meta.identity_key_public_base64] != null) { + if (device[db.identity_meta.identity_key_public_base64] != identity_key) { + critical("Tried to use a different identity key for a known device id."); + return false; + } + } else { + debug("Learn new device from incoming message from %s/%d", from_jid.to_string(), sid); + bool blind_trust = db.trust.get_blind_trust(identity_id, from_jid.to_string(), true); + if (db.identity_meta.insert_device_session(identity_id, from_jid.to_string(), sid, identity_key, blind_trust ? TrustLevel.TRUSTED : TrustLevel.UNKNOWN) < 0) { + critical("Failed learning a device."); + return false; + } + + XmppStream? stream = stream_interactor.get_stream(account); + if (device == null && stream != null) { + stream.get_module(StreamModule.IDENTITY).request_user_devicelist.begin(stream, from_jid); + } + } + return true; + } + + private string arr_to_str(uint8[] arr) { + // null-terminate the array + uint8[] rarr = new uint8[arr.length+1]; + Memory.copy(rarr, arr, arr.length); + return (string)rarr; + } + } + + public class DecryptMessageListener : MessageListener { + public string[] after_actions_const = new string[]{ }; + public override string action_group { get { return "DECRYPT"; } } + public override string[] after_actions { get { return after_actions_const; } } + + private HashMap<Account, OmemoDecryptor> decryptors; + + public DecryptMessageListener(HashMap<Account, OmemoDecryptor> decryptors) { + this.decryptors = decryptors; + } + + public override async bool run(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) { + decryptors[message.account].decrypt_message(message, stanza, conversation); + return false; + } + } +} + diff --git a/main/src/plugins/omemo/logic/encrypt.vala b/main/src/plugins/omemo/logic/encrypt.vala new file mode 100644 index 00000000..8994d00d --- /dev/null +++ b/main/src/plugins/omemo/logic/encrypt.vala @@ -0,0 +1,132 @@ +using Gee; +using Omemo; +using Dino.Crypto.Omemo; +using Dino.Entities; +using Xmpp; +using Xmpp.Xep.Omemo; + +namespace Dino.Plugins.Omemo { + + public class OmemoEncryptor : Xep.Omemo.OmemoEncryptor { + + private Account account; + private Store store; + private TrustManager trust_manager; + + public override uint32 own_device_id { get { return store.local_registration_id; }} + + public OmemoEncryptor(Account account, TrustManager trust_manager, Store store) { + this.account = account; + this.trust_manager = trust_manager; + this.store = store; + } + + public override Xep.Omemo.EncryptionData encrypt_plaintext(string plaintext) throws GLib.Error { + const uint KEY_SIZE = 16; + const uint IV_SIZE = 12; + + //Create a key and use it to encrypt the message + uint8[] key = new uint8[KEY_SIZE]; + Crypto.randomize(key); + uint8[] iv = new uint8[IV_SIZE]; + Crypto.randomize(iv); + + uint8[] aes_encrypt_result = aes_encrypt(Cipher.AES_GCM_NOPADDING, key, iv, plaintext.data); + uint8[] ciphertext = aes_encrypt_result[0:aes_encrypt_result.length - 16]; + uint8[] tag = aes_encrypt_result[aes_encrypt_result.length - 16:aes_encrypt_result.length]; + uint8[] keytag = new uint8[key.length + tag.length]; + Memory.copy(keytag, key, key.length); + Memory.copy((uint8*)keytag + key.length, tag, tag.length); + + var ret = new Xep.Omemo.EncryptionData(own_device_id); + ret.ciphertext = ciphertext; + ret.keytag = keytag; + ret.iv = iv; + return ret; + } + + public EncryptState encrypt(MessageStanza message, Jid self_jid, Gee.List<Jid> recipients, XmppStream stream) { + + EncryptState status = new EncryptState(); + if (!Plugin.ensure_context()) return status; + if (message.to == null) return status; + + try { + EncryptionData enc_data = encrypt_plaintext(message.body); + status = encrypt_key_to_recipients(enc_data, self_jid, recipients, stream); + + message.stanza.put_node(enc_data.get_encrypted_node()); + Xep.ExplicitEncryption.add_encryption_tag_to_message(message, NS_URI, "OMEMO"); + message.body = "[This message is OMEMO encrypted]"; + status.encrypted = true; + } catch (Error e) { + warning(@"error while encrypting message: $(e.message)\n"); + message.body = "[OMEMO encryption failed]"; + status.encrypted = false; + } + return status; + } + + internal EncryptState encrypt_key_to_recipients(EncryptionData enc_data, Jid self_jid, Gee.List<Jid> recipients, XmppStream stream) throws Error { + EncryptState status = new EncryptState(); + + //Check we have the bundles and device lists needed to send the message + if (!trust_manager.is_known_address(account, self_jid)) return status; + status.own_list = true; + status.own_devices = trust_manager.get_trusted_devices(account, self_jid).size; + status.other_waiting_lists = 0; + status.other_devices = 0; + foreach (Jid recipient in recipients) { + if (!trust_manager.is_known_address(account, recipient)) { + status.other_waiting_lists++; + } + if (status.other_waiting_lists > 0) return status; + status.other_devices += trust_manager.get_trusted_devices(account, recipient).size; + } + if (status.own_devices == 0 || status.other_devices == 0) return status; + + + //Encrypt the key for each recipient's device individually + foreach (Jid recipient in recipients) { + EncryptionResult enc_res = encrypt_key_to_recipient(stream, enc_data, recipient); + status.add_result(enc_res, false); + } + + // Encrypt the key for each own device + EncryptionResult enc_res = encrypt_key_to_recipient(stream, enc_data, self_jid); + status.add_result(enc_res, true); + + return status; + } + + public override EncryptionResult encrypt_key_to_recipient(XmppStream stream, Xep.Omemo.EncryptionData enc_data, Jid recipient) throws GLib.Error { + var result = new EncryptionResult(); + StreamModule module = stream.get_module(StreamModule.IDENTITY); + + foreach(int32 device_id in trust_manager.get_trusted_devices(account, recipient)) { + if (module.is_ignored_device(recipient, device_id)) { + result.lost++; + continue; + } + try { + encrypt_key(enc_data, recipient, device_id); + result.success++; + } catch (Error e) { + if (e.code == ErrorCode.UNKNOWN) result.unknown++; + else result.failure++; + } + } + return result; + } + + public override void encrypt_key(Xep.Omemo.EncryptionData encryption_data, Jid jid, int32 device_id) throws GLib.Error { + Address address = new Address(jid.to_string(), device_id); + SessionCipher cipher = store.create_session_cipher(address); + CiphertextMessage device_key = cipher.encrypt(encryption_data.keytag); + address.device_id = 0; + debug("Created encrypted key for %s/%d", jid.to_string(), device_id); + + encryption_data.add_device_key(device_id, device_key.serialized, device_key.type == CiphertextType.PREKEY); + } + } +} diff --git a/main/src/plugins/omemo/logic/manager.vala b/main/src/plugins/omemo/logic/manager.vala new file mode 100644 index 00000000..358db4e3 --- /dev/null +++ b/main/src/plugins/omemo/logic/manager.vala @@ -0,0 +1,431 @@ +using Gee; + +using Dino.Crypto.Omemo; +using Dino.Entities; +using Dino.Qlite; +using Omemo; +using Xmpp; + +namespace Dino.Plugins.Omemo { + +public class Manager : StreamInteractionModule, Object { + public static ModuleIdentity<Manager> IDENTITY = new ModuleIdentity<Manager>("omemo_manager"); + public string id { get { return IDENTITY.id; } } + + private StreamInteractor stream_interactor; + private Database db; + private TrustManager trust_manager; + private HashMap<Account, OmemoEncryptor> encryptors; + private Map<Entities.Message, MessageState> message_states = new HashMap<Entities.Message, MessageState>(Entities.Message.hash_func, Entities.Message.equals_func); + + private class MessageState { + public Entities.Message msg { get; private set; } + public Xep.Omemo.EncryptState last_try { get; private set; } + public int waiting_other_sessions { get; set; } + public int waiting_own_sessions { get; set; } + public bool waiting_own_devicelist { get; set; } + public int waiting_other_devicelists { get; set; } + public bool force_next_attempt { get; set; } + public bool will_send_now { get; private set; } + public bool active_send_attempt { get; set; } + + public MessageState(Entities.Message msg, Xep.Omemo.EncryptState last_try) { + update_from_encrypt_status(msg, last_try); + } + + public void update_from_encrypt_status(Entities.Message msg, Xep.Omemo.EncryptState new_try) { + this.msg = msg; + this.last_try = new_try; + this.waiting_other_sessions = new_try.other_unknown; + this.waiting_own_sessions = new_try.own_unknown; + this.waiting_own_devicelist = !new_try.own_list; + this.waiting_other_devicelists = new_try.other_waiting_lists; + this.active_send_attempt = false; + will_send_now = false; + if (new_try.other_failure > 0 || (new_try.other_lost == new_try.other_devices && new_try.other_devices > 0)) { + msg.marked = Entities.Message.Marked.WONTSEND; + } else if (new_try.other_unknown > 0 || new_try.own_unknown > 0 || new_try.other_waiting_lists > 0 || !new_try.own_list || new_try.own_devices == 0) { + msg.marked = Entities.Message.Marked.UNSENT; + } else if (!new_try.encrypted) { + msg.marked = Entities.Message.Marked.WONTSEND; + } else { + will_send_now = true; + } + } + + public bool should_retry_now() { + return !waiting_own_devicelist && waiting_other_devicelists <= 0 && waiting_other_sessions <= 0 && waiting_own_sessions <= 0 && !active_send_attempt; + } + + public string to_string() { + return @"MessageState (msg=$(msg.stanza_id), send=$will_send_now, $last_try)"; + } + } + + private Manager(StreamInteractor stream_interactor, Database db, TrustManager trust_manager, HashMap<Account, OmemoEncryptor> encryptors) { + this.stream_interactor = stream_interactor; + this.db = db; + this.trust_manager = trust_manager; + this.encryptors = encryptors; + + stream_interactor.account_added.connect(on_account_added); + stream_interactor.stream_negotiated.connect(on_stream_negotiated); + stream_interactor.get_module(MessageProcessor.IDENTITY).pre_message_send.connect(on_pre_message_send); + stream_interactor.get_module(RosterManager.IDENTITY).mutual_subscription.connect(on_mutual_subscription); + } + + public void clear_device_list(Account account) { + XmppStream? stream = stream_interactor.get_stream(account); + if (stream == null) return; + + stream.get_module(StreamModule.IDENTITY).clear_device_list(stream); + } + + private Gee.List<Jid> get_occupants(Jid jid, Account account){ + Gee.List<Jid> occupants = new ArrayList<Jid>(Jid.equals_bare_func); + if(!stream_interactor.get_module(MucManager.IDENTITY).is_groupchat(jid, account)){ + occupants.add(jid); + } + Gee.List<Jid>? occupant_jids = stream_interactor.get_module(MucManager.IDENTITY).get_offline_members(jid, account); + if(occupant_jids == null) { + return occupants; + } + foreach (Jid occupant in occupant_jids) { + if(!occupant.equals(account.bare_jid)){ + occupants.add(occupant.bare_jid); + } + } + return occupants; + } + + private void on_pre_message_send(Entities.Message message, Xmpp.MessageStanza message_stanza, Conversation conversation) { + if (message.encryption == Encryption.OMEMO) { + if (message.type_ == Message.Type.GROUPCHAT_PM) { + message.marked = Message.Marked.WONTSEND; + return; + } + XmppStream? stream = stream_interactor.get_stream(conversation.account); + if (stream == null) { + message.marked = Entities.Message.Marked.UNSENT; + return; + } + StreamModule? module_ = ((!)stream).get_module(StreamModule.IDENTITY); + if (module_ == null) { + message.marked = Entities.Message.Marked.UNSENT; + return; + } + StreamModule module = (!)module_; + + //Get a list of everyone for whom the message should be encrypted + Gee.List<Jid> recipients; + if (message_stanza.type_ == MessageStanza.TYPE_GROUPCHAT) { + recipients = get_occupants((!)message.to.bare_jid, conversation.account); + if (recipients.size == 0) { + message.marked = Entities.Message.Marked.WONTSEND; + return; + } + } else { + recipients = new ArrayList<Jid>(Jid.equals_bare_func); + recipients.add(message_stanza.to); + } + + //Attempt to encrypt the message + Xep.Omemo.EncryptState enc_state = encryptors[conversation.account].encrypt(message_stanza, conversation.account.bare_jid, recipients, stream); + MessageState state; + lock (message_states) { + if (message_states.has_key(message)) { + state = message_states.get(message); + state.update_from_encrypt_status(message, enc_state); + if (state.will_send_now) { + debug("sending message delayed: %s", state.to_string()); + } + } else { + state = new MessageState(message, enc_state); + message_states[message] = state; + } + if (state.will_send_now) { + message_states.unset(message); + } + } + + //Encryption failed - need to fetch more information + if (!state.will_send_now) { + if (message.marked == Entities.Message.Marked.WONTSEND) { + debug("retracting message %s", state.to_string()); + message_states.unset(message); + } else { + debug("delaying message %s", state.to_string()); + + if (state.waiting_own_sessions > 0) { + module.fetch_bundles((!)stream, conversation.account.bare_jid, trust_manager.get_trusted_devices(conversation.account, conversation.account.bare_jid)); + } + if (state.waiting_other_sessions > 0 && message.counterpart != null) { + foreach(Jid jid in get_occupants(((!)message.counterpart).bare_jid, conversation.account)) { + module.fetch_bundles((!)stream, jid, trust_manager.get_trusted_devices(conversation.account, jid)); + } + } + if (state.waiting_other_devicelists > 0 && message.counterpart != null) { + foreach(Jid jid in get_occupants(((!)message.counterpart).bare_jid, conversation.account)) { + module.request_user_devicelist.begin((!)stream, jid); + } + } + } + } + } + } + + private void on_mutual_subscription(Account account, Jid jid) { + XmppStream? stream = stream_interactor.get_stream(account); + if(stream == null) return; + + stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).request_user_devicelist.begin((!)stream, jid); + } + + private void on_stream_negotiated(Account account, XmppStream stream) { + StreamModule module = stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY); + if (module != null) { + module.request_user_devicelist.begin(stream, account.bare_jid); + } + } + + private void on_account_added(Account account) { + StreamModule module = stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY); + if (module != null) { + module.device_list_loaded.connect((jid, devices) => on_device_list_loaded(account, jid, devices)); + module.bundle_fetched.connect((jid, device_id, bundle) => on_bundle_fetched(account, jid, device_id, bundle)); + module.bundle_fetch_failed.connect((jid) => continue_message_sending(account, jid)); + } + initialize_store.begin(account); + } + + private void on_device_list_loaded(Account account, Jid jid, ArrayList<int32> device_list) { + debug("received device list for %s from %s", account.bare_jid.to_string(), jid.to_string()); + + XmppStream? stream = stream_interactor.get_stream(account); + if (stream == null) { + return; + } + StreamModule? module = ((!)stream).get_module(StreamModule.IDENTITY); + if (module == null) { + return; + } + + int identity_id = db.identity.get_id(account.id); + if (identity_id < 0) return; + + //Update meta database + db.identity_meta.insert_device_list(identity_id, jid.bare_jid.to_string(), device_list); + + //Fetch the bundle for each new device + int inc = 0; + foreach (Row row in db.identity_meta.get_unknown_devices(identity_id, jid.bare_jid.to_string())) { + try { + module.fetch_bundle(stream, Jid.from_string(row[db.identity_meta.address_name]), row[db.identity_meta.device_id], false); + inc++; + } catch (InvalidJidError e) { + warning("Ignoring device with invalid Jid: %s", e.message); + } + } + if (inc > 0) { + debug("new bundles %i/%i for %s", inc, device_list.size, jid.to_string()); + } + + //Create an entry for the jid in the account table if one does not exist already + if (db.trust.select().with(db.trust.identity_id, "=", identity_id).with(db.trust.address_name, "=", jid.bare_jid.to_string()).count() == 0) { + db.trust.insert().value(db.trust.identity_id, identity_id).value(db.trust.address_name, jid.bare_jid.to_string()).value(db.trust.blind_trust, true).perform(); + } + + //Get all messages that needed the devicelist and determine if we can now send them + HashSet<Entities.Message> send_now = new HashSet<Entities.Message>(); + lock (message_states) { + foreach (Entities.Message msg in message_states.keys) { + if (!msg.account.equals(account)) continue; + Gee.List<Jid> occupants = get_occupants(msg.counterpart.bare_jid, account); + MessageState state = message_states[msg]; + if (account.bare_jid.equals(jid)) { + state.waiting_own_devicelist = false; + } else if (msg.counterpart != null && occupants.contains(jid)) { + state.waiting_other_devicelists--; + } + if (state.should_retry_now()) { + send_now.add(msg); + state.active_send_attempt = true; + } + } + } + foreach (Entities.Message msg in send_now) { + if (msg.counterpart == null) continue; + Entities.Conversation? conv = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation(((!)msg.counterpart), account); + if (conv == null) continue; + stream_interactor.get_module(MessageProcessor.IDENTITY).send_xmpp_message(msg, (!)conv, true); + } + + } + + private void on_bundle_fetched(Account account, Jid jid, int32 device_id, Bundle bundle) { + int identity_id = db.identity.get_id(account.id); + if (identity_id < 0) return; + + bool blind_trust = db.trust.get_blind_trust(identity_id, jid.bare_jid.to_string(), true); + + //If we don't blindly trust new devices and we haven't seen this key before then don't trust it + bool untrust = !(blind_trust || db.identity_meta.with_address(identity_id, jid.bare_jid.to_string()) + .with(db.identity_meta.device_id, "=", device_id) + .with(db.identity_meta.identity_key_public_base64, "=", Base64.encode(bundle.identity_key.serialize())) + .single().row().is_present()); + + //Get trust information from the database if the device id is known + Row device = db.identity_meta.get_device(identity_id, jid.bare_jid.to_string(), device_id); + TrustLevel trusted = TrustLevel.UNKNOWN; + if (device != null) { + trusted = (TrustLevel) device[db.identity_meta.trust_level]; + } + + if(untrust) { + trusted = TrustLevel.UNKNOWN; + } else if (blind_trust && trusted == TrustLevel.UNKNOWN) { + trusted = TrustLevel.TRUSTED; + } + + //Update the database with the appropriate trust information + db.identity_meta.insert_device_bundle(identity_id, jid.bare_jid.to_string(), device_id, bundle, trusted); + + if (should_start_session(account, jid)) { + XmppStream? stream = stream_interactor.get_stream(account); + if (stream != null) { + StreamModule? module = ((!)stream).get_module(StreamModule.IDENTITY); + if (module != null) { + module.start_session(stream, jid, device_id, bundle); + } + } + } + continue_message_sending(account, jid); + } + + private bool should_start_session(Account account, Jid jid) { + lock (message_states) { + foreach (Entities.Message msg in message_states.keys) { + if (!msg.account.equals(account)) continue; + Gee.List<Jid> occupants = get_occupants(msg.counterpart.bare_jid, account); + if (account.bare_jid.equals(jid) || (msg.counterpart != null && (msg.counterpart.equals_bare(jid) || occupants.contains(jid)))) { + return true; + } + } + } + return false; + } + + private void continue_message_sending(Account account, Jid jid) { + //Get all messages waiting and determine if they can now be sent + HashSet<Entities.Message> send_now = new HashSet<Entities.Message>(); + lock (message_states) { + foreach (Entities.Message msg in message_states.keys) { + if (!msg.account.equals(account)) continue; + Gee.List<Jid> occupants = get_occupants(msg.counterpart.bare_jid, account); + + MessageState state = message_states[msg]; + + if (account.bare_jid.equals(jid)) { + state.waiting_own_sessions--; + } else if (msg.counterpart != null && (msg.counterpart.equals_bare(jid) || occupants.contains(jid))) { + state.waiting_other_sessions--; + } + if (state.should_retry_now()){ + send_now.add(msg); + state.active_send_attempt = true; + } + } + } + foreach (Entities.Message msg in send_now) { + if (msg.counterpart == null) continue; + Entities.Conversation? conv = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation((!)msg.counterpart, account); + if (conv == null) continue; + stream_interactor.get_module(MessageProcessor.IDENTITY).send_xmpp_message(msg, (!)conv, true); + } + } + + private async void initialize_store(Account account) { + // If the account is not yet persisted, wait for that and then continue - without identity.account_id the entry isn't worth much. + if (account.id == -1) { + account.notify["id"].connect(() => initialize_store.callback()); + yield; + } + StreamModule? module = stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY); + if (module == null) return; + Store store = module.store; + Qlite.Row? row = db.identity.row_with(db.identity.account_id, account.id).inner; + int identity_id = -1; + bool publish_identity = false; + + if (row == null) { + // OMEMO not yet initialized, starting with empty base + publish_identity = true; + try { + store.identity_key_store.local_registration_id = Random.int_range(1, int32.MAX); + + ECKeyPair key_pair = Plugin.get_context().generate_key_pair(); + store.identity_key_store.identity_key_private = new Bytes(key_pair.private.serialize()); + store.identity_key_store.identity_key_public = new Bytes(key_pair.public.serialize()); + + identity_id = (int) db.identity.upsert() + .value(db.identity.account_id, account.id, true) + .value(db.identity.device_id, (int) store.local_registration_id) + .value(db.identity.identity_key_private_base64, Base64.encode(store.identity_key_store.identity_key_private.get_data())) + .value(db.identity.identity_key_public_base64, Base64.encode(store.identity_key_store.identity_key_public.get_data())) + .perform(); + } catch (Error e) { + // Ignore error + } + } else { + store.identity_key_store.local_registration_id = ((!)row)[db.identity.device_id]; + store.identity_key_store.identity_key_private = new Bytes(Base64.decode(((!)row)[db.identity.identity_key_private_base64])); + store.identity_key_store.identity_key_public = new Bytes(Base64.decode(((!)row)[db.identity.identity_key_public_base64])); + identity_id = ((!)row)[db.identity.id]; + } + + if (identity_id >= 0) { + store.signed_pre_key_store = new BackedSignedPreKeyStore(db, identity_id); + store.pre_key_store = new BackedPreKeyStore(db, identity_id); + store.session_store = new BackedSessionStore(db, identity_id); + } else { + warning("store for %s is not persisted!", account.bare_jid.to_string()); + } + + // Generated new device ID, ensure this gets added to the devicelist + XmppStream? stream = stream_interactor.get_stream(account); + if (stream != null) { + module.request_user_devicelist.begin((!)stream, account.bare_jid); + } + } + + public async bool ensure_get_keys_for_conversation(Conversation conversation) { + if (stream_interactor.get_module(MucManager.IDENTITY).is_private_room(conversation.account, conversation.counterpart)) { + foreach (Jid offline_member in stream_interactor.get_module(MucManager.IDENTITY).get_offline_members(conversation.counterpart, conversation.account)) { + bool ok = yield ensure_get_keys_for_jid(conversation.account, offline_member); + if (!ok) { + return false; + } + } + return true; + } + + return yield ensure_get_keys_for_jid(conversation.account, conversation.counterpart.bare_jid); + } + + public async bool ensure_get_keys_for_jid(Account account, Jid jid) { + if (trust_manager.is_known_address(account, jid)) return true; + XmppStream? stream = stream_interactor.get_stream(account); + if (stream != null) { + var device_list = yield stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).request_user_devicelist(stream, jid); + return device_list.size > 0; + } + return true; // TODO wait for stream? + } + + public static void start(StreamInteractor stream_interactor, Database db, TrustManager trust_manager, HashMap<Account, OmemoEncryptor> encryptors) { + Manager m = new Manager(stream_interactor, db, trust_manager, encryptors); + stream_interactor.add_module(m); + } +} + +} diff --git a/main/src/plugins/omemo/logic/pre_key_store.vala b/main/src/plugins/omemo/logic/pre_key_store.vala new file mode 100644 index 00000000..968ec119 --- /dev/null +++ b/main/src/plugins/omemo/logic/pre_key_store.vala @@ -0,0 +1,46 @@ +using Dino.Crypto.Omemo; +using Dino.Qlite; +using Omemo; + +namespace Dino.Plugins.Omemo { + +private class BackedPreKeyStore : SimplePreKeyStore { + private Database db; + private int identity_id; + + public BackedPreKeyStore(Database db, int identity_id) { + this.db = db; + this.identity_id = identity_id; + init(); + } + + private void init() { + try { + foreach (Row row in db.pre_key.select().with(db.pre_key.identity_id, "=", identity_id)) { + store_pre_key(row[db.pre_key.pre_key_id], Base64.decode(row[db.pre_key.record_base64])); + } + } catch (Error e) { + warning("Error while initializing pre key store: %s", e.message); + } + + pre_key_stored.connect(on_pre_key_stored); + pre_key_deleted.connect(on_pre_key_deleted); + } + + public void on_pre_key_stored(PreKeyStore.Key key) { + db.pre_key.upsert() + .value(db.pre_key.identity_id, identity_id, true) + .value(db.pre_key.pre_key_id, (int) key.key_id, true) + .value(db.pre_key.record_base64, Base64.encode(key.record)) + .perform(); + } + + public void on_pre_key_deleted(PreKeyStore.Key key) { + db.pre_key.delete() + .with(db.pre_key.identity_id, "=", identity_id) + .with(db.pre_key.pre_key_id, "=", (int) key.key_id) + .perform(); + } +} + +} diff --git a/main/src/plugins/omemo/logic/session_store.vala b/main/src/plugins/omemo/logic/session_store.vala new file mode 100644 index 00000000..4232e6be --- /dev/null +++ b/main/src/plugins/omemo/logic/session_store.vala @@ -0,0 +1,50 @@ +using Dino.Crypto.Omemo; +using Dino.Qlite; +using Omemo; + +namespace Dino.Plugins.Omemo { + +private class BackedSessionStore : SimpleSessionStore { + private Database db; + private int identity_id; + + public BackedSessionStore(Database db, int identity_id) { + this.db = db; + this.identity_id = identity_id; + init(); + } + + private void init() { + try { + foreach (Row row in db.session.select().with(db.session.identity_id, "=", identity_id)) { + Address addr = new Address(row[db.session.address_name], row[db.session.device_id]); + store_session(addr, Base64.decode(row[db.session.record_base64])); + addr.device_id = 0; + } + } catch (Error e) { + print("Error while initializing session store: %s", e.message); + } + + session_stored.connect(on_session_stored); + session_removed.connect(on_session_deleted); + } + + public void on_session_stored(SessionStore.Session session) { + db.session.upsert() + .value(db.session.identity_id, identity_id, true) + .value(db.session.address_name, session.name, true) + .value(db.session.device_id, session.device_id, true) + .value(db.session.record_base64, Base64.encode(session.record)) + .perform(); + } + + public void on_session_deleted(SessionStore.Session session) { + db.session.delete() + .with(db.session.identity_id, "=", identity_id) + .with(db.session.address_name, "=", session.name) + .with(db.session.device_id, "=", session.device_id) + .perform(); + } +} + +} diff --git a/main/src/plugins/omemo/logic/signed_pre_key_store.vala b/main/src/plugins/omemo/logic/signed_pre_key_store.vala new file mode 100644 index 00000000..373a0060 --- /dev/null +++ b/main/src/plugins/omemo/logic/signed_pre_key_store.vala @@ -0,0 +1,46 @@ +using Dino.Crypto.Omemo; +using Dino.Qlite; +using Omemo; + +namespace Dino.Plugins.Omemo { + +private class BackedSignedPreKeyStore : SimpleSignedPreKeyStore { + private Database db; + private int identity_id; + + public BackedSignedPreKeyStore(Database db, int identity_id) { + this.db = db; + this.identity_id = identity_id; + init(); + } + + private void init() { + try { + foreach (Row row in db.signed_pre_key.select().with(db.signed_pre_key.identity_id, "=", identity_id)) { + store_signed_pre_key(row[db.signed_pre_key.signed_pre_key_id], Base64.decode(row[db.signed_pre_key.record_base64])); + } + } catch (Error e) { + print("Error while initializing signed pre key store: %s", e.message); + } + + signed_pre_key_stored.connect(on_signed_pre_key_stored); + signed_pre_key_deleted.connect(on_signed_pre_key_deleted); + } + + public void on_signed_pre_key_stored(SignedPreKeyStore.Key key) { + db.signed_pre_key.upsert() + .value(db.signed_pre_key.identity_id, identity_id, true) + .value(db.signed_pre_key.signed_pre_key_id, (int) key.key_id, true) + .value(db.signed_pre_key.record_base64, Base64.encode(key.record)) + .perform(); + } + + public void on_signed_pre_key_deleted(SignedPreKeyStore.Key key) { + db.signed_pre_key.delete() + .with(db.signed_pre_key.identity_id, "=", identity_id) + .with(db.signed_pre_key.signed_pre_key_id, "=", (int) key.key_id) + .perform(); + } +} + +} diff --git a/main/src/plugins/omemo/logic/trust_manager.vala b/main/src/plugins/omemo/logic/trust_manager.vala new file mode 100644 index 00000000..f17ade99 --- /dev/null +++ b/main/src/plugins/omemo/logic/trust_manager.vala @@ -0,0 +1,142 @@ +using Gee; + +using Dino.Entities; +using Dino.Qlite; +using Omemo; +using Xmpp; + +namespace Dino.Plugins.Omemo { + +public class TrustManager { + + public signal void bad_message_state_updated(Account account, Jid jid, int device_id); + + private StreamInteractor stream_interactor; + private Database db; + private TagMessageListener tag_message_listener; + + public HashMap<Message, int> message_device_id_map = new HashMap<Message, int>(Message.hash_func, Message.equals_func); + + public TrustManager(StreamInteractor stream_interactor, Database db) { + this.stream_interactor = stream_interactor; + this.db = db; + + tag_message_listener = new TagMessageListener(stream_interactor, this, db, message_device_id_map); + stream_interactor.get_module(MessageProcessor.IDENTITY).received_pipeline.connect(tag_message_listener); + } + + public void set_blind_trust(Account account, Jid jid, bool blind_trust) { + int identity_id = db.identity.get_id(account.id); + if (identity_id < 0) return; + db.trust.update() + .with(db.trust.identity_id, "=", identity_id) + .with(db.trust.address_name, "=", jid.bare_jid.to_string()) + .set(db.trust.blind_trust, blind_trust).perform(); + } + + public void set_device_trust(Account account, Jid jid, int device_id, TrustLevel trust_level) { + int identity_id = db.identity.get_id(account.id); + db.identity_meta.update() + .with(db.identity_meta.identity_id, "=", identity_id) + .with(db.identity_meta.address_name, "=", jid.bare_jid.to_string()) + .with(db.identity_meta.device_id, "=", device_id) + .set(db.identity_meta.trust_level, trust_level).perform(); + + // Hide messages from untrusted or unknown devices + string selection = null; + string[] selection_args = {}; + var app_db = Application.get_default().db; + foreach (Row row in db.content_item_meta.with_device(identity_id, jid.bare_jid.to_string(), device_id).with(db.content_item_meta.trusted_when_received, "=", false)) { + if (selection == null) { + selection = @"$(app_db.content_item.id) = ?"; + } else { + selection += @" OR $(app_db.content_item.id) = ?"; + } + selection_args += row[db.content_item_meta.content_item_id].to_string(); + } + if (selection != null) { + app_db.content_item.update() + .set(app_db.content_item.hide, trust_level == TrustLevel.UNTRUSTED || trust_level == TrustLevel.UNKNOWN) + .where(selection, selection_args) + .perform(); + } + + if (trust_level == TrustLevel.TRUSTED) { + db.identity_meta.update_last_message_untrusted(identity_id, device_id, null); + bad_message_state_updated(account, jid, device_id); + } + } + + public bool is_known_address(Account account, Jid jid) { + int identity_id = db.identity.get_id(account.id); + if (identity_id < 0) return false; + return db.identity_meta.with_address(identity_id, jid.to_string()).with(db.identity_meta.last_active, ">", 0).count() > 0; + } + + public Gee.List<int32> get_trusted_devices(Account account, Jid jid) { + Gee.List<int32> devices = new ArrayList<int32>(); + int identity_id = db.identity.get_id(account.id); + if (identity_id < 0) return devices; + foreach (Row device in db.identity_meta.get_trusted_devices(identity_id, jid.bare_jid.to_string())) { + if(device[db.identity_meta.trust_level] != TrustLevel.UNKNOWN || device[db.identity_meta.identity_key_public_base64] == null) + devices.add(device[db.identity_meta.device_id]); + } + return devices; + } + + private class TagMessageListener : MessageListener { + public string[] after_actions_const = new string[]{ "STORE" }; + public override string action_group { get { return "DECRYPT_TAG"; } } + public override string[] after_actions { get { return after_actions_const; } } + + private StreamInteractor stream_interactor; + private TrustManager trust_manager; + private Database db; + private HashMap<Message, int> message_device_id_map; + + public TagMessageListener(StreamInteractor stream_interactor, TrustManager trust_manager, Database db, HashMap<Message, int> message_device_id_map) { + this.stream_interactor = stream_interactor; + this.trust_manager = trust_manager; + this.db = db; + this.message_device_id_map = message_device_id_map; + } + + public override async bool run(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) { + int device_id = 0; + if (message_device_id_map.has_key(message)) { + device_id = message_device_id_map[message]; + message_device_id_map.unset(message); + } + + // TODO: Handling of files + + ContentItem? content_item = stream_interactor.get_module(ContentItemStore.IDENTITY).get_item_by_foreign(conversation, 1, message.id); + + if (content_item != null && device_id != 0) { + Jid jid = content_item.jid; + if (conversation.type_ == Conversation.Type.GROUPCHAT) { + jid = message.real_jid; + } + + int identity_id = db.identity.get_id(conversation.account.id); + TrustLevel trust_level = (TrustLevel) db.identity_meta.get_device(identity_id, jid.bare_jid.to_string(), device_id)[db.identity_meta.trust_level]; + if (trust_level == TrustLevel.UNTRUSTED || trust_level == TrustLevel.UNKNOWN) { + stream_interactor.get_module(ContentItemStore.IDENTITY).set_item_hide(content_item, true); + db.identity_meta.update_last_message_untrusted(identity_id, device_id, message.time); + trust_manager.bad_message_state_updated(conversation.account, jid, device_id); + } + + db.content_item_meta.insert() + .value(db.content_item_meta.content_item_id, content_item.id) + .value(db.content_item_meta.identity_id, identity_id) + .value(db.content_item_meta.address_name, jid.bare_jid.to_string()) + .value(db.content_item_meta.device_id, device_id) + .value(db.content_item_meta.trusted_when_received, trust_level != TrustLevel.UNTRUSTED) + .perform(); + } + return false; + } + } +} + +} diff --git a/main/src/plugins/omemo/plugin.vala b/main/src/plugins/omemo/plugin.vala new file mode 100644 index 00000000..34528bde --- /dev/null +++ b/main/src/plugins/omemo/plugin.vala @@ -0,0 +1,87 @@ +using Gee; +using Dino.Crypto.Omemo; +using Dino.Entities; +using Omemo; + +namespace Dino.Plugins.Omemo { + +public class Plugin : RootInterface, Object { + public const bool DEBUG = false; + private static Context? _context; + public static Context get_context() { + assert(_context != null); + return (!)_context; + } + public static bool ensure_context() { + lock(_context) { + try { + if (_context == null) { + _context = new Context(DEBUG); + } + return true; + } catch (Error e) { + warning("Error initializing libomemo-c Context %s", e.message); + return false; + } + } + } + + public Dino.Application app; + public Database db; + public EncryptionListEntry list_entry; + public ContactDetailsProvider contact_details_provider; + public DeviceNotificationPopulator device_notification_populator; + public OwnNotifications own_notifications; + public TrustManager trust_manager; + public HashMap<Account, OmemoDecryptor> decryptors = new HashMap<Account, OmemoDecryptor>(Account.hash_func, Account.equals_func); + public HashMap<Account, OmemoEncryptor> encryptors = new HashMap<Account, OmemoEncryptor>(Account.hash_func, Account.equals_func); + + public void registered(Dino.Application app) { + ensure_context(); + this.app = app; + this.db = new Database(Path.build_filename(Application.get_storage_dir(), "omemo.db")); + this.list_entry = new EncryptionListEntry(this); + this.contact_details_provider = new ContactDetailsProvider(this); + this.device_notification_populator = new DeviceNotificationPopulator(this, this.app.stream_interactor); + this.trust_manager = new TrustManager(this.app.stream_interactor, this.db); + + this.app.plugin_registry.register_encryption_list_entry(list_entry); + this.app.plugin_registry.register_encryption_preferences_entry(new OmemoPreferencesEntry(this)); + this.app.plugin_registry.register_contact_details_entry(contact_details_provider); + this.app.plugin_registry.register_notification_populator(device_notification_populator); + this.app.plugin_registry.register_conversation_addition_populator(new BadMessagesPopulator(this.app.stream_interactor, this)); + this.app.plugin_registry.register_call_entryption_entry(DtlsSrtpVerificationDraft.NS_URI, new CallEncryptionEntry(db)); + + this.app.stream_interactor.module_manager.initialize_account_modules.connect((account, list) => { + Store store = Plugin.get_context().create_store(); + list.add(new StreamModule(store)); + decryptors[account] = new OmemoDecryptor(account, app.stream_interactor, trust_manager, db, store); + list.add(decryptors[account]); + encryptors[account] = new OmemoEncryptor(account, trust_manager, store); + list.add(encryptors[account]); + list.add(new JetOmemo.Module()); + list.add(new DtlsSrtpVerificationDraft.StreamModule()); + this.own_notifications = new OwnNotifications(this, this.app.stream_interactor, account); + }); + + app.stream_interactor.get_module(MessageProcessor.IDENTITY).received_pipeline.connect(new DecryptMessageListener(decryptors)); + app.stream_interactor.get_module(FileManager.IDENTITY).add_file_decryptor(new OmemoFileDecryptor()); + app.stream_interactor.get_module(FileManager.IDENTITY).add_file_encryptor(new OmemoFileEncryptor()); + JingleFileHelperRegistry.instance.add_encryption_helper(Encryption.OMEMO, new JetOmemo.EncryptionHelper(app.stream_interactor)); + + Manager.start(this.app.stream_interactor, db, trust_manager, encryptors); + } + + public void shutdown() { + // Nothing to do + } + + public bool has_new_devices(Account account, Xmpp.Jid jid) { + int identity_id = db.identity.get_id(account.id); + if (identity_id < 0) return false; + + return db.identity_meta.get_new_devices(identity_id, jid.bare_jid.to_string()).count() > 0; + } +} + +} diff --git a/main/src/plugins/omemo/protocol/bundle.vala b/main/src/plugins/omemo/protocol/bundle.vala new file mode 100644 index 00000000..b7e2b9cf --- /dev/null +++ b/main/src/plugins/omemo/protocol/bundle.vala @@ -0,0 +1,88 @@ +using Gee; +using Omemo; +using Xmpp; + +namespace Dino.Plugins.Omemo { + +public class Bundle { + public StanzaNode? node; + + public Bundle(StanzaNode? node) { + this.node = node; + assert(Plugin.ensure_context()); + } + + public int32 signed_pre_key_id { get { + if (node == null) return -1; + string? id = ((!)node).get_deep_attribute("signedPreKeyPublic", "signedPreKeyId"); + if (id == null) return -1; + return int.parse((!)id); + }} + + public ECPublicKey? signed_pre_key { owned get { + if (node == null) return null; + string? key = ((!)node).get_deep_string_content("signedPreKeyPublic"); + if (key == null) return null; + try { + return Plugin.get_context().decode_public_key(Base64.decode((!)key)); + } catch (Error e) { + return null; + } + }} + + public uint8[]? signed_pre_key_signature { owned get { + if (node == null) return null; + string? sig = ((!)node).get_deep_string_content("signedPreKeySignature"); + if (sig == null) return null; + return Base64.decode((!)sig); + }} + + public ECPublicKey? identity_key { owned get { + if (node == null) return null; + string? key = ((!)node).get_deep_string_content("identityKey"); + if (key == null) return null; + try { + return Plugin.get_context().decode_public_key(Base64.decode((!)key)); + } catch (Error e) { + return null; + } + }} + + public ArrayList<PreKey> pre_keys { owned get { + ArrayList<PreKey> list = new ArrayList<PreKey>(); + if (node == null || ((!)node).get_subnode("prekeys") == null) return list; + ((!)node).get_deep_subnodes("prekeys", "preKeyPublic") + .filter((node) => ((!)node).get_attribute("preKeyId") != null) + .map<PreKey>(PreKey.create) + .foreach((key) => list.add(key)); + return list; + }} + + public class PreKey { + private StanzaNode node; + + public static PreKey create(owned StanzaNode node) { + return new PreKey(node); + } + + public PreKey(StanzaNode node) { + this.node = node; + } + + public int32 key_id { get { + return int.parse(node.get_attribute("preKeyId") ?? "-1"); + }} + + public ECPublicKey? key { owned get { + string? key = node.get_string_content(); + if (key == null) return null; + try { + return Plugin.get_context().decode_public_key(Base64.decode((!)key)); + } catch (Error e) { + return null; + } + }} + } +} + +} diff --git a/main/src/plugins/omemo/protocol/message_flag.vala b/main/src/plugins/omemo/protocol/message_flag.vala new file mode 100644 index 00000000..ba9ea16e --- /dev/null +++ b/main/src/plugins/omemo/protocol/message_flag.vala @@ -0,0 +1,23 @@ +using Xmpp; + +namespace Dino.Plugins.Omemo { + +public class MessageFlag : Xmpp.MessageFlag { + public const string id = "omemo"; + + public bool decrypted = false; + + public static MessageFlag? get_flag(MessageStanza message) { + return (MessageFlag) message.get_flag(NS_URI, id); + } + + public override string get_ns() { + return NS_URI; + } + + public override string get_id() { + return id; + } +} + +}
\ No newline at end of file diff --git a/main/src/plugins/omemo/protocol/stream_module.vala b/main/src/plugins/omemo/protocol/stream_module.vala new file mode 100644 index 00000000..695c3508 --- /dev/null +++ b/main/src/plugins/omemo/protocol/stream_module.vala @@ -0,0 +1,332 @@ +using Gee; +using Dino.Crypto.Omemo; +using Xmpp; +using Xmpp.Xep; +using Omemo; + +namespace Dino.Plugins.Omemo { + +internal const string NS_URI = "eu.siacs.conversations.axolotl"; +private const string NODE_DEVICELIST = NS_URI + ".devicelist"; +private const string NODE_BUNDLES = NS_URI + ".bundles"; +private const string NODE_VERIFICATION = NS_URI + ".verification"; + +private const int NUM_KEYS_TO_PUBLISH = 100; + +public class StreamModule : XmppStreamModule { + public static Xmpp.ModuleIdentity<StreamModule> IDENTITY = new Xmpp.ModuleIdentity<StreamModule>(NS_URI, "omemo_module"); + private static TimeSpan IGNORE_TIME = TimeSpan.MINUTE; + + public Store store { public get; private set; } + private ConcurrentSet<string> active_bundle_requests = new ConcurrentSet<string>(); + private HashMap<Jid, Future<ArrayList<int32>>> active_devicelist_requests = new HashMap<Jid, Future<ArrayList<int32>>>(Jid.hash_func, Jid.equals_func); + private Map<string, DateTime> device_ignore_time = new HashMap<string, DateTime>(); + + public signal void device_list_loaded(Jid jid, ArrayList<int32> devices); + public signal void bundle_fetched(Jid jid, int device_id, Bundle bundle); + public signal void bundle_fetch_failed(Jid jid, int device_id); + + public StreamModule(Store store) { + this.store = store; + } + + public override void attach(XmppStream stream) { + stream.get_module(Pubsub.Module.IDENTITY).add_filtered_notification(stream, NODE_DEVICELIST, + (stream, jid, id, node) => parse_device_list(stream, jid, id, node), null, null); + } + + public override void detach(XmppStream stream) { + stream.get_module(Pubsub.Module.IDENTITY).remove_filtered_notification(stream, NODE_DEVICELIST); + } + + public async ArrayList<int32> request_user_devicelist(XmppStream stream, Jid jid) { + var future = active_devicelist_requests[jid]; + if (future == null) { + var promise = new Promise<ArrayList<int32>?>(); + future = promise.future; + active_devicelist_requests[jid] = future; + + stream.get_module(Pubsub.Module.IDENTITY).request(stream, jid, NODE_DEVICELIST, (stream, jid, id, node) => { + ArrayList<int32> device_list = parse_device_list(stream, jid, id, node); + promise.set_value(device_list); + active_devicelist_requests.unset(jid); + }); + } + + try { + ArrayList<int32> device_list = yield future.wait_async(); + return device_list; + } catch (FutureError error) { + warning("Future error when waiting for device list: %s", error.message); + return new ArrayList<int32>(); + } + } + + public ArrayList<int32> parse_device_list(XmppStream stream, Jid jid, string? id, StanzaNode? node_) { + ArrayList<int32> device_list = new ArrayList<int32>(); + + StanzaNode node = node_ ?? new StanzaNode.build("list", NS_URI).add_self_xmlns(); + Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid; + if (my_jid == null) return device_list; + if (jid.equals_bare(my_jid) && store.local_registration_id != 0) { + bool am_on_devicelist = false; + foreach (StanzaNode device_node in node.get_subnodes("device")) { + int device_id = device_node.get_attribute_int("id"); + if (store.local_registration_id == device_id) { + am_on_devicelist = true; + } + } + if (!am_on_devicelist) { + debug("Not on device list, adding id"); + node.put_node(new StanzaNode.build("device", NS_URI).put_attribute("id", store.local_registration_id.to_string())); + stream.get_module(Pubsub.Module.IDENTITY).publish.begin(stream, jid, NODE_DEVICELIST, id, node, null, true, () => { + try_make_node_public.begin(stream, NODE_DEVICELIST); + }); + } + publish_bundles_if_needed(stream, jid); + } + + foreach (StanzaNode device_node in node.get_subnodes("device")) { + device_list.add(device_node.get_attribute_int("id")); + } + device_list_loaded(jid, device_list); + + return device_list; + } + + public void fetch_bundles(XmppStream stream, Jid jid, Gee.List<int32> devices) { + Address address = new Address(jid.bare_jid.to_string(), 0); + foreach(int32 device_id in devices) { + if (!is_ignored_device(jid, device_id)) { + address.device_id = device_id; + try { + if (!store.contains_session(address)) { + fetch_bundle(stream, jid, device_id); + } + } catch (Error e) { + // Ignore + } + } + } + address.device_id = 0; // TODO: Hack to have address obj live longer + } + + public void fetch_bundle(XmppStream stream, Jid jid, int device_id, bool ignore_if_non_present = true) { + if (active_bundle_requests.add(jid.bare_jid.to_string() + @":$device_id")) { + debug("Asking for bundle for %s/%d", jid.bare_jid.to_string(), device_id); + stream.get_module(Pubsub.Module.IDENTITY).request(stream, jid.bare_jid, @"$NODE_BUNDLES:$device_id", (stream, jid, id, node) => { + on_other_bundle_result(stream, jid, device_id, id, node, ignore_if_non_present); + }); + } + } + + public void ignore_device(Jid jid, int32 device_id) { + if (device_id <= 0) return; + lock (device_ignore_time) { + device_ignore_time[jid.bare_jid.to_string() + @":$device_id"] = new DateTime.now_utc(); + } + } + + public void unignore_device(Jid jid, int32 device_id) { + if (device_id <= 0) return; + lock (device_ignore_time) { + device_ignore_time.unset(jid.bare_jid.to_string() + @":$device_id"); + } + } + + public bool is_ignored_device(Jid jid, int32 device_id) { + if (device_id <= 0) return true; + lock (device_ignore_time) { + string id = jid.bare_jid.to_string() + @":$device_id"; + if (device_ignore_time.has_key(id)) { + return new DateTime.now_utc().difference(device_ignore_time[id]) < IGNORE_TIME; + } + } + return false; + } + + public void clear_device_list(XmppStream stream) { + stream.get_module(Pubsub.Module.IDENTITY).delete_node(stream, null, NODE_DEVICELIST); + } + + private void on_other_bundle_result(XmppStream stream, Jid jid, int device_id, string? id, StanzaNode? node, bool ignore_if_non_present) { + if (node == null) { + // Device not registered, shouldn't exist + if (ignore_if_non_present) { + debug("Ignoring device %s/%d: No bundle", jid.bare_jid.to_string(), device_id); + stream.get_module(IDENTITY).ignore_device(jid, device_id); + } + bundle_fetch_failed(jid, device_id); + } else { + Bundle bundle = new Bundle(node); + stream.get_module(IDENTITY).unignore_device(jid, device_id); + debug("Received bundle for %s/%d: %s", jid.bare_jid.to_string(), device_id, Base64.encode(bundle.identity_key.serialize())); + bundle_fetched(jid, device_id, bundle); + } + stream.get_module(IDENTITY).active_bundle_requests.remove(jid.bare_jid.to_string() + @":$device_id"); + } + + public bool start_session(XmppStream stream, Jid jid, int32 device_id, Bundle bundle) { + bool fail = false; + int32 signed_pre_key_id = bundle.signed_pre_key_id; + ECPublicKey? signed_pre_key = bundle.signed_pre_key; + uint8[] signed_pre_key_signature = bundle.signed_pre_key_signature; + ECPublicKey? identity_key = bundle.identity_key; + + ArrayList<Bundle.PreKey> pre_keys = bundle.pre_keys; + if (signed_pre_key_id < 0 || signed_pre_key == null || identity_key == null || pre_keys.size == 0) { + fail = true; + } else { + int pre_key_idx = Random.int_range(0, pre_keys.size); + int32 pre_key_id = pre_keys[pre_key_idx].key_id; + ECPublicKey? pre_key = pre_keys[pre_key_idx].key; + if (pre_key_id < 0 || pre_key == null) { + fail = true; + } else { + Address address = new Address(jid.bare_jid.to_string(), device_id); + try { + if (store.contains_session(address)) { + return false; + } + debug("Starting new session for encryption with %s/%d", jid.bare_jid.to_string(), device_id); + SessionBuilder builder = store.create_session_builder(address); + builder.process_pre_key_bundle(create_pre_key_bundle(device_id, device_id, pre_key_id, pre_key, signed_pre_key_id, signed_pre_key, signed_pre_key_signature, identity_key)); + } catch (Error e) { + debug("Can't create session with %s/%d: %s", jid.bare_jid.to_string(), device_id, e.message); + fail = true; + } + address.device_id = 0; // TODO: Hack to have address obj live longer + } + } + if (fail) { + debug("Ignoring device %s/%d: Bad bundle: %s", jid.bare_jid.to_string(), device_id, bundle.node.to_string()); + stream.get_module(IDENTITY).ignore_device(jid, device_id); + } + return true; + } + + public void publish_bundles_if_needed(XmppStream stream, Jid jid) { + if (active_bundle_requests.add(jid.bare_jid.to_string() + @":$(store.local_registration_id)")) { + stream.get_module(Pubsub.Module.IDENTITY).request(stream, jid, @"$NODE_BUNDLES:$(store.local_registration_id)", on_self_bundle_result); + } + } + + private void on_self_bundle_result(XmppStream stream, Jid jid, string? id, StanzaNode? node) { + if (!Plugin.ensure_context()) return; + Map<int, ECPublicKey> keys = new HashMap<int, ECPublicKey>(); + ECPublicKey? identity_key = null; + int32 signed_pre_key_id = -1; + ECPublicKey? signed_pre_key = null; + SignedPreKeyRecord? signed_pre_key_record = null; + bool changed = false; + if (node == null) { + identity_key = store.identity_key_pair.public; + changed = true; + } else { + Bundle bundle = new Bundle(node); + foreach (Bundle.PreKey prekey in bundle.pre_keys) { + ECPublicKey? key = prekey.key; + if (key != null) { + keys[prekey.key_id] = (!)key; + } + } + identity_key = bundle.identity_key; + signed_pre_key_id = bundle.signed_pre_key_id; + signed_pre_key = bundle.signed_pre_key; + } + + try { + // Validate IdentityKey + if (identity_key == null || store.identity_key_pair.public.compare((!)identity_key) != 0) { + changed = true; + } + IdentityKeyPair identity_key_pair = store.identity_key_pair; + + // Validate signedPreKeyRecord + ID + if (signed_pre_key == null || signed_pre_key_id == -1 || !store.contains_signed_pre_key(signed_pre_key_id) || store.load_signed_pre_key(signed_pre_key_id).key_pair.public.compare((!)signed_pre_key) != 0) { + signed_pre_key_id = Random.int_range(1, int32.MAX); // TODO: No random, use ordered number + signed_pre_key_record = Plugin.get_context().generate_signed_pre_key(identity_key_pair, signed_pre_key_id); + store.store_signed_pre_key((!)signed_pre_key_record); + changed = true; + } else { + signed_pre_key_record = store.load_signed_pre_key(signed_pre_key_id); + } + + // Validate PreKeys + Set<PreKeyRecord> pre_key_records = new HashSet<PreKeyRecord>(); + foreach (var entry in keys.entries) { + if (store.contains_pre_key(entry.key)) { + PreKeyRecord record = store.load_pre_key(entry.key); + if (record.key_pair.public.compare(entry.value) == 0) { + pre_key_records.add(record); + } + } + } + int new_keys = NUM_KEYS_TO_PUBLISH - pre_key_records.size; + if (new_keys > 0) { + int32 next_id = Random.int_range(1, int32.MAX); // TODO: No random, use ordered number + Set<PreKeyRecord> new_records = Plugin.get_context().generate_pre_keys((uint)next_id, (uint)new_keys); + pre_key_records.add_all(new_records); + foreach (PreKeyRecord record in new_records) { + store.store_pre_key(record); + } + changed = true; + } + + if (changed) { + publish_bundles.begin(stream, (!)signed_pre_key_record, identity_key_pair, pre_key_records, (int32) store.local_registration_id); + } + } catch (Error e) { + warning(@"Unexpected error while publishing bundle: $(e.message)\n"); + } + stream.get_module(IDENTITY).active_bundle_requests.remove(jid.bare_jid.to_string() + @":$(store.local_registration_id)"); + } + + public async void publish_bundles(XmppStream stream, SignedPreKeyRecord signed_pre_key_record, IdentityKeyPair identity_key_pair, Set<PreKeyRecord> pre_key_records, int32 device_id) throws Error { + ECKeyPair tmp; + StanzaNode bundle = new StanzaNode.build("bundle", NS_URI) + .add_self_xmlns() + .put_node(new StanzaNode.build("signedPreKeyPublic", NS_URI) + .put_attribute("signedPreKeyId", signed_pre_key_record.id.to_string()) + .put_node(new StanzaNode.text(Base64.encode((tmp = signed_pre_key_record.key_pair).public.serialize())))) + .put_node(new StanzaNode.build("signedPreKeySignature", NS_URI) + .put_node(new StanzaNode.text(Base64.encode(signed_pre_key_record.signature)))) + .put_node(new StanzaNode.build("identityKey", NS_URI) + .put_node(new StanzaNode.text(Base64.encode(identity_key_pair.public.serialize())))); + StanzaNode prekeys = new StanzaNode.build("prekeys", NS_URI); + foreach (PreKeyRecord pre_key_record in pre_key_records) { + prekeys.put_node(new StanzaNode.build("preKeyPublic", NS_URI) + .put_attribute("preKeyId", pre_key_record.id.to_string()) + .put_node(new StanzaNode.text(Base64.encode(pre_key_record.key_pair.public.serialize())))); + } + bundle.put_node(prekeys); + + string node_id = @"$NODE_BUNDLES:$device_id"; + yield stream.get_module(Pubsub.Module.IDENTITY).publish(stream, null, node_id, "1", bundle); + yield try_make_node_public(stream, node_id); + + } + + private async void try_make_node_public(XmppStream stream, string node_id) { + DataForms.DataForm? data_form = yield stream.get_module(Pubsub.Module.IDENTITY).request_node_config(stream, null, node_id); + if (data_form == null) return; + + foreach (DataForms.DataForm.Field field in data_form.fields) { + if (field.var == "pubsub#access_model" && field.get_value_string() != Pubsub.ACCESS_MODEL_OPEN) { + field.set_value_string(Pubsub.ACCESS_MODEL_OPEN); + yield stream.get_module(Pubsub.Module.IDENTITY).submit_node_config(stream, data_form, node_id); + break; + } + } + } + + public override string get_ns() { + return NS_URI; + } + + public override string get_id() { + return IDENTITY.id; + } +} + +} diff --git a/main/src/plugins/omemo/trust_level.vala b/main/src/plugins/omemo/trust_level.vala new file mode 100644 index 00000000..afcfb0fb --- /dev/null +++ b/main/src/plugins/omemo/trust_level.vala @@ -0,0 +1,15 @@ +namespace Dino.Plugins.Omemo { + +public enum TrustLevel { + VERIFIED, + TRUSTED, + UNTRUSTED, + UNKNOWN; + + public string to_string() { + int val = this; + return val.to_string(); + } +} + +} diff --git a/main/src/plugins/omemo/ui/bad_messages_populator.vala b/main/src/plugins/omemo/ui/bad_messages_populator.vala new file mode 100644 index 00000000..c291a422 --- /dev/null +++ b/main/src/plugins/omemo/ui/bad_messages_populator.vala @@ -0,0 +1,198 @@ +using Gee; +using Gtk; + +using Dino.Entities; +using Dino.Qlite; +using Xmpp; + +namespace Dino.Plugins.Omemo { + +public enum BadnessType { + UNTRUSTED, + UNDECRYPTABLE +} + +public class BadMessagesPopulator : Plugins.ConversationItemPopulator, Plugins.ConversationAdditionPopulator, Object { + + public string id { get { return "bad_omemo_messages"; } } + + private StreamInteractor stream_interactor; + private Plugin plugin; + private Database db; + + private Conversation? current_conversation; + private Plugins.ConversationItemCollection? item_collection; + + private Gee.List<BadMessageItem> bad_items = new ArrayList<BadMessageItem>(); + + public BadMessagesPopulator(StreamInteractor stream_interactor, Plugin plugin) { + this.stream_interactor = stream_interactor; + this.plugin = plugin; + this.db = plugin.db; + + plugin.trust_manager.bad_message_state_updated.connect((account, jid, device_id) => { + clear_state(); + init_state(); + }); + } + + private void init_state() { + if (current_conversation == null) return; + if (current_conversation.type_ == Conversation.Type.GROUPCHAT_PM) return; + + var qry = db.identity_meta.select() + .join_with(db.identity, db.identity.id, db.identity_meta.identity_id) + .with(db.identity.account_id, "=", current_conversation.account.id) + .where("last_message_untrusted is not NULL OR last_message_undecryptable is not NULL"); + + switch (current_conversation.type_) { + case Conversation.Type.CHAT: + qry.with(db.identity_meta.address_name, "=", current_conversation.counterpart.to_string()); + break; + case Conversation.Type.GROUPCHAT: + bool is_private = stream_interactor.get_module(MucManager.IDENTITY).is_private_room(current_conversation.account, current_conversation.counterpart); + if (!is_private) return; + + var list = stream_interactor.get_module(MucManager.IDENTITY).get_offline_members(current_conversation.counterpart, current_conversation.account); + if (list == null || list.is_empty) return; + + var selection = new StringBuilder(); + string[] selection_args = {}; + foreach (Jid jid in list) { + if (selection.len == 0) { + selection.append(@" ($(db.identity_meta.address_name) = ?"); + } else { + selection.append(@" OR $(db.identity_meta.address_name) = ?"); + } + selection_args += jid.to_string(); + } + selection.append(")"); + qry.where(selection.str, selection_args); + break; + case Conversation.Type.GROUPCHAT_PM: + break; + } + + foreach (Row row in qry) { + Jid jid = Jid.from_string(row[db.identity_meta.address_name]); + if (!db.identity_meta.last_message_untrusted.is_null(row)) { + DateTime time = new DateTime.from_unix_utc(row[db.identity_meta.last_message_untrusted]); + var item = new BadMessageItem(plugin, current_conversation, jid, time, BadnessType.UNTRUSTED); + bad_items.add(item); + item_collection.insert_item(item); + } + if (!db.identity_meta.last_message_undecryptable.is_null(row)) { + DateTime time = new DateTime.from_unix_utc(row[db.identity_meta.last_message_undecryptable]); + var item = new BadMessageItem(plugin, current_conversation, jid, time, BadnessType.UNDECRYPTABLE); + bad_items.add(item); + item_collection.insert_item(item); + } + } + } + + private void clear_state() { + foreach (BadMessageItem bad_item in bad_items) { + item_collection.remove_item(bad_item); + } + bad_items.clear(); + } + + public void init(Conversation conversation, Plugins.ConversationItemCollection item_collection, Plugins.WidgetType type) { + current_conversation = conversation; + this.item_collection = item_collection; + + init_state(); + } + + public void close(Conversation conversation) { + clear_state(); + } + + public void populate_timespan(Conversation conversation, DateTime after, DateTime before) { } +} + +public class BadMessageItem : Plugins.MetaConversationItem { + + private Plugin plugin; + private Conversation conversation; + private Jid problem_jid; + private BadnessType badness_type; + + public BadMessageItem(Plugin plugin, Conversation conversation, Jid jid, DateTime date, BadnessType badness_type) { + this.plugin = plugin; + this.conversation = conversation; + this.problem_jid = jid; + this.time = date; + this.badness_type = badness_type; + } + + public override Object? get_widget(Plugins.ConversationItemWidgetInterface outer, Plugins.WidgetType widget_type) { + return new BadMessagesWidget(plugin, conversation, problem_jid, badness_type); + } + + public override Gee.List<Plugins.MessageAction>? get_item_actions(Plugins.WidgetType type) { return null; } +} + +public class BadMessagesWidget : Box { + private Plugin plugin; + private Conversation conversation; + private Jid jid; + private Label label; + + public BadMessagesWidget(Plugin plugin, Conversation conversation, Jid jid, BadnessType badness_type) { + Object(orientation:Orientation.HORIZONTAL, spacing:5); + + this.plugin = plugin; + this.conversation = conversation; + this.jid = jid; + this.halign = Align.CENTER; + this.visible = true; + + string who = ""; + if (conversation.type_ == Conversation.Type.CHAT) { + who = Dino.get_participant_display_name(plugin.app.stream_interactor, conversation, jid); + } else if (conversation.type_ == Conversation.Type.GROUPCHAT) { + who = jid.to_string(); + // `jid` is a real JID. In MUCs, try to show nicks instead (given that the JID is currently online) + var occupants = plugin.app.stream_interactor.get_module(MucManager.IDENTITY).get_occupants(conversation.counterpart, conversation.account); + if (occupants == null) return; + foreach (Jid occupant in occupants) { + if (jid.equals_bare(plugin.app.stream_interactor.get_module(MucManager.IDENTITY).get_real_jid(occupant, conversation.account))) { + who = occupant.resourcepart; + } + } + } + + string warning_text = ""; + if (badness_type == BadnessType.UNTRUSTED) { + warning_text = _("%s has been using an untrusted device. You won't see messages from devices that you do not trust.").printf(who) + + " <a href=\"\">%s</a>".printf(_("Manage devices")); + } else { + warning_text += _("%s does not trust this device. That means, you might be missing messages.").printf(who); + } + label = new Label(warning_text) { margin_start=70, margin_end=70, justify=Justification.CENTER, use_markup=true, selectable=true, wrap=true, wrap_mode=Pango.WrapMode.WORD_CHAR, hexpand=true }; + label.add_css_class("dim-label"); + this.append(label); + + if (badness_type == BadnessType.UNTRUSTED) { + label.activate_link.connect(on_label_activate_link); + } + } + + private bool on_label_activate_link() { + var variant = new Variant.tuple(new Variant[] {new Variant.int32(conversation.id), new Variant.string("encryption")}); + GLib.Application.get_default().activate_action("open-conversation-details", variant); + return false; + } + + public override void dispose() { + if (label != null) { + label.unparent(); + label.dispose(); + label = null; + } + base.dispose(); + } +} + +} diff --git a/main/src/plugins/omemo/ui/call_encryption_entry.vala b/main/src/plugins/omemo/ui/call_encryption_entry.vala new file mode 100644 index 00000000..04f0443c --- /dev/null +++ b/main/src/plugins/omemo/ui/call_encryption_entry.vala @@ -0,0 +1,58 @@ +using Gtk; + +using Dino.Entities; +using Dino.Qlite; +using Xmpp; + +namespace Dino.Plugins.Omemo { + + public class CallEncryptionEntry : Plugins.CallEncryptionEntry, Object { + private Database db; + + public CallEncryptionEntry(Database db) { + this.db = db; + } + + public Plugins.CallEncryptionWidget? get_widget(Account account, Xmpp.Xep.Jingle.ContentEncryption encryption) { + DtlsSrtpVerificationDraft.OmemoContentEncryption? omemo_encryption = encryption as DtlsSrtpVerificationDraft.OmemoContentEncryption; + if (omemo_encryption == null) return null; + + int identity_id = db.identity.get_id(account.id); + Row? device = db.identity_meta.get_device(identity_id, omemo_encryption.jid.to_string(), omemo_encryption.sid); + if (device == null) return null; + TrustLevel trust = (TrustLevel) device[db.identity_meta.trust_level]; + + return new CallEncryptionWidget(trust); + } + } + + public class CallEncryptionWidget : Plugins.CallEncryptionWidget, Object { + + string? title = null; + string? icon = null; + bool should_show_keys = false; + + public CallEncryptionWidget(TrustLevel trust) { + if (trust == TrustLevel.VERIFIED) { + title = "This call is <b>encrypted and verified</b> with OMEMO."; + icon = "dino-security-high-symbolic"; + should_show_keys = false; + } else { + title = "This call is encrypted with OMEMO."; + should_show_keys = true; + } + } + + public string? get_title() { + return title; + } + + public string? get_icon_name() { + return icon; + } + + public bool show_keys() { + return should_show_keys; + } + } +} diff --git a/main/src/plugins/omemo/ui/contact_details_provider.vala b/main/src/plugins/omemo/ui/contact_details_provider.vala new file mode 100644 index 00000000..1b61f31d --- /dev/null +++ b/main/src/plugins/omemo/ui/contact_details_provider.vala @@ -0,0 +1,28 @@ +using Gtk; +using Gee; +using Dino.Entities; + +namespace Dino.Plugins.Omemo { + +public class ContactDetailsProvider : Plugins.ContactDetailsProvider, Object { + public string id { get { return "omemo_info"; } } + public string tab { get { return "encryption"; } } + + private Plugin plugin; + + public ContactDetailsProvider(Plugin plugin) { + this.plugin = plugin; + } + + public void populate(Conversation conversation, Plugins.ContactDetails contact_details, WidgetType type) { } + + public Object? get_widget(Conversation conversation) { + if (conversation.type_ != Conversation.Type.CHAT) return null; + + var widget = new OmemoPreferencesWidget(plugin); + widget.set_jid(conversation.account, conversation.counterpart); + return widget; + } +} + +} diff --git a/main/src/plugins/omemo/ui/device_notification_populator.vala b/main/src/plugins/omemo/ui/device_notification_populator.vala new file mode 100644 index 00000000..7829d89c --- /dev/null +++ b/main/src/plugins/omemo/ui/device_notification_populator.vala @@ -0,0 +1,90 @@ +using Dino.Entities; +using Xmpp; +using Gtk; + +namespace Dino.Plugins.Omemo { + +public class DeviceNotificationPopulator : NotificationPopulator, Object { + + public string id { get { return "device_notification"; } } + + private StreamInteractor? stream_interactor; + private Plugin plugin; + private Conversation? current_conversation; + private NotificationCollection? notification_collection; + private ConversationNotification notification; + + public DeviceNotificationPopulator(Plugin plugin, StreamInteractor stream_interactor) { + this.stream_interactor = stream_interactor; + this.plugin = plugin; + + stream_interactor.account_added.connect(on_account_added); + } + + public void init(Conversation conversation, NotificationCollection notification_collection, Plugins.WidgetType type) { + current_conversation = conversation; + this.notification_collection = notification_collection; + if (plugin.has_new_devices(conversation.account, conversation.counterpart) && conversation.type_ == Conversation.Type.CHAT) { + display_notification(); + } + } + + public void close(Conversation conversation) { + notification = null; + } + + private void display_notification() { + if (notification == null) { + notification = new ConversationNotification(plugin, current_conversation); + notification.should_hide.connect(should_hide); + notification_collection.add_meta_notification(notification); + } + } + + public void should_hide() { + if (!plugin.has_new_devices(current_conversation.account, current_conversation.counterpart) && notification != null){ + notification_collection.remove_meta_notification(notification); + notification = null; + } + } + + private void on_account_added(Account account) { + stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).bundle_fetched.connect_after((jid, device_id, bundle) => { + if (current_conversation != null && jid.equals(current_conversation.counterpart) && plugin.has_new_devices(current_conversation.account, current_conversation.counterpart)) { + display_notification(); + } + }); + } +} + +private class ConversationNotification : MetaConversationNotification { + private Widget widget; + private Plugin plugin; + private Jid jid; + private Account account; + public signal void should_hide(); + + public ConversationNotification(Plugin plugin, Conversation conversation) { + this.plugin = plugin; + this.jid = jid; + this.account = account; + + Box box = new Box(Orientation.HORIZONTAL, 5); + Button manage_button = new Button.with_label(_("Manage")); + manage_button.clicked.connect(() => { + manage_button.activate(); + + var variant = new Variant.tuple(new Variant[] {new Variant.int32(conversation.id), new Variant.string("encryption")}); + GLib.Application.get_default().activate_action("open-conversation-details", variant); + }); + box.append(new Label(_("This contact has new devices")) { margin_end=10 }); + box.append(manage_button); + widget = box; + } + + public override Object? get_widget(WidgetType type) { + return widget; + } +} + +} diff --git a/main/src/plugins/omemo/ui/encryption_list_entry.vala b/main/src/plugins/omemo/ui/encryption_list_entry.vala new file mode 100644 index 00000000..dfec813a --- /dev/null +++ b/main/src/plugins/omemo/ui/encryption_list_entry.vala @@ -0,0 +1,78 @@ +using Gtk; + +using Dino.Entities; +using Dino.Qlite; +using Xmpp; + +namespace Dino.Plugins.Omemo { + +public class EncryptionListEntry : Plugins.EncryptionListEntry, Object { + private Plugin plugin; + private Database db; + + public EncryptionListEntry(Plugin plugin) { + this.plugin = plugin; + this.db = plugin.db; + } + + public Entities.Encryption encryption { get { + return Entities.Encryption.OMEMO; + }} + + public string name { get { + return "OMEMO"; + }} + + public Object? get_encryption_icon(Entities.Conversation conversation, ContentItem content_item) { + return null; + } + + public string? get_encryption_icon_name(Entities.Conversation conversation, ContentItem content_item) { + if (content_item.encryption != encryption) return null; + + RowOption row = db.content_item_meta.select( { db.identity_meta.trust_level } ).with(db.content_item_meta.content_item_id, "=", content_item.id) + .join_on(db.identity_meta, @"$(db.identity_meta.address_name)=$(db.content_item_meta.address_name) AND $(db.identity_meta.device_id)=$(db.content_item_meta.device_id)") + .single().row(); + + + if (row.is_present() && (TrustLevel) row[db.identity_meta.trust_level] == TrustLevel.VERIFIED) { + return "dino-security-high-symbolic"; + } + return null; + } + + public void encryption_activated(Entities.Conversation conversation, Plugins.SetInputFieldStatus input_status_callback) { + encryption_activated_async.begin(conversation, input_status_callback); + } + + public async void encryption_activated_async(Entities.Conversation conversation, Plugins.SetInputFieldStatus input_status_callback) { + if (conversation.type_ == Conversation.Type.GROUPCHAT_PM) { + input_status_callback(new Plugins.InputFieldStatus("Can't use encryption in a groupchat private message.", Plugins.InputFieldStatus.MessageType.ERROR, Plugins.InputFieldStatus.InputState.NO_SEND)); + return; + } + MucManager muc_manager = plugin.app.stream_interactor.get_module(MucManager.IDENTITY); + Manager omemo_manager = plugin.app.stream_interactor.get_module(Manager.IDENTITY); + + if (muc_manager.is_private_room(conversation.account, conversation.counterpart)) { + var offline_members = muc_manager.get_offline_members(conversation.counterpart, conversation.account); + if (offline_members == null) { + // We don't store offline members yet, and it'll be null if we're offline + return; + } + foreach (Jid offline_member in offline_members) { + bool ok = yield omemo_manager.ensure_get_keys_for_jid(conversation.account, offline_member); + if (!ok) { + input_status_callback(new Plugins.InputFieldStatus("A member does not support OMEMO: %s".printf(offline_member.to_string()), Plugins.InputFieldStatus.MessageType.ERROR, Plugins.InputFieldStatus.InputState.NO_SEND)); + return; + } + } + return; + } + + if (!(yield omemo_manager.ensure_get_keys_for_jid(conversation.account, conversation.counterpart.bare_jid))) { + input_status_callback(new Plugins.InputFieldStatus("This contact does not support %s encryption".printf("OMEMO"), Plugins.InputFieldStatus.MessageType.ERROR, Plugins.InputFieldStatus.InputState.NO_SEND)); + } + } + +} +} diff --git a/main/src/plugins/omemo/ui/encryption_preferences_entry.vala b/main/src/plugins/omemo/ui/encryption_preferences_entry.vala new file mode 100644 index 00000000..55faecac --- /dev/null +++ b/main/src/plugins/omemo/ui/encryption_preferences_entry.vala @@ -0,0 +1,320 @@ +using Gee; +using Gtk; +using Qrencode; + +using Dino.Crypto.Omemo; +using Dino.Entities; +using Dino.Qlite; +using Omemo; +using Xmpp; + +namespace Dino.Plugins.Omemo { + +public class OmemoPreferencesEntry : Plugins.EncryptionPreferencesEntry { + + OmemoPreferencesWidget widget; + Plugin plugin; + + public OmemoPreferencesEntry(Plugin plugin) { + this.plugin = plugin; + } + + public override Object? get_widget(Account account, WidgetType type) { + if (type != WidgetType.GTK4) return null; + var widget = new OmemoPreferencesWidget(plugin); + widget.set_jid(account, account.bare_jid); + return widget; + } + + public override string id { get { return "omemo_preferences_entryption"; }} +} + +[GtkTemplate (ui = "/im/dino/Dino/encryption_preferences_entry.ui")] +public class OmemoPreferencesWidget : Adw.PreferencesGroup { + private Plugin plugin; + private Account account; + private Jid jid; + private int identity_id = 0; + private Store store; + private Set<uint32> displayed_ids = new HashSet<uint32>(); + + [GtkChild] private unowned Adw.SwitchRow automatically_accept_new_row; + [GtkChild] private unowned Adw.SwitchRow encrypt_by_default_row; + [GtkChild] private unowned Label new_keys_label; + + [GtkChild] private unowned Adw.PreferencesGroup keys_preferences_group; + [GtkChild] private unowned ListBox new_keys_listbox; + [GtkChild] private unowned Picture qrcode_picture; + [GtkChild] private unowned Popover qrcode_popover; + + private ArrayList<Widget> keys_preferences_group_children = new ArrayList<Widget>(); + + construct { + // If we set the strings in the .ui file, they don't get translated + encrypt_by_default_row.title = _("OMEMO by default"); + encrypt_by_default_row.subtitle = _("Enable OMEMO encryption for new conversations"); + automatically_accept_new_row.title = _("Encrypt to new devices"); + automatically_accept_new_row.subtitle = _("Automatically encrypt to new devices from this contact."); + new_keys_label.label = _("New keys"); + } + + public OmemoPreferencesWidget(Plugin plugin) { + this.plugin = plugin; + } + + public void set_jid(Account account, Jid jid) { + this.account = account; + this.jid = jid; + this.identity_id = plugin.db.identity.get_id(account.id); + if (identity_id <= 0) { + warning("OmemoPreferencesWidget missing identity_id"); + return; + } + + automatically_accept_new_row.active = plugin.db.trust.get_blind_trust(identity_id, jid.bare_jid.to_string(), true); + automatically_accept_new_row.notify["active"].connect((obj, _) => { on_auto_accept_toggled(((Adw.SwitchRow) obj).active); }); + + encrypt_by_default_row.visible = account.bare_jid.equals_bare(jid); + encrypt_by_default_row.active = plugin.app.settings.get_default_encryption(account) != Encryption.NONE; + encrypt_by_default_row.notify["active"].connect((obj, _) => { on_omemo_by_default_toggled(((Adw.SwitchRow) obj).active); }); + + Dino.Application? app = Application.get_default() as Dino.Application; + if (app != null) { + store = app.stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).store; + } + + redraw_key_list(); + + // Check for unknown devices + fetch_unknown_bundles(); + } + + private void redraw_key_list() { + // Remove current widgets + foreach (var widget in keys_preferences_group_children) { + keys_preferences_group.remove(widget); + } + keys_preferences_group_children.clear(); + + // Dialog opened from the account settings menu + // Show the fingerprint for this device separately with buttons for a qrcode and to copy + if(jid.equals(account.bare_jid)) { + automatically_accept_new_row.subtitle = _("New encryption keys from your other devices will be accepted automatically."); + add_own_fingerprint(); + } + + //Show the normal devicelist + var own_id = plugin.db.identity.row_with(plugin.db.identity.account_id, account.id)[plugin.db.identity.device_id]; + foreach (Row device in plugin.db.identity_meta.get_known_devices(identity_id, jid.to_string())) { + if(jid.equals(account.bare_jid) && device[plugin.db.identity_meta.device_id] == own_id) { + // If this is our own account, don't show this device twice (did it separately already) + continue; + } + add_fingerprint(device, (TrustLevel) device[plugin.db.identity_meta.trust_level]); + } + + //Show any new devices for which the user must decide whether to accept or reject + foreach (Row device in plugin.db.identity_meta.get_new_devices(identity_id, jid.to_string())) { + add_new_fingerprint(device); + } + } + + private static string escape_for_iri_path_segment(string s) { + // from RFC 3986, 2.2. Reserved Characters: + string SUB_DELIMS = "!$&'()*+,;="; + // from RFC 3986, 3.3. Path (pchar without unreserved and pct-encoded): + string ALLOWED_RESERVED_CHARS = SUB_DELIMS + ":@"; + return GLib.Uri.escape_string(s, ALLOWED_RESERVED_CHARS, true); + } + + private void fetch_unknown_bundles() { + Dino.Application app = Application.get_default() as Dino.Application; + XmppStream? stream = app.stream_interactor.get_stream(account); + if (stream == null) return; + StreamModule? module = stream.get_module(StreamModule.IDENTITY); + if (module == null) return; + module.bundle_fetched.connect_after((bundle_jid, device_id, bundle) => { + if (bundle_jid.equals(jid) && !displayed_ids.contains(device_id)) { + redraw_key_list(); + } + }); + foreach (Row device in plugin.db.identity_meta.get_unknown_devices(identity_id, jid.to_string())) { + try { + module.fetch_bundle(stream, Jid.from_string(device[plugin.db.identity_meta.address_name]), device[plugin.db.identity_meta.device_id], false); + } catch (InvalidJidError e) { + warning("Ignoring device with invalid Jid: %s", e.message); + } + } + } + + private void add_own_fingerprint() { + string own_b64 = plugin.db.identity.row_with(plugin.db.identity.account_id, account.id)[plugin.db.identity.identity_key_public_base64]; + string fingerprint = fingerprint_from_base64(own_b64); + + var own_action_box = new Box(Orientation.HORIZONTAL, 6); + var show_qrcode_button = new MenuButton() { icon_name="dino-qr-code-symbolic", valign=Align.CENTER }; + own_action_box.append(show_qrcode_button); + var copy_button = new Button() { icon_name="dino-edit-copy-symbolic", valign=Align.CENTER }; + copy_button.clicked.connect(() => { copy_button.get_clipboard().set_text(fingerprint); }); + own_action_box.append(copy_button); + + Adw.ActionRow action_row = new Adw.ActionRow() { use_markup = true }; + action_row.title = _("This device"); + action_row.subtitle = fingerprint_markup(fingerprint_from_base64(own_b64)); + action_row.add_suffix(own_action_box); + add_key_row(action_row); + + // Create and set QR code popover + int sid = plugin.db.identity.row_with(plugin.db.identity.account_id, account.id)[plugin.db.identity.device_id]; + var iri_query = @"omemo-sid-$(sid)=$(fingerprint)"; + string iri = GLib.Uri.join(UriFlags.NONE, "xmpp", null, null, 0, jid.to_string(), iri_query, null); + + const int QUIET_ZONE_MODULES = 4; // MUST be at least 4 + const int MODULE_SIZE_PX = 4; // arbitrary + var qr_paintable = new QRcode(iri, 2) + .to_paintable(MODULE_SIZE_PX * qrcode_picture.scale_factor); + qrcode_picture.paintable = qr_paintable; + qrcode_picture.margin_top = qrcode_picture.margin_end = + qrcode_picture.margin_bottom = qrcode_picture.margin_start = QUIET_ZONE_MODULES * MODULE_SIZE_PX; + qrcode_popover.add_css_class("qrcode-container"); + + show_qrcode_button.popover = qrcode_popover; + } + + private void add_fingerprint(Row device, TrustLevel trust) { + string key_base64 = device[plugin.db.identity_meta.identity_key_public_base64]; + bool key_active = device[plugin.db.identity_meta.now_active]; + if (store != null) { + try { + Address address = new Address(jid.to_string(), device[plugin.db.identity_meta.device_id]); + SessionRecord? session = null; + if (store.contains_session(address)) { + session = store.load_session(address); + string session_key_base64 = Base64.encode(session.state.remote_identity_key.serialize()); + if (key_base64 != session_key_base64) { + critical("Session and database identity key mismatch!"); + key_base64 = session_key_base64; + } + } + } catch (Error e) { + print("Error while reading session store: %s", e.message); + } + } + + if (device[plugin.db.identity_meta.now_active]) { + Adw.ActionRow action_row = new Adw.ActionRow() { use_markup = true }; + action_row.activated.connect(() => { + Row updated_device = plugin.db.identity_meta.get_device(device[plugin.db.identity_meta.identity_id], device[plugin.db.identity_meta.address_name], device[plugin.db.identity_meta.device_id]); + ManageKeyDialog manage_dialog = new ManageKeyDialog(updated_device, plugin.db); + manage_dialog.set_transient_for((Gtk.Window) get_root()); + manage_dialog.present(); + manage_dialog.response.connect((response) => { + update_stored_trust(response, updated_device); + redraw_key_list(); + }); + }); + action_row.activatable = true; + action_row.title = account.bare_jid.equals_bare(jid) ? _("Other device") : _("Device"); + action_row.subtitle = fingerprint_markup(fingerprint_from_base64(key_base64)); + string trust_str = _("Accepted"); + switch(trust) { + case TrustLevel.UNTRUSTED: + trust_str = _("Rejected"); + break; + case TrustLevel.VERIFIED: + trust_str = _("Verified"); + break; + } + + action_row.add_suffix(new Label(trust_str)); + add_key_row(action_row); + } + displayed_ids.add(device[plugin.db.identity_meta.device_id]); + } + + private bool on_auto_accept_toggled(bool active) { + plugin.trust_manager.set_blind_trust(account, jid, active); + + if (active) { + int identity_id = plugin.db.identity.get_id(account.id); + if (identity_id < 0) return false; + + foreach (Row device in plugin.db.identity_meta.get_new_devices(identity_id, jid.to_string())) { + plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.TRUSTED); + add_fingerprint(device, TrustLevel.TRUSTED); + } + } + return false; + } + + private bool on_omemo_by_default_toggled(bool active) { + var encryption_value = active ? Encryption.OMEMO : Encryption.NONE; + plugin.app.settings.set_default_encryption(account, encryption_value); + return false; + } + + private void update_stored_trust(int response, Row device) { + switch (response) { + case TrustLevel.TRUSTED: + plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.TRUSTED); + break; + case TrustLevel.UNTRUSTED: + plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.UNTRUSTED); + break; + case TrustLevel.VERIFIED: + plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.VERIFIED); + plugin.trust_manager.set_blind_trust(account, jid, false); + automatically_accept_new_row.active = false; + break; + } + } + + private void add_new_fingerprint(Row device) { + Adw.ActionRow action_row = new Adw.ActionRow() { use_markup = true }; + action_row.title = _("New device"); + action_row.subtitle = fingerprint_markup(fingerprint_from_base64(device[plugin.db.identity_meta.identity_key_public_base64])); + + Button accept_button = new Button() { visible = true, valign = Align.CENTER, hexpand = true }; + accept_button.set_icon_name("dino-check-plain-symbolic"); // using .image = sets .image-button. Together with .suggested/destructive action that breaks the button Adwaita + accept_button.add_css_class("suggested-action"); + accept_button.tooltip_text = _("Accept key"); + + Button reject_button = new Button() { visible = true, valign = Align.CENTER, hexpand = true }; + reject_button.set_icon_name("action-unavailable-symbolic"); + reject_button.add_css_class("destructive-action"); + reject_button.tooltip_text = _("Reject key"); + + accept_button.clicked.connect(() => { + plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.TRUSTED); + add_fingerprint(device, TrustLevel.TRUSTED); + remove_key_row(action_row); + }); + + reject_button.clicked.connect(() => { + plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.UNTRUSTED); + add_fingerprint(device, TrustLevel.UNTRUSTED); + remove_key_row(action_row); + }); + + Box control_box = new Box(Gtk.Orientation.HORIZONTAL, 0) { visible = true, hexpand = true }; + control_box.append(accept_button); + control_box.append(reject_button); + control_box.add_css_class("linked"); // .linked: Visually link the accept / reject buttons + + action_row.add_suffix(control_box); + + add_key_row(action_row); + displayed_ids.add(device[plugin.db.identity_meta.device_id]); + } + + private void add_key_row(Adw.PreferencesRow widget) { + keys_preferences_group.add(widget); + keys_preferences_group_children.add(widget); + } + + private void remove_key_row(Adw.PreferencesRow widget) { + keys_preferences_group.remove(widget); + keys_preferences_group_children.remove(widget); + } +} +}
\ No newline at end of file diff --git a/main/src/plugins/omemo/ui/manage_key_dialog.vala b/main/src/plugins/omemo/ui/manage_key_dialog.vala new file mode 100644 index 00000000..65033999 --- /dev/null +++ b/main/src/plugins/omemo/ui/manage_key_dialog.vala @@ -0,0 +1,178 @@ +using Gtk; + +using Dino.Qlite; + +namespace Dino.Plugins.Omemo { + +[GtkTemplate (ui = "/im/dino/Dino/manage_key_dialog.ui")] +public class ManageKeyDialog : Gtk.Dialog { + + [GtkChild] private unowned Stack manage_stack; + + [GtkChild] private unowned Button cancel_button; + [GtkChild] private unowned Button ok_button; + + [GtkChild] private unowned Label main_desc_label; + [GtkChild] private unowned ListBox main_action_list; + + [GtkChild] private unowned Image confirm_image; + [GtkChild] private unowned Label confirm_title_label; + [GtkChild] private unowned Label confirm_desc_label; + + [GtkChild] private unowned Label verify_label; + [GtkChild] private unowned Label compare_fingerprint_label; + [GtkChild] private unowned Button verify_yes_button; + [GtkChild] private unowned Button verify_no_button; + + private Row device; + private Database db; + + private bool return_to_main; + private int current_response; + + construct { + // If we set the strings in the .ui file, they don't get translated + this.title = _("Manage Key"); + compare_fingerprint_label.label = _("Compare the fingerprint, character by character, with the one shown on your contact's device."); + verify_no_button.label = _("Fingerprints differ"); + verify_yes_button.label = _("Fingerprints match"); + cancel_button.label = _("Cancel"); + ok_button.label = _("Confirm"); + } + + public ManageKeyDialog(Row device, Database db) { + Object(use_header_bar : 1); + + this.device = device; + this.db = db; + + setup_main_screen(); + setup_verify_screen(); + + cancel_button.clicked.connect(handle_cancel); + ok_button.clicked.connect(() => { + response(current_response); + close(); + }); + + verify_yes_button.clicked.connect(() => { + confirm_image.set_from_icon_name("security-high-symbolic"); + confirm_title_label.label = _("Verify key"); + confirm_desc_label.set_markup(_("Future messages sent by %s from the device that uses this key will be highlighted accordingly in the chat window.").printf(@"<b>$(device[db.identity_meta.address_name])</b>")); + manage_stack.set_visible_child_name("confirm"); + ok_button.sensitive = true; + return_to_main = false; + current_response = TrustLevel.VERIFIED; + }); + + verify_no_button.clicked.connect(() => { + return_to_main = false; + confirm_image.set_from_icon_name("dino-dialog-warning-symbolic"); + confirm_title_label.label = _("Fingerprints do not match"); + confirm_desc_label.set_markup(_("Please verify that you are comparing the correct fingerprint. If fingerprints do not match, %s's account may be compromised and you should consider rejecting this key.").printf(@"<b>$(device[db.identity_meta.address_name])</b>")); + manage_stack.set_visible_child_name("confirm"); + }); + } + + private void handle_cancel() { + if (manage_stack.get_visible_child_name() == "main") close(); + + if (manage_stack.get_visible_child_name() == "verify") { + manage_stack.set_visible_child_name("main"); + cancel_button.label = _("Cancel"); + } + + if (manage_stack.get_visible_child_name() == "confirm") { + if (return_to_main) { + manage_stack.set_visible_child_name("main"); + cancel_button.label = _("Cancel"); + } else { + manage_stack.set_visible_child_name("verify"); + } + } + + ok_button.sensitive = false; + } + + private Box make_action_box(string title, string desc){ + Box box = new Box(Orientation.VERTICAL, 0) { visible = true, margin_start = 20, margin_end = 20, margin_top = 14, margin_bottom = 14 }; + Label lbl_title = new Label(title) { visible = true, halign = Align.START }; + Label lbl_desc = new Label(desc) { visible = true, xalign = 0, wrap = true, max_width_chars = 40 }; + + Pango.AttrList title_attrs = new Pango.AttrList(); + title_attrs.insert(Pango.attr_scale_new(1.1)); + lbl_title.attributes = title_attrs; + Pango.AttrList desc_attrs = new Pango.AttrList(); + desc_attrs.insert(Pango.attr_scale_new(0.8)); + lbl_desc.attributes = desc_attrs; + lbl_desc.add_css_class("dim-label"); + + box.append(lbl_title); + box.append(lbl_desc); + + return box; + } + + private void setup_main_screen() { + main_action_list.set_header_func((row, before_row) => { + if (row.get_header() == null && before_row != null) { + row.set_header(new Separator(Orientation.HORIZONTAL)); + } + }); + + ListBoxRow verify_row = new ListBoxRow() { visible = true }; + verify_row.set_child(make_action_box(_("Verify key fingerprint"), _("Compare this key's fingerprint with the fingerprint displayed on the contact's device."))); + ListBoxRow reject_row = new ListBoxRow() { visible = true }; + reject_row.set_child(make_action_box(_("Reject key"), _("Block encrypted communication with the contact's device that uses this key."))); + ListBoxRow accept_row = new ListBoxRow() {visible = true }; + accept_row.set_child(make_action_box(_("Accept key"), _("Allow encrypted communication with the contact's device that uses this key."))); + + switch((TrustLevel) device[db.identity_meta.trust_level]) { + case TrustLevel.TRUSTED: + main_desc_label.set_markup(_("This key is currently %s.").printf("<span color='#1A63D9'>"+_("accepted")+"</span>")+" "+_("This means it can be used by %s to receive and send encrypted messages.").printf(@"<b>$(device[db.identity_meta.address_name])</b>")); + main_action_list.append(verify_row); + main_action_list.append(reject_row); + break; + case TrustLevel.VERIFIED: + main_desc_label.set_markup(_("This key is currently %s.").printf("<span color='#1A63D9'>"+_("verified")+"</span>")+" "+_("This means it can be used by %s to receive and send encrypted messages.").printf(@"<b>$(device[db.identity_meta.address_name])</b>") + " " + _("Additionally it has been verified to match the key on the contact's device.")); + main_action_list.append(reject_row); + break; + case TrustLevel.UNTRUSTED: + main_desc_label.set_markup(_("This key is currently %s.").printf("<span color='#D91900'>"+_("rejected")+"</span>")+" "+_("This means it cannot be used by %s to decipher your messages, and you won't see messages encrypted with it.").printf(@"<b>$(device[db.identity_meta.address_name])</b>")); + main_action_list.append(accept_row); + break; + } + + //Row clicked - go to appropriate screen + main_action_list.row_activated.connect((row) => { + if(row == verify_row) { + manage_stack.set_visible_child_name("verify"); + } else if (row == reject_row) { + confirm_image.set_from_icon_name("action-unavailable-symbolic"); + confirm_title_label.label = _("Reject key"); + confirm_desc_label.set_markup(_("You won't see encrypted messages from the device of %s that uses this key. Conversely, that device won't be able to decipher your messages anymore.").printf(@"<b>$(device[db.identity_meta.address_name])</b>")); + manage_stack.set_visible_child_name("confirm"); + ok_button.sensitive = true; + return_to_main = true; + current_response = TrustLevel.UNTRUSTED; + } else if (row == accept_row) { + confirm_image.set_from_icon_name("dino-check-plain-symbolic"); + confirm_title_label.label = _("Accept key"); + confirm_desc_label.set_markup(_("You will be able to exchange encrypted messages with the device of %s that uses this key.").printf(@"<b>$(device[db.identity_meta.address_name])</b>")); + manage_stack.set_visible_child_name("confirm"); + ok_button.sensitive = true; + return_to_main = true; + current_response = TrustLevel.TRUSTED; + } + cancel_button.label = _("Back"); + }); + + manage_stack.set_visible_child_name("main"); + } + + private void setup_verify_screen() { + verify_label.set_markup(fingerprint_markup(fingerprint_from_base64(device[db.identity_meta.identity_key_public_base64]))); + } +} + +} diff --git a/main/src/plugins/omemo/ui/own_notifications.vala b/main/src/plugins/omemo/ui/own_notifications.vala new file mode 100644 index 00000000..7ff10e30 --- /dev/null +++ b/main/src/plugins/omemo/ui/own_notifications.vala @@ -0,0 +1,35 @@ +using Dino.Entities; +using Xmpp; +using Gtk; + +namespace Dino.Plugins.Omemo { + +public class OwnNotifications { + + private StreamInteractor stream_interactor; + private Plugin plugin; + private Account account; + + public OwnNotifications (Plugin plugin, StreamInteractor stream_interactor, Account account) { + this.stream_interactor = (!)stream_interactor; + this.plugin = plugin; + this.account = account; + stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).bundle_fetched.connect_after((jid, device_id, bundle) => { + if (jid.equals(account.bare_jid) && plugin.has_new_devices(account, account.bare_jid)) { + display_notification(); + } + }); + + if (plugin.has_new_devices(account, account.bare_jid)) { + display_notification(); + } + } + + private void display_notification() { + Notification notification = new Notification(_("OMEMO trust decision required")); + notification.set_default_action_and_target_value("app.own-keys", new Variant.int32(account.id)); + notification.set_body(_("Did you add a new device for account %s?").printf(@"$(account.bare_jid.to_string())")); + plugin.app.send_notification(account.id.to_string()+"-new-device", notification); + } +} +} diff --git a/main/src/plugins/omemo/ui/util.vala b/main/src/plugins/omemo/ui/util.vala new file mode 100644 index 00000000..e250ff4d --- /dev/null +++ b/main/src/plugins/omemo/ui/util.vala @@ -0,0 +1,40 @@ +using Xmpp.Util; + +namespace Dino.Plugins.Omemo { + +public static string fingerprint_from_base64(string b64) { + uint8[] arr = Base64.decode(b64); + + arr = arr[1:arr.length]; + string s = ""; + foreach (uint8 i in arr) { + string tmp = i.to_string("%x"); + if (tmp.length == 1) tmp = "0" + tmp; + s = s + tmp; + } + + return s; +} + +public static string fingerprint_markup(string s) { + return "<span font_family='monospace' font='9'>" + format_fingerprint(s) + "</span>"; +} + +public static string format_fingerprint(string s) { + string markup = ""; + for (int i = 0; i < s.length; i += 4) { + string four_chars = s.substring(i, 4).down(); + + if (i % 32 == 0 && i != 0) markup += "\n"; + markup += four_chars; + if (i % 16 == 12 && i % 32 != 28) { + markup += " "; + } + if (i % 8 == 4 && i % 16 != 12) { + markup += "\u00a0"; // Non-breaking space + } + } + return markup; +} + +} |
