Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/key-weakness.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ Two failure classes, following the standard taxonomy (see the research survey th

`src/pubkey.cpp`, text-anchored like the secrets engine because that is how firmware carries keys:

- **X.509 certificates** — PEM `CERTIFICATE`, and a whole-file bare DER cert. The `SubjectPublicKeyInfo`
is located by trying each `tbsCertificate` child SEQUENCE (only the SPKI parses as one).
- **X.509 certificates** — PEM `CERTIFICATE` (and OpenSSL's `X509 CERTIFICATE` / `TRUSTED CERTIFICATE`),
a whole-file bare DER cert, and every certificate in a PKCS#7 / CMS bundle (PEM `PKCS7` / `CMS`, or DER
such as a `.p7b` or an APK `META-INF/*.RSA`). The `SubjectPublicKeyInfo` is located by trying each
`tbsCertificate` child SEQUENCE (only the SPKI parses as one).
- **Certificate requests** — the requested key in a PKCS#10 CSR (PEM `CERTIFICATE REQUEST` / `NEW
CERTIFICATE REQUEST`, or DER), labeled `certificate-request`.
- **OpenSSH public keys** — `ssh-rsa` / `ssh-ed25519` / `ssh-dss` / `ecdsa-sha2-*` lines in
`authorized_keys`, `*.pub`, `known_hosts`. Decoded from the SSH wire format (length-prefixed fields).
- **PEM/DER public keys** — a `SubjectPublicKeyInfo` or a bare PKCS#1 `RSAPublicKey`.
Expand Down
9 changes: 5 additions & 4 deletions src/boot.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -809,12 +809,13 @@ std::vector<Finding> scan_boot(const std::string& path, std::span<const uint8_t>
return base.size() >= s.size() &&
base.compare(base.size() - s.size(), s.size(), s) == 0;
};
std::vector<uint8_t> cert;
std::vector<std::vector<uint8_t>> certs;
if (ends(".RSA") || ends(".DSA") || ends(".EC"))
cert = cert_from_pkcs7(data);
certs = certs_in_pkcs7(data); // every cert: a chain need not list the signer first
else if (ends(".x509.pem") || ends(".crt") || ends(".cer") || ends(".der") || ends(".pem"))
cert = cert_from_any(data);
if (!cert.empty()) {
certs.push_back(cert_from_any(data));
for (const auto& cert : certs) {
if (cert.empty()) continue;
if (const KnownKey* kt = known_cert(cert_fingerprint(cert))) {
out.push_back(mk("apk-test-signing-cert", "high", std::string("cert = ") + kt->label,
std::string("code-signing certificate is a known test key; its "
Expand Down
48 changes: 37 additions & 11 deletions src/certid.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -100,22 +100,48 @@ std::vector<std::vector<uint8_t>> certs_in_efi_signature_list(std::span<const ui
return out;
}

std::vector<uint8_t> cert_from_pkcs7(std::span<const uint8_t> der) {
auto outer = der_at(der, 0);
if (!outer || outer->tag != 0x30) return {};
size_t i = outer->content;
while (i < outer->end) {
std::vector<std::vector<uint8_t>> certs_in_pkcs7(std::span<const uint8_t> der) {
// id-signedData, 1.2.840.113549.1.7.2
static constexpr uint8_t kOidSignedData[] = {0x2A, 0x86, 0x48, 0x86, 0xF7,
0x0D, 0x01, 0x07, 0x02};
std::vector<std::vector<uint8_t>> out;
auto sd = der_at(der, 0);
if (!sd || sd->tag != 0x30) return out;
auto first = der_at(der, sd->content);
if (!first || first->end > sd->end) return out;
if (first->tag == 0x06) {
// ContentInfo { contentType OID, content [0] EXPLICIT }: the standard
// form. Step into the SignedData. Any other content type (envelopedData,
// data, ...) carries no certificate set.
if (first->end - first->content != sizeof(kOidSignedData) ||
!std::equal(kOidSignedData, kOidSignedData + sizeof(kOidSignedData),
der.begin() + first->content))
return out;
auto wrap = der_at(der, first->end);
if (!wrap || wrap->tag != 0xA0 || wrap->end > sd->end) return out;
sd = der_at(der, wrap->content);
if (!sd || sd->tag != 0x30 || sd->end > wrap->end) return out;
} else if (first->tag != 0x02) {
return out; // a bare SignedData begins with its INTEGER version
}
// SignedData { version, digestAlgorithms, encapContentInfo,
// certificates [0] IMPLICIT OPTIONAL, crls [1], signerInfos }
for (size_t i = sd->content; i < sd->end;) {
auto node = der_at(der, i);
if (!node) break;
if (node->tag == 0xA0) { // certificates [0] IMPLICIT
auto cert = der_at(der, node->content);
if (cert && cert->tag == 0x30)
return std::vector<uint8_t>(der.begin() + node->content, der.begin() + cert->end);
if (!node || node->end > sd->end) break;
if (node->tag == 0xA0) {
for (size_t j = node->content; j < node->end && out.size() < 256;) {
auto cert = der_at(der, j);
if (!cert || cert->end > node->end) break;
if (cert->tag == 0x30) // a Certificate; other CHOICE arms are [n]
out.emplace_back(der.begin() + j, der.begin() + cert->end);
j = cert->end;
}
break;
}
i = node->end;
}
return {};
return out;
}

std::vector<uint8_t> cert_from_any(std::span<const uint8_t> data) {
Expand Down
12 changes: 8 additions & 4 deletions src/certid.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
// certificate out of the container a device ships it in, and fingerprint it the
// standard way (SHA-256 of the DER cert). Two containers:
// - UEFI EFI_SIGNATURE_LIST (PK/KEK/db variable data) -> each X.509 cert
// - PKCS#7 SignedData (an APK/OTA `*.RSA` signature block) -> the signer cert
// - PKCS#7 / CMS SignedData (an APK/OTA `*.RSA` signature block, a .p7b
// bundle) -> its certificates
// A raw DER/PEM certificate is handled directly. All parsing is a bounded DER
// TLV walk (no crypto dependency); SHA-256 is src/sha256.cpp.
#pragma once
Expand All @@ -24,9 +25,12 @@ std::string cert_fingerprint(std::span<const uint8_t> der_cert);
// as a UEFI PK/KEK/db variable stores). Returns copies of each cert's DER bytes.
std::vector<std::vector<uint8_t>> certs_in_efi_signature_list(std::span<const uint8_t> data);

// The first (signer) X.509 certificate in a DER PKCS#7 SignedData; empty if not
// a PKCS#7 or no certificate is present.
std::vector<uint8_t> cert_from_pkcs7(std::span<const uint8_t> der);
// Every X.509 certificate in a DER PKCS#7 / CMS SignedData: the standard
// ContentInfo-wrapped form (SEQ { OID signedData, [0] EXPLICIT SignedData }), as
// APK/JAR signature blocks, OTA signatures and .p7b bundles store it, or a bare
// SignedData. Returns copies of each cert's DER bytes; empty if not a SignedData
// or no certificate is present.
std::vector<std::vector<uint8_t>> certs_in_pkcs7(std::span<const uint8_t> der);

// If `data` is a PEM or bare-DER X.509 certificate, its DER bytes; else empty.
std::vector<uint8_t> cert_from_any(std::span<const uint8_t> data);
Expand Down
51 changes: 47 additions & 4 deletions src/pubkey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const char* origin_name(KeyOrigin o) {
case KeyOrigin::SshPublicKey: return "ssh-public-key";
case KeyOrigin::PublicKeyInfo: return "public-key";
case KeyOrigin::PrivateKey: return "private-key";
case KeyOrigin::CertificateRequest: return "certificate-request";
}
return "public-key";
}
Expand Down Expand Up @@ -169,20 +170,31 @@ bool parse_spki(std::span<const uint8_t> d, const Der& spki, PublicKey& k) {

// A DER X.509 certificate: SEQ { tbsCertificate SEQ {...}, sigAlg, sig }. Find the
// SubjectPublicKeyInfo inside tbs by trying each child SEQUENCE (issuer/subject are
// also SEQUENCEs, but only the SPKI parses as one). Fingerprint = SHA-256 of DER.
// also SEQUENCEs, but only the SPKI parses as one). Fingerprint = SHA-256 of the
// certificate's own DER, so bytes after it (a TRUSTED CERTIFICATE's trust settings)
// do not change it. A PKCS#10 request has the same outer shape, and its
// CertificationRequestInfo { INTEGER version, Name subject, SPKI, [0] } parses the
// same way. It is told apart by the Name (a SEQUENCE of SETs) after the leading
// INTEGER, where a v1 certificate's serial is followed by an AlgorithmIdentifier.
std::optional<PublicKey> parse_cert(std::span<const uint8_t> der) {
auto outer = der_at(der, 0);
if (!outer || outer->tag != 0x30) return std::nullopt;
auto tbs = der_at(der, outer->body);
if (!tbs || tbs->tag != 0x30) return std::nullopt;
bool request = false;
if (auto ver = der_at(der, tbs->body); ver && ver->tag == 0x02) {
auto name = der_at(der, ver->end);
auto rdn = name && name->len ? der_at(der, name->body) : std::nullopt;
request = name && name->tag == 0x30 && (name->len == 0 || (rdn && rdn->tag == 0x31));
}
for (size_t i = tbs->body; i < tbs->end;) {
auto child = der_at(der, i);
if (!child) break;
if (child->tag == 0x30) {
PublicKey k;
if (parse_spki(der, *child, k)) {
k.origin = KeyOrigin::Certificate;
k.fp_der = hexpre(der);
k.origin = request ? KeyOrigin::CertificateRequest : KeyOrigin::Certificate;
k.fp_der = hexpre(der.first(outer->end));
return k;
}
}
Expand Down Expand Up @@ -415,6 +427,19 @@ bool is_private_pem(const std::string& kind) {
return kind.find("PRIVATE KEY") != std::string::npos;
}

// A certificate, or a request carrying a key: RFC 7468 CERTIFICATE and CERTIFICATE
// REQUEST, plus OpenSSL's legacy X509 CERTIFICATE and NEW CERTIFICATE REQUEST, and
// its TRUSTED CERTIFICATE (a certificate followed by trust settings).
bool is_cert_pem(const std::string& kind) {
return kind == "CERTIFICATE" || kind == "TRUSTED CERTIFICATE" || kind == "X509 CERTIFICATE" ||
kind == "CERTIFICATE REQUEST" || kind == "NEW CERTIFICATE REQUEST";
}

// A PKCS#7 / CMS SignedData (a .p7b/.p7c certificate bundle, a signature).
bool is_pkcs7_pem(const std::string& kind) {
return kind == "PKCS7" || kind == "CMS" || kind == "PKCS #7 SIGNED DATA";
}

} // namespace

std::vector<PublicKey> extract_public_keys(std::span<const uint8_t> data) {
Expand All @@ -426,8 +451,18 @@ std::vector<PublicKey> extract_public_keys(std::span<const uint8_t> data) {

// 1. PEM blocks (certificates, public keys, private keys).
for (auto& pem : find_pem(text)) {
if (is_pkcs7_pem(pem.kind)) { // a bundle: every certificate in it
for (auto& der : certs_in_pkcs7(pem.der)) {
if (auto c = parse_cert(der)) {
c->offset = pem.offset;
set_label(*c);
out.push_back(std::move(*c));
}
}
continue;
}
std::optional<PublicKey> k;
if (pem.kind == "CERTIFICATE") {
if (is_cert_pem(pem.kind)) {
k = parse_cert(pem.der);
} else if (is_private_pem(pem.kind)) {
k = parse_priv_der(pem.der, pem.kind);
Expand Down Expand Up @@ -469,6 +504,14 @@ std::vector<PublicKey> extract_public_keys(std::span<const uint8_t> data) {
}
}

// 3b. Whole-buffer DER PKCS#7 / CMS (a .p7b bundle, an APK/JAR META-INF/*.RSA
// signature block): every certificate it carries.
if (!data.empty() && data[0] == 0x30) {
for (auto& der : certs_in_pkcs7(data)) {
if (auto k = parse_cert(der)) { set_label(*k); out.push_back(std::move(*k)); }
}
}

// 4. EFI_SIGNATURE_LIST wrapper (an extracted UEFI Secure Boot variable —
// PK/KEK/db): unwrap its X.509 certificates so their keys are analyzed too.
static const uint8_t kEfiCertX509[16] = {0xA1, 0x59, 0xC0, 0xA5, 0xE4, 0x94, 0xA7, 0x4A,
Expand Down
1 change: 1 addition & 0 deletions src/pubkey.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ enum class KeyOrigin : uint8_t {
SshPublicKey, // an OpenSSH-format public key line (authorized_keys / *.pub)
PublicKeyInfo, // a PEM/DER SubjectPublicKeyInfo or PKCS#1 RSA public key
PrivateKey, // the public half extracted from an embedded private key
CertificateRequest, // a PKCS#10 certificate signing request (PEM / DER)
};

const char* origin_name(KeyOrigin o);
Expand Down
33 changes: 33 additions & 0 deletions tests/test_boot.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,27 @@ def tlv(d, i):
return None


def _tlv(tag, body):
n = len(body)
ln = bytes([n]) if n < 0x80 else bytes([0x80 | ((n.bit_length() + 7) // 8)]) + \
n.to_bytes((n.bit_length() + 7) // 8, "big")
return bytes([tag]) + ln + body


def content_info_signed(signed_data):
"""Wrap a bare SignedData as ContentInfo { signedData, [0] EXPLICIT SignedData },
the on-disk form of an APK/JAR/OTA signature block (`openssl pkcs7 -inform DER`
reads only this form)."""
oid_signed_data = bytes.fromhex("06092a864886f70d010702") # 1.2.840.113549.1.7.2
return _tlv(0x30, oid_signed_data + _tlv(0xA0, signed_data))


def signed_data_with_certs(certs):
"""A certs-only SignedData { 1, {}, { data }, [0] certs, {} }."""
return _tlv(0x30, bytes.fromhex("020101" "3100" "300b06092a864886f70d010701") +
_tlv(0xA0, b"".join(certs)) + bytes.fromhex("3100"))


def efi_sig_list(cert):
sigsize = 16 + len(cert)
return X509GUID + struct.pack("<III", 28 + sigsize, 0, sigsize) + b"\x00" * 16 + cert
Expand Down Expand Up @@ -436,6 +457,18 @@ def check(cond, msg):
"apk: AOSP platform test cert (PEM) detected")
h = run("CERT.RSA", AMI_P7)
check("apk-test-signing-cert" in types(h), "apk: PKCS#7 signature block cert matched")
h = run("CERT.RSA", content_info_signed(AMI_P7))
check("apk-test-signing-cert" in types(h),
"apk: ContentInfo-wrapped PKCS#7 signature block (the on-disk form) cert matched")
# A block carrying a chain lists certificates in no fixed order (JAR blocks
# often put the CA first): the known cert is found when it is not first.
ami = _cert_from_p7(AMI_P7)
other = ami[:-1] + bytes([ami[-1] ^ 1]) # same shape, a fingerprint not in the corpus
h = run("CERT.RSA", content_info_signed(signed_data_with_certs([other, ami])))
check("apk-test-signing-cert" in types(h),
"apk: known cert matched when it is not the first in the signature block")
h = run("CERT.RSA", content_info_signed(signed_data_with_certs([other])))
check("apk-test-signing-cert" not in types(h), "apk: unknown cert alone is not flagged")

# --- AMI NVAR variable store (the format most vendor BIOSes use) ---
ami_cert = _cert_from_p7(AMI_P7)
Expand Down
Loading