sign_options.go 15 KB

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