public static void DecryptLegacyRsa <T>(this JObject encrypted, ICryptoManager cryptoManager, string path)
        {
            var cryptoField = encrypted.SelectToken(path);
            var kid         = cryptoField.SelectToken(EncryptionField.KeyIdentifier).Value <string>();
            var ciphertext  = cryptoField.SelectToken(EncryptionField.CipherText).Value <string>();
            var alg         = cryptoField.SelectToken(EncryptionField.Algorithm).Value <string>();

            var unencrypted = cryptoManager.Decrypt(new EncryptionResult
            {
                Alg        = alg,
                Ciphertext = ciphertext,
                Kid        = kid
            });

            var value = JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(unencrypted));

            encrypted.Property(path).Remove();

            var typeCode     = Type.GetTypeCode(typeof(T));
            var propertyName = path.Replace("__crypt_", "");

            if (value is System.Collections.IList)
            {
                encrypted.Add(propertyName, new JArray(value));
            }
            else if (typeCode == TypeCode.Object)
            {
                encrypted.Add(propertyName, JObject.FromObject(value));
            }
            else
            {
                encrypted.Add(propertyName, new JValue(value));
            }
        }
        public static void DecryptField <T>(this JObject jsonJObject, ICryptoManager cryptoManager, string path)
        {
            var jToken     = jsonJObject.SelectToken(cryptoManager.Mangle(path));
            var kid        = jToken.SelectToken(EncryptionField.KeyIdentifier).Value <string>();
            var cipherText = jToken.SelectToken(EncryptionField.CipherText).Value <string>();
            var alg        = jToken.SelectToken(EncryptionField.Algorithm).Value <string>();

            var decryptedBytes = cryptoManager.Decrypt(new EncryptionResult
            {
                Alg        = alg,
                Kid        = kid,
                Ciphertext = cipherText
            });

            var rawText = Encoding.UTF8.GetString(decryptedBytes);

            jsonJObject.Property(cryptoManager.Mangle(path)).Remove();

            var typeCode = Type.GetTypeCode(typeof(T));

            if (typeCode == TypeCode.String)
            {
                jsonJObject.Add(new JProperty(path, rawText));
            }
            else
            {
                var value = JsonConvert.DeserializeObject(rawText);
                jsonJObject.Add(new JProperty(path, value));
            }
        }
        public string Read()
        {
            if (!File.Exists(_configPath))
            {
                throw new FileNotFoundException("File not found", _configPath);
            }

            using (FileStream fileStream = File.OpenRead(_configPath))
            {
                byte[]       buffer       = new byte[_blockSize];
                UTF8Encoding utf8Encoding = new UTF8Encoding(true);

                string textContent = string.Empty;

                int bytesRead;
                do
                {
                    bytesRead    = fileStream.Read(buffer, 0, buffer.Length);
                    textContent += utf8Encoding.GetString(buffer, 0, bytesRead);
                    Array.Clear(buffer, 0, bytesRead);
                } while (bytesRead > 0);

                return(_cryptoManager.Decrypt(textContent));
            }
        }
