Ejemplo n.º 1
0
        // insert a row in the table SessionRecord
        public string InsertNewSession(SessionRecord session, string sqlStatement)
        {
            // create the sql connection
            using (SqlConnection sqlConnection = new SqlConnection(connectionStr))
            {
                // create and initialise a sql command
                using (SqlCommand sqlCommand = new SqlCommand(sqlStatement, sqlConnection))
                {
                    // set the parameters of the sql statement
                    sqlCommand.Parameters.AddWithValue("@staff_id", session.StaffId);
                    sqlCommand.Parameters.AddWithValue("@session_start_time", session.StartTime);
                    sqlCommand.Parameters.AddWithValue("@session_end_time", session.EndTime);

                    // open the connection and execute the command containing the sql statement
                    try
                    {
                        sqlConnection.Open();
                        int noOfRows = sqlCommand.ExecuteNonQuery();

                        //return the no of rows inserted(is 1 if executed correctly)
                        return(noOfRows + "");
                    }
                    catch (SqlException ex)
                    {
                        Console.WriteLine(ex.Message);
                        return(ex.Message);
                    }
                }
            }
        }
        /**
         * Initiate a new session by sending an initial KeyExchangeMessage to the recipient.
         *
         * @return the KeyExchangeMessage to deliver.
         */
        public KeyExchangeMessage process()
        {
            lock (SessionCipher.SESSION_LOCK)
            {
                try
                {
                    uint            sequence         = KeyHelper.getRandomSequence(65534) + 1;
                    uint            flags            = KeyExchangeMessage.INITIATE_FLAG;
                    ECKeyPair       baseKey          = Curve.generateKeyPair();
                    ECKeyPair       ratchetKey       = Curve.generateKeyPair();
                    IdentityKeyPair identityKey      = identityKeyStore.GetIdentityKeyPair();
                    byte[]          baseKeySignature = Curve.calculateSignature(identityKey.getPrivateKey(), baseKey.getPublicKey().serialize());
                    SessionRecord   sessionRecord    = sessionStore.LoadSession(remoteAddress);

                    sessionRecord.getSessionState().setPendingKeyExchange(sequence, baseKey, ratchetKey, identityKey);
                    sessionStore.StoreSession(remoteAddress, sessionRecord);

                    return(new KeyExchangeMessage(CiphertextMessage.CURRENT_VERSION, sequence, flags, baseKey.getPublicKey(), baseKeySignature,
                                                  ratchetKey.getPublicKey(), identityKey.getPublicKey()));
                }
                catch (InvalidKeyException e)
                {
                    throw new Exception(e.Message);
                }
            }
        }
Ejemplo n.º 3
0
        /**
         * Encrypt a message.
         *
         * @param  paddedMessage The plaintext message bytes, optionally padded to a constant multiple.
         * @return A ciphertext message encrypted to the recipient+device tuple.
         */
        public CiphertextMessage Encrypt(byte[] paddedMessage)
        {
            lock (SessionLock)
            {
                SessionRecord sessionRecord   = _sessionStore.LoadSession(_remoteAddress);
                SessionState  sessionState    = sessionRecord.GetSessionState();
                ChainKey      chainKey        = sessionState.GetSenderChainKey();
                MessageKeys   messageKeys     = chainKey.GetMessageKeys();
                IEcPublicKey  senderEphemeral = sessionState.GetSenderRatchetKey();
                uint          previousCounter = sessionState.GetPreviousCounter();
                uint          sessionVersion  = sessionState.GetSessionVersion();

                byte[]            ciphertextBody    = GetCiphertext(sessionVersion, messageKeys, paddedMessage);
                CiphertextMessage ciphertextMessage = new SignalMessage(sessionVersion, messageKeys.GetMacKey(),
                                                                        senderEphemeral, chainKey.GetIndex(),
                                                                        previousCounter, ciphertextBody,
                                                                        sessionState.GetLocalIdentityKey(),
                                                                        sessionState.GetRemoteIdentityKey());

                if (sessionState.HasUnacknowledgedPreKeyMessage())
                {
                    SessionState.UnacknowledgedPreKeyMessageItems items = sessionState.GetUnacknowledgedPreKeyMessageItems();
                    uint localRegistrationId = sessionState.GetLocalRegistrationId();

                    ciphertextMessage = new PreKeySignalMessage(sessionVersion, localRegistrationId, items.GetPreKeyId(),
                                                                items.GetSignedPreKeyId(), items.GetBaseKey(),
                                                                sessionState.GetLocalIdentityKey(),
                                                                (SignalMessage)ciphertextMessage);
                }

                sessionState.SetSenderChainKey(chainKey.GetNextChainKey());
                _sessionStore.StoreSession(_remoteAddress, sessionRecord);
                return(ciphertextMessage);
            }
        }
