sign_options.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/rsa"
  5. "crypto/sha256"
  6. "crypto/subtle"
  7. "crypto/x509"
  8. "encoding/base64"
  9. "encoding/json"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "reflect"
  14. "slices"
  15. "time"
  16. "go.step.sm/crypto/keyutil"
  17. "go.step.sm/crypto/x509util"
  18. "github.com/smallstep/certificates/authority/policy"
  19. "github.com/smallstep/certificates/errs"
  20. "github.com/smallstep/certificates/internal/cryptoutil"
  21. )
  22. // DefaultCertValidity is the default validity for a certificate if none is specified.
  23. const DefaultCertValidity = 24 * time.Hour
  24. // SignOptions contains the options that can be passed to the Sign method. Backdate
  25. // is automatically filled and can only be configured in the CA.
  26. type SignOptions struct {
  27. NotAfter TimeDuration `json:"notAfter"`
  28. NotBefore TimeDuration `json:"notBefore"`
  29. TemplateData json.RawMessage `json:"templateData"`
  30. Backdate time.Duration `json:"-"`
  31. }
  32. // SignOption is the interface used to collect all extra options used in the
  33. // Sign method.
  34. type SignOption any
  35. // CertificateValidator is an interface used to validate a given X.509 certificate.
  36. type CertificateValidator interface {
  37. Valid(cert *x509.Certificate, opts SignOptions) error
  38. }
  39. // CertificateRequestValidator is an interface used to validate a given X.509 certificate request.
  40. type CertificateRequestValidator interface {
  41. Valid(cr *x509.CertificateRequest) error
  42. }
  43. // CertificateModifier is an interface used to modify a given X.509 certificate.
  44. // Types implementing this interface will be validated with a
  45. // CertificateValidator.
  46. type CertificateModifier interface {
  47. Modify(cert *x509.Certificate, opts SignOptions) error
  48. }
  49. // CertificateEnforcer is an interface used to modify a given X.509 certificate.
  50. // Types implemented this interface will NOT be validated with a
  51. // CertificateValidator.
  52. type CertificateEnforcer interface {
  53. Enforce(cert *x509.Certificate) error
  54. }
  55. // CertificateModifierFunc allows to create simple certificate modifiers just
  56. // with a function.
  57. type CertificateModifierFunc func(cert *x509.Certificate, opts SignOptions) error
  58. // Modify implements CertificateModifier and just calls the defined function.
  59. func (fn CertificateModifierFunc) Modify(cert *x509.Certificate, opts SignOptions) error {
  60. return fn(cert, opts)
  61. }
  62. // CertificateEnforcerFunc allows to create simple certificate enforcer just
  63. // with a function.
  64. type CertificateEnforcerFunc func(cert *x509.Certificate) error
  65. // Enforce implements CertificateEnforcer and just calls the defined function.
  66. func (fn CertificateEnforcerFunc) Enforce(cert *x509.Certificate) error {
  67. return fn(cert)
  68. }
  69. // AttestationData is a SignOption used to pass attestation information to the
  70. // sign methods.
  71. type AttestationData struct {
  72. PermanentIdentifier string
  73. }
  74. // defaultPublicKeyValidator validates the public key of a certificate request.
  75. type defaultPublicKeyValidator struct{}
  76. // Valid checks that certificate request common name matches the one configured.
  77. func (v defaultPublicKeyValidator) Valid(req *x509.CertificateRequest) error {
  78. return newPublicKeyMinimumLengthValidator(8 * keyutil.MinRSAKeyBytes).Valid(req)
  79. }
  80. // publicKeyMinimumLengthValidator validates the length (in bits) of the public key
  81. // of a certificate request is at least a certain length
  82. type publicKeyMinimumLengthValidator struct {
  83. length int
  84. }
  85. // newPublicKeyMinimumLengthValidator creates a new publicKeyMinimumLengthValidator
  86. // with the given length as its minimum value
  87. // TODO: change the defaultPublicKeyValidator to have a configurable length instead?
  88. func newPublicKeyMinimumLengthValidator(length int) publicKeyMinimumLengthValidator {
  89. return publicKeyMinimumLengthValidator{
  90. length: length,
  91. }
  92. }
  93. // Valid checks that certificate request common name matches the one configured.
  94. func (v publicKeyMinimumLengthValidator) Valid(req *x509.CertificateRequest) error {
  95. if rsaKey, ok := req.PublicKey.(*rsa.PublicKey); ok {
  96. minimumLengthInBytes := v.length / 8
  97. if rsaKey.Size() < minimumLengthInBytes {
  98. return errs.Forbidden("certificate request RSA key must be at least %d bits (%d bytes)",
  99. v.length, minimumLengthInBytes)
  100. }
  101. return nil
  102. }
  103. if cryptoutil.IsSupportedPublicKey(req.PublicKey) {
  104. return nil
  105. }
  106. return errs.BadRequest("certificate request key of type '%T' is not supported", req.PublicKey)
  107. }
  108. // commonNameValidator validates the common name of a certificate request.
  109. type commonNameValidator string
  110. // Valid checks that certificate request common name matches the one configured.
  111. // An empty common name is considered valid.
  112. func (v commonNameValidator) Valid(req *x509.CertificateRequest) error {
  113. if req.Subject.CommonName == "" {
  114. return nil
  115. }
  116. if req.Subject.CommonName != string(v) {
  117. return errs.Forbidden("certificate request does not contain the valid common name - got %s, want %s", req.Subject.CommonName, v)
  118. }
  119. return nil
  120. }
  121. // commonNameSliceValidator validates that the common name of a certificate
  122. // request is present in the slice. An empty common name is considered valid.
  123. type commonNameSliceValidator []string
  124. func (v commonNameSliceValidator) Valid(req *x509.CertificateRequest) error {
  125. if req.Subject.CommonName == "" {
  126. return nil
  127. }
  128. if slices.Contains(v, req.Subject.CommonName) {
  129. return nil
  130. }
  131. return errs.Forbidden("certificate request does not contain the valid common name - got %s, want %s", req.Subject.CommonName, v)
  132. }
  133. // dnsNamesValidator validates the DNS names SAN of a certificate request.
  134. type dnsNamesValidator []string
  135. // Valid checks that certificate request DNS Names match those configured in
  136. // the bootstrap (token) flow.
  137. func (v dnsNamesValidator) Valid(req *x509.CertificateRequest) error {
  138. if len(req.DNSNames) == 0 {
  139. return nil
  140. }
  141. want := make(map[string]bool)
  142. for _, s := range v {
  143. want[s] = true
  144. }
  145. got := make(map[string]bool)
  146. for _, s := range req.DNSNames {
  147. got[s] = true
  148. }
  149. if !reflect.DeepEqual(want, got) {
  150. return errs.Forbidden("certificate request does not contain the valid DNS names - got %v, want %v", req.DNSNames, v)
  151. }
  152. return nil
  153. }
  154. // dnsNamesSubsetValidator validates the DNS name SANs of a certificate request.
  155. type dnsNamesSubsetValidator []string
  156. // Valid checks that all DNS name SANs in the certificate request are present in
  157. // the allowed list of DNS names.
  158. func (v dnsNamesSubsetValidator) Valid(req *x509.CertificateRequest) error {
  159. if len(req.DNSNames) == 0 {
  160. return nil
  161. }
  162. allowed := make(map[string]struct{}, len(v))
  163. for _, s := range v {
  164. allowed[s] = struct{}{}
  165. }
  166. for _, s := range req.DNSNames {
  167. if _, ok := allowed[s]; !ok {
  168. return errs.Forbidden("certificate request contains unauthorized DNS names - got %v, allowed %v", req.DNSNames, v)
  169. }
  170. }
  171. return nil
  172. }
  173. // ipAddressesValidator validates the IP addresses SAN of a certificate request.
  174. type ipAddressesValidator []net.IP
  175. // Valid checks that certificate request IP Addresses match those configured in
  176. // the bootstrap (token) flow.
  177. func (v ipAddressesValidator) Valid(req *x509.CertificateRequest) error {
  178. if len(req.IPAddresses) == 0 {
  179. return nil
  180. }
  181. want := make(map[string]bool)
  182. for _, ip := range v {
  183. want[ip.String()] = true
  184. }
  185. got := make(map[string]bool)
  186. for _, ip := range req.IPAddresses {
  187. got[ip.String()] = true
  188. }
  189. if !reflect.DeepEqual(want, got) {
  190. return errs.Forbidden("certificate request does not contain the valid IP addresses - got %v, want %v", req.IPAddresses, v)
  191. }
  192. return nil
  193. }
  194. // emailAddressesValidator validates the email address SANs of a certificate request.
  195. type emailAddressesValidator []string
  196. // Valid checks that certificate request IP Addresses match those configured in
  197. // the bootstrap (token) flow.
  198. func (v emailAddressesValidator) Valid(req *x509.CertificateRequest) error {
  199. if len(req.EmailAddresses) == 0 {
  200. return nil
  201. }
  202. want := make(map[string]bool)
  203. for _, s := range v {
  204. want[s] = true
  205. }
  206. got := make(map[string]bool)
  207. for _, s := range req.EmailAddresses {
  208. got[s] = true
  209. }
  210. if !reflect.DeepEqual(want, got) {
  211. return errs.Forbidden("certificate request does not contain the valid email addresses - got %v, want %v", req.EmailAddresses, v)
  212. }
  213. return nil
  214. }
  215. // urisValidator validates the URI SANs of a certificate request.
  216. type urisValidator struct {
  217. ctx context.Context
  218. uris []*url.URL
  219. }
  220. func newURIsValidator(ctx context.Context, uris []*url.URL) *urisValidator {
  221. return &urisValidator{ctx, uris}
  222. }
  223. // Valid checks that certificate request IP Addresses match those configured in
  224. // the bootstrap (token) flow.
  225. func (v urisValidator) Valid(req *x509.CertificateRequest) error {
  226. // SignIdentityMethod does not need to validate URIs.
  227. if MethodFromContext(v.ctx) == SignIdentityMethod {
  228. return nil
  229. }
  230. if len(req.URIs) == 0 {
  231. return nil
  232. }
  233. want := make(map[string]bool)
  234. for _, u := range v.uris {
  235. want[u.String()] = true
  236. }
  237. got := make(map[string]bool)
  238. for _, u := range req.URIs {
  239. got[u.String()] = true
  240. }
  241. if !reflect.DeepEqual(want, got) {
  242. return errs.Forbidden("certificate request does not contain the valid URIs - got %v, want %v", req.URIs, v.uris)
  243. }
  244. return nil
  245. }
  246. // defaultsSANsValidator stores a set of SANs to eventually validate 1:1 against
  247. // the SANs in an x509 certificate request.
  248. type defaultSANsValidator struct {
  249. ctx context.Context
  250. sans []string
  251. }
  252. func newDefaultSANsValidator(ctx context.Context, sans []string) *defaultSANsValidator {
  253. return &defaultSANsValidator{ctx, sans}
  254. }
  255. // Valid verifies that the SANs stored in the validator match 1:1 with those
  256. // requested in the x509 certificate request.
  257. func (v defaultSANsValidator) Valid(req *x509.CertificateRequest) (err error) {
  258. dnsNames, ips, emails, uris := x509util.SplitSANs(v.sans)
  259. if err = dnsNamesValidator(dnsNames).Valid(req); err != nil {
  260. return
  261. } else if err = emailAddressesValidator(emails).Valid(req); err != nil {
  262. return
  263. } else if err = ipAddressesValidator(ips).Valid(req); err != nil {
  264. return
  265. } else if err = newURIsValidator(v.ctx, uris).Valid(req); err != nil {
  266. return
  267. }
  268. return
  269. }
  270. // profileDefaultDuration is a modifier that sets the certificate
  271. // duration.
  272. type profileDefaultDuration time.Duration
  273. // Modify sets the certificate NotBefore and NotAfter using the following order:
  274. // - From the SignOptions that we get from flags.
  275. // - From x509.Certificate that we get from the template.
  276. // - NotBefore from the current time with a backdate.
  277. // - NotAfter from NotBefore plus the duration in v.
  278. func (v profileDefaultDuration) Modify(cert *x509.Certificate, so SignOptions) error {
  279. var backdate time.Duration
  280. notBefore := timeOr(so.NotBefore.Time(), cert.NotBefore)
  281. if notBefore.IsZero() {
  282. notBefore = now()
  283. backdate = -1 * so.Backdate
  284. }
  285. notAfter := timeOr(so.NotAfter.RelativeTime(notBefore), cert.NotAfter)
  286. if notAfter.IsZero() {
  287. if v != 0 {
  288. notAfter = notBefore.Add(time.Duration(v))
  289. } else {
  290. notAfter = notBefore.Add(DefaultCertValidity)
  291. }
  292. }
  293. cert.NotBefore = notBefore.Add(backdate)
  294. cert.NotAfter = notAfter
  295. return nil
  296. }
  297. // profileLimitDuration is an x509 profile option that modifies an x509 validity
  298. // period according to an imposed expiration time.
  299. type profileLimitDuration struct {
  300. def time.Duration
  301. notBefore, notAfter time.Time
  302. }
  303. // Modify sets the certificate NotBefore and NotAfter but limits the validity
  304. // period to the certificate to one that is superficially imposed.
  305. //
  306. // The expected NotBefore and NotAfter are set using the following order:
  307. // - From the SignOptions that we get from flags.
  308. // - From x509.Certificate that we get from the template.
  309. // - NotBefore from the current time with a backdate.
  310. // - NotAfter from NotBefore plus the duration v or the notAfter in v if lower.
  311. func (v profileLimitDuration) Modify(cert *x509.Certificate, so SignOptions) error {
  312. var backdate time.Duration
  313. notBefore := timeOr(so.NotBefore.Time(), cert.NotBefore)
  314. if notBefore.IsZero() {
  315. notBefore = now()
  316. backdate = -1 * so.Backdate
  317. }
  318. if notBefore.Before(v.notBefore) {
  319. return errs.Forbidden(
  320. "requested certificate notBefore (%s) is before the active validity window of the provisioning credential (%s)",
  321. notBefore, v.notBefore)
  322. }
  323. notAfter := timeOr(so.NotAfter.RelativeTime(notBefore), cert.NotAfter)
  324. if notAfter.After(v.notAfter) {
  325. return errs.Forbidden(
  326. "requested certificate notAfter (%s) is after the expiration of the provisioning credential (%s)",
  327. notAfter, v.notAfter)
  328. }
  329. if notAfter.IsZero() {
  330. t := notBefore.Add(v.def)
  331. if t.After(v.notAfter) {
  332. notAfter = v.notAfter
  333. } else {
  334. notAfter = t
  335. }
  336. }
  337. cert.NotBefore = notBefore.Add(backdate)
  338. cert.NotAfter = notAfter
  339. return nil
  340. }
  341. // validityValidator validates the certificate validity settings.
  342. type validityValidator struct {
  343. min time.Duration
  344. max time.Duration
  345. }
  346. // newValidityValidator return a new validity validator.
  347. func newValidityValidator(minDur, maxDur time.Duration) *validityValidator {
  348. return &validityValidator{min: minDur, max: maxDur}
  349. }
  350. // Valid validates the certificate validity settings (notBefore/notAfter) and
  351. // total duration.
  352. func (v *validityValidator) Valid(cert *x509.Certificate, o SignOptions) error {
  353. var (
  354. na = cert.NotAfter.Truncate(time.Second)
  355. nb = cert.NotBefore.Truncate(time.Second)
  356. now = time.Now().Truncate(time.Second)
  357. )
  358. d := na.Sub(nb)
  359. if na.Before(now) {
  360. return errs.BadRequest("notAfter cannot be in the past; na=%v", na)
  361. }
  362. if na.Before(nb) {
  363. return errs.BadRequest("notAfter cannot be before notBefore; na=%v, nb=%v", na, nb)
  364. }
  365. if d < v.min {
  366. return errs.Forbidden("requested duration of %v is less than the authorized minimum certificate duration of %v", d, v.min)
  367. }
  368. // NOTE: this check is not "technically correct". We're allowing the max
  369. // duration of a cert to be "max + backdate" and not all certificates will
  370. // be backdated (e.g. if a user passes the NotBefore value then we do not
  371. // apply a backdate). This is good enough.
  372. if d > v.max+o.Backdate {
  373. return errs.Forbidden("requested duration of %v is more than the authorized maximum certificate duration of %v", d, v.max+o.Backdate)
  374. }
  375. return nil
  376. }
  377. // x509NamePolicyValidator validates that the certificate (to be signed)
  378. // contains only allowed SANs.
  379. type x509NamePolicyValidator struct {
  380. policyEngine policy.X509Policy
  381. }
  382. // newX509NamePolicyValidator return a new SANs allow/deny validator.
  383. func newX509NamePolicyValidator(engine policy.X509Policy) *x509NamePolicyValidator {
  384. return &x509NamePolicyValidator{
  385. policyEngine: engine,
  386. }
  387. }
  388. // Valid validates that the certificate (to be signed) contains only allowed SANs.
  389. func (v *x509NamePolicyValidator) Valid(cert *x509.Certificate, _ SignOptions) error {
  390. if v.policyEngine == nil {
  391. return nil
  392. }
  393. return v.policyEngine.IsX509CertificateAllowed(cert)
  394. }
  395. type forceCNOption struct {
  396. ForceCN bool
  397. }
  398. func newForceCNOption(forceCN bool) *forceCNOption {
  399. return &forceCNOption{forceCN}
  400. }
  401. func (o *forceCNOption) Modify(cert *x509.Certificate, _ SignOptions) error {
  402. if !o.ForceCN {
  403. return nil
  404. }
  405. // Force the common name to be the first DNS if not provided.
  406. if cert.Subject.CommonName == "" {
  407. if len(cert.DNSNames) == 0 {
  408. return errs.BadRequest("cannot force common name, DNS names is empty")
  409. }
  410. cert.Subject.CommonName = cert.DNSNames[0]
  411. }
  412. return nil
  413. }
  414. type provisionerExtensionOption struct {
  415. Extension
  416. Disabled bool
  417. }
  418. func newProvisionerExtensionOption(typ Type, name, credentialID string, keyValuePairs ...string) *provisionerExtensionOption {
  419. return &provisionerExtensionOption{
  420. Extension: Extension{
  421. Type: typ,
  422. Name: name,
  423. CredentialID: credentialID,
  424. KeyValuePairs: keyValuePairs,
  425. },
  426. }
  427. }
  428. // WithControllerOptions updates the provisionerExtensionOption with options
  429. // from the controller. Currently only the DisableSmallstepExtensions
  430. // provisioner claim is used.
  431. func (o *provisionerExtensionOption) WithControllerOptions(c *Controller) *provisionerExtensionOption {
  432. o.Disabled = c.Claimer.IsDisableSmallstepExtensions()
  433. return o
  434. }
  435. func (o *provisionerExtensionOption) Modify(cert *x509.Certificate, _ SignOptions) error {
  436. if o.Disabled {
  437. return nil
  438. }
  439. ext, err := o.ToExtension()
  440. if err != nil {
  441. return errs.NewError(http.StatusInternalServerError, err, "error creating certificate")
  442. }
  443. // Replace or append the provisioner extension to avoid the inclusions of
  444. // malicious stepOIDProvisioner using templates.
  445. for i, e := range cert.ExtraExtensions {
  446. if e.Id.Equal(StepOIDProvisioner) {
  447. cert.ExtraExtensions[i] = ext
  448. return nil
  449. }
  450. }
  451. cert.ExtraExtensions = append(cert.ExtraExtensions, ext)
  452. return nil
  453. }
  454. // csrFingerprintValidator is a CertificateRequestValidator that checks the
  455. // fingerprint of the certificate request with the provided one.
  456. type csrFingerprintValidator string
  457. func (s csrFingerprintValidator) Valid(cr *x509.CertificateRequest) error {
  458. if s != "" {
  459. expected, err := base64.RawURLEncoding.DecodeString(string(s))
  460. if err != nil {
  461. return errs.ForbiddenErr(err, "error decoding fingerprint")
  462. }
  463. sum := sha256.Sum256(cr.Raw)
  464. if subtle.ConstantTimeCompare(expected, sum[:]) != 1 {
  465. return errs.Forbidden("certificate request fingerprint does not match %q", s)
  466. }
  467. }
  468. return nil
  469. }
  470. // SignCSROption is the interface used to collect extra options in the SignCSR
  471. // method of the SCEP authority.
  472. type SignCSROption any
  473. // TemplateDataModifier is an interface that allows to modify template data.
  474. type TemplateDataModifier interface {
  475. Modify(data x509util.TemplateData)
  476. }
  477. type templateDataModifier struct {
  478. fn func(x509util.TemplateData)
  479. }
  480. func (t *templateDataModifier) Modify(data x509util.TemplateData) {
  481. t.fn(data)
  482. }
  483. // TemplateDataModifierFunc returns a TemplateDataModifier with the given
  484. // function.
  485. func TemplateDataModifierFunc(fn func(data x509util.TemplateData)) TemplateDataModifier {
  486. return &templateDataModifier{
  487. fn: fn,
  488. }
  489. }