public override void ExecuteCmdlet()
        {
            if (ShouldProcess(VaultName, Properties.Resources.CreateKeyVault))
            {
                if (VaultExistsInCurrentSubscription(this.VaultName))
                {
                    throw new ArgumentException(PSKeyVaultProperties.Resources.VaultAlreadyExists);
                }

                var userObjectId = string.Empty;
                AccessPolicyEntry accessPolicy = null;

                try
                {
                    userObjectId = GetCurrentUsersObjectId();
                }
                catch (Exception ex)
                {
                    // Show the graph exceptions as a warning, but still proceed to create a vault with no access policy
                    // This is to unblock Key Vault in Fairfax as Graph has issues in this environment.
                    WriteWarning(ex.Message);
                }
                if (!string.IsNullOrWhiteSpace(userObjectId))
                {
                    accessPolicy = new AccessPolicyEntry()
                    {
                        TenantId    = GetTenantId(),
                        ObjectId    = userObjectId,
                        Permissions = new Permissions
                        {
                            Keys         = DefaultPermissionsToKeys,
                            Secrets      = DefaultPermissionsToSecrets,
                            Certificates = DefaultPermissionsToCertificates
                        }
                    };
                }

                var newVault = KeyVaultManagementClient.CreateNewVault(new PSKeyVaultModels.VaultCreationParameters()
                {
                    VaultName                    = this.VaultName,
                    ResourceGroupName            = this.ResourceGroupName,
                    Location                     = this.Location,
                    EnabledForDeployment         = this.EnabledForDeployment.IsPresent,
                    EnabledForTemplateDeployment = EnabledForTemplateDeployment.IsPresent,
                    EnabledForDiskEncryption     = EnabledForDiskEncryption.IsPresent,
                    SkuFamilyName                = DefaultSkuFamily,
                    SkuName      = this.Sku,
                    TenantId     = GetTenantId(),
                    AccessPolicy = accessPolicy,
                    Tags         = this.Tag
                },
                                                                       ActiveDirectoryClient
                                                                       );

                this.WriteObject(newVault);

                if (accessPolicy == null)
                {
                    WriteWarning(PSKeyVaultProperties.Resources.VaultNoAccessPolicyWarning);
                }
            }
        }
