sign_options.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. // profileDefaultDuration is a wrapper against x509util.WithOption to conform the
  47. // interface.
  48. type profileDefaultDuration time.Duration
  49. func (v profileDefaultDuration) Option(so Options) x509util.WithOption {
  50. notBefore := so.NotBefore.Time()
  51. if notBefore.IsZero() {
  52. notBefore = time.Now()
  53. }
  54. notAfter := so.NotAfter.RelativeTime(notBefore)
  55. return x509util.WithNotBeforeAfterDuration(notBefore, notAfter, time.Duration(v))
  56. }
  57. // emailOnlyIdentity is a CertificateRequestValidator that checks that the only
  58. // SAN provided is the given email address.
  59. type emailOnlyIdentity string
  60. func (e emailOnlyIdentity) Valid(req *x509.CertificateRequest) error {
  61. switch {
  62. case len(req.DNSNames) > 0:
  63. return errors.New("certificate request cannot contain DNS names")
  64. case len(req.IPAddresses) > 0:
  65. return errors.New("certificate request cannot contain IP addresses")
  66. case len(req.URIs) > 0:
  67. return errors.New("certificate request cannot contain URIs")
  68. case len(req.EmailAddresses) == 0:
  69. return errors.New("certificate request does not contain any email address")
  70. case len(req.EmailAddresses) > 1:
  71. return errors.New("certificate request contains too many email addresses")
  72. case req.EmailAddresses[0] == "":
  73. return errors.New("certificate request cannot contain an empty email address")
  74. case req.EmailAddresses[0] != string(e):
  75. return errors.Errorf("certificate request does not contain the valid email address, got %s, want %s", req.EmailAddresses[0], e)
  76. default:
  77. return nil
  78. }
  79. }
  80. // defaultPublicKeyValidator validates the public key of a certificate request.
  81. type defaultPublicKeyValidator struct{}
  82. // Valid checks that certificate request common name matches the one configured.
  83. func (v defaultPublicKeyValidator) Valid(req *x509.CertificateRequest) error {
  84. switch k := req.PublicKey.(type) {
  85. case *rsa.PublicKey:
  86. if k.Size() < 256 {
  87. return errors.New("rsa key in CSR must be at least 2048 bits (256 bytes)")
  88. }
  89. case *ecdsa.PublicKey, ed25519.PublicKey:
  90. default:
  91. return errors.Errorf("unrecognized public key of type '%T' in CSR", k)
  92. }
  93. return nil
  94. }
  95. // commonNameValidator validates the common name of a certificate request.
  96. type commonNameValidator string
  97. // Valid checks that certificate request common name matches the one configured.
  98. func (v commonNameValidator) Valid(req *x509.CertificateRequest) error {
  99. if req.Subject.CommonName == "" {
  100. return errors.New("certificate request cannot contain an empty common name")
  101. }
  102. if req.Subject.CommonName != string(v) {
  103. return errors.Errorf("certificate request does not contain the valid common name, got %s, want %s", req.Subject.CommonName, v)
  104. }
  105. return nil
  106. }
  107. // commonNameSliceValidator validates thats the common name of a certificate request is present in the slice.
  108. type commonNameSliceValidator []string
  109. func (v commonNameSliceValidator) Valid(req *x509.CertificateRequest) error {
  110. if req.Subject.CommonName == "" {
  111. return errors.New("certificate request cannot contain an empty common name")
  112. }
  113. for _, cn := range v {
  114. if req.Subject.CommonName == cn {
  115. return nil
  116. }
  117. }
  118. return errors.Errorf("certificate request does not contain the valid common name, got %s, want %s", req.Subject.CommonName, v)
  119. }
  120. // dnsNamesValidator validates the DNS names SAN of a certificate request.
  121. type dnsNamesValidator []string
  122. // Valid checks that certificate request DNS Names match those configured in
  123. // the bootstrap (token) flow.
  124. func (v dnsNamesValidator) Valid(req *x509.CertificateRequest) error {
  125. want := make(map[string]bool)
  126. for _, s := range v {
  127. want[s] = true
  128. }
  129. got := make(map[string]bool)
  130. for _, s := range req.DNSNames {
  131. got[s] = true
  132. }
  133. if !reflect.DeepEqual(want, got) {
  134. return errors.Errorf("certificate request does not contain the valid DNS names - got %v, want %v", req.DNSNames, v)
  135. }
  136. return nil
  137. }
  138. // ipAddressesValidator validates the IP addresses SAN of a certificate request.
  139. type ipAddressesValidator []net.IP
  140. // Valid checks that certificate request IP Addresses match those configured in
  141. // the bootstrap (token) flow.
  142. func (v ipAddressesValidator) Valid(req *x509.CertificateRequest) error {
  143. want := make(map[string]bool)
  144. for _, ip := range v {
  145. want[ip.String()] = true
  146. }
  147. got := make(map[string]bool)
  148. for _, ip := range req.IPAddresses {
  149. got[ip.String()] = true
  150. }
  151. if !reflect.DeepEqual(want, got) {
  152. return errors.Errorf("IP Addresses claim failed - got %v, want %v", req.IPAddresses, v)
  153. }
  154. return nil
  155. }
  156. // emailAddressesValidator validates the email address SANs of a certificate request.
  157. type emailAddressesValidator []string
  158. // Valid checks that certificate request IP Addresses match those configured in
  159. // the bootstrap (token) flow.
  160. func (v emailAddressesValidator) Valid(req *x509.CertificateRequest) error {
  161. want := make(map[string]bool)
  162. for _, s := range v {
  163. want[s] = true
  164. }
  165. got := make(map[string]bool)
  166. for _, s := range req.EmailAddresses {
  167. got[s] = true
  168. }
  169. if !reflect.DeepEqual(want, got) {
  170. return errors.Errorf("certificate request does not contain the valid Email Addresses - got %v, want %v", req.EmailAddresses, v)
  171. }
  172. return nil
  173. }
  174. // validityValidator validates the certificate temporal validity settings.
  175. type validityValidator struct {
  176. min time.Duration
  177. max time.Duration
  178. }
  179. // newValidityValidator return a new validity validator.
  180. func newValidityValidator(min, max time.Duration) *validityValidator {
  181. return &validityValidator{min: min, max: max}
  182. }
  183. // Validate validates the certificate temporal validity settings.
  184. func (v *validityValidator) Valid(crt *x509.Certificate) error {
  185. var (
  186. na = crt.NotAfter
  187. nb = crt.NotBefore
  188. d = na.Sub(nb)
  189. now = time.Now()
  190. )
  191. if na.Before(now) {
  192. return errors.Errorf("NotAfter: %v cannot be in the past", na)
  193. }
  194. if na.Before(nb) {
  195. return errors.Errorf("NotAfter: %v cannot be before NotBefore: %v", na, nb)
  196. }
  197. if d < v.min {
  198. return errors.Errorf("requested duration of %v is less than the authorized minimum certificate duration of %v",
  199. d, v.min)
  200. }
  201. if d > v.max {
  202. return errors.Errorf("requested duration of %v is more than the authorized maximum certificate duration of %v",
  203. d, v.max)
  204. }
  205. return nil
  206. }
  207. var (
  208. stepOIDRoot = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64}
  209. stepOIDProvisioner = append(asn1.ObjectIdentifier(nil), append(stepOIDRoot, 1)...)
  210. )
  211. type stepProvisionerASN1 struct {
  212. Type int
  213. Name []byte
  214. CredentialID []byte
  215. KeyValuePairs []string `asn1:"optional,omitempty"`
  216. }
  217. type provisionerExtensionOption struct {
  218. Type int
  219. Name string
  220. CredentialID string
  221. KeyValuePairs []string
  222. }
  223. func newProvisionerExtensionOption(typ Type, name, credentialID string, keyValuePairs ...string) *provisionerExtensionOption {
  224. return &provisionerExtensionOption{
  225. Type: int(typ),
  226. Name: name,
  227. CredentialID: credentialID,
  228. KeyValuePairs: keyValuePairs,
  229. }
  230. }
  231. func (o *provisionerExtensionOption) Option(Options) x509util.WithOption {
  232. return func(p x509util.Profile) error {
  233. crt := p.Subject()
  234. ext, err := createProvisionerExtension(o.Type, o.Name, o.CredentialID, o.KeyValuePairs...)
  235. if err != nil {
  236. return err
  237. }
  238. crt.ExtraExtensions = append(crt.ExtraExtensions, ext)
  239. return nil
  240. }
  241. }
  242. func createProvisionerExtension(typ int, name, credentialID string, keyValuePairs ...string) (pkix.Extension, error) {
  243. b, err := asn1.Marshal(stepProvisionerASN1{
  244. Type: typ,
  245. Name: []byte(name),
  246. CredentialID: []byte(credentialID),
  247. KeyValuePairs: keyValuePairs,
  248. })
  249. if err != nil {
  250. return pkix.Extension{}, errors.Wrapf(err, "error marshaling provisioner extension")
  251. }
  252. return pkix.Extension{
  253. Id: stepOIDProvisioner,
  254. Critical: false,
  255. Value: b,
  256. }, nil
  257. }
  258. func init() {
  259. // Avoid dead-code warning in profileWithOption
  260. _ = profileWithOption(nil)
  261. }