dongpao5658 2016-02-14 10:29
浏览 224
已采纳

在GoLang中执行反向代理时确认TLS证书

In GoLang I'm using NewSingleHostReverseProxy to preform a reverse proxy, however I need to confirm the SSL certificates of the host site, to make sure I have the correct secure certificate... any ideas how I should do this? Should I be doing this with the handler or transport? I'm new to GoLang and still getting my head around it. Thanks

proxy := httputil.NewSingleHostReverseProxy(&url.URL{
         Scheme: "https",
         Host:   "sha256.badssl.com",
})

http.ListenAndServe("127.0.0.1:80", proxy)
  • 写回答

2条回答 默认 最新

  • dongrao1862 2016-02-15 00:18
    关注

    To access the certificate, you will have get access to the ConnectionState. The easiest way to do that is to provide your own version of DialTLS. In there you connect to the server using net.Dial, do the TLS handshake and then you are free to verify.

    package main
    
    import (
        "crypto/tls"
        "log"
        "net"
        "net/http"
        "net/http/httputil"
        "net/url"
    )
    
    func main() {
        proxy := httputil.NewSingleHostReverseProxy(&url.URL{
            Scheme: "https",
            Host:   "sha256.badssl.com",
        })
    
        // Set a custom DialTLS to access the TLS connection state
        proxy.Transport = &http.Transport{DialTLS: dialTLS}
    
        // Change req.Host so badssl.com host check is passed
        director := proxy.Director
        proxy.Director = func(req *http.Request) {
            director(req)
            req.Host = req.URL.Host
        }
    
        log.Fatal(http.ListenAndServe("127.0.0.1:3000", proxy))
    }
    
    func dialTLS(network, addr string) (net.Conn, error) {
        conn, err := net.Dial(network, addr)
        if err != nil {
            return nil, err
        }
    
        host, _, err := net.SplitHostPort(addr)
        if err != nil {
            return nil, err
        }
        cfg := &tls.Config{ServerName: host}
    
        tlsConn := tls.Client(conn, cfg)
        if err := tlsConn.Handshake(); err != nil {
            conn.Close()
            return nil, err
        }
    
        cs := tlsConn.ConnectionState()
        cert := cs.PeerCertificates[0]
    
        // Verify here
        cert.VerifyHostname(host)
        log.Println(cert.Subject)
    
        return tlsConn, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?