Ejemplo n.º 4
0
 public void StoreSession(AxolotlAddress address, SessionRecord record)
 {
     if (this.OnstoreSession != null)
     {
         this.OnstoreSession(address.getName(), address.getDeviceId(), record.serialize());
     }
 }
Ejemplo n.º 5
0
        /**
         * Build a new session from a received {@link org.whispersystems.libaxolotl.protocol.PreKeyWhisperMessage}.
         *
         * After a session is constructed in this way, the embedded {@link org.whispersystems.libaxolotl.protocol.WhisperMessage}
         * can be decrypted.
         *
         * @param message The received {@link org.whispersystems.libaxolotl.protocol.PreKeyWhisperMessage}.
         * @throws org.whispersystems.libaxolotl.InvalidKeyIdException when there is no local
         *                                                             {@link org.whispersystems.libaxolotl.state.PreKeyRecord}
         *                                                             that corresponds to the PreKey ID in
         *                                                             the message.
         * @throws org.whispersystems.libaxolotl.InvalidKeyException when the message is formatted incorrectly.
         * @throws org.whispersystems.libaxolotl.UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
         */
        /*package*/

        internal May <uint> Process(SessionRecord sessionRecord, PreKeyWhisperMessage message)
        {
            uint        messageVersion   = message.GetMessageVersion();
            IdentityKey theirIdentityKey = message.GetIdentityKey();

            May <uint> unsignedPreKeyId;

            if (!identityKeyStore.IsTrustedIdentity(remoteAddress.GetName(), theirIdentityKey))
            {
                throw new UntrustedIdentityException(remoteAddress.GetName(), theirIdentityKey);
            }

            switch (messageVersion)
            {
            case 2:
                unsignedPreKeyId = ProcessV2(sessionRecord, message);
                break;

            case 3:
                unsignedPreKeyId = ProcessV3(sessionRecord, message);
                break;

            default:
                throw new Exception("Unknown version: " + messageVersion);
            }

            identityKeyStore.SaveIdentity(remoteAddress.GetName(), theirIdentityKey);
            return(unsignedPreKeyId);
        }
Ejemplo n.º 6
0
        /**
         * Encrypt a message.
         *
         * @param  paddedMessage The plaintext message bytes, optionally padded to a constant multiple.
         * @return A ciphertext message encrypted to the recipient+device tuple.
         */
        public CiphertextMessage encrypt(byte[] paddedMessage)
        {
            lock (SESSION_LOCK)
            {
                SessionRecord sessionRecord   = sessionStore.loadSession(remoteAddress);
                SessionState  sessionState    = sessionRecord.getSessionState();
                ChainKey      chainKey        = sessionState.getSenderChainKey();
                MessageKeys   messageKeys     = chainKey.getMessageKeys();
                ECPublicKey   senderEphemeral = sessionState.getSenderRatchetKey();
                uint          previousCounter = sessionState.getPreviousCounter();
                uint          sessionVersion  = sessionState.getSessionVersion();

                byte[]            ciphertextBody    = getCiphertext(sessionVersion, messageKeys, paddedMessage);
                CiphertextMessage ciphertextMessage = new WhisperMessage(sessionVersion, messageKeys.getMacKey(),
                                                                         senderEphemeral, chainKey.getIndex(),
                                                                         previousCounter, ciphertextBody,
                                                                         sessionState.getLocalIdentityKey(),
                                                                         sessionState.getRemoteIdentityKey());

                if (sessionState.hasUnacknowledgedPreKeyMessage())
                {
                    SessionState.UnacknowledgedPreKeyMessageItems items = sessionState.getUnacknowledgedPreKeyMessageItems();
                    uint localRegistrationId = sessionState.getLocalRegistrationId();

                    ciphertextMessage = new PreKeyWhisperMessage(sessionVersion, localRegistrationId, items.getPreKeyId(),
                                                                 items.getSignedPreKeyId(), items.getBaseKey(),
                                                                 sessionState.getLocalIdentityKey(),
                                                                 (WhisperMessage)ciphertextMessage);
                }

                sessionState.setSenderChainKey(chainKey.getNextChainKey());
                sessionStore.storeSession(remoteAddress, sessionRecord);
                return(ciphertextMessage);
            }
        }
