/// <summary>
        /// Perform validation for a specific deployment task configuration
        /// </summary>
        /// <param name="managedCertificate"></param>
        /// <param name="taskConfig"></param>
        /// <returns></returns>
        public async Task <List <ActionResult> > ValidateDeploymentTask(ManagedCertificate managedCertificate, DeploymentTaskConfig taskConfig)
        {
            var provider = DeploymentTaskProviderFactory.Create(taskConfig.TaskTypeId.ToLower(), _pluginManager.DeploymentTaskProviders);

            Dictionary <string, string> credentials = null;

            if (!string.IsNullOrEmpty(taskConfig.ChallengeCredentialKey))
            {
                credentials = await _credentialsManager.GetUnlockedCredentialsDictionary(taskConfig.ChallengeCredentialKey);
            }

            try
            {
                var execParams = new DeploymentTaskExecutionParams(null, _credentialsManager, managedCertificate, taskConfig, credentials, true, provider.GetDefinition(), CancellationToken.None, new DeploymentContext {
                    PowershellExecutionPolicy = _serverConfig.PowershellExecutionPolicy
                });
                var validationResult = await provider.Validate(execParams);

                return(validationResult);
            }
            catch (Exception exp)
            {
                return(new List <ActionResult> {
                    new ActionResult("Failed to validate task: " + exp.ToString(), false)
                });
            }
        }
Beispiel #2
0
        /// <summary>
        /// Execute a local powershell script
        /// </summary>
        /// <param name="log"></param>
        /// <param name="managedCert"></param>
        /// <param name="settings"></param>
        /// <param name="credentials"></param>
        /// <param name="isPreviewOnly"></param>
        /// <returns></returns>
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var msg = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "message")?.Value;

            bool.TryParse(execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "throw")?.Value, out var shouldThrow);

            if (string.IsNullOrEmpty(msg))
            {
                // fail task
                execParams.Log?.Warning($"Mock Task says: <msg not supplied, task will fail>");

                return(new List <ActionResult> {
                    new ActionResult("Mock Task message not supplied.", false)
                });
            }
            else
            {
                if (shouldThrow)
                {
                    throw new System.Exception($"Mock task should throw: {msg}");
                }
                else
                {
                    execParams.Log?.Information($"Mock Task says: {msg}");
                    return(new List <ActionResult> {
                        new ActionResult($"{msg}.", true),
                        new ActionResult($"MockTaskWorkCompleted.", true)
                    });
                }
            }
        }
Beispiel #3
0
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

            var managedCert = ManagedCertificate.GetManagedCertificate(execParams.Subject);

            // check settings are valid before proceeding
            var validationResults = await Validate(execParams);

            if (validationResults.Any())
            {
                return(validationResults);
            }

            var requestedStore = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "storetype")?.Value.Trim().ToLower();
            var friendlyName   = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "friendlyname")?.Value.Trim();

            //store cert against primary domain, optionally with custom friendly name
            var certStoreName = CertificateManager.DEFAULT_STORE_NAME;

            if (requestedStore != "default")
            {
                certStoreName = requestedStore;
            }

            X509Certificate2 storedCert = null;

            if (!execParams.IsPreviewOnly)
            {
                try
                {
                    storedCert = await CertificateManager.StoreCertificate(
                        managedCert.RequestConfig.PrimaryDomain,
                        managedCert.CertificatePath,
                        isRetry : false,
                        enableRetryBehaviour : _enableCertDoubleImportBehaviour,
                        storeName : certStoreName,
                        customFriendlyName : friendlyName
                        );

                    if (storedCert != null)
                    {
                        // certHash = storedCert.GetCertHash();

                        results.Add(new ActionResult("Certificate stored OK", true));
                    }
                }
                catch (Exception exp)
                {
                    results.Add(new ActionResult("Error storing certificate :: " + exp.Message, false));
                }
            }
            else
            {
                results.Add(new ActionResult($"Would store certificate in Local Certificate Store [{certStoreName}]", true));
            }

            return(results);
        }
        /// <summary>
        /// Deploy current cert to Azure Key Vault
        /// </summary>
        /// <param name="log"></param>
        /// <param name="managedCert"></param>
        /// <param name="settings"></param>
        /// <param name="credentials"></param>
        /// <param name="isPreviewOnly"></param>
        /// <returns></returns>
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var definition = GetDefinition(execParams.Definition);

            var results = await Validate(execParams);

            if (results.Any())
            {
                return(results);
            }

            var managedCert = ManagedCertificate.GetManagedCertificate(execParams.Subject);

            if (string.IsNullOrEmpty(managedCert.CertificatePath))
            {
                results.Add(new ActionResult("No certificate to deploy.", false));
                return(results);
            }

            var keyVaultUri = new Uri(execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "vault_uri")?.Value);

            var pfxData = File.ReadAllBytes(managedCert.CertificatePath);

            // from application user details in Azure AD

            var cred = new ClientSecretCredential(execParams.Credentials["tenantid"], execParams.Credentials["clientid"], execParams.Credentials["secret"]);

            var client = new CertificateClient(keyVaultUri, cred);

            var customName = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "cert_name")?.Value;

            var certName = GetStringAsKeyVaultName(customName ?? managedCert.Name);

            var importOptions = new ImportCertificateOptions(certName, pfxData);

            try
            {
                await client.ImportCertificateAsync(importOptions);

                execParams.Log.Information($"Deployed certificate [{certName}] to Azure Key Vault");

                results.Add(new ActionResult("Certificate Deployed to Azure Key Vault", true));
            }
            catch (AuthenticationFailedException exp)
            {
                execParams.Log.Error($"Azure Authentiation error: {exp.InnerException?.Message ?? exp.Message}");
                results.Add(new ActionResult("Key Vault Deployment Failed", false));
            }
            catch (Exception exp)
            {
                execParams.Log.Error($"Failed to deploy certificate [{certName}] to Azure Key Vault :{exp}");
                results.Add(new ActionResult("Key Vault Deployment Failed", false));
            }

            return(results);
        }
