oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package seal is Mapa's only encryption surface.
2//
3// The one rule (spec §4): titles, aliases, dates, bodies, drafts, member
4// addresses and time zones are sealed at rest, and the durable file never
5// holds a readable one. The DEK arrives as platform config and is never
6// written to the database it decrypts.
7//
8// This is a near-copy of Fichas' internal/fichas/seal, which says the same
9// of memoria's and Sheets'. Fichas' comment records that three copies is
10// the point to re-examine sharing one; this is the fourth, and the
11// construction being identical is still what matters.
12//
13// The HKDF info string is app-namespaced, "oficina/mapa:", so the same DEK
14// under two apps derives different keys. It must never change: it is baked
15// into every byte already sealed.
16package seal
17
18import (
19 "crypto/aes"
20 "crypto/cipher"
21 "crypto/hkdf"
22 "crypto/hmac"
23 "crypto/rand"
24 "crypto/sha256"
25 "encoding/hex"
26 "errors"
27 "sync"
28)
29
30// Purposes. One per kind of thing sealed, so a value sealed as one kind
31// cannot be opened as another.
32const (
33 // PurposeRecord seals a page's record: its title, date and body, on
34 // the page row and in the revision store alike.
35 PurposeRecord = "page.record"
36 // PurposeDraft seals a draft's text, which is not yet a revision.
37 PurposeDraft = "draft.record"
38 // PurposeAlias seals a title a team page used to have.
39 PurposeAlias = "alias.title"
40 // PurposeAddress seals a member's address, for display.
41 PurposeAddress = "member.address"
42 // PurposeTimeZone seals a member's time zone setting.
43 PurposeTimeZone = "member.timezone"
44 // PurposePins seals the pages a member pinned to their sidebar.
45 PurposePins = "member.pins"
46 // PurposeLocale seals a member's date and number format setting.
47 PurposeLocale = "member.locale"
48 // PurposeImage seals an image's bytes, padded (Pad), before they
49 // leave the process for the object store (images spec decision 1).
50 PurposeImage = "image"
51 // PurposeImageRecord seals what is known of an image: its sniffed
52 // type, its width and height after orientation, and its true size.
53 PurposeImageRecord = "image-record"
54
55 // The Notion import's (its spec §15). The token and the workspace
56 // it is bound to; a map row's coordinate (the Notion id, the Mapa
57 // page it became, what the import last wrote); a surveyed tree,
58 // held between Survey and Write.
59 PurposeNotionToken = "notion.token"
60 PurposeNotionWorkspace = "notion.workspace"
61 PurposeNotionCoordinate = "notion.coordinate"
62 PurposeNotionStaged = "notion.staged"
63 // PurposeNotionImage seals an image block's place: its block id,
64 // edit time, Mapa page and image, or why it was refused.
65 PurposeNotionImage = "notion.image"
66)
67
68// PadStep is what an image's plaintext is padded to a multiple of
69// before sealing, so a stored size says only "within 64 KiB" (images
70// spec decision 1, §1.3).
71const PadStep = 64 << 10
72
73// Overhead is what sealing adds to a plaintext: the nonce and GCM's
74// tag. A stored image is a multiple of PadStep plus this (IMG2).
75const Overhead = 12 + 16
76
77// Pad is plain followed by zeros to the next multiple of PadStep. The
78// true length is kept apart, in the sealed record; the zeros carry
79// nothing.
80func Pad(plain []byte) []byte {
81 size := (len(plain) + PadStep - 1) / PadStep * PadStep
82 if size == 0 {
83 size = PadStep
84 }
85 out := make([]byte, size)
86 copy(out, plain)
87 return out
88}
89
90// Print purposes. Each answers one equality question and no other, so a
91// title print can never be compared with an address print.
92const (
93 PrintTitle = "print.title"
94 PrintDaily = "print.daily"
95 PrintAddress = "print.address"
96 // PrintNotionPage is a Notion id's handle in the import's map. Its
97 // key is derived as "oficina/mapa:print:notion.page".
98 PrintNotionPage = "notion.page"
99 // PrintNotionImage is an image block's handle, alone or on a page:
100 // "oficina/mapa:print:notion.image".
101 PrintNotionImage = "notion.image"
102)
103
104// keyLength is AES-256's.
105const keyLength = 32
106
107// Sealer holds the data encryption key. One per process.
108//
109// It caches each purpose's derived AEAD: deriving one is most of an
110// Open's cost, and a purpose's key never changes. A GCM AEAD holds only
111// read-only state after construction and is safe for concurrent use.
112type Sealer struct {
113 dek []byte
114
115 mutex sync.RWMutex
116 aeads map[string]cipher.AEAD
117 keys map[string][]byte
118}
119
120// New returns a Sealer. The DEK must be exactly 32 bytes.
121func New(dek []byte) (*Sealer, error) {
122 if len(dek) != keyLength {
123 return nil, errors.New("seal: DEK must be 32 bytes")
124 }
125 own := append([]byte(nil), dek...)
126 return &Sealer{dek: own, aeads: map[string]cipher.AEAD{},
127 keys: map[string][]byte{}}, nil
128}
129
130// purposeKey derives purpose's key with HKDF over the DEK.
131func (sealer *Sealer) purposeKey(purpose string) ([]byte, error) {
132 return hkdf.Key(sha256.New, sealer.dek, nil,
133 "oficina/mapa:"+purpose, keyLength)
134}
135
136func (sealer *Sealer) aeadFor(purpose string) (cipher.AEAD, error) {
137 sealer.mutex.RLock()
138 aead, ok := sealer.aeads[purpose]
139 sealer.mutex.RUnlock()
140 if ok {
141 return aead, nil
142 }
143 key, err := sealer.purposeKey(purpose)
144 if err != nil {
145 return nil, err
146 }
147 block, err := aes.NewCipher(key)
148 if err != nil {
149 return nil, err
150 }
151 aead, err = cipher.NewGCM(block)
152 if err != nil {
153 return nil, err
154 }
155 sealer.mutex.Lock()
156 sealer.aeads[purpose] = aead
157 sealer.mutex.Unlock()
158 return aead, nil
159}
160
161// Seal encrypts plaintext under purpose. The nonce is prepended.
162func (sealer *Sealer) Seal(purpose string, plaintext []byte) ([]byte, error) {
163 aead, err := sealer.aeadFor(purpose)
164 if err != nil {
165 return nil, err
166 }
167 nonce := make([]byte, aead.NonceSize())
168 if _, err := rand.Read(nonce); err != nil {
169 return nil, err
170 }
171 return aead.Seal(nonce, nonce, plaintext, nil), nil
172}
173
174// SealPadded is Seal(purpose, Pad(plain)) in one allocation: the
175// padded plaintext is sealed in place, so a 10 MiB image costs one
176// buffer here, not three (images spec §1.4).
177func (sealer *Sealer) SealPadded(purpose string, plain []byte) ([]byte,
178 error) {
179 aead, err := sealer.aeadFor(purpose)
180 if err != nil {
181 return nil, err
182 }
183 size := max((len(plain)+PadStep-1)/PadStep*PadStep, PadStep)
184 nonce := aead.NonceSize()
185 out := make([]byte, nonce+size, nonce+size+aead.Overhead())
186 if _, err := rand.Read(out[:nonce]); err != nil {
187 return nil, err
188 }
189 copy(out[nonce:], plain)
190 return aead.Seal(out[:nonce], out[:nonce], out[nonce:], nil), nil
191}
192
193// Open decrypts a value sealed under the same purpose.
194func (sealer *Sealer) Open(purpose string, sealed []byte) ([]byte, error) {
195 aead, err := sealer.aeadFor(purpose)
196 if err != nil {
197 return nil, err
198 }
199 if len(sealed) < aead.NonceSize() {
200 return nil, errors.New("seal: ciphertext too short")
201 }
202 nonce, body := sealed[:aead.NonceSize()], sealed[aead.NonceSize():]
203 return aead.Open(nil, nonce, body, nil)
204}
205
206// Print is a keyed, deterministic fingerprint of plaintext under purpose.
207//
208// Keyed, never a bare hash: a bare SHA-256 of a title is a confirmation
209// oracle for anyone holding the file and a guess. HMAC under a purpose key
210// keeps the equality and removes the oracle (spec §4, title prints).
211func (sealer *Sealer) Print(purpose string, plaintext []byte) (string, error) {
212 key, err := sealer.printKey(purpose)
213 if err != nil {
214 return "", err
215 }
216 mac := hmac.New(sha256.New, key)
217 mac.Write(plaintext)
218 return hex.EncodeToString(mac.Sum(nil)), nil
219}
220
221// printKey is purpose's HMAC key, derived once.
222func (sealer *Sealer) printKey(purpose string) ([]byte, error) {
223 sealer.mutex.RLock()
224 key, ok := sealer.keys[purpose]
225 sealer.mutex.RUnlock()
226 if ok {
227 return key, nil
228 }
229 key, err := sealer.purposeKey("print:" + purpose)
230 if err != nil {
231 return nil, err
232 }
233 sealer.mutex.Lock()
234 sealer.keys[purpose] = key
235 sealer.mutex.Unlock()
236 return key, nil
237}
238