sign_options.go 16 KB

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