TCP / TLS issue

Hi All.

I’m trying to make TCP / TLS connection and I keep getting:

Exception calling "AuthenticateAsClient" with "1" argument(s): "The handshake failed due to an unexpected packet format.

My code is below:

$tcpClient = New-Object System.Net.Sockets.TcpClient($ipAddress, $port)
$stream = $tcpClient.GetStream()
$sslStream = New-Object System.Net.Security.SslStream $stream,$false

$sslStream.AuthenticateAsClient($cn)

I’m thinking that using this constructor for TcpClient could help https://msdn.microsoft.com/en-us/library/ms145056(v=vs.100).aspx

But I don’t know how to create validation delegate in powershell.

Could someone please point me to some direction?

PowerShell will allow you to pass any ScriptBlock object to a .NET method which expects a delegate or Func/Action object. In this case, RemoteCertificateValidationCallback is passed 4 arguments, and expected to return a bool, so you could do this:

$delegate = {
    param (
        [object] $Sender,
        [System.Security.Cryptography.X509Certificates.X509Certificate] $Certificate,
        [System.Security.Cryptography.X509Certificates.X509Chain] $Chain,
        [System.Net.Security.SslPolicyErrors] $SslPolicyErrors
    )

    # some logic here

    return $true
}

$sslStream = New-Object System.Net.Security.SslStream($stream, $false, $delegate)

You don’t have to use a param block if you don’t want to (in which case you would refer to $args[0] through $args[3]), and you don’t have to assign the delegate to another variable before calling your constructor, but those things can often make the code easier to read.

Thank you Dave :slight_smile: I will try this