Esempio n. 1
0
        public void Dispose()
        {
            if (disposed)
            {
                return;
            }

            disposed = true;

            if (requestQueue != null)
            {
                requestQueue.Dispose();
            }

            if (handler != null)
            {
                handler.Shutdown(string.Empty);
            }

            if (diffieHellman != null)
            {
                diffieHellman.Dispose();
            }

            lock (syncObject)
            {
                waitingCommands.Clear();
                keys.Clear();
            }
        }
Esempio n. 2
0
        protected virtual void Clean()
        {
            if (handler != null)
            {
                if (handler.Connected)
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Disconnect(false);
                    OnDisconnected(null);
                }

                handler.Dispose();
                handler = null;
            }

            if (diffieHellman != null)
            {
                diffieHellman.Dispose();
                diffieHellman = null;
            }

            if (received != null)
            {
                received.Dispose();
                received = null;
            }

            key = null;
            connectionInfoSent = false;
            remoteInfo         = null;
        }
Esempio n. 3
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;

            if (_requestQueue != null)
            {
                _requestQueue.Dispose();
            }

            if (_handler != null)
            {
                _handler.Shutdown(string.Empty);
            }

            if (_diffieHellman != null)
            {
                _diffieHellman.Dispose();
            }

            lock (_syncObject)
            {
                _waitingCommands.Clear();
                _packers.Clear();
            }
        }
Esempio n. 4
0
        protected virtual void Clean()
        {
            if (_handler != null)
            {
                if (_handler.Connected)
                {
                    _handler.Shutdown(SocketShutdown.Both);
                    _handler.Disconnect(false);
                    OnDisconnected(null);
                }

                _handler.Dispose();
                _handler = null;
            }

            if (_diffieHellman != null)
            {
                _diffieHellman.Dispose();
                _diffieHellman = null;
            }

            if (_received != null)
            {
                _received.Dispose();
                _received = null;
            }

            _connectionInfoSent = false;
            _remoteInfo         = null;
        }
Esempio n. 5
0
        protected virtual void DisposeManagedResources()
        {
            if (handler != null)
            {
                if (handler.Connected)
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Disconnect(false);
                    OnDisconnected(null);
                }

                handler.Dispose();
            }

            if (diffieHellman != null)
            {
                diffieHellman.Dispose();
            }

            if (received != null)
            {
                received.Dispose();
            }

            key = null;
        }
Esempio n. 6
0
 protected override void Dispose(bool disposing)
 {
     if (_ecdh != null && disposing)
     {
         _ecdh.Dispose();
         _ecdh = null;
     }
     base.Dispose(disposing);
 }
Esempio n. 7
0
 public virtual void Dispose()
 {
     if (_dados != null)
     {
         _dados.Dispose();
         _dados = null;
     }
     _chaveIndividual = null;
 }
Esempio n. 8
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (diffieHellman != null)
         {
             diffieHellman.Dispose();
         }
     }
 }
