Example #1
0
        private static async Task <List <ActionResult> > RunSSHScript(ILog log, string command, string args, DeploymentTaskConfig settings, Dictionary <string, string> credentials)
        {
            var sshConfig = SshClient.GetConnectionConfig(settings, credentials);

            var ssh = new SshClient(sshConfig);

            var commandList = new List <string>
            {
                $"{command} {args}"
            };

            log?.Information($"Executing command via SSH [{sshConfig.Host}:{sshConfig.Port}]");

            var scriptResults = await Task.FromResult(ssh.ExecuteCommands(commandList, log));

            if (scriptResults.Any(r => r.IsError))
            {
                var firstError = scriptResults.First(c => c.IsError);
                return(new List <ActionResult> {
                    new ActionResult {
                        IsSuccess = false, Message = $"One or more commands failed: {firstError.Command} :: {firstError.Result}"
                    }
                });
            }
            else
            {
                return(new List <ActionResult> {
                    new ActionResult {
                        IsSuccess = true, Message = "Command Completed"
                    }
                });
            }
        }
Example #2
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));
        }