mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 19:17:28 +01:00
A local KMS key's key_material can now be written as ${NAME}, so the key
can come from a Kubernetes Secret, or any secret store that hands it to the
process as an environment variable, instead of sitting in the config file.
This works in the S3 JSON config and in filer.toml.
A reference to a variable that is unset or empty, or one that isn't written
as ${NAME}, fails the load with an error that leaves the reference and the
material out. The expansion is the one static S3 credentials already use,
moved to weed/util so both share it.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
866 lines
26 KiB
Go
866 lines
26 KiB
Go
package local
|
|
|
|
import (
|
|
"context"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/kms"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
// LocalKMSProvider's master keys are listed under "keys" or generated in memory. Generated
|
|
// keys are lost on a reload or restart, along with every data key they wrapped.
|
|
type LocalKMSProvider struct {
|
|
mu sync.RWMutex
|
|
keys map[string]*LocalKey
|
|
defaultKeyID string
|
|
enableOnDemandCreate bool // Whether to create keys on-demand for missing key IDs
|
|
}
|
|
|
|
// LocalKey represents a key stored in the local KMS
|
|
type LocalKey struct {
|
|
KeyID string `json:"keyId"`
|
|
ARN string `json:"arn"`
|
|
Description string `json:"description"`
|
|
KeyMaterial []byte `json:"keyMaterial"` // 256-bit master key
|
|
KeyUsage kms.KeyUsage `json:"keyUsage"`
|
|
KeyState kms.KeyState `json:"keyState"`
|
|
Origin kms.KeyOrigin `json:"origin"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
Aliases []string `json:"aliases"`
|
|
Metadata map[string]string `json:"metadata"`
|
|
}
|
|
|
|
const localARNPrefix = "arn:aws:kms:local:000000000000:"
|
|
|
|
// awsS3KeyAlias names the key a request that names no key gets when keys are configured, as
|
|
// AWS answers those with its aws/s3 managed key.
|
|
const awsS3KeyAlias = "alias/aws/s3"
|
|
|
|
func keyARN(keyID string) string {
|
|
return localARNPrefix + "key/" + keyID
|
|
}
|
|
|
|
func aliasName(alias string) string {
|
|
if strings.HasPrefix(alias, "alias/") {
|
|
return alias
|
|
}
|
|
return "alias/" + alias
|
|
}
|
|
|
|
// keyName returns the name a key or alias ARN is stored under, as AWS KMS accepts either form.
|
|
func keyName(keyIdentifier string) string {
|
|
rest, ok := strings.CutPrefix(keyIdentifier, localARNPrefix)
|
|
if !ok {
|
|
return keyIdentifier
|
|
}
|
|
if keyID, ok := strings.CutPrefix(rest, "key/"); ok {
|
|
return keyID
|
|
}
|
|
if strings.HasPrefix(rest, "alias/") {
|
|
return rest
|
|
}
|
|
return keyIdentifier
|
|
}
|
|
|
|
func newLocalKey(keyID, description string, material []byte, origin kms.KeyOrigin, aliases []string) *LocalKey {
|
|
return &LocalKey{
|
|
KeyID: keyID,
|
|
ARN: keyARN(keyID),
|
|
Description: description,
|
|
KeyMaterial: material,
|
|
KeyUsage: kms.KeyUsageEncryptDecrypt,
|
|
KeyState: kms.KeyStateEnabled,
|
|
Origin: origin,
|
|
CreatedAt: time.Now(),
|
|
Aliases: aliases,
|
|
Metadata: make(map[string]string),
|
|
}
|
|
}
|
|
|
|
func randomKeyMaterial() ([]byte, error) {
|
|
material := make([]byte, 32)
|
|
if _, err := io.ReadFull(rand.Reader, material); err != nil {
|
|
return nil, fmt.Errorf("failed to generate key material: %w", err)
|
|
}
|
|
return material, nil
|
|
}
|
|
|
|
// util.Configuration has no getter for a list of tables, so the keys are read through Get,
|
|
// which the manager's adapter and Viper both have.
|
|
type configGetter interface {
|
|
Get(key string) interface{}
|
|
}
|
|
|
|
func init() {
|
|
// Register the local KMS provider
|
|
kms.RegisterProvider("local", NewLocalKMSProvider)
|
|
}
|
|
|
|
// NewLocalKMSProvider creates a new local KMS provider
|
|
func NewLocalKMSProvider(config util.Configuration) (kms.KMSProvider, error) {
|
|
provider := &LocalKMSProvider{
|
|
keys: make(map[string]*LocalKey),
|
|
enableOnDemandCreate: true, // Default to true for development/testing convenience
|
|
}
|
|
|
|
// Load configuration if provided
|
|
if config != nil {
|
|
if err := provider.loadConfig(config); err != nil {
|
|
return nil, fmt.Errorf("failed to load local KMS config: %v", err)
|
|
}
|
|
}
|
|
|
|
// Skipped when keys are configured, or a request naming no key would be wrapped by a
|
|
// key that's gone after a restart.
|
|
if len(provider.keys) == 0 {
|
|
defaultKey, err := provider.createDefaultKey()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create default key: %v", err)
|
|
}
|
|
provider.defaultKeyID = defaultKey.KeyID
|
|
glog.V(1).Infof("Local KMS: Created default key %s", defaultKey.KeyID)
|
|
}
|
|
|
|
return provider, nil
|
|
}
|
|
|
|
// loadConfig loads configuration from the provided config
|
|
func (p *LocalKMSProvider) loadConfig(config util.Configuration) (err error) {
|
|
if config == nil {
|
|
return nil
|
|
}
|
|
// The provider is dropped on error, so clear the keys loaded before it.
|
|
defer func() {
|
|
if err != nil {
|
|
p.Close()
|
|
}
|
|
}()
|
|
|
|
p.enableOnDemandCreate = config.GetBool("enableOnDemandCreate")
|
|
|
|
getter, ok := config.(configGetter)
|
|
if !ok {
|
|
return fmt.Errorf("can't read keys from a %T configuration", config)
|
|
}
|
|
configured, err := p.loadKeys(getter.Get("keys"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if configured > 0 && p.enableOnDemandCreate {
|
|
return fmt.Errorf("enableOnDemandCreate can't be combined with keys: a mistyped key ID would get a key that's lost on restart, with every object it encrypted")
|
|
}
|
|
|
|
if configured > 0 && p.keys[awsS3KeyAlias] == nil {
|
|
glog.Warningf("Local KMS: no configured key has the alias aws/s3, so requests that name no key fail, including S3 writes to a bucket whose default encryption names no key")
|
|
}
|
|
|
|
glog.V(2).Infof("Local KMS: %d configured keys, enableOnDemandCreate = %v", configured, p.enableOnDemandCreate)
|
|
return nil
|
|
}
|
|
|
|
// The keys are a list rather than a map keyed by ID because Viper lowercases map keys, which
|
|
// would change the IDs read from TOML and orphan every data key wrapped under the original ones.
|
|
func (p *LocalKMSProvider) loadKeys(raw interface{}) (int, error) {
|
|
var entries []map[string]interface{}
|
|
switch v := raw.(type) {
|
|
case nil:
|
|
return 0, nil
|
|
case []map[string]interface{}:
|
|
entries = v
|
|
case []interface{}:
|
|
for i, entry := range v {
|
|
fields, ok := entry.(map[string]interface{})
|
|
if !ok {
|
|
return 0, fmt.Errorf("keys[%d]: expected a table, got %T", i, entry)
|
|
}
|
|
entries = append(entries, fields)
|
|
}
|
|
default:
|
|
return 0, fmt.Errorf("keys: expected a list, got %T", raw)
|
|
}
|
|
if len(entries) == 0 {
|
|
return 0, fmt.Errorf("keys is empty")
|
|
}
|
|
|
|
for i, fields := range entries {
|
|
key, err := configuredKey(fields)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("keys[%d]: %w", i, err)
|
|
}
|
|
if err := p.registerKey(key); err != nil {
|
|
return 0, fmt.Errorf("keys[%d]: %w", i, err)
|
|
}
|
|
}
|
|
return len(entries), nil
|
|
}
|
|
|
|
// The errors leave the key_id out, as the caller names the entry by its index: fields
|
|
// swapped by mistake put the key material in key_id.
|
|
func configuredKey(fields map[string]interface{}) (*LocalKey, error) {
|
|
keyID, err := stringField(fields, "key_id")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if keyID == "" {
|
|
return nil, fmt.Errorf("key_id is required")
|
|
}
|
|
if keyID, err = keyIDName("key_id", keyID); err != nil {
|
|
return nil, err
|
|
}
|
|
aliases, err := stringList(fields["aliases"])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("aliases: %w", err)
|
|
}
|
|
if aliases, err = aliasNames(aliases); err != nil {
|
|
return nil, err
|
|
}
|
|
description, err := stringField(fields, "description")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
material, err := stringField(fields, "key_material")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
material, resolved := util.ExpandEnvRefs(material)
|
|
if !resolved {
|
|
return nil, fmt.Errorf("key_material names an environment variable that is unset or empty, or isn't written as ${NAME}")
|
|
}
|
|
keyMaterial, err := decodeKeyMaterial(material)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return newLocalKey(keyID, description, keyMaterial, kms.KeyOriginExternal, aliases), nil
|
|
}
|
|
|
|
func aliasNames(aliases []string) ([]string, error) {
|
|
names := make([]string, len(aliases))
|
|
for i, alias := range aliases {
|
|
if strings.HasPrefix(alias, localARNPrefix+"key/") {
|
|
return nil, fmt.Errorf("aliases[%d] is a key ARN, not an alias", i)
|
|
}
|
|
names[i] = aliasName(keyName(alias))
|
|
if err := checkName(fmt.Sprintf("aliases[%d]", i), strings.TrimPrefix(names[i], "alias/")); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return names, nil
|
|
}
|
|
|
|
func keyIDName(field, keyID string) (string, error) {
|
|
keyID = keyName(keyID)
|
|
if err := checkName(field, keyID); err != nil {
|
|
return "", err
|
|
}
|
|
if strings.HasPrefix(keyID, "alias/") {
|
|
return "", fmt.Errorf("%s is an alias, not a key ID", field)
|
|
}
|
|
if keyName(keyID) != keyID {
|
|
return "", fmt.Errorf("%s is an ARN inside an ARN", field)
|
|
}
|
|
return keyID, nil
|
|
}
|
|
|
|
// checkName refuses a blank name or one with spaces around it. A templating slip produces
|
|
// these, and only a request carrying the same spaces would ever match them.
|
|
func checkName(field, name string) error {
|
|
switch trimmed := strings.TrimSpace(name); {
|
|
case trimmed == "":
|
|
return fmt.Errorf("%s is empty", field)
|
|
case trimmed != name:
|
|
return fmt.Errorf("%s has spaces around it", field)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func stringField(fields map[string]interface{}, name string) (string, error) {
|
|
return stringValue(name, fields[name])
|
|
}
|
|
|
|
func stringValue(name string, value interface{}) (string, error) {
|
|
switch v := value.(type) {
|
|
case nil:
|
|
return "", nil
|
|
case string:
|
|
return v, nil
|
|
default:
|
|
return "", fmt.Errorf("%s must be a string, got %T", name, v)
|
|
}
|
|
}
|
|
|
|
// decodeKeyMaterial reads 64 hex characters or standard base64, which takes 44 for 32 bytes,
|
|
// so the two can't be confused. Spaces around it, like a Secret file's trailing newline, are
|
|
// dropped. Errors leave the material out.
|
|
func decodeKeyMaterial(s string) ([]byte, error) {
|
|
s = strings.TrimSpace(s)
|
|
if s == "" {
|
|
return nil, fmt.Errorf("key_material is required")
|
|
}
|
|
if len(s) == hex.EncodedLen(32) {
|
|
b, err := hex.DecodeString(s)
|
|
if err != nil {
|
|
kms.ClearSensitiveData(b)
|
|
return nil, fmt.Errorf("key_material of 64 characters must be hex")
|
|
}
|
|
return b, nil
|
|
}
|
|
b, err := base64.StdEncoding.DecodeString(s)
|
|
if err != nil {
|
|
kms.ClearSensitiveData(b)
|
|
return nil, fmt.Errorf("key_material must be 64 hex characters or standard base64")
|
|
}
|
|
if len(b) != 32 {
|
|
kms.ClearSensitiveData(b)
|
|
return nil, fmt.Errorf("key_material must be 32 bytes, got %d", len(b))
|
|
}
|
|
return b, nil
|
|
}
|
|
|
|
func stringList(raw interface{}) ([]string, error) {
|
|
switch v := raw.(type) {
|
|
case nil:
|
|
return nil, nil
|
|
case []string:
|
|
return append([]string(nil), v...), nil
|
|
case []interface{}:
|
|
list := make([]string, 0, len(v))
|
|
for _, item := range v {
|
|
s, ok := item.(string)
|
|
if !ok {
|
|
return nil, fmt.Errorf("expected strings, got %T", item)
|
|
}
|
|
list = append(list, s)
|
|
}
|
|
return list, nil
|
|
default:
|
|
return nil, fmt.Errorf("expected a list, got %T", raw)
|
|
}
|
|
}
|
|
|
|
// registerKey refuses a name that's already taken, so a typo can't point an alias at another
|
|
// key. A refused key has its material cleared.
|
|
func (p *LocalKMSProvider) registerKey(key *LocalKey) error {
|
|
names := append([]string{key.KeyID}, key.Aliases...)
|
|
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
|
|
seen := make(map[string]bool, len(names))
|
|
for i, name := range names {
|
|
if p.keys[name] != nil || seen[name] {
|
|
kms.ClearSensitiveData(key.KeyMaterial)
|
|
if i == 0 {
|
|
return fmt.Errorf("key_id is already taken")
|
|
}
|
|
return fmt.Errorf("aliases[%d] is already taken", i-1)
|
|
}
|
|
seen[name] = true
|
|
}
|
|
for _, name := range names {
|
|
p.keys[name] = key
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// createDefaultKey creates a default master key for the local KMS
|
|
func (p *LocalKMSProvider) createDefaultKey() (*LocalKey, error) {
|
|
keyID, err := generateKeyID()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate key ID: %w", err)
|
|
}
|
|
keyMaterial, err := randomKeyMaterial()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
key := newLocalKey(keyID, "Default local KMS key for SeaweedFS", keyMaterial, kms.KeyOriginLocal, []string{"alias/seaweedfs-default"})
|
|
if err := p.registerKey(key); err != nil {
|
|
return nil, err
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
// GenerateDataKey implements the KMSProvider interface
|
|
func (p *LocalKMSProvider) GenerateDataKey(ctx context.Context, req *kms.GenerateDataKeyRequest) (*kms.GenerateDataKeyResponse, error) {
|
|
if req.KeySpec != kms.KeySpecAES256 {
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeInvalidKeyUsage,
|
|
Message: fmt.Sprintf("Unsupported key spec: %s", req.KeySpec),
|
|
KeyID: req.KeyID,
|
|
}
|
|
}
|
|
|
|
// Resolve the key
|
|
key, err := p.getOrCreateKey(req.KeyID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if key.KeyState != kms.KeyStateEnabled {
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeKeyUnavailable,
|
|
Message: fmt.Sprintf("Key %s is in state %s", key.KeyID, key.KeyState),
|
|
KeyID: key.KeyID,
|
|
}
|
|
}
|
|
|
|
dataKey, err := randomKeyMaterial()
|
|
if err != nil {
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeKMSInternalFailure,
|
|
Message: "Failed to generate data key",
|
|
KeyID: key.KeyID,
|
|
}
|
|
}
|
|
|
|
// Encrypt the data key with the master key
|
|
encryptedDataKey, err := p.encryptDataKey(dataKey, key, req.EncryptionContext)
|
|
if err != nil {
|
|
kms.ClearSensitiveData(dataKey)
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeKMSInternalFailure,
|
|
Message: fmt.Sprintf("Failed to encrypt data key: %v", err),
|
|
KeyID: key.KeyID,
|
|
}
|
|
}
|
|
|
|
return &kms.GenerateDataKeyResponse{
|
|
KeyID: key.KeyID,
|
|
Plaintext: dataKey,
|
|
CiphertextBlob: encryptedDataKey,
|
|
}, nil
|
|
}
|
|
|
|
// Decrypt implements the KMSProvider interface
|
|
func (p *LocalKMSProvider) Decrypt(ctx context.Context, req *kms.DecryptRequest) (*kms.DecryptResponse, error) {
|
|
// Parse the encrypted data key to extract metadata
|
|
metadata, err := p.parseEncryptedDataKey(req.CiphertextBlob)
|
|
if err != nil {
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeInvalidCiphertext,
|
|
Message: fmt.Sprintf("Invalid ciphertext format: %v", err),
|
|
}
|
|
}
|
|
|
|
// Verify encryption context matches
|
|
if !p.encryptionContextMatches(metadata.EncryptionContext, req.EncryptionContext) {
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeInvalidCiphertext,
|
|
Message: "Encryption context mismatch",
|
|
KeyID: metadata.KeyID,
|
|
}
|
|
}
|
|
|
|
// Get the master key
|
|
key, err := p.getKey(metadata.KeyID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if key.KeyState != kms.KeyStateEnabled {
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeKeyUnavailable,
|
|
Message: fmt.Sprintf("Key %s is in state %s", key.KeyID, key.KeyState),
|
|
KeyID: key.KeyID,
|
|
}
|
|
}
|
|
|
|
// Decrypt the data key
|
|
dataKey, err := p.decryptDataKey(metadata, key)
|
|
if err != nil {
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeInvalidCiphertext,
|
|
Message: fmt.Sprintf("Failed to decrypt data key: %v", err),
|
|
KeyID: key.KeyID,
|
|
}
|
|
}
|
|
|
|
// A key configured by its ARN once had that ARN as its ID, and callers stored it.
|
|
keyID := key.KeyID
|
|
if keyName(metadata.KeyID) == key.KeyID {
|
|
keyID = metadata.KeyID
|
|
}
|
|
return &kms.DecryptResponse{
|
|
KeyID: keyID,
|
|
Plaintext: dataKey,
|
|
}, nil
|
|
}
|
|
|
|
// DescribeKey implements the KMSProvider interface
|
|
func (p *LocalKMSProvider) DescribeKey(ctx context.Context, req *kms.DescribeKeyRequest) (*kms.DescribeKeyResponse, error) {
|
|
key, err := p.getKey(req.KeyID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &kms.DescribeKeyResponse{
|
|
KeyID: key.KeyID,
|
|
ARN: key.ARN,
|
|
Description: key.Description,
|
|
KeyUsage: key.KeyUsage,
|
|
KeyState: key.KeyState,
|
|
Origin: key.Origin,
|
|
}, nil
|
|
}
|
|
|
|
// GetKeyID implements the KMSProvider interface
|
|
func (p *LocalKMSProvider) GetKeyID(ctx context.Context, keyIdentifier string) (string, error) {
|
|
key, err := p.getKey(keyIdentifier)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return key.KeyID, nil
|
|
}
|
|
|
|
// Close implements the KMSProvider interface
|
|
func (p *LocalKMSProvider) Close() error {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
|
|
// Clear all key material from memory
|
|
for _, key := range p.keys {
|
|
kms.ClearSensitiveData(key.KeyMaterial)
|
|
}
|
|
p.keys = make(map[string]*LocalKey)
|
|
return nil
|
|
}
|
|
|
|
// getKey retrieves a key by ID, alias or ARN.
|
|
func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) {
|
|
name := keyName(keyIdentifier)
|
|
// A key ARN names a key ID, never an alias its ID happens to spell.
|
|
namedKey := func(key *LocalKey) bool {
|
|
return !strings.HasPrefix(keyIdentifier, localARNPrefix+"key/") || key.KeyID == name
|
|
}
|
|
p.mu.RLock()
|
|
|
|
// Try direct lookup first. An ARN with an empty key ID names "", which is no key.
|
|
if key, exists := p.keys[name]; exists && namedKey(key) {
|
|
p.mu.RUnlock()
|
|
return key, nil
|
|
}
|
|
|
|
if keyIdentifier == "" {
|
|
defaultKeyID := p.defaultKeyID
|
|
if defaultKeyID == "" {
|
|
defaultKeyID = awsS3KeyAlias
|
|
}
|
|
if key, exists := p.keys[defaultKeyID]; exists {
|
|
p.mu.RUnlock()
|
|
return key, nil
|
|
}
|
|
}
|
|
|
|
p.mu.RUnlock()
|
|
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeNotFoundException,
|
|
Message: fmt.Sprintf("Key not found: %s", keyIdentifier),
|
|
KeyID: keyIdentifier,
|
|
}
|
|
}
|
|
|
|
// getOrCreateKey is getKey that creates a missing key on demand if enabled. Only new data
|
|
// keys create keys, as no other request can succeed with a key that didn't exist before it.
|
|
func (p *LocalKMSProvider) getOrCreateKey(keyIdentifier string) (*LocalKey, error) {
|
|
key, err := p.getKey(keyIdentifier)
|
|
name := keyName(keyIdentifier)
|
|
// A key ARN spelling an alias names no key, so it can't create one either.
|
|
keyARNOfAlias := strings.HasPrefix(keyIdentifier, localARNPrefix+"key/") && strings.HasPrefix(name, "alias/")
|
|
var kmsErr *kms.KMSError
|
|
if !errors.As(err, &kmsErr) || kmsErr.Code != kms.ErrCodeNotFoundException ||
|
|
!p.enableOnDemandCreate || keyARNOfAlias || !p.isReasonableKeyIdentifier(name) {
|
|
return key, err
|
|
}
|
|
|
|
glog.V(1).Infof("Creating on-demand local KMS key: %s", name)
|
|
key, err = p.createOnDemandKey(name)
|
|
if err != nil {
|
|
return nil, &kms.KMSError{
|
|
Code: kms.ErrCodeKMSInternalFailure,
|
|
Message: fmt.Sprintf("Failed to create on-demand key %s: %v", name, err),
|
|
KeyID: name,
|
|
}
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
// isReasonableKeyIdentifier determines if a key identifier is reasonable for on-demand creation
|
|
func (p *LocalKMSProvider) isReasonableKeyIdentifier(keyIdentifier string) bool {
|
|
// Basic validation: reasonable length and character set
|
|
if len(keyIdentifier) < 3 || len(keyIdentifier) > 100 {
|
|
return false
|
|
}
|
|
|
|
// Allow alphanumeric characters, hyphens, underscores, and forward slashes
|
|
// This covers most reasonable key identifier formats without being overly restrictive
|
|
for _, r := range keyIdentifier {
|
|
if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') ||
|
|
(r >= '0' && r <= '9') || r == '-' || r == '_' || r == '/') {
|
|
return false
|
|
}
|
|
}
|
|
|
|
// Reject keys that start or end with separators
|
|
if keyIdentifier[0] == '-' || keyIdentifier[0] == '_' || keyIdentifier[0] == '/' ||
|
|
keyIdentifier[len(keyIdentifier)-1] == '-' || keyIdentifier[len(keyIdentifier)-1] == '_' || keyIdentifier[len(keyIdentifier)-1] == '/' {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// encryptedDataKeyMetadata represents the metadata stored with encrypted data keys
|
|
type encryptedDataKeyMetadata struct {
|
|
KeyID string `json:"keyId"`
|
|
EncryptionContext map[string]string `json:"encryptionContext"`
|
|
EncryptedData []byte `json:"encryptedData"`
|
|
Nonce []byte `json:"nonce"` // Renamed from IV to be more explicit about AES-GCM usage
|
|
}
|
|
|
|
// masterKeyGCM builds the cipher under the lock Close clears key material with. A reload
|
|
// closes the provider it replaces while requests may still hold its keys, and a cleared key
|
|
// would wrap data keys under zeros that no provider can unwrap.
|
|
func (p *LocalKMSProvider) masterKeyGCM(masterKey *LocalKey) (cipher.AEAD, error) {
|
|
p.mu.RLock()
|
|
defer p.mu.RUnlock()
|
|
if p.keys[masterKey.KeyID] != masterKey {
|
|
return nil, fmt.Errorf("key %s was closed", masterKey.KeyID)
|
|
}
|
|
block, err := aes.NewCipher(masterKey.KeyMaterial)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return cipher.NewGCM(block)
|
|
}
|
|
|
|
// encryptDataKey encrypts a data key using the master key with AES-GCM for authenticated encryption
|
|
func (p *LocalKMSProvider) encryptDataKey(dataKey []byte, masterKey *LocalKey, encryptionContext map[string]string) ([]byte, error) {
|
|
gcm, err := p.masterKeyGCM(masterKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Generate a random nonce
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Prepare additional authenticated data (AAD) from the encryption context
|
|
// Use deterministic marshaling to ensure consistent AAD
|
|
var aad []byte
|
|
if len(encryptionContext) > 0 {
|
|
var err error
|
|
aad, err = marshalEncryptionContextDeterministic(encryptionContext)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal encryption context for AAD: %w", err)
|
|
}
|
|
}
|
|
|
|
// Encrypt using AES-GCM
|
|
encryptedData := gcm.Seal(nil, nonce, dataKey, aad)
|
|
|
|
// Create metadata structure
|
|
metadata := &encryptedDataKeyMetadata{
|
|
KeyID: masterKey.KeyID,
|
|
EncryptionContext: encryptionContext,
|
|
EncryptedData: encryptedData,
|
|
Nonce: nonce,
|
|
}
|
|
|
|
// Serialize metadata to JSON
|
|
return json.Marshal(metadata)
|
|
}
|
|
|
|
// decryptDataKey decrypts a data key using the master key with AES-GCM for authenticated decryption
|
|
func (p *LocalKMSProvider) decryptDataKey(metadata *encryptedDataKeyMetadata, masterKey *LocalKey) ([]byte, error) {
|
|
gcm, err := p.masterKeyGCM(masterKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Prepare additional authenticated data (AAD)
|
|
var aad []byte
|
|
if len(metadata.EncryptionContext) > 0 {
|
|
var err error
|
|
aad, err = marshalEncryptionContextDeterministic(metadata.EncryptionContext)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal encryption context for AAD: %w", err)
|
|
}
|
|
}
|
|
|
|
// Decrypt using AES-GCM
|
|
nonce := metadata.Nonce
|
|
if len(nonce) != gcm.NonceSize() {
|
|
return nil, fmt.Errorf("invalid nonce size: expected %d, got %d", gcm.NonceSize(), len(nonce))
|
|
}
|
|
|
|
dataKey, err := gcm.Open(nil, nonce, metadata.EncryptedData, aad)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to decrypt with GCM: %w", err)
|
|
}
|
|
|
|
return dataKey, nil
|
|
}
|
|
|
|
// parseEncryptedDataKey parses the encrypted data key blob
|
|
func (p *LocalKMSProvider) parseEncryptedDataKey(ciphertextBlob []byte) (*encryptedDataKeyMetadata, error) {
|
|
var metadata encryptedDataKeyMetadata
|
|
if err := json.Unmarshal(ciphertextBlob, &metadata); err != nil {
|
|
return nil, fmt.Errorf("failed to parse ciphertext blob: %v", err)
|
|
}
|
|
return &metadata, nil
|
|
}
|
|
|
|
// encryptionContextMatches checks if two encryption contexts match
|
|
func (p *LocalKMSProvider) encryptionContextMatches(ctx1, ctx2 map[string]string) bool {
|
|
if len(ctx1) != len(ctx2) {
|
|
return false
|
|
}
|
|
for k, v := range ctx1 {
|
|
if ctx2[k] != v {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// generateKeyID generates a random key ID
|
|
func generateKeyID() (string, error) {
|
|
// Generate a UUID-like key ID
|
|
b := make([]byte, 16)
|
|
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
|
return "", fmt.Errorf("failed to generate random bytes for key ID: %w", err)
|
|
}
|
|
|
|
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
|
|
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
|
}
|
|
|
|
// CreateKey creates a new key in the local KMS (for testing)
|
|
func (p *LocalKMSProvider) CreateKey(description string, aliases []string) (*LocalKey, error) {
|
|
keyID, err := generateKeyID()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate key ID: %w", err)
|
|
}
|
|
names, err := aliasNames(aliases)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
keyMaterial, err := randomKeyMaterial()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return p.addKey(newLocalKey(keyID, description, keyMaterial, kms.KeyOriginLocal, names))
|
|
}
|
|
|
|
// CreateKeyWithID creates a key with a specific keyID, refusing one that's already taken.
|
|
func (p *LocalKMSProvider) CreateKeyWithID(keyID, description string) (*LocalKey, error) {
|
|
keyID, err := keyIDName("keyID", keyID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
keyMaterial, err := randomKeyMaterial()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return p.addKey(newLocalKey(keyID, description, keyMaterial, kms.KeyOriginLocal, []string{}))
|
|
}
|
|
|
|
func (p *LocalKMSProvider) addKey(key *LocalKey) (*LocalKey, error) {
|
|
if err := p.registerKey(key); err != nil {
|
|
return nil, err
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
// createOnDemandKey creates a key for a name no key has yet. An alias gets a key with a
|
|
// generated ID, as it would in AWS, rather than one whose ID is the alias.
|
|
func (p *LocalKMSProvider) createOnDemandKey(name string) (*LocalKey, error) {
|
|
keyID, aliases := name, []string{}
|
|
if strings.HasPrefix(name, "alias/") {
|
|
var err error
|
|
if keyID, err = generateKeyID(); err != nil {
|
|
return nil, err
|
|
}
|
|
aliases = []string{name}
|
|
}
|
|
keyMaterial, err := randomKeyMaterial()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return p.storeKey(name, newLocalKey(keyID, fmt.Sprintf("Auto-created local KMS key: %s", name), keyMaterial, kms.KeyOriginLocal, aliases))
|
|
}
|
|
|
|
// storeKey returns the key already stored under name rather than replacing it, as two
|
|
// on-demand requests for a new name can race and the first may have wrapped a data key
|
|
// already.
|
|
func (p *LocalKMSProvider) storeKey(name string, key *LocalKey) (*LocalKey, error) {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
|
|
if existing := p.keys[name]; existing != nil {
|
|
kms.ClearSensitiveData(key.KeyMaterial)
|
|
return existing, nil
|
|
}
|
|
for _, n := range append([]string{key.KeyID}, key.Aliases...) {
|
|
p.keys[n] = key
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
// marshalEncryptionContextDeterministic creates a deterministic byte representation of encryption context
|
|
// This ensures that the same encryption context always produces the same AAD for AES-GCM
|
|
func marshalEncryptionContextDeterministic(encryptionContext map[string]string) ([]byte, error) {
|
|
if len(encryptionContext) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
// Sort keys to ensure deterministic output
|
|
keys := make([]string, 0, len(encryptionContext))
|
|
for k := range encryptionContext {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
|
|
// Build deterministic representation with proper JSON escaping
|
|
var buf strings.Builder
|
|
buf.WriteString("{")
|
|
for i, k := range keys {
|
|
if i > 0 {
|
|
buf.WriteString(",")
|
|
}
|
|
// Marshal key and value to get proper JSON string escaping
|
|
keyBytes, err := json.Marshal(k)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal encryption context key '%s': %w", k, err)
|
|
}
|
|
valueBytes, err := json.Marshal(encryptionContext[k])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal encryption context value for key '%s': %w", k, err)
|
|
}
|
|
buf.Write(keyBytes)
|
|
buf.WriteString(":")
|
|
buf.Write(valueBytes)
|
|
}
|
|
buf.WriteString("}")
|
|
|
|
return []byte(buf.String()), nil
|
|
}
|