Search in sources :

Example 1 with Function

use of im.actor.runtime.function.Function in project actor-platform by actorapp.

the class EncryptedPeerActor method doDecrypt.

private Promise<DecryptBoxResponse> doDecrypt(final EncryptedBox data) {
    if (!isReady) {
        stash();
        return null;
    }
    final int senderKeyGroup = ByteStrings.bytesToInt(ByteStrings.substring(data.getEncryptedPackage(), 0, 4));
    final byte[] encPackage = ByteStrings.substring(data.getEncryptedPackage(), 4, data.getEncryptedPackage().length - 4);
    if (ignoredKeyGroups.contains(senderKeyGroup)) {
        throw new RuntimeException("This key group is ignored");
    }
    return PromisesArray.of(data.getKeys()).filter(EncryptedBoxKey.FILTER(myUid(), ownKeyGroupId)).first().flatMap(new Function<EncryptedBoxKey, Promise<Tuple2<SessionActor, EncryptedBoxKey>>>() {

        @Override
        public Promise<Tuple2<SessionActor, EncryptedBoxKey>> apply(final EncryptedBoxKey boxKey) {
            final long senderPreKeyId = ByteStrings.bytesToLong(boxKey.getEncryptedKey(), 4);
            final long receiverPreKeyId = ByteStrings.bytesToLong(boxKey.getEncryptedKey(), 12);
            if (activeSessions.containsKey(boxKey.getKeyGroupId())) {
                for (SessionActor s : activeSessions.get(senderKeyGroup).getSessions()) {
                    if (s.getSession().getOwnPreKeyId() == receiverPreKeyId && s.getSession().getTheirPreKeyId() == senderPreKeyId) {
                        return success(new Tuple2<>(s, boxKey));
                    }
                }
            }
            return context().getEncryption().getSessionManagerInt().pickSession(uid, senderKeyGroup, receiverPreKeyId, senderPreKeyId).map(new Function<PeerSession, Tuple2<SessionActor, EncryptedBoxKey>>() {

                @Override
                public Tuple2<SessionActor, EncryptedBoxKey> apply(PeerSession src) {
                    return new Tuple2<>(spawnSession(src), boxKey);
                }
            });
        }
    }).flatMap(new Function<Tuple2<SessionActor, EncryptedBoxKey>, Promise<EncryptedSessionActor.DecryptedPackage>>() {

        @Override
        public Promise<EncryptedSessionActor.DecryptedPackage> apply(Tuple2<SessionActor, EncryptedBoxKey> src) {
            Log.d(TAG, "Key size:" + src.getT2().getEncryptedKey().length);
            // TODO: Implement
            return null;
        }
    }).map(new Function<EncryptedSessionActor.DecryptedPackage, DecryptBoxResponse>() {

        @Override
        public DecryptBoxResponse apply(EncryptedSessionActor.DecryptedPackage decryptedPackage) {
            byte[] encData;
            try {
                byte[] encKeyExtended = decryptedPackage.getData().length >= 128 ? decryptedPackage.getData() : keyPrf.calculate(decryptedPackage.getData(), "ActorPackage", 128);
                encData = ActorBox.openBox(ByteStrings.intToBytes(senderKeyGroup), encPackage, new ActorBoxKey(encKeyExtended));
                Log.d(TAG, "Box size: " + encData.length);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            return new DecryptBoxResponse(encData);
        }
    });
}
Also used : IOException(java.io.IOException) Promise(im.actor.runtime.promise.Promise) Function(im.actor.runtime.function.Function) PeerSession(im.actor.core.entity.encryption.PeerSession) EncryptedBoxKey(im.actor.core.modules.encryption.entity.EncryptedBoxKey) Tuple2(im.actor.runtime.function.Tuple2) ActorBoxKey(im.actor.runtime.crypto.box.ActorBoxKey)

Example 2 with Function

use of im.actor.runtime.function.Function in project actor-platform by actorapp.

the class UserRouter method checkIsInPhoneBook.

@Verified
protected Promise<Void> checkIsInPhoneBook(User user) {
    if (!config().isEnableOnClientPrivacy()) {
        return Promise.success(null);
    }
    Log.d("ON_CLIENT_PRIVACY", "checking " + user.getName() + " is in phone book");
    return getPhoneBook().flatMap(new Function<List<PhoneBookContact>, Promise<Void>>() {

        @Override
        public Promise<Void> apply(List<PhoneBookContact> phoneBookContacts) {
            return new Promise<Void>(resolver -> {
                List<ContactRecord> userRecords = user.getRecords();
                Log.d("ON_CLIENT_PRIVACY", "phonebook have " + phoneBookContacts.size() + " records");
                Log.d("ON_CLIENT_PRIVACY", "user have " + userRecords.size() + " records");
                outer: for (ContactRecord record : userRecords) {
                    for (PhoneBookContact phoneBookContact : phoneBookContacts) {
                        for (PhoneBookPhone phone1 : phoneBookContact.getPhones()) {
                            if (record.getRecordType() == ContactRecordType.PHONE) {
                                if (record.getRecordData().equals(phone1.getNumber() + "")) {
                                    context().getContactsModule().markInPhoneBook(user.getUid());
                                    getUserVM(user.getUid()).isInPhoneBook().change(true);
                                    Log.d("ON_CLIENT_PRIVACY", "in record book!");
                                    break outer;
                                }
                            }
                        }
                        for (PhoneBookEmail email : phoneBookContact.getEmails()) {
                            if (record.getRecordType() == ContactRecordType.EMAIL) {
                                if (record.getRecordData().equals(email.getEmail())) {
                                    context().getContactsModule().markInPhoneBook(user.getUid());
                                    getUserVM(user.getUid()).isInPhoneBook().change(true);
                                    Log.d("ON_CLIENT_PRIVACY", "in record book!");
                                    break outer;
                                }
                            }
                        }
                    }
                }
                Log.d("ON_CLIENT_PRIVACY", "finish check");
                resolver.result(null);
            });
        }
    });
}
Also used : ModuleContext(im.actor.core.modules.ModuleContext) ContactRecord(im.actor.core.entity.ContactRecord) PhoneBookContact(im.actor.core.entity.PhoneBookContact) ApiUser(im.actor.core.api.ApiUser) UpdateUserContactsChanged(im.actor.core.api.updates.UpdateUserContactsChanged) ApiMapValue(im.actor.core.api.ApiMapValue) ApiBotCommand(im.actor.core.api.ApiBotCommand) PhoneBookEmail(im.actor.core.entity.PhoneBookEmail) PromisesArray(im.actor.runtime.promise.PromisesArray) RouterLoadFullUser(im.actor.core.modules.users.router.entity.RouterLoadFullUser) UpdateContactRegistered(im.actor.core.api.updates.UpdateContactRegistered) UpdateUserNameChanged(im.actor.core.api.updates.UpdateUserNameChanged) ContactRecordType(im.actor.core.entity.ContactRecordType) Tuple2(im.actor.runtime.function.Tuple2) UpdateUserBlocked(im.actor.core.api.updates.UpdateUserBlocked) Void(im.actor.runtime.actors.messages.Void) Verified(im.actor.runtime.annotations.Verified) UserPhone(im.actor.core.viewmodel.UserPhone) ResponseLoadFullUsers(im.actor.core.api.rpc.ResponseLoadFullUsers) UpdateUserAvatarChanged(im.actor.core.api.updates.UpdateUserAvatarChanged) List(java.util.List) UpdateUserAboutChanged(im.actor.core.api.updates.UpdateUserAboutChanged) ModuleActor(im.actor.core.modules.ModuleActor) ArrayListUserPhone(im.actor.core.viewmodel.generics.ArrayListUserPhone) UpdateUserFullExtChanged(im.actor.core.api.updates.UpdateUserFullExtChanged) UserEmail(im.actor.core.viewmodel.UserEmail) Peer(im.actor.core.entity.Peer) UpdateUserExtChanged(im.actor.core.api.updates.UpdateUserExtChanged) MessageState(im.actor.core.entity.MessageState) Message(im.actor.core.entity.Message) ApiUserOutPeer(im.actor.core.api.ApiUserOutPeer) ApiAvatar(im.actor.core.api.ApiAvatar) ApiContactRecord(im.actor.core.api.ApiContactRecord) UpdateUserTimeZoneChanged(im.actor.core.api.updates.UpdateUserTimeZoneChanged) Function(im.actor.runtime.function.Function) ServiceUserRegistered(im.actor.core.entity.content.ServiceUserRegistered) PhoneBookProvider(im.actor.core.providers.PhoneBookProvider) Promise(im.actor.runtime.promise.Promise) UpdateUserBotCommandsChanged(im.actor.core.api.updates.UpdateUserBotCommandsChanged) UpdateUserNickChanged(im.actor.core.api.updates.UpdateUserNickChanged) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) User(im.actor.core.entity.User) UpdateUserLocalNameChanged(im.actor.core.api.updates.UpdateUserLocalNameChanged) ArrayListUserEmail(im.actor.core.viewmodel.generics.ArrayListUserEmail) JavaUtil.equalsE(im.actor.core.util.JavaUtil.equalsE) UpdateUserUnblocked(im.actor.core.api.updates.UpdateUserUnblocked) RequestLoadFullUsers(im.actor.core.api.rpc.RequestLoadFullUsers) ContactsSyncActor(im.actor.core.modules.contacts.ContactsSyncActor) UserVM(im.actor.core.viewmodel.UserVM) RouterFetchMissingUsers(im.actor.core.modules.users.router.entity.RouterFetchMissingUsers) BookImportStorage(im.actor.core.modules.contacts.entity.BookImportStorage) RouterApplyUsers(im.actor.core.modules.users.router.entity.RouterApplyUsers) UpdateUserPreferredLanguagesChanged(im.actor.core.api.updates.UpdateUserPreferredLanguagesChanged) Log(im.actor.runtime.Log) PhoneBookPhone(im.actor.core.entity.PhoneBookPhone) Update(im.actor.core.network.parser.Update) RouterUserUpdate(im.actor.core.modules.users.router.entity.RouterUserUpdate) Promise(im.actor.runtime.promise.Promise) PhoneBookContact(im.actor.core.entity.PhoneBookContact) List(java.util.List) ArrayList(java.util.ArrayList) PhoneBookEmail(im.actor.core.entity.PhoneBookEmail) Void(im.actor.runtime.actors.messages.Void) ContactRecord(im.actor.core.entity.ContactRecord) ApiContactRecord(im.actor.core.api.ApiContactRecord) PhoneBookPhone(im.actor.core.entity.PhoneBookPhone) Verified(im.actor.runtime.annotations.Verified)

