remote_attestation_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. package integration
  2. import (
  3. "crypto/rand"
  4. "crypto/sha256"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/asn1"
  8. "encoding/base64"
  9. "encoding/json"
  10. "fmt"
  11. "net"
  12. "net/http"
  13. "net/http/httptest"
  14. "net/url"
  15. "path/filepath"
  16. "sync"
  17. "testing"
  18. "time"
  19. "github.com/stretchr/testify/assert"
  20. "github.com/stretchr/testify/require"
  21. "go.step.sm/crypto/keyutil"
  22. "go.step.sm/crypto/minica"
  23. "go.step.sm/crypto/pemutil"
  24. "github.com/smallstep/certificates/acme"
  25. "github.com/smallstep/certificates/attestation"
  26. cstest "github.com/smallstep/certificates/attestation/confidentialspace/confidentialspacetest"
  27. "github.com/smallstep/certificates/authority/config"
  28. "github.com/smallstep/certificates/authority/policy"
  29. "github.com/smallstep/certificates/authority/provisioner"
  30. "github.com/smallstep/certificates/ca"
  31. "github.com/smallstep/certificates/db"
  32. "github.com/smallstep/certificates/webhook"
  33. )
  34. // oidTestAttestation is the OID of the extension the test template sets from
  35. // the verified attestation, under the enterprise number RFC 5612 reserves for
  36. // documentation.
  37. var oidTestAttestation = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 32473, 1}
  38. // remoteAttestationTestTemplate names the certificate from the enriching
  39. // webhook's response and records the verified attestation, as a workload
  40. // identity deployment would. The order names nothing itself.
  41. const remoteAttestationTestTemplate = `{
  42. "subject": {},
  43. "uris": [{{ toJson .Webhooks.control.spiffeID }}],
  44. "extensions": [{
  45. "id": "1.3.6.1.4.1.32473.1",
  46. "value": {{ asn1Enc (printf "utf8:%s/%s" .Attestation.Format .Attestation.ConfidentialSpace.Claims.hwmodel) | toJson }}
  47. }],
  48. "keyUsage": ["digitalSignature"],
  49. "extKeyUsage": ["clientAuth"]
  50. }`
  51. // TestRemoteAttestation runs the ACME remote-attest-01 flow
  52. // (draft-ietf-acme-rats) against a CA, from a new account to the certificate,
  53. // with a Confidential Space token as the evidence and an enriching webhook that
  54. // receives the verified attestation and names the certificate.
  55. func TestRemoteAttestation(t *testing.T) {
  56. dir := t.TempDir()
  57. t.Setenv("STEPPATH", dir)
  58. m, err := minica.New(minica.WithName("Step E2E"))
  59. require.NoError(t, err)
  60. rootFilepath := filepath.Join(dir, "root.crt")
  61. _, err = pemutil.Serialize(m.Root, pemutil.WithFilename(rootFilepath))
  62. require.NoError(t, err)
  63. intermediateCertFilepath := filepath.Join(dir, "intermediate.crt")
  64. _, err = pemutil.Serialize(m.Intermediate, pemutil.WithFilename(intermediateCertFilepath))
  65. require.NoError(t, err)
  66. intermediateKeyFilepath := filepath.Join(dir, "intermediate.key")
  67. _, err = pemutil.Serialize(m.Signer, pemutil.WithFilename(intermediateKeyFilepath))
  68. require.NoError(t, err)
  69. // The enriching webhook, served with a certificate from the CA's own
  70. // PKI, which the CA's webhook client trusts.
  71. var (
  72. mu sync.Mutex
  73. received *webhook.Attestation
  74. )
  75. whSrv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  76. var body webhook.RequestBody
  77. if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
  78. http.Error(w, err.Error(), http.StatusBadRequest)
  79. return
  80. }
  81. mu.Lock()
  82. received = body.Attestation
  83. mu.Unlock()
  84. resp := webhook.ResponseBody{Allow: body.Attestation != nil}
  85. if body.Attestation != nil {
  86. resp.Data = map[string]any{"spiffeID": "spiffe://example.org/workload/" + body.Attestation.Hint}
  87. }
  88. _ = json.NewEncoder(w).Encode(resp)
  89. }))
  90. whKey, err := keyutil.GenerateDefaultSigner()
  91. require.NoError(t, err)
  92. whCert, err := m.Sign(&x509.Certificate{
  93. DNSNames: []string{"localhost"},
  94. IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
  95. PublicKey: whKey.Public(),
  96. })
  97. require.NoError(t, err)
  98. whSrv.TLS = &tls.Config{
  99. Certificates: []tls.Certificate{{
  100. Certificate: [][]byte{whCert.Raw, m.Intermediate.Raw},
  101. PrivateKey: whKey,
  102. }},
  103. MinVersion: tls.VersionTLS12,
  104. }
  105. whSrv.StartTLS()
  106. t.Cleanup(whSrv.Close)
  107. attestor := cstest.New(t)
  108. host, port := reservePort(t)
  109. cfg := &config.Config{
  110. Root: []string{rootFilepath},
  111. IntermediateCert: intermediateCertFilepath,
  112. IntermediateKey: intermediateKeyFilepath,
  113. Address: net.JoinHostPort(host, port),
  114. DNSNames: []string{"127.0.0.1", "[::1]", "localhost"},
  115. AuthorityConfig: &config.AuthConfig{
  116. AuthorityID: "stepca-test",
  117. DeploymentType: "standalone-test",
  118. Provisioners: provisioner.List{
  119. &provisioner.ACME{
  120. Type: "ACME",
  121. Name: "attested",
  122. Challenges: []provisioner.ACMEChallenge{provisioner.REMOTE_ATTEST_01},
  123. RemoteAttestation: &provisioner.ACMERemoteAttestation{
  124. Formats: []attestation.Format{attestation.FormatConfidentialSpace},
  125. ClaimsHint: []string{"hwmodel", "submods"},
  126. ConfidentialSpace: &provisioner.ACMEConfidentialSpace{
  127. Roots: attestor.RootPEM(),
  128. },
  129. },
  130. Claims: &config.GlobalProvisionerClaims,
  131. Options: &provisioner.Options{
  132. X509: &provisioner.X509Options{Template: remoteAttestationTestTemplate},
  133. Webhooks: []*provisioner.Webhook{{
  134. Name: "control",
  135. URL: whSrv.URL + "/enrich",
  136. Kind: "ENRICHING",
  137. CertType: "X509",
  138. Secret: base64.StdEncoding.EncodeToString([]byte("webhook-secret")),
  139. }},
  140. },
  141. },
  142. },
  143. },
  144. DB: &db.Config{
  145. Type: "bbolt",
  146. DataSource: filepath.Join(dir, "db"),
  147. },
  148. Logger: json.RawMessage(`{"format": "text"}`),
  149. }
  150. c, err := ca.New(cfg)
  151. require.NoError(t, err)
  152. var wg sync.WaitGroup
  153. wg.Go(func() {
  154. err := c.Run()
  155. require.ErrorIs(t, err, http.ErrServerClosed)
  156. })
  157. t.Cleanup(func() {
  158. require.NoError(t, c.Stop())
  159. wg.Wait()
  160. })
  161. requireCAServerToBeAvailable(t, net.JoinHostPort("localhost", port), 10*time.Second)
  162. directory := fmt.Sprintf("https://localhost:%s/acme/attested/directory", port)
  163. client, err := ca.NewACMEClient(directory, nil, ca.WithRootFile(rootFilepath))
  164. require.NoError(t, err)
  165. order, err := client.NewOrder([]byte(`{"identifiers":[{"type":"remote-attestation","value":"measured_boot"}]}`))
  166. require.NoError(t, err)
  167. require.Len(t, order.AuthorizationURLs, 1)
  168. az, err := client.GetAuthz(order.AuthorizationURLs[0])
  169. require.NoError(t, err)
  170. require.Len(t, az.Challenges, 1)
  171. ch := az.Challenges[0]
  172. require.Equal(t, acme.REMOTEATTEST01, ch.Type)
  173. require.NotEmpty(t, ch.FreshnessNonce)
  174. assert.Equal(t, []string{"hwmodel", "submods"}, ch.AttestClaimsHint)
  175. // The workload's key, and the binding its evidence carries first:
  176. // SHA-256 of the key authorization followed by the key's DER
  177. // SubjectPublicKeyInfo. The relying party's own nonce follows.
  178. certKey, err := keyutil.GenerateDefaultSigner()
  179. require.NoError(t, err)
  180. keyAuth, err := acme.KeyAuthorization(ch.FreshnessNonce, client.Key)
  181. require.NoError(t, err)
  182. spki, err := x509.MarshalPKIXPublicKey(certKey.Public())
  183. require.NoError(t, err)
  184. binding := sha256.Sum256(append([]byte(keyAuth), spki...))
  185. token := attestor.Mint(t, cstest.Claims(time.Now(), directory,
  186. base64.RawURLEncoding.EncodeToString(binding[:]),
  187. "relying-party-nonce",
  188. ))
  189. payload, err := json.Marshal([]any{"application/eat+jwt", base64.RawURLEncoding.EncodeToString([]byte(token)), 8})
  190. require.NoError(t, err)
  191. require.NoError(t, client.ValidateWithPayload(ch.URL, payload))
  192. ch, err = client.GetChallenge(ch.URL)
  193. require.NoError(t, err)
  194. require.Equal(t, acme.StatusValid, ch.Status, "challenge error: %v", ch.Error)
  195. // A CSR with a key other than the attested one is refused, and the order
  196. // stays ready.
  197. otherKey, err := keyutil.GenerateDefaultSigner()
  198. require.NoError(t, err)
  199. otherDER, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{}, otherKey)
  200. require.NoError(t, err)
  201. otherCSR, err := x509.ParseCertificateRequest(otherDER)
  202. require.NoError(t, err)
  203. err = client.FinalizeOrder(order.FinalizeURL, otherCSR)
  204. require.Error(t, err)
  205. assert.Contains(t, err.Error(), "The client lacks sufficient authorization")
  206. readyOrder, err := client.GetOrder(order.ID)
  207. require.NoError(t, err)
  208. assert.Equal(t, acme.StatusReady, readyOrder.Status)
  209. // The order names nothing, so neither does the CSR.
  210. csrDER, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{}, certKey)
  211. require.NoError(t, err)
  212. csr, err := x509.ParseCertificateRequest(csrDER)
  213. require.NoError(t, err)
  214. require.NoError(t, client.FinalizeOrder(order.FinalizeURL, csr))
  215. order, err = client.GetOrder(order.ID)
  216. require.NoError(t, err)
  217. require.Equal(t, acme.StatusValid, order.Status)
  218. leaf, _, err := client.GetCertificate(order.CertificateURL)
  219. require.NoError(t, err)
  220. // The webhook received the verified attestation and named the
  221. // certificate; the template recorded the attestation.
  222. mu.Lock()
  223. got := received
  224. mu.Unlock()
  225. require.NotNil(t, got)
  226. assert.Equal(t, "remote-attest-01", got.Challenge)
  227. assert.Equal(t, "measured_boot", got.Hint)
  228. assert.Equal(t, ch.FreshnessNonce, got.FreshnessNonce)
  229. assert.Equal(t, keyAuth, got.KeyAuthorization)
  230. assert.Equal(t, fmt.Sprintf("%x", binding), got.BindingDigest)
  231. assert.Empty(t, got.ClaimNonce)
  232. require.NotNil(t, got.Account)
  233. assert.NotEmpty(t, got.Account.ID)
  234. assert.Empty(t, got.Account.Reference)
  235. assert.Equal(t, []any{base64.RawURLEncoding.EncodeToString(binding[:]), "relying-party-nonce"}, got.ConfidentialSpace.Claims["eat_nonce"])
  236. assert.Equal(t, attestation.FormatConfidentialSpace, got.Format)
  237. assert.Equal(t, []byte(token), got.Evidence)
  238. require.NotNil(t, got.ConfidentialSpace)
  239. assert.Equal(t, "my-project", got.ConfidentialSpace.Claims["submods"].(map[string]any)["gce"].(map[string]any)["project_id"])
  240. spiffeID, err := url.Parse("spiffe://example.org/workload/measured_boot")
  241. require.NoError(t, err)
  242. assert.Equal(t, []*url.URL{spiffeID}, leaf.URIs)
  243. assert.Empty(t, leaf.DNSNames)
  244. assert.Equal(t, []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, leaf.ExtKeyUsage)
  245. var recorded string
  246. for _, ext := range leaf.Extensions {
  247. if ext.Id.Equal(oidTestAttestation) {
  248. _, err := asn1.UnmarshalWithParams(ext.Value, &recorded, "utf8")
  249. require.NoError(t, err)
  250. }
  251. }
  252. assert.Equal(t, "confidential-space/GCP_INTEL_TDX", recorded)
  253. }
  254. // TestRemoteAttestationWithoutTemplate runs the flow against a provisioner with
  255. // no template and no webhook. The order, whose hint is empty, and the request
  256. // name nothing, so the default template signs a certificate with no names,
  257. // which a policy that allows only URIs admits. The token carries the binding
  258. // as its only nonce.
  259. func TestRemoteAttestationWithoutTemplate(t *testing.T) {
  260. dir := t.TempDir()
  261. t.Setenv("STEPPATH", dir)
  262. m, err := minica.New(minica.WithName("Step E2E"))
  263. require.NoError(t, err)
  264. rootFilepath := filepath.Join(dir, "root.crt")
  265. _, err = pemutil.Serialize(m.Root, pemutil.WithFilename(rootFilepath))
  266. require.NoError(t, err)
  267. intermediateCertFilepath := filepath.Join(dir, "intermediate.crt")
  268. _, err = pemutil.Serialize(m.Intermediate, pemutil.WithFilename(intermediateCertFilepath))
  269. require.NoError(t, err)
  270. intermediateKeyFilepath := filepath.Join(dir, "intermediate.key")
  271. _, err = pemutil.Serialize(m.Signer, pemutil.WithFilename(intermediateKeyFilepath))
  272. require.NoError(t, err)
  273. attestor := cstest.New(t)
  274. host, port := reservePort(t)
  275. cfg := &config.Config{
  276. Root: []string{rootFilepath},
  277. IntermediateCert: intermediateCertFilepath,
  278. IntermediateKey: intermediateKeyFilepath,
  279. Address: net.JoinHostPort(host, port),
  280. DNSNames: []string{"127.0.0.1", "[::1]", "localhost"},
  281. AuthorityConfig: &config.AuthConfig{
  282. AuthorityID: "stepca-test",
  283. DeploymentType: "standalone-test",
  284. Provisioners: provisioner.List{
  285. &provisioner.ACME{
  286. Type: "ACME",
  287. Name: "attested",
  288. Challenges: []provisioner.ACMEChallenge{provisioner.REMOTE_ATTEST_01},
  289. RemoteAttestation: &provisioner.ACMERemoteAttestation{
  290. Require: true,
  291. Formats: []attestation.Format{attestation.FormatConfidentialSpace},
  292. ConfidentialSpace: &provisioner.ACMEConfidentialSpace{
  293. Roots: attestor.RootPEM(),
  294. },
  295. },
  296. Claims: &config.GlobalProvisionerClaims,
  297. Options: &provisioner.Options{
  298. X509: &provisioner.X509Options{
  299. AllowedNames: &policy.X509NameOptions{URIDomains: []string{"example.org"}},
  300. },
  301. },
  302. },
  303. },
  304. },
  305. DB: &db.Config{
  306. Type: "bbolt",
  307. DataSource: filepath.Join(dir, "db"),
  308. },
  309. Logger: json.RawMessage(`{"format": "text"}`),
  310. }
  311. c, err := ca.New(cfg)
  312. require.NoError(t, err)
  313. var wg sync.WaitGroup
  314. wg.Go(func() {
  315. err := c.Run()
  316. require.ErrorIs(t, err, http.ErrServerClosed)
  317. })
  318. t.Cleanup(func() {
  319. require.NoError(t, c.Stop())
  320. wg.Wait()
  321. })
  322. requireCAServerToBeAvailable(t, net.JoinHostPort("localhost", port), 10*time.Second)
  323. directory := fmt.Sprintf("https://localhost:%s/acme/attested/directory", port)
  324. client, err := ca.NewACMEClient(directory, nil, ca.WithRootFile(rootFilepath))
  325. require.NoError(t, err)
  326. order, err := client.NewOrder([]byte(`{"identifiers":[{"type":"remote-attestation","value":""}]}`))
  327. require.NoError(t, err)
  328. require.Len(t, order.AuthorizationURLs, 1)
  329. az, err := client.GetAuthz(order.AuthorizationURLs[0])
  330. require.NoError(t, err)
  331. require.Len(t, az.Challenges, 1)
  332. ch := az.Challenges[0]
  333. require.Equal(t, acme.REMOTEATTEST01, ch.Type)
  334. certKey, err := keyutil.GenerateDefaultSigner()
  335. require.NoError(t, err)
  336. keyAuth, err := acme.KeyAuthorization(ch.FreshnessNonce, client.Key)
  337. require.NoError(t, err)
  338. spki, err := x509.MarshalPKIXPublicKey(certKey.Public())
  339. require.NoError(t, err)
  340. binding := sha256.Sum256(append([]byte(keyAuth), spki...))
  341. token := attestor.Mint(t, cstest.Claims(time.Now(), directory, base64.RawURLEncoding.EncodeToString(binding[:])))
  342. payload, err := json.Marshal([]any{"application/eat+jwt", base64.RawURLEncoding.EncodeToString([]byte(token)), 8})
  343. require.NoError(t, err)
  344. require.NoError(t, client.ValidateWithPayload(ch.URL, payload))
  345. ch, err = client.GetChallenge(ch.URL)
  346. require.NoError(t, err)
  347. require.Equal(t, acme.StatusValid, ch.Status, "challenge error: %v", ch.Error)
  348. csrDER, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{}, certKey)
  349. require.NoError(t, err)
  350. csr, err := x509.ParseCertificateRequest(csrDER)
  351. require.NoError(t, err)
  352. require.NoError(t, client.FinalizeOrder(order.FinalizeURL, csr))
  353. order, err = client.GetOrder(order.ID)
  354. require.NoError(t, err)
  355. require.Equal(t, acme.StatusValid, order.Status)
  356. leaf, _, err := client.GetCertificate(order.CertificateURL)
  357. require.NoError(t, err)
  358. assert.Empty(t, leaf.Subject.String())
  359. assert.Empty(t, leaf.DNSNames)
  360. assert.Empty(t, leaf.IPAddresses)
  361. assert.Empty(t, leaf.EmailAddresses)
  362. assert.Empty(t, leaf.URIs)
  363. assert.Equal(t, certKey.Public(), leaf.PublicKey)
  364. assert.Equal(t, m.Intermediate.Subject.String(), leaf.Issuer.String())
  365. }