Ejemplo n.º 7
0
        public static SessionRecord LoadSession(SignalProtocolAddress address)
        {
            string        index = GetSessionCacheIndex(address.Name, address.DeviceId);
            SessionRecord record;

            lock (DBLock)
            {
                if (SessionsCache.TryGetValue(index, out record))
                {
                    return(record);
                }
                using (var ctx = new LibsignalDBContext())
                {
                    var session = ctx.Sessions
                                  .Where(s => s.Username == address.Name && s.DeviceId == address.DeviceId)
                                  .AsNoTracking()
                                  .SingleOrDefault();
                    if (session != null)
                    {
                        record = new SessionRecord(Base64.decode(session.Session));
                    }
                    else
                    {
                        record = new SessionRecord();
                    }
                    SessionsCache[index] = record;
                    return(record);
                }
            }
        }
Ejemplo n.º 8
0
        public static void StoreSession(SignalProtocolAddress address, SessionRecord record)
        {
            string index = GetSessionCacheIndex(address.Name, address.DeviceId);

            lock (DBLock)
            {
                using (var ctx = new LibsignalDBContext())
                {
                    var session = ctx.Sessions
                                  .Where(s => s.DeviceId == address.DeviceId && s.Username == address.Name)
                                  .SingleOrDefault();
                    if (session != null)
                    {
                        session.Session = Base64.encodeBytes(record.serialize());
                    }
                    else
                    {
                        ctx.Sessions.Add(new SignalSession()
                        {
                            DeviceId = address.DeviceId,
                            Session  = Base64.encodeBytes(record.serialize()),
                            Username = address.Name
                        });
                    }
                    SessionsCache[index] = record;
                    ctx.SaveChanges();
                }
            }
        }
Ejemplo n.º 9
0
 public void StoreSession(AxolotlAddress address, SessionRecord record)
 {
     if (this.OnStoreSession != null)
     {
         this.OnStoreSession(address, record);
     }
 }
Ejemplo n.º 10
0
 public uint GetRemoteRegistrationId()
 {
     lock (SessionLock)
     {
         SessionRecord record = _sessionStore.LoadSession(_remoteAddress);
         return(record.GetSessionState().GetRemoteRegistrationId());
     }
 }
Ejemplo n.º 11
0
        public void testBasicSessionV2()
        {
            SessionRecord aliceSessionRecord = new SessionRecord();
            SessionRecord bobSessionRecord   = new SessionRecord();

            initializeSessionsV2(aliceSessionRecord.getSessionState(), bobSessionRecord.getSessionState());
            runInteraction(aliceSessionRecord, bobSessionRecord);
        }
Ejemplo n.º 12
0
 public void storeSession(AxolotlAddress address, SessionRecord record)
 {
     if (sessions.ContainsKey(address)) //mimic HashMap update behaviour
     {
         sessions.Remove(address);
     }
     sessions.Add(address, record.serialize()); // put
 }
