/// <summary>
        /// Start The Scenario
        /// </summary>
        /// <returns></returns>
        public async Task Run()
        {
            // Create the mounts and policies and store in Vault
            await CreateBackendMounts();
            await CreatePolicies();

            // Mount the Secret Engine
            _secretEngine =
                (KV2SecretEngine)_masterVaultAgent.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beKV2Name, _beKV2Name);

            // Mount the Authentication Engine, so roles can login
            _appRoleAuthEngine = (AppRoleAuthEngine)_masterVaultAgent.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);


            // Create the roles - assigning policies to the roles
            roleMother = await CreateRole("roleMother", _policyHouse_Full.Name);

            roleFather = await CreateRole("roleFather", _policyHouse_Full.Name);

            roleTeenager = await CreateRole("roleTeenager", _policyTeenagerBedroom_Full.Name,
                                            _policyKitchenRefrigerator_Write.Name, _policyHouseOnly_Read.Name, _policyKitchen_Write.Name);

            roleToddler = await CreateRole("roleToddler", _policyToddlerBedroom_Full.Name);

            // Create Login SIDS for each role
            _sidMother = await _appRoleAuthEngine.CreateSecretID(roleMother.Name);

            _sidFather = await _appRoleAuthEngine.CreateSecretID(roleFather.Name);

            _sidTeenager = await _appRoleAuthEngine.CreateSecretID(roleTeenager.Name);

            _sidToddler = await _appRoleAuthEngine.CreateSecretID(roleToddler.Name);

            // Set the Mother role to have full access.
            KV2Secret a = new KV2Secret(HOUSE.HOUSE_PATH);

            await SaveSecret(_secretEngine, a);


            // It's important to note:  Up to now we have been using the Master token to create objects, secret stores, policies and the initial House Secret.  From here forward each
            // user will login and perform the actions under their user ID.

            await Perform_MotherTasks();
            await Perform_TeenTasks();
        }
        /// <summary>
        /// We will walk thru the following sequence:
        ///  - Create a new Vault authentication backend for App Roles
        ///  - Create a set of policies that roles will use to restrict access
        ///  - Create a set of roles that will be used to provide tokens to "applications"
        ///  - Create tokens against those roles.
        ///  - Test the access of those tokens to confirm they have the necessary permissions.
        /// </summary>
        /// <returns></returns>
        public async Task Run()
        {
            try {
                // Create the backends if they do not exist.
                await CreateBackendMounts();

                // Create all the necessary policies.
                await CreatePoliciesController();

                // Create the roles and assign the policies.
                roleMaster = await CreateRole("roleMaster", _polRoleMaster.Name);

                role1 = await CreateRole("role1", _polRole1.Name);

                role2 = await CreateRole("role2", _polRole2.Name);

//				roleAppA = await CreateRole("roleAppA", _polCommon.Name, _polSharedDB.Name);
//				roleAppB = await CreateRole("roleAppB", _polCommon.Name, _polSharedDB.Name);
                roleAppA = await CreateRole("roleAppA", _polRoleAppA.Name, _polSharedDB.Name);

                roleAppB = await CreateRole("roleAppB", _polRoleAppB.Name, _polSharedDB.Name, _polSharedEmail.Name);


                // Create Secret ID's for each of the Application Roles
                _SIDRoleMaster = await _appRoleAuthEngine.CreateSecretID(roleMaster.Name);

                _SIDRole1 = await _appRoleAuthEngine.CreateSecretID(role1.Name);

                _SIDRole2 = await _appRoleAuthEngine.CreateSecretID(role2.Name);

                _SIDRoleAppA = await _appRoleAuthEngine.CreateSecretID(roleAppA.Name);

                _SIDRoleAppB = await _appRoleAuthEngine.CreateSecretID(roleAppB.Name);



                // Main testing logic begins here.

                // For this sequence of steps we need to create a new instance of the Vault as we will be connecting via the new token.  We connect to the requested backend.

                /*
                 * VaultAgentAPI A_VaultAgentAPI = new VaultAgentAPI("SecretRole A",_vaultAgent.IP,_vaultAgent.Port);
                 * AppRoleAuthEngine A_appRoleAuthEngine = (AppRoleAuthEngine) A_VaultAgentAPI.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _beAuthName, _beAuthName);
                 * KV2SecretEngine A_KV2SecretEngine =
                 * (KV2SecretEngine) A_VaultAgentAPI.ConnectToSecretBackend (EnumSecretBackendTypes.KeyValueV2, "Test  KV2 Secrets", _beKV2Name);
                 */
                await PerformRoleMasterTasks();

                // Role1 can create any secret/subsecret on the path1/ and appdata/ paths
                await PerformRole1Tasks();


                // Perform RoleAppA tasks
                await PerformRoleATasks();


                // Perform RoleAppB tasks
                await PerformRoleBTasks();


                // Role2 can only read anything found within path1/
                await PerformRole2Tasks();


                return;


                // List current roles.  Create role if does not exist.  Read the role.  List the roles again.

                /*
                 * List<string> appRoles = await AppRole_ListRoles();
                 *              if (!appRoles.Contains(_AppRoleName)) {
                 *                      await AppRole_Create();
                 *              }
                 *
                 *              await ReadRole();
                 *
                 *              appRoles = await AppRole_ListRoles();
                 *
                 *              // Now get a role ID
                 *              string roleID = await _appRoleAuthEngine.ReadRoleID(_AppRoleName);
                 *
                 *              // Now delete the app role.
                 *              bool rc = await _appRoleAuthEngine.DeleteRole(_AppRoleName);
                 */
            }
            catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); }
        }