Esempio n. 9
0
 public void Dispose()
 {
     lock (l)
     {
         if (_keyPair != null)
         {
             _keyPair.Dispose();
         }
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing">
        /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only
        /// unmanaged resources.
        /// </param>
        protected override void DisposeResources(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            _encryptor?.Dispose();

            _dh?.Dispose();
        }
Esempio n. 11
0
        public static partial ECDiffieHellman Create(ECParameters parameters)
        {
            ECDiffieHellman ecdh = new ECDiffieHellmanCng();

            try
            {
                ecdh.ImportParameters(parameters);
                return(new ECDiffieHellmanWrapper(ecdh));
            }
            catch
            {
                ecdh.Dispose();
                throw;
            }
        }
Esempio n. 12
0
        protected string Encrypt(string blob, string externalKey)
        {
            var self = new ECDiffieHellmanCng();

            self.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            self.HashAlgorithm         = CngAlgorithm.Sha256;

            publicKey = Convert.ToBase64String(self.PublicKey.ToByteArray());

            var externalKeyBytes = Convert.FromBase64String(externalKey);

            var externalKeyObject = ECDiffieHellmanCngPublicKey.FromByteArray(externalKeyBytes,
                                                                              CngKeyBlobFormat.GenericPublicBlob);

            var sharedSecret = self.DeriveKeyMaterial(externalKeyObject);

            var aes = new AesManaged();

            aes.Key = sharedSecret;
            aes.GenerateIV();

            var transform = aes.CreateEncryptor();

            using (var memoryStream = new MemoryStream())
            {
                var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);

                var data = Encoding.ASCII.GetBytes(blob);

                cryptoStream.Write(data, 0, data.Length);
                cryptoStream.Close();

                var encryptedData = memoryStream.ToArray();

                blob = Convert.ToBase64String(encryptedData);

                self.Dispose();
                aes.Dispose();

                return(AddEncryptionHeaders(blob));
            }
        }
Esempio n. 13
0
        public void Dispose()
        {
#if TSS_USE_BCRYPT
            Key.Dispose();
#else
            if (RsaProvider != null)
            {
                RsaProvider.Dispose();
            }
#if !__MonoCS__
            if (EcdsaProvider != null)
            {
                EcdsaProvider.Dispose();
            }
            if (EcDhProvider != null)
            {
                EcDhProvider.Dispose();
            }
#endif //!__MonoCS__
#endif // !TSS_USE_BCRYPT
        }
Esempio n. 14
0
        protected virtual void Clean()
        {
            if (_handler != null)
            {
                if (_handler.Connected)
                {
                    try
                    {
                        _handler.Shutdown(SocketShutdown.Both);
                        _handler.Disconnect(false);
                    }
                    catch (Exception e)
                    {
                        _logger.Write(e);
                    }
                    finally
                    {
                        OnDisconnected(null);
                    }
                }

                _handler.Dispose();
                _handler = null;
            }

            if (_diffieHellman != null)
            {
                _diffieHellman.Dispose();
                _diffieHellman = null;
            }

            if (_received != null)
            {
                _received.Dispose();
                _received = null;
            }

            _connectionInfoSent = false;
            _remoteInfo         = null;
        }
        /// <summary>
        /// This analysis will examine the client IP's previous failed attempts to login to this account
        /// to determine if any failed attempts were due to typos.
        /// </summary>
        /// <param name="clientsIpHistory">Records of this client's previous attempts to examine.</param>
        /// <param name="accountController"></param>
        /// <param name="account">The account that the client is currently trying to login to.</param>
        /// <param name="whenUtc"></param>
        /// <param name="correctPassword">The correct password for this account.  (We can only know it because
        /// the client must have provided the correct one this loginAttempt.)</param>
        /// <param name="phase1HashOfCorrectPassword">The phase1 hash of that correct password (which we could
        /// recalculate from the information in the previous parameters, but doing so would be expensive.)</param>
        /// <returns></returns>
        protected void AdjustBlockingScoreForPastTyposTreatedAsFullFailures(
            IpHistory clientsIpHistory,
            IUserAccountController <TUserAccount> accountController,
            TUserAccount account,
            DateTime whenUtc,
            string correctPassword,
            byte[] phase1HashOfCorrectPassword)
        {
            double credit = 0d;

            if (clientsIpHistory == null)
            {
                return;
            }

            LoginAttemptSummaryForTypoAnalysis[] recentPotentialTypos = clientsIpHistory.RecentPotentialTypos.MostRecentFirst.ToArray();
            ECDiffieHellmanCng ecPrivateAccountLogKey = null;

            try
            {
                foreach (LoginAttemptSummaryForTypoAnalysis potentialTypo in recentPotentialTypos)
                {
                    bool usernameCorrect = potentialTypo.UsernameOrAccountId == account.UsernameOrAccountId;
                    //bool usernameHadTypo = !usernameCorrect &&
                    //    EditDistance.Calculate(potentialTypo.UsernameOrAccountId, account.UsernameOrAccountId) <=
                    //_options.MaxEditDistanceConsideredATypo;

                    if (usernameCorrect) // || usernameHadTypo
                    {
                        // Get the plaintext password from the previous login attempt
                        string passwordSubmittedInFailedAttempt = null;
                        if (account.GetType().Name == "SimulatedUserAccount")
                        {
                            passwordSubmittedInFailedAttempt = potentialTypo.EncryptedIncorrectPassword.Ciphertext;
                        }
                        else
                        {
                            if (ecPrivateAccountLogKey == null)
                            {
                                // Get the EC decryption key, which is stored encrypted with the Phase1 password hash
                                try
                                {
                                    ecPrivateAccountLogKey = accountController.DecryptPrivateAccountLogKey(account,
                                                                                                           phase1HashOfCorrectPassword);
                                }
                                catch (Exception)
                                {
                                    // There's a problem with the key that prevents us from decrypting it.  We won't be able to do this analysis.
                                    return;
                                }
                            }
                            // Now try to decrypt the incorrect password from the previous attempt and perform the typo analysis
                            try
                            {
                                // Attempt to decrypt the password.
                                passwordSubmittedInFailedAttempt =
                                    potentialTypo.EncryptedIncorrectPassword.Read(ecPrivateAccountLogKey);
                            }
                            catch (Exception)
                            {
                                // An exception is likely due to an incorrect key (perhaps outdated).
                                // Since we simply can't do anything with a record we can't Decrypt, we carry on
                                // as if nothing ever happened.  No.  Really.  Nothing to see here.
                            }
                        }

                        if (passwordSubmittedInFailedAttempt != null)
                        {
                            //bool passwordCorrect = passwordSubmittedInFailedAttempt == correctPassword;
                            bool passwordHadTypo = // !passwordCorrect &&
                                                   EditDistance.Calculate(passwordSubmittedInFailedAttempt, correctPassword) <=
                                                   _options.MaxEditDistanceConsideredATypo;

                            // Get credit for this nearly-correct attempt to counter penalty
                            if (passwordHadTypo)
                            {
                                credit += potentialTypo.Penalty.GetValue(_options.AccountCreditLimitHalfLife, whenUtc) *
                                          (1d - _options.PenaltyMulitiplierForTypo);
                            }
                        }
                    }

                    // Now that we know whether this past event was a typo or not, we no longer need to keep track
                    // of it (and we should remove it so we don't double credit it).
                    clientsIpHistory.RecentPotentialTypos.Remove(potentialTypo);
                }

                // Remove the amount to be credited from the block score due to the discovery of typos
                clientsIpHistory.CurrentBlockScore.SubtractInPlace(account.CreditHalfLife, credit, whenUtc);
            }
            finally
            {
                ecPrivateAccountLogKey?.Dispose();
            }
        }
Esempio n. 16
0
        private static void OnConnected()
        {
            if (diffieHellman != null)
            {
                diffieHellman.Dispose();
            }

            diffieHellman = new ECDiffieHellmanCng();
            byte[] servicePublicPart = diffieHellman.PublicKey.ToByteArray();
            using (MemoryStream sendStream = new MemoryStream(servicePublicPart.Length + 2))
            {
                using (BinaryWriter writer = new BinaryWriter(sendStream))
                {
                    writer.Write((ushort)servicePublicPart.Length);
                    writer.Write(servicePublicPart);
                }
                connection.SendObject <byte[]>("Handshake", sendStream.GetBuffer());
                connection.AppendIncomingPacketHandler <byte[]>("HandshakeResponse", (header, connection, bytes) =>
                {
                    connection.RemoveIncomingPacketHandler("HandshakeResponse");
                    using (MemoryStream receiveStream = new MemoryStream(bytes))
                    {
                        using (BinaryReader reader = new BinaryReader(receiveStream))
                        {
                            ushort saltLength      = reader.ReadUInt16();
                            byte[] salt            = reader.ReadBytes(saltLength);
                            ushort keyBlobLength   = reader.ReadUInt16();
                            byte[] keyBlob         = reader.ReadBytes(keyBlobLength);
                            ushort signatureLength = reader.ReadUInt16();
                            byte[] signature       = reader.ReadBytes(signatureLength);

                            using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                            {
                                try
                                {
                                    StringReader stringReader = new StringReader(Properties.Resources.publickey);
                                    XmlSerializer serializer  = new XmlSerializer(typeof(RSAParameters));
                                    RSAParameters rsaParams   = (RSAParameters)serializer.Deserialize(stringReader);
                                    csp.ImportParameters(rsaParams);
                                    if (!csp.VerifyData(keyBlob, new SHA512CryptoServiceProvider(), signature))
                                    {
                                        //Something is wrong here. The public blob does not match the signature. Possible MITM.
                                        connection.CloseConnection(true);
                                        connection = null;
                                    }
                                    else
                                    {
                                        //Connection was fine. Key exchange worked. Let's set the encryption up!
                                        byte[] sharedMaterial = diffieHellman.DeriveKeyMaterial(CngKey.Import(keyBlob, CngKeyBlobFormat.EccPublicBlob));
                                        using (Rfc2898DeriveBytes keyDerive = new Rfc2898DeriveBytes(sharedMaterial, salt, 1000))
                                        {
                                            encryptionKey = keyDerive.GetBytes(32); // 32 bytes = 256 bits, for AES encryption. Salt is generated per message
                                        }
                                        SetupMessageHandlers();
                                    }
                                }
                                finally
                                {
                                    csp.PersistKeyInCsp = false;
                                    if (diffieHellman != null)
                                    {
                                        diffieHellman.Dispose();
                                        diffieHellman = null;
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }