http.ListenAndServeTLS with multiple certificates

2020-06-23 05:52发布

How do I ListenAndServeTLS with multiple domains? I see the function accepts a cert and key file, but I believe the key file may only contain a single private key. I have a few private keys, for different certificate chains.

标签: ssl go https
2条回答
Evening l夕情丶
2楼-- · 2020-06-23 06:27

http.ListenAndServeTLS is meant to be present a bare minimal configuration. If you want to add other options, you can create an http.Server with a custom tls.Config. You can then either manually map names in tls.Config.NameToCertificate, or call BuildNameToCertificate() to build the map programatically.

You can still use Server.ListenAndServeTLS however, since it will load the certs in the config as well a cert passed in via the methods args.

cfg := &tls.Config{}

cert, err := tls.LoadX509KeyPair("cert_one.pem", "key_one.pem")
if err != nil {
    log.Fatal(err)
}

cfg.Certificates = append(cfg.Certificates, cert)
// keep adding remaining certs to cfg.Certificates

cfg.BuildNameToCertificate()

server := http.Server{
    Addr:      "127.0.0.1:443",
    Handler:   myHandler,
    TLSConfig: cfg,
}

server.ListenAndServeTLS("", "")
查看更多
啃猪蹄的小仙女
3楼-- · 2020-06-23 06:27

I'm no Go user myself but if you want to use multiple certificates on the same TLS listener you must have some way to decide which certificate should be used once a client connects because only a single certificate + chain can be sent inside the TLS handshake.

The main use case for this is Server Name Indication (SNI). With SNI you have multiple certificates and you want to select the appropriate one based on the name the client asked for within the TLS handshake.

Searching for go sni server results in this post from 2013. This post shows that using multiple certificates with ListenAndServeTLS is not possible (or was in 2013) but it also shows how to achieve the necessary functionality.

查看更多
登录 后发表回答