Exemple #3
0
        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));
        }
Exemple #4
0
        public async Task TestCapabilitiesFunctionality()
        {
            string appBE = _uniqueKeys.GetKey("appBE");
            string kv2BE = _uniqueKeys.GetKey("kv2BE");


            // 1 - 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.
            await _vaultSystemBackend.SysMountCreate(kv2BE, "ClientTest KeyValue 2 Secrets", EnumSecretBackendTypes.KeyValueV2);


            // Now we create secret backend
            VaultAgentAPI vault = await VaultServerRef.ConnectVault("PolicyBeCapa2");

            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, appBE, appBE);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", kv2BE);


            // 2. Setup the policy to provide the permissions to test against.
            VaultPolicyContainer policyContainer = new VaultPolicyContainer("capa");

            VaultPolicyPathItem vppi1 = new VaultPolicyPathItem(kv2BE, "data/app/appA/*");
            VaultPolicyPathItem vppi2 = new VaultPolicyPathItem(kv2BE + "data/app/appA/subItem/*");
            VaultPolicyPathItem vppi3 = new VaultPolicyPathItem(kv2BE + "metadata/app/appA/*");
            VaultPolicyPathItem vppi4 = new VaultPolicyPathItem(kv2BE + "data/shared/*");

            vppi1.FullControl = true;
            vppi2.FullControl = true;
            vppi3.ReadAllowed = true;
            vppi4.ReadAllowed = true;

            policyContainer.AddPolicyPathObject(vppi1);
            policyContainer.AddPolicyPathObject(vppi2);
            policyContainer.AddPolicyPathObject(vppi3);
            policyContainer.AddPolicyPathObject(vppi4);

            await _vaultSystemBackend.SysPoliciesACLCreate(policyContainer);


            // 3. Now create an App Role & Secret ID
            string  roleName = _uniqueKeys.GetKey("role");
            AppRole appRole  = new AppRole(roleName);

            appRole.Policies.Add(policyContainer.Name);
            appRole = await authEngine.SaveRoleAndReturnRoleObject(appRole);

            AppRoleSecret secretID = await authEngine.CreateSecretID(appRole.Name);


            // 4.  Now we can create a token against that
            Token token = await authEngine.Login(appRole.RoleID, secretID.ID);


            // 5.  Now we can finally test the capabilities of that token.
            List <string> paths = new List <string>();
            string        path1 = kv2BE + "/data/app/appA/subItem";
            string        path2 = kv2BE + "/data/app/appB/subItem";
            string        path3 = kv2BE + "/noaccess/app/appA";
            string        path4 = kv2BE + "/data/noaccess/app/appA/subItem";

            paths.Add(path1);
            paths.Add(path2);
            paths.Add(path3);
            paths.Add(path4);



            Dictionary <string, List <string> > permissions;

            permissions = await _vaultSystemBackend.GetTokenCapabilityOnPaths(token.ID, paths);

            // 6. Validate the results.
            Assert.AreEqual(4, permissions.Count, "A10:  Expected to receive 4 permission objects back.");
            Assert.AreEqual(6, permissions[path1].Count, "A20:  Expected the item: " + path1 + " to contain 6 permissions.");
            Assert.AreEqual(1, permissions[path2].Count, "A30:  Expected the item: " + path2 + " to contain 1 deny permission.");
            CollectionAssert.Contains(permissions[path2], "deny", "A35:  Expected the permission to be deny for path: " + path2);
            Assert.AreEqual(1, permissions[path3].Count, "A40:  Expected the item: " + path3 + " to contain 1 deny permission.");
            CollectionAssert.Contains(permissions[path3], "deny", "A35:  Expected the permission to be deny for path: " + path3);
            Assert.AreEqual(1, permissions[path4].Count, "A40:  Expected the item: " + path4 + " to contain 1 deny permission.");
            CollectionAssert.Contains(permissions[path4], "deny", "A35:  Expected the permission to be deny for path: " + path4);
        }