Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
leefine02 authored and leefine02 committed Apr 7, 2024
1 parent 08cd1d0 commit b3b215e
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 50 deletions.
5 changes: 3 additions & 2 deletions RemoteFile/RemoteCertificateStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
using Keyfactor.Extensions.Orchestrator.RemoteFile.Models;
using Keyfactor.Logging;
using System.Management.Automation;
using System.Runtime.InteropServices;

namespace Keyfactor.Extensions.Orchestrator.RemoteFile
{
Expand Down Expand Up @@ -332,8 +333,8 @@ internal void Initialize()
{
logger.MethodEntry(LogLevel.Debug);

if (ServerType == ServerTypeEnum.Linux)
RemoteHandler = new SSHHandler(Server, ServerId, ServerPassword);
if (ServerType == ServerTypeEnum.Linux || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
RemoteHandler = new SSHHandler(Server, ServerId, ServerPassword, ServerType == ServerTypeEnum.Linux);
else
RemoteHandler = new WinRMHandler(Server, ServerId, ServerPassword);

Expand Down
8 changes: 8 additions & 0 deletions RemoteFile/RemoteFile.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>none</DebugType>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType>
</PropertyGroup>

<ItemGroup>
<Compile Remove="ImplementedStoreTypes\JKS\JksStore.cs" />
<Compile Remove="RemoteHandlers\SSHHelper.cs" />
Expand Down
122 changes: 76 additions & 46 deletions RemoteFile/RemoteHandlers/SSHHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,77 +19,91 @@
using Keyfactor.Logging;
using Keyfactor.PKI.PrivateKeys;
using Keyfactor.PKI.PEM;
using System.Runtime.InteropServices;

namespace Keyfactor.Extensions.Orchestrator.RemoteFile.RemoteHandlers
{
class SSHHandler : BaseRemoteHandler
{
private const string LINUX_PERMISSION_REGEXP = "^[0-7]{3}$";
private ConnectionInfo Connection { get; set; }
private bool RunLocal { get; set; }
private bool IsStoreServerLinux { get; set; }

private SshClient sshClient;

internal SSHHandler(string server, string serverLogin, string serverPassword)
internal SSHHandler(string server, string serverLogin, string serverPassword, bool isStoreServerLinux)
{
_logger.MethodEntry(LogLevel.Debug);

Server = server;
RunLocal = Server.ToLower() == "localhost" || Server.ToLower().EndsWith("|localmachine");
IsStoreServerLinux = isStoreServerLinux;

List<AuthenticationMethod> authenticationMethods = new List<AuthenticationMethod>();
if (serverPassword.Length < PASSWORD_LENGTH_MAX)
if (!RunLocal)
{
authenticationMethods.Add(new PasswordAuthenticationMethod(serverLogin, serverPassword));
}
else
{
PrivateKeyFile privateKeyFile;

try
List<AuthenticationMethod> authenticationMethods = new List<AuthenticationMethod>();
if (serverPassword.Length < PASSWORD_LENGTH_MAX)
{
using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(FormatRSAPrivateKey(serverPassword))))
{
privateKeyFile = new PrivateKeyFile(ms);
}
authenticationMethods.Add(new PasswordAuthenticationMethod(serverLogin, serverPassword));
}
catch (Exception ex)
else
{
using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(ConvertToPKCS1(serverPassword))))
PrivateKeyFile privateKeyFile;

try
{
using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(FormatRSAPrivateKey(serverPassword))))
{
privateKeyFile = new PrivateKeyFile(ms);
}
}
catch (Exception ex)

Check warning on line 61 in RemoteFile/RemoteHandlers/SSHHandler.cs

View workflow job for this annotation

GitHub Actions / call-starter-workflow / call-dotnet-build-and-release-workflow / dotnet-build-and-release

The variable 'ex' is declared but never used
{
privateKeyFile = new PrivateKeyFile(ms);
using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(ConvertToPKCS1(serverPassword))))
{
privateKeyFile = new PrivateKeyFile(ms);
}
}

authenticationMethods.Add(new PrivateKeyAuthenticationMethod(serverLogin, privateKeyFile));
}

