feat(push-gateway): verify Android Key Attestation (#9562)

## What and why

Ticket 3 of the Android push plan ([design PR
#9555](https://github.com/block/buzz/pull/9555)). The gateway now
verifies Android Key Attestation at enrollment instead of rejecting
every Android chain, and rate limits signed installation calls per
attested key.

Stacked on [#9560](https://github.com/block/buzz/pull/9560) (Android
enrollment and FCM wakes). This PR's base is that branch; it will be
retargeted once that merges.

- **Chain.** It must end at a configured Google attestation root
(Google's [published hardware
roots](https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate)
are built in, pinned by public key), with valid signatures and issuer
links, CA issuers above the attestation key certificate, and no SHA-1
signatures. The attestation key certificate itself is exempt from the CA
flags, because some factory keyboxes issue it with CA:FALSE and
digitalSignature only (Google's Sony Xperia 10 III sample); a Keystore
leaf still cannot act as an issuer, since the extension is refused above
the leaf. Validity is enforced for Remote Key Provisioning chains;
Google tells verifiers to keep trusting the long-expired factory chains,
which the revocation list covers instead. The attestation extension must
be in the leaf and nowhere else. The leaf key must be EC P-256; it
becomes the installation's signing key.
- **KeyDescription.** Attestation and KeyMint security levels must be
TrustedEnvironment or StrongBox. The challenge must equal SHA-256 of the
enrollment transcript. Key properties (generated, EC, P-256, sign-only)
and the root of trust come only from the hardware-enforced list. The
bootloader must be locked, and the boot state Verified, or SelfSigned
with a verified boot key on an operator-configured list. The application
id (the one software-enforced value) must name exactly the configured
package with a configured signing digest.
- **Revocation.** A background task fetches Google's status list at
startup and then on its cache lifetime (5 minutes to 1 day), with a 30
second timeout, an 8 MiB size cap, capped exponential backoff and
jitter. Any REVOKED or SUSPENDED serial in the chain is rejected. With
no list yet, or a list older than the grace period, enrollment fails
closed. Enrollment reads an in-memory snapshot and never waits on a
fetch.
- **Rate limit.** Signed installation calls (delegate, revoke
delegation, rotate endpoint, revoke installation, on both platforms) are
limited per attested key. A call is counted only after its signature
verifies, so forged requests cannot spend another installation's
allowance. Counters are in memory per replica, bounded to 100,000 keys.
- **Dependencies.** None added. `x509-parser` gains its `verify-aws`
feature, which uses the `aws-lc-rs` the crate already depends on.

## Configuration

All optional; Android stays off unless the ticket 2 settings are
present. Documented in `docs/push-gateway-deployment.md` and
`.env.example` with example values only, and passed through
`deploy/charts/buzz-push-gateway` (disabled by default, schema-checked,
covered by `tests/runtime-options.sh`).

- `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS`: SHA-256 digests of verified boot
keys accepted with a SelfSigned boot state. Empty by default, so a
default gateway accepts stock Android only.
- `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH`: PEM bundle replacing the
built-in roots, for a reviewed root rollout. In the chart,
`android.attestationRoots.secretName` and `secretKey` mount it from a
Secret; an empty name keeps the built-in roots.
- `BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS`: default 604800 (7 days),
minimum 3600.
- `BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS` and
`BUZZ_PUSH_SIGNED_CALL_MAX_CALLS`: defaults 60 and 30.

## Tests

- `cargo test -p buzz-push-gateway` (all pass, 18 ignored), `cargo fmt
--all --check`, `cargo clippy -p buzz-push-gateway --all-targets -- -D
warnings`, and the chart tests (`render.sh`, `release-contract.sh`).
- Key Attestation chains are generated in the tests with a test root
injected as the configured root, and run through the production
verifier. One table rejects: unlocked bootloader, Unverified, Failed,
SelfSigned with an unlisted key, boot key only in the software list (two
variants), key properties only in the software list, extra key purposes,
wrong curve, wrong package, two packages, wrong signing digest, wrong
challenge, software-backed key (two variants), unknown root, forged leaf
signature, expired provisioned intermediate, extension repeated above
the leaf, non-P-256 leaf, a CA:FALSE certificate issuing the attestation
key certificate. Another accepts Verified with any boot key, SelfSigned
with a listed key, StrongBox and TrustedEnvironment, an expired factory
intermediate, and a CA:FALSE, digitalSignature attestation key
certificate. Revoked leaf, intermediate and root, a missing list and a
stale list are rejected. The status list parser and refresh (backoff,
cap, keeping the last list through failures) run against a scripted fake
source; no test touches the network.
- The per-key rate limit runs through the public router: forged calls do
not spend the allowance, the fourth authentic call is refused whatever
its kind, and another installation is unaffected.
- Break check: disabling the locked-bootloader guard and the rate limit
turned `rejected_attestations` and the rate limit test red; restored.

## Not here

The app side (ticket 7) generates the Keystore key and sends the chain.
The end to end run on a physical Android phone against a test gateway is
also still to do.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
This commit is contained in:
Tom Brow
2026-11-17 19:18:35 -08:00
committed by GitHub
parent b769d5bee8
commit 25b58ab98f
21 changed files with 2629 additions and 50 deletions

View File

@@ -102,6 +102,13 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns
# BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS=<64-hex-char SHA-256 of the app signing certificate>[,...]
# BUZZ_PUSH_FCM_PROJECT_ID=example-project
# BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH=/etc/buzz-push/fcm-service-account.json
# Optional Android attestation settings. Boot keys are SHA-256 digests of verified
# boot keys accepted with a self-signed boot state; empty accepts stock Android only.
# BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS=<64-hex-char digest>[,...]
# BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH=/etc/buzz-push/attestation-roots.pem
# BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS=604800
# BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS=60
# BUZZ_PUSH_SIGNED_CALL_MAX_CALLS=30
# -----------------------------------------------------------------------------
# Admin Dashboard (private moderation surface)

1
Cargo.lock generated
View File

@@ -12288,6 +12288,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
dependencies = [
"asn1-rs",
"aws-lc-rs",
"data-encoding",
"der-parser",
"lazy_static",

View File

@@ -26,7 +26,7 @@ minicbor = { version = "0.25", features = ["std", "half"] }
p256 = { version = "0.14", features = ["ecdsa"] }
rustls-pki-types = { version = "1", features = ["std"] }
webpki = { package = "rustls-webpki", version = "0.103.9", default-features = false, features = ["aws-lc-rs", "alloc"] }
x509-parser = { version = "0.18.1", default-features = false }
x509-parser = { version = "0.18.1", default-features = false, features = ["verify-aws"] }
axum = { workspace = true }
async-trait = "0.1"
base64 = "0.22"

View File

@@ -1,12 +1,22 @@
//! Android installation authentication: the Key Attestation seam used at
//! enrollment, and verification of the installation calls the attested Keystore
//! key signs afterward.
//! Android installation authentication: Key Attestation verification at
//! enrollment, and verification of the installation calls the attested
//! Keystore key signs afterward.
//!
//! Enrollment hands a certificate chain to an [`AndroidAttestationVerifier`].
//! The production verifier (Key Attestation chain validation) is a separate
//! change; until it exists the gateway starts with [`PendingAttestationVerifier`],
//! which rejects every chain. The test-only verifier below is compiled only
//! into test builds, so no configuration can select it.
//! Production uses [`KeyAttestationVerifier`]; the test-only verifier below is
//! compiled only into test builds, so no configuration can select it.
mod key_attestation;
mod key_description;
mod revocation;
pub use key_attestation::{
KeyAttestationPolicy, KeyAttestationVerifier, RootsError, GOOGLE_ROOTS_PEM,
};
pub use revocation::{
parse_status_list, refresh_once, run_refresh_loop, FetchError, HttpStatusListSource,
RevocationList, StatusDownload, StatusListSource, GOOGLE_STATUS_LIST_URL,
};
use base64::{engine::general_purpose::STANDARD, Engine as _};
use p256::ecdsa::{signature::Verifier, Signature, VerifyingKey};
@@ -40,25 +50,6 @@ pub trait AndroidAttestationVerifier: Send + Sync {
) -> Result<VerifiedAndroidKey, AndroidAttestationError>;
}
/// Rejects every chain. It stands in for the real verifier so that a gateway
/// configured for Android fails closed until Key Attestation verification ships.
pub struct PendingAttestationVerifier;
impl AndroidAttestationVerifier for PendingAttestationVerifier {
fn verify(
&self,
_: &[Vec<u8>],
_: &[u8],
) -> Result<VerifiedAndroidKey, AndroidAttestationError> {
tracing::warn!(
operation = "attestation",
reason = "unavailable",
"Android Key Attestation verification is not implemented in this build"
);
Err(AndroidAttestationError::Invalid)
}
}
/// Verify an installation call signed by the attested Keystore key: a base64
/// DER ECDSA P-256 signature over the same transcript bytes iOS signs. The
/// signature has no counter; replay protection is the single-use challenge

View File

@@ -0,0 +1,51 @@
# Google's published hardware attestation roots, from
# https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate
# (machine-readable list: https://android.googleapis.com/attestation/root).
# Verification pins each root's public key, so the older certificates Google
# lists as "previously issued" for the first key are covered by it.
# A change to this list is a reviewed rollout; operators can replace it with
# BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH.
-----BEGIN CERTIFICATE-----
MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw
NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7
174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC
W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G
tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx
oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG
1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF
mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
w1IdYIg2Wxg7yHcQZemFQg==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICIjCCAaigAwIBAgIRAISp0Cl7DrWK5/8OgN52BgUwCgYIKoZIzj0EAwMwUjEc
MBoGA1UEAwwTS2V5IEF0dGVzdGF0aW9uIENBMTEQMA4GA1UECwwHQW5kcm9pZDET
MBEGA1UECgwKR29vZ2xlIExMQzELMAkGA1UEBhMCVVMwHhcNMjUwNzE3MjIzMjE4
WhcNMzUwNzE1MjIzMjE4WjBSMRwwGgYDVQQDDBNLZXkgQXR0ZXN0YXRpb24gQ0Ex
MRAwDgYDVQQLDAdBbmRyb2lkMRMwEQYDVQQKDApHb29nbGUgTExDMQswCQYDVQQG
EwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABCPaI3FO3z5bBQo8cuiEas4HjqCt
G/mLFfRT0MsIssPBEEU5Cfbt6sH5yOAxqEi5QagpU1yX4HwnGb7OtBYpDTB57uH5
Eczm34A5FNijV3s0/f0UPl7zbJcTx6xwqMIRq6NCMEAwDwYDVR0TAQH/BAUwAwEB
/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFFIyuyz7RkOb3NaBqQ5lZuA0QepA
MAoGCCqGSM49BAMDA2gAMGUCMETfjPO/HwqReR2CS7p0ZWoD/LHs6hDi422opifH
EUaYLxwGlT9SLdjkVpz0UUOR5wIxAIoGyxGKRHVTpqpGRFiJtQEOOTp/+s1GcxeY
uR2zh/80lQyu9vAFCj6E4AXc+osmRg==
-----END CERTIFICATE-----

View File

@@ -0,0 +1,340 @@
//! The production Android Key Attestation verifier.
//!
//! Follows Google's verification guidance
//! (<https://developer.android.com/privacy-and-security/security-key-attestation>):
//! the chain must end at a pinned Google root, every signature must verify,
//! no certificate may be on the revocation list, and the attestation
//! extension is read only from the hardware-enforced list, except for the
//! application id, which the operating system writes into the
//! software-enforced list.
use std::sync::Arc;
use base64::{engine::general_purpose::STANDARD, Engine as _};
use p256::elliptic_curve::sec1::ToSec1Point;
use sha2::{Digest, Sha256};
use x509_parser::{certificate::X509Certificate, parse_x509_certificate, time::ASN1Time};
use super::{
key_description::{
self, KeyDescription, VerifiedBootState, KEY_DESCRIPTION_OID, STRONG_BOX,
TRUSTED_ENVIRONMENT,
},
revocation::{serial_key, RevocationList},
AndroidAttestationError, AndroidAttestationVerifier, VerifiedAndroidKey,
};
/// Google's published hardware attestation roots, pinned by public key.
pub const GOOGLE_ROOTS_PEM: &str = include_str!("google_roots.pem");
/// Present in certificates issued through Remote Key Provisioning. Their short
/// validity is part of the threat model, so it is enforced; the long-expired
/// factory chains Google tells verifiers to keep trusting have no such
/// extension and are covered by the revocation list instead.
const PROVISIONING_INFO_OID: &str = "1.3.6.1.4.1.11129.2.1.30";
const EC_PUBLIC_KEY_OID: &str = "1.2.840.10045.2.1";
const PRIME256V1_OID: &str = "1.2.840.10045.3.1.7";
const SHA1_SIGNATURE_OIDS: [&str; 3] =
["1.2.840.113549.1.1.5", "1.3.14.3.2.29", "1.2.840.10045.4.1"];
// Android `Algorithm`, `EcCurve`, `KeyOrigin` and `KeyPurpose` values.
const ALGORITHM_EC: u64 = 3;
const CURVE_P256: u64 = 1;
const ORIGIN_GENERATED: u64 = 0;
const PURPOSE_SIGN: u64 = 2;
/// What the app and the operator accept in an attestation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyAttestationPolicy {
/// The one package the attestation must name.
pub package_name: String,
/// Accepted SHA-256 digests of the app's signing certificate.
pub signing_cert_digests: Vec<[u8; 32]>,
/// Verified boot keys (SHA-256 digests) accepted with a SelfSigned boot
/// state. Empty accepts stock Android only.
pub boot_key_digests: Vec<[u8; 32]>,
}
/// A trust root or the verifier's setup was unusable.
#[derive(Debug, thiserror::Error)]
#[error("invalid Android attestation roots")]
pub struct RootsError;
/// Verifies Android Key Attestation chains offline against pinned roots and
/// the in-memory revocation list.
pub struct KeyAttestationVerifier {
/// SubjectPublicKeyInfo DER of each trusted root.
root_keys: Vec<Vec<u8>>,
policy: KeyAttestationPolicy,
revocations: Arc<RevocationList>,
now: fn() -> i64,
}
/// Split a PEM bundle into DER certificates. Text outside the blocks, such
/// as comments, is ignored.
fn pem_certificates(pem: &str) -> Result<Vec<Vec<u8>>, RootsError> {
const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
const END: &str = "-----END CERTIFICATE-----";
let mut out = Vec::new();
let mut rest = pem;
while let Some(start) = rest.find(BEGIN) {
let after = &rest[start + BEGIN.len()..];
let end = after.find(END).ok_or(RootsError)?;
let body: String = after[..end].split_whitespace().collect();
out.push(STANDARD.decode(body).map_err(|_| RootsError)?);
rest = &after[end + END.len()..];
}
if out.is_empty() {
return Err(RootsError);
}
Ok(out)
}
impl KeyAttestationVerifier {
/// Build a verifier that trusts the roots in `roots_pem`, usually
/// [`GOOGLE_ROOTS_PEM`].
pub fn new(
roots_pem: &str,
policy: KeyAttestationPolicy,
revocations: Arc<RevocationList>,
now: fn() -> i64,
) -> Result<Self, RootsError> {
let root_keys = pem_certificates(roots_pem)?
.iter()
.map(|der| {
let (rest, cert) = parse_x509_certificate(der).map_err(|_| RootsError)?;
rest.is_empty()
.then(|| cert.public_key().raw.to_vec())
.ok_or(RootsError)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
root_keys,
policy,
revocations,
now,
})
}
fn check(
&self,
chain: &[Vec<u8>],
client_data: &[u8],
) -> Result<VerifiedAndroidKey, &'static str> {
let now = (self.now)();
let certs = chain
.iter()
.map(|der| match parse_x509_certificate(der) {
Ok(([], cert)) => Ok(cert),
_ => Err("certificate_encoding"),
})
.collect::<Result<Vec<_>, _>>()?;
if certs.len() < 2 {
return Err("chain_too_short");
}
// RFC 5280 allows each extension once; a duplicate hides a second
// attestation extension from a first-match lookup.
for cert in &certs {
cert.extensions_map().map_err(|_| "certificate_encoding")?;
}
self.check_path(&certs, now)?;
let serials: Vec<String> = certs
.iter()
.map(|cert| serial_key(cert.raw_serial()))
.collect();
self.revocations
.check(&serials, now)
.map_err(|failure| match failure {
super::revocation::RevocationFailure::Unavailable => "revocation_list_unavailable",
super::revocation::RevocationFailure::Stale => "revocation_list_stale",
super::revocation::RevocationFailure::Listed => "certificate_revoked",
})?;
let description = attestation_extension(&certs)?;
self.check_description(&description, client_data)?;
Ok(VerifiedAndroidKey {
public_key: p256_public_key(&certs[0])?,
})
}
/// Pinned root, issuer links, signatures, CA flags and validity.
fn check_path(&self, certs: &[X509Certificate<'_>], now: i64) -> Result<(), &'static str> {
let root = certs.last().ok_or("chain_too_short")?;
if !self
.root_keys
.iter()
.any(|key| key.as_slice() == root.public_key().raw)
{
return Err("untrusted_root");
}
root.verify_signature(None).map_err(|_| "bad_signature")?;
for pair in certs.windows(2) {
let (cert, issuer) = (&pair[0], &pair[1]);
if cert.issuer() != issuer.subject() {
return Err("issuer_mismatch");
}
cert.verify_signature(Some(issuer.public_key()))
.map_err(|_| "bad_signature")?;
}
for cert in certs {
let algorithm = cert.signature_algorithm.algorithm.to_id_string();
if SHA1_SIGNATURE_OIDS.contains(&algorithm.as_str()) {
return Err("weak_signature");
}
}
// The attestation key certificate (`certs[1]`) is exempt: some factory
// keyboxes issue it with CA:FALSE and digitalSignature only (Google's
// Sony Xperia 10 III sample), and Google's validator never checks these
// flags. A Keystore leaf cannot stand in for it, because a
// KeyDescription above the leaf is refused.
for issuer in certs.iter().skip(2) {
let is_ca = matches!(issuer.basic_constraints(), Ok(Some(ext)) if ext.value.ca);
let may_sign = match issuer.key_usage() {
Ok(Some(usage)) => usage.value.key_cert_sign(),
Ok(None) => true,
Err(_) => false,
};
if !is_ca || !may_sign {
return Err("issuer_not_a_ca");
}
}
let provisioned = certs[1..]
.iter()
.any(|cert| has_extension(cert, PROVISIONING_INFO_OID));
if provisioned {
let at = ASN1Time::from_timestamp(now).map_err(|_| "clock")?;
if certs.iter().any(|cert| !cert.validity().is_valid_at(at)) {
return Err("certificate_expired");
}
}
Ok(())
}
fn check_description(
&self,
description: &KeyDescription,
client_data: &[u8],
) -> Result<(), &'static str> {
let hardware_level = |level: u64| level == TRUSTED_ENVIRONMENT || level == STRONG_BOX;
if !hardware_level(description.attestation_security_level)
|| !hardware_level(description.keymaster_security_level)
{
return Err("not_hardware_backed");
}
if description.challenge.as_slice() != Sha256::digest(client_data).as_slice() {
return Err("challenge_mismatch");
}
// Everything below comes from the hardware-enforced list only.
let hardware = &description.hardware;
if hardware.algorithm != Some(ALGORITHM_EC)
|| hardware.ec_curve != Some(CURVE_P256)
|| hardware.origin != Some(ORIGIN_GENERATED)
|| hardware.purposes.as_deref() != Some(&[PURPOSE_SIGN])
{
return Err("key_properties");
}
let root_of_trust = hardware.root_of_trust.as_ref().ok_or("no_root_of_trust")?;
if !root_of_trust.device_locked {
return Err("bootloader_unlocked");
}
match root_of_trust.verified_boot_state {
VerifiedBootState::Verified => {}
VerifiedBootState::SelfSigned => {
if !self
.policy
.boot_key_digests
.iter()
.any(|digest| digest.as_slice() == root_of_trust.verified_boot_key)
{
return Err("boot_key_not_accepted");
}
}
VerifiedBootState::Unverified | VerifiedBootState::Failed => {
return Err("boot_state_rejected")
}
}
let application = description
.application_id
.as_ref()
.ok_or("no_application_id")?;
match application.package_names.as_slice() {
[name] if name.as_slice() == self.policy.package_name.as_bytes() => {}
_ => return Err("package_mismatch"),
}
if !application.signature_digests.iter().any(|digest| {
self.policy
.signing_cert_digests
.iter()
.any(|accepted| accepted.as_slice() == digest.as_slice())
}) {
return Err("signing_digest_mismatch");
}
Ok(())
}
}
fn has_extension(cert: &X509Certificate<'_>, oid: &str) -> bool {
cert.extensions()
.iter()
.any(|extension| extension.oid.to_id_string() == oid)
}
/// The attestation extension must be in the leaf and nowhere else: a copy in
/// any other certificate was not issued by the secure hardware.
fn attestation_extension(certs: &[X509Certificate<'_>]) -> Result<KeyDescription, &'static str> {
if certs[1..]
.iter()
.any(|cert| has_extension(cert, KEY_DESCRIPTION_OID))
{
return Err("attestation_extension_misplaced");
}
// Uniqueness was checked with the whole chain's extension maps.
let extension = certs[0]
.extensions()
.iter()
.find(|extension| extension.oid.to_id_string() == KEY_DESCRIPTION_OID)
.ok_or("attestation_extension_missing")?;
key_description::parse(extension.value).ok_or("attestation_extension")
}
/// The leaf's key as an uncompressed SEC1 P-256 point.
fn p256_public_key(leaf: &X509Certificate<'_>) -> Result<Vec<u8>, &'static str> {
let spki = leaf.public_key();
let curve = spki
.algorithm
.parameters
.as_ref()
.and_then(|parameters| parameters.as_oid().ok())
.map(|oid| oid.to_id_string());
if spki.algorithm.algorithm.to_id_string() != EC_PUBLIC_KEY_OID
|| curve.as_deref() != Some(PRIME256V1_OID)
|| spki.subject_public_key.unused_bits != 0
{
return Err("leaf_key_not_p256");
}
let key = p256::PublicKey::from_sec1_bytes(spki.subject_public_key.data.as_ref())
.map_err(|_| "leaf_key_not_p256")?;
Ok(key.to_sec1_point(false).as_bytes().to_vec())
}
impl AndroidAttestationVerifier for KeyAttestationVerifier {
fn verify(
&self,
chain: &[Vec<u8>],
client_data: &[u8],
) -> Result<VerifiedAndroidKey, AndroidAttestationError> {
self.check(chain, client_data).map_err(|reason| {
tracing::warn!(
operation = "attestation",
platform = "android",
reason,
"Android Key Attestation rejected"
);
AndroidAttestationError::Invalid
})
}
}
#[cfg(test)]
#[path = "key_attestation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,890 @@
//! Key Attestation chains generated here, with a test root injected as the
//! configured root, run through the production verifier.
use super::*;
use crate::android_attestation::revocation::RevocationList;
use openssl::{
asn1::{Asn1Object, Asn1OctetString, Asn1Time},
bn::BigNum,
ec::{EcGroup, EcKey},
hash::MessageDigest,
nid::Nid,
pkey::{PKey, Private},
x509::{
extension::{BasicConstraints, KeyUsage},
X509Builder, X509Extension, X509NameBuilder, X509,
},
};
use std::collections::HashSet;
const NOW: i64 = 1_750_000_000;
const PACKAGE: &str = "com.example.buzz";
const DIGEST: [u8; 32] = [0xab; 32];
const BOOT_KEY: [u8; 32] = [0x11; 32];
const TRANSCRIPT: &[u8] = b"buzz.push.enroll.v1\n{\"challenge\":\"example\"}";
fn now() -> i64 {
NOW
}
// DER building blocks.
fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
let mut out = vec![tag];
match content.len() {
n if n < 0x80 => out.push(n as u8),
n if n < 0x100 => out.extend([0x81, n as u8]),
n => out.extend([0x82, (n >> 8) as u8, n as u8]),
}
out.extend_from_slice(content);
out
}
fn int(value: u64, tag: u8) -> Vec<u8> {
let mut bytes: Vec<u8> = value
.to_be_bytes()
.into_iter()
.skip_while(|b| *b == 0)
.collect();
if bytes.first().is_none_or(|b| b & 0x80 != 0) {
bytes.insert(0, 0);
}
tlv(tag, &bytes)
}
fn octets(bytes: &[u8]) -> Vec<u8> {
tlv(0x04, bytes)
}
/// An explicitly tagged, constructed context-specific field.
fn tagged(number: u32, content: &[u8]) -> Vec<u8> {
if number < 31 {
return tlv(0xa0 | number as u8, content);
}
let mut out = vec![0xbf, 0x80 | (number >> 7) as u8, (number & 0x7f) as u8];
let length = tlv(0, content);
out.extend_from_slice(&length[1..]);
out
}
/// One attestation as the device's secure hardware and operating system
/// would write it. `Default` is acceptable to a default gateway.
#[derive(Clone)]
struct Spec {
attestation_level: u64,
keymaster_level: u64,
/// Overrides the challenge, which is otherwise SHA-256 of the transcript.
challenge: Option<Vec<u8>>,
locked: bool,
boot_state: u64,
boot_key: Vec<u8>,
hardware_root_of_trust: bool,
/// A root of trust placed in the attacker-controlled software list.
software_root_of_trust: Option<(bool, u64, Vec<u8>)>,
hardware_key_properties: bool,
software_key_properties: bool,
purposes: Vec<u64>,
curve: u64,
packages: Vec<&'static str>,
digests: Vec<[u8; 32]>,
}
impl Default for Spec {
fn default() -> Self {
Self {
attestation_level: STRONG_BOX,
keymaster_level: STRONG_BOX,
challenge: None,
locked: true,
boot_state: 0,
boot_key: vec![0x77; 32],
hardware_root_of_trust: true,
software_root_of_trust: None,
hardware_key_properties: true,
software_key_properties: false,
purposes: vec![2],
curve: 1,
packages: vec![PACKAGE],
digests: vec![DIGEST],
}
}
}
fn root_of_trust(locked: bool, state: u64, key: &[u8]) -> Vec<u8> {
let body = [
octets(key),
tlv(0x01, &[if locked { 0xff } else { 0x00 }]),
int(state, 0x0a),
octets(&[0; 32]),
]
.concat();
tagged(704, &tlv(0x30, &body))
}
fn key_properties(spec: &Spec) -> Vec<u8> {
let purposes: Vec<u8> = spec.purposes.iter().flat_map(|p| int(*p, 0x02)).collect();
[
tagged(1, &tlv(0x31, &purposes)),
tagged(2, &int(3, 0x02)),
tagged(10, &int(spec.curve, 0x02)),
tagged(702, &int(0, 0x02)),
]
.concat()
}
fn key_description(spec: &Spec, transcript: &[u8]) -> Vec<u8> {
use sha2::{Digest, Sha256};
let challenge = spec
.challenge
.clone()
.unwrap_or_else(|| Sha256::digest(transcript).to_vec());
let packages: Vec<u8> = spec
.packages
.iter()
.flat_map(|name| tlv(0x30, &[octets(name.as_bytes()), int(1, 0x02)].concat()))
.collect();
let digests: Vec<u8> = spec.digests.iter().flat_map(|d| octets(d)).collect();
let application_id = tlv(0x30, &[tlv(0x31, &packages), tlv(0x31, &digests)].concat());
let mut software = Vec::new();
if spec.software_key_properties {
software.extend(key_properties(spec));
}
if let Some((locked, state, key)) = &spec.software_root_of_trust {
software.extend(root_of_trust(*locked, *state, key));
}
software.extend(tagged(709, &octets(&application_id)));
let mut hardware = Vec::new();
if spec.hardware_key_properties {
hardware.extend(key_properties(spec));
}
if spec.hardware_root_of_trust {
hardware.extend(root_of_trust(spec.locked, spec.boot_state, &spec.boot_key));
}
tlv(
0x30,
&[
int(300, 0x02),
int(spec.attestation_level, 0x0a),
int(300, 0x02),
int(spec.keymaster_level, 0x0a),
octets(&challenge),
octets(&[]),
tlv(0x30, &software),
tlv(0x30, &hardware),
]
.concat(),
)
}
/// How the certificate chain around the attestation is built.
#[derive(Clone, Default)]
struct Pki {
/// The intermediate expired before `NOW`.
expired_intermediate: bool,
/// The intermediate carries the Remote Key Provisioning extension.
provisioned: bool,
/// The chain ends at a root the gateway does not trust.
rogue_root: bool,
/// The leaf is signed by a key other than the intermediate's.
forged_leaf_signature: bool,
/// A copy of the attestation extension on the intermediate.
extension_on_intermediate: bool,
leaf_p384: bool,
/// The leaf certificate encodes its key as a compressed point.
leaf_compressed: bool,
/// The intermediate is CA:FALSE with digitalSignature only, as some
/// factory attestation key certificates are.
intermediate_not_ca: bool,
/// A CA:FALSE, digitalSignature certificate between the root and the
/// intermediate issues the intermediate.
non_ca_issues_intermediate: bool,
}
fn ec_key(nid: Nid) -> PKey<Private> {
PKey::from_ec_key(EcKey::generate(&EcGroup::from_curve_name(nid).unwrap()).unwrap()).unwrap()
}
fn name(common_name: &str) -> openssl::x509::X509Name {
let mut builder = X509NameBuilder::new().unwrap();
builder.append_entry_by_text("CN", common_name).unwrap();
builder.build()
}
struct Issuer<'a> {
name: &'a openssl::x509::X509NameRef,
key: &'a PKey<Private>,
}
fn certificate(
serial: u32,
subject: &str,
key: &PKey<Private>,
issuer: Option<Issuer<'_>>,
ca: bool,
not_after: &str,
extensions: Vec<X509Extension>,
) -> X509 {
let subject_name = name(subject);
let mut builder = X509Builder::new().unwrap();
builder.set_version(2).unwrap();
builder
.set_serial_number(&BigNum::from_u32(serial).unwrap().to_asn1_integer().unwrap())
.unwrap();
builder.set_subject_name(&subject_name).unwrap();
builder
.set_issuer_name(issuer.as_ref().map_or(&*subject_name, |i| i.name))
.unwrap();
builder.set_pubkey(key).unwrap();
builder
.set_not_before(&Asn1Time::from_str("20200101000000Z").unwrap())
.unwrap();
builder
.set_not_after(&Asn1Time::from_str(not_after).unwrap())
.unwrap();
if ca {
builder
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
.unwrap();
builder
.append_extension(KeyUsage::new().critical().key_cert_sign().build().unwrap())
.unwrap();
}
for extension in extensions {
builder.append_extension(extension).unwrap();
}
let signer = issuer.as_ref().map_or(key, |i| i.key);
let digest = match signer.ec_key().unwrap().group().curve_name() {
Some(Nid::SECP384R1) => MessageDigest::sha384(),
_ => MessageDigest::sha256(),
};
builder.sign(signer, digest).unwrap();
builder.build()
}
fn custom_extension(oid: &str, der: &[u8]) -> X509Extension {
X509Extension::new_from_der(
&Asn1Object::from_str(oid).unwrap(),
false,
&Asn1OctetString::new_from_bytes(der).unwrap(),
)
.unwrap()
}
/// A generated chain: DER certificates leaf first, and the trusted root.
struct Generated {
chain: Vec<Vec<u8>>,
root_pem: String,
}
const ROOT_SERIAL: u32 = 0x10;
const INTERMEDIATE_SERIAL: u32 = 0x20;
const LEAF_SERIAL: u32 = 0x30;
const UPPER_SERIAL: u32 = 0x40;
/// Basic constraints CA:FALSE and key usage digitalSignature only, the shape
/// of some factory attestation key certificates.
fn not_a_ca() -> Vec<X509Extension> {
vec![
BasicConstraints::new().critical().build().unwrap(),
KeyUsage::new()
.critical()
.digital_signature()
.build()
.unwrap(),
]
}
fn generate(spec: &Spec, pki: &Pki, transcript: &[u8]) -> Generated {
let trusted_root_key = ec_key(Nid::SECP384R1);
let trusted_root = certificate(
ROOT_SERIAL,
"Example Attestation Root",
&trusted_root_key,
None,
true,
"20400101000000Z",
vec![],
);
let (signing_root_key, signing_root) = if pki.rogue_root {
let key = ec_key(Nid::SECP384R1);
let cert = certificate(
ROOT_SERIAL,
"Example Attestation Root",
&key,
None,
true,
"20400101000000Z",
vec![],
);
(key, cert)
} else {
(trusted_root_key.clone(), trusted_root.clone())
};
let intermediate_key = ec_key(Nid::X9_62_PRIME256V1);
let mut intermediate_extensions = Vec::new();
if pki.provisioned {
intermediate_extensions.push(custom_extension(PROVISIONING_INFO_OID, &octets(&[1])));
}
if pki.intermediate_not_ca {
intermediate_extensions.extend(not_a_ca());
}
let upper_key = ec_key(Nid::X9_62_PRIME256V1);
let upper = pki.non_ca_issues_intermediate.then(|| {
certificate(
UPPER_SERIAL,
"Example Attestation Key Issuer",
&upper_key,
Some(Issuer {
name: signing_root.subject_name(),
key: &signing_root_key,
}),
false,
"20400101000000Z",
not_a_ca(),
)
});
let (intermediate_issuer_name, intermediate_issuer_key) = match &upper {
Some(upper) => (upper.subject_name(), &upper_key),
None => (signing_root.subject_name(), &signing_root_key),
};
let description = key_description(spec, transcript);
if pki.extension_on_intermediate {
intermediate_extensions.push(custom_extension(KEY_DESCRIPTION_OID, &description));
}
let intermediate = certificate(
INTERMEDIATE_SERIAL,
"Example Attestation Intermediate",
&intermediate_key,
Some(Issuer {
name: intermediate_issuer_name,
key: intermediate_issuer_key,
}),
!pki.intermediate_not_ca,
if pki.expired_intermediate {
"20210101000000Z"
} else {
"20400101000000Z"
},
intermediate_extensions,
);
let leaf_key = ec_key(if pki.leaf_p384 {
Nid::SECP384R1
} else {
Nid::X9_62_PRIME256V1
});
let leaf_key = if pki.leaf_compressed {
compressed(&leaf_key)
} else {
leaf_key
};
let other_signer = ec_key(Nid::X9_62_PRIME256V1);
let leaf = certificate(
LEAF_SERIAL,
"Example Attested Key",
&leaf_key,
Some(Issuer {
name: intermediate.subject_name(),
key: if pki.forged_leaf_signature {
&other_signer
} else {
&intermediate_key
},
}),
false,
"20400101000000Z",
vec![custom_extension(KEY_DESCRIPTION_OID, &description)],
);
Generated {
chain: [
Some(&leaf),
Some(&intermediate),
upper.as_ref(),
Some(&signing_root),
]
.into_iter()
.flatten()
.map(|cert| cert.to_der().unwrap())
.collect(),
root_pem: String::from_utf8(trusted_root.to_pem().unwrap()).unwrap(),
}
}
/// The same P-256 key, parsed from an ECPrivateKey that encodes its public
/// key as a compressed point, so a certificate built from it keeps that form.
fn compressed(key: &PKey<Private>) -> PKey<Private> {
let ec = key.ec_key().unwrap();
let mut context = openssl::bn::BigNumContext::new().unwrap();
let point = ec
.public_key()
.to_bytes(
ec.group(),
openssl::ec::PointConversionForm::COMPRESSED,
&mut context,
)
.unwrap();
// SEQUENCE { 1, OCTET STRING d, [0] prime256v1, [1] BIT STRING point }
let mut der = hex::decode("30570201010420").unwrap();
der.extend_from_slice(&ec.private_key().to_vec_padded(32).unwrap());
der.extend_from_slice(&hex::decode("a00a06082a8648ce3d030107a124032200").unwrap());
der.extend_from_slice(&point);
PKey::from_ec_key(EcKey::private_key_from_der(&der).unwrap()).unwrap()
}
fn fresh_list(revoked: &[u32]) -> Arc<RevocationList> {
let list = Arc::new(RevocationList::new(7 * 86_400));
list.replace(
revoked
.iter()
.map(|serial| serial_key(&serial.to_be_bytes()))
.collect::<HashSet<_>>(),
NOW,
);
list
}
fn policy() -> KeyAttestationPolicy {
KeyAttestationPolicy {
package_name: PACKAGE.into(),
signing_cert_digests: vec![[0xee; 32], DIGEST],
boot_key_digests: vec![BOOT_KEY],
}
}
fn verifier(
generated: &Generated,
policy: KeyAttestationPolicy,
list: Arc<RevocationList>,
) -> KeyAttestationVerifier {
KeyAttestationVerifier::new(&generated.root_pem, policy, list, now).unwrap()
}
fn verify_with(
spec: &Spec,
pki: &Pki,
policy: KeyAttestationPolicy,
list: Arc<RevocationList>,
) -> Result<VerifiedAndroidKey, &'static str> {
let generated = generate(spec, pki, TRANSCRIPT);
verifier(&generated, policy, list).check(&generated.chain, TRANSCRIPT)
}
fn verify(spec: &Spec, pki: &Pki) -> Result<VerifiedAndroidKey, &'static str> {
verify_with(spec, pki, policy(), fresh_list(&[]))
}
#[test]
fn accepted_attestations_prove_the_leaf_key() {
let self_signed = |key: &[u8]| Spec {
boot_state: 1,
boot_key: key.to_vec(),
..Spec::default()
};
for (row, spec, pki) in [
("verified, strongbox", Spec::default(), Pki::default()),
(
"verified, trusted environment",
Spec {
attestation_level: TRUSTED_ENVIRONMENT,
keymaster_level: TRUSTED_ENVIRONMENT,
..Spec::default()
},
Pki::default(),
),
(
"verified with an unlisted boot key",
Spec {
boot_key: vec![0x99; 32],
..Spec::default()
},
Pki::default(),
),
(
"self-signed with a listed key",
self_signed(&BOOT_KEY),
Pki::default(),
),
(
"second of several signing digests",
Spec {
digests: vec![[0x01; 32], DIGEST],
..Spec::default()
},
Pki::default(),
),
(
"expired factory-provisioned intermediate",
Spec::default(),
Pki {
expired_intermediate: true,
..Pki::default()
},
),
(
"current remote-provisioned intermediate",
Spec::default(),
Pki {
provisioned: true,
..Pki::default()
},
),
(
"factory attestation key certificate that is not a CA",
Spec::default(),
Pki {
intermediate_not_ca: true,
..Pki::default()
},
),
(
"software list claims a different boot state",
Spec {
software_root_of_trust: Some((false, 3, vec![0x55; 32])),
..Spec::default()
},
Pki::default(),
),
] {
let proven = verify(&spec, &pki).unwrap_or_else(|reason| panic!("{row}: {reason}"));
assert_eq!(proven.public_key.len(), 65, "{row}");
assert_eq!(proven.public_key[0], 4, "{row}");
}
}
/// The proven key is the leaf's key as an uncompressed point, however the
/// certificate encodes it, so one key always has one key id.
#[test]
fn the_proven_key_is_the_leaf_key() {
for (compressed, spki_len) in [(false, 91), (true, 59)] {
let pki = Pki {
leaf_compressed: compressed,
..Pki::default()
};
let generated = generate(&Spec::default(), &pki, TRANSCRIPT);
let proven = verifier(&generated, policy(), fresh_list(&[]))
.check(&generated.chain, TRANSCRIPT)
.unwrap();
let leaf = X509::from_der(&generated.chain[0]).unwrap();
let public = leaf.public_key().unwrap();
assert_eq!(public.public_key_to_der().unwrap().len(), spki_len);
let ec = public.ec_key().unwrap();
let mut context = openssl::bn::BigNumContext::new().unwrap();
let expected = ec
.public_key()
.to_bytes(
ec.group(),
openssl::ec::PointConversionForm::UNCOMPRESSED,
&mut context,
)
.unwrap();
assert_eq!(proven.public_key, expected, "compressed: {compressed}");
}
}
#[test]
fn rejected_attestations() {
let weak_boot = |locked: bool, state: u64, key: &[u8]| Spec {
locked,
boot_state: state,
boot_key: key.to_vec(),
..Spec::default()
};
let rows: Vec<(&str, Spec, Pki, &str)> = vec![
(
"unlocked bootloader",
weak_boot(false, 0, &[0x77; 32]),
Pki::default(),
"bootloader_unlocked",
),
(
"unlocked bootloader with a listed self-signed key",
weak_boot(false, 1, &BOOT_KEY),
Pki::default(),
"bootloader_unlocked",
),
(
"unverified",
weak_boot(true, 2, &BOOT_KEY),
Pki::default(),
"boot_state_rejected",
),
(
"failed",
weak_boot(true, 3, &BOOT_KEY),
Pki::default(),
"boot_state_rejected",
),
(
"self-signed with an unlisted key",
weak_boot(true, 1, &[0x42; 32]),
Pki::default(),
"boot_key_not_accepted",
),
(
"boot key only in the software list",
Spec {
hardware_root_of_trust: false,
software_root_of_trust: Some((true, 0, BOOT_KEY.to_vec())),
..Spec::default()
},
Pki::default(),
"no_root_of_trust",
),
(
"listed boot key only in the software list, hardware self-signed with another",
Spec {
boot_state: 1,
boot_key: vec![0x42; 32],
software_root_of_trust: Some((true, 1, BOOT_KEY.to_vec())),
..Spec::default()
},
Pki::default(),
"boot_key_not_accepted",
),
(
"key properties only in the software list",
Spec {
hardware_key_properties: false,
software_key_properties: true,
..Spec::default()
},
Pki::default(),
"key_properties",
),
(
"key usable for more than signing",
Spec {
purposes: vec![2, 3],
..Spec::default()
},
Pki::default(),
"key_properties",
),
(
"not a P-256 attested key",
Spec {
curve: 3,
..Spec::default()
},
Pki::default(),
"key_properties",
),
(
"wrong package",
Spec {
packages: vec!["com.example.other"],
..Spec::default()
},
Pki::default(),
"package_mismatch",
),
(
"two packages",
Spec {
packages: vec![PACKAGE, "com.example.other"],
..Spec::default()
},
Pki::default(),
"package_mismatch",
),
(
"wrong signing digest",
Spec {
digests: vec![[0x01; 32]],
..Spec::default()
},
Pki::default(),
"signing_digest_mismatch",
),
(
"wrong challenge",
Spec {
challenge: Some(vec![0; 32]),
..Spec::default()
},
Pki::default(),
"challenge_mismatch",
),
(
"software-backed key",
Spec {
attestation_level: 0,
keymaster_level: 0,
..Spec::default()
},
Pki::default(),
"not_hardware_backed",
),
(
"software-backed KeyMint behind a hardware attestation",
Spec {
keymaster_level: 0,
..Spec::default()
},
Pki::default(),
"not_hardware_backed",
),
(
"unknown root",
Spec::default(),
Pki {
rogue_root: true,
..Pki::default()
},
"untrusted_root",
),
(
"leaf not signed by its issuer",
Spec::default(),
Pki {
forged_leaf_signature: true,
..Pki::default()
},
"bad_signature",
),
(
"expired remote-provisioned intermediate",
Spec::default(),
Pki {
provisioned: true,
expired_intermediate: true,
..Pki::default()
},
"certificate_expired",
),
(
"attestation extension repeated above the leaf",
Spec::default(),
Pki {
extension_on_intermediate: true,
..Pki::default()
},
"attestation_extension_misplaced",
),
(
"issuer of the attestation key certificate is not a CA",
Spec::default(),
Pki {
non_ca_issues_intermediate: true,
..Pki::default()
},
"issuer_not_a_ca",
),
(
"leaf key is not P-256",
Spec::default(),
Pki {
leaf_p384: true,
..Pki::default()
},
"leaf_key_not_p256",
),
];
for (row, spec, pki, reason) in rows {
assert_eq!(verify(&spec, &pki).err(), Some(reason), "{row}");
}
}
#[test]
fn an_empty_boot_key_list_accepts_stock_android_only() {
let stock_only = KeyAttestationPolicy {
boot_key_digests: vec![],
..policy()
};
let self_signed = Spec {
boot_state: 1,
boot_key: BOOT_KEY.to_vec(),
..Spec::default()
};
assert_eq!(
verify_with(
&self_signed,
&Pki::default(),
stock_only.clone(),
fresh_list(&[])
)
.err(),
Some("boot_key_not_accepted")
);
assert!(verify_with(
&Spec::default(),
&Pki::default(),
stock_only,
fresh_list(&[])
)
.is_ok());
}
#[test]
fn listed_certificates_and_unusable_lists_are_rejected() {
for (row, serial) in [
("leaf", LEAF_SERIAL),
("intermediate", INTERMEDIATE_SERIAL),
("root", ROOT_SERIAL),
] {
assert_eq!(
verify_with(
&Spec::default(),
&Pki::default(),
policy(),
fresh_list(&[serial])
)
.err(),
Some("certificate_revoked"),
"{row}"
);
}
// A serial that is not in the chain does not matter.
assert!(verify_with(
&Spec::default(),
&Pki::default(),
policy(),
fresh_list(&[0x99])
)
.is_ok());
// No list yet: fail closed.
assert_eq!(
verify_with(
&Spec::default(),
&Pki::default(),
policy(),
Arc::new(RevocationList::new(86_400))
)
.err(),
Some("revocation_list_unavailable")
);
// A list older than its grace period: fail closed.
let stale = Arc::new(RevocationList::new(3600));
stale.replace(HashSet::new(), NOW - 3601);
assert_eq!(
verify_with(&Spec::default(), &Pki::default(), policy(), stale).err(),
Some("revocation_list_stale")
);
let within_grace = Arc::new(RevocationList::new(3600));
within_grace.replace(HashSet::new(), NOW - 3600);
assert!(verify_with(&Spec::default(), &Pki::default(), policy(), within_grace).is_ok());
}
#[test]
fn the_trait_rejects_without_saying_why() {
let generated = generate(&Spec::default(), &Pki::default(), TRANSCRIPT);
let verifier = verifier(&generated, policy(), fresh_list(&[]));
assert!(verifier.verify(&generated.chain, TRANSCRIPT).is_ok());
assert!(verifier
.verify(&generated.chain, b"another transcript")
.is_err());
assert!(verifier.verify(&[], TRANSCRIPT).is_err());
assert!(verifier.verify(&generated.chain[..1], TRANSCRIPT).is_err());
assert!(verifier
.verify(&vec![vec![0x30, 0x00]; 3], TRANSCRIPT)
.is_err());
}
#[test]
fn google_roots_load_and_pin_both_keys() {
let verifier = KeyAttestationVerifier::new(
GOOGLE_ROOTS_PEM,
policy(),
Arc::new(RevocationList::new(1)),
now,
)
.unwrap();
assert_eq!(verifier.root_keys.len(), 2);
assert!(
KeyAttestationVerifier::new("", policy(), Arc::new(RevocationList::new(1)), now).is_err()
);
}

View File

@@ -0,0 +1,321 @@
//! Parser for the Android Key Attestation extension (`KeyDescription`).
//!
//! Only the fields the gateway enforces are decoded. The software-enforced
//! list is attacker-controlled on a compromised device, so the parser exposes
//! the hardware-enforced properties and the application id separately and the
//! caller never has to choose between them.
/// OID of the Key Attestation extension, 1.3.6.1.4.1.11129.2.1.17.
pub(super) const KEY_DESCRIPTION_OID: &str = "1.3.6.1.4.1.11129.2.1.17";
/// Android `SecurityLevel`.
pub(super) const TRUSTED_ENVIRONMENT: u64 = 1;
/// Android `SecurityLevel`.
pub(super) const STRONG_BOX: u64 = 2;
const TAG_PURPOSE: u32 = 1;
const TAG_ALGORITHM: u32 = 2;
const TAG_EC_CURVE: u32 = 10;
const TAG_ORIGIN: u32 = 702;
const TAG_ROOT_OF_TRUST: u32 = 704;
const TAG_APPLICATION_ID: u32 = 709;
const UNIVERSAL_INTEGER: u8 = 0x02;
const UNIVERSAL_OCTET_STRING: u8 = 0x04;
const UNIVERSAL_BOOLEAN: u8 = 0x01;
const UNIVERSAL_ENUMERATED: u8 = 0x0a;
const UNIVERSAL_SEQUENCE: u8 = 0x30;
const UNIVERSAL_SET: u8 = 0x31;
/// One decoded DER element.
#[derive(Clone, Copy)]
struct Tlv<'a> {
/// First identifier octet for universal tags, otherwise the class and
/// constructed bits with the tag number in `number`.
class_byte: u8,
number: u32,
content: &'a [u8],
}
/// Read one definite-length DER element and return it with the remainder.
fn read(input: &[u8]) -> Option<(Tlv<'_>, &[u8])> {
let (&first, rest) = input.split_first()?;
let mut number = u32::from(first & 0x1f);
let mut rest = rest;
if number == 0x1f {
// High tag number form: base-128, minimal, at most 3 octets.
number = 0;
for index in 0..3 {
let (&octet, tail) = rest.split_first()?;
rest = tail;
if index == 0 && octet == 0x80 {
return None;
}
number = (number << 7) | u32::from(octet & 0x7f);
if octet & 0x80 == 0 {
break;
}
if index == 2 {
return None;
}
}
if number < 0x1f {
return None;
}
}
let (&length_octet, rest) = rest.split_first()?;
let (length, rest) = if length_octet < 0x80 {
(usize::from(length_octet), rest)
} else {
let count = usize::from(length_octet & 0x7f);
// Indefinite lengths and lengths wider than 3 octets are not DER we accept.
if count == 0 || count > 3 || rest.len() < count || rest[0] == 0 {
return None;
}
let length = rest[..count]
.iter()
.fold(0usize, |acc, octet| (acc << 8) | usize::from(*octet));
if length < 0x80 {
return None;
}
(length, &rest[count..])
};
if rest.len() < length {
return None;
}
let (content, tail) = rest.split_at(length);
Some((
Tlv {
class_byte: first & 0xe0,
number,
content,
},
tail,
))
}
/// Read one element that must be universal and carry `tag` as its full
/// identifier octet, such as `0x30` for SEQUENCE.
fn read_universal(input: &[u8], tag: u8) -> Option<(&[u8], &[u8])> {
let (&first, _) = input.split_first()?;
if first != tag {
return None;
}
let (tlv, rest) = read(input)?;
Some((tlv.content, rest))
}
fn small_unsigned(content: &[u8]) -> Option<u64> {
// Non-negative, minimal, and small enough for every field we read.
match content {
[] => None,
[first, ..] if *first & 0x80 != 0 || content.len() > 8 => None,
[0, second, ..] if *second & 0x80 == 0 => None,
_ => Some(
content
.iter()
.fold(0u64, |acc, b| (acc << 8) | u64::from(*b)),
),
}
}
fn read_integer(input: &[u8], tag: u8) -> Option<(u64, &[u8])> {
let (content, rest) = read_universal(input, tag)?;
Some((small_unsigned(content)?, rest))
}
/// Boot state reported in the hardware-enforced `RootOfTrust`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum VerifiedBootState {
Verified,
SelfSigned,
Unverified,
Failed,
}
/// The hardware-enforced `RootOfTrust`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct RootOfTrust {
pub verified_boot_key: Vec<u8>,
pub device_locked: bool,
pub verified_boot_state: VerifiedBootState,
}
/// The fields of the hardware-enforced authorization list the gateway checks.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(super) struct HardwareEnforced {
pub purposes: Option<Vec<u64>>,
pub algorithm: Option<u64>,
pub ec_curve: Option<u64>,
pub origin: Option<u64>,
pub root_of_trust: Option<RootOfTrust>,
}
/// The package and signing digests the operating system recorded for the app.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct ApplicationId {
pub package_names: Vec<Vec<u8>>,
pub signature_digests: Vec<Vec<u8>>,
}
/// A decoded `KeyDescription`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct KeyDescription {
pub attestation_security_level: u64,
pub keymaster_security_level: u64,
pub challenge: Vec<u8>,
pub hardware: HardwareEnforced,
/// Read from the software-enforced list: the operating system fills it in.
pub application_id: Option<ApplicationId>,
}
/// Decode a `KeyDescription` from the extension's value. Returns `None` for
/// anything malformed, including trailing bytes and duplicate fields.
pub(super) fn parse(extension_value: &[u8]) -> Option<KeyDescription> {
let (body, rest) = read_universal(extension_value, UNIVERSAL_SEQUENCE)?;
if !rest.is_empty() {
return None;
}
let (_version, body) = read_integer(body, UNIVERSAL_INTEGER)?;
let (attestation_security_level, body) = read_integer(body, UNIVERSAL_ENUMERATED)?;
let (_keymaster_version, body) = read_integer(body, UNIVERSAL_INTEGER)?;
let (keymaster_security_level, body) = read_integer(body, UNIVERSAL_ENUMERATED)?;
let (challenge, body) = read_universal(body, UNIVERSAL_OCTET_STRING)?;
let (_unique_id, body) = read_universal(body, UNIVERSAL_OCTET_STRING)?;
let (software, body) = read_universal(body, UNIVERSAL_SEQUENCE)?;
let (hardware, body) = read_universal(body, UNIVERSAL_SEQUENCE)?;
if !body.is_empty() {
return None;
}
Some(KeyDescription {
attestation_security_level,
keymaster_security_level,
challenge: challenge.to_vec(),
hardware: parse_hardware(hardware)?,
application_id: parse_software_application_id(software)?,
})
}
/// Iterate an authorization list's explicitly tagged fields, failing on a
/// malformed element or a repeated tag.
fn fields(list: &[u8]) -> Option<Vec<(u32, &[u8])>> {
let mut out: Vec<(u32, &[u8])> = Vec::new();
let mut rest = list;
while !rest.is_empty() {
let (tlv, tail) = read(rest)?;
// Context-specific, constructed (explicit tagging).
if tlv.class_byte != 0xa0 || out.iter().any(|(number, _)| *number == tlv.number) {
return None;
}
out.push((tlv.number, tlv.content));
rest = tail;
}
Some(out)
}
fn explicit_integer(content: &[u8]) -> Option<u64> {
let (value, rest) = read_integer(content, UNIVERSAL_INTEGER)?;
rest.is_empty().then_some(value)
}
fn parse_hardware(list: &[u8]) -> Option<HardwareEnforced> {
let mut out = HardwareEnforced::default();
for (number, content) in fields(list)? {
match number {
TAG_PURPOSE => {
let (set, rest) = read_universal(content, UNIVERSAL_SET)?;
if !rest.is_empty() {
return None;
}
let mut purposes = Vec::new();
let mut items = set;
while !items.is_empty() {
let (value, tail) = read_integer(items, UNIVERSAL_INTEGER)?;
purposes.push(value);
items = tail;
}
out.purposes = Some(purposes);
}
TAG_ALGORITHM => out.algorithm = Some(explicit_integer(content)?),
TAG_EC_CURVE => out.ec_curve = Some(explicit_integer(content)?),
TAG_ORIGIN => out.origin = Some(explicit_integer(content)?),
TAG_ROOT_OF_TRUST => out.root_of_trust = Some(parse_root_of_trust(content)?),
_ => {}
}
}
Some(out)
}
fn parse_root_of_trust(content: &[u8]) -> Option<RootOfTrust> {
let (body, rest) = read_universal(content, UNIVERSAL_SEQUENCE)?;
if !rest.is_empty() {
return None;
}
let (key, body) = read_universal(body, UNIVERSAL_OCTET_STRING)?;
let (locked, body) = read_universal(body, UNIVERSAL_BOOLEAN)?;
let device_locked = match locked {
[0x00] => false,
[0xff] => true,
_ => return None,
};
let (state, _hash_and_extensions) = read_integer(body, UNIVERSAL_ENUMERATED)?;
let verified_boot_state = match state {
0 => VerifiedBootState::Verified,
1 => VerifiedBootState::SelfSigned,
2 => VerifiedBootState::Unverified,
3 => VerifiedBootState::Failed,
_ => return None,
};
Some(RootOfTrust {
verified_boot_key: key.to_vec(),
device_locked,
verified_boot_state,
})
}
/// `Some(None)` when the software list has no application id, `None` when it
/// is malformed.
fn parse_software_application_id(list: &[u8]) -> Option<Option<ApplicationId>> {
let Some((_, content)) = fields(list)?
.into_iter()
.find(|(number, _)| *number == TAG_APPLICATION_ID)
else {
return Some(None);
};
let (octets, rest) = read_universal(content, UNIVERSAL_OCTET_STRING)?;
if !rest.is_empty() {
return None;
}
let (body, rest) = read_universal(octets, UNIVERSAL_SEQUENCE)?;
if !rest.is_empty() {
return None;
}
let (packages, body) = read_universal(body, UNIVERSAL_SET)?;
let (digests, body) = read_universal(body, UNIVERSAL_SET)?;
if !body.is_empty() {
return None;
}
let mut package_names = Vec::new();
let mut items = packages;
while !items.is_empty() {
let (info, tail) = read_universal(items, UNIVERSAL_SEQUENCE)?;
let (name, info_rest) = read_universal(info, UNIVERSAL_OCTET_STRING)?;
let (_version, info_rest) = read_integer(info_rest, UNIVERSAL_INTEGER)?;
if !info_rest.is_empty() {
return None;
}
package_names.push(name.to_vec());
items = tail;
}
let mut signature_digests = Vec::new();
let mut items = digests;
while !items.is_empty() {
let (digest, tail) = read_universal(items, UNIVERSAL_OCTET_STRING)?;
signature_digests.push(digest.to_vec());
items = tail;
}
Some(Some(ApplicationId {
package_names,
signature_digests,
}))
}

