TCP / TLS issue

This topic contains 2 replies, has 2 voices, and was last updated by  casparoff 2 years, 1 month ago.

  • Author
    Posts
  • #31022

    casparoff
    Participant

    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%28v=vs.100%29.aspx

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

    Could someone please point me to some direction?

  • #31029

    Dave Wyatt
    Moderator

    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.

  • #31043

    casparoff
    Participant

    Thank you Dave 🙂 I will try this

You must be logged in to reply to this topic.