Exemplo n.º 1
0
        public Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var settings = execParams.Settings;

            var results = new List <ActionResult> {
            };

            if (settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL || settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL_AS_USER)
            {
                //
            }
            else if (settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_WINDOWS)
            {
                //if windows network and paths are not UNC, fail validation
                var path = settings.Parameters.FirstOrDefault(c => c.Key == "path")?.Value.Trim();
                if (!path.StartsWith("\\\\"))
                {
                    results.Add(new ActionResult {
                        IsSuccess = false, Message = "UNC Path Expected for Windows Network resource"
                    });
                }
            }

            return(Task.FromResult(results));
        }
Exemplo n.º 2
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult> {
            };

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

            if (string.IsNullOrEmpty(duration))
            {
                results.Add(new ActionResult("Invalid duration specified. An integer value is required.", false));
                return(results);
            }

            if (!int.TryParse(execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "duration")?.Value, out var durationSeconds))
            {
                results.Add(new ActionResult("Invalid duration specified. An integer value is required.", false));
            }
            else
            {
                if (durationSeconds < 0 || durationSeconds > MAX_DURATION)
                {
                    results.Add(new ActionResult($"Duration specified is outside the supported range. Max wait duration is {MAX_DURATION}", false));
                }
            }

            return(await Task.FromResult(results));
        }
Exemplo n.º 3
0
        public new async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var definition = GetDefinition(execParams.Definition);
            var settings   = execParams.Settings;

            // for each item, execute a certificate export
            var results = new List <ActionResult>();

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

            settings.Parameters.Add(new ProviderParameterSetting("path", null));
            settings.Parameters.Add(new ProviderParameterSetting("type", null));

            var certPath = settings.Parameters.FirstOrDefault(p => p.Key == "path_pfx");

            if (!string.IsNullOrWhiteSpace(certPath?.Value))
            {
                settings.Parameters.Find(p => p.Key == "path").Value = certPath.Value;
                settings.Parameters.Find(p => p.Key == "type").Value = "pfxfull";

                execParams.Log.Information(definition.Title + ":: exporting PFX format certificates and key");
                results.AddRange(await base.Execute(new DeploymentTaskExecutionParams(execParams, definition)));
            }

            return(results);
        }
Exemplo n.º 4
0
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var validation = await Validate(execParams);

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

            var script = Helpers.ReadStringResource(SCRIPT_NAME);

            var certRequest = execParams.Subject as CertificateRequestResult;

            execParams.Log?.Information("Executing command via PowerShell");

            var services        = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "services")?.Value;
            var doNotRequireSsl = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "donotrequiressl")?.Value;

            var parameters = new Dictionary <string, object>
            {
                { "services", services },
                { "addDoNotRequireSslFlag", doNotRequireSsl }
            };

            var scriptResult = await PowerShellManager.RunScript(execParams.Context.PowershellExecutionPolicy, certRequest, parameters : parameters, scriptContent : script, credentials : execParams.Credentials);

            return(new List <ActionResult> {
                scriptResult
            });
        }
Exemplo n.º 5
0
        public new async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            // validate a certificate export
            var results  = new List <ActionResult>();
            var settings = execParams.Settings;

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

            settings.Parameters.Add(new ProviderParameterSetting("path", null));
            settings.Parameters.Add(new ProviderParameterSetting("type", null));

            var certPath = settings.Parameters.FirstOrDefault(p => p.Key == "path_pfx");

            if (string.IsNullOrEmpty(certPath.Value))
            {
                results.Add(new ActionResult
                {
                    IsSuccess = false,
                    Message   = "Required: " + Definition.ProviderParameters.First(f => f.Key == "path_pfx").Name
                });
            }
            else
            {
                settings.Parameters.Find(p => p.Key == "path").Value = certPath.Value;
                settings.Parameters.Find(p => p.Key == "type").Value = "pfxfull";
                results.AddRange(await base.Validate(execParams));
            }

            return(results);
        }