Ejemplo n.º 13
0
 public uint getRemoteRegistrationId()
 {
     lock (SESSION_LOCK)
     {
         SessionRecord record = sessionStore.loadSession(remoteAddress);
         return(record.getSessionState().getRemoteRegistrationId());
     }
 }
        public void TestBasicSessionV3()
        {
            SessionRecord aliceSessionRecord = new SessionRecord();
            SessionRecord bobSessionRecord   = new SessionRecord();

            InitializeSessionsV3(aliceSessionRecord.GetSessionState(), bobSessionRecord.GetSessionState());
            RunInteraction(aliceSessionRecord, bobSessionRecord);
        }
Ejemplo n.º 15
0
        /**
         * Build a new session from a {@link org.whispersystems.libaxolotl.state.PreKeyBundle} retrieved from
         * a server.
         *
         * @param preKey A PreKey for the destination recipient, retrieved from a server.
         * @throws InvalidKeyException when the {@link org.whispersystems.libaxolotl.state.PreKeyBundle} is
         *                             badly formatted.
         * @throws org.whispersystems.libaxolotl.UntrustedIdentityException when the sender's
         *                                                                  {@link IdentityKey} is not
         *                                                                  trusted.
         */
        public void process(PreKeyBundle preKey)
        {
            lock (SessionCipher.SESSION_LOCK)
            {
                if (!identityKeyStore.IsTrustedIdentity(remoteAddress.getName(), preKey.getIdentityKey()))
                {
                    throw new UntrustedIdentityException(remoteAddress.getName(), preKey.getIdentityKey());
                }

                if (preKey.getSignedPreKey() != null &&
                    !Curve.verifySignature(preKey.getIdentityKey().getPublicKey(),
                                           preKey.getSignedPreKey().serialize(),
                                           preKey.getSignedPreKeySignature()))
                {
                    throw new InvalidKeyException("Invalid signature on device key!");
                }

                if (preKey.getSignedPreKey() == null && preKey.getPreKey() == null)
                {
                    throw new InvalidKeyException("Both signed and unsigned prekeys are absent!");
                }

                bool              supportsV3        = preKey.getSignedPreKey() != null;
                SessionRecord     sessionRecord     = sessionStore.LoadSession(remoteAddress);
                ECKeyPair         ourBaseKey        = Curve.generateKeyPair();
                ECPublicKey       theirSignedPreKey = supportsV3 ? preKey.getSignedPreKey() : preKey.getPreKey();
                ECPublicKey       test = preKey.getPreKey(); // TODO: cleanup
                May <ECPublicKey> theirOneTimePreKey   = (test == null) ? May <ECPublicKey> .NoValue : new May <ECPublicKey>(test);
                May <uint>        theirOneTimePreKeyId = theirOneTimePreKey.HasValue ? new May <uint>(preKey.getPreKeyId()) :
                                                         May <uint> .NoValue;

                AliceAxolotlParameters.Builder parameters = AliceAxolotlParameters.newBuilder();

                parameters.setOurBaseKey(ourBaseKey)
                .setOurIdentityKey(identityKeyStore.GetIdentityKeyPair())
                .setTheirIdentityKey(preKey.getIdentityKey())
                .setTheirSignedPreKey(theirSignedPreKey)
                .setTheirRatchetKey(theirSignedPreKey)
                .setTheirOneTimePreKey(supportsV3 ? theirOneTimePreKey : May <ECPublicKey> .NoValue);

                if (!sessionRecord.isFresh())
                {
                    sessionRecord.archiveCurrentState();
                }

                RatchetingSession.initializeSession(sessionRecord.getSessionState(),
                                                    supportsV3 ? (uint)3 : 2,
                                                    parameters.create());

                sessionRecord.getSessionState().setUnacknowledgedPreKeyMessage(theirOneTimePreKeyId, preKey.getSignedPreKeyId(), ourBaseKey.getPublicKey());
                sessionRecord.getSessionState().setLocalRegistrationId(identityKeyStore.GetLocalRegistrationId());
                sessionRecord.getSessionState().setRemoteRegistrationId(preKey.getRegistrationId());
                sessionRecord.getSessionState().setAliceBaseKey(ourBaseKey.getPublicKey().serialize());

                sessionStore.StoreSession(remoteAddress, sessionRecord);
                identityKeyStore.SaveIdentity(remoteAddress.getName(), preKey.getIdentityKey());
            }
        }
        /// <summary>
        /// End the session and wipe the data.
        /// </summary>
        public static void EndSession()
        {
            if (!AllowRecording)
            {
                return;
            }

            _currentSession = null;
        }
        /// <summary>
        /// Build a new session from a {@link org.whispersystems.libsignal.state.PreKeyBundle} retrieved from
        /// a server.
        /// </summary>
        /// @param preKey A PreKey for the destination recipient, retrieved from a server.
        /// @throws InvalidKeyException when the {@link org.whispersystems.libsignal.state.PreKeyBundle} is
        ///                             badly formatted.
        /// @throws org.whispersystems.libsignal.UntrustedIdentityException when the sender's
        ///                                                                  {@link IdentityKey} is not
        ///                                                                  trusted.
        ///
        public void Process(PreKeyBundle preKey)
        {
            lock (SessionCipher.SessionLock)
            {
                if (!_identityKeyStore.IsTrustedIdentity(_remoteAddress, preKey.GetIdentityKey(), Direction.Sending))
                {
                    throw new UntrustedIdentityException(_remoteAddress.Name, preKey.GetIdentityKey());
                }

                if (preKey.GetSignedPreKey() != null &&
                    !Curve.VerifySignature(preKey.GetIdentityKey().GetPublicKey(),
                                           preKey.GetSignedPreKey().Serialize(),
                                           preKey.GetSignedPreKeySignature()))
                {
                    throw new InvalidKeyException("Invalid signature on device key!");
                }

                if (preKey.GetSignedPreKey() == null)
                {
                    throw new InvalidKeyException("No signed prekey!");
                }

                SessionRecord      sessionRecord     = _sessionStore.LoadSession(_remoteAddress);
                EcKeyPair          ourBaseKey        = Curve.GenerateKeyPair();
                IEcPublicKey       theirSignedPreKey = preKey.GetSignedPreKey();
                IEcPublicKey       test = preKey.GetPreKey();
                May <IEcPublicKey> theirOneTimePreKey   = (test == null) ? May <IEcPublicKey> .NoValue : new May <IEcPublicKey>(test);
                May <uint>         theirOneTimePreKeyId = theirOneTimePreKey.HasValue ? new May <uint>(preKey.GetPreKeyId()) :
                                                          May <uint> .NoValue;

                AliceSignalProtocolParameters.Builder parameters = AliceSignalProtocolParameters.NewBuilder();

                parameters.SetOurBaseKey(ourBaseKey)
                .SetOurIdentityKey(_identityKeyStore.GetIdentityKeyPair())
                .SetTheirIdentityKey(preKey.GetIdentityKey())
                .SetTheirSignedPreKey(theirSignedPreKey)
                .SetTheirRatchetKey(theirSignedPreKey)
                .SetTheirOneTimePreKey(theirOneTimePreKey);

                if (!sessionRecord.IsFresh())
                {
                    sessionRecord.ArchiveCurrentState();
                }

                RatchetingSession.InitializeSession(sessionRecord.GetSessionState(), parameters.Create());

                sessionRecord.GetSessionState().SetUnacknowledgedPreKeyMessage(theirOneTimePreKeyId, preKey.GetSignedPreKeyId(), ourBaseKey.GetPublicKey());
                sessionRecord.GetSessionState().SetLocalRegistrationId(_identityKeyStore.GetLocalRegistrationId());
                sessionRecord.GetSessionState().SetRemoteRegistrationId(preKey.GetRegistrationId());
                sessionRecord.GetSessionState().SetAliceBaseKey(ourBaseKey.GetPublicKey().Serialize());

                _identityKeyStore.SaveIdentity(_remoteAddress, preKey.GetIdentityKey());

                _sessionStore.StoreSession(_remoteAddress, sessionRecord);
            }
        }