Example #2
0
        private static KeyBundle CreateKeyVaultKeyAccessibleByIdentity(SqlManagementTestContext context,
                                                                       ResourceGroup resourceGroup, ResourceIdentity identity)
        {
            var sqlClient = context.GetClient <SqlManagementClient>();
            var keyVaultManagementClient = context.GetClient <KeyVaultManagementClient>();
            var keyVaultClient           = TestEnvironmentUtilities.GetKeyVaultClient();

            // Prepare vault permissions for the server
            var permissions = new Permissions()
            {
                Keys = new List <string>()
                {
                    KeyPermissions.WrapKey,
                    KeyPermissions.UnwrapKey,
                    KeyPermissions.Get,
                    KeyPermissions.List
                }
            };

            var aclEntry = new AccessPolicyEntry(identity.TenantId.Value,
                                                 identity.PrincipalId.Value.ToString(), permissions);

            // Prepare vault permissions for the app used in this test
            var appPermissions = new Permissions()
            {
                Keys = new List <string>()
                {
                    KeyPermissions.Create,
                    KeyPermissions.Delete,
                    KeyPermissions.Get,
                    KeyPermissions.List
                }
            };
            string authObjectId = TestEnvironmentUtilities.GetUserObjectId();
            var    aclEntryUser = new AccessPolicyEntry(identity.TenantId.Value, authObjectId, appPermissions);

            // Create a vault
            var accessPolicy = new List <AccessPolicyEntry>()
            {
                aclEntry, aclEntryUser
            };
            string vaultName     = SqlManagementTestUtilities.GenerateName();
            string vaultLocation = TestEnvironmentUtilities.DefaultLocation;
            var    vault         = keyVaultManagementClient.Vaults.CreateOrUpdate(resourceGroup.Name, vaultName,
                                                                                  new VaultCreateOrUpdateParameters()
            {
                Location   = vaultLocation,
                Properties = new VaultProperties()
                {
                    AccessPolicies   = accessPolicy,
                    TenantId         = identity.TenantId.Value,
                    EnableSoftDelete = true
                }
            });

            // Create a key
            // This can be flaky if attempted immediately after creating the vault. Adding short sleep to improve robustness.
            TestUtilities.Wait(TimeSpan.FromSeconds(3));
            string keyName = SqlManagementTestUtilities.GenerateName();

            return(keyVaultClient.CreateKeyAsync(vault.Properties.VaultUri, keyName, JsonWebKeyType.Rsa,
                                                 keyOps: JsonWebKeyOperation.AllOperations).GetAwaiter().GetResult());
        }
        protected async Task Initialize()
        {
            var resourceManagementClient = GetResourceManagementClient();

            ResourcesClient         = resourceManagementClient.Resources;
            ResourceGroupsClient    = resourceManagementClient.ResourceGroups;
            ResourceProvidersClient = resourceManagementClient.Providers;

            var keyVaultManagementClient = GetKeyVaultManagementClient();

            VaultsClient = keyVaultManagementClient.Vaults;

            if (Mode == RecordedTestMode.Playback)
            {
                this.ObjectId = Recording.GetVariable(ObjectIdKey, string.Empty);
            }
            else if (Mode == RecordedTestMode.Record)
            {
                var spClient             = new RbacManagementClient(TestEnvironment.TenantId, TestEnvironment.Credential).ServicePrincipals;
                var servicePrincipalList = spClient.ListAsync($"appId eq '{TestEnvironment.ClientId}'").ToEnumerableAsync().Result;
                foreach (var servicePrincipal in servicePrincipalList)
                {
                    this.ObjectId = servicePrincipal.ObjectId;
                    Recording.GetVariable(ObjectIdKey, this.ObjectId);
                    break;
                }
            }
            var provider = (await ResourceProvidersClient.GetAsync("Microsoft.KeyVault")).Value;

            this.Location = provider.ResourceTypes.Where(
                (resType) =>
            {
                if (resType.ResourceType == "vaults")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
                ).First().Locations.FirstOrDefault();

            ResGroupName = Recording.GenerateAssetName("sdktestrg");
            await ResourceGroupsClient.CreateOrUpdateAsync(ResGroupName, new Management.Resources.Models.ResourceGroup(Location));

            VaultName = Recording.GenerateAssetName("sdktestvault");

            TenantIdGuid = new Guid(TestEnvironment.TenantId);
            Tags         = new Dictionary <string, string> {
                { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" }
            };

            var permissions = new Permissions
            {
                Keys         = { new KeyPermissions("all") },
                Secrets      = { new SecretPermissions("all") },
                Certificates = { new CertificatePermissions("all") },
                Storage      = { new StoragePermissions("all") },
            };

            AccessPolicy = new AccessPolicyEntry(TenantIdGuid, ObjectId, permissions);

            VaultProperties = new VaultProperties(TenantIdGuid, new Sku(SkuFamily.A, SkuName.Standard));

            VaultProperties.EnabledForDeployment         = true;
            VaultProperties.EnabledForDiskEncryption     = true;
            VaultProperties.EnabledForTemplateDeployment = true;
            VaultProperties.EnableSoftDelete             = true;
            VaultProperties.VaultUri    = "";
            VaultProperties.NetworkAcls = new NetworkRuleSet()
            {
                Bypass        = "******",
                DefaultAction = "Allow",
                IpRules       =
                {
                    new IPRule("1.2.3.4/32"),
                    new IPRule("1.0.0.0/25")
                }
            };
            VaultProperties.AccessPolicies.Add(AccessPolicy);
        }
        protected Vault CreateKeyVault(string clusterName, string vaultName, string vaultLocation, string resouceGroupName)
        {
            var userObjectId = string.Empty;
            AccessPolicyEntry accessPolicy = null;

            try
            {
                userObjectId = GetCurrentUserObjectId();
            }
            catch (Exception e)
            {
                WriteWarning(e.Message);
            }

            if (!string.IsNullOrWhiteSpace(userObjectId))
            {
                accessPolicy = new AccessPolicyEntry()
                {
                    TenantId    = GetTenantId(DefaultContext),
                    ObjectId    = userObjectId,
                    Permissions = new Permissions
                    {
                        Keys         = DefaultPermissionsToKeys,
                        Secrets      = DefaultPermissionsToSecrets,
                        Certificates = DefaultPermissionsToCertificates
                    }
                };
            }

            var keyVaultParameter = new VaultCreateOrUpdateParameters()
            {
                Location   = vaultLocation,
                Properties = new VaultProperties
                {
                    Sku = new Azure.Commands.Common.KeyVault.Version2016_10_1.Models.Sku
                    {
                        Name = SkuName.Standard,
                    },
                    EnabledForDeployment = true,
                    TenantId             = GetTenantId(DefaultContext),
                    VaultUri             = string.Empty,
                    AccessPolicies       = accessPolicy == null ?
                                           new AccessPolicyEntry[] { } :
                    new[] { accessPolicy }
                },
                Tags = new Dictionary <string, string>()
                {
                    { "clusterName", clusterName },
                    { "resourceType", Constants.ServieFabricTag }
                }
            };

            var vault = KeyVaultManageClient.Vaults.CreateOrUpdate(
                resouceGroupName,
                vaultName,
                keyVaultParameter);

            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(NewCreatedKeyVaultWaitTimeInSec));

            if (accessPolicy == null)
            {
                WriteWarning(ServiceFabricProperties.Resources.VaultCreatedWithOutAccessPolicy);
            }

            return(vault);
        }
 public AccessPolicyEntryItem(int index, AccessPolicyEntry ape)
 {
     Index = index;
     _ape  = ape;
 }
Example #6
0
        public void KeyVaultManagementVaultCreateUpdateDelete()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var testBase = new KeyVaultTestBase(context);
                var client   = testBase.client;

                string rgName = TestUtilities.GenerateName("sdktestrg");
                testBase.resourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup {
                    Location = testBase.location
                });

                string vaultName    = TestUtilities.GenerateName("sdktestvault");
                var    tenantIdGuid = Guid.Parse(testBase.tenantId);
                var    objectIdGuid = Guid.Parse(testBase.objectId);
                var    tags         = new Dictionary <string, string> {
                    { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" }
                };
                var accPol = new AccessPolicyEntry
                {
                    TenantId    = tenantIdGuid,
                    ObjectId    = objectIdGuid,
                    Permissions = new Permissions
                    {
                        Keys         = new string[] { "all" },
                        Secrets      = null,
                        Certificates = new string[] { "all" }
                    }
                };
                var createdVault = client.Vaults.CreateOrUpdate(
                    resourceGroupName: rgName,
                    vaultName: vaultName,
                    parameters: new VaultCreateOrUpdateParameters
                {
                    Location   = testBase.location,
                    Tags       = tags,
                    Properties = new VaultProperties
                    {
                        EnabledForDeployment         = true,
                        EnabledForDiskEncryption     = true,
                        EnabledForTemplateDeployment = true,
                        Sku = new Microsoft.Azure.Management.KeyVault.Models.Sku {
                            Name = SkuName.Standard
                        },
                        TenantId       = tenantIdGuid,
                        VaultUri       = "",
                        AccessPolicies = new[]
                        {
                            accPol
                        }
                    }
                }
                    );

                ValidateVault(createdVault,
                              vaultName,
                              rgName,
                              testBase.subscriptionId,
                              tenantIdGuid,
                              testBase.location,
                              "A",
                              SkuName.Standard,
                              true,
                              true,
                              true,
                              new[] { accPol },
                              tags);

                //Update

                createdVault.Properties.Sku.Name       = SkuName.Premium;
                accPol.Permissions.Secrets             = new string[] { "get", "set" };
                accPol.Permissions.Keys                = null;
                createdVault.Properties.AccessPolicies = new[] { accPol };

                var updateVault = client.Vaults.CreateOrUpdate(
                    resourceGroupName: rgName,
                    vaultName: vaultName,
                    parameters: new VaultCreateOrUpdateParameters
                {
                    Location   = testBase.location,
                    Tags       = tags,
                    Properties = createdVault.Properties
                }
                    );

                ValidateVault(updateVault,
                              vaultName,
                              rgName,
                              testBase.subscriptionId,
                              tenantIdGuid,
                              testBase.location,
                              "A",
                              SkuName.Premium,
                              true,
                              true,
                              true,
                              new[] { accPol },
                              tags);

                var retrievedVault = client.Vaults.Get(
                    resourceGroupName: rgName,
                    vaultName: vaultName);

                ValidateVault(retrievedVault,
                              vaultName,
                              rgName,
                              testBase.subscriptionId,
                              tenantIdGuid,
                              testBase.location,
                              "A",
                              SkuName.Premium,
                              true,
                              true,
                              true,
                              new[] { accPol },
                              tags);

                // Delete
                client.Vaults.Delete(
                    resourceGroupName: rgName,
                    vaultName: vaultName);

                Assert.Throws <CloudException>(() =>
                {
                    client.Vaults.Get(
                        resourceGroupName: rgName,
                        vaultName: vaultName);
                });
            }
        }
