sign_options.go 15 KB

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