Go server (API, embedded web UI, CLI) backed by PostgreSQL with AES-GCM sealed BMC secrets; Debian live commissioning agent and live-build recipe; Proxmox lab with pve-vbmc virtual BMCs; Gitea workflows for CI, releases and deployment; project website. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
75 lines
1.8 KiB
Go
75 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
// Sealer encrypts BMC secrets at rest with AES-256-GCM.
|
|
type Sealer struct{ aead cipher.AEAD }
|
|
|
|
// loadOrCreateKey reads a 32-byte hex key from path, creating it (0600) when absent.
|
|
func loadOrCreateKey(path string) (*Sealer, error) {
|
|
b, err := os.ReadFile(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
raw := make([]byte, 32)
|
|
if _, err := rand.Read(raw); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := os.WriteFile(path, []byte(hex.EncodeToString(raw)+"\n"), 0o600); err != nil {
|
|
return nil, fmt.Errorf("create master key: %w", err)
|
|
}
|
|
b = []byte(hex.EncodeToString(raw))
|
|
} else if err != nil {
|
|
return nil, err
|
|
}
|
|
key, err := hex.DecodeString(strings.TrimSpace(string(b)))
|
|
if err != nil || len(key) != 32 {
|
|
return nil, fmt.Errorf("%s: expected 32-byte hex key", path)
|
|
}
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
aead, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Sealer{aead: aead}, nil
|
|
}
|
|
|
|
// Seal returns nonce||ciphertext; aad binds the secret to a machine id.
|
|
func (s *Sealer) Seal(plaintext, aad string) ([]byte, error) {
|
|
nonce := make([]byte, s.aead.NonceSize())
|
|
if _, err := rand.Read(nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
return append(nonce, s.aead.Seal(nil, nonce, []byte(plaintext), []byte(aad))...), nil
|
|
}
|
|
|
|
func (s *Sealer) Open(blob []byte, aad string) (string, error) {
|
|
n := s.aead.NonceSize()
|
|
if len(blob) < n {
|
|
return "", errors.New("ciphertext too short")
|
|
}
|
|
pt, err := s.aead.Open(nil, blob[:n], blob[n:], []byte(aad))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(pt), nil
|
|
}
|
|
|
|
func randomToken(nbytes int) string {
|
|
b := make([]byte, nbytes)
|
|
if _, err := rand.Read(b); err != nil {
|
|
panic(err)
|
|
}
|
|
return hex.EncodeToString(b)
|
|
}
|