Exemplo n.º 6
0
        public async Task <List <ActionResult> > Execute(
            ILog log,
            ICredentialsManager credentialsManager,
            object subject,
            CancellationToken cancellationToken,
            bool isPreviewOnly = true
            )
        {
            if (TaskProvider != null && TaskConfig != null)
            {
                try
                {
                    var execParams = new DeploymentTaskExecutionParams(log, credentialsManager, subject, TaskConfig, _credentials, isPreviewOnly, null, cancellationToken);

                    return(await TaskProvider.Execute(execParams));
                }
                catch (Exception exp)
                {
                    return(new List <ActionResult> {
                        new ActionResult {
                            IsSuccess = false, Message = $"{TaskConfig.TaskName} ({TaskProvider.GetDefinition()?.Title }) :: Task Failed with Exception :: {exp?.ToString()}"
                        }
                    });
                }
            }
            else
            {
                return(new List <ActionResult> {
                    new ActionResult {
                        IsSuccess = false, Message = "Cannot Execute Deployment Task: TaskProvider or Config not set."
                    }
                });
            }
        }
Exemplo n.º 7
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

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

            if (string.IsNullOrEmpty(path))
            {
                results.Add(new ActionResult("A path to a script is required.", false));
            }
            else
            {
                if (!System.IO.File.Exists(path))
                {
                    results.Add(new ActionResult("There is no script file present at the given path: " + path, false));
                }
            }

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

            if (!string.IsNullOrEmpty(timeoutMinutes))
            {
                if (!int.TryParse(timeoutMinutes, out int timeout))
                {
                    results.Add(new ActionResult("Timeout (Minutes) value is invalid", false));
                }

                if (timeout < 1 || timeout > 120)
                {
                    results.Add(new ActionResult("Timeout (Minutes) value is out of range (1-120).", false));
                }
            }
            return(await Task.FromResult(results));
        }
Exemplo n.º 8
0
        public async new Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var definition = GetDefinition(execParams.Definition);
            var settings   = execParams.Settings;

            // for each item, execute a certificate export
            var results = new List <ActionResult>();

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

            settings.Parameters.Add(new ProviderParameterSetting("path", null));
            settings.Parameters.Add(new ProviderParameterSetting("type", null));

            var certPath = settings.Parameters.FirstOrDefault(p => p.Key == "path_cert");

            if (certPath != null)
            {
                settings.Parameters.Find(p => p.Key == "path").Value = certPath.Value;
                settings.Parameters.Find(p => p.Key == "type").Value = "pemcrtpartialchain";
                results.AddRange(await base.Execute(execParams));
            }

            var keyPath = settings.Parameters.FirstOrDefault(p => p.Key == "path_key");

            if (keyPath != null && !results.Any(r => r.IsSuccess == false))
            {
                settings.Parameters.Find(p => p.Key == "path").Value = keyPath.Value;
                settings.Parameters.Find(p => p.Key == "type").Value = "pemkey";
                results.AddRange(await base.Execute(new DeploymentTaskExecutionParams(execParams, definition)));
            }

            return(results);
        }
Exemplo n.º 9
0
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var validation = await Validate(execParams);

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

            var script = Helpers.ReadStringResource(SCRIPT_NAME);

            var definition = execParams.Definition;

            definition = GetDefinition(definition);

            var certRequest = execParams.Subject as CertificateRequestResult;

            execParams.Log?.Information("Executing command via PowerShell");

            var performRestart      = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "performServiceRestart")?.Value ?? "false";
            var alternateTlsBinding = execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "alternateTlsBinding")?.Value ?? "false";

            var parameters = new Dictionary <string, object>
            {
                { "performServiceRestart", performRestart },
                { "alternateTlsBinding", alternateTlsBinding }
            };

            var scriptResult = await PowerShellManager.RunScript(execParams.Context.PowershellExecutionPolicy, certRequest, parameters : parameters, scriptContent : script, credentials : execParams.Credentials);

            return(new List <ActionResult> {
                scriptResult
            });
        }
