keysutil

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2024 License: MPL-2.0 Imports: 44 Imported by: 10

Documentation

Index

Constants

View Source
const (
	// DefaultCacheSize is used if no cache size is specified for
	// NewEncryptedKeyStorage. This value is the number of cache entries to
	// store, not the size in bytes of the cache.
	DefaultCacheSize = 16 * 1024

	// DefaultPrefix is used if no prefix is specified for
	// NewEncryptedKeyStorage. Prefix must be defined so we can provide context
	// for the base folder.
	DefaultPrefix = "encryptedkeys/"

	// EncryptedKeyPolicyVersionTpl is a template that can be used to minimize
	// the amount of data that's stored with the ciphertext.
	EncryptedKeyPolicyVersionTpl = "{{version}}:"
)
View Source
const (
	Kdf_hmac_sha256_counter = iota // built-in helper
	Kdf_hkdf_sha256                // golang.org/x/crypto/hkdf

	HmacMinKeySize = 256 / 8
	HmacMaxKeySize = 4096 / 8
)

Careful with iota; don't put anything before it in this const block because we need the default of zero to be the old-style KDF

View Source
const (
	KeyType_AES256_GCM96 = iota
	KeyType_ECDSA_P256
	KeyType_ED25519
	KeyType_RSA2048
	KeyType_RSA4096
	KeyType_ChaCha20_Poly1305
	KeyType_ECDSA_P384
	KeyType_ECDSA_P521
	KeyType_AES128_GCM96
	KeyType_RSA3072
	KeyType_MANAGED_KEY
	KeyType_HMAC
)

Or this one...we need the default of zero to be the original AES256-GCM96

View Source
const (
	// ErrTooOld is returned whtn the ciphertext or signatures's key version is
	// too old.
	ErrTooOld = "ciphertext or signature version is disallowed by policy (too old)"

	// DefaultVersionTemplate is used when no version template is provided.
	DefaultVersionTemplate = "vault:v{{version}}:"
)

Variables

View Source
var (
	// ErrPolicyDerivedKeys is returned if the provided policy does not use
	// derived keys. This is a requirement for this storage implementation.
	ErrPolicyDerivedKeys = errors.New("key policy must use derived keys")

	// ErrPolicyConvergentEncryption is returned if the provided policy does not use
	// convergent encryption. This is a requirement for this storage implementation.
	ErrPolicyConvergentEncryption = errors.New("key policy must use convergent encryption")

	// ErrPolicyConvergentVersion is returned if the provided policy does not use
	// a new enough convergent version. This is a requirement for this storage
	// implementation.
	ErrPolicyConvergentVersion = errors.New("key policy must use convergent version > 2")

	// ErrNilStorage is returned if the provided storage is nil.
	ErrNilStorage = errors.New("nil storage provided")

	// ErrNilPolicy is returned if the provided policy is nil.
	ErrNilPolicy = errors.New("nil policy provided")
)

Functions

func ParsePKCS8Ed25519PrivateKey added in v0.5.1

func ParsePKCS8Ed25519PrivateKey(der []byte) (key interface{}, err error)

ParsePKCS8Ed25519PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.

It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, or a ed25519.PrivateKey. More types might be supported in the future.

This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".

func ParsePKCS8RSAPSSPrivateKey added in v0.9.0

func ParsePKCS8RSAPSSPrivateKey(der []byte) (key interface{}, err error)

ParsePKCS8RSAPSSPrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.

This helper only supports RSA/PSS keys (with OID 1.2.840.113549.1.1.10).

It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, or a ed25519.PrivateKey. More types might be supported in the future.

This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".

Types

type AEADFactory added in v0.6.0

type AEADFactory interface {
	GetAEAD(iv []byte) (cipher.AEAD, error)
}

type AssociatedDataFactory added in v0.6.1

type AssociatedDataFactory interface {
	GetAssociatedData() ([]byte, error)
}

type BackupInfo

type BackupInfo struct {
	Time    time.Time `json:"time"`
	Version int       `json:"version"`
}

type Cache added in v0.1.12