Example #7
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string _azureToken      = request.DataStore.GetJson("AzureToken")["access_token"].ToString();
            string subscriptionID   = request.DataStore.GetJson("SelectedSubscription")["SubscriptionId"].ToString();
            string resourceGroup    = request.DataStore.GetValue("SelectedResourceGroup");
            string vaultName        = request.DataStore.GetValue("VaultName") ?? "bpst-mscrm-vault";
            string secretName       = request.DataStore.GetValue("SecretName") ?? "bpst-mscrm-secret";
            string connectionString = request.DataStore.GetAllValues("SqlConnectionString")[0];
            string organizationId   = request.DataStore.GetValue("OrganizationId");
            string tenantId         = request.DataStore.GetValue("TenantId") ?? "72f988bf-86f1-41af-91ab-2d7cd011db47";

            SubscriptionCloudCredentials credentials = new TokenCloudCredentials(subscriptionID, _azureToken);

            using (KeyVaultManagementClient client = new KeyVaultManagementClient(credentials))
            {
                // Check if a vault already exists
                Vault             vault  = null;
                VaultListResponse vaults = client.Vaults.List(resourceGroup, 100);
                foreach (var v in vaults.Vaults)
                {
                    if (v.Name.EqualsIgnoreCase(vaultName))
                    {
                        vault = (Vault)v;
                        break;
                    }
                }

                AccessPolicyEntry ape = new AccessPolicyEntry
                {
                    PermissionsToSecrets = new[] { "get" },
                    ApplicationId        = _crmServicePrincipal,
                    ObjectId             = _crmServicePrincipal
                };

                // Create the vault
                if (vault == null)
                {
                    using (ResourceManagementClient resourceClient = new ResourceManagementClient(credentials))
                    {
                        // Set properties
                        VaultProperties p = new VaultProperties();
                        p.Sku = new Sku()
                        {
                            Family = "A", Name = "standard"
                        };
                        p.TenantId = new Guid(tenantId);

                        // Set who has permission to read this
                        p.AccessPolicies.Add(ape);

                        VaultCreateOrUpdateParameters vaultParams = new VaultCreateOrUpdateParameters()
                        {
                            Location   = resourceClient.ResourceGroups.Get(resourceGroup).ResourceGroup.Location,
                            Properties = p
                        };
                        vault = client.Vaults.CreateOrUpdate(resourceGroup, vaultName, vaultParams).Vault;
                    }
                }
                else
                {
                    // Set who has permission to read this
                    vault.Properties.AccessPolicies.Add(ape);
                }

                // Create the secret
                KeyVaultClient kvClient = new KeyVaultClient(GetAccessToken);

                Secret secret = await kvClient.SetSecretAsync(vault.Properties.VaultUri, secretName, connectionString, new Dictionary <string, string>() { { organizationId, tenantId } },
                                                              null, new SecretAttributes()
                {
                    Enabled = true
                });

                request.DataStore.AddToDataStore("KeyVault", secret.Id, DataStoreType.Private);
                return(new ActionResponse(ActionStatus.Success, secret.Id, true));
            }
        }
