Migration files restructured with shared helpers; verified byte-identical SQLite schema vs previous commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Lx9FNLG2CqeBbVGGd9bFsP
225 lines
5.9 KiB
Go
225 lines
5.9 KiB
Go
// Package secrets encrypts credential fields at rest with AES-256-GCM. Keys
|
|
// live in a file outside the data dir, newest first, so old ciphertext stays
|
|
// readable while it is re-encrypted after a rotation.
|
|
package secrets
|
|
|
|
import (
|
|
"bufio"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
const keyLen = 32
|
|
|
|
var (
|
|
// ErrUnknownKeyVersion means the ciphertext was sealed with a key not in the file.
|
|
ErrUnknownKeyVersion = errors.New("secrets: unknown key version")
|
|
// ErrDecrypt means authentication failed: wrong key, wrong aad or tampered data.
|
|
ErrDecrypt = errors.New("secrets: decrypt failed")
|
|
)
|
|
|
|
type keyEntry struct {
|
|
version int
|
|
key []byte
|
|
}
|
|
|
|
// Keyring holds the current key and any previous keys.
|
|
type Keyring struct {
|
|
current keyEntry
|
|
byVer map[int]cipher.AEAD
|
|
}
|
|
|
|
// GenerateKeyFile creates path (mode 0600) holding one new key as version 1.
|
|
// It never overwrites an existing file.
|
|
func GenerateKeyFile(path string) error {
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
|
return err
|
|
}
|
|
k, err := newKey()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := f.WriteString(formatLine(entry(1, k))); err != nil {
|
|
// Best effort: the write error is the one worth reporting.
|
|
_ = f.Close()
|
|
_ = os.Remove(path)
|
|
return err
|
|
}
|
|
return f.Close()
|
|
}
|
|
|
|
// Rotate prepends a new current key to path and keeps the old ones. It returns
|
|
// the new key's version.
|
|
func Rotate(path string) (int, error) {
|
|
entries, err := readEntries(path)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
k, err := newKey()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
e := entry(entries[0].version+1, k)
|
|
var b strings.Builder
|
|
b.WriteString(formatLine(e))
|
|
for _, old := range entries {
|
|
b.WriteString(formatLine(old))
|
|
}
|
|
tmp, err := os.CreateTemp(filepath.Dir(path), ".nmon-key-*")
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer func() { _ = os.Remove(tmp.Name()) }() // no-op after a successful rename
|
|
if err := tmp.Chmod(0o600); err != nil {
|
|
_ = tmp.Close()
|
|
return 0, err
|
|
}
|
|
if _, err := tmp.WriteString(b.String()); err != nil {
|
|
_ = tmp.Close()
|
|
return 0, err
|
|
}
|
|
if err := tmp.Close(); err != nil {
|
|
return 0, err
|
|
}
|
|
if err := os.Rename(tmp.Name(), path); err != nil {
|
|
return 0, err
|
|
}
|
|
return e.version, nil
|
|
}
|
|
|
|
// LoadKeyring reads the key file. It refuses a file readable by group or others.
|
|
func LoadKeyring(path string) (*Keyring, error) {
|
|
entries, err := readEntries(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
kr := &Keyring{current: entries[0], byVer: make(map[int]cipher.AEAD, len(entries))}
|
|
for _, e := range entries {
|
|
block, err := aes.NewCipher(e.key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
kr.byVer[e.version] = gcm
|
|
}
|
|
return kr, nil
|
|
}
|
|
|
|
// CurrentVersion is the version new data is encrypted with.
|
|
func (k *Keyring) CurrentVersion() int { return k.current.version }
|
|
|
|
// Encrypt seals plaintext with the current key, binding it to aad. The result
|
|
// is nonce || sealed. Empty plaintext encrypts to empty, meaning "not set".
|
|
func (k *Keyring) Encrypt(plaintext []byte, aad string) ([]byte, int, error) {
|
|
if len(plaintext) == 0 {
|
|
return nil, k.current.version, nil
|
|
}
|
|
gcm := k.byVer[k.current.version]
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := rand.Read(nonce); err != nil {
|
|
return nil, 0, err
|
|
}
|
|
return gcm.Seal(nonce, nonce, plaintext, []byte(aad)), k.current.version, nil
|
|
}
|
|
|
|
// Decrypt reverses Encrypt for the key version recorded with the ciphertext.
|
|
func (k *Keyring) Decrypt(ciphertext []byte, keyVersion int, aad string) ([]byte, error) {
|
|
if len(ciphertext) == 0 {
|
|
return nil, nil
|
|
}
|
|
gcm, ok := k.byVer[keyVersion]
|
|
if !ok {
|
|
return nil, fmt.Errorf("%w: v%d", ErrUnknownKeyVersion, keyVersion)
|
|
}
|
|
n := gcm.NonceSize()
|
|
if len(ciphertext) < n+gcm.Overhead() {
|
|
return nil, ErrDecrypt
|
|
}
|
|
pt, err := gcm.Open(nil, ciphertext[:n], ciphertext[n:], []byte(aad))
|
|
if err != nil {
|
|
return nil, ErrDecrypt
|
|
}
|
|
return pt, nil
|
|
}
|
|
|
|
func newKey() ([]byte, error) {
|
|
k := make([]byte, keyLen)
|
|
_, err := rand.Read(k)
|
|
return k, err
|
|
}
|
|
|
|
func entry(v int, k []byte) keyEntry { return keyEntry{version: v, key: k} }
|
|
|
|
func formatLine(e keyEntry) string {
|
|
return fmt.Sprintf("v%d %s\n", e.version, base64.StdEncoding.EncodeToString(e.key))
|
|
}
|
|
|
|
func readEntries(path string) ([]keyEntry, error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = f.Close() }() // read-only handle
|
|
st, err := f.Stat()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if st.Mode().Perm()&0o077 != 0 {
|
|
return nil, fmt.Errorf("secrets: key file %s has mode %04o; must not be group- or world-accessible", path, st.Mode().Perm())
|
|
}
|
|
var out []keyEntry
|
|
seen := map[int]bool{}
|
|
sc := bufio.NewScanner(f)
|
|
for n := 1; sc.Scan(); n++ {
|
|
line := strings.TrimSpace(sc.Text())
|
|
if line == "" || strings.HasPrefix(line, "#") {
|
|
continue
|
|
}
|
|
e, err := parseKeyLine(line, path, n, seen)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
seen[e.version] = true
|
|
out = append(out, e)
|
|
}
|
|
if err := sc.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(out) == 0 {
|
|
return nil, fmt.Errorf("secrets: %s has no keys", path)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// parseKeyLine decodes one "v<N> <base64 key>" line; seen holds versions already read.
|
|
func parseKeyLine(line, path string, n int, seen map[int]bool) (keyEntry, error) {
|
|
ver, enc, ok := strings.Cut(line, " ")
|
|
if !ok || !strings.HasPrefix(ver, "v") {
|
|
return keyEntry{}, fmt.Errorf("secrets: %s:%d: want \"v<N> <base64 key>\"", path, n)
|
|
}
|
|
v, err := strconv.Atoi(ver[1:])
|
|
if err != nil || v < 1 || seen[v] {
|
|
return keyEntry{}, fmt.Errorf("secrets: %s:%d: bad or duplicate version %q", path, n, ver)
|
|
}
|
|
key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(enc))
|
|
if err != nil || len(key) != keyLen {
|
|
return keyEntry{}, fmt.Errorf("secrets: %s:%d: key must be %d bytes of base64", path, n, keyLen)
|
|
}
|
|
return entry(v, key), nil
|
|
}
|