Skip to content

Commit

Permalink
new binding version
Browse files Browse the repository at this point in the history
  • Loading branch information
bhillkeyfactor committed Jun 17, 2024
1 parent e169be3 commit bc7b13c
Show file tree
Hide file tree
Showing 49 changed files with 620 additions and 707 deletions.
150 changes: 41 additions & 109 deletions PaloAlto/Client/PaloAltoClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Keyfactor.Extensions.Orchestrator.PaloAlto.Models.Requests;
using Keyfactor.Extensions.Orchestrator.PaloAlto.Models.Responses;
using Keyfactor.Logging;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -119,26 +118,6 @@ public async Task<CommitResponse> GetCommitResponse()
}
}

public async Task<CommitResponse> GetDecryptionRulesByCertName(string certName,string vsysName)
{
try
{
var xpath =
$"/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='{vsysName}']/rulebase/decryption/rules[.//ssl-inbound-inspection='{certName}']";

var uri =
$"/api/?&type=commit&action=partial&cmd=<commit><partial><admin><member>{ServerUserName}</member></admin></partial></commit>&key={ApiKey}";

var response = await GetXmlResponseAsync<CommitResponse>(await HttpClient.GetAsync(uri));
return response;
}
catch (Exception e)
{
_logger.LogError($"Error Occured in PaloAltoClient.GetCertificateList: {e.Message}");
throw;
}
}

public async Task<CommitResponse> GetCommitAllResponse(string deviceGroup)
{
try
Expand All @@ -157,25 +136,6 @@ public async Task<CommitResponse> GetCommitAllResponse(string deviceGroup)
}
}

public async Task<ErrorSuccessResponse> SubmitEditProfile(EditProfileRequest request, string templateName, string storePath)
{
try
{
var editXml =
$"<entry name=\"{request.Name}\"><protocol-settings><min-version>{request.ProtocolSettings.MinVersion.Text}</min-version><max-version>{request.ProtocolSettings.MaxVersion.Text}</max-version></protocol-settings><certificate>{request.Certificate}</certificate></entry>";

string uri=
$@"/api/?type=config&action=edit&xpath={storePath}/ssl-tls-service-profile/entry[@name='{request.Name}']&element={editXml}&key={ApiKey}&target-tpl={GetTemplateName(storePath)}";

var response = await GetXmlResponseAsync<ErrorSuccessResponse>(await HttpClient.GetAsync(uri));
return response;
}
catch (Exception e)
{
_logger.LogError($"Error Occured in PaloAltoClient.SubmitDeleteCertificate: {e.Message}");
throw;
}
}

private string GetTemplateName(string storePath)
{
Expand All @@ -192,22 +152,6 @@ private string GetTemplateName(string storePath)
return templateName;
}

public async Task<GetProfileByCertificateResponse> GetProfileByCertificate(string storePath, string certificate)
{
try
{
var xPath = $"{storePath}/ssl-tls-service-profile/entry[./certificate='{certificate}']";
var uri = $"/api/?type=config&action=get&target-tpl={GetTemplateName(storePath)}&xpath={xPath}&key={ApiKey}";
var response =
await GetXmlResponseAsync<GetProfileByCertificateResponse>(await HttpClient.GetAsync(uri));
return response;
}
catch (Exception e)
{
_logger.LogError($"Error Occured in PaloAltoClient.GetProfileByCertificate: {e.Message}");
throw;
}
}

public async Task<AuthenticationResponse> GetAuthenticationResponse()
{
Expand Down Expand Up @@ -253,56 +197,7 @@ public async Task<string> GetCertificateByName(string name)
}
}

public async Task<string> GetDecryptionRuleBindings(string certificateName,string vsysName)
{
try
{
var xPath = $"/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='{vsysName}']/rulebase/decryption/rules[.//ssl-inbound-inspection='{certificateName}']";
var uri = $"/api/?type=config&key={ApiKey}&xpath={xPath}";

return await GetResponseAsync(await HttpClient.GetAsync(uri));
}
catch (Exception e)
{
_logger.LogError($"Error Occured in PaloAltoClient.GetCertificateByName: {e.Message}");
throw;
}
}


public async Task<string> GetTlsProfileBindings(string certificateName, string vsysName)
{
try
{
var xPath = $"/config/devices/entry/vsys/entry[@name='{vsysName}']/ssl-tls-service-profile";
var uri = $"/api/?type=config&key={ApiKey}&xpath={xPath}";

return await GetResponseAsync(await HttpClient.GetAsync(uri));
}
catch (Exception e)
{
_logger.LogError($"Error Occured in PaloAltoClient.GetCertificateByName: {e.Message}");
throw;
}
}