Ejemplo n.º 18
0
        private KeyExchangeMessage ProcessInitiate(KeyExchangeMessage message)
        {
            uint          flags         = KeyExchangeMessage.RESPONSE_FLAG;
            SessionRecord sessionRecord = sessionStore.LoadSession(remoteAddress);

            if (message.GetVersion() >= 3 &&
                !Curve.VerifySignature(message.GetIdentityKey().GetPublicKey(),
                                       message.GetBaseKey().Serialize(),
                                       message.GetBaseKeySignature()))
            {
                throw new InvalidKeyException("Bad signature!");
            }

            SymmetricAxolotlParameters.Builder builder = SymmetricAxolotlParameters.NewBuilder();

            if (!sessionRecord.GetSessionState().HasPendingKeyExchange())
            {
                builder.SetOurIdentityKey(identityKeyStore.GetIdentityKeyPair())
                .SetOurBaseKey(Curve.GenerateKeyPair())
                .SetOurRatchetKey(Curve.GenerateKeyPair());
            }
            else
            {
                builder.SetOurIdentityKey(sessionRecord.GetSessionState().GetPendingKeyExchangeIdentityKey())
                .SetOurBaseKey(sessionRecord.GetSessionState().GetPendingKeyExchangeBaseKey())
                .SetOurRatchetKey(sessionRecord.GetSessionState().GetPendingKeyExchangeRatchetKey());
                flags |= KeyExchangeMessage.SIMULTAENOUS_INITIATE_FLAG;
            }

            builder.SetTheirBaseKey(message.GetBaseKey())
            .SetTheirRatchetKey(message.GetRatchetKey())
            .SetTheirIdentityKey(message.GetIdentityKey());

            SymmetricAxolotlParameters parameters = builder.Create();

            if (!sessionRecord.IsFresh())
            {
                sessionRecord.ArchiveCurrentState();
            }

            RatchetingSession.InitializeSession(sessionRecord.GetSessionState(),
                                                Math.Min(message.GetMaxVersion(), CipherTextMessage.CURRENT_VERSION),
                                                parameters);

            sessionStore.StoreSession(remoteAddress, sessionRecord);
            identityKeyStore.SaveIdentity(remoteAddress.GetName(), message.GetIdentityKey());

            byte[] baseKeySignature = Curve.CalculateSignature(parameters.GetOurIdentityKey().GetPrivateKey(),
                                                               parameters.GetOurBaseKey().GetPublicKey().Serialize());

            return(new KeyExchangeMessage(sessionRecord.GetSessionState().GetSessionVersion(),
                                          message.GetSequence(), flags,
                                          parameters.GetOurBaseKey().GetPublicKey(),
                                          baseKeySignature, parameters.GetOurRatchetKey().GetPublicKey(),
                                          parameters.GetOurIdentityKey().GetPublicKey()));
        }
        private KeyExchangeMessage processInitiate(KeyExchangeMessage message)
        {
            uint          flags         = KeyExchangeMessage.RESPONSE_FLAG;
            SessionRecord sessionRecord = sessionStore.LoadSession(remoteAddress);

            if (!Curve.verifySignature(message.getIdentityKey().getPublicKey(),
                                       message.getBaseKey().serialize(),
                                       message.getBaseKeySignature()))
            {
                throw new InvalidKeyException("Bad signature!");
            }

            SymmetricSignalProtocolParameters.Builder builder = SymmetricSignalProtocolParameters.newBuilder();

            if (!sessionRecord.getSessionState().hasPendingKeyExchange())
            {
                builder.setOurIdentityKey(identityKeyStore.GetIdentityKeyPair())
                .setOurBaseKey(Curve.generateKeyPair())
                .setOurRatchetKey(Curve.generateKeyPair());
            }
            else
            {
                builder.setOurIdentityKey(sessionRecord.getSessionState().getPendingKeyExchangeIdentityKey())
                .setOurBaseKey(sessionRecord.getSessionState().getPendingKeyExchangeBaseKey())
                .setOurRatchetKey(sessionRecord.getSessionState().getPendingKeyExchangeRatchetKey());
                flags |= KeyExchangeMessage.SIMULTAENOUS_INITIATE_FLAG;
            }

            builder.setTheirBaseKey(message.getBaseKey())
            .setTheirRatchetKey(message.getRatchetKey())
            .setTheirIdentityKey(message.getIdentityKey());

            SymmetricSignalProtocolParameters parameters = builder.create();

            if (!sessionRecord.isFresh())
            {
                sessionRecord.archiveCurrentState();
            }

            RatchetingSession.initializeSession(sessionRecord.getSessionState(),
                                                parameters);

            sessionStore.StoreSession(remoteAddress, sessionRecord);
            identityKeyStore.SaveIdentity(remoteAddress.getName(), message.getIdentityKey());

            byte[] baseKeySignature = Curve.calculateSignature(parameters.getOurIdentityKey().getPrivateKey(),
                                                               parameters.getOurBaseKey().getPublicKey().serialize());

            return(new KeyExchangeMessage(sessionRecord.getSessionState().getSessionVersion(),
                                          message.getSequence(), flags,
                                          parameters.getOurBaseKey().getPublicKey(),
                                          baseKeySignature, parameters.getOurRatchetKey().getPublicKey(),
                                          parameters.getOurIdentityKey().getPublicKey()));
        }
