oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package operator verifies private administrative requests independently of
2// browser identities and instance bearer credentials.
3package operator
4
5import (
6 "bytes"
7 "crypto/elliptic"
8 "crypto/sha256"
9 "encoding/base64"
10 "encoding/hex"
11 "errors"
12 "net/url"
13 "strings"
14 "time"
15 "unicode/utf8"
16
17 family "amadan.net/rastrillo/rastrillo/crypto"
18 "github.com/go-json-experiment/json"
19 "github.com/go-json-experiment/json/jsontext"
20)
21
22const (
23 BodyLimit = 64 << 10
24 InputLimit = 48 << 10
25 AuthorizationLimit = 16 << 10
26 InputContext = "oficina/home/operator-input/v1"
27 OwnerContext = "oficina/home/owner-seed/v1"
28)
29
30var (
31 ErrRefused = errors.New("operator: refused")
32 ErrUnavailable = errors.New("operator: unavailable")
33)
34
35type Authorization struct {
36 Version int `json:"version"`
37 Purpose string `json:"purpose"`
38 Role string `json:"role"`
39 Origin string `json:"origin"`
40 Installation string `json:"installation"`
41 Registry string `json:"registry"`
42 Device string `json:"device"`
43 Sequence int64 `json:"sequence"`
44 Initial bool `json:"initial_authority"`
45 Previous string `json:"previous"`
46 JournalSequence int64 `json:"journal_sequence"`
47 OperationID string `json:"operation_id"`
48 Action string `json:"action"`
49 InputDigest string `json:"input_digest"`
50 Issued int64 `json:"issued_at"`
51 Expires int64 `json:"expires_at"`
52}
53
54type Pins struct {
55 Role, Origin, Installation, Registry, Device string
56 PublicKey string
57 Actions []string
58}
59
60type envelope struct {
61 Version int `json:"v"`
62 KeyID string `json:"kid"`
63 Payload string `json:"payload"`
64 Signature string `json:"signature"`
65}
66
67type wrapper struct {
68 Version int `json:"version"`
69 Authorization jsontext.Value `json:"signed_authorization"`
70 Input jsontext.Value `json:"operation_input"`
71}
72
73type Verifier struct {
74 pins Pins
75 key []byte
76 kid string
77 actions map[string]bool
78}
79
80// Request's authority and input bytes can only be produced by Verify. Returned
81// copies cannot change the verified request retained by the transaction layer.
82type Request struct {
83 authorization Authorization
84 input []byte
85 head string
86 valid bool
87}
88
89func (r Request) Authorization() Authorization { return r.authorization }
90func (r Request) Input() []byte { return append([]byte(nil), r.input...) }
91func (r Request) Head() string { return r.head }
92func (r Request) Valid() bool { return r.valid }
93func (r Request) Fresh(now time.Time) bool {
94 n := now.Unix()
95 a := r.authorization
96 return r.valid && n > 0 && a.Issued <= n && n < a.Expires
97}
98
99func CanonicalToken(s string) bool { _, ok := canonical(s, 32); return ok }
100func canonical(s string, n int) ([]byte, bool) {
101 if len(s) > BodyLimit {
102 return nil, false
103 }
104 b, e := base64.RawURLEncoding.Strict().DecodeString(s)
105 return b, e == nil && (n < 0 || len(b) == n) && base64.RawURLEncoding.EncodeToString(b) == s
106}
107func Origin(s string) bool {
108 if len(s) == 0 || len(s) > 253 {
109 return false
110 }
111 u, e := url.Parse(s)
112 return e == nil && u.Scheme == "https" && u.Host != "" && u.Host == strings.ToLower(u.Host) && u.User == nil && u.Path == "" && u.RawPath == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && u.RawFragment == "" && !strings.ContainsAny(u.Host, "%\\:") && !strings.HasSuffix(u.Host, ".") && u.String() == s
113}
114func digest(b []byte) string {
115 h := sha256.Sum256(b)
116 return base64.RawURLEncoding.EncodeToString(h[:])
117}
118func keyID(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) }
119func public(encoded string) ([]byte, error) {
120 b, ok := canonical(encoded, 65)
121 if !ok {
122 return nil, ErrRefused
123 }
124 x, _ := elliptic.Unmarshal(elliptic.P256(), b)
125 if x == nil {
126 return nil, ErrRefused
127 }
128 return b, nil
129}
130func allowedAction(role, a string) bool {
131 if role == "credential" {
132 switch a {
133 case "credential.owner-seed", "credential.register-consumer", "credential.retire-consumer", "credential.inspect":
134 return true
135 }
136 }
137 if role == "directory" {
138 switch a {
139 case "directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer":
140 return true
141 }
142 }
143 return false
144}
145func NewVerifier(p Pins) (*Verifier, error) {
146 if !Origin(p.Origin) || !CanonicalToken(p.Installation) || !CanonicalToken(p.Registry) || !CanonicalToken(p.Device) || len(p.Actions) == 0 || len(p.Actions) > 8 {
147 return nil, ErrRefused
148 }
149 k, e := public(p.PublicKey)
150 if e != nil {
151 return nil, ErrRefused
152 }
153 v := &Verifier{pins: p, key: k, kid: keyID(k), actions: map[string]bool{}}
154 v.pins.Actions = append([]string(nil), p.Actions...)
155 for _, a := range p.Actions {
156 if !allowedAction(p.Role, a) || v.actions[a] {
157 return nil, ErrRefused
158 }
159 v.actions[a] = true
160 }
161 return v, nil
162}
163func strict(b []byte, d any) error {
164 if !utf8.Valid(b) || json.Unmarshal(b, d, json.RejectUnknownMembers(true)) != nil {
165 return ErrRefused
166 }
167 return nil
168}
169func encode(v any) ([]byte, error) {
170 b, e := json.Marshal(v, json.Deterministic(true))
171 if e != nil {
172 return nil, ErrRefused
173 }
174 return b, nil
175}
176func strictCanonical(b []byte, d any) error {
177 if strict(b, d) != nil {
178 return ErrRefused
179 }
180 canonical, e := encode(d)
181 if e != nil || !bytes.Equal(b, canonical) {
182 return ErrRefused
183 }
184 return nil
185}
186func (a Authorization) valid() bool {
187 return a.Version == 1 && a.Purpose == "operator-input" && allowedAction(a.Role, a.Action) && Origin(a.Origin) && CanonicalToken(a.Installation) && CanonicalToken(a.Registry) && CanonicalToken(a.Device) && CanonicalToken(a.OperationID) && CanonicalToken(a.InputDigest) && a.Sequence > 0 && a.Initial == (a.Sequence == 1) && a.JournalSequence > 0 && ((a.Sequence == 1 && a.Previous == "") || (a.Sequence > 1 && CanonicalToken(a.Previous))) && a.Issued > 0 && a.Expires > a.Issued && a.Expires-a.Issued <= 300
188}
189
190// Verify deliberately retains an expired but authentic request for exact result
191// recovery. A storage mutation must also require Fresh after checking replay.
192func (v *Verifier) Verify(raw []byte) (Request, error) {
193 if v == nil || len(raw) == 0 || len(raw) > BodyLimit {
194 return Request{}, ErrRefused
195 }
196 var w wrapper
197 if strictCanonical(raw, &w) != nil || w.Version != 1 || len(w.Authorization) == 0 || len(w.Authorization) > AuthorizationLimit || len(w.Input) == 0 || len(w.Input) > InputLimit {
198 return Request{}, ErrRefused
199 }
200 var e envelope
201 if strictCanonical(w.Authorization, &e) != nil || e.Version != 1 || e.KeyID != v.kid {
202 return Request{}, ErrRefused
203 }
204 payload, ok := canonical(e.Payload, -1)
205 sig, ok2 := canonical(e.Signature, 64)
206 if !ok || !ok2 || len(payload) > AuthorizationLimit || !family.Verify(v.key, InputContext, payload, sig) {
207 return Request{}, ErrRefused
208 }
209 var a Authorization
210 if strictCanonical(payload, &a) != nil || !a.valid() || !v.actions[a.Action] || a.Role != v.pins.Role || a.Origin != v.pins.Origin || a.Installation != v.pins.Installation || a.Registry != v.pins.Registry || a.Device != v.pins.Device || a.InputDigest != digest(w.Input) {
211 return Request{}, ErrRefused
212 }
213 return Request{a, append([]byte(nil), w.Input...), digest(w.Authorization), true}, nil
214}
215
216func DecodeInput(r Request, dst any) error {
217 if !r.valid || strictCanonical(r.input, dst) != nil {
218 return ErrRefused
219 }
220 return nil
221}
222
223// SignRequest is used by the separate provisioner. It does not grant execution
224// authority; the platform still requires fresh owner approval and a held fence.
225func SignRequest(k *family.Keypair, a Authorization, input any) ([]byte, error) {
226 if !signingKey(k) {
227 return nil, ErrRefused
228 }
229 b, e := encode(input)
230 if e != nil || len(b) > InputLimit {
231 return nil, ErrRefused
232 }
233 a.InputDigest = digest(b)
234 if !a.valid() {
235 return nil, ErrRefused
236 }
237 p, e := encode(a)
238 if e != nil {
239 return nil, e
240 }
241 signature, e := family.Sign(k, InputContext, p)
242 if e != nil {
243 return nil, ErrUnavailable
244 }
245 env, e := encode(envelope{1, keyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(p), base64.RawURLEncoding.EncodeToString(signature)})
246 if e != nil || len(env) > AuthorizationLimit {
247 return nil, ErrRefused
248 }
249 out, e := encode(wrapper{1, env, b})
250 if e != nil || len(out) > BodyLimit {
251 return nil, ErrRefused
252 }
253 return out, nil
254}
255
256func signingKey(k *family.Keypair) bool {
257 if k == nil || k.SignPriv == nil {
258 return false
259 }
260 p := k.SignPriv
261 return p.Curve == elliptic.P256() && p.D != nil && p.D.Sign() > 0 && p.D.Cmp(elliptic.P256().Params().N) < 0 && p.X != nil && p.Y != nil && elliptic.P256().IsOnCurve(p.X, p.Y)
262}
263