Search in sources :

Example 16 with PreKeyBundle

use of org.whispersystems.libsignal.state.PreKeyBundle in project Pix-Art-Messenger by kriztan.

the class IqParser method bundle.

public PreKeyBundle bundle(final IqPacket bundle) {
    Element bundleItem = getItem(bundle);
    if (bundleItem == null) {
        return null;
    }
    final Element bundleElement = bundleItem.findChild("bundle");
    if (bundleElement == null) {
        return null;
    }
    ECPublicKey signedPreKeyPublic = signedPreKeyPublic(bundleElement);
    Integer signedPreKeyId = signedPreKeyId(bundleElement);
    byte[] signedPreKeySignature = signedPreKeySignature(bundleElement);
    IdentityKey identityKey = identityKey(bundleElement);
    if (signedPreKeyId == null || signedPreKeyPublic == null || identityKey == null) {
        return null;
    }
    return new PreKeyBundle(0, 0, 0, null, signedPreKeyId, signedPreKeyPublic, signedPreKeySignature, identityKey);
}
Also used : PreKeyBundle(org.whispersystems.libsignal.state.PreKeyBundle) IdentityKey(org.whispersystems.libsignal.IdentityKey) ECPublicKey(org.whispersystems.libsignal.ecc.ECPublicKey) Element(de.pixart.messenger.xml.Element)

Example 17 with PreKeyBundle

use of org.whispersystems.libsignal.state.PreKeyBundle in project Pix-Art-Messenger by kriztan.

the class AxolotlService method buildSessionFromPEP.

private void buildSessionFromPEP(final SignalProtocolAddress address) {
    Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new session for " + address.toString());
    if (address.equals(getOwnAxolotlAddress())) {
        throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
    }
    try {
        IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(Jid.fromString(address.getName()), address.getDeviceId());
        Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
        mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {

            @Override
            public void onIqPacketReceived(Account account, IqPacket packet) {
                if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
                    fetchStatusMap.put(address, FetchStatus.TIMEOUT);
                } else if (packet.getType() == IqPacket.TYPE.RESULT) {
                    Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
                    final IqParser parser = mXmppConnectionService.getIqParser();
                    final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
                    final PreKeyBundle bundle = parser.bundle(packet);
                    if (preKeyBundleList.isEmpty() || bundle == null) {
                        Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
                        fetchStatusMap.put(address, FetchStatus.ERROR);
                        finishBuildingSessionsFromPEP(address);
                        return;
                    }
                    Random random = new Random();
                    final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
                    if (preKey == null) {
                        // should never happen
                        fetchStatusMap.put(address, FetchStatus.ERROR);
                        finishBuildingSessionsFromPEP(address);
                        return;
                    }
                    final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(), preKey.getPreKeyId(), preKey.getPreKey(), bundle.getSignedPreKeyId(), bundle.getSignedPreKey(), bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
                    try {
                        SessionBuilder builder = new SessionBuilder(axolotlStore, address);
                        builder.process(preKeyBundle);
                        XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
                        sessions.put(address, session);
                        if (Config.X509_VERIFICATION) {
                            verifySessionWithPEP(session);
                        } else {
                            FingerprintStatus status = getFingerprintTrust(CryptoHelper.bytesToHex(bundle.getIdentityKey().getPublicKey().serialize()));
                            FetchStatus fetchStatus;
                            if (status != null && status.isVerified()) {
                                fetchStatus = FetchStatus.SUCCESS_VERIFIED;
                            } else if (status != null && status.isTrusted()) {
                                fetchStatus = FetchStatus.SUCCESS_TRUSTED;
                            } else {
                                fetchStatus = FetchStatus.SUCCESS;
                            }
                            fetchStatusMap.put(address, fetchStatus);
                            finishBuildingSessionsFromPEP(address);
                        }
                    } catch (UntrustedIdentityException | InvalidKeyException e) {
                        Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": " + e.getClass().getName() + ", " + e.getMessage());
                        fetchStatusMap.put(address, FetchStatus.ERROR);
                        finishBuildingSessionsFromPEP(address);
                    }
                } else {
                    fetchStatusMap.put(address, FetchStatus.ERROR);
                    Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
                    finishBuildingSessionsFromPEP(address);
                }
            }
        });
    } catch (InvalidJidException e) {
        Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
    }
}
Also used : Account(de.pixart.messenger.entities.Account) IqParser(de.pixart.messenger.parser.IqParser) UntrustedIdentityException(org.whispersystems.libsignal.UntrustedIdentityException) OnIqPacketReceived(de.pixart.messenger.xmpp.OnIqPacketReceived) InvalidJidException(de.pixart.messenger.xmpp.jid.InvalidJidException) SessionBuilder(org.whispersystems.libsignal.SessionBuilder) InvalidKeyException(org.whispersystems.libsignal.InvalidKeyException) IqPacket(de.pixart.messenger.xmpp.stanzas.IqPacket) PreKeyBundle(org.whispersystems.libsignal.state.PreKeyBundle) Random(java.util.Random)

