challenge_tpmsimulator_test.go 32 KB

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