public async Task<string> GetTlsProfileBindings(string certificateName)
{
try
{
var xPath = "/config/shared/ssl-tls-service-profile";
var uri = $"/api/?type=config&key={ApiKey}&xpath={xPath}";

return await GetResponseAsync(await HttpClient.GetAsync(uri));
}
catch (Exception e)
{
_logger.LogError($"Error Occured in PaloAltoClient.GetCertificateByName: {e.Message}");
throw;
}
}

public async Task<ErrorSuccessResponse> SubmitDeleteCertificate(string name, string storePath)
{
try
Expand Down Expand Up @@ -335,7 +230,7 @@ public async Task<ErrorSuccessResponse> SubmitDeleteTrustedRoot(string name, str
public async Task<ErrorSuccessResponse> SubmitSetTrustedRoot(string name, string storePath)
{
try
{
{
string uri = $@"/api/?type=config&action=set&xpath={storePath}/ssl-decrypt&element=<trusted-root-CA><member>{name}</member></trusted-root-CA>&key={ApiKey}&target-tpl={GetTemplateName(storePath)}";
return await GetXmlResponseAsync<ErrorSuccessResponse>(await HttpClient.GetAsync(uri));
}
Expand All @@ -344,16 +239,40 @@ public async Task<ErrorSuccessResponse> SubmitSetTrustedRoot(string name, string
_logger.LogError($"Error Occured in PaloAltoClient.SubmitSetTrustedRoot: {e.Message}");
throw;
}
}

public async Task<ErrorSuccessResponse> SetPanoramaTarget(string storePath)
{
try
{
string uri = $"/api/?type=op&cmd=<set><system><setting><target><template><name>{GetTemplateName(storePath)}</name><vsys>{GetVirtualSystemFromPath(storePath)}</vsys></template></target></setting></system></set>&key={ApiKey}";
return await GetXmlResponseAsync<ErrorSuccessResponse>(await HttpClient.GetAsync(uri));
}
catch (Exception e)
{
_logger.LogError($"Error Occured in PaloAltoClient.SubmitSetTrustedRoot: {e.Message}");
throw;
}
}


public async Task<ErrorSuccessResponse> ImportCertificate(string name, string passPhrase, byte[] bytes,
string includeKey, string category, string storePath)
{
try
{
var templateName=GetTemplateName(storePath);
var uri =
$@"/api/?type=import&category={category}&certificate-name={name}&format=pem&include-key={includeKey}&passphrase={passPhrase}&target-tpl={templateName}&target-tpl-vsys=&vsys&key={ApiKey}";
var vsys = GetVirtualSystemFromPath(storePath);
string uri;
if (!Validators.IsValidPanoramaVsysFormat(storePath))
{
uri =$@"/api/?type=import&category={category}&certificate-name={name}&format=pem&include-key={includeKey}&passphrase={passPhrase}&target-tpl={templateName}&vsys={vsys}&key={ApiKey}";
}
else
{
uri = $@"/api/?type=import&category={category}&certificate-name={name}&format=pem&include-key={includeKey}&passphrase={passPhrase}&key={ApiKey}";
}

var boundary = $"--------------------------{Guid.NewGuid():N}";
var requestContent = new MultipartFormDataContent();
requestContent.Headers.Remove("Content-Type");
Expand All @@ -375,7 +294,20 @@ public async Task<ErrorSuccessResponse> ImportCertificate(string name, string pa
}
}

static string GetVirtualSystemFromPath(string path)
{
string pattern = @"vsys/entry\[@name='([^']*)'\]";

Match match = Regex.Match(path, pattern);

if (match.Success)
{
string vsysName = match.Groups[1].Value;
return vsysName;
}

return "";
}
public async Task<T> GetXmlResponseAsync<T>(HttpResponseMessage response)
{
try
Expand Down
81 changes: 7 additions & 74 deletions PaloAlto/Jobs/Inventory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,8 @@
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Xml.Serialization;
using Keyfactor.Extensions.Orchestrator.PaloAlto.Client;
using Keyfactor.Extensions.Orchestrator.PaloAlto.Models.Responses;
using Keyfactor.Logging;
using Keyfactor.Orchestrators.Common.Enums;
using Keyfactor.Orchestrators.Extensions;
Expand Down Expand Up @@ -68,36 +65,21 @@ public string ResolvePamField(string name, string value)
return _resolver.Resolve(value);
}

static string GetVirtualSystemFromPath(string path)
{
string pattern = @"vsys/entry\[@name='([^']*)'\]";

Match match = Regex.Match(path, pattern);

if (match.Success)
{
string vsysName = match.Groups[1].Value;
return vsysName;
}
else
{
return "";
}
}

private JobResult PerformInventory(InventoryJobConfiguration config, SubmitInventoryUpdate submitInventory)
{
try
{
_logger.MethodEntry(LogLevel.Debug);
ServerPassword = ResolvePamField("ServerPassword", config.ServerPassword);
ServerUserName = ResolvePamField("ServerUserName", config.ServerUsername);
_logger.LogTrace("Got Server User Name and Password");

var (valid, result) = Validators.ValidateStoreProperties(StoreProperties,
config.CertificateStoreDetails.StorePath, config.CertificateStoreDetails.ClientMachine,
config.JobHistoryId, ServerUserName, ServerPassword);
if (!valid) return result;

_logger.LogTrace("Store Properties are Valid");
_logger.LogTrace($"Inventory Config {JsonConvert.SerializeObject(config)}");
_logger.LogTrace(
$"Client Machine: {config.CertificateStoreDetails.ClientMachine} ApiKey: {config.ServerPassword}");
Expand Down Expand Up @@ -131,36 +113,8 @@ private JobResult PerformInventory(InventoryJobConfiguration config, SubmitInven
{
_logger.LogTrace(
$"Building Cert List Inventory Item Alias: {c.Name} Pem: {c.PublicKey} Private Key: {c.PrivateKey?.Length > 0}");

var bindingList=new Dictionary<string,object>();
if (config.CertificateStoreDetails.StorePath.Contains("/vsys"))
{
var vsys = GetVirtualSystemFromPath(config.CertificateStoreDetails.StorePath);
var drBindings = client.GetDecryptionRuleBindings(c.Name, vsys).Result;
var tlsBindings = client.GetTlsProfileBindings(c.Name, vsys).Result;
if (tlsBindings.Length > 0)
{
var tlsCsv = GetTlsCsv(tlsBindings, c.Name);
bindingList.Add("TlsProfile", tlsCsv);
}

if (drBindings.Length > 0)
{
var drCsv = GetDrBindingsCsv(drBindings);
bindingList.Add("DecryptionRule", drCsv);
}
}
else
{
var tlsBindings = client.GetTlsProfileBindings(c.Name).Result;
if (tlsBindings.Length > 0)
{
var tlsCsv = GetTlsCsv(tlsBindings, c.Name);
bindingList.Add("TlsProfile", tlsCsv);
}
}

return BuildInventoryItem(c.Name, c.PublicKey, c.PrivateKey?.Length>0, bindingList, false);

return BuildInventoryItem(c.Name, c.PublicKey, c.PrivateKey?.Length>0, false);
}
catch
{
Expand All @@ -183,7 +137,7 @@ private JobResult PerformInventory(InventoryJobConfiguration config, SubmitInven
var cert = new X509Certificate2(bytes);
_logger.LogTrace(
$"Building Trusted Root Inventory Item Pem: {certificatePem.Result} Has Private Key: {cert.HasPrivateKey}");
inventoryItems.Add(BuildInventoryItem(trustedRootCert.Name, certificatePem.Result, cert.HasPrivateKey,new Dictionary<string, object>(), true));
inventoryItems.Add(BuildInventoryItem(trustedRootCert.Name, certificatePem.Result, cert.HasPrivateKey, true));
}
catch
{
Expand All @@ -208,26 +162,6 @@ private JobResult PerformInventory(InventoryJobConfiguration config, SubmitInven
}
}

public static string GetDrBindingsCsv(string xmlContent)
{
XDocument doc = XDocument.Parse(xmlContent);
var names = doc.Descendants("entry")
.Select(e => e.Attribute("name")?.Value)
.Where(name => !string.IsNullOrEmpty(name));

return string.Join(", ", names);
}

static string GetTlsCsv(string xmlResponse, string certificateName)
{
XDocument doc = XDocument.Parse(xmlResponse);
var entries = doc.Descendants("entry")
.Where(e => (string)e.Element("certificate") == certificateName)
.Select(e => (string)e.Attribute("name"));

return string.Join(",", entries);
}

private JobResult ReturnJobResult(InventoryJobConfiguration config, bool warningFlag, StringBuilder sb)
{
if (warningFlag)
Expand Down Expand Up @@ -258,7 +192,7 @@ private void LogResponse<T>(T content)
_logger.LogTrace($"Serialized Xml Response {resWriter}");
}

protected virtual CurrentInventoryItem BuildInventoryItem(string alias, string certPem, bool privateKey, Dictionary<string,object> bindings,bool trustedRoot)
protected virtual CurrentInventoryItem BuildInventoryItem(string alias, string certPem, bool privateKey,bool trustedRoot)
{
try
{
Expand All @@ -271,8 +205,7 @@ protected virtual CurrentInventoryItem BuildInventoryItem(string alias, string c
Certificates = new[] {certPem},
ItemStatus = OrchestratorInventoryItemStatus.Unknown,
PrivateKeyEntry = privateKey,
UseChainLevel = false,
Parameters = bindings
UseChainLevel = false
};

return acsi;
Expand Down
Loading

0 comments on commit bc7b13c

Please sign in to comment.