public override void ExecuteCmdlet() { if (ShouldProcess(VaultName, Properties.Resources.RemoveVaultAccessPolicy)) { if (ParameterSetName == ForVault && !EnabledForDeployment.IsPresent && !EnabledForTemplateDeployment.IsPresent && !EnabledForDiskEncryption.IsPresent) { throw new ArgumentException(PSKeyVaultProperties.Resources.VaultPermissionFlagMissing); } ResourceGroupName = string.IsNullOrWhiteSpace(ResourceGroupName) ? GetResourceGroupName(VaultName) : ResourceGroupName; // Get the vault to be updated PSKeyVaultModels.PSVault existingVault = null; if (!string.IsNullOrWhiteSpace(ResourceGroupName)) { existingVault = KeyVaultManagementClient.GetVault( VaultName, ResourceGroupName); } if (existingVault == null) { throw new ArgumentException(string.Format(PSKeyVaultProperties.Resources.VaultNotFound, VaultName, ResourceGroupName)); } if (ApplicationId.HasValue && ApplicationId.Value == Guid.Empty) { throw new ArgumentException(PSKeyVaultProperties.Resources.InvalidApplicationId); } // Update vault policies var updatedPolicies = existingVault.AccessPolicies; if (!string.IsNullOrEmpty(UserPrincipalName) || !string.IsNullOrEmpty(ServicePrincipalName) || (ObjectId != Guid.Empty)) { if (ObjectId == Guid.Empty) { ObjectId = GetObjectId(this.ObjectId, this.UserPrincipalName, this.ServicePrincipalName); } updatedPolicies = existingVault.AccessPolicies.Where(ap => !ShallBeRemoved(ap, ObjectId, this.ApplicationId)).ToArray(); } // Update the vault var updatedVault = KeyVaultManagementClient.UpdateVault(existingVault, updatedPolicies, EnabledForDeployment.IsPresent ? false : existingVault.EnabledForDeployment, EnabledForTemplateDeployment.IsPresent ? false : existingVault.EnabledForTemplateDeployment, EnabledForDiskEncryption.IsPresent ? false : existingVault.EnabledForDiskEncryption, ActiveDirectoryClient); if (PassThru.IsPresent) { WriteObject(updatedVault); } } }
public override void ExecuteCmdlet() { 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, PermissionsToKeys = DefaultPermissionsToKeys, PermissionsToSecrets = DefaultPermissionsToSecrets }; } 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 = string.IsNullOrWhiteSpace(this.Sku) ? DefaultSkuName : this.Sku, TenantId = GetTenantId(), AccessPolicy = accessPolicy, Tags = this.Tag }, ActiveDirectoryClient ); this.WriteObject(newVault); if (accessPolicy == null) { WriteWarning(PSKeyVaultProperties.Resources.VaultNoAccessPolicyWarning); } }
/// <summary> /// Ctor /// </summary> /// <param name="commonData"></param> /// <param name="context"></param> public HDInsightManagementHelper(CommonTestFixture commonData, HDInsightMockContext context) { resourceManagementClient = context.GetServiceClient <ResourceManagementClient>(); storageManagementClient = context.GetServiceClient <StorageManagementClient>(); identityManagementClient = context.GetServiceClient <ManagedServiceIdentityClient>(); authorizationManagementClient = context.GetServiceClient <AuthorizationManagementClient>(); keyVaultManagementClient = context.GetServiceClient <KeyVaultManagementClient>(); keyVaultClient = GetKeyVaultClient(); networkManagementClient = context.GetServiceClient <NetworkManagementClient>(); this.commonData = commonData; }
public static KeyVaultManagementClient GetKeyVaultManagementClient(MockContext context, RecordedDelegatingHandler handler) { if (handler != null) { handler.IsPassThrough = true; KeyVaultManagementClient keyValutManagementClient = context.GetServiceClient <KeyVaultManagementClient>(handlers: handler); return(keyValutManagementClient); } return(null); }
private void InstantiateSample(string tenantId, string objectId, string appId, string appSecret, string subscriptionId, string resourceGroupName, string vaultLocation, string vaultName) { context = ClientContext.Build(tenantId, objectId, appId, subscriptionId, resourceGroupName, vaultLocation, vaultName); // log in with as the specified service principal var serviceCredentials = Task.Run(() => ClientContext.GetServiceCredentialsAsync(tenantId, appId, appSecret)).ConfigureAwait(false).GetAwaiter().GetResult(); // instantiate the management client ManagementClient = new KeyVaultManagementClient(serviceCredentials); ManagementClient.SubscriptionId = subscriptionId; }
/// <summary> /// This method retrieves the KeyVaults from all the pages of KeyVaults as one page can only store a limited number of KeyVaults. /// </summary> /// <param name="kvmClient">The KeyVaultManagementClient</param> /// <param name="vaultsRetrieved">The list of Vault objects to add to</param> /// <param name="resourceGroup">The ResourceGroup name(if applicable). Default is null.</param> /// <returns>The updated vaultsRetrieved list</returns> public List <Vault> getVaultsAllPages(KeyVaultManagementClient kvmClient, List <Vault> vaultsRetrieved, string resourceGroup = "") { IPage <Vault> vaultsCurPg = null; // Retrieves the first page of KeyVaults at the Subscription scope if (resourceGroup.Length == 0) { try { vaultsCurPg = kvmClient.Vaults.ListBySubscription(); } catch (CloudException e) { log.Error(e.Message); ConsoleError(e.Message); } } // Retrieves the first page of KeyVaults at the ResourceGroup scope else { try { vaultsCurPg = kvmClient.Vaults.ListByResourceGroup(resourceGroup); } catch (CloudException e) { log.Error(e.Message); ConsoleError(e.Message); } } // Get remaining pages if vaults were found if (vaultsCurPg != null) { vaultsRetrieved.AddRange(vaultsCurPg); while (vaultsCurPg.NextPageLink != null) { IPage <Vault> vaultsNextPg = null; // Retrieves the remaining pages of KeyVaults at the Subscription scope if (resourceGroup.Length == 0) // then by Subscription { vaultsNextPg = kvmClient.Vaults.ListBySubscriptionNext(vaultsCurPg.NextPageLink); } // Retrieves the remaining pages of KeyVaults at the ResourceGroup scope else { vaultsNextPg = kvmClient.Vaults.ListByResourceGroupNext(vaultsCurPg.NextPageLink); } vaultsRetrieved.AddRange(vaultsNextPg); vaultsCurPg = vaultsNextPg; } } return(vaultsRetrieved); }
public override void ExecuteCmdlet() { switch (ParameterSetName) { case RemoveVaultParameterSet: ResourceGroupName = string.IsNullOrWhiteSpace(ResourceGroupName) ? GetResourceGroupName(VaultName) : ResourceGroupName; if (string.IsNullOrWhiteSpace(ResourceGroupName)) { throw new ArgumentException(string.Format(PSKeyVaultProperties.Resources.VaultNotFound, VaultName, ResourceGroupName)); } ConfirmAction( Force.IsPresent, string.Format( CultureInfo.InvariantCulture, PSKeyVaultProperties.Resources.RemoveVaultWarning, VaultName), string.Format( CultureInfo.InvariantCulture, PSKeyVaultProperties.Resources.RemoveVaultWhatIfMessage, VaultName), VaultName, () => { KeyVaultManagementClient.DeleteVault( vaultName: VaultName, resourceGroupName: this.ResourceGroupName); }); break; case RemoveDeletedVaultParameterSet: ConfirmAction( Force.IsPresent, string.Format( CultureInfo.InvariantCulture, PSKeyVaultProperties.Resources.PurgeVaultWarning, VaultName), string.Format( CultureInfo.InvariantCulture, PSKeyVaultProperties.Resources.PurgeVaultWhatIfMessage, VaultName), VaultName, () => { KeyVaultManagementClient.PurgeVault( vaultName: VaultName, location: Location); }); break; default: throw new ArgumentException(PSKeyVaultProperties.Resources.BadParameterSetName); } }
public static List <KeyVaultProperties> runProgram(string[] args, bool testing) { AccessPoliciesToYaml ap = new AccessPoliciesToYaml(testing); UpdatePoliciesFromYaml up = new UpdatePoliciesFromYaml(testing); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("Refer to 'Log.log' for more details should an error be thrown.\n"); Console.ResetColor(); Console.WriteLine("Reading input files..."); up.verifyFileExtensions(args); JsonInput vaultList = ap.readJsonFile(args[0]); Console.WriteLine("Finished!"); Console.WriteLine("Grabbing secrets..."); Dictionary <string, string> secrets = ap.getSecrets(); Console.WriteLine("Finished!"); Console.WriteLine("Creating KeyVaultManagementClient, GraphServiceClient, and AzureClient..."); KeyVaultManagementClient kvmClient = ap.createKVMClient(secrets); GraphServiceClient graphClient = ap.createGraphClient(secrets); IAuthenticated azureClient = ap.createAzureClient(secrets); Console.WriteLine("Finished!");; Console.WriteLine("Checking access and retrieving key vaults..."); ap.checkAccess(vaultList, azureClient); List <KeyVaultProperties> vaultsRetrieved = ap.getVaults(vaultList, kvmClient, graphClient); Console.WriteLine("Finished!"); Console.WriteLine("Reading yaml file..."); List <KeyVaultProperties> yamlVaults = up.deserializeYaml(args[1]); Console.WriteLine("Finished!"); Console.WriteLine("Updating key vaults..."); List <KeyVaultProperties> deletedPolicies = up.updateVaults(yamlVaults, vaultsRetrieved, kvmClient, secrets, graphClient); Console.WriteLine("Finished!"); Console.WriteLine("Generating DeletedPolicies yaml..."); up.convertToYaml(deletedPolicies, args[2]); Console.WriteLine("Finished!"); if (testing) { return(up.Changed); } return(null); }
public async Task <KeyVaultManagementClient> GetManagementClientInstance() { String BearerToken = await this._authenticationHandler.GetBearerToken(); ServiceClientCredentials Creds = new TokenCredentials(BearerToken); KeyVaultManagementClient Client = new KeyVaultManagementClient(Creds) { SubscriptionId = _subscriptionId }; return(Client); }
public static async Task AddKeyVaultAccessPolicyAsync(KeyVaultManagementClient keyVaultClient, string pipelineName, string tenantId, string resourceGroupName, string vaultUri, string identityPrincipalId) { var vaultName = GetKVNameFromUri(vaultUri); Console.WriteLine($"Adding accessPolicy for pipeline '{pipelineName}' to vault '{vaultName}'."); var vault = await keyVaultClient.Vaults.GetAsync(resourceGroupName, vaultName).ConfigureAwait(false); if (vault != null) { var accessPolicy = new AccessPolicyEntry { TenantId = new System.Guid(tenantId), ObjectId = identityPrincipalId, Permissions = new Permissions { Secrets = new List <string> { { "get" } } } }; if (vault.Properties.AccessPolicies.Contains(accessPolicy)) { Console.WriteLine($"The vault '{vaultName}' already contains this access policy for principalId '{identityPrincipalId}'. Skip."); } else { Console.WriteLine($"Adding access policy for principalId '{identityPrincipalId} to the vault '{vaultName}'."); await keyVaultClient.Vaults.UpdateAccessPolicyAsync( resourceGroupName, vaultName, AccessPolicyUpdateKind.Add, new VaultAccessPolicyParameters { Properties = new VaultAccessPolicyProperties { AccessPolicies = new List <AccessPolicyEntry>() { accessPolicy } } }).ConfigureAwait(false); } } else { throw new ArgumentException($"Could not find key vault '{vaultName}'. Please ensure the vault exists in the current resource group {resourceGroupName}."); } }
protected PSKeyVault UpdateCurrentVault(PSKeyVault existingVault, PSKeyVaultNetworkRuleSet updatedNetworkAcls) { return(KeyVaultManagementClient.UpdateVault( existingVault, existingVault.AccessPolicies, existingVault.EnabledForDeployment, existingVault.EnabledForTemplateDeployment, existingVault.EnabledForDiskEncryption, existingVault.EnableSoftDelete, existingVault.EnablePurgeProtection, updatedNetworkAcls, ActiveDirectoryClient)); }
public async Task <Vault> CreateKeyVaultAsync( Identity.Identity portalIdentity, Identity.Identity ownerIdentity, Guid subscriptionId, string resourceGroupName, string location, string keyVaultName, string environmentName) { await RegisterProvider(subscriptionId, "Microsoft.KeyVault"); var accessToken = await GetAccessToken(); var token = new TokenCredentials(accessToken); var kvClient = new KeyVaultManagementClient(token) { SubscriptionId = subscriptionId.ToString() }; var permissions = new Microsoft.Azure.Management.KeyVault.Models.Permissions( secrets: new[] { "get", "list", "set", "delete" }, certificates: new[] { "get", "list", "update", "delete", "create", "import" }); var accessPolicies = new[] { // Portal MSI new AccessPolicyEntry( portalIdentity.TenantId, portalIdentity.ObjectId.ToString(), permissions), // Owner new AccessPolicyEntry( ownerIdentity.TenantId, ownerIdentity.ObjectId.ToString(), permissions) }; // TODO - Make SKU configurable var kvParams = new VaultCreateOrUpdateParameters( location, new VaultProperties( portalIdentity.TenantId, new Microsoft.Azure.Management.KeyVault.Models.Sku(Microsoft.Azure.Management.KeyVault.Models.SkuName.Standard), accessPolicies), GetEnvironmentTags(environmentName)); return(await kvClient.Vaults.CreateOrUpdateAsync( resourceGroupName, keyVaultName, kvParams)); }
public override void ExecuteCmdlet() { if (this.IsParameterBound(c => c.InputObject)) { this.ResourceGroupName = this.InputObject.ResourceGroupName; this.VaultName = this.InputObject.VaultName; } if (this.IsParameterBound(c => c.ResourceId)) { var resourceIdentifier = new ResourceIdentifier(this.ResourceId); this.ResourceGroupName = resourceIdentifier.ResourceGroupName; this.VaultName = resourceIdentifier.ResourceName; } PSKeyVault existingResource = null; try { existingResource = KeyVaultManagementClient.GetVault(this.VaultName, this.ResourceGroupName); } catch { existingResource = null; } if (existingResource == null) { throw new Exception(string.Format("A key vault with name '{0}' in resource group '{1}' does not exist. Please use New-AzKeyVault to create a key vault with these properties.", this.VaultName, this.ResourceGroupName)); } if (this.ShouldProcess(this.VaultName, string.Format("Updating key vault '{0}' in resource group '{1}'.", this.VaultName, this.ResourceGroupName))) { var result = KeyVaultManagementClient.UpdateVault(existingResource, existingResource.AccessPolicies, existingResource.EnabledForDeployment, existingResource.EnabledForTemplateDeployment, existingResource.EnabledForDiskEncryption, EnableSoftDelete.IsPresent ? (true as bool?) : null, EnablePurgeProtection.IsPresent ? (true as bool?) : null, EnableRbacAuthorization, this.IsParameterBound(c => c.SoftDeleteRetentionInDays) ? (SoftDeleteRetentionInDays as int?) : (existingResource.SoftDeleteRetentionInDays ?? Constants.DefaultSoftDeleteRetentionDays), existingResource.NetworkAcls ); WriteObject(result); } }
private void InstantiateSample(string tenantId, string appId, string appSecret, string subscriptionId, string resourceGroupName, string vaultLocation, string vaultName, string storageAccountName, string storageAccountResourceId) { context = ClientContext.Build(tenantId, appId, appSecret, subscriptionId, resourceGroupName, vaultLocation, vaultName, storageAccountName, storageAccountResourceId); // log in with as the specified service principal for vault management operations var serviceCredentials = Task.Run(() => ClientContext.GetServiceCredentialsAsync(tenantId, appId, appSecret)).ConfigureAwait(false).GetAwaiter().GetResult(); // instantiate the management client ManagementClient = new KeyVaultManagementClient(serviceCredentials); ManagementClient.SubscriptionId = subscriptionId; // instantiate the data client, specifying the user-based access token retrieval callback DataClient = new KeyVaultClient(ClientContext.AcquireUserAccessTokenAsync); }
public async Task RunAsync() { // Generate a random name for a new vault String vaultName = Util.generateRandomVaultId(); // Set up credentials to access management plane to set up example key vault AzureCredentials credentials = new AzureCredentialsFactory().FromServicePrincipal( settings.ClientID, settings.ClientSecret, settings.TenantID, AzureEnvironment.AzureGlobalCloud ); // Ensure that our sample resource group exists. Console.WriteLine("Creating sample resource group"); ResourceManagementClient resourceMgmtClient = new ResourceManagementClient(credentials); resourceMgmtClient.SubscriptionId = settings.SubscriptionID; await resourceMgmtClient.ResourceGroups.CreateOrUpdateAsync(settings.ResourceGroupName, new ResourceGroupInner(settings.AzureLocation)); // Create the sample key vault. Console.WriteLine("Creating sample Key Vault - " + vaultName); // Set up the params for the API call VaultCreateOrUpdateParametersInner createParams = new VaultCreateOrUpdateParametersInner( settings.AzureLocation, new VaultProperties( Guid.Parse(settings.TenantID), new Microsoft.Azure.Management.KeyVault.Fluent.Models.Sku(SkuName.Standard), // Create an access policy granting all secret permissions to our sample's service principal new[] { new AccessPolicyEntry(Guid.Parse(settings.TenantID), settings.ClientOID, new Permissions(null, new[] { "all" })) } ) ); KeyVaultManagementClient kvMgmtClient = new KeyVaultManagementClient(credentials); kvMgmtClient.SubscriptionId = settings.SubscriptionID; VaultInner vault = await kvMgmtClient.Vaults.CreateOrUpdateAsync(settings.ResourceGroupName, vaultName, createParams); // Now demo authentication to the vault using ADAL // Add a delay to wait for KV DNS record to be created. See: https://github.com/Azure/azure-sdk-for-node/pull/1938 System.Threading.Thread.Sleep(15000); await authUsingADALCallbackAsync(vault.Properties.VaultUri); }
protected PSKeyVault UpdateCurrentVault(PSKeyVault existingVault, PSKeyVaultNetworkRuleSet updatedNetworkAcls) { return(KeyVaultManagementClient.UpdateVault( existingVault, existingVault.AccessPolicies, existingVault.EnabledForDeployment, existingVault.EnabledForTemplateDeployment, existingVault.EnabledForDiskEncryption, existingVault.EnableSoftDelete, existingVault.EnablePurgeProtection, existingVault.EnableRbacAuthorization, existingVault.SoftDeleteRetentionInDays, updatedNetworkAcls, GraphClient)); }
public override void ExecuteCmdlet() { if (ShouldProcess(VaultName, Properties.Resources.RecoverVault)) { var newVault = KeyVaultManagementClient.CreateNewVault(new PSKeyVaultModels.VaultCreationParameters() { VaultName = this.VaultName, ResourceGroupName = this.ResourceGroupName, Location = this.Location, Tags = this.Tag, CreateMode = CreateMode.Recover }); this.WriteObject(newVault); } }
public override void ExecuteCmdlet() { if (this.IsParameterBound(c => c.InputObject)) { this.ResourceGroupName = this.InputObject.ResourceGroupName; this.VaultName = this.InputObject.VaultName; } if (this.IsParameterBound(c => c.ResourceId)) { var resourceIdentifier = new ResourceIdentifier(this.ResourceId); this.ResourceGroupName = resourceIdentifier.ResourceGroupName; this.VaultName = resourceIdentifier.ResourceName; } PSKeyVault existingResource = null; try { existingResource = KeyVaultManagementClient.GetVault(this.VaultName, this.ResourceGroupName); } catch { existingResource = null; } if (existingResource == null) { throw new Exception(string.Format("A key vault with name '{0}' in resource group '{1}' does not exist. Please use New-AzKeyVault to create a key vault with these properties.", this.VaultName, this.ResourceGroupName)); } if (this.ShouldProcess(this.VaultName, string.Format("Updating key vault '{0}' in resource group '{1}'.", this.VaultName, this.ResourceGroupName))) { var result = KeyVaultManagementClient.UpdateVault( existingResource, updatedParamater: new VaultCreationOrUpdateParameters { EnablePurgeProtection = this.EnablePurgeProtection.IsPresent ? (true as bool?) : null, EnableRbacAuthorization = this.EnableRbacAuthorization, PublicNetworkAccess = this.PublicNetworkAccess, Tags = this.Tag } ); WriteObject(result); } }
/// <summary> /// Instantiates the base sample class, creating the service clients. /// </summary> /// <param name="tenantId">Tenant identifier which contains the Service Principal used to run this test.</param> /// <param name="appId">Identifier of the AD application used to log into Azure.</param> /// <param name="appSecret">Secret of the AD application.</param> /// <param name="objectId">Object identifier of the Service Principal corresponding to the AD application used to run this test.</param> /// <param name="subscriptionId">Subscription containing the resources.</param> /// <param name="vaultResourceGroupName">Vault resource group name.</param> /// <param name="vaultLocation">Vault location.</param> /// <param name="vaultName">Vault name.</param> /// <param name="vnetSubnetResourceId">Resource identifier of the subnet to use for testing; /// all other coordinates are derived from this resource id.</param> private void InstantiateSample(string tenantId, string appId, string appSecret, string objectId, string subscriptionId, string vaultResourceGroupName, string vaultLocation, string vaultName, string vnetSubnetResourceId) { context = ClientContext.Build(tenantId, appId, appSecret, objectId, subscriptionId, vaultResourceGroupName, vaultLocation, vaultName, vnetSubnetResourceId); // log in with as the specified service principal for vault management operations var serviceCredentials = Task.Run(() => ClientContext.GetServiceCredentialsAsync(tenantId, appId, appSecret)).ConfigureAwait(false).GetAwaiter().GetResult(); // instantiate the management client KVManagementClient = new KeyVaultManagementClient(serviceCredentials); KVManagementClient.SubscriptionId = subscriptionId; // instantiate the data client DataClient = new KeyVaultClient(ClientContext.AcquireAccessTokenAsync); // instantiate the network management client NetworkManagementClient = new NetworkManagementClient(serviceCredentials); NetworkManagementClient.SubscriptionId = context.SubscriptionId; }
public override void ExecuteCmdlet() { if (InputObject != null) { Name = InputObject.Name; ResourceGroupName = InputObject.ResourceGroupName; } else if (ResourceId != null) { var resourceIdentifier = new ResourceIdentifier(ResourceId); Name = resourceIdentifier.ResourceName; ResourceGroupName = resourceIdentifier.ResourceGroupName; } // Get resource group name for Managed HSM ResourceGroupName = string.IsNullOrWhiteSpace(ResourceGroupName) ? GetResourceGroupName(Name, true) : ResourceGroupName; if (string.IsNullOrWhiteSpace(ResourceGroupName)) { throw new ArgumentException(string.Format(Resources.HsmNotFound, Name, ResourceGroupName)); } ConfirmAction( Force.IsPresent, string.Format( CultureInfo.InvariantCulture, Resources.RemoveHsmWarning, Name), string.Format( CultureInfo.InvariantCulture, Resources.RemoveHsmWhatIfMessage, Name), Name, () => { KeyVaultManagementClient.DeleteManagedHsm( managedHsm: Name, resourceGroupName: ResourceGroupName); if (PassThru) { WriteObject(true); } }); }
public async Task <Microsoft.Azure.Management.KeyVault.Models.CheckNameAvailabilityResult> ValidateKeyVaultName( Guid subscriptionId, string resourceGroupName, string keyVaultName) { var accessToken = await GetAccessToken(); var token = new TokenCredentials(accessToken); var kvClient = new KeyVaultManagementClient(token) { SubscriptionId = subscriptionId.ToString() }; var param = new VaultCheckNameAvailabilityParameters { Name = keyVaultName }; var result = await kvClient.Vaults.CheckNameAvailabilityAsync(param); if (!result.NameAvailable.GetValueOrDefault(true)) { // The name isn't available, let's see if it's our KV bool available = false; try { await kvClient.Vaults.GetAsync(resourceGroupName, keyVaultName); available = true; } catch (CloudException ce) { if (!ce.ResourceNotFound()) { _logger.LogError(ce, $"Exception validating Key Vault {keyVaultName} " + $"in resource group {resourceGroupName} " + $"in subscription {subscriptionId} " + $"with request {ce.RequestId}"); throw; } } return(new Microsoft.Azure.Management.KeyVault.Models.CheckNameAvailabilityResult(available, result.Reason, result.Message)); } return(result); }
public KeyVaultAdminService(IOptionsSnapshot <AzureAdOptions> azureAdOptions, IOptionsSnapshot <AdminConfig> adminConfig, IOptionsSnapshot <Resources> resources, IGraphHttpService graphHttpService, IHttpContextAccessor contextAccessor) { var principal = contextAccessor.HttpContext.User; userId = principal.FindFirst("oid").Value; tenantId = Guid.Parse(principal.FindFirst("tid").Value); clientId = Guid.Parse(azureAdOptions.Value.ClientId); adalContext = new AuthenticationContext($"{azureAdOptions.Value.AADInstance}{azureAdOptions.Value.TenantId}", new ADALSessionCache(userId, contextAccessor)); resourceGroup = adminConfig.Value.ResourceGroup; kvManagmentClient = new KeyVaultManagementClient(new KeyVaultCredential(GetAppToken)); kvManagmentClient.SubscriptionId = adminConfig.Value.SubscriptionId; kvClient = new KeyVaultClient(new KeyVaultCredential(GetAppTokenForKv)); this.azureAdOptions = azureAdOptions.Value; this.adminConfig = adminConfig.Value; this.graphHttpService = graphHttpService; this.resources = resources.Value; }
public KeyVaultMgmtClient( string subscriptionId, RestClient restClient ) { if (string.IsNullOrWhiteSpace(subscriptionId)) { throw new ArgumentNullException(nameof(subscriptionId)); } if (restClient is null) { throw new ArgumentNullException(nameof(restClient)); } _keyVaultManagementClient = new KeyVaultManagementClient(restClient) { SubscriptionId = subscriptionId }; }
/// <summary> /// Create a vault to test. /// </summary> /// <param name="clientId"></param> /// <param name="clientSecret"></param> /// <param name="tenantId"></param> /// <param name="subId"></param> /// <param name="location"></param> /// <param name="objectId"></param> /// <returns></returns> private async Task <VaultInner> GetVaultAsync(string clientId, string clientSecret, string tenantId, string subId, string location, string objectId, string rg) { var credential = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud); var restClient = RestClient.Configure() .WithEnvironment(credential.Environment) .WithCredentials(credential) .Build(); var client = new KeyVaultManagementClient(restClient); client.SubscriptionId = subId; var para = GetVaultCreateOrUpdateParameters(tenantId, location, objectId); var vault = await client.Vaults.CreateOrUpdateAsync(rg, "vault0512test", para); return(vault); }
/// <summary> /// This method creates and returns a KeyVaulManagementClient. /// </summary> /// <param name="secrets">The dictionary of information obtained from environment variables</param> /// <returns>The KeyVaultManagementClient created using the secret information</returns> public KeyVaultManagementClient createKVMClient(Dictionary <string, string> secrets) { log.Info("Creating KVM Client..."); try { AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(secrets["clientId"], secrets["clientKey"], secrets["tenantId"], AzureEnvironment.AzureGlobalCloud); var kvmClient = new KeyVaultManagementClient(credentials); log.Info("KVM Client created!"); return(kvmClient); } catch (Exception e) { log.Error("KVMClientFail", e); log.Debug($"Refer to https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.management.keyvault.keyvaultmanagementclient?view=azure-dotnet for information on KeyVaultManagementClient class."); Exit(e.Message); return(null); } }
private void CreateVault(KeyVaultManagementClient mgmtClient, string location, string tenantId) { mgmtClient.Vaults.CreateOrUpdate( ResourceGroupName, PreCreatedVault, new VaultCreateOrUpdateParameters { Location = location, Tags = new Dictionary<string, string> { { TagName, TagValue } }, Properties = new VaultProperties { EnabledForDeployment = false, Sku = new Sku { Name = SkuName.Premium }, TenantId = Guid.Parse(tenantId), VaultUri = "", AccessPolicies = new AccessPolicyEntry[]{ } } }); }
public override void ExecuteCmdlet() { MSGraphMessageHelper.WriteMessageForCmdletsSwallowException(this); switch (ParameterSetName) { case GetVaultParameterSet: List <PSKeyVaultIdentityItem> vaults = null; if (string.IsNullOrWhiteSpace(ResourceGroupName)) { vaults = ListVaults(ResourceGroupName, Tag); ResourceGroupName = vaults?.FirstOrDefault(r => r.VaultName.Equals(VaultName, StringComparison.OrdinalIgnoreCase))?.ResourceGroupName; } if (ShouldGetByName(ResourceGroupName, VaultName)) { PSKeyVault vault = KeyVaultManagementClient.GetVault( VaultName, ResourceGroupName, GraphClient); WriteObject(FilterByTag(vault, Tag)); } else { WriteObject(TopLevelWildcardFilter(ResourceGroupName, VaultName, vaults ?? ListVaults(ResourceGroupName, Tag)), true); } break; case GetDeletedVaultParameterSet: WriteObject(KeyVaultManagementClient.GetDeletedVault(VaultName, Location)); break; case ListDeletedVaultsParameterSet: WriteObject(KeyVaultManagementClient.ListDeletedVaults(), true); break; default: throw new ArgumentException(Resources.BadParameterSetName); } }
public override void ExecuteCmdlet() { if (this.IsParameterBound(c => c.InputObject)) { this.ResourceGroupName = this.InputObject.ResourceGroupName; this.Name = this.InputObject.Name; } if (this.IsParameterBound(c => c.ResourceId)) { var resourceIdentifier = new ResourceIdentifier(this.ResourceId); this.ResourceGroupName = resourceIdentifier.ResourceGroupName; this.Name = resourceIdentifier.ResourceName; } PSManagedHsm existingResource = null; try { existingResource = KeyVaultManagementClient.GetManagedHsm(this.Name, this.ResourceGroupName); } catch { existingResource = null; } if (existingResource == null) { throw new Exception(string.Format("A managed HSM with name '{0}' in resource group '{1}' does not exist. Please use New-AzManagedHsm to create a managed HSM with these properties.", this.Name, this.ResourceGroupName)); } if (this.ShouldProcess(this.Name, string.Format("Updating managed HSM '{0}' in resource group '{1}'.", this.Name, this.ResourceGroupName))) { var result = KeyVaultManagementClient.UpdateManagedHsm(existingResource, new VaultCreationOrUpdateParameters { Tags = Tag }, null); WriteObject(result); } }
public override void ExecuteCmdlet() { if (this.IsParameterBound(c => c.InputObject)) { this.ResourceGroupName = this.InputObject.ResourceGroupName; this.Name = this.InputObject.Name; } if (this.IsParameterBound(c => c.ResourceId)) { var resourceIdentifier = new ResourceIdentifier(this.ResourceId); this.ResourceGroupName = resourceIdentifier.ResourceGroupName; this.Name = resourceIdentifier.ResourceName; } PSManagedHsm existingResource = null; try { existingResource = KeyVaultManagementClient.GetManagedHsm(this.Name, this.ResourceGroupName); } catch { existingResource = null; } if (existingResource == null) { throw new Exception(string.Format(Resources.HsmNotFound, this.Name, this.ResourceGroupName)); } if (this.ShouldProcess(this.Name, string.Format(Resources.UpdateHsmShouldProcessMessage, this.Name, this.ResourceGroupName))) { var result = KeyVaultManagementClient.UpdateManagedHsm(existingResource, new VaultCreationOrUpdateParameters { Tags = Tag }, null); WriteObject(result); } }
public override void ExecuteCmdlet() { switch (ParameterSetName) { case GetManagedHsmParameterSet: ResourceGroupName = string.IsNullOrWhiteSpace(ResourceGroupName) ? GetResourceGroupName(Name, true) : ResourceGroupName; if (ShouldGetByName(ResourceGroupName, Name)) { WriteObject(FilterByTag(KeyVaultManagementClient.GetManagedHsm( Name, ResourceGroupName, GraphClient), Tag)); } else { WriteObject( TopLevelWildcardFilter( ResourceGroupName, Name, FilterByTag( KeyVaultManagementClient.ListManagedHsms(ResourceGroupName, GraphClient), Tag)), true); } break; case GetDeletedManagedHsmParameterSet: WriteObject(FilterByTag(KeyVaultManagementClient.GetDeletedManagedHsm( Name, Location), Tag)); break; case ListDeletedManagedHsmsParameterSet: WriteObject(FilterByTag( KeyVaultManagementClient.ListDeletedManagedHsms(), Tag), true); break; default: throw new ArgumentException(Resources.BadParameterSetName); } }
private Vault CreateVault(KeyVaultManagementClient mgmtClient, string location, string tenantId) { var createResponse = mgmtClient.Vaults.CreateOrUpdate( resourceGroupName: resourceGroupName, vaultName: preCreatedVault, parameters: new VaultCreateOrUpdateParameters { Location = location, Tags = new Dictionary<string, string> { { tagName, tagValue } }, Properties = new VaultProperties { EnabledForDeployment = false, Sku = new Sku { Name = SkuName.Premium }, TenantId = Guid.Parse(tenantId), VaultUri = "", AccessPolicies = new AccessPolicyEntry[] { } } } ); return createResponse; }
private static void HandleCreateVault(Options options, AuthenticationContext authContext, AuthenticationResult token, ResourceManagementClient resourceManagementClient) { if (!string.IsNullOrEmpty(options.CreateVault)) { var vaults = resourceManagementClient.Resources .List(new ResourceListParameters { ResourceType = "Microsoft.KeyVault/vaults" }); if (options.AllowUpdate || !vaults.Resources.Any(v => v.Name == options.CreateVault)) { ResourceGroupExtended rg = GetResourceGroup(options, resourceManagementClient); var graphtoken = authContext.AcquireToken("https://graph.windows.net/", options.ClientID, new Uri(options.RedirectUri), PromptBehavior.Auto); var graph = new ActiveDirectoryClient(new Uri("https://graph.windows.net/" + graphtoken.TenantId), () => Task.FromResult(graphtoken.AccessToken)); var principals = graph.ServicePrincipals.Where(p => p.AppId == options.ApplicaitonId).ExecuteSingleAsync().GetAwaiter().GetResult(); // var a = graph.GetObjectsByObjectIdsAsync(new[] { "ffe34afb-c9e7-45bc-a8d2-c1dedc649b7c" }, new string[] { }).GetAwaiter().GetResult().ToArray(); using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken))) { Console.WriteLine(JsonConvert.SerializeObject( client.Vaults.CreateOrUpdate(options.ResourceGroup, options.CreateVault, new VaultCreateOrUpdateParameters { Properties = new VaultProperties { EnabledForDeployment = true, // EnabledForDiskEncryption = true, // EnabledForTemplateDeployment = true, Sku = new Sku { Name = "Premium", Family = "A" }, AccessPolicies = new List<AccessPolicyEntry>{ new AccessPolicyEntry{ TenantId = Guid.Parse(token.TenantId), ObjectId = Guid.Parse(principals.ObjectId), PermissionsToSecrets=new []{"all"}, PermissionsToKeys = new []{"all"} }, new AccessPolicyEntry{ TenantId = Guid.Parse(token.TenantId), ObjectId = Guid.Parse(token.UserInfo.UniqueId), PermissionsToSecrets=new []{"all"}, PermissionsToKeys = new []{"all"} } }, TenantId = Guid.Parse(token.TenantId) }, Location = rg.Location, }), Formatting.Indented)); } } else { using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken))) { Console.WriteLine(JsonConvert.SerializeObject( client.Vaults.Get(options.ResourceGroup, options.CreateVault).Vault, Formatting.Indented)); } } } }
private static void HandleDeploy(Options options, AuthenticationContext authContext, AuthenticationResult token, ResourceManagementClient resourceManagementClient) { if (!string.IsNullOrWhiteSpace(options.Deploy)) { ResourceGroupExtended rg = GetResourceGroup(options, resourceManagementClient); //Fix location to displayname from template using (var subscriptionClient = new SubscriptionClient(new TokenCloudCredentials(token.AccessToken))) { var a = subscriptionClient.Subscriptions.ListLocations(options.SubscriptionId); rg.Location = a.Locations.Single(l => l.Name == rg.Location).DisplayName; } var graphtoken = authContext.AcquireToken("https://graph.windows.net/", options.ClientID, new Uri(options.RedirectUri), PromptBehavior.Auto); var graph = new ActiveDirectoryClient(new Uri("https://graph.windows.net/" + graphtoken.TenantId), () => Task.FromResult(graphtoken.AccessToken)); var principal = graph.ServicePrincipals.Where(p => p.AppId == options.ApplicaitonId).ExecuteSingleAsync().GetAwaiter().GetResult(); DeploymentExtended deploymentInfo = null; if (!resourceManagementClient.Deployments.CheckExistence(options.ResourceGroup, options.DeployName).Exists) { var deployment = new Deployment { Properties = new DeploymentProperties { Mode = DeploymentMode.Incremental, //Dont Delete other resources Template = File.ReadAllText(options.Deploy), Parameters = new JObject( new JProperty("siteName", CreateValue(options.SiteName)), new JProperty("hostingPlanName", CreateValue(options.HostingPlanName)), new JProperty("storageAccountType", CreateValue(options.StorageAccountType)), new JProperty("siteLocation", CreateValue(rg.Location)), new JProperty("sku", CreateValue(options.WebsitePlan)), new JProperty("tenantId", CreateValue(token.TenantId)), new JProperty("objectId", CreateValue(token.UserInfo.UniqueId)), new JProperty("appOwnerTenantId", CreateValue(principal.AppOwnerTenantId.Value.ToString())), new JProperty("appOwnerObjectId", CreateValue(principal.ObjectId)) ).ToString(), } }; var result = resourceManagementClient.Deployments.CreateOrUpdate(options.ResourceGroup, options.DeployName, deployment); deploymentInfo = result.Deployment; } else { var deploymentStatus = resourceManagementClient.Deployments.Get(options.ResourceGroup, options.DeployName); deploymentInfo = deploymentStatus.Deployment; } while (!(deploymentInfo.Properties.ProvisioningState == "Succeeded" || deploymentInfo.Properties.ProvisioningState == "Failed")) { var deploymentStatus = resourceManagementClient.Deployments.Get(options.ResourceGroup, options.DeployName); deploymentInfo = deploymentStatus.Deployment; Thread.Sleep(5000); } Console.WriteLine(deploymentInfo.Properties.Outputs); var outputs = JObject.Parse(deploymentInfo.Properties.Outputs); var storageAccountName = outputs["storageAccount"]["value"].ToString(); var keyvaultName = outputs["keyvault"]["value"].ToString(); using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken))) { using (var storageClient = new StorageManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken))) { var keys = storageClient.StorageAccounts.ListKeys(options.ResourceGroup, storageAccountName); var vaultInfo = client.Vaults.Get(options.ResourceGroup, keyvaultName); //CHEATING (using powershell application id to get token on behhalf of user); var vaultToken = authContext.AcquireToken("https://vault.azure.net", "1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")); var keyvaultClient = new KeyVaultClient((_, b, c) => Task.FromResult(vaultToken.AccessToken)); var secrets = keyvaultClient.GetSecretsAsync(vaultInfo.Vault.Properties.VaultUri).GetAwaiter().GetResult(); if (secrets.Value == null || !secrets.Value.Any(s => s.Id == vaultInfo.Vault.Properties.VaultUri + "secrets/storage")) { keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, "storage", $"{storageAccountName}:{keys.StorageAccountKeys.Key1}").GetAwaiter().GetResult(); keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, "storage", $"{storageAccountName}:{keys.StorageAccountKeys.Key2}").GetAwaiter().GetResult(); var secret = keyvaultClient.GetSecretVersionsAsync(vaultInfo.Vault.Properties.VaultUri, "storage").GetAwaiter().GetResult(); } } } } }
private static void HandleCertificateOperations(Options options, AuthenticationContext authContext, AuthenticationResult token) { using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken))) { if (!string.IsNullOrEmpty(options.ResourceGroup)) { if (!string.IsNullOrEmpty(options.Vault)) { var vaultInfo = client.Vaults.Get(options.ResourceGroup, options.Vault); var vaultToken = authContext.AcquireToken("https://vault.azure.net", "1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")); var keyvaultClient = new KeyVaultClient((_, b, c) => Task.FromResult(vaultToken.AccessToken)); if (!string.IsNullOrEmpty(options.ExportCert)) { var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.ExportCert).GetAwaiter().GetResult(); var cert = new X509Certificate2(Convert.FromBase64String(secret.Value), new SecureString(), X509KeyStorageFlags.Exportable); File.WriteAllBytes(options.Out, cert.Export(X509ContentType.Pfx)); } if (!string.IsNullOrEmpty(options.Encrypt)) { var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName).GetAwaiter().GetResult(); var cert = new X509Certificate2(Convert.FromBase64String(secret.Value)); byte[] encoded = System.Text.UTF8Encoding.UTF8.GetBytes(options.Encrypt); var content = new ContentInfo(encoded); var env = new EnvelopedCms(content); env.Encrypt(new CmsRecipient(cert)); string encrypted64 = Convert.ToBase64String(env.Encode()); Console.WriteLine("Encrypting: {0}", options.Encrypt); Console.WriteLine("Encrypted Base64 String: {0}", encrypted64); } if (!string.IsNullOrEmpty(options.Decrypt)) { var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName).GetAwaiter().GetResult(); var cert = new X509Certificate2(Convert.FromBase64String(secret.Value)); var encryptedBytes = Convert.FromBase64String(options.Decrypt); var envelope = new EnvelopedCms(); envelope.Decode(encryptedBytes); envelope.Decrypt(new X509Certificate2Collection(cert)); Console.WriteLine("Decrypting: {0}", options.Decrypt); Console.WriteLine("Decrypted String: {0}", Encoding.UTF8.GetString(envelope.ContentInfo.Content)); } if (options.MakeCert) { var cert = Convert.ToBase64String(Certificate.CreateSelfSignCertificatePfx(string.Format("CN={0}", options.CertificateName), DateTime.UtcNow, DateTime.UtcNow.AddYears(2))); var cert1 = new X509Certificate2(Convert.FromBase64String(cert)); var secrets = keyvaultClient.GetSecretsAsync(vaultInfo.Vault.Properties.VaultUri).GetAwaiter().GetResult(); if (secrets.Value == null || !secrets.Value.Any(s => s.Id == vaultInfo.Vault.Properties.VaultUri + "secrets/" + options.CertificateName)) { Console.WriteLine( JsonConvert.SerializeObject(keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName, cert, null, "application/pkcs12").GetAwaiter().GetResult() , Formatting.Indented)); } } } } } }
private static void HandleAddToApplication(Options options, AuthenticationContext authContext, AuthenticationResult token) { if (!string.IsNullOrEmpty(options.AddApplication)) { using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken))) { var graphtoken = authContext.AcquireToken("https://graph.windows.net/", options.ClientID, new Uri(options.RedirectUri), PromptBehavior.Auto); var graph = new ActiveDirectoryClient(new Uri("https://graph.windows.net/" + graphtoken.TenantId), () => Task.FromResult(graphtoken.AccessToken)); var principals = graph.ServicePrincipals.Where(p => p.AppId == options.AddApplication).ExecuteSingleAsync().GetAwaiter().GetResult(); var vault = client.Vaults.GetAsync(options.ResourceGroup, options.Vault).GetAwaiter().GetResult(); if (!vault.Vault.Properties.AccessPolicies.Any(a => a.ObjectId == Guid.Parse(principals.ObjectId))) { vault.Vault.Properties.AccessPolicies.Add(new AccessPolicyEntry { TenantId = Guid.Parse(principals.AppOwnerTenantId.ToString()), ObjectId = Guid.Parse(principals.ObjectId), PermissionsToSecrets = new[] { "all" }, PermissionsToKeys = new[] { "all" } }); } Console.WriteLine(JsonConvert.SerializeObject( client.Vaults.CreateOrUpdate(options.ResourceGroup, options.Vault, new VaultCreateOrUpdateParameters(vault.Vault.Properties, vault.Vault.Location) { Tags = vault.Vault.Tags, }), Formatting.Indented)); } } }
private VaultGetResponse CreateVault(KeyVaultManagementClient mgmtClient, string location, string tenantId, ServicePrincipalGetResult servicePrincipal) { var createResponse = mgmtClient.Vaults.CreateOrUpdate( resourceGroupName: rgName, vaultName: vaultName, parameters: new VaultCreateOrUpdateParameters { Location = location, Tags = new Dictionary<string, string>(), Properties = new VaultProperties { EnabledForDeployment = true, Sku = new Sku {Family = "A", Name = "Premium"}, TenantId = Guid.Parse(tenantId), VaultUri = "", AccessPolicies = new[] { new AccessPolicyEntry { TenantId = Guid.Parse(tenantId), ObjectId = Guid.Parse(servicePrincipal.ServicePrincipal.ObjectId), PermissionsToKeys = new string[]{"all"}, PermissionsToSecrets = new string[]{"all"} } } } } ); return createResponse; }