Exemple #1
0
        private void handleEndSessionMessage(/*MasterSecretUnion     masterSecret,*/
            TextSecureEnvelope envelope,
            TextSecureDataMessage message /*,
                                           * Optional<Long>        smsMessageId*/)
        {
            /*EncryptingSmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
             * IncomingTextMessage incomingTextMessage = new IncomingTextMessage(envelope.getSource(),
             *                                                                  envelope.getSourceDevice(),
             *                                                                  (long)message.getTimestamp(),
             *                                                                  "", May<TextSecureGroup>.NoValue);
             *
             * long threadId;
             *
             * if (!smsMessageId.isPresent())
             * {
             *  IncomingEndSessionMessage incomingEndSessionMessage = new IncomingEndSessionMessage(incomingTextMessage);
             *  Pair<Long, Long> messageAndThreadId = smsDatabase.insertMessageInbox(masterSecret, incomingEndSessionMessage);
             *
             *  threadId = messageAndThreadId.second;
             * }
             * else
             * {
             *  smsDatabase.markAsEndSession(smsMessageId.get());
             *  threadId = smsDatabase.getThreadIdForMessage(smsMessageId.get());
             * }
             *
             * SessionStore sessionStore = new TextSecureSessionStore();
             * sessionStore.deleteAllSessions(envelope.getSource());*/

            //SecurityEvent.broadcastSecurityUpdateEvent(context, threadId);
            //MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), threadId);
        }
Exemple #2
0
        private void OnMessageRecevied(TextSecureMessagePipe sender, TextSecureEnvelope envelope)
        {
            var task = new PushContentReceiveTask();

            task.handle(envelope, false);
            //throw new NotImplementedException("OnMessageReceived");
        }
        private byte[] decrypt(TextSecureEnvelope envelope, byte[] ciphertext)

        {
            AxolotlAddress sourceAddress = new AxolotlAddress(envelope.getSource(), envelope.getSourceDevice());
            SessionCipher  sessionCipher = new SessionCipher(axolotlStore, sourceAddress);

            byte[] paddedMessage;

            if (envelope.isPreKeyWhisperMessage())
            {
                paddedMessage = sessionCipher.decrypt(new PreKeyWhisperMessage(ciphertext));
            }
            else if (envelope.isWhisperMessage())
            {
                paddedMessage = sessionCipher.decrypt(new WhisperMessage(ciphertext));
            }
            else
            {
                throw new InvalidMessageException("Unknown type: " + envelope.getType());
            }

            PushTransportDetails transportDetails = new PushTransportDetails(sessionCipher.getSessionVersion());

            return(transportDetails.getStrippedPaddingMessageBody(paddedMessage));
        }
        /**
         * Decrypt a received {@link org.whispersystems.textsecure.api.messages.TextSecureEnvelope}
         *
         * @param envelope The received TextSecureEnvelope
         * @return a decrypted TextSecureMessage
         * @throws InvalidVersionException
         * @throws InvalidMessageException
         * @throws InvalidKeyException
         * @throws DuplicateMessageException
         * @throws InvalidKeyIdException
         * @throws UntrustedIdentityException
         * @throws LegacyMessageException
         * @throws NoSessionException
         */
        public TextSecureContent decrypt(TextSecureEnvelope envelope)
        {
            try
            {
                TextSecureContent content = new TextSecureContent();

                if (envelope.hasLegacyMessage())
                {
                    DataMessage message = DataMessage.ParseFrom(decrypt(envelope, envelope.getLegacyMessage()));
                    content = new TextSecureContent(createTextSecureMessage(envelope, message));
                }
                else if (envelope.hasContent())
                {
                    Content message = Content.ParseFrom(decrypt(envelope, envelope.getContent()));

                    if (message.HasDataMessage)
                    {
                        content = new TextSecureContent(createTextSecureMessage(envelope, message.DataMessage));
                    }
                    else if (message.HasSyncMessage && localAddress.getNumber().Equals(envelope.getSource()))
                    {
                        content = new TextSecureContent(createSynchronizeMessage(envelope, message.SyncMessage));
                    }
                }

                return(content);
            }
            catch (InvalidProtocolBufferException e)
            {
                throw new InvalidMessageException(e);
            }
        }
