Exemplo n.º 1
0
        /*
         * Input: AzureResourceInformation, KeyVaultInformation, Logger
         * Get the necessary credential information for VM management and KeyVault access.
         */
        private async Task Initialize(AzureResourceInformation resourceInfo, KeyVaultInformation vault, ILogger log)
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();

            _kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            string _id   = (await _kv.GetSecretAsync(vault.KeyVaultUri, vault.KV_SecretName_ServicePrinciple)).Value;
            string _cred = (await _kv.GetSecretAsync(vault.KeyVaultUri, vault.KV_SecretName_ServicePrinciplePwd)).Value;

            // Get the LabResourceGroup
            resourceInfo.LabResourceGroup = ParseLabResourceGroup(resourceInfo.ResourceUri);
            resourceInfo.LabName          = await GetLabName(resourceInfo, log);

            AzureCredentials _azureCred = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
                _id, _cred, resourceInfo.TenantId, AzureEnvironment.AzureGlobalCloud);

            _msiazure = Azure.Authenticate(_azureCred).WithSubscription(resourceInfo.SubscriptionId);

            _clientCred = new ClientCredential(_id, _cred);

            var context = new AuthenticationContext($"https://login.windows.net/{resourceInfo.TenantId}", false);
            var token   = await context.AcquireTokenAsync("https://management.azure.com/", _clientCred);

            _accessToken = token.AccessToken;
        }
Exemplo n.º 2
0
 public AzureResourceManager(AzureResourceInformation resourceId, KeyVaultInformation kvInfo, ILogger log)
 {
     Initialize(resourceId, kvInfo, log).Wait();
     if (!String.IsNullOrEmpty(resourceId.LabName))
     {
         AddIMSIToVMAsync(resourceId, kvInfo, log).Wait();
     }
 }
Exemplo n.º 3
0
        public static void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
        {
            // Get Environment variables.
            KeyVaultInformation djSecrets = new KeyVaultInformation();
            djSecrets.KeyVaultName = GetEnvironmentVariable("AzureKeyVaultName"); //azureKeyVaultName;
            djSecrets.KeyVaultUri = "https://" + djSecrets.KeyVaultName + ".vault.azure.net";
            djSecrets.KeyVaultResourceGroup = GetEnvironmentVariable("AzureKeyVaultResourceGroup");
            djSecrets.KV_SecretName_ServicePrinciple = GetEnvironmentVariable("AzureServicePrincipalIdSecretName");
            djSecrets.KV_SecretName_ServicePrinciplePwd = GetEnvironmentVariable("AzureServicePrincipalCredSecretName");

            // Handle Azure Events
            AzureResourceInformation resourceId = GetVmResourceId(eventGridEvent);
            
            if (!string.IsNullOrWhiteSpace(resourceId.ResourceUri))
            {
                AzureResourceManager arm = new AzureResourceManager(resourceId, djSecrets, log);
            }
            log.LogInformation(eventGridEvent.Data.ToString());
        }
Exemplo n.º 4
0
        // Enable the IMSI on the Vm and add the IMSI id to the keyvault access policy
        public async Task AddIMSIToVMAsync(AzureResourceInformation resourceInfo, KeyVaultInformation vault, ILogger log)
        {
            // Handle multiple VMs in the same lab
            List <string> allVms = await GetArtifactInfoAsync(resourceInfo);

            if (allVms.Count > 0)
            {
                foreach (string vmResourceId in allVms)
                {
                    if (!string.IsNullOrWhiteSpace(vmResourceId))
                    {
                        try
                        {
                            var vm = await _msiazure.VirtualMachines.GetByIdAsync(vmResourceId);

                            if (!vm.IsManagedServiceIdentityEnabled)
                            {
                                // Don't await this call as issue where hangs, handle manually below
                                vm.Update().WithSystemAssignedManagedServiceIdentity().ApplyAsync();
                                // Handle await manually.
                                TimeSpan timeSpan = new TimeSpan(0, 0, 10);
                                int      counter  = 0;
                                await Task.Delay(timeSpan);

                                while ((!vm.IsManagedServiceIdentityEnabled) || (String.IsNullOrEmpty(vm.SystemAssignedManagedServiceIdentityPrincipalId)))
                                {
                                    counter++;
                                    await Task.Delay(timeSpan);

                                    log.LogInformation("[EnableVmMSIFunction] Enable IMSI loop:" + DateTime.Now.ToString());
                                    await vm.RefreshAsync();

                                    if (counter == 20)
                                    {
                                        break;
                                    }
                                }
                            }

                            await vm.RefreshAsync();

                            // Get the keyvault
                            var _keyVault = _msiazure.Vaults.GetByResourceGroup(vault.KeyVaultResourceGroup, vault.KeyVaultName);
                            // Add access policy
                            await _keyVault.Update()
                            .DefineAccessPolicy()
                            .ForObjectId(vm.SystemAssignedManagedServiceIdentityPrincipalId)
                            .AllowSecretPermissions(SecretPermissions.Get)
                            .Attach()
                            .ApplyAsync();

                            // Remove after 4 min
                            log.LogInformation("[EnableVmMSIFunction] Cleanup:" + DateTime.Now.ToString());
                            await RemoveAccess(vm, _keyVault, log);
                        }
                        catch (Exception e) {
                            log.LogInformation("[EnableVmMSIFunction][Error] " + e.Message);
                        }
                    }
                }
            }
        }