From c5fe042b572878fbda3281e428c6d75e3446e7a0 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Fri, 18 Feb 2022 15:48:43 -0500 Subject: [PATCH 1/2] Added Logging and Error Improvements --- AnyAgent/CertManager.cs | 685 ++++++++++++++++++++++---------- AnyAgent/Inventory.cs | 12 +- AnyAgent/InventoryManagement.cs | 36 +- 3 files changed, 503 insertions(+), 230 deletions(-) diff --git a/AnyAgent/CertManager.cs b/AnyAgent/CertManager.cs index 7e5da4a..387d93f 100644 --- a/AnyAgent/CertManager.cs +++ b/AnyAgent/CertManager.cs @@ -11,7 +11,6 @@ // 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; using System.Collections.Generic; using System.Configuration; @@ -25,6 +24,7 @@ using DataPower.API.client; using Keyfactor.Platform.Extensions.Agents; using Keyfactor.Platform.Extensions.Agents.Enums; +using Newtonsoft.Json; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Pkcs; @@ -42,18 +42,22 @@ public CertManager() _appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); _protocol = _appConfig.AppSettings.Settings["Protocol"].Value; } - + public bool DoesCryptoCertificateObjectExist(CertStoreInfo ci, string cryptoCertObjectName, ApiClient apiClient) { var bUpdateCryptoCertificateObject = false; try { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); //Get a count of the crypto certificates that have the name we are looking for should be equal to one if it exists var viewAllCryptoCertRequest = new ViewCryptoCertificatesRequest(ci.Domain); + Logger.Trace($"viewAllCryptoCertRequest JSON {JsonConvert.SerializeObject(viewAllCryptoCertRequest)}"); var viewAllCryptoCertResponse = apiClient.ViewCertificates(viewAllCryptoCertRequest); + Logger.Trace($"viewAllCryptoCertResponse JSON {JsonConvert.SerializeObject(viewAllCryptoCertResponse)}"); - if(viewAllCryptoCertResponse.CryptoCertificates.Count(x=> x.Name== cryptoCertObjectName)==1) + if (viewAllCryptoCertResponse.CryptoCertificates.Count(x => x.Name == cryptoCertObjectName) == 1) { + Logger.Trace("Only One Found, we are good!"); bUpdateCryptoCertificateObject = true; } } @@ -61,12 +65,14 @@ public bool DoesCryptoCertificateObjectExist(CertStoreInfo ci, string cryptoCert { Logger.Error($"There was an issue receiving the certificates: {cryptoCertObjectName} Error {ex.Message}"); } + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return bUpdateCryptoCertificateObject; } public void DisableCryptoCertificateObject(string cryptoCertObjectName, ApiClient apiClient) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); Logger.Trace($"Disable State for Crypto Certificate Object: {cryptoCertObjectName}"); try { @@ -82,7 +88,10 @@ public void DisableCryptoCertificateObject(string cryptoCertObjectName, ApiClien PasswordAlias = null } }; + Logger.Trace($"cryptoCertUpdateRequest JSON {JsonConvert.SerializeObject(cryptoCertUpdateRequest)}"); apiClient.UpdateCryptoCertificate(cryptoCertUpdateRequest); + Logger.Trace("Crypto Certificate Updated"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); } catch (Exception ex) { @@ -92,14 +101,18 @@ public void DisableCryptoCertificateObject(string cryptoCertObjectName, ApiClien public bool DoesCryptoKeyObjectExist(CertStoreInfo ci, string cryptoKeyObjectName, ApiClient apiClient) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); var bUpdateCryptoKeyObject = false; try { //Look for CryptoKey var viewCryptoKeyRequest = new ViewCryptoKeysRequest(ci.Domain); + Logger.Trace($"viewCryptoKeyRequest JSON {JsonConvert.SerializeObject(viewCryptoKeyRequest)}"); var viewCryptoKeyResponse = apiClient.ViewCryptoKeys(viewCryptoKeyRequest); + Logger.Trace($"viewCryptoKeyResponse JSON {JsonConvert.SerializeObject(viewCryptoKeyResponse)}"); if (viewCryptoKeyResponse.CryptoKeys.Count(x => x.Name == cryptoKeyObjectName) == 1) { + Logger.Trace("Only One Found, we are good!"); bUpdateCryptoKeyObject = true; } } @@ -107,12 +120,13 @@ public bool DoesCryptoKeyObjectExist(CertStoreInfo ci, string cryptoKeyObjectNam { Logger.Error($"Crypto Key Object does not exist: {cryptoKeyObjectName} : {ex.Message}"); } - + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return bUpdateCryptoKeyObject; } public void DisableCryptoKeyObject(string cryptoKeyObjectName, ApiClient apiClient) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); Logger.Trace($"Disable State for Crypto Certificate Object: {cryptoKeyObjectName}"); try { @@ -127,7 +141,10 @@ public void DisableCryptoKeyObject(string cryptoKeyObjectName, ApiClient apiClie PasswordAlias = null } }; + Logger.Trace($"cryptoKeyUpdateRequest JSON {JsonConvert.SerializeObject(cryptoKeyUpdateRequest)}"); apiClient.UpdateCryptoKey(cryptoKeyUpdateRequest); + Logger.Trace("Crypto Key Updated!"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); } catch (Exception ex) { @@ -138,29 +155,33 @@ public void DisableCryptoKeyObject(string cryptoKeyObjectName, ApiClient apiClie public void UpdatePrivateKey(CertStoreInfo ci, string cryptoKeyObjectName, ApiClient apiClient, string keyFileName, string alias) { - Logger.Trace($"Updating Crypto Key Object: {cryptoKeyObjectName}"); - try + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + Logger.Trace($"Updating Crypto Key Object: {cryptoKeyObjectName}"); + try + { + var cryptoKeyRequest = new CryptoKeyUpdateRequest(apiClient.Domain, cryptoKeyObjectName) { - var cryptoKeyRequest = new CryptoKeyUpdateRequest(apiClient.Domain, cryptoKeyObjectName) + CryptoKey = new CryptoKey { - CryptoKey = new CryptoKey - { - CertFile = ci.CertificateStore.Trim() + ":///" + keyFileName, - Name = cryptoKeyObjectName - } - }; - - apiClient.UpdateCryptoKey(cryptoKeyRequest); - } - catch (Exception ex) - { - Logger.Error($"There was an issue updating the private key: {cryptoKeyObjectName} Error {ex.Message}"); - } + CertFile = ci.CertificateStore.Trim() + ":///" + keyFileName, + Name = cryptoKeyObjectName + } + }; + Logger.Trace($"cryptoKeyRequest JSON {JsonConvert.SerializeObject(cryptoKeyRequest)}"); + apiClient.UpdateCryptoKey(cryptoKeyRequest); + Logger.Trace("Private Key Updated!"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); + } + catch (Exception ex) + { + Logger.Error($"There was an issue updating the private key: {cryptoKeyObjectName} Error {ex.Message}"); + } } public void AddCryptoKey(CertStoreInfo ci, string cryptoKeyObjectName, ApiClient apiClient, string keyFileName, string alias) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); Logger.Trace( $"Adding CryptoKey Object for Private Key {alias} to CERT store with Filename {keyFileName} "); try @@ -173,8 +194,10 @@ public void AddCryptoKey(CertStoreInfo ci, string cryptoKeyObjectName, ApiClient Name = cryptoKeyObjectName } }; - + Logger.Trace($"cryptoKeyRequest JSON {JsonConvert.SerializeObject(cryptoKeyRequest)}"); apiClient.AddCryptoKey(cryptoKeyRequest); + Logger.Trace("Private Key Added!"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); } catch (Exception ex) { @@ -185,17 +208,27 @@ public void AddCryptoKey(CertStoreInfo ci, string cryptoKeyObjectName, ApiClient public AnyErrors RemovePrivateKeyFile(AnyJobConfigInfo addConfig, CertStoreInfo ci, string keyFileName) { + try + { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); Logger.Trace($"Removing Old Private Key File {keyFileName}"); - var removeFileResult=RemoveFile(addConfig, ci, keyFileName); + var removeFileResult = RemoveFile(addConfig, ci, keyFileName); Logger.Trace($"Private Key {keyFileName} is removed"); - + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return removeFileResult; + } + catch (Exception e) + { + Logger.Error($"Error In CertManager.RemovePrivateKeyFile: {e.Message}"); + throw; + } } public CertificateAddRequest AddPrivateKey(CertStoreInfo ci, string alias, string keyFileName, ApiClient apiClient, string privateKeyString) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); Logger.Trace($"Adding Private Key {alias} to CERT store with Filename {keyFileName} "); try { @@ -207,6 +240,8 @@ public CertificateAddRequest AddPrivateKey(CertStoreInfo ci, string alias, strin Content = privateKeyString } }; + Logger.Trace($"certKeyRequest JSON {JsonConvert.SerializeObject(certKeyRequest)}"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return certKeyRequest; } catch (Exception ex) @@ -220,29 +255,34 @@ public CertificateAddRequest AddPrivateKey(CertStoreInfo ci, string alias, strin public void UpdateCryptoCert(CertStoreInfo ci, string cryptoCertObjectName, ApiClient apiClient, string certFileName, string alias) { - Logger.Trace($"Updating Crypto Certificate Object: {cryptoCertObjectName}"); - try + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + Logger.Trace($"Updating Crypto Certificate Object: {cryptoCertObjectName}"); + try + { + var cryptoCertRequest = new CryptoCertificateUpdateRequest(apiClient.Domain, cryptoCertObjectName) { - var cryptoCertRequest = new CryptoCertificateUpdateRequest(apiClient.Domain, cryptoCertObjectName) + CryptoCert = new CryptoCertificate { - CryptoCert = new CryptoCertificate - { - CertFile = ci.CertificateStore.Trim() + ":///" + certFileName, - Name = cryptoCertObjectName - } - }; + CertFile = ci.CertificateStore.Trim() + ":///" + certFileName, + Name = cryptoCertObjectName + } + }; - apiClient.UpdateCryptoCertificate(cryptoCertRequest); - } - catch (Exception ex) - { - Logger.Error($"Error Updating Crypto Certificate Object: {cryptoCertObjectName} Error {ex.Message}"); - } + Logger.Trace($"certKeyRequest JSON {JsonConvert.SerializeObject(cryptoCertRequest)}"); + apiClient.UpdateCryptoCertificate(cryptoCertRequest); + Logger.Trace("UpdateCryptoCert Updated !"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); + } + catch (Exception ex) + { + Logger.Error($"Error Updating Crypto Certificate Object: {cryptoCertObjectName} Error {ex.Message}"); + } } public void AddCryptoCert(CertStoreInfo ci, string cryptoCertObjectName, ApiClient apiClient, string certFileName, string alias) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); Logger.Trace( $"Adding Crypto Object for Certificate {alias} to CERT store with Filename {certFileName} "); try @@ -255,8 +295,10 @@ public void AddCryptoCert(CertStoreInfo ci, string cryptoCertObjectName, ApiClie Name = cryptoCertObjectName } }; - + Logger.Trace($"cryptoCertRequest JSON {JsonConvert.SerializeObject(cryptoCertRequest)}"); apiClient.AddCryptoCertificate(cryptoCertRequest); + Logger.Trace("AddCryptoCert Added!"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); } catch (Exception ex) { @@ -266,16 +308,26 @@ public void AddCryptoCert(CertStoreInfo ci, string cryptoCertObjectName, ApiClie public AnyErrors RemoveCertificate(AnyJobConfigInfo addConfig, CertStoreInfo ci, string certFileName) { - Logger.Trace($"Removing Old Certificate File {certFileName}"); - var result=RemoveFile(addConfig, ci, certFileName); + try + { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + Logger.Trace($"Removing Old Certificate File {certFileName}"); + var result = RemoveFile(addConfig, ci, certFileName); Logger.Trace($"Old Certificate File {certFileName} is removed"); - + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return result; + } + catch (Exception e) + { + Logger.Error($"Error In CertManager.RemovePrivateKeyFile: {e.Message}"); + throw; + } } public CertificateAddRequest CertificateAddRequest(CertStoreInfo ci, string alias, string certFileName, ApiClient apiClient, string certPem) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); Logger.Trace($"Adding Certificate {alias} with Filename {certFileName} "); try { @@ -287,6 +339,8 @@ public CertificateAddRequest CertificateAddRequest(CertStoreInfo ci, string alia Content = certPem } }; + Logger.Trace($"certRequest JSON {JsonConvert.SerializeObject(certRequest)}"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return certRequest; } catch (Exception ex) @@ -299,6 +353,7 @@ public CertificateAddRequest CertificateAddRequest(CertStoreInfo ci, string alia public bool DoesKeyFileExist(CertStoreInfo ci, string keyFileName, ViewPublicCertificatesResponse viewCertificateCollection) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); var bRemoveKeyFile = false; try { @@ -316,13 +371,14 @@ public bool DoesKeyFileExist(CertStoreInfo ci, string keyFileName, ViewPublicCer { Logger.Error($"Error Matching Key File {keyFileName} was found in domain {ci.Domain} Error {ex.Message}"); } - + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return bRemoveKeyFile; } public bool DoesCertificateFileExist(CertStoreInfo ci, ApiClient apiClient, - string certFileName,ViewPublicCertificatesResponse viewCertificateCollection) + string certFileName, ViewPublicCertificatesResponse viewCertificateCollection) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); var bRemoveCertificateFile = false; try { @@ -339,13 +395,15 @@ public bool DoesCertificateFileExist(CertStoreInfo ci, ApiClient apiClient, { Logger.Error($"Error Matching Certificate File {certFileName} was found in domain {ci.Domain} Error {ex.Message}"); } - + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return bRemoveCertificateFile; } public string GetCertPem(AnyJobConfigInfo addConfig, string alias, ref string privateKeyString) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + Logger.Trace($"alias {alias} privateKeyString {privateKeyString}"); string certPem = null; try { @@ -360,7 +418,7 @@ public string GetCertPem(AnyJobConfigInfo addConfig, string alias, ref string pr { store = new Pkcs12Store(ms, addConfig.Job.PfxPassword.ToCharArray()); - + string storeAlias; TextWriter streamWriter; using (var memoryStream = new MemoryStream()) @@ -404,25 +462,30 @@ public string GetCertPem(AnyJobConfigInfo addConfig, string alias, ref string pr { Logger.Error($"Error Generating PEM: Error {ex.Message}"); } - + Logger.Trace($"PEM {certPem}"); + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); return certPem; } public AnyErrors AddPubCert(AnyJobConfigInfo addPubConfig, CertStoreInfo ci, NamePrefix np) { - - var error=new AnyErrors(); - Logger.Trace("Entering AddPubCert"); + + var error = new AnyErrors(); + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); error.HasError = false; Logger.Trace($"Entering AddPubCert for Domain: {ci.Domain} and Certificate Store: {ci.CertificateStore}"); - + Logger.Trace($"Creating API Client Created with user: {addPubConfig.Server.Username} password: {addPubConfig.Server.Password} protocol: {_protocol} ClientMachine: {addPubConfig.Store.ClientMachine.Trim()} Domain: {ci.Domain}"); var apiClient = new ApiClient(addPubConfig.Server.Username, addPubConfig.Server.Password, $"{_protocol}://" + addPubConfig.Store.ClientMachine.Trim(), ci.Domain); + Logger.Trace("API Client Created"); var certAlias = addPubConfig.Job.Alias; + if (string.IsNullOrEmpty(certAlias)) certAlias = Guid.NewGuid().ToString(); + Logger.Trace($"certAlias {certAlias}"); + try { @@ -431,8 +494,9 @@ public AnyErrors AddPubCert(AnyJobConfigInfo addPubConfig, CertStoreInfo ci, Nam var certData = Convert.FromBase64String(addPubConfig.Job.EntryContents); //If you have a password then you will get a PFX in return instead of the base64 encoded string - if(!String.IsNullOrEmpty(addPubConfig.Job?.PfxPassword)) + if (!String.IsNullOrEmpty(addPubConfig.Job?.PfxPassword)) { + Logger.Trace($"Has PFX Password {addPubConfig.Job?.PfxPassword}"); using (MemoryStream ms = new MemoryStream(certData)) { @@ -446,11 +510,13 @@ public AnyErrors AddPubCert(AnyJobConfigInfo addPubConfig, CertStoreInfo ci, Nam { certPem = Utility.Pemify(addPubConfig.Job.EntryContents); } - + + Logger.Trace($"certPem {certPem}"); + var certFileName = certAlias.Replace(".", "_") + ".pem"; - + Logger.Trace( - $"Adding Public Cert Certificate {certAlias} to PUBCERT store with Filename {certFileName} "); + $"Adding Public Cert Certificate {certAlias} to PubCert store with Filename {certFileName} "); var certRequest = new CertificateAddRequest(apiClient.Domain, certFileName, ci.CertificateStore.Trim()) { @@ -460,9 +526,12 @@ public AnyErrors AddPubCert(AnyJobConfigInfo addPubConfig, CertStoreInfo ci, Nam Content = certPem } }; - + Logger.Trace($"certRequest JSON {JsonConvert.SerializeObject(certRequest)}"); apiClient.AddCertificateFile(certRequest); + Logger.Trace("Certificate Added!"); apiClient.SaveConfig(); + Logger.Trace("Configuration Saved!"); + } catch (Exception ex) { @@ -470,52 +539,67 @@ public AnyErrors AddPubCert(AnyJobConfigInfo addPubConfig, CertStoreInfo ci, Nam Logger.Trace($"Error on {certAlias}: {ex.Message}"); apiClient.SaveConfig(); } - + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return error; } private AnyErrors RemoveCertFromDomain(AnyJobConfigInfo removeConfig, CertStoreInfo ci, NamePrefix np) { - var error = new AnyErrors {HasError = false}; + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + var error = new AnyErrors { HasError = false }; Logger.Trace($"Entering RemoveCertStore for {removeConfig.Job.Alias} "); Logger.Trace( $"Entering RemoveCertStore for Domain: {ci.Domain} and Certificate Store: {ci.CertificateStore}"); + Logger.Trace($"Creating API Client Created with user: {removeConfig.Server.Username} password: {removeConfig.Server.Password} protocol: {_protocol} ClientMachine: {removeConfig.Store.ClientMachine.Trim()} Domain: {ci.Domain}"); var apiClient = new ApiClient(removeConfig.Server.Username, removeConfig.Server.Password, $"{_protocol}://" + removeConfig.Store.ClientMachine.Trim(), ci.Domain); - + Logger.Trace("API Client Created!"); try { Logger.Trace($"Checking to find CryptoCertObject {removeConfig.Job.Alias} "); var viewCert = new ViewCryptoCertificatesRequest(apiClient.Domain, removeConfig.Job.Alias); + Logger.Trace($"viewCert JSON {JsonConvert.SerializeObject(viewCert)}"); + var viewCertificateSingle = apiClient.ViewCryptoCertificate(viewCert); + Logger.Trace($"viewCert JSON {JsonConvert.SerializeObject(viewCertificateSingle)}"); + if (viewCertificateSingle != null && !string.IsNullOrEmpty(viewCertificateSingle.CryptoCertificate.Name)) { Logger.Trace($"Remove CryptoObject {viewCertificateSingle.CryptoCertificate.Name} "); var request = new DeleteCryptoCertificateRequest(apiClient.Domain, removeConfig.Job.Alias); + Logger.Trace($"request JSON {JsonConvert.SerializeObject(request)}"); apiClient.DeleteCryptoCertificate(request); Logger.Trace($"Remove Certificate File {viewCertificateSingle.CryptoCertificate.CertFile} "); var request2 = new DeleteCertificateRequest(apiClient.Domain, viewCertificateSingle.CryptoCertificate.CertFile.Replace(ci.CertificateStore + ":///", "")); + Logger.Trace($"request2 JSON {JsonConvert.SerializeObject(request2)}"); apiClient.DeleteCertificate(request2); + Logger.Trace("Certificate Deleted!"); } var cryptoKeyObjectName = Utility.ReplaceFirstOccurrence(removeConfig.Job.Alias, np.CryptoCertObjectPrefix?.Trim() ?? String.Empty, np.CryptoKeyObjectPrefix?.Trim() ?? String.Empty); Logger.Trace($"Checking to find CryptoKeyObject {cryptoKeyObjectName} "); var viewKey = new ViewCryptoKeysRequest(apiClient.Domain); + Logger.Trace($"viewKey JSON {JsonConvert.SerializeObject(viewKey)}"); var viewKeyResponse = apiClient.ViewCryptoKeys(viewKey); + Logger.Trace($"viewKeyResponse JSON {JsonConvert.SerializeObject(viewKeyResponse)}"); var cryptoKey = viewKeyResponse.CryptoKeys.FirstOrDefault(x => x.Name == cryptoKeyObjectName); + Logger.Trace($"cryptoKey JSON {JsonConvert.SerializeObject(cryptoKey)}"); if (viewKeyResponse.CryptoKeys != null && !string.IsNullOrEmpty(cryptoKey?.Name)) { Logger.Trace($"Remove CryptoKeyObject {cryptoKey.Name} "); var request = new DeleteCryptoKeyRequest(apiClient.Domain, cryptoKeyObjectName); + Logger.Trace($"request JSON {JsonConvert.SerializeObject(request)}"); apiClient.DeleteCryptoKey(request); Logger.Trace($"Remove Key File {cryptoKey.CertFile} "); var request2 = new DeleteCertificateRequest(apiClient.Domain, cryptoKey.CertFile.Replace(ci.CertificateStore + ":///", "")); + Logger.Trace($"request2 JSON {JsonConvert.SerializeObject(request2)}"); apiClient.DeleteCertificate(request2); + Logger.Trace("Certificate Deleted!"); } } catch (Exception ex) @@ -524,26 +608,31 @@ private AnyErrors RemoveCertFromDomain(AnyJobConfigInfo removeConfig, CertStoreI error.ErrorMessage = ex.Message; Logger.Trace($"Error on {removeConfig.Job.Alias}: {ex.Message}"); } - + Logger.Trace("Saving Config!"); apiClient.SaveConfig(); - + Logger.Trace("Config Saved!"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return error; } private AnyErrors RemoveFile(AnyJobConfigInfo removeConfig, CertStoreInfo ci, string filename) { - var error = new AnyErrors {HasError = false}; - Logger.Trace($"Entering RemoveFile for {removeConfig.Job.Alias} "); + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + var error = new AnyErrors { HasError = false }; + Logger.Trace($"Entering RemoveFile for {removeConfig.Job.Alias} filename {filename}"); Logger.Trace($"Entering RemoveFile for Domain: {ci.Domain} and Certificate Store: {ci.CertificateStore}"); + Logger.Trace($"Creating API Client Created with user: {removeConfig.Server.Username} password: {removeConfig.Server.Password} protocol: {_protocol} ClientMachine: {removeConfig.Store.ClientMachine.Trim()} Domain: {ci.Domain}"); var apiClient = new ApiClient(removeConfig.Server.Username, removeConfig.Server.Password, $"{_protocol}://" + removeConfig.Store.ClientMachine.Trim(), ci.Domain); - + Logger.Trace("Api Client Created!"); try { Logger.Trace($"Deleting Actual File {filename} "); var request2 = new DeleteCertificateRequest(apiClient.Domain, filename.Replace(ci.CertificateStore + ":///", "")); + Logger.Trace($"request2 JSON {JsonConvert.SerializeObject(request2)}"); apiClient.DeleteCertificate(request2); + Logger.Trace("Certificate Deleted!"); } catch (Exception ex) { @@ -551,95 +640,147 @@ private AnyErrors RemoveFile(AnyJobConfigInfo removeConfig, CertStoreInfo ci, st error.ErrorMessage = ex.Message; Logger.Trace($"Error on {removeConfig.Job.Alias}: {ex.Message}"); } - + Logger.Trace("Saving Config!"); apiClient.SaveConfig(); + Logger.Trace("Config Saved!"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return error; } public AnyErrors Remove(AnyJobConfigInfo removeConfig, CertStoreInfo ci, NamePrefix np) { - var error=new AnyErrors(); - Logger.Trace("Entering Remove"); - error.HasError = false; - - var publicCertStoreName = _appConfig.AppSettings.Settings["PublicCertStoreName"].Value; - var storePath = removeConfig.Store.StorePath; - - if (storePath.Contains(publicCertStoreName)) + try { - Logger.Trace("Cannot Remove Public Certificates"); - error.HasError = true; + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + var error = new AnyErrors { HasError = false }; + + var publicCertStoreName = _appConfig.AppSettings.Settings["PublicCertStoreName"].Value; + var storePath = removeConfig.Store.StorePath; + Logger.Trace($"publicCertStoreName: {publicCertStoreName} storePath: {storePath}"); + + if (storePath.Contains(publicCertStoreName)) + { + Logger.Trace("Cannot Remove Public Certificates"); + error.HasError = true; + } + else + { + error = RemoveCertFromDomain(removeConfig, ci, np); + } + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); + Logger.Trace($"AnyErrors Return {JsonConvert.SerializeObject(error)}"); + return error; } - else + catch (Exception e) { - error=RemoveCertFromDomain(removeConfig, ci, np); + Logger.Error($"Error In CertManager.Remove {e.Message}!"); + throw; } - - return error; } public AnyErrors Add(AnyJobConfigInfo addConfig, CertStoreInfo ci, NamePrefix np) { - var result = new AnyErrors(); - Logger.Trace("Entering Add"); - result.HasError = false; - - var publicCertStoreName = _appConfig.AppSettings.Settings["PublicCertStoreName"].Value; - var storePath = addConfig.Store.StorePath; + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + try + { + var result = new AnyErrors(); + Logger.Trace("Entering Add"); + result.HasError = false; - result = storePath.Contains(publicCertStoreName) ? AddPubCert(addConfig, ci, np) : AddCertStore(addConfig, ci, np); + var publicCertStoreName = _appConfig.AppSettings.Settings["PublicCertStoreName"].Value; + var storePath = addConfig.Store.StorePath; + Logger.Trace($"publicCertStoreName: {publicCertStoreName} storePath: {storePath}"); - return result; + result = storePath.Contains(publicCertStoreName) ? AddPubCert(addConfig, ci, np) : AddCertStore(addConfig, ci, np); + Logger.Trace($"result Return {JsonConvert.SerializeObject(result)}"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); + return result; + } + catch (Exception e) + { + Logger.Error($"Error In CertManager.Add {e.Message}!"); + throw; + } } private AnyErrors AddCertStore(AnyJobConfigInfo addConfig, CertStoreInfo ci, NamePrefix np) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); var error = new AnyErrors(); - Logger.Trace("Entering AddCertStore"); var privateKeyString = ""; Logger.Trace($"Entering AddCertStore for Domain: {ci.Domain} and Certificate Store: {ci.CertificateStore}"); + Logger.Trace($"Creating API Client Created with user: {addConfig.Server.Username} password: {addConfig.Server.Password} protocol: {_protocol} ClientMachine: {addConfig.Store.ClientMachine.Trim()} Domain: {ci.Domain}"); var apiClient = new ApiClient(addConfig.Server.Username, addConfig.Server.Password, $"{_protocol}://" + addConfig.Store.ClientMachine.Trim(), ci.Domain); + Logger.Trace("apiClient created!"); var alias = addConfig.Job.Alias.ToLower(); if (string.IsNullOrEmpty(alias)) alias = Guid.NewGuid().ToString().ToLower(); + + Logger.Trace($"alias: {alias}"); + try { if (!string.IsNullOrEmpty(addConfig.Job.PfxPassword)) { + Logger.Trace($"Has Password: {addConfig.Job.PfxPassword}"); var certPem = GetCertPem(addConfig, alias, ref privateKeyString); - + Logger.Trace($"certPem: {certPem}"); var baseAlias = alias.ToLower(); + Logger.Trace($"baseAlias: {baseAlias}"); var cryptoObjectPrefix = np.CryptoCertObjectPrefix?.Trim().ToLower() ?? string.Empty; var keyFileNamePrefix = np.KeyFilePrefix?.Trim().ToLower() ?? string.Empty; var certFileNamePrefix = np.CertFilePrefix?.Trim().ToLower() ?? string.Empty; var cryptoKeyObjectPrefix = np.CryptoKeyObjectPrefix?.Trim().ToLower() ?? string.Empty; + Logger.Trace($"cryptoObjectPrefix: {cryptoObjectPrefix}"); + Logger.Trace($"keyFileNamePrefix: {keyFileNamePrefix}"); + Logger.Trace($"certFileNamePrefix: {certFileNamePrefix}"); + Logger.Trace($"cryptoKeyObjectPrefix: {cryptoKeyObjectPrefix}"); + if (alias.ToLower().StartsWith(cryptoObjectPrefix)) baseAlias = Utility.ReplaceAlias(alias.ToLower(), cryptoObjectPrefix, ""); + Logger.Trace($"baseAlias: {baseAlias}"); + var certFileName = certFileNamePrefix + baseAlias + ".cer"; var keyFileName = keyFileNamePrefix + baseAlias + ".pem"; var cryptoCertObjectName = cryptoObjectPrefix + baseAlias; var cryptoKeyObjectName = cryptoKeyObjectPrefix + baseAlias; + Logger.Trace($"certFileName: {certFileName}"); + Logger.Trace($"keyFileName: {keyFileName}"); + Logger.Trace($"cryptoCertObjectName: {cryptoCertObjectName}"); + Logger.Trace($"cryptoKeyObjectName: {cryptoKeyObjectName}"); + //Get the certificate collection to be used to check for cert files and private keys var viewCert = new ViewPublicCertificatesRequest(ci.Domain, ci.CertificateStore); + Logger.Trace($"viewCert JSON {JsonConvert.SerializeObject(viewCert)}"); var viewCertificateCollection = apiClient.ViewPublicCertificates(viewCert); + Logger.Trace($"viewCertificateCollection JSON {JsonConvert.SerializeObject(viewCertificateCollection)}"); + Logger.Trace("Starting ReplaceCertificateFile!"); ReplaceCertificateFile(addConfig, ci, apiClient, certFileName, viewCertificateCollection, alias, certPem); + Logger.Trace("Finished ReplaceCertificateFile!"); + Logger.Trace("Starting ReplaceCryptoObject!"); ReplaceCryptoObject(ci, cryptoCertObjectName, apiClient, certFileName, alias); + Logger.Trace("Finished ReplaceCryptoObject!"); + Logger.Trace("Starting ReplacePrivateKey!"); ReplacePrivateKey(addConfig, ci, keyFileName, viewCertificateCollection, alias, apiClient, privateKeyString); + Logger.Trace("Finished ReplacePrivateKey!"); + Logger.Trace("Starting ReplaceCryptoKeyObject!"); ReplaceCryptoKeyObject(ci, cryptoKeyObjectName, apiClient, keyFileName, alias); + Logger.Trace("Finished ReplaceCryptoKeyObject!"); } - + Logger.Trace("Saving Config!"); apiClient.SaveConfig(); + Logger.Trace("Config Saved!"); } catch (Exception ex) { @@ -647,7 +788,7 @@ private AnyErrors AddCertStore(AnyJobConfigInfo addConfig, CertStoreInfo ci, Nam Logger.Trace($"Error on {alias}: {ex.Message}"); apiClient.SaveConfig(); } - + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return error; } @@ -655,194 +796,298 @@ private void ReplacePrivateKey(AnyJobConfigInfo addConfig, CertStoreInfo ci, str ViewPublicCertificatesResponse viewCertificateCollection, string alias, ApiClient apiClient, string privateKeyString) { - //See if KeyFile Exists if so remove and add a new one, if not just add a new one - var bRemoveKeyFile = DoesKeyFileExist(ci, keyFileName, viewCertificateCollection); - if (bRemoveKeyFile) - RemovePrivateKeyFile(addConfig, ci, keyFileName); - - var certKeyRequest = - AddPrivateKey(ci, alias, keyFileName, apiClient, privateKeyString); - Logger.Trace($"Adding Private File {keyFileName}"); - apiClient.AddCertificateFile(certKeyRequest); + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + try + { + //See if KeyFile Exists if so remove and add a new one, if not just add a new one + var bRemoveKeyFile = DoesKeyFileExist(ci, keyFileName, viewCertificateCollection); + Logger.Trace($"bRemoveKeyFile {bRemoveKeyFile}"); + if (bRemoveKeyFile) + { + Logger.Trace("Removing Private Key!"); + RemovePrivateKeyFile(addConfig, ci, keyFileName); + Logger.Trace("Private Key Removed!"); + } + + var certKeyRequest = + AddPrivateKey(ci, alias, keyFileName, apiClient, privateKeyString); + Logger.Trace($"certKeyRequest {JsonConvert.SerializeObject(certKeyRequest)}"); + Logger.Trace($"Adding Private File {keyFileName}"); + apiClient.AddCertificateFile(certKeyRequest); + Logger.Trace("Certificate File Added!"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); + } + catch (Exception e) + { + Logger.Error($"Error in CertManager.ReplacePrivateKey {e.Message}"); + throw; + } } private void ReplaceCertificateFile(AnyJobConfigInfo addConfig, CertStoreInfo ci, ApiClient apiClient, string certFileName, ViewPublicCertificatesResponse viewCertificateCollection, string alias, string certPem) { - //See if Certificate File Exists, if so remove it and add a new one, if not just add it - var certificateFileExists = - DoesCertificateFileExist(ci, apiClient, certFileName, viewCertificateCollection); - if (certificateFileExists) - RemoveCertificate(addConfig, ci, certFileName); - - Logger.Trace($"Adding Certificate File {certFileName}"); - var certRequest = CertificateAddRequest(ci, alias, certFileName, apiClient, certPem); - apiClient.AddCertificateFile(certRequest); + try + { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + Logger.Trace($"Cert Store Info {JsonConvert.SerializeObject(ci)}"); + Logger.Trace($"Cert Pem {certPem}"); + Logger.Trace($"certFileName {certFileName}"); + Logger.Trace($"alias {alias}"); + + //See if Certificate File Exists, if so remove it and add a new one, if not just add it + var certificateFileExists = + DoesCertificateFileExist(ci, apiClient, certFileName, viewCertificateCollection); + if (certificateFileExists) + RemoveCertificate(addConfig, ci, certFileName); + + Logger.Trace($"Adding Certificate File {certFileName}"); + var certRequest = CertificateAddRequest(ci, alias, certFileName, apiClient, certPem); + apiClient.AddCertificateFile(certRequest); + } + catch (Exception e) + { + Logger.Error($"Error in CertManager.ReplaceCertificateFile {e.Message}"); + throw; + } } private void ReplaceCryptoKeyObject(CertStoreInfo ci, string cryptoKeyObjectName, ApiClient apiClient, string keyFileName, string alias) { - //Search to See if the Crypto *Key* Object Already Exists (If so, it needs disabled and updated, If not add a new one) - //Crypto Objects can not be removed since they may be already referenced by sites and such so they need disabled instead - var cryptoKeyExists = - DoesCryptoKeyObjectExist(ci, cryptoKeyObjectName, apiClient); - if (cryptoKeyExists) + try { - DisableCryptoKeyObject(cryptoKeyObjectName, apiClient); - UpdatePrivateKey(ci, cryptoKeyObjectName, apiClient, keyFileName, alias); + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + + Logger.Trace($"Cert Store Info {JsonConvert.SerializeObject(ci)}"); + Logger.Trace($"Crypto Key Object Name {cryptoKeyObjectName}"); + Logger.Trace($"keyFileName {keyFileName}"); + Logger.Trace($"alias {alias}"); + + //Search to See if the Crypto *Key* Object Already Exists (If so, it needs disabled and updated, If not add a new one) + //Crypto Objects can not be removed since they may be already referenced by sites and such so they need disabled instead + var cryptoKeyExists = + DoesCryptoKeyObjectExist(ci, cryptoKeyObjectName, apiClient); + Logger.Trace($"Crypto Object Exists equals {cryptoKeyExists}"); + + if (cryptoKeyExists) + { + Logger.Trace("Disabling Crypto Key Object..."); + DisableCryptoKeyObject(cryptoKeyObjectName, apiClient); + Logger.Trace("Updating Crypto Key Object..."); + UpdatePrivateKey(ci, cryptoKeyObjectName, apiClient, keyFileName, alias); + Logger.Trace("Crypto Key Object Updated..."); + } + else + { + AddCryptoKey(ci, cryptoKeyObjectName, apiClient, keyFileName, alias); + } + + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); } - else + catch (Exception e) { - AddCryptoKey(ci, cryptoKeyObjectName, apiClient, keyFileName, alias); + Logger.Error($"Error in CertManager.ReplaceCryptoKeyObject {e.Message}"); + throw; } } private void ReplaceCryptoObject(CertStoreInfo ci, string cryptoCertObjectName, ApiClient apiClient, string certFileName, string alias) { - //Search to See if the Crypto *Certificate* Object Already Exists (If so, it needs disabled and updated, If not add a new one) - //Crypto Objects can not be removed since they may be already referenced by sites and such so they need disabled instead - var cryptoObjectExists = - DoesCryptoCertificateObjectExist(ci, cryptoCertObjectName, apiClient); - if (cryptoObjectExists) + try { - DisableCryptoCertificateObject(cryptoCertObjectName, apiClient); - UpdateCryptoCert(ci, cryptoCertObjectName, apiClient, - certFileName, alias); + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + //Search to See if the Crypto *Certificate* Object Already Exists (If so, it needs disabled and updated, If not add a new one) + //Crypto Objects can not be removed since they may be already referenced by sites and such so they need disabled instead + + Logger.Trace($"Cert Store Info {JsonConvert.SerializeObject(ci)}"); + Logger.Trace($"Crypto Object Name {cryptoCertObjectName}"); + Logger.Trace($"certFileName {certFileName}"); + Logger.Trace($"alias {alias}"); + + var cryptoObjectExists = + DoesCryptoCertificateObjectExist(ci, cryptoCertObjectName, apiClient); + + Logger.Trace($"Crypto Object Exists equals {cryptoObjectExists}"); + + if (cryptoObjectExists) + { + Logger.Trace("Disabling Crypto Certificate Object..."); + DisableCryptoCertificateObject(cryptoCertObjectName, apiClient); + Logger.Trace("Updating Crypto Certificate Object..."); + UpdateCryptoCert(ci, cryptoCertObjectName, apiClient, + certFileName, alias); + Logger.Trace("Disable and Update Complete.."); + } + else + { + Logger.Trace("Adding Crypto Certificate Object..."); + AddCryptoCert(ci, cryptoCertObjectName, apiClient, certFileName, alias); + } + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); } - else + catch (Exception e) { - AddCryptoCert(ci, cryptoCertObjectName, apiClient, certFileName, alias); + Logger.Error($"Error in CertManager.ReplaceCryptoObject {e.Message}"); + throw; } } public InventoryResult GetPublicCerts(ApiClient apiClient) { - var result = new InventoryResult(); - var error = new AnyErrors { HasError = false }; + try + { + var result = new InventoryResult(); + var error = new AnyErrors { HasError = false }; - Logger.Trace("GetPublicCerts"); - var viewCert = new ViewPublicCertificatesRequest(); - var viewCertificateCollection = apiClient.ViewPublicCertificates(viewCert); + Logger.Trace("GetPublicCerts"); + var viewCert = new ViewPublicCertificatesRequest(); + Logger.Trace($"Public Cert List Request {JsonConvert.SerializeObject(viewCert)}"); + var viewCertificateCollection = apiClient.ViewPublicCertificates(viewCert); + Logger.Trace($"Public Cert List Response {JsonConvert.SerializeObject(viewCertificateCollection)}"); - var intCount = 0; - char[] s = { ',' }; + var intCount = 0; + char[] s = { ',' }; - var intMax = Convert.ToInt32(_appConfig.AppSettings.Settings["MaxInventoryCapacity"].Value); - var blackList = _appConfig.AppSettings.Settings["InventoryBlackList"].Value.Split(s); - Logger.Trace("Got App Config Settings from File"); + var intMax = Convert.ToInt32(_appConfig.AppSettings.Settings["MaxInventoryCapacity"].Value); + var blackList = _appConfig.AppSettings.Settings["InventoryBlackList"].Value.Split(s); - var inventoryItems = new List(); - if (viewCertificateCollection.PubFileStoreLocation.PubFileStore?.PubFiles != null) - foreach (var pc in viewCertificateCollection.PubFileStoreLocation.PubFileStore.PubFiles) - { - Logger.Trace($"Looping through public files: {pc.Name}"); - var viewCertDetail = new ViewPubCertificateDetailRequest(pc.Name); + Logger.Trace($"Max Inventory: {intMax} Inventory Black List: {blackList}"); - try - { - var viewCertResponse = apiClient.ViewPublicCertificate(viewCertDetail); + Logger.Trace("Got App Config Settings from File"); - Logger.Trace($"Add to List: {pc.Name}"); + var inventoryItems = new List(); + if (viewCertificateCollection.PubFileStoreLocation.PubFileStore?.PubFiles != null) + foreach (var pc in viewCertificateCollection.PubFileStoreLocation.PubFileStore.PubFiles) + { + Logger.Trace($"Looping through public files: {pc.Name}"); + var viewCertDetail = new ViewPubCertificateDetailRequest(pc.Name); + Logger.Trace($"Cert Detail Request: {JsonConvert.SerializeObject(viewCertDetail)}"); + try + { + var viewCertResponse = apiClient.ViewPublicCertificate(viewCertDetail); + Logger.Trace($"Cert Detail Response: {JsonConvert.SerializeObject(viewCertResponse)}"); - var cert=new X509Certificate2(Encoding.UTF8.GetBytes(viewCertResponse.File)); + Logger.Trace($"Add to List: {pc.Name}"); - if (intCount < intMax) - { - if (!blackList.Contains(pc.Name) && cert.Thumbprint!=null) - inventoryItems.Add( - new AgentCertStoreInventoryItem - { - Certificates = new[] {viewCertResponse.File}, - Alias = pc.Name, - PrivateKeyEntry = false, - ItemStatus = AgentInventoryItemStatus.Unknown, - UseChainLevel = true - }); + var cert = new X509Certificate2(Encoding.UTF8.GetBytes(viewCertResponse.File)); - intCount++; + Logger.Trace($"Created X509Certificate2: {cert.SerialNumber} : {cert.Subject}"); - Logger.Trace($"Inv-Certs: {pc.Name}"); - Logger.Trace($"Certificates: {viewCertResponse.File}"); + if (intCount < intMax) + { + if (!blackList.Contains(pc.Name) && cert.Thumbprint != null) + inventoryItems.Add( + new AgentCertStoreInventoryItem + { + Certificates = new[] { viewCertResponse.File }, + Alias = pc.Name, + PrivateKeyEntry = false, + ItemStatus = AgentInventoryItemStatus.Unknown, + UseChainLevel = true + }); + + intCount++; + + Logger.Trace($"Inv-Certs: {pc.Name}"); + Logger.Trace($"Certificates: {viewCertResponse.File}"); + } + } + catch (Exception ex) + { + Logger.Error($"Error on {pc.Name}: {ex.Message}"); + error.ErrorMessage = ex.Message; + error.HasError = true; } } - catch (Exception ex) - { - Logger.Error($"Error on {pc.Name}: {ex.Message}"); - error.ErrorMessage = ex.Message; - error.HasError = true; - } - } - result.Errors = error; - result.InventoryList = inventoryItems; - - return result; + result.Errors = error; + result.InventoryList = inventoryItems; + Logger.Trace($"Serialized Result: {JsonConvert.SerializeObject(result)}"); + return result; + } + catch (Exception e) + { + Logger.Error($"Error in CertManager.GetPublicCerts {e.Message}"); + throw; + } } public InventoryResult GetCerts(ApiClient apiClient) { - var result = new InventoryResult(); - var error = new AnyErrors { HasError = false }; - - Logger.Trace("GetCerts"); - var viewCert = new ViewCryptoCertificatesRequest(apiClient.Domain); - var viewCertificateCollection = apiClient.ViewCertificates(viewCert); - - var inventoryItems = new List(); + try + { + var result = new InventoryResult(); + var error = new AnyErrors { HasError = false }; - Logger.Trace("Start loop"); + Logger.Trace("GetCerts"); + var viewCert = new ViewCryptoCertificatesRequest(apiClient.Domain); + Logger.Trace($"Get Certs Request: {JsonConvert.SerializeObject(viewCert)}"); + var viewCertificateCollection = apiClient.ViewCertificates(viewCert); + Logger.Trace($"Get Certs Response: {JsonConvert.SerializeObject(viewCertificateCollection)}"); + var inventoryItems = new List(); - foreach (var cc in viewCertificateCollection.CryptoCertificates) - if (!string.IsNullOrEmpty(cc.Name)) - { - Logger.Trace($"Looping through Certificate Store files: {cc.Name}"); + Logger.Trace("Start loop"); - try + foreach (var cc in viewCertificateCollection.CryptoCertificates) + if (!string.IsNullOrEmpty(cc.Name)) { - var viewCertDetail = new ViewCertificateDetailRequest(apiClient.Domain) + Logger.Trace($"Looping through Certificate Store files: {cc.Name}"); + + try { - CertObjectRequest = new CertificateObjectRequest + var viewCertDetail = new ViewCertificateDetailRequest(apiClient.Domain) { - ObjectName = cc.Name - } - }; + CertObjectRequest = new CertificateObjectRequest + { + ObjectName = cc.Name + } + }; + Logger.Trace($"Get Cert Request: {JsonConvert.SerializeObject(viewCertDetail)}"); + var viewCertResponse = apiClient.ViewCryptoCertificate(viewCertDetail); + Logger.Trace($"Get Cert Response: {JsonConvert.SerializeObject(viewCertResponse)}"); - var viewCertResponse = apiClient.ViewCryptoCertificate(viewCertDetail); + //check this is a valid cert, if not fall to the errors + var cert = new X509Certificate2(Encoding.UTF8.GetBytes(viewCertResponse.CryptoCertObject.CertDetailsObject.EncodedCert.Value)); - //check this is a valid cert, if not fall to the errors - var cert = new X509Certificate2(Encoding.UTF8.GetBytes(viewCertResponse.CryptoCertObject.CertDetailsObject.EncodedCert.Value)); + Logger.Trace($"Created X509Certificate2: {cert.SerialNumber} : {cert.Subject}"); - Logger.Trace($"Add to list: {cc.Name}"); - if (cert.Thumbprint != null) + Logger.Trace($"Add to list: {cc.Name}"); + if (cert.Thumbprint != null) + { + inventoryItems.Add( + new AgentCertStoreInventoryItem + { + Certificates = new[] + {viewCertResponse.CryptoCertObject.CertDetailsObject.EncodedCert.Value}, + Alias = cc.Name, + PrivateKeyEntry = true, + ItemStatus = AgentInventoryItemStatus.Unknown, + UseChainLevel = true + }); + } + } + catch (Exception ex) { - inventoryItems.Add( - new AgentCertStoreInventoryItem - { - Certificates = new[] - {viewCertResponse.CryptoCertObject.CertDetailsObject.EncodedCert.Value}, - Alias = cc.Name, - PrivateKeyEntry = true, - ItemStatus = AgentInventoryItemStatus.Unknown, - UseChainLevel = true - }); + Logger.Error($"Certificate not retrievable: Error on {cc.Name}: {ex.Message}"); + error.ErrorMessage = ex.Message; + error.HasError = true; } } - catch (Exception ex) - { - Logger.Error($"Certificate not retrievable: Error on {cc.Name}: {ex.Message}"); - error.ErrorMessage = ex.Message; - error.HasError = true; - } - } - result.Errors = error; - result.InventoryList = inventoryItems; - - return result; + result.Errors = error; + result.InventoryList = inventoryItems; + Logger.Trace($"Serialized Result: {JsonConvert.SerializeObject(result)}"); + return result; + } + catch (Exception e) + { + Logger.Error($"Error in CertManager.GetCerts {e.Message}"); + throw; + } } } } diff --git a/AnyAgent/Inventory.cs b/AnyAgent/Inventory.cs index ed515e5..a2bd77d 100644 --- a/AnyAgent/Inventory.cs +++ b/AnyAgent/Inventory.cs @@ -20,6 +20,7 @@ using Keyfactor.Platform.Extensions.Agents; using Keyfactor.Platform.Extensions.Agents.Delegates; using Keyfactor.Platform.Extensions.Agents.Interfaces; +using Newtonsoft.Json; namespace DataPower { @@ -53,25 +54,26 @@ public AnyJobCompleteInfo processJob(AnyJobConfigInfo config, SubmitInventoryUpd Logger.Trace("Parse: Certificate Inventory: " + config.Store.StorePath); var ci = Utility.ParseCertificateConfig(config); Logger.Trace($"Certificate Config Domain: {ci.Domain} and Certificate Store: {ci.CertificateStore}"); - + Logger.Trace($"Any Job Config {JsonConvert.SerializeObject(config)}"); + Logger.Trace($"submitEnrollmentRequest {JsonConvert.SerializeObject(submitEnrollmentRequest)}"); Logger.Trace("Entering IBM DataPower: Certificate Inventory"); Logger.Trace($"Entering processJob for Domain: {ci.Domain} and Certificate Store: {ci.CertificateStore}"); var apiClient = new ApiClient(config.Server.Username, config.Server.Password, $"{_protocol}://" + config.Store.ClientMachine.Trim(), ci.Domain); - var publicCertStoreName= _appConfig.AppSettings.Settings["PublicCertStoreName"].Value; + var publicCertStoreName = _appConfig.AppSettings.Settings["PublicCertStoreName"].Value; Logger.Trace($"$Public Store name is {publicCertStoreName}"); var storePath = config.Store.StorePath; var inventoryResult = storePath.Contains(_appConfig.AppSettings.Settings["PublicCertStoreName"].Value) ? _certManager.GetPublicCerts(apiClient) : _certManager.GetCerts(apiClient); - var returnVal=submitInventory.Invoke(inventoryResult.InventoryList); + var returnVal = submitInventory.Invoke(inventoryResult.InventoryList); if (returnVal == false) { Logger.Error("There were issues submitting the inventory."); - return new AnyJobCompleteInfo { Status = (int)JobStatuses.JobError, Message = "Error submitting the inventory to Keyfactor"}; + return new AnyJobCompleteInfo { Status = (int)JobStatuses.JobError, Message = "Error submitting the inventory to Keyfactor" }; } if (inventoryResult.Errors.HasError) @@ -81,7 +83,7 @@ public AnyJobCompleteInfo processJob(AnyJobConfigInfo config, SubmitInventoryUpd } //we want to inventory what we can an log the rest as errors - return new AnyJobCompleteInfo {Status = (int)JobStatuses.JobSuccess, Message = "Inventory Complete"}; + return new AnyJobCompleteInfo { Status = (int)JobStatuses.JobSuccess, Message = "Inventory Complete" }; } } } \ No newline at end of file diff --git a/AnyAgent/InventoryManagement.cs b/AnyAgent/InventoryManagement.cs index b710048..9dac162 100644 --- a/AnyAgent/InventoryManagement.cs +++ b/AnyAgent/InventoryManagement.cs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System; using System.Configuration; using System.Reflection; using CSS.Common.Logging; @@ -19,6 +20,7 @@ using Keyfactor.Platform.Extensions.Agents.Delegates; using Keyfactor.Platform.Extensions.Agents.Enums; using Keyfactor.Platform.Extensions.Agents.Interfaces; +using Newtonsoft.Json; namespace DataPower { @@ -40,41 +42,65 @@ public string GetJobClass() public string GetStoreType() { - return _appConfig.AppSettings.Settings["StoreType"].Value; + try + { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + Logger.Trace($"StoreType {_appConfig.AppSettings.Settings["StoreType"].Value}"); + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); + return _appConfig.AppSettings.Settings["StoreType"].Value; + } + catch (Exception e) + { + Logger.Error($"Error Getting Store Type: {e.Message}"); + throw; + } } public AnyJobCompleteInfo processJob(AnyJobConfigInfo initialConfig, SubmitInventoryUpdate submitInventory, SubmitEnrollmentRequest submitEnrollmentRequest, SubmitDiscoveryResults sdr) { + Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); + Logger.Trace($"Any Job Config {JsonConvert.SerializeObject(initialConfig)}"); + Logger.Trace($"submitEnrollmentRequest {JsonConvert.SerializeObject(submitEnrollmentRequest)}"); + var ci = Utility.ParseCertificateConfig(initialConfig); var np = Utility.ParseStoreProperties(initialConfig); + Logger.Trace($"ci {JsonConvert.SerializeObject(ci)}"); + Logger.Trace($"np {JsonConvert.SerializeObject(np)}"); + AnyErrors result; Logger.Trace("Entering IBM DataPower: Inventory Management for DOMAIN: " + ci.Domain); switch (initialConfig.Job.OperationType) { case AnyJobOperationType.Add: + Logger.Trace("Entering Add Job.."); result = _certManager.Add(initialConfig, ci, np); + Logger.Trace("Finished Add Job.."); + Logger.Trace($"result {JsonConvert.SerializeObject(result)}"); break; case AnyJobOperationType.Remove: + Logger.Trace("Entering Remove Job.."); result = _certManager.Remove(initialConfig, ci, np); + Logger.Trace("Finished Remove Job.."); + Logger.Trace($"result {JsonConvert.SerializeObject(result)}"); break; default: return new AnyJobCompleteInfo { - Status = (int) JobStatuses.JobError, + Status = (int)JobStatuses.JobError, Message = "Unsupported operation " + initialConfig.Job.OperationType }; } - + Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return result.HasError ? new AnyJobCompleteInfo { - Status = (int) JobStatuses.JobWarning, + Status = (int)JobStatuses.JobWarning, Message = "Management has Issues creating certificate objects" } - : new AnyJobCompleteInfo {Status = (int) JobStatuses.JobSuccess, Message = "Job complete"}; + : new AnyJobCompleteInfo { Status = (int)JobStatuses.JobSuccess, Message = "Job complete" }; } } } \ No newline at end of file From 1d18cc1486a7795390bad848937cd796603ac278 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Tue, 22 Feb 2022 21:00:54 -0500 Subject: [PATCH 2/2] Added Flatten Exception --- AnyAgent/CertManager.cs | 58 +++++++++++++++---------------- AnyAgent/InventoryManagement.cs | 2 +- DataPower.API/client/ApiClient.cs | 4 +-- 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/AnyAgent/CertManager.cs b/AnyAgent/CertManager.cs index 387d93f..080d213 100644 --- a/AnyAgent/CertManager.cs +++ b/AnyAgent/CertManager.cs @@ -63,7 +63,7 @@ public bool DoesCryptoCertificateObjectExist(CertStoreInfo ci, string cryptoCert } catch (Exception ex) { - Logger.Error($"There was an issue receiving the certificates: {cryptoCertObjectName} Error {ex.Message}"); + Logger.Error($"There was an issue receiving the certificates: {cryptoCertObjectName} Error {LogHandler.FlattenException(ex)}"); } Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); @@ -95,7 +95,7 @@ public void DisableCryptoCertificateObject(string cryptoCertObjectName, ApiClien } catch (Exception ex) { - Logger.Error($"There was an issue disabling the certificate object: {cryptoCertObjectName} Error {ex.Message}"); + Logger.Error($"There was an issue disabling the certificate object: {cryptoCertObjectName} Error {LogHandler.FlattenException(ex)}"); } } @@ -118,7 +118,7 @@ public bool DoesCryptoKeyObjectExist(CertStoreInfo ci, string cryptoKeyObjectNam } catch (Exception ex) { - Logger.Error($"Crypto Key Object does not exist: {cryptoKeyObjectName} : {ex.Message}"); + Logger.Error($"Crypto Key Object does not exist: {cryptoKeyObjectName} : {LogHandler.FlattenException(ex)}"); } Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return bUpdateCryptoKeyObject; @@ -148,7 +148,7 @@ public void DisableCryptoKeyObject(string cryptoKeyObjectName, ApiClient apiClie } catch (Exception ex) { - Logger.Error($"There was an issue disabling the certificate *key*: {cryptoKeyObjectName} Error {ex.Message}"); + Logger.Error($"There was an issue disabling the certificate *key*: {cryptoKeyObjectName} Error {LogHandler.FlattenException(ex)}"); } } @@ -174,7 +174,7 @@ public void UpdatePrivateKey(CertStoreInfo ci, string cryptoKeyObjectName, } catch (Exception ex) { - Logger.Error($"There was an issue updating the private key: {cryptoKeyObjectName} Error {ex.Message}"); + Logger.Error($"There was an issue updating the private key: {cryptoKeyObjectName} Error {LogHandler.FlattenException(ex)}"); } } @@ -201,7 +201,7 @@ public void AddCryptoKey(CertStoreInfo ci, string cryptoKeyObjectName, ApiClient } catch (Exception ex) { - Logger.Error($"Error Adding CryptoKey Object for Private Key {alias}: {cryptoKeyObjectName} Error {ex.Message}"); + Logger.Error($"Error Adding CryptoKey Object for Private Key {alias}: {cryptoKeyObjectName} Error {LogHandler.FlattenException(ex)}"); } } @@ -219,7 +219,7 @@ public AnyErrors RemovePrivateKeyFile(AnyJobConfigInfo addConfig, CertStoreInfo } catch (Exception e) { - Logger.Error($"Error In CertManager.RemovePrivateKeyFile: {e.Message}"); + Logger.Error($"Error In CertManager.RemovePrivateKeyFile: {LogHandler.FlattenException(e)}"); throw; } } @@ -246,7 +246,7 @@ public CertificateAddRequest AddPrivateKey(CertStoreInfo ci, string alias, strin } catch (Exception ex) { - Logger.Error($"Error Adding Private Key {alias} to CERT store with Filename {keyFileName} Error {ex.Message}"); + Logger.Error($"Error Adding Private Key {alias} to CERT store with Filename {keyFileName} Error {LogHandler.FlattenException(ex)}"); } return null; @@ -275,7 +275,7 @@ public void UpdateCryptoCert(CertStoreInfo ci, string cryptoCertObjectName, } catch (Exception ex) { - Logger.Error($"Error Updating Crypto Certificate Object: {cryptoCertObjectName} Error {ex.Message}"); + Logger.Error($"Error Updating Crypto Certificate Object: {cryptoCertObjectName} Error {LogHandler.FlattenException(ex)}"); } } @@ -302,7 +302,7 @@ public void AddCryptoCert(CertStoreInfo ci, string cryptoCertObjectName, ApiClie } catch (Exception ex) { - Logger.Error($"Error Adding Crypto Object for Certificate {alias} to CERT store with Filename {certFileName} Error {ex.Message}"); + Logger.Error($"Error Adding Crypto Object for Certificate {alias} to CERT store with Filename {certFileName} Error {LogHandler.FlattenException(ex)}"); } } @@ -319,7 +319,7 @@ public AnyErrors RemoveCertificate(AnyJobConfigInfo addConfig, CertStoreInfo ci, } catch (Exception e) { - Logger.Error($"Error In CertManager.RemovePrivateKeyFile: {e.Message}"); + Logger.Error($"Error In CertManager.RemovePrivateKeyFile: {LogHandler.FlattenException(e)}"); throw; } } @@ -345,7 +345,7 @@ public CertificateAddRequest CertificateAddRequest(CertStoreInfo ci, string alia } catch (Exception ex) { - Logger.Error($"Error Adding Certificate {alias} with Filename {certFileName} Error {ex.Message}"); + Logger.Error($"Error Adding Certificate {alias} with Filename {certFileName} Error {LogHandler.FlattenException(ex)}"); } return null; @@ -369,7 +369,7 @@ public bool DoesKeyFileExist(CertStoreInfo ci, string keyFileName, ViewPublicCer } catch (Exception ex) { - Logger.Error($"Error Matching Key File {keyFileName} was found in domain {ci.Domain} Error {ex.Message}"); + Logger.Error($"Error Matching Key File {keyFileName} was found in domain {ci.Domain} Error {LogHandler.FlattenException(ex)}"); } Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return bRemoveKeyFile; @@ -393,7 +393,7 @@ public bool DoesCertificateFileExist(CertStoreInfo ci, ApiClient apiClient, } catch (Exception ex) { - Logger.Error($"Error Matching Certificate File {certFileName} was found in domain {ci.Domain} Error {ex.Message}"); + Logger.Error($"Error Matching Certificate File {certFileName} was found in domain {ci.Domain} Error {LogHandler.FlattenException(ex)}"); } Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); return bRemoveCertificateFile; @@ -460,7 +460,7 @@ public string GetCertPem(AnyJobConfigInfo addConfig, string alias, ref string pr } catch (Exception ex) { - Logger.Error($"Error Generating PEM: Error {ex.Message}"); + Logger.Error($"Error Generating PEM: Error {LogHandler.FlattenException(ex)}"); } Logger.Trace($"PEM {certPem}"); Logger.MethodEntry(ILogExtensions.MethodLogLevel.Debug); @@ -536,7 +536,7 @@ public AnyErrors AddPubCert(AnyJobConfigInfo addPubConfig, CertStoreInfo ci, Nam catch (Exception ex) { error.HasError = true; - Logger.Trace($"Error on {certAlias}: {ex.Message}"); + Logger.Trace($"Error on {certAlias}: {LogHandler.FlattenException(ex)}"); apiClient.SaveConfig(); } Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); @@ -606,7 +606,7 @@ private AnyErrors RemoveCertFromDomain(AnyJobConfigInfo removeConfig, CertStoreI { error.HasError = true; error.ErrorMessage = ex.Message; - Logger.Trace($"Error on {removeConfig.Job.Alias}: {ex.Message}"); + Logger.Trace($"Error on {removeConfig.Job.Alias}: {LogHandler.FlattenException(ex)}"); } Logger.Trace("Saving Config!"); apiClient.SaveConfig(); @@ -638,7 +638,7 @@ private AnyErrors RemoveFile(AnyJobConfigInfo removeConfig, CertStoreInfo ci, st { error.HasError = true; error.ErrorMessage = ex.Message; - Logger.Trace($"Error on {removeConfig.Job.Alias}: {ex.Message}"); + Logger.Trace($"Error on {removeConfig.Job.Alias}: {LogHandler.FlattenException(ex)}"); } Logger.Trace("Saving Config!"); apiClient.SaveConfig(); @@ -674,7 +674,7 @@ public AnyErrors Remove(AnyJobConfigInfo removeConfig, CertStoreInfo ci, NamePre } catch (Exception e) { - Logger.Error($"Error In CertManager.Remove {e.Message}!"); + Logger.Error($"Error In CertManager.Remove {LogHandler.FlattenException(e)}!"); throw; } } @@ -699,7 +699,7 @@ public AnyErrors Add(AnyJobConfigInfo addConfig, CertStoreInfo ci, NamePrefix np } catch (Exception e) { - Logger.Error($"Error In CertManager.Add {e.Message}!"); + Logger.Error($"Error In CertManager.Add {LogHandler.FlattenException(e)}!"); throw; } } @@ -785,7 +785,7 @@ private AnyErrors AddCertStore(AnyJobConfigInfo addConfig, CertStoreInfo ci, Nam catch (Exception ex) { error.HasError = true; - Logger.Trace($"Error on {alias}: {ex.Message}"); + Logger.Trace($"Error on {alias}: {LogHandler.FlattenException(ex)}"); apiClient.SaveConfig(); } Logger.MethodExit(ILogExtensions.MethodLogLevel.Debug); @@ -819,7 +819,7 @@ private void ReplacePrivateKey(AnyJobConfigInfo addConfig, CertStoreInfo ci, str } catch (Exception e) { - Logger.Error($"Error in CertManager.ReplacePrivateKey {e.Message}"); + Logger.Error($"Error in CertManager.ReplacePrivateKey {LogHandler.FlattenException(e)}"); throw; } } @@ -847,7 +847,7 @@ private void ReplaceCertificateFile(AnyJobConfigInfo addConfig, CertStoreInfo ci } catch (Exception e) { - Logger.Error($"Error in CertManager.ReplaceCertificateFile {e.Message}"); + Logger.Error($"Error in CertManager.ReplaceCertificateFile {LogHandler.FlattenException(e)}"); throw; } } @@ -887,7 +887,7 @@ private void ReplaceCryptoKeyObject(CertStoreInfo ci, string cryptoKeyObjectName } catch (Exception e) { - Logger.Error($"Error in CertManager.ReplaceCryptoKeyObject {e.Message}"); + Logger.Error($"Error in CertManager.ReplaceCryptoKeyObject {LogHandler.FlattenException(e)}"); throw; } } @@ -929,7 +929,7 @@ private void ReplaceCryptoObject(CertStoreInfo ci, string cryptoCertObjectName, } catch (Exception e) { - Logger.Error($"Error in CertManager.ReplaceCryptoObject {e.Message}"); + Logger.Error($"Error in CertManager.ReplaceCryptoObject {LogHandler.FlattenException(e)}"); throw; } } @@ -997,7 +997,7 @@ public InventoryResult GetPublicCerts(ApiClient apiClient) } catch (Exception ex) { - Logger.Error($"Error on {pc.Name}: {ex.Message}"); + Logger.Error($"Error on {pc.Name}: {LogHandler.FlattenException(ex)}"); error.ErrorMessage = ex.Message; error.HasError = true; } @@ -1010,7 +1010,7 @@ public InventoryResult GetPublicCerts(ApiClient apiClient) } catch (Exception e) { - Logger.Error($"Error in CertManager.GetPublicCerts {e.Message}"); + Logger.Error($"Error in CertManager.GetPublicCerts {LogHandler.FlattenException(e)}"); throw; } } @@ -1071,7 +1071,7 @@ public InventoryResult GetCerts(ApiClient apiClient) } catch (Exception ex) { - Logger.Error($"Certificate not retrievable: Error on {cc.Name}: {ex.Message}"); + Logger.Error($"Certificate not retrievable: Error on {cc.Name}: {LogHandler.FlattenException(ex)}"); error.ErrorMessage = ex.Message; error.HasError = true; } @@ -1085,7 +1085,7 @@ public InventoryResult GetCerts(ApiClient apiClient) } catch (Exception e) { - Logger.Error($"Error in CertManager.GetCerts {e.Message}"); + Logger.Error($"Error in CertManager.GetCerts {LogHandler.FlattenException(e)}"); throw; } } diff --git a/AnyAgent/InventoryManagement.cs b/AnyAgent/InventoryManagement.cs index 9dac162..fea7923 100644 --- a/AnyAgent/InventoryManagement.cs +++ b/AnyAgent/InventoryManagement.cs @@ -51,7 +51,7 @@ public string GetStoreType() } catch (Exception e) { - Logger.Error($"Error Getting Store Type: {e.Message}"); + Logger.Error($"Error Getting Store Type: {LogHandler.FlattenException(e)}"); throw; } } diff --git a/DataPower.API/client/ApiClient.cs b/DataPower.API/client/ApiClient.cs index 1a0e539..77d1497 100644 --- a/DataPower.API/client/ApiClient.cs +++ b/DataPower.API/client/ApiClient.cs @@ -62,7 +62,7 @@ public bool SaveConfig() } catch (Exception ex) { - Logger.Error($"Error Saving the Config: {ex.Message}"); + Logger.Error($"Error Saving the Config: {LogHandler.FlattenException(ex)}"); return false; } } @@ -296,7 +296,7 @@ public string ApiRequestString(string strCall, string strPostUrl, string strMeth } catch (Exception ex) { - Logger.Trace($"END APIRequestString error: {ex.Message}"); + Logger.Trace($"END APIRequestString error: {LogHandler.FlattenException(ex)}"); throw; } }