diff --git a/.github/workflows/keyfactor-starter-workflow.yml b/.github/workflows/keyfactor-starter-workflow.yml index 6d8de53..a4649f2 100644 --- a/.github/workflows/keyfactor-starter-workflow.yml +++ b/.github/workflows/keyfactor-starter-workflow.yml @@ -11,9 +11,10 @@ on: jobs: call-starter-workflow: - uses: keyfactor/actions/.github/workflows/starter.yml@v2 + uses: keyfactor/actions/.github/workflows/starter.yml@3.1.2 secrets: token: ${{ secrets.V2BUILDTOKEN}} APPROVE_README_PUSH: ${{ secrets.APPROVE_README_PUSH}} gpg_key: ${{ secrets.KF_GPG_PRIVATE_KEY }} gpg_pass: ${{ secrets.KF_GPG_PASSPHRASE }} + scan_token: ${{ secrets.SAST_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index e336168..4a63b26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +2.5.0 +* Added the Bindings to the end of the thumbprint to make the alias unique. +* Using new IISWebBindings commandlet to use additional SSL flags when binding certificate to website. +* Added multi-platform support for .Net6 and .Net8. +* Updated various PowerShell scripts to handle both .Net6 and .Net8 differences (specifically the absense of the WebAdministration module in PS SDK 7.4.x+) +* Fixed issue to update multiple websites when using the same cert. +* Removed renewal thumbprint logic to update multiple website; each job now updates its own specific certificate. + 2.4.4 * Fix an issue with WinRM parameters when migrating Legacy IIS Stores to the WinCert type * Fix an issue with "Delete" script in the Legacy IIS Migration that did not remove some records from dependent tables diff --git a/IISU/CertificateStore.cs b/IISU/CertificateStore.cs index 0ea35e6..75c1d0a 100644 --- a/IISU/CertificateStore.cs +++ b/IISU/CertificateStore.cs @@ -181,30 +181,13 @@ public static List GetIISBoundCertificates(Runspace runSpa if (foundCert == null) continue; - var sniValue = ""; - switch (Convert.ToInt16(binding.Properties["sniFlg"]?.Value)) - { - case 0: - sniValue = "0 - No SNI"; - break; - case 1: - sniValue = "1 - SNI Enabled"; - break; - case 2: - sniValue = "2 - Non SNI Binding"; - break; - case 3: - sniValue = "3 - SNI Binding"; - break; - } - var siteSettingsDict = new Dictionary { { "SiteName", binding.Properties["Name"]?.Value }, { "Port", binding.Properties["Bindings"]?.Value.ToString()?.Split(':')[1] }, { "IPAddress", binding.Properties["Bindings"]?.Value.ToString()?.Split(':')[0] }, { "HostName", binding.Properties["Bindings"]?.Value.ToString()?.Split(':')[2] }, - { "SniFlag", sniValue }, + { "SniFlag", binding.Properties["sniFlg"]?.Value }, { "Protocol", binding.Properties["Protocol"]?.Value } }; @@ -212,7 +195,7 @@ public static List GetIISBoundCertificates(Runspace runSpa new CurrentInventoryItem { Certificates = new[] { foundCert.CertificateData }, - Alias = thumbPrint, + Alias = thumbPrint + ":" + binding.Properties["Bindings"]?.Value.ToString(), PrivateKeyEntry = foundCert.HasPrivateKey, UseChainLevel = false, ItemStatus = OrchestratorInventoryItemStatus.Unknown, diff --git a/IISU/CertificateStoreException.cs b/IISU/CertificateStoreException.cs index b510548..f207566 100644 --- a/IISU/CertificateStoreException.cs +++ b/IISU/CertificateStoreException.cs @@ -18,7 +18,7 @@ namespace Keyfactor.Extensions.Orchestrator.WindowsCertStore { [Serializable] - internal class CertificateStoreException : Exception + public class CertificateStoreException : Exception { public CertificateStoreException() { diff --git a/IISU/ClientPSCertStoreInventory.cs b/IISU/ClientPSCertStoreInventory.cs index 0bde6f5..b3b85e1 100644 --- a/IISU/ClientPSCertStoreInventory.cs +++ b/IISU/ClientPSCertStoreInventory.cs @@ -11,6 +11,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +using Keyfactor.Extensions.Orchestrator.WindowsCertStore.IISU; using Keyfactor.Logging; using Microsoft.Extensions.Logging; using System; @@ -21,9 +22,15 @@ namespace Keyfactor.Extensions.Orchestrator.WindowsCertStore { - abstract class ClientPSCertStoreInventory + public abstract class ClientPSCertStoreInventory { private ILogger _logger; + + protected ClientPSCertStoreInventory() + { + _logger = LogHandler.GetClassLogger(); + } + public ClientPSCertStoreInventory(ILogger logger) { _logger = logger; diff --git a/IISU/ClientPSCertStoreManager.cs b/IISU/ClientPSCertStoreManager.cs index 3a75960..e768f08 100644 --- a/IISU/ClientPSCertStoreManager.cs +++ b/IISU/ClientPSCertStoreManager.cs @@ -27,7 +27,7 @@ namespace Keyfactor.Extensions.Orchestrator.WindowsCertStore { - internal class ClientPSCertStoreManager + public class ClientPSCertStoreManager { private ILogger _logger; private Runspace _runspace; @@ -40,6 +40,11 @@ public X509Certificate2 X509Cert get { return x509Cert; } } + public ClientPSCertStoreManager(Runspace runSpace) + { + _logger = LogHandler.GetClassLogger(); + _runspace = runSpace; + } public ClientPSCertStoreManager(ILogger logger, Runspace runSpace, long jobNumber) { @@ -126,9 +131,9 @@ public JobResult ImportPFXFile(string filePath, string privateKeyPassword, strin { ps.Runspace = _runspace; - if (cryptoProviderName == null) + if (string.IsNullOrEmpty(cryptoProviderName)) { - if (privateKeyPassword == null) + if (string.IsNullOrEmpty(privateKeyPassword)) { // If no private key password is provided, import the pfx file directory to the store using addstore argument string script = @" @@ -179,7 +184,7 @@ public JobResult ImportPFXFile(string filePath, string privateKeyPassword, strin } else { - if (privateKeyPassword == null) + if (string.IsNullOrEmpty(privateKeyPassword)) { string script = @" param($pfxFilePath, $cspName, $storePath) diff --git a/IISU/ClientPSIIManager.cs b/IISU/ClientPSIIManager.cs index dd57b4a..996b46d 100644 --- a/IISU/ClientPSIIManager.cs +++ b/IISU/ClientPSIIManager.cs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using Keyfactor.Extensions.Orchestrator.WindowsCertStore.Scripts; using Keyfactor.Logging; using Keyfactor.Orchestrators.Common.Enums; using Keyfactor.Orchestrators.Extensions; @@ -20,17 +21,14 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; -using System.Net; using System.Security.Cryptography.X509Certificates; -using System.Text; namespace Keyfactor.Extensions.Orchestrator.WindowsCertStore { - internal class ClientPSIIManager + public class ClientPSIIManager { private string SiteName { get; set; } private string Port { get; set; } @@ -55,22 +53,30 @@ internal class ClientPSIIManager private PowerShell ps; - //public ClientPSIIManager(ILogger logger, Runspace runSpace) - //{ - // _logger = logger; - // _runSpace = runSpace; - - // ps = PowerShell.Create(); - // ps.Runspace = _runSpace; - //} - - //public ClientPSIIManager(ILogger logger, Runspace runSpace, PowerShell powerShell) - //{ - // _logger = logger; - // _runSpace = runSpace; - - // ps = powerShell; - //} + /// + /// This constructor is used for unit testing + /// + /// + /// + /// + /// + /// + /// + /// + public ClientPSIIManager(Runspace runSpace, string SiteName, string Protocol, string IPAddress, string Port, string HostName, string Thumbprint, string StorePath, string sniFlag) + { + _logger = LogHandler.GetClassLogger(); + _runSpace = runSpace; + + this.SiteName = SiteName; + this.Protocol = Protocol; + this.IPAddress = IPAddress; + this.Port = Port; + this.HostName = HostName; + this.RenewalThumbprint = Thumbprint; + this.StorePath = StorePath; + this.SniFlag = sniFlag; + } public ClientPSIIManager(ReenrollmentJobConfiguration config, string serverUsername, string serverPassword) { @@ -82,7 +88,7 @@ public ClientPSIIManager(ReenrollmentJobConfiguration config, string serverUsern Port = config.JobProperties["Port"].ToString(); HostName = config.JobProperties["HostName"]?.ToString(); Protocol = config.JobProperties["Protocol"].ToString(); - SniFlag = config.JobProperties["SniFlag"]?.ToString()[..1]; + SniFlag = MigrateSNIFlag(config.JobProperties["SniFlag"]?.ToString()); IPAddress = config.JobProperties["IPAddress"].ToString(); PrivateKeyPassword = ""; // A reenrollment does not have a PFX Password @@ -115,17 +121,19 @@ public ClientPSIIManager(ManagementJobConfiguration config, string serverUsernam try { + _logger.LogTrace("Setting Job Properties"); SiteName = config.JobProperties["SiteName"].ToString(); Port = config.JobProperties["Port"].ToString(); HostName = config.JobProperties["HostName"]?.ToString(); Protocol = config.JobProperties["Protocol"].ToString(); - SniFlag = config.JobProperties["SniFlag"].ToString()?[..1]; + SniFlag = MigrateSNIFlag(config.JobProperties["SniFlag"]?.ToString()); IPAddress = config.JobProperties["IPAddress"].ToString(); PrivateKeyPassword = ""; // A reenrollment does not have a PFX Password - RenewalThumbprint = ""; // A reenrollment will always be empty + RenewalThumbprint = ""; // This property will not be used for renewals starting in version 2.5 CertContents = ""; // Not needed for a reenrollment + _logger.LogTrace("Certificate details"); ClientMachineName = config.CertificateStoreDetails.ClientMachine; StorePath = config.CertificateStoreDetails.StorePath; @@ -136,9 +144,15 @@ public ClientPSIIManager(ManagementJobConfiguration config, string serverUsernam RenewalThumbprint = config.JobProperties["RenewalThumbprint"].ToString(); _logger.LogTrace($"Found Thumbprint Will Renew all Certs with this thumbprint: {RenewalThumbprint}"); } + else + { + _logger.LogTrace("No renewal Thumbprint was provided."); + } // Establish PowerShell Runspace var jobProperties = JsonConvert.DeserializeObject(config.CertificateStoreDetails.Properties, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Populate }); + _logger.LogTrace($"Job properties value: {jobProperties}"); + string winRmProtocol = jobProperties.WinRmProtocol; string winRmPort = jobProperties.WinRmPort; bool includePortInSPN = jobProperties.SpnPortFlag; @@ -148,7 +162,7 @@ public ClientPSIIManager(ManagementJobConfiguration config, string serverUsernam } catch (Exception e) { - throw new Exception($"Error when initiating an IIS ReEnrollment Job: {e.Message}", e.InnerException); + throw new Exception($"Error when initiating an IIS Management Job: {e.Message}", e.InnerException); } } @@ -162,135 +176,67 @@ public JobResult BindCertificate(X509Certificate2 x509Cert) ps = PowerShell.Create(); ps.Runspace = _runSpace; - //if thumbprint is there it is a renewal so we have to search all the sites for that thumbprint and renew them all - if (RenewalThumbprint?.Length > 0) + bool hadError = false; + string errorMessage = string.Empty; + + try { - _logger.LogTrace($"Thumbprint Length > 0 {RenewalThumbprint}"); - ps.AddCommand("Import-Module") - .AddParameter("Name", "WebAdministration") - .AddStatement(); + Collection results = (Collection)PerformIISBinding(SiteName, Protocol, IPAddress, Port, HostName, SniFlag, x509Cert.Thumbprint, StorePath); - _logger.LogTrace("WebAdministration Imported"); - var searchScript = - "Foreach($Site in get-website) { Foreach ($Bind in $Site.bindings.collection) {[pscustomobject]@{name=$Site.name;Protocol=$Bind.Protocol;Bindings=$Bind.BindingInformation;thumbprint=$Bind.certificateHash;sniFlg=$Bind.sslFlags}}}"; - ps.AddScript(searchScript).AddStatement(); - _logger.LogTrace($"Search Script: {searchScript}"); - var bindings = ps.Invoke(); - foreach (var binding in bindings) + if (ps.HadErrors) { - if (binding.Properties["Protocol"].Value.ToString().Contains("https")) - { - _logger.LogTrace("Looping Bindings...."); - var bindingSiteName = binding.Properties["name"].Value.ToString(); - var bindingBindings = binding.Properties["Bindings"].Value.ToString()?.Split(':'); - var bindingIpAddress = bindingBindings?.Length > 0 ? bindingBindings[0] : null; - var bindingPort = bindingBindings?.Length > 1 ? bindingBindings[1] : null; - var bindingHostName = bindingBindings?.Length > 2 ? bindingBindings[2] : null; - var bindingProtocol = binding.Properties["Protocol"]?.Value?.ToString(); - var bindingThumbprint = binding.Properties["thumbprint"]?.Value?.ToString(); - var bindingSniFlg = binding.Properties["sniFlg"]?.Value?.ToString(); - - _logger.LogTrace( - $"bindingSiteName: {bindingSiteName}, bindingIpAddress: {bindingIpAddress}, bindingPort: {bindingPort}, bindingHostName: {bindingHostName}, bindingProtocol: {bindingProtocol}, bindingThumbprint: {bindingThumbprint}, bindingSniFlg: {bindingSniFlg}"); - - //if the thumbprint of the renewal request matches the thumbprint of the cert in IIS, then renew it - if (RenewalThumbprint == bindingThumbprint) - { - _logger.LogTrace($"Thumbprint Match {RenewalThumbprint}={bindingThumbprint}"); - var funcScript = string.Format(@" - $ErrorActionPreference = ""Stop"" - - $IISInstalled = Get-Module -ListAvailable | where {{$_.Name -eq ""WebAdministration""}} - if($IISInstalled) {{ - Import-Module WebAdministration - Get-WebBinding -Name ""{0}"" -IPAddress ""{1}"" -HostHeader ""{4}"" -Port ""{2}"" -Protocol ""{3}"" | - ForEach-Object {{ Remove-WebBinding -BindingInformation $_.bindingInformation }} - - New-WebBinding -Name ""{0}"" -IPAddress ""{1}"" -HostHeader ""{4}"" -Port ""{2}"" -Protocol ""{3}"" -SslFlags ""{7}"" - Get-WebBinding -Name ""{0}"" -IPAddress ""{1}"" -HostHeader ""{4}"" -Port ""{2}"" -Protocol ""{3}"" | - ForEach-Object {{ $_.AddSslCertificate(""{5}"", ""{6}"") }} - }}", bindingSiteName, //{0} - bindingIpAddress, //{1} - bindingPort, //{2} - bindingProtocol, //{3} - bindingHostName, //{4} - x509Cert.Thumbprint, //{5} - StorePath, //{6} - bindingSniFlg); //{7} - - _logger.LogTrace($"funcScript {funcScript}"); - ps.AddScript(funcScript); - _logger.LogTrace("funcScript added..."); - ps.Invoke(); - _logger.LogTrace("funcScript Invoked..."); - foreach (var cmd in ps.Commands.Commands) - { - _logger.LogTrace("Logging PowerShell Command"); - _logger.LogTrace(cmd.CommandText); - } - - ps.Commands.Clear(); - _logger.LogTrace("Commands Cleared.."); - } - } + var psError = ps.Streams.Error.ReadAll() + .Aggregate(string.Empty, (current, error) => + current + (error.ErrorDetails != null && !string.IsNullOrEmpty(error.ErrorDetails.Message) + ? error.ErrorDetails.Message + : error.Exception != null + ? error.Exception.Message + : error.ToString()) + Environment.NewLine); + + errorMessage = psError; + hadError = true; + } } - else + catch (Exception e) { - var funcScript = string.Format(@" - $ErrorActionPreference = ""Stop"" - - $IISInstalled = Get-Module -ListAvailable | where {{$_.Name -eq ""WebAdministration""}} - if($IISInstalled) {{ - Import-Module WebAdministration - Get-WebBinding -Name ""{0}"" -IPAddress ""{1}"" -Port ""{2}"" -Protocol ""{3}"" -HostHeader ""{4}"" | - ForEach-Object {{ Remove-WebBinding -BindingInformation $_.bindingInformation }} - - New-WebBinding -Name ""{0}"" -IPAddress ""{1}"" -HostHeader ""{4}"" -Port ""{2}"" -Protocol ""{3}"" -SslFlags ""{7}"" - Get-WebBinding -Name ""{0}"" -IPAddress ""{1}"" -HostHeader ""{4}"" -Port ""{2}"" -Protocol ""{3}"" | - ForEach-Object {{ $_.AddSslCertificate(""{5}"", ""{6}"") }} - }}", SiteName, //{0} - IPAddress, //{1} - Port, //{2} - Protocol, //{3} - HostName, //{4} - x509Cert.Thumbprint, //{5} - StorePath, //{6} - Convert.ToInt16(SniFlag)); //{7} - foreach (var cmd in ps.Commands.Commands) + string computerName = string.Empty; + if (_runSpace.ConnectionInfo is null) { - _logger.LogTrace("Logging PowerShell Command"); - _logger.LogTrace(cmd.CommandText); + computerName = "localMachine"; } + else { computerName = "Server: " + _runSpace.ConnectionInfo.ComputerName; } - _logger.LogTrace($"funcScript {funcScript}"); - ps.AddScript(funcScript); - _logger.LogTrace("funcScript added..."); - ps.Invoke(); - _logger.LogTrace("funcScript Invoked..."); + errorMessage = $"Binding attempt failed on Site {SiteName} on {computerName}, Application error: {e.Message}"; + hadError = true; + _logger.LogTrace(errorMessage); } - if (ps.HadErrors) + if (hadError) { - var psError = ps.Streams.Error.ReadAll() - .Aggregate(string.Empty, (current, error) => current + error.ErrorDetails.Message); + string computerName = string.Empty; + if (_runSpace.ConnectionInfo is null) { - return new JobResult - { - Result = OrchestratorJobStatusJobResult.Failure, - JobHistoryId = JobHistoryID, - FailureMessage = - $"Site {StorePath} on server {_runSpace.ConnectionInfo.ComputerName}: {psError}" - }; + computerName = "localMachine"; } - } + else { computerName = "Server: " + _runSpace.ConnectionInfo.ComputerName; } - return new JobResult + return new JobResult + { + Result = OrchestratorJobStatusJobResult.Failure, + JobHistoryId = JobHistoryID, + FailureMessage = $"Binding attempt failed on Site {SiteName} on {computerName}: {errorMessage}" + }; + } + else { - Result = OrchestratorJobStatusJobResult.Success, - JobHistoryId = JobHistoryID, - FailureMessage = "" - }; + return new JobResult + { + Result = OrchestratorJobStatusJobResult.Success, + JobHistoryId = JobHistoryID, + FailureMessage = "" + }; + } } catch (Exception e) { @@ -298,7 +244,7 @@ public JobResult BindCertificate(X509Certificate2 x509Cert) { Result = OrchestratorJobStatusJobResult.Failure, JobHistoryId = JobHistoryID, - FailureMessage = $"Error Occurred in InstallCertificate {LogHandler.FlattenException(e)}" + FailureMessage = $"Application Error Occurred in BindCertificate: {LogHandler.FlattenException(e)}" }; } finally @@ -311,6 +257,81 @@ public JobResult BindCertificate(X509Certificate2 x509Cert) public JobResult UnBindCertificate() { +#if NET8_0_OR_GREATER + bool hadError = false; + string errorMessage = string.Empty; + + try + { + _logger.MethodEntry(); + + _runSpace.Open(); + ps = PowerShell.Create(); + ps.Runspace = _runSpace; + + Collection results = (Collection)PerformIISUnBinding(SiteName, Protocol, IPAddress, Port, HostName); + + if (ps.HadErrors) + { + var psError = ps.Streams.Error.ReadAll() + .Aggregate(string.Empty, (current, error) => + current + (error.ErrorDetails != null && !string.IsNullOrEmpty(error.ErrorDetails.Message) + ? error.ErrorDetails.Message + : error.Exception != null + ? error.Exception.Message + : error.ToString()) + Environment.NewLine); + + errorMessage = psError; + hadError = true; + + } + } + catch (Exception e) + { + string computerName = string.Empty; + if (_runSpace.ConnectionInfo is null) + { + computerName = "localMachine"; + } + else { computerName = "Server: " + _runSpace.ConnectionInfo.ComputerName; } + + errorMessage = $"Binding attempt failed on Site {SiteName} on {computerName}, Application error: {e.Message}"; + hadError = true; + _logger.LogTrace(errorMessage); + } + finally + { + _runSpace.Close(); + ps.Runspace.Close(); + ps.Dispose(); + } + + if (hadError) + { + string computerName = string.Empty; + if (_runSpace.ConnectionInfo is null) + { + computerName = "localMachine"; + } + else { computerName = "Server: " + _runSpace.ConnectionInfo.ComputerName; } + + return new JobResult + { + Result = OrchestratorJobStatusJobResult.Failure, + JobHistoryId = JobHistoryID, + FailureMessage = $"Binding attempt failed on Site {SiteName} on {computerName}: {errorMessage}" + }; + } + else + { + return new JobResult + { + Result = OrchestratorJobStatusJobResult.Success, + JobHistoryId = JobHistoryID, + FailureMessage = "" + }; + } +#endif try { _logger.MethodEntry(); @@ -340,12 +361,20 @@ public JobResult UnBindCertificate() if (foundBindings.Count == 0) { _logger.LogTrace($"{foundBindings.Count} Bindings Found..."); + + string computerName = string.Empty; + if (_runSpace.ConnectionInfo is null) + { + computerName = "localMachine"; + } + else { computerName = "Server: " + _runSpace.ConnectionInfo.ComputerName; } + return new JobResult { - Result = OrchestratorJobStatusJobResult.Failure, + Result = OrchestratorJobStatusJobResult.Success, JobHistoryId = JobHistoryID, FailureMessage = - $"Site {Protocol} binding for Site {SiteName} on server {_runSpace.ConnectionInfo.ComputerName} not found." + $"No bindings we found for Site {SiteName} on {computerName}." }; } @@ -356,17 +385,15 @@ public JobResult UnBindCertificate() _logger.LogTrace(cmd.CommandText); } - ps.Commands.Clear(); - _logger.LogTrace("Cleared Commands"); - - ps.AddCommand("Import-Module") - .AddParameter("Name", "WebAdministration") - .AddStatement(); - - _logger.LogTrace("Imported WebAdministration Module"); foreach (var binding in foundBindings) { + ps.AddCommand("Import-Module") + .AddParameter("Name", "WebAdministration") + .AddStatement(); + + _logger.LogTrace("Imported WebAdministration Module"); + ps.AddCommand("Remove-WebBinding") .AddParameter("Name", SiteName) .AddParameter("BindingInformation", @@ -387,14 +414,30 @@ public JobResult UnBindCertificate() { _logger.LogTrace("PowerShell Had Errors"); var psError = ps.Streams.Error.ReadAll().Aggregate(String.Empty, (current, error) => current + error.ErrorDetails.Message); + //var psError = ps.Streams.Error.ReadAll() + // .Aggregate(string.Empty, (current, error) => + // current + (error.ErrorDetails != null && !string.IsNullOrEmpty(error.ErrorDetails.Message) + // ? error.ErrorDetails.Message + // : error.Exception != null + // ? error.Exception.Message + // : error.ToString()) + Environment.NewLine); + + string computerName = string.Empty; + if (_runSpace.ConnectionInfo is null) + { + computerName = "localMachine"; + } + else { computerName = "Server: " + _runSpace.ConnectionInfo.ComputerName; } + return new JobResult { Result = OrchestratorJobStatusJobResult.Failure, JobHistoryId = JobHistoryID, FailureMessage = - $"Failed to remove {Protocol} binding for Site {SiteName} on server {_runSpace.ConnectionInfo.ComputerName} not found, error {psError}" + $"Failed to remove {Protocol} binding for Site {SiteName} on {computerName} not found, error {psError}" }; } + ps.Commands.Clear(); } return new JobResult @@ -407,7 +450,14 @@ public JobResult UnBindCertificate() } catch (Exception ex) { - var failureMessage = $"Unbinging for Site '{StorePath}' on server '{_runSpace.ConnectionInfo.ComputerName}' with error: '{LogHandler.FlattenException(ex)}'"; + string computerName = string.Empty; + if (_runSpace.ConnectionInfo is null) + { + computerName = "localMachine"; + } + else { computerName = "Server: " + _runSpace.ConnectionInfo.ComputerName; } + + var failureMessage = $"Unbinding for Site '{StorePath}' on {computerName} with error: {LogHandler.FlattenException(ex)}"; _logger.LogWarning(failureMessage); return new JobResult @@ -424,6 +474,214 @@ public JobResult UnBindCertificate() ps.Dispose(); } } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private object PerformIISUnBinding(string webSiteName, string protocol, string ipAddress, string port, string hostName) + { + string funcScript = @" + param ( + [string]$SiteName, # Name of the site + [string]$IPAddress, # IP Address of the binding + [string]$Port, # Port number of the binding + [string]$Hostname, # Hostname (optional) + [string]$Protocol = ""https"" # Protocol (default to """"https"""") + ) + + # Set Execution Policy (optional, depending on your environment) + Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force + + # Check if the IISAdministration module is already loaded + if (-not (Get-Module -Name IISAdministration)) { + try { + # Attempt to import the IISAdministration module + Import-Module IISAdministration -ErrorAction Stop + } + catch { + throw ""Failed to load the IISAdministration module. Ensure it is installed and available."" + } + } + + try { + # Get the bindings for the specified site + $bindings = Get-IISSiteBinding -Name $SiteName + + # Check if any bindings match the specified criteria + $matchingBindings = $bindings | Where-Object { + ($_.bindingInformation -eq ""${IPAddress}:${Port}:${Hostname}"") -and + ($_.protocol -eq $Protocol) + } + + if ($matchingBindings) { + # Unbind the matching certificates + foreach ($binding in $matchingBindings) { + Write-Host """"Removing binding: $($binding.bindingInformation) with protocol: $($binding.protocol)"""" + Write-Host """"Binding information: + Remove-IISSiteBinding -Name $SiteName -BindingInformation $binding.bindingInformation -Protocol $binding.protocol -confirm:$false + } + Write-Host """"Successfully removed the matching bindings from the site: $SiteName"""" + } else { + Write-Host """"No matching bindings found for site: $SiteName"""" + } + } + catch { + throw ""An error occurred while unbinding the certificate from site ${SiteName}: $_"" + } + "; + + ps.AddScript(funcScript); + ps.AddParameter("SiteName", webSiteName); + ps.AddParameter("IPAddress", ipAddress); + ps.AddParameter("Port", port); + ps.AddParameter("Hostname", hostName); + ps.AddParameter("Protocol", protocol); + + _logger.LogTrace("funcScript added..."); + var results = ps.Invoke(); + _logger.LogTrace("funcScript Invoked..."); + + return results; + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private object PerformIISBinding(string webSiteName, string protocol, string ipAddress, string port, string hostName, string sslFlags, string thumbprint, string storeName) + { + //string funcScript = @" + // param ( + // $SiteName, # The name of the IIS site + // $IPAddress, # The IP Address for the binding + // $Port, # The port number for the binding + // $Hostname, # Hostname for the binding (if any) + // $Protocol, # Protocol (e.g., HTTP, HTTPS) + // $Thumbprint, # Certificate thumbprint for HTTPS bindings + // $StoreName, # Certificate store location (e.g., ""My"" for personal certs) + // $SslFlags # SSL flags (if any) + // ) + + // # Set Execution Policy (optional, depending on your environment) + // Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force + + // ## Check if the IISAdministration module is available + // #$module = Get-Module -Name IISAdministration -ListAvailable + + // #if (-not $module) { + // # throw ""The IISAdministration module is not installed on this system."" + // #} + + // # Check if the IISAdministration module is already loaded + // if (-not (Get-Module -Name IISAdministration)) { + // try { + // # Attempt to import the IISAdministration module + // Import-Module IISAdministration -ErrorAction Stop + // } + // catch { + // throw ""Failed to load the IISAdministration module. Ensure it is installed and available."" + // } + // } + + // # Retrieve the existing binding information + // $myBinding = ""${IPAddress}:${Port}:${Hostname}"" + // Write-Host ""myBinding: "" $myBinding + + // $siteBindings = Get-IISSiteBinding -Name $SiteName + // $existingBinding = $siteBindings | Where-Object { $_.bindingInformation -eq $myBinding -and $_.protocol -eq $Protocol } + + // Write-Host ""Binding:"" $existingBinding + + // if ($null -ne $existingBinding) { + // # Remove the existing binding + // Remove-IISSiteBinding -Name $SiteName -BindingInformation $existingBinding.BindingInformation -Protocol $existingBinding.Protocol -Confirm:$false + + // Write-Host ""Removed existing binding: $($existingBinding.BindingInformation)"" + // } + + // # Create the new binding with modified properties + // $newBindingInfo = ""${IPAddress}:${Port}:${Hostname}"" + + // try + // { + // New-IISSiteBinding -Name $SiteName ` + // -BindingInformation $newBindingInfo ` + // -Protocol $Protocol ` + // -CertificateThumbprint $Thumbprint ` + // -CertStoreLocation $StoreName ` + // -SslFlag $SslFlags + + // Write-Host ""New binding added: $newBindingInfo"" + // } + // catch { + // throw $_ + // } + //"; +#if NET6_0 + string funcScript = PowerShellScripts.UpdateIISBindingsV6; +#elif NET8_0_OR_GREATER + string funcScript = PowerShellScripts.UpdateIISBindingsV8; +#endif + + ps.AddScript(funcScript); + ps.AddParameter("SiteName", webSiteName); + ps.AddParameter("IPAddress", ipAddress); + ps.AddParameter("Port", port); + ps.AddParameter("Hostname", hostName); + ps.AddParameter("Protocol", protocol); + ps.AddParameter("Thumbprint", thumbprint); + ps.AddParameter("StoreName", storeName); + ps.AddParameter("SslFlags", sslFlags); + + _logger.LogTrace("funcScript added..."); + var results = ps.Invoke(); + _logger.LogTrace("funcScript Invoked..."); + + return results; + } + + public static string MigrateSNIFlag(string input) + { + // Check if the input is numeric, if so, just return it as an integer + if (int.TryParse(input, out int numericValue)) + { + return numericValue.ToString(); + } + + if (string.IsNullOrEmpty(input)) { throw new ArgumentNullException("SNI/SSL Flag", "The SNI or SSL Flag flag must not be empty or null."); } + + // Handle the string cases + switch (input.ToLower()) + { + case "0 - no sni": + return "0"; + case "1 - sni enabled": + return "1"; + case "2 - non sni binding": + return "2"; + case "3 - sni binding": + return "3"; + default: + throw new ArgumentOutOfRangeException($"Received an invalid value '{input}' for sni/ssl Flag value"); + } + } } } diff --git a/IISU/ClientPsSqlManager.cs b/IISU/ClientPsSqlManager.cs index b36084f..a98d8b0 100644 --- a/IISU/ClientPsSqlManager.cs +++ b/IISU/ClientPsSqlManager.cs @@ -216,7 +216,7 @@ public string GetSqlInstanceValue(string instanceName,PowerShell ps) } return null; } - catch (ArgumentOutOfRangeException ex) + catch (ArgumentOutOfRangeException) { throw new Exception($"There were no SQL instances with the name: {instanceName}. Please check the spelling of the SQL instance."); } diff --git a/IISU/ImplementedStoreTypes/Win/Inventory.cs b/IISU/ImplementedStoreTypes/Win/Inventory.cs index 65f5602..c04f322 100644 --- a/IISU/ImplementedStoreTypes/Win/Inventory.cs +++ b/IISU/ImplementedStoreTypes/Win/Inventory.cs @@ -30,7 +30,7 @@ namespace Keyfactor.Extensions.Orchestrator.WindowsCertStore.WinCert public class Inventory : WinCertJobTypeBase, IInventoryJobExtension { private ILogger _logger; - public string ExtensionName => string.Empty; + public string ExtensionName => "WinCertInventory"; public Inventory(IPAMSecretResolver resolver) { diff --git a/IISU/ImplementedStoreTypes/Win/Management.cs b/IISU/ImplementedStoreTypes/Win/Management.cs index f251c7f..b897987 100644 --- a/IISU/ImplementedStoreTypes/Win/Management.cs +++ b/IISU/ImplementedStoreTypes/Win/Management.cs @@ -33,7 +33,7 @@ public class Management : WinCertJobTypeBase, IManagementJobExtension { private ILogger _logger; - public string ExtensionName => string.Empty; + public string ExtensionName => "WinCertManagement"; private Runspace myRunspace; @@ -51,7 +51,14 @@ public JobResult ProcessJob(ManagementJobConfiguration config) _logger = LogHandler.GetClassLogger(); _logger.MethodEntry(); - _logger.LogTrace(JobConfigurationParser.ParseManagementJobConfiguration(config)); + try + { + _logger.LogTrace(JobConfigurationParser.ParseManagementJobConfiguration(config)); + } + catch (Exception e) + { + _logger.LogTrace(e.Message); + } string serverUserName = PAMUtilities.ResolvePAMField(_resolver, _logger, "Server UserName", config.ServerUsername); string serverPassword = PAMUtilities.ResolvePAMField(_resolver, _logger, "Server Password", config.ServerPassword); diff --git a/IISU/ImplementedStoreTypes/Win/ReEnrollment.cs b/IISU/ImplementedStoreTypes/Win/ReEnrollment.cs index cf9abc6..8f0c4de 100644 --- a/IISU/ImplementedStoreTypes/Win/ReEnrollment.cs +++ b/IISU/ImplementedStoreTypes/Win/ReEnrollment.cs @@ -22,7 +22,7 @@ public class ReEnrollment : WinCertJobTypeBase, IReenrollmentJobExtension { private ILogger _logger; - public string ExtensionName => string.Empty; + public string ExtensionName => "WinCertReEnrollment"; public ReEnrollment(IPAMSecretResolver resolver) { diff --git a/IISU/ImplementedStoreTypes/WinIIS/Inventory.cs b/IISU/ImplementedStoreTypes/WinIIS/Inventory.cs index a3855ec..0255948 100644 --- a/IISU/ImplementedStoreTypes/WinIIS/Inventory.cs +++ b/IISU/ImplementedStoreTypes/WinIIS/Inventory.cs @@ -27,7 +27,7 @@ public class Inventory : WinCertJobTypeBase, IInventoryJobExtension { private ILogger _logger; - public string ExtensionName => string.Empty; + public string ExtensionName => "WinIISUInventory"; public Inventory(IPAMSecretResolver resolver) { diff --git a/IISU/ImplementedStoreTypes/WinIIS/Management.cs b/IISU/ImplementedStoreTypes/WinIIS/Management.cs index 09877c3..f917eb7 100644 --- a/IISU/ImplementedStoreTypes/WinIIS/Management.cs +++ b/IISU/ImplementedStoreTypes/WinIIS/Management.cs @@ -32,7 +32,7 @@ public class Management : WinCertJobTypeBase, IManagementJobExtension { private ILogger _logger; - public string ExtensionName => string.Empty; + public string ExtensionName => "WinIISUManagement"; private Runspace myRunspace; @@ -48,7 +48,14 @@ public JobResult ProcessJob(ManagementJobConfiguration config) _logger = LogHandler.GetClassLogger(); _logger.MethodEntry(); - _logger.LogTrace(JobConfigurationParser.ParseManagementJobConfiguration(config)); + try + { + _logger.LogTrace(JobConfigurationParser.ParseManagementJobConfiguration(config)); + } + catch (Exception e) + { + _logger.LogTrace(e.Message); + } string serverUserName = PAMUtilities.ResolvePAMField(_resolver, _logger, "Server UserName", config.ServerUsername); string serverPassword = PAMUtilities.ResolvePAMField(_resolver, _logger, "Server Password", config.ServerPassword); diff --git a/IISU/ImplementedStoreTypes/WinIIS/ReEnrollment.cs b/IISU/ImplementedStoreTypes/WinIIS/ReEnrollment.cs index 8c07b0b..109b554 100644 --- a/IISU/ImplementedStoreTypes/WinIIS/ReEnrollment.cs +++ b/IISU/ImplementedStoreTypes/WinIIS/ReEnrollment.cs @@ -29,7 +29,7 @@ public ReEnrollment(IPAMSecretResolver resolver) _resolver = resolver; } - public string ExtensionName => string.Empty; + public string ExtensionName => "WinIISUReEnrollment"; public JobResult ProcessJob(ReenrollmentJobConfiguration config, SubmitReenrollmentCSR submitReEnrollmentUpdate) { diff --git a/IISU/ImplementedStoreTypes/WinIIS/WinIISInventory.cs b/IISU/ImplementedStoreTypes/WinIIS/WinIISInventory.cs index 2ae070b..0ce7320 100644 --- a/IISU/ImplementedStoreTypes/WinIIS/WinIISInventory.cs +++ b/IISU/ImplementedStoreTypes/WinIIS/WinIISInventory.cs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using Keyfactor.Logging; using Keyfactor.Orchestrators.Common.Enums; using Keyfactor.Orchestrators.Extensions; using Microsoft.Extensions.Logging; @@ -25,9 +26,15 @@ namespace Keyfactor.Extensions.Orchestrator.WindowsCertStore.IISU { - internal class WinIISInventory : ClientPSCertStoreInventory + public class WinIISInventory : ClientPSCertStoreInventory { private ILogger _logger; + + public WinIISInventory() + { + _logger = LogHandler.GetClassLogger(); + } + public WinIISInventory(ILogger logger) : base(logger) { _logger = logger; @@ -97,30 +104,13 @@ public List GetInventoryItems(Runspace runSpace, string st if (foundCert == null) continue; - var sniValue = ""; - switch (Convert.ToInt16(binding.Properties["sniFlg"]?.Value)) - { - case 0: - sniValue = "0 - No SNI"; - break; - case 1: - sniValue = "1 - SNI Enabled"; - break; - case 2: - sniValue = "2 - Non SNI Binding"; - break; - case 3: - sniValue = "3 - SNI Binding"; - break; - } - var siteSettingsDict = new Dictionary { { "SiteName", binding.Properties["Name"]?.Value }, { "Port", binding.Properties["Bindings"]?.Value.ToString()?.Split(':')[1] }, { "IPAddress", binding.Properties["Bindings"]?.Value.ToString()?.Split(':')[0] }, { "HostName", binding.Properties["Bindings"]?.Value.ToString()?.Split(':')[2] }, - { "SniFlag", sniValue }, + { "SniFlag", binding.Properties["sniFlg"]?.Value.ToString() }, { "Protocol", binding.Properties["Protocol"]?.Value }, { "ProviderName", foundCert.CryptoServiceProvider }, { "SAN", foundCert.SAN } @@ -130,7 +120,7 @@ public List GetInventoryItems(Runspace runSpace, string st new CurrentInventoryItem { Certificates = new[] { foundCert.CertificateData }, - Alias = thumbPrint, + Alias = thumbPrint + ":" + binding.Properties["Bindings"]?.Value.ToString(), PrivateKeyEntry = foundCert.HasPrivateKey, UseChainLevel = false, ItemStatus = OrchestratorInventoryItemStatus.Unknown, diff --git a/IISU/ImplementedStoreTypes/WinSQL/Inventory.cs b/IISU/ImplementedStoreTypes/WinSQL/Inventory.cs index 1950a84..31511a0 100644 --- a/IISU/ImplementedStoreTypes/WinSQL/Inventory.cs +++ b/IISU/ImplementedStoreTypes/WinSQL/Inventory.cs @@ -28,7 +28,7 @@ public class Inventory : WinCertJobTypeBase, IInventoryJobExtension { private ILogger _logger; - public string ExtensionName => string.Empty; + public string ExtensionName => "WinSqlInventory"; public Inventory(IPAMSecretResolver resolver) { diff --git a/IISU/ImplementedStoreTypes/WinSQL/Management.cs b/IISU/ImplementedStoreTypes/WinSQL/Management.cs index f13f7e5..a4d2ffe 100644 --- a/IISU/ImplementedStoreTypes/WinSQL/Management.cs +++ b/IISU/ImplementedStoreTypes/WinSQL/Management.cs @@ -29,7 +29,7 @@ public class Management : WinCertJobTypeBase, IManagementJobExtension { private ILogger _logger; - public string ExtensionName => string.Empty; + public string ExtensionName => "WinSqlManagement"; private Runspace myRunspace; @@ -47,7 +47,14 @@ public JobResult ProcessJob(ManagementJobConfiguration config) _logger = LogHandler.GetClassLogger(); _logger.MethodEntry(); - _logger.LogTrace(JobConfigurationParser.ParseManagementJobConfiguration(config)); + try + { + _logger.LogTrace(JobConfigurationParser.ParseManagementJobConfiguration(config)); + } + catch (Exception e) + { + _logger.LogTrace(e.Message); + } string serverUserName = PAMUtilities.ResolvePAMField(_resolver, _logger, "Server UserName", config.ServerUsername); string serverPassword = PAMUtilities.ResolvePAMField(_resolver, _logger, "Server Password", config.ServerPassword); diff --git a/IISU/ImplementedStoreTypes/WinSQL/ReEnrollment.cs b/IISU/ImplementedStoreTypes/WinSQL/ReEnrollment.cs index c4e178f..a96782d 100644 --- a/IISU/ImplementedStoreTypes/WinSQL/ReEnrollment.cs +++ b/IISU/ImplementedStoreTypes/WinSQL/ReEnrollment.cs @@ -23,7 +23,7 @@ public class ReEnrollment : WinCertJobTypeBase, IReenrollmentJobExtension { private ILogger _logger; - public string ExtensionName => string.Empty; + public string ExtensionName => "WinSqlReEnrollment"; public ReEnrollment(IPAMSecretResolver resolver) { diff --git a/IISU/JobConfigurationParser.cs b/IISU/JobConfigurationParser.cs index 9d7583b..4d64749 100644 --- a/IISU/JobConfigurationParser.cs +++ b/IISU/JobConfigurationParser.cs @@ -33,54 +33,98 @@ public static string ParseManagementJobConfiguration(ManagementJobConfiguration IManagementJobLogger managementParser = new ManagementJobLogger(); - // JobConfiguration - managementParser.JobCancelled = config.JobCancelled; - managementParser.ServerError = config.ServerError; - managementParser.JobHistoryID = config.JobHistoryId; - managementParser.RequestStatus = config.RequestStatus; - managementParser.ServerUserName = config.ServerUsername; - managementParser.ServerPassword = "**********"; - managementParser.UseSSL = config.UseSSL; - managementParser.JobTypeID = config.JobTypeId; - managementParser.JobID = config.JobId; - managementParser.Capability = config.Capability; + try + { + // JobConfiguration + managementParser.JobCancelled = config.JobCancelled; + managementParser.ServerError = config.ServerError; + managementParser.JobHistoryID = config.JobHistoryId; + managementParser.RequestStatus = config.RequestStatus; + managementParser.ServerUserName = config.ServerUsername; + managementParser.ServerPassword = "**********"; + managementParser.UseSSL = config.UseSSL; + managementParser.JobTypeID = config.JobTypeId; + managementParser.JobID = config.JobId; + managementParser.Capability = config.Capability; - // JobProperties - JobProperties jobProperties = JsonConvert.DeserializeObject(config.CertificateStoreDetails.Properties, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Populate }); - managementParser.JobConfigurationProperties = jobProperties; + } + catch (Exception e) + { + throw new Exception($"Error while paring management Job Configuration: {e.Message}"); + } - // PreviousInventoryItem - managementParser.LastInventory = config.LastInventory; + + try + { + // JobProperties + JobProperties jobProperties = JsonConvert.DeserializeObject(config.CertificateStoreDetails.Properties, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Populate }); + managementParser.JobConfigurationProperties = jobProperties; + } + catch (Exception e) + { + throw new Exception($"Error while parsing management Job Properties: {e.Message}"); + } - //CertificateStore - managementParser.CertificateStoreDetails.ClientMachine = config.CertificateStoreDetails.ClientMachine; - managementParser.CertificateStoreDetails.StorePath = config.CertificateStoreDetails.StorePath; - managementParser.CertificateStoreDetails.StorePassword = "**********"; - managementParser.CertificateStoreDetails.Type = config.CertificateStoreDetails.Type; + try + { + // PreviousInventoryItem + managementParser.LastInventory = config.LastInventory; + } + catch (Exception e) + { + throw new Exception($"Error while parsing Previous Inventory Item: {e.Message}"); + } - bool isEmpty = (config.JobProperties.Count == 0); // Check if the dictionary is empty or not - if (!isEmpty) + try { - object value = ""; - if (config.JobProperties.TryGetValue("SiteName", out value)) managementParser.CertificateStoreDetailProperties.SiteName = config.JobProperties["SiteName"].ToString(); - if (config.JobProperties.TryGetValue("Port", out value)) managementParser.CertificateStoreDetailProperties.Port = config.JobProperties["Port"].ToString(); - if (config.JobProperties.TryGetValue("HostName", out value)) managementParser.CertificateStoreDetailProperties.HostName = config.JobProperties["HostName"]?.ToString(); - if (config.JobProperties.TryGetValue("Protocol", out value)) managementParser.CertificateStoreDetailProperties.Protocol = config.JobProperties["Protocol"].ToString(); - if (config.JobProperties.TryGetValue("SniFlag", out value)) managementParser.CertificateStoreDetailProperties.SniFlag = config.JobProperties["SniFlag"].ToString()?[..1]; - if (config.JobProperties.TryGetValue("IPAddress", out value)) managementParser.CertificateStoreDetailProperties.IPAddress = config.JobProperties["IPAddress"].ToString(); - if (config.JobProperties.TryGetValue("ProviderName", out value)) managementParser.CertificateStoreDetailProperties.ProviderName = config.JobProperties["ProviderName"]?.ToString(); - if (config.JobProperties.TryGetValue("SAN", out value)) managementParser.CertificateStoreDetailProperties.SAN = config.JobProperties["SAN"]?.ToString(); + //CertificateStore + managementParser.CertificateStoreDetails.ClientMachine = config.CertificateStoreDetails.ClientMachine; + managementParser.CertificateStoreDetails.StorePath = config.CertificateStoreDetails.StorePath; + managementParser.CertificateStoreDetails.StorePassword = "**********"; + managementParser.CertificateStoreDetails.Type = config.CertificateStoreDetails.Type; + + bool isEmpty = (config.JobProperties.Count == 0); // Check if the dictionary is empty or not + if (!isEmpty) + { + object value = ""; + if (config.JobProperties.TryGetValue("SiteName", out value)) managementParser.CertificateStoreDetailProperties.SiteName = config.JobProperties["SiteName"].ToString(); + if (config.JobProperties.TryGetValue("Port", out value)) managementParser.CertificateStoreDetailProperties.Port = config.JobProperties["Port"].ToString(); + if (config.JobProperties.TryGetValue("HostName", out value)) managementParser.CertificateStoreDetailProperties.HostName = config.JobProperties["HostName"]?.ToString(); + if (config.JobProperties.TryGetValue("Protocol", out value)) managementParser.CertificateStoreDetailProperties.Protocol = config.JobProperties["Protocol"].ToString(); + if (config.JobProperties.TryGetValue("SniFlag", out value)) managementParser.CertificateStoreDetailProperties.SniFlag = config.JobProperties["SniFlag"].ToString(); + if (config.JobProperties.TryGetValue("IPAddress", out value)) managementParser.CertificateStoreDetailProperties.IPAddress = config.JobProperties["IPAddress"].ToString(); + if (config.JobProperties.TryGetValue("ProviderName", out value)) managementParser.CertificateStoreDetailProperties.ProviderName = config.JobProperties["ProviderName"]?.ToString(); + if (config.JobProperties.TryGetValue("SAN", out value)) managementParser.CertificateStoreDetailProperties.SAN = config.JobProperties["SAN"]?.ToString(); + } + } + catch (Exception e) + { + throw new Exception($"Error while parsing Certificate Store: {e.Message}"); } - // Management Base - managementParser.OperationType = config.OperationType; - managementParser.Overwrite = config.Overwrite; + try + { + // Management Base + managementParser.OperationType = config.OperationType; + managementParser.Overwrite = config.Overwrite; + } + catch (Exception e) + { + throw new Exception($"Error while parsing Management Base: {e.Message}"); + } - // JobCertificate - managementParser.JobCertificateProperties.Thumbprint = config.JobCertificate.Thumbprint; - managementParser.JobCertificateProperties.Contents = config.JobCertificate.Contents; - managementParser.JobCertificateProperties.Alias = config.JobCertificate.Alias; - managementParser.JobCertificateProperties.PrivateKeyPassword = "**********"; + try + { + // JobCertificate + managementParser.JobCertificateProperties.Thumbprint = config.JobCertificate.Thumbprint; + managementParser.JobCertificateProperties.Contents = config.JobCertificate.Contents; + managementParser.JobCertificateProperties.Alias = config.JobCertificate.Alias; + managementParser.JobCertificateProperties.PrivateKeyPassword = "**********"; + } + catch (Exception e) + { + throw new Exception($"Error while parsing Job Certificate: {e.Message}"); + } return JsonConvert.SerializeObject(managementParser); } diff --git a/IISU/Models/JobProperties.cs b/IISU/Models/JobProperties.cs index 5fb03bf..a6ef63b 100644 --- a/IISU/Models/JobProperties.cs +++ b/IISU/Models/JobProperties.cs @@ -45,19 +45,11 @@ public JobProperties() public bool ServerUseSsl { get; set; } [JsonProperty("sniflag")] - [DefaultValue(SniFlag.None)] - public SniFlag SniFlag { get; set; } + [DefaultValue("0")] + public string SniFlag { get; set; } [JsonProperty("RestartService")] [DefaultValue(true)] public bool RestartService { get; set; } } - - internal enum SniFlag - { - None = 0, - Sni = 1, - NoneCentral = 2, - SniCentral = 3 - } } \ No newline at end of file diff --git a/IISU/PSHelper.cs b/IISU/PSHelper.cs index c125751..e1016f6 100644 --- a/IISU/PSHelper.cs +++ b/IISU/PSHelper.cs @@ -50,11 +50,22 @@ public static Runspace GetClientPsRunspace(string winRmProtocol, string clientMa if (isLocal) { - //return RunspaceFactory.CreateRunspace(); +#if NET6_0 PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(5, 1), null, null, false); Runspace rs = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(Array.Empty()), instance); - return rs; +#elif NET8_0_OR_GREATER + try + { + InitialSessionState iss = InitialSessionState.CreateDefault(); + Runspace rs = RunspaceFactory.CreateRunspace(iss); + return rs; + } + catch (global::System.Exception) + { + throw new Exception($"An error occurred while attempting to create the PowerShell instance. This version requires .Net8 and PowerShell SDK 7.2 or greater. Please verify the version of .Net8 and PowerShell installed on your machine."); + } +#endif } else { diff --git a/IISU/Scripts/PowerShellScripts.cs b/IISU/Scripts/PowerShellScripts.cs new file mode 100644 index 0000000..3da10e3 --- /dev/null +++ b/IISU/Scripts/PowerShellScripts.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Keyfactor.Extensions.Orchestrator.WindowsCertStore.Scripts +{ + public class PowerShellScripts + { + public const string UpdateIISBindingsV6 = @" + param ( + $SiteName, # The name of the IIS site + $IPAddress, # The IP Address for the binding + $Port, # The port number for the binding + $Hostname, # Hostname for the binding (if any) + $Protocol, # Protocol (e.g., HTTP, HTTPS) + $Thumbprint, # Certificate thumbprint for HTTPS bindings + $StoreName, # Certificate store location (e.g., ""My"" for personal certs) + $SslFlags # SSL flags (if any) + ) + + # Set Execution Policy (optional, depending on your environment) + Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force + + # Check if the WebAdministration module is available + $module = Get-Module -Name WebAdministration -ListAvailable + + if (-not $module) { + throw ""The WebAdministration module is not installed on this system."" + } + + # Check if the WebAdministration module is already loaded + if (-not (Get-Module -Name WebAdministration)) { + try { + # Attempt to import the WebAdministration module + Import-Module WebAdministration -ErrorAction Stop + } + catch { + throw ""Failed to load the WebAdministration module. Ensure it is installed and available."" + } + } + + # Retrieve the existing binding information + $myBinding = ""${IPAddress}:${Port}:${Hostname}"" + Write-Host ""myBinding: "" $myBinding + + $siteBindings = Get-IISSiteBinding -Name $SiteName + $existingBinding = $siteBindings | Where-Object { $_.bindingInformation -eq $myBinding -and $_.protocol -eq $Protocol } + + Write-Host ""Binding:"" $existingBinding + + if ($null -ne $existingBinding) { + # Remove the existing binding + Remove-IISSiteBinding -Name $SiteName -BindingInformation $existingBinding.BindingInformation -Protocol $existingBinding.Protocol -Confirm:$false + + Write-Host ""Removed existing binding: $($existingBinding.BindingInformation)"" + } + + # Create the new binding with modified properties + $newBindingInfo = ""${IPAddress}:${Port}:${Hostname}"" + + New-IISSiteBinding -Name $SiteName ` + -BindingInformation $newBindingInfo ` + -Protocol $Protocol ` + -CertificateThumbprint $Thumbprint ` + -CertStoreLocation $StoreName ` + -SslFlag $SslFlags + + Write-Host ""New binding added: $newBindingInfo"""; + + public const string UpdateIISBindingsV8 = @" + param ( + $SiteName, # The name of the IIS site + $IPAddress, # The IP Address for the binding + $Port, # The port number for the binding + $Hostname, # Hostname for the binding (if any) + $Protocol, # Protocol (e.g., HTTP, HTTPS) + $Thumbprint, # Certificate thumbprint for HTTPS bindings + $StoreName, # Certificate store location (e.g., ""My"" for personal certs) + $SslFlags # SSL flags (if any) + ) + + # Set Execution Policy (optional, depending on your environment) + Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force + + ## Check if the IISAdministration module is available + #$module = Get-Module -Name IISAdministration -ListAvailable + + #if (-not $module) { + # throw ""The IISAdministration module is not installed on this system."" + #} + + # Check if the IISAdministration module is already loaded + if (-not (Get-Module -Name IISAdministration)) { + try { + # Attempt to import the IISAdministration module + Import-Module IISAdministration -ErrorAction Stop + } + catch { + throw ""Failed to load the IISAdministration module. Ensure it is installed and available."" + } + } + + # Retrieve the existing binding information + $myBinding = ""${IPAddress}:${Port}:${Hostname}"" + Write-Host ""myBinding: "" $myBinding + + $siteBindings = Get-IISSiteBinding -Name $SiteName + $existingBinding = $siteBindings | Where-Object { $_.bindingInformation -eq $myBinding -and $_.protocol -eq $Protocol } + + Write-Host ""Binding:"" $existingBinding + + if ($null -ne $existingBinding) { + # Remove the existing binding + Remove-IISSiteBinding -Name $SiteName -BindingInformation $existingBinding.BindingInformation -Protocol $existingBinding.Protocol -Confirm:$false + + Write-Host ""Removed existing binding: $($existingBinding.BindingInformation)"" + } + + # Create the new binding with modified properties + $newBindingInfo = ""${IPAddress}:${Port}:${Hostname}"" + + try + { + New-IISSiteBinding -Name $SiteName ` + -BindingInformation $newBindingInfo ` + -Protocol $Protocol ` + -CertificateThumbprint $Thumbprint ` + -CertStoreLocation $StoreName ` + -SslFlag $SslFlags + + Write-Host ""New binding added: $newBindingInfo"" + } + catch { + throw $_ + }"; + + } +} diff --git a/IISU/WindowsCertStore.csproj b/IISU/WindowsCertStore.csproj index b224ebf..6bedf26 100644 --- a/IISU/WindowsCertStore.csproj +++ b/IISU/WindowsCertStore.csproj @@ -3,7 +3,7 @@ Keyfactor.Extensions.Orchestrator.WindowsCertStore true - net6.0 + NET6.0;NET8.0 AnyCPU @@ -31,8 +31,9 @@ - - + + + @@ -41,4 +42,10 @@ + + + 7.4.5 + + + diff --git a/Migration-Scripts/IISU Sni Flag 2.5 upgrade script.sql b/Migration-Scripts/IISU Sni Flag 2.5 upgrade script.sql new file mode 100644 index 0000000..4122385 --- /dev/null +++ b/Migration-Scripts/IISU Sni Flag 2.5 upgrade script.sql @@ -0,0 +1,80 @@ +SET NOCOUNT ON + +BEGIN TRY + BEGIN TRANSACTION + + DECLARE @IISUShortName VARCHAR(50) = 'IISU' + DECLARE @SniFlagParameter VARCHAR(50) = 'SniFlag' + + DECLARE @StoreTypeId INT + + -- get store type id + SELECT @StoreTypeId = storetypes.[StoreType] + FROM [cms_agents].[CertStoreTypes] AS storetypes + WHERE @IISUShortName = storetypes.[ShortName] + + -- get list of cert stores guids of that type + SELECT certstores.[Id] + INTO #StoreGuids + FROM [cms_agents].[CertStores] AS certstores + WHERE @StoreTypeId = certstores.[CertStoreType] + + -- get list of certstoreinventoryitems matching on store guid + SELECT inventory.[Id], inventory.[EntryParameters] + INTO #InventoryItems + FROM [cms_agents].[CertStoreInventoryItems] AS inventory + INNER JOIN #StoreGuids ON #StoreGuids.[Id] = inventory.[CertStoreId] + + -- update entry parameters to new setting + UPDATE [cms_agents].[CertStoreTypeEntryParameters] + SET [DisplayName] = 'SSL Flags', + [Type] = '0', + [DefaultValue] = '0', + [Options] = NULL + WHERE [StoreTypeId] = @StoreTypeId + AND [Name] = @SniFlagParameter + + -- perform batch processing on certstoreinventoryitems to alter their EntryParameters to change the SNiFlag value to be a simple character instead of lots of text + -- replace 0 - No SNI + UPDATE inventoryitems + SET inventoryitems.[EntryParameters] = REPLACE(inventory.[EntryParameters], '0 - No SNI', '0') + FROM [cms_agents].[CertStoreInventoryItems] AS inventoryitems + INNER JOIN #InventoryItems ON inventoryitems.[Id] = #InventoryItems.[Id] + WHERE inventoryitems.[EntryParameters] LIKE '%0 - No SNI%' + + -- replace 1 - SNI Enabled + UPDATE inventoryitems + SET inventoryitems.[EntryParameters] = REPLACE(inventory.[EntryParameters], '1 - SNI Enabled', '1') + FROM [cms_agents].[CertStoreInventoryItems] AS inventoryitems + INNER JOIN #InventoryItems ON inventoryitems.[Id] = #InventoryItems.[Id] + WHERE inventoryitems.[EntryParameters] LIKE '%1 - SNI Enabled%' + + -- replace 2 - Non SNI Binding + UPDATE inventoryitems + SET inventoryitems.[EntryParameters] = REPLACE(inventory.[EntryParameters], '2 - Non SNI Binding', '2') + FROM [cms_agents].[CertStoreInventoryItems] AS inventoryitems + INNER JOIN #InventoryItems ON inventoryitems.[Id] = #InventoryItems.[Id] + WHERE inventoryitems.[EntryParameters] LIKE '%2 - Non SNI Binding%' + + -- replace 3 - SNI Binding + UPDATE inventoryitems + SET inventoryitems.[EntryParameters] = REPLACE(inventory.[EntryParameters], '3 - SNI Binding', '3') + FROM [cms_agents].[CertStoreInventoryItems] AS inventoryitems + INNER JOIN #InventoryItems ON inventoryitems.[Id] = #InventoryItems.[Id] + WHERE inventoryitems.[EntryParameters] LIKE '%3 - SNI Binding%' + + COMMIT TRANSACTION +END TRY + +BEGIN CATCH + IF (@@TRANCOUNT > 0) + BEGIN + ROLLBACK TRANSACTION; + END + + SELECT + ERROR_MESSAGE() AS ErrorMessage, + ERROR_SEVERITY() AS Severity, + ERROR_STATE() AS ErrorState; +END CATCH + diff --git a/Migration-Scripts/Legacy-IIS/CreateIISUCertStoreType.sql b/Migration-Scripts/Legacy-IIS/CreateIISUCertStoreType.sql index c48a372..4d6fc16 100644 --- a/Migration-Scripts/Legacy-IIS/CreateIISUCertStoreType.sql +++ b/Migration-Scripts/Legacy-IIS/CreateIISUCertStoreType.sql @@ -358,14 +358,14 @@ BEGIN TRY ) VALUES ( - @current_storetype_id, -- StoreTypeId + @current_storetype_id, -- StoreTypeId 'SniFlag', -- Name - 'SNI Support', -- DisplayName - 2, -- Type + 'SSL Flags', -- DisplayName + 0, -- Type 14, -- RequiredWhen NULL, -- DependsOn - '0 - No SNI', -- DefaultValue - '0 - No SNI,1 - SNI Enabled,2 - Non SNI Binding,3 - SNI Binding' -- Options + '0', -- DefaultValue + NULL -- Options ); -- create Protocol entry parameter diff --git a/README.md b/README.md index 0353ab2..c928b28 100644 --- a/README.md +++ b/README.md @@ -1,133 +1,129 @@ +

+ Windows Certificate Universal Orchestrator Extension +

+ +

+ +Integration Status: production +Release +Issues +GitHub Downloads (all assets, all releases) +

-# WinCertStore Orchestrator - -The Windows Certificate Store Orchestrator Extension implements two certificate store types. 1) “WinCert” which manages certificates in a Windows local machine store, and 2) “IISU” which manages certificates and their bindings in a Windows local machine store that are bound to Internet Information Server (IIS) websites. These extensions replace the now deprecated “IIS” cert store type that ships with Keyfactor Command. The “IISU” extension also replaces the “IISBin” certificate store type from prior versions of this repository. This orchestrator extension is in the process of being renamed from “IIS Orchestrator” as it now supports certificates that are not in use by IIS. - -#### Integration status: Production - Ready for use in production environments. - -## About the Keyfactor Universal Orchestrator Extension - -This repository contains a Universal Orchestrator Extension which is a plugin to the Keyfactor Universal Orchestrator. Within the Keyfactor Platform, Orchestrators are used to manage “certificate stores” — collections of certificates and roots of trust that are found within and used by various applications. +

+ + + Support + + · + + Installation + + · + + License + + · + + Related Integrations + +

-The Universal Orchestrator is part of the Keyfactor software distribution and is available via the Keyfactor customer portal. For general instructions on installing Extensions, see the “Keyfactor Command Orchestrator Installation and Configuration Guide” section of the Keyfactor documentation. For configuration details of this specific Extension see below in this readme. +## Overview -The Universal Orchestrator is the successor to the Windows Orchestrator. This Orchestrator Extension plugin only works with the Universal Orchestrator and does not work with the Windows Orchestrator. +The WinCertStore Orchestrator remotely manages certificates in a Windows Server local machine certificate store. Users are able to determine which store they wish to place certificates in by entering the correct store path. For a complete list of local machine cert stores you can execute the PowerShell command: -## Support for WinCertStore Orchestrator + Get-ChildItem Cert:\LocalMachine -WinCertStore Orchestrator is supported by Keyfactor for Keyfactor customers. If you have a support issue, please open a support ticket via the Keyfactor Support Portal at https://support.keyfactor.com +The returned list will contain the actual certificate store name to be used when entering store location. -###### To report a problem or suggest a new feature, use the **[Issues](../../issues)** tab. If you want to contribute actual bug fixes or proposed enhancements, use the **[Pull requests](../../pulls)** tab. +By default, most certificates are stored in the “Personal” (My) and “Web Hosting” (WebHosting) stores. ---- +This extension implements four job types: Inventory, Management Add/Remove, and Reenrollment. -### Migrating Legacy IIS Stores -If you have existing IIS stores with the built-in IIS types, and plan to upgrade to Keyfactor Command 11 or later, you will need to migrate from the legacy store types to the IISU and WinCert store type defined in this repository. +WinRM is used to remotely manage the certificate stores and IIS bindings. WinRM must be properly configured to allow the orchestrator on the server to manage the certificates. Setting up WinRM is not in the scope of this document. -You can find the guide and migration scripts in this repository, located here: -[Legacy IIS Migration](./Migration-Scripts/Legacy-IIS) ---- +**Note:** +In version 2.0 of the IIS Orchestrator, the certificate store type has been renamed and additional parameters have been added. Prior to 2.0 the certificate store type was called “IISBin” and as of 2.0 it is called “IISU”. If you have existing certificate stores of type “IISBin”, you have three options: +1. Leave them as is and continue to manage them with a pre 2.0 IIS Orchestrator Extension. Create the new IISU certificate store type and create any new IIS stores using the new type. +1. Delete existing IIS stores. Delete the IISBin store type. Create the new IISU store type. Recreate the IIS stores using the new IISU store type. +1. Convert existing IISBin certificate stores to IISU certificate stores. There is not currently a way to do this via the Keyfactor API, so direct updates to the underlying Keyfactor SQL database is required. A SQL script (IIS-Conversion.sql) is available in the repository to do this. Hosted customers, which do not have access to the underlying database, will need to work Keyfactor support to run the conversion. On-premises customers can run the script themselves, but are strongly encouraged to ensure that a SQL backup is taken prior running the script (and also be confident that they have a tested database restoration process.) +**Note: There is an additional (and deprecated) certificate store type of “IIS” that ships with the Keyfactor platform. Migration of certificate stores from the “IIS” type to either the “IISBin” or “IISU” types is not currently supported.** +**Note: If Looking to use GMSA Accounts to run the Service Keyfactor Command 10.2 or greater is required for No Value checkbox to work** -## Keyfactor Version Supported +The Windows Certificate Universal Orchestrator extension implements 3 Certificate Store Types. Depending on your use case, you may elect to use one, or all of these Certificate Store Types. Descriptions of each are provided below. -The minimum version of the Keyfactor Universal Orchestrator Framework needed to run this version of the extension is 10.1 -## Platform Specific Notes +
Windows Certificate (WinCert) -The Keyfactor Universal Orchestrator may be installed on either Windows or Linux based platforms. The certificate operations supported by a capability may vary based what platform the capability is installed on. The table below indicates what capabilities are supported based on which platform the encompassing Universal Orchestrator is running. -| Operation | Win | Linux | -|-----|-----|------| -|Supports Management Add|✓ | | -|Supports Management Remove|✓ | | -|Supports Create Store| | | -|Supports Discovery| | | -|Supports Reenrollment|✓ | | -|Supports Inventory|✓ | | +### WinCert -## PAM Integration +The Windows Certificate Certificate Store Type, known by its short name 'WinCert,' enables the management of certificates within the Windows local machine certificate stores. This store type is a versatile option for general Windows certificate management and supports functionalities including inventory, add, remove, and reenrollment of certificates. -This orchestrator extension has the ability to connect to a variety of supported PAM providers to allow for the retrieval of various client hosted secrets right from the orchestrator server itself. This eliminates the need to set up the PAM integration on Keyfactor Command which may be in an environment that the client does not want to have access to their PAM provider. +The store type represents the various certificate stores present on a Windows Server. Users can specify these stores by entering the correct store path. To get a complete list of available certificate stores, the PowerShell command `Get-ChildItem Cert:\LocalMachine` can be executed, providing the actual certificate store names needed for configuration. -The secrets that this orchestrator extension supports for use with a PAM Provider are: +#### Key Features and Considerations -|Name|Description| -|----|-----------| -|Server Username|The user id that will be used to authenticate into the server hosting the store| -|Server Password|The password that will be used to authenticate into the server hosting the store| +- **Functionality:** The WinCert store type supports essential certificate management tasks, such as inventorying existing certificates, adding new certificates, removing old ones, and reenrolling certificates. +- **Caveats:** It's important to ensure that the Windows Remote Management (WinRM) is properly configured on the target server. The orchestrator relies on WinRM to perform its tasks, such as manipulating the Windows Certificate Stores. Misconfiguration of WinRM may lead to connection and permission issues. -It is not necessary to use a PAM Provider for all of the secrets available above. If a PAM Provider should not be used, simply enter in the actual value to be used, as normal. +- **Limitations:** Users should be aware that for this store type to function correctly, certain permissions are necessary. While some advanced users successfully use non-administrator accounts with specific permissions, it is officially supported only with Local Administrator permissions. Complexities with interactions between Group Policy, WinRM, User Account Control, and other environmental factors may impede operations if not properly configured. +
-If a PAM Provider will be used for one of the fields above, start by referencing the [Keyfactor Integration Catalog](https://keyfactor.github.io/integrations-catalog/content/pam). The GitHub repo for the PAM Provider to be used contains important information such as the format of the `json` needed. What follows is an example but does not reflect the `json` values for all PAM Providers as they have different "instance" and "initialization" parameter names and values. +
IIS Bound Certificate (IISU) -
General PAM Provider Configuration -

+### IISU +The IIS Bound Certificate Certificate Store Type, identified by its short name 'IISU,' is designed for the management of certificates bound to IIS (Internet Information Services) servers. This store type allows users to automate and streamline the process of adding, removing, and reenrolling certificates for IIS sites, making it significantly easier to manage web server certificates. -### Example PAM Provider Setup +#### Key Features and Representation -To use a PAM Provider to resolve a field, in this example the __Server Password__ will be resolved by the `Hashicorp-Vault` provider, first install the PAM Provider extension from the [Keyfactor Integration Catalog](https://keyfactor.github.io/integrations-catalog/content/pam) on the Universal Orchestrator. +The IISU store type represents the IIS servers and their certificate bindings. It specifically caters to managing SSL/TLS certificates tied to IIS websites, allowing bind operations such as specifying site names, IP addresses, ports, and enabling Server Name Indication (SNI). By default, it supports job types like Inventory, Add, Remove, and Reenrollment, thereby offering comprehensive management capabilities for IIS certificates. -Next, complete configuration of the PAM Provider on the UO by editing the `manifest.json` of the __PAM Provider__ (e.g. located at extensions/Hashicorp-Vault/manifest.json). The "initialization" parameters need to be entered here: +#### Limitations and Areas of Confusion -~~~ json - "Keyfactor:PAMProviders:Hashicorp-Vault:InitializationInfo": { - "Host": "http://127.0.0.1:8200", - "Path": "v1/secret/data", - "Token": "xxxxxx" - } -~~~ +- **Caveats:** It's important to ensure that the Windows Remote Management (WinRM) is properly configured on the target server. The orchestrator relies on WinRM to perform its tasks, such as manipulating the Windows Certificate Stores. Misconfiguration of WinRM may lead to connection and permission issues. -After these values are entered, the Orchestrator needs to be restarted to pick up the configuration. Now the PAM Provider can be used on other Orchestrator Extensions. +- **Limitations:** Users should be aware that for this store type to function correctly, certain permissions are necessary. While some advanced users successfully use non-administrator accounts with specific permissions, it is officially supported only with Local Administrator permissions. Complexities with interactions between Group Policy, WinRM, User Account Control, and other environmental factors may impede operations if not properly configured. -### Use the PAM Provider -With the PAM Provider configured as an extenion on the UO, a `json` object can be passed instead of an actual value to resolve the field with a PAM Provider. Consult the [Keyfactor Integration Catalog](https://keyfactor.github.io/integrations-catalog/content/pam) for the specific format of the `json` object. +- **Custom Alias and Private Keys:** The store type does not support custom aliases for individual entries and requires private keys because IIS certificates without private keys would be invalid. +

-To have the __Server Password__ field resolved by the `Hashicorp-Vault` provider, the corresponding `json` object from the `Hashicorp-Vault` extension needs to be copied and filed in with the correct information: +
WinSql (WinSql) -~~~ json -{"Secret":"my-kv-secret","Key":"myServerPassword"} -~~~ -This text would be entered in as the value for the __Server Password__, instead of entering in the actual password. The Orchestrator will attempt to use the PAM Provider to retrieve the __Server Password__. If PAM should not be used, just directly enter in the value for the field. -

-
+### WinSql +The WinSql Certificate Store Type, referred to by its short name 'WinSql,' is designed for the management of certificates used by SQL Server instances. This store type allows users to automate the process of adding, removing, reenrolling, and inventorying certificates associated with SQL Server, thereby simplifying the management of SSL/TLS certificates for database servers. +#### Caveats and Limitations +- **Caveats:** It's important to ensure that the Windows Remote Management (WinRM) is properly configured on the target server. The orchestrator relies on WinRM to perform its tasks, such as manipulating the Windows Certificate Stores. Misconfiguration of WinRM may lead to connection and permission issues. ---- +- **Limitations:** Users should be aware that for this store type to function correctly, certain permissions are necessary. While some advanced users successfully use non-administrator accounts with specific permissions, it is officially supported only with Local Administrator permissions. Complexities with interactions between Group Policy, WinRM, User Account Control, and other environmental factors may impede operations if not properly configured. +
-# WinCertStore Orchestrator Configuration -## Overview +## Compatibility -The WinCertStore Orchestrator remotely manages certificates in a Windows Server local machine certificate store. Users are able to determine which store they wish to place certificates in by entering the correct store path. For a complete list of local machine cert stores you can execute the PowerShell command: +This integration is compatible with Keyfactor Universal Orchestrator version 10.1 and later. - Get-ChildItem Cert:\LocalMachine +## Support +The Windows Certificate Universal Orchestrator extension is supported by Keyfactor for Keyfactor customers. If you have a support issue, please open a support ticket with your Keyfactor representative. If you have a support issue, please open a support ticket via the Keyfactor Support Portal at https://support.keyfactor.com. + +> To report a problem or suggest a new feature, use the **[Issues](../../issues)** tab. If you want to contribute actual bug fixes or proposed enhancements, use the **[Pull requests](../../pulls)** tab. -The returned list will contain the actual certificate store name to be used when entering store location. +## Requirements & Prerequisites -By default, most certificates are stored in the “Personal” (My) and “Web Hosting” (WebHosting) stores. +Before installing the Windows Certificate Universal Orchestrator extension, we recommend that you install [kfutil](https://github.com/Keyfactor/kfutil). Kfutil is a command-line tool that simplifies the process of creating store types, installing extensions, and instantiating certificate stores in Keyfactor Command. -This extension implements four job types: Inventory, Management Add/Remove, and Reenrollment. -WinRM is used to remotely manage the certificate stores and IIS bindings. WinRM must be properly configured to allow the orchestrator on the server to manage the certificates. Setting up WinRM is not in the scope of this document. +### Security and Permission Considerations -**Note:** -In version 2.0 of the IIS Orchestrator, the certificate store type has been renamed and additional parameters have been added. Prior to 2.0 the certificate store type was called “IISBin” and as of 2.0 it is called “IISU”. If you have existing certificate stores of type “IISBin”, you have three options: -1. Leave them as is and continue to manage them with a pre 2.0 IIS Orchestrator Extension. Create the new IISU certificate store type and create any new IIS stores using the new type. -1. Delete existing IIS stores. Delete the IISBin store type. Create the new IISU store type. Recreate the IIS stores using the new IISU store type. -1. Convert existing IISBin certificate stores to IISU certificate stores. There is not currently a way to do this via the Keyfactor API, so direct updates to the underlying Keyfactor SQL database is required. A SQL script (IIS-Conversion.sql) is available in the repository to do this. Hosted customers, which do not have access to the underlying database, will need to work Keyfactor support to run the conversion. On-premises customers can run the script themselves, but are strongly encouraged to ensure that a SQL backup is taken prior running the script (and also be confident that they have a tested database restoration process.) - -**Note: There is an additional (and deprecated) certificate store type of “IIS” that ships with the Keyfactor platform. Migration of certificate stores from the “IIS” type to either the “IISBin” or “IISU” types is not currently supported.** - -**Note: If Looking to use GMSA Accounts to run the Service Keyfactor Command 10.2 or greater is required for No Value checkbox to work** - -## Security and Permission Considerations From an official support point of view, Local Administrator permissions are required on the target server. Some customers have been successful with using other accounts and granting rights to the underlying certificate and private key stores. Due to complexities with the interactions between Group Policy, WinRM, User Account Control, and other unpredictable customer environmental factors, Keyfactor cannot provide assistance with using accounts other than the local administrator account. For customers wishing to use something other than the local administrator account, the following information may be helpful: @@ -148,350 +144,545 @@ For customers wishing to use something other than the local administrator accoun - Access any Cryptographic Service Provider (CSP) referenced in re-enrollment jobs. - Read and Write values in the registry (HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server) when performing SQL Server certificate binding. -## Creating New Certificate Store Types -Currently this orchestrator handles three types of extensions: IISU for IIS servers with bound certificates, WinCert for general Windows Certificates and WinSql for managing certificates for SQL Server. -Below describes how each of these certificate store types are created and configured. -
- IISU Extension -**In Keyfactor Command create a new Certificate Store Type as specified below:** +## Create Certificate Store Types + +To use the Windows Certificate Universal Orchestrator extension, you **must** create the Certificate Store Types required for your usecase. This only needs to happen _once_ per Keyfactor Command instance. + +The Windows Certificate Universal Orchestrator extension implements 3 Certificate Store Types. Depending on your use case, you may elect to use one, or all of these Certificate Store Types. + +
Windows Certificate (WinCert) + -**Basic Settings:** +* **Create WinCert using kfutil**: -CONFIG ELEMENT | VALUE | DESCRIPTION ---|--|-- -Name | IIS Bound Certificate | Display name for the store type (may be customized) -Short Name| IISU | Short display name for the store type -Custom Capability | IISU | Store type name orchestrator will register with. Check the box to allow entry of value -Supported Job Types | Inventory, Add, Remove, Reenrollment | Job types the extension supports -Needs Server | Checked | Determines if a target server name is required when creating store -Blueprint Allowed | Unchecked | Determines if store type may be included in an Orchestrator blueprint -Uses PowerShell | Unchecked | Determines if underlying implementation is PowerShell -Requires Store Password | Unchecked | Determines if a store password is required when configuring an individual store. -Supports Entry Password | Unchecked | Determines if an individual entry within a store can have a password. + ```shell + # Windows Certificate + kfutil store-types create WinCert + ``` -![](images/IISUCertStoreBasic.png) +* **Create WinCert manually in the Command UI**: +
Create WinCert manually in the Command UI -**Advanced Settings:** + Create a store type called `WinCert` with the attributes in the tables below: -CONFIG ELEMENT | VALUE | DESCRIPTION ---|--|-- -Store Path Type | Multiple Choice | Determines what restrictions are applied to the store path field when configuring a new store. -Store Path Value | My,WebHosting | Comma separated list of options configure multiple choice. This, combined with the hostname, will determine the location used for the certificate store management and inventory. -Supports Custom Alias | Forbidden | Determines if an individual entry within a store can have a custom Alias. -Private Keys | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. -PFX Password Style | Default or Custom | "Default" - PFX password is randomly generated, "Custom" - PFX password may be specified when the enrollment job is created (Requires the *Allow Custom Password* application setting to be enabled.) + #### Basic Tab + | Attribute | Value | Description | + | --------- | ----- | ----- | + | Name | Windows Certificate | Display name for the store type (may be customized) | + | Short Name | WinCert | Short display name for the store type | + | Capability | WinCert | Store type name orchestrator will register with. Check the box to allow entry of value | + | Supports Add | ✅ Checked | Check the box. Indicates that the Store Type supports Management Add | + | Supports Remove | ✅ Checked | Check the box. Indicates that the Store Type supports Management Remove | + | Supports Discovery | 🔲 Unchecked | Indicates that the Store Type supports Discovery | + | Supports Reenrollment | ✅ Checked | Indicates that the Store Type supports Reenrollment | + | Supports Create | 🔲 Unchecked | Indicates that the Store Type supports store creation | + | Needs Server | ✅ Checked | Determines if a target server name is required when creating store | + | Blueprint Allowed | 🔲 Unchecked | Determines if store type may be included in an Orchestrator blueprint | + | Uses PowerShell | 🔲 Unchecked | Determines if underlying implementation is PowerShell | + | Requires Store Password | 🔲 Unchecked | Enables users to optionally specify a store password when defining a Certificate Store. | + | Supports Entry Password | 🔲 Unchecked | Determines if an individual entry within a store can have a password. | -![](images/IISUCertStoreAdv.png) + The Basic tab should look like this: -**Custom Fields:** + ![WinCert Basic Tab](docsource/images/WinCert-basic-store-type-dialog.png) -Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote -target server containing the certificate store to be managed + #### Advanced Tab + | Attribute | Value | Description | + | --------- | ----- | ----- | + | Supports Custom Alias | Forbidden | Determines if an individual entry within a store can have a custom Alias. | + | Private Key Handling | Optional | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | + | PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | -Name|Display Name|Type|Default Value / Options|Required|Description ----|---|---|---|---|--- -WinRm Protocol|WinRm Protocol|Multiple Choice| https,http |Yes|Protocol that target server WinRM listener is using -WinRm Port|WinRm Port|String|5986|Yes| Port that target server WinRM listener is using. Typically 5985 for HTTP and 5986 for HTTPS -spnwithport|SPN With Port|Bool|false|No|Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. -ServerUsername|Server Username|Secret||No|The username to log into the target server (This field is automatically created). Check the No Value Checkbox when using GMSA Accounts. -ServerPassword|Server Password|Secret||No|The password that matches the username to log into the target server (This field is automatically created). Check the No Value Checkbox when using GMSA Accounts. -ServerUseSsl|Use SSL|Bool|true|Yes|Determine whether the server uses SSL or not (This field is automatically created) + The Advanced tab should look like this: -*Note that some of the Names in the first column above have spaces and some do not, it is important to configure the Name field exactly as above.* + ![WinCert Advanced Tab](docsource/images/WinCert-advanced-store-type-dialog.png) + #### Custom Fields Tab + Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: -![](images/IISUCustomFields.png) + | Name | Display Name | Description | Type | Default Value/Options | Required | + | ---- | ------------ | ---- | --------------------- | -------- | ----------- | + | spnwithport | SPN With Port | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | Bool | false | 🔲 Unchecked | + | WinRM Protocol | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | MultipleChoice | https,http | ✅ Checked | + | WinRM Port | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | String | 5986 | ✅ Checked | + | ServerUsername | Server Username | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | Secret | | 🔲 Unchecked | + | ServerPassword | Server Password | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | Secret | | 🔲 Unchecked | + | ServerUseSsl | Use SSL | Determine whether the server uses SSL or not (This field is automatically created) | Bool | true | ✅ Checked | -**Entry Parameters:** + The Custom Fields tab should look like this: -Entry parameters are inventoried and maintained for each entry within a certificate store. -They are typically used to support binding of a certificate to a resource. + ![WinCert Custom Fields Tab](docsource/images/WinCert-custom-fields-store-type-dialog.png) -Name|Display Name| Type|Default Value|Required When|Description ----|---|---|---|---|--- -SiteName | IIS Site Name|String|Default Web Site|Adding, Removing, Reenrolling | IIS web site to bind certificate to -IPAddress | IP Address | String | * | Adding, Removing, Reenrolling | IP address to bind certificate to (use '*' for all IP addresses) -Port | Port | String | 443 || Adding, Removing, Reenrolling|IP port for bind certificate to -HostName | Host Name | String |||| Host name (host header) to bind certificate to, leave blank for all host names -SniFlag | SNI Support | Multiple Choice | 0 - No SNI||Type of SNI for binding
(Multiple choice configuration should be entered as "0 - No SNI,1 - SNI Enabled,2 - Non SNI Binding,3 - SNI Binding") -Protocol | Protocol | Multiple Choice | https| Adding, Removing, Reenrolling|Protocol to bind to (always "https").
(Multiple choice configuration should be "https") -ProviderName | Crypto Provider Name | String ||| Name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing the private keys. If not specified, defaults to 'Microsoft Strong Cryptographic Provider'. This value would typically be specified when leveraging a Hardware Security Module (HSM). The specified cryptographic provider must be available on the target server being managed. The list of installed cryptographic providers can be obtained by running 'certutil -csplist' on the target Server. -SAN | SAN | String || Reenrolling | Specifies Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Certificate templates generally require a SAN that matches the subject of the certificate (per RFC 2818). Format is a list of = entries separated by ampersands. Examples: 'dns=www.mysite.com' for a single SAN or 'dns=www.mysite.com&dns=www.mysite2.com' for multiple SANs. Can be made optional if RFC 2818 is disabled on the CA. -None of the above entry parameters have the "Depends On" field set. -![](images/IISUEntryParams.png) + #### Entry Parameters Tab -Click Save to save the Certificate Store Type. + | Name | Display Name | Description | Type | Default Value | Entry has a private key | Adding an entry | Removing an entry | Reenrolling an entry | + | ---- | ------------ | ---- | ------------- | ----------------------- | ---------------- | ----------------- | ------------------- | ----------- | + | ProviderName | Crypto Provider Name | Name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing the private keys. If not specified, defaults to 'Microsoft Strong Cryptographic Provider'. This value would typically be specified when leveraging a Hardware Security Module (HSM). The specified cryptographic provider must be available on the target server being managed. The list of installed cryptographic providers can be obtained by running 'certutil -csplist' on the target Server. | String | | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | + | SAN | SAN | String value specifying the Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Format as a list of = entries separated by ampersands; Example: 'dns=www.example.com&dns=www.example2.com' for multiple SANs. Can be made optional if RFC 2818 is disabled on the CA. | String | | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | ✅ Checked | + The Entry Parameters tab should look like this: + + ![WinCert Entry Parameters Tab](docsource/images/WinCert-entry-parameters-store-type-dialog.png) + + + +
-
- SQL Server Extension -**In Keyfactor Command create a new Certificate Store Type as specified below:** +
IIS Bound Certificate (IISU) + + +* **Create IISU using kfutil**: + + ```shell + # IIS Bound Certificate + kfutil store-types create IISU + ``` + +* **Create IISU manually in the Command UI**: +
Create IISU manually in the Command UI + + Create a store type called `IISU` with the attributes in the tables below: -**Basic Settings:** + #### Basic Tab + | Attribute | Value | Description | + | --------- | ----- | ----- | + | Name | IIS Bound Certificate | Display name for the store type (may be customized) | + | Short Name | IISU | Short display name for the store type | + | Capability | IISU | Store type name orchestrator will register with. Check the box to allow entry of value | + | Supports Add | ✅ Checked | Check the box. Indicates that the Store Type supports Management Add | + | Supports Remove | ✅ Checked | Check the box. Indicates that the Store Type supports Management Remove | + | Supports Discovery | 🔲 Unchecked | Indicates that the Store Type supports Discovery | + | Supports Reenrollment | ✅ Checked | Indicates that the Store Type supports Reenrollment | + | Supports Create | 🔲 Unchecked | Indicates that the Store Type supports store creation | + | Needs Server | ✅ Checked | Determines if a target server name is required when creating store | + | Blueprint Allowed | 🔲 Unchecked | Determines if store type may be included in an Orchestrator blueprint | + | Uses PowerShell | 🔲 Unchecked | Determines if underlying implementation is PowerShell | + | Requires Store Password | 🔲 Unchecked | Enables users to optionally specify a store password when defining a Certificate Store. | + | Supports Entry Password | 🔲 Unchecked | Determines if an individual entry within a store can have a password. | -CONFIG ELEMENT | VALUE | DESCRIPTION ---|--|-- -Name | Windows SQL Server Certificate| Display name for the store type (may be customized) -Short Name| WinSql | Short display name for the store type -Custom Capability | Leave Unchecked | Store type name orchestrator will register with. Check the box to allow entry of value -Supported Job Types | Inventory, Add, Remove, Reenrollment | Job types the extension supports -Needs Server | Checked | Determines if a target server name is required when creating store -Blueprint Allowed | Checked | Determines if store type may be included in an Orchestrator blueprint -Uses PowerShell | Unchecked | Determines if underlying implementation is PowerShell -Requires Store Password | Unchecked | Determines if a store password is required when configuring an individual store. -Supports Entry Password | Unchecked | Determines if an individual entry within a store can have a password. + The Basic tab should look like this: -![](images/SQLServerCertStoreBasic.png) + ![IISU Basic Tab](docsource/images/IISU-basic-store-type-dialog.png) -**Advanced Settings:** + #### Advanced Tab + | Attribute | Value | Description | + | --------- | ----- | ----- | + | Supports Custom Alias | Forbidden | Determines if an individual entry within a store can have a custom Alias. | + | Private Key Handling | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | + | PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | -CONFIG ELEMENT | VALUE | DESCRIPTION ---|--|-- -Store Path Type | Fixed | Fixed to a defined path. SQL Server Supports the Personal or "My" store on the Local Machine. -Store Path Value | My | Fixed Value My on the Local Machine Store. -Supports Custom Alias | Forbidden | Determines if an individual entry within a store can have a custom Alias. -Private Keys | Required | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because SQL Server certificates without private keys would be useless. -PFX Password Style | Default or Custom | "Default" - PFX password is randomly generated, "Custom" - PFX password may be specified when the enrollment job is created (Requires the *Allow Custom Password* application setting to be enabled.) + The Advanced tab should look like this: -![](images/SQLServerCertStoreAdvanced.png) + ![IISU Advanced Tab](docsource/images/IISU-advanced-store-type-dialog.png) -**Custom Fields:** + #### Custom Fields Tab + Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: -Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote -target server containing the certificate store to be managed + | Name | Display Name | Description | Type | Default Value/Options | Required | + | ---- | ------------ | ---- | --------------------- | -------- | ----------- | + | spnwithport | SPN With Port | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | Bool | false | 🔲 Unchecked | + | WinRM Protocol | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | MultipleChoice | https,http | ✅ Checked | + | WinRM Port | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | String | 5986 | ✅ Checked | + | ServerUsername | Server Username | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | Secret | | 🔲 Unchecked | + | ServerPassword | Server Password | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | Secret | | 🔲 Unchecked | + | ServerUseSsl | Use SSL | Determine whether the server uses SSL or not (This field is automatically created) | Bool | true | ✅ Checked | -Name|Display Name|Type|Default Value / Options|Required|Description ----|---|---|---|---|--- -WinRm Protocol|WinRm Protocol|Multiple Choice| https,http |Yes|Protocol that target server WinRM listener is using -WinRm Port|WinRm Port|String|5986|Yes| Port that target server WinRM listener is using. Typically 5985 for HTTP and 5986 for HTTPS -spnwithport|SPN With Port|Bool|false|No|Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. -ServerUsername|Server Username|Secret||No|The username to log into the target server (This field is automatically created). Check the No Value Checkbox when using GMSA Accounts. -ServerPassword|Server Password|Secret||No|The password that matches the username to log into the target server (This field is automatically created). Check the No Value Checkbox when using GMSA Accounts. -ServerUseSsl|Use SSL|Bool|true|Yes|Determine whether the server uses SSL or not (This field is automatically created) -RestartService|Restart SQL Service After Cert Installed|Bool|False|Yes|If true, Orchestrator will restart the SQL Server Service after installing the certificate. + The Custom Fields tab should look like this: + ![IISU Custom Fields Tab](docsource/images/IISU-custom-fields-store-type-dialog.png) -*Note that some of the Names in the first column above have spaces and some do not, it is important to configure the Name field exactly as above.* -![](images/SQLServerCustomFields.png) + #### Entry Parameters Tab -**Entry Parameters:** + | Name | Display Name | Description | Type | Default Value | Entry has a private key | Adding an entry | Removing an entry | Reenrolling an entry | + | ---- | ------------ | ---- | ------------- | ----------------------- | ---------------- | ----------------- | ------------------- | ----------- | + | Port | Port | String value specifying the IP port to bind the certificate to for the IIS site. Example: '443' for HTTPS. | String | 443 | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | + | IPAddress | IP Address | String value specifying the IP address to bind the certificate to for the IIS site. Example: '*' for all IP addresses or '192.168.1.1' for a specific IP address. | String | * | 🔲 Unchecked | ✅ Checked | ✅ Checked | ✅ Checked | + | HostName | Host Name | String value specifying the host name (host header) to bind the certificate to for the IIS site. Leave blank for all host names or enter a specific hostname such as 'www.example.com'. | String | | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | + | SiteName | IIS Site Name | String value specifying the name of the IIS web site to bind the certificate to. Example: 'Default Web Site' or any custom site name such as 'MyWebsite'. | String | Default Web Site | 🔲 Unchecked | ✅ Checked | ✅ Checked | ✅ Checked | + | SniFlag | SSL Flags | A 128-Bit Flag that determines what type of SSL settings you wish to use. The default is 0, meaning No SNI. For more information, check IIS documentation for the appropriate bit setting.) | String | 0 | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | + | Protocol | Protocol | Multiple choice value specifying the protocol to bind to. Example: 'https' for secure communication. | MultipleChoice | https | 🔲 Unchecked | ✅ Checked | ✅ Checked | ✅ Checked | + | ProviderName | Crypto Provider Name | Name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing the private keys. If not specified, defaults to 'Microsoft Strong Cryptographic Provider'. This value would typically be specified when leveraging a Hardware Security Module (HSM). The specified cryptographic provider must be available on the target server being managed. The list of installed cryptographic providers can be obtained by running 'certutil -csplist' on the target Server. | String | | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | + | SAN | SAN | String value specifying the Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Format as a list of = entries separated by ampersands; Example: 'dns=www.example.com&dns=www.example2.com' for multiple SANs. Can be made optional if RFC 2818 is disabled on the CA. | String | | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | ✅ Checked | -Entry parameters are inventoried and maintained for each entry within a certificate store. -They are typically used to support binding of a certificate to a resource. + The Entry Parameters tab should look like this: -Name|Display Name| Type|Default Value|Required When|Description ----|---|---|---|---|--- -InstanceName | Instance Name|String||Not required | When enrolling leave blank or use MSSQLServer for the Default Instance, Instance Name for an Instance or MSSQLServer,Instance Name if enrolling to multiple instances plus the default instance. -ProviderName | Crypto Provider Name | String ||| Name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing the private keys. If not specified, defaults to 'Microsoft Strong Cryptographic Provider'. This value would typically be specified when leveraging a Hardware Security Module (HSM). The specified cryptographic provider must be available on the target server being managed. The list of installed cryptographic providers can be obtained by running 'certutil -csplist' on the target Server. -SAN | SAN | String || Reenrolling | Specifies Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Certificate templates generally require a SAN that matches the subject of the certificate (per RFC 2818). Format is a list of = entries separated by ampersands. Examples: 'dns=www.mysite.com' for a single SAN or 'dns=www.mysite.com&dns=www.mysite2.com' for multiple SANs. Can be made optional if RFC 2818 is disabled on the CA. + ![IISU Entry Parameters Tab](docsource/images/IISU-entry-parameters-store-type-dialog.png) -![](images/SQLServerEntryParams.png) -Click Save to save the Certificate Store Type. +
-
- WinCert Extension -**1. In Keyfactor Command create a new Certificate Store Type using the settings below** +
WinSql (WinSql) -**Basic Settings:** -CONFIG ELEMENT | VALUE | DESCRIPTION ---|--|-- -Name | Windows Certificate | Display name for the store type (may be customized) -Short Name| WinCert | Short display name for the store type -Custom Capability | WinCert | Store type name orchestrator will register with. Check the box to allow entry of value -Supported Job Types | Inventory, Add, Remove, Reenrollment | Job types the extension supports -Needs Server | Checked | Determines if a target server name is required when creating store -Blueprint Allowed | Unchecked | Determines if store type may be included in an Orchestrator blueprint -Uses PowerShell | Unchecked | Determines if underlying implementation is PowerShell -Requires Store Password | Unchecked | Determines if a store password is required when configuring an individual store. -Supports Entry Password | Unchecked | Determines if an individual entry within a store can have a password. +* **Create WinSql using kfutil**: -![](images/WinCertBasic.png) + ```shell + # WinSql + kfutil store-types create WinSql + ``` -**Advanced Settings:** +* **Create WinSql manually in the Command UI**: +
Create WinSql manually in the Command UI -CONFIG ELEMENT | VALUE | DESCRIPTION ---|--|-- -Store Path Type | Freeform | Allows users to type in a valid certificate store. -Supports Custom Alias | Forbidden | Determines if an individual entry within a store can have a custom Alias. -Private Keys | Optional | This determines if Keyfactor can send the private key associated with a certificate to the store. Typically the personal store would have private keys, whereas trusted root would not. -PFX Password Style | Default or Custom | "Default" - PFX password is randomly generated, "Custom" - PFX password may be specified when the enrollment job is created (Requires the *Allow Custom Password* application setting to be enabled.) + Create a store type called `WinSql` with the attributes in the tables below: -![](images/WinCertAdvanced.png) + #### Basic Tab + | Attribute | Value | Description | + | --------- | ----- | ----- | + | Name | WinSql | Display name for the store type (may be customized) | + | Short Name | WinSql | Short display name for the store type | + | Capability | WinSql | Store type name orchestrator will register with. Check the box to allow entry of value | + | Supports Add | ✅ Checked | Check the box. Indicates that the Store Type supports Management Add | + | Supports Remove | ✅ Checked | Check the box. Indicates that the Store Type supports Management Remove | + | Supports Discovery | 🔲 Unchecked | Indicates that the Store Type supports Discovery | + | Supports Reenrollment | 🔲 Unchecked | Indicates that the Store Type supports Reenrollment | + | Supports Create | 🔲 Unchecked | Indicates that the Store Type supports store creation | + | Needs Server | ✅ Checked | Determines if a target server name is required when creating store | + | Blueprint Allowed | ✅ Checked | Determines if store type may be included in an Orchestrator blueprint | + | Uses PowerShell | 🔲 Unchecked | Determines if underlying implementation is PowerShell | + | Requires Store Password | 🔲 Unchecked | Enables users to optionally specify a store password when defining a Certificate Store. | + | Supports Entry Password | 🔲 Unchecked | Determines if an individual entry within a store can have a password. | -**Custom Fields:** + The Basic tab should look like this: -Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed + ![WinSql Basic Tab](docsource/images/WinSql-basic-store-type-dialog.png) -Name|Display Name|Type|Default Value / Options|Required|Description ----|---|---|---|---|--- -WinRm Protocol|WinRm Protocol|Multiple Choice| https,http |Yes|Protocol that target server WinRM listener is using -WinRm Port|WinRm Port|String|5986|Yes| Port that target server WinRM listener is using. Typically 5985 for HTTP and 5986 for HTTPS -spnwithport|SPN With Port|Bool|false|No|Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. -ServerUsername|Server Username|Secret||No|The username to log into the target server (This field is automatically created) -ServerPassword|Server Password|Secret||No|The password that matches the username to log into the target server (This field is automatically created) -ServerUseSsl|Use SSL|Bool|True|Yes|Determine whether the server uses SSL or not (This field is automatically created) + #### Advanced Tab + | Attribute | Value | Description | + | --------- | ----- | ----- | + | Supports Custom Alias | Forbidden | Determines if an individual entry within a store can have a custom Alias. | + | Private Key Handling | Optional | This determines if Keyfactor can send the private key associated with a certificate to the store. Required because IIS certificates without private keys would be invalid. | + | PFX Password Style | Default | 'Default' - PFX password is randomly generated, 'Custom' - PFX password may be specified when the enrollment job is created (Requires the Allow Custom Password application setting to be enabled.) | -*Note that some of the Names in the first column above have spaces and some do not, it is important to configure the Name field exactly as above.* + The Advanced tab should look like this: -![](images/WinCertCustom.png) + ![WinSql Advanced Tab](docsource/images/WinSql-advanced-store-type-dialog.png) -**Entry Parameters:** + #### Custom Fields Tab + Custom fields operate at the certificate store level and are used to control how the orchestrator connects to the remote target server containing the certificate store to be managed. The following custom fields should be added to the store type: -Entry parameters are inventoried and maintained for each entry within a certificate store. -They are typically used to support binding of a certificate to a resource. -For the WinCert store type they are used to control how reenrollment jobs are performed. + | Name | Display Name | Description | Type | Default Value/Options | Required | + | ---- | ------------ | ---- | --------------------- | -------- | ----------- | + | spnwithport | SPN With Port | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | Bool | false | 🔲 Unchecked | + | WinRM Protocol | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | MultipleChoice | https,http | ✅ Checked | + | WinRM Port | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | String | 5986 | ✅ Checked | + | ServerUsername | Server Username | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | Secret | | 🔲 Unchecked | + | ServerPassword | Server Password | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | Secret | | 🔲 Unchecked | + | ServerUseSsl | Use SSL | Determine whether the server uses SSL or not (This field is automatically created) | Bool | true | ✅ Checked | + | RestartService | Restart SQL Service After Cert Installed | Boolean value (true or false) indicating whether to restart the SQL Server service after installing the certificate. Example: 'true' to enable service restart after installation. | Bool | false | ✅ Checked | -Name|Display Name| Type|Default Value|Required When|Description ----|---|---|---|---|--- -ProviderName | Crypto Provider Name | String ||| Name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing the private keys. If not specified, defaults to 'Microsoft Strong Cryptographic Provider'. This value would typically be specified when leveraging a Hardware Security Module (HSM). The specified cryptographic provider must be available on the target server being managed. The list of installed cryptographic providers can be obtained by running 'certutil -csplist' on the target Server. -SAN | SAN | String || Reenrolling | Specifies Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Certificate templates generally require a SAN that matches the subject of the certificate (per RFC 2818). Format is a list of = entries separated by ampersands. Examples: 'dns=www.mysite.com' for a single SAN or 'dns=www.mysite.com&dns=www.mysite2.com' for multiple SANs. Can be made optional if RFC 2818 is disabled on the CA. + The Custom Fields tab should look like this: -None of the above entry parameters have the "Depends On" field set. + ![WinSql Custom Fields Tab](docsource/images/WinSql-custom-fields-store-type-dialog.png) -![](images/WinCertEntryParams.png) -Click Save to save the Certificate Store Type. -
+ #### Entry Parameters Tab + | Name | Display Name | Description | Type | Default Value | Entry has a private key | Adding an entry | Removing an entry | Reenrolling an entry | + | ---- | ------------ | ---- | ------------- | ----------------------- | ---------------- | ----------------- | ------------------- | ----------- | + | InstanceName | Instance Name | String value specifying the SQL Server instance name to bind the certificate to. Example: 'MSSQLServer' for the default instance or 'Instance1' for a named instance. | String | | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | + | ProviderName | Crypto Provider Name | Optional string value specifying the name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing private keys. Example: 'Microsoft Strong Cryptographic Provider'. | String | | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | + | SAN | SAN | String value specifying the Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Format as a list of = entries separated by ampersands; Example: 'dns=www.example.com&dns=www.example2.com' for multiple SANs. | String | | 🔲 Unchecked | 🔲 Unchecked | 🔲 Unchecked | ✅ Checked | -## Creating New Certificate Stores -Once the Certificate Store Types have been created, you need to create the Certificate Stores prior to using the extension. + The Entry Parameters tab should look like this: -### Note Regarding Client Machine -If running as an agent (accessing stores on the server where the Universal Orchestrator Services is installed ONLY), the Client Machine can be entered, OR you can bypass a WinRM connection and access the local file system directly by adding "|LocalMachine" to the end of your value for Client Machine, for example "1.1.1.1|LocalMachine". In this instance the value to the left of the pipe (|) is ignored. It is important to make sure the values for Client Machine and Store Path together are unique for each certificate store created, as Keyfactor Command requires the Store Type you select, along with Client Machine, and Store Path together must be unique. To ensure this, it is good practice to put the full DNS or IP Address to the left of the | character when setting up a certificate store that will be accessed without a WinRM connection. + ![WinSql Entry Parameters Tab](docsource/images/WinSql-entry-parameters-store-type-dialog.png) -Here are the settings required for each Store Type previously configured. -
-IISU Certificate Store - -In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the settings defined below. - -#### STORE CONFIGURATION -CONFIG ELEMENT |DESCRIPTION -----------------|--------------- -Category | Select IIS Bound Certificate or the customized certificate store display name from above. -Container | Optional container to associate certificate store with. -Client Machine | Contains the Hostname of the Windows Server containing the certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. -Store Path | Windows certificate store to manage. Choose "My" for the Personal Store or "WebHosting" for the Web Hosting Store. -Orchestrator | Select an approved orchestrator capable of managing IIS Bound Certificates (one that has declared the IISU capability) -WinRm Protocol | Protocol to use when establishing the WinRM session. (Listener on Client Machine must be configured for selected protocol.) -WinRm Port | Port WinRM listener is configured for (HTTPS default is 5986) -SPN with Port | Typically False. Needed in some Kerberos configurations. -Server Username | Account to use when establishing the WinRM session to the Client Machine. Account needs to be an administrator or have been granted rights to manage IIS configuration and manipulate the local machine certificate store. If no account is specified, the security context of the Orchestrator service account will be used. -Server Password | Password to use when establishing the WinRM session to the Client Machine -Use SSL | Ignored for this certificate store type. Transport encryption is determined by the WinRM Protocol Setting -Inventory Schedule | The interval that the system will use to report on what certificates are currently in the store. - -![](images/IISUAddCertStore.png) - -Click Save to save the settings for this Certificate Store -
-
-SQL Server Certificate Store - -In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the settings defined below. - -#### STORE CONFIGURATION -CONFIG ELEMENT |DESCRIPTION -----------------|--------------- -Category | Select SQL Server Bound Certificate or the customized certificate store display name from above. -Container | Optional container to associate certificate store with. -Client Machine | Hostname of the Windows Server containing the certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. -Store Path | Windows certificate store to manage. Fixed to "My". -Orchestrator | Select an approved orchestrator capable of managing SQL Server Bound Certificates. -WinRm Protocol | Protocol to use when establishing the WinRM session. (Listener on Client Machine must be configured for selected protocol.) -WinRm Port | Port WinRM listener is configured for (HTTPS default is 5986) -SPN with Port | Typically False. Needed in some Kerberos configurations. -Server Username | Account to use when establishing the WinRM session to the Client Machine. Account needs to be an administrator or have been granted rights to manage IIS configuration and manipulate the local machine certificate store. If no account is specified, the security context of the Orchestrator service account will be used. -Server Password | Password to use when establishing the WinRM session to the Client Machine -Restart SQL Service After Cert Installed | For each instance the certificate is tied to, the service for that instance will be restarted after the certificate is successfully installed. -Use SSL | Ignored for this certificate store type. Transport encryption is determined by the WinRM Protocol Setting -Inventory Schedule | The interval that the system will use to report on what certificates are currently in the store. - -![](images/SQLServerAddCertStore.png) - -Click Save to save the settings for this Certificate Store +
-
-WinCert Certificate Store -In Keyfactor Command, navigate to Certificate Stores from the Locations Menu. Click the Add button to create a new Certificate Store using the settings defined below. - - -#### STORE CONFIGURATION -CONFIG ELEMENT |DESCRIPTION -----------------|--------------- -Category | Select Windows Certificate or the customized certificate store display name from above. -Container | Optional container to associate certificate store with. -Client Machine | Hostname of the Windows Server containing the certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. -Store Path | Windows certificate store to manage. Store must exist in the Local Machine store on the target server. -Orchestrator | Select an approved orchestrator capable of managing Windows Certificates (one that has declared the WinCert capability) -WinRm Protocol | Protocol to use when establishing the WinRM session. (Listener on Client Machine must be configured for selected protocol.) -WinRm Port | Port WinRM listener is configured for (HTTPS default is 5986) -SPN with Port | Typically False. Needed in some Kerberos configurations. -Server Username | Account to use when establishing the WinRM session to the Client Machine. Account needs to be an admin or have been granted rights to manipulate the local machine certificate store. If no account is specified, the security context of the Orchestrator service account will be used. -Server Password | Password to use when establishing the WinRM session to the Client Machine -Use SSL | Ignored for this certificate store type. Transport encryption is determined by the WinRM Protocol Setting -Inventory Schedule | The interval that the system will use to report on what certificates are currently in the store. - -![](images/WinCertAddCertStore.png) + + +## Installation + +1. **Download the latest Windows Certificate Universal Orchestrator extension from GitHub.** + + Navigate to the [Windows Certificate Universal Orchestrator extension GitHub version page](https://github.com/Keyfactor/iis-orchestrator/releases/latest). Refer to the compatibility matrix below to determine whether the `net6.0` or `net8.0` asset should be downloaded. Then, click the corresponding asset to download the zip archive. + | Universal Orchestrator Version | Latest .NET version installed on the Universal Orchestrator server | `rollForward` condition in `Orchestrator.runtimeconfig.json` | `iis-orchestrator` .NET version to download | + | --------- | ----------- | ----------- | ----------- | + | Older than `11.0.0` | | | `net6.0` | + | Between `11.0.0` and `11.5.1` (inclusive) | `net6.0` | | `net6.0` | + | Between `11.0.0` and `11.5.1` (inclusive) | `net8.0` | `Disable` | `net6.0` | + | Between `11.0.0` and `11.5.1` (inclusive) | `net8.0` | `LatestMajor` | `net8.0` | + | `11.6` _and_ newer | `net8.0` | | `net8.0` | + + Unzip the archive containing extension assemblies to a known location. + + > **Note** If you don't see an asset with a corresponding .NET version, you should always assume that it was compiled for `net6.0`. + +2. **Locate the Universal Orchestrator extensions directory.** + + * **Default on Windows** - `C:\Program Files\Keyfactor\Keyfactor Orchestrator\extensions` + * **Default on Linux** - `/opt/keyfactor/orchestrator/extensions` + +3. **Create a new directory for the Windows Certificate Universal Orchestrator extension inside the extensions directory.** + + Create a new directory called `iis-orchestrator`. + > The directory name does not need to match any names used elsewhere; it just has to be unique within the extensions directory. + +4. **Copy the contents of the downloaded and unzipped assemblies from __step 2__ to the `iis-orchestrator` directory.** + +5. **Restart the Universal Orchestrator service.** + + Refer to [Starting/Restarting the Universal Orchestrator service](https://software.keyfactor.com/Core-OnPrem/Current/Content/InstallingAgents/NetCoreOrchestrator/StarttheService.htm). + + + +> The above installation steps can be supplimented by the [official Command documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/InstallingAgents/NetCoreOrchestrator/CustomExtensions.htm?Highlight=extensions). + + + +## Defining Certificate Stores + +The Windows Certificate Universal Orchestrator extension implements 3 Certificate Store Types, each of which implements different functionality. Refer to the individual instructions below for each Certificate Store Type that you deemed necessary for your use case from the installation section. + +
Windows Certificate (WinCert) + + +* **Manually with the Command UI** + +
Create Certificate Stores manually in the UI + + 1. **Navigate to the _Certificate Stores_ page in Keyfactor Command.** + + Log into Keyfactor Command, toggle the _Locations_ dropdown, and click _Certificate Stores_. + + 2. **Add a Certificate Store.** + + Click the Add button to add a new Certificate Store. Use the table below to populate the **Attributes** in the **Add** form. + | Attribute | Description | + | --------- | ----------- | + | Category | Select "Windows Certificate" or the customized certificate store name from the previous step. | + | Container | Optional container to associate certificate store with. | + | Client Machine | Hostname of the Windows Server containing the certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine). | + | Store Path | Windows certificate store path to manage. The store must exist in the Local Machine store on the target server, e.g., 'My' for the Personal Store or 'Root' for the Trusted Root Certification Authorities Store. | + | Orchestrator | Select an approved orchestrator capable of managing `WinCert` certificates. Specifically, one with the `WinCert` capability. | + | spnwithport | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | + | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | + | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | + | ServerUsername | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | + | ServerPassword | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | + | ServerUseSsl | Determine whether the server uses SSL or not (This field is automatically created) | + + + + +
+ +* **Using kfutil** + +
Create Certificate Stores with kfutil + + 1. **Generate a CSV template for the WinCert certificate store** + + ```shell + kfutil stores import generate-template --store-type-name WinCert --outpath WinCert.csv + ``` + 2. **Populate the generated CSV file** + + Open the CSV file, and reference the table below to populate parameters for each **Attribute**. + | Attribute | Description | + | --------- | ----------- | + | Category | Select "Windows Certificate" or the customized certificate store name from the previous step. | + | Container | Optional container to associate certificate store with. | + | Client Machine | Hostname of the Windows Server containing the certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine). | + | Store Path | Windows certificate store path to manage. The store must exist in the Local Machine store on the target server, e.g., 'My' for the Personal Store or 'Root' for the Trusted Root Certification Authorities Store. | + | Orchestrator | Select an approved orchestrator capable of managing `WinCert` certificates. Specifically, one with the `WinCert` capability. | + | spnwithport | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | + | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | + | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | + | ServerUsername | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | + | ServerPassword | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | + | ServerUseSsl | Determine whether the server uses SSL or not (This field is automatically created) | + + + + + 3. **Import the CSV file to create the certificate stores** + + ```shell + kfutil stores import csv --store-type-name WinCert --file WinCert.csv + ``` +
+ +> The content in this section can be supplimented by the [official Command documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/ReferenceGuide/Certificate%20Stores.htm?Highlight=certificate%20store). +
+
IIS Bound Certificate (IISU) + + +* **Manually with the Command UI** + +
Create Certificate Stores manually in the UI + + 1. **Navigate to the _Certificate Stores_ page in Keyfactor Command.** + + Log into Keyfactor Command, toggle the _Locations_ dropdown, and click _Certificate Stores_. + + 2. **Add a Certificate Store.** + + Click the Add button to add a new Certificate Store. Use the table below to populate the **Attributes** in the **Add** form. + | Attribute | Description | + | --------- | ----------- | + | Category | Select "IIS Bound Certificate" or the customized certificate store name from the previous step. | + | Container | Optional container to associate certificate store with. | + | Client Machine | Hostname of the Windows Server containing the IIS certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine). | + | Store Path | Windows certificate store path to manage. Choose 'My' for the Personal store or 'WebHosting' for the Web Hosting store. | + | Orchestrator | Select an approved orchestrator capable of managing `IISU` certificates. Specifically, one with the `IISU` capability. | + | spnwithport | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | + | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | + | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | + | ServerUsername | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | + | ServerPassword | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | + | ServerUseSsl | Determine whether the server uses SSL or not (This field is automatically created) | + + + + +
+ +* **Using kfutil** + +
Create Certificate Stores with kfutil + + 1. **Generate a CSV template for the IISU certificate store** + + ```shell + kfutil stores import generate-template --store-type-name IISU --outpath IISU.csv + ``` + 2. **Populate the generated CSV file** + + Open the CSV file, and reference the table below to populate parameters for each **Attribute**. + | Attribute | Description | + | --------- | ----------- | + | Category | Select "IIS Bound Certificate" or the customized certificate store name from the previous step. | + | Container | Optional container to associate certificate store with. | + | Client Machine | Hostname of the Windows Server containing the IIS certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine). | + | Store Path | Windows certificate store path to manage. Choose 'My' for the Personal store or 'WebHosting' for the Web Hosting store. | + | Orchestrator | Select an approved orchestrator capable of managing `IISU` certificates. Specifically, one with the `IISU` capability. | + | spnwithport | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | + | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | + | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | + | ServerUsername | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | + | ServerPassword | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | + | ServerUseSsl | Determine whether the server uses SSL or not (This field is automatically created) | + + + + + 3. **Import the CSV file to create the certificate stores** + + ```shell + kfutil stores import csv --store-type-name IISU --file IISU.csv + ``` +
+ +> The content in this section can be supplimented by the [official Command documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/ReferenceGuide/Certificate%20Stores.htm?Highlight=certificate%20store). -## Test Cases -
-IISU - -Case Number|Case Name|Enrollment Params|Expected Results|Passed|Screenshot -----|------------------------|------------------------------------|--------------|----------------|------------------------- -1 |New Cert Enrollment To New Binding With KFSecret Creds|**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsite.com
**Sni Flag:** 0 - No SNI
**Protocol:** https|New Binding Created with Enrollment Params specified creds pulled from KFSecret|True|![](images/TestCase1Results.gif) -2 |New Cert Enrollment To Existing Binding|**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsite.com
**Sni Flag:** 0 - No SNI
**Protocol:** https|Existing Binding From Case 1 Updated with New Cert|True|![](images/TestCase2Results.gif) -3 |New Cert Enrollment To Existing Binding Enable SNI |**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsite.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|Will Update Site In Case 2 to Have Sni Enabled|True|![](images/TestCase3Results.gif) -4 |New Cert Enrollment New IP Address|**Site Name:** FirstSite
**Port:** 443
**IP Address:**`192.168.58.162`
**Host Name:** www.firstsite.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|New Binding Created With New IP and New SNI on Same Port|True|![](images/TestCase4Results.gif) -5 |New Cert Enrollment New Host Name|**Site Name:** FirstSite
**Port:** 443
**IP Address:**`192.168.58.162`
**Host Name:** www.newhostname.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|New Binding Created With different host on Same Port and IP Address|True|![](images/TestCase5Results.gif) -6 |New Cert Enrollment Same Site New Port |**Site Name:** FirstSite
**Port:** 4443
**IP Address:**`192.168.58.162`
**Host Name:** www.newhostname.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|New Binding on different port will be created with new cert enrolled|True|![](images/TestCase6Results.gif) -7 |Remove Cert and Binding From Test Case 6|**Site Name:** FirstSite
**Port:** 4443
**IP Address:**`192.168.58.162`
**Host Name:** www.newhostname.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|Cert and Binding From Test Case 6 Removed|True|![](images/TestCase7Results.gif) -8 |Renew Same Cert on 2 Different Sites|`SITE 1`
**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsite.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https
`SITE 2`
**First Site**
**Site Name:** SecondSite
**Port:** 443
**IP Address:**`*`
**Host Name:** cstiis04.cstpki.int
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|Cert will be renewed on both sites because it has the same thumbprint|True|![](images/TestCase8Site1.gif)![](images/TestCase8Site2.gif) -9 |Renew Same Cert on Same Site Same Binding Settings Different Hostname|`BINDING 1`
**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsitebinding1.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https
`BINDING 2`
**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsitebinding2.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|Cert will be renewed on both bindings because it has the same thumbprint|True|![](images/TestCase9Binding1.gif)![](images/TestCase9Binding2.gif) -10 |Renew Single Cert on Same Site Same Binding Settings Different Hostname Different Certs|`BINDING 1`
**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsitebinding1.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https
`BINDING 2`
**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsitebinding2.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|Cert will be renewed on only one binding because the other binding does not match thumbprint|True|![](images/TestCase10Binding1.gif)![](images/TestCase10Binding2.gif) -11 |Renew Same Cert on Same Site Same Binding Settings Different IPs|`BINDING 1`
**Site Name:** FirstSite
**Port:** 443
**IP Address:**`192.168.58.162`
**Host Name:** www.firstsitebinding1.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https
`BINDING 2`
**Site Name:** FirstSite
**Port:** 443
**IP Address:**`192.168.58.160`
**Host Name:** www.firstsitebinding1.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|Cert will be renewed on both bindings because it has the same thumbprint|True|![](images/TestCase11Binding1.gif)![](images/TestCase11Binding2.gif) -12 |Renew Same Cert on Same Site Same Binding Settings Different Ports|`BINDING 1`
**Site Name:** FirstSite
**Port:** 443
**IP Address:**`192.168.58.162`
**Host Name:** www.firstsitebinding1.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https
`BINDING 2`
**Site Name:** FirstSite
**Port:** 543
**IP Address:**`192.168.58.162`
**Host Name:** www.firstsitebinding1.com
**Sni Flag:** 1 - SNI Enabled
**Protocol:** https|Cert will be renewed on both bindings because it has the same thumbprint|True|![](images/TestCase12Binding1.gif)![](images/TestCase12Binding2.gif) -13 |ReEnrollment to Fortanix HSM|**Subject Name:** cn=www.mysite.com
**Port:** 433
**IP Address:**`*`
**Host Name:** mysite.command.local
**Site Name:**Default Web Site
**Sni Flag:** 0 - No SNI
**Protocol:** https
**Provider Name:** Fortanix KMS CNG Provider
**SAN:** dns=www.mysite.com&dns=mynewsite.com|Cert will be generated with keys stored in Fortanix HSM and the cert will be bound to the supplied site.|true|![](images/ReEnrollment1a.png)![](images/ReEnrollment1b.png) -14 |New Cert Enrollment To New Binding With Pam Creds|**Site Name:** FirstSite
**Port:** 443
**IP Address:**`*`
**Host Name:** www.firstsite.com
**Sni Flag:** 0 - No SNI
**Protocol:** https|New Binding Created with Enrollment Params specified creds pulled from Pam Provider|True|![](images/TestCase1Results.gif) -15 |New Cert Enrollment Default Site No HostName|**Site Name:** Default Web Site
**Port:** 443
**IP Address:**`*`
**Host Name:**
**Sni Flag:** 0 - No SNI
**Protocol:** https|New Binding Installed with no HostName|True|![](images/TestCase15Results.gif) -
-
-WinSql - -Case Number|Case Name|Enrollment Params|Expected Results|Passed|Screenshot -----|------------------------|------------------------------------|--------------|----------------|------------------------- -1 |New Cert Enrollment To Default Instance Leave Blank|**Instance Name:** |Cert will be Installed to default Instance, Service will be restarted for default instance|True|![](images/SQLTestCase1.gif) -2 |New Cert Enrollment To Default Instance MSSQLServer|**Instance Name:** MSSQLServer|Cert will be Installed to default Instance, Service will be restarted for default instance|True|![](images/SQLTestCase2.gif) -3 |New Cert Enrollment To Instance1|**Instance Name:** Instance1|Cert will be Installed to Instance1, Service will be restarted for Instance1|True|![](images/SQLTestCase3.gif) -4 |New Cert Enrollment To Instance1 and Default Instance|**Instance Name:** MSSQLServer,Instance1|Cert will be Installed to Default Instance and Instance1, Service will be restarted for Default Instance and Instance1|True|![](images/SQLTestCase4.gif) -5 |One Click Renew Cert Enrollment To Instance1 and Default Instance|N/A|Cert will be Renewed/Installed to Default Instance and Instance1, Service will be restarted for Default Instance and Instance1|True|![](images/SQLTestCase5.gif) -6 |Remove Cert From Instance1 and Default Instance|**Instance Name:** |Cert from TC5 will be Removed From Default Instance and Instance1|True|![](images/SQLTestCase6.gif) -7 |Inventory Different Certs Different Instance|N/A|2 Certs will be inventoried and each tied to its Instance|True|![](images/SQLTestCase7.gif) -8 |Inventory Same Cert Different Instance|N/A|2 Certs will be inventoried the cert will have a comma separated list of Instances|True|![](images/SQLTestCase8.gif) -9 |Inventory Against Machine Without SQL Server|N/A|Will fail with error saying it can't find SQL Server|True|![](images/SQLTestCase9.gif) - + +
WinSql (WinSql) + + +* **Manually with the Command UI** + +
Create Certificate Stores manually in the UI + + 1. **Navigate to the _Certificate Stores_ page in Keyfactor Command.** + + Log into Keyfactor Command, toggle the _Locations_ dropdown, and click _Certificate Stores_. + + 2. **Add a Certificate Store.** + + Click the Add button to add a new Certificate Store. Use the table below to populate the **Attributes** in the **Add** form. + | Attribute | Description | + | --------- | ----------- | + | Category | Select "WinSql" or the customized certificate store name from the previous step. | + | Container | Optional container to associate certificate store with. | + | Client Machine | Hostname of the Windows Server containing the SQL Server Certificate Store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine). | + | Store Path | Fixed string value 'My' indicating the Personal store on the Local Machine. This denotes the Windows certificate store to be managed for SQL Server. | + | Orchestrator | Select an approved orchestrator capable of managing `WinSql` certificates. Specifically, one with the `WinSql` capability. | + | spnwithport | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | + | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | + | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | + | ServerUsername | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | + | ServerPassword | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | + | ServerUseSsl | Determine whether the server uses SSL or not (This field is automatically created) | + | RestartService | Boolean value (true or false) indicating whether to restart the SQL Server service after installing the certificate. Example: 'true' to enable service restart after installation. | + + + + +
+ +* **Using kfutil** + +
Create Certificate Stores with kfutil + + 1. **Generate a CSV template for the WinSql certificate store** + + ```shell + kfutil stores import generate-template --store-type-name WinSql --outpath WinSql.csv + ``` + 2. **Populate the generated CSV file** + + Open the CSV file, and reference the table below to populate parameters for each **Attribute**. + | Attribute | Description | + | --------- | ----------- | + | Category | Select "WinSql" or the customized certificate store name from the previous step. | + | Container | Optional container to associate certificate store with. | + | Client Machine | Hostname of the Windows Server containing the SQL Server Certificate Store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine). | + | Store Path | Fixed string value 'My' indicating the Personal store on the Local Machine. This denotes the Windows certificate store to be managed for SQL Server. | + | Orchestrator | Select an approved orchestrator capable of managing `WinSql` certificates. Specifically, one with the `WinSql` capability. | + | spnwithport | Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations. | + | WinRM Protocol | Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication. | + | WinRM Port | String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP. | + | ServerUsername | Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\username'. | + | ServerPassword | Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'. | + | ServerUseSsl | Determine whether the server uses SSL or not (This field is automatically created) | + | RestartService | Boolean value (true or false) indicating whether to restart the SQL Server service after installing the certificate. Example: 'true' to enable service restart after installation. | + + + + + 3. **Import the CSV file to create the certificate stores** + + ```shell + kfutil stores import csv --store-type-name WinSql --file WinSql.csv + ``` +
+ +> The content in this section can be supplimented by the [official Command documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/ReferenceGuide/Certificate%20Stores.htm?Highlight=certificate%20store). + +
-When creating cert store type manually, that store property names and entry parameter names are case sensitive +## Note Regarding Client Machine + +If running as an agent (accessing stores on the server where the Universal Orchestrator Services is installed ONLY), the Client Machine can be entered, OR you can bypass a WinRM connection and access the local file system directly by adding "|LocalMachine" to the end of your value for Client Machine, for example "1.1.1.1|LocalMachine". In this instance the value to the left of the pipe (|) is ignored. It is important to make sure the values for Client Machine and Store Path together are unique for each certificate store created, as Keyfactor Command requires the Store Type you select, along with Client Machine, and Store Path together must be unique. To ensure this, it is good practice to put the full DNS or IP Address to the left of the | character when setting up a certificate store that will be accessed without a WinRM connection. + +Here are the settings required for each Store Type previously configured. + + +## License + +Apache License 2.0, see [LICENSE](LICENSE). + +## Related Integrations + +See all [Keyfactor Universal Orchestrator extensions](https://github.com/orgs/Keyfactor/repositories?q=orchestrator). \ No newline at end of file diff --git a/WinCertTestConsole/WinCertTestConsole.csproj b/WinCertTestConsole/WinCertTestConsole.csproj index 504e735..e75510b 100644 --- a/WinCertTestConsole/WinCertTestConsole.csproj +++ b/WinCertTestConsole/WinCertTestConsole.csproj @@ -1,8 +1,8 @@ - + Exe - net6.0 + net8.0 AnyCPU @@ -10,7 +10,7 @@ - + diff --git a/WinCertUnitTests/CertificateHelper.cs b/WinCertUnitTests/CertificateHelper.cs new file mode 100644 index 0000000..61c73c3 --- /dev/null +++ b/WinCertUnitTests/CertificateHelper.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace WinCertUnitTests +{ + internal class CertificateHelper + { + public static void CreateSelfSignedCertificate(string certName, string password, string pfxPath) + { + // Set certificate subject and other properties + var distinguishedName = new X500DistinguishedName($"CN={certName}"); + + using (RSA rsa = RSA.Create(2048)) + { + // Define the certificate request + var certificateRequest = new CertificateRequest( + distinguishedName, + rsa, + HashAlgorithmName.SHA256, + RSASignaturePadding.Pkcs1); + + // Add key usage and enhanced key usage (EKU) extensions + certificateRequest.CertificateExtensions.Add( + new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true)); + + certificateRequest.CertificateExtensions.Add( + new X509EnhancedKeyUsageExtension( + new OidCollection + { + new Oid("1.3.6.1.5.5.7.3.1") // OID for Server Authentication + }, true)); + + // Create the self-signed certificate + var startDate = DateTimeOffset.Now; + var endDate = startDate.AddYears(1); + + using (X509Certificate2 certificate = certificateRequest.CreateSelfSigned(startDate, endDate)) + { + // Export the certificate with a password to a PFX file + byte[] pfxBytes = certificate.Export(X509ContentType.Pfx, password); + + // Save to a file + File.WriteAllBytes(pfxPath, pfxBytes); + + Console.WriteLine($"Certificate created and saved at {pfxPath}"); + } + } + } + } +} diff --git a/WinCertUnitTests/UnitTestIISBinding.cs b/WinCertUnitTests/UnitTestIISBinding.cs new file mode 100644 index 0000000..7c17a65 --- /dev/null +++ b/WinCertUnitTests/UnitTestIISBinding.cs @@ -0,0 +1,190 @@ +using Keyfactor.Orchestrators.Extensions; +using Keyfactor.Extensions.Orchestrator.WindowsCertStore.IISU; +using Keyfactor.Extensions.Orchestrator.WindowsCertStore; +using System.Security.Cryptography.X509Certificates; +using System.Management.Automation.Runspaces; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting.Logging; +using System.Net; +//using System.Web.Services.Description; +using System.Management.Automation; +using Keyfactor.Orchestrators.Common.Enums; +using System.Security.Policy; +using Microsoft.Web.Administration; +namespace WinCertUnitTests +{ + [TestClass] + public class UnitTestIISBinding + { + private string certName = ""; + private string certPassword = ""; + private string pfxPath = ""; + + public UnitTestIISBinding() + { + certName = "UnitTestCertificate"; + certPassword = "lkjglj655asd"; + pfxPath = Path.Combine(Directory.GetCurrentDirectory(), "TestCertificate.pfx"); + + if (!File.Exists(pfxPath)) + { + CertificateHelper.CreateSelfSignedCertificate(certName, certPassword, pfxPath); + } + } + + + [TestMethod] + public void RenewBindingCertificate() + { + X509Certificate2 cert = new X509Certificate2(pfxPath, certPassword); + + Runspace rs = PsHelper.GetClientPsRunspace("", "localhost", "", false, "", ""); + + ClientPSIIManager IIS = new ClientPSIIManager(rs, "Default Web Site", "https", "*", "443", "", cert.Thumbprint, "My", "0"); + JobResult result = IIS.BindCertificate(cert); + Assert.AreEqual("Success", result.Result.ToString()); + } + + [TestMethod] + public void UnBindCertificate() + { + X509Certificate2 cert = new X509Certificate2(pfxPath, certPassword); + + Runspace rs = PsHelper.GetClientPsRunspace("", "localhost", "", false, "", ""); + BindingNewCertificate(); + + string sslFlag = "0"; + ClientPSIIManager IIS = new ClientPSIIManager(rs, "Default Web Site", "https", "*", "443", "", "", "My", sslFlag); + JobResult result = IIS.UnBindCertificate(); + + Assert.AreEqual("Success", result.Result.ToString()); + } + + [TestMethod] + public void BindingNewCertificate() + { + X509Certificate2 cert = new X509Certificate2(pfxPath, certPassword); + + Runspace rs = PsHelper.GetClientPsRunspace("", "localhost", "", false, "", ""); + + string sslFlag = "0"; + + ClientPSIIManager IIS = new ClientPSIIManager(rs, "Default Web Site", "https", "*", "443", "", "", "My", sslFlag); + JobResult result = IIS.BindCertificate(cert); + + Assert.AreEqual("Success", result.Result.ToString()); + } + + [TestMethod] + public void BindingNewCertificateBadSslFlag() + { + X509Certificate2 cert = new X509Certificate2(pfxPath, certPassword); + + Runspace rs = PsHelper.GetClientPsRunspace("", "localhost", "", false, "", ""); + + string sslFlag = "909"; // known bad value + + ClientPSIIManager IIS = new ClientPSIIManager(rs, "Default Web Site", "https", "*", "443", "", "", "My", sslFlag); + JobResult result = IIS.BindCertificate(cert); + + Assert.AreEqual("Failure", result.Result.ToString()); + } + + [TestMethod] + public void AddCertificate() + { + Runspace rs = PsHelper.GetClientPsRunspace("", "localhost", "", false, "", ""); + rs.Open(); + + ClientPSCertStoreManager certStoreManager = new ClientPSCertStoreManager(rs); + JobResult result = certStoreManager.ImportPFXFile(pfxPath, certPassword, "", "My"); + rs.Close(); + + Assert.AreEqual("Success", result.Result.ToString()); + } + + [TestMethod] + public void RemoveCertificate() + { + Runspace rs = PsHelper.GetClientPsRunspace("", "localhost", "", false, "", ""); + rs.Open(); + + ClientPSCertStoreManager certStoreManager = new ClientPSCertStoreManager(rs); + try + { + certStoreManager.RemoveCertificate("0a3f880aa17c03ef2c75493497d89756cfafa165", "My"); + Assert.IsTrue(true, "Certificate was successfully removed."); + } + catch (Exception e) + { + Assert.IsFalse(false, e.Message); + } + rs.Close(); + } + + + [TestMethod] + public void GetBoundCertificates() + { + Runspace rs = PsHelper.GetClientPsRunspace("", "localhost", "", false, "", ""); + rs.Open(); + WinIISInventory IISInventory = new WinIISInventory(); + List certs = IISInventory.GetInventoryItems(rs, "My"); + rs.Close(); + + Assert.IsNotNull(certs); + + } + + [TestMethod] + public void OrigSNIFlagZeroReturnsZero() + { + string expectedResult = "32"; + string result = ClientPSIIManager.MigrateSNIFlag("32"); + Assert.AreEqual(expectedResult, result); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void InvalidSNIFlagThrowException() + { + string result = ClientPSIIManager.MigrateSNIFlag("Bad value"); + } + + static bool TestValidSslFlag(int sslFlag) + { + try + { + using (ServerManager serverManager = new ServerManager()) + { + // Loop through all sites in IIS + foreach (Microsoft.Web.Administration.Site site in serverManager.Sites) + { + // Loop through all bindings for each site + foreach (Binding binding in site.Bindings) + { + // Check if the binding uses the HTTPS protocol + if (binding.Protocol == "https") + { + // Get the SslFlags value (stored in binding.Attributes) + int currentSslFlags = (int)binding.Attributes["sslFlags"].Value; + + // Check if the SslFlag value matches the provided one + if (currentSslFlags == sslFlag) + { + return true; // Valid SslFlag found + } + } + } + } + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + + return false; // No matching SslFlag found + } + } +} \ No newline at end of file diff --git a/WinCertUnitTests/WinCertUnitTests.csproj b/WinCertUnitTests/WinCertUnitTests.csproj new file mode 100644 index 0000000..17f1bd0 --- /dev/null +++ b/WinCertUnitTests/WinCertUnitTests.csproj @@ -0,0 +1,29 @@ + + + + net6.0 + enable + enable + + false + true + + + + + + + + + + + + + + + + + + + + diff --git a/WindowsCertStore.sln b/WindowsCertStore.sln index 883ef0b..7d2f736 100644 --- a/WindowsCertStore.sln +++ b/WindowsCertStore.sln @@ -36,6 +36,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "images", "images", "{630203 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinCertTestConsole", "WinCertTestConsole\WinCertTestConsole.csproj", "{D0F4A3CC-5236-4393-9C97-AE55ACE319F2}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinCertUnitTests", "WinCertUnitTests\WinCertUnitTests.csproj", "{AEE85A79-8614-447A-B14A-FD5A389C510B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -59,6 +61,14 @@ Global {D0F4A3CC-5236-4393-9C97-AE55ACE319F2}.Release|Any CPU.ActiveCfg = Release|Any CPU {D0F4A3CC-5236-4393-9C97-AE55ACE319F2}.Release|Any CPU.Build.0 = Release|Any CPU {D0F4A3CC-5236-4393-9C97-AE55ACE319F2}.Release|x64.ActiveCfg = Release|Any CPU + {AEE85A79-8614-447A-B14A-FD5A389C510B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AEE85A79-8614-447A-B14A-FD5A389C510B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AEE85A79-8614-447A-B14A-FD5A389C510B}.Debug|x64.ActiveCfg = Debug|Any CPU + {AEE85A79-8614-447A-B14A-FD5A389C510B}.Debug|x64.Build.0 = Debug|Any CPU + {AEE85A79-8614-447A-B14A-FD5A389C510B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AEE85A79-8614-447A-B14A-FD5A389C510B}.Release|Any CPU.Build.0 = Release|Any CPU + {AEE85A79-8614-447A-B14A-FD5A389C510B}.Release|x64.ActiveCfg = Release|Any CPU + {AEE85A79-8614-447A-B14A-FD5A389C510B}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/docsource/content.md b/docsource/content.md new file mode 100644 index 0000000..8acf59d --- /dev/null +++ b/docsource/content.md @@ -0,0 +1,53 @@ +## Overview + +The WinCertStore Orchestrator remotely manages certificates in a Windows Server local machine certificate store. Users are able to determine which store they wish to place certificates in by entering the correct store path. For a complete list of local machine cert stores you can execute the PowerShell command: + + Get-ChildItem Cert:\LocalMachine + +The returned list will contain the actual certificate store name to be used when entering store location. + +By default, most certificates are stored in the “Personal” (My) and “Web Hosting” (WebHosting) stores. + +This extension implements four job types: Inventory, Management Add/Remove, and Reenrollment. + +WinRM is used to remotely manage the certificate stores and IIS bindings. WinRM must be properly configured to allow the orchestrator on the server to manage the certificates. Setting up WinRM is not in the scope of this document. + +**Note:** +In version 2.0 of the IIS Orchestrator, the certificate store type has been renamed and additional parameters have been added. Prior to 2.0 the certificate store type was called “IISBin” and as of 2.0 it is called “IISU”. If you have existing certificate stores of type “IISBin”, you have three options: +1. Leave them as is and continue to manage them with a pre 2.0 IIS Orchestrator Extension. Create the new IISU certificate store type and create any new IIS stores using the new type. +1. Delete existing IIS stores. Delete the IISBin store type. Create the new IISU store type. Recreate the IIS stores using the new IISU store type. +1. Convert existing IISBin certificate stores to IISU certificate stores. There is not currently a way to do this via the Keyfactor API, so direct updates to the underlying Keyfactor SQL database is required. A SQL script (IIS-Conversion.sql) is available in the repository to do this. Hosted customers, which do not have access to the underlying database, will need to work Keyfactor support to run the conversion. On-premises customers can run the script themselves, but are strongly encouraged to ensure that a SQL backup is taken prior running the script (and also be confident that they have a tested database restoration process.) + +**Note: There is an additional (and deprecated) certificate store type of “IIS” that ships with the Keyfactor platform. Migration of certificate stores from the “IIS” type to either the “IISBin” or “IISU” types is not currently supported.** + +**Note: If Looking to use GMSA Accounts to run the Service Keyfactor Command 10.2 or greater is required for No Value checkbox to work** + +## Requirements + +### Security and Permission Considerations + +From an official support point of view, Local Administrator permissions are required on the target server. Some customers have been successful with using other accounts and granting rights to the underlying certificate and private key stores. Due to complexities with the interactions between Group Policy, WinRM, User Account Control, and other unpredictable customer environmental factors, Keyfactor cannot provide assistance with using accounts other than the local administrator account. + +For customers wishing to use something other than the local administrator account, the following information may be helpful: + +* The WinCert extensions (WinCert, IISU, WinSQL) create a WinRM (remote PowerShell) session to the target server in order to manipulate the Windows Certificate Stores, perform binding (in the case of the IISU extension), or to access the registry (in the case of the WinSQL extension). + +* When the WinRM session is created, the certificate store credentials are used if they have been specified, otherwise the WinRM session is created in the context of the Universal Orchestrator (UO) Service account (which potentially could be the network service account, a regular account, or a GMSA account) + +* WinRM needs to be properly set up between the server hosting the UO and the target server. This means that a WinRM client running on the UO server when running in the context of the UO service account needs to be able to create a session on the target server using the configured credentials of the target server and any PowerShell commands running on the remote session need to have appropriate permissions. + +* Even though a given account may be in the administrators group or have administrative privileges on the target system and may be able to execute certificate and binding operations when running locally, the same account may not work when being used via WinRM. User Account Control (UAC) can get in the way and filter out administrative privledges. UAC / WinRM configuration has a LocalAccountTokenFilterPolicy setting that can be adjusted to not filter out administrative privledges for remote users, but enabling this may have other security ramifications. + +* The following list may not be exhaustive, but in general the account (when running under a remote WinRM session) needs permissions to: + - Instantiate and open a .NET X509Certificates.X509Store object for the target certificate store and be able to read and write both the certificates and related private keys. Note that ACL permissions on the stores and private keys are separate. + - Use the Import-Certificate, Get-WebSite, Get-WebBinding, and New-WebBinding PowerShell CmdLets. + - Create and delete temporary files. + - Execute certreq commands. + - Access any Cryptographic Service Provider (CSP) referenced in re-enrollment jobs. + - Read and Write values in the registry (HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server) when performing SQL Server certificate binding. + +## Note Regarding Client Machine + +If running as an agent (accessing stores on the server where the Universal Orchestrator Services is installed ONLY), the Client Machine can be entered, OR you can bypass a WinRM connection and access the local file system directly by adding "|LocalMachine" to the end of your value for Client Machine, for example "1.1.1.1|LocalMachine". In this instance the value to the left of the pipe (|) is ignored. It is important to make sure the values for Client Machine and Store Path together are unique for each certificate store created, as Keyfactor Command requires the Store Type you select, along with Client Machine, and Store Path together must be unique. To ensure this, it is good practice to put the full DNS or IP Address to the left of the | character when setting up a certificate store that will be accessed without a WinRM connection. + +Here are the settings required for each Store Type previously configured. diff --git a/docsource/iisu.md b/docsource/iisu.md new file mode 100644 index 0000000..ad9209e --- /dev/null +++ b/docsource/iisu.md @@ -0,0 +1,15 @@ +## Overview + +The IIS Bound Certificate Certificate Store Type, identified by its short name 'IISU,' is designed for the management of certificates bound to IIS (Internet Information Services) servers. This store type allows users to automate and streamline the process of adding, removing, and reenrolling certificates for IIS sites, making it significantly easier to manage web server certificates. + +### Key Features and Representation + +The IISU store type represents the IIS servers and their certificate bindings. It specifically caters to managing SSL/TLS certificates tied to IIS websites, allowing bind operations such as specifying site names, IP addresses, ports, and enabling Server Name Indication (SNI). By default, it supports job types like Inventory, Add, Remove, and Reenrollment, thereby offering comprehensive management capabilities for IIS certificates. + +### Limitations and Areas of Confusion + +- **Caveats:** It's important to ensure that the Windows Remote Management (WinRM) is properly configured on the target server. The orchestrator relies on WinRM to perform its tasks, such as manipulating the Windows Certificate Stores. Misconfiguration of WinRM may lead to connection and permission issues. + +- **Limitations:** Users should be aware that for this store type to function correctly, certain permissions are necessary. While some advanced users successfully use non-administrator accounts with specific permissions, it is officially supported only with Local Administrator permissions. Complexities with interactions between Group Policy, WinRM, User Account Control, and other environmental factors may impede operations if not properly configured. + +- **Custom Alias and Private Keys:** The store type does not support custom aliases for individual entries and requires private keys because IIS certificates without private keys would be invalid. diff --git a/docsource/images/IISU-advanced-store-type-dialog.png b/docsource/images/IISU-advanced-store-type-dialog.png new file mode 100644 index 0000000..18402cb Binary files /dev/null and b/docsource/images/IISU-advanced-store-type-dialog.png differ diff --git a/docsource/images/IISU-basic-store-type-dialog.png b/docsource/images/IISU-basic-store-type-dialog.png new file mode 100644 index 0000000..a168f94 Binary files /dev/null and b/docsource/images/IISU-basic-store-type-dialog.png differ diff --git a/docsource/images/IISU-custom-fields-store-type-dialog.png b/docsource/images/IISU-custom-fields-store-type-dialog.png new file mode 100644 index 0000000..cb0d115 Binary files /dev/null and b/docsource/images/IISU-custom-fields-store-type-dialog.png differ diff --git a/docsource/images/IISU-entry-parameters-store-type-dialog.png b/docsource/images/IISU-entry-parameters-store-type-dialog.png new file mode 100644 index 0000000..415d843 Binary files /dev/null and b/docsource/images/IISU-entry-parameters-store-type-dialog.png differ diff --git a/docsource/images/WinCert-advanced-store-type-dialog.png b/docsource/images/WinCert-advanced-store-type-dialog.png new file mode 100644 index 0000000..fb418e6 Binary files /dev/null and b/docsource/images/WinCert-advanced-store-type-dialog.png differ diff --git a/docsource/images/WinCert-basic-store-type-dialog.png b/docsource/images/WinCert-basic-store-type-dialog.png new file mode 100644 index 0000000..ff825da Binary files /dev/null and b/docsource/images/WinCert-basic-store-type-dialog.png differ diff --git a/docsource/images/WinCert-custom-fields-store-type-dialog.png b/docsource/images/WinCert-custom-fields-store-type-dialog.png new file mode 100644 index 0000000..cb0d115 Binary files /dev/null and b/docsource/images/WinCert-custom-fields-store-type-dialog.png differ diff --git a/docsource/images/WinCert-entry-parameters-store-type-dialog.png b/docsource/images/WinCert-entry-parameters-store-type-dialog.png new file mode 100644 index 0000000..ff17c42 Binary files /dev/null and b/docsource/images/WinCert-entry-parameters-store-type-dialog.png differ diff --git a/docsource/images/WinSql-advanced-store-type-dialog.png b/docsource/images/WinSql-advanced-store-type-dialog.png new file mode 100644 index 0000000..fb418e6 Binary files /dev/null and b/docsource/images/WinSql-advanced-store-type-dialog.png differ diff --git a/docsource/images/WinSql-basic-store-type-dialog.png b/docsource/images/WinSql-basic-store-type-dialog.png new file mode 100644 index 0000000..5d29a87 Binary files /dev/null and b/docsource/images/WinSql-basic-store-type-dialog.png differ diff --git a/docsource/images/WinSql-custom-fields-store-type-dialog.png b/docsource/images/WinSql-custom-fields-store-type-dialog.png new file mode 100644 index 0000000..54cc862 Binary files /dev/null and b/docsource/images/WinSql-custom-fields-store-type-dialog.png differ diff --git a/docsource/images/WinSql-entry-parameters-store-type-dialog.png b/docsource/images/WinSql-entry-parameters-store-type-dialog.png new file mode 100644 index 0000000..a1604c6 Binary files /dev/null and b/docsource/images/WinSql-entry-parameters-store-type-dialog.png differ diff --git a/docsource/wincert.md b/docsource/wincert.md new file mode 100644 index 0000000..9b8b74c --- /dev/null +++ b/docsource/wincert.md @@ -0,0 +1,14 @@ +## Overview + +The Windows Certificate Certificate Store Type, known by its short name 'WinCert,' enables the management of certificates within the Windows local machine certificate stores. This store type is a versatile option for general Windows certificate management and supports functionalities including inventory, add, remove, and reenrollment of certificates. + +The store type represents the various certificate stores present on a Windows Server. Users can specify these stores by entering the correct store path. To get a complete list of available certificate stores, the PowerShell command `Get-ChildItem Cert:\LocalMachine` can be executed, providing the actual certificate store names needed for configuration. + +### Key Features and Considerations + +- **Functionality:** The WinCert store type supports essential certificate management tasks, such as inventorying existing certificates, adding new certificates, removing old ones, and reenrolling certificates. + +- **Caveats:** It's important to ensure that the Windows Remote Management (WinRM) is properly configured on the target server. The orchestrator relies on WinRM to perform its tasks, such as manipulating the Windows Certificate Stores. Misconfiguration of WinRM may lead to connection and permission issues. + +- **Limitations:** Users should be aware that for this store type to function correctly, certain permissions are necessary. While some advanced users successfully use non-administrator accounts with specific permissions, it is officially supported only with Local Administrator permissions. Complexities with interactions between Group Policy, WinRM, User Account Control, and other environmental factors may impede operations if not properly configured. + diff --git a/docsource/winsql.md b/docsource/winsql.md new file mode 100644 index 0000000..19af1af --- /dev/null +++ b/docsource/winsql.md @@ -0,0 +1,10 @@ +## Overview + +The WinSql Certificate Store Type, referred to by its short name 'WinSql,' is designed for the management of certificates used by SQL Server instances. This store type allows users to automate the process of adding, removing, reenrolling, and inventorying certificates associated with SQL Server, thereby simplifying the management of SSL/TLS certificates for database servers. + +### Caveats and Limitations + +- **Caveats:** It's important to ensure that the Windows Remote Management (WinRM) is properly configured on the target server. The orchestrator relies on WinRM to perform its tasks, such as manipulating the Windows Certificate Stores. Misconfiguration of WinRM may lead to connection and permission issues. + +- **Limitations:** Users should be aware that for this store type to function correctly, certain permissions are necessary. While some advanced users successfully use non-administrator accounts with specific permissions, it is officially supported only with Local Administrator permissions. Complexities with interactions between Group Policy, WinRM, User Account Control, and other environmental factors may impede operations if not properly configured. + diff --git a/integration-manifest.json b/integration-manifest.json index 87833f4..4b555b0 100644 --- a/integration-manifest.json +++ b/integration-manifest.json @@ -1,448 +1,495 @@ { - "$schema": "https://keyfactor.github.io/integration-manifest-schema.json", - "integration_type": "orchestrator", - "name": "WinCertStore Orchestrator", - "status": "production", - "link_github": true, - "release_dir": "IISU/bin/Release/net6.0", - "update_catalog": true, - "support_level": "kf-supported", - "description": "The Windows Certificate Store Orchestrator Extension implements two certificate store types. 1) “WinCert” which manages certificates in a Windows local machine store, and 2) “IISU” which manages certificates and their bindings in a Windows local machine store that are bound to Internet Information Server (IIS) websites. These extensions replace the now deprecated “IIS” cert store type that ships with Keyfactor Command. The “IISU” extension also replaces the “IISBin” certificate store type from prior versions of this repository. This orchestrator extension is in the process of being renamed from “IIS Orchestrator” as it now supports certificates that are not in use by IIS.", - "about": { - "orchestrator": { - "UOFramework": "10.1", - "pam_support": true, - "keyfactor_platform_version": "9.10", - "win": { - "supportsCreateStore": false, - "supportsDiscovery": false, - "supportsManagementAdd": true, - "supportsManagementRemove": true, - "supportsReenrollment": true, - "supportsInventory": true, - "platformSupport": "Unused" - }, - "linux": { - "supportsCreateStore": false, - "supportsDiscovery": false, - "supportsManagementAdd": false, - "supportsManagementRemove": false, - "supportsReenrollment": false, - "supportsInventory": false, - "platformSupport": "Unused" - }, - "store_types": [ - { - "Name": "Windows Certificate", - "ShortName": "WinCert", - "Capability": "WinCert", - "LocalStore": false, - "SupportedOperations": { - "Add": true, - "Create": false, - "Discovery": false, - "Enrollment": true, - "Remove": true - }, - "Properties": [ - { - "Name": "spnwithport", - "DisplayName": "SPN With Port", - "Type": "Bool", - "DependsOn": "", - "DefaultValue": "false", - "Required": false + "$schema": "https://keyfactor.github.io/v2/integration-manifest-schema.json", + "integration_type": "orchestrator", + "name": "Windows Certificate Orchestrator", + "status": "production", + "link_github": true, + "release_dir": "IISU/bin/Release", + "release_project": "IISU/WindowsCertStore.csproj", + "update_catalog": true, + "support_level": "kf-supported", + "description": "The Windows Certificate Store Orchestrator Extension implements two certificate store types. 1) \u201cWinCert\u201d which manages certificates in a Windows local machine store, and 2) \u201cIISU\u201d which manages certificates and their bindings in a Windows local machine store that are bound to Internet Information Server (IIS) websites. These extensions replace the now deprecated \u201cIIS\u201d cert store type that ships with Keyfactor Command. The \u201cIISU\u201d extension also replaces the \u201cIISBin\u201d certificate store type from prior versions of this repository. This orchestrator extension is in the process of being renamed from \u201cIIS Orchestrator\u201d as it now supports certificates that are not in use by IIS.", + "about": { + "orchestrator": { + "UOFramework": "10.1", + "pam_support": true, + "keyfactor_platform_version": "9.10", + "win": { + "supportsCreateStore": false, + "supportsDiscovery": false, + "supportsManagementAdd": true, + "supportsManagementRemove": true, + "supportsReenrollment": true, + "supportsInventory": true, + "platformSupport": "Unused" }, - { - "Name": "WinRM Protocol", - "DisplayName": "WinRM Protocol", - "Type": "MultipleChoice", - "DependsOn": "", - "DefaultValue": "https,http", - "Required": true + "linux": { + "supportsCreateStore": false, + "supportsDiscovery": false, + "supportsManagementAdd": false, + "supportsManagementRemove": false, + "supportsReenrollment": false, + "supportsInventory": false, + "platformSupport": "Unused" }, - { - "Name": "WinRM Port", - "DisplayName": "WinRM Port", - "Type": "String", - "DependsOn": "", - "DefaultValue": "5986", - "Required": true - }, - { - "Name": "ServerUsername", - "DisplayName": "Server Username", - "Type": "Secret", - "DependsOn": "", - "DefaultValue": null, - "Required": false - }, - { - "Name": "ServerPassword", - "DisplayName": "Server Password", - "Type": "Secret", - "DependsOn": "", - "DefaultValue": null, - "Required": false - }, - { - "Name": "ServerUseSsl", - "DisplayName": "Use SSL", - "Type": "Bool", - "DependsOn": "", - "DefaultValue": "true", - "Required": true - } - ], - "EntryParameters": [ - { - "Name": "ProviderName", - "DisplayName": "Crypto Provider Name", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": false - }, - "DependsOn": "", - "DefaultValue": "", - "Options": "" - }, - { - "Name": "SAN", - "DisplayName": "SAN", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": true - }, - "DependsOn": "", - "DefaultValue": "", - "Options": "" - } - ], - "PasswordOptions": { - "EntrySupported": false, - "StoreRequired": false, - "Style": "Default" - }, - "StorePathValue": "", - "PrivateKeyAllowed": "Optional", - "ServerRequired": true, - "PowerShell": false, - "BlueprintAllowed": false, - "CustomAliasAllowed": "Forbidden" - }, - { - "Name": "IIS Bound Certificate", - "ShortName": "IISU", - "Capability": "IISU", - "LocalStore": false, - "SupportedOperations": { - "Add": true, - "Create": false, - "Discovery": false, - "Enrollment": true, - "Remove": true - }, - "Properties": [ - { - "Name": "spnwithport", - "DisplayName": "SPN With Port", - "Type": "Bool", - "DependsOn": "", - "DefaultValue": "false", - "Required": false - }, - { - "Name": "WinRm Protocol", - "DisplayName": "WinRm Protocol", - "Type": "MultipleChoice", - "DependsOn": "", - "DefaultValue": "https,http", - "Required": true - }, - { - "Name": "WinRm Port", - "DisplayName": "WinRm Port", - "Type": "String", - "DependsOn": "", - "DefaultValue": "5986", - "Required": true - }, - { - "Name": "ServerUsername", - "DisplayName": "Server Username", - "Type": "Secret", - "DependsOn": "", - "DefaultValue": null, - "Required": false - }, - { - "Name": "ServerPassword", - "DisplayName": "Server Password", - "Type": "Secret", - "DependsOn": "", - "DefaultValue": null, - "Required": false - }, - { - "Name": "ServerUseSsl", - "DisplayName": "Use SSL", - "Type": "Bool", - "DependsOn": "", - "DefaultValue": "true", - "Required": true - } - ], - "EntryParameters": [ - { - "Name": "Port", - "DisplayName": "Port", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": false - }, - "DependsOn": "", - "DefaultValue": "443", - "Options": "" - }, - { - "Name": "IPAddress", - "DisplayName": "IP Address", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": true, - "OnRemove": true, - "OnReenrollment": true - }, - "DependsOn": "", - "DefaultValue": "*", - "Options": "" - }, - { - "Name": "HostName", - "DisplayName": "Host Name", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": false - }, - "DependsOn": "", - "DefaultValue": "", - "Options": "" - }, - { - "Name": "SiteName", - "DisplayName": "IIS Site Name", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": true, - "OnRemove": true, - "OnReenrollment": true - }, - "DependsOn": "", - "DefaultValue": "Default Web Site", - "Options": "" - }, - { - "Name": "SniFlag", - "DisplayName": "SNI Support", - "Type": "MultipleChoice", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": false - }, - "DependsOn": "", - "DefaultValue": "0 - No SNI", - "Options": "0 - No SNI,1 - SNI Enabled,2 - Non SNI Binding,3 - SNI Binding" - }, - { - "Name": "Protocol", - "DisplayName": "Protocol", - "Type": "MultipleChoice", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": true, - "OnRemove": true, - "OnReenrollment": true - }, - "DependsOn": "", - "DefaultValue": "https", - "Options": "https,http" - }, - { - "Name": "ProviderName", - "DisplayName": "Crypto Provider Name", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": false - }, - "DependsOn": "", - "DefaultValue": "", - "Options": "" - }, - { - "Name": "SAN", - "DisplayName": "SAN", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": true - }, - "DependsOn": "", - "DefaultValue": "", - "Options": "" - } - ], - "PasswordOptions": { - "EntrySupported": false, - "StoreRequired": false, - "Style": "Default" - }, - "StorePathValue": "[\"My\",\"WebHosting\"]", - "PrivateKeyAllowed": "Required", - "ServerRequired": true, - "PowerShell": false, - "BlueprintAllowed": false, - "CustomAliasAllowed": "Forbidden" - }, - { - "Name": "WinSql", - "ShortName": "WinSql", - "Capability": "WinSql", - "LocalStore": false, - "SupportedOperations": { - "Add": true, - "Create": false, - "Discovery": false, - "Enrollment": false, - "Remove": true - }, - "Properties": [ - { - "Name": "WinRm Protocol", - "DisplayName": "WinRm Protocol", - "Type": "MultipleChoice", - "DependsOn": null, - "DefaultValue": "https,http", - "Required": true - }, - { - "Name": "WinRm Port", - "DisplayName": "WinRm Port", - "Type": "String", - "DependsOn": null, - "DefaultValue": "5986", - "Required": true - }, - { - "Name": "ServerUsername", - "DisplayName": "Server Username", - "Type": "Secret", - "DependsOn": null, - "DefaultValue": null, - "Required": false - }, - { - "Name": "ServerPassword", - "DisplayName": "Server Password", - "Type": "Secret", - "DependsOn": null, - "DefaultValue": null, - "Required": false - }, - { - "Name": "ServerUseSsl", - "DisplayName": "Use SSL", - "Type": "Bool", - "DependsOn": null, - "DefaultValue": "true", - "Required": true - }, - { - "Name": "RestartService", - "DisplayName": "Restart SQL Service After Cert Installed", - "Type": "Bool", - "DependsOn": null, - "DefaultValue": "false", - "Required": true - } - ], - "EntryParameters": [ - { - "Name": "InstanceName", - "DisplayName": "Instance Name", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": false - } - }, - { - "Name": "ProviderName", - "DisplayName": "Crypto Provider Name", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": false - }, - "DependsOn": "", - "DefaultValue": "", - "Options": "" - }, - { - "Name": "SAN", - "DisplayName": "SAN", - "Type": "String", - "RequiredWhen": { - "HasPrivateKey": false, - "OnAdd": false, - "OnRemove": false, - "OnReenrollment": true - }, - "DependsOn": "", - "DefaultValue": "", - "Options": "" - } - ], - "PasswordOptions": { - "EntrySupported": false, - "StoreRequired": false, - "Style": "Default" - }, - "StorePathValue": "My", - "PrivateKeyAllowed": "Optional", - "JobProperties": [ - "InstanceName" - ], - "ServerRequired": true, - "PowerShell": false, - "BlueprintAllowed": true, - "CustomAliasAllowed": "Forbidden" + "store_types": [ + { + "Name": "Windows Certificate", + "ShortName": "WinCert", + "Capability": "WinCert", + "LocalStore": false, + "SupportedOperations": { + "Add": true, + "Create": false, + "Discovery": false, + "Enrollment": true, + "Remove": true + }, + "Properties": [ + { + "Name": "spnwithport", + "DisplayName": "SPN With Port", + "Type": "Bool", + "DependsOn": "", + "DefaultValue": "false", + "Required": false, + "Description": "Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations." + }, + { + "Name": "WinRM Protocol", + "DisplayName": "WinRM Protocol", + "Type": "MultipleChoice", + "DependsOn": "", + "DefaultValue": "https,http", + "Required": true, + "Description": "Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication." + }, + { + "Name": "WinRM Port", + "DisplayName": "WinRM Port", + "Type": "String", + "DependsOn": "", + "DefaultValue": "5986", + "Required": true, + "Description": "String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP." + }, + { + "Name": "ServerUsername", + "DisplayName": "Server Username", + "Type": "Secret", + "DependsOn": "", + "DefaultValue": "", + "Required": false, + "Description": "Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\\username'." + }, + { + "Name": "ServerPassword", + "DisplayName": "Server Password", + "Type": "Secret", + "DependsOn": "", + "DefaultValue": "", + "Required": false, + "Description": "Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'." + }, + { + "Name": "ServerUseSsl", + "DisplayName": "Use SSL", + "Type": "Bool", + "DependsOn": "", + "DefaultValue": "true", + "Required": true, + "Description": "Determine whether the server uses SSL or not (This field is automatically created)" + } + ], + "EntryParameters": [ + { + "Name": "ProviderName", + "DisplayName": "Crypto Provider Name", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": false + }, + "DependsOn": "", + "DefaultValue": "", + "Options": "", + "Description": "Name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing the private keys. If not specified, defaults to 'Microsoft Strong Cryptographic Provider'. This value would typically be specified when leveraging a Hardware Security Module (HSM). The specified cryptographic provider must be available on the target server being managed. The list of installed cryptographic providers can be obtained by running 'certutil -csplist' on the target Server." + }, + { + "Name": "SAN", + "DisplayName": "SAN", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": true + }, + "DependsOn": "", + "DefaultValue": "", + "Options": "", + "Description": "String value specifying the Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Format as a list of = entries separated by ampersands; Example: 'dns=www.example.com&dns=www.example2.com' for multiple SANs. Can be made optional if RFC 2818 is disabled on the CA." + } + ], + "PasswordOptions": { + "EntrySupported": false, + "StoreRequired": false, + "Style": "Default" + }, + "StorePathValue": "", + "PrivateKeyAllowed": "Optional", + "ServerRequired": true, + "PowerShell": false, + "BlueprintAllowed": false, + "CustomAliasAllowed": "Forbidden", + "ClientMachineDescription": "Hostname of the Windows Server containing the certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine).", + "StorePathDescription": "Windows certificate store path to manage. The store must exist in the Local Machine store on the target server, e.g., 'My' for the Personal Store or 'Root' for the Trusted Root Certification Authorities Store." + }, + { + "Name": "IIS Bound Certificate", + "ShortName": "IISU", + "Capability": "IISU", + "LocalStore": false, + "SupportedOperations": { + "Add": true, + "Create": false, + "Discovery": false, + "Enrollment": true, + "Remove": true + }, + "Properties": [ + { + "Name": "spnwithport", + "DisplayName": "SPN With Port", + "Type": "Bool", + "DependsOn": "", + "DefaultValue": "false", + "Required": false, + "Description": "Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations." + }, + { + "Name": "WinRM Protocol", + "DisplayName": "WinRM Protocol", + "Type": "MultipleChoice", + "DependsOn": "", + "DefaultValue": "https,http", + "Required": true, + "Description": "Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication." + }, + { + "Name": "WinRM Port", + "DisplayName": "WinRM Port", + "Type": "String", + "DependsOn": "", + "DefaultValue": "5986", + "Required": true, + "Description": "String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP." + }, + { + "Name": "ServerUsername", + "DisplayName": "Server Username", + "Type": "Secret", + "DependsOn": "", + "DefaultValue": "", + "Required": false, + "Description": "Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\\username'." + }, + { + "Name": "ServerPassword", + "DisplayName": "Server Password", + "Type": "Secret", + "DependsOn": "", + "DefaultValue": "", + "Required": false, + "Description": "Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'." + }, + { + "Name": "ServerUseSsl", + "DisplayName": "Use SSL", + "Type": "Bool", + "DependsOn": "", + "DefaultValue": "true", + "Required": true, + "Description": "Determine whether the server uses SSL or not (This field is automatically created)" + } + ], + "EntryParameters": [ + { + "Name": "Port", + "DisplayName": "Port", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": false + }, + "DependsOn": "", + "DefaultValue": "443", + "Options": "", + "Description": "String value specifying the IP port to bind the certificate to for the IIS site. Example: '443' for HTTPS." + }, + { + "Name": "IPAddress", + "DisplayName": "IP Address", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": true, + "OnRemove": true, + "OnReenrollment": true + }, + "DependsOn": "", + "DefaultValue": "*", + "Options": "", + "Description": "String value specifying the IP address to bind the certificate to for the IIS site. Example: '*' for all IP addresses or '192.168.1.1' for a specific IP address." + }, + { + "Name": "HostName", + "DisplayName": "Host Name", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": false + }, + "DependsOn": "", + "DefaultValue": "", + "Options": "", + "Description": "String value specifying the host name (host header) to bind the certificate to for the IIS site. Leave blank for all host names or enter a specific hostname such as 'www.example.com'." + }, + { + "Name": "SiteName", + "DisplayName": "IIS Site Name", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": true, + "OnRemove": true, + "OnReenrollment": true + }, + "DependsOn": "", + "DefaultValue": "Default Web Site", + "Options": "", + "Description": "String value specifying the name of the IIS web site to bind the certificate to. Example: 'Default Web Site' or any custom site name such as 'MyWebsite'." + }, + { + "Name": "SniFlag", + "DisplayName": "SSL Flags", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": false + }, + "DependsOn": "", + "DefaultValue": "0", + "Options": "", + "Description": "A 128-Bit Flag that determines what type of SSL settings you wish to use. The default is 0, meaning No SNI. For more information, check IIS documentation for the appropriate bit setting.)" + }, + { + "Name": "Protocol", + "DisplayName": "Protocol", + "Type": "MultipleChoice", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": true, + "OnRemove": true, + "OnReenrollment": true + }, + "DependsOn": "", + "DefaultValue": "https", + "Options": "https,http", + "Description": "Multiple choice value specifying the protocol to bind to. Example: 'https' for secure communication." + }, + { + "Name": "ProviderName", + "DisplayName": "Crypto Provider Name", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": false + }, + "DependsOn": "", + "DefaultValue": "", + "Options": "", + "Description": "Name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing the private keys. If not specified, defaults to 'Microsoft Strong Cryptographic Provider'. This value would typically be specified when leveraging a Hardware Security Module (HSM). The specified cryptographic provider must be available on the target server being managed. The list of installed cryptographic providers can be obtained by running 'certutil -csplist' on the target Server." + }, + { + "Name": "SAN", + "DisplayName": "SAN", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": true + }, + "DependsOn": "", + "DefaultValue": "", + "Options": "", + "Description": "String value specifying the Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Format as a list of = entries separated by ampersands; Example: 'dns=www.example.com&dns=www.example2.com' for multiple SANs. Can be made optional if RFC 2818 is disabled on the CA." + } + ], + "PasswordOptions": { + "EntrySupported": false, + "StoreRequired": false, + "Style": "Default" + }, + "StorePathValue": "[\"My\",\"WebHosting\"]", + "PrivateKeyAllowed": "Required", + "ServerRequired": true, + "PowerShell": false, + "BlueprintAllowed": false, + "CustomAliasAllowed": "Forbidden", + "ClientMachineDescription": "Hostname of the Windows Server containing the IIS certificate store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine).", + "StorePathDescription": "Windows certificate store path to manage. Choose 'My' for the Personal store or 'WebHosting' for the Web Hosting store." + }, + { + "Name": "WinSql", + "ShortName": "WinSql", + "Capability": "WinSql", + "LocalStore": false, + "SupportedOperations": { + "Add": true, + "Create": false, + "Discovery": false, + "Enrollment": false, + "Remove": true + }, + "Properties": [ + { + "Name": "spnwithport", + "DisplayName": "SPN With Port", + "Type": "Bool", + "DependsOn": "", + "DefaultValue": "false", + "Required": false, + "Description": "Internally set the -IncludePortInSPN option when creating the remote PowerShell connection. Needed for some Kerberos configurations." + }, + { + "Name": "WinRM Protocol", + "DisplayName": "WinRM Protocol", + "Type": "MultipleChoice", + "DependsOn": "", + "DefaultValue": "https,http", + "Required": true, + "Description": "Multiple choice value specifying the protocol (https or http) that the target server's WinRM listener is using. Example: 'https' to use secure communication." + }, + { + "Name": "WinRM Port", + "DisplayName": "WinRM Port", + "Type": "String", + "DependsOn": "", + "DefaultValue": "5986", + "Required": true, + "Description": "String value specifying the port number that the target server's WinRM listener is configured to use. Example: '5986' for HTTPS or '5985' for HTTP." + }, + { + "Name": "ServerUsername", + "DisplayName": "Server Username", + "Type": "Secret", + "DependsOn": "", + "DefaultValue": "", + "Required": false, + "Description": "Username used to log into the target server for establishing the WinRM session. Example: 'administrator' or 'domain\\username'." + }, + { + "Name": "ServerPassword", + "DisplayName": "Server Password", + "Type": "Secret", + "DependsOn": "", + "DefaultValue": "", + "Required": false, + "Description": "Password corresponding to the Server Username used to log into the target server for establishing the WinRM session. Example: 'P@ssw0rd123'." + }, + { + "Name": "ServerUseSsl", + "DisplayName": "Use SSL", + "Type": "Bool", + "DependsOn": "", + "DefaultValue": "true", + "Required": true, + "Description": "Determine whether the server uses SSL or not (This field is automatically created)" + }, + { + "Name": "RestartService", + "DisplayName": "Restart SQL Service After Cert Installed", + "Type": "Bool", + "DependsOn": "", + "DefaultValue": "false", + "Required": true, + "Description": "Boolean value (true or false) indicating whether to restart the SQL Server service after installing the certificate. Example: 'true' to enable service restart after installation." + } + ], + "EntryParameters": [ + { + "Name": "InstanceName", + "DisplayName": "Instance Name", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": false + }, + "Description": "String value specifying the SQL Server instance name to bind the certificate to. Example: 'MSSQLServer' for the default instance or 'Instance1' for a named instance." + }, + { + "Name": "ProviderName", + "DisplayName": "Crypto Provider Name", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": false + }, + "DependsOn": "", + "DefaultValue": "", + "Options": "", + "Description": "Optional string value specifying the name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing private keys. Example: 'Microsoft Strong Cryptographic Provider'." + }, + { + "Name": "SAN", + "DisplayName": "SAN", + "Type": "String", + "RequiredWhen": { + "HasPrivateKey": false, + "OnAdd": false, + "OnRemove": false, + "OnReenrollment": true + }, + "DependsOn": "", + "DefaultValue": "", + "Options": "", + "Description": "String value specifying the Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Format as a list of = entries separated by ampersands; Example: 'dns=www.example.com&dns=www.example2.com' for multiple SANs." + } + ], + "PasswordOptions": { + "EntrySupported": false, + "StoreRequired": false, + "Style": "Default" + }, + "StorePathValue": "My", + "PrivateKeyAllowed": "Optional", + "JobProperties": [ + "InstanceName" + ], + "ServerRequired": true, + "PowerShell": false, + "BlueprintAllowed": true, + "CustomAliasAllowed": "Forbidden", + "ClientMachineDescription": "Hostname of the Windows Server containing the SQL Server Certificate Store to be managed. If this value is a hostname, a WinRM session will be established using the credentials specified in the Server Username and Server Password fields. For more information, see [Client Machine](#note-regarding-client-machine).", + "StorePathDescription": "Fixed string value 'My' indicating the Personal store on the Local Machine. This denotes the Windows certificate store to be managed for SQL Server." + } + ] } - ] } - } } \ No newline at end of file diff --git a/readme_source.md b/readme_source.md index 07c1a8c..23bc0ba 100644 --- a/readme_source.md +++ b/readme_source.md @@ -108,9 +108,9 @@ Name|Display Name| Type|Default Value|Required When|Description ---|---|---|---|---|--- SiteName | IIS Site Name|String|Default Web Site|Adding, Removing, Reenrolling | IIS web site to bind certificate to IPAddress | IP Address | String | * | Adding, Removing, Reenrolling | IP address to bind certificate to (use '*' for all IP addresses) -Port | Port | String | 443 || Adding, Removing, Reenrolling|IP port for bind certificate to -HostName | Host Name | String |||| Host name (host header) to bind certificate to, leave blank for all host names -SniFlag | SNI Support | Multiple Choice | 0 - No SNI||Type of SNI for binding
(Multiple choice configuration should be entered as "0 - No SNI,1 - SNI Enabled,2 - Non SNI Binding,3 - SNI Binding") +Port | Port | String | 443 | Adding, Removing, Reenrolling|IP port for bind certificate to +HostName | Host Name | String ||| Host name (host header) to bind certificate to, leave blank for all host names +SniFlag | SNI Support | String |0| Adding, Removing, Reenrolling |A 128-Bit Flag that determines what type of SSL settings you wish to use. The default is 0, meaning No SNI. For more information, check IIS documentation for the appropriate bit setting.) Protocol | Protocol | Multiple Choice | https| Adding, Removing, Reenrolling|Protocol to bind to (always "https").
(Multiple choice configuration should be "https") ProviderName | Crypto Provider Name | String ||| Name of the Windows cryptographic provider to use during reenrollment jobs when generating and storing the private keys. If not specified, defaults to 'Microsoft Strong Cryptographic Provider'. This value would typically be specified when leveraging a Hardware Security Module (HSM). The specified cryptographic provider must be available on the target server being managed. The list of installed cryptographic providers can be obtained by running 'certutil -csplist' on the target Server. SAN | SAN | String || Reenrolling | Specifies Subject Alternative Name (SAN) to be used when performing reenrollment jobs. Certificate templates generally require a SAN that matches the subject of the certificate (per RFC 2818). Format is a list of = entries separated by ampersands. Examples: 'dns=www.mysite.com' for a single SAN or 'dns=www.mysite.com&dns=www.mysite2.com' for multiple SANs. Can be made optional if RFC 2818 is disabled on the CA.