feat(crypto): report private keys from PKCS#12 and JKS keystores (#11524)

This commit is contained in:
Nikita Pivkin authored and GitHub committed 2026-11-03 08:52:50 +00:00
1 parent 1d1ab074ed
commit d8890eeda0
17 files changed
+3252 -2446

No files matched your search

+6 -4
View File
@@ -22,9 +22,9 @@ Keystores are selected by the `.p12`, `.pfx`, `.jks` and `.keystore` extensions
| Material | Formats |
| --- | --- |
| X.509 certificates | PEM, DER, PKCS#12 and JKS keystores |
| Private keys | PKCS#1, PKCS#8, SEC1, in PEM or DER |
| Private keys | PKCS#1, PKCS#8, SEC1, in PEM or DER, or in PKCS#12 keystores |
| Public keys | PKIX, in PEM or DER |
| Encrypted private keys | PKCS#8 in PEM or DER, legacy encrypted PEM |
| Encrypted private keys | PKCS#8 in PEM or DER, legacy encrypted PEM, or in PKCS#12 and JKS keystores |
A single file may hold many objects. A certificate chain, a CA bundle of several hundred certificates, or a certificate stored next to its key are all read block by block, and an entry Trivy cannot read is skipped without discarding the rest of the file.
@@ -237,6 +237,8 @@ Some objects are recognized and skipped. Certificate signing requests, CRLs and
From certificates and keys on the curve P-192, only the `EC-P-192` algorithm is extracted.
Trivy does not decrypt PKCS#12 keystores and does not report their private keys, so it reads only the certificates stored without encryption. keytool, OpenSSL and .NET encrypt the certificates unless encryption is turned off explicitly, such as with `-certpbe NONE` in OpenSSL or `-J-Dkeystore.pkcs12.certProtectionAlgorithm=NONE` in keytool. OpenSSL encrypts them even with an empty password. The `cacerts` trust store that ships with JDK 18 and later has no password and is read in full. A PKCS#12 keystore protected by a public-key signature instead of a password-based MAC is not read. Parts of a keystore encoded in BER rather than DER are skipped. Trivy reads at most 10000 bags from one keystore.
Trivy does not decrypt PKCS#12 keystores and reads only what is stored without encryption. Private keys are usually stored this way, because keytool, OpenSSL and .NET encrypt each key separately and keep it out of the encrypted part. An encrypted key is reported without its algorithm, and a key stored in the clear, such as with `-keypbe NONE` in OpenSSL, is reported with it. The same tools encrypt certificates unless this is turned off, such as with `-J-Dkeystore.pkcs12.certProtectionAlgorithm=NONE` in keytool or `-certpbe NONE` in OpenSSL. OpenSSL encrypts them even with an empty password. The `cacerts` trust store of JDK 18 and later has no password, so all its certificates are reported.
A JKS keystore stores its certificates without encryption, so Trivy reads all of them, including the `cacerts` trust store of JDK 17 and earlier. Trivy does not decrypt JKS keystores and does not report private keys, but it reads the certificate chains associated with private key entries. Trivy reads at most 10000 certificates from one JKS keystore.
A PKCS#12 keystore protected by a public-key signature instead of a password-based MAC is not read. Parts of a keystore encoded in BER rather than DER are skipped. Trivy reads at most 10000 bags from one keystore.
A JKS keystore stores its certificates without encryption, so Trivy reads all of them, including the `cacerts` trust store of JDK 17 and earlier. Trivy does not decrypt JKS keystores, so a private key entry gives an encrypted key and the certificates of its chain. Trivy reads at most 10000 certificates and keys from one JKS keystore.
+2 -2
View File
@@ -334,7 +334,7 @@ func TestClientServer(t *testing.T) {
args: csArgs{
Format: types.FormatCycloneDX,
Scanners: []string{"crypto"},
Input: "testdata/fixtures/images/crypto-v2.tar.gz",
Input: "testdata/fixtures/images/crypto-v3.tar.gz",
},
golden: goldenCryptoCDX,
},
@@ -343,7 +343,7 @@ func TestClientServer(t *testing.T) {
args: csArgs{
Format: types.FormatJSON,
Scanners: []string{"crypto"},
Input: "testdata/fixtures/images/crypto-v2.tar.gz",
Input: "testdata/fixtures/images/crypto-v3.tar.gz",
},
golden: goldenCryptoJSON,
},
+2 -2
View File
@@ -404,7 +404,7 @@ func TestTar(t *testing.T) {
args: args{
Format: types.FormatCycloneDX,
Scanners: []string{"crypto"},
Input: "testdata/fixtures/images/crypto-v2.tar.gz",
Input: "testdata/fixtures/images/crypto-v3.tar.gz",
// Findings do not affect the exit code of CycloneDX output.
ExitCode: 1,
},
@@ -415,7 +415,7 @@ func TestTar(t *testing.T) {
args: args{
Format: types.FormatJSON,
Scanners: []string{"crypto"},
Input: "testdata/fixtures/images/crypto-v2.tar.gz",
Input: "testdata/fixtures/images/crypto-v3.tar.gz",
},
golden: goldenCryptoJSON,
},
File diff suppressed because it is too large. Load diff
+1846 -1489
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -1,4 +1,4 @@
package jks
// MaxCertificates exports maxCertificates for testing.
const MaxCertificates = maxCertificates
// MaxObjects exports maxObjects for testing.
const MaxObjects = maxObjects
+33 -23
View File
@@ -26,19 +26,19 @@ const (
tagTrustedCert = 2
)
// maxCertificates bounds the number of X.509 certificates read from one keystore. A real trust
// store holds a few hundred.
const maxCertificates = 10000
// maxObjects bounds the number of certificates and private keys read from one keystore. A real
// trust store holds a few hundred.
const maxObjects = 10000
const certificateTypeX509 = "X.509"
// ErrNotJKS means that the content is not a JKS file.
var ErrNotJKS = errors.New("not a JKS file")
// Parse describes the certificates of a JKS keystore as assets.
// Parse describes the certificates and encrypted private keys of a JKS keystore as assets.
//
// Content that is not a JKS file gives ErrNotJKS. Material that cannot be read is logged
// and skipped. Any other error means a parsed certificate could not be described.
// and skipped. Any other error means a parsed object could not be described.
func Parse(ctx context.Context, filePath string, content []byte) ([]ftypes.CryptoAsset, error) {
s := cryptobyte.String(content)
var m uint32
@@ -47,13 +47,13 @@ func Parse(ctx context.Context, filePath string, content []byte) ([]ftypes.Crypt
}
ctx = log.WithContextPrefix(ctx, "jks")
ctx = log.WithContextAttrs(ctx, log.FilePath(filePath))
return x509.ParseCertificates(ctx, filePath, certificates(ctx, s), ftypes.CryptoKeystoreJKS)
return x509.ParseKeystoreObjects(ctx, filePath, objects(ctx, s), ftypes.CryptoKeystoreJKS)
}
// certificates yields the DER of each trusted certificate and of each certificate in the
// chain of a private key.
func certificates(ctx context.Context, data []byte) iter.Seq[[]byte] {
return func(yield func([]byte) bool) {
// objects yields each trusted certificate, and each private key with the certificates of its
// chain.
func objects(ctx context.Context, data []byte) iter.Seq[x509.KeystoreObject] {
return func(yield func(x509.KeystoreObject) bool) {
s := cryptobyte.String(data)
var version, count uint32
if !s.ReadUint32(&version) || !s.ReadUint32(&count) {
@@ -65,14 +65,14 @@ func certificates(ctx context.Context, data []byte) iter.Seq[[]byte] {
return
}
budget := maxCertificates
next := func(der []byte) bool {
budget := maxObjects
next := func(obj x509.KeystoreObject) bool {
if budget == 0 {
log.WarnContext(ctx, "Too many JKS certificates")
log.WarnContext(ctx, "Too many JKS objects")
return false
}
budget--
return yield(der)
return yield(obj)
}
// An entry carries no length of its own, so the rest of the file is lost after a
@@ -102,14 +102,19 @@ func certificates(ctx context.Context, data []byte) iter.Seq[[]byte] {
}
}
// readPrivateKeyEntry skips the encrypted key of an entry and yields the certificates of
// its chain. It reports whether reading can continue.
func readPrivateKeyEntry(ctx context.Context, s *cryptobyte.String, version uint32, yield func([]byte) bool) bool {
var keyLen, chainLen uint32
if !s.ReadUint32(&keyLen) || !s.Skip(int(keyLen)) || !s.ReadUint32(&chainLen) {
// readPrivateKeyEntry yields the encrypted key of an entry and the certificates of its
// chain. It reports whether reading can continue.
func readPrivateKeyEntry(ctx context.Context, s *cryptobyte.String, version uint32, yield func(x509.KeystoreObject) bool) bool {
var chainLen uint32
var key []byte
if !readUint32LengthPrefixed(s, &key) || !s.ReadUint32(&chainLen) {
log.WarnContext(ctx, "Malformed JKS entry")
return false
}
// The key is an EncryptedPrivateKeyInfo with the algorithm of the JKS key protector.
if !yield(x509.KeystoreObject{Kind: x509.KeystoreEncryptedPrivateKey, DER: key}) {
return false
}
for range chainLen {
if !readCertificate(ctx, s, version, yield) {
return false
@@ -120,7 +125,7 @@ func readPrivateKeyEntry(ctx context.Context, s *cryptobyte.String, version uint
// readCertificate yields one certificate of an entry. It reports whether reading can
// continue.
func readCertificate(ctx context.Context, s *cryptobyte.String, version uint32, yield func([]byte) bool) bool {
func readCertificate(ctx context.Context, s *cryptobyte.String, version uint32, yield func(x509.KeystoreObject) bool) bool {
certType := certificateTypeX509
if version == version2 {
var t cryptobyte.String
@@ -131,9 +136,8 @@ func readCertificate(ctx context.Context, s *cryptobyte.String, version uint32,
certType = string(t)
}
var certLen uint32
var der []byte
if !s.ReadUint32(&certLen) || !s.ReadBytes(&der, int(certLen)) {
if !readUint32LengthPrefixed(s, &der) {
log.WarnContext(ctx, "Malformed JKS certificate")
return false
}
@@ -141,5 +145,11 @@ func readCertificate(ctx context.Context, s *cryptobyte.String, version uint32,
log.DebugContext(ctx, "Unsupported JKS certificate type", log.String("cert_type", certType))
return true
}
return yield(der)
return yield(x509.KeystoreObject{Kind: x509.KeystoreCertificate, DER: der})
}
// readUint32LengthPrefixed reads bytes prefixed with their 32-bit length.
func readUint32LengthPrefixed(s *cryptobyte.String, out *[]byte) bool {
var n uint32
return s.ReadUint32(&n) && s.ReadBytes(out, int(n))
}
+69 -17
View File
@@ -6,6 +6,7 @@ import (
"crypto/rand"
stdx509 "crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"math/big"
"os"
"path/filepath"
@@ -24,9 +25,23 @@ import (
// parsedFilePath is the path every keystore is parsed from.
const parsedFilePath = "keystore.jks"
// encryptedKeyName is the name of every encrypted private key.
const encryptedKeyName = "Encrypted PKCS#8 private key"
// oidKeyProtector identifies the algorithm of sun.security.provider.KeyProtector.
var oidKeyProtector = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 42, 2, 17, 1, 1}
// encryptedPrivateKeyInfo is a PKCS#8 EncryptedPrivateKeyInfo, as defined in RFC 5208.
type encryptedPrivateKeyInfo struct {
Algorithm pkix.AlgorithmIdentifier
EncryptedData []byte
}
func TestParse(t *testing.T) {
certificate := newCertificate(t, "example.test")
other := newCertificate(t, "other.example.test")
encryptedKey := newEncryptedKey(t, []byte{0x01})
otherEncryptedKey := newEncryptedKey(t, []byte{0x02})
// The last 30 bytes are the 20-byte integrity hash and the end of the second certificate.
truncated := keystore(2,
@@ -49,7 +64,7 @@ func TestParse(t *testing.T) {
{
name: "keytool keystore with a private key",
content: fixture(t, "keytool-keystore.jks"),
want: []string{"keytool-key.example.test"},
want: []string{encryptedKeyName, "keytool-key.example.test"},
},
{
name: "version 1",
@@ -58,16 +73,37 @@ func TestParse(t *testing.T) {
},
{
name: "private key with a chain",
content: keystore(2, privateKeyEntry(2, []byte{0x01}, certificate, other)),
want: []string{"example.test", "other.example.test"},
content: keystore(2, privateKeyEntry(2, encryptedKey, certificate, other)),
want: []string{encryptedKeyName, "example.test", "other.example.test"},
},
{
name: "repeated certificate",
content: keystore(2,
privateKeyEntry(2, []byte{0x01}, certificate),
privateKeyEntry(2, encryptedKey, certificate),
trustedCertEntry(2, "X.509", certificate),
),
want: []string{"example.test"},
want: []string{encryptedKeyName, "example.test"},
},
{
name: "repeated private key",
content: keystore(2,
privateKeyEntry(2, encryptedKey, certificate),
privateKeyEntry(2, encryptedKey, certificate),
),
want: []string{encryptedKeyName, "example.test"},
},
{
name: "two private keys",
content: keystore(2,
privateKeyEntry(2, encryptedKey, certificate),
privateKeyEntry(2, otherEncryptedKey, other),
),
want: []string{encryptedKeyName, "example.test", encryptedKeyName, "other.example.test"},
},
{
name: "malformed private key",
content: keystore(2, privateKeyEntry(2, []byte{0x01}, certificate)),
want: []string{"example.test"},
},
{
name: "certificate of another type",
@@ -120,20 +156,20 @@ func TestParse(t *testing.T) {
want: []string{"example.test"},
},
{
name: "certificates at the limit",
name: "objects at the limit",
content: keystore(2,
privateKeyEntry(2, []byte{0x01}, slices.Repeat([][]byte{certificate}, jks.MaxCertificates-1)...),
privateKeyEntry(2, encryptedKey, slices.Repeat([][]byte{certificate}, jks.MaxObjects-2)...),
trustedCertEntry(2, "X.509", other),
),
want: []string{"example.test", "other.example.test"},
want: []string{encryptedKeyName, "example.test", "other.example.test"},
},
{
name: "certificates over the limit",
name: "objects over the limit",
content: keystore(2,
privateKeyEntry(2, []byte{0x01}, slices.Repeat([][]byte{certificate}, jks.MaxCertificates)...),
privateKeyEntry(2, encryptedKey, slices.Repeat([][]byte{certificate}, jks.MaxObjects-1)...),
trustedCertEntry(2, "X.509", other),
),
want: []string{"example.test"},
want: []string{encryptedKeyName, "example.test"},
},
{
name: "JCEKS keystore",
@@ -154,24 +190,29 @@ func TestParse(t *testing.T) {
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, certificateNames(t, assets))
assert.Equal(t, tt.want, assetNames(t, assets))
})
}
}
// certificateNames checks that every asset is valid and returns the names of the
// certificates among them.
func certificateNames(t *testing.T, assets []ftypes.CryptoAsset) []string {
// assetNames checks that every asset is valid, and returns the names of the certificates and
// private keys among them.
func assetNames(t *testing.T, assets []ftypes.CryptoAsset) []string {
t.Helper()
var names []string
for i, asset := range assets {
require.NoErrorf(t, asset.Validate(), "asset %d", i)
assert.Equalf(t, parsedFilePath, asset.FilePath, "asset %d", i)
if asset.Kind != ftypes.CryptoKindCertificate {
switch {
case asset.Kind == ftypes.CryptoKindCertificate:
case asset.KeyType == ftypes.CryptoKeyTypePrivate:
// A JKS key is always encrypted.
assert.Truef(t, asset.Key.Encrypted, "asset %d", i)
assert.Equalf(t, ftypes.CryptoKeyFormatPKCS8, asset.Format, "asset %d", i)
default:
continue
}
assert.Equalf(t, ftypes.CryptoEncodingDER, asset.Encoding, "asset %d", i)
assert.Equalf(t, ftypes.CryptoKeystoreJKS, asset.Keystore, "asset %d", i)
names = append(names, asset.Name)
}
@@ -238,6 +279,17 @@ func privateKeyEntry(version uint32, encryptedKey []byte, chain ...[]byte) []byt
})
}
func newEncryptedKey(t *testing.T, data []byte) []byte {
t.Helper()
der, err := asn1.Marshal(encryptedPrivateKeyInfo{
Algorithm: pkix.AlgorithmIdentifier{Algorithm: oidKeyProtector},
EncryptedData: data,
})
require.NoError(t, err)
return der
}
// addCertificate writes a certificate, which states its type only in version 2.
func addCertificate(b *cryptobyte.Builder, version uint32, certType string, der []byte) {
if version == 2 {
+4
View File
@@ -24,6 +24,10 @@ var (
OIDEnvelopedDataContentType = oidEnvelopedDataContentType
// OIDEncryptedDataContentType exports oidEncryptedDataContentType for testing.
OIDEncryptedDataContentType = oidEncryptedDataContentType
// OIDKeyBag exports oidKeyBag for testing.
OIDKeyBag = oidKeyBag
// OIDPKCS8ShroudedKeyBag exports oidPKCS8ShroudedKeyBag for testing.
OIDPKCS8ShroudedKeyBag = oidPKCS8ShroudedKeyBag
// OIDCertBag exports oidCertBag for testing.
OIDCertBag = oidCertBag
// OIDSafeContentsBag exports oidSafeContentsBag for testing.
+27 -14
View File
@@ -28,8 +28,10 @@ var (
oidEnvelopedDataContentType = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 3}
oidEncryptedDataContentType = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 6}
oidCertBag = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 3}
oidSafeContentsBag = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 6}
oidKeyBag = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 1}
oidPKCS8ShroudedKeyBag = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 2}
oidCertBag = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 3}
oidSafeContentsBag = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 6}
oidX509Certificate = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 22, 1}
)
@@ -61,10 +63,11 @@ type certBag struct {
Data []byte `asn1:"tag:0,explicit"`
}
// Parse describes the unencrypted certificates of a PKCS#12 keystore as assets.
// Parse describes the certificates and private keys stored in the unencrypted contents of a
// PKCS#12 keystore as assets.
//
// Content that is not a PKCS#12 file in DER gives ErrNotPKCS12. Material that cannot be read
// is logged and skipped. Any other error means a parsed certificate could not be described.
// is logged and skipped. Any other error means a parsed object could not be described.
func Parse(ctx context.Context, filePath string, content []byte) ([]ftypes.CryptoAsset, error) {
var p pfx
if err := unmarshal(content, &p); err != nil || p.Version != 3 {
@@ -72,13 +75,13 @@ func Parse(ctx context.Context, filePath string, content []byte) ([]ftypes.Crypt
}
ctx = log.WithContextPrefix(ctx, "pkcs12")
ctx = log.WithContextAttrs(ctx, log.FilePath(filePath))
return x509.ParseCertificates(ctx, filePath, certificates(ctx, p), ftypes.CryptoKeystorePKCS12)
return x509.ParseKeystoreObjects(ctx, filePath, objects(ctx, p), ftypes.CryptoKeystorePKCS12)
}
// certificates yields the DER of each certificate stored in an unencrypted content of the
// objects yields each certificate and private key stored in an unencrypted content of the
// authenticated safe of p.
func certificates(ctx context.Context, p pfx) iter.Seq[[]byte] {
return func(yield func([]byte) bool) {
func objects(ctx context.Context, p pfx) iter.Seq[x509.KeystoreObject] {
return func(yield func(x509.KeystoreObject) bool) {
rest, ok := authenticatedSafe(ctx, p)
if !ok {
return
@@ -139,16 +142,16 @@ func authenticatedSafe(ctx context.Context, p pfx) ([]byte, bool) {
return contentInfos, true
}
// walker reads the certificates of one keystore and passes each to yield. The bags of the
// whole keystore share one budget.
// walker reads the objects of one keystore and passes each to yield. The bags of the whole
// keystore share one budget.
type walker struct {
ctx context.Context
budget int
yield func([]byte) bool
yield func(x509.KeystoreObject) bool
}
// walk yields the certificates of a safe contents structure and of the safe contents nested
// in it. It reports false when the walk has to stop, because yield asks to stop or the
// walk yields the objects of a safe contents structure and of the safe contents nested in
// it. It reports false when the walk has to stop, because yield asks to stop or the
// budget runs out.
func (w *walker) walk(der []byte, depth int) bool {
if depth > maxDepth {
@@ -182,7 +185,17 @@ func (w *walker) walk(der []byte, depth int) bool {
log.DebugContext(w.ctx, "Unsupported PKCS#12 certificate type", log.String("cert_type", cert.ID.String()))
continue
}
if !w.yield(cert.Data) {
if !w.yield(x509.KeystoreObject{Kind: x509.KeystoreCertificate, DER: cert.Data}) {
return false
}
case bag.ID.Equal(oidKeyBag):
if !w.yield(x509.KeystoreObject{Kind: x509.KeystorePrivateKey, DER: bag.Value.Bytes}) {
return false
}
case bag.ID.Equal(oidPKCS8ShroudedKeyBag):
// The bag holds an EncryptedPrivateKeyInfo, which stays in plain data content
// even when the certificates are encrypted.
if !w.yield(x509.KeystoreObject{Kind: x509.KeystoreEncryptedPrivateKey, DER: bag.Value.Bytes}) {
return false
}
case bag.ID.Equal(oidSafeContentsBag):
+107 -8
View File
@@ -25,14 +25,26 @@ import (
// parsedFilePath is the path every keystore is parsed from.
const parsedFilePath = "keystore.p12"
// encryptedKeyName is the name of every encrypted private key.
const encryptedKeyName = "Encrypted PKCS#8 private key"
var (
oidSecretBag = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 12, 10, 1, 5}
oidSDSICertificate = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 22, 2}
oidPBES2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 13}
)
// encryptedPrivateKeyInfo is a PKCS#8 EncryptedPrivateKeyInfo, as defined in RFC 5208.
type encryptedPrivateKeyInfo struct {
Algorithm pkix.AlgorithmIdentifier
EncryptedData []byte
}
func TestParse(t *testing.T) {
certificate := newCertificate(t, "example.test")
other := newCertificate(t, "other.example.test")
encryptedKey := newEncryptedKey(t, []byte{0x01})
otherEncryptedKey := newEncryptedKey(t, []byte{0x02})
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
@@ -52,7 +64,7 @@ func TestParse(t *testing.T) {
{
name: "OpenSSL keystore without a password",
content: fixture(t, "openssl-no-password.p12"),
want: []string{"openssl-leaf.example.test", "openssl-ca.example.test"},
want: []string{"openssl-leaf.example.test", "openssl-ca.example.test", "EC-P-256 private key"},
},
{
name: "keytool trust store without a password",
@@ -62,6 +74,7 @@ func TestParse(t *testing.T) {
{
name: "keytool keystore with a password",
content: fixture(t, "keytool-password.p12"),
want: []string{encryptedKeyName},
},
{
name: "certificate",
@@ -76,6 +89,62 @@ func TestParse(t *testing.T) {
),
want: []string{"example.test"},
},
{
name: "private key",
content: keystore(t, dataContent(t, safeContents(t,
newKeyBag(t, pkcs8Key),
newCertBag(t, pkcs12.OIDX509Certificate, certificate),
))),
want: []string{"EC-P-256 private key", "example.test"},
},
{
name: "repeated private key",
content: keystore(t,
dataContent(t, safeContents(t, newKeyBag(t, pkcs8Key))),
dataContent(t, safeContents(t, newKeyBag(t, pkcs8Key))),
),
want: []string{"EC-P-256 private key"},
},
{
name: "malformed private key",
content: keystore(t, dataContent(t, safeContents(t,
newKeyBag(t, marshal(t, 1)),
newCertBag(t, pkcs12.OIDX509Certificate, certificate),
))),
want: []string{"example.test"},
},
{
name: "encrypted private key",
content: keystore(t, dataContent(t, safeContents(t,
newShroudedKeyBag(t, encryptedKey),
newCertBag(t, pkcs12.OIDX509Certificate, certificate),
))),
want: []string{encryptedKeyName, "example.test"},
},
{
name: "repeated encrypted private key",
content: keystore(t,
dataContent(t, safeContents(t, newShroudedKeyBag(t, encryptedKey))),
dataContent(t, safeContents(t, newShroudedKeyBag(t, encryptedKey))),
),
want: []string{encryptedKeyName},
},
{
name: "two encrypted private keys",
content: keystore(t, dataContent(t, safeContents(t,
newShroudedKeyBag(t, encryptedKey),
newShroudedKeyBag(t, otherEncryptedKey),
))),
want: []string{encryptedKeyName, encryptedKeyName},
},
{
name: "malformed encrypted private key",
content: keystore(t, dataContent(t, safeContents(t,
newShroudedKeyBag(t, marshal(t, 1)),
newCertBag(t, pkcs12.OIDX509Certificate, certificate),
))),
want: []string{"example.test"},
},
{
name: "nested safe contents at the depth limit",
content: keystore(t, dataContent(t, safeContents(t,
@@ -257,25 +326,28 @@ func TestParse(t *testing.T) {
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, certificateNames(t, assets))
assert.Equal(t, tt.want, assetNames(t, assets))
})
}
}
// certificateNames checks that every asset is valid and not a private key, and returns the
// names of the certificates among them.
func certificateNames(t *testing.T, assets []ftypes.CryptoAsset) []string {
// assetNames checks that every asset is valid, and returns the names of the certificates and
// private keys among them.
func assetNames(t *testing.T, assets []ftypes.CryptoAsset) []string {
t.Helper()
var names []string
for i, asset := range assets {
require.NoErrorf(t, asset.Validate(), "asset %d", i)
assert.Equalf(t, parsedFilePath, asset.FilePath, "asset %d", i)
assert.NotEqualf(t, ftypes.CryptoKeyTypePrivate, asset.KeyType, "asset %d", i)
if asset.Kind != ftypes.CryptoKindCertificate {
switch {
case asset.Kind == ftypes.CryptoKindCertificate:
case asset.KeyType == ftypes.CryptoKeyTypePrivate:
assert.Equalf(t, asset.Name == encryptedKeyName, asset.Key.Encrypted, "asset %d", i)
assert.Equalf(t, ftypes.CryptoKeyFormatPKCS8, asset.Format, "asset %d", i)
default:
continue
}
assert.Equalf(t, ftypes.CryptoEncodingDER, asset.Encoding, "asset %d", i)
assert.Equalf(t, ftypes.CryptoKeystorePKCS12, asset.Keystore, "asset %d", i)
names = append(names, asset.Name)
}
@@ -347,6 +419,33 @@ func newCertBag(t *testing.T, certType asn1.ObjectIdentifier, der []byte) pkcs12
}
}
func newKeyBag(t *testing.T, der []byte) pkcs12.SafeBag {
t.Helper()
return pkcs12.SafeBag{
ID: pkcs12.OIDKeyBag,
Value: explicit(der),
}
}
func newShroudedKeyBag(t *testing.T, der []byte) pkcs12.SafeBag {
t.Helper()
return pkcs12.SafeBag{
ID: pkcs12.OIDPKCS8ShroudedKeyBag,
Value: explicit(der),
}
}
func newEncryptedKey(t *testing.T, data []byte) []byte {
t.Helper()
return marshal(t, encryptedPrivateKeyInfo{
Algorithm: pkix.AlgorithmIdentifier{Algorithm: oidPBES2},
EncryptedData: data,
})
}
func secretBags(t *testing.T, n int) []pkcs12.SafeBag {
t.Helper()
+2
View File
@@ -129,6 +129,7 @@ func describeStandaloneKey(obj object, keyType ftypes.CryptoKeyType) ([]ftypes.C
CryptoAssetInfo: key,
Format: obj.keyFormat,
Encoding: obj.encoding,
Keystore: obj.keystore,
},
// An algorithm has no format or encoding.
{CryptoAssetInfo: keyAlgorithm},
@@ -154,6 +155,7 @@ func describeEncryptedPrivateKey(obj object) ([]ftypes.CryptoAsset, error) {
CryptoAssetInfo: key,
Format: obj.keyFormat,
Encoding: obj.encoding,
Keystore: obj.keystore,
}}, nil
}
+74
View File
@@ -0,0 +1,74 @@
package x509
import (
"context"
"fmt"
"iter"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
)
// KeystoreObjectKind identifies the structure of a DER object read out of a keystore.
type KeystoreObjectKind uint8
const (
// KeystoreCertificate identifies an X.509 certificate.
KeystoreCertificate KeystoreObjectKind = iota + 1
// KeystorePrivateKey identifies a PKCS#8 PrivateKeyInfo.
KeystorePrivateKey
// KeystoreEncryptedPrivateKey identifies a PKCS#8 EncryptedPrivateKeyInfo.
KeystoreEncryptedPrivateKey
)
func (k KeystoreObjectKind) String() string {
switch k {
case KeystoreCertificate:
return "certificate"
case KeystorePrivateKey:
return "private key"
case KeystoreEncryptedPrivateKey:
return "encrypted private key"
default:
return fmt.Sprintf("KeystoreObjectKind(%d)", uint8(k))
}
}
// KeystoreObject is a DER object read out of a keystore.
type KeystoreObject struct {
Kind KeystoreObjectKind
DER []byte
}
// ParseKeystoreObjects describes DER objects stored in the given keystore as assets. An
// object that cannot be read is logged and skipped, and a repeated asset is reported once.
func ParseKeystoreObjects(ctx context.Context, filePath string, objects iter.Seq[KeystoreObject], keystore ftypes.CryptoKeystoreType) ([]ftypes.CryptoAsset, error) {
parsed := func(yield func(object) bool) {
for o := range objects {
obj, err := parseKeystoreObject(o)
if err != nil {
logParseError(ctx, err, log.String("keystore_object", o.Kind.String()))
continue
}
obj.encoding = ftypes.CryptoEncodingDER
obj.keystore = keystore
if !yield(obj) {
return
}
}
}
return describe(filePath, parsed)
}
func parseKeystoreObject(o KeystoreObject) (object, error) {
switch o.Kind {
case KeystoreCertificate:
return certificateObject(o.DER)
case KeystorePrivateKey:
return pkcs8PrivateKeyObject(o.DER)
case KeystoreEncryptedPrivateKey:
return encryptedPKCS8Object(o.DER)
default:
return object{}, errUnsupportedCrypto
}
}
+99
View File
@@ -0,0 +1,99 @@
package x509_test
import (
"crypto/x509/pkix"
"encoding/asn1"
"slices"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
cryptox509 "github.com/aquasecurity/trivy/pkg/crypto/parser/x509"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
)
func TestParseKeystoreObjects(t *testing.T) {
encryptedDER, err := asn1.Marshal(cryptox509.EncryptedPrivateKeyInfo{
Algorithm: pkix.AlgorithmIdentifier{Algorithm: oidPBES2},
EncryptedData: []byte{0x01, 0x02, 0x03},
})
require.NoError(t, err)
encryptedKey := ftypes.CryptoAsset{
CryptoAssetInfo: ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindKey,
KeyType: ftypes.CryptoKeyTypePrivate,
Identity: ftypes.DigestIdentity(ftypes.CryptoMethodEncryptedPKCS8SHA256, encryptedDER),
Name: "Encrypted PKCS#8 private key",
Key: &ftypes.CryptoKey{
Encrypted: true,
},
},
FilePath: parsedFilePath,
Format: ftypes.CryptoKeyFormatPKCS8,
Encoding: ftypes.CryptoEncodingDER,
Keystore: ftypes.CryptoKeystorePKCS12,
}
tests := []struct {
name string
objects []cryptox509.KeystoreObject
want []ftypes.CryptoAsset
}{
{
name: "encrypted private key",
objects: []cryptox509.KeystoreObject{
{Kind: cryptox509.KeystoreEncryptedPrivateKey, DER: encryptedDER},
},
want: []ftypes.CryptoAsset{encryptedKey},
},
{
// An algorithm belongs to no keystore.
name: "P-192 private key",
objects: []cryptox509.KeystoreObject{
{Kind: cryptox509.KeystorePrivateKey, DER: decodePEM(t, p192PKCS8PrivateKeyPEM)},
},
want: []ftypes.CryptoAsset{at(p192Algorithm)},
},
{
// An algorithm belongs to no keystore.
name: "P-192 certificate",
objects: []cryptox509.KeystoreObject{
{Kind: cryptox509.KeystoreCertificate, DER: decodePEM(t, p192CertificatePEM)},
},
want: []ftypes.CryptoAsset{at(p192Algorithm)},
},
{
name: "repeated object",
objects: []cryptox509.KeystoreObject{
{Kind: cryptox509.KeystoreEncryptedPrivateKey, DER: encryptedDER},
{Kind: cryptox509.KeystoreEncryptedPrivateKey, DER: encryptedDER},
},
want: []ftypes.CryptoAsset{encryptedKey},
},
{
name: "malformed object",
objects: []cryptox509.KeystoreObject{
{Kind: cryptox509.KeystorePrivateKey, DER: []byte{0x01}},
{Kind: cryptox509.KeystoreEncryptedPrivateKey, DER: encryptedDER},
},
want: []ftypes.CryptoAsset{encryptedKey},
},
{
name: "object without a kind",
objects: []cryptox509.KeystoreObject{
{DER: encryptedDER},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assets, err := cryptox509.ParseKeystoreObjects(t.Context(), parsedFilePath, slices.Values(tt.objects), ftypes.CryptoKeystorePKCS12)
require.NoError(t, err)
checkAssets(t, assets)
assert.Equal(t, tt.want, assets)
})
}
}
+9 -39
View File
@@ -174,27 +174,6 @@ func Parse(ctx context.Context, filePath string, content []byte) ([]ftypes.Crypt
return describe(filePath, parse(ctx, content))
}
// ParseCertificates describes DER certificates stored in the given keystore as assets. A
// certificate that cannot be read is logged and skipped, and a repeated certificate is
// reported once.
func ParseCertificates(ctx context.Context, filePath string, certificates iter.Seq[[]byte], keystore ftypes.CryptoKeystoreType) ([]ftypes.CryptoAsset, error) {
objects := func(yield func(object) bool) {
for der := range certificates {
obj, err := certificateObject(der)
if err != nil {
logParseError(ctx, "", err)
continue
}
obj.encoding = ftypes.CryptoEncodingDER
obj.keystore = keystore
if !yield(obj) {
return
}
}
}
return describe(filePath, objects)
}
// describe describes objects as assets found in filePath, reporting each asset once per
// container format.
func describe(filePath string, objects iter.Seq[object]) ([]ftypes.CryptoAsset, error) {
@@ -247,7 +226,7 @@ func parse(ctx context.Context, content []byte) iter.Seq[object] {
}
recognized = true
if err != nil {
logParseError(ctx, block.Type, err)
logParseError(ctx, err, log.String("pem_type", block.Type))
continue
}
if !yield(obj) {
@@ -266,7 +245,7 @@ func parse(ctx context.Context, content []byte) iter.Seq[object] {
// No PEM block was decoded, so try the whole file as DER.
obj, err := parseDERObject(content)
if err != nil {
logParseError(ctx, "", err)
logParseError(ctx, err)
return
}
obj.encoding = ftypes.CryptoEncodingDER
@@ -338,11 +317,7 @@ func parsePEMObject(label string, der []byte) (object, error) {
case "PUBLIC KEY":
return publicKeyObject(der)
case "ENCRYPTED PRIVATE KEY":
obj, ok := parseEncryptedPKCS8(der)
if !ok {
return object{}, errMalformedCrypto
}
return obj, nil
return encryptedPKCS8Object(der)
case "CERTIFICATE REQUEST",
"NEW CERTIFICATE REQUEST",
"X509 CRL",
@@ -551,7 +526,7 @@ func parseDERObject(der []byte) (object, error) {
return obj, nil
}
if obj, ok := parseEncryptedPKCS8(der); ok {
if obj, err := encryptedPKCS8Object(der); err == nil {
return obj, nil
}
@@ -671,19 +646,19 @@ func publicKeyObject(der []byte) (object, error) {
}, nil
}
// parseEncryptedPKCS8 validates only the opaque envelope and retains the DER it was read from.
func parseEncryptedPKCS8(der []byte) (object, bool) {
// encryptedPKCS8Object validates only the opaque envelope and retains the DER it was read from.
func encryptedPKCS8Object(der []byte) (object, error) {
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{}, errMalformedCrypto
}
return object{
kind: objectEncryptedPrivateKey,
encrypted: der,
encryption: encryptionFormatPKCS8,
keyFormat: ftypes.CryptoKeyFormatPKCS8,
}, true
}, nil
}
func isSupportedPublicKey(key any) bool {
@@ -695,12 +670,7 @@ func isSupportedPublicKey(key any) bool {
}
}
func logParseError(ctx context.Context, pemType string, err error) {
var attrs []any
if pemType != "" {
attrs = append(attrs, log.String("pem_type", pemType))
}
func logParseError(ctx context.Context, err error, attrs ...any) {
switch {
case errors.Is(err, errUnsupportedCrypto):
log.DebugContext(ctx, "Unsupported cryptographic object", attrs...)
+30 -23
View File
@@ -135,6 +135,20 @@ d4uUkKGsPSFY3xVCR5JmqacVJM/EssNZucY3
`
)
// p192Algorithm is the only asset described from P-192 material.
var p192Algorithm = ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.10045.2.1",
Parameters: "curve=P-192",
},
Name: "EC-P-192",
Algorithm: &ftypes.CryptoAlgorithm{
Primitive: ftypes.CryptoPrimitiveUnknown,
},
}
// rsaPrivateKeyDER encodes a structurally valid 2048-bit RSA key in PKCS#1 after applying
// mutate to it. Its values are not consistent with each other.
func rsaPrivateKeyDER(t *testing.T, mutate func(*cryptox509.PKCS1PrivateKey)) []byte {
@@ -701,18 +715,6 @@ func TestParseAssets(t *testing.T) {
Primitive: ftypes.CryptoPrimitiveUnknown,
},
}
p192Algorithm := ftypes.CryptoAssetInfo{
Kind: ftypes.CryptoKindAlgorithm,
Identity: ftypes.CryptoIdentity{
Method: ftypes.CryptoMethodOID,
Value: "1.2.840.10045.2.1",
Parameters: "curve=P-192",
},
Name: "EC-P-192",
Algorithm: &ftypes.CryptoAlgorithm{
Primitive: ftypes.CryptoPrimitiveUnknown,
},
}
var p192Certificate struct {
TBSCertificate asn1.RawValue
}
@@ -893,14 +895,6 @@ func TestParseAssets(t *testing.T) {
}},
}
// at states where a description was found.
at := func(info ftypes.CryptoAssetInfo) ftypes.CryptoAsset {
return ftypes.CryptoAsset{
CryptoAssetInfo: info,
FilePath: parsedFilePath,
}
}
tests := []struct {
name string
input []byte
@@ -1613,13 +1607,27 @@ func TestParseIdentity(t *testing.T) {
})
}
// parse describes a file and checks that every asset it reports is valid and relates only
// to assets reported with it.
// parse describes a file and checks the assets it reports.
func parse(t *testing.T, content []byte) []ftypes.CryptoAsset {
t.Helper()
assets, err := cryptox509.Parse(t.Context(), parsedFilePath, content)
require.NoError(t, err)
checkAssets(t, assets)
return assets
}
// at states where a description was found.
func at(info ftypes.CryptoAssetInfo) ftypes.CryptoAsset {
return ftypes.CryptoAsset{
CryptoAssetInfo: info,
FilePath: parsedFilePath,
}
}
// checkAssets checks that every asset is valid and relates only to assets reported with it.
func checkAssets(t *testing.T, assets []ftypes.CryptoAsset) {
t.Helper()
reported := set.New[ftypes.CryptoDescriptor]()
for i, asset := range assets {
@@ -1631,7 +1639,6 @@ func parse(t *testing.T, content []byte) []ftypes.CryptoAsset {
require.Truef(t, reported.Contains(relationship.RelatedAsset), "asset %d", i)
}
}
return assets
}
// recognized reduces assets to what the input was recognized as. Algorithm assets are left
+1 -1
View File
@@ -24,7 +24,7 @@ func init() {
}
const (
version = 5
version = 6
// maxFileSize bounds what is read into memory. The eligible extensions are shared with
// unrelated formats, such as Keynote presentations, which grow far beyond any file of