sign_options.go 18 KB

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