Debian Codegraph @

modules/caddypki/acmeserver/acmeserver.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package acmeserver
16
17 import (
18 "context"
19 "fmt"
20 weakrand "math/rand/v2"
21 "net"
22 "net/http"
23 "os"
24 "path/filepath"
25 "regexp"
26 "strings"
27 "time"
28
29 "github.com/go-chi/chi/v5"
30 "github.com/smallstep/certificates/acme"
31 "github.com/smallstep/certificates/acme/api"
32 acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
33 "github.com/smallstep/certificates/authority"
34 "github.com/smallstep/certificates/authority/provisioner"
35 "github.com/smallstep/certificates/db"
36 "github.com/smallstep/nosql"
37 "go.uber.org/zap"
38 "go.uber.org/zap/zapcore"
39
40 "github.com/caddyserver/caddy/v2"
41 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
42 "github.com/caddyserver/caddy/v2/modules/caddypki"
43 "github.com/caddyserver/caddy/v2/modules/caddytls"
44 )
45
46 func init() {
47 caddy.RegisterModule(Handler{})
48 }
49
50 // Handler is an ACME server handler.
51 type Handler struct {
52 // The ID of the CA to use for signing. This refers to
53 // the ID given to the CA in the `pki` app. If omitted,
54 // the default ID is "local".
55 CA string `json:"ca,omitempty"`
56
57 // The lifetime for issued certificates
58 Lifetime caddy.Duration `json:"lifetime,omitempty"`
59
60 // The hostname or IP address by which ACME clients
61 // will access the server. This is used to populate
62 // the ACME directory endpoint. If not set, the Host
63 // header of the request will be used.
64 // COMPATIBILITY NOTE / TODO: This property may go away in the
65 // future. Do not rely on this property long-term; check release notes.
66 Host string `json:"host,omitempty"`
67
68 // The path prefix under which to serve all ACME
69 // endpoints. All other requests will not be served
70 // by this handler and will be passed through to
71 // the next one. Default: "/acme/".
72 // COMPATIBILITY NOTE / TODO: This property may go away in the
73 // future, as it is currently only required due to
74 // limitations in the underlying library. Do not rely
75 // on this property long-term; check release notes.
76 PathPrefix string `json:"path_prefix,omitempty"`
77
78 // If true, the CA's root will be the issuer instead of
79 // the intermediate. This is NOT recommended and should
80 // only be used when devices/clients do not properly
81 // validate certificate chains. EXPERIMENTAL: Might be
82 // changed or removed in the future.
83 SignWithRoot bool `json:"sign_with_root,omitempty"`
84
85 // The addresses of DNS resolvers to use when looking up
86 // the TXT records for solving DNS challenges.
87 // It accepts [network addresses](/docs/conventions#network-addresses)
88 // with port range of only 1. If the host is an IP address,
89 // it will be dialed directly to resolve the upstream server.
90 // If the host is not an IP address, the addresses are resolved
91 // using the [name resolution convention](https://golang.org/pkg/net/#hdr-Name_Resolution)
92 // of the Go standard library. If the array contains more
93 // than 1 resolver address, one is chosen at random.
94 Resolvers []string `json:"resolvers,omitempty"`
95
96 // Specify the set of enabled ACME challenges. An empty or absent value
97 // means all challenges are enabled. Accepted values are:
98 // "http-01", "dns-01", "tls-alpn-01"
99 Challenges ACMEChallenges `json:"challenges,omitempty" `
100
101 // The policy to use for issuing certificates
102 Policy *Policy `json:"policy,omitempty"`
103
104 logger *zap.Logger
105 resolvers []caddy.NetworkAddress
106 ctx caddy.Context
107
108 acmeDB acme.DB
109 acmeAuth *authority.Authority
110 acmeClient acme.Client
111 acmeLinker acme.Linker
112 acmeEndpoints http.Handler
113 }
114
115 // CaddyModule returns the Caddy module information.
116 func (Handler) CaddyModule() caddy.ModuleInfo {
117 return caddy.ModuleInfo{
118 ID: "http.handlers.acme_server",
119 New: func() caddy.Module { return new(Handler) },
120 }
121 }
122
123 // Provision sets up the ACME server handler.
124 func (ash *Handler) Provision(ctx caddy.Context) error {
125 ash.ctx = ctx
126 ash.logger = ctx.Logger()
127
128 // set some defaults
129 if ash.CA == "" {
130 ash.CA = caddypki.DefaultCAID
131 }
132 if ash.PathPrefix == "" {
133 ash.PathPrefix = defaultPathPrefix
134 }
135 if ash.Lifetime == 0 {
136 ash.Lifetime = caddy.Duration(12 * time.Hour)
137 }
138 if len(ash.Challenges) > 0 {
139 if err := ash.Challenges.validate(); err != nil {
140 return err
141 }
142 }
143
144 ash.warnIfPolicyAllowsAll()
145
146 // get a reference to the configured CA
147 appModule, err := ctx.App("pki")
148 if err != nil {
149 return err
150 }
151 pkiApp := appModule.(*caddypki.PKI)
152 ca, err := pkiApp.GetCA(ctx, ash.CA)
153 if err != nil {
154 return err
155 }
156
157 // make sure leaf cert lifetime is less than the intermediate cert lifetime. this check only
158 // applies for caddy-managed intermediate certificates
159 if ca.Intermediate == nil && ash.Lifetime >= ca.IntermediateLifetime {
160 return fmt.Errorf("certificate lifetime (%s) should be less than intermediate certificate lifetime (%s)", time.Duration(ash.Lifetime), time.Duration(ca.IntermediateLifetime))
161 }
162
163 database, err := ash.openDatabase()
164 if err != nil {
165 return err
166 }
167
168 authorityConfig := caddypki.AuthorityConfig{
169 SignWithRoot: ash.SignWithRoot,
170 AuthConfig: &authority.AuthConfig{
171 Provisioners: provisioner.List{
172 &provisioner.ACME{
173 Name: ash.CA,
174 Challenges: ash.Challenges.toSmallstepType(),
175 Options: &provisioner.Options{
176 X509: ash.Policy.normalizeRules(),
177 },
178 Type: provisioner.TypeACME.String(),
179 Claims: &provisioner.Claims{
180 MinTLSDur: &provisioner.Duration{Duration: 5 * time.Minute},
181 MaxTLSDur: &provisioner.Duration{Duration: 24 * time.Hour * 365},
182 DefaultTLSDur: &provisioner.Duration{Duration: time.Duration(ash.Lifetime)},
183 },
184 },
185 },
186 },
187 DB: database,
188 }
189
190 ash.acmeAuth, err = ca.NewAuthority(authorityConfig)
191 if err != nil {
192 return err
193 }
194
195 ash.acmeDB, err = acmeNoSQL.New(ash.acmeAuth.GetDatabase().(nosql.DB))
196 if err != nil {
197 return fmt.Errorf("configuring ACME DB: %v", err)
198 }
199
200 ash.acmeClient, err = ash.makeClient()
201 if err != nil {
202 return err
203 }
204
205 ash.acmeLinker = acme.NewLinker(
206 ash.Host,
207 strings.Trim(ash.PathPrefix, "/"),
208 )
209
210 // extract its http.Handler so we can use it directly
211 r := chi.NewRouter()
212 r.Route(ash.PathPrefix, func(r chi.Router) {
213 api.Route(r)
214 })
215 ash.acmeEndpoints = r
216
217 return nil
218 }
219
220 func (ash *Handler) warnIfPolicyAllowsAll() {
221 allow := ash.Policy.normalizeAllowRules()
222 deny := ash.Policy.normalizeDenyRules()
223 if allow != nil || deny != nil {
224 return
225 }
226
227 allowWildcardNames := ash.Policy != nil && ash.Policy.AllowWildcardNames
228 ash.logger.Warn(
229 "acme_server policy has no allow/deny rules; order identifiers are unrestricted (allow-all)",
230 zap.String("ca", ash.CA),
231 zap.Bool("allow_wildcard_names", allowWildcardNames),
232 )
233 }
234
235 func (ash Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
236 if strings.HasPrefix(r.URL.Path, ash.PathPrefix) {
237 acmeCtx := acme.NewContext(
238 r.Context(),
239 ash.acmeDB,
240 ash.acmeClient,
241 ash.acmeLinker,
242 nil,
243 )
244 acmeCtx = authority.NewContext(acmeCtx, ash.acmeAuth)
245 r = r.WithContext(acmeCtx)
246
247 ash.acmeEndpoints.ServeHTTP(w, r)
248 return nil
249 }
250 return next.ServeHTTP(w, r)
251 }
252
253 func (ash Handler) getDatabaseKey() string {
254 key := ash.CA
255 key = strings.ToLower(key)
256 key = strings.TrimSpace(key)
257 return keyCleaner.ReplaceAllLiteralString(key, "")
258 }
259
260 // Cleanup implements caddy.CleanerUpper and closes any idle databases.
261 func (ash Handler) Cleanup() error {
262 key := ash.getDatabaseKey()
263 deleted, err := databasePool.Delete(key)
264 if deleted {
265 if c := ash.logger.Check(zapcore.DebugLevel, "unloading unused CA database"); c != nil {
266 c.Write(zap.String("db_key", key))
267 }
268 }
269 if err != nil {
270 if c := ash.logger.Check(zapcore.ErrorLevel, "closing CA database"); c != nil {
271 c.Write(zap.String("db_key", key), zap.Error(err))
272 }
273 }
274 return err
275 }
276
277 func (ash Handler) openDatabase() (*db.AuthDB, error) {
278 key := ash.getDatabaseKey()
279 database, loaded, err := databasePool.LoadOrNew(key, func() (caddy.Destructor, error) {
280 dbFolder := filepath.Join(caddy.AppDataDir(), "acme_server", key)
281 dbPath := filepath.Join(dbFolder, "db")
282
283 err := os.MkdirAll(dbFolder, 0o755)
284 if err != nil {
285 return nil, fmt.Errorf("making folder for CA database: %v", err)
286 }
287
288 dbConfig := &db.Config{
289 Type: "bbolt",
290 DataSource: dbPath,
291 }
292 database, err := db.New(dbConfig)
293 return databaseCloser{&database}, err
294 })
295
296 if loaded {
297 if c := ash.logger.Check(zapcore.DebugLevel, "loaded preexisting CA database"); c != nil {
298 c.Write(zap.String("db_key", key))
299 }
300 }
301
302 return database.(databaseCloser).DB, err
303 }
304
305 // makeClient creates an ACME client which will use a custom
306 // resolver instead of net.DefaultResolver.
307 func (ash Handler) makeClient() (acme.Client, error) {
308 // If no local resolvers are configured, check for global resolvers from TLS app
309 resolversToUse := ash.Resolvers
310 if len(resolversToUse) == 0 {
311 tlsAppIface, err := ash.ctx.App("tls")
312 if err == nil {
313 tlsApp := tlsAppIface.(*caddytls.TLS)
314 if len(tlsApp.Resolvers) > 0 {
315 resolversToUse = tlsApp.Resolvers
316 }
317 }
318 }
319
320 for _, v := range resolversToUse {
321 addr, err := caddy.ParseNetworkAddressWithDefaults(v, "udp", 53)
322 if err != nil {
323 return nil, err
324 }
325 if addr.PortRangeSize() != 1 {
326 return nil, fmt.Errorf("resolver address must have exactly one address; cannot call %v", addr)
327 }
328 ash.resolvers = append(ash.resolvers, addr)
329 }
330
331 var resolver *net.Resolver
332 if len(ash.resolvers) != 0 {
333 dialer := &net.Dialer{
334 Timeout: 2 * time.Second,
335 }
336 resolver = &net.Resolver{
337 PreferGo: true,
338 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
339 //nolint:gosec
340 addr := ash.resolvers[weakrand.IntN(len(ash.resolvers))]
341 return dialer.DialContext(ctx, addr.Network, addr.JoinHostPort(0))
342 },
343 }
344 } else {
345 resolver = net.DefaultResolver
346 }
347
348 return resolverClient{
349 Client: acme.NewClient(),
350 resolver: resolver,
351 ctx: ash.ctx,
352 }, nil
353 }
354
355 type resolverClient struct {
356 acme.Client
357
358 resolver *net.Resolver
359 ctx context.Context
360 }
361
362 func (c resolverClient) LookupTxt(name string) ([]string, error) {
363 return c.resolver.LookupTXT(c.ctx, name)
364 }
365
366 const defaultPathPrefix = "/acme/"
367
368 var (
369 keyCleaner = regexp.MustCompile(`[^\w.-_]`)
370 databasePool = caddy.NewUsagePool()
371 )
372
373 type databaseCloser struct {
374 DB *db.AuthDB
375 }
376
377 func (closer databaseCloser) Destruct() error {
378 return (*closer.DB).Shutdown()
379 }
380
381 // Interface guards
382 var (
383 _ caddyhttp.MiddlewareHandler = (*Handler)(nil)
384 _ caddy.Provisioner = (*Handler)(nil)
385 )