Извлечение общего имени из входящего запроса https в Голанге - PullRequest
1 голос
/ 04 июня 2019

Мой API находится за шлюзом, и шлюз завершает рукопожатие ssl от клиента и инициирует отдельное рукопожатие с моим API. Ни один клиент не должен вызывать мой API напрямую. Мое требование заключается в том, что я должен извлечь общее имя из входящего запроса https и проверить его по списку.

Я новичок в работе с go и использовал этот пример https://venilnoronha.io/a-step-by-step-guide-to-mtls-in-go в качестве отправной точки для создания сервера go с использованием https.

Но не уверен, как перейти к извлечению COMMON NAME from the leaf certificate из цепочки сертификатов.

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!\n")
}

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"))

}

Я должен быть в состоянии print the Common Name of the leaf certificate войти в цепочку сертификатов.

1 Ответ

2 голосов
/ 04 июня 2019

Вы можете получить его из VerifiedChains члена поля TLS запроса:

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!\n", commonName))
    }

    // Write "Hello, world!" to the response body
    io.WriteString(w, "Hello, world!\n")
}

Листовой сертификат всегда первый в цепочке.

...