type Cache interface {
	Delete(key interface{})
	Load(key interface{}) (value interface{}, ok bool)
	Store(key, value interface{})
	Size() int
}

type EncryptedKeyStorageConfig

type EncryptedKeyStorageConfig struct {
	// Policy is the key policy to use to encrypt the key paths.
	Policy *Policy

	// Prefix is the storage prefix for this instance of the EncryptedKeyStorage
	// object. This is stored in plaintext. If not set the DefaultPrefix will be
	// used.
	Prefix string

	// CacheSize is the number of elements to cache. If not set the
	// DetaultCacheSize will be used.
	CacheSize int
}

EncryptedKeyStorageConfig is used to configure an EncryptedKeyStorage object.

type EncryptedKeyStorageWrapper

type EncryptedKeyStorageWrapper struct {
	// contains filtered or unexported fields
}

func NewEncryptedKeyStorageWrapper

func NewEncryptedKeyStorageWrapper(config EncryptedKeyStorageConfig) (*EncryptedKeyStorageWrapper, error)

NewEncryptedKeyStorageWrapper takes an EncryptedKeyStorageConfig and returns a new EncryptedKeyStorage object.

func (*EncryptedKeyStorageWrapper) Wrap

type HashType

type HashType uint32
const (
	HashTypeNone HashType = iota
	HashTypeSHA1
	HashTypeSHA2224
	HashTypeSHA2256
	HashTypeSHA2384
	HashTypeSHA2512
	HashTypeSHA3224
	HashTypeSHA3256
	HashTypeSHA3384
	HashTypeSHA3512
)

type KeyData

type KeyData struct {
	Policy       *Policy       `json:"policy"`
	ArchivedKeys *archivedKeys `json:"archived_keys"`
}

type KeyEntry

type KeyEntry struct {
	// AES or some other kind that is a pure byte slice like ED25519
	Key []byte `json:"key"`

	// Key used for HMAC functions
	HMACKey []byte `json:"hmac_key"`

	// Time of creation
	CreationTime time.Time `json:"time"`

	EC_X *big.Int `json:"ec_x"`
	EC_Y *big.Int `json:"ec_y"`
	EC_D *big.Int `json:"ec_d"`

	RSAKey       *rsa.PrivateKey `json:"rsa_key"`
	RSAPublicKey *rsa.PublicKey  `json:"rsa_public_key"`

	// The public key in an appropriate format for the type of key
	FormattedPublicKey string `json:"public_key"`

	// If convergent is enabled, the version (falling back to what's in the
	// policy)
	ConvergentVersion int `json:"convergent_version"`

	// This is deprecated (but still filled) in favor of the value above which
	// is more precise
	DeprecatedCreationTime int64 `json:"creation_time"`

	ManagedKeyUUID string `json:"managed_key_id,omitempty"`

	// Key entry certificate chain. If set, leaf certificate key matches the
	// KeyEntry key
	CertificateChain [][]byte `json:"certificate_chain"`
}

KeyEntry stores the key and metadata

func (*KeyEntry) IsPrivateKeyMissing added in v0.9.1

func (ke *KeyEntry) IsPrivateKeyMissing() bool

func (*KeyEntry) WrapKey added in v0.9.2

func (ke *KeyEntry) WrapKey(targetKey interface{}, targetKeyType KeyType, hash hash.Hash) (string, error)

type KeyType

type KeyType int

func (KeyType) AssociatedDataSupported added in v0.6.1

func (kt KeyType) AssociatedDataSupported() bool

func (KeyType) DecryptionSupported

func (kt KeyType) DecryptionSupported() bool

func (KeyType) DerivationSupported

func (kt KeyType) DerivationSupported() bool

func (KeyType) EncryptionSupported

func (kt KeyType) EncryptionSupported() bool

func (KeyType) HashSignatureInput

func (kt KeyType) HashSignatureInput() bool

func (KeyType) ImportPublicKeySupported added in v0.9.1

func (kt KeyType) ImportPublicKeySupported() bool

func (KeyType) SigningSupported

