Ejemplo n.º 1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            //Logging.LogInformation("C# HTTP trigger function processed a request.");


            string  requestBody       = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data              = JsonConvert.DeserializeObject(requestBody);
            string  Subscription      = data?.subscriptionid;
            string  SQLServer         = data?.vmname;
            string  LoginNameToEnable = data?.vmresourcegroup;


            AzureCredentials msiCred = Helpers.GetAzureCreds(Helpers.GlobalConfigs.UseMSI);

            Microsoft.Azure.Management.Fluent.Azure.IAuthenticated azureAuth = Microsoft.Azure.Management.Fluent.Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders).Authenticate(msiCred);
            IAzure azure = azureAuth.WithSubscription(Subscription);



            return(SQLServer != null
                ? (ActionResult) new OkObjectResult($"Function completed for VM:")
                : new BadRequestObjectResult("Please pass a name, resourcegroup and action to request body"));
        }
Ejemplo n.º 2
0
        protected BaseDeployment(IAuthenticated azure, DeploymentOptions options)
        {
            Azure   = azure;
            Options = options;

            watch = new Stopwatch();
        }
 public KeyVaultDeployment(
     string vaultName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     VaultName = vaultName;
 }
 public StorageAccountDeployment(
     string accountName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     AccountName = accountName;
 }
Ejemplo n.º 5
0
 public VirtualMachineDeployment(
     string virtualMachineName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     VirtualMachineName = virtualMachineName;
 }
Ejemplo n.º 6
0
 public AzureFunctionDeployment(
     string appName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     AppName = appName;
 }
 public CosmosDbAccountDeployment(
     string docDbName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     DocDbName = docDbName;
 }
Ejemplo n.º 8
0
 public SqlAzureDeployment(
     string serverName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     ServerName = serverName;
 }
Ejemplo n.º 9
0
        public async Task <Result[]> Deploy(IAuthenticated azure, DeploymentOptions options, IEnumerable <AzureResource> resources)
        {
            var tasks = resources.Select(resource => CreateResourceAsync(azure, options, resource.Name, resource.Type)).ToList();

            var processingTasks = tasks.Select(async t => await t).ToArray();

            var result = await Task.WhenAll(processingTasks);

            return(result);
        }
Ejemplo n.º 10
0
        static Task <Result> CreateResourceAsync(IAuthenticated azure, DeploymentOptions options, string resourceName, AzureResourceType resourceType)
        {
            var            rName        = GetRandomResourceName(resourceType, resourceName);
            BaseDeployment deployment   = null;
            var            notSupported = $"Service {resourceType} not supported!";

            if (resourceType.Id == AzureResourceTypes.AppService.Id || resourceType.Id == AzureResourceTypes.WebApp.Id)
            {
                deployment = new WebAppDeployment(rName, azure, options);
            }
            else if (resourceType.Id == AzureResourceTypes.Storage.Id)
            {
                deployment = new StorageAccountDeployment(rName, azure, options);
            }
            else if (resourceType.Id == AzureResourceTypes.CosmosDB.Id)
            {
                deployment = new CosmosDbAccountDeployment(rName, azure, options);
            }
            else if (resourceType.Id == AzureResourceTypes.Functions.Id)
            {
                deployment = new AzureFunctionDeployment(rName, azure, options);
            }
            else if (resourceType.Id == AzureResourceTypes.SqlDatabase.Id)
            {
                deployment = new SqlAzureDeployment(rName, azure, options);
            }
            else if (resourceType.Id == AzureResourceTypes.KeyVault.Id)
            {
                deployment = new KeyVaultDeployment(rName, azure, options);
            }
            else if (resourceType.Id == AzureResourceTypes.VirtualMachine.Id)
            {
                deployment = new VirtualMachineDeployment(rName, azure, options);
            }
            else
            {
                Debug.WriteLine(notSupported);
            }

            return(deployment?.CreateAsync() ?? Task.FromResult(Result.Fail(notSupported)));
        }
Ejemplo n.º 11
0
 public ScanningFunctions(Microsoft.Azure.Management.Fluent.Azure.IAuthenticated auth, ILoggerFactory loggerFactory, IOptions <TaggingOptions> options) : base(auth, loggerFactory)
 {
     _options          = options.Value;
     _expirationTagKey = _options.ExpirationTagKey;
 }
