sign_options.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. // emailOnlyIdentity is a CertificateRequestValidator that checks that the only
  71. // SAN provided is the given email address.
  72. type emailOnlyIdentity string
  73. func (e emailOnlyIdentity) Valid(req *x509.CertificateRequest) error {
  74. switch {
  75. case len(req.DNSNames) > 0:
  76. return errs.Forbidden("certificate request cannot contain DNS names")
  77. case len(req.IPAddresses) > 0:
  78. return errs.Forbidden("certificate request cannot contain IP addresses")
  79. case len(req.URIs) > 0:
  80. return errs.Forbidden("certificate request cannot contain URIs")
  81. case len(req.EmailAddresses) == 0:
  82. return errs.Forbidden("certificate request does not contain any email address")
  83. case len(req.EmailAddresses) > 1:
  84. return errs.Forbidden("certificate request contains too many email addresses")
  85. case req.EmailAddresses[0] == "":
  86. return errs.Forbidden("certificate request cannot contain an empty email address")
  87. case req.EmailAddresses[0] != string(e):
  88. return errs.Forbidden("certificate request does not contain the valid email address - got %s, want %s", req.EmailAddresses[0], e)
  89. default:
  90. return nil
  91. }
  92. }
  93. // defaultPublicKeyValidator validates the public key of a certificate request.
  94. type defaultPublicKeyValidator struct{}
  95. // Valid checks that certificate request common name matches the one configured.
  96. func (v defaultPublicKeyValidator) Valid(req *x509.CertificateRequest) error {
  97. switch k := req.PublicKey.(type) {
  98. case *rsa.PublicKey:
  99. if k.Size() < keyutil.MinRSAKeyBytes {
  100. return errs.Forbidden("certificate request RSA key must be at least %d bits (%d bytes)",
  101. 8*keyutil.MinRSAKeyBytes, keyutil.MinRSAKeyBytes)
  102. }
  103. case *ecdsa.PublicKey, ed25519.PublicKey:
  104. default:
  105. return errs.BadRequest("certificate request key of type '%T' is not supported", k)
  106. }
  107. return nil
  108. }
  109. // publicKeyMinimumLengthValidator validates the length (in bits) of the public key
  110. // of a certificate request is at least a certain length
  111. type publicKeyMinimumLengthValidator struct {
  112. length int
  113. }
  114. // newPublicKeyMinimumLengthValidator creates a new publicKeyMinimumLengthValidator
  115. // with the given length as its minimum value
  116. // TODO: change the defaultPublicKeyValidator to have a configurable length instead?
  117. func newPublicKeyMinimumLengthValidator(length int) publicKeyMinimumLengthValidator {
  118. return publicKeyMinimumLengthValidator{
  119. length: length,
  120. }
  121. }
  122. // Valid checks that certificate request common name matches the one configured.
  123. func (v publicKeyMinimumLengthValidator) Valid(req *x509.CertificateRequest) error {
  124. switch k := req.PublicKey.(type) {
  125. case *rsa.PublicKey:
  126. minimumLengthInBytes := v.length / 8
  127. if k.Size() < minimumLengthInBytes {
  128. return errs.Forbidden("certificate request RSA key must be at least %d bits (%d bytes)",
  129. v.length, minimumLengthInBytes)
  130. }
  131. case *ecdsa.PublicKey, ed25519.PublicKey:
  132. default:
  133. return errs.BadRequest("certificate request key of type '%T' is not supported", k)
  134. }
  135. return nil
  136. }
  137. // commonNameValidator validates the common name of a certificate request.
  138. type commonNameValidator string
  139. // Valid checks that certificate request common name matches the one configured.
  140. // An empty common name is considered valid.
  141. func (v commonNameValidator) Valid(req *x509.CertificateRequest) error {
  142. if req.Subject.CommonName == "" {
  143. return nil
  144. }
  145. if req.Subject.CommonName != string(v) {
  146. return errs.Forbidden("certificate request does not contain the valid common name - got %s, want %s", req.Subject.CommonName, v)
  147. }
  148. return nil
  149. }
  150. // commonNameSliceValidator validates thats the common name of a certificate
  151. // request is present in the slice. An empty common name is considered valid.
  152. type commonNameSliceValidator []string
  153. func (v commonNameSliceValidator) Valid(req *x509.CertificateRequest) error {
  154. if req.Subject.CommonName == "" {
  155. return nil
  156. }
  157. for _, cn := range v {
  158. if req.Subject.CommonName == cn {
  159. return nil
  160. }
  161. }
  162. return errs.Forbidden("certificate request does not contain the valid common name - got %s, want %s", req.Subject.CommonName, v)
  163. }
  164. // dnsNamesValidator validates the DNS names SAN of a certificate request.
  165. type dnsNamesValidator []string
  166. // Valid checks that certificate request DNS Names match those configured in
  167. // the bootstrap (token) flow.
  168. func (v dnsNamesValidator) Valid(req *x509.CertificateRequest) error {
  169. if len(req.DNSNames) == 0 {
  170. return nil
  171. }
  172. want := make(map[string]bool)
  173. for _, s := range v {
  174. want[s] = true
  175. }
  176. got := make(map[string]bool)
  177. for _, s := range req.DNSNames {
  178. got[s] = true
  179. }
  180. if !reflect.DeepEqual(want, got) {
  181. return errs.Forbidden("certificate request does not contain the valid DNS names - got %v, want %v", req.DNSNames, v)
  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 []*url.URL
  229. // Valid checks that certificate request IP Addresses match those configured in
  230. // the bootstrap (token) flow.
  231. func (v urisValidator) Valid(req *x509.CertificateRequest) error {
  232. if len(req.URIs) == 0 {
  233. return nil
  234. }
  235. want := make(map[string]bool)
  236. for _, u := range v {
  237. want[u.String()] = true
  238. }
  239. got := make(map[string]bool)
  240. for _, u := range req.URIs {
  241. got[u.String()] = true
  242. }
  243. if !reflect.DeepEqual(want, got) {
  244. return errs.Forbidden("certificate request does not contain the valid URIs - got %v, want %v", req.URIs, v)
  245. }
  246. return nil
  247. }
  248. // defaultsSANsValidator stores a set of SANs to eventually validate 1:1 against
  249. // the SANs in an x509 certificate request.
  250. type defaultSANsValidator []string
  251. // Valid verifies that the SANs stored in the validator match 1:1 with those
  252. // requested in the x509 certificate request.
  253. func (v defaultSANsValidator) Valid(req *x509.CertificateRequest) (err error) {
  254. dnsNames, ips, emails, uris := x509util.SplitSANs(v)
  255. if err = dnsNamesValidator(dnsNames).Valid(req); err != nil {
  256. return
  257. } else if err = emailAddressesValidator(emails).Valid(req); err != nil {
  258. return
  259. } else if err = ipAddressesValidator(ips).Valid(req); err != nil {
  260. return
  261. } else if err = urisValidator(uris).Valid(req); err != nil {
  262. return
  263. }
  264. return
  265. }
  266. // profileDefaultDuration is a modifier that sets the certificate
  267. // duration.
  268. type profileDefaultDuration time.Duration
  269. func (v profileDefaultDuration) Modify(cert *x509.Certificate, so SignOptions) error {
  270. var backdate time.Duration
  271. notBefore := so.NotBefore.Time()
  272. if notBefore.IsZero() {
  273. notBefore = now()
  274. backdate = -1 * so.Backdate
  275. }
  276. notAfter := so.NotAfter.RelativeTime(notBefore)
  277. if notAfter.IsZero() {
  278. if v != 0 {
  279. notAfter = notBefore.Add(time.Duration(v))
  280. } else {
  281. notAfter = notBefore.Add(DefaultCertValidity)
  282. }
  283. }
  284. cert.NotBefore = notBefore.Add(backdate)
  285. cert.NotAfter = notAfter
  286. return nil
  287. }
  288. // profileLimitDuration is an x509 profile option that modifies an x509 validity
  289. // period according to an imposed expiration time.
  290. type profileLimitDuration struct {
  291. def time.Duration
  292. notBefore, notAfter time.Time
  293. }
  294. // Option returns an x509util option that limits the validity period of a
  295. // certificate to one that is superficially imposed.
  296. func (v profileLimitDuration) Modify(cert *x509.Certificate, so SignOptions) error {
  297. var backdate time.Duration
  298. notBefore := so.NotBefore.Time()
  299. if notBefore.IsZero() {
  300. notBefore = now()
  301. backdate = -1 * so.Backdate
  302. }
  303. if notBefore.Before(v.notBefore) {
  304. return errs.Forbidden(
  305. "requested certificate notBefore (%s) is before the active validity window of the provisioning credential (%s)",
  306. notBefore, v.notBefore)
  307. }
  308. notAfter := so.NotAfter.RelativeTime(notBefore)
  309. if notAfter.After(v.notAfter) {
  310. return errs.Forbidden(
  311. "requested certificate notAfter (%s) is after the expiration of the provisioning credential (%s)",
  312. notAfter, v.notAfter)
  313. }
  314. if notAfter.IsZero() {
  315. t := notBefore.Add(v.def)
  316. if t.After(v.notAfter) {
  317. notAfter = v.notAfter
  318. } else {
  319. notAfter = t
  320. }
  321. }
  322. cert.NotBefore = notBefore.Add(backdate)
  323. cert.NotAfter = notAfter
  324. return nil
  325. }
  326. // validityValidator validates the certificate validity settings.
  327. type validityValidator struct {
  328. min time.Duration
  329. max time.Duration
  330. }
  331. // newValidityValidator return a new validity validator.
  332. func newValidityValidator(min, max time.Duration) *validityValidator {
  333. return &validityValidator{min: min, max: max}
  334. }
  335. // Valid validates the certificate validity settings (notBefore/notAfter) and
  336. // total duration.
  337. func (v *validityValidator) Valid(cert *x509.Certificate, o SignOptions) error {
  338. var (
  339. na = cert.NotAfter.Truncate(time.Second)
  340. nb = cert.NotBefore.Truncate(time.Second)
  341. now = time.Now().Truncate(time.Second)
  342. )
  343. d := na.Sub(nb)
  344. if na.Before(now) {
  345. return errs.BadRequest("notAfter cannot be in the past; na=%v", na)
  346. }
  347. if na.Before(nb) {
  348. return errs.BadRequest("notAfter cannot be before notBefore; na=%v, nb=%v", na, nb)
  349. }
  350. if d < v.min {
  351. return errs.Forbidden("requested duration of %v is less than the authorized minimum certificate duration of %v", d, v.min)
  352. }
  353. // NOTE: this check is not "technically correct". We're allowing the max
  354. // duration of a cert to be "max + backdate" and not all certificates will
  355. // be backdated (e.g. if a user passes the NotBefore value then we do not
  356. // apply a backdate). This is good enough.
  357. if d > v.max+o.Backdate {
  358. return errs.Forbidden("requested duration of %v is more than the authorized maximum certificate duration of %v", d, v.max+o.Backdate)
  359. }
  360. return nil
  361. }
  362. // x509NamePolicyValidator validates that the certificate (to be signed)
  363. // contains only allowed SANs.
  364. type x509NamePolicyValidator struct {
  365. policyEngine policy.X509Policy
  366. }
  367. // newX509NamePolicyValidator return a new SANs allow/deny validator.
  368. func newX509NamePolicyValidator(engine policy.X509Policy) *x509NamePolicyValidator {
  369. return &x509NamePolicyValidator{
  370. policyEngine: engine,
  371. }
  372. }
  373. // Valid validates that the certificate (to be signed) contains only allowed SANs.
  374. func (v *x509NamePolicyValidator) Valid(cert *x509.Certificate, _ SignOptions) error {
  375. if v.policyEngine == nil {
  376. return nil
  377. }
  378. return v.policyEngine.IsX509CertificateAllowed(cert)
  379. }
  380. type forceCNOption struct {
  381. ForceCN bool
  382. }
  383. func newForceCNOption(forceCN bool) *forceCNOption {
  384. return &forceCNOption{forceCN}
  385. }
  386. func (o *forceCNOption) Modify(cert *x509.Certificate, _ SignOptions) error {
  387. if !o.ForceCN {
  388. return nil
  389. }
  390. // Force the common name to be the first DNS if not provided.
  391. if cert.Subject.CommonName == "" {
  392. if len(cert.DNSNames) == 0 {
  393. return errs.BadRequest("cannot force common name, DNS names is empty")
  394. }
  395. cert.Subject.CommonName = cert.DNSNames[0]
  396. }
  397. return nil
  398. }
  399. type provisionerExtensionOption struct {
  400. Extension
  401. }
  402. func newProvisionerExtensionOption(typ Type, name, credentialID string, keyValuePairs ...string) *provisionerExtensionOption {
  403. return &provisionerExtensionOption{
  404. Extension: Extension{
  405. Type: typ,
  406. Name: name,
  407. CredentialID: credentialID,
  408. KeyValuePairs: keyValuePairs,
  409. },
  410. }
  411. }
  412. func (o *provisionerExtensionOption) Modify(cert *x509.Certificate, _ SignOptions) error {
  413. ext, err := o.ToExtension()
  414. if err != nil {
  415. return errs.NewError(http.StatusInternalServerError, err, "error creating certificate")
  416. }
  417. // Replace or append the provisioner extension to avoid the inclusions of
  418. // malicious stepOIDProvisioner using templates.
  419. for i, e := range cert.ExtraExtensions {
  420. if e.Id.Equal(StepOIDProvisioner) {
  421. cert.ExtraExtensions[i] = ext
  422. return nil
  423. }
  424. }
  425. cert.ExtraExtensions = append(cert.ExtraExtensions, ext)
  426. return nil
  427. }