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

在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条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?