Skip to content

Commit 6003556

Browse files
Get-DbaNetworkEncryption - Fix empty certificate properties by using SslStream.RemoteCertificate
Replace callback-based certificate capture ($script:capturedCertificate) with $sslStream.RemoteCertificate. Scriptblock callbacks invoked by .NET do not reliably write back to PowerShell session variables, so the captured variable stayed null and New-Object X509Certificate2($null) produced an empty object. Reading RemoteCertificate directly after AuthenticateAsClient is the correct approach. (do Get-DbaNetworkEncryption) Co-authored-by: Andreas Jordan <andreasjordan@users.noreply.github.com>
1 parent 1de6d6d commit 6003556

1 file changed

Lines changed: 7 additions & 6 deletions

File tree

public/Get-DbaNetworkEncryption.ps1

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -329,12 +329,11 @@ namespace DbaTools {
329329
# TdsWrappingStream adds/strips that framing so SslStream negotiates correctly.
330330
$tdsStream = New-Object DbaTools.TdsWrappingStream($networkStream, [byte]0x12)
331331

332-
# The server certificate is captured via the validation callback
333-
$script:capturedCertificate = $null
334-
335-
$certValidationCallback = {
332+
# Use a validation callback that always accepts the certificate so we can
333+
# complete the handshake regardless of chain/policy errors, then read
334+
# RemoteCertificate from the stream after authentication.
335+
$certValidationCallback = [System.Net.Security.RemoteCertificateValidationCallback] {
336336
param($sender, $certificate, $chain, $sslPolicyErrors)
337-
$script:capturedCertificate = $certificate
338337
return $true
339338
}
340339

@@ -346,7 +345,9 @@ namespace DbaTools {
346345

347346
$sslStream.AuthenticateAsClient($TargetHost)
348347

349-
return $script:capturedCertificate
348+
# RemoteCertificate is the reliable way to retrieve the server certificate
349+
# after a successful TLS handshake.
350+
return $sslStream.RemoteCertificate
350351
} catch {
351352
throw
352353
} finally {

0 commit comments

Comments
 (0)