public async Task TestWindowsNetworkFileCopy() { var destPath = ConfigSettings["TestUNCPath"]; var credentialsManager = new CredentialsManager { StorageSubfolder = "credentials\\test" }; var storedCred = await credentialsManager.GetUnlockedCredentialsDictionary(ConfigSettings["TestCredentialsKey_UNC"]); // 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 + @"\test-copy.txt" } }; var credentials = Plugin.DeploymentTasks.Shared.Helpers.GetWindowsCredentials(storedCred); var client = new WindowsNetworkFileClient(credentials); // test file list var fileList = client.ListFiles(destPath); Assert.IsTrue(fileList.Count > 0); // test file copy var results = client.CopyLocalToRemote(_log, files); File.Delete(tmpPath); Assert.IsTrue(results.All(s => s.IsSuccess == true)); }
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}" } }); } }
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)); }