|
| 1 | +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')] |
| 2 | +param () |
| 3 | + |
| 4 | +BeforeDiscovery { |
| 5 | + try |
| 6 | + { |
| 7 | + if (-not (Get-Module -Name 'DscResource.Test')) |
| 8 | + { |
| 9 | + # Assumes dependencies have been resolved, so if this module is not available, run 'noop' task. |
| 10 | + if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable)) |
| 11 | + { |
| 12 | + # Redirect all streams to $null, except the error stream (stream 2) |
| 13 | + & "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null |
| 14 | + } |
| 15 | + |
| 16 | + # If the dependencies have not been resolved, this will throw an error. |
| 17 | + Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop' |
| 18 | + } |
| 19 | + } |
| 20 | + catch [System.IO.FileNotFoundException] |
| 21 | + { |
| 22 | + throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.' |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +BeforeAll { |
| 27 | + $script:moduleName = 'SqlServerDsc' |
| 28 | + |
| 29 | + Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop' |
| 30 | +} |
| 31 | + |
| 32 | +# cSpell: ignore DSCSQLTEST |
| 33 | +Describe 'PostInstallationConfiguration' -Tag @('Integration_SQL2017', 'Integration_SQL2019', 'Integration_SQL2022') { |
| 34 | + Context 'When configuring SSL certificate for encryption support on DSCSQLTEST instance' { |
| 35 | + BeforeAll { |
| 36 | + $script:instanceName = 'DSCSQLTEST' |
| 37 | + $script:computerName = Get-ComputerName |
| 38 | + $script:computerNameFqdn = Get-ComputerName -FullyQualifiedDomainName |
| 39 | + $script:serviceAccountName = 'svc-SqlPrimary' |
| 40 | + } |
| 41 | + |
| 42 | + It 'Should verify the SQL Server instance is running with the expected service account' { |
| 43 | + $serviceName = "MSSQL`$$script:instanceName" |
| 44 | + $service = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$serviceName'" -ErrorAction 'Stop' |
| 45 | + |
| 46 | + $service | Should -Not -BeNullOrEmpty |
| 47 | + $service.State | Should -Be 'Running' |
| 48 | + $service.StartName | Should -BeLike "*\$script:serviceAccountName" |
| 49 | + } |
| 50 | + |
| 51 | + It 'Should create a self-signed certificate for SQL Server encryption' { |
| 52 | + # Create self-signed certificate with proper configuration for SQL Server |
| 53 | + $certificateParams = @{ |
| 54 | + Type = 'SSLServerAuthentication' |
| 55 | + Subject = "CN=$script:computerName" |
| 56 | + DnsName = @( |
| 57 | + $script:computerName |
| 58 | + $script:computerNameFqdn |
| 59 | + 'localhost' |
| 60 | + ) |
| 61 | + KeyAlgorithm = 'RSA' |
| 62 | + KeyLength = 2048 |
| 63 | + HashAlgorithm = 'SHA256' |
| 64 | + TextExtension = '2.5.29.37={text}1.3.6.1.5.5.7.3.1' |
| 65 | + NotAfter = (Get-Date).AddYears(3) |
| 66 | + KeySpec = 'KeyExchange' |
| 67 | + Provider = 'Microsoft RSA SChannel Cryptographic Provider' |
| 68 | + CertStoreLocation = 'cert:\LocalMachine\My' |
| 69 | + } |
| 70 | + |
| 71 | + $script:certificate = New-SelfSignedCertificate @certificateParams -ErrorAction 'Stop' |
| 72 | + |
| 73 | + $script:certificate | Should -Not -BeNullOrEmpty |
| 74 | + $script:certificate.Thumbprint | Should -Not -BeNullOrEmpty |
| 75 | + $script:certificateThumbprint = $script:certificate.Thumbprint |
| 76 | + } |
| 77 | + |
| 78 | + It 'Should export the certificate to file' { |
| 79 | + $script:certificatePath = Join-Path -Path $env:TEMP -ChildPath 'SqlServerEncryption.cer' |
| 80 | + |
| 81 | + Export-Certificate -Cert $script:certificate -FilePath $script:certificatePath -ErrorAction 'Stop' |
| 82 | + |
| 83 | + Test-Path -Path $script:certificatePath | Should -BeTrue |
| 84 | + } |
| 85 | + |
| 86 | + It 'Should import certificate to Trusted Root Certification Authorities' { |
| 87 | + # Import to trusted root for self-signed certificates |
| 88 | + Import-Certificate -FilePath $script:certificatePath -CertStoreLocation 'Cert:\LocalMachine\Root' -ErrorAction 'Stop' |
| 89 | + |
| 90 | + # Verify certificate is in trusted root |
| 91 | + $trustedCert = Get-ChildItem -Path 'Cert:\LocalMachine\Root' | Where-Object -FilterScript { $_.Thumbprint -eq $script:certificateThumbprint } |
| 92 | + $trustedCert | Should -Not -BeNullOrEmpty |
| 93 | + } |
| 94 | + |
| 95 | + It 'Should grant SQL Server service account permission to certificate private key' { |
| 96 | + # Get the certificate from the Personal store |
| 97 | + $cert = Get-ChildItem -Path "Cert:\LocalMachine\My\$script:certificateThumbprint" -ErrorAction 'Stop' |
| 98 | + |
| 99 | + # Get the private key |
| 100 | + $rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert) |
| 101 | + $privateKeyPath = $rsaCert.Key.UniqueName |
| 102 | + |
| 103 | + # Build the full path to the private key file |
| 104 | + $privateKeyFile = Join-Path -Path "$env:ALLUSERSPROFILE\Microsoft\Crypto\RSA\MachineKeys" -ChildPath $privateKeyPath |
| 105 | + |
| 106 | + # Verify the private key file exists |
| 107 | + Test-Path -Path $privateKeyFile | Should -BeTrue |
| 108 | + |
| 109 | + # Grant read permission to the SQL Server service account |
| 110 | + $acl = Get-Acl -Path $privateKeyFile -ErrorAction 'Stop' |
| 111 | + $accessRule = [System.Security.AccessControl.FileSystemAccessRule]::new( |
| 112 | + $script:serviceAccountName, |
| 113 | + [System.Security.AccessControl.FileSystemRights]::Read, |
| 114 | + [System.Security.AccessControl.AccessControlType]::Allow |
| 115 | + ) |
| 116 | + $acl.AddAccessRule($accessRule) |
| 117 | + Set-Acl -Path $privateKeyFile -AclObject $acl -ErrorAction 'Stop' |
| 118 | + |
| 119 | + # Verify permission was granted |
| 120 | + $updatedAcl = Get-Acl -Path $privateKeyFile -ErrorAction 'Stop' |
| 121 | + $serviceAccountAccess = $updatedAcl.Access | Where-Object -FilterScript { |
| 122 | + $_.IdentityReference -like "*$script:serviceAccountName*" -and $_.FileSystemRights -match 'Read' |
| 123 | + } |
| 124 | + $serviceAccountAccess | Should -Not -BeNullOrEmpty |
| 125 | + } |
| 126 | + |
| 127 | + It 'Should configure SQL Server instance to use the certificate' { |
| 128 | + # Get the SQL Server instance registry key path |
| 129 | + # For named instance DSCSQLTEST, the registry path includes the instance name |
| 130 | + $registryPath = "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL*.$script:instanceName\MSSQLServer\SuperSocketNetLib" |
| 131 | + |
| 132 | + # Find the actual registry path (version number varies) |
| 133 | + $actualRegistryPath = Get-Item -Path $registryPath -ErrorAction 'Stop' | Select-Object -First 1 -ExpandProperty Name |
| 134 | + $actualRegistryPath = "Registry::$actualRegistryPath" |
| 135 | + |
| 136 | + # Set the certificate thumbprint (without spaces) |
| 137 | + $thumbprintValue = $script:certificateThumbprint -replace '\s', '' |
| 138 | + Set-ItemProperty -Path $actualRegistryPath -Name 'Certificate' -Value $thumbprintValue -ErrorAction 'Stop' |
| 139 | + |
| 140 | + # Verify the certificate was set |
| 141 | + $setCertificate = Get-ItemProperty -Path $actualRegistryPath -Name 'Certificate' -ErrorAction 'Stop' |
| 142 | + $setCertificate.Certificate | Should -Be $thumbprintValue |
| 143 | + } |
| 144 | + |
| 145 | + It 'Should restart SQL Server service to apply certificate changes' { |
| 146 | + $serviceName = "MSSQL`$$script:instanceName" |
| 147 | + |
| 148 | + # Restart the SQL Server service |
| 149 | + Restart-Service -Name $serviceName -Force -ErrorAction 'Stop' |
| 150 | + |
| 151 | + # Wait for service to be running |
| 152 | + $maxRetries = 30 |
| 153 | + $retryCount = 0 |
| 154 | + do { |
| 155 | + Start-Sleep -Seconds 2 |
| 156 | + $service = Get-Service -Name $serviceName -ErrorAction 'Stop' |
| 157 | + $retryCount++ |
| 158 | + } while ($service.Status -ne 'Running' -and $retryCount -lt $maxRetries) |
| 159 | + |
| 160 | + $service.Status | Should -Be 'Running' |
| 161 | + |
| 162 | + Write-Verbose -Message "SQL Server instance $script:instanceName restarted with SSL certificate configuration" -Verbose |
| 163 | + } |
| 164 | + |
| 165 | + It 'Should verify SQL Server is online without using the certificate for encryption' { |
| 166 | + # Connect to SQL Server and verify encryption is available |
| 167 | + $sqlAdministratorUserName = 'SqlAdmin' |
| 168 | + $sqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force |
| 169 | + $credential = [System.Management.Automation.PSCredential]::new($sqlAdministratorUserName, $sqlAdministratorPassword) |
| 170 | + |
| 171 | + $serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:instanceName -Credential $credential -ErrorAction 'Stop' |
| 172 | + |
| 173 | + # The server should be online |
| 174 | + $serverObject.Status.ToString() | Should -Match '^Online$' |
| 175 | + |
| 176 | + # Clean up |
| 177 | + Disconnect-SqlDscDatabaseEngine -ServerObject $serverObject -ErrorAction 'Stop' |
| 178 | + } |
| 179 | + |
| 180 | + It 'Should verify the connection is using encryption via DMV query' { |
| 181 | + # Connect to SQL Server with encryption enabled |
| 182 | + $sqlAdministratorUserName = 'SqlAdmin' |
| 183 | + $sqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force |
| 184 | + $credential = [System.Management.Automation.PSCredential]::new($sqlAdministratorUserName, $sqlAdministratorPassword) |
| 185 | + |
| 186 | + $serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:instanceName -Credential $credential -Encrypt -ErrorAction 'Stop' |
| 187 | + |
| 188 | + # Query sys.dm_exec_connections to verify encryption is being used |
| 189 | + # See: https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-sql-server-encryption?view=sql-server-ver17#verify-network-encryption |
| 190 | + $encryptionQuery = @" |
| 191 | +SELECT |
| 192 | + session_id, |
| 193 | + encrypt_option, |
| 194 | + net_transport |
| 195 | +FROM sys.dm_exec_connections |
| 196 | +WHERE session_id = @@SPID |
| 197 | +"@ |
| 198 | + |
| 199 | + $result = Invoke-SqlDscQuery -ServerObject $serverObject -DatabaseName 'master' -Query $encryptionQuery -PassThru -Force -ErrorAction 'Stop' |
| 200 | + |
| 201 | + # Verify the connection is encrypted |
| 202 | + $result | Should -Not -BeNullOrEmpty |
| 203 | + $result.Tables[0].Rows.Count | Should -Be 1 |
| 204 | + $result.Tables[0].Rows[0]['encrypt_option'] | Should -Be 'TRUE' |
| 205 | + |
| 206 | + # Clean up |
| 207 | + Disconnect-SqlDscDatabaseEngine -ServerObject $serverObject -ErrorAction 'Stop' |
| 208 | + |
| 209 | + Write-Verbose -Message "Verified encrypted connection using sys.dm_exec_connections DMV" -Verbose |
| 210 | + Write-Verbose -Message "SSL certificate successfully configured for SQL Server instance $script:instanceName" -Verbose |
| 211 | + } |
| 212 | + } |
| 213 | +} |
0 commit comments