Debian Codegraph @

admin.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 caddy
16
17 import (
18 "bytes"
19 "context"
20 "crypto"
21 "crypto/tls"
22 "crypto/x509"
23 "encoding/base64"
24 "encoding/json"
25 "errors"
26 "expvar"
27 "fmt"
28 "hash"
29 "io"
30 "net"
31 "net/http"
32 "net/http/pprof"
33 "net/url"
34 "os"
35 "path"
36 "regexp"
37 "slices"
38 "strconv"
39 "strings"
40 "sync"
41 "time"
42
43 "github.com/caddyserver/certmagic"
44 "github.com/cespare/xxhash/v2"
45 "github.com/prometheus/client_golang/prometheus"
46 "go.uber.org/zap"
47 "go.uber.org/zap/zapcore"
48
49 "github.com/caddyserver/caddy/v2/internal"
50 )
51
52 // testCertMagicStorageOverride is a package-level test hook. Tests may set
53 // this variable to provide a temporary certmagic.Storage so that cert
54 // management in tests does not hit the real default storage on disk.
55 // This must NOT be set in production code.
56 var testCertMagicStorageOverride certmagic.Storage
57
58 func init() {
59 // The hard-coded default `DefaultAdminListen` can be overridden
60 // by setting the `CADDY_ADMIN` environment variable.
61 // The environment variable may be used by packagers to change
62 // the default admin address to something more appropriate for
63 // that platform. See #5317 for discussion.
64 if env, exists := os.LookupEnv("CADDY_ADMIN"); exists {
65 DefaultAdminListen = env
66 }
67 }
68
69 // AdminConfig configures Caddy's API endpoint, which is used
70 // to manage Caddy while it is running.
71 type AdminConfig struct {
72 // If true, the admin endpoint will be completely disabled.
73 // Note that this makes any runtime changes to the config
74 // impossible, since the interface to do so is through the
75 // admin endpoint.
76 Disabled bool `json:"disabled,omitempty"`
77
78 // The address to which the admin endpoint's listener should
79 // bind itself. Can be any single network address that can be
80 // parsed by Caddy. Accepts placeholders.
81 // Default: the value of the `CADDY_ADMIN` environment variable,
82 // or `localhost:2019` otherwise.
83 //
84 // Remember: When changing this value through a config reload,
85 // be sure to use the `--address` CLI flag to specify the current
86 // admin address if the currently-running admin endpoint is not
87 // the default address.
88 Listen string `json:"listen,omitempty"`
89
90 // If true, CORS headers will be emitted, and requests to the
91 // API will be rejected if their `Host` and `Origin` headers
92 // do not match the expected value(s). Use `origins` to
93 // customize which origins/hosts are allowed. If `origins` is
94 // not set, the listen address is the only value allowed by
95 // default. Enforced only on local (plaintext) endpoint.
96 EnforceOrigin bool `json:"enforce_origin,omitempty"`
97
98 // The list of allowed origins/hosts for API requests. Only needed
99 // if accessing the admin endpoint from a host different from the
100 // socket's network interface or if `enforce_origin` is true. If not
101 // set, the listener address will be the default value. If set but
102 // empty, no origins will be allowed. Enforced only on local
103 // (plaintext) endpoint.
104 Origins []string `json:"origins,omitempty"`
105
106 // Options pertaining to configuration management.
107 Config *ConfigSettings `json:"config,omitempty"`
108
109 // Options that establish this server's identity. Identity refers to
110 // credentials which can be used to uniquely identify and authenticate
111 // this server instance. This is required if remote administration is
112 // enabled (but does not require remote administration to be enabled).
113 // Default: no identity management.
114 Identity *IdentityConfig `json:"identity,omitempty"`
115
116 // Options pertaining to remote administration. By default, remote
117 // administration is disabled. If enabled, identity management must
118 // also be configured, as that is how the endpoint is secured.
119 // See the neighboring "identity" object.
120 //
121 // EXPERIMENTAL: This feature is subject to change.
122 Remote *RemoteAdmin `json:"remote,omitempty"`
123 }
124
125 // ConfigSettings configures the management of configuration.
126 type ConfigSettings struct {
127 // Whether to keep a copy of the active config on disk. Default is true.
128 // Note that "pulled" dynamic configs (using the neighboring "load" module)
129 // are not persisted; only configs that are pushed to Caddy get persisted.
130 Persist *bool `json:"persist,omitempty"`
131
132 // Loads a new configuration. This is helpful if your configs are
133 // managed elsewhere and you want Caddy to pull its config dynamically
134 // when it starts. The pulled config completely replaces the current
135 // one, just like any other config load. It is an error if a pulled
136 // config is configured to pull another config without a load_delay,
137 // as this creates a tight loop.
138 //
139 // EXPERIMENTAL: Subject to change.
140 LoadRaw json.RawMessage `json:"load,omitempty" caddy:"namespace=caddy.config_loaders inline_key=module"`
141
142 // The duration after which to load config. If set, config will be pulled
143 // from the config loader after this duration. A delay is required if a
144 // dynamically-loaded config is configured to load yet another config. To
145 // load configs on a regular interval, ensure this value is set the same
146 // on all loaded configs; it can also be variable if needed, and to stop
147 // the loop, simply remove dynamic config loading from the next-loaded
148 // config.
149 //
150 // EXPERIMENTAL: Subject to change.
151 LoadDelay Duration `json:"load_delay,omitempty"`
152 }
153
154 // IdentityConfig configures management of this server's identity. An identity
155 // consists of credentials that uniquely verify this instance; for example,
156 // TLS certificates (public + private key pairs).
157 type IdentityConfig struct {
158 // List of names or IP addresses which refer to this server.
159 // Certificates will be obtained for these identifiers so
160 // secure TLS connections can be made using them.
161 Identifiers []string `json:"identifiers,omitempty"`
162
163 // Issuers that can provide this admin endpoint its identity
164 // certificate(s). Default: ACME issuers configured for
165 // ZeroSSL and Let's Encrypt. Be sure to change this if you
166 // require credentials for private identifiers.
167 IssuersRaw []json.RawMessage `json:"issuers,omitempty" caddy:"namespace=tls.issuance inline_key=module"`
168
169 issuers []certmagic.Issuer
170 }
171
172 // RemoteAdmin enables and configures remote administration. If enabled,
173 // a secure listener enforcing mutual TLS authentication will be started
174 // on a different port from the standard plaintext admin server.
175 //
176 // This endpoint is secured using identity management, which must be
177 // configured separately (because identity management does not depend
178 // on remote administration). See the admin/identity config struct.
179 //
180 // EXPERIMENTAL: Subject to change.
181 type RemoteAdmin struct {
182 // The address on which to start the secure listener. Accepts placeholders.
183 // Default: :2021
184 Listen string `json:"listen,omitempty"`
185
186 // List of access controls for this secure admin endpoint.
187 // This configures TLS mutual authentication (i.e. authorized
188 // client certificates), but also application-layer permissions
189 // like which paths and methods each identity is authorized for.
190 AccessControl []*AdminAccess `json:"access_control,omitempty"`
191 }
192
193 // AdminAccess specifies what permissions an identity or group
194 // of identities are granted.
195 type AdminAccess struct {
196 // Base64-encoded DER certificates containing public keys to accept.
197 // (The contents of PEM certificate blocks are base64-encoded DER.)
198 // Any of these public keys can appear in any part of a verified chain.
199 PublicKeys []string `json:"public_keys,omitempty"`
200
201 // Limits what the associated identities are allowed to do.
202 // If unspecified, all permissions are granted.
203 Permissions []AdminPermissions `json:"permissions,omitempty"`
204
205 publicKeys []crypto.PublicKey
206 }
207
208 // AdminPermissions specifies what kinds of requests are allowed
209 // to be made to the admin endpoint.
210 type AdminPermissions struct {
211 // The API paths allowed. A request path must either equal an
212 // allowed path or be a subpath with a path-segment boundary.
213 Paths []string `json:"paths,omitempty"`
214
215 // The HTTP methods allowed for the given paths.
216 Methods []string `json:"methods,omitempty"`
217 }
218
219 // newAdminHandler reads admin's config and returns an http.Handler suitable
220 // for use in an admin endpoint server, which will be listening on listenAddr.
221 func (admin *AdminConfig) newAdminHandler(addr NetworkAddress, remote bool, ctx Context) (adminHandler, error) {
222 muxWrap := adminHandler{mux: http.NewServeMux()}
223
224 // secure the local or remote endpoint respectively
225 if remote {
226 muxWrap.remoteControl = admin.Remote
227 } else {
228 // see comment in allowedOrigins() as to why we disable the host check for unix/fd networks
229 muxWrap.enforceHost = !addr.isWildcardInterface() && !addr.IsUnixNetwork() && !addr.IsFdNetwork()
230 muxWrap.allowedOrigins = admin.allowedOrigins(addr)
231 muxWrap.enforceOrigin = admin.EnforceOrigin
232 }
233
234 addRouteWithMetrics := func(pattern string, handlerLabel string, h http.Handler) {
235 labels := prometheus.Labels{"path": pattern, "handler": handlerLabel}
236 h = instrumentHandlerCounter(
237 adminMetrics.requestCount.MustCurryWith(labels),
238 h,
239 )
240 muxWrap.mux.Handle(pattern, h)
241 }
242 // addRoute just calls muxWrap.mux.Handle after
243 // wrapping the handler with error handling
244 addRoute := func(pattern string, handlerLabel string, h AdminHandler) {
245 wrapper := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
246 err := h.ServeHTTP(w, r)
247 if err != nil {
248 labels := prometheus.Labels{
249 "path": pattern,
250 "handler": handlerLabel,
251 "method": strings.ToUpper(r.Method),
252 }
253 adminMetrics.requestErrors.With(labels).Inc()
254 }
255 muxWrap.handleError(w, r, err)
256 })
257 addRouteWithMetrics(pattern, handlerLabel, wrapper)
258 }
259
260 const handlerLabel = "admin"
261
262 // register standard config control endpoints
263 addRoute("/"+rawConfigKey+"/", handlerLabel, AdminHandlerFunc(handleConfig))
264 addRoute("/id/", handlerLabel, AdminHandlerFunc(handleConfigID))
265 addRoute("/stop", handlerLabel, AdminHandlerFunc(handleStop))
266
267 // register debugging endpoints
268 addRouteWithMetrics("/debug/pprof/", handlerLabel, http.HandlerFunc(pprof.Index))
269 addRouteWithMetrics("/debug/pprof/cmdline", handlerLabel, http.HandlerFunc(pprof.Cmdline))
270 addRouteWithMetrics("/debug/pprof/profile", handlerLabel, http.HandlerFunc(pprof.Profile))
271 addRouteWithMetrics("/debug/pprof/symbol", handlerLabel, http.HandlerFunc(pprof.Symbol))
272 addRouteWithMetrics("/debug/pprof/trace", handlerLabel, http.HandlerFunc(pprof.Trace))
273 addRouteWithMetrics("/debug/vars", handlerLabel, expvar.Handler())
274
275 // register third-party module endpoints
276 for _, m := range GetModules("admin.api") {
277 router := m.New().(AdminRouter)
278
279 // provision the router before registering its routes, so
280 // handlers have access to all provisioned state
281 if provisioner, ok := router.(Provisioner); ok {
282 if err := provisioner.Provision(ctx); err != nil {
283 return adminHandler{}, fmt.Errorf("provisioning admin router module %s: %v", m.ID, err)
284 }
285 }
286
287 for _, route := range router.Routes() {
288 addRoute(route.Pattern, handlerLabel, route.Handler)
289 }
290 }
291
292 return muxWrap, nil
293 }
294
295 // allowedOrigins returns a list of origins that are allowed.
296 // If admin.Origins is nil (null), the provided listen address
297 // will be used as the default origin. If admin.Origins is
298 // empty, no origins will be allowed, effectively bricking the
299 // endpoint for non-unix-socket endpoints, but whatever.
300 func (admin AdminConfig) allowedOrigins(addr NetworkAddress) []*url.URL {
301 uniqueOrigins := make(map[string]struct{})
302 for _, o := range admin.Origins {
303 uniqueOrigins[o] = struct{}{}
304 }
305 // RFC 2616, Section 14.26:
306 // "A client MUST include a Host header field in all HTTP/1.1 request
307 // messages. If the requested URI does not include an Internet host
308 // name for the service being requested, then the Host header field MUST
309 // be given with an empty value."
310 //
311 // UPDATE July 2023: Go broke this by patching a minor security bug in 1.20.6.
312 // Understandable, but frustrating. See:
313 // https://github.com/golang/go/issues/60374
314 // See also the discussion here:
315 // https://github.com/golang/go/issues/61431
316 //
317 // We can no longer conform to RFC 2616 Section 14.26 from either Go or curl
318 // in purity. (Curl allowed no host between 7.40 and 7.50, but now requires a
319 // bogus host; see https://superuser.com/a/925610.) If we disable Host/Origin
320 // security checks, the infosec community assures me that it is secure to do
321 // so, because:
322 //
323 // 1) Browsers do not allow access to unix sockets
324 // 2) DNS is irrelevant to unix sockets
325 //
326 // If either of those two statements ever fail to hold true, it is not the
327 // fault of Caddy.
328 //
329 // Thus, we do not fill out allowed origins and do not enforce Host
330 // requirements for unix sockets. Enforcing it leads to confusion and
331 // frustration, when UDS have their own permissions from the OS.
332 // Enforcing host requirements here is effectively security theater,
333 // and a false sense of security.
334 //
335 // See also the discussion in #6832.
336 if admin.Origins == nil && !addr.IsUnixNetwork() && !addr.IsFdNetwork() {
337 if addr.isLoopback() {
338 uniqueOrigins[net.JoinHostPort("localhost", addr.port())] = struct{}{}
339 uniqueOrigins[net.JoinHostPort("::1", addr.port())] = struct{}{}
340 uniqueOrigins[net.JoinHostPort("127.0.0.1", addr.port())] = struct{}{}
341 } else {
342 uniqueOrigins[addr.JoinHostPort(0)] = struct{}{}
343 }
344 }
345 allowed := make([]*url.URL, 0, len(uniqueOrigins))
346 for originStr := range uniqueOrigins {
347 var origin *url.URL
348 if strings.Contains(originStr, "://") {
349 var err error
350 origin, err = url.Parse(originStr)
351 if err != nil {
352 continue
353 }
354 origin.Path = ""
355 origin.RawPath = ""
356 origin.Fragment = ""
357 origin.RawFragment = ""
358 origin.RawQuery = ""
359 } else {
360 origin = &url.URL{Host: originStr}
361 }
362 allowed = append(allowed, origin)
363 }
364 return allowed
365 }
366
367 // replaceLocalAdminServer replaces the running local admin server
368 // according to the relevant configuration in cfg. If no configuration
369 // for the admin endpoint exists in cfg, a default one is used, so
370 // that there is always an admin server (unless it is explicitly
371 // configured to be disabled).
372 // Critically note that some elements and functionality of the context
373 // may not be ready, e.g. storage. Tread carefully.
374 func replaceLocalAdminServer(cfg *Config, ctx Context) error {
375 // always* be sure to close down the old admin endpoint
376 // as gracefully as possible, even if the new one is
377 // disabled -- careful to use reference to the current
378 // (old) admin endpoint since it will be different
379 // when the function returns
380 // (* except if the new one fails to start)
381 oldAdminServer := localAdminServer
382 var err error
383 defer func() {
384 // do the shutdown asynchronously so that any
385 // current API request gets a response; this
386 // goroutine may last a few seconds
387 if oldAdminServer != nil && err == nil {
388 go func(oldAdminServer *http.Server) {
389 err := stopAdminServer(oldAdminServer)
390 if err != nil {
391 Log().Named("admin").Error("stopping current admin endpoint", zap.Error(err))
392 }
393 }(oldAdminServer)
394 }
395 }()
396
397 // set a default if admin wasn't otherwise configured
398 if cfg.Admin == nil {
399 cfg.Admin = &AdminConfig{
400 Listen: DefaultAdminListen,
401 }
402 }
403
404 // if new admin endpoint is to be disabled, we're done
405 if cfg.Admin.Disabled {
406 Log().Named("admin").Warn("admin endpoint disabled")
407 return nil
408 }
409
410 // extract a singular listener address
411 addr, err := parseAdminListenAddr(cfg.Admin.Listen, DefaultAdminListen)
412 if err != nil {
413 return err
414 }
415
416 handler, err := cfg.Admin.newAdminHandler(addr, false, ctx)
417 if err != nil {
418 return err
419 }
420
421 ln, err := addr.Listen(context.TODO(), 0, net.ListenConfig{})
422 if err != nil {
423 return err
424 }
425
426 serverMu.Lock()
427 localAdminServer = &http.Server{
428 Addr: addr.String(), // for logging purposes only
429 Handler: handler,
430 ReadTimeout: 10 * time.Second,
431 ReadHeaderTimeout: 5 * time.Second,
432 IdleTimeout: 60 * time.Second,
433 MaxHeaderBytes: 1024 * 64,
434 }
435 serverMu.Unlock()
436
437 adminLogger := Log().Named("admin")
438 go func() {
439 serverMu.Lock()
440 server := localAdminServer
441 serverMu.Unlock()
442 if err := server.Serve(ln.(net.Listener)); !errors.Is(err, http.ErrServerClosed) {
443 adminLogger.Error("admin server shutdown for unknown reason", zap.Error(err))
444 }
445 }()
446
447 adminLogger.Info("admin endpoint started",
448 zap.String("address", addr.String()),
449 zap.Bool("enforce_origin", cfg.Admin.EnforceOrigin),
450 zap.Array("origins", loggableURLArray(handler.allowedOrigins)))
451
452 if !handler.enforceHost {
453 adminLogger.Warn("admin endpoint on open interface; host checking disabled",
454 zap.String("address", addr.String()))
455 }
456
457 return nil
458 }
459
460 // manageIdentity sets up automated identity management for this server.
461 func manageIdentity(ctx Context, cfg *Config) error {
462 if cfg == nil || cfg.Admin == nil || cfg.Admin.Identity == nil {
463 return nil
464 }
465
466 // set default issuers; this is pretty hacky because we can't
467 // import the caddytls package -- but it works
468 if cfg.Admin.Identity.IssuersRaw == nil {
469 cfg.Admin.Identity.IssuersRaw = []json.RawMessage{
470 json.RawMessage(`{"module": "acme"}`),
471 }
472 }
473
474 // load and provision issuer modules
475 if cfg.Admin.Identity.IssuersRaw != nil {
476 val, err := ctx.LoadModule(cfg.Admin.Identity, "IssuersRaw")
477 if err != nil {
478 return fmt.Errorf("loading identity issuer modules: %s", err)
479 }
480 for _, issVal := range val.([]any) {
481 cfg.Admin.Identity.issuers = append(cfg.Admin.Identity.issuers, issVal.(certmagic.Issuer))
482 }
483 }
484
485 // we'll make a new cache when we make the CertMagic config, so stop any previous cache
486 if identityCertCache != nil {
487 identityCertCache.Stop()
488 }
489
490 logger := Log().Named("admin.identity")
491 cmCfg := cfg.Admin.Identity.certmagicConfig(logger, true)
492
493 // issuers have circular dependencies with the configs because,
494 // as explained in the caddytls package, they need access to the
495 // correct storage and cache to solve ACME challenges
496 for _, issuer := range cfg.Admin.Identity.issuers {
497 // avoid import cycle with caddytls package, so manually duplicate the interface here, yuck
498 if annoying, ok := issuer.(interface{ SetConfig(cfg *certmagic.Config) }); ok {
499 annoying.SetConfig(cmCfg)
500 }
501 }
502
503 // obtain and renew server identity certificate(s)
504 return cmCfg.ManageAsync(ctx, cfg.Admin.Identity.Identifiers)
505 }
506
507 // replaceRemoteAdminServer replaces the running remote admin server
508 // according to the relevant configuration in cfg. It stops any previous
509 // remote admin server and only starts a new one if configured.
510 func replaceRemoteAdminServer(ctx Context, cfg *Config) error {
511 if cfg == nil {
512 return nil
513 }
514
515 remoteLogger := Log().Named("admin.remote")
516
517 oldAdminServer := remoteAdminServer
518 defer func() {
519 if oldAdminServer != nil {
520 go func(oldAdminServer *http.Server) {
521 err := stopAdminServer(oldAdminServer)
522 if err != nil {
523 Log().Named("admin").Error("stopping current secure admin endpoint", zap.Error(err))
524 }
525 }(oldAdminServer)
526 }
527 }()
528
529 if cfg.Admin == nil || cfg.Admin.Remote == nil {
530 return nil
531 }
532
533 addr, err := parseAdminListenAddr(cfg.Admin.Remote.Listen, DefaultRemoteAdminListen)
534 if err != nil {
535 return err
536 }
537
538 // make the HTTP handler but disable Host/Origin enforcement
539 // because we are using TLS authentication instead
540 handler, err := cfg.Admin.newAdminHandler(addr, true, ctx)
541 if err != nil {
542 return err
543 }
544
545 // create client certificate pool for TLS mutual auth, and extract public keys
546 // so that we can enforce access controls at the application layer
547 clientCertPool := x509.NewCertPool()
548 for i, accessControl := range cfg.Admin.Remote.AccessControl {
549 for j, certBase64 := range accessControl.PublicKeys {
550 cert, err := decodeBase64DERCert(certBase64)
551 if err != nil {
552 return fmt.Errorf("access control %d public key %d: parsing base64 certificate DER: %v", i, j, err)
553 }
554 accessControl.publicKeys = append(accessControl.publicKeys, cert.PublicKey)
555 clientCertPool.AddCert(cert)
556 }
557 }
558
559 // create TLS config that will enforce mutual authentication
560 if identityCertCache == nil {
561 return fmt.Errorf("cannot enable remote admin without a certificate cache; configure identity management to initialize a certificate cache")
562 }
563 cmCfg := cfg.Admin.Identity.certmagicConfig(remoteLogger, false)
564 tlsConfig := cmCfg.TLSConfig()
565 tlsConfig.NextProtos = nil // this server does not solve ACME challenges
566 tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
567 tlsConfig.ClientCAs = clientCertPool
568
569 // convert logger to stdlib so it can be used by HTTP server
570 serverLogger, err := zap.NewStdLogAt(remoteLogger, zap.DebugLevel)
571 if err != nil {
572 return err
573 }
574
575 serverMu.Lock()
576 // create secure HTTP server
577 remoteAdminServer = &http.Server{
578 Addr: addr.String(), // for logging purposes only
579 Handler: handler,
580 TLSConfig: tlsConfig,
581 ReadTimeout: 10 * time.Second,
582 ReadHeaderTimeout: 5 * time.Second,
583 IdleTimeout: 60 * time.Second,
584 MaxHeaderBytes: 1024 * 64,
585 ErrorLog: serverLogger,
586 }
587 serverMu.Unlock()
588
589 // start listener
590 lnAny, err := addr.Listen(ctx, 0, net.ListenConfig{})
591 if err != nil {
592 return err
593 }
594 ln := lnAny.(net.Listener)
595 ln = tls.NewListener(ln, tlsConfig)
596
597 go func() {
598 serverMu.Lock()
599 server := remoteAdminServer
600 serverMu.Unlock()
601 if err := server.Serve(ln); !errors.Is(err, http.ErrServerClosed) {
602 remoteLogger.Error("admin remote server shutdown for unknown reason", zap.Error(err))
603 }
604 }()
605
606 remoteLogger.Info("secure admin remote control endpoint started",
607 zap.String("address", addr.String()))
608
609 return nil
610 }
611
612 func (ident *IdentityConfig) certmagicConfig(logger *zap.Logger, makeCache bool) *certmagic.Config {
613 var cmCfg *certmagic.Config
614 if ident == nil {
615 // user might not have configured identity; that's OK, we can still make a
616 // certmagic config, although it'll be mostly useless for remote management
617 ident = new(IdentityConfig)
618 }
619 // Choose storage: prefer the package-level test override when present,
620 // otherwise use the configured DefaultStorage. Tests may set an override
621 // to divert storage into a temporary location. Otherwise, in production
622 // we use the DefaultStorage since we don't want to act as part of a
623 // cluster; this storage is for the server's local identity only.
624 var storage certmagic.Storage
625 if testCertMagicStorageOverride != nil {
626 storage = testCertMagicStorageOverride
627 } else {
628 storage = DefaultStorage
629 }
630 template := certmagic.Config{
631 Storage: storage,
632 Logger: logger,
633 Issuers: ident.issuers,
634 }
635 if makeCache {
636 identityCertCache = certmagic.NewCache(certmagic.CacheOptions{
637 GetConfigForCert: func(certmagic.Certificate) (*certmagic.Config, error) {
638 return cmCfg, nil
639 },
640 Logger: logger.Named("cache"),
641 })
642 }
643 cmCfg = certmagic.New(identityCertCache, template)
644 return cmCfg
645 }
646
647 // IdentityCredentials returns this instance's configured, managed identity credentials
648 // that can be used in TLS client authentication.
649 func (ctx Context) IdentityCredentials(logger *zap.Logger) ([]tls.Certificate, error) {
650 if ctx.cfg == nil || ctx.cfg.Admin == nil || ctx.cfg.Admin.Identity == nil {
651 return nil, fmt.Errorf("no server identity configured")
652 }
653 ident := ctx.cfg.Admin.Identity
654 if len(ident.Identifiers) == 0 {
655 return nil, fmt.Errorf("no identifiers configured")
656 }
657 if logger == nil {
658 logger = Log()
659 }
660 magic := ident.certmagicConfig(logger, false)
661 return magic.ClientCredentials(ctx, ident.Identifiers)
662 }
663
664 // enforceAccessControls enforces application-layer access controls for r based on remote.
665 // It expects that the TLS server has already established at least one verified chain of
666 // trust, and then looks for a matching, authorized public key that is allowed to access
667 // the defined path(s) using the defined method(s).
668 func (remote RemoteAdmin) enforceAccessControls(r *http.Request) error {
669 for _, chain := range r.TLS.VerifiedChains {
670 for _, peerCert := range chain {
671 for _, adminAccess := range remote.AccessControl {
672 for _, allowedKey := range adminAccess.publicKeys {
673 // see if we found a matching public key; the TLS server already verified the chain
674 // so we know the client possesses the associated private key; this handy interface
675 // doesn't appear to be defined anywhere in the std lib, but was implemented here:
676 // https://github.com/golang/go/commit/b5f2c0f50297fa5cd14af668ddd7fd923626cf8c
677 comparer, ok := peerCert.PublicKey.(interface{ Equal(crypto.PublicKey) bool })
678 if !ok || !comparer.Equal(allowedKey) {
679 continue
680 }
681
682 // key recognized; make sure its HTTP request is permitted
683 for _, accessPerm := range adminAccess.Permissions {
684 // verify method
685 methodFound := accessPerm.Methods == nil || slices.Contains(accessPerm.Methods, r.Method)
686 if !methodFound {
687 return APIError{
688 HTTPStatus: http.StatusForbidden,
689 Message: "not authorized to use this method",
690 }
691 }
692
693 // verify path
694 pathFound := accessPerm.Paths == nil
695 for _, allowedPath := range accessPerm.Paths {
696 if adminPathAllowed(r.URL.Path, allowedPath) {
697 pathFound = true
698 break
699 }
700 }
701 if !pathFound {
702 return APIError{
703 HTTPStatus: http.StatusForbidden,
704 Message: "not authorized to access this path",
705 }
706 }
707 }
708
709 // public key authorized, method and path allowed
710 return nil
711 }
712 }
713 }
714 }
715
716 // in theory, this should never happen; with an unverified chain, the TLS server
717 // should not accept the connection in the first place, and the acceptable cert
718 // pool is configured using the same list of public keys we verify against
719 return APIError{
720 HTTPStatus: http.StatusUnauthorized,
721 Message: "client identity not authorized",
722 }
723 }
724
725 func adminPathAllowed(reqPath, allowedPath string) bool {
726 if allowedPath == "" || allowedPath == "/" {
727 return strings.HasPrefix(reqPath, allowedPath)
728 }
729 if reqPath == allowedPath {
730 return true
731 }
732 if strings.HasSuffix(allowedPath, "/") {
733 return strings.HasPrefix(reqPath, allowedPath)
734 }
735 return strings.HasPrefix(reqPath, allowedPath+"/")
736 }
737
738 func stopAdminServer(srv *http.Server) error {
739 if srv == nil {
740 return fmt.Errorf("no admin server")
741 }
742 timeout := 10 * time.Second
743 ctx, cancel := context.WithTimeoutCause(context.Background(), timeout, fmt.Errorf("stopping admin server: %ds timeout", int(timeout.Seconds())))
744 defer cancel()
745 err := srv.Shutdown(ctx)
746 if err != nil {
747 if cause := context.Cause(ctx); cause != nil && errors.Is(err, context.DeadlineExceeded) {
748 err = cause
749 }
750 return fmt.Errorf("shutting down admin server: %v", err)
751 }
752 Log().Named("admin").Info("stopped previous server", zap.String("address", srv.Addr))
753 return nil
754 }
755
756 // AdminRouter is a type which can return routes for the admin API.
757 type AdminRouter interface {
758 Routes() []AdminRoute
759 }
760
761 // AdminRoute represents a route for the admin endpoint.
762 type AdminRoute struct {
763 Pattern string
764 Handler AdminHandler
765 }
766
767 type adminHandler struct {
768 mux *http.ServeMux
769
770 // security for local/plaintext endpoint
771 enforceOrigin bool
772 enforceHost bool
773 allowedOrigins []*url.URL
774
775 // security for remote/encrypted endpoint
776 remoteControl *RemoteAdmin
777 }
778
779 // ServeHTTP is the external entry point for API requests.
780 // It will only be called once per request.
781 func (h adminHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
782 ip, port, err := net.SplitHostPort(r.RemoteAddr)
783 if err != nil {
784 ip = r.RemoteAddr
785 port = ""
786 }
787 log := Log().Named("admin.api").With(
788 zap.String("method", r.Method),
789 zap.String("host", r.Host),
790 zap.String("uri", r.RequestURI),
791 zap.String("remote_ip", ip),
792 zap.String("remote_port", port),
793 zap.Object("headers", internal.LoggableHTTPHeader{Header: r.Header}),
794 )
795 if r.TLS != nil {
796 log = log.With(
797 zap.Bool("secure", true),
798 zap.Int("verified_chains", len(r.TLS.VerifiedChains)),
799 )
800 }
801 if r.RequestURI == "/metrics" {
802 log.Debug("received request")
803 } else {
804 log.Info("received request")
805 }
806 h.serveHTTP(w, r)
807 }
808
809 // serveHTTP is the internal entry point for API requests. It may
810 // be called more than once per request, for example if a request
811 // is rewritten (i.e. internal redirect).
812 func (h adminHandler) serveHTTP(w http.ResponseWriter, r *http.Request) {
813 if h.remoteControl != nil {
814 // enforce access controls on secure endpoint
815 if err := h.remoteControl.enforceAccessControls(r); err != nil {
816 h.handleError(w, r, err)
817 return
818 }
819 }
820
821 // common mitigations in browser contexts
822 if strings.Contains(r.Header.Get("Upgrade"), "websocket") {
823 // I've never been able demonstrate a vulnerability myself, but apparently
824 // WebSocket connections originating from browsers aren't subject to CORS
825 // restrictions, so we'll just be on the safe side
826 h.handleError(w, r, APIError{
827 HTTPStatus: http.StatusBadRequest,
828 Err: errors.New("websocket connections aren't allowed"),
829 Message: "WebSocket connections aren't allowed.",
830 })
831 return
832 }
833 if strings.Contains(r.Header.Get("Sec-Fetch-Mode"), "no-cors") {
834 // turns out web pages can just disable the same-origin policy (!???!?)
835 // but at least browsers let us know that's the case, holy heck
836 h.handleError(w, r, APIError{
837 HTTPStatus: http.StatusBadRequest,
838 Err: errors.New("client attempted to make request by disabling same-origin policy using no-cors mode"),
839 Message: "Disabling same-origin restrictions is not allowed.",
840 })
841 return
842 }
843 if r.Header.Get("Origin") == "null" {
844 // bug in Firefox in certain cross-origin situations (yikes?)
845 // (not strictly a security vuln on its own, but it's red flaggy,
846 // since it seems to manifest in cross-origin contexts)
847 h.handleError(w, r, APIError{
848 HTTPStatus: http.StatusBadRequest,
849 Err: errors.New("invalid origin 'null'"),
850 Message: "Buggy browser is sending null Origin header.",
851 })
852 return
853 }
854
855 if h.enforceHost {
856 // DNS rebinding mitigation
857 err := h.checkHost(r)
858 if err != nil {
859 h.handleError(w, r, err)
860 return
861 }
862 }
863
864 _, hasOriginHeader := r.Header["Origin"]
865 _, hasSecHeader := r.Header["Sec-Fetch-Mode"]
866 if h.enforceOrigin || hasOriginHeader || hasSecHeader {
867 // cross-site mitigation
868 origin, err := h.checkOrigin(r)
869 if err != nil {
870 h.handleError(w, r, err)
871 return
872 }
873
874 if r.Method == http.MethodOptions {
875 w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
876 w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Cache-Control")
877 w.Header().Set("Access-Control-Allow-Credentials", "true")
878 }
879 w.Header().Set("Access-Control-Allow-Origin", origin)
880 }
881
882 h.mux.ServeHTTP(w, r)
883 }
884
885 func (h adminHandler) handleError(w http.ResponseWriter, r *http.Request, err error) {
886 if err == nil {
887 return
888 }
889 if err == errInternalRedir {
890 h.serveHTTP(w, r)
891 return
892 }
893
894 apiErr, ok := err.(APIError)
895 if !ok {
896 apiErr = APIError{
897 HTTPStatus: http.StatusInternalServerError,
898 Err: err,
899 }
900 }
901 if apiErr.HTTPStatus == 0 {
902 apiErr.HTTPStatus = http.StatusInternalServerError
903 }
904 if apiErr.Message == "" && apiErr.Err != nil {
905 apiErr.Message = apiErr.Err.Error()
906 }
907
908 Log().Named("admin.api").Error("request error",
909 zap.Error(err),
910 zap.Int("status_code", apiErr.HTTPStatus),
911 )
912
913 w.Header().Set("Content-Type", "application/json")
914 w.WriteHeader(apiErr.HTTPStatus)
915 encErr := json.NewEncoder(w).Encode(apiErr)
916 if encErr != nil {
917 Log().Named("admin.api").Error("failed to encode error response", zap.Error(encErr))
918 }
919 }
920
921 // checkHost returns a handler that wraps next such that
922 // it will only be called if the request's Host header matches
923 // a trustworthy/expected value. This helps to mitigate DNS
924 // rebinding attacks.
925 func (h adminHandler) checkHost(r *http.Request) error {
926 allowed := slices.ContainsFunc(h.allowedOrigins, func(u *url.URL) bool {
927 return r.Host == u.Host
928 })
929 if !allowed {
930 return APIError{
931 HTTPStatus: http.StatusForbidden,
932 Err: fmt.Errorf("host not allowed: %s", r.Host),
933 }
934 }
935 return nil
936 }
937
938 // checkOrigin ensures that the Origin header, if
939 // set, matches the intended target; prevents arbitrary
940 // sites from issuing requests to our listener. It
941 // returns the origin that was obtained from r.
942 func (h adminHandler) checkOrigin(r *http.Request) (string, error) {
943 originStr, origin := h.getOrigin(r)
944 if origin == nil {
945 return "", APIError{
946 HTTPStatus: http.StatusForbidden,
947 Err: fmt.Errorf("required Origin header is missing or invalid"),
948 }
949 }
950 if !h.originAllowed(origin) {
951 return "", APIError{
952 HTTPStatus: http.StatusForbidden,
953 Err: fmt.Errorf("client is not allowed to access from origin '%s'", originStr),
954 }
955 }
956 return origin.String(), nil
957 }
958
959 func (h adminHandler) getOrigin(r *http.Request) (string, *url.URL) {
960 origin := r.Header.Get("Origin")
961 if origin == "" {
962 origin = r.Header.Get("Referer")
963 }
964 originURL, err := url.Parse(origin)
965 if err != nil {
966 return origin, nil
967 }
968 originURL.Path = ""
969 originURL.RawPath = ""
970 originURL.Fragment = ""
971 originURL.RawFragment = ""
972 originURL.RawQuery = ""
973 return origin, originURL
974 }
975
976 func (h adminHandler) originAllowed(origin *url.URL) bool {
977 for _, allowedOrigin := range h.allowedOrigins {
978 if allowedOrigin.Scheme != "" && origin.Scheme != allowedOrigin.Scheme {
979 continue
980 }
981 if origin.Host == allowedOrigin.Host {
982 return true
983 }
984 }
985 return false
986 }
987
988 // etagHasher returns the hasher we used on the config to both
989 // produce and verify ETags.
990 func etagHasher() hash.Hash { return xxhash.New() }
991
992 // makeEtag returns an Etag header value (including quotes) for
993 // the given config path and hash of contents at that path.
994 func makeEtag(path string, hash hash.Hash) string {
995 return fmt.Sprintf(`"%s %x"`, path, hash.Sum(nil))
996 }
997
998 // This buffer pool is used to keep buffers for
999 // reading the config file during eTag header generation
1000 var bufferPool = sync.Pool{
1001 New: func() any {
1002 return new(bytes.Buffer)
1003 },
1004 }
1005
1006 func handleConfig(w http.ResponseWriter, r *http.Request) error {
1007 switch r.Method {
1008 case http.MethodGet:
1009 w.Header().Set("Content-Type", "application/json")
1010 hash := etagHasher()
1011
1012 // Read the config into a buffer instead of writing directly to
1013 // the response writer, as we want to set the ETag as the header,
1014 // not the trailer.
1015 buf := bufferPool.Get().(*bytes.Buffer)
1016 buf.Reset()
1017 defer bufferPool.Put(buf)
1018
1019 configWriter := io.MultiWriter(buf, hash)
1020 err := readConfig(r.URL.Path, configWriter)
1021 if err != nil {
1022 return APIError{HTTPStatus: http.StatusBadRequest, Err: err}
1023 }
1024
1025 // we could consider setting up a sync.Pool for the summed
1026 // hashes to reduce GC pressure.
1027 w.Header().Set("Etag", makeEtag(r.URL.Path, hash))
1028 _, err = w.Write(buf.Bytes())
1029 if err != nil {
1030 return APIError{HTTPStatus: http.StatusInternalServerError, Err: err}
1031 }
1032
1033 return nil
1034
1035 case http.MethodPost,
1036 http.MethodPut,
1037 http.MethodPatch,
1038 http.MethodDelete:
1039
1040 // DELETE does not use a body, but the others do
1041 var body []byte
1042 if r.Method != http.MethodDelete {
1043 if ct := r.Header.Get("Content-Type"); !strings.Contains(ct, "/json") {
1044 return APIError{
1045 HTTPStatus: http.StatusBadRequest,
1046 Err: fmt.Errorf("unacceptable content-type: %v; 'application/json' required", ct),
1047 }
1048 }
1049
1050 buf := bufPool.Get().(*bytes.Buffer)
1051 buf.Reset()
1052 defer bufPool.Put(buf)
1053
1054 const maxConfigSize = 100 * 1024 * 1024 // 100 MB
1055 r.Body = http.MaxBytesReader(w, r.Body, maxConfigSize)
1056
1057 _, err := io.Copy(buf, r.Body)
1058 if err != nil {
1059 return APIError{
1060 HTTPStatus: http.StatusBadRequest,
1061 Err: fmt.Errorf("reading request body: %v", err),
1062 }
1063 }
1064 body = buf.Bytes()
1065 }
1066
1067 forceReload := r.Header.Get("Cache-Control") == "must-revalidate"
1068
1069 err := changeConfig(r.Method, r.URL.Path, body, r.Header.Get("If-Match"), forceReload)
1070 if err != nil && !errors.Is(err, errSameConfig) {
1071 return err
1072 }
1073
1074 // If this request changed the config, clear the last
1075 // config info we have stored, if it is different from
1076 // the original source.
1077 ClearLastConfigIfDifferent(
1078 r.Header.Get("Caddy-Config-Source-File"),
1079 r.Header.Get("Caddy-Config-Source-Adapter"))
1080
1081 default:
1082 return APIError{
1083 HTTPStatus: http.StatusMethodNotAllowed,
1084 Err: fmt.Errorf("method %s not allowed", r.Method),
1085 }
1086 }
1087
1088 return nil
1089 }
1090
1091 func handleConfigID(w http.ResponseWriter, r *http.Request) error {
1092 idPath := r.URL.Path
1093
1094 parts := strings.Split(idPath, "/")
1095 if len(parts) < 3 || parts[2] == "" {
1096 return APIError{
1097 HTTPStatus: http.StatusBadRequest,
1098 Err: fmt.Errorf("request path is missing object ID"),
1099 }
1100 }
1101 if parts[0] != "" || parts[1] != "id" {
1102 return APIError{
1103 HTTPStatus: http.StatusBadRequest,
1104 Err: fmt.Errorf("malformed object path"),
1105 }
1106 }
1107 id := parts[2]
1108
1109 // map the ID to the expanded path
1110 rawCfgMu.RLock()
1111 expanded, ok := rawCfgIndex[id]
1112 rawCfgMu.RUnlock()
1113 if !ok {
1114 return APIError{
1115 HTTPStatus: http.StatusNotFound,
1116 Err: fmt.Errorf("unknown object ID '%s'", id),
1117 }
1118 }
1119
1120 // piece the full URL path back together
1121 parts = append([]string{expanded}, parts[3:]...)
1122 r.URL.Path = path.Join(parts...)
1123
1124 return errInternalRedir
1125 }
1126
1127 func handleStop(w http.ResponseWriter, r *http.Request) error {
1128 if r.Method != http.MethodPost {
1129 return APIError{
1130 HTTPStatus: http.StatusMethodNotAllowed,
1131 Err: fmt.Errorf("method not allowed"),
1132 }
1133 }
1134
1135 exitProcess(context.Background(), Log().Named("admin.api"))
1136 return nil
1137 }
1138
1139 func parseCanonicalArrayIndex(idx string) (int, error) {
1140 if idx == "" {
1141 return 0, fmt.Errorf("empty index")
1142 }
1143 i, err := strconv.Atoi(idx)
1144 if err != nil {
1145 return 0, err
1146 }
1147 if strconv.Itoa(i) != idx {
1148 return 0, fmt.Errorf("non-canonical array index")
1149 }
1150 return i, nil
1151 }
1152
1153 // unsyncedConfigAccess traverses into the current config and performs
1154 // the operation at path according to method, using body and out as
1155 // needed. This is a low-level, unsynchronized function; most callers
1156 // will want to use changeConfig or readConfig instead. This requires a
1157 // read or write lock on currentCtxMu, depending on method (GET needs
1158 // only a read lock; all others need a write lock).
1159 func unsyncedConfigAccess(method, path string, body []byte, out io.Writer) error {
1160 var err error
1161 var val any
1162
1163 // if there is a request body, decode it into the
1164 // variable that will be set in the config according
1165 // to method and path
1166 if len(body) > 0 {
1167 err = json.Unmarshal(body, &val)
1168 if err != nil {
1169 if jsonErr, ok := err.(*json.SyntaxError); ok {
1170 return fmt.Errorf("decoding request body: %w, at offset %d", jsonErr, jsonErr.Offset)
1171 }
1172 return fmt.Errorf("decoding request body: %w", err)
1173 }
1174 }
1175
1176 enc := json.NewEncoder(out)
1177
1178 cleanPath := strings.Trim(path, "/")
1179 if cleanPath == "" {
1180 return fmt.Errorf("no traversable path")
1181 }
1182
1183 parts := strings.Split(cleanPath, "/")
1184 if len(parts) == 0 {
1185 return fmt.Errorf("path missing")
1186 }
1187
1188 // A path that ends with "..." implies:
1189 // 1) the part before it is an array
1190 // 2) the payload is an array
1191 // and means that the user wants to expand the elements
1192 // in the payload array and append each one into the
1193 // destination array, like so:
1194 // array = append(array, elems...)
1195 // This special case is handled below.
1196 ellipses := parts[len(parts)-1] == "..."
1197 if ellipses {
1198 parts = parts[:len(parts)-1]
1199 }
1200
1201 var ptr any = rawCfg
1202
1203 traverseLoop:
1204 for i, part := range parts {
1205 switch v := ptr.(type) {
1206 case map[string]any:
1207 // if the next part enters a slice, and the slice is our destination,
1208 // handle it specially (because appending to the slice copies the slice
1209 // header, which does not replace the original one like we want)
1210 if arr, ok := v[part].([]any); ok && i == len(parts)-2 {
1211 var idx int
1212 if method != http.MethodPost {
1213 idxStr := parts[len(parts)-1]
1214 idx, err = parseCanonicalArrayIndex(idxStr)
1215 if err != nil {
1216 return fmt.Errorf("[%s] invalid array index '%s': %v",
1217 path, idxStr, err)
1218 }
1219
1220 if idx < 0 || (method != http.MethodPut && idx >= len(arr)) || idx > len(arr) {
1221 return fmt.Errorf("[%s] array index out of bounds: %s", path, idxStr)
1222 }
1223 }
1224
1225 switch method {
1226 case http.MethodGet:
1227 err = enc.Encode(arr[idx])
1228 if err != nil {
1229 return fmt.Errorf("encoding config: %v", err)
1230 }
1231 case http.MethodPost:
1232 if ellipses {
1233 valArray, ok := val.([]any)
1234 if !ok {
1235 return fmt.Errorf("final element is not an array")
1236 }
1237 v[part] = append(arr, valArray...)
1238 } else {
1239 v[part] = append(arr, val)
1240 }
1241 case http.MethodPut:
1242 // avoid creation of new slice and a second copy (see
1243 // https://github.com/golang/go/wiki/SliceTricks#insert)
1244 arr = append(arr, nil)
1245 copy(arr[idx+1:], arr[idx:])
1246 arr[idx] = val
1247 v[part] = arr
1248 case http.MethodPatch:
1249 arr[idx] = val
1250 case http.MethodDelete:
1251 v[part] = append(arr[:idx], arr[idx+1:]...)
1252 default:
1253 return fmt.Errorf("unrecognized method %s", method)
1254 }
1255 break traverseLoop
1256 }
1257
1258 if i == len(parts)-1 {
1259 switch method {
1260 case http.MethodGet:
1261 err = enc.Encode(v[part])
1262 if err != nil {
1263 return fmt.Errorf("encoding config: %v", err)
1264 }
1265 case http.MethodPost:
1266 // if the part is an existing list, POST appends to
1267 // it, otherwise it just sets or creates the value
1268 if arr, ok := v[part].([]any); ok {
1269 if ellipses {
1270 valArray, ok := val.([]any)
1271 if !ok {
1272 return fmt.Errorf("final element is not an array")
1273 }
1274 v[part] = append(arr, valArray...)
1275 } else {
1276 v[part] = append(arr, val)
1277 }
1278 } else {
1279 v[part] = val
1280 }
1281 case http.MethodPut:
1282 if _, ok := v[part]; ok {
1283 return APIError{
1284 HTTPStatus: http.StatusConflict,
1285 Err: fmt.Errorf("[%s] key already exists: %s", path, part),
1286 }
1287 }
1288 v[part] = val
1289 case http.MethodPatch:
1290 if _, ok := v[part]; !ok {
1291 return APIError{
1292 HTTPStatus: http.StatusNotFound,
1293 Err: fmt.Errorf("[%s] key does not exist: %s", path, part),
1294 }
1295 }
1296 v[part] = val
1297 case http.MethodDelete:
1298 if _, ok := v[part]; !ok {
1299 return APIError{
1300 HTTPStatus: http.StatusNotFound,
1301 Err: fmt.Errorf("[%s] key does not exist: %s", path, part),
1302 }
1303 }
1304 delete(v, part)
1305 default:
1306 return fmt.Errorf("unrecognized method %s", method)
1307 }
1308 } else {
1309 // if we are "PUTting" a new resource, the key(s) in its path
1310 // might not exist yet; that's OK but we need to make them as
1311 // we go, while we still have a pointer from the level above
1312 if v[part] == nil && method == http.MethodPut {
1313 v[part] = make(map[string]any)
1314 }
1315 ptr = v[part]
1316 }
1317
1318 case []any:
1319 partInt, err := parseCanonicalArrayIndex(part)
1320 if err != nil {
1321 return fmt.Errorf("[/%s] invalid array index '%s': %v",
1322 strings.Join(parts[:i+1], "/"), part, err)
1323 }
1324 if partInt < 0 || partInt >= len(v) {
1325 return fmt.Errorf("[/%s] array index out of bounds: %s",
1326 strings.Join(parts[:i+1], "/"), part)
1327 }
1328 ptr = v[partInt]
1329
1330 default:
1331 return fmt.Errorf("invalid traversal path at: %s", strings.Join(parts[:i+1], "/"))
1332 }
1333 }
1334
1335 return nil
1336 }
1337
1338 // RemoveMetaFields removes meta fields like "@id" from a JSON message
1339 // by using a simple regular expression. (An alternate way to do this
1340 // would be to delete them from the raw, map[string]any
1341 // representation as they are indexed, then iterate the index we made
1342 // and add them back after encoding as JSON, but this is simpler.)
1343 func RemoveMetaFields(rawJSON []byte) []byte {
1344 return idRegexp.ReplaceAllFunc(rawJSON, func(in []byte) []byte {
1345 // matches with a comma on both sides (when "@id" property is
1346 // not the first or last in the object) need to keep exactly
1347 // one comma for correct JSON syntax
1348 comma := []byte{','}
1349 if bytes.HasPrefix(in, comma) && bytes.HasSuffix(in, comma) {
1350 return comma
1351 }
1352 return []byte{}
1353 })
1354 }
1355
1356 // AdminHandler is like http.Handler except ServeHTTP may return an error.
1357 //
1358 // If any handler encounters an error, it should be returned for proper
1359 // handling.
1360 type AdminHandler interface {
1361 ServeHTTP(http.ResponseWriter, *http.Request) error
1362 }
1363
1364 // AdminHandlerFunc is a convenience type like http.HandlerFunc.
1365 type AdminHandlerFunc func(http.ResponseWriter, *http.Request) error
1366
1367 // ServeHTTP implements the Handler interface.
1368 func (f AdminHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
1369 return f(w, r)
1370 }
1371
1372 // APIError is a structured error that every API
1373 // handler should return for consistency in logging
1374 // and client responses. If Message is unset, then
1375 // Err.Error() will be serialized in its place.
1376 type APIError struct {
1377 HTTPStatus int `json:"-"`
1378 Err error `json:"-"`
1379 Message string `json:"error"`
1380 }
1381
1382 func (e APIError) Error() string {
1383 if e.Err != nil {
1384 return e.Err.Error()
1385 }
1386 return e.Message
1387 }
1388
1389 // parseAdminListenAddr extracts a singular listen address from either addr
1390 // or defaultAddr, returning the network and the address of the listener.
1391 func parseAdminListenAddr(addr string, defaultAddr string) (NetworkAddress, error) {
1392 input, err := NewReplacer().ReplaceOrErr(addr, true, true)
1393 if err != nil {
1394 return NetworkAddress{}, fmt.Errorf("replacing listen address: %v", err)
1395 }
1396 if input == "" {
1397 input = defaultAddr
1398 }
1399 listenAddr, err := ParseNetworkAddress(input)
1400 if err != nil {
1401 return NetworkAddress{}, fmt.Errorf("parsing listener address: %v", err)
1402 }
1403 if listenAddr.PortRangeSize() != 1 {
1404 return NetworkAddress{}, fmt.Errorf("must be exactly one listener address; cannot listen on: %s", listenAddr)
1405 }
1406 return listenAddr, nil
1407 }
1408
1409 // decodeBase64DERCert base64-decodes, then DER-decodes, certStr.
1410 func decodeBase64DERCert(certStr string) (*x509.Certificate, error) {
1411 derBytes, err := base64.StdEncoding.DecodeString(certStr)
1412 if err != nil {
1413 return nil, err
1414 }
1415 return x509.ParseCertificate(derBytes)
1416 }
1417
1418 type loggableURLArray []*url.URL
1419
1420 func (ua loggableURLArray) MarshalLogArray(enc zapcore.ArrayEncoder) error {
1421 if ua == nil {
1422 return nil
1423 }
1424 for _, u := range ua {
1425 enc.AppendString(u.String())
1426 }
1427 return nil
1428 }
1429
1430 var (
1431 // DefaultAdminListen is the address for the local admin
1432 // listener, if none is specified at startup.
1433 DefaultAdminListen = "localhost:2019"
1434
1435 // DefaultRemoteAdminListen is the address for the remote
1436 // (TLS-authenticated) admin listener, if enabled and not
1437 // specified otherwise.
1438 DefaultRemoteAdminListen = ":2021"
1439 )
1440
1441 // PIDFile writes a pidfile to the file at filename. It
1442 // will get deleted before the process gracefully exits.
1443 func PIDFile(filename string) error {
1444 pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
1445 err := os.WriteFile(filename, pid, 0o600)
1446 if err != nil {
1447 return err
1448 }
1449 pidfile = filename
1450 return nil
1451 }
1452
1453 // idRegexp is used to match ID fields and their associated values
1454 // in the config. It also matches adjacent commas so that syntax
1455 // can be preserved no matter where in the object the field appears.
1456 // It supports string and most numeric values.
1457 var idRegexp = regexp.MustCompile(`(?m),?\s*"` + idKey + `"\s*:\s*(-?[0-9]+(\.[0-9]+)?|(?U)".*")\s*,?`)
1458
1459 // pidfile is the name of the pidfile, if any.
1460 var pidfile string
1461
1462 // errInternalRedir indicates an internal redirect
1463 // and is useful when admin API handlers rewrite
1464 // the request; in that case, authentication and
1465 // authorization needs to happen again for the
1466 // rewritten request.
1467 var errInternalRedir = fmt.Errorf("internal redirect; re-authorization required")
1468
1469 const (
1470 rawConfigKey = "config"
1471 idKey = "@id"
1472 )
1473
1474 var bufPool = sync.Pool{
1475 New: func() any {
1476 return new(bytes.Buffer)
1477 },
1478 }
1479
1480 // keep a reference to admin endpoint singletons while they're active
1481 var (
1482 serverMu sync.Mutex
1483 localAdminServer, remoteAdminServer *http.Server
1484 identityCertCache *certmagic.Cache
1485 )