func (kt KeyType) SigningSupported() bool

func (KeyType) String

func (kt KeyType) String() string

type LockManager

type LockManager struct {
	// contains filtered or unexported fields
}

func NewLockManager

func NewLockManager(useCache bool, cacheSize int) (*LockManager, error)

func (*LockManager) BackupPolicy

func (lm *LockManager) BackupPolicy(ctx context.Context, storage logical.Storage, name string) (string, error)

func (*LockManager) DeletePolicy

func (lm *LockManager) DeletePolicy(ctx context.Context, storage logical.Storage, name string) error

func (*LockManager) GetCacheSize added in v0.1.12

func (lm *LockManager) GetCacheSize() int

func (*LockManager) GetPolicy

func (lm *LockManager) GetPolicy(ctx context.Context, req PolicyRequest, rand io.Reader) (retP *Policy, retUpserted bool, retErr error)

When the function returns, if caching was disabled, the Policy's lock must be unlocked when the caller is done (and it should not be re-locked).

func (*LockManager) GetUseCache added in v0.1.12

func (lm *LockManager) GetUseCache() bool

func (*LockManager) ImportPolicy added in v0.5.0

func (lm *LockManager) ImportPolicy(ctx context.Context, req PolicyRequest, key []byte, rand io.Reader) error

func (*LockManager) InitCache added in v0.3.0

func (lm *LockManager) InitCache(cacheSize int) error

func (*LockManager) InvalidatePolicy

func (lm *LockManager) InvalidatePolicy(name string)

func (*LockManager) RestorePolicy

func (lm *LockManager) RestorePolicy(ctx context.Context, storage logical.Storage, name, backup string, force bool) error

RestorePolicy acquires an exclusive lock on the policy name and restores the given policy along with the archive.

type ManagedKeyFactory added in v0.8.0

type ManagedKeyFactory interface {
	GetManagedKeyParameters() ManagedKeyParameters
}

type ManagedKeyParameters added in v0.8.0

type ManagedKeyParameters struct {
	ManagedKeySystemView logical.ManagedKeySystemView
	BackendUUID          string
	Context              context.Context
}

type MarshalingType

type MarshalingType uint32
const (
	MarshalingTypeASN1 MarshalingType = iota
	MarshalingTypeJWS
)

type Policy

type Policy struct {
	Name    string      `json:"name"`
	Key     []byte      `json:"key,omitempty"`      // DEPRECATED
	KeySize int         `json:"key_size,omitempty"` // For algorithms with variable key sizes
	Keys    keyEntryMap `json:"keys"`

	// Derived keys MUST provide a context and the master underlying key is
	// never used. If convergent encryption is true, the context will be used
	// as the nonce as well.
	Derived              bool `json:"derived"`
	KDF                  int  `json:"kdf"`
	ConvergentEncryption bool `json:"convergent_encryption"`

	// Whether the key is exportable
	Exportable bool `json:"exportable"`

	// The minimum version of the key allowed to be used for decryption
	MinDecryptionVersion int `json:"min_decryption_version"`

	// The minimum version of the key allowed to be used for encryption
	MinEncryptionVersion int `json:"min_encryption_version"`

	// The latest key version in this policy
	LatestVersion int `json:"latest_version"`

	// The latest key version in the archive. We never delete these, so this is
	// a max.
	ArchiveVersion int `json:"archive_version"`

	// ArchiveMinVersion is the minimum version of the key in the archive.
	ArchiveMinVersion int `json:"archive_min_version"`

	// MinAvailableVersion is the minimum version of the key present. All key
	// versions before this would have been deleted.
	MinAvailableVersion int `json:"min_available_version"`

	// Whether the key is allowed to be deleted
	DeletionAllowed bool `json:"deletion_allowed"`

	// The version of the convergent nonce to use
	ConvergentVersion int `json:"convergent_version"`

	// The type of key
	Type KeyType `json:"type"`

	// BackupInfo indicates the information about the backup action taken on
	// this policy
	BackupInfo *BackupInfo `json:"backup_info"`

	// RestoreInfo indicates the information about the restore action taken on
	// this policy
	RestoreInfo *RestoreInfo `json:"restore_info"`

	// AllowPlaintextBackup allows taking backup of the policy in plaintext
	AllowPlaintextBackup bool `json:"allow_plaintext_backup"`

	// VersionTemplate is used to prefix the ciphertext with information about
	// the key version. It must inclide {{version}} and a delimiter between the
	// version prefix and the ciphertext.
	VersionTemplate string `json:"version_template"`

	// StoragePrefix is used to add a prefix when storing and retrieving the
	// policy object.
	StoragePrefix string `json:"storage_prefix"`

	// AutoRotatePeriod defines how frequently the key should automatically
	// rotate. Setting this to zero disables automatic rotation for the key.
	AutoRotatePeriod time.Duration `json:"auto_rotate_period"`

	// Imported indicates whether the key was generated by Vault or imported
	// from an external source
	Imported bool

	// AllowImportedKeyRotation indicates whether an imported key may be rotated by Vault
	AllowImportedKeyRotation bool
	// contains filtered or unexported fields
}