Exemple #5
0
        /*private void handleGroupMessage(@NonNull MasterSecretUnion masterSecret,
         *                              @NonNull TextSecureEnvelope envelope,
         *                              @NonNull TextSecureDataMessage message,
         *                              @NonNull Optional<Long> smsMessageId)
         * {
         *  GroupMessageProcessor.process(context, masterSecret, envelope, message);
         *
         *  if (smsMessageId.isPresent())
         *  {
         *      DatabaseFactory.getSmsDatabase(context).deleteMessage(smsMessageId.get());
         *  }
         * }
         *
         * private void handleSynchronizeSentMessage(@NonNull MasterSecretUnion masterSecret,
         *                                        @NonNull SentTranscriptMessage message,
         *                                        @NonNull Optional<Long> smsMessageId)
         * throws MmsException
         * {
         * if (message.getMessage().getAttachments().isPresent()) {
         *      handleSynchronizeSentMediaMessage(masterSecret, message, smsMessageId);
         *  } else {
         *      handleSynchronizeSentTextMessage(masterSecret, message, smsMessageId);
         *  }
         * }
         *
         * private void handleSynchronizeRequestMessage(@NonNull MasterSecretUnion masterSecret,
         *                                           @NonNull RequestMessage message)
         * {
         *  if (message.isContactsRequest())
         *  {
         *      ApplicationContext.getInstance(context)
         *                        .getJobManager()
         *                        .add(new MultiDeviceContactUpdateJob(getContext()));
         *  }
         *
         *  if (message.isGroupsRequest())
         *  {
         *      ApplicationContext.getInstance(context)
         *                        .getJobManager()
         *                        .add(new MultiDeviceGroupUpdateJob(getContext()));
         *  }
         * }
         *
         * private void handleMediaMessage(@NonNull MasterSecretUnion masterSecret,
         *                              @NonNull TextSecureEnvelope envelope,
         *                              @NonNull TextSecureDataMessage message,
         *                              @NonNull Optional<Long> smsMessageId)
         * throws MmsException
         * {
         *  MmsDatabase database     = DatabaseFactory.getMmsDatabase(context);
         *  String localNumber  = TextSecurePreferences.getLocalNumber(context);
         *  IncomingMediaMessage mediaMessage = new IncomingMediaMessage(masterSecret, envelope.getSource(),
         *                                                       localNumber, message.getTimestamp(),
         *                                                       Optional.fromNullable(envelope.getRelay()),
         *                                                       message.getBody(),
         *                                                       message.getGroupInfo(),
         *                                                       message.getAttachments());
         *
         *  Pair<Long, Long> messageAndThreadId =  database.insertSecureDecryptedMessageInbox(masterSecret, mediaMessage, -1);
         *
         *  ApplicationContext.getInstance(context)
         *            .getJobManager()
         *            .add(new AttachmentDownloadJob(context, messageAndThreadId.first));
         *
         * if (smsMessageId.isPresent()) {
         *      DatabaseFactory.getSmsDatabase(context).deleteMessage(smsMessageId.get());
         *  }
         *
         *  MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
         * }
         *
         * private void handleSynchronizeSentMediaMessage(@NonNull MasterSecretUnion masterSecret,
         *                                             @NonNull SentTranscriptMessage message,
         *                                             @NonNull Optional<Long> smsMessageId)
         * throws MmsException
         * {
         *  MmsDatabase database     = DatabaseFactory.getMmsDatabase(context);
         *  Recipients recipients   = getSyncMessageDestination(message);
         *  OutgoingMediaMessage mediaMessage = new OutgoingMediaMessage(context, masterSecret, recipients,
         *                                                        message.getMessage().getAttachments().get(),
         *                                                        message.getMessage().getBody().orNull());
         *
         *  mediaMessage = new OutgoingSecureMediaMessage(mediaMessage);
         *
         *  long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
         *  long messageId = database.insertMessageOutbox(masterSecret, mediaMessage, threadId, false, message.getTimestamp());
         *
         *  database.markAsSent(messageId, "push".getBytes(), 0);
         *  database.markAsPush(messageId);
         *
         *  ApplicationContext.getInstance(context)
         *                    .getJobManager()
         *                    .add(new AttachmentDownloadJob(context, messageId));
         *
         *  if (smsMessageId.isPresent())
         *  {
         *      DatabaseFactory.getSmsDatabase(context).deleteMessage(smsMessageId.get());
         *  }
         *  }
         */
        private void handleTextMessage(/*@NonNull MasterSecretUnion masterSecret,*/
            TextSecureEnvelope envelope,
            TextSecureDataMessage message /*,
                                           * @NonNull Optional<Long> smsMessageId*/)
        {
            MessageDatabase database = DatabaseFactory.getMessageDatabase();
            String          body     = message.getBody().HasValue ? message.getBody().ForceGetValue() : "";

            /*Pair<Long, Long> messageAndThreadId;
             *
             * if (smsMessageId.hasValue)
             * {
             *  messageAndThreadId = database.updateBundleMessageBody(masterSecret, smsMessageId.get(), body);
             * }
             * else
             * {*/
            IncomingTextMessage textMessage = new IncomingTextMessage(envelope.getSource(),
                                                                      envelope.getSourceDevice(),
                                                                      (long)message.getTimestamp(), body,
                                                                      message.getGroupInfo());

            textMessage = new IncomingEncryptedMessage(textMessage, body);
            /*messageAndThreadId = */ database.insertMessageInbox(/*masterSecret, */ textMessage);

            /*}
             *
             * MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);*/
        }
