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.
virt/agent/auth/auth.go

258 lines
7.4 KiB
Go

package auth
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
const (
HeaderTimestamp = "X-Virt-Timestamp"
HeaderNonce = "X-Virt-Nonce"
HeaderBodyDigest = "X-Virt-Content-SHA256"
HeaderActor = "X-Virt-Actor"
HeaderSignature = "X-Virt-Signature"
MaxActorHeaderLen = 4096
)
var (
ErrUnauthorized = errors.New("unauthorized")
ErrReplay = errors.New("request nonce has already been used")
ErrNonceStore = errors.New("nonce store unavailable")
noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
hexPattern = regexp.MustCompile(`^[0-9a-f]+$`)
operationID = regexp.MustCompile(`^[A-Za-z0-9_-]{8,80}$`)
)
type Actor struct {
UserID int64 `json:"user_id"`
IsAdmin bool `json:"is_admin"`
IsSuperAdmin bool `json:"is_super_admin"`
CanManage bool `json:"can_manage"`
SystemRecovery bool `json:"system_recovery,omitempty"`
OperationID string `json:"operation_id,omitempty"`
}
func (a Actor) Validate() error {
if a.UserID < 0 {
return errors.New("user_id cannot be negative")
}
if a.OperationID != "" && !operationID.MatchString(a.OperationID) {
return errors.New("operation_id must be 8-80 URL-safe characters")
}
if a.SystemRecovery {
if a.UserID != 0 || a.IsAdmin || a.IsSuperAdmin || a.CanManage {
return errors.New("system_recovery actor must be unprivileged with user_id 0")
}
if a.OperationID == "" {
return errors.New("system_recovery actor must name one operation_id")
}
}
return nil
}
type Authenticator struct {
secret []byte
skew time.Duration
nonceTTL time.Duration
now func() time.Time
mu sync.Mutex
store NonceStore
}
type NonceStore interface {
// UseNonce atomically persists a nonce through expiresAt. It returns false
// when that nonce is already live; expiry is strictly before now.
UseNonce(nonce string, now, expiresAt time.Time) (bool, error)
}
type memoryNonceStore struct {
mu sync.Mutex
nonces map[string]time.Time
}
func New(secret []byte, skew, nonceTTL time.Duration) (*Authenticator, error) {
return NewWithNonceStore(secret, skew, nonceTTL, &memoryNonceStore{nonces: make(map[string]time.Time)})
}
func NewWithNonceStore(secret []byte, skew, nonceTTL time.Duration, store NonceStore) (*Authenticator, error) {
if len(secret) < 32 {
return nil, errors.New("HMAC secret must contain at least 32 bytes")
}
if skew <= 0 || nonceTTL < skew || nonceTTL-skew < skew {
return nil, errors.New("nonce TTL must be at least twice the positive clock skew")
}
if store == nil {
return nil, errors.New("nonce store is required")
}
copySecret := append([]byte(nil), secret...)
return &Authenticator{
secret: copySecret, skew: skew, nonceTTL: nonceTTL,
now: time.Now, store: store,
}, nil
}
func (a *Authenticator) SetClockForTesting(now func() time.Time) {
a.mu.Lock()
defer a.mu.Unlock()
a.now = now
}
func BodyDigest(body []byte) string {
sum := sha256.Sum256(body)
return hex.EncodeToString(sum[:])
}
func RequestTarget(r *http.Request) string {
path := r.URL.EscapedPath()
if path == "" {
path = "/"
}
if r.URL.RawQuery != "" {
return path + "?" + r.URL.RawQuery
}
return path
}
func Canonical(method, target, digest, timestamp, nonce, actor string) string {
return strings.ToUpper(method) + "\n" + target + "\n" + digest + "\n" +
timestamp + "\n" + nonce + "\n" + actor
}
func Signature(secret []byte, canonical string) string {
mac := hmac.New(sha256.New, secret)
_, _ = mac.Write([]byte(canonical))
return hex.EncodeToString(mac.Sum(nil))
}
// Sign applies the complete wire contract. It is useful to panel clients and
// tests; production callers should generate a cryptographically random nonce.
func Sign(r *http.Request, body []byte, actor Actor, secret []byte, timestamp int64, nonce string) error {
if err := actor.Validate(); err != nil {
return err
}
actorJSON, err := json.Marshal(actor)
if err != nil {
return err
}
actorHeader := base64.RawURLEncoding.EncodeToString(actorJSON)
digest := BodyDigest(body)
ts := strconv.FormatInt(timestamp, 10)
r.Header.Set(HeaderTimestamp, ts)
r.Header.Set(HeaderNonce, nonce)
r.Header.Set(HeaderBodyDigest, digest)
r.Header.Set(HeaderActor, actorHeader)
r.Header.Set(HeaderSignature, Signature(secret, Canonical(r.Method, RequestTarget(r), digest, ts, nonce, actorHeader)))
return nil
}
func (a *Authenticator) Authenticate(r *http.Request, body []byte) (Actor, error) {
timestampHeader := r.Header.Get(HeaderTimestamp)
nonce := r.Header.Get(HeaderNonce)
digestHeader := r.Header.Get(HeaderBodyDigest)
actorHeader := r.Header.Get(HeaderActor)
signatureHeader := r.Header.Get(HeaderSignature)
if timestampHeader == "" || nonce == "" || digestHeader == "" || actorHeader == "" || signatureHeader == "" {
return Actor{}, ErrUnauthorized
}
if !noncePattern.MatchString(nonce) || len(actorHeader) > MaxActorHeaderLen ||
len(digestHeader) != sha256.Size*2 || !hexPattern.MatchString(digestHeader) ||
len(signatureHeader) != sha256.Size*2 || !hexPattern.MatchString(signatureHeader) {
return Actor{}, ErrUnauthorized
}
timestamp, err := strconv.ParseInt(timestampHeader, 10, 64)
if err != nil || strconv.FormatInt(timestamp, 10) != timestampHeader {
return Actor{}, ErrUnauthorized
}
now := a.currentTime()
requestTime := time.Unix(timestamp, 0)
if requestTime.Before(now.Add(-a.skew)) || requestTime.After(now.Add(a.skew)) {
return Actor{}, ErrUnauthorized
}
expectedDigest := BodyDigest(body)
if subtle.ConstantTimeCompare([]byte(expectedDigest), []byte(digestHeader)) != 1 {
return Actor{}, ErrUnauthorized
}
canonical := Canonical(r.Method, RequestTarget(r), digestHeader, timestampHeader, nonce, actorHeader)
expectedSignature := Signature(a.secret, canonical)
if subtle.ConstantTimeCompare([]byte(expectedSignature), []byte(signatureHeader)) != 1 {
return Actor{}, ErrUnauthorized
}
actor, err := decodeActor(actorHeader)
if err != nil {
return Actor{}, ErrUnauthorized
}
if err := a.useNonce(nonce, now); err != nil {
return Actor{}, err
}
return actor, nil
}
func (a *Authenticator) currentTime() time.Time {
a.mu.Lock()
defer a.mu.Unlock()
return a.now()
}
func (a *Authenticator) useNonce(nonce string, now time.Time) error {
accepted, err := a.store.UseNonce(nonce, now, now.Add(a.nonceTTL))
if err != nil {
return fmt.Errorf("%w: %v", ErrNonceStore, err)
}
if !accepted {
return ErrReplay
}
return nil
}
func (s *memoryNonceStore) UseNonce(nonce string, now, expiresAt time.Time) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
for value, expiry := range s.nonces {
if expiry.Before(now) {
delete(s.nonces, value)
}
}
if _, exists := s.nonces[nonce]; exists {
return false, nil
}
s.nonces[nonce] = expiresAt
return true, nil
}
func decodeActor(encoded string) (Actor, error) {
raw, err := base64.RawURLEncoding.DecodeString(encoded)
if err != nil {
return Actor{}, fmt.Errorf("decode actor: %w", err)
}
decoder := json.NewDecoder(strings.NewReader(string(raw)))
decoder.DisallowUnknownFields()
var actor Actor
if err := decoder.Decode(&actor); err != nil {
return Actor{}, err
}
var extra any
if err := decoder.Decode(&extra); err != io.EOF {
return Actor{}, errors.New("actor must contain exactly one JSON object")
}
if err := actor.Validate(); err != nil {
return Actor{}, err
}
return actor, nil
}