Ejemplo n.º 20
0
        public SessionRecord LoadSession(SignalProtocolAddress address)
        {
            SessionRecord session = OmemoSignalKeyDBManager.INSTANCE.getSession(address, ACCOUNT.getBareJid());

            if (session is null)
            {
                Logger.Warn("No existing libsignal session found for: " + address.ToString());
                session = new SessionRecord();
            }
            return(session);
        }
Ejemplo n.º 21
0
 public void setSession(SignalProtocolAddress address, SessionRecord record, string accountId)
 {
     dB.InsertOrReplace(new SessionStoreTable()
     {
         id        = SessionStoreTable.generateId(address, accountId),
         accountId = accountId,
         deviceId  = address.getDeviceId(),
         name      = address.getName(),
         session   = record.serialize()
     });
 }
Ejemplo n.º 22
0
        public SessionRecord LoadSession(SignalProtocolAddress address)
        {
            SessionRecord session = SignalKeyDBManager.INSTANCE.getSession(address, ACCOUNT.getIdAndDomain());

            if (session == null)
            {
                Logger.Warn("No existing session information found.");
                session = new SessionRecord();
            }
            return(session);
        }
        public Window1()
        {
            InitializeComponent();

            DatabaseConnection.ConnectionStr = Properties.Settings.Default.PMSDatabaseConnectionString;
            SessionRecord  session = new SessionRecord(1, "11/17/2015 21.05.55", "11/17/2015 23.05.55");
            string         rows    = DatabaseConnection.DatabaseConnectionInstance.InsertNewSession(session, insertRow);
            PatientFactory factory = new PatientFactory();

            controller = new Controller(this, factory);
            controller.RunMonitor();
        }
