GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — crypt/keyring.go at main · ubgo/crypt Expand file tree/ Copy pathkeyring.goMore file actions 422 lines (393 loc) · 13.1 KB / Copy pathkeyring.goFile metadata and controls422 lines (393 loc) · 13.1 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 package crypt import ( "crypto/aes" "crypto/cipher" "encoding/base64" "errors" "fmt" "io" "sync" "sync/atomic" ) // KeyRing supports graceful key rotation: writes always use the // active key; reads dispatch by the kid (key id) embedded in each // ciphertext. // // Wire format (version 0x03): // // [0x03][kid_len:1][kid:kid_len][nonce:12][ciphertext:N][tag:16] // // Old AEAD ciphertext (version 0x01, no kid) is also openable by // KeyRing: Open tries the active key first, then every other key in // the ring. // // # Concurrency // // A KeyRing is safe for concurrent use by multiple goroutines, and // that includes changing it while it is in use: [KeyRing.Add], // [KeyRing.SetActive] and [KeyRing.Remove] may run at the same time // as [KeyRing.Seal], [KeyRing.Open], [KeyRing.Reseal] and // [KeyRing.ActiveKid], so keys can be rotated in a running process // without a restart. // // The ring keeps an immutable snapshot of its keys behind an atomic // pointer. Every read operation loads that snapshot once (one atomic // load, no lock) and works only on it, so one Seal or Open always // sees one consistent state: the kid written into a ciphertext is // always the kid of the key that sealed it. A change builds a new // snapshot under a mutex that only writers take, and publishes it // atomically. A Seal that started before a SetActive may still use // the previous active key; a Seal that starts after SetActive returns // uses the new one. // // A KeyRing must be created with [NewKeyRing] and must not be copied // after first use. // // Use cases: // - Annual key rotation (compliance). // - Compromise response: add new active key, drop old key after // all data has rotated through (see [KeyRing.Reseal] and // [SealedKeyID]). type KeyRing struct { mu sync.Mutex // serialises writers; readers never take it state atomic.Pointer[keyRingState] } // keyRingState is one immutable snapshot of a KeyRing. It is never // modified after it has been published; writers copy it. type keyRingState struct { active string activeKey cipher.AEAD keys map[string]cipher.AEAD } // errKeyRingUninitialised is returned when a KeyRing was declared as // a zero value instead of being built with NewKeyRing. var errKeyRingUninitialised = errors.New("crypt: KeyRing is not initialised; construct it with NewKeyRing") // NewKeyRing constructs a ring with one key marked active. The // active kid identifies the key used for new Seals. Other kids // can be added with Add. // // kid must be 1..64 bytes. Reasonable choices: "v1", "2026-q1", a // UUID, etc. func NewKeyRing(activeKid string, activeKey []byte) (*KeyRing, error) { if err := validKid(activeKid); err != nil { return nil, err } gcm, err := newRingAEAD(activeKey) if err != nil { return nil, err } r := &KeyRing{} r.state.Store(&keyRingState{ active: activeKid, activeKey: gcm, keys: map[string]cipher.AEAD{activeKid: gcm}, }) return r, nil } // newRingAEAD validates a ring key and builds its AES-256-GCM AEAD. func newRingAEAD(key []byte) (cipher.AEAD, error) { if len(key) != AEADKeySize { return nil, fmt.Errorf("%w: KeyRing requires %d bytes; got %d", ErrInvalidKey, AEADKeySize, len(key)) } block, err := aes.NewCipher(key) if err != nil { return nil, fmt.Errorf("crypt: aes.NewCipher: %w", err) } gcm, err := cipher.NewGCM(block) if err != nil { return nil, fmt.Errorf("crypt: cipher.NewGCM: %w", err) } return gcm, nil } // load returns the current snapshot, or an error for a zero-value // KeyRing. func (r *KeyRing) load() (*keyRingState, error) { s := r.state.Load() if s == nil { return nil, errKeyRingUninitialised } return s, nil } // update runs change on a private copy of the current key map under // the writer mutex and publishes the result. change returns the new // active kid. func (r *KeyRing) update(change func(active string, keys map[string]cipher.AEAD) (string, error)) error { r.mu.Lock() defer r.mu.Unlock() cur, err := r.load() if err != nil { return err } keys := make(map[string]cipher.AEAD, len(cur.keys)+1) for kid, gcm := range cur.keys { keys[kid] = gcm } active, err := change(cur.active, keys) if err != nil { return err } r.state.Store(&keyRingState{active: active, activeKey: keys[active], keys: keys}) return nil } // Add registers an additional key under kid. Used to keep retired // keys readable during a rotation window, or to load the next key // before it is made active. Safe to call while other goroutines use // the ring. func (r *KeyRing) Add(kid string, key []byte) error { if err := validKid(kid); err != nil { return err } gcm, err := newRingAEAD(key) if err != nil { return err } return r.update(func(active string, keys map[string]cipher.AEAD) (string, error) { if _, exists := keys[kid]; exists { return "", fmt.Errorf("crypt: KeyRing already has kid %q", kid) } keys[kid] = gcm return active, nil }) } // Remove drops a kid from the ring. After this, ciphertexts tagged // with that kid become unreadable — call this only after all // ciphertexts have been re-sealed (see [KeyRing.Reseal]). The active // kid cannot be removed. Safe to call while other goroutines use the // ring. func (r *KeyRing) Remove(kid string) error { return r.update(func(active string, keys map[string]cipher.AEAD) (string, error) { if kid == active { return "", fmt.Errorf("crypt: cannot remove active kid %q", kid) } if _, exists := keys[kid]; !exists { return "", fmt.Errorf("crypt: KeyRing has no kid %q", kid) } delete(keys, kid) return active, nil }) } // ActiveKid returns the kid of the currently-active key, or "" for a // zero-value KeyRing. func (r *KeyRing) ActiveKid() string { s := r.state.Load() if s == nil { return "" } return s.active } // SetActive marks an existing kid as active. Seal calls that start // after SetActive returns use the new active key. Old ciphertexts // remain readable. Safe to call while other goroutines use the ring. func (r *KeyRing) SetActive(kid string) error { return r.update(func(_ string, keys map[string]cipher.AEAD) (string, error) { if _, exists := keys[kid]; !exists { return "", fmt.Errorf("crypt: KeyRing has no kid %q", kid) } return kid, nil }) } // Seal encrypts under the active key, tagging the ciphertext with // the active kid. func (r *KeyRing) Seal(plaintext, aad []byte) (string, error) { s, err := r.load() if err != nil { return "", err } raw, err := s.sealRaw(plaintext, aad) if err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(raw), nil } // Open decrypts a ciphertext, dispatching by the embedded kid for v3 // ciphertexts. v1 ciphertexts (no kid) are tried with the active key // first, then with every other key in the ring. func (r *KeyRing) Open(ciphertext string, aad []byte) ([]byte, error) { s, err := r.load() if err != nil { return nil, err } raw, err := base64.RawURLEncoding.DecodeString(ciphertext) if err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidCiphertext, err) } return s.openRaw(raw, aad) } // Reseal opens ciphertext with whichever key in the ring sealed it // and seals the plaintext again under the active key, with the same // associated data. It accepts everything [KeyRing.Open] accepts (v3 // values under any kid in the ring, and v1 values without a kid) and // returns a v3 value tagged with the active kid. // // Use it to move stored values off a retired key before calling // [KeyRing.Remove]. Reseal always produces a fresh ciphertext; to skip // values that are already on the active key, check them first with // [SealedKeyID]: // // kid, err := crypt.SealedKeyID(ct) // if errors.Is(err, crypt.ErrNoKeyID) || (err == nil && kid != ring.ActiveKid()) { // ct, err = ring.Reseal(ct, aad) // } func (r *KeyRing) Reseal(ciphertext string, aad []byte) (string, error) { pt, err := r.Open(ciphertext, aad) if err != nil { return "", err } defer zeroBytes(pt) return r.Seal(pt, aad) } // SealedKeyID returns the kid written in the header of a value sealed // by [KeyRing.Seal], without opening it and without any key. Use it to // find values still sealed with an old key, then move them to the // active key with [KeyRing.Reseal]. // // The header is not authenticated until the value is opened: treat // the kid as a hint about which key to expect, never as proof. // // Errors: // - [ErrInvalidCiphertext] if the value is not base64url or its kid // length is out of range. // - [ErrCiphertextTooShort] if the value is too short for its format. // - [ErrNoKeyID] for a plain AES-256-GCM value (version 0x01, from // [Seal] or [Sealer]): it carries no kid, a KeyRing opens it by // trying every key, and a rotation job should re-seal it. // - [ErrUnsupportedVersion] for every other format (ChaCha20, // asymmetric, envelope, unknown version bytes): a KeyRing cannot // open such a value. func SealedKeyID(ciphertext string) (string, error) { raw, err := base64.RawURLEncoding.DecodeString(ciphertext) if err != nil { return "", fmt.Errorf("%w: %v", ErrInvalidCiphertext, err) } if len(raw) == 0 { return "", ErrCiphertextTooShort } switch raw[0] { case VersionAEADv3: kid, _, err := parseV3Header(raw) return kid, err case VersionAEADv1: if len(raw) < aeadMinSize { return "", ErrCiphertextTooShort } return "", ErrNoKeyID default: return "", fmt.Errorf("%w: 0x%02x is not a key ring format", ErrUnsupportedVersion, raw[0]) } } // sealRaw seals plaintext under the snapshot's active key and returns // the raw (not base64) v3 frame. func (s *keyRingState) sealRaw(plaintext, aad []byte) ([]byte, error) { nonce := make([]byte, aeadNonceSize) if _, err := io.ReadFull(randReader, nonce); err != nil { return nil, fmt.Errorf("crypt: random nonce: %w", err) } out := make([]byte, 0, 1+1+len(s.active)+aeadNonceSize+len(plaintext)+aeadTagSize) out = append(out, VersionAEADv3) out = append(out, byte(len(s.active))) out = append(out, s.active...) out = append(out, nonce...) out = s.activeKey.Seal(out, nonce, plaintext, aad) return out, nil } // openRaw opens a raw v3 frame, or a raw v1 frame by trying every // key in the snapshot (active key first). func (s *keyRingState) openRaw(raw, aad []byte) ([]byte, error) { if len(raw) < aeadMinSize { return nil, ErrCiphertextTooShort } switch raw[0] { case VersionAEADv1: for _, gcm := range s.aeadsActiveFirst() { pt, err := openV1WithAEAD(gcm, raw, aad) if err == nil { return pt, nil } } return nil, fmt.Errorf("%w: no key in ring opens this v1 ciphertext", ErrTampered) case VersionAEADv3: return s.openV3(raw, aad) default: return nil, fmt.Errorf("%w: 0x%02x", ErrUnsupportedVersion, raw[0]) } } // openV3 opens a raw v3 frame with the key its kid names. func (s *keyRingState) openV3(raw, aad []byte) ([]byte, error) { kid, rest, err := parseV3Header(raw) if err != nil { return nil, err } gcm, ok := s.keys[kid] if !ok { return nil, fmt.Errorf("%w: no key for kid %q in ring", ErrTampered, kid) } nonce := rest[:aeadNonceSize] body := rest[aeadNonceSize:] pt, err := gcm.Open(nil, nonce, body, aad) if err != nil { return nil, fmt.Errorf("%w: %v", ErrTampered, err) } return pt, nil } // parseV3Header reads the kid from a raw v3 frame and returns it with // the remaining bytes (nonce, ciphertext and tag). It checks that the // frame is long enough to hold a nonce and a tag after the kid. func parseV3Header(raw []byte) (string, []byte, error) { if len(raw) < 2 { return "", nil, ErrCiphertextTooShort } if raw[0] != VersionAEADv3 { return "", nil, fmt.Errorf("%w: 0x%02x", ErrUnsupportedVersion, raw[0]) } kidLen := int(raw[1]) if kidLen < 1 || kidLen > keyRingMaxKidLen { return "", nil, fmt.Errorf("%w: invalid kid length %d", ErrInvalidCiphertext, kidLen) } if len(raw) < 2+kidLen+aeadNonceSize+aeadTagSize { return "", nil, ErrCiphertextTooShort } return string(raw[2 : 2+kidLen]), raw[2+kidLen:], nil } // aeadsActiveFirst returns the snapshot's AEADs with the active one // first, then the rest in map order. Order doesn't matter for // correctness (try-each-until-success) but checking the active key // first is the common case. func (s *keyRingState) aeadsActiveFirst() []cipher.AEAD { out := make([]cipher.AEAD, 0, len(s.keys)) out = append(out, s.activeKey) for kid, gcm := range s.keys { if kid != s.active { out = append(out, gcm) } } return out } // openV1WithAEAD parses a v1 ciphertext and decrypts with the given // AEAD. Used by KeyRing for v1 fallback. func openV1WithAEAD(gcm cipher.AEAD, raw, aad []byte) ([]byte, error) { if len(raw) < aeadMinSize { return nil, ErrCiphertextTooShort } if raw[0] != VersionAEADv1 { return nil, ErrUnsupportedVersion } nonce := raw[1:aeadHeaderSize] body := raw[aeadHeaderSize:] pt, err := gcm.Open(nil, nonce, body, aad) if err != nil { return nil, err } return pt, nil } // validKid checks that kid is non-empty and within length bounds. // We accept any byte content; ASCII is the convention but not // enforced (UTF-8 emoji-as-kid is technically allowed). func validKid(kid string) error { if len(kid) == 0 { return fmt.Errorf("crypt: kid must be non-empty") } if len(kid) > keyRingMaxKidLen { return fmt.Errorf("crypt: kid length %d exceeds limit %d", len(kid), keyRingMaxKidLen) } return nil } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |