challenge_tpmsimulator_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. //go:build tpmsimulator
  2. // +build tpmsimulator
  3. package acme
  4. import (
  5. "context"
  6. "crypto"
  7. "crypto/sha256"
  8. "crypto/x509"
  9. "encoding/asn1"
  10. "encoding/base64"
  11. "encoding/json"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "net/url"
  16. "testing"
  17. "github.com/fxamacker/cbor/v2"
  18. "github.com/stretchr/testify/assert"
  19. "github.com/stretchr/testify/require"
  20. "github.com/smallstep/go-attestation/attest"
  21. "go.step.sm/crypto/jose"
  22. "go.step.sm/crypto/keyutil"
  23. "go.step.sm/crypto/minica"
  24. "go.step.sm/crypto/tpm"
  25. "go.step.sm/crypto/tpm/simulator"
  26. tpmstorage "go.step.sm/crypto/tpm/storage"
  27. "go.step.sm/crypto/x509util"
  28. )
  29. func newSimulatedTPM(t *testing.T) *tpm.TPM {
  30. t.Helper()
  31. tmpDir := t.TempDir()
  32. tpm, err := tpm.New(withSimulator(t), tpm.WithStore(tpmstorage.NewDirstore(tmpDir))) // TODO: provide in-memory storage implementation instead
  33. require.NoError(t, err)
  34. return tpm
  35. }
  36. func withSimulator(t *testing.T) tpm.NewTPMOption {
  37. t.Helper()
  38. var sim simulator.Simulator
  39. t.Cleanup(func() {
  40. if sim == nil {
  41. return
  42. }
  43. err := sim.Close()
  44. require.NoError(t, err)
  45. })
  46. sim, err := simulator.New()
  47. require.NoError(t, err)
  48. err = sim.Open()
  49. require.NoError(t, err)
  50. return tpm.WithSimulator(sim)
  51. }
  52. func generateKeyID(t *testing.T, pub crypto.PublicKey) []byte {
  53. t.Helper()
  54. b, err := x509.MarshalPKIXPublicKey(pub)
  55. require.NoError(t, err)
  56. hash := sha256.Sum256(b)
  57. return hash[:]
  58. }
  59. func mustAttestTPM(t *testing.T, keyAuthorization string, permanentIdentifiers []string) ([]byte, crypto.Signer, *x509.Certificate) {
  60. t.Helper()
  61. aca, err := minica.New(
  62. minica.WithName("TPM Testing"),
  63. minica.WithGetSignerFunc(
  64. func() (crypto.Signer, error) {
  65. return keyutil.GenerateSigner("RSA", "", 2048)
  66. },
  67. ),
  68. )
  69. require.NoError(t, err)
  70. // prepare simulated TPM and create an AK
  71. stpm := newSimulatedTPM(t)
  72. eks, err := stpm.GetEKs(context.Background())
  73. require.NoError(t, err)
  74. ak, err := stpm.CreateAK(context.Background(), "first-ak")
  75. require.NoError(t, err)
  76. require.NotNil(t, ak)
  77. // extract the AK public key // TODO(hs): replace this when there's a simpler method to get the AK public key (e.g. ak.Public())
  78. ap, err := ak.AttestationParameters(context.Background())
  79. require.NoError(t, err)
  80. akp, err := attest.ParseAKPublic(attest.TPMVersion20, ap.Public)
  81. require.NoError(t, err)
  82. // create template and sign certificate for the AK public key
  83. keyID := generateKeyID(t, eks[0].Public())
  84. template := &x509.Certificate{
  85. PublicKey: akp.Public,
  86. IsCA: false,
  87. UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
  88. }
  89. sans := []x509util.SubjectAlternativeName{}
  90. uris := []*url.URL{{Scheme: "urn", Opaque: "ek:sha256:" + base64.StdEncoding.EncodeToString(keyID)}}
  91. for _, pi := range permanentIdentifiers {
  92. sans = append(sans, x509util.SubjectAlternativeName{
  93. Type: x509util.PermanentIdentifierType,
  94. Value: pi,
  95. })
  96. }
  97. asn1Value := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMModel, "SLB 9670 TPM2.0", oidTPMVersion, "7.55"))
  98. sans = append(sans, x509util.SubjectAlternativeName{
  99. Type: x509util.DirectoryNameType,
  100. ASN1Value: asn1Value,
  101. })
  102. ext, err := createSubjectAltNameExtension(nil, nil, nil, uris, sans, true)
  103. require.NoError(t, err)
  104. ext.Set(template)
  105. akCert, err := aca.Sign(template)
  106. require.NoError(t, err)
  107. require.NotNil(t, akCert)
  108. // create a new key attested by the AK, while including
  109. // the key authorization bytes as qualifying data.
  110. keyAuthSum := sha256.Sum256([]byte(keyAuthorization))
  111. config := tpm.AttestKeyConfig{
  112. Algorithm: "RSA",
  113. Size: 2048,
  114. QualifyingData: keyAuthSum[:],
  115. }
  116. key, err := stpm.AttestKey(context.Background(), "first-ak", "first-key", config)
  117. require.NoError(t, err)
  118. require.NotNil(t, key)
  119. require.Equal(t, "first-key", key.Name())
  120. require.NotEqual(t, 0, len(key.Data()))
  121. require.Equal(t, "first-ak", key.AttestedBy())
  122. require.True(t, key.WasAttested())
  123. require.True(t, key.WasAttestedBy(ak))
  124. signer, err := key.Signer(context.Background())
  125. require.NoError(t, err)
  126. // prepare the attestation object with the AK certificate chain,
  127. // the attested key, its metadata and the signature signed by the
  128. // AK.
  129. params, err := key.CertificationParameters(context.Background())
  130. require.NoError(t, err)
  131. attObj, err := cbor.Marshal(struct {
  132. Format string `json:"fmt"`
  133. AttStatement map[string]interface{} `json:"attStmt,omitempty"`
  134. }{
  135. Format: "tpm",
  136. AttStatement: map[string]interface{}{
  137. "ver": "2.0",
  138. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  139. "alg": int64(-257), // RS256
  140. "sig": params.CreateSignature,
  141. "certInfo": params.CreateAttestation,
  142. "pubArea": params.Public,
  143. },
  144. })
  145. require.NoError(t, err)
  146. // marshal the ACME payload
  147. payload, err := json.Marshal(struct {
  148. AttObj string `json:"attObj"`
  149. }{
  150. AttObj: base64.RawURLEncoding.EncodeToString(attObj),
  151. })
  152. require.NoError(t, err)
  153. return payload, signer, aca.Root
  154. }
  155. func Test_deviceAttest01ValidateWithTPMSimulator(t *testing.T) {
  156. type args struct {
  157. ctx context.Context
  158. ch *Challenge
  159. db DB
  160. jwk *jose.JSONWebKey
  161. payload []byte
  162. }
  163. type test struct {
  164. args args
  165. wantErr *Error
  166. }
  167. tests := map[string]func(t *testing.T) test{
  168. "ok/doTPMAttestationFormat-storeError": func(t *testing.T) test {
  169. jwk, keyAuth := mustAccountAndKeyAuthorization(t, "token")
  170. payload, _, root := mustAttestTPM(t, keyAuth, nil) // TODO: value(s) for AK cert?
  171. caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
  172. ctx := NewProvisionerContext(context.Background(), mustAttestationProvisioner(t, caRoot))
  173. // parse payload, set invalid "ver", remarshal
  174. var p payloadType
  175. err := json.Unmarshal(payload, &p)
  176. require.NoError(t, err)
  177. attObj, err := base64.RawURLEncoding.DecodeString(p.AttObj)
  178. require.NoError(t, err)
  179. att := attestationObject{}
  180. err = cbor.Unmarshal(attObj, &att)
  181. require.NoError(t, err)
  182. att.AttStatement["ver"] = "bogus"
  183. attObj, err = cbor.Marshal(struct {
  184. Format string `json:"fmt"`
  185. AttStatement map[string]interface{} `json:"attStmt,omitempty"`
  186. }{
  187. Format: "tpm",
  188. AttStatement: att.AttStatement,
  189. })
  190. require.NoError(t, err)
  191. payload, err = json.Marshal(struct {
  192. AttObj string `json:"attObj"`
  193. }{
  194. AttObj: base64.RawURLEncoding.EncodeToString(attObj),
  195. })
  196. require.NoError(t, err)
  197. return test{
  198. args: args{
  199. ctx: ctx,
  200. jwk: jwk,
  201. ch: &Challenge{
  202. ID: "chID",
  203. AuthorizationID: "azID",
  204. Token: "token",
  205. Type: "device-attest-01",
  206. Status: StatusPending,
  207. Value: "device.id.12345678",
  208. },
  209. payload: payload,
  210. db: &MockDB{
  211. MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
  212. assert.Equal(t, "azID", id)
  213. return &Authorization{ID: "azID"}, nil
  214. },
  215. MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
  216. assert.Equal(t, "chID", updch.ID)
  217. assert.Equal(t, "token", updch.Token)
  218. assert.Equal(t, StatusInvalid, updch.Status)
  219. assert.Equal(t, ChallengeType("device-attest-01"), updch.Type)
  220. assert.Equal(t, "device.id.12345678", updch.Value)
  221. err := NewDetailedError(ErrorBadAttestationStatementType, `version "bogus" is not supported`)
  222. assert.EqualError(t, updch.Error.Err, err.Err.Error())
  223. assert.Equal(t, err.Type, updch.Error.Type)
  224. assert.Equal(t, err.Detail, updch.Error.Detail)
  225. assert.Equal(t, err.Status, updch.Error.Status)
  226. assert.Equal(t, err.Subproblems, updch.Error.Subproblems)
  227. return nil
  228. },
  229. },
  230. },
  231. wantErr: nil,
  232. }
  233. },
  234. "ok with invalid PermanentIdentifier SAN": func(t *testing.T) test {
  235. jwk, keyAuth := mustAccountAndKeyAuthorization(t, "token")
  236. payload, _, root := mustAttestTPM(t, keyAuth, []string{"device.id.12345678"}) // TODO: value(s) for AK cert?
  237. caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
  238. ctx := NewProvisionerContext(context.Background(), mustAttestationProvisioner(t, caRoot))
  239. return test{
  240. args: args{
  241. ctx: ctx,
  242. jwk: jwk,
  243. ch: &Challenge{
  244. ID: "chID",
  245. AuthorizationID: "azID",
  246. Token: "token",
  247. Type: "device-attest-01",
  248. Status: StatusPending,
  249. Value: "device.id.99999999",
  250. },
  251. payload: payload,
  252. db: &MockDB{
  253. MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
  254. assert.Equal(t, "azID", id)
  255. return &Authorization{ID: "azID"}, nil
  256. },
  257. MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
  258. assert.Equal(t, "chID", updch.ID)
  259. assert.Equal(t, "token", updch.Token)
  260. assert.Equal(t, StatusInvalid, updch.Status)
  261. assert.Equal(t, ChallengeType("device-attest-01"), updch.Type)
  262. assert.Equal(t, "device.id.99999999", updch.Value)
  263. err := NewDetailedError(ErrorBadAttestationStatementType, `permanent identifier does not match`).
  264. AddSubproblems(NewSubproblemWithIdentifier(
  265. ErrorRejectedIdentifierType,
  266. Identifier{Type: "permanent-identifier", Value: "device.id.99999999"},
  267. `challenge identifier "device.id.99999999" doesn't match any of the attested hardware identifiers ["device.id.12345678"]`,
  268. ))
  269. assert.EqualError(t, updch.Error.Err, err.Err.Error())
  270. assert.Equal(t, err.Type, updch.Error.Type)
  271. assert.Equal(t, err.Detail, updch.Error.Detail)
  272. assert.Equal(t, err.Status, updch.Error.Status)
  273. assert.Equal(t, err.Subproblems, updch.Error.Subproblems)
  274. return nil
  275. },
  276. },
  277. },
  278. wantErr: nil,
  279. }
  280. },
  281. "ok": func(t *testing.T) test {
  282. jwk, keyAuth := mustAccountAndKeyAuthorization(t, "token")
  283. payload, signer, root := mustAttestTPM(t, keyAuth, nil) // TODO: value(s) for AK cert?
  284. caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
  285. ctx := NewProvisionerContext(context.Background(), mustAttestationProvisioner(t, caRoot))
  286. return test{
  287. args: args{
  288. ctx: ctx,
  289. jwk: jwk,
  290. ch: &Challenge{
  291. ID: "chID",
  292. AuthorizationID: "azID",
  293. Token: "token",
  294. Type: "device-attest-01",
  295. Status: StatusPending,
  296. Value: "device.id.12345678",
  297. },
  298. payload: payload,
  299. db: &MockDB{
  300. MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
  301. assert.Equal(t, "azID", id)
  302. return &Authorization{ID: "azID"}, nil
  303. },
  304. MockUpdateAuthorization: func(ctx context.Context, az *Authorization) error {
  305. fingerprint, err := keyutil.Fingerprint(signer.Public())
  306. assert.NoError(t, err)
  307. assert.Equal(t, "azID", az.ID)
  308. assert.Equal(t, fingerprint, az.Fingerprint)
  309. return nil
  310. },
  311. MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
  312. assert.Equal(t, "chID", updch.ID)
  313. assert.Equal(t, "token", updch.Token)
  314. assert.Equal(t, StatusValid, updch.Status)
  315. assert.Equal(t, ChallengeType("device-attest-01"), updch.Type)
  316. assert.Equal(t, "device.id.12345678", updch.Value)
  317. return nil
  318. },
  319. },
  320. },
  321. wantErr: nil,
  322. }
  323. },
  324. "ok with PermanentIdentifier SAN": func(t *testing.T) test {
  325. jwk, keyAuth := mustAccountAndKeyAuthorization(t, "token")
  326. payload, signer, root := mustAttestTPM(t, keyAuth, []string{"device.id.12345678"}) // TODO: value(s) for AK cert?
  327. caRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: root.Raw})
  328. ctx := NewProvisionerContext(context.Background(), mustAttestationProvisioner(t, caRoot))
  329. return test{
  330. args: args{
  331. ctx: ctx,
  332. jwk: jwk,
  333. ch: &Challenge{
  334. ID: "chID",
  335. AuthorizationID: "azID",
  336. Token: "token",
  337. Type: "device-attest-01",
  338. Status: StatusPending,
  339. Value: "device.id.12345678",
  340. },
  341. payload: payload,
  342. db: &MockDB{
  343. MockGetAuthorization: func(ctx context.Context, id string) (*Authorization, error) {
  344. assert.Equal(t, "azID", id)
  345. return &Authorization{ID: "azID"}, nil
  346. },
  347. MockUpdateAuthorization: func(ctx context.Context, az *Authorization) error {
  348. fingerprint, err := keyutil.Fingerprint(signer.Public())
  349. assert.NoError(t, err)
  350. assert.Equal(t, "azID", az.ID)
  351. assert.Equal(t, fingerprint, az.Fingerprint)
  352. return nil
  353. },
  354. MockUpdateChallenge: func(ctx context.Context, updch *Challenge) error {
  355. assert.Equal(t, "chID", updch.ID)
  356. assert.Equal(t, "token", updch.Token)
  357. assert.Equal(t, StatusValid, updch.Status)
  358. assert.Equal(t, ChallengeType("device-attest-01"), updch.Type)
  359. assert.Equal(t, "device.id.12345678", updch.Value)
  360. return nil
  361. },
  362. },
  363. },
  364. wantErr: nil,
  365. }
  366. },
  367. }
  368. for name, run := range tests {
  369. t.Run(name, func(t *testing.T) {
  370. tc := run(t)
  371. if err := deviceAttest01Validate(tc.args.ctx, tc.args.ch, tc.args.db, tc.args.jwk, tc.args.payload); err != nil {
  372. assert.Error(t, tc.wantErr)
  373. assert.EqualError(t, err, tc.wantErr.Error())
  374. return
  375. }
  376. assert.Nil(t, tc.wantErr)
  377. })
  378. }
  379. }
  380. func newBadAttestationStatementError(msg string) *Error {
  381. return &Error{
  382. Type: "urn:ietf:params:acme:error:badAttestationStatement",
  383. Status: 400,
  384. Err: errors.New(msg),
  385. }
  386. }
  387. func newInternalServerError(msg string) *Error {
  388. return &Error{
  389. Type: "urn:ietf:params:acme:error:serverInternal",
  390. Status: 500,
  391. Err: errors.New(msg),
  392. }
  393. }
  394. var (
  395. oidPermanentIdentifier = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 8, 3}
  396. oidHardwareModuleNameIdentifier = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 8, 4}
  397. )
  398. func Test_doTPMAttestationFormat(t *testing.T) {
  399. ctx := context.Background()
  400. aca, err := minica.New(
  401. minica.WithName("TPM Testing"),
  402. minica.WithGetSignerFunc(
  403. func() (crypto.Signer, error) {
  404. return keyutil.GenerateSigner("RSA", "", 2048)
  405. },
  406. ),
  407. )
  408. require.NoError(t, err)
  409. acaRoot := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: aca.Root.Raw})
  410. // prepare simulated TPM and create an AK
  411. stpm := newSimulatedTPM(t)
  412. eks, err := stpm.GetEKs(context.Background())
  413. require.NoError(t, err)
  414. ak, err := stpm.CreateAK(context.Background(), "first-ak")
  415. require.NoError(t, err)
  416. require.NotNil(t, ak)
  417. // extract the AK public key // TODO(hs): replace this when there's a simpler method to get the AK public key (e.g. ak.Public())
  418. ap, err := ak.AttestationParameters(context.Background())
  419. require.NoError(t, err)
  420. akp, err := attest.ParseAKPublic(attest.TPMVersion20, ap.Public)
  421. require.NoError(t, err)
  422. // create template and sign certificate for the AK public key
  423. keyID := generateKeyID(t, eks[0].Public())
  424. template := &x509.Certificate{
  425. PublicKey: akp.Public,
  426. IsCA: false,
  427. UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
  428. }
  429. sans := []x509util.SubjectAlternativeName{}
  430. uris := []*url.URL{{Scheme: "urn", Opaque: "ek:sha256:" + base64.StdEncoding.EncodeToString(keyID)}}
  431. asn1Value := []byte(fmt.Sprintf(`{"extraNames":[{"type": %q, "value": %q},{"type": %q, "value": %q},{"type": %q, "value": %q}]}`, oidTPMManufacturer, "1414747215", oidTPMModel, "SLB 9670 TPM2.0", oidTPMVersion, "7.55"))
  432. sans = append(sans, x509util.SubjectAlternativeName{
  433. Type: x509util.DirectoryNameType,
  434. ASN1Value: asn1Value,
  435. })
  436. ext, err := createSubjectAltNameExtension(nil, nil, nil, uris, sans, true)
  437. require.NoError(t, err)
  438. ext.Set(template)
  439. akCert, err := aca.Sign(template)
  440. require.NoError(t, err)
  441. require.NotNil(t, akCert)
  442. invalidTemplate := &x509.Certificate{
  443. PublicKey: akp.Public,
  444. IsCA: false,
  445. UnknownExtKeyUsage: []asn1.ObjectIdentifier{oidTCGKpAIKCertificate},
  446. }
  447. invalidAKCert, err := aca.Sign(invalidTemplate)
  448. require.NoError(t, err)
  449. require.NotNil(t, invalidAKCert)
  450. // generate a JWK and the key authorization value
  451. jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  452. require.NoError(t, err)
  453. keyAuthorization, err := KeyAuthorization("token", jwk)
  454. require.NoError(t, err)
  455. // create a new key attested by the AK, while including
  456. // the key authorization bytes as qualifying data.
  457. keyAuthSum := sha256.Sum256([]byte(keyAuthorization))
  458. config := tpm.AttestKeyConfig{
  459. Algorithm: "RSA",
  460. Size: 2048,
  461. QualifyingData: keyAuthSum[:],
  462. }
  463. key, err := stpm.AttestKey(context.Background(), "first-ak", "first-key", config)
  464. require.NoError(t, err)
  465. require.NotNil(t, key)
  466. params, err := key.CertificationParameters(context.Background())
  467. require.NoError(t, err)
  468. signer, err := key.Signer(context.Background())
  469. require.NoError(t, err)
  470. fingerprint, err := keyutil.Fingerprint(signer.Public())
  471. require.NoError(t, err)
  472. // attest another key and get its certification parameters
  473. anotherKey, err := stpm.AttestKey(context.Background(), "first-ak", "another-key", config)
  474. require.NoError(t, err)
  475. require.NotNil(t, key)
  476. anotherKeyParams, err := anotherKey.CertificationParameters(context.Background())
  477. require.NoError(t, err)
  478. type args struct {
  479. ctx context.Context
  480. prov Provisioner
  481. ch *Challenge
  482. jwk *jose.JSONWebKey
  483. att *attestationObject
  484. }
  485. tests := []struct {
  486. name string
  487. args args
  488. want *tpmAttestationData
  489. expErr *Error
  490. }{
  491. {"ok", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  492. Format: "tpm",
  493. AttStatement: map[string]interface{}{
  494. "ver": "2.0",
  495. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  496. "alg": int64(-257), // RS256
  497. "sig": params.CreateSignature,
  498. "certInfo": params.CreateAttestation,
  499. "pubArea": params.Public,
  500. },
  501. }}, nil, nil},
  502. {"fail ver not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  503. Format: "tpm",
  504. AttStatement: map[string]interface{}{
  505. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  506. "alg": int64(-257), // RS256
  507. "sig": params.CreateSignature,
  508. "certInfo": params.CreateAttestation,
  509. "pubArea": params.Public,
  510. },
  511. }}, nil, newBadAttestationStatementError("ver not present")},
  512. {"fail ver type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  513. Format: "tpm",
  514. AttStatement: map[string]interface{}{
  515. "ver": []interface{}{},
  516. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  517. "alg": int64(-257), // RS256
  518. "sig": params.CreateSignature,
  519. "certInfo": params.CreateAttestation,
  520. "pubArea": params.Public,
  521. },
  522. }}, nil, newBadAttestationStatementError("ver not present")},
  523. {"fail bogus ver", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  524. Format: "tpm",
  525. AttStatement: map[string]interface{}{
  526. "ver": "bogus",
  527. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  528. "alg": int64(-257), // RS256
  529. "sig": params.CreateSignature,
  530. "certInfo": params.CreateAttestation,
  531. "pubArea": params.Public,
  532. },
  533. }}, nil, newBadAttestationStatementError(`version "bogus" is not supported`)},
  534. {"fail x5c not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  535. Format: "tpm",
  536. AttStatement: map[string]interface{}{
  537. "ver": "2.0",
  538. "alg": int64(-257), // RS256
  539. "sig": params.CreateSignature,
  540. "certInfo": params.CreateAttestation,
  541. "pubArea": params.Public,
  542. },
  543. }}, nil, newBadAttestationStatementError("x5c not present")},
  544. {"fail x5c type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  545. Format: "tpm",
  546. AttStatement: map[string]interface{}{
  547. "ver": "2.0",
  548. "x5c": [][]byte{akCert.Raw, aca.Intermediate.Raw},
  549. "alg": int64(-257), // RS256
  550. "sig": params.CreateSignature,
  551. "certInfo": params.CreateAttestation,
  552. "pubArea": params.Public,
  553. },
  554. }}, nil, newBadAttestationStatementError("x5c not present")},
  555. {"fail x5c empty", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  556. Format: "tpm",
  557. AttStatement: map[string]interface{}{
  558. "ver": "2.0",
  559. "x5c": []interface{}{},
  560. "alg": int64(-257), // RS256
  561. "sig": params.CreateSignature,
  562. "certInfo": params.CreateAttestation,
  563. "pubArea": params.Public,
  564. },
  565. }}, nil, newBadAttestationStatementError("x5c is empty")},
  566. {"fail leaf type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  567. Format: "step",
  568. AttStatement: map[string]interface{}{
  569. "ver": "2.0",
  570. "x5c": []interface{}{"leaf", aca.Intermediate.Raw},
  571. "alg": int64(-257), // RS256
  572. "sig": params.CreateSignature,
  573. "certInfo": params.CreateAttestation,
  574. "pubArea": params.Public,
  575. },
  576. }}, nil, newBadAttestationStatementError("x5c is malformed")},
  577. {"fail leaf parse", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  578. Format: "step",
  579. AttStatement: map[string]interface{}{
  580. "ver": "2.0",
  581. "x5c": []interface{}{akCert.Raw[:100], aca.Intermediate.Raw},
  582. "alg": int64(-257), // RS256
  583. "sig": params.CreateSignature,
  584. "certInfo": params.CreateAttestation,
  585. "pubArea": params.Public,
  586. },
  587. }}, nil, newBadAttestationStatementError("x5c is malformed: x509: malformed certificate")},
  588. {"fail intermediate type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  589. Format: "step",
  590. AttStatement: map[string]interface{}{
  591. "ver": "2.0",
  592. "x5c": []interface{}{akCert.Raw, "intermediate"},
  593. "alg": int64(-257), // RS256
  594. "sig": params.CreateSignature,
  595. "certInfo": params.CreateAttestation,
  596. "pubArea": params.Public,
  597. },
  598. }}, nil, newBadAttestationStatementError("x5c is malformed")},
  599. {"fail intermediate parse", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  600. Format: "step",
  601. AttStatement: map[string]interface{}{
  602. "ver": "2.0",
  603. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw[:100]},
  604. "alg": int64(-257), // RS256
  605. "sig": params.CreateSignature,
  606. "certInfo": params.CreateAttestation,
  607. "pubArea": params.Public,
  608. },
  609. }}, nil, newBadAttestationStatementError("x5c is malformed: x509: malformed certificate")},
  610. {"fail roots", args{ctx, mustAttestationProvisioner(t, nil), &Challenge{Token: "token"}, jwk, &attestationObject{
  611. Format: "tpm",
  612. AttStatement: map[string]interface{}{
  613. "ver": "2.0",
  614. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  615. "alg": int64(-257), // RS256
  616. "sig": params.CreateSignature,
  617. "certInfo": params.CreateAttestation,
  618. "pubArea": params.Public,
  619. },
  620. }}, nil, newInternalServerError("no root CA bundle available to verify the attestation certificate")},
  621. {"fail verify", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  622. Format: "step",
  623. AttStatement: map[string]interface{}{
  624. "ver": "2.0",
  625. "x5c": []interface{}{akCert.Raw},
  626. "alg": int64(-257), // RS256
  627. "sig": params.CreateSignature,
  628. "certInfo": params.CreateAttestation,
  629. "pubArea": params.Public,
  630. },
  631. }}, nil, newBadAttestationStatementError("x5c is not valid: x509: certificate signed by unknown authority")},
  632. {"fail validateAKCertificate", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  633. Format: "tpm",
  634. AttStatement: map[string]interface{}{
  635. "ver": "2.0",
  636. "x5c": []interface{}{invalidAKCert.Raw, aca.Intermediate.Raw},
  637. "alg": int64(-257), // RS256
  638. "sig": params.CreateSignature,
  639. "certInfo": params.CreateAttestation,
  640. "pubArea": params.Public,
  641. },
  642. }}, nil, newBadAttestationStatementError("AK certificate is not valid: missing TPM manufacturer")},
  643. {"fail pubArea not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  644. Format: "tpm",
  645. AttStatement: map[string]interface{}{
  646. "ver": "2.0",
  647. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  648. "alg": int64(-257), // RS256
  649. "sig": params.CreateSignature,
  650. "certInfo": params.CreateAttestation,
  651. },
  652. }}, nil, newBadAttestationStatementError("invalid pubArea in attestation statement")},
  653. {"fail pubArea type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  654. Format: "tpm",
  655. AttStatement: map[string]interface{}{
  656. "ver": "2.0",
  657. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  658. "alg": int64(-257), // RS256
  659. "sig": params.CreateSignature,
  660. "certInfo": params.CreateAttestation,
  661. "pubArea": []interface{}{},
  662. },
  663. }}, nil, newBadAttestationStatementError("invalid pubArea in attestation statement")},
  664. {"fail pubArea empty", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  665. Format: "tpm",
  666. AttStatement: map[string]interface{}{
  667. "ver": "2.0",
  668. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  669. "alg": int64(-257), // RS256
  670. "sig": params.CreateSignature,
  671. "certInfo": params.CreateAttestation,
  672. "pubArea": []byte{},
  673. },
  674. }}, nil, newBadAttestationStatementError("pubArea is empty")},
  675. {"fail sig not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  676. Format: "tpm",
  677. AttStatement: map[string]interface{}{
  678. "ver": "2.0",
  679. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  680. "alg": int64(-257), // RS256
  681. "certInfo": params.CreateAttestation,
  682. "pubArea": params.Public,
  683. },
  684. }}, nil, newBadAttestationStatementError("invalid sig in attestation statement")},
  685. {"fail sig type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  686. Format: "tpm",
  687. AttStatement: map[string]interface{}{
  688. "ver": "2.0",
  689. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  690. "alg": int64(-257), // RS256
  691. "sig": []interface{}{},
  692. "certInfo": params.CreateAttestation,
  693. "pubArea": params.Public,
  694. },
  695. }}, nil, newBadAttestationStatementError("invalid sig in attestation statement")},
  696. {"fail sig empty", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  697. Format: "tpm",
  698. AttStatement: map[string]interface{}{
  699. "ver": "2.0",
  700. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  701. "alg": int64(-257), // RS256
  702. "sig": []byte{},
  703. "certInfo": params.CreateAttestation,
  704. "pubArea": params.Public,
  705. },
  706. }}, nil, newBadAttestationStatementError("sig is empty")},
  707. {"fail certInfo not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  708. Format: "tpm",
  709. AttStatement: map[string]interface{}{
  710. "ver": "2.0",
  711. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  712. "alg": int64(-257), // RS256
  713. "sig": params.CreateSignature,
  714. "pubArea": params.Public,
  715. },
  716. }}, nil, newBadAttestationStatementError("invalid certInfo in attestation statement")},
  717. {"fail certInfo type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  718. Format: "tpm",
  719. AttStatement: map[string]interface{}{
  720. "ver": "2.0",
  721. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  722. "alg": int64(-257), // RS256
  723. "sig": params.CreateSignature,
  724. "certInfo": []interface{}{},
  725. "pubArea": params.Public,
  726. },
  727. }}, nil, newBadAttestationStatementError("invalid certInfo in attestation statement")},
  728. {"fail certInfo empty", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  729. Format: "tpm",
  730. AttStatement: map[string]interface{}{
  731. "ver": "2.0",
  732. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  733. "alg": int64(-257), // RS256
  734. "sig": params.CreateSignature,
  735. "certInfo": []byte{},
  736. "pubArea": params.Public,
  737. },
  738. }}, nil, newBadAttestationStatementError("certInfo is empty")},
  739. {"fail alg not present", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  740. Format: "tpm",
  741. AttStatement: map[string]interface{}{
  742. "ver": "2.0",
  743. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  744. "sig": params.CreateSignature,
  745. "certInfo": params.CreateAttestation,
  746. "pubArea": params.Public,
  747. },
  748. }}, nil, newBadAttestationStatementError("invalid alg in attestation statement")},
  749. {"fail alg type", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  750. Format: "tpm",
  751. AttStatement: map[string]interface{}{
  752. "ver": "2.0",
  753. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  754. "alg": int64(0), // invalid alg
  755. "sig": params.CreateSignature,
  756. "certInfo": params.CreateAttestation,
  757. "pubArea": params.Public,
  758. },
  759. }}, nil, newBadAttestationStatementError("invalid alg 0 in attestation statement")},
  760. {"fail attestation verification", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, jwk, &attestationObject{
  761. Format: "tpm",
  762. AttStatement: map[string]interface{}{
  763. "ver": "2.0",
  764. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  765. "alg": int64(-257), // RS256
  766. "sig": params.CreateSignature,
  767. "certInfo": params.CreateAttestation,
  768. "pubArea": anotherKeyParams.Public,
  769. },
  770. }}, nil, newBadAttestationStatementError("invalid certification parameters: certification refers to a different key")},
  771. {"fail keyAuthorization", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "token"}, &jose.JSONWebKey{Key: []byte("not an asymmetric key")}, &attestationObject{
  772. Format: "tpm",
  773. AttStatement: map[string]interface{}{
  774. "ver": "2.0",
  775. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  776. "alg": int64(-257), // RS256
  777. "sig": params.CreateSignature,
  778. "certInfo": params.CreateAttestation,
  779. "pubArea": params.Public,
  780. },
  781. }}, nil, newInternalServerError("failed creating key auth digest: error generating JWK thumbprint: go-jose/go-jose: unknown key type '[]uint8'")},
  782. {"fail different keyAuthorization", args{ctx, mustAttestationProvisioner(t, acaRoot), &Challenge{Token: "aDifferentToken"}, jwk, &attestationObject{
  783. Format: "tpm",
  784. AttStatement: map[string]interface{}{
  785. "ver": "2.0",
  786. "x5c": []interface{}{akCert.Raw, aca.Intermediate.Raw},
  787. "alg": int64(-257), //
  788. "sig": params.CreateSignature,
  789. "certInfo": params.CreateAttestation,
  790. "pubArea": params.Public,
  791. },
  792. }}, nil, newBadAttestationStatementError("key authorization invalid")},
  793. }
  794. for _, tt := range tests {
  795. t.Run(tt.name, func(t *testing.T) {
  796. got, err := doTPMAttestationFormat(tt.args.ctx, tt.args.prov, tt.args.ch, tt.args.jwk, tt.args.att)
  797. if tt.expErr != nil {
  798. var ae *Error
  799. if assert.True(t, errors.As(err, &ae)) {
  800. assert.EqualError(t, err, tt.expErr.Error())
  801. assert.Equal(t, ae.StatusCode(), tt.expErr.StatusCode())
  802. assert.Equal(t, ae.Type, tt.expErr.Type)
  803. }
  804. assert.Nil(t, got)
  805. return
  806. }
  807. assert.NoError(t, err)
  808. if assert.NotNil(t, got) {
  809. assert.Equal(t, akCert, got.Certificate)
  810. assert.Equal(t, [][]*x509.Certificate{
  811. {
  812. akCert, aca.Intermediate, aca.Root,
  813. },
  814. }, got.VerifiedChains)
  815. assert.Equal(t, fingerprint, got.Fingerprint)
  816. assert.Empty(t, got.PermanentIdentifiers) // currently expected to be always empty
  817. }
  818. })
  819. }
  820. }