sign_options.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package provisioner
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "crypto/x509/pkix"
  7. "encoding/asn1"
  8. "net"
  9. "reflect"
  10. "time"
  11. "github.com/pkg/errors"
  12. "github.com/smallstep/cli/crypto/x509util"
  13. "golang.org/x/crypto/ed25519"
  14. )
  15. // Options contains the options that can be passed to the Sign method. Backdate
  16. // is automatically filled and can only be configured in the CA.
  17. type Options struct {
  18. NotAfter TimeDuration `json:"notAfter"`
  19. NotBefore TimeDuration `json:"notBefore"`
  20. Backdate time.Duration `json:"-"`
  21. }
  22. // SignOption is the interface used to collect all extra options used in the
  23. // Sign method.
  24. type SignOption interface{}
  25. // CertificateValidator is the interface used to validate a X.509 certificate.
  26. type CertificateValidator interface {
  27. SignOption
  28. Valid(cert *x509.Certificate, o Options) error
  29. }
  30. // CertificateRequestValidator is the interface used to validate a X.509
  31. // certificate request.
  32. type CertificateRequestValidator interface {
  33. SignOption
  34. Valid(req *x509.CertificateRequest) error
  35. }
  36. // ProfileModifier is the interface used to add custom options to the profile
  37. // constructor. The options are used to modify the final certificate.
  38. type ProfileModifier interface {
  39. SignOption
  40. Option(o Options) x509util.WithOption
  41. }
  42. // profileWithOption is a wrapper against x509util.WithOption to conform the
  43. // interface.
  44. type profileWithOption x509util.WithOption
  45. func (v profileWithOption) Option(Options) x509util.WithOption {
  46. return x509util.WithOption(v)
  47. }
  48. // emailOnlyIdentity is a CertificateRequestValidator that checks that the only
  49. // SAN provided is the given email address.
  50. type emailOnlyIdentity string
  51. func (e emailOnlyIdentity) Valid(req *x509.CertificateRequest) error {
  52. switch {
  53. case len(req.DNSNames) > 0:
  54. return errors.New("certificate request cannot contain DNS names")
  55. case len(req.IPAddresses) > 0:
  56. return errors.New("certificate request cannot contain IP addresses")
  57. case len(req.URIs) > 0:
  58. return errors.New("certificate request cannot contain URIs")
  59. case len(req.EmailAddresses) == 0:
  60. return errors.New("certificate request does not contain any email address")
  61. case len(req.EmailAddresses) > 1:
  62. return errors.New("certificate request contains too many email addresses")
  63. case req.EmailAddresses[0] == "":
  64. return errors.New("certificate request cannot contain an empty email address")
  65. case req.EmailAddresses[0] != string(e):
  66. return errors.Errorf("certificate request does not contain the valid email address, got %s, want %s", req.EmailAddresses[0], e)
  67. default:
  68. return nil
  69. }
  70. }
  71. // defaultPublicKeyValidator validates the public key of a certificate request.
  72. type defaultPublicKeyValidator struct{}
  73. // Valid checks that certificate request common name matches the one configured.
  74. func (v defaultPublicKeyValidator) Valid(req *x509.CertificateRequest) error {
  75. switch k := req.PublicKey.(type) {
  76. case *rsa.PublicKey:
  77. if k.Size() < 256 {
  78. return errors.New("rsa key in CSR must be at least 2048 bits (256 bytes)")
  79. }
  80. case *ecdsa.PublicKey, ed25519.PublicKey:
  81. default:
  82. return errors.Errorf("unrecognized public key of type '%T' in CSR", k)
  83. }
  84. return nil
  85. }
  86. // commonNameValidator validates the common name of a certificate request.
  87. type commonNameValidator string
  88. // Valid checks that certificate request common name matches the one configured.
  89. func (v commonNameValidator) Valid(req *x509.CertificateRequest) error {
  90. if req.Subject.CommonName == "" {
  91. return errors.New("certificate request cannot contain an empty common name")
  92. }
  93. if req.Subject.CommonName != string(v) {
  94. return errors.Errorf("certificate request does not contain the valid common name; requested common name = %s, token subject = %s", req.Subject.CommonName, v)
  95. }
  96. return nil
  97. }
  98. // commonNameSliceValidator validates thats the common name of a certificate request is present in the slice.
  99. type commonNameSliceValidator []string
  100. func (v commonNameSliceValidator) Valid(req *x509.CertificateRequest) error {
  101. if req.Subject.CommonName == "" {
  102. return errors.New("certificate request cannot contain an empty common name")
  103. }
  104. for _, cn := range v {
  105. if req.Subject.CommonName == cn {
  106. return nil
  107. }
  108. }
  109. return errors.Errorf("certificate request does not contain the valid common name, got %s, want %s", req.Subject.CommonName, v)
  110. }
  111. // dnsNamesValidator validates the DNS names SAN of a certificate request.
  112. type dnsNamesValidator []string
  113. // Valid checks that certificate request DNS Names match those configured in
  114. // the bootstrap (token) flow.
  115. func (v dnsNamesValidator) Valid(req *x509.CertificateRequest) error {
  116. want := make(map[string]bool)
  117. for _, s := range v {
  118. want[s] = true
  119. }
  120. got := make(map[string]bool)
  121. for _, s := range req.DNSNames {
  122. got[s] = true
  123. }
  124. if !reflect.DeepEqual(want, got) {
  125. return errors.Errorf("certificate request does not contain the valid DNS names - got %v, want %v", req.DNSNames, v)
  126. }
  127. return nil
  128. }
  129. // ipAddressesValidator validates the IP addresses SAN of a certificate request.
  130. type ipAddressesValidator []net.IP
  131. // Valid checks that certificate request IP Addresses match those configured in
  132. // the bootstrap (token) flow.
  133. func (v ipAddressesValidator) Valid(req *x509.CertificateRequest) error {
  134. want := make(map[string]bool)
  135. for _, ip := range v {
  136. want[ip.String()] = true
  137. }
  138. got := make(map[string]bool)
  139. for _, ip := range req.IPAddresses {
  140. got[ip.String()] = true
  141. }
  142. if !reflect.DeepEqual(want, got) {
  143. return errors.Errorf("IP Addresses claim failed - got %v, want %v", req.IPAddresses, v)
  144. }
  145. return nil
  146. }
  147. // emailAddressesValidator validates the email address SANs of a certificate request.
  148. type emailAddressesValidator []string
  149. // Valid checks that certificate request IP Addresses match those configured in
  150. // the bootstrap (token) flow.
  151. func (v emailAddressesValidator) Valid(req *x509.CertificateRequest) error {
  152. want := make(map[string]bool)
  153. for _, s := range v {
  154. want[s] = true
  155. }
  156. got := make(map[string]bool)
  157. for _, s := range req.EmailAddresses {
  158. got[s] = true
  159. }
  160. if !reflect.DeepEqual(want, got) {
  161. return errors.Errorf("certificate request does not contain the valid Email Addresses - got %v, want %v", req.EmailAddresses, v)
  162. }
  163. return nil
  164. }
  165. // profileDefaultDuration is a wrapper against x509util.WithOption to conform
  166. // the SignOption interface.
  167. type profileDefaultDuration time.Duration
  168. func (v profileDefaultDuration) Option(so Options) x509util.WithOption {
  169. var backdate time.Duration
  170. notBefore := so.NotBefore.Time()
  171. if notBefore.IsZero() {
  172. notBefore = now()
  173. backdate = -1 * so.Backdate
  174. }
  175. notAfter := so.NotAfter.RelativeTime(notBefore)
  176. return func(p x509util.Profile) error {
  177. fn := x509util.WithNotBeforeAfterDuration(notBefore, notAfter, time.Duration(v))
  178. if err := fn(p); err != nil {
  179. return err
  180. }
  181. crt := p.Subject()
  182. crt.NotBefore = crt.NotBefore.Add(backdate)
  183. return nil
  184. }
  185. }
  186. // profileLimitDuration is an x509 profile option that modifies an x509 validity
  187. // period according to an imposed expiration time.
  188. type profileLimitDuration struct {
  189. def time.Duration
  190. notAfter time.Time
  191. }
  192. // Option returns an x509util option that limits the validity period of a
  193. // certificate to one that is superficially imposed.
  194. func (v profileLimitDuration) Option(so Options) x509util.WithOption {
  195. return func(p x509util.Profile) error {
  196. var backdate time.Duration
  197. n := now()
  198. notBefore := so.NotBefore.Time()
  199. if notBefore.IsZero() {
  200. notBefore = n
  201. backdate = -1 * so.Backdate
  202. }
  203. if notBefore.After(v.notAfter) {
  204. return errors.Errorf("provisioning credential expiration (%s) is before "+
  205. "requested certificate notBefore (%s)", v.notAfter, notBefore)
  206. }
  207. notAfter := so.NotAfter.RelativeTime(notBefore)
  208. if notAfter.After(v.notAfter) {
  209. return errors.Errorf("provisioning credential expiration (%s) is before "+
  210. "requested certificate notAfter (%s)", v.notAfter, notBefore)
  211. }
  212. if notAfter.IsZero() {
  213. t := notBefore.Add(v.def)
  214. if t.After(v.notAfter) {
  215. notAfter = v.notAfter
  216. } else {
  217. notAfter = t
  218. }
  219. }
  220. crt := p.Subject()
  221. crt.NotBefore = notBefore.Add(backdate)
  222. crt.NotAfter = notAfter
  223. return nil
  224. }
  225. }
  226. // validityValidator validates the certificate validity settings.
  227. type validityValidator struct {
  228. min time.Duration
  229. max time.Duration
  230. }
  231. // newValidityValidator return a new validity validator.
  232. func newValidityValidator(min, max time.Duration) *validityValidator {
  233. return &validityValidator{min: min, max: max}
  234. }
  235. // Valid validates the certificate validity settings (notBefore/notAfter) and
  236. // and total duration.
  237. func (v *validityValidator) Valid(cert *x509.Certificate, o Options) error {
  238. var (
  239. na = cert.NotAfter.Truncate(time.Second)
  240. nb = cert.NotBefore.Truncate(time.Second)
  241. now = time.Now().Truncate(time.Second)
  242. )
  243. d := na.Sub(nb)
  244. if na.Before(now) {
  245. return errors.Errorf("notAfter cannot be in the past; na=%v", na)
  246. }
  247. if na.Before(nb) {
  248. return errors.Errorf("notAfter cannot be before notBefore; na=%v, nb=%v", na, nb)
  249. }
  250. if d < v.min {
  251. return errors.Errorf("requested duration of %v is less than the authorized minimum certificate duration of %v",
  252. d, v.min)
  253. }
  254. // NOTE: this check is not "technically correct". We're allowing the max
  255. // duration of a cert to be "max + backdate" and not all certificates will
  256. // be backdated (e.g. if a user passes the NotBefore value then we do not
  257. // apply a backdate). This is good enough.
  258. if d > v.max+o.Backdate {
  259. return errors.Errorf("requested duration of %v is more than the authorized maximum certificate duration of %v",
  260. d, v.max+o.Backdate)
  261. }
  262. return nil
  263. }
  264. var (
  265. stepOIDRoot = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64}
  266. stepOIDProvisioner = append(asn1.ObjectIdentifier(nil), append(stepOIDRoot, 1)...)
  267. )
  268. type stepProvisionerASN1 struct {
  269. Type int
  270. Name []byte
  271. CredentialID []byte
  272. KeyValuePairs []string `asn1:"optional,omitempty"`
  273. }
  274. type provisionerExtensionOption struct {
  275. Type int
  276. Name string
  277. CredentialID string
  278. KeyValuePairs []string
  279. }
  280. func newProvisionerExtensionOption(typ Type, name, credentialID string, keyValuePairs ...string) *provisionerExtensionOption {
  281. return &provisionerExtensionOption{
  282. Type: int(typ),
  283. Name: name,
  284. CredentialID: credentialID,
  285. KeyValuePairs: keyValuePairs,
  286. }
  287. }
  288. func (o *provisionerExtensionOption) Option(Options) x509util.WithOption {
  289. return func(p x509util.Profile) error {
  290. crt := p.Subject()
  291. ext, err := createProvisionerExtension(o.Type, o.Name, o.CredentialID, o.KeyValuePairs...)
  292. if err != nil {
  293. return err
  294. }
  295. crt.ExtraExtensions = append(crt.ExtraExtensions, ext)
  296. return nil
  297. }
  298. }
  299. func createProvisionerExtension(typ int, name, credentialID string, keyValuePairs ...string) (pkix.Extension, error) {
  300. b, err := asn1.Marshal(stepProvisionerASN1{
  301. Type: typ,
  302. Name: []byte(name),
  303. CredentialID: []byte(credentialID),
  304. KeyValuePairs: keyValuePairs,
  305. })
  306. if err != nil {
  307. return pkix.Extension{}, errors.Wrapf(err, "error marshaling provisioner extension")
  308. }
  309. return pkix.Extension{
  310. Id: stepOIDProvisioner,
  311. Critical: false,
  312. Value: b,
  313. }, nil
  314. }
  315. func init() {
  316. // Avoid dead-code warning in profileWithOption
  317. _ = profileWithOption(nil)
  318. }