feat(crypto): describe parsed material as cryptographic assets (#11092)

This commit is contained in:
Nikita Pivkin authored and GitHub committed 2026-09-17 06:54:00 +00:00
1 parent ef28d95fea
commit 7d0a892930
16 files changed
+2321 -450

No files matched your search

+40 -33
View File
@@ -18,20 +18,22 @@ func WithMutate(mutate func(*types.CryptoAsset)) Option {
// CertificateAsset returns a valid certificate asset.
func CertificateAsset(opts ...Option) types.CryptoAsset {
asset := types.CryptoAsset{
Kind: types.CryptoKindCertificate,
Identity: types.CryptoIdentity{
Method: types.CryptoMethodSHA256,
Value: strings.Repeat("a", 64),
CryptoAssetInfo: types.CryptoAssetInfo{
Kind: types.CryptoKindCertificate,
Identity: types.CryptoIdentity{
Method: types.CryptoMethodSHA256,
Value: strings.Repeat("a", 64),
},
Name: "example.test",
Certificate: &types.CryptoCertificate{
Subject: "CN=example.test",
Issuer: "CN=Example Test CA",
SerialNumber: "1",
Format: types.CryptoCertificateFormatX509,
},
},
Name: "example.test",
FilePath: "/etc/example.pem",
Certificate: &types.CryptoCertificate{
Subject: "CN=example.test",
Issuer: "CN=Example Test CA",
SerialNumber: "1",
Format: types.CryptoCertificateFormatX509,
Encoding: types.CryptoEncodingPEM,
},
Encoding: types.CryptoEncodingPEM,
}
return applyOptions(asset, opts)
}
@@ -39,18 +41,20 @@ func CertificateAsset(opts ...Option) types.CryptoAsset {
// PublicKeyAsset returns a valid public key asset.
func PublicKeyAsset(opts ...Option) types.CryptoAsset {
asset := types.CryptoAsset{
Kind: types.CryptoKindKey,
KeyType: types.CryptoKeyTypePublic,
Identity: types.CryptoIdentity{
Method: types.CryptoMethodSPKISHA256,
Value: strings.Repeat("b", 64),
CryptoAssetInfo: types.CryptoAssetInfo{
Kind: types.CryptoKindKey,
KeyType: types.CryptoKeyTypePublic,
Identity: types.CryptoIdentity{
Method: types.CryptoMethodSPKISHA256,
Value: strings.Repeat("b", 64),
},
Key: &types.CryptoKey{
Size: 2048,
},
},
FilePath: "/etc/example-public.pem",
Key: &types.CryptoKey{
Size: 2048,
Format: types.CryptoKeyFormatPKIX,
Encoding: types.CryptoEncodingPEM,
},
Format: types.CryptoKeyFormatPKIX,
Encoding: types.CryptoEncodingPEM,
}
return applyOptions(asset, opts)
}
@@ -60,7 +64,7 @@ func PrivateKeyAsset(opts ...Option) types.CryptoAsset {
asset := PublicKeyAsset()
asset.KeyType = types.CryptoKeyTypePrivate
asset.FilePath = "/etc/example-private.pem"
asset.Key.Format = types.CryptoKeyFormatPKCS8
asset.Format = types.CryptoKeyFormatPKCS8
return applyOptions(asset, opts)
}
@@ -77,24 +81,27 @@ func EncryptedPrivateKeyAsset(opts ...Option) types.CryptoAsset {
func RFC1423EncryptedPrivateKeyAsset(opts ...Option) types.CryptoAsset {
asset := EncryptedPrivateKeyAsset()
asset.Identity.Method = types.CryptoMethodEncryptedRFC1423SHA256
asset.Key.Format = types.CryptoKeyFormatPKCS1
asset.Format = types.CryptoKeyFormatPKCS1
return applyOptions(asset, opts)
}
// AlgorithmAsset returns a valid algorithm asset.
func AlgorithmAsset(opts ...Option) types.CryptoAsset {
asset := types.CryptoAsset{
Kind: types.CryptoKindAlgorithm,
Identity: types.CryptoIdentity{
Method: types.CryptoMethodOID,
Value: "1.2.840.113549.1.1.1",
CryptoAssetInfo: types.CryptoAssetInfo{
Kind: types.CryptoKindAlgorithm,
Identity: types.CryptoIdentity{
Method: types.CryptoMethodOID,
Value: "1.2.840.113549.1.1.1",
},
Name: "RSA",
// rsaEncryption identifies both signature and encryption keys, so the primitive
// stays unknown and the family stays empty, as the algorithm catalog describes it.
Algorithm: &types.CryptoAlgorithm{
Primitive: types.CryptoPrimitiveUnknown,
},
},
Name: "RSA",
FilePath: "/etc/example-algorithm.pem",
Algorithm: &types.CryptoAlgorithm{
Family: "RSA",
Primitive: types.CryptoPrimitivePKE,
},
}
return applyOptions(asset, opts)
}
+40
View File
@@ -0,0 +1,40 @@
package crypto
import (
"strconv"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
)
// DescribeAlgorithm describes the algorithm an OID identifies. The size and the curve
// belong to the key the algorithm is used with and are zero for a signature algorithm.
func DescribeAlgorithm(oid string, size int, curve string) ftypes.CryptoAssetInfo {
found := lookupAlgorithm(oid)
name := found.name
var parameters string
switch {
case found.parameter == ftypes.CryptoParameterKeySize && size > 0:
value := strconv.Itoa(size)
name += "-" + value
parameters = string(ftypes.CryptoParameterKeySize) + "=" + value
case found.parameter == ftypes.CryptoParameterCurve && curve != "":
name += "-" + curve
parameters = string(ftypes.CryptoParameterCurve) + "=" + curve
}
return ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: oid,
Parameters: parameters,
},
Name: name,
Algorithm: &ftypes.CryptoAlgorithm{
Family: found.family,
Primitive: found.primitive,
},
}
}
+118
View File
@@ -0,0 +1,118 @@
package crypto_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/trivy/pkg/crypto"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
)
func TestDescribeAlgorithm(t *testing.T) {
tests := []struct {
name string
oid string
size int
curve string
want ftypes.CryptoAssetInfo
}{
{
// A signature algorithm is described without key parameters, because the key
// that produced the signature is not the one being described.
name: "signature algorithm",
oid: "1.2.840.113549.1.1.11",
want: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.113549.1.1.11",
},
Name: "RSA-PKCS1-1.5-SHA-256",
Algorithm: &ftypes.CryptoAlgorithm{
Family: "RSASSA-PKCS1",
Primitive: ftypes.CryptoPrimitiveSignature,
},
},
},
{
// The catalog names the property that tells assets sharing an OID apart, and
// the value of that property becomes part of the identity.
name: "key size parameter",
oid: "1.2.840.113549.1.1.1",
size: 2048,
want: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.113549.1.1.1",
Parameters: "key-size=2048",
},
Name: "RSA-2048",
Algorithm: &ftypes.CryptoAlgorithm{
Primitive: ftypes.CryptoPrimitiveUnknown,
},
},
},
{
name: "curve parameter",
oid: "1.2.840.10045.2.1",
size: 256,
curve: "P-256",
want: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.10045.2.1",
Parameters: "curve=P-256",
},
Name: "EC-P-256",
Algorithm: &ftypes.CryptoAlgorithm{
Primitive: ftypes.CryptoPrimitiveUnknown,
},
},
},
{
// RSASSA-PSS is left out of the catalog because its variants share one OID.
name: "algorithm outside the catalog",
oid: "1.2.840.113549.1.1.10",
want: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.113549.1.1.10",
},
Name: "1.2.840.113549.1.1.10",
Algorithm: &ftypes.CryptoAlgorithm{
Primitive: ftypes.CryptoPrimitiveUnknown,
},
},
},
{
// A catalog entry that names a parameter is described without it when the key
// does not state one, which is what a signature algorithm does.
name: "missing parameter value",
oid: "1.2.840.10045.2.1",
want: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.10045.2.1",
},
Name: "EC",
Algorithm: &ftypes.CryptoAlgorithm{
Primitive: ftypes.CryptoPrimitiveUnknown,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := crypto.DescribeAlgorithm(tt.oid, tt.size, tt.curve)
assert.Equal(t, tt.want, got)
require.NoError(t, got.Validate())
})
}
}
+145
View File
@@ -0,0 +1,145 @@
package crypto
import ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
// algorithm is the hand-maintained knowledge about an OID: the name and family it
// carries in the CycloneDX cryptography vocabulary, the primitive it provides, and the
// key property that distinguishes assets sharing it.
//
// An OID whose purpose cannot be decided carries no family and an unknown primitive.
// RFC 3279 section 2.3.1 states that rsaEncryption identifies both signature and
// encryption keys, and id-ecPublicKey is shared by ECDSA and ECDH just as widely.
// Naming a family for either would assert a purpose the certificate does not state.
//
// A name is a base name: an algorithm with a parameter is named together with the value
// of that parameter, such as RSA-2048.
type algorithm struct {
name string
family string
primitive ftypes.CryptoPrimitive
parameter ftypes.CryptoAlgorithmParameter
}
// algorithms maps the OIDs that appear in the certificates and keys this package
// describes. An OID is read out of the DER rather than taken from a crypto/x509
// enumeration, so an algorithm the standard library does not recognize reaches this table
// as well.
//
// A name follows the naming pattern the CycloneDX cryptography vocabulary defines for
// the family: RSASSA-PKCS1 carries the pattern RSA-PKCS1-1.5[-{digestAlgorithm}][-{keyLength}],
// which yields RSA-PKCS1-1.5-SHA-256 for sha256WithRSAEncryption. A signature name stops
// at the digest: the key length in the pattern describes the key that produced the
// signature, and that key belongs to the issuer, while a certificate carries the key of
// its subject.
//
// An OID with no family has no pattern to follow, because the vocabulary defines one per
// family. Its name is built by the same rule as every other: the base name carries the
// value of the parameter that distinguishes the asset, which yields RSA-2048 and EC-P-256.
//
// RSA-PSS is absent on purpose: its variants share one OID and differ only in the
// signature parameters, so identifying it needs parameter-aware handling.
var algorithms = map[string]algorithm{
// Certificate signature algorithms.
"1.2.840.113549.1.1.4": {
name: "RSA-PKCS1-1.5-MD5",
family: "RSASSA-PKCS1",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.113549.1.1.5": {
name: "RSA-PKCS1-1.5-SHA-1",
family: "RSASSA-PKCS1",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.113549.1.1.11": {
name: "RSA-PKCS1-1.5-SHA-256",
family: "RSASSA-PKCS1",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.113549.1.1.12": {
name: "RSA-PKCS1-1.5-SHA-384",
family: "RSASSA-PKCS1",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.113549.1.1.13": {
name: "RSA-PKCS1-1.5-SHA-512",
family: "RSASSA-PKCS1",
primitive: ftypes.CryptoPrimitiveSignature,
},
// The ISO arc carries a second OID for SHA-1 with RSA, which makecert.exe has been
// known to produce. The two OIDs name one algorithm but stay two assets, because an
// algorithm is identified by the OID the certificate carries.
"1.3.14.3.2.29": {
name: "RSA-PKCS1-1.5-SHA-1",
family: "RSASSA-PKCS1",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.10040.4.3": {
name: "DSA-SHA-1",
family: "DSA",
primitive: ftypes.CryptoPrimitiveSignature,
},
"2.16.840.1.101.3.4.3.2": {
name: "DSA-SHA-256",
family: "DSA",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.10045.4.1": {
name: "ECDSA-SHA-1",
family: "ECDSA",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.10045.4.3.2": {
name: "ECDSA-SHA-256",
family: "ECDSA",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.10045.4.3.3": {
name: "ECDSA-SHA-384",
family: "ECDSA",
primitive: ftypes.CryptoPrimitiveSignature,
},
"1.2.840.10045.4.3.4": {
name: "ECDSA-SHA-512",
family: "ECDSA",
primitive: ftypes.CryptoPrimitiveSignature,
},
// Subject public key algorithms.
"1.2.840.113549.1.1.1": {
name: "RSA",
primitive: ftypes.CryptoPrimitiveUnknown,
parameter: ftypes.CryptoParameterKeySize,
},
"1.2.840.10045.2.1": {
name: "EC",
primitive: ftypes.CryptoPrimitiveUnknown,
parameter: ftypes.CryptoParameterCurve,
},
"1.2.840.10040.4.1": {
name: "DSA",
family: "DSA",
primitive: ftypes.CryptoPrimitiveSignature,
parameter: ftypes.CryptoParameterKeySize,
},
// Ed25519 uses one OID as both the key and the signature algorithm, and the curve
// fixes its parameters.
"1.3.101.112": {
name: "Ed25519",
family: "EdDSA",
primitive: ftypes.CryptoPrimitiveSignature,
},
}
// lookupAlgorithm reports what the catalog knows about an OID. An OID the table does not
// list is named by the OID itself and its primitive is unknown, because every other
// attribute comes from the table.
func lookupAlgorithm(oid string) algorithm {
if found, known := algorithms[oid]; known {
return found
}
return algorithm{
name: oid,
primitive: ftypes.CryptoPrimitiveUnknown,
}
}
+3
View File
@@ -0,0 +1,3 @@
// Package crypto describes the keys and algorithms that every source format has in common.
// Reading a container is left to the parser of that format.
package crypto
+176
View File
@@ -0,0 +1,176 @@
package crypto
import (
stdcrypto "crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"errors"
"fmt"
"math/big"
"golang.org/x/xerrors"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
)
// ErrNoCanonicalForm reports a key that cannot be reduced to SubjectPublicKeyInfo, such as
// the absent key of a certificate whose algorithm crypto/x509 does not recognize.
var ErrNoCanonicalForm = errors.New("key has no canonical form")
// DescribeKey describes a key and the algorithm it belongs to. A private key is described
// through its public projection, so it differs from a public key only in its key type.
//
// A key that cannot be encoded is reported with ErrNoCanonicalForm. Any other error means
// the SubjectPublicKeyInfo produced here does not parse back, and the encoder is wrong.
func DescribeKey(
pub stdcrypto.PublicKey,
keyType ftypes.CryptoKeyType,
) (key, keyAlgorithm ftypes.CryptoAssetInfo, err error) {
identity, algorithmOID, err := publicKeyInfo(pub)
if err != nil {
return ftypes.CryptoAssetInfo{}, ftypes.CryptoAssetInfo{}, err
}
size, curve := keyDetails(pub)
keyAlgorithm = DescribeAlgorithm(algorithmOID, size, curve)
key = ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: keyType,
Identity: identity,
Name: keyAlgorithm.Name + " " + string(keyType) + " key",
Key: &ftypes.CryptoKey{
Size: size,
Curve: curve,
},
Relationships: []ftypes.CryptoRelationship{{
Type: ftypes.CryptoRelationshipUsedWith,
RelatedAsset: keyAlgorithm.Descriptor(),
}},
}
return key, keyAlgorithm, nil
}
// DescribeEncryptedKey describes an encrypted private key container. Its algorithm, size
// and curve live inside the encrypted payload and stay unset.
func DescribeEncryptedKey(
method ftypes.CryptoIdentityMethod,
canonical []byte,
format ftypes.CryptoKeyFormat,
) ftypes.CryptoAssetInfo {
return ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePrivate,
Identity: ftypes.DigestIdentity(method, canonical),
// The container states its format, and nothing else about the key is readable
// without the passphrase.
Name: "Encrypted " + string(format) + " private key",
Key: &ftypes.CryptoKey{
Encrypted: true,
},
}
}
// keyDetails reports the size in bits and the curve of a public key.
func keyDetails(pub stdcrypto.PublicKey) (int, string) {
switch pub := pub.(type) {
case *rsa.PublicKey:
return pub.N.BitLen(), ""
case *dsa.PublicKey:
return pub.P.BitLen(), ""
case *ecdsa.PublicKey:
return pub.Curve.Params().BitSize, pub.Curve.Params().Name
case ed25519.PublicKey:
// An Ed25519 key is the raw point, so its length is the key size in bytes.
return len(pub) * 8, ""
}
return 0, ""
}
// publicKeyInfo canonicalizes a key as PKIX SubjectPublicKeyInfo and reports the identity
// it yields together with the OID of its algorithm.
func publicKeyInfo(pub stdcrypto.PublicKey) (ftypes.CryptoIdentity, string, error) {
der, err := MarshalPublicKey(pub)
if err != nil {
return ftypes.CryptoIdentity{}, "", fmt.Errorf("%w: %w", ErrNoCanonicalForm, err)
}
oid, err := subjectPublicKeyOID(der)
if err != nil {
return ftypes.CryptoIdentity{}, "", xerrors.Errorf("read the algorithm of the encoded key: %w", err)
}
return ftypes.DigestIdentity(ftypes.CryptoMethodSPKISHA256, der), oid, nil
}
// oidDSA identifies a DSA public key, defined by RFC 3279 section 2.3.2.
// See https://datatracker.ietf.org/doc/html/rfc3279#section-2.3.2
var oidDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
// MarshalPublicKey encodes a public key as PKIX SubjectPublicKeyInfo, the canonical form a
// key is identified by. A DSA key is encoded here, because crypto/x509 parses that form but
// cannot produce it.
func MarshalPublicKey(pub stdcrypto.PublicKey) ([]byte, error) {
if key, ok := pub.(*dsa.PublicKey); ok {
return marshalDSAPublicKey(key)
}
return x509.MarshalPKIXPublicKey(pub)
}
// marshalDSAPublicKey encodes a DSA public key the way RFC 3279 section 2.3.2 defines it:
// the domain parameters travel in the algorithm identifier, and the public value is a
// DER integer inside the bit string. crypto/x509 parses this form but cannot produce it.
// See https://datatracker.ietf.org/doc/html/rfc3279#section-2.3.2
func marshalDSAPublicKey(pub *dsa.PublicKey) ([]byte, error) {
parameters, err := asn1.Marshal(struct {
P, Q, G *big.Int
}{pub.P, pub.Q, pub.G})
if err != nil {
return nil, xerrors.Errorf("marshal DSA parameters: %w", err)
}
value, err := asn1.Marshal(pub.Y)
if err != nil {
return nil, xerrors.Errorf("marshal DSA public value: %w", err)
}
der, err := asn1.Marshal(struct {
Algorithm pkix.AlgorithmIdentifier
SubjectPublicKey asn1.BitString
}{
Algorithm: pkix.AlgorithmIdentifier{
Algorithm: oidDSA,
Parameters: asn1.RawValue{FullBytes: parameters},
},
SubjectPublicKey: asn1.BitString{
Bytes: value,
BitLength: len(value) * 8,
},
})
if err != nil {
return nil, xerrors.Errorf("marshal DSA subject public key info: %w", err)
}
return der, nil
}
// subjectPublicKeyOID reads the algorithm OID out of SubjectPublicKeyInfo DER. The OID is
// read from the encoding rather than from PublicKeyAlgorithm, which is an enumeration that
// does not carry it.
func subjectPublicKeyOID(der []byte) (string, error) {
// The key itself follows the algorithm and is left unread, because encoding/asn1
// tolerates elements of a sequence that the target struct does not declare.
var info struct {
Algorithm pkix.AlgorithmIdentifier
}
if _, err := asn1.Unmarshal(der, &info); err != nil {
return "", xerrors.Errorf("unmarshal subject public key info: %w", err)
}
return info.Algorithm.Algorithm.String(), nil
}
+357
View File
@@ -0,0 +1,357 @@
package crypto_test
import (
"crypto/dsa"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
stdx509 "crypto/x509"
"math/big"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/trivy/pkg/crypto"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
)
type keyFixtures struct {
rsaPublic *rsa.PublicKey
ecdsaPublic *ecdsa.PublicKey
ed25519Public ed25519.PublicKey
dsaPublic *dsa.PublicKey
}
func TestDescribeKey(t *testing.T) {
fixtures := newKeyFixtures(t)
// The algorithm of an RSA key cannot be told apart from a signature algorithm by its
// OID alone, so it carries an unknown primitive and no family.
rsaAlgorithm := ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.113549.1.1.1",
Parameters: "key-size=2048",
},
Name: "RSA-2048",
Algorithm: &ftypes.CryptoAlgorithm{
Primitive: ftypes.CryptoPrimitiveUnknown,
},
}
ecAlgorithm := ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.10045.2.1",
Parameters: "curve=P-256",
},
Name: "EC-P-256",
Algorithm: &ftypes.CryptoAlgorithm{
Primitive: ftypes.CryptoPrimitiveUnknown,
},
}
ed25519Algorithm := ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.3.101.112",
},
Name: "Ed25519",
Algorithm: &ftypes.CryptoAlgorithm{
Family: "EdDSA",
Primitive: ftypes.CryptoPrimitiveSignature,
},
}
dsaAlgorithm := ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.10040.4.1",
Parameters: "key-size=2048",
},
Name: "DSA-2048",
Algorithm: &ftypes.CryptoAlgorithm{
Family: "DSA",
Primitive: ftypes.CryptoPrimitiveSignature,
},
}
tests := []struct {
name string
pub any
keyType ftypes.CryptoKeyType
wantKey ftypes.CryptoAssetInfo
wantAlgorithm ftypes.CryptoAssetInfo
}{
{
name: "RSA public key",
pub: fixtures.rsaPublic,
keyType: ftypes.CryptoKeyTypePublic,
wantKey: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePublic,
Identity: spkiIdentity(t, fixtures.rsaPublic),
Name: "RSA-2048 public key",
Key: &ftypes.CryptoKey{
Size: 2048,
},
Relationships: []ftypes.CryptoRelationship{{
Type: ftypes.CryptoRelationshipUsedWith,
RelatedAsset: rsaAlgorithm.Descriptor(),
}},
},
wantAlgorithm: rsaAlgorithm,
},
{
name: "ECDSA public key",
pub: fixtures.ecdsaPublic,
keyType: ftypes.CryptoKeyTypePublic,
wantKey: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePublic,
Identity: spkiIdentity(t, fixtures.ecdsaPublic),
Name: "EC-P-256 public key",
Key: &ftypes.CryptoKey{
Size: 256,
Curve: "P-256",
},
Relationships: []ftypes.CryptoRelationship{{
Type: ftypes.CryptoRelationshipUsedWith,
RelatedAsset: ecAlgorithm.Descriptor(),
}},
},
wantAlgorithm: ecAlgorithm,
},
{
name: "Ed25519 public key",
pub: fixtures.ed25519Public,
keyType: ftypes.CryptoKeyTypePublic,
wantKey: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePublic,
Identity: spkiIdentity(t, fixtures.ed25519Public),
Name: "Ed25519 public key",
Key: &ftypes.CryptoKey{
Size: 256,
},
Relationships: []ftypes.CryptoRelationship{{
Type: ftypes.CryptoRelationshipUsedWith,
RelatedAsset: ed25519Algorithm.Descriptor(),
}},
},
wantAlgorithm: ed25519Algorithm,
},
{
// crypto/x509 parses a DSA key but cannot encode it, so the canonical form
// comes from this package.
name: "DSA public key",
pub: fixtures.dsaPublic,
keyType: ftypes.CryptoKeyTypePublic,
wantKey: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePublic,
Identity: spkiIdentity(t, fixtures.dsaPublic),
Name: "DSA-2048 public key",
Key: &ftypes.CryptoKey{
Size: 2048,
},
Relationships: []ftypes.CryptoRelationship{{
Type: ftypes.CryptoRelationshipUsedWith,
RelatedAsset: dsaAlgorithm.Descriptor(),
}},
},
wantAlgorithm: dsaAlgorithm,
},
{
// A private key is described through its public projection, so only the key
// type tells the two apart.
name: "private key",
pub: fixtures.rsaPublic,
keyType: ftypes.CryptoKeyTypePrivate,
wantKey: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePrivate,
Identity: spkiIdentity(t, fixtures.rsaPublic),
Name: "RSA-2048 private key",
Key: &ftypes.CryptoKey{
Size: 2048,
},
Relationships: []ftypes.CryptoRelationship{{
Type: ftypes.CryptoRelationshipUsedWith,
RelatedAsset: rsaAlgorithm.Descriptor(),
}},
},
wantAlgorithm: rsaAlgorithm,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
key, algorithm, err := crypto.DescribeKey(tt.pub, tt.keyType)
require.NoError(t, err)
assert.Equal(t, tt.wantKey, key)
assert.Equal(t, tt.wantAlgorithm, algorithm)
require.NoError(t, key.Validate())
require.NoError(t, algorithm.Validate())
})
}
}
// TestDescribeKeyNoCanonicalForm covers the key of a certificate whose algorithm
// crypto/x509 does not recognize, which parsing leaves absent.
func TestDescribeKeyNoCanonicalForm(t *testing.T) {
_, _, err := crypto.DescribeKey(nil, ftypes.CryptoKeyTypePublic)
require.ErrorIs(t, err, crypto.ErrNoCanonicalForm)
}
func TestDescribeEncryptedKey(t *testing.T) {
container := []byte("encrypted container")
tests := []struct {
name string
method ftypes.CryptoIdentityMethod
format ftypes.CryptoKeyFormat
want ftypes.CryptoAssetInfo
}{
{
name: "PKCS#8",
method: ftypes.CryptoMethodEncryptedPKCS8SHA256,
format: ftypes.CryptoKeyFormatPKCS8,
want: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePrivate,
Identity: ftypes.DigestIdentity(ftypes.CryptoMethodEncryptedPKCS8SHA256, container),
Name: "Encrypted PKCS#8 private key",
Key: &ftypes.CryptoKey{
Encrypted: true,
},
},
},
{
name: "RFC 1423",
method: ftypes.CryptoMethodEncryptedRFC1423SHA256,
format: ftypes.CryptoKeyFormatPKCS1,
want: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePrivate,
Identity: ftypes.DigestIdentity(ftypes.CryptoMethodEncryptedRFC1423SHA256, container),
Name: "Encrypted PKCS#1 private key",
Key: &ftypes.CryptoKey{
Encrypted: true,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := crypto.DescribeEncryptedKey(tt.method, container, tt.format)
assert.Equal(t, tt.want, got)
require.NoError(t, got.Validate())
})
}
}
func TestDescribeKeyIdentity(t *testing.T) {
fixtures := newKeyFixtures(t)
public, _, err := crypto.DescribeKey(fixtures.rsaPublic, ftypes.CryptoKeyTypePublic)
require.NoError(t, err)
private, _, err := crypto.DescribeKey(fixtures.rsaPublic, ftypes.CryptoKeyTypePrivate)
require.NoError(t, err)
// The two are the same key material, and the key type is what keeps them apart.
assert.Equal(t, public.Identity, private.Identity)
assert.NotEqual(t, public.Descriptor(), private.Descriptor())
}
// TestMarshalPublicKey checks the encoding by reading the key back with crypto/x509, which
// parses every form produced here, including the DSA one it refuses to produce itself.
func TestMarshalPublicKey(t *testing.T) {
fixtures := newKeyFixtures(t)
tests := []struct {
name string
pub any
wantErr string
}{
{
name: "RSA",
pub: fixtures.rsaPublic,
},
{
name: "ECDSA",
pub: fixtures.ecdsaPublic,
},
{
name: "Ed25519",
pub: fixtures.ed25519Public,
},
{
// The only key type encoded here rather than by crypto/x509.
name: "DSA",
pub: fixtures.dsaPublic,
},
{
name: "unsupported key type",
pub: "not a key",
wantErr: "unsupported public key type",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
der, err := crypto.MarshalPublicKey(tt.pub)
if tt.wantErr != "" {
require.ErrorContains(t, err, tt.wantErr)
return
}
require.NoError(t, err)
parsed, err := stdx509.ParsePKIXPublicKey(der)
require.NoError(t, err)
assert.Equal(t, tt.pub, parsed)
})
}
}
func newKeyFixtures(t *testing.T) keyFixtures {
t.Helper()
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
ed25519Public, _, err := ed25519.GenerateKey(rand.Reader)
require.NoError(t, err)
return keyFixtures{
rsaPublic: &rsaKey.PublicKey,
ecdsaPublic: &ecdsaKey.PublicKey,
ed25519Public: ed25519Public,
dsaPublic: &dsa.PublicKey{
Parameters: dsa.Parameters{
// A 2048-bit modulus, so that the reported key size is a realistic one.
// The group is not a valid one, which nothing on this path checks.
P: new(big.Int).Lsh(big.NewInt(1), 2047),
Q: big.NewInt(11),
G: big.NewInt(2),
},
Y: big.NewInt(4),
},
}
}
func spkiIdentity(t *testing.T, pub any) ftypes.CryptoIdentity {
t.Helper()
der, err := crypto.MarshalPublicKey(pub)
require.NoError(t, err)
return ftypes.DigestIdentity(ftypes.CryptoMethodSPKISHA256, der)
}
+200
View File
@@ -0,0 +1,200 @@
package x509
import (
"cmp"
"context"
stdx509 "crypto/x509"
"encoding/asn1"
"errors"
"net"
"net/url"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/crypto"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
xslices "github.com/aquasecurity/trivy/pkg/x/slices"
)
// objectToAssets describes a parsed object as assets. Material it cannot describe is
// logged and left out, and an error means the description itself is broken.
func objectToAssets(ctx context.Context, obj object) ([]ftypes.CryptoAsset, error) {
switch obj.kind {
case objectCertificate:
return describeCertificate(ctx, obj.certificate, obj.encoding)
case objectPublicKey:
return describeStandaloneKey(ctx, obj, ftypes.CryptoKeyTypePublic)
case objectPrivateKey:
return describeStandaloneKey(ctx, obj, ftypes.CryptoKeyTypePrivate)
case objectEncryptedPrivateKey:
return describeEncryptedPrivateKey(obj)
default:
return nil, xerrors.Errorf("object kind %d has no description", obj.kind)
}
}
// describeCertificate describes a certificate, the algorithm it is signed with, the key
// it carries and the algorithm of that key. A key that cannot be described is left out,
// and the certificate keeps the relationships it can state.
func describeCertificate(
ctx context.Context,
cert certificate,
encoding ftypes.CryptoEncoding,
) ([]ftypes.CryptoAsset, error) {
// The full distinguished name is reported, because a certificate authority often
// identifies itself by organization alone and carries no common name.
subject := cert.Subject.String()
info := ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindCertificate,
Identity: ftypes.DigestIdentity(ftypes.CryptoMethodSHA256, cert.Raw),
Name: cmp.Or(cert.Subject.CommonName, subject),
Certificate: &ftypes.CryptoCertificate{
Subject: subject,
Issuer: cert.Issuer.String(),
SerialNumber: cert.SerialNumber.Text(16),
NotBefore: cert.NotBefore,
NotAfter: cert.NotAfter,
Format: ftypes.CryptoCertificateFormatX509,
KeyUsage: keyUsages(cert.KeyUsage),
ExtendedKeyUsage: extendedKeyUsages(cert.Certificate),
DNSNames: cert.DNSNames,
EmailAddresses: cert.EmailAddresses,
IPAddresses: xslices.Map(cert.IPAddresses, func(ip net.IP) string {
return ip.String()
}),
URIs: xslices.Map(cert.URIs, func(u *url.URL) string {
return u.String()
}),
BasicConstraintsValid: cert.BasicConstraintsValid,
IsCA: cert.IsCA,
// crypto/x509 reports -1 when basic constraints carry no path length,
// which this model represents as an unset zero.
MaxPathLen: max(cert.MaxPathLen, 0),
MaxPathLenZero: cert.MaxPathLenZero,
},
}
// A signature algorithm gets no key parameters, because the key that produced the
// signature belongs to the issuer, and this certificate stores the key of its subject.
signature := crypto.DescribeAlgorithm(cert.signatureOID, 0, "")
info.Relationships = append(info.Relationships, ftypes.CryptoRelationship{
Type: ftypes.CryptoRelationshipSignedWith,
RelatedAsset: signature.Descriptor(),
})
// Nothing a certificate carries has a container of its own.
related := []ftypes.CryptoAsset{{CryptoAssetInfo: signature}}
key, keyAlgorithm, err := crypto.DescribeKey(cert.PublicKey, ftypes.CryptoKeyTypePublic)
switch {
// TODO: cover a certificate whose key algorithm OID crypto/x509 does not recognize,
// such as Ed448.
case errors.Is(err, crypto.ErrNoCanonicalForm):
log.DebugContext(ctx, "Certificate key not described", log.Err(err))
case err != nil:
return nil, xerrors.Errorf("describe certificate key: %w", err)
default:
info.Relationships = append(info.Relationships, ftypes.CryptoRelationship{
Type: ftypes.CryptoRelationshipContains,
RelatedAsset: key.Descriptor(),
})
related = append(related,
ftypes.CryptoAsset{CryptoAssetInfo: key},
ftypes.CryptoAsset{CryptoAssetInfo: keyAlgorithm},
)
}
asset := ftypes.CryptoAsset{
CryptoAssetInfo: info,
Encoding: encoding,
}
return append([]ftypes.CryptoAsset{asset}, related...), nil
}
// describeStandaloneKey describes a key object as the key itself and the algorithm it
// belongs to.
func describeStandaloneKey(
ctx context.Context,
obj object,
keyType ftypes.CryptoKeyType,
) ([]ftypes.CryptoAsset, error) {
key, keyAlgorithm, err := crypto.DescribeKey(obj.publicKey, keyType)
switch {
case errors.Is(err, crypto.ErrNoCanonicalForm):
log.DebugContext(ctx, "Key not described", log.Err(err))
return nil, nil
case err != nil:
return nil, xerrors.Errorf("describe %s key: %w", keyType, err)
}
return []ftypes.CryptoAsset{
{
CryptoAssetInfo: key,
Format: obj.keyFormat,
Encoding: obj.encoding,
},
// The algorithm is derived and has no encoded form.
{CryptoAssetInfo: keyAlgorithm},
}, nil
}
// describeEncryptedPrivateKey describes an encrypted private key container. The container
// format selects the identification method, because each method digests a different
// canonical form.
func describeEncryptedPrivateKey(obj object) ([]ftypes.CryptoAsset, error) {
var method ftypes.CryptoIdentityMethod
switch obj.encryption {
case encryptionFormatPKCS8:
method = ftypes.CryptoMethodEncryptedPKCS8SHA256
case encryptionFormatRFC1423:
method = ftypes.CryptoMethodEncryptedRFC1423SHA256
default:
return nil, xerrors.Errorf("encryption format %d has no identification method", obj.encryption)
}
key := crypto.DescribeEncryptedKey(method, obj.encrypted, obj.keyFormat)
return []ftypes.CryptoAsset{{
CryptoAssetInfo: key,
Format: obj.keyFormat,
Encoding: obj.encoding,
}}, nil
}
// keyUsageBits lists every RFC 5280 key usage bit. The order is fixed so that a
// certificate always reports its usages in the same order.
var keyUsageBits = []stdx509.KeyUsage{
stdx509.KeyUsageDigitalSignature,
stdx509.KeyUsageContentCommitment,
stdx509.KeyUsageKeyEncipherment,
stdx509.KeyUsageDataEncipherment,
stdx509.KeyUsageKeyAgreement,
stdx509.KeyUsageCertSign,
stdx509.KeyUsageCRLSign,
stdx509.KeyUsageEncipherOnly,
stdx509.KeyUsageDecipherOnly,
}
// keyUsages names the bits set in usage. Each bit is named on its own because a
// combined mask is not a named constant.
func keyUsages(usage stdx509.KeyUsage) []string {
var usages []string
for _, bit := range keyUsageBits {
if usage&bit != 0 {
usages = append(usages, bit.String())
}
}
return usages
}
// extendedKeyUsages reports recognized usages by name and the rest by OID, because a
// usage defined outside RFC 5280 has no name to report.
func extendedKeyUsages(cert *stdx509.Certificate) []string {
usages := xslices.Map(cert.ExtKeyUsage, func(usage stdx509.ExtKeyUsage) string {
return usage.String()
})
unknown := xslices.Map(cert.UnknownExtKeyUsage, func(oid asn1.ObjectIdentifier) string {
return oid.String()
})
return append(usages, unknown...)
}
@@ -0,0 +1,96 @@
package x509
import (
stdx509 "crypto/x509"
"math/big"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
)
// TestObjectToAssetsInvariants covers the branches that report a broken invariant of this
// package. Parsing produces no object that reaches them, so they are covered here rather
// than through Parse.
func TestObjectToAssetsInvariants(t *testing.T) {
tests := []struct {
name string
object object
wantErr string
}{
{
name: "object kind without a description",
object: object{},
wantErr: "has no description",
},
{
name: "encrypted private key without a container format",
object: object{
kind: objectEncryptedPrivateKey,
keyFormat: ftypes.CryptoKeyFormatPKCS8,
},
wantErr: "has no identification method",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := objectToAssets(t.Context(), tt.object)
require.ErrorContains(t, err, tt.wantErr)
})
}
}
// TestObjectToAssetsWithUnknownKeyAlgorithm covers a certificate whose key is left out
// because crypto/x509 does not recognize its algorithm. The certificate keeps the rest of
// its description.
func TestObjectToAssetsWithUnknownKeyAlgorithm(t *testing.T) {
signatureAlgorithm := ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.113549.1.1.11",
},
Name: "RSA-PKCS1-1.5-SHA-256",
Algorithm: &ftypes.CryptoAlgorithm{
Family: "RSASSA-PKCS1",
Primitive: ftypes.CryptoPrimitiveSignature,
},
}
// crypto/x509 leaves PublicKey nil for a key algorithm it does not recognize.
obj := object{
kind: objectCertificate,
certificate: certificate{
Certificate: &stdx509.Certificate{SerialNumber: big.NewInt(1)},
signatureOID: "1.2.840.113549.1.1.11",
},
encoding: ftypes.CryptoEncodingPEM,
}
assets, err := objectToAssets(t.Context(), obj)
require.NoError(t, err)
// The certificate keeps the algorithm it is signed with and describes no key.
want := []ftypes.CryptoAsset{
{
CryptoAssetInfo: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindCertificate,
Identity: ftypes.DigestIdentity(ftypes.CryptoMethodSHA256, nil),
Certificate: &ftypes.CryptoCertificate{
SerialNumber: "1",
Format: ftypes.CryptoCertificateFormatX509,
},
Relationships: []ftypes.CryptoRelationship{{
Type: ftypes.CryptoRelationshipSignedWith,
RelatedAsset: signatureAlgorithm.Descriptor(),
}},
},
Encoding: ftypes.CryptoEncodingPEM,
},
{CryptoAssetInfo: signatureAlgorithm},
}
assert.Equal(t, want, assets)
}
+171 -126
View File
@@ -7,11 +7,9 @@ import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/sha256"
stdx509 "crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"errors"
@@ -19,46 +17,53 @@ import (
"github.com/aquasecurity/trivy/pkg/log"
)
// ObjectKind identifies the kind of parsed cryptographic object.
type ObjectKind uint8
// objectKind identifies the kind of parsed cryptographic object.
type objectKind uint8
const (
// ObjectCertificate identifies an X.509 certificate.
ObjectCertificate ObjectKind = iota + 1
// ObjectPrivateKey identifies a private key projected to its public key.
ObjectPrivateKey
// ObjectPublicKey identifies a public key.
ObjectPublicKey
// ObjectEncryptedPrivateKey identifies an opaque encrypted private key.
ObjectEncryptedPrivateKey
// objectCertificate identifies an X.509 certificate.
objectCertificate objectKind = iota + 1
// objectPrivateKey identifies a private key projected to its public key.
objectPrivateKey
// objectPublicKey identifies a public key.
objectPublicKey
// objectEncryptedPrivateKey identifies an opaque encrypted private key.
objectEncryptedPrivateKey
)
// EncryptionFormat identifies the container format of an encrypted private key.
type EncryptionFormat uint8
// encryptionFormat identifies the container format of an encrypted private key.
type encryptionFormat uint8
const (
// EncryptionFormatPKCS8 identifies an encrypted PKCS#8 container.
EncryptionFormatPKCS8 EncryptionFormat = iota + 1
// EncryptionFormatRFC1423 identifies an RFC 1423 encrypted PEM container.
EncryptionFormatRFC1423
// encryptionFormatPKCS8 identifies an encrypted PKCS#8 container.
encryptionFormatPKCS8 encryptionFormat = iota + 1
// encryptionFormatRFC1423 identifies an RFC 1423 encrypted PEM container.
encryptionFormatRFC1423
)
// Object is a safe projection of a parsed cryptographic object.
type Object struct {
// Kind identifies the parsed object kind.
Kind ObjectKind
// Certificate contains the parsed certificate for ObjectCertificate.
Certificate *stdx509.Certificate
// PublicKey contains a public key or the public projection of a private key.
PublicKey any
// EncryptedSHA256 contains the lowercase SHA-256 digest of an encrypted private-key container.
EncryptedSHA256 string
// EncryptionFormat identifies the encrypted private-key container format.
EncryptionFormat EncryptionFormat
// Encoding identifies the source encoding.
Encoding ftypes.CryptoEncoding
// KeyFormat identifies the source key container format.
KeyFormat ftypes.CryptoKeyFormat
// certificate is a parsed certificate together with the OID of the algorithm it is signed
// with, which crypto/x509 reports as an enumeration that does not carry it.
type certificate struct {
*stdx509.Certificate
signatureOID string
}
// object carries the material of a parsed cryptographic object from parsing to description.
type object struct {
// kind identifies the parsed object kind.
kind objectKind
// certificate contains the parsed certificate for objectCertificate.
certificate certificate
// publicKey contains a public key or the public projection of a private key.
publicKey any
// encrypted contains the canonical form an encrypted private-key container is identified by.
encrypted []byte
// encryption identifies the encrypted private-key container format.
encryption encryptionFormat
// encoding identifies the source encoding.
encoding ftypes.CryptoEncoding
// keyFormat identifies the source key container format.
keyFormat ftypes.CryptoKeyFormat
}
type encryptedPrivateKeyInfo struct {
@@ -72,11 +77,33 @@ var (
errMalformedCrypto = errors.New("malformed cryptographic object")
)
// Parse sniffs content because eligible extensions such as .crt, .cer, and .key do not reliably identify PEM or DER.
// It decodes PEM blocks first, then falls back to DER when no valid PEM block is found.
func Parse(ctx context.Context, filePath string, content []byte) []Object {
// Parse describes the cryptographic material a file carries as assets, each stating
// filePath and the container it was read from.
//
// Material that cannot be read is logged and skipped. An error means a parsed object
// could not be described.
func Parse(ctx context.Context, filePath string, content []byte) ([]ftypes.CryptoAsset, error) {
ctx = log.WithContextPrefix(ctx, "x509")
var objects []Object
ctx = log.WithContextAttrs(ctx, log.FilePath(filePath))
var assets []ftypes.CryptoAsset
for _, obj := range parse(ctx, content) {
described, err := objectToAssets(ctx, obj)
if err != nil {
return nil, err
}
for _, asset := range described {
asset.FilePath = filePath
assets = append(assets, asset)
}
}
return assets, nil
}
// parse sniffs content because eligible extensions such as .crt, .cer, and .key do not reliably identify PEM or DER.
// It decodes PEM blocks first, then falls back to DER when no valid PEM block is found.
func parse(ctx context.Context, content []byte) []object {
var objects []object
var decodedPEM, recognized bool
// pem.Decode scans past malformed leading data and returns the next valid block.
for rest := content; ; {
@@ -87,60 +114,60 @@ func Parse(ctx context.Context, filePath string, content []byte) []Object {
decodedPEM = true
rest = next
object, err := parsePEMBlock(block)
obj, err := parsePEMBlock(block)
if errors.Is(err, errNotCryptographic) {
continue
}
recognized = true
if err != nil {
logParseError(ctx, filePath, block.Type, err)
logParseError(ctx, block.Type, err)
continue
}
objects = append(objects, object)
objects = append(objects, obj)
}
// A decoded PEM file is complete even when none of its blocks is supported.
if decodedPEM {
if !recognized {
log.DebugContext(ctx, "No cryptographic object found", log.FilePath(filePath))
log.DebugContext(ctx, "No cryptographic object found")
}
return objects
}
// No PEM block was decoded, so try the whole file as DER.
object, err := parseDERObject(content)
obj, err := parseDERObject(content)
if err != nil {
logParseError(ctx, filePath, "", err)
logParseError(ctx, "", err)
return nil
}
object.Encoding = ftypes.CryptoEncodingDER
return []Object{object}
obj.encoding = ftypes.CryptoEncodingDER
return []object{obj}
}
// parsePEMBlock parses a supported PEM block and records its source encoding.
func parsePEMBlock(block *pem.Block) (Object, error) {
func parsePEMBlock(block *pem.Block) (object, error) {
if block.Headers["Proc-Type"] == "4,ENCRYPTED" || block.Headers["DEK-Info"] != "" {
object, err := parseRFC1423EncryptedPrivateKey(block)
obj, err := parseRFC1423EncryptedPrivateKey(block)
if err != nil {
return Object{}, err
return object{}, err
}
object.Encoding = ftypes.CryptoEncodingPEM
return object, nil
obj.encoding = ftypes.CryptoEncodingPEM
return obj, nil
}
object, err := parsePEMObject(block.Type, block.Bytes)
obj, err := parsePEMObject(block.Type, block.Bytes)
if err != nil {
return Object{}, err
return object{}, err
}
object.Encoding = ftypes.CryptoEncodingPEM
return object, nil
obj.encoding = ftypes.CryptoEncodingPEM
return obj, nil
}
// parseRFC1423EncryptedPrivateKey validates an encrypted PEM block and retains only its canonical digest.
func parseRFC1423EncryptedPrivateKey(block *pem.Block) (Object, error) {
// parseRFC1423EncryptedPrivateKey validates an encrypted PEM block and retains only its canonical form.
func parseRFC1423EncryptedPrivateKey(block *pem.Block) (object, error) {
if block.Headers["Proc-Type"] != "4,ENCRYPTED" || block.Headers["DEK-Info"] == "" || len(block.Bytes) == 0 {
return Object{}, errMalformedCrypto
return object{}, errMalformedCrypto
}
var keyFormat ftypes.CryptoKeyFormat
@@ -152,90 +179,84 @@ func parseRFC1423EncryptedPrivateKey(block *pem.Block) (Object, error) {
case "EC PRIVATE KEY":
keyFormat = ftypes.CryptoKeyFormatSEC1
default:
return Object{}, errUnsupportedCrypto
return object{}, errUnsupportedCrypto
}
// Re-encoding normalizes header order, line endings, and Base64 wrapping.
encoded := pem.EncodeToMemory(block)
if encoded == nil {
return Object{}, errMalformedCrypto
return object{}, errMalformedCrypto
}
digest := sha256.Sum256(encoded)
return Object{
Kind: ObjectEncryptedPrivateKey,
EncryptedSHA256: hex.EncodeToString(digest[:]),
EncryptionFormat: EncryptionFormatRFC1423,
KeyFormat: keyFormat,
return object{
kind: objectEncryptedPrivateKey,
encrypted: encoded,
encryption: encryptionFormatRFC1423,
keyFormat: keyFormat,
}, nil
}
func parsePEMObject(label string, der []byte) (Object, error) {
func parsePEMObject(label string, der []byte) (object, error) {
switch label {
case "CERTIFICATE":
certificate, err := stdx509.ParseCertificate(der)
if err != nil {
return Object{}, errMalformedCrypto
}
return Object{
Kind: ObjectCertificate,
Certificate: certificate,
}, nil
return certificateObject(der)
case "PRIVATE KEY":
privateKey, err := stdx509.ParsePKCS8PrivateKey(der)
if err != nil {
return Object{}, errMalformedCrypto
return object{}, errMalformedCrypto
}
return privateKeyToObject(privateKey, ftypes.CryptoKeyFormatPKCS8)
case "RSA PRIVATE KEY":
privateKey, err := stdx509.ParsePKCS1PrivateKey(der)
if err != nil {
return Object{}, errMalformedCrypto
return object{}, errMalformedCrypto
}
return privateKeyToObject(privateKey, ftypes.CryptoKeyFormatPKCS1)
case "EC PRIVATE KEY":
privateKey, err := stdx509.ParseECPrivateKey(der)
if err != nil {
return Object{}, errMalformedCrypto
return object{}, errMalformedCrypto
}
return privateKeyToObject(privateKey, ftypes.CryptoKeyFormatSEC1)
case "PUBLIC KEY":
publicKey, err := stdx509.ParsePKIXPublicKey(der)
if err != nil {
return Object{}, errMalformedCrypto
return object{}, errMalformedCrypto
}
return publicKeyToObject(publicKey)
case "ENCRYPTED PRIVATE KEY":
object, ok := parseEncryptedPKCS8(der)
obj, ok := parseEncryptedPKCS8(der)
if !ok {
return Object{}, errMalformedCrypto
return object{}, errMalformedCrypto
}
return object, nil
return obj, nil
case "CERTIFICATE REQUEST",
"NEW CERTIFICATE REQUEST",
"X509 CRL",
"OPENSSH PRIVATE KEY",
// TODO: describe this key as well. It holds a PKCS#1 public key, which
// x509.ParsePKCS1PublicKey reads.
"RSA PUBLIC KEY",
"DSA PRIVATE KEY",
"DSA PUBLIC KEY",
"EC PARAMETERS",
"DH PARAMETERS",
"DSA PARAMETERS",
// TODO: describe this certificate as well. It holds an X.509 certificate followed
// by the OpenSSL trust settings, so x509.ParseCertificate rejects the block as a
// whole and only the leading certificate is readable.
"TRUSTED CERTIFICATE",
"PKCS7",
"PKCS12":
return Object{}, errUnsupportedCrypto
return object{}, errUnsupportedCrypto
default:
return Object{}, errNotCryptographic
return object{}, errNotCryptographic
}
}
func parseDERObject(der []byte) (Object, error) {
func parseDERObject(der []byte) (object, error) {
// The target ASN.1 DER structures have no common outer discriminator, so try their schema-specific parsers in order.
if certificate, err := stdx509.ParseCertificate(der); err == nil {
return Object{
Kind: ObjectCertificate,
Certificate: certificate,
}, nil
if obj, err := certificateObject(der); err == nil {
return obj, nil
}
if privateKey, err := stdx509.ParsePKCS1PrivateKey(der); err == nil {
@@ -254,69 +275,93 @@ func parseDERObject(der []byte) (Object, error) {
return publicKeyToObject(publicKey)
}
if object, ok := parseEncryptedPKCS8(der); ok {
return object, nil
if obj, ok := parseEncryptedPKCS8(der); ok {
return obj, nil
}
if _, err := stdx509.ParseCertificateRequest(der); err == nil {
return Object{}, errUnsupportedCrypto
return object{}, errUnsupportedCrypto
}
if _, err := stdx509.ParseRevocationList(der); err == nil {
return Object{}, errUnsupportedCrypto
return object{}, errUnsupportedCrypto
}
var raw asn1.RawValue
rest, err := asn1.Unmarshal(der, &raw)
if err == nil && len(rest) == 0 && raw.Class == asn1.ClassUniversal && raw.Tag == asn1.TagSequence && raw.IsCompound {
return Object{}, errUnsupportedCrypto
return object{}, errUnsupportedCrypto
}
if len(der) > 0 && der[0] == byte(asn1.TagSequence)|0x20 {
return Object{}, errMalformedCrypto
return object{}, errMalformedCrypto
}
return Object{}, errNotCryptographic
return object{}, errNotCryptographic
}
// privateKeyToObject converts a private key to an Object containing its public projection.
func privateKeyToObject(privateKey any, format ftypes.CryptoKeyFormat) (Object, error) {
// certificateObject parses a certificate and reads the OID of its signature algorithm out
// of the encoded algorithm identifier.
func certificateObject(der []byte) (object, error) {
parsed, err := stdx509.ParseCertificate(der)
if err != nil {
return object{}, errMalformedCrypto
}
// The OID is read from the encoding because crypto/x509 reports the algorithm as an
// enumeration, and an algorithm it does not recognize collapses into a single unknown
// value.
var signature pkix.AlgorithmIdentifier
if _, err := asn1.Unmarshal(parsed.RawSignatureAlgorithm, &signature); err != nil {
return object{}, errMalformedCrypto
}
return object{
kind: objectCertificate,
certificate: certificate{
Certificate: parsed,
signatureOID: signature.Algorithm.String(),
},
}, nil
}
// privateKeyToObject converts a private key to an object containing its public projection.
func privateKeyToObject(privateKey any, format ftypes.CryptoKeyFormat) (object, error) {
signer, ok := privateKey.(stdcrypto.Signer)
if !ok {
return Object{}, errUnsupportedCrypto
return object{}, errUnsupportedCrypto
}
publicKey := signer.Public()
if !isSupportedPublicKey(publicKey) {
return Object{}, errUnsupportedCrypto
return object{}, errUnsupportedCrypto
}
return Object{
Kind: ObjectPrivateKey,
PublicKey: publicKey,
KeyFormat: format,
return object{
kind: objectPrivateKey,
publicKey: publicKey,
keyFormat: format,
}, nil
}
func publicKeyToObject(publicKey any) (Object, error) {
func publicKeyToObject(publicKey any) (object, error) {
if !isSupportedPublicKey(publicKey) {
return Object{}, errUnsupportedCrypto
return object{}, errUnsupportedCrypto
}
return Object{
Kind: ObjectPublicKey,
PublicKey: publicKey,
KeyFormat: ftypes.CryptoKeyFormatPKIX,
return object{
kind: objectPublicKey,
publicKey: publicKey,
keyFormat: ftypes.CryptoKeyFormatPKIX,
}, nil
}
// parseEncryptedPKCS8 validates only the opaque envelope and retains its digest.
func parseEncryptedPKCS8(der []byte) (Object, bool) {
// parseEncryptedPKCS8 validates only the opaque envelope and retains the DER it was read from.
func parseEncryptedPKCS8(der []byte) (object, bool) {
var encrypted encryptedPrivateKeyInfo
rest, err := asn1.Unmarshal(der, &encrypted)
if err != nil || len(rest) != 0 || len(encrypted.Algorithm.Algorithm) == 0 || len(encrypted.EncryptedData) == 0 {
return Object{}, false
return object{}, false
}
digest := sha256.Sum256(der)
return Object{
Kind: ObjectEncryptedPrivateKey,
EncryptedSHA256: hex.EncodeToString(digest[:]),
EncryptionFormat: EncryptionFormatPKCS8,
KeyFormat: ftypes.CryptoKeyFormatPKCS8,
return object{
kind: objectEncryptedPrivateKey,
encrypted: der,
encryption: encryptionFormatPKCS8,
keyFormat: ftypes.CryptoKeyFormatPKCS8,
}, true
}
@@ -329,18 +374,18 @@ func isSupportedPublicKey(key any) bool {
}
}
func logParseError(ctx context.Context, filePath, pemType string, err error) {
logger := log.With(log.FilePath(filePath))
func logParseError(ctx context.Context, pemType string, err error) {
var attrs []any
if pemType != "" {
logger = logger.With(log.String("pem_type", pemType))
attrs = append(attrs, log.String("pem_type", pemType))
}
switch {
case errors.Is(err, errUnsupportedCrypto):
logger.DebugContext(ctx, "Unsupported cryptographic object")
log.DebugContext(ctx, "Unsupported cryptographic object", attrs...)
case errors.Is(err, errMalformedCrypto):
logger.WarnContext(ctx, "Malformed cryptographic object")
log.WarnContext(ctx, "Malformed cryptographic object", attrs...)
default:
logger.DebugContext(ctx, "No cryptographic object found")
log.DebugContext(ctx, "No cryptographic object found", attrs...)
}
}
File diff suppressed because it is too large. Load diff
+68 -28
View File
@@ -1,6 +1,8 @@
package types
import (
"crypto/sha256"
"encoding/hex"
"slices"
"github.com/samber/lo"
@@ -42,6 +44,16 @@ type CryptoIdentity struct {
Parameters string `json:",omitempty"`
}
// DigestIdentity identifies material by the SHA-256 digest of its canonical form. The
// method states which form that is.
func DigestIdentity(method CryptoIdentityMethod, canonical []byte) CryptoIdentity {
digest := sha256.Sum256(canonical)
return CryptoIdentity{
Method: method,
Value: hex.EncodeToString(digest[:]),
}
}
// CryptoEncoding identifies the outer encoding of source cryptographic data.
type CryptoEncoding string
@@ -52,14 +64,13 @@ const (
CryptoEncodingDER CryptoEncoding = "DER"
)
// CryptoAsset describes a format-neutral cryptographic asset.
type CryptoAsset struct {
// CryptoAssetInfo describes a format-neutral cryptographic asset. Its identity is derived
// from the material itself, so material found in several places has one description.
type CryptoAssetInfo struct {
Kind CryptoKind `json:",omitempty"`
KeyType CryptoKeyType `json:",omitempty"`
Identity CryptoIdentity `json:",omitzero"`
Name string `json:",omitempty"`
FilePath string `json:",omitempty"`
Layer Layer `json:",omitzero"`
Certificate *CryptoCertificate `json:",omitempty"`
Key *CryptoKey `json:",omitempty"`
@@ -68,7 +79,7 @@ type CryptoAsset struct {
}
// Descriptor returns the comparable identity projected from the asset.
func (a *CryptoAsset) Descriptor() CryptoDescriptor {
func (a CryptoAssetInfo) Descriptor() CryptoDescriptor {
return CryptoDescriptor{
Kind: a.Kind,
KeyType: a.KeyType,
@@ -77,7 +88,7 @@ func (a *CryptoAsset) Descriptor() CryptoDescriptor {
}
// Validate checks the intrinsic asset invariants.
func (a *CryptoAsset) Validate() error {
func (a CryptoAssetInfo) Validate() error {
descriptor := a.Descriptor()
if err := descriptor.Validate(); err != nil {
return xerrors.Errorf("validate descriptor: %w", err)
@@ -123,9 +134,9 @@ func (a *CryptoAsset) Validate() error {
return nil
}
// Clone returns a deep copy of the asset.
func (a *CryptoAsset) Clone() CryptoAsset {
clone := *a
// Clone returns a deep copy of the description.
func (a CryptoAssetInfo) Clone() CryptoAssetInfo {
clone := a
clone.Relationships = slices.Clone(a.Relationships)
if a.Certificate != nil {
clone.Certificate = new(*a.Certificate)
@@ -145,15 +156,10 @@ func (a *CryptoAsset) Clone() CryptoAsset {
return clone
}
func (a *CryptoAsset) validateCertificate() error {
func (a CryptoAssetInfo) validateCertificate() error {
if a.Certificate.Format != CryptoCertificateFormatX509 {
return xerrors.Errorf("unknown certificate format %q", a.Certificate.Format)
}
switch a.Certificate.Encoding {
case "", CryptoEncodingPEM, CryptoEncodingDER:
default:
return xerrors.Errorf("unknown certificate encoding %q", a.Certificate.Encoding)
}
if a.Certificate.MaxPathLen < 0 {
return xerrors.Errorf("certificate path length must not be negative")
}
@@ -163,21 +169,10 @@ func (a *CryptoAsset) validateCertificate() error {
return nil
}
func (a *CryptoAsset) validateKey() error {
func (a CryptoAssetInfo) validateKey() error {
if a.Key.Size < 0 {
return xerrors.Errorf("key size must not be negative")
}
switch a.Key.Format {
case "", CryptoKeyFormatPKCS1, CryptoKeyFormatPKCS8, CryptoKeyFormatSEC1, CryptoKeyFormatPKIX:
default:
return xerrors.Errorf("unknown key format %q", a.Key.Format)
}
switch a.Key.Encoding {
case "", CryptoEncodingPEM, CryptoEncodingDER:
default:
return xerrors.Errorf("unknown key encoding %q", a.Key.Encoding)
}
encrypted := a.KeyType == CryptoKeyTypePrivate &&
(a.Identity.Method == CryptoMethodEncryptedPKCS8SHA256 || a.Identity.Method == CryptoMethodEncryptedRFC1423SHA256)
if a.Key.Encrypted != encrypted {
@@ -186,7 +181,7 @@ func (a *CryptoAsset) validateKey() error {
return nil
}
func (a *CryptoAsset) validateAlgorithm() error {
func (a CryptoAssetInfo) validateAlgorithm() error {
switch a.Algorithm.Primitive {
case CryptoPrimitiveUnknown, CryptoPrimitiveSignature, CryptoPrimitivePKE:
default:
@@ -194,3 +189,48 @@ func (a *CryptoAsset) validateAlgorithm() error {
}
return nil
}
// CryptoAsset is a described asset together with the file it was found in and the
// container it was stored in there.
type CryptoAsset struct {
CryptoAssetInfo
FilePath string `json:",omitempty"`
// Format is empty for a key with no container of its own, such as the key of a certificate.
Format CryptoKeyFormat `json:",omitempty"`
// Encoding is empty for a derived asset, such as an algorithm.
Encoding CryptoEncoding `json:",omitempty"`
// Layer is empty for a target that has no layers.
Layer Layer `json:",omitzero"`
}
// Validate checks the asset invariants together with those of its description.
func (a CryptoAsset) Validate() error {
if err := a.CryptoAssetInfo.Validate(); err != nil {
return xerrors.Errorf("validate description: %w", err)
}
switch a.Format {
case "", CryptoKeyFormatPKCS1, CryptoKeyFormatPKCS8, CryptoKeyFormatSEC1, CryptoKeyFormatPKIX:
default:
return xerrors.Errorf("unknown key container format %q", a.Format)
}
if a.Format != "" && a.Kind != CryptoKindKey {
return xerrors.Errorf("asset kind %q has no key container", a.Kind)
}
switch a.Encoding {
case "", CryptoEncodingPEM, CryptoEncodingDER:
default:
return xerrors.Errorf("unknown encoding %q", a.Encoding)
}
if a.Encoding != "" && a.Kind == CryptoKindAlgorithm {
return xerrors.Errorf("asset kind %q has no encoded form", a.Kind)
}
return nil
}
// Clone returns a deep copy of the asset.
func (a CryptoAsset) Clone() CryptoAsset {
a.CryptoAssetInfo = a.CryptoAssetInfo.Clone()
return a
}
+4 -6
View File
@@ -10,17 +10,15 @@ const (
CryptoCertificateFormatX509 CryptoCertificateFormat = "X.509"
)
// CryptoCertificate contains certificate-specific metadata. Format identifies
// the certificate structure, while Encoding identifies whether its source
// representation was PEM or DER.
// CryptoCertificate contains certificate-specific metadata.
type CryptoCertificate struct {
Subject string `json:",omitempty"`
Issuer string `json:",omitempty"`
Subject string `json:",omitempty"`
Issuer string `json:",omitempty"`
// SerialNumber is the serial number written in hexadecimal.
SerialNumber string `json:",omitempty"`
NotBefore time.Time `json:",omitzero"`
NotAfter time.Time `json:",omitzero"`
Format CryptoCertificateFormat `json:",omitempty"`
Encoding CryptoEncoding `json:",omitempty"`
KeyUsage []string `json:",omitempty"`
ExtendedKeyUsage []string `json:",omitempty"`
DNSNames []string `json:",omitempty"`
+13 -2
View File
@@ -196,19 +196,30 @@ func parseDescriptor(s string) (CryptoDescriptor, error) {
return descriptor, nil
}
// CryptoAlgorithmParameter names the property that distinguishes algorithm assets
// sharing one OID. It is empty for an algorithm whose OID identifies it completely.
type CryptoAlgorithmParameter string
const (
// CryptoParameterKeySize distinguishes algorithm assets by key size in bits.
CryptoParameterKeySize CryptoAlgorithmParameter = "key-size"
// CryptoParameterCurve distinguishes algorithm assets by curve name.
CryptoParameterCurve CryptoAlgorithmParameter = "curve"
)
// validateAlgorithmParameters accepts only empty parameters, key-size=<canonical positive
// decimal>, and curve=<non-empty name>.
func validateAlgorithmParameters(parameters string) error {
if parameters == "" {
return nil
}
if value, ok := strings.CutPrefix(parameters, "key-size="); ok {
if value, ok := strings.CutPrefix(parameters, string(CryptoParameterKeySize)+"="); ok {
if !isCanonicalPositiveDecimal(value) {
return xerrors.Errorf("key size parameter must be a canonical positive decimal")
}
return nil
}
if value, ok := strings.CutPrefix(parameters, "curve="); ok {
if value, ok := strings.CutPrefix(parameters, string(CryptoParameterCurve)+"="); ok {
if value == "" {
return xerrors.Errorf("curve parameter must not be empty")
}
+2 -8
View File
@@ -24,17 +24,11 @@ const (
CryptoKeyFormatPKIX CryptoKeyFormat = "PKIX"
)
// CryptoKey contains key-specific metadata.
// CryptoKey contains key-specific metadata. An encrypted container states only Encrypted,
// because its size and curve stay inside the ciphertext.
type CryptoKey struct {
Size int `json:",omitempty"`
Curve string `json:",omitempty"`
// Format identifies the source standalone key container. It is empty when
// the key is derived from an enclosing object, such as a certificate.
Format CryptoKeyFormat `json:",omitempty"`
// Encoding identifies the source standalone key encoding. It is empty when
// the key is derived from an enclosing object, such as a certificate.
Encoding CryptoEncoding `json:",omitempty"`
Encrypted bool `json:",omitempty"`
}
+39 -14
View File
@@ -20,6 +20,24 @@ func TestCryptoAlgorithmJSON(t *testing.T) {
assert.JSONEq(t, `{"Primitive":""}`, string(got))
}
// TestDigestIdentity checks the value against the SHA-256 vector published for "abc" in
// FIPS 180-2 appendix B.1, and against the canonical form Validate requires.
func TestDigestIdentity(t *testing.T) {
t.Parallel()
identity := types.DigestIdentity(types.CryptoMethodSHA256, []byte("abc"))
assert.Equal(t, types.CryptoIdentity{
Method: types.CryptoMethodSHA256,
Value: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
}, identity)
descriptor := types.CryptoDescriptor{
Kind: types.CryptoKindCertificate,
Identity: identity,
}
require.NoError(t, descriptor.Validate())
}
func TestCryptoAssetDescriptor(t *testing.T) {
t.Parallel()
@@ -70,7 +88,7 @@ func TestCryptoAssetValidate(t *testing.T) {
{
name: "DER certificate",
asset: cryptotest.CertificateAsset(cryptotest.WithMutate(func(a *types.CryptoAsset) {
a.Certificate.Encoding = types.CryptoEncodingDER
a.Encoding = types.CryptoEncodingDER
})),
wantErr: "",
},
@@ -97,8 +115,8 @@ func TestCryptoAssetValidate(t *testing.T) {
{
name: "derived public key without format or encoding",
asset: cryptotest.PublicKeyAsset(cryptotest.WithMutate(func(a *types.CryptoAsset) {
a.Key.Format = ""
a.Key.Encoding = ""
a.Format = ""
a.Encoding = ""
})),
wantErr: "",
},
@@ -196,25 +214,32 @@ func TestCryptoAssetValidate(t *testing.T) {
wantErr: `unknown certificate format "PEM"`,
},
{
name: "unknown certificate encoding",
name: "unknown encoding",
asset: cryptotest.CertificateAsset(cryptotest.WithMutate(func(a *types.CryptoAsset) {
a.Certificate.Encoding = "SSH"
a.Encoding = "SSH"
})),
wantErr: `unknown certificate encoding "SSH"`,
wantErr: `unknown encoding "SSH"`,
},
{
name: "unknown key format",
name: "unknown key container format",
asset: cryptotest.PublicKeyAsset(cryptotest.WithMutate(func(a *types.CryptoAsset) {
a.Key.Format = "OpenSSH"
a.Format = "OpenSSH"
})),
wantErr: `unknown key format "OpenSSH"`,
wantErr: `unknown key container format "OpenSSH"`,
},
{
name: "unknown key encoding",
asset: cryptotest.PublicKeyAsset(cryptotest.WithMutate(func(a *types.CryptoAsset) {
a.Key.Encoding = "SSH"
name: "key container format on a certificate",
asset: cryptotest.CertificateAsset(cryptotest.WithMutate(func(a *types.CryptoAsset) {
a.Format = types.CryptoKeyFormatPKCS8
})),
wantErr: `unknown key encoding "SSH"`,
wantErr: `asset kind "certificate" has no key container`,
},
{
name: "encoding on an algorithm",
asset: cryptotest.AlgorithmAsset(cryptotest.WithMutate(func(a *types.CryptoAsset) {
a.Encoding = types.CryptoEncodingPEM
})),
wantErr: `asset kind "algorithm" has no encoded form`,
},
{
name: "unknown primitive",
@@ -411,6 +436,6 @@ func TestCryptoAssetClone(t *testing.T) {
assert.Equal(t, source, clone)
clone.Algorithm.Family = "changed"
assert.Equal(t, "RSA", source.Algorithm.Family)
assert.Empty(t, source.Algorithm.Family)
})
}