View File

@@ -0,0 +1,416 @@
//! Google's attestation status list: an in-memory snapshot the verifier reads
//! synchronously, and the background refresh that keeps it current.
//!
//! Enrollment never waits on a fetch. The verifier reads whatever snapshot is
//! installed; with none, or one older than the grace period, it fails closed.
use std::{
collections::{HashMap, HashSet},
sync::{Arc, RwLock},
time::Duration,
};
use async_trait::async_trait;
use rand::RngExt;
use serde::Deserialize;
/// Where Google publishes the status list. See
/// <https://developer.android.com/privacy-and-security/security-key-attestation#certificate_status>.
pub const GOOGLE_STATUS_LIST_URL: &str = "https://android.googleapis.com/attestation/status";
/// Largest status list body accepted. The published list is a few hundred KiB.
const MAX_BODY_BYTES: usize = 8 * 1024 * 1024;
const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
/// Refresh pacing when Google's `Cache-Control` is missing or out of range.
const DEFAULT_REFRESH_SECONDS: u64 = 3600;
const MIN_REFRESH_SECONDS: u64 = 300;
const MAX_REFRESH_SECONDS: u64 = 86_400;
const BACKOFF_START_SECONDS: u64 = 30;
const BACKOFF_CAP_SECONDS: u64 = 3600;
/// Why a chain could not be checked against the list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RevocationFailure {
/// No list has been fetched yet.
Unavailable,
/// The newest list is older than the grace period.
Stale,
/// A certificate in the chain appears in the list.
Listed,
}
struct Snapshot {
fetched_at: i64,
serials: HashSet<String>,
}
/// The newest attestation status list and how long it may be relied on.
pub struct RevocationList {
grace_seconds: i64,
snapshot: RwLock<Option<Snapshot>>,
}
impl RevocationList {
/// An empty list. Until [`RevocationList::replace`] runs, every chain
/// check fails closed.
pub fn new(grace_seconds: i64) -> Self {
Self {
grace_seconds,
snapshot: RwLock::new(None),
}
}
/// Install a freshly fetched set of listed serials.
pub fn replace(&self, serials: HashSet<String>, fetched_at: i64) {
// A poisoned lock still holds a complete snapshot: writes are one swap.
let mut guard = self
.snapshot
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner());
*guard = Some(Snapshot {
fetched_at,
serials,
});
}
/// Fail unless the list is fresh enough and names none of `serials`
/// (lowercase hex without leading zeros).
pub(super) fn check(&self, serials: &[String], now: i64) -> Result<(), RevocationFailure> {
let guard = self
.snapshot
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let snapshot = guard.as_ref().ok_or(RevocationFailure::Unavailable)?;
if now.saturating_sub(snapshot.fetched_at) > self.grace_seconds {
return Err(RevocationFailure::Stale);
}
if serials
.iter()
.any(|serial| snapshot.serials.contains(serial))
{
return Err(RevocationFailure::Listed);
}
Ok(())
}
}
/// Normalize a certificate serial or list key to lowercase hex with no
/// leading zeros, the form Google's list uses.
pub(super) fn serial_key(raw: &[u8]) -> String {
let hex = hex::encode(raw);
match hex.trim_start_matches('0') {
"" => "0".to_owned(),
trimmed => trimmed.to_owned(),
}
}
#[derive(Deserialize)]
struct StatusDocument {
entries: HashMap<String, serde::de::IgnoredAny>,
}
/// Decode the status list. Every entry is a certificate Google no longer
/// vouches for (REVOKED or SUSPENDED), so any listed serial is rejected
/// whatever its status or expiry says.
pub fn parse_status_list(body: &[u8]) -> Result<HashSet<String>, FetchError> {
if body.len() > MAX_BODY_BYTES {
return Err(FetchError::TooLarge);
}
let document: StatusDocument =
serde_json::from_slice(body).map_err(|_| FetchError::Malformed)?;
document
.entries
.into_keys()
.map(|key| {
let lower = key.to_ascii_lowercase();
let valid = !lower.is_empty() && lower.bytes().all(|b| b.is_ascii_hexdigit());
let trimmed = lower.trim_start_matches('0');
valid
.then(|| {
if trimmed.is_empty() {
"0".to_owned()
} else {
trimmed.to_owned()
}
})
.ok_or(FetchError::Malformed)
})
.collect()
}
/// Why a refresh did not produce a list.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum FetchError {
/// The request failed or timed out.
#[error("status list request failed")]
Request,
/// Google answered with a non-success status.
#[error("status list request was refused")]
Refused,
/// The body exceeded the size limit.
#[error("status list is too large")]
TooLarge,
/// The body was not a status list.
#[error("status list is malformed")]
Malformed,
}
/// One successful download.
pub struct StatusDownload {
pub body: Vec<u8>,
/// Seconds from Google's `Cache-Control: max-age`, when present.
pub max_age: Option<u64>,
}
/// The network boundary of the refresh, replaced by a fake in tests.
#[async_trait]
pub trait StatusListSource: Send + Sync {
/// Download the status list once.
async fn fetch(&self) -> Result<StatusDownload, FetchError>;
}
/// Downloads the list over HTTPS with a bounded time and size.
pub struct HttpStatusListSource {
client: reqwest::Client,
url: String,
}
impl HttpStatusListSource {
/// A source for [`GOOGLE_STATUS_LIST_URL`].
pub fn google() -> Result<Self, FetchError> {
let client = reqwest::Client::builder()
.timeout(FETCH_TIMEOUT)
.build()
.map_err(|_| FetchError::Request)?;
Ok(Self {
client,
url: GOOGLE_STATUS_LIST_URL.to_owned(),
})
}
}
fn max_age(value: &str) -> Option<u64> {
value
.split(',')
.find_map(|directive| directive.trim().strip_prefix("max-age="))
.and_then(|seconds| seconds.trim().parse().ok())
}
#[async_trait]
impl StatusListSource for HttpStatusListSource {
async fn fetch(&self) -> Result<StatusDownload, FetchError> {
let mut response = self
.client
.get(&self.url)
.send()
.await
.map_err(|_| FetchError::Request)?;
if !response.status().is_success() {
return Err(FetchError::Refused);
}
let max_age = response
.headers()
.get(reqwest::header::CACHE_CONTROL)
.and_then(|value| value.to_str().ok())
.and_then(max_age);
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|_| FetchError::Request)? {
if body.len() + chunk.len() > MAX_BODY_BYTES {
return Err(FetchError::TooLarge);
}
body.extend_from_slice(&chunk);
}
Ok(StatusDownload { body, max_age })
}
}
impl RevocationList {
/// The longest wait between refresh attempts that still leaves room inside
/// the grace period for jitter (up to 10%), the fetch timeout and a retry,
/// so a list refreshed on schedule never goes stale.
fn longest_refresh_wait(&self) -> u64 {
u64::try_from(self.grace_seconds / 2)
.unwrap_or(0)
.saturating_sub(FETCH_TIMEOUT.as_secs())
.max(1)
}
}
/// One refresh attempt: fetch, parse, and install on success. The previous
/// snapshot stays in place on failure. Returns the seconds to wait before the
/// next attempt, before jitter, never longer than the grace period allows.
pub async fn refresh_once(
list: &RevocationList,
source: &dyn StatusListSource,
now: i64,
consecutive_failures: &mut u32,
) -> u64 {
let wait =
match source.fetch().await.and_then(|download| {
parse_status_list(&download.body).map(|set| (set, download.max_age))
}) {
Ok((serials, max_age)) => {
*consecutive_failures = 0;
list.replace(serials, now);
max_age
.unwrap_or(DEFAULT_REFRESH_SECONDS)
.clamp(MIN_REFRESH_SECONDS, MAX_REFRESH_SECONDS)
}
Err(error) => {
*consecutive_failures = consecutive_failures.saturating_add(1);
tracing::warn!(
operation = "attestation_status_list",
%error,
failures = *consecutive_failures,
"Android attestation status list refresh failed"
);
BACKOFF_START_SECONDS
.saturating_mul(1u64 << (*consecutive_failures - 1).min(16))
.min(BACKOFF_CAP_SECONDS)
}
};
wait.min(list.longest_refresh_wait())
}
/// Refresh the list forever: immediately, then on Google's cache lifetime, with
/// capped exponential backoff after failures and up to 10% jitter so replicas
/// do not fetch in step.
pub async fn run_refresh_loop(
list: Arc<RevocationList>,
source: Arc<dyn StatusListSource>,
now: fn() -> i64,
) {
let mut failures = 0;
loop {
let wait = refresh_once(&list, source.as_ref(), now(), &mut failures).await;
let jitter = rand::rng().random_range(0..=wait / 10);
tokio::time::sleep(Duration::from_secs(wait + jitter)).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
/// Replays scripted downloads in order.
struct Script(Mutex<Vec<Result<StatusDownload, FetchError>>>);
#[async_trait]
impl StatusListSource for Script {
async fn fetch(&self) -> Result<StatusDownload, FetchError> {
self.0.lock().unwrap().remove(0)
}
}
fn download(body: &str, max_age: Option<u64>) -> Result<StatusDownload, FetchError> {
Ok(StatusDownload {
body: body.as_bytes().to_vec(),
max_age,
})
}
const LIST: &str = r#"{"entries": {
"2C8CDDDFD5E03BFC": {"status": "REVOKED", "reason": "KEY_COMPROMISE", "expires": "2030-01-01"},
"c8966fcb2fbb0d7a": {"status": "SUSPENDED"},
"6681152659205225093": {"status": "REVOKED"}
}}"#;
#[test]
fn status_list_parsing_normalizes_serials_and_rejects_everything_else() {
let serials = parse_status_list(LIST.as_bytes()).unwrap();
assert_eq!(serials.len(), 3);
// Leading zeros and case do not change a serial's identity.
for serial in [
&[0, 0x2c, 0x8c, 0xdd, 0xdf, 0xd5, 0xe0, 0x3b, 0xfc][..],
&[0xc8, 0x96, 0x6f, 0xcb, 0x2f, 0xbb, 0x0d, 0x7a],
] {
assert!(serials.contains(&serial_key(serial)));
}
for body in [
"".as_bytes(),
b"{}",
br#"{"entries": []}"#,
br#"{"entries": {"not hex": {"status": "REVOKED"}}}"#,
br#"{"entries": {"": {"status": "REVOKED"}}}"#,
] {
assert_eq!(parse_status_list(body), Err(FetchError::Malformed));
}
assert_eq!(
parse_status_list(&vec![b' '; MAX_BODY_BYTES + 1]),
Err(FetchError::TooLarge)
);
assert!(parse_status_list(br#"{"entries": {}}"#).unwrap().is_empty());
}
#[tokio::test]
async fn refresh_installs_good_lists_and_keeps_the_last_one_through_failures() {
let list = RevocationList::new(200_000);
let source = Script(Mutex::new(vec![
download(LIST, Some(60)),
Err(FetchError::Request),
download("not json", None),
Err(FetchError::Refused),
download(r#"{"entries": {}}"#, Some(999_999)),
]));
let mut failures = 0;
let listed = [serial_key(&[
0x2c, 0x8c, 0xdd, 0xdf, 0xd5, 0xe0, 0x3b, 0xfc,
])];
// Google's cache lifetime paces refreshes, within sane bounds.
assert_eq!(
refresh_once(&list, &source, 1_000, &mut failures).await,
MIN_REFRESH_SECONDS
);
assert_eq!(list.check(&listed, 1_000), Err(RevocationFailure::Listed));
// Failures back off with a cap and never discard the installed list.
let mut waits = Vec::new();
for _ in 0..3 {
waits.push(refresh_once(&list, &source, 1_050, &mut failures).await);
}
assert_eq!(waits, [30, 60, 120]);
assert_eq!(list.check(&listed, 1_050), Err(RevocationFailure::Listed));
// Past the grace period without a fresh list, checks fail closed.
assert_eq!(list.check(&[], 201_001), Err(RevocationFailure::Stale));
assert_eq!(
refresh_once(&list, &source, 1_200, &mut failures).await,
MAX_REFRESH_SECONDS
);
assert_eq!(failures, 0);
assert_eq!(list.check(&listed, 1_200), Ok(()));
assert_eq!(
RevocationList::new(1).check(&[], 0),
Err(RevocationFailure::Unavailable)
);
// A short grace period caps the wait, even when Google's cache
// lifetime is longer, so a list refreshed on schedule never goes stale.
let short = RevocationList::new(3600);
let source = Script(Mutex::new(vec![
download(LIST, Some(3600)),
download(LIST, None),
download(LIST, Some(86_400)),
]));
let mut failures = 0;
for _ in 0..3 {
let wait = refresh_once(&short, &source, 0, &mut failures).await;
assert_eq!(wait, 1770);
assert!(wait + wait / 10 + FETCH_TIMEOUT.as_secs() < 3600);
}
}
#[tokio::test]
async fn backoff_is_capped_and_cache_control_is_read() {
let list = RevocationList::new(604_800);
let mut failures = 40;
let source = Script(Mutex::new(vec![Err(FetchError::Request)]));
let wait = refresh_once(&list, &source, 0, &mut failures).await;
assert_eq!(wait, BACKOFF_CAP_SECONDS);
assert_eq!(max_age("public, max-age=86400"), Some(86_400));
assert_eq!(max_age("no-store"), None);
assert_eq!(max_age("max-age=soon"), None);
}
}

View File

@@ -32,6 +32,15 @@ pub struct AndroidConfig {
pub fcm_project_id: String,
/// Mounted service account key JSON the gateway uses to call FCM HTTP v1.
pub fcm_service_account_path: PathBuf,
/// Verified boot keys (SHA-256 digests) accepted when the hardware reports
/// a SelfSigned boot state. Empty, the default, accepts stock Android only.
pub boot_key_digests: Vec<[u8; 32]>,
/// PEM bundle of attestation roots that replaces Google's built-in
/// defaults, for a reviewed root rollout ahead of a release.
pub attestation_roots_path: Option<PathBuf>,
/// How long the attestation status list may go without a successful
/// refresh before Android enrollment fails closed.
pub revocation_grace_seconds: i64,
}
/// Apple App Attest environment, independent of the APNs transport environment.
@@ -58,6 +67,10 @@ pub struct Config {
pub max_installation_lifetime_seconds: i64,
pub endpoint_quota_window_seconds: i64,
pub endpoint_quota_max_deliveries: i64,
/// Window of the per-attested-key limit on signed installation calls.
pub signed_call_window_seconds: i64,
/// Signed installation calls one attested key may make per window.
pub signed_call_max_calls: i64,
/// Server-owned application identity and APNs transport.
pub application: ApplicationConfig,
/// Android identity and FCM credentials, when this gateway serves Android.
@@ -168,6 +181,28 @@ const ANDROID_SETTINGS: [&str; 4] = [
"BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH",
];
const ANDROID_OPTIONAL_SETTINGS: [&str; 3] = [
"BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS",
"BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH",
"BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS",
];
/// A comma-separated list of SHA-256 digests in hex. Empty means none.
fn parse_digests(value: &str, key: &'static str) -> Result<Vec<[u8; 32]>, ConfigError> {
if value.is_empty() {
return Ok(Vec::new());
}
value
.split(',')
.map(|digest| {
hex::decode(digest)
.ok()
.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
.ok_or(ConfigError::Invalid(key))
})
.collect()
}
fn valid_android_package_name(name: &str) -> bool {
let segments: Vec<&str> = name.split('.').collect();
segments.len() >= 2
@@ -184,7 +219,11 @@ fn valid_android_package_name(name: &str) -> bool {
fn parse_android(e: &HashMap<String, String>) -> Result<Option<AndroidConfig>, ConfigError> {
// A partial configuration is a mistake, not a request to disable Android.
if ANDROID_SETTINGS.iter().all(|key| !e.contains_key(*key)) {
if ANDROID_SETTINGS
.iter()
.chain(&ANDROID_OPTIONAL_SETTINGS)
.all(|key| !e.contains_key(*key))
{
return Ok(None);
}
let required = |key: &'static str| {
@@ -199,20 +238,32 @@ fn parse_android(e: &HashMap<String, String>) -> Result<Option<AndroidConfig>, C
if !valid_android_package_name(package_name) {
return Err(ConfigError::Invalid(package_key));
}
let signing_cert_digests = required(digests_key)?
.split(',')
.map(|digest| {
hex::decode(digest)
.ok()
.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
.ok_or(ConfigError::Invalid(digests_key))
})
.collect::<Result<Vec<_>, _>>()?;
let signing_cert_digests = parse_digests(required(digests_key)?, digests_key)?;
let boot_key_key = ANDROID_OPTIONAL_SETTINGS[0];
let boot_key_digests = parse_digests(
e.get(boot_key_key).map(String::as_str).unwrap_or(""),
boot_key_key,
)?;
let grace_key = ANDROID_OPTIONAL_SETTINGS[2];
let revocation_grace_seconds = match e.get(grace_key) {
None => 604_800,
Some(value) => value
.parse::<i64>()
.ok()
.filter(|seconds| (3600..=31_536_000).contains(seconds))
.ok_or(ConfigError::Invalid(grace_key))?,
};
Ok(Some(AndroidConfig {
package_name: package_name.to_owned(),
signing_cert_digests,
fcm_project_id: required(ANDROID_SETTINGS[2])?.to_owned(),
fcm_service_account_path: PathBuf::from(required(ANDROID_SETTINGS[3])?),
boot_key_digests,
attestation_roots_path: e
.get(ANDROID_OPTIONAL_SETTINGS[1])
.filter(|path| !path.is_empty())
.map(PathBuf::from),
revocation_grace_seconds,
}))
}
@@ -268,6 +319,10 @@ impl Config {
bounded_positive("BUZZ_PUSH_ENDPOINT_QUOTA_WINDOW_SECONDS", 10, 86_400)?;
let endpoint_quota_max_deliveries =
bounded_positive("BUZZ_PUSH_ENDPOINT_QUOTA_MAX_DELIVERIES", 10, 10_000)?;
let signed_call_window_seconds =
bounded_positive("BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS", 60, 86_400)?;
let signed_call_max_calls =
bounded_positive("BUZZ_PUSH_SIGNED_CALL_MAX_CALLS", 30, 10_000)?;
let application = parse_application(e)?;
let android = parse_android(e)?;
let bind_addr = e
@@ -289,6 +344,8 @@ impl Config {
max_installation_lifetime_seconds,
endpoint_quota_window_seconds,
endpoint_quota_max_deliveries,
signed_call_window_seconds,
signed_call_max_calls,
application,
android,
database_url: req(e, "DATABASE_URL")?.to_owned(),
@@ -506,6 +563,40 @@ mod tests {
assert_eq!(android.package_name, "com.example.buzz");
assert_eq!(android.signing_cert_digests, vec![[0xab; 32], [0xcd; 32]]);
assert_eq!(android.fcm_project_id, "example-project");
assert!(android.boot_key_digests.is_empty());
assert_eq!(android.attestation_roots_path, None);
assert_eq!(android.revocation_grace_seconds, 604_800);
let mut env = android_env();
env.extend([
(
"BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS".to_owned(),
format!("{},{}", "01".repeat(32), "02".repeat(32)),
),
(
"BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH".to_owned(),
"/roots.pem".to_owned(),
),
(
"BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS".to_owned(),
"7200".to_owned(),
),
]);
let android = Config::from_map(&env).unwrap().android.unwrap();
assert_eq!(android.boot_key_digests, vec![[1; 32], [2; 32]]);
assert_eq!(android.attestation_roots_path, Some("/roots.pem".into()));
assert_eq!(android.revocation_grace_seconds, 7200);
// An empty boot-key list is the default, as Helm renders it.
env.insert("BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS".into(), String::new());
assert!(Config::from_map(&env)
.unwrap()
.android
.unwrap()
.boot_key_digests
.is_empty());
// An Android option without the required settings is a mistake.
let mut env = base();
env.insert("BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS".into(), String::new());
assert!(Config::from_map(&env).is_err());
for variable in ANDROID_SETTINGS {
let mut env = android_env();
env.remove(variable);
@@ -526,6 +617,12 @@ mod tests {
("BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS", "abcd"),
("BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS", "zz"),
("BUZZ_PUSH_FCM_PROJECT_ID", ""),
("BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS", "abcd"),
("BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS", "zz"),
("BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS", "0"),
("BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS", "soon"),
("BUZZ_PUSH_SIGNED_CALL_MAX_CALLS", "0"),
("BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS", "x"),
] {
let mut env = android_env();
env.insert(key.into(), value.into());

View File

@@ -13,6 +13,7 @@ use crate::{
},
grant::GrantKeyring,
model::*,
signed_call_limiter::SignedCallLimiter,
token::TokenKeyring,
};
use axum::{
@@ -66,6 +67,8 @@ pub struct AppState {
pub max_installation_lifetime_seconds: i64,
pub endpoint_quota_window_seconds: i64,
pub endpoint_quota_max_deliveries: i64,
/// Limits signed installation calls per attested key.
pub signed_calls: Arc<SignedCallLimiter>,
pub now: fn() -> i64,
pub accepting: Arc<AtomicBool>,
}
@@ -513,6 +516,11 @@ async fn verify_installation_assertion<T: serde::Serialize>(
None
}
};
// Counted only for authentic calls, so nobody can spend another
// installation's allowance with forged requests.
if !s.signed_calls.admit(&installation.app_attest_key_id, now) {
return Err(error(StatusCode::TOO_MANY_REQUESTS, "rate_limited"));
}
s.authority
.consume_challenge(challenge.id, challenge_bytes, now)
.await
@@ -1109,6 +1117,9 @@ mod request_limit_tests {
max_installation_lifetime_seconds: 86_400,
endpoint_quota_window_seconds: 60,
endpoint_quota_max_deliveries: 10,
signed_calls: Arc::new(crate::signed_call_limiter::SignedCallLimiter::new(
60, 1_000,
)),
now: fixed_now,
accepting: Arc::new(AtomicBool::new(true)),
}

View File

@@ -54,6 +54,10 @@ struct Gateway {
}
fn gateway(with_android: bool) -> Gateway {
gateway_limited(with_android, 1_000)
}
fn gateway_limited(with_android: bool, signed_calls_per_window: i64) -> Gateway {
let fcm = Arc::new(FakeFcm::default());
let grant_keyring =
Arc::new(GrantKeyring::new(vec![GrantKey::new("test", &[1; 32]).unwrap()]).unwrap());
@@ -81,6 +85,10 @@ fn gateway(with_android: bool) -> Gateway {
max_installation_lifetime_seconds: 600,
endpoint_quota_window_seconds: 60,
endpoint_quota_max_deliveries: 10,
signed_calls: Arc::new(crate::signed_call_limiter::SignedCallLimiter::new(
60,
signed_calls_per_window,
)),
now: fixed_now,
accepting: Arc::new(AtomicBool::new(true)),
});
@@ -575,8 +583,8 @@ async fn android_enrollment_derives_platform_from_the_attestation_and_rejects_ba
StatusCode::BAD_REQUEST
);
// The attestation must bind this exact transcript, prove a P-256 point and
// stay within the chain bounds.
// The attestation must bind this exact transcript, prove an uncompressed
// P-256 point and stay within the chain bounds.
let other_transcript = enroll_transcript(&ch, ROTATED_FCM_TOKEN);
let mut wrong_binding = good.clone();
wrong_binding["android_attestation"] = phone.chain(&other_transcript).into();
@@ -585,10 +593,17 @@ async fn android_enrollment_derives_platform_from_the_attestation_and_rejects_ba
STANDARD.encode([4u8; 65]),
STANDARD.encode(Sha256::digest(enroll_transcript(&ch, FCM_TOKEN).as_bytes())),
]);
// One key has one id: the same key as a compressed point would get a
// second id, and a second rate-limit bucket.
let mut compressed = good.clone();
compressed["android_attestation"] = json!([
STANDARD.encode(phone.key.verifying_key().to_sec1_point(true).as_ref()),
STANDARD.encode(Sha256::digest(enroll_transcript(&ch, FCM_TOKEN).as_bytes())),
]);
let mut long_chain = good.clone();
long_chain["android_attestation"] =
vec![STANDARD.encode(b"c"); MAX_ANDROID_CHAIN_CERTIFICATES + 1].into();
for body in [wrong_binding, not_a_point, long_chain] {
for body in [wrong_binding, not_a_point, compressed, long_chain] {
assert_eq!(enroll_status(&g, body).await, StatusCode::UNAUTHORIZED);
}
@@ -605,3 +620,51 @@ async fn android_enrollment_derives_platform_from_the_attestation_and_rejects_ba
replay.1["installation_handle"]
);
}
#[tokio::test]
async fn signed_installation_calls_are_limited_per_attested_key() {
let g = gateway_limited(true, 3);
let (phone, other, forger) = (Phone::new(7), Phone::new(8), Phone::new(9));
let relay = "aa".repeat(32);
let handle = enroll(&g, &phone).await;
let delegate = |generation| Call::Delegate {
relay: relay.clone(),
epoch: 1,
generation,
};
let revoke = Call::RevokeDelegation {
relay: relay.clone(),
generation: 1,
};
// Forged calls fail authentication before they are counted, so they
// cannot spend the installation's allowance.
for _ in 0..5 {
let (status, _) = send_call(&g, handle, &delegate(1), &delegate(1), &forger).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
}
call_ok(&g, handle, &delegate(1), &phone).await;
call_ok(&g, handle, &revoke, &phone).await;
call_ok(&g, handle, &delegate(2), &phone).await;
// The fourth authentic call in the window is refused, whichever kind.
for call in [Call::RevokeInstallation { epoch: 1 }, delegate(3)] {
let (status, body) = send_call(&g, handle, &call, &call, &phone).await;
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "{body}");
}
// Another installation has its own allowance.
let other_handle = {
let ch = challenge(&g.app).await;
let (status, body) = post(
&g.app,
"/v1/installations",
&enroll_body(&other, &ch, ROTATED_FCM_TOKEN),
)
.await;
assert_eq!(status, StatusCode::CREATED, "{body}");
body["installation_handle"]
.as_str()
.unwrap()
.parse()
.unwrap()
};
call_ok(&g, other_handle, &delegate(1), &other).await;
}

View File

@@ -117,6 +117,9 @@ async fn fixture() -> (axum::Router, Keys, Vec<u8>, Arc<AtomicUsize>) {
max_installation_lifetime_seconds: 600,
endpoint_quota_window_seconds: 60,
endpoint_quota_max_deliveries: 10,
signed_calls: Arc::new(crate::signed_call_limiter::SignedCallLimiter::new(
60, 1_000,
)),
now,
accepting: Arc::new(AtomicBool::new(true)),
});

View File

@@ -10,6 +10,7 @@ pub mod http;
pub mod metrics;
pub mod model;
pub mod postgres;
pub mod signed_call_limiter;
pub(crate) mod strict_json;
pub mod token;
pub use http::{router, router_with_metrics, AppState};

View File

@@ -1,5 +1,8 @@
use buzz_push_gateway::{
android_attestation::PendingAttestationVerifier,
android_attestation::{
run_refresh_loop, HttpStatusListSource, KeyAttestationPolicy, KeyAttestationVerifier,
RevocationList, GOOGLE_ROOTS_PEM,
},
apns::ApnsTransport,
app_attest::AppAttestVerifier,
authority::AuthorityStore,
@@ -8,6 +11,7 @@ use buzz_push_gateway::{
grant::{GrantKey, GrantKeyring},
postgres::PostgresAuthorityStore,
router_with_metrics,
signed_call_limiter::SignedCallLimiter,
token::{TokenKey, TokenKeyring},
AppState,
};
@@ -47,6 +51,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let metrics_handle = buzz_push_gateway::metrics::install()?;
let app_attest_root = fs::read(&c.app_attest_root_cert_path)?;
let configured = &c.application;
let mut refresh_tasks = Vec::new();
let application = {
let apple = AppAttestVerifier::with_environment(
configured.app_attest_app_id.clone(),
@@ -67,13 +72,34 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
&android.fcm_project_id,
&fs::read(&android.fcm_service_account_path)?,
)?;
tracing::warn!(
let roots = match &android.attestation_roots_path {
Some(path) => fs::read_to_string(path)?,
None => GOOGLE_ROOTS_PEM.to_owned(),
};
let revocations = Arc::new(RevocationList::new(android.revocation_grace_seconds));
// Enrollment fails closed until the first refresh succeeds.
refresh_tasks.push(tokio::spawn(run_refresh_loop(
revocations.clone(),
Arc::new(HttpStatusListSource::google()?),
|| chrono::Utc::now().timestamp(),
)));
let verifier = KeyAttestationVerifier::new(
&roots,
KeyAttestationPolicy {
package_name: android.package_name.clone(),
signing_cert_digests: android.signing_cert_digests.clone(),
boot_key_digests: android.boot_key_digests.clone(),
},
revocations,
|| chrono::Utc::now().timestamp(),
)?;
tracing::info!(
package = %android.package_name,
"Android configured, but Key Attestation verification is not implemented in \
this build: every Android enrollment will be rejected"
boot_keys = android.boot_key_digests.len(),
"Android Key Attestation verifier configured"
);
Ok(buzz_push_gateway::http::AndroidRuntime {
attestation: Arc::new(PendingAttestationVerifier),
attestation: Arc::new(verifier),
transport: Arc::new(fcm),
})
})
@@ -131,6 +157,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
max_installation_lifetime_seconds: c.max_installation_lifetime_seconds,
endpoint_quota_window_seconds: c.endpoint_quota_window_seconds,
endpoint_quota_max_deliveries: c.endpoint_quota_max_deliveries,
signed_calls: Arc::new(SignedCallLimiter::new(
c.signed_call_window_seconds,
c.signed_call_max_calls,
)),
now: || chrono::Utc::now().timestamp(),
accepting: accepting.clone(),
},
@@ -163,6 +193,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let _ = htx.send(true);
let _ = h.await;
reaper.abort();
for task in refresh_tasks {
task.abort();
}
Ok(())
}
async fn shutdown_signal() -> std::io::Result<()> {

View File

@@ -0,0 +1,97 @@
//! Per-attested-key rate limit on signed installation calls.
//!
//! Attestation carries no stable device id and each enrollment makes a fresh
//! key, so enrollment is not limited per device. The challenge quota caps only
//! outstanding challenges (consuming one deletes it), not the rate of
//! completed enrollments. After enrollment the attested key is the
//! installation's identity, and this limit keeps one installation from
//! flooding the gateway. Counters live in memory, per replica, so a deployment
//! with several replicas allows each key up to that many times the configured
//! calls.
use std::{collections::HashMap, sync::Mutex};
/// Most keys tracked at once. Past it, the key with the oldest window is
/// dropped, so memory stays bounded however many keys call.
const MAX_TRACKED_KEYS: usize = 100_000;
/// A fixed-window counter per attested key.
pub struct SignedCallLimiter {
window_seconds: i64,
max_calls: i64,
windows: Mutex<HashMap<Vec<u8>, Window>>,
}
#[derive(Clone, Copy)]
struct Window {
started_at: i64,
calls: i64,
}
impl SignedCallLimiter {
/// At most `max_calls` calls per key in each `window_seconds` window.
pub fn new(window_seconds: i64, max_calls: i64) -> Self {
Self {
window_seconds,
max_calls,
windows: Mutex::new(HashMap::new()),
}
}
/// Count one call by `key` at `now`; false when the key is over its limit.
pub fn admit(&self, key: &[u8], now: i64) -> bool {
// The map holds only counters, so a poisoned lock is still consistent.
let mut windows = self
.windows
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !windows.contains_key(key) && windows.len() >= MAX_TRACKED_KEYS {
let window_seconds = self.window_seconds;
windows.retain(|_, w| now.saturating_sub(w.started_at) < window_seconds);
if windows.len() >= MAX_TRACKED_KEYS {
let oldest = windows
.iter()
.min_by_key(|(_, w)| w.started_at)
.map(|(key, _)| key.clone());
if let Some(oldest) = oldest {
windows.remove(&oldest);
}
}
}
let window = windows.entry(key.to_vec()).or_insert(Window {
started_at: now,
calls: 0,
});
if now.saturating_sub(window.started_at) >= self.window_seconds {
*window = Window {
started_at: now,
calls: 0,
};
}
if window.calls >= self.max_calls {
return false;
}
window.calls += 1;
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_key_has_its_own_window_and_the_map_stays_bounded() {
let limiter = SignedCallLimiter::new(60, 2);
assert!(limiter.admit(b"a", 100));
assert!(limiter.admit(b"a", 101));
assert!(!limiter.admit(b"a", 159));
assert!(limiter.admit(b"b", 159), "another key is unaffected");
assert!(limiter.admit(b"a", 160), "the window rolled over");
for index in 0..(MAX_TRACKED_KEYS + 10) {
limiter.admit(&index.to_be_bytes(), 1_000);
}
let tracked = limiter.windows.lock().unwrap().len();
assert!(tracked <= MAX_TRACKED_KEYS, "tracked {tracked} keys");
}
}

View File

@@ -53,6 +53,20 @@ spec:
- { name: BUZZ_PUSH_APNS_TOPIC, value: {{ .Values.application.apnsTopic | quote }} }
- { name: BUZZ_PUSH_APNS_ENVIRONMENT, value: {{ .Values.application.apnsEnvironment | quote }} }
- { name: BUZZ_PUSH_APNS_CERT_PATH, value: /run/buzz/apns/identity.pem }
{{/* Schema bounds these integers; normalize before quote. */}}
- { name: BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS, value: {{ .Values.signedCallRateLimit.windowSeconds | int64 | quote }} }
- { name: BUZZ_PUSH_SIGNED_CALL_MAX_CALLS, value: {{ .Values.signedCallRateLimit.maxCalls | int64 | quote }} }
{{- if .Values.android.enabled }}
- { name: BUZZ_PUSH_ANDROID_PACKAGE_NAME, value: {{ .Values.android.packageName | quote }} }
- { name: BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS, value: {{ join "," .Values.android.signingCertDigests | quote }} }
- { name: BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS, value: {{ join "," .Values.android.bootKeyDigests | quote }} }
- { name: BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS, value: {{ .Values.android.revocationGraceSeconds | int64 | quote }} }
- { name: BUZZ_PUSH_FCM_PROJECT_ID, value: {{ .Values.android.fcmProjectId | quote }} }
- { name: BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH, value: /run/buzz/fcm/service-account.json }
{{- if .Values.android.attestationRoots.secretName }}
- { name: BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH, value: /run/buzz/android-attestation/roots.pem }
{{- end }}
{{- end }}
{{- range $name := list "DATABASE_URL" "BUZZ_PUSH_GRANT_KEYS" "BUZZ_PUSH_TOKEN_KEYS" }}
- name: {{ $name }}
valueFrom: { secretKeyRef: { name: {{ $.Values.existingSecret }}, key: {{ $name }} } }
@@ -60,6 +74,12 @@ spec:
volumeMounts:
- { name: app-attest-root, mountPath: /run/buzz/app-attest, readOnly: true }
- { name: apns, mountPath: /run/buzz/apns, readOnly: true }
{{- if .Values.android.enabled }}
- { name: fcm, mountPath: /run/buzz/fcm, readOnly: true }
{{- if .Values.android.attestationRoots.secretName }}
- { name: android-attestation-roots, mountPath: /run/buzz/android-attestation, readOnly: true }
{{- end }}
{{- end }}
livenessProbe: { httpGet: { path: /_liveness, port: health }, periodSeconds: 10, timeoutSeconds: 3, failureThreshold: 3 }
readinessProbe: { httpGet: { path: /_readiness, port: health }, periodSeconds: 5, timeoutSeconds: 3, failureThreshold: 3 }
startupProbe: { httpGet: { path: /_liveness, port: health }, periodSeconds: 2, failureThreshold: 60 }
@@ -69,6 +89,16 @@ spec:
secret: { secretName: {{ .Values.appAttestRoot.secretName }}, items: [{ key: {{ .Values.appAttestRoot.secretKey }}, path: root.pem }] }
- name: apns
secret: { secretName: {{ .Values.application.apnsCert.secretName }}, defaultMode: 0400, items: [{ key: {{ .Values.application.apnsCert.secretKey }}, path: identity.pem }] }
{{- if .Values.android.enabled }}
- name: fcm
secret: { secretName: {{ .Values.android.fcmServiceAccount.secretName }}, defaultMode: 0400, items: [{ key: {{ .Values.android.fcmServiceAccount.secretKey }}, path: service-account.json }] }
{{- with .Values.android.attestationRoots }}
{{- if .secretName }}
- name: android-attestation-roots
secret: { secretName: {{ .secretName }}, items: [{ key: {{ .secretKey }}, path: roots.pem }] }
{{- end }}
{{- end }}
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector: {{- toYaml . | nindent 8 }}
{{- end }}

View File

@@ -37,6 +37,46 @@ reject --set networkPolicy.enabled=false --set-string 'networkPolicy.externalPol
reject --set networkPolicy.externalPolicyName=conflicting-policy
reject --set terminationGracePeriodSeconds=59
reject --set podLabels.invalid=true
# Android stays off by default, and enabling it needs a signing digest.
if grep -q 'BUZZ_PUSH_ANDROID\|BUZZ_PUSH_FCM' "$out/default.yaml"; then
echo 'default values must leave Android disabled' >&2
exit 1
fi
digest=$(printf 'ab%.0s' {1..32})
helm template push "$chart" --set android.enabled=true \
--set "android.signingCertDigests[0]=$digest" >"$out/android.yaml"
for needle in BUZZ_PUSH_ANDROID_PACKAGE_NAME "$digest" BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS \
BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH; do
grep -q "$needle" "$out/android.yaml" || { echo "Android render lacks $needle" >&2; exit 1; }
done
if grep -q 'ATTESTATION_ROOTS\|android-attestation' "$out/android.yaml"; then
echo 'an empty attestationRoots.secretName must keep the built-in roots' >&2
exit 1
fi
helm template push "$chart" --set android.enabled=true \
--set "android.signingCertDigests[0]=$digest" \
--set android.attestationRoots.secretName=attestation-roots >"$out/android-roots.yaml"
env -u GEM_HOME -u GEM_PATH -u RUBYLIB -u RUBYOPT ruby -ryaml - "$out" <<'RUBY'
docs = YAML.load_stream(File.read("#{ARGV[0]}/android-roots.yaml")).compact
pod = docs.find { |r| r['kind'] == 'Deployment' }.dig('spec', 'template', 'spec')
gateway = pod['containers'].find { |c| c['name'] == 'gateway' }
env = gateway['env'].find { |e| e['name'] == 'BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH' }
raise 'roots override env missing' unless env && env['value'] == '/run/buzz/android-attestation/roots.pem'
mount = gateway['volumeMounts'].find { |m| m['name'] == 'android-attestation-roots' }
raise 'roots override mount missing' unless mount && mount['mountPath'] == '/run/buzz/android-attestation'
volume = pod['volumes'].find { |v| v['name'] == 'android-attestation-roots' }
expected = { 'secretName' => 'attestation-roots', 'items' => [{ 'key' => 'android-attestation-roots.pem', 'path' => 'roots.pem' }] }
raise "roots override volume wrong: #{volume.inspect}" unless volume && volume['secret'] == expected
RUBY
helm template push "$chart" --set android.attestationRoots.secretName=attestation-roots >"$out/roots-disabled.yaml"
cmp -s "$out/default.yaml" "$out/roots-disabled.yaml" || { echo 'roots override must not render while Android is disabled' >&2; exit 1; }
reject --set android.attestationRoots.secretName=attestation-roots --set-string android.attestationRoots.secretKey=
reject --set android.enabled=true
reject --set 'android.signingCertDigests[0]=abcd'
reject --set 'android.bootKeyDigests[0]=zz'
reject --set android.revocationGraceSeconds=60
reject --set signedCallRateLimit.maxCalls=0
for label in name instance component; do
reject --set-string "podLabels.app\\.kubernetes\\.io/$label=override"
done

View File

@@ -330,7 +330,13 @@
"application": {
"$ref": "#/$defs/application"
},
"profiles": false
"profiles": false,
"android": {
"$ref": "#/$defs/android"
},
"signedCallRateLimit": {
"$ref": "#/$defs/signedCallRateLimit"
}
},
"$defs": {
"apnsCert": {
@@ -379,6 +385,113 @@
"$ref": "#/$defs/apnsCert"
}
}
},
"android": {
"type": "object",
"additionalProperties": false,
"required": [
"enabled",
"packageName",
"signingCertDigests",
"bootKeyDigests",
"revocationGraceSeconds",
"fcmProjectId",
"fcmServiceAccount",
"attestationRoots"
],
"properties": {
"enabled": {
"type": "boolean"
},
"packageName": {
"type": "string",
"pattern": "^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+$"
},
"signingCertDigests": {
"type": "array",
"items": {
"type": "string",
"pattern": "^[0-9a-fA-F]{64}$"
}
},
"bootKeyDigests": {
"type": "array",
"items": {
"type": "string",
"pattern": "^[0-9a-fA-F]{64}$"
}
},
"revocationGraceSeconds": {
"type": "integer",
"minimum": 3600,
"maximum": 31536000
},
"fcmProjectId": {
"type": "string",
"minLength": 1
},
"fcmServiceAccount": {
"$ref": "#/$defs/apnsCert"
},
"attestationRoots": {
"type": "object",
"additionalProperties": false,
"required": [
"secretName",
"secretKey"
],
"properties": {
"secretName": {
"type": "string"
},
"secretKey": {
"type": "string",
"minLength": 1
}
}
}
},
"allOf": [
{
"if": {
"properties": {
"enabled": {
"const": true
}
},
"required": [
"enabled"
]
},
"then": {
"properties": {
"signingCertDigests": {
"minItems": 1
}
}
}
}
]
},
"signedCallRateLimit": {
"type": "object",
"additionalProperties": false,
"required": [
"windowSeconds",
"maxCalls"
],
"properties": {
"windowSeconds": {
"type": "integer",
"minimum": 1,
"maximum": 86400
},
"maxCalls": {
"type": "integer",
"minimum": 1,
"maximum": 10000
}
}
}
},
"required": [

View File

@@ -31,6 +31,34 @@ application:
apnsCert:
secretName: buzz-push-gateway
secretKey: apns-identity.pem
# Android is off unless enabled. Enabling it needs the package, at least one
# signing certificate digest and the Firebase project and service account.
android:
enabled: false
# Exact application package the attestation must name.
packageName: com.example.buzz
# SHA-256 digests (64 hex characters each) of the app's signing certificates.
signingCertDigests: []
# Verified boot keys (SHA-256 digests, 64 hex characters each) accepted when
# the hardware reports a self-signed boot state. Empty accepts stock Android
# only. Add the published keys of a custom operating system to support it.
bootKeyDigests: []
# Seconds the attestation revocation list may go without a successful refresh
# before Android enrollment fails closed.
revocationGraceSeconds: 604800
fcmProjectId: example-project
fcmServiceAccount:
secretName: buzz-push-gateway
secretKey: fcm-service-account.json
# Optional PEM bundle replacing the built-in Google attestation roots, for a
# reviewed root rollout. Empty secretName keeps the built-in roots.
attestationRoots:
secretName: ""
secretKey: android-attestation-roots.pem
# Rate limit on signed installation calls, per attested key and replica.
signedCallRateLimit:
windowSeconds: 60
maxCalls: 30
appAttestRoot:
secretName: buzz-push-gateway
secretKey: app-attest-root.pem

View File

@@ -34,7 +34,7 @@ See [Buzz push notes](buzz-push.md) for the current experimental contract.
## Android (optional)
The same gateway serves the app's Android installations through Firebase Cloud
Messaging (FCM HTTP v1). Android is off unless all four settings are present;
Messaging (FCM HTTP v1). Android is off unless all four settings below are present;
a partial set fails startup. The platform of an installation is recorded only in
gateway state, derived from the attestation type at enrollment. The relay never
sees it.
@@ -53,9 +53,55 @@ delegation, rotate the endpoint, revoke the installation) with its attested
Keystore key: an ECDSA P-256 signature over the same transcript bytes iOS
signs, whose single-use challenge is its replay protection.
Android Key Attestation chain verification is not part of this build yet: a
gateway configured for Android starts, logs a warning, and rejects every Android
enrollment until it lands. Enable Android in production only after that.
### Key Attestation
Enrollment is public, so an Android installation proves it is your app on real
hardware before it can enroll. The gateway verifies the Key Attestation chain
offline and accepts it only when all of these hold:
- The chain ends at a configured Google attestation root and no certificate in
it is on Google's [status list](https://android.googleapis.com/attestation/status).
Google's [published hardware attestation roots](https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate)
are built in, pinned by public key. A root change is a reviewed rollout: set
`BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH` to a PEM bundle to replace the
built-in list before upgrading.
- The attestation challenge equals the SHA-256 of the enrollment transcript.
- The hardware-enforced properties (never the software-enforced ones) report a
locked bootloader and either a Verified boot state, or SelfSigned with a
verified boot key on your `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS` list. Unverified,
Failed, and SelfSigned with any other key are rejected.
- Both security levels are TrustedEnvironment or StrongBox, and the key is a
generated, sign-only P-256 key.
- The attested application id names exactly one package, the configured one,
with a configured signing digest. The operating system writes this value, so
it is trusted only as far as the boot state and boot key vouch for that
operating system.
| Variable | Purpose |
|---|---|
| `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS` | Optional comma-separated SHA-256 digests (64 hex characters each) of verified boot keys accepted with a SelfSigned boot state. Empty by default, which accepts stock Android only. Add the published per-device keys of a custom operating system to support it, and update the list when new devices ship. |
| `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH` | Optional PEM bundle that replaces the built-in Google roots. |
| `BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS` | How long the status list may go without a successful refresh before Android enrollment fails closed. Default `604800` (7 days), minimum `3600`. |
| `BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS`, `BUZZ_PUSH_SIGNED_CALL_MAX_CALLS` | Per-attested-key rate limit on signed installation calls (all platforms). Defaults `60` and `30`. Counters are per replica. |
The gateway fetches the status list once at startup and then on Google's cache
lifetime (between 5 minutes and 1 day), with a 30 second timeout, an 8 MiB size
limit, and capped exponential backoff after failures. Enrollment never waits on
a fetch: until the first fetch succeeds, or after the grace period passes
without a refresh, Android enrollment is rejected. Allow outbound HTTPS to
`android.googleapis.com`. Every certificate listed as REVOKED or SUSPENDED is
rejected. Phones without hardware-backed attestation, with an unlocked
bootloader, or running an operating system whose boot key you have not listed
get no push; there is no software fallback.
With the Helm chart, set `android.enabled=true` together with
`android.packageName`, `android.signingCertDigests`, `android.fcmProjectId` and
the Secret holding the service account key. `android.bootKeyDigests` and
`android.revocationGraceSeconds` map to the settings above. To replace the
built-in roots, name a Secret holding the PEM bundle in
`android.attestationRoots.secretName` (and its key in `secretKey`); the chart
mounts it and sets `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH`. Android is
disabled by default.
Optional endpoint quota policy variables are `BUZZ_PUSH_ENDPOINT_QUOTA_WINDOW_SECONDS` (default `10`, max `86400`) and `BUZZ_PUSH_ENDPOINT_QUOTA_MAX_DELIVERIES` (default `10`, max `10000`). These are Buzz policy hypotheses, not Apple-published limits; tune under load while retaining a hard ceiling.