authenticationMethods.Add(new PrivateKeyAuthenticationMethod(serverLogin, privateKeyFile));
Connection = new ConnectionInfo(server, serverLogin, authenticationMethods.ToArray());
}

Connection = new ConnectionInfo(server, serverLogin, authenticationMethods.ToArray());

_logger.MethodExit(LogLevel.Debug);
}

public override void Initialize()
{
_logger.MethodEntry(LogLevel.Debug);

try
{
sshClient = new SshClient(Connection);
sshClient.Connect();
}
catch (Exception ex)
if (!RunLocal)
{
throw new RemoteFileException($"Error making a SSH connection to remote server {Connection.Host}, for user {Connection.Username}. Please contact your company's system administrator to verify connection and permission settings.", ex);
try
{
sshClient = new SshClient(Connection);
sshClient.Connect();
}
catch (Exception ex)
{
throw new RemoteFileException($"Error making a SSH connection to remote server {Connection.Host}, for user {Connection.Username}. Please contact your company's system administrator to verify connection and permission settings.", ex);
}
}

_logger.MethodExit(LogLevel.Debug);
}

public override void Terminate()
{
_logger.MethodEntry(LogLevel.Debug);

sshClient.Disconnect();
sshClient.Dispose();

if (!RunLocal)
{
sshClient.Disconnect();
sshClient.Dispose();
}

_logger.MethodExit(LogLevel.Debug);
}
Expand All @@ -104,10 +118,18 @@ public override string RunCommand(string commandText, object[] arguments, bool w

try
{
if (withSudo)
if (withSudo && IsStoreServerLinux)
commandText = sudo + commandText;

commandText = echo + commandText;
if (IsStoreServerLinux)
{
commandText = echo + commandText;
}
else
{
commandText = "powershell -Command \"" + commandText + "\"";
commandText = commandText.Replace(@"\", @"\\");
}

string displayCommand = commandText;
if (passwordsToMaskInLog != null)
Expand Down Expand Up @@ -162,7 +184,7 @@ public override void UploadCertificateFile(string path, string fileName, byte[]

using (MemoryStream stream = new MemoryStream(certBytes))
{
client.Upload(stream, FormatFTPPath(uploadPath));
client.Upload(stream, FormatFTPPath(uploadPath, false));
}
}
catch (Exception ex)
Expand Down Expand Up @@ -193,7 +215,7 @@ public override void UploadCertificateFile(string path, string fileName, byte[]

using (MemoryStream stream = new MemoryStream(certBytes))
{
client.UploadFile(stream, FormatFTPPath(uploadPath));
client.UploadFile(stream, FormatFTPPath(uploadPath, !IsStoreServerLinux));
}
}
catch (Exception ex)
Expand All @@ -209,7 +231,7 @@ public override void UploadCertificateFile(string path, string fileName, byte[]
}
}

if (!string.IsNullOrEmpty(ApplicationSettings.SeparateUploadFilePath))
if (!string.IsNullOrEmpty(ApplicationSettings.SeparateUploadFilePath) && IsStoreServerLinux)
{
//RunCommand($"cat {uploadPath} > {path}/{fileName}", null, ApplicationSettings.UseSudo, null);
RunCommand($"tee {path}/{fileName} < {uploadPath} > /dev/null", null, ApplicationSettings.UseSudo, null);
Expand All @@ -230,7 +252,7 @@ public override byte[] DownloadCertificateFile(string path)
string altPathOnly = string.Empty;
string altFileNameOnly = string.Empty;

if (!string.IsNullOrEmpty(ApplicationSettings.SeparateUploadFilePath))
if (!string.IsNullOrEmpty(ApplicationSettings.SeparateUploadFilePath) && IsStoreServerLinux)
{
SplitStorePathFile(path, out altPathOnly, out altFileNameOnly);
downloadPath = ApplicationSettings.SeparateUploadFilePath + altFileNameOnly;
Expand All @@ -251,7 +273,7 @@ public override byte[] DownloadCertificateFile(string path)

using (MemoryStream stream = new MemoryStream())
{
client.Download(FormatFTPPath(downloadPath), stream);
client.Download(FormatFTPPath(downloadPath, false), stream);
rtnStore = stream.ToArray();
}
}
Expand Down Expand Up @@ -283,7 +305,7 @@ public override byte[] DownloadCertificateFile(string path)

using (MemoryStream stream = new MemoryStream())
{
client.DownloadFile(FormatFTPPath(downloadPath), stream);
client.DownloadFile(FormatFTPPath(downloadPath, !IsStoreServerLinux), stream);
rtnStore = stream.ToArray();
}
}
Expand All @@ -300,7 +322,7 @@ public override byte[] DownloadCertificateFile(string path)
}
}