Policy is the struct used to store metadata

func LoadPolicy

func LoadPolicy(ctx context.Context, s logical.Storage, path string) (*Policy, error)

LoadPolicy will load a policy from the provided storage path and set the necessary un-exported variables. It is particularly useful when accessing a policy without the lock manager.

func NewPolicy

func NewPolicy(config PolicyConfig) *Policy

NewPolicy takes a policy config and returns a Policy with those settings.

func (*Policy) Backup

func (p *Policy) Backup(ctx context.Context, storage logical.Storage) (out string, retErr error)

Backup should be called with an exclusive lock held on the policy

func (*Policy) CreateCsr added in v0.10.0

func (p *Policy) CreateCsr(keyVersion int, csrTemplate *x509.CertificateRequest) ([]byte, error)

func (*Policy) Decrypt

func (p *Policy) Decrypt(context, nonce []byte, value string) (string, error)

func (*Policy) DecryptWithFactory added in v0.6.1

func (p *Policy) DecryptWithFactory(context, nonce []byte, value string, factories ...interface{}) (string, error)

func (*Policy) DeriveKey

func (p *Policy) DeriveKey(context, salt []byte, ver int, numBytes int) ([]byte, error)

DeriveKey is used to derive a symmetric key given a context and salt. This does not check the policies Derived flag, but just implements the derivation logic. GetKey is responsible for switching on the policy config.

func (*Policy) Encrypt

func (p *Policy) Encrypt(ver int, context, nonce []byte, value string) (string, error)

func (*Policy) EncryptWithFactory added in v0.6.0

func (p *Policy) EncryptWithFactory(ver int, context []byte, nonce []byte, value string, factories ...interface{}) (string, error)

func (*Policy) GetKey added in v0.2.0

func (p *Policy) GetKey(context []byte, ver, numBytes int) ([]byte, error)

GetKey is used to derive the encryption key that should be used depending on the policy. If derivation is disabled the raw key is used and no context is required, otherwise the KDF mode is used with the context to derive the proper key.

func (*Policy) HMACKey

func (p *Policy) HMACKey(version int) ([]byte, error)

func (*Policy) HMACWithManagedKey added in v0.8.0

func (p *Policy) HMACWithManagedKey(ctx context.Context, ver int, managedKeySystemView logical.ManagedKeySystemView, backendUUID string, algorithm string, data []byte) (hmacBytes []byte, err error)

func (*Policy) Import added in v0.5.0

func (p *Policy) Import(ctx context.Context, storage logical.Storage, key []byte, randReader io.Reader) error

func (*Policy) ImportPrivateKeyForVersion added in v0.9.1

func (p *Policy) ImportPrivateKeyForVersion(ctx context.Context, storage logical.Storage, keyVersion int, key []byte) error

func (*Policy) ImportPublicOrPrivate added in v0.9.1

func (p *Policy) ImportPublicOrPrivate(ctx context.Context, storage logical.Storage, key []byte, isPrivateKey bool, randReader io.Reader) error

