コード例 #1
0
        public async Task TestSftpFileCopy()
        {
            var credentialsManager = new CredentialsManager
            {
                StorageSubfolder = "credentials\\test"
            };

            string destPath = ConfigSettings["TestSSHPath"];

            var storedCred = await credentialsManager.GetUnlockedCredentialsDictionary(ConfigSettings["TestCredentialsKey_SSH"]);

            // var credentials = new UserCredentials(storedCred["username"], storedCred["password"]);

            // create a test temp file
            var tmpPath = Path.GetTempFileName();

            File.WriteAllText(tmpPath, "This is a test temp file");

            var files = new List <FileCopy>
            {
                new FileCopy {
                    SourcePath = tmpPath, DestinationPath = destPath + "/testfilecopy.txt"
                }
            };

            var client = new SftpClient(new SshConnectionConfig
            {
                Host           = ConfigSettings["TestSSHHost"],
                KeyPassphrase  = storedCred["password"],
                Port           = 22,
                Username       = storedCred["username"],
                PrivateKeyPath = ConfigSettings["TestSSHPrivateKeyPath"]
            });

            // test file list
            var fileList = client.ListFiles(destPath, null);

            Assert.IsTrue(fileList.Count > 0);

            // test file copy
            var copiedOK = client.CopyLocalToRemote(files, null);

            Assert.IsTrue(copiedOK);

            File.Delete(tmpPath);
        }
コード例 #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));
        }