我被委托创建一个反向代理,该代理需要与被代理的服务建立TLS连接。我拥有的证书是每个请求独特的、存储在内存中的。
我尝试了很多方法,但仍未成功。以下是我的现状,希望有人可以帮忙:
func proxy(c *gin.Context) {
/* snip: magic here to get the x509 cert strings and remoteUrl */
proxy := httputil.NewSingleHostReverseProxy(remoteUrl)
cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte(signedCertString)})
key:= pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte(privateKeyString)})
certificate, err := tls.X509KeyPair(cert, key)
if err != nil {
c.JSON(400, gin.H{"message": "Invalid certificate"})
return
}
proxy.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{certificate},
InsecureSkipVerify: true,
}
}
c.Request.Host = remote.Host
c.Request.URL.Scheme = remote.Scheme
c.Request.URL.Host = remote.Host
c.Request.URL.Path = remote.Path
proxy.ServeHTTP(c.Writer, c.Request)
}
我还尝试设置RootCAs
(想着也许是因为我现在扭曲了关于TLS在这种情况下需要工作的想法):
func proxy(c *gin.Context) {
/* snip: magic here to get the x509 cert strings and remoteUrl */
proxy := httputil.NewSingleHostReverseProxy(remoteUrl)
cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte(signedCertString)})
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(cert)
proxy.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certPool,
InsecureSkipVerify: true,
}
}
c.Request.Host = remote.Host
c.Request.URL.Scheme = remote.Scheme
c.Request.URL.Host = remote.Host
c.Request.URL.Path = remote.Path
proxy.ServeHTTP(c.Writer, c.Request)
}
无论如何,我要定位的服务器似乎没有察觉到代理请求是TLS加密传输,我不确定该如何继续处理。