func (*Policy) KeyVersionCanBeUpdated added in v0.9.1

func (p *Policy) KeyVersionCanBeUpdated(keyVersion int, isPrivateKey bool) error

func (*Policy) LoadArchive

func (p *Policy) LoadArchive(ctx context.Context, storage logical.Storage) (*archivedKeys, error)

func (*Policy) Lock

func (p *Policy) Lock(exclusive bool)

func (*Policy) MigrateKeyToKeysMap

func (p *Policy) MigrateKeyToKeysMap()

func (*Policy) NeedsUpgrade

func (p *Policy) NeedsUpgrade() bool

func (*Policy) Persist

func (p *Policy) Persist(ctx context.Context, storage logical.Storage) (retErr error)

func (*Policy) Rotate

func (p *Policy) Rotate(ctx context.Context, storage logical.Storage, randReader io.Reader) (retErr error)

Rotate rotates the policy and persists it to storage. If the rotation partially fails, the policy state will be restored.

func (*Policy) RotateInMemory added in v0.2.0

func (p *Policy) RotateInMemory(randReader io.Reader) (retErr error)

RotateInMemory rotates the policy but does not persist it to storage.

func (*Policy) RotateManagedKey added in v0.8.0

func (p *Policy) RotateManagedKey(ctx context.Context, storage logical.Storage, managedKeyUUID string) error

func (*Policy) Serialize

func (p *Policy) Serialize() ([]byte, error)

func (*Policy) Sign

func (p *Policy) Sign(ver int, context, input []byte, hashAlgorithm HashType, sigAlgorithm string, marshaling MarshalingType) (*SigningResult, error)

func (*Policy) SignWithOptions added in v0.6.0

func (p *Policy) SignWithOptions(ver int, context, input []byte, options *SigningOptions) (*SigningResult, error)

func (*Policy) SymmetricDecryptRaw added in v0.2.0

func (p *Policy) SymmetricDecryptRaw(encKey, ciphertext []byte, opts SymmetricOpts) ([]byte, error)

Symmetrically decrypt a ciphertext given the convergence configuration and appropriate keys

func (*Policy) SymmetricEncryptRaw added in v0.2.0

func (p *Policy) SymmetricEncryptRaw(ver int, encKey, plaintext []byte, opts SymmetricOpts) ([]byte, error)

Symmetrically encrypt a plaintext given the convergence configuration and appropriate keys

func (*Policy) Unlock

func (p *Policy) Unlock()

func (*Policy) Upgrade

func (p *Policy) Upgrade(ctx context.Context, storage logical.Storage, randReader io.Reader) (retErr error)

func (*Policy) ValidateAndPersistCertificateChain added in v0.10.0

func (p *Policy) ValidateAndPersistCertificateChain(ctx context.Context, keyVersion int, certChain []*x509.Certificate, storage logical.Storage) error

func (*Policy) ValidateLeafCertKeyMatch added in v0.10.0

func (p *Policy) ValidateLeafCertKeyMatch(keyVersion int, certPublicKeyAlgorithm x509.PublicKeyAlgorithm, certPublicKey any) (bool, error)

func (*Policy) VerifySignature

func (p *Policy) VerifySignature(context, input []byte, hashAlgorithm HashType, sigAlgorithm string, marshaling MarshalingType, sig string) (bool, error)

func (*Policy) VerifySignatureWithOptions added in v0.6.0

func (p *Policy) VerifySignatureWithOptions(context, input []byte, sig string, options *SigningOptions) (bool, error)

func (*Policy) WrapKey added in v0.9.2

func (p *Policy) WrapKey(ver int, targetKey interface{}, targetKeyType KeyType, hash hash.Hash) (string, error)

type PolicyConfig

