acme.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/json"
  6. "encoding/pem"
  7. "fmt"
  8. "net"
  9. "net/http"
  10. "strings"
  11. "sync/atomic"
  12. "time"
  13. "github.com/pkg/errors"
  14. "golang.org/x/sync/singleflight"
  15. "github.com/smallstep/linkedca"
  16. "github.com/smallstep/certificates/acme/wire"
  17. )
  18. // ACMEChallenge represents the supported acme challenges.
  19. type ACMEChallenge string
  20. //nolint:staticcheck,revive // better names
  21. const (
  22. // HTTP_01 is the http-01 ACME challenge.
  23. HTTP_01 ACMEChallenge = "http-01"
  24. // DNS_01 is the dns-01 ACME challenge.
  25. DNS_01 ACMEChallenge = "dns-01"
  26. // TLS_ALPN_01 is the tls-alpn-01 ACME challenge.
  27. TLS_ALPN_01 ACMEChallenge = "tls-alpn-01"
  28. // DEVICE_ATTEST_01 is the device-attest-01 ACME challenge.
  29. DEVICE_ATTEST_01 ACMEChallenge = "device-attest-01"
  30. // WIREOIDC_01 is the Wire OIDC challenge.
  31. WIREOIDC_01 ACMEChallenge = "wire-oidc-01"
  32. // WIREDPOP_01 is the Wire DPoP challenge.
  33. WIREDPOP_01 ACMEChallenge = "wire-dpop-01"
  34. // REMOTE_ATTEST_01 is the remote-attest-01 ACME challenge
  35. // (draft-ietf-acme-rats).
  36. REMOTE_ATTEST_01 ACMEChallenge = "remote-attest-01"
  37. )
  38. // String returns a normalized version of the challenge.
  39. func (c ACMEChallenge) String() string {
  40. return strings.ToLower(string(c))
  41. }
  42. // Validate returns an error if the acme challenge is not a valid one.
  43. func (c ACMEChallenge) Validate() error {
  44. switch ACMEChallenge(c.String()) {
  45. case HTTP_01, DNS_01, TLS_ALPN_01, DEVICE_ATTEST_01, WIREOIDC_01, WIREDPOP_01, REMOTE_ATTEST_01:
  46. return nil
  47. default:
  48. return fmt.Errorf("acme challenge %q is not supported", c)
  49. }
  50. }
  51. // ACMEAttestationFormat represents the format used on a device-attest-01
  52. // challenge.
  53. type ACMEAttestationFormat string
  54. const (
  55. // ANDROIDKEY is the format used to enable device-attest-01 on Android devices.
  56. ANDROIDKEY ACMEAttestationFormat = "android-key"
  57. // APPLE is the format used to enable device-attest-01 on Apple devices.
  58. APPLE ACMEAttestationFormat = "apple"
  59. // STEP is the format used to enable device-attest-01 on devices that
  60. // provide attestation certificates like the PIV interface on YubiKeys.
  61. //
  62. // TODO(mariano): should we rename this to something else.
  63. STEP ACMEAttestationFormat = "step"
  64. // TPM is the format used to enable device-attest-01 with TPMs.
  65. TPM ACMEAttestationFormat = "tpm"
  66. )
  67. // String returns a normalized version of the attestation format.
  68. func (f ACMEAttestationFormat) String() string {
  69. return strings.ToLower(string(f))
  70. }
  71. // Validate returns an error if the attestation format is not a valid one.
  72. func (f ACMEAttestationFormat) Validate() error {
  73. switch ACMEAttestationFormat(f.String()) {
  74. case APPLE, STEP, TPM, ANDROIDKEY:
  75. return nil
  76. default:
  77. return fmt.Errorf("acme attestation format %q is not supported", f)
  78. }
  79. }
  80. // ACME is the acme provisioner type, an entity that can authorize the ACME
  81. // provisioning flow.
  82. type ACME struct {
  83. *base
  84. ID string `json:"-"`
  85. Type string `json:"type"`
  86. Name string `json:"name"`
  87. ForceCN bool `json:"forceCN,omitempty"`
  88. // TermsOfService contains a URL pointing to the ACME server's
  89. // terms of service. Defaults to empty.
  90. TermsOfService string `json:"termsOfService,omitempty"`
  91. // Website contains an URL pointing to more information about
  92. // the ACME server. Defaults to empty.
  93. Website string `json:"website,omitempty"`
  94. // CaaIdentities is an array of hostnames that the ACME server
  95. // identifies itself with. These hostnames can be used by ACME
  96. // clients to determine the correct issuer domain name to use
  97. // when configuring CAA records. Defaults to empty array.
  98. CaaIdentities []string `json:"caaIdentities,omitempty"`
  99. // RequireEAB makes the provisioner require ACME EAB to be provided
  100. // by clients when creating a new Account. If set to true, the provided
  101. // EAB will be verified. If set to false and an EAB is provided, it is
  102. // not verified. Defaults to false.
  103. RequireEAB bool `json:"requireEAB,omitempty"`
  104. // Challenges contains the enabled challenges for this provisioner. If this
  105. // value is not set the default http-01, dns-01 and tls-alpn-01 challenges
  106. // will be enabled, device-attest-01, wire-oidc-01, wire-dpop-01 and
  107. // remote-attest-01 will be disabled.
  108. Challenges []ACMEChallenge `json:"challenges,omitempty"`
  109. // AttestationFormats contains the enabled attestation formats for this
  110. // provisioner. If this value is not set the default apple, step and tpm
  111. // will be used.
  112. AttestationFormats []ACMEAttestationFormat `json:"attestationFormats,omitempty"`
  113. // AttestationRoots contains a bundle of root certificates in PEM format
  114. // that will be used to verify the attestation certificates. If provided,
  115. // this bundle will be used even for well-known CAs like Apple and Yubico.
  116. AttestationRoots []byte `json:"attestationRoots,omitempty"`
  117. // RemoteAttestation configures the remote-attest-01 challenge, if it is
  118. // enabled.
  119. RemoteAttestation *ACMERemoteAttestation `json:"remoteAttestation,omitempty"`
  120. Claims *Claims `json:"claims,omitempty"`
  121. Options *Options `json:"options,omitempty"`
  122. androidCRL *androidCRLCache
  123. attestationRootPool *x509.CertPool
  124. remoteAttestation *remoteAttestationVerifier
  125. ctl *Controller
  126. }
  127. // androidCRLCache caches the Android attestation revocation list.
  128. type androidCRLCache struct {
  129. current atomic.Pointer[androidCRL]
  130. group singleflight.Group
  131. }
  132. // androidCRL is an immutable snapshot of the Android attestation revocation
  133. // list. A new snapshot is swapped in atomically on each refresh, so readers
  134. // never observe a partially-updated set.
  135. type androidCRL struct {
  136. serials map[string]struct{} // set of revoked serial numbers
  137. fetchedAt time.Time
  138. }
  139. // contains returns whether or not [*x509.Certificate]'s
  140. // serial number is in the map of revoked certificate serial
  141. // numbers. Google encodes these as lowercase hex.
  142. func (a *androidCRL) contains(cert *x509.Certificate) bool {
  143. _, revoked := a.serials[cert.SerialNumber.Text(16)]
  144. return revoked
  145. }
  146. // GetID returns the provisioner unique identifier.
  147. func (p ACME) GetID() string {
  148. if p.ID != "" {
  149. return p.ID
  150. }
  151. return p.GetIDForToken()
  152. }
  153. // GetIDForToken returns an identifier that will be used to load the provisioner
  154. // from a token.
  155. func (p *ACME) GetIDForToken() string {
  156. return "acme/" + p.Name
  157. }
  158. // GetTokenID returns the identifier of the token. This provisioner will always
  159. // return [ErrTokenFlowNotSupported].
  160. func (p *ACME) GetTokenID(string) (string, error) {
  161. return "", ErrTokenFlowNotSupported
  162. }
  163. // GetName returns the name of the provisioner.
  164. func (p *ACME) GetName() string {
  165. return p.Name
  166. }
  167. // GetType returns the type of provisioner.
  168. func (p *ACME) GetType() Type {
  169. return TypeACME
  170. }
  171. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  172. func (p *ACME) GetEncryptedKey() (string, string, bool) {
  173. return "", "", false
  174. }
  175. // GetOptions returns the configured provisioner options.
  176. func (p *ACME) GetOptions() *Options {
  177. return p.Options
  178. }
  179. // DefaultTLSCertDuration returns the default TLS cert duration enforced by
  180. // the provisioner.
  181. func (p *ACME) DefaultTLSCertDuration() time.Duration {
  182. return p.ctl.Claimer.DefaultTLSCertDuration()
  183. }
  184. // Init initializes and validates the fields of an ACME type.
  185. func (p *ACME) Init(config Config) (err error) {
  186. switch {
  187. case p.Type == "":
  188. return errors.New("provisioner type cannot be empty")
  189. case p.Name == "":
  190. return errors.New("provisioner name cannot be empty")
  191. }
  192. for _, c := range p.Challenges {
  193. if err := c.Validate(); err != nil {
  194. return err
  195. }
  196. }
  197. for _, f := range p.AttestationFormats {
  198. if err := f.Validate(); err != nil {
  199. return err
  200. }
  201. }
  202. // Parse attestation roots.
  203. // The pool will be nil if there are no roots.
  204. if rest := p.AttestationRoots; len(rest) > 0 {
  205. var block *pem.Block
  206. var hasCert bool
  207. p.attestationRootPool = x509.NewCertPool()
  208. for rest != nil {
  209. block, rest = pem.Decode(rest)
  210. if block == nil {
  211. break
  212. }
  213. cert, err := x509.ParseCertificate(block.Bytes)
  214. if err != nil {
  215. return errors.New("error parsing attestationRoots: malformed certificate")
  216. }
  217. p.attestationRootPool.AddCert(cert)
  218. hasCert = true
  219. }
  220. if !hasCert {
  221. return errors.New("error parsing attestationRoots: no certificates found")
  222. }
  223. }
  224. if err := p.initializeWireOptions(); err != nil {
  225. return fmt.Errorf("failed initializing Wire options: %w", err)
  226. }
  227. p.androidCRL = &androidCRLCache{}
  228. if p.ctl, err = NewController(p, p.Claims, config, p.Options); err != nil {
  229. return err
  230. }
  231. if err := p.initializeRemoteAttestation(); err != nil {
  232. return fmt.Errorf("failed initializing remote attestation: %w", err)
  233. }
  234. return nil
  235. }
  236. const (
  237. androidAttestationStatusURL = "https://android.googleapis.com/attestation/status" // TODO(hs): make configurable through options?
  238. androidCRLTTL = 24 * time.Hour // TODO(hs): make configurable through options and/or Cache-Control header?
  239. )
  240. // snapshot returns a fresh-enough snapshot of the Android revocation list,
  241. // fetching a new one if the cached copy is missing or older than androidCRLTTL.
  242. // Concurrent refreshes are coalesced into a single upstream request, so a burst
  243. // of validations results in at most one call to the Android status endpoint.
  244. func (c *androidCRLCache) snapshot(ctx context.Context, client HTTPClient) (*androidCRL, error) {
  245. if crl := c.current.Load(); crl != nil && time.Since(crl.fetchedAt) < androidCRLTTL {
  246. return crl, nil
  247. }
  248. // The cache is missing or stale. Coalesce concurrent refreshes so that only
  249. // one upstream request is performed; all callers share its result.
  250. v, err, _ := c.group.Do("android-crl", func() (any, error) {
  251. // Re-check under the singleflight leader: another goroutine may have
  252. // refreshed the snapshot while we were queued behind it.
  253. if crl := c.current.Load(); crl != nil && time.Since(crl.fetchedAt) < androidCRLTTL {
  254. return crl, nil
  255. }
  256. // load the CRL. We choose to let all followers get a context.Canceled when the
  257. // leader's ctx is canceled. Clients will retry after.
  258. return c.load(ctx, client)
  259. })
  260. if err != nil {
  261. return nil, err
  262. }
  263. return v.(*androidCRL), nil
  264. }
  265. // load fetches the CRL at https://android.googleapis.com/attestation/status,
  266. // builds the set of revoked serial numbers, and atomically publishes it as the
  267. // current snapshot.
  268. func (c *androidCRLCache) load(ctx context.Context, client HTTPClient) (*androidCRL, error) {
  269. var crlResponse struct {
  270. Entries map[string]struct {
  271. Status string `json:"status"`
  272. Reason string `json:"reason"`
  273. } `json:"entries"`
  274. }
  275. req, err := http.NewRequestWithContext(ctx, http.MethodGet, androidAttestationStatusURL, http.NoBody)
  276. if err != nil {
  277. return nil, fmt.Errorf("failed creating Android CRL request: %w", err)
  278. }
  279. res, err := client.Do(req)
  280. if err != nil {
  281. return nil, fmt.Errorf("failed performing Android CRL request: %w", err)
  282. }
  283. defer res.Body.Close()
  284. if res.StatusCode != http.StatusOK {
  285. return nil, fmt.Errorf("unexpected Android CRL response %d", res.StatusCode)
  286. }
  287. if err := json.NewDecoder(res.Body).Decode(&crlResponse); err != nil {
  288. return nil, fmt.Errorf("error decoding Android CRL JSON: %w", err)
  289. }
  290. // Build the set of revoked serials. Currently no distinction is being made
  291. // based on the status of the certificate. The status can be "REVOKED" and
  292. // "SUSPENDED"; both statuses result in a certificate being considered
  293. // revoked.
  294. serials := make(map[string]struct{}, len(crlResponse.Entries))
  295. for k := range crlResponse.Entries {
  296. serials[k] = struct{}{}
  297. }
  298. crl := &androidCRL{serials: serials, fetchedAt: time.Now()}
  299. c.current.Store(crl)
  300. return crl, nil
  301. }
  302. // initializeWireOptions initializes the options for the ACME Wire
  303. // integration. It'll return early if no Wire challenge types are
  304. // enabled.
  305. func (p *ACME) initializeWireOptions() error {
  306. hasWireChallenges := false
  307. for _, c := range p.Challenges {
  308. if c == WIREOIDC_01 || c == WIREDPOP_01 {
  309. hasWireChallenges = true
  310. break
  311. }
  312. }
  313. if !hasWireChallenges {
  314. return nil
  315. }
  316. w, err := p.GetOptions().GetWireOptions()
  317. if err != nil {
  318. return fmt.Errorf("failed getting Wire options: %w", err)
  319. }
  320. if err := w.Validate(); err != nil {
  321. return fmt.Errorf("failed validating Wire options: %w", err)
  322. }
  323. // at this point the Wire options have been validated, and (mostly)
  324. // initialized. Remote keys will be loaded upon the first verification,
  325. // currently.
  326. // TODO(hs): can/should we "prime" the underlying remote keyset, to verify
  327. // auto discovery works as expected? Because of the current way provisioners
  328. // are initialized, doing that as part of the initialization isn't the best
  329. // time to do it, because it could result in operations not resulting in the
  330. // expected result in all cases.
  331. return nil
  332. }
  333. // ACMEIdentifierType encodes ACME Identifier types
  334. type ACMEIdentifierType string
  335. const (
  336. // IP is the ACME ip identifier type
  337. IP ACMEIdentifierType = "ip"
  338. // DNS is the ACME dns identifier type
  339. DNS ACMEIdentifierType = "dns"
  340. // WireUser is the Wire user identifier type
  341. WireUser ACMEIdentifierType = "wireapp-user"
  342. // WireDevice is the Wire device identifier type
  343. WireDevice ACMEIdentifierType = "wireapp-device"
  344. // RemoteAttestation is the remote-attestation identifier type
  345. // (draft-ietf-acme-rats). Its value is a hint of the attestation asked
  346. // for, and it puts nothing in the certificate.
  347. RemoteAttestation ACMEIdentifierType = "remote-attestation"
  348. )
  349. // ACMEIdentifier encodes ACME Order Identifiers
  350. type ACMEIdentifier struct {
  351. Type ACMEIdentifierType
  352. Value string
  353. }
  354. // AuthorizeOrderIdentifier verifies the provisioner is allowed to issue a
  355. // certificate for an ACME Order Identifier.
  356. func (p *ACME) AuthorizeOrderIdentifier(_ context.Context, identifier ACMEIdentifier) error {
  357. // A remote-attestation identifier names nothing in the certificate, so
  358. // no name policy applies to it.
  359. if identifier.Type == RemoteAttestation {
  360. return nil
  361. }
  362. x509Policy := p.ctl.getPolicy().getX509()
  363. // identifier is allowed if no policy is configured
  364. if x509Policy == nil {
  365. return nil
  366. }
  367. // assuming only valid identifiers (IP or DNS) are provided
  368. var err error
  369. switch identifier.Type {
  370. case IP:
  371. err = x509Policy.IsIPAllowed(net.ParseIP(identifier.Value))
  372. case DNS:
  373. err = x509Policy.IsDNSAllowed(identifier.Value)
  374. case WireUser:
  375. var wireID wire.UserID
  376. if wireID, err = wire.ParseUserID(identifier.Value); err != nil {
  377. return fmt.Errorf("failed parsing Wire SANs: %w", err)
  378. }
  379. err = x509Policy.AreSANsAllowed([]string{wireID.Handle})
  380. case WireDevice:
  381. var wireID wire.DeviceID
  382. if wireID, err = wire.ParseDeviceID(identifier.Value); err != nil {
  383. return fmt.Errorf("failed parsing Wire SANs: %w", err)
  384. }
  385. err = x509Policy.AreSANsAllowed([]string{wireID.ClientID})
  386. default:
  387. err = fmt.Errorf("invalid ACME identifier type '%s' provided", identifier.Type)
  388. }
  389. return err
  390. }
  391. // AuthorizeSign does not do any validation, because all validation is handled
  392. // in the ACME protocol. This method returns a list of modifiers / constraints
  393. // on the resulting certificate.
  394. func (p *ACME) AuthorizeSign(context.Context, string) ([]SignOption, error) {
  395. opts := []SignOption{
  396. p,
  397. // modifiers / withOptions
  398. newProvisionerExtensionOption(TypeACME, p.Name, "").WithControllerOptions(p.ctl),
  399. newForceCNOption(p.ForceCN),
  400. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  401. // validators
  402. defaultPublicKeyValidator{},
  403. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  404. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  405. p.ctl.newWebhookController(nil, linkedca.Webhook_X509),
  406. }
  407. return opts, nil
  408. }
  409. // AuthorizeRevoke is called just before the certificate is to be revoked by
  410. // the CA. It can be used to authorize revocation of a certificate. With the
  411. // ACME protocol, revocation authorization is specified and performed as part
  412. // of the client/server interaction, so this is a no-op.
  413. func (p *ACME) AuthorizeRevoke(context.Context, string) error {
  414. return nil
  415. }
  416. // AuthorizeRenew returns an error if the renewal is disabled.
  417. // NOTE: This method does not actually validate the certificate or check its
  418. // revocation status. Just confirms that the provisioner that created the
  419. // certificate was configured to allow renewals.
  420. func (p *ACME) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  421. return p.ctl.AuthorizeRenew(ctx, cert)
  422. }
  423. // IsChallengeEnabled checks if the given challenge is enabled. By default
  424. // http-01, dns-01 and tls-alpn-01 are enabled, to disable any of them the
  425. // Challenge provisioner property should have at least one element.
  426. func (p *ACME) IsChallengeEnabled(_ context.Context, challenge ACMEChallenge) bool {
  427. enabledChallenges := []ACMEChallenge{
  428. HTTP_01, DNS_01, TLS_ALPN_01,
  429. }
  430. if len(p.Challenges) > 0 {
  431. enabledChallenges = p.Challenges
  432. }
  433. for _, ch := range enabledChallenges {
  434. if strings.EqualFold(string(ch), string(challenge)) {
  435. return true
  436. }
  437. }
  438. return false
  439. }
  440. // IsAttestationFormatEnabled checks if the given attestation format is enabled.
  441. // By default apple, step and tpm are enabled, to disable any of them the
  442. // AttestationFormat provisioner property should have at least one element.
  443. func (p *ACME) IsAttestationFormatEnabled(_ context.Context, format ACMEAttestationFormat) bool {
  444. enabledFormats := []ACMEAttestationFormat{
  445. APPLE, STEP, TPM, ANDROIDKEY,
  446. }
  447. if len(p.AttestationFormats) > 0 {
  448. enabledFormats = p.AttestationFormats
  449. }
  450. for _, f := range enabledFormats {
  451. if strings.EqualFold(string(f), string(format)) {
  452. return true
  453. }
  454. }
  455. return false
  456. }
  457. // GetAttestationRoots returns certificate pool with the configured attestation
  458. // roots and reports if the pool contains at least one certificate.
  459. //
  460. // TODO(hs): we may not want to expose the root pool like this; call into an
  461. // interface function instead to authorize?
  462. func (p *ACME) GetAttestationRoots() (*x509.CertPool, bool) {
  463. return p.attestationRootPool, p.attestationRootPool != nil
  464. }
  465. // IsAndroidCertificateRevoked returns whether the serial number is
  466. // revoked or not.
  467. func (p *ACME) IsAndroidCertificateRevoked(ctx context.Context, cert *x509.Certificate) (bool, error) {
  468. // the check only has to be performed when the "android-key" attestation
  469. // format is enabled
  470. if !p.IsAttestationFormatEnabled(ctx, ANDROIDKEY) {
  471. return false, nil
  472. }
  473. if p.ctl.androidKeyCRLChecker != nil {
  474. revoked, err := p.ctl.androidKeyCRLChecker.IsRevoked(ctx, cert)
  475. if err != nil {
  476. return true, fmt.Errorf("failed checking certificate against Android CRL: %w", err)
  477. }
  478. return revoked, nil
  479. }
  480. // No CRL check is performed using Google's CRL if custom roots
  481. // are configured.
  482. if p.attestationRootPool != nil {
  483. return false, nil
  484. }
  485. // Fall back to the built-in CRL. A fetch error fails closed: the
  486. // certificate is reported as revoked so the attestation is rejected.
  487. crl, err := p.androidCRL.snapshot(ctx, p.ctl.GetHTTPClient())
  488. if err != nil {
  489. return true, err
  490. }
  491. return crl.contains(cert), nil
  492. }