You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
471 lines
17 KiB
Go
471 lines
17 KiB
Go
// Package auth implements the signed request envelope used in addition to
|
|
// mTLS. The key is loaded from a host-local secret file; it is never stored in
|
|
// the panel database or included in operation payloads.
|
|
package auth
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const fileKeyBytes = 32
|
|
|
|
var (
|
|
ErrUnavailable = errors.New("request signing is not configured")
|
|
ErrInvalid = errors.New("invalid signed request envelope")
|
|
noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
|
|
hexPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
|
agentIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$`)
|
|
)
|
|
|
|
type NonceStore struct {
|
|
mu sync.Mutex
|
|
values map[string]time.Time
|
|
}
|
|
|
|
// NonceConsumer is implemented by a durable host-local journal. Keeping this
|
|
// interface in auth avoids a package cycle while allowing production agents to
|
|
// survive a restart without reopening an old signed request.
|
|
type NonceConsumer interface {
|
|
ConsumeNonce(nonce string, expiresAt, now time.Time) bool
|
|
}
|
|
|
|
func NewNonceStore() *NonceStore {
|
|
return &NonceStore{values: make(map[string]time.Time)}
|
|
}
|
|
|
|
// Consume accepts a nonce once until expiresAt. Expired entries are removed
|
|
// opportunistically; production deployments should persist this boundary in
|
|
// the operation journal or another host-local durable store.
|
|
func (s *NonceStore) Consume(nonce string, expiresAt, now time.Time) bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for key, expiry := range s.values {
|
|
if !expiry.After(now) {
|
|
delete(s.values, key)
|
|
}
|
|
}
|
|
if _, exists := s.values[nonce]; exists {
|
|
return false
|
|
}
|
|
s.values[nonce] = expiresAt
|
|
return true
|
|
}
|
|
|
|
type Verifier struct {
|
|
key []byte
|
|
maxSkew time.Duration
|
|
nonces *NonceStore
|
|
consumer NonceConsumer
|
|
required bool
|
|
agentID string
|
|
}
|
|
|
|
func NewDisabled() *Verifier {
|
|
return &Verifier{maxSkew: 60 * time.Second, nonces: NewNonceStore()}
|
|
}
|
|
|
|
// New constructs a verifier from a raw key. It is retained as a concise
|
|
// compatibility entry point for tests and callers that already hold key
|
|
// bytes; configuration files must use FromFile instead.
|
|
func New(key []byte, required bool) (*Verifier, error) {
|
|
return NewRaw(key, required)
|
|
}
|
|
|
|
// NewRaw constructs a verifier from raw key bytes. The host-agent file
|
|
// protocol is deliberately separate: files contain standard base64 text and
|
|
// are decoded by FromFile before reaching this constructor.
|
|
func NewRaw(key []byte, required bool) (*Verifier, error) {
|
|
return NewWithNonceConsumer(key, required, nil)
|
|
}
|
|
|
|
func NewWithNonceConsumer(key []byte, required bool, consumer NonceConsumer) (*Verifier, error) {
|
|
return NewWithNonceConsumerForAgent(key, required, consumer, "")
|
|
}
|
|
|
|
// NewForAgent constructs a verifier bound to one configured host identity.
|
|
// The agent ID is included in the signed canonical envelope, so a valid
|
|
// panel request for host A cannot be replayed against host B that happens to
|
|
// share transport credentials.
|
|
func NewForAgent(key []byte, required bool, agentID string) (*Verifier, error) {
|
|
return NewWithNonceConsumerForAgent(key, required, nil, agentID)
|
|
}
|
|
|
|
func NewWithNonceConsumerForAgent(key []byte, required bool, consumer NonceConsumer, agentID string) (*Verifier, error) {
|
|
agentID = strings.TrimSpace(agentID)
|
|
if agentID != "" && !agentIDPattern.MatchString(agentID) {
|
|
return nil, fmt.Errorf("agent identity is invalid")
|
|
}
|
|
if len(key) == 0 {
|
|
if required {
|
|
return &Verifier{maxSkew: 60 * time.Second, nonces: NewNonceStore(), consumer: consumer, required: true, agentID: agentID}, nil
|
|
}
|
|
value := NewDisabled()
|
|
value.consumer = consumer
|
|
value.agentID = agentID
|
|
return value, nil
|
|
}
|
|
if len(key) < 32 {
|
|
return nil, fmt.Errorf("request signing key must contain at least 32 bytes")
|
|
}
|
|
return &Verifier{key: append([]byte(nil), key...), maxSkew: 60 * time.Second,
|
|
nonces: NewNonceStore(), consumer: consumer, required: required, agentID: agentID}, nil
|
|
}
|
|
|
|
func FromFile(path string, required bool) (*Verifier, error) {
|
|
return FromFileWithNonceConsumer(path, required, nil)
|
|
}
|
|
|
|
func FromFileForAgent(path string, required bool, agentID string) (*Verifier, error) {
|
|
return FromFileWithNonceConsumerForAgent(path, required, nil, agentID)
|
|
}
|
|
|
|
func FromFileWithNonceConsumer(path string, required bool, consumer NonceConsumer) (*Verifier, error) {
|
|
return FromFileWithNonceConsumerForAgent(path, required, consumer, "")
|
|
}
|
|
|
|
func FromFileWithNonceConsumerForAgent(path string, required bool, consumer NonceConsumer, agentID string) (*Verifier, error) {
|
|
if strings.TrimSpace(path) == "" {
|
|
return NewWithNonceConsumerForAgent(nil, required, consumer, agentID)
|
|
}
|
|
data, err := readKeyFile(path)
|
|
if err != nil {
|
|
if required {
|
|
unavailable, _ := NewWithNonceConsumerForAgent(nil, true, consumer, agentID)
|
|
return unavailable, err
|
|
}
|
|
return nil, err
|
|
}
|
|
key, err := decodeFileKey(data)
|
|
if err != nil {
|
|
// Keep liveness available while making an invalid required secret
|
|
// explicitly visible to startup/readiness. The returned verifier cannot
|
|
// authenticate requests until the file is repaired.
|
|
if required {
|
|
unavailable, _ := NewWithNonceConsumerForAgent(nil, true, consumer, agentID)
|
|
return unavailable, err
|
|
}
|
|
return nil, err
|
|
}
|
|
return NewWithNonceConsumerForAgent(key, required, consumer, agentID)
|
|
}
|
|
|
|
// readKeyFile applies the host-secret boundary before decoding the wire
|
|
// format. The process stays alive in degraded mode when this check fails, but
|
|
// a key that is a symlink, non-regular file, or readable by group/other users
|
|
// can never become an active request verifier. A second Stat after opening
|
|
// narrows the lstat/open replacement window without introducing a platform-
|
|
// specific syscall into the cross-built agent.
|
|
func readKeyFile(path string) ([]byte, error) {
|
|
path, err := normalizeSecretPath(path, "request signing key")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read request signing key: %w", err)
|
|
}
|
|
parentInfo, err := checkSecretParent(filepath.Dir(path))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read request signing key: %w", err)
|
|
}
|
|
info, err := os.Lstat(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read request signing key: %w", err)
|
|
}
|
|
if info.Mode()&os.ModeSymlink != 0 {
|
|
return nil, fmt.Errorf("request signing key must not be a symlink")
|
|
}
|
|
if !info.Mode().IsRegular() {
|
|
return nil, fmt.Errorf("request signing key must be a regular file")
|
|
}
|
|
if !secureKeyMode(info.Mode()) {
|
|
return nil, fmt.Errorf("request signing key permissions must be owner-read-only or owner-read-write")
|
|
}
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read request signing key: %w", err)
|
|
}
|
|
defer file.Close()
|
|
openedInfo, err := file.Stat()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("stat request signing key: %w", err)
|
|
}
|
|
if !secureSecretFile(openedInfo) || !os.SameFile(info, openedInfo) {
|
|
return nil, fmt.Errorf("request signing key changed to an unsafe file")
|
|
}
|
|
currentParent, err := checkSecretParent(filepath.Dir(path))
|
|
if err != nil || !os.SameFile(parentInfo, currentParent) {
|
|
if err != nil {
|
|
return nil, fmt.Errorf("recheck request signing key parent: %w", err)
|
|
}
|
|
return nil, fmt.Errorf("request signing key parent changed while opening")
|
|
}
|
|
// Lstat the name after opening as well. This catches a replacement with a
|
|
// symlink (including a link back to the same inode) during the lstat/open
|
|
// window while the descriptor keeps the bytes we read stable.
|
|
currentInfo, err := os.Lstat(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("recheck request signing key: %w", err)
|
|
}
|
|
if !secureSecretFile(currentInfo) || !os.SameFile(info, currentInfo) {
|
|
return nil, fmt.Errorf("request signing key changed while opening")
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(file, 4097))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read request signing key: %w", err)
|
|
}
|
|
if len(data) > 4096 {
|
|
return nil, fmt.Errorf("request signing key exceeds 4096 bytes")
|
|
}
|
|
currentInfo, err = os.Lstat(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("recheck request signing key after read: %w", err)
|
|
}
|
|
if !secureSecretFile(currentInfo) || !os.SameFile(info, currentInfo) {
|
|
return nil, fmt.Errorf("request signing key changed while reading")
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
func secureKeyMode(mode os.FileMode) bool {
|
|
permissions := mode.Perm()
|
|
return (permissions == 0o400 || permissions == 0o600) &&
|
|
mode&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) == 0
|
|
}
|
|
|
|
// normalizeSecretPath makes the path used for every subsequent check and
|
|
// open unambiguous. Relative paths remain supported for local/test callers,
|
|
// but traversal components are rejected so cleaning cannot skip a symlinked
|
|
// component that was present in the caller's spelling.
|
|
func normalizeSecretPath(path, label string) (string, error) {
|
|
if path == "" || strings.TrimSpace(path) != path || strings.IndexByte(path, 0) >= 0 {
|
|
return "", fmt.Errorf("%s path is empty or malformed", label)
|
|
}
|
|
for _, component := range strings.FieldsFunc(path, func(r rune) bool {
|
|
return r == '/' || r == '\\'
|
|
}) {
|
|
if component == ".." {
|
|
return "", fmt.Errorf("%s path must not contain traversal components", label)
|
|
}
|
|
}
|
|
abs, err := filepath.Abs(path)
|
|
if err != nil {
|
|
return "", fmt.Errorf("resolve %s path: %w", label, err)
|
|
}
|
|
return filepath.Clean(abs), nil
|
|
}
|
|
|
|
// checkSecretParent checks every directory component rather than only the
|
|
// immediate parent. Lstat on the complete path follows an intermediate
|
|
// symlink, so each component is inspected independently. Parent directories
|
|
// may be readable by other users, but must never be writable by group/other
|
|
// unless the OS sticky bit protects the standard shared temporary boundary
|
|
// (for example /tmp). The final key file remains owner-only.
|
|
func checkSecretParent(path string) (os.FileInfo, error) {
|
|
abs, err := filepath.Abs(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolve secret parent: %w", err)
|
|
}
|
|
abs = filepath.Clean(abs)
|
|
root := filepath.VolumeName(abs) + string(filepath.Separator)
|
|
if filepath.VolumeName(abs) == "" {
|
|
root = string(filepath.Separator)
|
|
}
|
|
rest := strings.TrimPrefix(abs, root)
|
|
current := root
|
|
if rest == "" {
|
|
return checkSecretDirectory(current, path)
|
|
}
|
|
var last os.FileInfo
|
|
for _, component := range strings.Split(rest, string(filepath.Separator)) {
|
|
if component == "" || component == "." {
|
|
continue
|
|
}
|
|
current = filepath.Join(current, component)
|
|
info, err := checkSecretDirectory(current, path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
last = info
|
|
}
|
|
return last, nil
|
|
}
|
|
|
|
func checkSecretDirectory(path, original string) (os.FileInfo, error) {
|
|
info, err := os.Lstat(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("inspect request signing key parent %q: %w", original, err)
|
|
}
|
|
if info.Mode()&os.ModeSymlink != 0 {
|
|
if !trustedDarwinAlias(path) {
|
|
return nil, fmt.Errorf("request signing key parent %q must contain only real directories", original)
|
|
}
|
|
resolved, resolveErr := filepath.EvalSymlinks(path)
|
|
if resolveErr != nil {
|
|
return nil, fmt.Errorf("resolve request signing key parent %q: %w", original, resolveErr)
|
|
}
|
|
resolvedInfo, statErr := os.Lstat(resolved)
|
|
if statErr != nil || resolvedInfo.Mode()&os.ModeSymlink != 0 || !resolvedInfo.IsDir() {
|
|
if statErr != nil {
|
|
return nil, fmt.Errorf("inspect request signing key parent %q: %w", original, statErr)
|
|
}
|
|
return nil, fmt.Errorf("request signing key parent %q must contain only real directories", original)
|
|
}
|
|
info = resolvedInfo
|
|
}
|
|
if !info.IsDir() {
|
|
return nil, fmt.Errorf("request signing key parent %q must contain only real directories", original)
|
|
}
|
|
if !safeSecretDirectoryMode(info.Mode()) {
|
|
return nil, fmt.Errorf("request signing key parent %q must not be group/world writable", original)
|
|
}
|
|
return info, nil
|
|
}
|
|
|
|
func safeSecretDirectoryMode(mode os.FileMode) bool {
|
|
if mode&(os.ModeSetuid|os.ModeSetgid) != 0 {
|
|
return false
|
|
}
|
|
if mode.Perm()&0o022 == 0 {
|
|
return true
|
|
}
|
|
// A sticky directory prevents another user from replacing entries owned by
|
|
// the agent. This is the standard protection on /tmp and lets test/runtime
|
|
// paths use a private child directory without weakening the key-file mode.
|
|
return mode&os.ModeSticky != 0
|
|
}
|
|
|
|
// macOS exposes /var as a fixed root-level compatibility alias. It is unlike a
|
|
// caller-controlled symlink nested below the configured state directory. Keep
|
|
// this one narrow exception so t.TempDir paths remain usable on macOS while a
|
|
// custom symlinked ancestor is still rejected.
|
|
func trustedDarwinAlias(path string) bool {
|
|
if runtime.GOOS != "darwin" {
|
|
return false
|
|
}
|
|
switch filepath.Clean(path) {
|
|
case "/var":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func secureSecretFile(info os.FileInfo) bool {
|
|
return info != nil && info.Mode()&os.ModeSymlink == 0 && info.Mode().IsRegular() && secureKeyMode(info.Mode())
|
|
}
|
|
|
|
// decodeFileKey enforces the on-disk protocol shared with PHP CloudSecrets:
|
|
// canonical standard base64 encoding of exactly 32 raw key bytes. A single
|
|
// trailing newline (or other surrounding whitespace accepted by trim) is
|
|
// allowed for ordinary secret-file tooling; embedded whitespace and
|
|
// non-canonical padding are rejected.
|
|
func decodeFileKey(data []byte) ([]byte, error) {
|
|
encoded := strings.TrimSpace(string(data))
|
|
if encoded == "" {
|
|
return nil, fmt.Errorf("request signing key file is empty")
|
|
}
|
|
key, err := base64.StdEncoding.Strict().DecodeString(encoded)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("request signing key must be strict base64")
|
|
}
|
|
if len(key) != fileKeyBytes {
|
|
return nil, fmt.Errorf("request signing key must decode to %d bytes", fileKeyBytes)
|
|
}
|
|
if base64.StdEncoding.EncodeToString(key) != encoded {
|
|
return nil, fmt.Errorf("request signing key must use canonical base64")
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
func (v *Verifier) Ready() bool {
|
|
return v != nil && (!v.required || len(v.key) >= 32)
|
|
}
|
|
|
|
func Canonical(method, target, digest, timestamp, nonce, actor string) []byte {
|
|
return []byte(strings.ToUpper(method) + "\n" + target + "\n" + digest + "\n" + timestamp + "\n" + nonce + "\n" + actor)
|
|
}
|
|
|
|
// CanonicalForAgent extends the v1 envelope with a host identity. The empty
|
|
// agent ID intentionally retains the unbound test/local form; production
|
|
// agents created by main always use a non-empty configured identity.
|
|
func CanonicalForAgent(method, target, digest, timestamp, nonce, agentID, actor string) []byte {
|
|
if agentID == "" {
|
|
return Canonical(method, target, digest, timestamp, nonce, actor)
|
|
}
|
|
return []byte(strings.ToUpper(method) + "\n" + target + "\n" + digest + "\n" + timestamp + "\n" + nonce + "\n" + agentID + "\n" + actor)
|
|
}
|
|
|
|
func Sign(key []byte, method, target string, body []byte, timestamp time.Time, nonce, actor string) string {
|
|
return SignForAgent(key, method, target, body, timestamp, nonce, "", actor)
|
|
}
|
|
|
|
func SignForAgent(key []byte, method, target string, body []byte, timestamp time.Time, nonce, agentID, actor string) string {
|
|
digest := sha256.Sum256(body)
|
|
timestampRaw := strconv.FormatInt(timestamp.Unix(), 10)
|
|
mac := hmac.New(sha256.New, key)
|
|
_, _ = mac.Write(CanonicalForAgent(method, target, hex.EncodeToString(digest[:]), timestampRaw, nonce, agentID, actor))
|
|
return hex.EncodeToString(mac.Sum(nil))
|
|
}
|
|
|
|
func (v *Verifier) Verify(r *http.Request, body []byte, now time.Time) error {
|
|
if v == nil || (!v.required && len(v.key) == 0) {
|
|
return nil
|
|
}
|
|
if !v.Ready() {
|
|
return ErrUnavailable
|
|
}
|
|
timestampRaw := r.Header.Get("X-Cloud-Timestamp")
|
|
nonce := r.Header.Get("X-Cloud-Nonce")
|
|
agentID := r.Header.Get("X-Cloud-Agent-ID")
|
|
actor := r.Header.Get("X-Cloud-Actor")
|
|
signature := r.Header.Get("X-Cloud-Signature")
|
|
if !regexp.MustCompile(`^[0-9]{1,12}$`).MatchString(timestampRaw) ||
|
|
!noncePattern.MatchString(nonce) ||
|
|
!hexPattern.MatchString(signature) || actor == "" || len(actor) > 8192 ||
|
|
!regexp.MustCompile(`^[A-Za-z0-9_-]+$`).MatchString(actor) {
|
|
return ErrInvalid
|
|
}
|
|
if v.agentID != "" {
|
|
if agentID != v.agentID || !agentIDPattern.MatchString(agentID) {
|
|
return ErrInvalid
|
|
}
|
|
} else if agentID != "" && !agentIDPattern.MatchString(agentID) {
|
|
return ErrInvalid
|
|
}
|
|
timestamp, err := strconv.ParseInt(timestampRaw, 10, 64)
|
|
if err != nil || now.Sub(time.Unix(timestamp, 0)) > v.maxSkew || time.Unix(timestamp, 0).Sub(now) > v.maxSkew {
|
|
return ErrInvalid
|
|
}
|
|
digest := sha256.Sum256(body)
|
|
expectedMac := hmac.New(sha256.New, v.key)
|
|
_, _ = expectedMac.Write(CanonicalForAgent(r.Method, r.URL.RequestURI(), hex.EncodeToString(digest[:]), timestampRaw, nonce, agentID, actor))
|
|
expected := expectedMac.Sum(nil)
|
|
provided, err := hex.DecodeString(signature)
|
|
if err != nil || !hmac.Equal(expected, provided) {
|
|
return ErrInvalid
|
|
}
|
|
expiresAt := now.Add(v.maxSkew*2 + time.Second)
|
|
accepted := false
|
|
if v.consumer != nil {
|
|
accepted = v.consumer.ConsumeNonce(nonce, expiresAt, now)
|
|
} else {
|
|
accepted = v.nonces.Consume(nonce, expiresAt, now)
|
|
}
|
|
if !accepted {
|
|
return ErrInvalid
|
|
}
|
|
return nil
|
|
}
|