type PolicyConfig struct {
	// The name of the policy
	Name string `json:"name"`

	// The type of key
	Type KeyType

	// Derived keys MUST provide a context and the master underlying key is
	// never used.
	Derived              bool
	KDF                  int
	ConvergentEncryption bool

	// Whether the key is exportable
	Exportable bool

	// Whether the key is allowed to be deleted
	DeletionAllowed bool

	// AllowPlaintextBackup allows taking backup of the policy in plaintext
	AllowPlaintextBackup bool

	// VersionTemplate is used to prefix the ciphertext with information about
	// the key version. It must inclide {{version}} and a delimiter between the
	// version prefix and the ciphertext.
	VersionTemplate string

	// StoragePrefix is used to add a prefix when storing and retrieving the
	// policy object.
	StoragePrefix string
}

PolicyConfig is used to create a new policy

type PolicyRequest

type PolicyRequest struct {
	// The storage to use
	Storage logical.Storage

	// The name of the policy
	Name string

	// The key type
	KeyType KeyType

	// The key size for variable key size algorithms
	KeySize int

	// Whether it should be derived
	Derived bool

	// Whether to enable convergent encryption
	Convergent bool

	// Whether to allow export
	Exportable bool

	// Whether to upsert
	Upsert bool

	// Whether to allow plaintext backup
	AllowPlaintextBackup bool

	// How frequently the key should automatically rotate
	AutoRotatePeriod time.Duration

	// AllowImportedKeyRotation indicates whether an imported key may be rotated by Vault
	AllowImportedKeyRotation bool

	// Indicates whether a private or public key is imported/upserted
	IsPrivateKey bool

	// The UUID of the managed key, if using one
	ManagedKeyUUID string
}

PolicyRequest holds values used when requesting a policy. Most values are only used during an upsert.

type RestoreInfo

type RestoreInfo struct {
	Time    time.Time `json:"time"`
	Version int       `json:"version"`
}

type SigningOptions added in v0.6.0

type SigningOptions struct {
	HashAlgorithm    HashType
	Marshaling       MarshalingType
	SaltLength       int
	SigAlgorithm     string
	ManagedKeyParams ManagedKeyParameters
}

type SigningResult

type SigningResult struct {
	Signature string
	PublicKey []byte
}

type SymmetricOpts added in v0.2.0

type SymmetricOpts struct {
	// Whether to use convergent encryption
	Convergent bool
	// The version of the convergent encryption scheme
	ConvergentVersion int
	// The nonce, if not randomly generated
	Nonce []byte
	// Additional data to include in AEAD authentication
	AdditionalData []byte
	// The HMAC key, for generating IVs in convergent encryption
	HMACKey []byte
	// Allows an external provider of the AEAD, for e.g. managed keys
	AEADFactory AEADFactory
}

SymmetricOpts are the arguments to symmetric operations that are "optional", e.g. not always used. This improves the aesthetics of calls to those functions.

type TransitLRU added in v0.1.12

type TransitLRU struct {
	// contains filtered or unexported fields
}

func NewTransitLRU added in v0.1.12

func NewTransitLRU(size int) (*TransitLRU, error)

func (*TransitLRU) Delete added in v0.1.12

func (c *TransitLRU) Delete(key interface{})

func (*TransitLRU) Load added in v0.1.12

func (c *TransitLRU) Load(key interface{}) (value interface{}, ok bool)

func (*TransitLRU) Size added in v0.1.12

func (c *TransitLRU) Size() int

func (*TransitLRU) Store added in v0.1.12

func (c *TransitLRU) Store(key, value interface{})

type TransitSyncMap added in v0.1.12

type TransitSyncMap struct {
	// contains filtered or unexported fields
}

func NewTransitSyncMap added in v0.1.12

func NewTransitSyncMap() *TransitSyncMap

func (*TransitSyncMap) Delete added in v0.1.12

func (c *TransitSyncMap) Delete(key interface{})

func (*TransitSyncMap) Load added in v0.1.12

func (c *TransitSyncMap) Load(key interface{}) (value interface{}, ok bool)

func (*TransitSyncMap) Size added in v0.1.12

func (c *TransitSyncMap) Size() int

func (*TransitSyncMap) Store added in v0.1.12

func (c *TransitSyncMap) Store(key, value interface{})

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL