| 1 | package hostedwire |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/ed25519" |
| 7 | "encoding/base64" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "net/http" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // One sentinel per kind of refusal, so the controller can count them. Error |
| 17 | // texts never hold key material or a body. |
| 18 | var ( |
| 19 | ErrUnsigned = errors.New("hostedwire: signature header missing") |
| 20 | ErrMalformed = errors.New("hostedwire: signature header malformed or repeated") |
| 21 | ErrUnknownKey = errors.New("hostedwire: unknown key ID") |
| 22 | ErrSharedKey = errors.New("hostedwire: public key listed under more than one key ID") |
| 23 | ErrSkew = errors.New("hostedwire: timestamp outside the allowed skew") |
| 24 | ErrTooLarge = errors.New("hostedwire: body too large") |
| 25 | ErrBadSignature = errors.New("hostedwire: bad signature") |
| 26 | ErrReplay = errors.New("hostedwire: nonce already used") |
| 27 | ErrNonceStore = errors.New("hostedwire: nonce store failed") |
| 28 | ErrNotConfigured = errors.New("hostedwire: verifier not configured") |
| 29 | ) |
| 30 | |
| 31 | // NonceStore remembers nonces per key. Remember records (id, nonce) until |
| 32 | // the given time and reports true when it was not already held. It must be |
| 33 | // atomic: of two concurrent calls with the same pair, at most one gets true. |
| 34 | type NonceStore interface { |
| 35 | Remember(ctx context.Context, id KeyID, nonce string, until time.Time) (bool, error) |
| 36 | } |
| 37 | |
| 38 | // Verifier checks signed requests. All three fields are required. Now is the |
| 39 | // controller's clock. |
| 40 | type Verifier struct { |
| 41 | Keys map[KeyID]VerifyKey |
| 42 | Nonces NonceStore |
| 43 | Now func() time.Time |
| 44 | } |
| 45 | |
| 46 | // Verify checks r's signature headers against body, the exact bytes read |
| 47 | // from r.Body, and returns the signer. In order it: parses the headers |
| 48 | // strictly, looks up the key, checks the skew against v.Now, checks the body |
| 49 | // size, verifies the signature, and only then records the nonce with |
| 50 | // Remember(r.Context(), id, nonce, now+NonceTTL). A nonce already held is a |
| 51 | // replay; a store error denies. |
| 52 | func (v *Verifier) Verify(r *http.Request, body []byte) (KeyID, VerifyKey, error) { |
| 53 | if v == nil || v.Keys == nil || v.Nonces == nil || v.Now == nil { |
| 54 | return "", VerifyKey{}, ErrNotConfigured |
| 55 | } |
| 56 | h, err := parseRequestHeaders(r.Header) |
| 57 | if err != nil { |
| 58 | return "", VerifyKey{}, err |
| 59 | } |
| 60 | key, err := v.lookup(h.id) |
| 61 | if err != nil { |
| 62 | return "", VerifyKey{}, err |
| 63 | } |
| 64 | now := v.Now() |
| 65 | // A timestamp near the top of int64 wraps inside time.Unix to a date |
| 66 | // far in the past, which the skew check refuses (TestSkewRefused). |
| 67 | sent := time.Unix(h.ts, 0) |
| 68 | if now.Sub(sent) > MaxSkew || sent.Sub(now) > MaxSkew { |
| 69 | return "", VerifyKey{}, ErrSkew |
| 70 | } |
| 71 | if len(body) > MaxBody { |
| 72 | return "", VerifyKey{}, ErrTooLarge |
| 73 | } |
| 74 | target, err := requestTarget(r) |
| 75 | if err != nil { |
| 76 | return "", VerifyKey{}, err |
| 77 | } |
| 78 | if !ed25519.Verify(key.Public, requestMessage(r.Method, target, h.ts, h.nonce, body), h.sig) { |
| 79 | return "", VerifyKey{}, ErrBadSignature |
| 80 | } |
| 81 | fresh, err := v.Nonces.Remember(r.Context(), h.id, h.nonce, now.Add(NonceTTL)) |
| 82 | if err != nil { |
| 83 | return "", VerifyKey{}, fmt.Errorf("%w: %w", ErrNonceStore, err) |
| 84 | } |
| 85 | if !fresh { |
| 86 | return "", VerifyKey{}, ErrReplay |
| 87 | } |
| 88 | return h.id, VerifyKey{Public: bytes.Clone(key.Public), Role: key.Role}, nil |
| 89 | } |
| 90 | |
| 91 | // lookup finds id's key and refuses a table where its public key is also |
| 92 | // listed under another ID: the key ID is not signed, so a shared public key |
| 93 | // would let its holder pick either ID and that ID's role. |
| 94 | func (v *Verifier) lookup(id KeyID) (VerifyKey, error) { |
| 95 | key, ok := v.Keys[id] |
| 96 | if !ok { |
| 97 | return VerifyKey{}, ErrUnknownKey |
| 98 | } |
| 99 | if len(key.Public) != ed25519.PublicKeySize { |
| 100 | return VerifyKey{}, fmt.Errorf("%w: public key for a key ID has the wrong length", ErrNotConfigured) |
| 101 | } |
| 102 | for other, k := range v.Keys { |
| 103 | if other != id && bytes.Equal(k.Public, key.Public) { |
| 104 | return VerifyKey{}, ErrSharedKey |
| 105 | } |
| 106 | } |
| 107 | return key, nil |
| 108 | } |
| 109 | |
| 110 | type requestHeaders struct { |
| 111 | id KeyID |
| 112 | ts int64 |
| 113 | nonce string |
| 114 | sig []byte |
| 115 | } |
| 116 | |
| 117 | func parseRequestHeaders(h http.Header) (requestHeaders, error) { |
| 118 | var out requestHeaders |
| 119 | id, err := single(h, HeaderKeyID) |
| 120 | if err != nil { |
| 121 | return out, err |
| 122 | } |
| 123 | tsText, err := single(h, HeaderTimestamp) |
| 124 | if err != nil { |
| 125 | return out, err |
| 126 | } |
| 127 | nonce, err := single(h, HeaderNonce) |
| 128 | if err != nil { |
| 129 | return out, err |
| 130 | } |
| 131 | sigText, err := single(h, HeaderSignature) |
| 132 | if err != nil { |
| 133 | return out, err |
| 134 | } |
| 135 | if !validKeyID(id) { |
| 136 | return out, fmt.Errorf("%w: key ID", ErrMalformed) |
| 137 | } |
| 138 | ts, err := strconv.ParseInt(tsText, 10, 64) |
| 139 | if err != nil || ts < 0 || strconv.FormatInt(ts, 10) != tsText { |
| 140 | return out, fmt.Errorf("%w: timestamp", ErrMalformed) |
| 141 | } |
| 142 | if !validNonce(nonce) { |
| 143 | return out, fmt.Errorf("%w: nonce", ErrMalformed) |
| 144 | } |
| 145 | sig, err := parseSignature(sigText) |
| 146 | if err != nil { |
| 147 | return out, err |
| 148 | } |
| 149 | return requestHeaders{id: KeyID(id), ts: ts, nonce: nonce, sig: sig}, nil |
| 150 | } |
| 151 | |
| 152 | func parseSignature(text string) ([]byte, error) { |
| 153 | sig, err := base64.StdEncoding.Strict().DecodeString(text) |
| 154 | if err != nil || len(sig) != ed25519.SignatureSize { |
| 155 | return nil, fmt.Errorf("%w: signature", ErrMalformed) |
| 156 | } |
| 157 | return sig, nil |
| 158 | } |
| 159 | |
| 160 | // single returns the one value of the header name, matching keys without |
| 161 | // regard to case so a second copy under a non-canonical key still counts. |
| 162 | func single(h http.Header, name string) (string, error) { |
| 163 | var vals []string |
| 164 | for k, v := range h { |
| 165 | if strings.EqualFold(k, name) { |
| 166 | vals = append(vals, v...) |
| 167 | } |
| 168 | } |
| 169 | switch len(vals) { |
| 170 | case 0: |
| 171 | return "", fmt.Errorf("%w: %s", ErrUnsigned, name) |
| 172 | case 1: |
| 173 | return vals[0], nil |
| 174 | default: |
| 175 | return "", fmt.Errorf("%w: %s repeated", ErrMalformed, name) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // VerifyResponse checks that resp, with body (the exact bytes read from |
| 180 | // resp.Body), was signed by pub as the answer to the request whose nonce was |
| 181 | // requestNonce. |
| 182 | func VerifyResponse(resp *http.Response, body []byte, requestNonce string, pub ed25519.PublicKey) error { |
| 183 | if len(pub) != ed25519.PublicKeySize { |
| 184 | return fmt.Errorf("%w: controller key has the wrong length", ErrNotConfigured) |
| 185 | } |
| 186 | if !validNonce(requestNonce) { |
| 187 | return fmt.Errorf("%w: request nonce", ErrMalformed) |
| 188 | } |
| 189 | if resp == nil { |
| 190 | return ErrUnsigned |
| 191 | } |
| 192 | text, err := single(resp.Header, HeaderSignature) |
| 193 | if err != nil { |
| 194 | return err |
| 195 | } |
| 196 | sig, err := parseSignature(text) |
| 197 | if err != nil { |
| 198 | return err |
| 199 | } |
| 200 | if len(body) > MaxBody { |
| 201 | return ErrTooLarge |
| 202 | } |
| 203 | if !ed25519.Verify(pub, responseMessage(resp.StatusCode, requestNonce, body), sig) { |
| 204 | return ErrBadSignature |
| 205 | } |
| 206 | return nil |
| 207 | } |
| 208 | |