示例#1
0
        public async Task AppRoleLoginConnector_Test()
        {
            // PRE-Test

            VaultSystemBackend vaultSystemBackend = new VaultSystemBackend(_vault.TokenID, _vault);
            string             approleMountName   = _UK.GetKey("AppAuth");

            // Create an AppRole authentication connection.
            AppRoleAuthEngine appRoleAuthEngine = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, "AppRole", approleMountName);


            // Create an Authentication method of App Role.	- This only needs to be done when the Auth method is created.
            AuthMethod am = new AuthMethod(approleMountName, EnumAuthMethods.AppRole);
            bool       rc = await vaultSystemBackend.AuthEnable(am);

            string  rName = _UK.GetKey("Role");
            AppRole roleA = new AppRole(rName);

            Assert.True(await appRoleAuthEngine.SaveRole(roleA));

            string roleID = await appRoleAuthEngine.ReadRoleID(roleA.Name);

            // Now create the a secret
            AppRoleSecret secret_A = await appRoleAuthEngine.GenerateSecretID(roleA.Name);


            // ACTUAL TEST
            // Create Login Connector
            AppRoleLoginConnector loginConnector = new AppRoleLoginConnector(_vault, approleMountName, "Test AppRole", roleID, secret_A.ID);
            bool result = await loginConnector.Connect(true);

            Assert.IsTrue(result, "A10:  Login Failed");
        }
示例#2
0
        public async Task MountDefaultAppRoleMount_Success()
        {
            AppRoleAuthEngine defaultBE = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole);
            AuthMethod        defaultAM = new AuthMethod(defaultBE.MountPoint, EnumAuthMethods.AppRole);

            try {
                Assert.True(await _vaultSystemBackend.AuthEnable(defaultAM));
            }
            catch (VaultException e) {
                if (e.SpecificErrorCode == EnumVaultExceptionCodes.BackendMountAlreadyExists)
                {
                    // Disable and re-enable to confirm we can do this.
                    Assert.True(await _vaultSystemBackend.AuthDisable(defaultAM));
                    Assert.True(await _vaultSystemBackend.AuthEnable(defaultAM));
                }
                else
                {
                    Assert.Fail("Unexpected Vault Error - " + e.Message);
                }
            }
            catch (Exception e) {
                Assert.Fail("Unexpected error from Vault: " + e.Message);
            }


            string  name = _uniqueKeys.GetKey("RoleDef");
            AppRole ar   = new AppRole(name);

            Assert.True(await _appRoleAuthEngine.SaveRole(ar));
        }
示例#3
0
        public async Task LoginWithValidCredentials_Success()
        {
            string  roleName_A = _uniqueKeys.GetKey("RLogin");
            AppRole roleA      = new AppRole(roleName_A);

            Assert.True(await _appRoleAuthEngine.SaveRole(roleA), "A1: Saving the role failed.");

            // Read the role ID back.
            string roleID = await _appRoleAuthEngine.ReadRoleID(roleA.Name);

            // Now create the a secret
            AppRoleSecret secret_A = await _appRoleAuthEngine.GenerateSecretID(roleA.Name);


            // Now attempt to login - We need to create a new vault object or else we will screw with the other tests, since a successful login changes the token.
            VaultAgentAPI     v    = new VaultAgentAPI("logintest", VaultServerRef.vaultURI);
            AppRoleAuthEngine eng1 = (AppRoleAuthEngine)v.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, "Test", _appRoleAuthEngine.MountPoint);

            Token token = await eng1.Login(roleID, secret_A.ID);

/*		    bool rc;
 *                  rc = await _appRoleAuthEngine.Login(roleID, secret_A.ID);
 *
 *                  Assert.True(rc);
 */
            Assert.IsNotNull(token, "A1:  A token was not returned.  The login failed.");
            Assert.IsNotEmpty(token.ID, "A2:  A token was returned, but it did not have an ID value.");
        }
示例#4
0
        /// <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); }
        }
示例#5
0
        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,)
        }
示例#6
0
        public VC_AppRoleAuthEngine(VaultAgentAPI vaultAgent)
        {
            UniqueKeys uniqueKeys = new UniqueKeys();

            // We will create a unique App Role Authentication Engine with the given name.
            _AppBEName          = "BEAppRole";
            _vaultAgent         = vaultAgent;
            _vaultSystemBackend = new VaultSystemBackend(_vaultAgent.TokenID, _vaultAgent);
            _appRoleAuthEngine  = (AppRoleAuthEngine)vaultAgent.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
            _idEngine           = (IdentitySecretEngine)vaultAgent.ConnectToSecretBackend(EnumSecretBackendTypes.Identity);
        }
示例#7
0
        public async Task Run()
        {
            await CreateBackendMounts();

            _appRoleAuthEngine = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _beAuthName, _beAuthName);
            _idEngine          = (IdentitySecretEngine)_vault.ConnectToSecretBackend(EnumSecretBackendTypes.Identity);
            _kv2SecretEngine   =
                (KV2SecretEngine)_vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "KV2 Secrets", _beKV2Name);



            await AppRoleBE_UpdateRoleID();

            Console.WriteLine("Finished With Optimization Run.  Press any key to continue.");
            Console.ReadKey();
        }