Exemplo n.º 10
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

            // validate

            return(await Task.FromResult(results));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Execute a script or program either locally or remotely, windows or ssh
        /// </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 command = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "path")?.Value;
            var args    = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "args")?.Value;


            //TODO: non-ssh local script
            if (execParams.Settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_SSH)
            {
                return(await RunSSHScript(execParams.Log, command, args, execParams.Settings, execParams.Credentials));
            }
            else if (execParams.Settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL)
            {
                var result = RunLocalScript(execParams.Log, command, args, execParams.Settings, execParams.Credentials);
                results.Add(result);
            }
            else if (execParams.Settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL_AS_USER || execParams.Settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_WINDOWS)
            {
                UserCredentials windowsCredentials = null;
                if (execParams.Credentials != null && execParams.Credentials.Count > 0)
                {
                    try
                    {
                        windowsCredentials = Helpers.GetWindowsCredentials(execParams.Credentials);
                    }
                    catch
                    {
                        var err = "Task with Windows Credentials requires username and password.";
                        execParams.Log.Error(err);

                        return(new List <ActionResult> {
                            new ActionResult {
                                IsSuccess = false, Message = err
                            }
                        });
                    }
                }

                var _defaultLogonType = LogonType.NewCredentials;

                Impersonation.RunAsUser(windowsCredentials, _defaultLogonType, () =>
                {
                    var result = RunLocalScript(execParams.Log, command, args, execParams.Settings, execParams.Credentials);
                    results.Add(result);
                });
            }
            return(results);
        }
Exemplo n.º 12
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 results = new List <ActionResult>();

            var certRequest = execParams.Subject as CertificateRequestResult;

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

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

            var parameters = new Dictionary <string, object>();

            if (inputResultAsArgument?.Trim().ToLower() == "true")
            {
                parameters.Add("result", certRequest);
            }
            ;

            if (!string.IsNullOrEmpty(args))
            {
                foreach (var o in args.Split(';'))
                {
                    if (!string.IsNullOrEmpty(o))
                    {
                        var keyValuePair = o.Split('=');

                        if (keyValuePair.Length == 1)
                        {
                            // item has a key only
                            parameters.Add(keyValuePair[0].Trim(), "");
                        }
                        else
                        {
                            // item has a key and value
                            parameters.Add(keyValuePair[0].Trim(), keyValuePair[1].Trim());
                        }
                    }
                }
            }

            execParams.Log?.Information("Executing command via PowerShell");

            string logonType = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "logontype")?.Value ?? null;

            // if running as local/default service user no credentials are provided for user impersonation
            var credentials = execParams.Settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL ? null : execParams.Credentials;

            var result = await PowerShellManager.RunScript(execParams.Context.PowershellExecutionPolicy, null, command, parameters, null, credentials : credentials, logonType : logonType);

            results.Add(result);

            return(results);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Create new set of exec params from a source with a different provider definition
 /// </summary>
 /// <param name="execParams"></param>
 /// <param name="definition"></param>
 public DeploymentTaskExecutionParams(DeploymentTaskExecutionParams execParams, DeploymentProviderDefinition definition)
 {
     Log = execParams.Log;
     CredentialsManager = execParams.CredentialsManager;
     Subject            = execParams.Subject;
     Settings           = execParams.Settings;
     Credentials        = execParams.Credentials;
     IsPreviewOnly      = execParams.IsPreviewOnly;
     Definition         = definition ?? execParams.Definition;
     CancellationToken  = execParams.CancellationToken;
 }
Exemplo n.º 14
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

            if (string.IsNullOrEmpty(execParams.Settings.Parameters.FirstOrDefault(p => p.Key == "services")?.Value))
            {
                results.Add(new ActionResult("One or more services are required to apply certificate to. E.g. POP,IMAP,SMTP,IIS", false));
            }

            return(await Task.FromResult(results));
        }