Ejemplo n.º 24
0
        public void StoreSession(AxolotlAddress address, SessionRecord record)
        {
            DeleteSession(address); // TODO: sqlite-net combined private keys for insertOrReplace

            var session = new Session()
            {
                DeviceId = address.getDeviceId(), Name = address.getName(), Record = record.serialize()
            };

            conn.InsertOrReplace(session);
            return;
        }
Ejemplo n.º 25
0
        public uint GetSessionVersion()
        {
            lock (SessionLock)
            {
                if (!_sessionStore.ContainsSession(_remoteAddress))
                {
                    throw new Exception($"No session for {_remoteAddress}!");                     // IllegalState
                }

                SessionRecord record = _sessionStore.LoadSession(_remoteAddress);
                return(record.GetSessionState().GetSessionVersion());
            }
        }
Ejemplo n.º 26
0
        public uint getSessionVersion()
        {
            lock (SESSION_LOCK)
            {
                if (!sessionStore.containsSession(remoteAddress))
                {
                    throw new Exception($"No session for {remoteAddress}!"); // IllegalState
                }

                SessionRecord record = sessionStore.loadSession(remoteAddress);
                return(record.getSessionState().getSessionVersion());
            }
        }
Ejemplo n.º 27
0
        public uint GetSessionVersion()
        {
            lock (SESSION_LOCK)
            {
                if (!sessionStore.ContainsSession(remoteAddress))
                {
                    throw new Exception($"No session for {remoteAddress}!");
                }

                SessionRecord record = sessionStore.LoadSession(remoteAddress);
                return(record.GetSessionState().GetSessionVersion());
            }
        }
