public void ExportNewKey() { var keyPath = Path.GetTempFileName(); using (var sman = SecretsManager.CreateStore()) { sman.GenerateKey(); sman.ExportKey(keyPath); } Assert.IsTrue(File.Exists(keyPath)); Assert.AreNotEqual(0, new FileInfo(keyPath).Length, "Exported key is zero bytes!"); }
private void CreateTestStore(string storePath, string keyPath) { using (var sman = SecretsManager.CreateStore()) { sman.GenerateKey(); foreach (var key in SecureData.Keys) { sman.Set(key, SecureData[key]); } sman.SaveStore(storePath); sman.ExportKey(keyPath); } }
public GameV2() { Player = new Player(this, true); Opponent = new Player(this, false); IsInMenu = true; SecretsManager = new SecretsManager(this, new RemoteArenaSettings()); _battlegroundsBoardState = new BattlegroundsBoardState(this); Reset(); LiveDataManager.OnStreamingChecked += async streaming => { MetaData.TwitchVodData = await UpdateTwitchVodData(streaming); }; }
public void CreateStore() { var storePath = Path.GetTempFileName(); using (var sman = SecretsManager.CreateStore()) { sman.GenerateKey(); sman.SaveStore(storePath); } Assert.IsTrue(File.Exists(storePath)); Assert.AreNotEqual(0, new FileInfo(storePath).Length, "Saved store is zero bytes!"); }
public void Toggle_SingleClass() { var game = new MockGame { CurrentGameType = GameType.GT_RANKED, CurrentFormat = Format.Wild }; var secretsManager = new SecretsManager(game, new MockArenaSettings()); var entity = new Entity(0); entity.SetTag(GameTag.SECRET, 1); entity.SetTag(GameTag.CLASS, (int)CardClass.PALADIN); secretsManager.NewSecret(entity); Assert.AreEqual(1, secretsManager.Secrets.Count); var cards = secretsManager.GetSecretList(); Assert.AreEqual(1, cards.Single(x => Paladin.Avenge == x.Id).Count); secretsManager.Toggle(Paladin.Avenge); cards = secretsManager.GetSecretList(); Assert.AreEqual(0, cards.Single(x => Paladin.Avenge == x.Id).Count); secretsManager.Toggle(Paladin.Avenge); cards = secretsManager.GetSecretList(); Assert.AreEqual(1, cards.Single(x => Paladin.Avenge == x.Id).Count); foreach (var id in Paladin.All) { secretsManager.Toggle(id); } cards = secretsManager.GetSecretList(); foreach (var card in cards) { Assert.AreEqual(0, card.Count); } foreach (var id in Paladin.All) { secretsManager.Toggle(id); } cards = secretsManager.GetSecretList(); foreach (var card in cards) { Assert.AreEqual(1, card.Count); } }
/// <summary>Wraps a call to the secrets manager, and queries the user for a value, if one /// isn't already on record.</summary> /// <param name="id">The secret's ID.</param> /// <param name="prompt">The string with which to ask the user for a value.</param> /// <param name="value">When this returns, contains the secret; or the null or empty string /// if the retrieval failed.</param> /// <returns>True if the retrieval or prompt succeeded; otherwise, false.</returns> private static bool GetSecret(string id, string prompt, out string value) { if (SecretsManager.TryGet(id, out value) && !string.IsNullOrWhiteSpace(value)) { return(true); } Console.Write(prompt + " "); value = Console.ReadLine(); value = value.Trim(); return(!string.IsNullOrEmpty(value)); }
public async void Process(IThreatModel model) { Connect.ChangeDisconnectButtonStatus(null, false); var schemaManager = new DevOpsConfigPropertySchemaManager(model); var connector = schemaManager.GetDevOpsConnector(out var url, out var project); if (connector != null && !string.IsNullOrWhiteSpace(url) && !string.IsNullOrWhiteSpace(project)) { try { var tokenManager = new SecretsManager(); var token = tokenManager.GetSecret(url); if (!string.IsNullOrWhiteSpace(token)) { connector.Connect(url, token); var projects = (await connector.GetProjectsAsync())?.ToArray(); if (projects?.Contains(project) ?? false) { if (connector.OpenProject(project)) { DevOpsManager.Register(connector, model); Connect.ChangeDisconnectButtonStatus(connector, true); var configManager = new ExtensionConfigurationManager(model, this.GetExtensionId()); configManager.Apply(); await DevOpsManager.UpdateAsync(model); } } else { connector.Disconnect(); ShowWarning?.Invoke( "DevOps system cannot be automatically connected due to an internal error."); } } else { ShowWarning?.Invoke( "DevOps system cannot be automatically connected because no Personal Access Token has been found."); } } catch (Exception exc) { ShowWarning?.Invoke($@"DevOps system cannot be automatically connected due to the following error: {exc.Message}. Everything else should be unaffected."); } } }
public void UpdateProductEF() { string connectionString = SecretsManager.GetSecrets <DatabaseSettings>("ConnectionString"); EntityFrameworkCoreData efData = new EntityFrameworkCoreData(connectionString); IQueryable <Product> products = efData.Products.Where(p => p.ProductName.Contains("EF Product")); foreach (Product product in products) { product.ProductName = "EF Product Edited"; } efData.Products.UpdateRange(products); int recordsAffected = efData.SaveChanges(); efData.Dispose(); }
protected override void ProcessRecord() { try { if (File.Exists(StorePath)) { using (var sman = SecretsManager.LoadStore(StorePath)) { if (ParameterSetName == "KeyPath") { KeyPath = GetUnresolvedProviderPathFromPSPath(KeyPath); sman.LoadKeyFromFile(KeyPath); } if (ParameterSetName == "Password") { sman.LoadKeyFromPassword(Password); } sman.Set(Name, Value); StorePath = GetUnresolvedProviderPathFromPSPath(StorePath); sman.SaveStore(StorePath); } } } catch { //either the file doesn't exist, or it is a non-secretful file using (var sman = SecretsManager.CreateStore()) { if (ParameterSetName == "KeyPath") { KeyPath = GetUnresolvedProviderPathFromPSPath(KeyPath); sman.LoadKeyFromFile(KeyPath); } if (ParameterSetName == "Password") { sman.LoadKeyFromPassword(Password); } sman.Set(Name, Value); StorePath = GetUnresolvedProviderPathFromPSPath(StorePath); sman.SaveStore(StorePath); } } }
public void StoreAndLoad() { var storePath = Path.GetTempFileName(); var keyPath = Path.GetTempFileName(); CreateTestStore(storePath, keyPath); using (var sman = SecretsManager.LoadStore(storePath)) { sman.LoadKeyFromFile(keyPath); foreach (var key in SecureData.Keys) { Assert.AreEqual(SecureData[key], sman.Retrieve(key), $"Retrieved data for key \"{key}\" does not match stored value!"); } } }
public static void CreateTestStore(string storePath, string keyPath = null) { using (var store = SecretsManager.CreateStore()) { store.GenerateKey(); foreach (var key in SecureData.Keys) { store.Set(key, SecureData[key]); } store.SaveStore(storePath); if (!string.IsNullOrEmpty(keyPath)) { store.ExportKey(keyPath); } } }
protected override void ProcessRecord() { StorePath = GetUnresolvedProviderPathFromPSPath(StorePath); using (var sman = SecretsManager.LoadStore(StorePath)) { if (All) { if (ParameterSetName == "KeyPath") { KeyPath = GetUnresolvedProviderPathFromPSPath(KeyPath); sman.LoadKeyFromFile(KeyPath); } if (ParameterSetName == "Password") { sman.LoadKeyFromPassword(Password); } Hashtable toReturn = new Hashtable(); foreach (var k in sman.Keys) { toReturn.Add(k, sman.Get(k)); } WriteObject(toReturn); } else { if (ParameterSetName == "KeyPath") { KeyPath = GetUnresolvedProviderPathFromPSPath(KeyPath); sman.LoadKeyFromFile(KeyPath); } if (ParameterSetName == "Password") { sman.LoadKeyFromPassword(Password); } WriteObject(sman.Get(Name)); } } }
public void DeleteProductADNSP() { string connectionString = SecretsManager.GetSecrets <DatabaseSettings>("ConnectionString"); AdoDotNetData aaa = new(connectionString); SqlCommandModel model = new() { CommandText = "DeleteProduct", CommandType = CommandType.StoredProcedure, CommandParameters = new SqlCommandParameterModel[] { new SqlCommandParameterModel() { ParameterName = "@ProductName", DataType = DbType.String, Value = "ADO.NET Product - Edited" } } }; aaa.ExecuteNonQuery(model); aaa.Dispose(); }
public void DeleteProductEFSP() { string connectionString = SecretsManager.GetSecrets <DatabaseSettings>("ConnectionString"); EntityFrameworkCoreData efData = new(connectionString); SqlCommandModel model = new() { CommandText = "EXEC DeleteProduct @ProductName = {0}", CommandType = CommandType.StoredProcedure, CommandParameters = new SqlCommandParameterModel[] { new SqlCommandParameterModel() { ParameterName = "@NewProductName", DataType = DbType.String, Value = "EF Product - Edited" } } }; efData.ExecuteNonQuerySP(model); efData.Dispose(); }
public void ReadFilteredProductsDDNSP() { string connectionString = SecretsManager.GetSecrets <DatabaseSettings>("ConnectionString"); DapperDotNet ddnData = new(connectionString); SqlCommandModel model = new() { CommandText = "GetProductName", CommandType = CommandType.StoredProcedure, CommandParameters = new SqlCommandParameterModel[] { new SqlCommandParameterModel() { ParameterName = "@ProductName", DataType = DbType.String, Value = "Dapper.NET Product" } } }; IEnumerator <Product> products = ddnData.ExecuteReaderSP <Product>(model); ddnData.Dispose(); }
public void ReadScalarProductADNSP() { string connectionString = SecretsManager.GetSecrets <DatabaseSettings>("ConnectionString"); AdoDotNetData aaa = new(connectionString); SqlCommandModel model = new SqlCommandModel() { CommandText = "GetProductName", CommandType = CommandType.StoredProcedure, CommandParameters = new SqlCommandParameterModel[] { new SqlCommandParameterModel() { ParameterName = "@ProductName", DataType = DbType.String, Value = "ADO.NET Product" } } }; string productName = aaa.ExecuteScalar <string>(model); aaa.Dispose(); }
/// <summary> /// Loads the SecureStore data from a stream. /// </summary> /// <param name="stream">The stream to read.</param> public override void Load(Stream stream) { var source = (SecureStoreConfigurationSource)Source; var dictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); using (var manager = SecretsManager.LoadStore(stream)) { switch (source.KeyType) { case KeyType.File: // ref: https://github.com/aspnet/Configuration/blob/master/src/Config.FileExtensions/FileConfigurationProvider.cs#L48 var file = source.KeyFileProvider?.GetFileInfo(source.Key); if (file == null || !file.Exists) { var error = new StringBuilder( $"The configuration key file '{source.Key}' was not found and is not optional."); if (!string.IsNullOrEmpty(file?.PhysicalPath)) { error.Append($" The physical path is '{file.PhysicalPath}'."); } throw new FileNotFoundException(error.ToString()); } manager.LoadKeyFromFile(file.PhysicalPath); break; case KeyType.Password: manager.LoadKeyFromPassword(source.Key); break; default: throw new ArgumentOutOfRangeException(nameof(source.KeyType)); } foreach (var key in manager.Keys) { dictionary.Add(key, manager.Get(key)); } } Data = dictionary; }
public async Task <IReadOnlyList <SecretListEntry> > GetAllSecrets(CancellationToken cancellationToken) { var result = new List <SecretListEntry>(); var query = default(ListSecretsResponse); do { var nextToken = query?.NextToken; var request = new ListSecretsRequest() { NextToken = nextToken }; query = await SecretsManager.ListSecretsAsync(request, cancellationToken).ConfigureAwait(false); result.AddRange(query.SecretList); } while (query.NextToken != null); return(result); }
public void InvalidClass() { var game = new MockGame { CurrentGameType = GameType.GT_RANKED, CurrentFormat = Format.Wild }; var secretsManager = new SecretsManager(game, new MockArenaSettings()); var entity = new Entity(0); entity.SetTag(GameTag.SECRET, 1); entity.SetTag(GameTag.CLASS, (int)CardClass.PRIEST); secretsManager.NewSecret(entity); Assert.AreEqual(1, secretsManager.Secrets.Count); Assert.AreEqual(0, secretsManager.GetSecretList().Count); secretsManager.Toggle(Paladin.Avenge); Assert.AreEqual(0, secretsManager.GetSecretList().Count); }
public void Reset() { var game = new MockGame { CurrentGameType = GameType.GT_RANKED, CurrentFormat = Format.Wild }; var secretsManager = new SecretsManager(game, new MockArenaSettings()); var entity = new Entity(0); entity.SetTag(GameTag.SECRET, 1); entity.SetTag(GameTag.CLASS, (int)CardClass.PALADIN); secretsManager.NewSecret(entity); Assert.AreEqual(1, secretsManager.Secrets.Count); secretsManager.Reset(); Assert.AreEqual(0, secretsManager.Secrets.Count); }
public void CatchTamperedData() { const string password = "******"; string storePath = Path.GetTempFileName(); // Generate a valid store using (var sman = SecretsManager.CreateStore()) { sman.LoadKeyFromPassword(password); sman.Set("foo", "bar"); sman.SaveStore(storePath); } // Load the store contents into memory var fileData = File.ReadAllText(storePath); // We don't have access to the internal encrypted bytes payloads are // deserialized to, but we can just access it directly. var deserialized = JsonConvert.DeserializeObject <MockStore>(fileData); var bytes = deserialized.Secrets["foo"].Payload; // Tamper with the data var prng = new Random(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] ^= (byte)prng.Next(); } // Write the changes back deserialized.Secrets["foo"].Payload = bytes; fileData = JsonConvert.SerializeObject(deserialized); File.WriteAllText(storePath, fileData); // Verify that tampering is caught using (var sman = SecretsManager.LoadStore(storePath)) { sman.LoadKeyFromPassword(password); Assert.ThrowsException <TamperedCipherTextException>(() => sman.Get("foo"), "Could not detect tampering with encrypted data!"); } }
public bool Upgrade(SecretsManager sman, Vault vault, string password) { // Upgrade from 10,000 PBKDF2 rounds to 256,000 PBKDF2 rounds if (password is null) { return(true); } // Load old key var oldKey = SecretsManager.DerivePassword(password, vault.IV, 10000); sman.SplitAndLoadKey(oldKey); var secrets = new Dictionary <string, SecureBuffer>(vault.Data.Count); foreach (var kv in vault.Data) { secrets.Add(kv.Key, sman.Decrypt(kv.Value)); } // Load new key with explicit IV length vault.IV = new byte[16]; SecretsManager.GenerateBytes(vault.IV); var newKey = SecretsManager.DerivePassword(password, vault.IV, 256000); sman.SplitAndLoadKey(newKey); // Update individual secrets foreach (var kv in secrets) { sman.Set(kv.Key, kv.Value); kv.Value.Dispose(); } // Update sentinel to match new password vault.Sentinel = null; sman.CreateSentinel(); return(true); }
public void CatchTamperedData() { const string password = "******"; string storePath = Path.GetTempFileName(); //generate a valid store using (var sman = SecretsManager.CreateStore()) { sman.LoadKeyFromPassword(password); sman.Set("foo", "bar"); sman.SaveStore(storePath); } //load the store contents into memory var fileData = File.ReadAllText(storePath); var deserialized = JsonConvert.DeserializeObject <dynamic>(fileData); string base64 = deserialized.Data.foo.Payload; var bytes = Convert.FromBase64String(base64); //tamper with the data var prng = new Random(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] ^= (byte)prng.Next(); } //write the changes back deserialized.Data.foo.Payload = Convert.ToBase64String(bytes); fileData = JsonConvert.SerializeObject(deserialized); File.WriteAllText(storePath, fileData); //test decryption using (var sman = SecretsManager.LoadStore(storePath)) { sman.LoadKeyFromPassword(password); Assert.ThrowsException <TamperedCipherTextException>(() => sman.Retrieve("foo"), "Could not detect tampering with encrypted data!"); } }
public void DeleteProductDDNSP() { string connectionString = SecretsManager.GetSecrets <DatabaseSettings>("ConnectionString"); DapperDotNet ddnData = new(connectionString); SqlCommandModel model = new() { CommandText = "DeleteProduct", CommandType = CommandType.StoredProcedure, CommandParameters = new SqlCommandParameterModel[] { new SqlCommandParameterModel() { ParameterName = "@ProductName", DataType = DbType.String, Value = "Dapper.NET Product - Edited" } } }; ddnData.ExecuteNonQuery(model); ddnData.Dispose(); } #endregion Dapper.NET Benchmarks }
private void CreateTestStore(string storePath, string key, KeyType type) { using (var sman = SecretsManager.CreateStore()) { if (type == KeyType.Password) { sman.LoadKeyFromPassword(key); } else { sman.GenerateKey(); } foreach (var secretKey in SecureData.Keys) { sman.Set(secretKey, SecureData[secretKey]); } sman.SaveStore(storePath); sman.ExportKey(key); } }
public void NewSecret_ValidEntity() { var game = new MockGame { CurrentGameType = GameType.GT_RANKED, CurrentFormat = Format.Wild }; var secretsManager = new SecretsManager(game, new MockArenaSettings()); Assert.AreEqual(0, secretsManager.GetSecretList().Count); var validEntity = new Entity(0); validEntity.SetTag(GameTag.SECRET, 1); validEntity.SetTag(GameTag.CLASS, (int)CardClass.PALADIN); var added = secretsManager.NewSecret(validEntity); Assert.IsTrue(added); Assert.AreEqual(1, secretsManager.Secrets.Count); var validEntity2 = new Entity(1); validEntity2.SetTag(GameTag.SECRET, 1); validEntity2.SetTag(GameTag.CLASS, (int)CardClass.PALADIN); added = secretsManager.NewSecret(validEntity); Assert.IsTrue(added); Assert.AreEqual(2, secretsManager.Secrets.Count); var validEntity3 = new Entity(2); validEntity3.SetTag(GameTag.SECRET, 1); validEntity3.SetTag(GameTag.CLASS, (int)CardClass.MAGE); added = secretsManager.NewSecret(validEntity); Assert.IsTrue(added); Assert.AreEqual(3, secretsManager.Secrets.Count); }
public void Reset(bool resetStats = true) { Log.Info("-------- Reset ---------"); Player.Reset(); Opponent.Reset(); if (!_matchInfoCacheInvalid && MatchInfo?.LocalPlayer != null && MatchInfo.OpposingPlayer != null) { Player.Name = MatchInfo.LocalPlayer.Name; Opponent.Name = MatchInfo.OpposingPlayer.Name; Player.Id = MatchInfo.LocalPlayer.Id; Opponent.Id = MatchInfo.OpposingPlayer.Id; } ProposedAttacker = 0; ProposedDefender = 0; Entities.Clear(); SavedReplay = false; SecretsManager.Reset(); _spectator = null; _currentGameMode = GameMode.None; _currentGameType = GameType.GT_UNKNOWN; _currentFormat = FormatType.FT_UNKNOWN; if (!IsInMenu && resetStats) { CurrentGameStats = new GameStats(GameResult.None, "", "") { PlayerName = "", OpponentName = "", Region = CurrentRegion } } ; PowerLog.Clear(); if (Core.Game != null && Core.Overlay != null) { Core.UpdatePlayerCards(true); Core.UpdateOpponentCards(true); } }
public void OnSecretsChangedEvent() { var game = new MockGame { CurrentGameType = GameType.GT_RANKED, CurrentFormat = Format.Wild }; var callbackCount = 0; var secretsManager = new SecretsManager(game, new MockArenaSettings()); secretsManager.OnSecretsChanged += secrets => callbackCount += 1; var entity = new Entity(0); entity.SetTag(GameTag.SECRET, 1); entity.SetTag(GameTag.CLASS, (int)CardClass.PALADIN); secretsManager.NewSecret(entity); Assert.AreEqual(1, callbackCount); secretsManager.Toggle(Paladin.Avenge); Assert.AreEqual(2, callbackCount); secretsManager.Exclude(new List <MultiIdCard> { Paladin.CompetitiveSpirit, Paladin.GetawayKodo }); Assert.AreEqual(3, callbackCount); secretsManager.Toggle(Paladin.Avenge); Assert.AreEqual(4, callbackCount); secretsManager.RemoveSecret(entity); Assert.AreEqual(5, callbackCount); secretsManager.Reset(); Assert.AreEqual(6, callbackCount); }
public void PasswordSalting() { const string password = "******"; string keyPath1 = Path.GetTempFileName(); string keyPath2 = Path.GetTempFileName(); using (var sman = SecretsManager.CreateStore()) { sman.LoadKeyFromPassword(password); sman.ExportKey(keyPath1); } using (var sman = SecretsManager.CreateStore()) { sman.LoadKeyFromPassword(password); sman.ExportKey(keyPath2); } var key1 = File.ReadAllBytes(keyPath1); var key2 = File.ReadAllBytes(keyPath2); Assert.IsTrue(key1.Length == key2.Length); Assert.IsFalse(key1.SequenceEqual(key2)); }
public void EncryptionTest() { string storePath = Path.GetTempFileName(); using (var sman = SecretsManager.CreateStore()) { sman.LoadKeyFromPassword("password1"); sman.Set("foo", "bar"); sman.SaveStore(storePath); } using (var sman = SecretsManager.LoadStore(storePath)) { sman.LoadKeyFromPassword("password2"); string retrieved = null; try { retrieved = sman.Get("foo"); } catch { } Assert.AreNotEqual("bar", retrieved, "Retrieved encrypted data with wrong password!"); } }