Example #8
0
        protected async Task Initialize()
        {
            Location     = "westcentralus";
            Client       = GetArmClient();
            Subscription = await Client.GetDefaultSubscriptionAsync();

            DeletedVaultCollection = Subscription.GetDeletedVaults();

            if (Mode == RecordedTestMode.Playback)
            {
                this.ObjectId = Recording.GetVariable(ObjectIdKey, string.Empty);
            }
            else if (Mode == RecordedTestMode.Record)
            {
                var spClient             = new RbacManagementClient(TestEnvironment.TenantId, TestEnvironment.Credential).ServicePrincipals;
                var servicePrincipalList = spClient.ListAsync($"appId eq '{TestEnvironment.ClientId}'").ToEnumerableAsync().Result;
                foreach (var servicePrincipal in servicePrincipalList)
                {
                    this.ObjectId = servicePrincipal.ObjectId;
                    Recording.GetVariable(ObjectIdKey, this.ObjectId);
                    break;
                }
            }

            ResGroupName = Recording.GenerateAssetName("sdktestrg-kv-");
            var rgResponse = await Subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, ResGroupName, new ResourceGroupData(Location)).ConfigureAwait(false);

            ResourceGroupResource = rgResponse.Value;

            VaultCollection = ResourceGroupResource.GetVaults();
            VaultName       = Recording.GenerateAssetName("sdktest-vault-");
            TenantIdGuid    = new Guid(TestEnvironment.TenantId);
            Tags            = new Dictionary <string, string> {
                { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" }
            };

            var permissions = new AccessPermissions
            {
                Keys         = { new KeyPermissions("all") },
                Secrets      = { new SecretPermissions("all") },
                Certificates = { new CertificatePermissions("all") },
                Storage      = { new StoragePermissions("all") },
            };

            AccessPolicy = new AccessPolicyEntry(TenantIdGuid, ObjectId, permissions);

            VaultProperties = new VaultProperties(TenantIdGuid, new KeyVaultSku(KeyVaultSkuFamily.A, KeyVaultSkuName.Standard));

            VaultProperties.EnabledForDeployment         = true;
            VaultProperties.EnabledForDiskEncryption     = true;
            VaultProperties.EnabledForTemplateDeployment = true;
            VaultProperties.EnableSoftDelete             = true;
            VaultProperties.VaultUri    = new Uri("http://vaulturi.com");
            VaultProperties.NetworkAcls = new NetworkRuleSet()
            {
                Bypass        = "******",
                DefaultAction = "Allow",
                IPRules       =
                {
                    new IPRule("1.2.3.4/32"),
                    new IPRule("1.0.0.0/25")
                }
            };
            VaultProperties.AccessPolicies.Add(AccessPolicy);

            ManagedHsmCollection = ResourceGroupResource.GetManagedHsms();
            ManagedHsmProperties = new ManagedHsmProperties();
            ManagedHsmProperties.InitialAdminObjectIds.Add(ObjectId);
            ManagedHsmProperties.CreateMode            = CreateMode.Default;
            ManagedHsmProperties.EnablePurgeProtection = false;
            ManagedHsmProperties.EnableSoftDelete      = true;
            ManagedHsmProperties.NetworkAcls           = new MhsmNetworkRuleSet()
            {
                Bypass        = "******",
                DefaultAction = "Deny" //Property properties.networkAcls.ipRules is not supported currently and must be set to null.
            };
            ManagedHsmProperties.PublicNetworkAccess       = PublicNetworkAccess.Disabled;
            ManagedHsmProperties.SoftDeleteRetentionInDays = 10;
            ManagedHsmProperties.TenantId = TenantIdGuid;
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(Name, Properties.Resources.CreateKeyVault))
            {
                if (VaultExistsInCurrentSubscription(Name))
                {
                    throw new ArgumentException(Resources.VaultAlreadyExists);
                }

                var userObjectId = string.Empty;
                AccessPolicyEntry accessPolicy = null;

                try
                {
                    userObjectId = GetCurrentUsersObjectId();
                }
                catch (Exception ex)
                {
                    // Show the graph exceptions as a warning, but still proceed to create a vault with no access policy
                    // This is to unblock Key Vault in Fairfax as Graph has issues in this environment.
                    WriteWarning(ex.Message);
                }

                if (!string.IsNullOrWhiteSpace(userObjectId))
                {
                    accessPolicy = new AccessPolicyEntry()
                    {
                        TenantId    = GetTenantId(),
                        ObjectId    = userObjectId,
                        Permissions = new Permissions
                        {
                            Keys         = DefaultPermissionsToKeys,
                            Secrets      = DefaultPermissionsToSecrets,
                            Certificates = DefaultPermissionsToCertificates,
                            Storage      = DefaultPermissionsToStorage
                        }
                    };
                }

                var newVault = KeyVaultManagementClient.CreateNewVault(new VaultCreationOrUpdateParameters()
                {
                    Name = this.Name,
                    ResourceGroupName            = this.ResourceGroupName,
                    Location                     = this.Location,
                    EnabledForDeployment         = this.EnabledForDeployment.IsPresent,
                    EnabledForTemplateDeployment = EnabledForTemplateDeployment.IsPresent,
                    EnabledForDiskEncryption     = EnabledForDiskEncryption.IsPresent,
                    EnableSoftDelete             = null,
                    EnablePurgeProtection        = EnablePurgeProtection.IsPresent ? true : (bool?)null, // false is not accepted
                    EnableRbacAuthorization      = EnableRbacAuthorization.IsPresent,

                    /*
                     * If retention days is not specified, use the default value,
                     * else use the vault user provides
                     */
                    SoftDeleteRetentionInDays = this.IsParameterBound(c => c.SoftDeleteRetentionInDays)
                            ? SoftDeleteRetentionInDays
                            : Constants.DefaultSoftDeleteRetentionDays,
                    SkuFamilyName = DefaultSkuFamily,
                    SkuName       = this.Sku,
                    TenantId      = GetTenantId(),
                    AccessPolicy  = accessPolicy,
                    NetworkAcls   = new NetworkRuleSet(),   // New key-vault takes in default network rule set
                    Tags          = this.Tag
                },
                                                                       ActiveDirectoryClient,
                                                                       NetworkRuleSet);

                this.WriteObject(newVault);

                if (accessPolicy == null)
                {
                    WriteWarning(Resources.VaultNoAccessPolicyWarning);
                }
            }
        }