Example 18 with PreKeyBundle

use of org.whispersystems.libsignal.state.PreKeyBundle in project Pix-Art-Messenger by kriztan.

the class AxolotlService method publishBundlesIfNeeded.

public void publishBundlesIfNeeded(final boolean announce, final boolean wipe) {
    if (pepBroken) {
        Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
        return;
    }
    if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
        this.changeAccessMode.set(account.isOptionSet(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE));
    } else {
        if (account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true)) {
            Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server doesn’t support publish-options. setting for later access mode change");
            mXmppConnectionService.databaseBackend.updateAccount(account);
        }
    }
    if (this.changeAccessMode.get()) {
        Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server gained publish-options capabilities. changing access model");
    }
    IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
    mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {

        @Override
        public void onIqPacketReceived(Account account, IqPacket packet) {
            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
                // ignore timeout. do nothing
                return;
            }
            if (packet.getType() == IqPacket.TYPE.ERROR) {
                Element error = packet.findChild("error");
                if (error == null || !error.hasChild("item-not-found")) {
                    pepBroken = true;
                    Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
                    return;
                }
            }
            PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
            Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
            boolean flush = false;
            if (bundle == null) {
                Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
                bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
                flush = true;
            }
            if (keys == null) {
                Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
            }
            try {
                boolean changed = false;
                // Validate IdentityKey
                IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
                if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
                    Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
                    changed = true;
                }
                // Validate signedPreKeyRecord + ID
                SignedPreKeyRecord signedPreKeyRecord;
                int numSignedPreKeys = axolotlStore.getSignedPreKeysCount();
                try {
                    signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
                    if (flush || !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey()) || !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
                        Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
                        signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
                        axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
                        changed = true;
                    }
                } catch (InvalidKeyIdException e) {
                    Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
                    signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
                    axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
                    changed = true;
                }
                // Validate PreKeys
                Set<PreKeyRecord> preKeyRecords = new HashSet<>();
                if (keys != null) {
                    for (Integer id : keys.keySet()) {
                        try {
                            PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
                            if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
                                preKeyRecords.add(preKeyRecord);
                            }
                        } catch (InvalidKeyIdException ignored) {
                        }
                    }
                }
                int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
                if (newKeys > 0) {
                    List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(axolotlStore.getCurrentPreKeyId() + 1, newKeys);
                    preKeyRecords.addAll(newRecords);
                    for (PreKeyRecord record : newRecords) {
                        axolotlStore.storePreKey(record.getId(), record);
                    }
                    changed = true;
                    Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
                }
                if (changed || changeAccessMode.get()) {
                    if (account.getPrivateKeyAlias() != null && Config.X509_VERIFICATION) {
                        mXmppConnectionService.publishDisplayName(account);
                        publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
                    } else {
                        publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
                    }
                } else {
                    Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
                    if (wipe) {
                        wipeOtherPepDevices();
                    } else if (announce) {
                        Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
                        publishOwnDeviceIdIfNeeded();
                    }
                }
            } catch (InvalidKeyException e) {
                Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
            }
        }
    });
}
Also used : Account(de.pixart.messenger.entities.Account) Set(java.util.Set) HashSet(java.util.HashSet) OnIqPacketReceived(de.pixart.messenger.xmpp.OnIqPacketReceived) Element(de.pixart.messenger.xml.Element) InvalidKeyException(org.whispersystems.libsignal.InvalidKeyException) IqPacket(de.pixart.messenger.xmpp.stanzas.IqPacket) PreKeyBundle(org.whispersystems.libsignal.state.PreKeyBundle) SignedPreKeyRecord(org.whispersystems.libsignal.state.SignedPreKeyRecord) PreKeyRecord(org.whispersystems.libsignal.state.PreKeyRecord) InvalidKeyIdException(org.whispersystems.libsignal.InvalidKeyIdException) List(java.util.List) ArrayList(java.util.ArrayList) IdentityKeyPair(org.whispersystems.libsignal.IdentityKeyPair) Map(java.util.Map) HashMap(java.util.HashMap) SignedPreKeyRecord(org.whispersystems.libsignal.state.SignedPreKeyRecord)

