sign_options.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. // commonNameValidator validates the common name of a certificate request.
  103. type commonNameValidator string
  104. // Valid checks that certificate request common name matches the one configured.
  105. // An empty common name is considered valid.
  106. func (v commonNameValidator) Valid(req *x509.CertificateRequest) error {
  107. if req.Subject.CommonName == "" {
  108. return nil
  109. }
  110. if req.Subject.CommonName != string(v) {
  111. return errors.Errorf("certificate request does not contain the valid common name; requested common name = %s, token subject = %s", req.Subject.CommonName, v)
  112. }
  113. return nil
  114. }
  115. // commonNameSliceValidator validates thats the common name of a certificate
  116. // request is present in the slice. An empty common name is considered valid.
  117. type commonNameSliceValidator []string
  118. func (v commonNameSliceValidator) Valid(req *x509.CertificateRequest) error {
  119. if req.Subject.CommonName == "" {
  120. return nil
  121. }
  122. for _, cn := range v {
  123. if req.Subject.CommonName == cn {
  124. return nil
  125. }
  126. }
  127. return errors.Errorf("certificate request does not contain the valid common name, got %s, want %s", req.Subject.CommonName, v)
  128. }
  129. // dnsNamesValidator validates the DNS names SAN of a certificate request.
  130. type dnsNamesValidator []string
  131. // Valid checks that certificate request DNS Names match those configured in
  132. // the bootstrap (token) flow.
  133. func (v dnsNamesValidator) Valid(req *x509.CertificateRequest) error {
  134. if len(req.DNSNames) == 0 {
  135. return nil
  136. }
  137. want := make(map[string]bool)
  138. for _, s := range v {
  139. want[s] = true
  140. }
  141. got := make(map[string]bool)
  142. for _, s := range req.DNSNames {
  143. got[s] = true
  144. }
  145. if !reflect.DeepEqual(want, got) {
  146. return errors.Errorf("certificate request does not contain the valid DNS names - got %v, want %v", req.DNSNames, v)
  147. }
  148. return nil
  149. }
  150. // ipAddressesValidator validates the IP addresses SAN of a certificate request.
  151. type ipAddressesValidator []net.IP
  152. // Valid checks that certificate request IP Addresses match those configured in
  153. // the bootstrap (token) flow.
  154. func (v ipAddressesValidator) Valid(req *x509.CertificateRequest) error {
  155. if len(req.IPAddresses) == 0 {
  156. return nil
  157. }
  158. want := make(map[string]bool)
  159. for _, ip := range v {
  160. want[ip.String()] = true
  161. }
  162. got := make(map[string]bool)
  163. for _, ip := range req.IPAddresses {
  164. got[ip.String()] = true
  165. }
  166. if !reflect.DeepEqual(want, got) {
  167. return errors.Errorf("IP Addresses claim failed - got %v, want %v", req.IPAddresses, v)
  168. }
  169. return nil
  170. }
  171. // emailAddressesValidator validates the email address SANs of a certificate request.
  172. type emailAddressesValidator []string
  173. // Valid checks that certificate request IP Addresses match those configured in
  174. // the bootstrap (token) flow.
  175. func (v emailAddressesValidator) Valid(req *x509.CertificateRequest) error {
  176. if len(req.EmailAddresses) == 0 {
  177. return nil
  178. }
  179. want := make(map[string]bool)
  180. for _, s := range v {
  181. want[s] = true
  182. }
  183. got := make(map[string]bool)
  184. for _, s := range req.EmailAddresses {
  185. got[s] = true
  186. }
  187. if !reflect.DeepEqual(want, got) {
  188. return errors.Errorf("certificate request does not contain the valid Email Addresses - got %v, want %v", req.EmailAddresses, v)
  189. }
  190. return nil
  191. }
  192. // urisValidator validates the URI SANs of a certificate request.
  193. type urisValidator []*url.URL
  194. // Valid checks that certificate request IP Addresses match those configured in
  195. // the bootstrap (token) flow.
  196. func (v urisValidator) Valid(req *x509.CertificateRequest) error {
  197. if len(req.URIs) == 0 {
  198. return nil
  199. }
  200. want := make(map[string]bool)
  201. for _, u := range v {
  202. want[u.String()] = true
  203. }
  204. got := make(map[string]bool)
  205. for _, u := range req.URIs {
  206. got[u.String()] = true
  207. }
  208. if !reflect.DeepEqual(want, got) {
  209. return errors.Errorf("URIs claim failed - got %v, want %v", req.URIs, v)
  210. }
  211. return nil
  212. }
  213. // defaultsSANsValidator stores a set of SANs to eventually validate 1:1 against
  214. // the SANs in an x509 certificate request.
  215. type defaultSANsValidator []string
  216. // Valid verifies that the SANs stored in the validator match 1:1 with those
  217. // requested in the x509 certificate request.
  218. func (v defaultSANsValidator) Valid(req *x509.CertificateRequest) (err error) {
  219. dnsNames, ips, emails, uris := x509util.SplitSANs(v)
  220. if err = dnsNamesValidator(dnsNames).Valid(req); err != nil {
  221. return
  222. } else if err = emailAddressesValidator(emails).Valid(req); err != nil {
  223. return
  224. } else if err = ipAddressesValidator(ips).Valid(req); err != nil {
  225. return
  226. } else if err = urisValidator(uris).Valid(req); err != nil {
  227. return
  228. }
  229. return
  230. }
  231. // profileDefaultDuration is a modifier that sets the certificate
  232. // duration.
  233. type profileDefaultDuration time.Duration
  234. func (v profileDefaultDuration) Modify(cert *x509.Certificate, so SignOptions) error {
  235. var backdate time.Duration
  236. notBefore := so.NotBefore.Time()
  237. if notBefore.IsZero() {
  238. notBefore = now()
  239. backdate = -1 * so.Backdate
  240. }
  241. notAfter := so.NotAfter.RelativeTime(notBefore)
  242. if notAfter.IsZero() {
  243. if v != 0 {
  244. notAfter = notBefore.Add(time.Duration(v))
  245. } else {
  246. notAfter = notBefore.Add(DefaultCertValidity)
  247. }
  248. }
  249. cert.NotBefore = notBefore.Add(backdate)
  250. cert.NotAfter = notAfter
  251. return nil
  252. }
  253. // profileLimitDuration is an x509 profile option that modifies an x509 validity
  254. // period according to an imposed expiration time.
  255. type profileLimitDuration struct {
  256. def time.Duration
  257. notBefore, notAfter time.Time
  258. }
  259. // Option returns an x509util option that limits the validity period of a
  260. // certificate to one that is superficially imposed.
  261. func (v profileLimitDuration) 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. if notBefore.Before(v.notBefore) {
  269. return errors.Errorf("requested certificate notBefore (%s) is before "+
  270. "the active validity window of the provisioning credential (%s)",
  271. notBefore, v.notBefore)
  272. }
  273. notAfter := so.NotAfter.RelativeTime(notBefore)
  274. if notAfter.After(v.notAfter) {
  275. return errors.Errorf("requested certificate notAfter (%s) is after "+
  276. "the expiration of the provisioning credential (%s)",
  277. notAfter, v.notAfter)
  278. }
  279. if notAfter.IsZero() {
  280. t := notBefore.Add(v.def)
  281. if t.After(v.notAfter) {
  282. notAfter = v.notAfter
  283. } else {
  284. notAfter = t
  285. }
  286. }
  287. cert.NotBefore = notBefore.Add(backdate)
  288. cert.NotAfter = notAfter
  289. return nil
  290. }
  291. // validityValidator validates the certificate validity settings.
  292. type validityValidator struct {
  293. min time.Duration
  294. max time.Duration
  295. }
  296. // newValidityValidator return a new validity validator.
  297. func newValidityValidator(min, max time.Duration) *validityValidator {
  298. return &validityValidator{min: min, max: max}
  299. }
  300. // Valid validates the certificate validity settings (notBefore/notAfter) and
  301. // and total duration.
  302. func (v *validityValidator) Valid(cert *x509.Certificate, o SignOptions) error {
  303. var (
  304. na = cert.NotAfter.Truncate(time.Second)
  305. nb = cert.NotBefore.Truncate(time.Second)
  306. now = time.Now().Truncate(time.Second)
  307. )
  308. d := na.Sub(nb)
  309. if na.Before(now) {
  310. return errors.Errorf("notAfter cannot be in the past; na=%v", na)
  311. }
  312. if na.Before(nb) {
  313. return errors.Errorf("notAfter cannot be before notBefore; na=%v, nb=%v", na, nb)
  314. }
  315. if d < v.min {
  316. return errors.Errorf("requested duration of %v is less than the authorized minimum certificate duration of %v",
  317. d, v.min)
  318. }
  319. // NOTE: this check is not "technically correct". We're allowing the max
  320. // duration of a cert to be "max + backdate" and not all certificates will
  321. // be backdated (e.g. if a user passes the NotBefore value then we do not
  322. // apply a backdate). This is good enough.
  323. if d > v.max+o.Backdate {
  324. return errors.Errorf("requested duration of %v is more than the authorized maximum certificate duration of %v",
  325. d, v.max+o.Backdate)
  326. }
  327. return nil
  328. }
  329. var (
  330. stepOIDRoot = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64}
  331. stepOIDProvisioner = append(asn1.ObjectIdentifier(nil), append(stepOIDRoot, 1)...)
  332. )
  333. type stepProvisionerASN1 struct {
  334. Type int
  335. Name []byte
  336. CredentialID []byte
  337. KeyValuePairs []string `asn1:"optional,omitempty"`
  338. }
  339. type forceCNOption struct {
  340. ForceCN bool
  341. }
  342. func newForceCNOption(forceCN bool) *forceCNOption {
  343. return &forceCNOption{forceCN}
  344. }
  345. func (o *forceCNOption) Modify(cert *x509.Certificate, _ SignOptions) error {
  346. if !o.ForceCN {
  347. // Forcing CN is disabled, do nothing to certificate
  348. return nil
  349. }
  350. if cert.Subject.CommonName == "" {
  351. if len(cert.DNSNames) > 0 {
  352. cert.Subject.CommonName = cert.DNSNames[0]
  353. } else {
  354. return errors.New("Cannot force CN, DNSNames is empty")
  355. }
  356. }
  357. return nil
  358. }
  359. type provisionerExtensionOption struct {
  360. Type int
  361. Name string
  362. CredentialID string
  363. KeyValuePairs []string
  364. }
  365. func newProvisionerExtensionOption(typ Type, name, credentialID string, keyValuePairs ...string) *provisionerExtensionOption {
  366. return &provisionerExtensionOption{
  367. Type: int(typ),
  368. Name: name,
  369. CredentialID: credentialID,
  370. KeyValuePairs: keyValuePairs,
  371. }
  372. }
  373. func (o *provisionerExtensionOption) Modify(cert *x509.Certificate, _ SignOptions) error {
  374. ext, err := createProvisionerExtension(o.Type, o.Name, o.CredentialID, o.KeyValuePairs...)
  375. if err != nil {
  376. return err
  377. }
  378. // Prepend the provisioner extension. In the auth.Sign code we will
  379. // force the resulting certificate to only have one extension, the
  380. // first stepOIDProvisioner that is found in the ExtraExtensions.
  381. // A client could pass a csr containing a malicious stepOIDProvisioner
  382. // ExtraExtension. If we were to append (rather than prepend) the correct
  383. // stepOIDProvisioner extension, then the resulting certificate would
  384. // contain the malicious extension, rather than the one applied by step-ca.
  385. cert.ExtraExtensions = append([]pkix.Extension{ext}, cert.ExtraExtensions...)
  386. return nil
  387. }
  388. func createProvisionerExtension(typ int, name, credentialID string, keyValuePairs ...string) (pkix.Extension, error) {
  389. b, err := asn1.Marshal(stepProvisionerASN1{
  390. Type: typ,
  391. Name: []byte(name),
  392. CredentialID: []byte(credentialID),
  393. KeyValuePairs: keyValuePairs,
  394. })
  395. if err != nil {
  396. return pkix.Extension{}, errors.Wrapf(err, "error marshaling provisioner extension")
  397. }
  398. return pkix.Extension{
  399. Id: stepOIDProvisioner,
  400. Critical: false,
  401. Value: b,
  402. }, nil
  403. }