Ejemplo n.º 12
0
        /// <summary>
        /// This method verifies that the Contributor permission has been granted on sufficient scopes to retrieve the key vaults.
        /// </summary>
        /// <param name="vaultList">The data obtained from deserializing json file</param>
        /// <param name="azureClient">The IAzure client used to access role assignments</param>
        public void checkAccess(JsonInput vaultList, Microsoft.Azure.Management.Fluent.Azure.IAuthenticated azureClient)
        {
            log.Info("Verifying access to Vaults...");
            List <string>    accessNeeded  = new List <string>();
            IRoleAssignments accessControl = azureClient.RoleAssignments;

            foreach (Resource res in vaultList.Resources)
            {
                try
                {
                    string subsPath        = Constants.SUBS_PATH + res.SubscriptionId;
                    var    roleAssignments = accessControl.ListByScope(subsPath).ToLookup(r => r.Inner.Scope);

                    var subsAccess = roleAssignments[subsPath].Count();
                    if (subsAccess == 0)
                    {
                        // At Subscription scope
                        if (res.ResourceGroups.Count == 0)
                        {
                            accessNeeded.Add(subsPath);
                        }
                        else
                        {
                            foreach (ResourceGroup resGroup in res.ResourceGroups)
                            {
                                string resGroupPath   = subsPath + Constants.RESGROUP_PATH + resGroup.ResourceGroupName;
                                var    resGroupAccess = roleAssignments[resGroupPath].Count();
                                if (resGroupAccess == 0)
                                {
                                    // At ResourceGroup scope
                                    if (resGroup.KeyVaults.Count == 0)
                                    {
                                        accessNeeded.Add(subsPath);
                                    }
                                    else
                                    {
                                        // At Vault scope
                                        foreach (string vaultName in resGroup.KeyVaults)
                                        {
                                            string vaultPath   = resGroupPath + Constants.VAULT_PATH + vaultName;
                                            var    vaultAccess = roleAssignments[vaultPath].Count();
                                            if (vaultAccess == 0)
                                            {
                                                accessNeeded.Add(vaultPath);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (CloudException e)
                {
                    log.Error("SubscriptionNotFound");
                    log.Debug($"{e.Message}. Please verify that your SubscriptionId is valid.");
                    Exit(e.Message);
                }
            }

            if (accessNeeded.Count() != 0)
            {
                log.Error("AuthorizationFail");
                log.Debug($"Contributor access is needed on the following scope(s): \n{string.Join("\n", accessNeeded)}. \nEnsure that your ResourceGroup and KeyVault names are spelled correctly " +
                          $"before proceeding. Note that if you are retrieving specific KeyVaults, your AAD must be granted access at either the KeyVault, ResourceGroup, Subscription level. " +
                          $"If you are retrieving all of the KeyVaults from a ResourceGroup, your AAD must be granted access at either the ResourceGroup or Subscription level. " +
                          $"If you are retrieving all of the KeyVaults from a SubscriptionId, your AAD must be granted access at the Subscription level. " +
                          $"Refer to the 'Granting Access to the AAD Application' section for more information on granting this access: https://github.com/microsoft/Managing-RBAC-in-Azure/blob/master/README.md");
                Exit($"Contributor access is needed on the following scope(s): \n{string.Join("\n", accessNeeded)}");
            }
            log.Info("Access verified!");
        }
Ejemplo n.º 13
0
 public async Task <Result> Deploy(IAuthenticated azure, DeploymentOptions options, AzureResource resource) =>
 await CreateResourceAsync(azure, options, resource.Name, resource.Type);
        public static async Task <JObject> StartAndStopVMsCore(HttpRequest req, Logging logging)
        {
            string  requestBody     = await new StreamReader(req.Body).ReadToEndAsync();
            JObject data            = JsonConvert.DeserializeObject <JObject>(requestBody);
            string  _TaskInstanceId = data["TaskInstanceId"].ToString();
            string  _ExecutionUid   = data["ExecutionUid"].ToString();

            try
            {
                logging.LogInformation("StartAndStopVMs function processed a request.");
                string Subscription    = data["Target"]["SubscriptionUid"].ToString();
                string VmName          = data["Target"]["VMname"].ToString();
                string VmResourceGroup = data["Target"]["ResourceGroup"].ToString();
                string VmAction        = data["Target"]["Action"].ToString();

                Microsoft.Azure.Management.Fluent.Azure.IAuthenticated azureAuth = Microsoft.Azure.Management.Fluent.Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders).Authenticate(Shared.Azure.AzureSDK.GetAzureCreds(Shared._ApplicationOptions.UseMSI));
                IAzure azure = azureAuth.WithSubscription(Subscription);
                logging.LogInformation("Selected subscription: " + azure.SubscriptionId);
                IVirtualMachine vm = azure.VirtualMachines.GetByResourceGroup(VmResourceGroup, VmName);
                if (vm.PowerState == Microsoft.Azure.Management.Compute.Fluent.PowerState.Deallocated && VmAction.ToLower() == "start")
                {
                    logging.LogInformation("VM State is: " + vm.PowerState.Value.ToString());
                    vm.StartAsync().Wait(5000);
                    logging.LogInformation("VM Start Initiated: " + vm.Name);
                }

                if (vm.PowerState != Microsoft.Azure.Management.Compute.Fluent.PowerState.Deallocated && VmAction.ToLower() == "stop")
                {
                    logging.LogInformation("VM State is: " + vm.PowerState.Value.ToString());
                    vm.DeallocateAsync().Wait(5000);
                    logging.LogInformation("VM Stop Initiated: " + vm.Name);
                }

                JObject Root = new JObject {
                    ["Result"] = "Complete"
                };

                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                if (VmName != null)
                {
                    Root["Result"] = "Complete";
                }
                else
                {
                    Root["Result"] = "Please pass a name, resourcegroup and action to request body";
                    TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, System.Guid.Empty, "Task missing VMname, ResourceGroup or SubscriptionUid in Target element.");
                    return(Root);
                }
                //Update Task Instance

                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.Complete, System.Guid.Empty, "");

                return(Root);
            }
            catch (System.Exception TaskException)
            {
                logging.LogErrors(TaskException);
                TaskMetaDataDatabase TMD = new TaskMetaDataDatabase();
                TMD.LogTaskInstanceCompletion(System.Convert.ToInt64(_TaskInstanceId), System.Guid.Parse(_ExecutionUid), TaskMetaData.BaseTasks.TaskStatus.FailedRetry, System.Guid.Empty, "Failed when trying to start or stop VM");

                JObject Root = new JObject
                {
                    ["Result"] = "Failed"
                };

                return(Root);
            }
        }