Example 3 with Function

use of im.actor.runtime.function.Function in project actor-platform by actorapp.

the class GroupRouter method onRequestLoadFullGroup.

private void onRequestLoadFullGroup(int gid) {
    if (requestedFullGroups.contains(gid)) {
        return;
    }
    requestedFullGroups.add(gid);
    freeze();
    groups().getValueAsync(gid).flatMap(new Function<Group, Promise<Group>>() {

        @Override
        public Promise<Group> apply(Group group) {
            if (!group.isHaveExtension()) {
                ArrayList<ApiGroupOutPeer> groups = new ArrayList<>();
                groups.add(new ApiGroupOutPeer(gid, group.getAccessHash()));
                return api(new RequestLoadFullGroups(groups)).map(r -> group.updateExt(r.getGroups().get(0)));
            } else {
                return Promise.failure(new RuntimeException("Already loaded"));
            }
        }
    }).then(r -> groups().addOrUpdateItem(r)).after((r, e) -> unfreeze());
}
Also used : ModuleContext(im.actor.core.modules.ModuleContext) RouterApplyGroups(im.actor.core.modules.groups.router.entity.RouterApplyGroups) Promise(im.actor.runtime.promise.Promise) UpdateGroupAvatarChanged(im.actor.core.api.updates.UpdateGroupAvatarChanged) RouterLoadFullGroup(im.actor.core.modules.groups.router.entity.RouterLoadFullGroup) UpdateGroupFullPermissionsChanged(im.actor.core.api.updates.UpdateGroupFullPermissionsChanged) RouterFetchMissingGroups(im.actor.core.modules.groups.router.entity.RouterFetchMissingGroups) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UpdateGroupMemberChanged(im.actor.core.api.updates.UpdateGroupMemberChanged) ApiMapValue(im.actor.core.api.ApiMapValue) PromisesArray(im.actor.runtime.promise.PromisesArray) UpdateGroupMemberAdminChanged(im.actor.core.api.updates.UpdateGroupMemberAdminChanged) UpdateGroupTitleChanged(im.actor.core.api.updates.UpdateGroupTitleChanged) UpdateGroupTopicChanged(im.actor.core.api.updates.UpdateGroupTopicChanged) RouterInt(im.actor.core.modules.messaging.router.RouterInt) RouterGroupUpdate(im.actor.core.modules.groups.router.entity.RouterGroupUpdate) UpdateGroupMemberDiff(im.actor.core.api.updates.UpdateGroupMemberDiff) Tuple2(im.actor.runtime.function.Tuple2) ApiGroup(im.actor.core.api.ApiGroup) UpdateGroupDeleted(im.actor.core.api.updates.UpdateGroupDeleted) Void(im.actor.runtime.actors.messages.Void) UpdateGroupOwnerChanged(im.actor.core.api.updates.UpdateGroupOwnerChanged) Verified(im.actor.runtime.annotations.Verified) ApiMember(im.actor.core.api.ApiMember) Group(im.actor.core.entity.Group) UpdateGroupAboutChanged(im.actor.core.api.updates.UpdateGroupAboutChanged) UpdateGroupFullExtChanged(im.actor.core.api.updates.UpdateGroupFullExtChanged) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) ModuleActor(im.actor.core.modules.ModuleActor) UpdateGroupPermissionsChanged(im.actor.core.api.updates.UpdateGroupPermissionsChanged) UpdateGroupMembersCountChanged(im.actor.core.api.updates.UpdateGroupMembersCountChanged) UpdateGroupMembersBecameAsync(im.actor.core.api.updates.UpdateGroupMembersBecameAsync) ApiGroupOutPeer(im.actor.core.api.ApiGroupOutPeer) ApiAvatar(im.actor.core.api.ApiAvatar) UpdateGroupHistoryShared(im.actor.core.api.updates.UpdateGroupHistoryShared) UpdateGroupShortNameChanged(im.actor.core.api.updates.UpdateGroupShortNameChanged) Function(im.actor.runtime.function.Function) RequestLoadFullGroups(im.actor.core.api.rpc.RequestLoadFullGroups) UpdateGroupExtChanged(im.actor.core.api.updates.UpdateGroupExtChanged) Update(im.actor.core.network.parser.Update) UpdateGroupMembersUpdated(im.actor.core.api.updates.UpdateGroupMembersUpdated) RouterLoadFullGroup(im.actor.core.modules.groups.router.entity.RouterLoadFullGroup) ApiGroup(im.actor.core.api.ApiGroup) Group(im.actor.core.entity.Group) Promise(im.actor.runtime.promise.Promise) RequestLoadFullGroups(im.actor.core.api.rpc.RequestLoadFullGroups) ArrayList(java.util.ArrayList) ApiGroupOutPeer(im.actor.core.api.ApiGroupOutPeer)

