acme.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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.
  126. func (p *ACME) GetTokenID(string) (string, error) {
  127. return "", errors.New("acme provisioner does not implement GetTokenID")
  128. }
  129. // GetName returns the name of the provisioner.
  130. func (p *ACME) GetName() string {
  131. return p.Name
  132. }
  133. // GetType returns the type of provisioner.
  134. func (p *ACME) GetType() Type {
  135. return TypeACME
  136. }
  137. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  138. func (p *ACME) GetEncryptedKey() (string, string, bool) {
  139. return "", "", false
  140. }
  141. // GetOptions returns the configured provisioner options.
  142. func (p *ACME) GetOptions() *Options {
  143. return p.Options
  144. }
  145. // DefaultTLSCertDuration returns the default TLS cert duration enforced by
  146. // the provisioner.
  147. func (p *ACME) DefaultTLSCertDuration() time.Duration {
  148. return p.ctl.Claimer.DefaultTLSCertDuration()
  149. }
  150. // Init initializes and validates the fields of an ACME type.
  151. func (p *ACME) Init(config Config) (err error) {
  152. switch {
  153. case p.Type == "":
  154. return errors.New("provisioner type cannot be empty")
  155. case p.Name == "":
  156. return errors.New("provisioner name cannot be empty")
  157. }
  158. for _, c := range p.Challenges {
  159. if err := c.Validate(); err != nil {
  160. return err
  161. }
  162. }
  163. for _, f := range p.AttestationFormats {
  164. if err := f.Validate(); err != nil {
  165. return err
  166. }
  167. }
  168. // Parse attestation roots.
  169. // The pool will be nil if there are no roots.
  170. if rest := p.AttestationRoots; len(rest) > 0 {
  171. var block *pem.Block
  172. var hasCert bool
  173. p.attestationRootPool = x509.NewCertPool()
  174. for rest != nil {
  175. block, rest = pem.Decode(rest)
  176. if block == nil {
  177. break
  178. }
  179. cert, err := x509.ParseCertificate(block.Bytes)
  180. if err != nil {
  181. return errors.New("error parsing attestationRoots: malformed certificate")
  182. }
  183. p.attestationRootPool.AddCert(cert)
  184. hasCert = true
  185. }
  186. if !hasCert {
  187. return errors.New("error parsing attestationRoots: no certificates found")
  188. }
  189. }
  190. if err := p.initializeWireOptions(); err != nil {
  191. return fmt.Errorf("failed initializing Wire options: %w", err)
  192. }
  193. p.ctl, err = NewController(p, p.Claims, config, p.Options)
  194. return
  195. }
  196. // initializeWireOptions initializes the options for the ACME Wire
  197. // integration. It'll return early if no Wire challenge types are
  198. // enabled.
  199. func (p *ACME) initializeWireOptions() error {
  200. hasWireChallenges := false
  201. for _, c := range p.Challenges {
  202. if c == WIREOIDC_01 || c == WIREDPOP_01 {
  203. hasWireChallenges = true
  204. break
  205. }
  206. }
  207. if !hasWireChallenges {
  208. return nil
  209. }
  210. w, err := p.GetOptions().GetWireOptions()
  211. if err != nil {
  212. return fmt.Errorf("failed getting Wire options: %w", err)
  213. }
  214. if err := w.Validate(); err != nil {
  215. return fmt.Errorf("failed validating Wire options: %w", err)
  216. }
  217. // at this point the Wire options have been validated, and (mostly)
  218. // initialized. Remote keys will be loaded upon the first verification,
  219. // currently.
  220. // TODO(hs): can/should we "prime" the underlying remote keyset, to verify
  221. // auto discovery works as expected? Because of the current way provisioners
  222. // are initialized, doing that as part of the initialization isn't the best
  223. // time to do it, because it could result in operations not resulting in the
  224. // expected result in all cases.
  225. return nil
  226. }
  227. // ACMEIdentifierType encodes ACME Identifier types
  228. type ACMEIdentifierType string
  229. const (
  230. // IP is the ACME ip identifier type
  231. IP ACMEIdentifierType = "ip"
  232. // DNS is the ACME dns identifier type
  233. DNS ACMEIdentifierType = "dns"
  234. // WireUser is the Wire user identifier type
  235. WireUser ACMEIdentifierType = "wireapp-user"
  236. // WireDevice is the Wire device identifier type
  237. WireDevice ACMEIdentifierType = "wireapp-device"
  238. )
  239. // ACMEIdentifier encodes ACME Order Identifiers
  240. type ACMEIdentifier struct {
  241. Type ACMEIdentifierType
  242. Value string
  243. }
  244. // AuthorizeOrderIdentifier verifies the provisioner is allowed to issue a
  245. // certificate for an ACME Order Identifier.
  246. func (p *ACME) AuthorizeOrderIdentifier(_ context.Context, identifier ACMEIdentifier) error {
  247. x509Policy := p.ctl.getPolicy().getX509()
  248. // identifier is allowed if no policy is configured
  249. if x509Policy == nil {
  250. return nil
  251. }
  252. // assuming only valid identifiers (IP or DNS) are provided
  253. var err error
  254. switch identifier.Type {
  255. case IP:
  256. err = x509Policy.IsIPAllowed(net.ParseIP(identifier.Value))
  257. case DNS:
  258. err = x509Policy.IsDNSAllowed(identifier.Value)
  259. case WireUser:
  260. var wireID wire.UserID
  261. if wireID, err = wire.ParseUserID(identifier.Value); err != nil {
  262. return fmt.Errorf("failed parsing Wire SANs: %w", err)
  263. }
  264. err = x509Policy.AreSANsAllowed([]string{wireID.Handle})
  265. case WireDevice:
  266. var wireID wire.DeviceID
  267. if wireID, err = wire.ParseDeviceID(identifier.Value); err != nil {
  268. return fmt.Errorf("failed parsing Wire SANs: %w", err)
  269. }
  270. err = x509Policy.AreSANsAllowed([]string{wireID.ClientID})
  271. default:
  272. err = fmt.Errorf("invalid ACME identifier type '%s' provided", identifier.Type)
  273. }
  274. return err
  275. }
  276. // AuthorizeSign does not do any validation, because all validation is handled
  277. // in the ACME protocol. This method returns a list of modifiers / constraints
  278. // on the resulting certificate.
  279. func (p *ACME) AuthorizeSign(context.Context, string) ([]SignOption, error) {
  280. opts := []SignOption{
  281. p,
  282. // modifiers / withOptions
  283. newProvisionerExtensionOption(TypeACME, p.Name, "").WithControllerOptions(p.ctl),
  284. newForceCNOption(p.ForceCN),
  285. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  286. // validators
  287. defaultPublicKeyValidator{},
  288. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  289. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  290. p.ctl.newWebhookController(nil, linkedca.Webhook_X509),
  291. }
  292. return opts, nil
  293. }
  294. // AuthorizeRevoke is called just before the certificate is to be revoked by
  295. // the CA. It can be used to authorize revocation of a certificate. With the
  296. // ACME protocol, revocation authorization is specified and performed as part
  297. // of the client/server interaction, so this is a no-op.
  298. func (p *ACME) AuthorizeRevoke(context.Context, string) error {
  299. return nil
  300. }
  301. // AuthorizeRenew returns an error if the renewal is disabled.
  302. // NOTE: This method does not actually validate the certificate or check its
  303. // revocation status. Just confirms that the provisioner that created the
  304. // certificate was configured to allow renewals.
  305. func (p *ACME) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  306. return p.ctl.AuthorizeRenew(ctx, cert)
  307. }
  308. // IsChallengeEnabled checks if the given challenge is enabled. By default
  309. // http-01, dns-01 and tls-alpn-01 are enabled, to disable any of them the
  310. // Challenge provisioner property should have at least one element.
  311. func (p *ACME) IsChallengeEnabled(_ context.Context, challenge ACMEChallenge) bool {
  312. enabledChallenges := []ACMEChallenge{
  313. HTTP_01, DNS_01, TLS_ALPN_01,
  314. }
  315. if len(p.Challenges) > 0 {
  316. enabledChallenges = p.Challenges
  317. }
  318. for _, ch := range enabledChallenges {
  319. if strings.EqualFold(string(ch), string(challenge)) {
  320. return true
  321. }
  322. }
  323. return false
  324. }
  325. // IsAttestationFormatEnabled checks if the given attestation format is enabled.
  326. // By default apple, step and tpm are enabled, to disable any of them the
  327. // AttestationFormat provisioner property should have at least one element.
  328. func (p *ACME) IsAttestationFormatEnabled(_ context.Context, format ACMEAttestationFormat) bool {
  329. enabledFormats := []ACMEAttestationFormat{
  330. APPLE, STEP, TPM,
  331. }
  332. if len(p.AttestationFormats) > 0 {
  333. enabledFormats = p.AttestationFormats
  334. }
  335. for _, f := range enabledFormats {
  336. if strings.EqualFold(string(f), string(format)) {
  337. return true
  338. }
  339. }
  340. return false
  341. }
  342. // GetAttestationRoots returns certificate pool with the configured attestation
  343. // roots and reports if the pool contains at least one certificate.
  344. //
  345. // TODO(hs): we may not want to expose the root pool like this; call into an
  346. // interface function instead to authorize?
  347. func (p *ACME) GetAttestationRoots() (*x509.CertPool, bool) {
  348. return p.attestationRootPool, p.attestationRootPool != nil
  349. }