// Package hostedwire is the signed protocol between the Equipo instance (and // operators) and equipo-hosted-controller, plus the strict JSON types of the // controller's HTTP routes. // // Every request carries four headers: the key ID, a Unix timestamp in // seconds, a single-use nonce and an ed25519 signature over // // "equipo-hosted-request-v1\n" + method + "\n" + escaped path and raw query + // "\n" + timestamp + "\n" + nonce + "\n" + hex(sha256(body)) // // Every response carries a signature by the controller's key over // // "equipo-hosted-response-v1\n" + status + "\n" + request nonce + "\n" + // hex(sha256(body)) // // so a response cannot be moved to another request. The key ID is not in the // signed message; it only picks the public key, and the Verifier refuses a key // table where two IDs share one public key. package hostedwire import ( "crypto/ed25519" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "net/http" "net/url" "strconv" "strings" "time" ) // Header names. Each must appear exactly once. const ( HeaderKeyID = "Equipo-Key-Id" HeaderTimestamp = "Equipo-Timestamp" // Unix seconds, decimal, no sign or leading zero HeaderNonce = "Equipo-Nonce" HeaderSignature = "Equipo-Signature" // base64 (standard, padded) of the 64-byte signature ) const ( // MaxBody is the largest request or response body either side accepts. MaxBody = 1 << 20 // MaxSkew is how far a request's timestamp may be from the verifier's // clock, either way. MaxSkew = 60 * time.Second // NonceTTL is how long a verifier keeps a nonce, from the time it // verified the request. It must outlive the skew window, so a request // whose nonce has been forgotten is already refused as skewed. NonceTTL = 10 * time.Minute requestDomain = "equipo-hosted-request-v1" responseDomain = "equipo-hosted-response-v1" ) // KeyID names a verify key in the controller's key table. type KeyID string // Role is what a key may do. type Role string const ( RoleInstance Role = "instance" RoleOperator Role = "operator" ) // VerifyKey is a public key and the role it holds. type VerifyKey struct { Public ed25519.PublicKey Role Role } // NewNonce returns a fresh request nonce: 32 characters of base64url from // 24 random bytes. func NewNonce() (string, error) { var b [24]byte if _, err := rand.Read(b[:]); err != nil { return "", fmt.Errorf("hostedwire: nonce: %w", err) } return base64.RawURLEncoding.EncodeToString(b[:]), nil } // SignRequest sets the four signature headers on r for body, which must be // the exact bytes r will send. It replaces any existing signature headers. func SignRequest(r *http.Request, body []byte, id KeyID, key ed25519.PrivateKey, now time.Time, nonce string) error { if len(key) != ed25519.PrivateKeySize { return fmt.Errorf("%w: signing key has the wrong length", ErrNotConfigured) } if !validKeyID(string(id)) { return fmt.Errorf("%w: key ID", ErrMalformed) } if !validNonce(nonce) { return fmt.Errorf("%w: nonce", ErrMalformed) } if len(body) > MaxBody { return ErrTooLarge } target, err := requestTarget(r) if err != nil { return err } ts := now.Unix() if ts < 0 { return fmt.Errorf("%w: timestamp before 1970", ErrMalformed) } sig := ed25519.Sign(key, requestMessage(r.Method, target, ts, nonce, body)) if r.Header == nil { r.Header = http.Header{} } for _, name := range []string{HeaderKeyID, HeaderTimestamp, HeaderNonce, HeaderSignature} { deleteFold(r.Header, name) } r.Header.Set(HeaderKeyID, string(id)) r.Header.Set(HeaderTimestamp, strconv.FormatInt(ts, 10)) r.Header.Set(HeaderNonce, nonce) r.Header.Set(HeaderSignature, base64.StdEncoding.EncodeToString(sig)) return nil } // SignResponse sets the response signature header in h. requestNonce is the // nonce of the request being answered. key must be a full ed25519 private // key; ed25519.Sign panics otherwise. func SignResponse(h http.Header, status int, requestNonce string, body []byte, key ed25519.PrivateKey) { sig := ed25519.Sign(key, responseMessage(status, requestNonce, body)) deleteFold(h, HeaderSignature) h.Set(HeaderSignature, base64.StdEncoding.EncodeToString(sig)) } func requestMessage(method, target string, ts int64, nonce string, body []byte) []byte { sum := sha256.Sum256(body) return []byte(requestDomain + "\n" + method + "\n" + target + "\n" + strconv.FormatInt(ts, 10) + "\n" + nonce + "\n" + hex.EncodeToString(sum[:])) } func responseMessage(status int, requestNonce string, body []byte) []byte { sum := sha256.Sum256(body) return []byte(responseDomain + "\n" + strconv.Itoa(status) + "\n" + requestNonce + "\n" + hex.EncodeToString(sum[:])) } // requestTarget is the escaped path and, when the URL has a query (even an // empty one), "?" and the raw query. Opaque URLs and control characters are // refused. func requestTarget(r *http.Request) (string, error) { if r.URL == nil || r.URL.Opaque != "" { return "", fmt.Errorf("%w: request URL", ErrMalformed) } if r.Method == "" || hasControlOrSpace(r.Method) { return "", fmt.Errorf("%w: method", ErrMalformed) } target := escapedPath(r.URL) // "/v1/vms?" and "/v1/vms" are different targets, so an empty query // keeps its "?" (url.URL marks it with ForceQuery). if r.URL.ForceQuery || r.URL.RawQuery != "" { target += "?" + r.URL.RawQuery } if hasControlOrSpace(target) { return "", fmt.Errorf("%w: request target", ErrMalformed) } return target, nil } func escapedPath(u *url.URL) string { p := u.EscapedPath() if p == "" { return "/" } return p } func hasControlOrSpace(s string) bool { for i := 0; i < len(s); i++ { if s[i] <= ' ' || s[i] == 0x7f { return true } } return false } // validNonce: 16 to 64 characters of [A-Za-z0-9_-]. func validNonce(s string) bool { return len(s) >= 16 && len(s) <= 64 && onlyChars(s, "_-") } // validKeyID: 1 to 64 characters of [A-Za-z0-9._-]. func validKeyID(s string) bool { return len(s) >= 1 && len(s) <= 64 && onlyChars(s, "._-") } func onlyChars(s, extra string) bool { for i := 0; i < len(s); i++ { c := s[i] ok := c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte(extra, c) >= 0 if !ok { return false } } return true } // deleteFold removes every key equal to name ignoring case, including keys // that were set without canonicalisation. func deleteFold(h http.Header, name string) { for k := range h { if strings.EqualFold(k, name) { delete(h, k) } } }