Home  >  Article  >  Backend Development  >  How to fix proxyconnect tcp: tls: first record doesn't look like TLS handshake

How to fix proxyconnect tcp: tls: first record doesn't look like TLS handshake

王林
王林forward
2024-02-11 10:18:07606browse

如何修复 proxyconnect tcp: tls: 第一条记录看起来不像 TLS 握手

php editor Apple is here to bring you a solution to the "proxyconnect tcp: tls: first record does not look like TLS handshake" problem. This error usually occurs when using a proxy server and can cause network connection issues. Before we can solve this problem, we first need to understand the source of the problem. With the following simple steps, we'll show you how to fix this problem to ensure your network connection is functioning properly.

Question content

In How to use the REST API in Go, a fully working example code is provided to call the public REST API. But if I try the example I get this error:

error getting cat fact: 
      Get "https://catfact.ninja/fact": 
      proxyconnect tcp: tls: first record does not look like a TLS handshake

Documentation on http status

<code>
For control over proxies, TLS configuration, keep-alives, compression, and other settings, create a Transport:
</code>

And transfer documents:

<code>    // DialContext specifies the dial function for creating unencrypted TCP connections.
    // If DialContext is nil (and the deprecated Dial below is also nil),
    // then the transport dials using package net.
    //
    // DialContext runs concurrently with calls to RoundTrip.
    // A RoundTrip call that initiates a dial may end up using
    // a connection dialed previously when the earlier connection
    // becomes idle before the later DialContext completes.
    DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
</code>

So I'm assuming that I have to configure the Dialcontext to enable insecure connections from the client to the proxy without TLS. But I don't know how to do it. Read these:

  • How to do proxy and TLS in golang;
  • How to do HTTP/HTTPS GET through a proxy; and
  • How to perform https request with wrong certificate?

doesn't help either. Some have the same error proxyconnect tcp: tls:first record does not Look like a TLS handshake and explain why:

<code>
This is because the proxy answers with an plain HTTP error to the strange HTTP request (which is actually the start of the TLS handshake).
</code>

But Steffen's reply does not have sample code on how to set itDialContext func(ctx context.Context, network, addr string), Bogdan and cyberdelia both recommend setting tls.Config{InsecureSkipVerify: true}, for example

<code>    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
</code>

But the above has no effect. I still get the same error. And the connection still calls https://* instead of http://*

Here is sample code where I tried to include the above suggestions and adapt them:

<code>var tr = &http.Transport{ TLSClientConfig: 
                           &tls.Config{InsecureSkipVerify: true}, } 
                           // lacks DialContext config
var client*  http.Client = &http.Client{Transport: tr} // modified * added
// var client *http.Client // code from tutorial

type CatFact struct {
    Fact   string `json:"fact"`
    Length int    `json:"length"`
}

func GetCatFact() {
    url := "http://catfact.ninja/fact" // changed from https to http
    var catFact CatFact

    err := GetJson(url, &catFact)
    if err != nil {
        fmt.Printf("error getting cat fact: %s\n", err.Error())
    } else {
        fmt.Printf("A super interesting Cat Fact: %s\n", catFact.Fact)
    }
}

func main() {
    client = &http.Client{Timeout: 10 * time.Second}
    GetCatFact()
    // same error 
    // proxyconnect tcp: tls: first record does 
    //                   not look like a TLS handshake
    // still uses https 
    // for GET catfact.ninja
}
</code>

How do I configure the connection to use an unencrypted connection from myClient through a proxy to the server? Would setting DialContext func(ctx context.Context, network, addr string) help to do this? what to do?

Solution

I just tried:

package main

import (
    "context"
    "crypto/tls"
    "encoding/json"
    "fmt"
    "net"
    "net/http"
    "time"
)

type CatFact struct {
    Fact   string `json:"fact"`
    Length int    `json:"length"`
}

// Custom dialing function to handle connections
func customDialContext(ctx context.Context, network, addr string) (net.Conn, error) {
    conn, err := net.Dial(network, addr)
    return conn, err
}

