douya7121 2019-06-03 21:13
浏览 203
已采纳

从golang中传入的https请求中提取通用名称

My api is behind a gateway and the gateway terminates the ssl handshake from client and initiate a separate handshake with my api. No client should call my api directly. My requirement is that I have to extract the Common Name from incoming https request and validate it against a list.

I am new to go and used this example https://venilnoronha.io/a-step-by-step-guide-to-mtls-in-go as my starting point to build a go server using https.

But not sure how can I move further to to extract COMMON NAME from the leaf certificate of the certificate chain.

package main

import (
    "crypto/tls"
    "crypto/x509"
    "io"
    "io/ioutil"
    "log"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    // Write "Hello, world!" to the response body
    io.WriteString(w, "Hello, world!
")
}

func main() {
    // Set up a /hello resource handler
    http.HandleFunc("/hello", helloHandler)

    // Create a CA certificate pool and add cert.pem to it
    caCert, err := ioutil.ReadFile("cert.pem")
    if err != nil {
        log.Fatal(err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    // Create the TLS Config with the CA pool and enable Client certificate validation
    tlsConfig := &tls.Config{
        ClientCAs:  caCertPool,
        ClientAuth: tls.RequireAndVerifyClientCert,
    }
    tlsConfig.BuildNameToCertificate()

    // Create a Server instance to listen on port 8443 with the TLS config
    server := &http.Server{
        Addr:      ":8443",
        TLSConfig: tlsConfig,
    }

    // Listen to HTTPS connections with the server certificate and wait
    log.Fatal(server.ListenAndServeTLS("cert.pem", "key.pem"))

}

I should be able to print the Common Name of the leaf certificate coming in the certificate chain.

  • 写回答

1条回答 默认 最新

  • dpl22899 2019-06-03 21:23
    关注

    You can retrieve it from the VerifiedChains member of the request's TLS field:

    func helloHandler(w http.ResponseWriter, r *http.Request) {
        if r.TLS != nil && len(r.TLS.VerifiedChains) > 0 && len(r.TLS.VerifiedChains[0]) > 0 {
            var commonName = r.TLS.VerifiedChains[0][0].Subject.CommonName
    
            // Do what you want with the common name.
            io.WriteString(w, fmt.Sprintf("Hello, %s!
    ", commonName))
        }
    
        // Write "Hello, world!" to the response body
        io.WriteString(w, "Hello, world!
    ")
    }
    

    The leaf certificate is always the first one in the chain.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器