if (!string.IsNullOrEmpty(ApplicationSettings.SeparateUploadFilePath))
if (!string.IsNullOrEmpty(ApplicationSettings.SeparateUploadFilePath) && IsStoreServerLinux)
{
RunCommand($"rm {downloadPath}", null, ApplicationSettings.UseSudo, null);
}
Expand All @@ -322,8 +344,13 @@ public override void CreateEmptyStoreFile(string path, string linuxFilePermissio
linuxFileGroup = linuxGroupOwner[1];
}

AreLinuxPermissionsValid(linuxFilePermissions);
RunCommand($"install -m {linuxFilePermissions} -o {linuxFileOwner} -g {linuxFileGroup} /dev/null {path}", null, ApplicationSettings.UseSudo, null);
if (IsStoreServerLinux)
{
AreLinuxPermissionsValid(linuxFilePermissions);
RunCommand($"install -m {linuxFilePermissions} -o {linuxFileOwner} -g {linuxFileGroup} /dev/null {path}", null, ApplicationSettings.UseSudo, null);
}
else
RunCommand($@"Out-File -FilePath ""{path}""", null, false, null);

_logger.MethodExit(LogLevel.Debug);
}
Expand All @@ -332,14 +359,15 @@ public override bool DoesFileExist(string path)
{
_logger.MethodEntry(LogLevel.Debug);
_logger.LogDebug($"DoesFileExist: {path}");

using (SftpClient client = new SftpClient(Connection))
{
try
{
client.Connect();
string existsPath = FormatFTPPath(path);
string existsPath = FormatFTPPath(path, false);
bool exists = client.Exists(existsPath);
_logger.LogDebug(existsPath);

_logger.MethodExit(LogLevel.Debug);

Expand Down Expand Up @@ -406,12 +434,14 @@ private string ConvertToPKCS1(string privateKey)
return pemString.Replace("PRIVATE", "RSA PRIVATE");
}

private string FormatFTPPath(string path)
private string FormatFTPPath(string path, bool addLeadingSlashForWindows)
{
_logger.MethodEntry(LogLevel.Debug);
_logger.MethodExit(LogLevel.Debug);

return path.Substring(0, 1) == @"/" ? path : @"/" + path.Replace("\\", "/");
string rtnPath = IsStoreServerLinux ? path : path.Replace("\\", "/");
_logger.LogTrace($"Formatted path: {rtnPath}");
return addLeadingSlashForWindows ? rtnPath : "/" + rtnPath;
}
}
}
7 changes: 5 additions & 2 deletions RemoteFile/RemoteHandlers/WinRMHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,16 @@ class WinRMHandler : BaseRemoteHandler

private Runspace runspace { get; set; }
private WSManConnectionInfo connectionInfo { get; set; }
private bool RunLocal { get; set; }

internal WinRMHandler(string server, string serverLogin, string serverPassword)
{
_logger.MethodEntry(LogLevel.Debug);

Server = server;
if (Server.ToLower() != "localhost")
RunLocal = Server.ToLower() == "localhost" || Server.ToLower().EndsWith("|localmachine");

if (!RunLocal)
{
connectionInfo = new WSManConnectionInfo(new System.Uri($"{Server}/wsman"));
if (!string.IsNullOrEmpty(serverLogin))
Expand All @@ -50,7 +53,7 @@ public override void Initialize()

try
{
if (Server.ToLower() == "localhost")
if (RunLocal)
{
runspace = RunspaceFactory.CreateRunspace();
}
Expand Down

0 comments on commit b3b215e

Please sign in to comment.