Skip to content

Commit

Permalink
Merge 526ee2b into 5bda999
Browse files Browse the repository at this point in the history
  • Loading branch information
doebrowsk authored Oct 11, 2021
2 parents 5bda999 + 526ee2b commit 1a6dd3c
Show file tree
Hide file tree
Showing 21 changed files with 318 additions and 687 deletions.
5 changes: 1 addition & 4 deletions .github/workflows/keyfactor-extension-prerelease.yml
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,7 @@ jobs:
run: |
md ${{ github.workspace }}\zip\Keyfactor
Compress-Archive -Path `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\*.dll, `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\*.json, `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\*.config, `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\Keyfactor.Extensions.Pam.Config.exe `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\netcoreapp3.1\* `
-DestinationPath ${{ github.workspace }}\zip\Keyfactor\$Env:REPO_NAME.zip -Force

Expand Down
23 changes: 12 additions & 11 deletions .github/workflows/keyfactor-extension-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,28 +91,29 @@ jobs:
run: |
$VersionRegex = "\d+\.\d+\.\d+"
$assemblyInfoFiles = (Get-ChildItem -Include AssemblyInfo.cs -File -Recurse).fullname
$newVer = "${{ steps.create_release.outputs.current_tag }}".TrimStart('v').Split('-')[0]
echo "Prepared to overwrite Assembly version to: ${newVer}"
foreach ($assemblyInfoFile in $assemblyInfoFiles)
if ($assemblyInfoFiles -ne $null)
{
$filecontent = Get-Content($assemblyInfoFile)
attrib $assemblyInfoFile -r
$filecontent -replace $VersionRegex, $newVer | Out-File $assemblyInfoFile
$newVer = "${{ steps.create_release.outputs.current_tag }}".TrimStart('v').Split('-')[0]
echo "Prepared to overwrite Assembly version to: ${newVer}"
foreach ($assemblyInfoFile in $assemblyInfoFiles)
{
$filecontent = Get-Content($assemblyInfoFile)
attrib $assemblyInfoFile -r
$filecontent -replace $VersionRegex, $newVer | Out-File $assemblyInfoFile
}
}
- name: Execute MSBuild Commands
run: |
MSBuild.exe $Env:SOLUTION_PATH -p:RestorePackagesConfig=false -p:Configuration=Release
$newVer = "${{ steps.create_release.outputs.current_tag }}".TrimStart('v').Split('-')[0]
MSBuild.exe $Env:SOLUTION_PATH -p:RestorePackagesConfig=false -p:Configuration=Release -p:Version=$newVer
- name: Archive Files
if: ${{ success() }}
run: |
md ${{ github.workspace }}\zip\Keyfactor
Compress-Archive -Path `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\*.dll, `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\*.json, `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\*.config, `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\Keyfactor.Extensions.Pam.Config.exe `
${{ env.SOLUTION_FOLDER }}\${{ env.PROJECT_FOLDER }}\bin\Release\netcoreapp3.1\* `
-DestinationPath ${{ github.workspace }}\zip\Keyfactor\$Env:REPO_NAME.zip -Force
- name: Upload Release Asset (x64)
Expand Down
23 changes: 7 additions & 16 deletions PEMStoreSSH.sln
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29020.237
VisualStudioVersion = 16.0.31515.178
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PEMStoreSSH", "PEMStoreSSH\PEMStoreSSH.csproj", "{F57D07DB-613D-4837-B709-6E943CD4BA10}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PEMStoreSSH", "PEMStoreSSH\PEMStoreSSH.csproj", "{CAF9DBE4-D7D5-400C-A4ED-7A1B29F78AED}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F57D07DB-613D-4837-B709-6E943CD4BA10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F57D07DB-613D-4837-B709-6E943CD4BA10}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F57D07DB-613D-4837-B709-6E943CD4BA10}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F57D07DB-613D-4837-B709-6E943CD4BA10}.Release|Any CPU.Build.0 = Release|Any CPU
{CAF9DBE4-D7D5-400C-A4ED-7A1B29F78AED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CAF9DBE4-D7D5-400C-A4ED-7A1B29F78AED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CAF9DBE4-D7D5-400C-A4ED-7A1B29F78AED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CAF9DBE4-D7D5-400C-A4ED-7A1B29F78AED}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {05D96C70-6482-4130-B82B-8B6C511A9C97}
EndGlobalSection
GlobalSection(TeamFoundationVersionControl) = preSolution
SccNumberOfProjects = 2
SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}
SccTeamFoundationServer = https://devops.corp.keyfactor.com/maincollection
SccLocalPath0 = .
SccProjectUniqueName1 = PEMStoreSSH\\PEMStoreSSH.csproj
SccProjectName1 = PEMStoreSSH
SccLocalPath1 = PEMStoreSSH
SolutionGuid = {4547129F-24F9-423B-85AD-683F7176E21C}
EndGlobalSection
EndGlobal
30 changes: 0 additions & 30 deletions PEMStoreSSH/App.config