示例#8
0
        public async Task EnablingABackendTwice_ProducesExpectedError()
        {
            string            engineName  = _uniqueKeys.GetKey("engA");
            AppRoleAuthEngine engA        = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, engineName, engineName);
            AuthMethod        authMethodA = new AuthMethod(engA.MountPoint, EnumAuthMethods.AppRole);

            // First time should succed.  Second should fail.
            for (int i = 0; i < 2; i++)
            {
                try {
                    Assert.True((await _vaultSystemBackend.AuthEnable(authMethodA)));
                }
                catch (VaultException e) {
                    Assert.AreEqual(e.SpecificErrorCode, EnumVaultExceptionCodes.BackendMountAlreadyExists);
                }
            }
        }
示例#9
0
        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++;
        }
        /// <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>
        /// Performs tasks that the teen wants to to.
        /// </summary>
        /// <returns></returns>
        private async Task Perform_TeenTasks()
        {
            // We cannot use the Vault Agent _masterVaultAgent, since it has the Master Token tied to it.  We will create a new VaultAgent and SecretEngine for use during this Task, which will have our
            // Mother role token AND not the master Token.
            // So, we wire up a new Vault, AppRole and Secret Engines AND use them throughout this routine.
            VaultAgentAPI     vault        = new VaultAgentAPI("TeenConnector", _masterVaultAgent.Uri);
            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beKV2Name, _beKV2Name);


            // Login.
            Token token = await authEngine.Login(roleTeenager.RoleID, _sidTeenager.ID);



            // Should be able to load the House Secret.  But not updated it.
            KV2Secret a = await secretEngine.ReadSecret <KV2Secret>(HOUSE.HOUSE_PATH);

            a.Attributes["Electric"] = "No";
            // Should Fail
            bool rc = await SaveSecret(secretEngine, a);


            // Should NOT be able to read anything in the Toddler's Bedroom
            (bool rcB, KV2Secret b) = await ReadSecret(secretEngine, HOUSE.TODDLER_BEDROOM);

            // Should be able to read and update the Kitchen secret
            (bool rcK, KV2Secret k) = await ReadSecret(secretEngine, HOUSE.KITCHEN);

            k.Attributes["Carrots"] = "Need";
            rcK = await SaveSecret(secretEngine, k);

            // Should be able to read and update the Fridge
            (bool rcR, KV2Secret r) = await ReadSecret(secretEngine, HOUSE.REFRIGERATOR);

            k.Attributes["Cold"] = "True";
            rcR = await SaveSecret(secretEngine, r);

            // Should have no writes to the Dishwasher
            (bool rcD, KV2Secret d) = await ReadSecret(secretEngine, HOUSE.DISHWASHER);
        }
示例#12
0
        public async Task AppRoleAuthEngineSetup()
        {
            // Build Connection to Vault.
            _vault = await VaultServerRef.ConnectVault("AppRoleVault");

            //_vault = new VaultAgentAPI("AppRoleVault", VaultServerRef.ipAddress, VaultServerRef.ipPort);  //, VaultServerRef.rootToken,true);
            _vaultSystemBackend = new VaultSystemBackend(_vault.TokenID, _vault);


            string approleMountName = _uniqueKeys.GetKey("AppAuth");


            // Create an AppRole authentication connection.
            _appRoleAuthEngine = (AppRoleAuthEngine)_vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, "AppRole", approleMountName);


            // Create an Authentication method of App Role.	- This only needs to be done when the Auth method is created.
            AuthMethod am = new AuthMethod(approleMountName, EnumAuthMethods.AppRole);
            bool       rc = await _vaultSystemBackend.AuthEnable(am);
        }
示例#13
0
        public async Task Setup()
        {
            string rootToken = "tokenA";
            string ip        = "127.0.0.1";
            int    port      = 47002;

            Uri vaultURI = new Uri("http://" + ip + ":" + port);

            // Connect to Vault, add an authentication backend of AppRole.
            _vaultAgent = new VaultAgentAPI("Vault", vaultURI);

            TokenLoginConnector loginConnector = new TokenLoginConnector(_vaultAgent, "Token Authenticator", rootToken);

            await CreateBackendMounts();

            _appRoleAuthEngine = (AppRoleAuthEngine)_vaultAgent.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _beAuthName, _beAuthName);
            _secretEngine      = (KV2SecretEngine)_vaultAgent.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, "Benchmarking KV2 Secrets", _beKV2Name);

            await SetupRoles();
        }
