首頁  >  文章  >  後端開發  >  如何從 golang tcp 握手中取得 clientCert.Subject.CommonName?

如何從 golang tcp 握手中取得 clientCert.Subject.CommonName?

王林
王林轉載
2024-02-06 09:36:03383瀏覽

如何从 golang tcp 握手中获取 clientCert.Subject.CommonName?

問題內容

我有很多客戶端使用不同的憑證連線到我的 TLS tcp 端點。我正在嘗試使用 RequireAndVerifyClientCert:

#
certPool := x509.NewCertPool()
    clientCACert, err := ioutil.ReadFile("client-ca.crt")
    if err != nil {
        log.Fatal(err)
    }
    certPool.AppendCertsFromPEM(clientCACert)

    // Create a base TLS config
    baseTLSConfig := &tls.Config{
        ClientCAs:    certPool,
        ClientAuth:   tls.RequireAndVerifyClientCert,
    }

因此,在我告訴它要使用哪個伺服器憑證和金鑰之前,我可以存取ConnectionState().PeerCertificates[0] 並首先讀取clientCert.Subject.CommonName 。即每個 CommonName 憑證需要不同的伺服器端憑證和金鑰。它不僅僅是用於所有連接的一個伺服器憑證和金鑰。

listener, err := tls.Listen("tcp", ":8080", baseTLSConfig)

    for {
        conn, _ := listener.Accept()
        clientCert := conn.(*tls.Conn).ConnectionState().PeerCertificates[0]
        switch clientCert.Subject.CommonName {

但是這個轉換失敗:(*tls.Conn) 並且我無法調用ConnectionState 或我進行另一個tcp.Server 調用,但len(PeerCertificates) 為零。我嘗試過:

GetConfigForClient: func(hello *tls.ClientHelloInfo) (*tls.Config, 錯誤) {

#將其傳遞給 tls.RequireAndVerifyClientCert 或除此之外,但 *tls.ClientHelloInfo 沒有我需要的資訊。


正確答案


無法根據客戶端憑證決定使用哪個伺服器憑證。

在 TLS 握手中,伺服器先傳送其伺服器證書,然後請求客戶端證書,只有在此之後客戶端才會將其客戶端證書傳送到伺服器。

以上是如何從 golang tcp 握手中取得 clientCert.Subject.CommonName?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除