// Function to get a cat fact
func GetCatFact(client *http.Client) {
    url := "https://catfact.ninja/fact"  // Reverted back to https
    var catFact CatFact

    err := GetJson(url, &catFact, client)
    if err != nil {
        fmt.Printf("error getting cat fact: %s\n", err.Error())
    } else {
        fmt.Printf("A super interesting Cat Fact: %s\n", catFact.Fact)
    }
}

// Function to send a GET request and decode the JSON response
func GetJson(url string, target interface{}, client *http.Client) error {
    resp, err := client.Get(url)
    if err != nil {
        return fmt.Errorf("error sending GET request: %w", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("received non-OK HTTP status: %d", resp.StatusCode)
    }

    err = json.NewDecoder(resp.Body).Decode(target)
    if err != nil {
        return fmt.Errorf("error decoding JSON response: %w", err)
    }

    return nil
}

func main() {
    // Create a custom Transport with the desired settings
    tr := &http.Transport{
        Proxy: http.ProxyFromEnvironment,  // Use the proxy settings from the environment
        DialContext: customDialContext,    // Use the custom dialing function
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,  // Skip certificate verification (not recommended in production)
        },
    }

    // Create a new HTTP client using the custom Transport
    client := &http.Client{
        Transport: tr,
        Timeout:   10 * time.Second,
    }

    // Call the function to get a cat fact
    GetCatFact(client)
}

it includes:

  • Custom dialing functioncustomDialContext
    This function is currently a simple wrapper around net.Dial, but it provides a place to introduce custom dialing logic if necessary. It is used as a custom dialing function for creating network connections.

  • Transmission configuration:

    • The modified code configures a custom http.Transport with specific settings, including custom dialing functionality, proxy settings in the environment, and a TLS configuration that skips certificate verification (for testing).
    • The original code also attempts to configure a custom http.Transport, but only contains a TLS configuration that skips certificate verification, and does not set custom dial-up capabilities or proxy settings.
  • Client configuration:

    • The modified code uses a custom http.Transport to create a new http.Client and sets the timeout to 10 seconds.
    • The original code also tries to create a new http.Client with a custom http.Transport, but then in the main function, it uses the new http.Client overrides the client variable, which contains the default Transport and a timeout of 10 seconds, effectively discarding the custom Transport.
  • Function signature:

    • The modified code modifies the GetCatFact and GetJson functions to accept the *http.Client parameter, allowing them to be used in main Custom http.Client created in.
    • The original code does not pass http.Client to these functions, so they will use the default http.Client provided by the net/http package.
  • Website:

    • The modified code restores the URL in the GetCatFact function to "https://catfact.ninja/fact" since the server redirects HTTP requests to HTTPS anyway.
    • The original code has changed the URL to "http://catfact.ninja/fact" to avoid TLS handshake errors.

The customDialContext function in the code provided above does not contain any logic to specifically ignore TLS handshake errors or change the TLS handshake to a non-TLS connection. It only provides custom dialing function. In the provided form, net.Dial is called directly without any special processing.

The mechanism for ignoring TLS certificate verification errors is actually provided by the TLSClientConfig field of the http.Transport structure, specifically by setting the InsecureSkipVerify field to true

tr := &http.Transport{
    TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}

该配置告诉 Go 跳过验证服务器的证书链和主机名,这是 TLS 握手过程的一部分。但是,它不会忽略其他类型的 TLS 握手错误或切换到非 TLS 连接。通常不建议在生产环境中使用 InsecureSkipVerify: true,因为它会禁用重要的安全检查。

如果您想强制使用非 TLS(纯 HTTP)连接,通常只需使用 http:// URL,而不是 https:// URL。但是,如果服务器或代理服务器将 HTTP 重定向到 HTTPS(例如 http://catfact.ninja/fact 的情况),则客户端将遵循重定向并切换到 TLS 连接。

The above is the detailed content of How to fix proxyconnect tcp: tls: first record doesn't look like TLS handshake. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete