challenge_remote_attestation_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package acme
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "crypto/sha256"
  9. "crypto/x509"
  10. "crypto/x509/pkix"
  11. "encoding/base64"
  12. "encoding/hex"
  13. "errors"
  14. "testing"
  15. "time"
  16. "github.com/stretchr/testify/assert"
  17. "github.com/stretchr/testify/require"
  18. "go.step.sm/crypto/keyutil"
  19. "go.step.sm/crypto/x509util"
  20. "github.com/smallstep/certificates/attestation"
  21. "github.com/smallstep/certificates/attestation/cmw"
  22. "github.com/smallstep/certificates/authority/provisioner"
  23. "github.com/smallstep/certificates/webhook"
  24. )
  25. const testFreshnessNonce = "yoW1RL2zPBzYEHBQ06Jy"
  26. // testRemoteAttestationCMW is a valid CMW record; the provisioner mocks decide
  27. // what it verifies to.
  28. var testRemoteAttestationCMW = []byte(`["application/eat+jwt", "ZXlKaGJHY2lPaUpTVXpJMU5pSjku", 8]`)
  29. func mustCSR(t *testing.T, cn string) (*x509.CertificateRequest, crypto.Signer) {
  30. t.Helper()
  31. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  32. require.NoError(t, err)
  33. der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
  34. Subject: pkix.Name{CommonName: cn},
  35. }, key)
  36. require.NoError(t, err)
  37. csr, err := x509.ParseCertificateRequest(der)
  38. require.NoError(t, err)
  39. return csr, key
  40. }
  41. // testBinding returns the binding the evidence of a challenge with the given
  42. // key authorization carries for the CSR's key.
  43. func testBinding(keyAuth string, csr *x509.CertificateRequest) []byte {
  44. sum := sha256.Sum256(append([]byte(keyAuth), csr.RawSubjectPublicKeyInfo...))
  45. return sum[:]
  46. }
  47. func TestRemoteAttestationBinding(t *testing.T) {
  48. csr, _ := mustCSR(t, "")
  49. want := testBinding("nonce.thumbprint", csr)
  50. assert.Equal(t, hex.EncodeToString(want), RemoteAttestationBinding("nonce.thumbprint", csr))
  51. assert.NotEqual(t, hex.EncodeToString(want), RemoteAttestationBinding("other.thumbprint", csr))
  52. }
  53. func TestRemoteAttest01Validate(t *testing.T) {
  54. jwk, keyAuth := mustAccountAndKeyAuthorization(t, testFreshnessNonce)
  55. csr, _ := mustCSR(t, "")
  56. binding := testBinding(keyAuth, csr)
  57. claimNonce := make([]byte, 32)
  58. for i := range claimNonce {
  59. claimNonce[i] = byte(i)
  60. }
  61. csResult := &attestation.Result{
  62. Format: attestation.FormatConfidentialSpace,
  63. MediaType: "application/eat+jwt",
  64. Evidence: []byte("token"),
  65. ConfidentialSpace: &attestation.ConfidentialSpace{Claims: map[string]any{"hwmodel": "GCP_INTEL_TDX"}},
  66. }
  67. tdxResult := &attestation.Result{Format: attestation.FormatTDX, TDX: &attestation.TDX{MRTD: "aa"}}
  68. type want struct {
  69. status Status
  70. errType string
  71. errDetail string
  72. err string
  73. stored bool
  74. format string
  75. claimNonce string
  76. result *attestation.Result
  77. }
  78. tests := []struct {
  79. name string
  80. payload []byte
  81. nonce string
  82. verify func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error)
  83. az func(az *Authorization)
  84. want want
  85. }{
  86. {"ok confidential space", testRemoteAttestationCMW, testFreshnessNonce,
  87. func(_ context.Context, r *cmw.Record, aud string) (*attestation.Result, []byte, error) {
  88. assert.Equal(t, "application/eat+jwt", r.MediaType)
  89. assert.Equal(t, "https://ca.example.com/acme/acme/directory", aud)
  90. return csResult, binding, nil
  91. }, nil, want{status: StatusValid, stored: true, format: "confidential-space", result: csResult}},
  92. // A quote's report data carries the relying party's claim nonce after
  93. // the binding.
  94. {"ok tdx with claim nonce", testRemoteAttestationCMW, testFreshnessNonce,
  95. func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
  96. return tdxResult, append(append([]byte(nil), binding...), claimNonce...), nil
  97. }, nil, want{status: StatusValid, stored: true, format: "tdx", result: tdxResult,
  98. claimNonce: base64.RawURLEncoding.EncodeToString(claimNonce)}},
  99. // The binding is checked when the order is finalized, so evidence
  100. // with any binding validates the challenge.
  101. {"ok binding checked at finalize", testRemoteAttestationCMW, testFreshnessNonce,
  102. func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
  103. return csResult, make([]byte, 32), nil
  104. }, nil, want{status: StatusValid, stored: true, format: "confidential-space", result: csResult}},
  105. {"ok empty payload", nil, testFreshnessNonce, nil, nil, want{status: StatusPending}},
  106. {"ok empty object", []byte(" {} "), testFreshnessNonce, nil, nil, want{status: StatusPending}},
  107. {"fail no nonce", testRemoteAttestationCMW, "", nil, nil, want{status: StatusPending, err: "has no freshness nonce"}},
  108. {"fail malformed", []byte(`["application/eat+jwt"]`), testFreshnessNonce, nil, nil,
  109. want{status: StatusPending, err: "must have 2 or 3 elements"}},
  110. {"fail invalid evidence", testRemoteAttestationCMW, testFreshnessNonce,
  111. func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
  112. return nil, nil, attestation.Invalidf("attestation token dbgstat is %q", "enabled")
  113. }, nil, want{status: StatusInvalid, errType: "badAttestationStatement", errDetail: `attestation token dbgstat is "enabled"`}},
  114. {"fail verifier", testRemoteAttestationCMW, testFreshnessNonce,
  115. func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
  116. return nil, nil, errors.New("error fetching tdx collateral")
  117. }, nil, want{status: StatusPending, err: "error verifying remote attestation"}},
  118. {"fail bound size", testRemoteAttestationCMW, testFreshnessNonce,
  119. func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
  120. return csResult, binding[:16], nil
  121. }, nil, want{status: StatusPending, err: "binds 16 bytes"}},
  122. // The challenge is requested under an authorization from the URL; the
  123. // attestation must not land on one that does not hold the challenge.
  124. {"fail challenge of another authorization", testRemoteAttestationCMW, testFreshnessNonce,
  125. func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
  126. return csResult, binding, nil
  127. }, func(az *Authorization) { az.Challenges = []*Challenge{{ID: "otherChID"}} },
  128. want{status: StatusPending, err: "does not belong to authorization"}},
  129. {"fail authorization of another account", testRemoteAttestationCMW, testFreshnessNonce,
  130. func(context.Context, *cmw.Record, string) (*attestation.Result, []byte, error) {
  131. return csResult, binding, nil
  132. }, func(az *Authorization) { az.AccountID = "otherAccID" },
  133. want{status: StatusPending, err: "does not belong to authorization"}},
  134. }
  135. for _, tt := range tests {
  136. t.Run(tt.name, func(t *testing.T) {
  137. var (
  138. updatedAz *Authorization
  139. updatedCh *Challenge
  140. )
  141. db := &MockDB{
  142. MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
  143. assert.Equal(t, "azID", id)
  144. az := &Authorization{
  145. ID: id, AccountID: "accID", Identifier: Identifier{Type: RemoteAttestation, Value: "measured_boot"},
  146. Challenges: []*Challenge{{ID: "chID"}},
  147. }
  148. if tt.az != nil {
  149. tt.az(az)
  150. }
  151. return az, nil
  152. },
  153. MockUpdateAuthorization: func(_ context.Context, az *Authorization) error {
  154. updatedAz = az
  155. return nil
  156. },
  157. MockUpdateChallenge: func(_ context.Context, ch *Challenge) error {
  158. updatedCh = ch
  159. return nil
  160. },
  161. }
  162. prov := &MockProvisioner{
  163. MgetName: func() string { return "acme" },
  164. MverifyRemoteAttestation: tt.verify,
  165. }
  166. ctx := NewProvisionerContext(context.Background(), prov)
  167. ctx = NewLinkerContext(ctx, NewLinker("ca.example.com", "acme"))
  168. ch := &Challenge{
  169. ID: "chID",
  170. AccountID: "accID",
  171. AuthorizationID: "azID",
  172. Type: REMOTEATTEST01,
  173. Status: StatusPending,
  174. Token: "token",
  175. FreshnessNonce: tt.nonce,
  176. }
  177. err := ch.Validate(ctx, db, jwk, tt.payload)
  178. if tt.want.err != "" {
  179. assert.ErrorContains(t, err, tt.want.err)
  180. } else {
  181. require.NoError(t, err)
  182. }
  183. assert.Equal(t, tt.want.status, ch.Status)
  184. if tt.want.errType != "" {
  185. require.NotNil(t, updatedCh)
  186. require.NotNil(t, ch.Error)
  187. assert.Equal(t, "urn:ietf:params:acme:error:"+tt.want.errType, ch.Error.Type)
  188. assert.Contains(t, ch.Error.Detail, tt.want.errDetail)
  189. assert.Nil(t, updatedAz)
  190. return
  191. }
  192. if !tt.want.stored {
  193. assert.Nil(t, updatedAz)
  194. assert.Nil(t, updatedCh)
  195. return
  196. }
  197. require.NotNil(t, updatedCh)
  198. assert.Nil(t, ch.Error)
  199. assert.NotEmpty(t, ch.ValidatedAt)
  200. assert.Equal(t, tt.want.format, ch.PayloadFormat)
  201. require.NotNil(t, updatedAz)
  202. require.NotNil(t, updatedAz.Attestation)
  203. att := updatedAz.Attestation
  204. assert.Equal(t, "remote-attest-01", att.Challenge)
  205. assert.Equal(t, "measured_boot", att.Hint)
  206. assert.Equal(t, testFreshnessNonce, att.FreshnessNonce)
  207. assert.Equal(t, keyAuth, att.KeyAuthorization)
  208. assert.Len(t, att.BindingDigest, 64)
  209. assert.Equal(t, tt.want.claimNonce, att.ClaimNonce)
  210. assert.Nil(t, att.Account, "the account is added at finalize")
  211. assert.Equal(t, tt.want.result, att.Result)
  212. })
  213. }
  214. }
  215. func TestOrder_checkAttestedKeys(t *testing.T) {
  216. csr, _ := mustCSR(t, "")
  217. otherCSR, _ := mustCSR(t, "")
  218. fp, err := keyutil.Fingerprint(csr.PublicKey)
  219. require.NoError(t, err)
  220. otherFP, err := keyutil.Fingerprint(otherCSR.PublicKey)
  221. require.NoError(t, err)
  222. newAtt := func(keyAuth string, csr *x509.CertificateRequest) *webhook.Attestation {
  223. return &webhook.Attestation{
  224. Challenge: "remote-attest-01",
  225. KeyAuthorization: keyAuth,
  226. BindingDigest: hex.EncodeToString(testBinding(keyAuth, csr)),
  227. }
  228. }
  229. att := newAtt("nonce.thumbprint", csr)
  230. otherKeyAtt := newAtt("nonce.thumbprint", otherCSR)
  231. // The binding is stored with one key authorization but was computed with
  232. // another, as evidence replayed from another challenge or account would be.
  233. replayedAtt := newAtt("nonce.thumbprint", csr)
  234. replayedAtt.KeyAuthorization = "other-nonce.other-thumbprint"
  235. tests := []struct {
  236. name string
  237. azs map[string]*Authorization
  238. want *webhook.Attestation
  239. wantErr string
  240. }{
  241. {"ok none", map[string]*Authorization{"az1": {}, "az2": {}}, nil, ""},
  242. {"ok fingerprint", map[string]*Authorization{"az1": {}, "az2": {Fingerprint: fp}}, nil, ""},
  243. {"ok attestation", map[string]*Authorization{"az1": {}, "az2": {Attestation: att}}, att, ""},
  244. {"ok both", map[string]*Authorization{"az1": {Fingerprint: fp}, "az2": {Attestation: att}}, att, ""},
  245. {"fail fingerprint", map[string]*Authorization{"az1": {Fingerprint: otherFP}, "az2": {}}, nil, "csr does not match the attested key"},
  246. {"fail attestation of another key", map[string]*Authorization{"az1": {}, "az2": {Attestation: otherKeyAtt}}, nil,
  247. "csr does not match the attested key"},
  248. {"fail replayed evidence", map[string]*Authorization{"az1": {}, "az2": {Attestation: replayedAtt}}, nil,
  249. "csr does not match the attested key"},
  250. {"fail attestation without key authorization", map[string]*Authorization{"az1": {Attestation: &webhook.Attestation{}}, "az2": {}}, nil,
  251. "csr does not match the attested key"},
  252. // A remote-attestation authorization made valid without its
  253. // challenge's attestation (a lost update, a challenge requested under
  254. // another authorization) fails closed.
  255. {"fail remote attestation without attestation", map[string]*Authorization{
  256. "az1": {Identifier: Identifier{Type: RemoteAttestation}}, "az2": {},
  257. }, nil, "has no attestation for its remote-attestation identifier"},
  258. // Every attested key is checked, not only the first one found.
  259. {"fail second fingerprint", map[string]*Authorization{"az1": {Fingerprint: fp}, "az2": {Fingerprint: otherFP}}, nil,
  260. "csr does not match the attested key"},
  261. {"fail attestation after fingerprint", map[string]*Authorization{"az1": {Fingerprint: fp}, "az2": {Attestation: otherKeyAtt}}, nil,
  262. "csr does not match the attested key"},
  263. {"fail db", map[string]*Authorization{"az1": nil}, nil, "error getting authorization"},
  264. }
  265. for _, tt := range tests {
  266. t.Run(tt.name, func(t *testing.T) {
  267. o := &Order{ID: "orderID", AuthorizationIDs: []string{"az1", "az2"}}
  268. db := &MockDB{
  269. MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
  270. az, ok := tt.azs[id]
  271. if !ok || az == nil {
  272. return nil, errors.New("force")
  273. }
  274. return az, nil
  275. },
  276. }
  277. got, err := o.checkAttestedKeys(context.Background(), db, csr)
  278. if tt.wantErr != "" {
  279. assert.ErrorContains(t, err, tt.wantErr)
  280. return
  281. }
  282. require.NoError(t, err)
  283. assert.Equal(t, tt.want, got)
  284. })
  285. }
  286. }
  287. // TestOrder_Finalize_remoteAttestation finalizes an order whose only
  288. // identifier is remote-attestation: the CSR names nothing, the binding is
  289. // checked against the CSR's key, and the attestation, with the account and its
  290. // EAB key, reaches the template data and the bodies of the webhook requests.
  291. func TestOrder_Finalize_remoteAttestation(t *testing.T) {
  292. csr, _ := mustCSR(t, "")
  293. newAtt := func() *webhook.Attestation {
  294. return &webhook.Attestation{
  295. Challenge: "remote-attest-01",
  296. KeyAuthorization: "nonce.thumbprint",
  297. BindingDigest: hex.EncodeToString(testBinding("nonce.thumbprint", csr)),
  298. ClaimNonce: "claim",
  299. Result: &attestation.Result{Format: attestation.FormatTDX, TDX: &attestation.TDX{MRTD: "aa"}},
  300. }
  301. }
  302. newOrder := func() *Order {
  303. return &Order{
  304. ID: "orderID",
  305. AccountID: "accID",
  306. ProvisionerID: "provID",
  307. Status: StatusReady,
  308. ExpiresAt: time.Now().Add(time.Hour),
  309. Identifiers: []Identifier{{Type: RemoteAttestation}},
  310. AuthorizationIDs: []string{"azID"},
  311. }
  312. }
  313. newDB := func(eak *ExternalAccountKey, eakErr error) *MockDB {
  314. return &MockDB{
  315. MockGetAuthorization: func(_ context.Context, id string) (*Authorization, error) {
  316. return &Authorization{ID: id, Status: StatusValid, Attestation: newAtt()}, nil
  317. },
  318. MockGetExternalAccountKeyByAccountID: func(_ context.Context, provisionerID, accountID string) (*ExternalAccountKey, error) {
  319. assert.Equal(t, "provID", provisionerID)
  320. assert.Equal(t, "accID", accountID)
  321. return eak, eakErr
  322. },
  323. MockCreateCertificate: func(_ context.Context, cert *Certificate) error {
  324. cert.ID = "certID"
  325. return nil
  326. },
  327. MockUpdateOrder: func(context.Context, *Order) error { return nil },
  328. }
  329. }
  330. newProv := func(requireEAB bool) *MockProvisioner {
  331. return &MockProvisioner{
  332. MauthorizeSign: func(context.Context, string) ([]provisioner.SignOption, error) {
  333. return []provisioner.SignOption{&provisioner.WebhookController{}}, nil
  334. },
  335. MgetOptions: func() *provisioner.Options { return nil },
  336. MisEABRequired: func() bool { return requireEAB },
  337. }
  338. }
  339. prov, eabProv := newProv(false), newProv(true)
  340. signAndCheck := func(t *testing.T, wantAccount *webhook.AttestationAccount) *mockSignAuth {
  341. leaf, intermediate := &x509.Certificate{Raw: []byte("leaf")}, &x509.Certificate{Raw: []byte("intermediate")}
  342. return &mockSignAuth{
  343. signWithContext: func(ctx context.Context, _ *x509.CertificateRequest, _ provisioner.SignOptions, opts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  344. var wc *provisioner.WebhookController
  345. for _, o := range opts {
  346. if c, ok := o.(*provisioner.WebhookController); ok {
  347. wc = c
  348. }
  349. }
  350. require.NotNil(t, wc)
  351. want := newAtt()
  352. want.Account = wantAccount
  353. data, ok := wc.TemplateData.(x509util.TemplateData)
  354. require.True(t, ok)
  355. assert.Equal(t, want, data["Attestation"])
  356. assert.Empty(t, data[x509util.SANsKey])
  357. req := &webhook.RequestBody{}
  358. require.NoError(t, wc.Enrich(ctx, req))
  359. assert.Equal(t, want, req.Attestation)
  360. return []*x509.Certificate{leaf, intermediate}, nil
  361. },
  362. }
  363. }
  364. t.Run("ok without eab", func(t *testing.T) {
  365. // A provisioner without EAB never reads the key, which some databases
  366. // report as missing with an error.
  367. o := newOrder()
  368. require.NoError(t, o.Finalize(context.Background(), newDB(nil, errors.New("not found")), csr, signAndCheck(t, &webhook.AttestationAccount{ID: "accID"}), prov))
  369. assert.Equal(t, StatusValid, o.Status)
  370. assert.Equal(t, "certID", o.CertificateID)
  371. })
  372. t.Run("ok with eab", func(t *testing.T) {
  373. eak := &ExternalAccountKey{ID: "eakID", Reference: "machine-1", AccountID: "accID"}
  374. o := newOrder()
  375. require.NoError(t, o.Finalize(context.Background(), newDB(eak, nil), csr, signAndCheck(t, &webhook.AttestationAccount{
  376. ID: "accID", ExternalAccountKeyID: "eakID", Reference: "machine-1",
  377. }), eabProv))
  378. assert.Equal(t, StatusValid, o.Status)
  379. })
  380. t.Run("fail eab lookup", func(t *testing.T) {
  381. err := newOrder().Finalize(context.Background(), newDB(nil, errors.New("force")), csr, &mockSignAuth{}, eabProv)
  382. assert.ErrorContains(t, err, "error getting the external account key")
  383. })
  384. t.Run("fail other key", func(t *testing.T) {
  385. other, _ := mustCSR(t, "")
  386. err := newOrder().Finalize(context.Background(), newDB(nil, nil), other, &mockSignAuth{}, prov)
  387. assert.ErrorContains(t, err, "csr does not match the attested key")
  388. })
  389. t.Run("fail common name", func(t *testing.T) {
  390. // The order names nothing, so the CSR cannot name anything either.
  391. named := mustCSRWithKeyOf(t, csr, "workload.example.com")
  392. err := newOrder().Finalize(context.Background(), newDB(nil, nil), named, &mockSignAuth{}, prov)
  393. var acmeErr *Error
  394. require.ErrorAs(t, err, &acmeErr)
  395. assert.Equal(t, "urn:ietf:params:acme:error:badCSR", acmeErr.Type)
  396. })
  397. }
  398. // mustCSRWithKeyOf returns a CSR whose public key is the one of csr, with the
  399. // given common name. Its signature is not valid, which Finalize does not check.
  400. func mustCSRWithKeyOf(t *testing.T, csr *x509.CertificateRequest, cn string) *x509.CertificateRequest {
  401. t.Helper()
  402. named := *csr
  403. named.Subject = pkix.Name{CommonName: cn}
  404. return &named
  405. }