From 6f0a465192d862c07e3c94417eebaa83212c8b2c Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Thu, 23 Jan 2025 14:39:52 +0000 Subject: [PATCH 1/4] Chain issue Fixes --- PaloAlto/Jobs/Management.cs | 300 ++++++++---------------------------- PaloAlto/PaloAlto.csproj | 2 +- 2 files changed, 66 insertions(+), 236 deletions(-) diff --git a/PaloAlto/Jobs/Management.cs b/PaloAlto/Jobs/Management.cs index 75ac686..047789e 100644 --- a/PaloAlto/Jobs/Management.cs +++ b/PaloAlto/Jobs/Management.cs @@ -18,6 +18,7 @@ using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Text.Json.Serialization; using System.Text.RegularExpressions; using System.Threading; using System.Xml.Serialization; @@ -100,7 +101,7 @@ private JobResult PerformManagement(ManagementJobConfiguration config) if (!valid) return result; _logger.LogTrace("Validated Store Properties for Management Job"); - + var complete = new JobResult { Result = OrchestratorJobStatusJobResult.Failure, @@ -203,7 +204,7 @@ private bool SetPanoramaTarget(ManagementJobConfiguration config, PaloAltoClient if (targetResult != null && targetResult.Status.Equals("error", StringComparison.CurrentCultureIgnoreCase)) { { - var error = targetResult.LineMsg != null ? Validators.BuildPaloError(targetResult):"Could not retrieve error results"; + var error = targetResult.LineMsg != null ? Validators.BuildPaloError(targetResult) : "Could not retrieve error results"; _logger.LogTrace($"Could not set target for Panorama vsys {error}"); return false; } @@ -256,7 +257,7 @@ private JobResult PerformAddition(ManagementJobConfiguration config) { _logger.MethodEntry(); var warnings = string.Empty; - + if (config.CertificateStoreDetails.StorePath.Length > 0) { _logger.LogTrace( @@ -297,101 +298,26 @@ private JobResult PerformAddition(ManagementJobConfiguration config) var certPem = GetPemFile(config); _logger.LogTrace($"Got certPem {certPem}"); - - //1. Get the chain in a list starting with root first, any intermediate then leaf - var orderedChainList = GetCertificateChain(config.JobCertificate.Contents, config.JobCertificate.PrivateKeyPassword); var alias = config.JobCertificate?.Alias; _logger.LogTrace($"Alias {alias}"); - - //2. Check palo alto for existing thumbprints of anything in the chain - var rawCertificatesResult = client.GetCertificateList($"{config.CertificateStoreDetails.StorePath}/certificate/entry").Result; - _logger.LogTrace("Got Raw Certificate Results"); + ErrorSuccessResponse content = null; string errorMsg = string.Empty; + _logger.LogTrace("Importing Certificate Chain"); + var type = string.IsNullOrWhiteSpace(config.JobCertificate.PrivateKeyPassword) ? "certificate" : "keypair"; + _logger.LogTrace($"Certificate Type of {type}"); + var importResult = client.ImportCertificate(alias, + config.JobCertificate.PrivateKeyPassword, + Encoding.UTF8.GetBytes(certPem), "yes", type, + config.CertificateStoreDetails.StorePath); + _logger.LogTrace("Finished Import About to Log Results..."); + content = importResult.Result; + LogResponse(content); + _logger.LogTrace("Finished Logging Import Results..."); + var caDict = new Dictionary(); - //1. Get a list of CAs with Thumbprints returned from The Palo Alto Device - if (rawCertificatesResult != null) - { - _logger.LogTrace("Logging Raw Certificate Results"); - LogResponse(rawCertificatesResult); - foreach (var cert in rawCertificatesResult.CertificateResult.Entry) - { - if (cert.PublicKey != null && cert.Ca.Equals("yes",StringComparison.CurrentCultureIgnoreCase)) - { - var pemContent = cert.PublicKey; - pemContent = Regex.Replace(pemContent, "-----BEGIN CERTIFICATE-----", string.Empty); - pemContent = Regex.Replace(pemContent, "-----END CERTIFICATE-----", string.Empty); - _logger.LogTrace(pemContent); - - // Convert the PEM string to a byte array - var certBytes = Convert.FromBase64String(pemContent); - // Create an X509Certificate2 object from the byte array - X509Certificate2 certificate = new X509Certificate2(certBytes); - - if (certificate.Thumbprint != null && !caDict.ContainsKey(certificate.Thumbprint)) - { - _logger.LogTrace($"Adding Thumbprint To Dictionary {certificate.Thumbprint} for {certificate.Subject}"); - caDict.Add(certificate.Thumbprint, cert.Name); - } - } - } - } - - foreach (var cert in orderedChainList) - { - //root and intermediate just upload the cert from the chain no private key - if (((cert.type == "root" || cert.type == "intermediate") && !caDict.ContainsKey(cert.certificate?.Thumbprint ?? string.Empty))) - { - _logger.LogTrace("Found a root or intermediate cert that was not in the dictionary, Generating name based on subject"); - var certName = GenerateCaCertName(cert); - _logger.LogTrace($"Generated Cert Name {certName}"); - - var importResult = client.ImportCertificate(certName, - config.JobCertificate.PrivateKeyPassword, - Encoding.UTF8.GetBytes(ExportToPem(cert.certificate)), "no", "certificate", - config.CertificateStoreDetails.StorePath); - content = importResult.Result; - _logger.LogTrace("Logging import result content."); - LogResponse(content); - - //Set as trusted Root if you successfully imported the root certificate - if (content != null && content.Status.ToUpper() != "ERROR") - { - _logger.LogTrace("Attempting to set cert to Trusted Root if type is root"); - ErrorSuccessResponse rootResponse = null; - if (cert.type == "root") - rootResponse = SetTrustedRoot(certName, client, config.CertificateStoreDetails.StorePath); - - if (rootResponse != null && rootResponse.Status.ToUpper() == "ERROR") - warnings += - $"Setting to Trusted Root Failed. {Validators.BuildPaloError(rootResponse)}"; - } - } - - //Leafs need the keypair only put leaf out there if root and intermediate succeeded - if (cert.type == "leaf" && errorMsg.Length == 0) - { - _logger.LogTrace("Found Leaf Certificate"); - var type = string.IsNullOrWhiteSpace(config.JobCertificate.PrivateKeyPassword) ? "certificate" : "keypair"; - _logger.LogTrace($"Certificate Type of {type}"); - var importResult = client.ImportCertificate(alias, - config.JobCertificate.PrivateKeyPassword, - Encoding.UTF8.GetBytes(certPem), "yes", type, - config.CertificateStoreDetails.StorePath); - _logger.LogTrace("Finished Import About to Log Results..."); - content = importResult.Result; - LogResponse(content); - _logger.LogTrace("Finished Logging Import Results..."); - - } - - if (content != null) - { - errorMsg += content.LineMsg != null ? Validators.BuildPaloError(content) : content.Text; - } - } //4. Try to commit to firewall or Palo Alto then Push to the devices if (errorMsg.Length == 0) @@ -400,7 +326,7 @@ private JobResult PerformAddition(ManagementJobConfiguration config) warnings = CommitChanges(config, client, warnings); } - return ReturnJobResult(config, warnings,true, errorMsg); + return ReturnJobResult(config, warnings, true, errorMsg); } @@ -436,7 +362,7 @@ private JobResult PerformAddition(ManagementJobConfiguration config) private string GenerateCaCertName((X509Certificate2 certificate, string type) cert) { DateTime currentDateTime = DateTime.UtcNow; - int unixTimestamp = (int) (currentDateTime.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; + int unixTimestamp = (int)(currentDateTime.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var isCa = PKI.Extensions.X509Extentions.IsCaCertificate(cert.certificate); _logger.LogTrace($"Ca Certificate? {isCa}"); var cn = GetCommonName(cert.certificate?.SubjectName.Name); @@ -466,7 +392,7 @@ private bool DeleteCertificate(ManagementJobConfiguration config, PaloAltoClient { if (!SetPanoramaTarget(config, client)) { - deleteResult = ReturnJobResult(config, warnings, false,"Could Not Set Panorama Target"); + deleteResult = ReturnJobResult(config, warnings, false, "Could Not Set Panorama Target"); return false; } @@ -594,11 +520,13 @@ private string GetPemFile(ManagementJobConfiguration config) } } - var pubCertPem = - Pemify(Convert.ToBase64String(p.GetCertificate(alias).Certificate.GetEncoded())); - _logger.LogTrace($"Public cert Pem {pubCertPem}"); + //var pubCertPem = + // Pemify(Convert.ToBase64String(p.GetCertificate(alias).Certificate.GetEncoded())); + //_logger.LogTrace($"Public cert Pem {pubCertPem}"); + + var pubCertPem = OrderCertificatesAndConvertToPem(p.GetCertificateChain(alias)); - var certPem = privateKeyString + certStart + pubCertPem + certEnd; + var certPem = privateKeyString + pubCertPem; return certPem; } @@ -624,7 +552,7 @@ private string CommitChanges(ManagementJobConfiguration config, PaloAltoClient c _logger.LogTrace("It is a panorama device, build some delay in there so it works, pan issue."); Thread.Sleep(120000); //Some delay built in so pushes to devices work _logger.LogTrace("Done sleeping"); - var commitAllResponse = client.GetCommitAllResponse(deviceGroup,config.CertificateStoreDetails.StorePath,templateStack).Result; + var commitAllResponse = client.GetCommitAllResponse(deviceGroup, config.CertificateStoreDetails.StorePath, templateStack).Result; _logger.LogTrace("Logging commit response from panorama."); LogResponse(commitAllResponse); if (commitAllResponse.Status != "success") @@ -640,92 +568,6 @@ private string CommitChanges(ManagementJobConfiguration config, PaloAltoClient c } - private List<(X509Certificate2 certificate, string type)> GetCertificateChain(string jobCertificate, string password) - { - _logger.MethodEntry(); - _logger.LogTrace("Decode the base64-encoded chain to get the bytes"); - - byte[] certificateChainBytes = Convert.FromBase64String(jobCertificate); - _logger.LogTrace($"Cert Chain Bytes: {certificateChainBytes}"); - - _logger.LogTrace("Create a collection to hold the certificates"); - X509Certificate2Collection certificateCollection = new X509Certificate2Collection(); - - _logger.LogTrace("Load the certificates from the byte array"); - certificateCollection.Import(certificateChainBytes, password, X509KeyStorageFlags.Exportable); - - _logger.LogTrace("Identify the root certificate"); - X509Certificate2 rootCertificate = FindRootCertificate(certificateCollection); - - _logger.LogTrace("Create a list to hold the ordered certificates"); - List<(X509Certificate2 certificate, string certType)> orderedCertificates = new List<(X509Certificate2, string)>(); - - _logger.LogTrace("Add the root certificate to the ordered list"); - if (rootCertificate != null) - orderedCertificates.Add((rootCertificate, "root")); - - _logger.LogTrace("Add intermediate certificates to the ordered list and mark them as intermediate"); - foreach (X509Certificate2 certificate in certificateCollection) - { - - _logger.LogTrace("Exclude root certificate"); - if (!certificate.Equals(rootCertificate)) - { - _logger.LogTrace("Check if the certificate is not the leaf certificate"); - - bool isLeaf = true; - foreach (X509Certificate2 potentialIssuer in certificateCollection) - { - _logger.LogTrace("Check if the certificate is not the leaf certificate"); - if (certificate?.Subject == potentialIssuer?.Issuer && potentialIssuer!=null && !potentialIssuer.Equals(certificate)) - { - _logger.LogTrace("Leaf is false"); - isLeaf = false; - break; - } - } - - _logger.LogTrace("If the certificate is not the leaf certificate, add it as an intermediate certificate"); - if (!isLeaf) - { - _logger.LogTrace("If the certificate is not the leaf certificate, add it as an intermediate certificate"); - orderedCertificates.Add((certificate, "intermediate")); - } - } - } - - _logger.LogTrace("Add leaf certificates to the ordered list"); - foreach (X509Certificate2 certificate in certificateCollection) - { - _logger.LogTrace("Check for add leaf certificates to the ordered list"); - if (!orderedCertificates.Exists(c => c.certificate != null && c.certificate.Equals(certificate))) - { - _logger.LogTrace("Added leaf certificates to the ordered list"); - orderedCertificates.Add((certificate, "leaf")); - } - } - _logger.MethodExit(); - return orderedCertificates; - } - - - private X509Certificate2 FindRootCertificate(X509Certificate2Collection certificates) - { - _logger.MethodEntry(); - foreach (X509Certificate2 certificate in certificates) - { - if (IsRootCertificate(certificate, certificates)) - { - _logger.MethodExit(); - return certificate; - } - } - - _logger.LogTrace("Return null if no root certificate is found"); - _logger.MethodExit(); - return null; - } - private string GetCommonName(string subject) { _logger.MethodEntry(); @@ -746,66 +588,54 @@ private string GetCommonName(string subject) } - private bool IsRootCertificate(X509Certificate2 certificate, X509Certificate2Collection certificates) + public static string OrderCertificatesAndConvertToPem(X509CertificateEntry[] certificateEntries) { - _logger.MethodEntry(); - // Check if the certificate is self-signed - if (certificate.Subject == certificate.Issuer) - { - // Check if there is no issuer in the collection with a matching subject - foreach (X509Certificate2 issuerCertificate in certificates) - { - if (issuerCertificate.Subject == certificate.Subject && !issuerCertificate.Equals(certificate)) - { - _logger.LogTrace("false"); - _logger.MethodExit(); - return false; - } - } - _logger.LogTrace("true"); - _logger.MethodExit(); - return true; - } - _logger.LogTrace("false"); + // Convert to X509Certificate objects for easier processing + var certificates = certificateEntries + .Select(entry => entry.Certificate) + .ToList(); - _logger.MethodExit(); - return false; - } + // Create a dictionary to map Subject DN to certificate + var subjectToCertificate = certificates.ToDictionary(cert => cert.SubjectDN.ToString()); + // Create a dictionary to map Issuer DN to subject DN + var issuerToSubjects = certificates + .GroupBy(cert => cert.IssuerDN.ToString()) + .ToDictionary(group => group.Key, group => group.Select(cert => cert.SubjectDN.ToString()).ToList()); - private string ExportToPem(X509Certificate2 certificate) - { - _logger.MethodEntry(); - StringBuilder builder = new StringBuilder(); - builder.AppendLine("-----BEGIN CERTIFICATE-----"); - builder.AppendLine(Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)); - builder.AppendLine("-----END CERTIFICATE-----"); - _logger.LogTrace(builder.ToString()); - _logger.MethodExit(); - return builder.ToString(); - } + // Find the end-entity certificate (subject DN not found as an issuer DN) + var endEntityCert = certificates.First(cert => !issuerToSubjects.ContainsKey(cert.SubjectDN.ToString())); + // Build the chain from end-entity to root + var orderedCertificates = new List(); + var currentCert = endEntityCert; - private ErrorSuccessResponse SetTrustedRoot(string jobCertificateAlias, PaloAltoClient client, - string templateName) - { - _logger.MethodEntry(); - try + while (currentCert != null) { - _logger.LogTrace("Setting Trusted Root"); - var result = client.SubmitSetTrustedRoot(jobCertificateAlias, templateName); - _logger.LogTrace("Trusted Root Set"); - _logger.LogTrace(result.Result.LineMsg.Line.Count > 0 - ? $"Set Trusted Root Response {string.Join(" ,", result.Result.LineMsg.Line)}" - : $"Set Trusted Root Response {result.Result.LineMsg.StringMsg}"); - _logger.MethodExit(); - return result.Result; + orderedCertificates.Add(currentCert); + var issuer = currentCert.IssuerDN.ToString(); + + if (issuer == currentCert.SubjectDN.ToString()) // Self-signed certificate (root) + break; + + currentCert = subjectToCertificate.ContainsKey(issuer) ? subjectToCertificate[issuer] : null; } - catch (Exception e) + + // Convert the ordered certificates to a PEM string + var pemString = string.Empty; + + foreach (var cert in orderedCertificates) { - _logger.LogError($"Error Occurred in Management.SetTrustedRoot {LogHandler.FlattenException(e)}"); - throw; + using (var stringWriter = new System.IO.StringWriter()) + { + var pemWriter = new PemWriter(stringWriter); + pemWriter.WriteObject(cert); + pemWriter.Writer.Flush(); + pemString += stringWriter.ToString(); + } } + + return pemString; } } } \ No newline at end of file diff --git a/PaloAlto/PaloAlto.csproj b/PaloAlto/PaloAlto.csproj index af55d40..268a8d1 100644 --- a/PaloAlto/PaloAlto.csproj +++ b/PaloAlto/PaloAlto.csproj @@ -27,7 +27,7 @@ - + From ffdda5a8a98a9d78a497fb46054517f2da8e1a81 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Fri, 24 Jan 2025 14:05:38 -0500 Subject: [PATCH 2/4] Fix for Chain Issues --- PaloAlto/Client/PaloAltoClient.cs | 55 ++++++++++++++++++++++++++ PaloAlto/Jobs/Inventory.cs | 18 +++++---- PaloAlto/Jobs/Management.cs | 28 ++++++------- PaloAltoTestConsole/KeyfactorClient.cs | 2 +- PaloAltoTestConsole/Program.cs | 2 + 5 files changed, 81 insertions(+), 24 deletions(-) diff --git a/PaloAlto/Client/PaloAltoClient.cs b/PaloAlto/Client/PaloAltoClient.cs index 732d943..9f2cd40 100644 --- a/PaloAlto/Client/PaloAltoClient.cs +++ b/PaloAlto/Client/PaloAltoClient.cs @@ -25,6 +25,8 @@ using Keyfactor.Extensions.Orchestrator.PaloAlto.Models.Responses; using Keyfactor.Logging; using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; namespace Keyfactor.Extensions.Orchestrator.PaloAlto.Client { @@ -393,6 +395,59 @@ private void EnsureSuccessfulResponse(HttpResponseMessage response) _logger.LogError($"Error Occured in PaloAltoClient.EnsureSuccessfulResponse: {e.Message}"); throw; } + } + + public string MaskSensitiveData(string json) + { + try + { + JObject jsonObject = JObject.Parse(json); + + // Replace all keys named "Password" or similar + MaskKey(jsonObject, "StorePassword"); + MaskKey(jsonObject, "ServerPassword"); + MaskKey(jsonObject, "PrivateKeyPassword"); + + return jsonObject.ToString(Newtonsoft.Json.Formatting.Indented); + } + catch (JsonException ex) + { + Console.WriteLine("Invalid JSON provided: " + ex.Message); + return json; // Return the original JSON if parsing fails + } + } + + private static void MaskKey(JObject jsonObject, string key) + { + foreach (var property in jsonObject.Properties()) + { + if (property.Name.Equals(key, StringComparison.OrdinalIgnoreCase)) + { + property.Value = "*****"; + } + else if (property.Value.Type == JTokenType.Object) + { + MaskKey((JObject)property.Value, key); + } + else if (property.Value.Type == JTokenType.String) + { + // Optionally handle nested JSON strings + string value = property.Value.ToString(); + if (value.StartsWith("{") && value.EndsWith("}")) + { + try + { + JObject nestedObject = JObject.Parse(value); + MaskKey(nestedObject, key); + property.Value = nestedObject.ToString(Newtonsoft.Json.Formatting.None); + } + catch + { + // Not a valid JSON string, skip + } + } + } + } } } } \ No newline at end of file diff --git a/PaloAlto/Jobs/Inventory.cs b/PaloAlto/Jobs/Inventory.cs index 19abe37..00557fc 100644 --- a/PaloAlto/Jobs/Inventory.cs +++ b/PaloAlto/Jobs/Inventory.cs @@ -40,6 +40,7 @@ public Inventory(IPAMSecretResolver resolver) _resolver = resolver; } + private PaloAltoClient _client; private string ServerPassword { get; set; } private string ServerUserName { get; set; } @@ -79,25 +80,26 @@ private JobResult PerformInventory(InventoryJobConfiguration config, SubmitInven config.JobHistoryId, ServerUserName, ServerPassword); if (!valid) return result; + //Get the list of certificates and Trusted Roots + _client = + new PaloAltoClient(config.CertificateStoreDetails.ClientMachine, + ServerUserName, ServerPassword); //Api base URL Plus Key + _logger.LogTrace("Store Properties are Valid"); - _logger.LogTrace($"Inventory Config {JsonConvert.SerializeObject(config)}"); + _logger.LogTrace($"Inventory Config {_client.MaskSensitiveData(JsonConvert.SerializeObject(config))}"); _logger.LogTrace( $"Client Machine: {config.CertificateStoreDetails.ClientMachine} ApiKey: {config.ServerPassword}"); - //Get the list of certificates and Trusted Roots - var client = - new PaloAltoClient(config.CertificateStoreDetails.ClientMachine, - ServerUserName, ServerPassword); //Api base URL Plus Key _logger.LogTrace("Inventory Palo Alto Client Created"); //Change the path if you are pointed to a Panorama Device - var rawCertificatesResult = client.GetCertificateList($"{config.CertificateStoreDetails.StorePath}/certificate/entry").Result; + var rawCertificatesResult = _client.GetCertificateList($"{config.CertificateStoreDetails.StorePath}/certificate/entry").Result; var certificatesResult = rawCertificatesResult.CertificateResult.Entry.FindAll(c => c.PublicKey != null); LogResponse(certificatesResult); //Trace Write Certificate List Response from Palo Alto - var trustedRootPayload = client.GetTrustedRootList().Result; + var trustedRootPayload = _client.GetTrustedRootList().Result; LogResponse(trustedRootPayload); //Trace Write Trusted Cert List Response from Palo Alto var warningFlag = false; @@ -133,7 +135,7 @@ private JobResult PerformInventory(InventoryJobConfiguration config, SubmitInven try { _logger.LogTrace($"Building Trusted Root Inventory Item Alias: {trustedRootCert.Name}"); - var certificatePem = client.GetCertificateByName(trustedRootCert.Name); + var certificatePem = _client.GetCertificateByName(trustedRootCert.Name); _logger.LogTrace($"Certificate String Back From Palo Pem: {certificatePem.Result}"); var bytes = Encoding.ASCII.GetBytes(certificatePem.Result); var cert = new X509Certificate2(bytes); diff --git a/PaloAlto/Jobs/Management.cs b/PaloAlto/Jobs/Management.cs index 047789e..165d08f 100644 --- a/PaloAlto/Jobs/Management.cs +++ b/PaloAlto/Jobs/Management.cs @@ -18,8 +18,6 @@ using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; -using System.Text.Json.Serialization; -using System.Text.RegularExpressions; using System.Threading; using System.Xml.Serialization; using Keyfactor.Extensions.Orchestrator.PaloAlto.Client; @@ -46,6 +44,8 @@ public class Management : IManagementJobExtension private readonly IPAMSecretResolver _resolver; + private PaloAltoClient _client; + private ILogger _logger; public Management(IPAMSecretResolver resolver) @@ -110,10 +110,14 @@ private JobResult PerformManagement(ManagementJobConfiguration config) "Invalid Management Operation" }; + + _client = new PaloAltoClient(config.CertificateStoreDetails.ClientMachine, ServerUserName, ServerPassword); //Api base URL Plus Key + if (config.OperationType.ToString() == "Add") { _logger.LogTrace("Adding..."); - _logger.LogTrace($"Add Config Json {JsonConvert.SerializeObject(config)}"); + if(config!=null) + _logger.LogTrace($"Add Config Json {_client.MaskSensitiveData(JsonConvert.SerializeObject(config))}"); complete = PerformAddition(config); _logger.LogTrace("Finished Perform Addition Function"); @@ -121,7 +125,7 @@ private JobResult PerformManagement(ManagementJobConfiguration config) else if (config.OperationType.ToString() == "Remove") { _logger.LogTrace("Removing..."); - _logger.LogTrace($"Remove Config Json {JsonConvert.SerializeObject(config)}"); + _logger.LogTrace($"Remove Config Json {_client.MaskSensitiveData(JsonConvert.SerializeObject(config))}"); complete = PerformRemoval(config); _logger.LogTrace("Finished Perform Removal Function"); @@ -146,13 +150,11 @@ private JobResult PerformRemoval(ManagementJobConfiguration config) _logger.MethodEntry(); _logger.LogTrace( - $"Credentials JSON: Url: {config.CertificateStoreDetails.ClientMachine} Password: {config.ServerPassword}"); - var client = - new PaloAltoClient(config.CertificateStoreDetails.ClientMachine, - ServerUserName, ServerPassword); //Api base URL Plus Key + $"Credentials JSON: Url: {config.CertificateStoreDetails.ClientMachine} Password:"); + _logger.LogTrace("Palo Alto Client Created"); - if (!SetPanoramaTarget(config, client)) + if (!SetPanoramaTarget(config, _client)) { return new JobResult { @@ -165,9 +167,9 @@ private JobResult PerformRemoval(ManagementJobConfiguration config) _logger.LogTrace( $"Alias to Remove From Palo Alto: {config.JobCertificate.Alias}"); - if (!DeleteCertificate(config, client, warnings, out var deleteResult)) return deleteResult; + if (!DeleteCertificate(config, _client, warnings, out var deleteResult)) return deleteResult; _logger.LogTrace("Attempting to Commit Changes for Removal Job..."); - warnings = CommitChanges(config, client, warnings); + warnings = CommitChanges(config, _client, warnings); _logger.LogTrace("Finished Committing Changes....."); if (warnings?.Length > 0) @@ -520,10 +522,6 @@ private string GetPemFile(ManagementJobConfiguration config) } } - //var pubCertPem = - // Pemify(Convert.ToBase64String(p.GetCertificate(alias).Certificate.GetEncoded())); - //_logger.LogTrace($"Public cert Pem {pubCertPem}"); - var pubCertPem = OrderCertificatesAndConvertToPem(p.GetCertificateChain(alias)); var certPem = privateKeyString + pubCertPem; diff --git a/PaloAltoTestConsole/KeyfactorClient.cs b/PaloAltoTestConsole/KeyfactorClient.cs index 47db9d5..bbda6ae 100644 --- a/PaloAltoTestConsole/KeyfactorClient.cs +++ b/PaloAltoTestConsole/KeyfactorClient.cs @@ -29,7 +29,7 @@ public async Task EnrollCertificate(string commonName var request = new RestRequest("/KeyfactorAPI/Enrollment/PFX", Method.Post); request.AddHeader("X-Keyfactor-Requested-With", "APIClient"); request.AddHeader("x-certificateformat", "PFX"); - request.AddHeader("Authorization", "Basic Authtoken"); + request.AddHeader("Authorization", "Basic sdfa="); request.AddHeader("Content-Type", "application/json"); var enrollRequest = new KeyfactorEnrollmentRequest { diff --git a/PaloAltoTestConsole/Program.cs b/PaloAltoTestConsole/Program.cs index f5d6dc3..a20325c 100644 --- a/PaloAltoTestConsole/Program.cs +++ b/PaloAltoTestConsole/Program.cs @@ -224,6 +224,7 @@ public static InventoryJobConfiguration GetPanoramaInventoryJobConfiguration() var fileContent = File.ReadAllText("PanoramaInventory.json").Replace("UserNameGoesHere", UserName) .Replace("PasswordGoesHere", Password).Replace("TemplateNameGoesHere", StorePath) + .Replace("TemplateStackGoesHere", TemplateStackName) .Replace("ClientMachineGoesHere", ClientMachine) .Replace("DeviceGroupGoesHere", DeviceGroup); @@ -278,6 +279,7 @@ public static ManagementJobConfiguration GetRemoveJobConfiguration() var fileContent = File.ReadAllText("ManagementRemove.json").Replace("UserNameGoesHere", UserName) .Replace("PasswordGoesHere", Password).Replace("TemplateNameGoesHere", StorePath) .Replace("DeviceGroupGoesHere", DeviceGroup).Replace("AliasGoesHere", CertAlias) + .Replace("TemplateStackGoesHere", TemplateStackName) .Replace("ClientMachineGoesHere", ClientMachine); var result = JsonConvert.DeserializeObject(fileContent); From f4ea8e0482f24e41ff28549ddcc9f35204d3fe77 Mon Sep 17 00:00:00 2001 From: Brian Hill <76450501+bhillkeyfactor@users.noreply.github.com> Date: Thu, 30 Jan 2025 13:33:52 -0500 Subject: [PATCH 3/4] Update Inventory.cs --- PaloAlto/Jobs/Inventory.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/PaloAlto/Jobs/Inventory.cs b/PaloAlto/Jobs/Inventory.cs index 00557fc..70e8dc9 100644 --- a/PaloAlto/Jobs/Inventory.cs +++ b/PaloAlto/Jobs/Inventory.cs @@ -87,8 +87,6 @@ private JobResult PerformInventory(InventoryJobConfiguration config, SubmitInven _logger.LogTrace("Store Properties are Valid"); _logger.LogTrace($"Inventory Config {_client.MaskSensitiveData(JsonConvert.SerializeObject(config))}"); - _logger.LogTrace( - $"Client Machine: {config.CertificateStoreDetails.ClientMachine} ApiKey: {config.ServerPassword}"); _logger.LogTrace("Inventory Palo Alto Client Created"); @@ -221,4 +219,4 @@ protected virtual CurrentInventoryItem BuildInventoryItem(string alias, string c } } } -} \ No newline at end of file +} From 4ec18f9dfbdc0abf6d82740bd887796a252ed794 Mon Sep 17 00:00:00 2001 From: Brian Hill <76450501+bhillkeyfactor@users.noreply.github.com> Date: Thu, 30 Jan 2025 13:36:37 -0500 Subject: [PATCH 4/4] Update CHANGELOG.md --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b1fd59..81a8890 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +2.3.1 +* Fixed issue where trace logs had extra info in them +* Fixed issue with chain support when pushing certs to palo + 2.3.0 * Added support for Template Only Commits * Added support for Template Stack Commits