Example #10
0
        public void KeyVaultManagementVaultCreateUpdateDelete()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                var testBase = new KeyVaultTestBase();
                var client   = testBase.client;

                string rgName = TestUtilities.GenerateName("sdktestrg");
                testBase.resourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup {
                    Location = testBase.location
                });

                string vaultName    = TestUtilities.GenerateName("sdktestvault");
                var    tenantIdGuid = Guid.Parse(testBase.tenantId);
                var    objectIdStr  = testBase.objectId;
                var    tags         = new Dictionary <string, string> {
                    { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" }
                };
                var accPol = new AccessPolicyEntry
                {
                    TenantId             = tenantIdGuid,
                    ObjectId             = objectIdStr,
                    PermissionsToKeys    = new string[] { "all" },
                    PermissionsToSecrets = null
                };
                var createResponse = client.Vaults.CreateOrUpdate(
                    resourceGroupName: rgName,
                    vaultName: vaultName,
                    parameters: new VaultCreateOrUpdateParameters
                {
                    Location   = testBase.location,
                    Tags       = tags,
                    Properties = new VaultProperties
                    {
                        EnabledForDeployment         = true,
                        EnabledForDiskEncryption     = true,
                        EnabledForTemplateDeployment = true,
                        Sku = new Sku {
                            Family = "A", Name = "Standard"
                        },
                        TenantId       = tenantIdGuid,
                        VaultUri       = "",
                        AccessPolicies = new[]
                        {
                            accPol
                        }
                    }
                }
                    );

                ValidateVaultGetResponse(createResponse,
                                         vaultName,
                                         rgName,
                                         testBase.subscriptionId,
                                         tenantIdGuid,
                                         testBase.location,
                                         "A",
                                         "Standard",
                                         true,
                                         true,
                                         true,
                                         new[] { accPol },
                                         tags);

                //Update

                createResponse.Vault.Properties.Sku.Name = "Premium";
                accPol.PermissionsToSecrets = new string[] { "get", "set" };
                accPol.PermissionsToKeys    = null;
                createResponse.Vault.Properties.AccessPolicies = new[] { accPol };

                var updateResponse = client.Vaults.CreateOrUpdate(
                    resourceGroupName: rgName,
                    vaultName: vaultName,
                    parameters: new VaultCreateOrUpdateParameters
                {
                    Location   = testBase.location,
                    Tags       = tags,
                    Properties = createResponse.Vault.Properties
                }
                    );

                ValidateVaultGetResponse(updateResponse,
                                         vaultName,
                                         rgName,
                                         testBase.subscriptionId,
                                         tenantIdGuid,
                                         testBase.location,
                                         "A",
                                         "Premium",
                                         true,
                                         true,
                                         true,
                                         new[] { accPol },
                                         tags);

                var getResponse = client.Vaults.Get(
                    resourceGroupName: rgName,
                    vaultName: vaultName);

                ValidateVaultGetResponse(getResponse,
                                         vaultName,
                                         rgName,
                                         testBase.subscriptionId,
                                         tenantIdGuid,
                                         testBase.location,
                                         "A",
                                         "Premium",
                                         true,
                                         true,
                                         true,
                                         new[] { accPol },
                                         tags);

                // Delete
                var deleteResponse = client.Vaults.Delete(
                    resourceGroupName: rgName,
                    vaultName: vaultName);

                Assert.Throws <CloudException>(() =>
                {
                    client.Vaults.Get(
                        resourceGroupName: rgName,
                        vaultName: vaultName);
                });
            }
        }
