登录
首页 >  Golang >  Go问答

了解双向 TLS 、带有服务器名称的客户端配置

来源:stackoverflow

时间:2024-03-17 08:54:28 304浏览 收藏

双向 TLS 是一种安全通信协议,要求客户端和服务器相互验证身份。当客户端尝试连接到具有特定服务器名称(例如“svc1.example.com”)的服务器时,如果服务器的证书与该名称不匹配,则会出现错误。为了解决此问题,客户端可以配置其 TLS 客户端配置以包含服务器名称或使用自定义函数来验证服务器证书,检查证书的主题公用名是否与预期的服务器名称匹配。

问题内容

我试图了解双向 tls 的工作原理,我有以下示例:

我有一个客户端想要连接到服务器“svc1.example.com”

但是服务器有

公共名称为“svc1.example.cloud”和 san 的服务器证书 作为“svc.example.test.cloud”。

现在,当我发出 get 请求时,我会收到以下内容:

x509:证书对 svc.example.test.cloud 有效,对 svc1.example.com 无效。

所以,我的问题是我应该更改 tls clientconfig 以包含服务器名称吗?或者我应该在 tls 客户端配置中添加自定义 verifypeercertificate 函数,如下所示?

请告诉我,服务器名称应该是什么,以及我应该在 verifypeercertificate 函数中检查什么。

func customverify(customCName func(*x509.Certificate) bool) func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
    if customCName == nil {
        return nil
    }
    return func(_ [][]byte, verifiedChains [][]*x509.Certificate) error {
        for _, certs := range verifiedChains {
            leaf := certs[0]
            if customCName(leaf) {
                return nil
            }
        }
        return fmt.Errorf("client identity verification failed")
    }
}




func configureClient(certFile, keyFile string) (*http.Client, error) {
    certpool, err := addRootCA()
    if err != nil {
        return nil, err
    }

cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
    return nil, err
}
transport := ytls.NewClientTransport()
transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
transport.TLSClientConfig.RootCAs = certpool
//transport.TLSClientConfig.ServerName = expectedCName
transport.TLSClientConfig.VerifyPeerCertificate = customverify(func(cert *x509.Certificate) bool {
    return cert.Subject.CommonName == "svc1.example.cloud"
})

httpClient := &http.Client{Transport: transport}
return httpClient, nil

}


解决方案


由于x509:证书对 svc.example.test.cloud 有效,因此 transport.TLSClientConfig.ServerName = "svc.example.test.cloud"

来自https://golang.org/pkg/crypto/tls/#Config

VerifyPeerCertificate,如果不为零,则在正常之后调用
由 TLS 客户端或服务器进行证书验证。它
接收对等方提供的原始 ASN.1 证书,并且
正常处理发现的任何经过验证的链。如果它返回一个
非零错误,握手被中止并导致错误。

如果正常验证失败,则握手将在之前中止
考虑这个回调。如果正常验证被禁用
设置 InsecureSkipVerify,或(对于服务器)当 ClientAuth 为
RequestClientCert 或 RequireAnyClientCert,则此回调将
被考虑,但 verifyChains 参数将始终为零。

VerifyPeerCertificate func(rawCerts [][]byte,verifiedChains [][]*x509.Certificate)错误

因此,如果正常验证失败,则 VerifyPeerCertificate 将不会被调用。另外,如果正常验证通过,我认为您不需要这个额外的检查 VerifyPeerCertificate

理论要掌握,实操不能落!以上关于《了解双向 TLS 、带有服务器名称的客户端配置》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>