16552: Option to get TLS certificates automatically from LE.
[arvados.git] / lib / boot / cert.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package boot
6
7 import (
8         "context"
9         "crypto/rsa"
10         "crypto/tls"
11         "crypto/x509"
12         "encoding/pem"
13         "errors"
14         "fmt"
15         "io/ioutil"
16         "net"
17         "net/http"
18         "net/url"
19         "os"
20         "path/filepath"
21         "strings"
22         "time"
23
24         "golang.org/x/crypto/acme"
25         "golang.org/x/crypto/acme/autocert"
26 )
27
28 const stagingDirectoryURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
29
30 var errInvalidHost = errors.New("unrecognized target host in incoming TLS request")
31
32 type createCertificates struct{}
33
34 func (createCertificates) String() string {
35         return "certificates"
36 }
37
38 func (createCertificates) Run(ctx context.Context, fail func(error), super *Supervisor) error {
39         if super.cluster.TLS.Automatic {
40                 return bootAutoCert(ctx, fail, super)
41         } else if super.cluster.TLS.Key == "" && super.cluster.TLS.Certificate == "" {
42                 return createSelfSignedCert(ctx, fail, super)
43         } else {
44                 return nil
45         }
46 }
47
48 // bootAutoCert uses Let's Encrypt to get certificates for all the
49 // domains appearing in ExternalURLs, writes them to files where Nginx
50 // can load them, and updates super.cluster.TLS fields (Key and
51 // Certificiate) to point to those files.
52 //
53 // It also runs a background task to keep the files up to date.
54 //
55 // After bootAutoCert returns, other service components will get the
56 // certificates they need by reading these files or by using a
57 // read-only autocert cache.
58 //
59 // Currently this only works when port 80 of every ExternalURL domain
60 // is routed to this host, i.e., on a single-node cluster. Wildcard
61 // domains [for WebDAV] are not supported.
62 func bootAutoCert(ctx context.Context, fail func(error), super *Supervisor) error {
63         hosts := map[string]bool{}
64         for _, svc := range super.cluster.Services.Map() {
65                 u := url.URL(svc.ExternalURL)
66                 if u.Scheme == "https" || u.Scheme == "wss" {
67                         hosts[strings.ToLower(u.Hostname())] = true
68                 }
69         }
70         mgr := &autocert.Manager{
71                 Cache:  autocert.DirCache(super.tempdir + "/autocert"),
72                 Prompt: autocert.AcceptTOS,
73                 HostPolicy: func(ctx context.Context, host string) error {
74                         if hosts[strings.ToLower(host)] {
75                                 return nil
76                         } else {
77                                 return errInvalidHost
78                         }
79                 },
80         }
81         if super.cluster.TLS.Staging {
82                 mgr.Client = &acme.Client{DirectoryURL: stagingDirectoryURL}
83         }
84         go func() {
85                 err := http.ListenAndServe(":80", mgr.HTTPHandler(nil))
86                 fail(fmt.Errorf("autocert http-01 challenge handler stopped: %w", err))
87         }()
88         u := url.URL(super.cluster.Services.Controller.ExternalURL)
89         extHost := u.Hostname()
90         update := func() error {
91                 for h := range hosts {
92                         cert, err := mgr.GetCertificate(&tls.ClientHelloInfo{ServerName: h})
93                         if err != nil {
94                                 return err
95                         }
96                         if h == extHost {
97                                 err = writeCert(super.tempdir, "server.key", "server.crt", cert)
98                                 if err != nil {
99                                         return err
100                                 }
101                         }
102                 }
103                 return nil
104         }
105         err := update()
106         if err != nil {
107                 return err
108         }
109         go func() {
110                 for range time.NewTicker(time.Hour).C {
111                         err := update()
112                         if err != nil {
113                                 super.logger.WithError(err).Error("error getting certificate from autocert")
114                         }
115                 }
116         }()
117         super.cluster.TLS.Key = "file://" + super.tempdir + "/server.key"
118         super.cluster.TLS.Certificate = "file://" + super.tempdir + "/server.crt"
119         return nil
120 }
121
122 // Save cert chain and key in a format Nginx can read.
123 func writeCert(outdir, keyfile, certfile string, cert *tls.Certificate) error {
124         keytmp, err := os.CreateTemp(outdir, keyfile+".tmp.*")
125         if err != nil {
126                 return err
127         }
128         defer keytmp.Close()
129         defer os.Remove(keytmp.Name())
130
131         certtmp, err := os.CreateTemp(outdir, certfile+".tmp.*")
132         if err != nil {
133                 return err
134         }
135         defer certtmp.Close()
136         defer os.Remove(certtmp.Name())
137
138         switch privkey := cert.PrivateKey.(type) {
139         case *rsa.PrivateKey:
140                 err = pem.Encode(keytmp, &pem.Block{
141                         Type:  "RSA PRIVATE KEY",
142                         Bytes: x509.MarshalPKCS1PrivateKey(privkey),
143                 })
144                 if err != nil {
145                         return err
146                 }
147         default:
148                 buf, err := x509.MarshalPKCS8PrivateKey(privkey)
149                 if err != nil {
150                         return err
151                 }
152                 err = pem.Encode(keytmp, &pem.Block{
153                         Type:  "PRIVATE KEY",
154                         Bytes: buf,
155                 })
156                 if err != nil {
157                         return err
158                 }
159         }
160         err = keytmp.Close()
161         if err != nil {
162                 return err
163         }
164
165         for _, cert := range cert.Certificate {
166                 err = pem.Encode(certtmp, &pem.Block{
167                         Type:  "CERTIFICATE",
168                         Bytes: cert,
169                 })
170                 if err != nil {
171                         return err
172                 }
173         }
174         err = certtmp.Close()
175         if err != nil {
176                 return err
177         }
178
179         err = os.Rename(keytmp.Name(), filepath.Join(outdir, keyfile))
180         if err != nil {
181                 return err
182         }
183         err = os.Rename(certtmp.Name(), filepath.Join(outdir, certfile))
184         if err != nil {
185                 return err
186         }
187         return nil
188 }
189
190 // Create a root CA key and use it to make a new server
191 // certificate+key pair.
192 //
193 // In future we'll make one root CA key per host instead of one per
194 // cluster, so it only needs to be imported to a browser once for
195 // ongoing dev/test usage.
196 func createSelfSignedCert(ctx context.Context, fail func(error), super *Supervisor) error {
197         san := "DNS:localhost,DNS:localhost.localdomain"
198         if net.ParseIP(super.ListenHost) != nil {
199                 san += fmt.Sprintf(",IP:%s", super.ListenHost)
200         } else {
201                 san += fmt.Sprintf(",DNS:%s", super.ListenHost)
202         }
203         hostname, err := os.Hostname()
204         if err != nil {
205                 return fmt.Errorf("hostname: %w", err)
206         }
207         if hostname != super.ListenHost {
208                 san += ",DNS:" + hostname
209         }
210
211         // Generate root key
212         err = super.RunProgram(ctx, super.tempdir, runOptions{}, "openssl", "genrsa", "-out", "rootCA.key", "4096")
213         if err != nil {
214                 return err
215         }
216         // Generate a self-signed root certificate
217         err = super.RunProgram(ctx, super.tempdir, runOptions{}, "openssl", "req", "-x509", "-new", "-nodes", "-key", "rootCA.key", "-sha256", "-days", "3650", "-out", "rootCA.crt", "-subj", "/C=US/ST=MA/O=Example Org/CN=localhost")
218         if err != nil {
219                 return err
220         }
221         // Generate server key
222         err = super.RunProgram(ctx, super.tempdir, runOptions{}, "openssl", "genrsa", "-out", "server.key", "2048")
223         if err != nil {
224                 return err
225         }
226         // Build config file for signing request
227         defaultconf, err := ioutil.ReadFile("/etc/ssl/openssl.cnf")
228         if err != nil {
229                 return err
230         }
231         conf := append(defaultconf, []byte(fmt.Sprintf("\n[SAN]\nsubjectAltName=%s\n", san))...)
232         err = ioutil.WriteFile(filepath.Join(super.tempdir, "server.cfg"), conf, 0644)
233         if err != nil {
234                 return err
235         }
236         // Generate signing request
237         err = super.RunProgram(ctx, super.tempdir, runOptions{}, "openssl", "req", "-new", "-sha256", "-key", "server.key", "-subj", "/C=US/ST=MA/O=Example Org/CN=localhost", "-reqexts", "SAN", "-config", "server.cfg", "-out", "server.csr")
238         if err != nil {
239                 return err
240         }
241         // Sign certificate
242         err = super.RunProgram(ctx, super.tempdir, runOptions{}, "openssl", "x509", "-req", "-in", "server.csr", "-CA", "rootCA.crt", "-CAkey", "rootCA.key", "-CAcreateserial", "-out", "server.crt", "-extfile", "server.cfg", "-extensions", "SAN", "-days", "3650", "-sha256")
243         if err != nil {
244                 return err
245         }
246         super.cluster.TLS.Key = "file://" + super.tempdir + "/server.key"
247         super.cluster.TLS.Certificate = "file://" + super.tempdir + "/server.crt"
248         return nil
249 }