Exemple #6
0
        protected override async Task <string> ExecuteAsync()
        {
            PushDatabase       database = DatabaseFactory.getPushDatabase();
            TextSecureEnvelope envelope = database.GetEnvelope(messageId);

            /*Optional<Long> optionalSmsMessageId = smsMessageId > 0 ? Optional.of(smsMessageId) :
             *                                                           Optional.< Long > absent();*/

            handleMessage(/*masterSecret,*/ envelope /*, optionalSmsMessageId*/);
            database.Delete(messageId);

            return("");
        }
Exemple #7
0
        private void handleMessage(TextSecureEnvelope envelope, bool sendExplicitReceipt)
        {
            var  worker    = App.Current.Worker;
            long messageId = DatabaseFactory.getPushDatabase().Insert(envelope);

            if (sendExplicitReceipt)
            {
                /*   worker.AddTaskActivities(new DeliveryReceiptTask(envelope.getSource(),
                 *                                       envelope.getTimestamp(),
                 *                                       envelope.getRelay()));*/
            }

            worker.AddTaskActivities(new PushDecryptTask(messageId, envelope.getSource()));
        }
        private TextSecureGroup createGroupInfo(TextSecureEnvelope envelope, DataMessage content)
        {
            if (!content.HasGroup)
            {
                return(null);
            }

            TextSecureGroup.Type type;

            switch (content.Group.Type)
            {
            case GroupContext.Types.Type.DELIVER: type = TextSecureGroup.Type.DELIVER; break;

            case GroupContext.Types.Type.UPDATE: type = TextSecureGroup.Type.UPDATE; break;

            case GroupContext.Types.Type.QUIT: type = TextSecureGroup.Type.QUIT; break;

            default: type = TextSecureGroup.Type.UNKNOWN; break;
            }

            if (content.Group.Type != GroupContext.Types.Type.DELIVER)
            {
                String         name                = null;
                IList <String> members             = null;
                TextSecureAttachmentPointer avatar = null;

                if (content.Group.HasName)
                {
                    name = content.Group.Name;
                }

                if (content.Group.MembersCount > 0)
                {
                    members = content.Group.MembersList;
                }

                if (content.Group.HasAvatar)
                {
                    avatar = new TextSecureAttachmentPointer(content.Group.Avatar.Id,
                                                             content.Group.Avatar.ContentType,
                                                             content.Group.Avatar.Key.ToByteArray(),
                                                             envelope.getRelay());
                }

                return(new TextSecureGroup(type, content.Group.Id.ToByteArray(), name, members, avatar));
            }

            return(new TextSecureGroup(content.Group.Id.ToByteArray()));
        }