Exemplo n.º 15
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

            var destinationPath = execParams.Settings.Parameters?.FirstOrDefault(d => d.Key == "path")?.Value;

            if (string.IsNullOrEmpty(destinationPath))
            {
                results.Add(new ActionResult("A path parameter is required for export.", false));
            }

            return(await Task.FromResult(results));
        }
Exemplo n.º 16
0
        public new async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var definition = GetDefinition(execParams.Definition);
            var settings   = execParams.Settings;

            // for each item, execute a certificate export
            var results = new List <ActionResult>();

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

            settings.Parameters.Add(new ProviderParameterSetting("path", null));
            settings.Parameters.Add(new ProviderParameterSetting("type", null));

            var certPath = settings.Parameters.FirstOrDefault(p => p.Key == "path_cert");

            if (!string.IsNullOrWhiteSpace(certPath?.Value))
            {
                settings.Parameters.Find(p => p.Key == "path").Value = certPath.Value;
                settings.Parameters.Find(p => p.Key == "type").Value = "pemcrt";

                execParams.Log.Information(definition.Title + ":: exporting PEM format certificate file");
                results.AddRange(await base.Execute(new DeploymentTaskExecutionParams(execParams, definition)));
            }

            var keyPath = settings.Parameters.FirstOrDefault(p => p.Key == "path_key");

            if (!string.IsNullOrWhiteSpace(keyPath?.Value) && !results.Any(r => r.IsSuccess == false))
            {
                settings.Parameters.Find(p => p.Key == "path").Value = keyPath.Value;
                settings.Parameters.Find(p => p.Key == "type").Value = "pemkey";

                execParams.Log.Information(definition.Title + ":: exporting PEM format key file");
                results.AddRange(await base.Execute(new DeploymentTaskExecutionParams(execParams, definition)));
            }

            var chainPath = settings.Parameters.FirstOrDefault(p => p.Key == "path_chain");

            if (!string.IsNullOrWhiteSpace(chainPath?.Value) && !results.Any(r => r.IsSuccess == false))
            {
                settings.Parameters.Find(p => p.Key == "path").Value = chainPath.Value;
                settings.Parameters.Find(p => p.Key == "type").Value = "pemchain";

                execParams.Log.Information(definition.Title + ":: exporting PEM format chain file");
                results.AddRange(await base.Execute(new DeploymentTaskExecutionParams(execParams, definition)));
            }

            return(results);
        }
Exemplo n.º 17
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 definition = GetDefinition(execParams.Definition);

            var validation = await Validate(execParams);

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

            if (int.TryParse(execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "duration")?.Value, out var durationSeconds))
            {
                execParams.Log?.Information($"Waiting for {durationSeconds} seconds..");
                await Task.Delay(durationSeconds * 1000, execParams.CancellationToken);
            }

            return(new List <ActionResult>());
        }
Exemplo n.º 18
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

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

            if (string.IsNullOrEmpty(path))
            {
                results.Add(new ActionResult("A path to a script is required.", false));
            }
            else
            {
                if (!System.IO.File.Exists(path))
                {
                    results.Add(new ActionResult("There is no script file present at the given path: " + path, false));
                }
            }

            return(await Task.FromResult(results));
        }
Exemplo n.º 19
0
        public async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List <ActionResult>();

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

            if (string.IsNullOrEmpty(path))
            {
                results.Add(new ActionResult("A path to a script is required.", false));
            }
            else
            {
                if ((execParams.Settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL || execParams.Settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL_AS_USER) && !System.IO.File.Exists(path))
                {
                    results.Add(new ActionResult("There is no local script file present at the given path: " + path, false));
                }
            }

            return(await Task.FromResult(results));
        }
Exemplo n.º 20
0
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var validation = await Validate(execParams);

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

            var script = Helpers.ReadStringResource(SCRIPT_NAME);

            var certRequest = execParams.Subject as CertificateRequestResult;

            execParams.Log?.Information("Executing command via PowerShell");

            var parameters = new Dictionary <string, object>();

            var scriptResult = await PowerShellManager.RunScript(execParams.Context.PowershellExecutionPolicy, certRequest, parameters : parameters, scriptContent : script, credentials : execParams.Credentials);

            return(new List <ActionResult> {
                scriptResult
            });
        }
