oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package hostedwire is the signed protocol between the Equipo instance (and
2// operators) and equipo-hosted-controller, plus the strict JSON types of the
3// controller's HTTP routes.
4//
5// Every request carries four headers: the key ID, a Unix timestamp in
6// seconds, a single-use nonce and an ed25519 signature over
7//
8// "equipo-hosted-request-v1\n" + method + "\n" + escaped path and raw query +
9// "\n" + timestamp + "\n" + nonce + "\n" + hex(sha256(body))
10//
11// Every response carries a signature by the controller's key over
12//
13// "equipo-hosted-response-v1\n" + status + "\n" + request nonce + "\n" +
14// hex(sha256(body))
15//
16// so a response cannot be moved to another request. The key ID is not in the
17// signed message; it only picks the public key, and the Verifier refuses a key
18// table where two IDs share one public key.
19package hostedwire
20
21import (
22 "crypto/ed25519"
23 "crypto/rand"
24 "crypto/sha256"
25 "encoding/base64"
26 "encoding/hex"
27 "fmt"
28 "net/http"
29 "net/url"
30 "strconv"
31 "strings"
32 "time"
33)
34
35// Header names. Each must appear exactly once.
36const (
37 HeaderKeyID = "Equipo-Key-Id"
38 HeaderTimestamp = "Equipo-Timestamp" // Unix seconds, decimal, no sign or leading zero
39 HeaderNonce = "Equipo-Nonce"
40 HeaderSignature = "Equipo-Signature" // base64 (standard, padded) of the 64-byte signature
41)
42
43const (
44 // MaxBody is the largest request or response body either side accepts.
45 MaxBody = 1 << 20
46 // MaxSkew is how far a request's timestamp may be from the verifier's
47 // clock, either way.
48 MaxSkew = 60 * time.Second
49 // NonceTTL is how long a verifier keeps a nonce, from the time it
50 // verified the request. It must outlive the skew window, so a request
51 // whose nonce has been forgotten is already refused as skewed.
52 NonceTTL = 10 * time.Minute
53
54 requestDomain = "equipo-hosted-request-v1"
55 responseDomain = "equipo-hosted-response-v1"
56)
57
58// KeyID names a verify key in the controller's key table.
59type KeyID string
60
61// Role is what a key may do.
62type Role string
63
64const (
65 RoleInstance Role = "instance"
66 RoleOperator Role = "operator"
67)
68
69// VerifyKey is a public key and the role it holds.
70type VerifyKey struct {
71 Public ed25519.PublicKey
72 Role Role
73}
74
75// NewNonce returns a fresh request nonce: 32 characters of base64url from
76// 24 random bytes.
77func NewNonce() (string, error) {
78 var b [24]byte
79 if _, err := rand.Read(b[:]); err != nil {
80 return "", fmt.Errorf("hostedwire: nonce: %w", err)
81 }
82 return base64.RawURLEncoding.EncodeToString(b[:]), nil
83}
84
85// SignRequest sets the four signature headers on r for body, which must be
86// the exact bytes r will send. It replaces any existing signature headers.
87func SignRequest(r *http.Request, body []byte, id KeyID, key ed25519.PrivateKey, now time.Time, nonce string) error {
88 if len(key) != ed25519.PrivateKeySize {
89 return fmt.Errorf("%w: signing key has the wrong length", ErrNotConfigured)
90 }
91 if !validKeyID(string(id)) {
92 return fmt.Errorf("%w: key ID", ErrMalformed)
93 }
94 if !validNonce(nonce) {
95 return fmt.Errorf("%w: nonce", ErrMalformed)
96 }
97 if len(body) > MaxBody {
98 return ErrTooLarge
99 }
100 target, err := requestTarget(r)
101 if err != nil {
102 return err
103 }
104 ts := now.Unix()
105 if ts < 0 {
106 return fmt.Errorf("%w: timestamp before 1970", ErrMalformed)
107 }
108 sig := ed25519.Sign(key, requestMessage(r.Method, target, ts, nonce, body))
109 if r.Header == nil {
110 r.Header = http.Header{}
111 }
112 for _, name := range []string{HeaderKeyID, HeaderTimestamp, HeaderNonce, HeaderSignature} {
113 deleteFold(r.Header, name)
114 }
115 r.Header.Set(HeaderKeyID, string(id))
116 r.Header.Set(HeaderTimestamp, strconv.FormatInt(ts, 10))
117 r.Header.Set(HeaderNonce, nonce)
118 r.Header.Set(HeaderSignature, base64.StdEncoding.EncodeToString(sig))
119 return nil
120}
121
122// SignResponse sets the response signature header in h. requestNonce is the
123// nonce of the request being answered. key must be a full ed25519 private
124// key; ed25519.Sign panics otherwise.
125func SignResponse(h http.Header, status int, requestNonce string, body []byte, key ed25519.PrivateKey) {
126 sig := ed25519.Sign(key, responseMessage(status, requestNonce, body))
127 deleteFold(h, HeaderSignature)
128 h.Set(HeaderSignature, base64.StdEncoding.EncodeToString(sig))
129}
130
131func requestMessage(method, target string, ts int64, nonce string, body []byte) []byte {
132 sum := sha256.Sum256(body)
133 return []byte(requestDomain + "\n" + method + "\n" + target + "\n" +
134 strconv.FormatInt(ts, 10) + "\n" + nonce + "\n" + hex.EncodeToString(sum[:]))
135}
136
137func responseMessage(status int, requestNonce string, body []byte) []byte {
138 sum := sha256.Sum256(body)
139 return []byte(responseDomain + "\n" + strconv.Itoa(status) + "\n" + requestNonce + "\n" +
140 hex.EncodeToString(sum[:]))
141}
142
143// requestTarget is the escaped path and, when the URL has a query (even an
144// empty one), "?" and the raw query. Opaque URLs and control characters are
145// refused.
146func requestTarget(r *http.Request) (string, error) {
147 if r.URL == nil || r.URL.Opaque != "" {
148 return "", fmt.Errorf("%w: request URL", ErrMalformed)
149 }
150 if r.Method == "" || hasControlOrSpace(r.Method) {
151 return "", fmt.Errorf("%w: method", ErrMalformed)
152 }
153 target := escapedPath(r.URL)
154 // "/v1/vms?" and "/v1/vms" are different targets, so an empty query
155 // keeps its "?" (url.URL marks it with ForceQuery).
156 if r.URL.ForceQuery || r.URL.RawQuery != "" {
157 target += "?" + r.URL.RawQuery
158 }
159 if hasControlOrSpace(target) {
160 return "", fmt.Errorf("%w: request target", ErrMalformed)
161 }
162 return target, nil
163}
164
165func escapedPath(u *url.URL) string {
166 p := u.EscapedPath()
167 if p == "" {
168 return "/"
169 }
170 return p
171}
172
173func hasControlOrSpace(s string) bool {
174 for i := 0; i < len(s); i++ {
175 if s[i] <= ' ' || s[i] == 0x7f {
176 return true
177 }
178 }
179 return false
180}
181
182// validNonce: 16 to 64 characters of [A-Za-z0-9_-].
183func validNonce(s string) bool {
184 return len(s) >= 16 && len(s) <= 64 && onlyChars(s, "_-")
185}
186
187// validKeyID: 1 to 64 characters of [A-Za-z0-9._-].
188func validKeyID(s string) bool {
189 return len(s) >= 1 && len(s) <= 64 && onlyChars(s, "._-")
190}
191
192func onlyChars(s, extra string) bool {
193 for i := 0; i < len(s); i++ {
194 c := s[i]
195 ok := c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte(extra, c) >= 0
196 if !ok {
197 return false
198 }
199 }
200 return true
201}
202
203// deleteFold removes every key equal to name ignoring case, including keys
204// that were set without canonicalisation.
205func deleteFold(h http.Header, name string) {
206 for k := range h {
207 if strings.EqualFold(k, name) {
208 delete(h, k)
209 }
210 }
211}
212