Ejemplo n.º 28
0
        public void StoreSession(AxolotlAddress address, SessionRecord record)
        {
            DeleteSession(address);

            SessionsRepository sessionsRepository = new SessionsRepository();
            Sessions           session            = new Sessions()
            {
                RecipientId = address.GetName(),
                DeviceId    = address.GetDeviceId(),
                Record      = record.Serialize()
            };

            sessionsRepository.Save(session);
        }
Ejemplo n.º 29
0
        public SessionRecord LoadSession(AxolotlAddress address)
        {
            SessionsRepository sessionsRepository = new SessionsRepository();
            List <Sessions>    sessions           = sessionsRepository.GetSessions(address.GetName(), address.GetDeviceId());

            if (sessions != null && sessions.Count > 0)
            {
                Sessions      session       = sessions.First();
                SessionRecord sessionRecord = new SessionRecord(session.Record);
                return(sessionRecord);
            }

            return(new SessionRecord());
        }
Ejemplo n.º 30
0
        private void ProcessResponse(KeyExchangeMessage message)
        {
            SessionRecord sessionRecord                  = sessionStore.LoadSession(remoteAddress);
            SessionState  sessionState                   = sessionRecord.GetSessionState();
            bool          hasPendingKeyExchange          = sessionState.HasPendingKeyExchange();
            bool          isSimultaneousInitiateResponse = message.IsResponseForSimultaneousInitiate();

            if (!hasPendingKeyExchange || sessionState.GetPendingKeyExchangeSequence() != message.GetSequence())
            {
                //Log.w(TAG, "No matching sequence for response. Is simultaneous initiate response: " + isSimultaneousInitiateResponse);
                if (!isSimultaneousInitiateResponse)
                {
                    throw new StaleKeyExchangeException();
                }
                else
                {
                    return;
                }
            }

            SymmetricAxolotlParameters.Builder parameters = SymmetricAxolotlParameters.NewBuilder();

            parameters.SetOurBaseKey(sessionRecord.GetSessionState().GetPendingKeyExchangeBaseKey())
            .SetOurRatchetKey(sessionRecord.GetSessionState().GetPendingKeyExchangeRatchetKey())
            .SetOurIdentityKey(sessionRecord.GetSessionState().GetPendingKeyExchangeIdentityKey())
            .SetTheirBaseKey(message.GetBaseKey())
            .SetTheirRatchetKey(message.GetRatchetKey())
            .SetTheirIdentityKey(message.GetIdentityKey());

            if (!sessionRecord.IsFresh())
            {
                sessionRecord.ArchiveCurrentState();
            }

            RatchetingSession.InitializeSession(sessionRecord.GetSessionState(),
                                                Math.Min(message.GetMaxVersion(), CipherTextMessage.CURRENT_VERSION),
                                                parameters.Create());

            if (sessionRecord.GetSessionState().GetSessionVersion() >= 3 &&
                !Curve.VerifySignature(message.GetIdentityKey().GetPublicKey(),
                                       message.GetBaseKey().Serialize(),
                                       message.GetBaseKeySignature()))
            {
                throw new InvalidKeyException("Base key signature doesn't match!");
            }

            sessionStore.StoreSession(remoteAddress, sessionRecord);
            identityKeyStore.SaveIdentity(remoteAddress.GetName(), message.GetIdentityKey());
        }
Ejemplo n.º 31
0
 public void storeSession(AxolotlAddress address, SessionRecord record)
 {
     sessionStore.storeSession(address, record);
 }