Example 19 with PreKeyBundle

use of org.whispersystems.libsignal.state.PreKeyBundle in project Signal-Android by signalapp.

the class SignalServiceMessageSender method handleMismatchedDevices.

private void handleMismatchedDevices(PushServiceSocket socket, SignalServiceAddress recipient, MismatchedDevices mismatchedDevices) throws IOException, UntrustedIdentityException {
    try {
        Log.w(TAG, "[handleMismatchedDevices] Address: " + recipient.getIdentifier() + ", ExtraDevices: " + mismatchedDevices.getExtraDevices() + ", MissingDevices: " + mismatchedDevices.getMissingDevices());
        archiveSessions(recipient, mismatchedDevices.getExtraDevices());
        for (int missingDeviceId : mismatchedDevices.getMissingDevices()) {
            PreKeyBundle preKey = socket.getPreKey(recipient, missingDeviceId);
            try {
                SignalSessionBuilder sessionBuilder = new SignalSessionBuilder(sessionLock, new SessionBuilder(store, new SignalProtocolAddress(recipient.getIdentifier(), missingDeviceId)));
                sessionBuilder.process(preKey);
            } catch (org.whispersystems.libsignal.UntrustedIdentityException e) {
                throw new UntrustedIdentityException("Untrusted identity key!", recipient.getIdentifier(), preKey.getIdentityKey());
            }
        }
    } catch (InvalidKeyException e) {
        throw new IOException(e);
    }
}
Also used : PreKeyBundle(org.whispersystems.libsignal.state.PreKeyBundle) SignalSessionBuilder(org.whispersystems.signalservice.api.crypto.SignalSessionBuilder) UntrustedIdentityException(org.whispersystems.signalservice.api.crypto.UntrustedIdentityException) SignalGroupSessionBuilder(org.whispersystems.signalservice.api.crypto.SignalGroupSessionBuilder) GroupSessionBuilder(org.whispersystems.libsignal.groups.GroupSessionBuilder) SessionBuilder(org.whispersystems.libsignal.SessionBuilder) SignalSessionBuilder(org.whispersystems.signalservice.api.crypto.SignalSessionBuilder) IOException(java.io.IOException) InvalidKeyException(org.whispersystems.libsignal.InvalidKeyException) ContentHint(org.whispersystems.signalservice.api.crypto.ContentHint) SignalProtocolAddress(org.whispersystems.libsignal.SignalProtocolAddress)

Example 20 with PreKeyBundle

use of org.whispersystems.libsignal.state.PreKeyBundle in project Signal-Android by signalapp.

the class SignalServiceMessageSender method getEncryptedMessage.

