androidkey.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // Package androidkey verifies attestation statements of the "android-key"
  2. // format of ACME device-attest-01 challenges, made by Android Key Attestation.
  3. package androidkey
  4. import (
  5. "bytes"
  6. "context"
  7. "crypto/x509"
  8. "encoding/asn1"
  9. "errors"
  10. "fmt"
  11. "slices"
  12. "time"
  13. keyattestation "github.com/smallstep/android-attestation"
  14. "go.step.sm/crypto/keyutil"
  15. "go.step.sm/crypto/pemutil"
  16. "github.com/smallstep/certificates/attestation"
  17. "github.com/smallstep/certificates/attestation/internal/keyauth"
  18. )
  19. // Android RSA Root CA
  20. // https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate
  21. const androidRSARootCA = `-----BEGIN CERTIFICATE-----
  22. MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
  23. BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw
  24. NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
  25. AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
  26. Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
  27. tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
  28. nar86461qO0rOs2cX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mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
  45. lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
  46. n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
  47. zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
  48. vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
  49. w1IdYIg2Wxg7yHcQZemFQg==
  50. -----END CERTIFICATE-----`
  51. // Android ECDSA (secp384r1) Root CA
  52. const androidECDSARootCA = `-----BEGIN CERTIFICATE-----
  53. MIICIjCCAaigAwIBAgIRAISp0Cl7DrWK5/8OgN52BgUwCgYIKoZIzj0EAwMwUjEc
  54. MBoGA1UEAwwTS2V5IEF0dGVzdGF0aW9uIENBMTEQMA4GA1UECwwHQW5kcm9pZDET
  55. MBEGA1UECgwKR29vZ2xlIExMQzELMAkGA1UEBhMCVVMwHhcNMjUwNzE3MjIzMjE4
  56. WhcNMzUwNzE1MjIzMjE4WjBSMRwwGgYDVQQDDBNLZXkgQXR0ZXN0YXRpb24gQ0Ex
  57. MRAwDgYDVQQLDAdBbmRyb2lkMRMwEQYDVQQKDApHb29nbGUgTExDMQswCQYDVQQG
  58. EwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABCPaI3FO3z5bBQo8cuiEas4HjqCt
  59. G/mLFfRT0MsIssPBEEU5Cfbt6sH5yOAxqEi5QagpU1yX4HwnGb7OtBYpDTB57uH5
  60. Eczm34A5FNijV3s0/f0UPl7zbJcTx6xwqMIRq6NCMEAwDwYDVR0TAQH/BAUwAwEB
  61. /zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFFIyuyz7RkOb3NaBqQ5lZuA0QepA
  62. MAoGCCqGSM49BAMDA2gAMGUCMETfjPO/HwqReR2CS7p0ZWoD/LHs6hDi422opifH
  63. EUaYLxwGlT9SLdjkVpz0UUOR5wIxAIoGyxGKRHVTpqpGRFiJtQEOOTp/+s1GcxeY
  64. uR2zh/80lQyu9vAFCj6E4AXc+osmRg==
  65. -----END CERTIFICATE-----`
  66. // OID for Android Key Attestation
  67. // https://source.android.com/docs/security/features/keystore/attestation#id-attestation
  68. var oidAndroidAttestation = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 1, 17}
  69. var (
  70. // ErrEmptyX5C is matched by the error of an attestation statement whose
  71. // x5c holds no certificates.
  72. ErrEmptyX5C = errors.New("x5c is empty")
  73. // ErrKeyDescription is matched by the error of a key attestation
  74. // extension that cannot be parsed.
  75. ErrKeyDescription = errors.New("error parsing attestation")
  76. )
  77. // RevocationChecker reports whether a certificate of an x5c chain is revoked.
  78. type RevocationChecker func(ctx context.Context, cert *x509.Certificate) (bool, error)
  79. // Data is what a verified "android-key" attestation statement attests.
  80. type Data struct {
  81. // Certificate is the attestation certificate, the certificate closest to
  82. // the root that carries a key attestation extension. It holds the
  83. // attested key.
  84. Certificate *x509.Certificate
  85. // Fingerprint is the fingerprint of the attested key.
  86. Fingerprint string
  87. // KeyDescription is the key attestation extension of the attestation
  88. // certificate.
  89. KeyDescription *keyattestation.KeyDescription
  90. }
  91. // findAndroidAttestationCert traverses the slice of [*x509.Certificate] from
  92. // end to start (root -> intermediate -> leaf) to locate the certificate closest
  93. // to the root carrying an Android Key Attestation extension.
  94. //
  95. // TODO(hs): implement the optional step of locating the provisioning information
  96. // extension? That should immediately precede the cert with the key attestation
  97. // extension.
  98. func findAndroidAttestationCert(certs []*x509.Certificate) *x509.Certificate {
  99. for _, cert := range slices.Backward(certs) {
  100. for _, ext := range cert.Extensions {
  101. if ext.Id.Equal(oidAndroidAttestation) {
  102. return cert
  103. }
  104. }
  105. }
  106. return nil
  107. }
  108. // Verify verifies an "android-key" attestation statement, following
  109. // https://developer.android.com/privacy-and-security/security-key-attestation,
  110. // against roots, or against Google's roots if roots is nil, and keyAuth, the
  111. // key authorization of the challenge. It performs the below steps:
  112. // - Verifies that the root public certificate is trustworthy and that each certificate signs
  113. // the next certificate in the chain.
  114. // - Checks each certificate's revocation status with isRevoked to ensure that none of the
  115. // certificates have been revoked.
  116. // - Finds the nearest certificate to the root that contains the key attestation certificate
  117. // extension, and verifies the statement's signature over keyAuth with its key.
  118. // - Checks that the attestation challenge of the extension is keyAuth.
  119. //
  120. // It returns the attestation certificate and its key description, whose
  121. // values the caller compares with the ones it expects the hardware-backed key
  122. // to have. Errors of the statement match attestation.ErrInvalidEvidence; errors
  123. // of isRevoked do not.
  124. func Verify(ctx context.Context, attStmt map[string]any, roots *x509.CertPool, keyAuth []byte, isRevoked RevocationChecker) (*Data, error) {
  125. if isRevoked == nil {
  126. return nil, errors.New("android-key attestation requires a revocation checker")
  127. }
  128. if roots == nil {
  129. rsaRoot, err := pemutil.ParseCertificate([]byte(androidRSARootCA))
  130. if err != nil {
  131. return nil, fmt.Errorf("error parsing Android RSA root CA: %w", err)
  132. }
  133. ecdsaRoot, err := pemutil.ParseCertificate([]byte(androidECDSARootCA))
  134. if err != nil {
  135. return nil, fmt.Errorf("error parsing Android ECDSA root CA: %w", err)
  136. }
  137. roots = x509.NewCertPool()
  138. roots.AddCert(rsaRoot)
  139. roots.AddCert(ecdsaRoot)
  140. }
  141. // extract x5c and verify certificate
  142. x5c, ok := attStmt["x5c"].([]any)
  143. if !ok {
  144. return nil, attestation.Invalidf("x5c not present")
  145. }
  146. if len(x5c) == 0 {
  147. return nil, attestation.Invalid(ErrEmptyX5C)
  148. }
  149. // Parse leaf, intermediates and root
  150. intermediates := x509.NewCertPool()
  151. var leaf, root *x509.Certificate
  152. for i, v := range x5c {
  153. der, dok := v.([]byte)
  154. if !dok {
  155. return nil, attestation.Invalidf("x5c element is malformed")
  156. }
  157. cert, err := x509.ParseCertificate(der)
  158. if err != nil {
  159. return nil, attestation.Invalidf("failed parsing certificate at index %d: %w", i, err)
  160. }
  161. // Verify certificate serial number against CRL
  162. revoked, err := isRevoked(ctx, cert)
  163. if err != nil {
  164. return nil, fmt.Errorf("failed checking certificate revocation status: %w", err)
  165. }
  166. if revoked {
  167. return nil, attestation.Invalidf("x5c element contains a revoked certificate")
  168. }
  169. switch i {
  170. case 0: // leaf
  171. leaf = cert
  172. case len(x5c) - 1: // root
  173. root = cert
  174. default: // intermediates
  175. intermediates.AddCert(cert)
  176. }
  177. }
  178. // Require a leaf in the chain
  179. if leaf == nil {
  180. return nil, attestation.Invalidf("missing leaf certificate in x5c chain")
  181. }
  182. // Require a root in the chain
  183. if root == nil {
  184. return nil, attestation.Invalidf("missing root certificate in x5c chain")
  185. }
  186. // Verify the root is one of the trusted roots
  187. _, err := root.Verify(x509.VerifyOptions{
  188. Roots: roots,
  189. CurrentTime: time.Now().Truncate(time.Second),
  190. })
  191. if err != nil {
  192. return nil, attestation.Invalidf("root certificate in chain is not trusted")
  193. }
  194. // Validate the full chain including root as trust anchor
  195. chains, err := leaf.Verify(x509.VerifyOptions{
  196. Intermediates: intermediates,
  197. Roots: roots,
  198. CurrentTime: time.Now().Truncate(time.Second),
  199. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  200. })
  201. if err != nil {
  202. return nil, attestation.Invalidf("x5c chain verification failed: %w", err)
  203. }
  204. switch {
  205. case len(chains) == 0:
  206. return nil, attestation.Invalidf("x5c does not contain a valid certificate chain")
  207. case len(chains) > 1:
  208. // currently we strictly prohibit multiple valid signing chains
  209. return nil, attestation.Invalidf("x5c contains multiple (%d) valid certificate chains", len(chains))
  210. }
  211. // Get signature
  212. sig, ok := attStmt["sig"].([]byte)
  213. if !ok {
  214. return nil, attestation.Invalidf("sig not present")
  215. }
  216. // Find the attestation certificate
  217. attCert := findAndroidAttestationCert(chains[0])
  218. if attCert == nil {
  219. return nil, attestation.Invalidf("no attestation certificate with OID 1.3.6.1.4.1.11129.2.1.17 found in the cert chain")
  220. }
  221. // Verify attestation statement sig
  222. if err := keyauth.Verify(attCert, keyAuth, sig); err != nil {
  223. return nil, err
  224. }
  225. data := &Data{
  226. Certificate: attCert,
  227. }
  228. if data.Fingerprint, err = keyutil.Fingerprint(attCert.PublicKey); err != nil {
  229. return nil, fmt.Errorf("error calculating key fingerprint: %w", err)
  230. }
  231. for _, ext := range attCert.Extensions {
  232. if !ext.Id.Equal(oidAndroidAttestation) {
  233. continue
  234. }
  235. keyDesc, err := keyattestation.ParseExtension(ext.Value)
  236. if err != nil {
  237. return nil, attestation.Invalid(fmt.Errorf("%w: %w", ErrKeyDescription, err))
  238. }
  239. data.KeyDescription = keyDesc
  240. break
  241. }
  242. // Validate key authorization
  243. if !bytes.Equal(data.KeyDescription.AttestationChallenge, keyAuth) {
  244. return nil, attestation.Invalidf("challenge mismatch; expected %q, got %q", keyAuth, data.KeyDescription.AttestationChallenge)
  245. }
  246. return data, nil
  247. }