Example 4 with Function

use of im.actor.runtime.function.Function in project actor-platform by actorapp.

the class EncryptedPeerActor method doEncrypt.

private Promise<EncryptBoxResponse> doEncrypt(final byte[] data) {
    if (!isReady) {
        stash();
        return null;
    }
    //
    // Stage 1: Loading User Key Groups
    // Stage 2: Pick sessions for encryption
    // Stage 3: Encrypt box_key int session
    // Stage 4: Encrypt box
    //
    final byte[] encKey = Crypto.randomBytes(32);
    final byte[] encKeyExtended = keyPrf.calculate(encKey, "ActorPackage", 128);
    Log.d(TAG, "doEncrypt");
    final long start = Runtime.getActorTime();
    return PromisesArray.of(theirKeys.getUserKeysGroups()).filter(new Predicate<UserKeysGroup>() {

        @Override
        public boolean apply(UserKeysGroup keysGroup) {
            return !ignoredKeyGroups.contains(keysGroup.getKeyGroupId());
        }
    }).mapOptional(new Function<UserKeysGroup, Promise<SessionActor>>() {

        @Override
        public Promise<SessionActor> apply(final UserKeysGroup keysGroup) {
            if (activeSessions.containsKey(keysGroup.getKeyGroupId())) {
                return success(activeSessions.get(keysGroup.getKeyGroupId()).getSessions().get(0));
            }
            return context().getEncryption().getSessionManagerInt().pickSession(uid, keysGroup.getKeyGroupId()).failure(new Consumer<Exception>() {

                @Override
                public void apply(Exception e) {
                    ignoredKeyGroups.add(keysGroup.getKeyGroupId());
                }
            }).map(new Function<PeerSession, SessionActor>() {

                @Override
                public SessionActor apply(PeerSession src) {
                    return spawnSession(src);
                }
            });
        }
    }).mapOptional(encrypt(encKeyExtended)).zip().map(new Function<List<EncryptedSessionActor.EncryptedPackageRes>, EncryptBoxResponse>() {

        @Override
        public EncryptBoxResponse apply(List<EncryptedSessionActor.EncryptedPackageRes> src) {
            if (src.size() == 0) {
                throw new RuntimeException("No sessions available");
            }
            Log.d(TAG, "Keys Encrypted in " + (Runtime.getActorTime() - start) + " ms");
            ArrayList<EncryptedBoxKey> encryptedKeys = new ArrayList<>();
            for (EncryptedSessionActor.EncryptedPackageRes r : src) {
                Log.d(TAG, "Keys: " + r.getKeyGroupId());
                encryptedKeys.add(new EncryptedBoxKey(uid, r.getKeyGroupId(), "curve25519", r.getData()));
            }
            byte[] encData;
            try {
                encData = ActorBox.closeBox(ByteStrings.intToBytes(ownKeyGroupId), data, Crypto.randomBytes(32), new ActorBoxKey(encKeyExtended));
            } catch (IntegrityException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            Log.d(TAG, "All Encrypted in " + (Runtime.getActorTime() - start) + " ms");
            return new EncryptBoxResponse(new EncryptedBox(encryptedKeys.toArray(new EncryptedBoxKey[encryptedKeys.size()]), ByteStrings.merge(ByteStrings.intToBytes(ownKeyGroupId), encData)));
        }
    });
}
Also used : ArrayList(java.util.ArrayList) IntegrityException(im.actor.runtime.crypto.IntegrityException) UserKeysGroup(im.actor.core.modules.encryption.entity.UserKeysGroup) IOException(java.io.IOException) IntegrityException(im.actor.runtime.crypto.IntegrityException) Function(im.actor.runtime.function.Function) Consumer(im.actor.runtime.function.Consumer) PeerSession(im.actor.core.entity.encryption.PeerSession) EncryptedBoxKey(im.actor.core.modules.encryption.entity.EncryptedBoxKey) EncryptedBox(im.actor.core.modules.encryption.entity.EncryptedBox) ArrayList(java.util.ArrayList) List(java.util.List) ActorBoxKey(im.actor.runtime.crypto.box.ActorBoxKey)

Example 5 with Function

use of im.actor.runtime.function.Function in project actor-platform by actorapp.

the class KeyManagerActor method fetchUserPreKey.

/**
     * Fetching user's random pre key
     *
     * @param uid        User's id
     * @param keyGroupId User's key group id
     */
private Promise<PublicKey> fetchUserPreKey(final int uid, final int keyGroupId) {
    return pickUserGroup(uid, keyGroupId).flatMap(new Function<Tuple2<UserKeysGroup, UserKeys>, Promise<PublicKey>>() {

        @Override
        public Promise<PublicKey> apply(final Tuple2<UserKeysGroup, UserKeys> keyGroups) {
            return api(new RequestLoadPrePublicKeys(new ApiUserOutPeer(uid, getUser(uid).getAccessHash()), keyGroupId)).map(new Function<ResponsePublicKeys, PublicKey>() {

                @Override
                public PublicKey apply(ResponsePublicKeys response) {
                    if (response.getPublicKey().size() == 0) {
                        throw new RuntimeException("User doesn't have pre keys");
                    }
                    ApiEncryptionKey key = response.getPublicKey().get(0);
                    ApiEncryptionKeySignature sig = null;
                    for (ApiEncryptionKeySignature s : response.getSignatures()) {
                        if (s.getKeyId() == key.getKeyId() && "Ed25519".equals(s.getSignatureAlg())) {
                            sig = s;
                            break;
                        }
                    }
                    if (sig == null) {
                        throw new RuntimeException("Unable to find public key on server");
                    }
                    byte[] keyHash = RatchetKeySignature.hashForSignature(key.getKeyId(), key.getKeyAlg(), key.getKeyMaterial());
                    if (!Curve25519.verifySignature(keyGroups.getT1().getIdentityKey().getPublicKey(), keyHash, sig.getSignature())) {
                        throw new RuntimeException("Key signature does not isMatch");
                    }
                    return new PublicKey(key.getKeyId(), key.getKeyAlg(), key.getKeyMaterial());
                }
            });
        }
    });
}
Also used : RequestLoadPrePublicKeys(im.actor.core.api.rpc.RequestLoadPrePublicKeys) ApiUserOutPeer(im.actor.core.api.ApiUserOutPeer) RequestLoadPublicKey(im.actor.core.api.rpc.RequestLoadPublicKey) PublicKey(im.actor.core.modules.encryption.entity.PublicKey) UserKeys(im.actor.core.modules.encryption.entity.UserKeys) ResponsePublicKeys(im.actor.core.api.rpc.ResponsePublicKeys) UserKeysGroup(im.actor.core.modules.encryption.entity.UserKeysGroup) Promise(im.actor.runtime.promise.Promise) Function(im.actor.runtime.function.Function) ApiEncryptionKeySignature(im.actor.core.api.ApiEncryptionKeySignature) Tuple2(im.actor.runtime.function.Tuple2) ApiEncryptionKey(im.actor.core.api.ApiEncryptionKey)

Aggregations

Function (im.actor.runtime.function.Function)8 Tuple2 (im.actor.runtime.function.Tuple2)6 Promise (im.actor.runtime.promise.Promise)6 ApiUserOutPeer (im.actor.core.api.ApiUserOutPeer)5 ArrayList (java.util.ArrayList)5 User (im.actor.core.entity.User)4 UserKeysGroup (im.actor.core.modules.encryption.entity.UserKeysGroup)4 ApiAvatar (im.actor.core.api.ApiAvatar)3 ApiMapValue (im.actor.core.api.ApiMapValue)3 ModuleActor (im.actor.core.modules.ModuleActor)3 ModuleContext (im.actor.core.modules.ModuleContext)3 UserKeys (im.actor.core.modules.encryption.entity.UserKeys)3 List (java.util.List)3 ApiBotCommand (im.actor.core.api.ApiBotCommand)2 ApiContactRecord (im.actor.core.api.ApiContactRecord)2 ApiEncryptionKey (im.actor.core.api.ApiEncryptionKey)2 ApiEncryptionKeySignature (im.actor.core.api.ApiEncryptionKeySignature)2 ApiUser (im.actor.core.api.ApiUser)2 RequestLoadFullUsers (im.actor.core.api.rpc.RequestLoadFullUsers)2 RequestLoadPublicKey (im.actor.core.api.rpc.RequestLoadPublicKey)2