示例#14
0
        /// <summary>
        /// Performs tasks that the Role1 user would do.  Creating the actual application folders.
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task PerformRole2Tasks()
        {
            try {
                // We just try and read secrets off path1/ folders.

                // 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, "Sheakley KV2 Secrets", _beKV2Name);


                // Now login.
                Token token = await authEngine.Login(role2.RoleID, _SIDRole2.ID);

                // Try and read a secret.
            }
            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); }
        }
        /// <summary>
        /// Perform tasks the mother wants to do
        /// </summary>
        /// <returns></returns>
        private async Task Perform_MotherTasks()
        {
            // We cannot use the Vault Agent _masterVaultAgent, since it has the Master Token tied to it.  We will create a new VaultAgent and SecretEngine for use during this Task, which will have our
            // Mother role token AND not the master Token.
            // So, we wire up a new Vault, AppRole and Secret Engines AND use them throughout this routine.
            VaultAgentAPI     vault        = new VaultAgentAPI("MotherConnector", _masterVaultAgent.Uri);
            AppRoleAuthEngine authEngine   = (AppRoleAuthEngine)vault.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, _AppBEName, _AppBEName);
            KV2SecretEngine   secretEngine =
                (KV2SecretEngine)vault.ConnectToSecretBackend(EnumSecretBackendTypes.KeyValueV2, _beKV2Name, _beKV2Name);


            // Login.
            Token token = await authEngine.Login(roleMother.RoleID, _sidMother.ID);

            // Load the house secret, modify it and save it.
            KV2Secret a = await secretEngine.ReadSecret <KV2Secret>(HOUSE.HOUSE_PATH);

            a.Attributes.Add("Electric", "Yes");
            await SaveSecret(secretEngine, a);

            // Create the Kitchen
            KV2Secret b = new KV2Secret(HOUSE.KITCHEN);

            b.Attributes.Add("Dishwasher", "Yes");
            await SaveSecret(secretEngine, b);

            // Refrigerator
            KV2Secret c = new KV2Secret(HOUSE.REFRIGERATOR);

            c.Attributes.Add("Milk", "Chocolate");
            c.Attributes.Add("Cheese", "American");
            await SaveSecret(secretEngine, c);

            // DishWasher
            KV2Secret c1 = new KV2Secret(HOUSE.DISHWASHER);

            c1.Attributes.Add("Drawers", "3");
            await SaveSecret(secretEngine, c1);

            // Garage
            KV2Secret d = new KV2Secret(HOUSE.GARAGE);

            d.Attributes.Add("Car", "Porsche");
            await SaveSecret(secretEngine, d);

            // Master Bedroom
            KV2Secret e = new KV2Secret(HOUSE.MASTER_BEDROOM);

            e.Attributes.Add("Safe", "Yes");
            await SaveSecret(secretEngine, e);

            // Teen Bedroom
            KV2Secret f = new KV2Secret(HOUSE.TEEN_BEDROOM);

            f.Attributes.Add("CarPoster", "Yes");
            await SaveSecret(secretEngine, f);

            // Toddler Bedroom
            KV2Secret g = new KV2Secret(HOUSE.TODDLER_BEDROOM);

            g.Attributes.Add("BabyMonitor", "On");
            await SaveSecret(secretEngine, g);
        }
示例#16
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);
        }
示例#17
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));
        }
        public async Task SetupAliasTestConditions()
        {
            lock (locking) {
                while (bLocking == true)
                {
                    Thread.Sleep(100);
                }

                // Set lock to true.
                bLocking = true;
            }

            string AppRoleEngine = "appRoleTST";

            try {
                // If already done this during this test run, then no need to do again.
                if (_appRoleAccessor != "")
                {
                    return;
                }

                // We need A role based Auth engine so we can test the Alias functionality.  This is a constant value.  If we can't find it then we create it.

                AuthMethod authMethod = null;
                while (authMethod == null)
                {
                    VaultSystemBackend vaultSystemBackend       = new VaultSystemBackend(_vaultAgentAPI.TokenID, _vaultAgentAPI);
                    Dictionary <string, AuthMethod> authMethods = await vaultSystemBackend.AuthListAll();

                    // See if the AppRole Backend exists.  We need to add a trailing slash because vault returns the key with a trailing slash.  Swallow exception not found.
                    try { authMethod = authMethods[AppRoleEngine + "/"]; }
                    catch (KeyNotFoundException) { }

                    if (authMethod == null)
                    {
                        AuthMethod am = new AuthMethod(AppRoleEngine, EnumAuthMethods.AppRole);
                        bool       rc = await vaultSystemBackend.AuthEnable(am);

                        Thread.Sleep(60);
                    }
                }

                // Connect the AppRole Authentication engine.
                _appRoleAuthEngine =
                    (AppRoleAuthEngine)_vaultAgentAPI.ConnectAuthenticationBackend(EnumBackendTypes.A_AppRole, AppRoleEngine, AppRoleEngine);

                // Store the accessor for use in entity-alias tests and to alert that we completed this setup task.
                _appRoleAccessor = authMethod.Accessor;
            }

            catch (Exception) { Assert.False(true, "[SetupAliasTestConditions]  Try block errored"); }
            finally {
                lock (locking) { bLocking = false; }
            }


            //TestContext.WriteLine("Role Name:     {0}", _theRole.Name);
            //TestContext.WriteLine("Role ID:       {0}", _theRole.RoleID);
            TestContext.WriteLine("Role Backend:  {0}", AppRoleEngine);
            TestContext.WriteLine("Role Accessor: {0}", _appRoleAccessor);
        }