Golang 证书验证

Hel*_*röm 1 ssl cryptography go x509

我正在使用 Go 通过自定义根 CA 执行 HTTPS 请求。根 CA 是我拥有的唯一证书。

我的代码如下所示:

// performRequest sets up the HTTPS Client we'll use for communication and handle the actual requesting to the external
// end point. It is used by the auth and collect adapters who set their response data up first.
func performRequest(rawData []byte, soapHeader string) (*http.Response, error) {
  conf := config.GetConfig()

  // Set up the certificate handler and the HTTP client.
  certPool := x509.NewCertPool()
  certPool.AppendCertsFromPEM(certificate)
  client := &http.Client{
    Transport: &http.Transport{
      TLSClientConfig: &tls.Config{
        RootCAs:            certPool,
        InsecureSkipVerify: false,
      },
    },
  }

  req, err := http.NewRequest(http.MethodPost, baseURL, bytes.NewBuffer(rawData))
  if err != nil {
    return nil, err
  }

  // Sets the SOAPAction and Content-Type headers to the request.
  req.Header.Set("SOAPAction", soapHeader)
  req.Header.Set("Content-Type", "text/xml; charset=UTF-8")

  // Send request as our custom client, return response
  return client.Do(req)
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是这样的:

2017/12/09 21:06:13 Post https://secure.site: x509: certificate is not valid for any names, but wanted to match secure.site
Run Code Online (Sandbox Code Playgroud)

我一直无法查明这到底是什么原因。当检查 CA 证书的 SAN 时,我在那里没有secure.site(根本没有名称,如错误所述),但我看不出我是如何做错的。

我应该怎么做才能解决这个问题?

Mar*_*arc 5

你需要做两件事:

  1. 服务器端也要添加CA证书,CA需要各方都知道。
  2. 在服务器上生成并使用服务器证书(证书中包含主机名)。服务器证书需要由 CA 签名。

你可以在这里找到一个例子(第一个谷歌示例)

编辑:澄清一下,该错误是由于您尝试安全连接到远程主机而导致的。默认情况下,go 客户端将查找服务器返回的有效证书。

有效手段(除其他外):

  1. 它是由已知的 CA 签名的
  2. 它在或字段中包含服务器的 ip/dns(您传递给的服务器http.NewRequest)。CommonNameSubject Alternative Name: DNS/IP

最终编辑

服务器证书包含Common Name服务器主机名的正确设置,但还包含Subject Alternative Name电子邮件地址的设置。

正如https://groups.google.com/a/chromium.org/forum/#!topic/security-dev/IGT2fLJrAeo中提到的,Go 现在会忽略Common Name是否找到 SAN。

  • “...如果找到 SAN,Go 现在会忽略通用名称...”根据 RFC 2818,这是一个纯粹且简单的错误。 (2认同)