sign_options.go 15 KB

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