acme.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "fmt"
  7. "net"
  8. "strings"
  9. "time"
  10. "github.com/pkg/errors"
  11. "github.com/smallstep/certificates/acme/wire"
  12. "github.com/smallstep/linkedca"
  13. )
  14. // ACMEChallenge represents the supported acme challenges.
  15. type ACMEChallenge string
  16. //nolint:staticcheck,revive // better names
  17. const (
  18. // HTTP_01 is the http-01 ACME challenge.
  19. HTTP_01 ACMEChallenge = "http-01"
  20. // DNS_01 is the dns-01 ACME challenge.
  21. DNS_01 ACMEChallenge = "dns-01"
  22. // TLS_ALPN_01 is the tls-alpn-01 ACME challenge.
  23. TLS_ALPN_01 ACMEChallenge = "tls-alpn-01"
  24. // DEVICE_ATTEST_01 is the device-attest-01 ACME challenge.
  25. DEVICE_ATTEST_01 ACMEChallenge = "device-attest-01"
  26. // WIREOIDC_01 is the Wire OIDC challenge.
  27. WIREOIDC_01 ACMEChallenge = "wire-oidc-01"
  28. // WIREDPOP_01 is the Wire DPoP challenge.
  29. WIREDPOP_01 ACMEChallenge = "wire-dpop-01"
  30. )
  31. // String returns a normalized version of the challenge.
  32. func (c ACMEChallenge) String() string {
  33. return strings.ToLower(string(c))
  34. }
  35. // Validate returns an error if the acme challenge is not a valid one.
  36. func (c ACMEChallenge) Validate() error {
  37. switch ACMEChallenge(c.String()) {
  38. case HTTP_01, DNS_01, TLS_ALPN_01, DEVICE_ATTEST_01, WIREOIDC_01, WIREDPOP_01:
  39. return nil
  40. default:
  41. return fmt.Errorf("acme challenge %q is not supported", c)
  42. }
  43. }
  44. // ACMEAttestationFormat represents the format used on a device-attest-01
  45. // challenge.
  46. type ACMEAttestationFormat string
  47. const (
  48. // APPLE is the format used to enable device-attest-01 on Apple devices.
  49. APPLE ACMEAttestationFormat = "apple"
  50. // STEP is the format used to enable device-attest-01 on devices that
  51. // provide attestation certificates like the PIV interface on YubiKeys.
  52. //
  53. // TODO(mariano): should we rename this to something else.
  54. STEP ACMEAttestationFormat = "step"
  55. // TPM is the format used to enable device-attest-01 with TPMs.
  56. TPM ACMEAttestationFormat = "tpm"
  57. )
  58. // String returns a normalized version of the attestation format.
  59. func (f ACMEAttestationFormat) String() string {
  60. return strings.ToLower(string(f))
  61. }
  62. // Validate returns an error if the attestation format is not a valid one.
  63. func (f ACMEAttestationFormat) Validate() error {
  64. switch ACMEAttestationFormat(f.String()) {
  65. case APPLE, STEP, TPM:
  66. return nil
  67. default:
  68. return fmt.Errorf("acme attestation format %q is not supported", f)
  69. }
  70. }
  71. // ACME is the acme provisioner type, an entity that can authorize the ACME
  72. // provisioning flow.
  73. type ACME struct {
  74. *base
  75. ID string `json:"-"`
  76. Type string `json:"type"`
  77. Name string `json:"name"`
  78. ForceCN bool `json:"forceCN,omitempty"`
  79. // TermsOfService contains a URL pointing to the ACME server's
  80. // terms of service. Defaults to empty.
  81. TermsOfService string `json:"termsOfService,omitempty"`
  82. // Website contains an URL pointing to more information about
  83. // the ACME server. Defaults to empty.
  84. Website string `json:"website,omitempty"`
  85. // CaaIdentities is an array of hostnames that the ACME server
  86. // identifies itself with. These hostnames can be used by ACME
  87. // clients to determine the correct issuer domain name to use
  88. // when configuring CAA records. Defaults to empty array.
  89. CaaIdentities []string `json:"caaIdentities,omitempty"`
  90. // RequireEAB makes the provisioner require ACME EAB to be provided
  91. // by clients when creating a new Account. If set to true, the provided
  92. // EAB will be verified. If set to false and an EAB is provided, it is
  93. // not verified. Defaults to false.
  94. RequireEAB bool `json:"requireEAB,omitempty"`
  95. // Challenges contains the enabled challenges for this provisioner. If this
  96. // value is not set the default http-01, dns-01 and tls-alpn-01 challenges
  97. // will be enabled, device-attest-01, wire-oidc-01 and wire-dpop-01 will be
  98. // disabled.
  99. Challenges []ACMEChallenge `json:"challenges,omitempty"`
  100. // AttestationFormats contains the enabled attestation formats for this
  101. // provisioner. If this value is not set the default apple, step and tpm
  102. // will be used.
  103. AttestationFormats []ACMEAttestationFormat `json:"attestationFormats,omitempty"`
  104. // AttestationRoots contains a bundle of root certificates in PEM format
  105. // that will be used to verify the attestation certificates. If provided,
  106. // this bundle will be used even for well-known CAs like Apple and Yubico.
  107. AttestationRoots []byte `json:"attestationRoots,omitempty"`
  108. Claims *Claims `json:"claims,omitempty"`
  109. Options *Options `json:"options,omitempty"`
  110. attestationRootPool *x509.CertPool
  111. ctl *Controller
  112. }
  113. // GetID returns the provisioner unique identifier.
  114. func (p ACME) GetID() string {
  115. if p.ID != "" {
  116. return p.ID
  117. }
  118. return p.GetIDForToken()
  119. }
  120. // GetIDForToken returns an identifier that will be used to load the provisioner
  121. // from a token.
  122. func (p *ACME) GetIDForToken() string {
  123. return "acme/" + p.Name
  124. }
  125. // GetTokenID returns the identifier of the token. This provisioner will always
  126. // return [ErrTokenFlowNotSupported].
  127. func (p *ACME) GetTokenID(string) (string, error) {
  128. return "", ErrTokenFlowNotSupported
  129. }
  130. // GetName returns the name of the provisioner.
  131. func (p *ACME) GetName() string {
  132. return p.Name
  133. }
  134. // GetType returns the type of provisioner.
  135. func (p *ACME) GetType() Type {
  136. return TypeACME
  137. }
  138. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  139. func (p *ACME) GetEncryptedKey() (string, string, bool) {
  140. return "", "", false
  141. }
  142. // GetOptions returns the configured provisioner options.
  143. func (p *ACME) GetOptions() *Options {
  144. return p.Options
  145. }
  146. // DefaultTLSCertDuration returns the default TLS cert duration enforced by
  147. // the provisioner.
  148. func (p *ACME) DefaultTLSCertDuration() time.Duration {
  149. return p.ctl.Claimer.DefaultTLSCertDuration()
  150. }
  151. // Init initializes and validates the fields of an ACME type.
  152. func (p *ACME) Init(config Config) (err error) {
  153. switch {
  154. case p.Type == "":
  155. return errors.New("provisioner type cannot be empty")
  156. case p.Name == "":
  157. return errors.New("provisioner name cannot be empty")
  158. }
  159. for _, c := range p.Challenges {
  160. if err := c.Validate(); err != nil {
  161. return err
  162. }
  163. }
  164. for _, f := range p.AttestationFormats {
  165. if err := f.Validate(); err != nil {
  166. return err
  167. }
  168. }
  169. // Parse attestation roots.
  170. // The pool will be nil if there are no roots.
  171. if rest := p.AttestationRoots; len(rest) > 0 {
  172. var block *pem.Block
  173. var hasCert bool
  174. p.attestationRootPool = x509.NewCertPool()
  175. for rest != nil {
  176. block, rest = pem.Decode(rest)
  177. if block == nil {
  178. break
  179. }
  180. cert, err := x509.ParseCertificate(block.Bytes)
  181. if err != nil {
  182. return errors.New("error parsing attestationRoots: malformed certificate")
  183. }
  184. p.attestationRootPool.AddCert(cert)
  185. hasCert = true
  186. }
  187. if !hasCert {
  188. return errors.New("error parsing attestationRoots: no certificates found")
  189. }
  190. }
  191. if err := p.initializeWireOptions(); err != nil {
  192. return fmt.Errorf("failed initializing Wire options: %w", err)
  193. }
  194. p.ctl, err = NewController(p, p.Claims, config, p.Options)
  195. return
  196. }
  197. // initializeWireOptions initializes the options for the ACME Wire
  198. // integration. It'll return early if no Wire challenge types are
  199. // enabled.
  200. func (p *ACME) initializeWireOptions() error {
  201. hasWireChallenges := false
  202. for _, c := range p.Challenges {
  203. if c == WIREOIDC_01 || c == WIREDPOP_01 {
  204. hasWireChallenges = true
  205. break
  206. }
  207. }
  208. if !hasWireChallenges {
  209. return nil
  210. }
  211. w, err := p.GetOptions().GetWireOptions()
  212. if err != nil {
  213. return fmt.Errorf("failed getting Wire options: %w", err)
  214. }
  215. if err := w.Validate(); err != nil {
  216. return fmt.Errorf("failed validating Wire options: %w", err)
  217. }
  218. // at this point the Wire options have been validated, and (mostly)
  219. // initialized. Remote keys will be loaded upon the first verification,
  220. // currently.
  221. // TODO(hs): can/should we "prime" the underlying remote keyset, to verify
  222. // auto discovery works as expected? Because of the current way provisioners
  223. // are initialized, doing that as part of the initialization isn't the best
  224. // time to do it, because it could result in operations not resulting in the
  225. // expected result in all cases.
  226. return nil
  227. }
  228. // ACMEIdentifierType encodes ACME Identifier types
  229. type ACMEIdentifierType string
  230. const (
  231. // IP is the ACME ip identifier type
  232. IP ACMEIdentifierType = "ip"
  233. // DNS is the ACME dns identifier type
  234. DNS ACMEIdentifierType = "dns"
  235. // WireUser is the Wire user identifier type
  236. WireUser ACMEIdentifierType = "wireapp-user"
  237. // WireDevice is the Wire device identifier type
  238. WireDevice ACMEIdentifierType = "wireapp-device"
  239. )
  240. // ACMEIdentifier encodes ACME Order Identifiers
  241. type ACMEIdentifier struct {
  242. Type ACMEIdentifierType
  243. Value string
  244. }
  245. // AuthorizeOrderIdentifier verifies the provisioner is allowed to issue a
  246. // certificate for an ACME Order Identifier.
  247. func (p *ACME) AuthorizeOrderIdentifier(_ context.Context, identifier ACMEIdentifier) error {
  248. x509Policy := p.ctl.getPolicy().getX509()
  249. // identifier is allowed if no policy is configured
  250. if x509Policy == nil {
  251. return nil
  252. }
  253. // assuming only valid identifiers (IP or DNS) are provided
  254. var err error
  255. switch identifier.Type {
  256. case IP:
  257. err = x509Policy.IsIPAllowed(net.ParseIP(identifier.Value))
  258. case DNS:
  259. err = x509Policy.IsDNSAllowed(identifier.Value)
  260. case WireUser:
  261. var wireID wire.UserID
  262. if wireID, err = wire.ParseUserID(identifier.Value); err != nil {
  263. return fmt.Errorf("failed parsing Wire SANs: %w", err)
  264. }
  265. err = x509Policy.AreSANsAllowed([]string{wireID.Handle})
  266. case WireDevice:
  267. var wireID wire.DeviceID
  268. if wireID, err = wire.ParseDeviceID(identifier.Value); err != nil {
  269. return fmt.Errorf("failed parsing Wire SANs: %w", err)
  270. }
  271. err = x509Policy.AreSANsAllowed([]string{wireID.ClientID})
  272. default:
  273. err = fmt.Errorf("invalid ACME identifier type '%s' provided", identifier.Type)
  274. }
  275. return err
  276. }
  277. // AuthorizeSign does not do any validation, because all validation is handled
  278. // in the ACME protocol. This method returns a list of modifiers / constraints
  279. // on the resulting certificate.
  280. func (p *ACME) AuthorizeSign(context.Context, string) ([]SignOption, error) {
  281. opts := []SignOption{
  282. p,
  283. // modifiers / withOptions
  284. newProvisionerExtensionOption(TypeACME, p.Name, "").WithControllerOptions(p.ctl),
  285. newForceCNOption(p.ForceCN),
  286. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  287. // validators
  288. defaultPublicKeyValidator{},
  289. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  290. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  291. p.ctl.newWebhookController(nil, linkedca.Webhook_X509),
  292. }
  293. return opts, nil
  294. }
  295. // AuthorizeRevoke is called just before the certificate is to be revoked by
  296. // the CA. It can be used to authorize revocation of a certificate. With the
  297. // ACME protocol, revocation authorization is specified and performed as part
  298. // of the client/server interaction, so this is a no-op.
  299. func (p *ACME) AuthorizeRevoke(context.Context, string) error {
  300. return nil
  301. }
  302. // AuthorizeRenew returns an error if the renewal is disabled.
  303. // NOTE: This method does not actually validate the certificate or check its
  304. // revocation status. Just confirms that the provisioner that created the
  305. // certificate was configured to allow renewals.
  306. func (p *ACME) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  307. return p.ctl.AuthorizeRenew(ctx, cert)
  308. }
  309. // IsChallengeEnabled checks if the given challenge is enabled. By default
  310. // http-01, dns-01 and tls-alpn-01 are enabled, to disable any of them the
  311. // Challenge provisioner property should have at least one element.
  312. func (p *ACME) IsChallengeEnabled(_ context.Context, challenge ACMEChallenge) bool {
  313. enabledChallenges := []ACMEChallenge{
  314. HTTP_01, DNS_01, TLS_ALPN_01,
  315. }
  316. if len(p.Challenges) > 0 {
  317. enabledChallenges = p.Challenges
  318. }
  319. for _, ch := range enabledChallenges {
  320. if strings.EqualFold(string(ch), string(challenge)) {
  321. return true
  322. }
  323. }
  324. return false
  325. }
  326. // IsAttestationFormatEnabled checks if the given attestation format is enabled.
  327. // By default apple, step and tpm are enabled, to disable any of them the
  328. // AttestationFormat provisioner property should have at least one element.
  329. func (p *ACME) IsAttestationFormatEnabled(_ context.Context, format ACMEAttestationFormat) bool {
  330. enabledFormats := []ACMEAttestationFormat{
  331. APPLE, STEP, TPM,
  332. }
  333. if len(p.AttestationFormats) > 0 {
  334. enabledFormats = p.AttestationFormats
  335. }
  336. for _, f := range enabledFormats {
  337. if strings.EqualFold(string(f), string(format)) {
  338. return true
  339. }
  340. }
  341. return false
  342. }
  343. // GetAttestationRoots returns certificate pool with the configured attestation
  344. // roots and reports if the pool contains at least one certificate.
  345. //
  346. // TODO(hs): we may not want to expose the root pool like this; call into an
  347. // interface function instead to authorize?
  348. func (p *ACME) GetAttestationRoots() (*x509.CertPool, bool) {
  349. return p.attestationRootPool, p.attestationRootPool != nil
  350. }