Exemplo n.º 21
0
        public async Task <List <ActionResult> > Execute(
            DeploymentTaskExecutionParams execParams
            )
        {
            var definition = execParams.Definition;

            if (definition == null)
            {
                definition = CertificateExport.Definition;
            }

            var results = await Validate(execParams);

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

            if (string.IsNullOrEmpty(managedCert.CertificatePath) || !File.Exists(managedCert.CertificatePath))
            {
                results.Add(new ActionResult("Source certificate file is not present. Export cannot continue.", false));
            }

            if (results.Any())
            {
                // failed validation
                return(results);
            }

            try
            {
                var settings = execParams.Settings;
                var log      = execParams.Log;

                // prepare collection of files in the required formats

                // copy files to the required destination (local, UNC or SFTP)

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

                // prepare list of files to copy

                var destPath = settings.Parameters.FirstOrDefault(c => c.Key == "path")?.Value.Trim();

                if (string.IsNullOrEmpty(destPath))
                {
                    return(new List <ActionResult> {
                        new ActionResult("Empty path provided. Skipping export", false)
                    });
                }

                var exportType = settings.Parameters.FirstOrDefault(c => c.Key == "type")?.Value.Trim();
                var files      = new Dictionary <string, byte[]>();

                var certPwd = "";

                if (!string.IsNullOrWhiteSpace(managedCert.CertificatePasswordCredentialId))
                {
                    var cred = await execParams.CredentialsManager.GetUnlockedCredentialsDictionary(managedCert.CertificatePasswordCredentialId);

                    if (cred != null)
                    {
                        certPwd = cred["password"];
                    }
                }


                // TODO: custom pfx pwd for export

                /*
                 * if (execParams.Credentials != null && execParams.Credentials.Any(c => c.Key == "cert_pwd_key"))
                 * {
                 *  var credKey = execParams.Credentials.First(c => c.Key == "cert_pwd_key");
                 * }
                 */

                if (exportType == "pfxfull")
                {
                    files.Add(destPath, pfxData);
                }
                else if (exportType == "pemkey")
                {
                    files.Add(destPath, GetCertComponentsAsPEMBytes(pfxData, certPwd, ExportFlags.PrivateKey));
                }
                else if (exportType == "pemchain")
                {
                    files.Add(destPath, GetCertComponentsAsPEMBytes(pfxData, certPwd, ExportFlags.IntermediateCertificates | ExportFlags.RootCertificate));
                }
                else if (exportType == "pemcrt")
                {
                    files.Add(destPath, GetCertComponentsAsPEMBytes(pfxData, certPwd, ExportFlags.EndEntityCertificate));
                }
                else if (exportType == "pemcrtpartialchain")
                {
                    files.Add(destPath, GetCertComponentsAsPEMBytes(pfxData, certPwd, ExportFlags.EndEntityCertificate | ExportFlags.IntermediateCertificates));
                }
                else if (exportType == "pemfull")
                {
                    files.Add(destPath, GetCertComponentsAsPEMBytes(pfxData, certPwd, ExportFlags.PrivateKey | ExportFlags.EndEntityCertificate | ExportFlags.IntermediateCertificates | ExportFlags.RootCertificate));
                }

                // copy to destination

                var copiedOk = false;
                var msg      = "";
                if (settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_SSH)
                {
                    // sftp file copy
                    var sshConfig = SshClient.GetConnectionConfig(settings, execParams.Credentials);

                    var sftp       = new SftpClient(sshConfig);
                    var remotePath = destPath;

                    if (execParams.IsPreviewOnly)
                    {
                        var step = $"{definition.Title}: (Preview) would copy file via sftp to {remotePath} on host {sshConfig.Host}:{sshConfig.Port}";
                        msg += step + "\r\n";
                        log.Information(msg);
                    }
                    else
                    {
                        // copy via sftp
                        copiedOk = sftp.CopyLocalToRemote(files, log);

                        if (copiedOk)
                        {
                            log.Information($"{definition.Title}: copied file via sftp to {remotePath} on host {sshConfig.Host}:{sshConfig.Port}");
                        }
                        else
                        {
                            // file copy failed, abort
                            return(new List <ActionResult> {
                                new ActionResult {
                                    IsSuccess = false, Message = "Export failed due to connection or file copy failure. Check log for more information."
                                }
                            });
                        }
                    }
                }
                else if (settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_WINDOWS || settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL_AS_USER || settings.ChallengeProvider == StandardAuthTypes.STANDARD_AUTH_LOCAL)
                {
                    // windows remote file copy

                    UserCredentials windowsCredentials = null;
                    if (execParams.Credentials != null && execParams.Credentials.Count > 0)
                    {
                        try
                        {
                            windowsCredentials = Helpers.GetWindowsCredentials(execParams.Credentials);
                        }
                        catch
                        {
                            var err = "Task with Windows Credentials requires username and password.";
                            log.Error(err);

                            return(new List <ActionResult> {
                                new ActionResult {
                                    IsSuccess = false, Message = err
                                }
                            });
                        }
                    }


                    var _client = new WindowsNetworkFileClient(windowsCredentials);
                    if (execParams.IsPreviewOnly)
                    {
                        var step = $"{definition.Title}: (Preview) Windows file copy to {destPath}";
                        msg += step + " \r\n";
                    }
                    else
                    {
                        var step = $"{definition.Title}: Copying file (Windows file copy) to {destPath}";
                        msg += step + " \r\n";
                        log.Information(step);

                        var copyResults = _client.CopyLocalToRemote(log, files);

                        results.AddRange(copyResults);
                    }
                }
            }
            catch (Exception exp)
            {
                results.Add(new ActionResult($"Export failed with error: {exp}", false));
            }

            return(await Task.FromResult(results));
        }
