/// <summary> /// </summary> /// <returns></returns> public async Task PerformRoleMasterTasks() { KV2SecretEngine secEngine = (KV2SecretEngine)_vaultAgent.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "Sheakley KV2 Secrets", _beKV2Name); // Create the Path1 "secret" KV2Secret a = new KV2Secret("path1"); var result = await secEngine.TryReadSecret(a); if (!result.IsSuccess) { await secEngine.SaveSecret(a, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } // Create the AppData Folder KV2Secret b = new KV2Secret(Constants.appData); result = await secEngine.TryReadSecret(b); if (!result.IsSuccess) { await secEngine.SaveSecret(b, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } return; }
/// <summary> /// Performs tasks that the Role1 user would do. Creating the actual application folders. /// </summary> /// <param name="role"></param> /// <returns></returns> public async Task PerformRole1Tasks() { try { // Here we will create the AppA and B folders in both the path1 and the appData paths. KV2Secret path1AppA = new KV2Secret(Constants.appName_A, "path1"); KV2Secret path1AppB = new KV2Secret(Constants.appName_B, "path1"); KV2Secret appDataAppA = new KV2Secret(Constants.appName_A, Constants.appData); KV2Secret appDataAppB = new KV2Secret(Constants.appName_B, Constants.appData); KV2Secret appData = new KV2Secret(Constants.appData); // We need to simulate a session as this Role1 User: VaultAgentAPI vault = new VaultAgentAPI("Role1", _vaultAgent.Uri); AppRoleAuthEngine authEngine = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName); KV2SecretEngine secretEngine = (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "Sheakley KV2 Secrets", _beKV2Name); // Now login. Token token = await authEngine.Login(role1.RoleID, _SIDRole1.ID); // Create the secrets if they do not exist. We can attempt to Read the Secret on the path1 paths as we have full control var result = await secretEngine.TryReadSecret(appData); if (!result.IsSuccess) { await secretEngine.SaveSecret(appData, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } result = await secretEngine.TryReadSecret(path1AppA); if (!result.IsSuccess) { await secretEngine.SaveSecret(path1AppA, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } result = await secretEngine.TryReadSecret(path1AppB); if (!result.IsSuccess) { await secretEngine.SaveSecret(path1AppB, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } // We have to list the "folders" or secrets on the AppData path as we only have create and List permissions. List <string> appFolders = await secretEngine.ListSecretsAtPath(appData); if (!appFolders.Contains(Constants.appName_A)) { await secretEngine.SaveSecret(appDataAppA, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } if (!appFolders.Contains(Constants.appName_B)) { await secretEngine.SaveSecret(appDataAppB, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist); } } catch (VaultForbiddenException e) { Console.WriteLine("The role does not have permission to perform the requested operation. - Original Error - {0}", e.Message); } catch (Exception e) { Console.WriteLine("Error detected in routine - PerformRole1Tasks - Error is - {0}", e.Message); } }
public async Task PerformRoleATasks() { // We need to simulate a session as this Role1 User: VaultAgentAPI vault = new VaultAgentAPI("Role2", _vaultAgent.Uri); AppRoleAuthEngine authEngine = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName); KV2SecretEngine secretEngine = (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", _beKV2Name); // Now login. Token token = await authEngine.Login(roleAppA.RoleID, _SIDRoleAppA.ID); // Read existing secrets. string rootPath = Constants.appData + "/" + Constants.appName_A + "/"; KV2Secret secretA1 = new KV2Secret("Database", rootPath); bool readSuccess = false; (readSuccess, secretA1) = await secretEngine.TryReadSecret <KV2Secret>(secretA1, 0); // If it did not exist then create it. if (!readSuccess) { secretA1 = new KV2Secret("Database", rootPath); // Create Some Secrets. secretA1.Attributes.Add("username", "abcUser"); secretA1.Attributes.Add("password", "passEncrypted"); secretA1.Attributes.Add("Connection", "db=1.2.3.4:4706/iInstance"); await secretEngine.SaveSecret(secretA1, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist, 0); } // Try to read the parent secret - should fail KV2Secret secretParent = new KV2Secret(Constants.appData); (readSuccess, secretParent) = await secretEngine.TryReadSecret <KV2Secret>(secretParent, 0); // Lets try and read an AppB secret. Should fail. try { // Lets try and read an AppA secret. Should fail. string rootBPath = Constants.appData + "/" + Constants.appName_B + "/"; KV2Secret secretB1 = new KV2Secret("Database", rootBPath); (readSuccess, secretB1) = await secretEngine.TryReadSecret <KV2Secret>(secretB1, 0); } catch (VaultForbiddenException) { Console.WriteLine("[SUCCESS-EXPECTED RESULT: User A does not have access to read from User B's secret store."); } // Lets update the secret. string passwd = secretA1.Attributes["password"]; passwd = passwd + DateTime.Now.Hour; secretA1.Attributes["password"] = passwd; //secretEngine.SaveSecret(secretA1,) }
/// <summary> /// Saves the given Secret to the Vault /// </summary> /// <param name="secret">The secret to save</param> /// <returns></returns> private async Task <bool> SaveSecret(KV2SecretEngine engine, KV2Secret secret) { try { return(await engine.SaveSecret(secret, KV2EnumSecretSaveOptions.AlwaysAllow)); } catch (VaultForbiddenException e) { return(false); } }
public async Task PerformRoleBTasks() { // We need to simulate a session as this Role1 User: VaultAgentAPI vault = new VaultAgentAPI("Role2", _vaultAgent.Uri); AppRoleAuthEngine authEngine = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName); KV2SecretEngine secretEngine = (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", _beKV2Name); // Now login. Token token = await authEngine.Login(roleAppB.RoleID, _SIDRoleAppB.ID); // Read existing secrets. string rootPath = Constants.appData + "/" + Constants.appName_B + "/"; KV2Secret secretB1 = new KV2Secret("Database", rootPath); bool readSuccess = false; (readSuccess, secretB1) = await secretEngine.TryReadSecret(secretB1, 0); if (!readSuccess) { secretB1 = new KV2Secret("Database", rootPath); // Create Some Secrets. secretB1.Attributes.Add("username", "Buser"); secretB1.Attributes.Add("password", "Bpassword"); secretB1.Attributes.Add("Connection", "db=99.100.101.102:0/iBInstance"); await secretEngine.SaveSecret(secretB1, KV2EnumSecretSaveOptions.OnlyIfKeyDoesNotExist, 0); } try { // Lets try and read an AppA secret. Should fail. string rootAPath = Constants.appData + "/" + Constants.appName_A + "/"; KV2Secret secretA1 = new KV2Secret("Database", rootAPath); (readSuccess, secretB1) = await secretEngine.TryReadSecret(secretA1, 0); } catch (VaultForbiddenException) { Console.WriteLine("[SUCCESS-EXPECTED RESULT: User B does not have access to read from User A's secret store."); } int bb = 0; bb++; }
public async Task TestTemplatedPolicies() { string appBE = _uniqueKeys.GetKey("appTE"); string kv2BE = _uniqueKeys.GetKey("kv2TE"); // 1A - Setup backends needed for testing. // We need to setup a KV2 Secrets engine and also an AppRole Backend. // Create an Authentication method of App Role. - This only needs to be done when the Auth method is created. AuthMethod am = new AuthMethod(appBE, EnumAuthMethods.AppRole); await _vaultSystemBackend.AuthEnable(am); // Create a KV2 Secret Mount if it does not exist. VaultSystemBackend vaultSystemBackend = new VaultSystemBackend(_vaultAgentAPI.TokenID, _vaultAgentAPI); await vaultSystemBackend.SysMountCreate(kv2BE, "ClientTest KeyValue 2 Secrets", EnumSecretBackendTypes.KeyValueV2); // 1B. Now we can connect to the backends. VaultAgentAPI vault = await VaultServerRef.ConnectVault("PolicyBECapa"); //new VaultAgentAPI("capability", _vaultAgentAPI.IP, _vaultAgentAPI.Port, _vaultAgentAPI.TokenID); AppRoleAuthEngine authEngine = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, appBE, appBE); KV2SecretEngine secretEngine = (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", kv2BE); IdentitySecretEngine idEngine = (IdentitySecretEngine)_vaultAgentAPI.ConnectToSecretBackend(EnumSecretBackendTypes.Identity); // 1C - Write out some values. TestContext.WriteLine("App Role Auth Backend: {0}", authEngine.Name); TestContext.WriteLine("KV2 Secret Backend: {0}", secretEngine.Name); // 2. Setup the policy to provide the permissions to test against. VaultPolicyContainer policyContainer = new VaultPolicyContainer("capa"); // 3. Now create an App Role & Secret ID. The app role in this case has no policies - it will get them from the Entity. string roleName = _uniqueKeys.GetKey("role"); AppRole appRole = new AppRole(roleName); appRole = await authEngine.SaveRoleAndReturnRoleObject(appRole); AppRoleSecret secretID = await authEngine.CreateSecretID(appRole.Name); // 4. Create an Entity and Entity Alias. // 4A. Get Authentication backend accessor. Dictionary <string, AuthMethod> authMethods = await vaultSystemBackend.AuthListAll(); AuthMethod authMethod = authMethods[authEngine.Name + "/"]; Assert.IsNotNull(authMethod, "B10: Expected to find the authentication backend. But did not."); string mountAccessor = authMethod.Accessor; // 4B. Create an entity for the app role. string name = _uniqueKeys.GetKey("EAR"); Entity entity = new Entity(roleName); entity.Policies.Add(policyContainer.Name); // 4C. Now save entity entity = await idEngine.SaveEntity(entity); Assert.IsNotNull(entity, "B20: Expected to receive an Entity object"); // 4D. Write out some values TestContext.WriteLine("Entity Name: {0}", entity.Name); TestContext.WriteLine("Entity ID: {0}", entity.Id); // 5. Create an alias that ties the Entity we just created to the AppRole in the authentication backend. Guid roleID = new Guid(appRole.RoleID); Guid aliasGuid = await idEngine.SaveAlias(entity.Id, mountAccessor, appRole.RoleID); Assert.AreNotEqual(aliasGuid.ToString(), Guid.Empty.ToString()); // 5B. Re-read the entity - it should now contain the alias. Entity fullEntity = await idEngine.ReadEntity(entity.Id); Assert.AreEqual(1, fullEntity.Aliases.Count, "B30: Expected the full entity to now contain the alias ID."); // 6. Now define the policy and save to Vault. policyContainer.PolicyPaths.Clear(); string appPath1 = "app/{{identity.entity.aliases." + mountAccessor + ".name}}/*"; VaultPolicyPathItem vppi1 = new VaultPolicyPathItem(kv2BE, "data/" + appPath1); VaultPolicyPathItem vppi2 = new VaultPolicyPathItem(kv2BE, "data/app/appA/subItem/*"); VaultPolicyPathItem vppi3 = new VaultPolicyPathItem(kv2BE, "data/shared/common/*"); VaultPolicyPathItem vppi4 = new VaultPolicyPathItem(kv2BE, "data/shared/info/*"); vppi1.FullControl = true; vppi2.FullControl = true; vppi3.CRUDAllowed = true; vppi4.ReadAllowed = true; policyContainer.AddPolicyPathObject(vppi1); policyContainer.AddPolicyPathObject(vppi2); policyContainer.AddPolicyPathObject(vppi3); policyContainer.AddPolicyPathObject(vppi4); await _vaultSystemBackend.SysPoliciesACLCreate(policyContainer); // 7. Now we can login to get a token.. Validate the entity policy has been set on token. Token token = await authEngine.Login(appRole.RoleID, secretID.ID); Assert.IsNotNull("B40: A valid token was not received."); CollectionAssert.Contains(token.IdentityPolicies, policyContainer.Name, "B100: Did not find the policy that should have been applied from the entity."); // 8. Now we can finally test the capabilities of that token. List <string> paths = new List <string>(); string pathBase = kv2BE + "/data/app/" + fullEntity.Aliases[0].Name + "/config"; string metaBase = kv2BE + "/metadata/app" + fullEntity.Aliases[0].Name + "/config"; string path1 = pathBase; string path2 = pathBase + "/subItem"; string path3 = kv2BE + "/data/shared/common/testEntry"; paths.Add(path1); paths.Add(path2); paths.Add(path3); Dictionary <string, List <string> > permissions; permissions = await _vaultSystemBackend.GetTokenCapabilityOnPaths(token.ID, paths); // 9. Validate the permission results. Assert.AreEqual(3, permissions.Count, "B130: Expected to receive 3 permission objects back."); Assert.AreEqual(6, permissions[path1].Count, "B140: Expected the item: " + path1 + " to contain 6 permissions."); Assert.AreEqual(6, permissions[path2].Count, "B150: Expected the item: " + path2 + " to contain 6 permissions."); Assert.AreEqual(4, permissions[path3].Count, "B160: Expected the item: " + path3 + " to contain 3 permissions."); CollectionAssert.Contains(permissions[path3], "create", "B170: Expected the permission to be create for path: " + path3); CollectionAssert.Contains(permissions[path3], "read", "B171: Expected the permission to be read for path: " + path3); CollectionAssert.Contains(permissions[path3], "update", "B172: Expected the permission to be update for path: " + path3); CollectionAssert.Contains(permissions[path3], "delete", "B173: Expected the permission to be read for path: " + path3); // 10. Try to create a secret at path 1 string secName1 = _uniqueKeys.GetKey("sec1"); KV2Secret secret1 = new KV2Secret("config", "app/" + fullEntity.Aliases[0].Name); secret1.Attributes.Add("version", "v12.2"); Assert.True(await secretEngine.SaveSecret(secret1, KV2EnumSecretSaveOptions.AlwaysAllow), "B200: Save of secret did not work. Check permissions."); // 11. Create and delete a secret at path3. KV2Secret secret2 = new KV2Secret("options", "shared/common/testEntry"); secret2.Attributes.Add("color", "blue"); secret2.Attributes.Add("size", "Large"); Assert.True(await secretEngine.SaveSecret(secret2, KV2EnumSecretSaveOptions.AlwaysAllow), "B210: Save of secret2 failed."); // Now delete it. Assert.True(await secretEngine.DeleteSecretVersion(secret2)); }
/// <summary> /// Reusable method that updates the provided secret and then returns the updated version. /// </summary> /// <param name="secret"></param> /// <returns></returns> private async Task <KV2Secret> UpdateSecretRandom(KV2Secret secret) { secret.Attributes.Add(_uniqueKeys.GetKey("attr"), "val"); Assert.True(await _rootEng.SaveSecret(secret, KV2EnumSecretSaveOptions.OnlyOnExistingVersionMatch, secret.Version), "UpdateSecretRandom: Failed to save correctly."); return(await _rootEng.ReadSecret(secret)); }