tpm.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // Package tpm verifies attestation statements of the "tpm" format of ACME
  2. // device-attest-01 challenges, made with the attestation keys of TPM 2.0
  3. // devices.
  4. package tpm
  5. import (
  6. "crypto"
  7. "crypto/sha256"
  8. "crypto/subtle"
  9. "crypto/x509"
  10. "encoding/asn1"
  11. "errors"
  12. "fmt"
  13. "time"
  14. "github.com/google/go-tpm/legacy/tpm2"
  15. "github.com/smallstep/go-attestation/attest"
  16. "go.step.sm/crypto/keyutil"
  17. "go.step.sm/crypto/x509util"
  18. "github.com/smallstep/certificates/attestation"
  19. "github.com/smallstep/certificates/internal/cast"
  20. )
  21. var (
  22. oidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
  23. )
  24. // Data is what a verified "tpm" attestation statement attests.
  25. type Data struct {
  26. // Certificate is the AK certificate, the leaf of the x5c chain.
  27. Certificate *x509.Certificate
  28. // VerifiedChains are the chains from the AK certificate to the roots.
  29. VerifiedChains [][]*x509.Certificate
  30. // PermanentIdentifiers are the permanent identifiers in the Subject
  31. // Alternative Names of the AK certificate.
  32. PermanentIdentifiers []string
  33. // Fingerprint is the fingerprint of the attested key.
  34. Fingerprint string
  35. }
  36. // coseAlgorithmIdentifier models a COSEAlgorithmIdentifier.
  37. // Also see https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier.
  38. type coseAlgorithmIdentifier int32
  39. const (
  40. coseAlgES256 = coseAlgorithmIdentifier(-7)
  41. coseAlgRS256 = coseAlgorithmIdentifier(-257)
  42. coseAlgRS1 = coseAlgorithmIdentifier(-65535) // deprecated, but (still) often used in TPMs
  43. )
  44. // Verify verifies a "tpm" attestation statement: the x5c chain of its AK
  45. // certificate against roots, the requirements on the AK certificate, the
  46. // certification of the attested key by the AK, and that the certification's
  47. // extra data is the SHA-256 digest of keyAuth, the key authorization of the
  48. // challenge. It returns what the AK certificate and the certification attest.
  49. // There are no default roots: Verify fails if roots is nil. Errors of the
  50. // statement match attestation.ErrInvalidEvidence.
  51. func Verify(attStmt map[string]any, roots *x509.CertPool, keyAuth []byte) (*Data, error) {
  52. ver, ok := attStmt["ver"].(string)
  53. if !ok {
  54. return nil, attestation.Invalidf("ver not present")
  55. }
  56. if ver != "2.0" {
  57. return nil, attestation.Invalidf("version %q is not supported", ver)
  58. }
  59. x5c, ok := attStmt["x5c"].([]any)
  60. if !ok {
  61. return nil, attestation.Invalidf("x5c not present")
  62. }
  63. if len(x5c) == 0 {
  64. return nil, attestation.Invalidf("x5c is empty")
  65. }
  66. akCertBytes, ok := x5c[0].([]byte)
  67. if !ok {
  68. return nil, attestation.Invalidf("x5c is malformed")
  69. }
  70. akCert, err := x509.ParseCertificate(akCertBytes)
  71. if err != nil {
  72. return nil, attestation.Invalidf("x5c is malformed: %w", err)
  73. }
  74. intermediates := x509.NewCertPool()
  75. for _, v := range x5c[1:] {
  76. intCertBytes, vok := v.([]byte)
  77. if !vok {
  78. return nil, attestation.Invalidf("x5c is malformed")
  79. }
  80. intCert, err := x509.ParseCertificate(intCertBytes)
  81. if err != nil {
  82. return nil, attestation.Invalidf("x5c is malformed: %w", err)
  83. }
  84. intermediates.AddCert(intCert)
  85. }
  86. // TODO(hs): this can be removed when permanent-identifier/hardware-module-name are handled correctly in
  87. // the stdlib in https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/crypto/x509/parser.go;drc=b5b2cf519fe332891c165077f3723ee74932a647;l=362,
  88. // but I doubt that will happen.
  89. if len(akCert.UnhandledCriticalExtensions) > 0 {
  90. unhandledCriticalExtensions := akCert.UnhandledCriticalExtensions[:0]
  91. for _, extOID := range akCert.UnhandledCriticalExtensions {
  92. if !extOID.Equal(oidSubjectAlternativeName) {
  93. // critical extensions other than the Subject Alternative Name remain unhandled
  94. unhandledCriticalExtensions = append(unhandledCriticalExtensions, extOID)
  95. }
  96. }
  97. akCert.UnhandledCriticalExtensions = unhandledCriticalExtensions
  98. }
  99. if roots == nil {
  100. return nil, errors.New("no root CA bundle available to verify the attestation certificate")
  101. }
  102. // verify that the AK certificate was signed by a trusted root,
  103. // chained to by the intermediates provided by the client. As part
  104. // of building the verified certificate chain, the signature over the
  105. // AK certificate is checked to be a valid signature of one of the
  106. // provided intermediates. Signatures over the intermediates are in
  107. // turn also verified to be valid signatures from one of the trusted
  108. // roots.
  109. verifiedChains, err := akCert.Verify(x509.VerifyOptions{
  110. Roots: roots,
  111. Intermediates: intermediates,
  112. CurrentTime: time.Now().Truncate(time.Second),
  113. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  114. })
  115. if err != nil {
  116. return nil, attestation.Invalidf("x5c is not valid: %w", err)
  117. }
  118. // validate additional AK certificate requirements
  119. if err := validateAKCertificate(akCert); err != nil {
  120. return nil, attestation.Invalidf("AK certificate is not valid: %w", err)
  121. }
  122. // TODO(hs): implement revocation check; Verify() doesn't perform CRL check nor OCSP lookup.
  123. sans, err := x509util.ParseSubjectAlternativeNames(akCert)
  124. if err != nil {
  125. return nil, attestation.Invalidf("failed parsing AK certificate Subject Alternative Names: %w", err)
  126. }
  127. permanentIdentifiers := make([]string, len(sans.PermanentIdentifiers))
  128. for i, pi := range sans.PermanentIdentifiers {
  129. permanentIdentifiers[i] = pi.Identifier
  130. }
  131. // extract and validate pubArea, sig, certInfo and alg properties from the request body
  132. pubArea, ok := attStmt["pubArea"].([]byte)
  133. if !ok {
  134. return nil, attestation.Invalidf("invalid pubArea in attestation statement")
  135. }
  136. if len(pubArea) == 0 {
  137. return nil, attestation.Invalidf("pubArea is empty")
  138. }
  139. sig, ok := attStmt["sig"].([]byte)
  140. if !ok {
  141. return nil, attestation.Invalidf("invalid sig in attestation statement")
  142. }
  143. if len(sig) == 0 {
  144. return nil, attestation.Invalidf("sig is empty")
  145. }
  146. certInfo, ok := attStmt["certInfo"].([]byte)
  147. if !ok {
  148. return nil, attestation.Invalidf("invalid certInfo in attestation statement")
  149. }
  150. if len(certInfo) == 0 {
  151. return nil, attestation.Invalidf("certInfo is empty")
  152. }
  153. alg, ok := attStmt["alg"].(int64)
  154. if !ok {
  155. return nil, attestation.Invalidf("invalid alg in attestation statement")
  156. }
  157. algI32, err := cast.SafeInt32(alg)
  158. if err != nil {
  159. return nil, attestation.Invalidf("invalid alg %d in attestation statement: %w", alg, err)
  160. }
  161. var hash crypto.Hash
  162. switch coseAlgorithmIdentifier(algI32) {
  163. case coseAlgRS256, coseAlgES256:
  164. hash = crypto.SHA256
  165. case coseAlgRS1:
  166. hash = crypto.SHA1
  167. default:
  168. return nil, attestation.Invalidf("invalid alg %d in attestation statement", alg)
  169. }
  170. // recreate the generated key certification parameter values and verify
  171. // the attested key using the public key of the AK.
  172. certificationParameters := &attest.CertificationParameters{
  173. Public: pubArea, // the public key that was attested
  174. CreateAttestation: certInfo, // the attested properties of the key
  175. CreateSignature: sig, // signature over the attested properties
  176. }
  177. verifyOpts := attest.VerifyOpts{
  178. Public: akCert.PublicKey, // public key of the AK that attested the key
  179. Hash: hash,
  180. }
  181. if err = certificationParameters.Verify(verifyOpts); err != nil {
  182. return nil, attestation.Invalidf("invalid certification parameters: %w", err)
  183. }
  184. // decode the "certInfo" data. This won't fail, as it's also done as part of Verify().
  185. tpmCertInfo, err := tpm2.DecodeAttestationData(certInfo)
  186. if err != nil {
  187. return nil, attestation.Invalidf("failed decoding attestation data: %w", err)
  188. }
  189. hashedKeyAuth := sha256.Sum256(keyAuth)
  190. // verify the WebAuthn object contains the expect key authorization digest, which is carried
  191. // within the encoded `certInfo` property of the attestation statement.
  192. if subtle.ConstantTimeCompare(hashedKeyAuth[:], []byte(tpmCertInfo.ExtraData)) == 0 {
  193. return nil, attestation.Invalidf("key authorization invalid")
  194. }
  195. // decode the (attested) public key and determine its fingerprint. This won't fail, as it's also done as part of Verify().
  196. pub, err := tpm2.DecodePublic(pubArea)
  197. if err != nil {
  198. return nil, attestation.Invalidf("failed decoding pubArea: %w", err)
  199. }
  200. publicKey, err := pub.Key()
  201. if err != nil {
  202. return nil, attestation.Invalidf("failed getting public key: %w", err)
  203. }
  204. data := &Data{
  205. Certificate: akCert,
  206. VerifiedChains: verifiedChains,
  207. PermanentIdentifiers: permanentIdentifiers,
  208. }
  209. if data.Fingerprint, err = keyutil.Fingerprint(publicKey); err != nil {
  210. return nil, fmt.Errorf("error calculating key fingerprint: %w", err)
  211. }
  212. // TODO(hs): pass more attestation data, so that that can be used/recorded too?
  213. return data, nil
  214. }
  215. var (
  216. oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
  217. oidTCGKpAIKCertificate = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
  218. )
  219. // validateAKCertificate validates the X.509 AK certificate to be
  220. // in accordance with the required properties. The requirements come from:
  221. // https://www.w3.org/TR/webauthn-2/#sctn-tpm-cert-requirements.
  222. //
  223. // - Version MUST be set to 3.
  224. // - Subject field MUST be set to empty.
  225. // - The Subject Alternative Name extension MUST be set as defined
  226. // in [TPMv2-EK-Profile] section 3.2.9.
  227. // - The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
  228. // ("joint-iso-itu-t(2) international-organizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)").
  229. // - The Basic Constraints extension MUST have the CA component set to false.
  230. // - An Authority Information Access (AIA) extension with entry id-ad-ocsp
  231. // and a CRL Distribution Point extension [RFC5280] are both OPTIONAL as
  232. // the status of many attestation certificates is available through metadata
  233. // services. See, for example, the FIDO Metadata Service.
  234. func validateAKCertificate(c *x509.Certificate) error {
  235. if c.Version != 3 {
  236. return fmt.Errorf("AK certificate has invalid version %d; only version 3 is allowed", c.Version)
  237. }
  238. if c.Subject.String() != "" {
  239. return fmt.Errorf("AK certificate subject must be empty; got %q", c.Subject)
  240. }
  241. if c.IsCA {
  242. return errors.New("AK certificate must not be a CA")
  243. }
  244. if err := validateAKCertificateExtendedKeyUsage(c); err != nil {
  245. return err
  246. }
  247. return validateAKCertificateSubjectAlternativeNames(c)
  248. }
  249. // validateAKCertificateSubjectAlternativeNames checks if the AK certificate
  250. // has TPM hardware details set.
  251. func validateAKCertificateSubjectAlternativeNames(c *x509.Certificate) error {
  252. sans, err := x509util.ParseSubjectAlternativeNames(c)
  253. if err != nil {
  254. return fmt.Errorf("failed parsing AK certificate Subject Alternative Names: %w", err)
  255. }
  256. details := sans.TPMHardwareDetails
  257. manufacturer, model, version := details.Manufacturer, details.Model, details.Version
  258. switch {
  259. case manufacturer == "":
  260. return errors.New("missing TPM manufacturer")
  261. case model == "":
  262. return errors.New("missing TPM model")
  263. case version == "":
  264. return errors.New("missing TPM version")
  265. }
  266. return nil
  267. }
  268. // validateAKCertificateExtendedKeyUsage checks if the AK certificate
  269. // has the "tcg-kp-AIKCertificate" Extended Key Usage set.
  270. func validateAKCertificateExtendedKeyUsage(c *x509.Certificate) error {
  271. var (
  272. valid = false
  273. ekus []asn1.ObjectIdentifier
  274. )
  275. for _, ext := range c.Extensions {
  276. if ext.Id.Equal(oidExtensionExtendedKeyUsage) {
  277. if _, err := asn1.Unmarshal(ext.Value, &ekus); err != nil || len(ekus) == 0 || !ekus[0].Equal(oidTCGKpAIKCertificate) {
  278. return errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")
  279. }
  280. valid = true
  281. }
  282. }
  283. if !valid {
  284. return errors.New("AK certificate is missing Extended Key Usage extension")
  285. }
  286. return nil
  287. }