This file was deleted.

8 changes: 7 additions & 1 deletion PEMStoreSSH/ApplicationSettings.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
using System.Configuration;
// Copyright 2021 Keyfactor
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
// and limitations under the License.

using System.IO;

using Newtonsoft.Json;
Expand Down
29 changes: 20 additions & 9 deletions PEMStoreSSH/CertificateFormats/PEMHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,15 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
// and limitations under the License.

using PEMStoreSSH.RemoteHandlers;
using Keyfactor.PKI.PEM;
using Keyfactor.PKI.PrivateKeys;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;

using CSS.PKI.PEM;
using CSS.PKI.PrivateKeys;

using PEMStoreSSH.RemoteHandlers;

namespace PEMStoreSSH
{
class PEMHandler : ICertificateFormatHandler
Expand Down Expand Up @@ -82,7 +79,7 @@ public List<SSHFileInfo> CreateCertificatePacket(string certToAdd, string alias,

if (!string.IsNullOrEmpty(pfxPassword))
{
PrivateKeyConverter converter = CSS.PKI.PrivateKeys.PrivateKeyConverterFactory.FromPKCS12(certBytes, pfxPassword);
PrivateKeyConverter converter = PrivateKeyConverterFactory.FromPKCS12(certBytes, pfxPassword);
byte[] privateKeyBytes = string.IsNullOrEmpty(storePassword) ? converter.ToPkcs8BlobUnencrypted() : converter.ToPkcs8Blob(storePassword);
string privateKeyPem = PemUtilities.DERToPEM(privateKeyBytes, string.IsNullOrEmpty(storePassword) ? PemUtilities.PemObjectType.PrivateKey : PemUtilities.PemObjectType.EncryptedPrivateKey);

Expand Down Expand Up @@ -130,9 +127,13 @@ public void AddCertificateToStore(List<SSHFileInfo> files, string storePath, str
X509Certificate2 x509Cert = new X509Certificate2(Encoding.ASCII.GetBytes(certInfo.FileContents));

if (isSingleCertificateStore)
{
ReplaceStoreContents(storePath, ssh, certInfo.FileContents, overwrite);
}
else
{
AddRemoveCertificate(serverType, storePath, ssh, certInfo.Alias, x509Cert.Thumbprint, certInfo.FileContents, privateKeyPath, hasPrivateKey, overwrite, true);
}


if (!string.IsNullOrEmpty(privateKeyPath) && files.Exists(p => p.FileType == SSHFileInfo.FileTypeEnum.PrivateKey))
Expand All @@ -147,7 +148,9 @@ public void RemoveCertificate(PEMStore.ServerTypeEnum serverType, string storePa
AddRemoveCertificate(serverType, storePath, ssh, alias, string.Empty, string.Empty, privateKeyPath, hasPrivateKey, false, false);

if (!string.IsNullOrEmpty(privateKeyPath))
{
ssh.UploadCertificateFile(privateKeyPath, new byte[] { });
}
}

public bool IsValidStore(string path, PEMStore.ServerTypeEnum serverType, IRemoteHandler ssh)
Expand All @@ -157,8 +160,6 @@ public bool IsValidStore(string path, PEMStore.ServerTypeEnum serverType, IRemot
return result.IndexOf(CertDelimBeg) > -1;
}



private void AddRemoveCertificate(PEMStore.ServerTypeEnum serverType, string storePath, IRemoteHandler ssh, string alias, string thumbprint, string replacementCert, string privateKeyPath, bool hasPrivateKey, bool overwrite, bool isAdd)
{
bool certFound = false;
Expand All @@ -167,7 +168,9 @@ private void AddRemoveCertificate(PEMStore.ServerTypeEnum serverType, string sto
string storeContents = Encoding.ASCII.GetString(storebytes);

if (hasPrivateKey && string.IsNullOrEmpty(privateKeyPath))
{
storeContents = RemoveAllPrivateKeys(storeContents);
}

string storeContentsParsing = storeContents;

Expand All @@ -181,7 +184,9 @@ private void AddRemoveCertificate(PEMStore.ServerTypeEnum serverType, string sto
if (x509CurrCertFromStore.Thumbprint == alias || x509CurrCertFromStore.Thumbprint == thumbprint)
{
if (!overwrite && isAdd)
{
throw new PEMException("Certificate with this alias/thumbprint already exists in store. Please select 'Overwrite' if you wish to replace this certificate.");
}

storeContents = storeContents.Replace(currCertFromStore, replacementCert);
certFound = true;
Expand All @@ -192,10 +197,14 @@ private void AddRemoveCertificate(PEMStore.ServerTypeEnum serverType, string sto
}

if (!certFound && !isAdd)
{
throw new PEMException("Certificate with this alias/thumbprint does not exist in store.");
}

if (storeContents.IndexOf(replacementCert) == -1 && isAdd)
{
storeContents += ("\n" + replacementCert);
}

ssh.UploadCertificateFile(storePath, Encoding.ASCII.GetBytes(storeContents));
}
Expand All @@ -205,7 +214,9 @@ private void ReplaceStoreContents(string storePath, IRemoteHandler ssh, string f
byte[] storebytes = ssh.DownloadCertificateFile(storePath, HasBinaryContent);
string storeContents = Encoding.ASCII.GetString(storebytes);
if (!overwrite && storeContents.IndexOf(CertDelimBeg, StringComparison.OrdinalIgnoreCase) > -1)
{
throw new PEMException("Certificate store currently contains one or more certificates. Please select 'overwrite' to replace the contents of the store.");
}

ssh.UploadCertificateFile(storePath, Encoding.ASCII.GetBytes(fileContents));
}
Expand Down
12 changes: 3 additions & 9 deletions PEMStoreSSH/CertificateFormats/PKCS12Handler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,15 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
// and limitations under the License.

using Keyfactor.PKI.X509;
using Org.BouncyCastle.Pkcs;
using PEMStoreSSH.RemoteHandlers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

using CSS.PKI.X509;

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;

using PEMStoreSSH.RemoteHandlers;

namespace PEMStoreSSH
{
class PKCS12Handler : ICertificateFormatHandler
Expand Down
68 changes: 41 additions & 27 deletions PEMStoreSSH/Discovery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,21 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
// and limitations under the License.

using CSS.Common.Logging;
using Keyfactor.Orchestrators.Common.Enums;
using Keyfactor.Orchestrators.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

using Newtonsoft.Json;

using Keyfactor.Platform.Extensions.Agents;
using Keyfactor.Platform.Extensions.Agents.Delegates;
using Keyfactor.Platform.Extensions.Agents.Interfaces;

using CSS.Common.Logging;

namespace PEMStoreSSH
{
public class Discovery : LoggingClientBase, IAgentJobExtension
public class Discovery : LoggingClientBase, IDiscoveryJobExtension
{
public string GetJobClass()
{
return "Discovery";
}

public string GetStoreType()
{
return "PEM-SSH";
}
public string ExtensionName => "PEM-SSH";

public AnyJobCompleteInfo processJob(AnyJobConfigInfo config, SubmitInventoryUpdate submitInventory, SubmitEnrollmentRequest submitEnrollmentRequest, SubmitDiscoveryResults sdr)
public JobResult ProcessJob(DiscoveryJobConfiguration config, SubmitDiscoveryUpdate submitDiscovery)
{
Logger.Debug($"Begin Discovery...");

Expand All @@ -41,7 +29,7 @@ public AnyJobCompleteInfo processJob(AnyJobConfigInfo config, SubmitInventoryUpd
{
ApplicationSettings.Initialize(this.GetType().Assembly.Location);

dynamic properties = JsonConvert.DeserializeObject(config.Job.Properties.ToString());
dynamic properties = JsonConvert.DeserializeObject(config.JobProperties.ToString());
string[] directoriesToSearch = properties.dirs.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] extensionsToSearch = properties.extensions.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] ignoredDirs = properties.ignoreddirs.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
Expand All @@ -50,34 +38,60 @@ public AnyJobCompleteInfo processJob(AnyJobConfigInfo config, SubmitInventoryUpd
bool isP12 = (bool)properties.compatibility.Value;

if (directoriesToSearch.Length == 0)
{
throw new PEMException("Blank or missing search directories for Discovery.");
if (extensionsToSearch.Length == 0)
}
else if (extensionsToSearch.Length == 0)
{
throw new PEMException("Blank or missing search extensions for Discovery.");
}

if (filesTosearch.Length == 0)
{
filesTosearch = new string[] { "*" };
}

PEMStore pemStore = new PEMStore(config.Store.ClientMachine, config.Server.Username, config.Server.Password, directoriesToSearch[0].Substring(0, 1) == "/" ? PEMStore.ServerTypeEnum.Linux : PEMStore.ServerTypeEnum.Windows,
isP12 ? PEMStore.FormatTypeEnum.PKCS12 : PEMStore.FormatTypeEnum.PEM);
PEMStore pemStore = new PEMStore
(
config.ClientMachine,
config.ServerUsername,
config.ServerPassword,
directoriesToSearch[0].Substring(0, 1) == "/" ? PEMStore.ServerTypeEnum.Linux : PEMStore.ServerTypeEnum.Windows,
isP12 ? PEMStore.FormatTypeEnum.PKCS12 : PEMStore.FormatTypeEnum.PEM
);

locations = pemStore.FindStores(directoriesToSearch, extensionsToSearch, filesTosearch).ToList();
foreach (string ignoredDir in ignoredDirs)
{
locations = locations.Where(p => !p.StartsWith(ignoredDir.TrimStart(' '))).ToList();
}

locations = locations.Where(p => pemStore.IsValidStore(p)).ToList();
}
catch (Exception ex)
{
return new AnyJobCompleteInfo() { Status = 4, Message = ExceptionHandler.FlattenExceptionMessages(ex, $"Site {config.Store.StorePath} on server {config.Store.ClientMachine}:") };
return new JobResult()
{
Result = OrchestratorJobStatusJobResult.Failure,
FailureMessage = ExceptionHandler.FlattenExceptionMessages(ex, $"Error on server {config.ClientMachine}:")
};
}

try
{
sdr.Invoke(locations);
return new AnyJobCompleteInfo() { Status = 2, Message = "Successful" };
submitDiscovery.Invoke(locations);
return new JobResult()
{
Result = OrchestratorJobStatusJobResult.Success
};
}
catch (Exception ex)
{
return new AnyJobCompleteInfo() { Status = 4, Message = ExceptionHandler.FlattenExceptionMessages(ex, $"Site {config.Store.StorePath} on server {config.Store.ClientMachine}:") };
return new JobResult()
{
Result = OrchestratorJobStatusJobResult.Failure,
FailureMessage = ExceptionHandler.FlattenExceptionMessages(ex, $"Error on server {config.ClientMachine}:")
};
}
}
}
Expand Down
Loading

0 comments on commit 1a6dd3c

Please sign in to comment.