Beispiel #5
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult> {
            };

            foreach (var p in execParams.Definition.ProviderParameters)
            {
                if (!execParams.Settings.Parameters.Exists(s => s.Key == p.Key) && p.IsRequired)
                {
                    results.Add(new ActionResult($"Required parameter not supplied: { p.Name}", false));
                }
            }
            return(results);
        }
Beispiel #6
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

            var requestedStore = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "storetype")?.Value.Trim().ToLower();
            var friendlyName   = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "friendlyname")?.Value;

            if (!string.IsNullOrEmpty(requestedStore))
            {
                // check store name is valid

                if (!(requestedStore == "default" || requestedStore.ToLower() == "my" || requestedStore == "webhosting"))
                {
                    results.Add(new ActionResult($"Invalid Certificate Store Name: {requestedStore}", false));
                }
            }

            return(results);
        }
Beispiel #7
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

            var url    = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "url")?.Value;
            var method = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "method")?.Value;

            if (url == null || !Uri.TryCreate(url, UriKind.Absolute, out var result))
            {
                results.Add(new ActionResult($"The webhook url must be a valid url.", false));
            }

            if (string.IsNullOrEmpty(method))
            {
                results.Add(new ActionResult($"The webhook HTTP method must be a selected.", false));
            }

            return(await Task.FromResult(results));
        }
Beispiel #8
0
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var managedCert = ManagedCertificate.GetManagedCertificate(execParams.Subject);

            try
            {
                var webhookConfig = new Shared.Utils.Webhook.WebhookConfig
                {
                    Url         = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "url")?.Value,
                    Method      = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "method")?.Value,
                    ContentType = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "contenttype")?.Value,
                    ContentBody = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "contentbody")?.Value
                };

                if (!execParams.IsPreviewOnly)
                {
                    var webHookResult = await Certify.Shared.Utils.Webhook.SendRequest(webhookConfig, managedCert, managedCert.LastRenewalStatus != RequestState.Error);

                    var msg = $"Webhook invoked: Url: {webhookConfig.Url}, Success: {webHookResult.Success}, StatusCode: {webHookResult.StatusCode}";

                    execParams.Log.Information(msg);

                    return(new List <ActionResult> {
                        new ActionResult(msg, true)
                    });
                }
                else
                {
                    return(await Validate(execParams));
                }
            }
            catch (Exception exp)
            {
                return(new List <ActionResult> {
                    new ActionResult("Webhook call failed: " + exp.ToString(), false)
                });
            }
        }
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult> {
            };

            var uri = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "vault_uri")?.Value;

            if (string.IsNullOrEmpty(uri))
            {
                results.Add(new ActionResult("Vault URI is required e.g. https://<vault-name>.vault.azure.net/", false));
            }

            var cert_name = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "cert_name")?.Value;

            if (!string.IsNullOrEmpty(cert_name))
            {
                if (!Regex.IsMatch(cert_name, "^[0-9a-zA-Z-]+$"))
                {
                    results.Add(new ActionResult("Certificate name can only be alphanumeric.", false));
                }
            }
            return(results);
        }
Beispiel #10
0
 public Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
 {
     throw new System.NotImplementedException();
 }