Пример #4
0
        public async Task <ConnectionProperties> GetByIdDecrypted(int id)
        {
            var props = await _work.ConnectionPropertiesRepository.Get(id);

            if (props.IsPasswordEncrypted)
            {
                props.Password = _cryptoManager.Decrypt(props.Password);
            }

            return(props);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            var encryptedJObject = (JObject)JToken.ReadFrom(reader);

            if (encryptedJObject.Value <string>("alg") != NonLegacyAlgorithim)
            {
                //decrypt using the legacy algorithm - will upgrade on write back
                var legacyPlainText = encryptedJObject.Decrypt(_cryptoManager, _legacySigningKeyName);
                return(ConvertToType(Encoding.UTF8.GetString(legacyPlainText)));
            }

            var encryptedResult = EncryptionResult.FromJObject(encryptedJObject);
            var plainText       = _cryptoManager.Decrypt(encryptedResult);

            return(ConvertToType(Encoding.UTF8.GetString(plainText)));
        }
        internal static byte[] Decrypt(this JObject encrypted, ICryptoManager cryptoManager, string signingKeyName)
        {
#pragma warning disable 618
            var sig = encrypted.SelectToken(EncryptionField.Signature).Value <string>();
#pragma warning restore 618
            var ciphertext = encrypted.SelectToken(EncryptionField.CipherText).Value <string>();
            var alg        = encrypted.SelectToken(EncryptionField.Algorithm).Value <string>();
#pragma warning disable 618
            var iv = encrypted.SelectToken(EncryptionField.InitializationVector).Value <string>();
#pragma warning restore 618
            var kid = encrypted.SelectToken(EncryptionField.KeyIdentifier).Value <string>();

            var kidBytes    = Encoding.UTF8.GetBytes(kid);
            var algBytes    = Encoding.UTF8.GetBytes(alg);
            var ivBytes     = Convert.FromBase64String(iv);
            var cipherBytes = Convert.FromBase64String(ciphertext);

            var buffer = new byte[kidBytes.Length + algBytes.Length + ivBytes.Length + cipherBytes.Length];
            Buffer.BlockCopy(kidBytes, 0, buffer, 0, kidBytes.Length);
            Buffer.BlockCopy(algBytes, 0, buffer, kidBytes.Length, algBytes.Length);
            Buffer.BlockCopy(ivBytes, 0, buffer, kidBytes.Length + algBytes.Length, ivBytes.Length);
            Buffer.BlockCopy(cipherBytes, 0, buffer, kidBytes.Length + algBytes.Length + ivBytes.Length, cipherBytes.Length);

            var signature = cryptoManager.Encrypt(buffer, signingKeyName);
            if (sig != signature.Ciphertext)
            {
                throw new DecryptionFailureException();
            }

            return(cryptoManager.Decrypt(new EncryptionResult
            {
                Alg = alg,
                Kid = kid,
                Ciphertext = ciphertext,
                Iv = Convert.FromBase64String(iv)
            }));
        }
Пример #7
0
        private void OnOpen(IWebSocketConnection socket)
        {
            socket.OnMessage += async s =>
            {
                if (!_users.TryGetValue(socket, out var user))
                {
                    if (_crypto.TryDecrypt(s, out var decryptResult) && _passwords.Select(x => x.User).Contains(decryptResult.password.User))
                    {
                        var item = _userFactory.Create(socket, decryptResult.password);
                        _users.TryAdd(socket, item);

                        socket.OnClose += () => { _users.TryRemove(socket, out _); };

                        item.OnDisconnected += RemoveUser;

                        await item.Write(_messageFactory.CreateLoginApiAccepted(), false);

                        await _logManager.LogInformation(
                            $"User {decryptResult.password.User} logged in.");
                    }
                    else
                    {
                        RemoveFromTimeout();
                        await socket.Send(_messageFactory.CreateLoginApiRejected());

                        socket.Close();
                    }
                }
                else
                {
                    var data = _crypto.Decrypt(s, user.Password.ToString());
                    if (string.IsNullOrEmpty(data))
                    {
                        return;
                    }

                    ApiMessage message;
                    try
                    {
                        message = JsonSerializer.Deserialize <ApiMessage>(data);
                    }
                    catch
                    {
                        _logger.LogWarning("ImpostorHQ Danger: user {Address} is sending malformed API messages.",
                                           socket.ConnectionInfo.ClientIpAddress);
                        await user.Kick();

                        RemoveUser();
                        return;
                    }

                    var(success, exception) = await user.HandleMessage(message);

                    if (!success)
                    {
                        _logger.LogWarning("ImpostorHQ Danger: user {Address} tried to execute an invalid operation.", socket.ConnectionInfo.ClientIpAddress);
                        await user.Kick();

                        RemoveUser();

                        await _logManager.LogError(
                            $"User {socket.ConnectionInfo.ClientIpAddress} created error on HandleMessage.", exception);
                    }
                }
            };

            void RemoveFromTimeout()
            {
                _timeouts.TryRemove(socket, out _);
            }

            void RemoveUser()
            {
                _users.TryRemove(socket, out _);
                socket.Close();
            }
        }