Exemple #9
0
        protected override async Task <string> ExecuteAsync()
        {
            try
            {
                String             sessionKey = TextSecurePreferences.getSignalingKey();
                TextSecureEnvelope envelope   = new TextSecureEnvelope(data, sessionKey);

                handle(envelope, true);
            }
            catch (/*IOException | InvalidVersion*/ Exception e) {
                Debug.WriteLine($"{this.GetType().Name}: Error: {e.Message}");
            }

            return("");
        }
        private TextSecureSyncMessage createSynchronizeMessage(TextSecureEnvelope envelope, SyncMessage content)
        {
            if (content.HasSent)
            {
                SyncMessage.Types.Sent sentContent = content.Sent;
                return(TextSecureSyncMessage.forSentTranscript(new SentTranscriptMessage(sentContent.Destination,
                                                                                         sentContent.Timestamp,
                                                                                         createTextSecureMessage(envelope, sentContent.Message))));
            }

            if (content.HasRequest)
            {
                return(TextSecureSyncMessage.forRequest(new RequestMessage(content.Request)));
            }

            return(TextSecureSyncMessage.empty());
        }
        private TextSecureDataMessage createTextSecureMessage(TextSecureEnvelope envelope, DataMessage content)
        {
            TextSecureGroup groupInfo = createGroupInfo(envelope, content);
            LinkedList <TextSecureAttachment> attachments = new LinkedList <TextSecureAttachment>();
            bool endSession = ((content.Flags & (uint)DataMessage.Types.Flags.END_SESSION) != 0);

            foreach (AttachmentPointer pointer in content.AttachmentsList)
            {
                attachments.AddLast(new TextSecureAttachmentPointer(pointer.Id,
                                                                    pointer.ContentType,
                                                                    pointer.Key.ToByteArray(),
                                                                    envelope.getRelay(),
                                                                    pointer.HasSize ? new May <uint>(pointer.Size) : May <uint> .NoValue,
                                                                    pointer.HasThumbnail ? new May <byte[]>(pointer.Thumbnail.ToByteArray()) : May <byte[]> .NoValue));
            }

            return(new TextSecureDataMessage(envelope.getTimestamp(), groupInfo, attachments,
                                             content.Body, endSession));
        }
Exemple #12
0
        public void handle(TextSecureEnvelope envelope, bool sendExplicitReceipt)
        {
            if (!isActiveNumber(envelope.getSource()))
            {
                TextSecureDirectory directory           = DatabaseFactory.getDirectoryDatabase();
                ContactTokenDetails contactTokenDetails = new ContactTokenDetails();
                contactTokenDetails.setNumber(envelope.getSource());

                directory.setNumber(contactTokenDetails, true);
            }

            if (envelope.isReceipt())
            {
                handleReceipt(envelope);
            }
            else
            {
                handleMessage(envelope, sendExplicitReceipt);
            }
        }
Exemple #13
0
        public async Task <List <TextSecureEnvelope> > retrieveMessages(MessageReceivedCallback callback)
        {
            List <TextSecureEnvelope>       results  = new List <TextSecureEnvelope>();
            List <TextSecureEnvelopeEntity> entities = await socket.getMessages();

            foreach (TextSecureEnvelopeEntity entity in entities)
            {
                TextSecureEnvelope envelope = new TextSecureEnvelope(entity.getType(), entity.getSource(),
                                                                     entity.getSourceDevice(), entity.getRelay(),
                                                                     entity.getTimestamp(), entity.getMessage(),
                                                                     entity.getContent());

                callback.onMessage(envelope);
                results.Add(envelope);

                socket.acknowledgeMessage(entity.getSource(), entity.getTimestamp());
            }

            return(results);
        }
Exemple #14
0
        public long Insert(TextSecureEnvelope envelope)
        {
            // TODO check if exists
            var push = new Push()
            {
                Type          = envelope.getType(),
                Source        = envelope.getSource(),
                DeviceId      = envelope.getSourceDevice(),
                LegacyMessage = envelope.hasLegacyMessage() ? Base64.encodeBytes(envelope.getLegacyMessage()) : "",
                Content       = envelope.hasContent() ? Base64.encodeBytes(envelope.getContent()) : "",
                Timestamp     = TimeUtil.GetDateTime(envelope.getTimestamp())
            };

            try
            {
                conn.Insert(push);
            } catch (Exception e) { Debug.WriteLine(e.Message); }


            return(push.PushId);
        }
