Skip to content
Permalink
Browse files

New-DbaComputerCertificateSigningRequest - new command (#6166)

* Initial commit

* New-DbaComputerCertificateSigningRequest initial commit
  • Loading branch information...
potatoqualitee committed Oct 29, 2019
1 parent c9b5527 commit 6b0e851a31579e033c242cab47739adb5b22776c
@@ -600,6 +600,7 @@
'Get-DbaForceNetworkEncryption',
'Disable-DbaHideInstance',
'Enable-DbaHideInstance',
'New-DbaComputerCertificateSigningRequest',
'Remove-DbaComputerCertificate',
'New-DbaComputerCertificate',
'Get-DbaComputerCertificate',
@@ -851,6 +851,7 @@ $script:windowsonly = @(
'Get-DbaForceNetworkEncryption',
'Disable-DbaHideInstance',
'Enable-DbaHideInstance',
'New-DbaComputerCertificateSigningRequest',
'Remove-DbaComputerCertificate',
'New-DbaComputerCertificate',
'Get-DbaComputerCertificate',
@@ -0,0 +1,233 @@
function New-DbaComputerCertificateSigningRequest {
<#
.SYNOPSIS
Creates a new computer certificate signing request. Useful for offline servers and Forcing Encryption.
.DESCRIPTION
Creates a new computer certificate signing request that is compatible with SQL Server.
By default, a key with a length of 1024 and a friendly name of the machines FQDN is generated.
.PARAMETER ComputerName
The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must also specify ClusterInstanceName (see below)
.PARAMETER Credential
Allows you to login to $ComputerName using alternative credentials.
.PARAMETER Path
The folder to export to.
.PARAMETER ClusterInstanceName
When creating certs for a cluster, use this parameter to create the certificate for the cluster node name. Use ComputerName for each of the nodes.
.PARAMETER FriendlyName
The FriendlyName listed in the certificate. This defaults to the FQDN of the $ComputerName
.PARAMETER KeyLength
The length of the key - defaults to 1024
.PARAMETER Dns
Specify the Dns entries listed in SAN. By default, it will be ComputerName + FQDN, or in the case of clusters, clustername + cluster FQDN.
.PARAMETER EnableException
By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
.PARAMETER WhatIf
Shows what would happen if the command were to run. No actions are actually performed.
.PARAMETER Confirm
Prompts you for confirmation before executing any changing operations within the command.
.NOTES
Tags: Certificate
Author: Chrissy LeMaire (@cl), netnerds.net
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.EXAMPLE
PS C:\> New-DbaComputerCertificate
Creates a computer certificate signing request for the local machine with the keylength of 1024.
.EXAMPLE
PS C:\> New-DbaComputerCertificate -ComputerName Server1
Creates a computer certificate signing request for server1 with the keylength of 1024.
.EXAMPLE
PS C:\> New-DbaComputerCertificate -ComputerName sqla, sqlb -ClusterInstanceName sqlcluster -KeyLength 4096
Creates a computer certificate signing request for sqlcluster with the keylength of 4096.
.EXAMPLE
PS C:\> New-DbaComputerCertificate -ComputerName Server1 -WhatIf
Shows what would happen if the command were run
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseOutputTypeCorrectly", "", Justification = "PSSA Rule Ignored by BOH")]
param (
[parameter(ValueFromPipeline)]
[DbaInstance[]]$ComputerName = $env:COMPUTERNAME,
[PSCredential]$Credential,
[string]$ClusterInstanceName,
[string]$Path = (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport'),
[string]$FriendlyName = "SQL Server",
[int]$KeyLength = 1024,
[string[]]$Dns,
[switch]$EnableException
)
begin {
$englishCodes = 9, 1033, 2057, 3081, 4105, 5129, 6153, 7177, 8201, 9225
if ($englishCodes -notcontains (Get-DbaCmObject -ClassName Win32_OperatingSystem).OSLanguage) {
Stop-Function -Message "Currently, this command is only supported in English OS locales. OS Locale detected: $([System.Globalization.CultureInfo]::GetCultureInfo([int](Get-DbaCmObject Win32_OperatingSystem).OSLanguage).DisplayName)`nWe apologize for the inconvenience and look into providing universal language support in future releases."
return
}

function GetHexLength {
[cmdletbinding()]
param(
[int]$strLen
)
$hex = [String]::Format("{0:X2}", $strLen)

if ($strLen -gt 127) { [String]::Format("{0:X2}", 128 + ($hex.Length / 2)) + $hex }
else { $hex }
}

function Get-SanExt {
[cmdletbinding()]
param(
[string[]]$hostName
)
# thanks to Lincoln of
# https://social.technet.microsoft.com/Forums/windows/en-US/f568edfa-7f93-46a4-aab9-a06151592dd9/converting-ascii-to-asn1-der

$temp = ''
foreach ($fqdn in $hostName) {
# convert each character of fqdn to hex
$hexString = ($fqdn.ToCharArray() | ForEach-Object { [String]::Format("{0:X2}", [int]$_) }) -join ''

# length of hex fqdn, in hex
$hexLength = GetHexLength ($hexString.Length / 2)

# concatenate special code 82, hex length, hex string
$temp += "82${hexLength}${hexString}"
}
# calculate total length of concatenated string, in hex
$totalHexLength = GetHexLength ($temp.Length / 2)
# concatenate special code 30, hex length, hex string
$temp = "30${totalHexLength}${temp}"
# convert to binary
$bytes = $(
for ($i = 0; $i -lt $temp.Length; $i += 2) {
[byte]"0x$($temp.SubString($i, 2))"
}
)
# convert to base 64
$base64 = [Convert]::ToBase64String($bytes)
# output in proper format
for ($i = 0; $i -lt $base64.Length; $i += 64) {
$line = $base64.SubString($i, [Math]::Min(64, $base64.Length - $i))
if ($i -eq 0) { "2.5.29.17=$line" }
else { "_continue_=$line" }
}
}
}

process {
if (Test-FunctionInterrupt) {
return
}

if (-not (Test-ElevationRequirement -ComputerName $env:COMPUTERNAME)) {
return
}

# uses dos command locally

foreach ($computer in $ComputerName) {
$stepCounter = 0

if (-not $secondaryNode) {

if ($ClusterInstanceName) {
if ($ClusterInstanceName -notmatch "\.") {
$fqdn = "$ClusterInstanceName.$env:USERDNSDOMAIN"
} else {
$fqdn = $ClusterInstanceName
}
} else {
$resolved = Resolve-DbaNetworkName -ComputerName $computer.ComputerName -WarningAction SilentlyContinue

if (-not $resolved) {
$fqdn = "$ComputerName.$env:USERDNSDOMAIN"
Write-Message -Level Warning -Message "Server name cannot be resolved. Guessing it's $fqdn"
} else {
$fqdn = $resolved.fqdn
}
}

$certDir = "$Path\$fqdn"
$certCfg = "$certDir\request.inf"
$certCsr = "$certDir\$fqdn.csr"

if (Test-Path($certDir)) {
Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Deleting files from $certDir"
$null = Remove-Item "$certDir\*.*"
} else {
Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Creating $certDir"
$null = New-Item -Path $certDir -ItemType Directory -Force
}

# Make sure output is compat with clusters
$shortName = $fqdn.Split(".")[0]

if (-not $dns) {
$dns = $shortName, $fqdn
}

$san = Get-SanExt $dns
# Write config file
Set-Content $certCfg "[Version]"
Add-Content $certCfg 'Signature="$Windows NT$"'
Add-Content $certCfg "[NewRequest]"
Add-Content $certCfg "Subject = ""CN=$fqdn"""
Add-Content $certCfg "KeySpec = 1"
Add-Content $certCfg "KeyLength = $KeyLength"
Add-Content $certCfg "Exportable = TRUE"
Add-Content $certCfg "MachineKeySet = TRUE"
Add-Content $certCfg "FriendlyName=""$FriendlyName"""
Add-Content $certCfg "SMIME = False"
Add-Content $certCfg "PrivateKeyArchive = FALSE"
Add-Content $certCfg "UserProtected = FALSE"
Add-Content $certCfg "UseExistingKeySet = FALSE"
Add-Content $certCfg "ProviderName = ""Microsoft RSA SChannel Cryptographic Provider"""
Add-Content $certCfg "ProviderType = 12"
if ($SelfSigned) {
Add-Content $certCfg "RequestType = Cert"
} else {
Add-Content $certCfg "RequestType = PKCS10"
}
Add-Content $certCfg "KeyUsage = 0xa0"
Add-Content $certCfg "[EnhancedKeyUsageExtension]"
Add-Content $certCfg "OID=1.3.6.1.5.5.7.3.1"
Add-Content $certCfg "[Extensions]"
Add-Content $certCfg $san
Add-Content $certCfg "Critical=2.5.29.17"


if ($PScmdlet.ShouldProcess("local", "Creating certificate for $computer")) {
Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Running: certreq -new $certCfg $certCsr"
$null = certreq -new $certCfg $certCsr
}
Get-ChildItem $certCfg, $certCsr
}
}
}
}
@@ -4,11 +4,11 @@ Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan

Describe "$CommandName Unit Tests" -Tag 'UnitTests' {
Context "Validate parameters" {
[object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')}
[object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') }
[object[]]$knownParameters = 'ComputerName', 'Credential', 'CaServer', 'CaName', 'ClusterInstanceName', 'SecurePassword', 'FriendlyName', 'CertificateTemplate', 'KeyLength', 'Store', 'Folder', 'Dns', 'SelfSigned', 'EnableException'
$knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters
It "Should only contain our specific parameters" {
(@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0
(@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0
}
}
}
@@ -0,0 +1,22 @@
$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "")
Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan
. "$PSScriptRoot\constants.ps1"

Describe "$CommandName Unit Tests" -Tag 'UnitTests' {
Context "Validate parameters" {
[object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') }
[object[]]$knownParameters = 'ComputerName', 'Credential', 'ClusterInstanceName', 'Path', 'FriendlyName', 'KeyLength', 'Dns', 'EnableException'
$knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters
It "Should only contain our specific parameters" {
(@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0
}
}
}

Describe "$CommandName Integration Tests" -Tags "IntegrationTests" {
It "generates a new certificate" {
$files = New-DbaComputerCertificateSigningRequest
$files.Count | Should -Be 2
$files | Remove-Item -Confirm:$false
}
}

0 comments on commit 6b0e851

Please sign in to comment.
You can’t perform that action at this time.