Example #11
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string azureToken       = request.DataStore.GetJson("AzureTokenKV", "access_token");
            string refreshToken     = request.DataStore.GetJson("AzureTokenKV", "refresh_token");
            string crmToken         = request.DataStore.GetJson("MsCrmToken", "access_token");
            string resourceGroup    = request.DataStore.GetValue("SelectedResourceGroup");
            string vaultName        = request.DataStore.GetValue("VaultName") ?? "bpstv-" + RandomGenerator.GetRandomLowerCaseCharacters(12);
            string secretName       = request.DataStore.GetValue("SecretName") ?? "bpst-mscrm-secret";
            string connectionString = request.DataStore.GetAllValues("SqlConnectionString")[0];
            string organizationId   = request.DataStore.GetValue("OrganizationId");

            _subscriptionId = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId");

            RetrieveKVToken(refreshToken, request.Info.WebsiteRootUrl, request.DataStore);
            RetrieveGraphToken(refreshToken, request.Info.WebsiteRootUrl, request.DataStore);

            SubscriptionCloudCredentials credentials = new TokenCloudCredentials(_subscriptionId, azureToken);


            // Get user's object ID and tenant ID (in the Azure subscription where the vault is created)
            string oid       = null;
            int    propCount = 0;

            foreach (var c in new JwtSecurityToken(azureToken).Claims)
            {
                switch (c.Type.ToLowerInvariant())
                {
                case "oid":
                    oid = c.Value;
                    propCount++;
                    break;

                case "tid":
                    _tenantId = c.Value;
                    propCount++;
                    break;
                }

                if (propCount >= 2)
                {
                    break;
                }
            }


            // Get user's tenant ID in the CRM implicit subscription
            string crmtenantId = null;

            foreach (var c in new JwtSecurityToken(crmToken).Claims)
            {
                if (c.Type.EqualsIgnoreCase("tid"))
                {
                    crmtenantId = c.Value;
                    break;
                }
            }

            try
            {
                TokenCredentials credentialsKv = new TokenCredentials(azureToken);

                using (KeyVaultManagementClient client = new KeyVaultManagementClient(credentialsKv))
                {
                    client.SubscriptionId = _subscriptionId;

                    // Check if a vault already exists
                    var vaults = client.Vaults.ListByResourceGroup(resourceGroup);

                    foreach (var v in client.Vaults.ListByResourceGroup(resourceGroup))
                    {
                        if (v.Name.EqualsIgnoreCase(vaultName))
                        {
                            client.Vaults.Delete(resourceGroup, vaultName);
                            break;
                        }
                    }


                    // Create the vault
                    string vaultUrl = null;
                    using (ResourceManagementClient resourceClient = new ResourceManagementClient(credentials))
                    {
                        // Set properties
                        VaultProperties p = new VaultProperties()
                        {
                            Sku            = new Sku(SkuName.Standard),
                            TenantId       = new Guid(_tenantId),
                            AccessPolicies = new List <AccessPolicyEntry>()
                        };

                        // Access policy for the owner
                        AccessPolicyEntry apeOwner = new AccessPolicyEntry();
                        apeOwner.Permissions = new Permissions(new[] { "get", "create", "delete", "list", "update", "import", "backup", "restore" }, new[] { "all" }, new[] { "all" });
                        apeOwner.TenantId    = p.TenantId;
                        apeOwner.ObjectId    = oid;
                        p.AccessPolicies.Add(apeOwner);

                        // Access policy for the CRM exporter
                        AccessPolicyEntry ape = new AccessPolicyEntry();
                        ape.Permissions = new Permissions(null, new[] { "get" });
                        ape.TenantId    = p.TenantId;
                        ape.ObjectId    = GetCrmConnectorObjectID(_graphToken, _tenantId).Result;
                        p.AccessPolicies.Add(ape);

                        VaultCreateOrUpdateParameters vaultParams = new VaultCreateOrUpdateParameters()
                        {
                            Location   = resourceClient.ResourceGroups.Get(resourceGroup).ResourceGroup.Location,
                            Properties = p
                        };

                        Vault vault = client.Vaults.CreateOrUpdate(resourceGroup, vaultName, vaultParams);
                        vaultUrl = vault.Properties.VaultUri;
                        Thread.Sleep(15000); // The vault DNS entry isn't there immediatly
                    }

                    // Create the secret
                    KeyVaultClient kvClient = new KeyVaultClient(new TokenCredentials(_kvToken));
                    SecretBundle   secret   = await kvClient.SetSecretAsync(vaultUrl,
                                                                            secretName,
                                                                            connectionString,
                                                                            new Dictionary <string, string>() { { organizationId, crmtenantId } },
                                                                            null /* Do I need to set a content type? */,
                                                                            new SecretAttributes()
                    {
                        Enabled = true
                    });

                    request.DataStore.AddToDataStore("KeyVault", secret.Id, DataStoreType.Private);
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject(), true));
        }
        private void Initialize()
        {
            rgName = TestUtilities.GenerateName("sdktestrg");
            resourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup {
                Location = location
            });

            vaultName    = TestUtilities.GenerateName("sdktestvault");
            tenantIdGuid = Guid.Parse(tenantId);
            objectIdGuid = objectId;
            tags         = new Dictionary <string, string> {
                { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" }
            };
            accPol = new AccessPolicyEntry
            {
                TenantId    = tenantIdGuid,
                ObjectId    = objectIdGuid,
                Permissions = new Permissions
                {
                    Keys         = new string[] { KeyPermissions.All },
                    Secrets      = new string[] { SecretPermissions.All },
                    Certificates = new string[] { CertificatePermissions.All },
                    Storage      = new string[] { StoragePermissions.All },
                }
            };

            IList <IPRule> ipRules = new List <IPRule>();

            ipRules.Add(new IPRule()
            {
                Value = "1.2.3.4/32"
            });
            ipRules.Add(new IPRule()
            {
                Value = "1.0.0.0/25"
            });

            vaultProperties = new VaultProperties
            {
                EnabledForDeployment         = true,
                EnabledForDiskEncryption     = true,
                EnabledForTemplateDeployment = true,
                EnableSoftDelete             = true,
                Sku = new Microsoft.Azure.Management.KeyVault.Models.Sku {
                    Name = SkuName.Standard
                },
                TenantId    = tenantIdGuid,
                VaultUri    = "",
                NetworkAcls = new NetworkRuleSet()
                {
                    Bypass = "******", DefaultAction = "Allow", IpRules = ipRules, VirtualNetworkRules = null
                },
                AccessPolicies = new[] { accPol }
            };

            systemData = new SystemData
            {
                CreatedBy          = "vaultuser",
                CreatedByType      = "user",
                CreatedAt          = DateTime.Parse("2020-02-27T07:41:03Z", CultureInfo.InvariantCulture).ToUniversalTime(),
                LastModifiedBy     = "vaultuser",
                LastModifiedByType = "user",
                LastModifiedAt     = DateTime.Parse("2020-02-27T07:41:03Z", CultureInfo.InvariantCulture).ToUniversalTime()
            };
        }
 ///GENMHASH:DB1CD9648996DA10B58423DFABD976E4:BC7BE29DA61C7F6594944FD23512AD2F
 internal AccessPolicyImpl(AccessPolicyEntry innerObject, Microsoft.Azure.Management.KeyVault.Fluent.VaultImpl parent) : base(innerObject, parent)
 {
     Inner.TenantId = Guid.Parse(parent.TenantId);
 }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(VaultName, Properties.Resources.CreateKeyVault))
            {
                if (VaultExistsInCurrentSubscription(this.VaultName))
                {
                    throw new ArgumentException(PSKeyVaultProperties.Resources.VaultAlreadyExists);
                }

                var userObjectId = Guid.Empty;
                AccessPolicyEntry accessPolicy = null;

                try
                {
                    userObjectId = GetCurrentUsersObjectId();
                }
                catch (Exception ex)
                {
                    // Show the graph exceptions as a warning, but still proceed to create a vault with no access policy
                    // This is to unblock Key Vault in Fairfax as Graph has issues in this environment.
                    WriteWarning(ex.Message);
                }
                if (userObjectId != Guid.Empty)
                {
                    accessPolicy = new AccessPolicyEntry()
                    {
                        TenantId = GetTenantId(),
                        ObjectId = userObjectId,
                        Permissions = new Permissions
                        {
                            Keys = DefaultPermissionsToKeys,
                            Secrets = DefaultPermissionsToSecrets,
                            Certificates = DefaultPermissionsToCertificates
                        }
                    };
                }

                var newVault = KeyVaultManagementClient.CreateNewVault(new PSKeyVaultModels.VaultCreationParameters()
                {
                    VaultName = this.VaultName,
                    ResourceGroupName = this.ResourceGroupName,
                    Location = this.Location,
                    EnabledForDeployment = this.EnabledForDeployment.IsPresent,
                    EnabledForTemplateDeployment = EnabledForTemplateDeployment.IsPresent,
                    EnabledForDiskEncryption = EnabledForDiskEncryption.IsPresent,
                    SkuFamilyName = DefaultSkuFamily,
                    SkuName = this.Sku,
                    TenantId = GetTenantId(),
                    AccessPolicy = accessPolicy,
                    Tags = this.Tag
                },
                ActiveDirectoryClient
                );

                this.WriteObject(newVault);

                if (accessPolicy == null)
                {
                    WriteWarning(PSKeyVaultProperties.Resources.VaultNoAccessPolicyWarning);
                }
            }
        }