Exemple #15
0
        private void OnMessageReceived(WebSocketConnection sender, WebSocketRequestMessage request)
        {
            WebSocketResponseMessage response = createWebSocketResponse(request);

            Debug.WriteLine($"Verb: {request.Verb}, Path {request.Path}, Body({request.Body.Length}): {request.Body}, Id: {request.Id}");

            try
            {
                if (isTextSecureEnvelope(request))
                {
                    TextSecureEnvelope envelope = new TextSecureEnvelope(request.Body.ToByteArray(),
                                                                         credentialsProvider.GetSignalingKey());

                    MessageReceived(this, envelope);
                }
            }
            //catch (Exception e) { } // ignore for now
            finally
            {
                websocket.sendResponse(response);
            }
        }
Exemple #16
0
        private void handleMessage(/*MasterSecretUnion masterSecret, */ TextSecureEnvelope envelope /*, Optional<Long> smsMessageId*/)
        {
            try
            {
                AxolotlStore      axolotlStore = new TextSecureAxolotlStore();
                TextSecureAddress localAddress = new TextSecureAddress(TextSecurePreferences.getLocalNumber());
                TextSecureCipher  cipher       = new TextSecureCipher(localAddress, axolotlStore);

                TextSecureContent content = cipher.decrypt(envelope);

                if (content.getDataMessage().HasValue)
                {
                    TextSecureDataMessage message = content.getDataMessage().ForceGetValue();

                    if (message.isEndSession())
                    {
                        handleEndSessionMessage(/*masterSecret, */ envelope, message /*, smsMessageId*/);
                    }
                    //else if (message.isGroupUpdate()) handleGroupMessage(masterSecret, envelope, message, smsMessageId);
                    //else if (message.getAttachments().isPresent()) handleMediaMessage(masterSecret, envelope, message, smsMessageId);
                    else
                    {
                        handleTextMessage(/*masterSecret, */ envelope, message /*, smsMessageId*/);
                    }
                }

                /*else if (content.getSyncMessage().HasValue) TODO: SYNC enable
                 * {
                 *  TextSecureSyncMessage syncMessage = content.getSyncMessage().ForceGetValue();
                 *
                 *  if (syncMessage.getSent().HasValue) handleSynchronizeSentMessage(masterSecret, syncMessage.getSent().ForceGetValue(), smsMessageId);
                 *  else if (syncMessage.getRequest().HasValue) handleSynchronizeRequestMessage(masterSecret, syncMessage.getRequest().ForceGetValue());
                 * }*/

                if (envelope.isPreKeyWhisperMessage())
                {
                    App.Current.Worker.AddTaskActivities(new RefreshPreKeysTask());
                    //ApplicationContext.getInstance(context).getJobManager().add(new RefreshPreKeysJob(context));
                }
            }
            catch (InvalidVersionException e)
            {
                //Log.w(TAG, e);
                //handleInvalidVersionMessage(masterSecret, envelope, smsMessageId);
            }

            /* catch (InvalidMessageException | InvalidKeyIdException | InvalidKeyException | MmsException e) {
             *   Log.w(TAG, e);
             *   handleCorruptMessage(masterSecret, envelope, smsMessageId);
             * } catch (NoSessionException e)
             * {
             *   Log.w(TAG, e);
             *   handleNoSessionMessage(masterSecret, envelope, smsMessageId);
             * }
             * catch (LegacyMessageException e)
             * {
             *   Log.w(TAG, e);
             *   handleLegacyMessage(masterSecret, envelope, smsMessageId);
             * }
             * catch (DuplicateMessageException e)
             * {
             *   Log.w(TAG, e);
             *   handleDuplicateMessage(masterSecret, envelope, smsMessageId);
             * }
             * catch (UntrustedIdentityException e)
             * {
             *   Log.w(TAG, e);
             *   handleUntrustedIdentityMessage(masterSecret, envelope, smsMessageId);
             * }*/
        }
Exemple #17
0
 public void onMessage(TextSecureEnvelope envelope)
 {
 }
Exemple #18
0
 private void handleReceipt(TextSecureEnvelope envelope)
 {
     Debug.WriteLine($"Received receipt: (XXXXX, {envelope.getTimestamp()})");
     DatabaseFactory.getMessageDatabase().incrementDeliveryReceiptCount(envelope.getSource(),
                                                                        (long)envelope.getTimestamp());
 }