Go (autocert)¶
A web server written in Go can get its certificate itself with
golang.org/x/crypto/acme/autocert: on the first TLS connection for a
name, it gets a certificate from BastionXP CA over tls-alpn-01, keeps it
in its cache, and renews it in the background.
main.go
package main
import (
"crypto/tls"
"crypto/x509"
"log"
"net/http"
"os"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
)
func main() {
// Trust BastionXP CA's root for the connection to the CA.
root, err := os.ReadFile("/etc/myapp/bastionxp-ca-root.crt")
if err != nil {
log.Fatal(err)
}
roots := x509.NewCertPool()
roots.AppendCertsFromPEM(root)
caClient := &http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: roots},
}}
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist("app.corp.internal"),
Cache: autocert.DirCache("/var/lib/myapp/autocert"),
Client: &acme.Client{
DirectoryURL: "https://ca.example.com:8443/acme/directory",
HTTPClient: caClient,
},
}
srv := &http.Server{
Addr: ":443",
TLSConfig: m.TLSConfig(),
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello\n")) }),
}
log.Fatal(srv.ListenAndServeTLS("", ""))
}
HostPolicylists the names the server may ask for; without it, any name a client sends would start an order.- The server must listen on port 443, where the CA connects for
tls-alpn-01. To usehttp-01as well, servem.HTTPHandler(nil)on port 80. - Keep the cache directory: it holds the certificates and their keys, so a restart does not ask the CA again.
- autocert renews when a third of the certificate's lifetime is left: for a 24-hour certificate, 8 hours before it ends.
Tested
BastionXP CA's end-to-end tests run a Go server with autocert (from
golang.org/x/crypto v0.58.0) against the CA on every change: it gets
its certificate on the first connection, and uses its cache after a
restart.