acme.go 18 KB

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