sign_options.go 10 KB

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