mirror of
https://github.com/caddyserver/caddy.git
synced 2024-12-02 05:33:38 +08:00
ab80ff4fd2
This commits dds 3 separate, but very related features: 1. Automated server identity management How do you know you're connecting to the server you think you are? How do you know the server connecting to you is the server instance you think it is? Mutually-authenticated TLS (mTLS) answers both of these questions. Using TLS to authenticate requires a public/private key pair (and the peer must trust the certificate you present to it). Fortunately, Caddy is really good at managing certificates by now. We tap into that power to make it possible for Caddy to obtain and renew its own identity credentials, or in other words, a certificate that can be used for both server verification when clients connect to it, and client verification when it connects to other servers. Its associated private key is essentially its identity, and TLS takes care of possession proofs. This configuration is simply a list of identifiers and an optional list of custom certificate issuers. Identifiers are things like IP addresses or DNS names that can be used to access the Caddy instance. The default issuers are ZeroSSL and Let's Encrypt, but these are public CAs, so they won't issue certs for private identifiers. Caddy will simply manage credentials for these, which other parts of Caddy can use, for example: remote administration or dynamic config loading (described below). 2. Remote administration over secure connection This feature adds generic remote admin functionality that is safe to expose on a public interface. - The "remote" (or "secure") endpoint is optional. It does not affect the standard/local/plaintext endpoint. - It's the same as the [API endpoint on localhost:2019](https://caddyserver.com/docs/api), but over TLS. - TLS cannot be disabled on this endpoint. - TLS mutual auth is required, and cannot be disabled. - The server's certificate _must_ be obtained and renewed via automated means, such as ACME. It cannot be manually loaded. - The TLS server takes care of verifying the client. - The admin handler takes care of application-layer permissions (methods and paths that each client is allowed to use).\ - Sensible defaults are still WIP. - Config fields subject to change/renaming. 3. Dyanmic config loading at startup Since this feature was planned in tandem with remote admin, and depends on its changes, I am combining them into one PR. Dynamic config loading is where you tell Caddy how to load its config, and then it loads and runs that. First, it will load the config you give it (and persist that so it can be optionally resumed later). Then, it will try pulling its _actual_ config using the module you've specified (dynamically loaded configs are _not_ persisted to storage, since resuming them doesn't make sense). This PR comes with a standard config loader module called `caddy.config_loaders.http`. Caddyfile config for all of this can probably be added later. COMMITS: * admin: Secure socket for remote management Functional, but still WIP. Optional secure socket for the admin endpoint is designed for remote management, i.e. to be exposed on a public port. It enforces TLS mutual authentication which cannot be disabled. The default port for this is :2021. The server certificate cannot be specified manually, it MUST be obtained from a certificate issuer (i.e. ACME). More polish and sensible defaults are still in development. Also cleaned up and consolidated the code related to quitting the process. * Happy lint * Implement dynamic config loading; HTTP config loader module This allows Caddy to load a dynamic config when it starts. Dynamically-loaded configs are intentionally not persisted to storage. Includes an implementation of the standard config loader, HTTPLoader. Can be used to download configs over HTTP(S). * Refactor and cleanup; prevent recursive config pulls Identity management is now separated from remote administration. There is no need to enable remote administration if all you want is identity management, but you will need to configure identity management if you want remote administration. * Fix lint warnings * Rename identities->identifiers for consistency
171 lines
4.7 KiB
Go
171 lines
4.7 KiB
Go
// Copyright 2015 Matthew Holt and The Caddy Authors
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package caddyconfig
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/caddyserver/caddy/v2"
|
|
)
|
|
|
|
func init() {
|
|
caddy.RegisterModule(adminLoad{})
|
|
}
|
|
|
|
// adminLoad is a module that provides the /load endpoint
|
|
// for the Caddy admin API. The only reason it's not baked
|
|
// into the caddy package directly is because of the import
|
|
// of the caddyconfig package for its GetAdapter function.
|
|
// If the caddy package depends on the caddyconfig package,
|
|
// then the caddyconfig package will not be able to import
|
|
// the caddy package, and it can more easily cause backward
|
|
// edges in the dependency tree (i.e. import cycle).
|
|
// Fortunately, the admin API has first-class support for
|
|
// adding endpoints from modules.
|
|
type adminLoad struct{}
|
|
|
|
// CaddyModule returns the Caddy module information.
|
|
func (adminLoad) CaddyModule() caddy.ModuleInfo {
|
|
return caddy.ModuleInfo{
|
|
ID: "admin.api.load",
|
|
New: func() caddy.Module { return new(adminLoad) },
|
|
}
|
|
}
|
|
|
|
// Routes returns a route for the /load endpoint.
|
|
func (al adminLoad) Routes() []caddy.AdminRoute {
|
|
return []caddy.AdminRoute{
|
|
{
|
|
Pattern: "/load",
|
|
Handler: caddy.AdminHandlerFunc(al.handleLoad),
|
|
},
|
|
}
|
|
}
|
|
|
|
// handleLoad replaces the entire current configuration with
|
|
// a new one provided in the response body. It supports config
|
|
// adapters through the use of the Content-Type header. A
|
|
// config that is identical to the currently-running config
|
|
// will be a no-op unless Cache-Control: must-revalidate is set.
|
|
func (adminLoad) handleLoad(w http.ResponseWriter, r *http.Request) error {
|
|
if r.Method != http.MethodPost {
|
|
return caddy.APIError{
|
|
HTTPStatus: http.StatusMethodNotAllowed,
|
|
Err: fmt.Errorf("method not allowed"),
|
|
}
|
|
}
|
|
|
|
buf := bufPool.Get().(*bytes.Buffer)
|
|
buf.Reset()
|
|
defer bufPool.Put(buf)
|
|
|
|
_, err := io.Copy(buf, r.Body)
|
|
if err != nil {
|
|
return caddy.APIError{
|
|
HTTPStatus: http.StatusBadRequest,
|
|
Err: fmt.Errorf("reading request body: %v", err),
|
|
}
|
|
}
|
|
body := buf.Bytes()
|
|
|
|
// if the config is formatted other than Caddy's native
|
|
// JSON, we need to adapt it before loading it
|
|
if ctHeader := r.Header.Get("Content-Type"); ctHeader != "" {
|
|
result, warnings, err := adaptByContentType(ctHeader, body)
|
|
if err != nil {
|
|
return caddy.APIError{
|
|
HTTPStatus: http.StatusBadRequest,
|
|
Err: err,
|
|
}
|
|
}
|
|
if len(warnings) > 0 {
|
|
respBody, err := json.Marshal(warnings)
|
|
if err != nil {
|
|
caddy.Log().Named("admin.api.load").Error(err.Error())
|
|
}
|
|
_, _ = w.Write(respBody)
|
|
}
|
|
body = result
|
|
}
|
|
|
|
forceReload := r.Header.Get("Cache-Control") == "must-revalidate"
|
|
|
|
err = caddy.Load(body, forceReload)
|
|
if err != nil {
|
|
return caddy.APIError{
|
|
HTTPStatus: http.StatusBadRequest,
|
|
Err: fmt.Errorf("loading config: %v", err),
|
|
}
|
|
}
|
|
|
|
caddy.Log().Named("admin.api").Info("load complete")
|
|
|
|
return nil
|
|
}
|
|
|
|
// adaptByContentType adapts body to Caddy JSON using the adapter specified by contenType.
|
|
// If contentType is empty or ends with "/json", the input will be returned, as a no-op.
|
|
func adaptByContentType(contentType string, body []byte) ([]byte, []Warning, error) {
|
|
// assume JSON as the default
|
|
if contentType == "" {
|
|
return body, nil, nil
|
|
}
|
|
|
|
ct, _, err := mime.ParseMediaType(contentType)
|
|
if err != nil {
|
|
return nil, nil, caddy.APIError{
|
|
HTTPStatus: http.StatusBadRequest,
|
|
Err: fmt.Errorf("invalid Content-Type: %v", err),
|
|
}
|
|
}
|
|
|
|
// if already JSON, no need to adapt
|
|
if strings.HasSuffix(ct, "/json") {
|
|
return body, nil, nil
|
|
}
|
|
|
|
// adapter name should be suffix of MIME type
|
|
slashIdx := strings.Index(ct, "/")
|
|
if slashIdx < 0 {
|
|
return nil, nil, fmt.Errorf("malformed Content-Type")
|
|
}
|
|
|
|
adapterName := ct[slashIdx+1:]
|
|
cfgAdapter := GetAdapter(adapterName)
|
|
if cfgAdapter == nil {
|
|
return nil, nil, fmt.Errorf("unrecognized config adapter '%s'", adapterName)
|
|
}
|
|
|
|
result, warnings, err := cfgAdapter.Adapt(body, nil)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("adapting config using %s adapter: %v", adapterName, err)
|
|
}
|
|
|
|
return result, warnings, nil
|
|
}
|
|
|
|
var bufPool = sync.Pool{
|
|
New: func() interface{} {
|
|
return new(bytes.Buffer)
|
|
},
|
|
}
|