sign_options.go 15 KB

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