Exemplo n.º 22
0
        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;

            }
            string vaultUri = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "vault_uri")?.Value;
            string vaultPath = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "vault_secret_path")?.Value;

            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("X-Vault-Token", execParams.Credentials["api_token"]);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var vaultUrl = $"{vaultUri}{vaultPath}";

            byte[] pfxData = File.ReadAllBytes(managedCert.CertificatePath);

            var pfxPwd = "";

            var secret = new
            {
                data = new
                {
                    key = GetEncodedCertComponent("pemkey", pfxData, pfxPwd),
                    cert = GetEncodedCertComponent("pemcrt", pfxData, pfxPwd),
                    intermediates = GetEncodedCertComponent("pemchain", pfxData, pfxPwd),
                    pfx = GetEncodedCertComponent("pfxfull", pfxData, pfxPwd)
                }
            };

            /*
                {
                  "data": { },
                  "options": { },
                  "version": 0
                }";
            */

            var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(secret), System.Text.UnicodeEncoding.UTF8, "application/json");

            execParams.Log.Information($"Deploying to Vault: {vaultUrl}");

            var response = await httpClient.PostAsync(vaultUrl, content);

            if (response.IsSuccessStatusCode)
            {
                return results;
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync();
                return new List<ActionResult> { new ActionResult("Vault storage failed: " + error, false) };
            }
        }
Exemplo n.º 23
0
 public new async Task <List <ActionResult> > Validate(DeploymentTaskExecutionParams execParams)
 {
     return(await base.Validate(execParams));
 }