private OutgoingPushMessage getEncryptedMessage(PushServiceSocket socket, SignalServiceAddress recipient, Optional<UnidentifiedAccess> unidentifiedAccess, int deviceId, EnvelopeContent plaintext) throws IOException, InvalidKeyException, UntrustedIdentityException {
    SignalProtocolAddress signalProtocolAddress = new SignalProtocolAddress(recipient.getIdentifier(), deviceId);
    SignalServiceCipher cipher = new SignalServiceCipher(localAddress, localDeviceId, store, sessionLock, null);
    if (!store.containsSession(signalProtocolAddress)) {
        try {
            List<PreKeyBundle> preKeys = socket.getPreKeys(recipient, unidentifiedAccess, deviceId);
            for (PreKeyBundle preKey : preKeys) {
                try {
                    SignalProtocolAddress preKeyAddress = new SignalProtocolAddress(recipient.getIdentifier(), preKey.getDeviceId());
                    SignalSessionBuilder sessionBuilder = new SignalSessionBuilder(sessionLock, new SessionBuilder(store, preKeyAddress));
                    sessionBuilder.process(preKey);
                } catch (org.whispersystems.libsignal.UntrustedIdentityException e) {
                    throw new UntrustedIdentityException("Untrusted identity key!", recipient.getIdentifier(), preKey.getIdentityKey());
                }
            }
            if (eventListener.isPresent()) {
                eventListener.get().onSecurityEvent(recipient);
            }
        } catch (InvalidKeyException e) {
            throw new IOException(e);
        }
    }
    try {
        return cipher.encrypt(signalProtocolAddress, unidentifiedAccess, plaintext);
    } catch (org.whispersystems.libsignal.UntrustedIdentityException e) {
        throw new UntrustedIdentityException("Untrusted on send", recipient.getIdentifier(), e.getUntrustedIdentity());
    }
}
Also used : PreKeyBundle(org.whispersystems.libsignal.state.PreKeyBundle) SignalSessionBuilder(org.whispersystems.signalservice.api.crypto.SignalSessionBuilder) UntrustedIdentityException(org.whispersystems.signalservice.api.crypto.UntrustedIdentityException) SignalServiceCipher(org.whispersystems.signalservice.api.crypto.SignalServiceCipher) SignalGroupSessionBuilder(org.whispersystems.signalservice.api.crypto.SignalGroupSessionBuilder) GroupSessionBuilder(org.whispersystems.libsignal.groups.GroupSessionBuilder) SessionBuilder(org.whispersystems.libsignal.SessionBuilder) SignalSessionBuilder(org.whispersystems.signalservice.api.crypto.SignalSessionBuilder) IOException(java.io.IOException) InvalidKeyException(org.whispersystems.libsignal.InvalidKeyException) SignalProtocolAddress(org.whispersystems.libsignal.SignalProtocolAddress)

Aggregations

PreKeyBundle (org.whispersystems.libsignal.state.PreKeyBundle)22 ECPublicKey (org.whispersystems.libsignal.ecc.ECPublicKey)11 IOException (java.io.IOException)10 InvalidKeyException (org.whispersystems.libsignal.InvalidKeyException)10 SessionBuilder (org.whispersystems.libsignal.SessionBuilder)9 SignalProtocolAddress (org.whispersystems.libsignal.SignalProtocolAddress)7 UntrustedIdentityException (org.whispersystems.signalservice.api.crypto.UntrustedIdentityException)7 NotFoundException (org.whispersystems.signalservice.api.push.exceptions.NotFoundException)7 UnregisteredUserException (org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException)7 ArrayList (java.util.ArrayList)5 LinkedList (java.util.LinkedList)4 GroupSessionBuilder (org.whispersystems.libsignal.groups.GroupSessionBuilder)4 SignalGroupSessionBuilder (org.whispersystems.signalservice.api.crypto.SignalGroupSessionBuilder)4 SignalServiceCipher (org.whispersystems.signalservice.api.crypto.SignalServiceCipher)4 SignalSessionBuilder (org.whispersystems.signalservice.api.crypto.SignalSessionBuilder)4 GroupsV2AuthorizationString (org.whispersystems.signalservice.api.groupsv2.GroupsV2AuthorizationString)4 GroupNotFoundException (org.whispersystems.signalservice.internal.push.exceptions.GroupNotFoundException)4 Element (eu.siacs.conversations.xml.Element)3 List (java.util.List)3 ImmutableList (com.google.common.collect.ImmutableList)2