Exemplo n.º 24
0
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var settings = execParams.Settings;

            var definition = GetDefinition(execParams.Definition);

            List <ActionResult> results = await Validate(execParams);

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

            if (!int.TryParse(settings.Parameters.FirstOrDefault(c => c.Key == "maxwait")?.Value, out var durationSeconds))
            {
                durationSeconds = 20;
            }

            var servicename = settings.Parameters.FirstOrDefault(c => c.Key == "servicename")?.Value;
            var action      = settings.Parameters.FirstOrDefault(c => c.Key == "action")?.Value;

            ServiceController service = new ServiceController(servicename);

            var ticks = System.TimeSpan.FromSeconds(durationSeconds);

            if (action == "restart")
            {
                if (service.Status != ServiceControllerStatus.Stopped)
                {
                    if (!execParams.IsPreviewOnly)
                    {
                        service = await StopServiceWithRetry(execParams.Log, servicename, service, ticks);
                    }
                }
                else
                {
                    execParams.Log?.Information($"Service already stopped [{servicename}] ");
                }

                if (!execParams.IsPreviewOnly)
                {
                    service = await StartServiceWithRetry(execParams.Log, servicename, service, ticks);

                    results.Add(new ActionResult("Service Restarted", true));
                }
                else
                {
                    results.Add(new ActionResult("[Preview] Service would restart.", true));
                }
            }
            else if (action == "stop")
            {
                if (service.Status != ServiceControllerStatus.Stopped)
                {
                    if (!execParams.IsPreviewOnly)
                    {
                        service = await StopServiceWithRetry(execParams.Log, servicename, service, ticks);

                        results.Add(new ActionResult("Service Stopped", true));
                    }
                    else
                    {
                        results.Add(new ActionResult("[Preview] Service would be stopped", true));
                    }
                }
                else
                {
                    execParams.Log?.Information($"Service already stopped [{servicename}] ");

                    results.Add(new ActionResult("Service already stopped", true));
                }
            }
            else if (action == "start")
            {
                if (!execParams.IsPreviewOnly)
                {
                    service = await StartServiceWithRetry(execParams.Log, servicename, service, ticks);

                    results.Add(new ActionResult("Service Started", true));
                }
                else
                {
                    results.Add(new ActionResult("[Preview] Service would be started", true));
                }
            }

            return(results);
        }
Exemplo n.º 25
0
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var validationResults = await this.Validate(execParams);

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

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

            UserCredentials windowsCredentials = null;

            if (execParams.Credentials != null && execParams.Credentials.Count > 0)
            {
                try
                {
                    windowsCredentials = Helpers.GetWindowsCredentials(execParams.Credentials);
                }
                catch
                {
                    return(new List <ActionResult> {
                        new ActionResult {
                            IsSuccess = false, Message = "CCS Export task with Windows Credentials requires username and password."
                        }
                    });
                }
            }

            try
            {
                var windowsFileClient = new WindowsNetworkFileClient(windowsCredentials);

                var domains = managedCert.GetCertificateDomains();

                var fileList = new List <FileCopy>();

                var destinationPath = execParams.Settings.Parameters?.FirstOrDefault(d => d.Key == "path")?.Value;

                foreach (var domain in domains)
                {
                    // normalise wildcard domains to _.domain.com for file store
                    var targetDomain = domain.Replace('*', '_');

                    // attempt save to store, which may be a network UNC path or otherwise authenticated resource

                    if (!string.IsNullOrWhiteSpace(destinationPath))
                    {
                        var filename = Path.Combine(destinationPath.Trim(), targetDomain + ".pfx");

                        execParams.Log?.Information($"{Definition.Title}: Storing PFX as {filename}");

                        fileList.Add(new FileCopy {
                            SourcePath = managedCert.CertificatePath, DestinationPath = filename
                        });
                    }
                }

                if (fileList.Count == 0)
                {
                    return(new List <ActionResult> {
                        new ActionResult {
                            IsSuccess = true, Message = $"{Definition.Title}: Nothing to copy."
                        }
                    });
                }
                else
                {
                    if (!execParams.IsPreviewOnly)
                    {
                        windowsFileClient.CopyLocalToRemote(execParams.Log, fileList);
                    }
                }

                return(new List <ActionResult> {
                    new ActionResult {
                        IsSuccess = true, Message = "File copying completed"
                    }
                });
            }
            catch (Exception exp)
            {
                return(new List <ActionResult> {
                    new ActionResult {
                        IsSuccess = false, Message = $"CCS Export Failed with error: {exp}"
                    }
                });
            }
        }