x5c.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "net/http"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/linkedca"
  10. "go.step.sm/crypto/jose"
  11. "go.step.sm/crypto/sshutil"
  12. "go.step.sm/crypto/x509util"
  13. "github.com/smallstep/certificates/errs"
  14. "github.com/smallstep/certificates/internal/cast"
  15. "github.com/smallstep/certificates/webhook"
  16. )
  17. // x5cPayload extends jwt.Claims with step attributes.
  18. type x5cPayload struct {
  19. jose.Claims
  20. SANs []string `json:"sans,omitempty"`
  21. Step *stepPayload `json:"step,omitempty"`
  22. Confirmation *cnfPayload `json:"cnf,omitempty"`
  23. chains [][]*x509.Certificate
  24. }
  25. // X5C is the default provisioner, an entity that can sign tokens necessary for
  26. // signature requests.
  27. type X5C struct {
  28. *base
  29. ID string `json:"-"`
  30. Type string `json:"type"`
  31. Name string `json:"name"`
  32. Roots []byte `json:"roots"`
  33. Claims *Claims `json:"claims,omitempty"`
  34. Options *Options `json:"options,omitempty"`
  35. ctl *Controller
  36. rootPool *x509.CertPool
  37. }
  38. // GetID returns the provisioner unique identifier. The name and credential id
  39. // should uniquely identify any X5C provisioner.
  40. func (p *X5C) GetID() string {
  41. if p.ID != "" {
  42. return p.ID
  43. }
  44. return p.GetIDForToken()
  45. }
  46. // GetIDForToken returns an identifier that will be used to load the provisioner
  47. // from a token.
  48. func (p *X5C) GetIDForToken() string {
  49. return "x5c/" + p.Name
  50. }
  51. // GetTokenID returns the identifier of the token.
  52. func (p *X5C) GetTokenID(ott string) (string, error) {
  53. // Validate payload
  54. token, err := jose.ParseSigned(ott)
  55. if err != nil {
  56. return "", errors.Wrap(err, "error parsing token")
  57. }
  58. // Get claims w/out verification. We need to look up the provisioner
  59. // key in order to verify the claims and we need the issuer from the claims
  60. // before we can look up the provisioner.
  61. var claims jose.Claims
  62. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  63. return "", errors.Wrap(err, "error verifying claims")
  64. }
  65. return claims.ID, nil
  66. }
  67. // GetName returns the name of the provisioner.
  68. func (p *X5C) GetName() string {
  69. return p.Name
  70. }
  71. // GetType returns the type of provisioner.
  72. func (p *X5C) GetType() Type {
  73. return TypeX5C
  74. }
  75. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  76. func (p *X5C) GetEncryptedKey() (string, string, bool) {
  77. return "", "", false
  78. }
  79. // Init initializes and validates the fields of a X5C type.
  80. func (p *X5C) Init(config Config) (err error) {
  81. switch {
  82. case p.Type == "":
  83. return errors.New("provisioner type cannot be empty")
  84. case p.Name == "":
  85. return errors.New("provisioner name cannot be empty")
  86. case len(p.Roots) == 0:
  87. return errors.New("provisioner root(s) cannot be empty")
  88. }
  89. p.rootPool = x509.NewCertPool()
  90. var (
  91. block *pem.Block
  92. rest = p.Roots
  93. count int
  94. )
  95. for rest != nil {
  96. block, rest = pem.Decode(rest)
  97. if block == nil {
  98. break
  99. }
  100. cert, err := x509.ParseCertificate(block.Bytes)
  101. if err != nil {
  102. return errors.Wrap(err, "error parsing x509 certificate from PEM block")
  103. }
  104. count++
  105. p.rootPool.AddCert(cert)
  106. }
  107. // Verify that at least one root was found.
  108. if count == 0 {
  109. return errors.Errorf("no x509 certificates found in roots attribute for provisioner '%s'", p.GetName())
  110. }
  111. config.Audiences = config.Audiences.WithFragment(p.GetIDForToken())
  112. p.ctl, err = NewController(p, p.Claims, config, p.Options)
  113. return
  114. }
  115. // authorizeToken performs common jwt authorization actions and returns the
  116. // claims for case specific downstream parsing.
  117. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  118. func (p *X5C) authorizeToken(token string, audiences []string) (*x5cPayload, error) {
  119. jwt, err := jose.ParseSigned(token)
  120. if err != nil {
  121. return nil, errs.Wrap(http.StatusUnauthorized, err, "x5c.authorizeToken; error parsing x5c token")
  122. }
  123. verifiedChains, err := jwt.Headers[0].Certificates(x509.VerifyOptions{
  124. Roots: p.rootPool,
  125. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  126. })
  127. if err != nil {
  128. return nil, errs.Wrap(http.StatusUnauthorized, err,
  129. "x5c.authorizeToken; error verifying x5c certificate chain in token")
  130. }
  131. leaf := verifiedChains[0][0]
  132. if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {
  133. return nil, errs.Unauthorized("x5c.authorizeToken; certificate used to sign x5c token cannot be used for digital signature")
  134. }
  135. // Using the leaf certificate's key to validate the claims accomplishes two
  136. // things:
  137. // 1. Asserts that the private key used to sign the token corresponds
  138. // to the public certificate in the `x5c` header of the token.
  139. // 2. Asserts that the claims are valid - have not been tampered with.
  140. var claims x5cPayload
  141. if err = jwt.Claims(leaf.PublicKey, &claims); err != nil {
  142. return nil, errs.Wrap(http.StatusUnauthorized, err, "x5c.authorizeToken; error parsing x5c claims")
  143. }
  144. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  145. // more than a few minutes.
  146. if err = claims.ValidateWithLeeway(jose.Expected{
  147. Issuer: p.Name,
  148. Time: time.Now().UTC(),
  149. }, time.Minute); err != nil {
  150. return nil, errs.Wrapf(http.StatusUnauthorized, err, "x5c.authorizeToken; invalid x5c claims")
  151. }
  152. // validate audiences with the defaults
  153. if !matchesAudience(claims.Audience, audiences) {
  154. return nil, errs.Unauthorized("x5c.authorizeToken; x5c token has invalid audience "+
  155. "claim (aud); expected %s, but got %s", audiences, claims.Audience)
  156. }
  157. if claims.Subject == "" {
  158. return nil, errs.Unauthorized("x5c.authorizeToken; x5c token subject cannot be empty")
  159. }
  160. // Save the verified chains on the x5c payload object.
  161. claims.chains = verifiedChains
  162. return &claims, nil
  163. }
  164. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  165. // revoke the certificate with serial number in the `sub` property.
  166. func (p *X5C) AuthorizeRevoke(_ context.Context, token string) error {
  167. _, err := p.authorizeToken(token, p.ctl.Audiences.Revoke)
  168. return errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeRevoke")
  169. }
  170. // AuthorizeSign validates the given token.
  171. func (p *X5C) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  172. claims, err := p.authorizeToken(token, p.ctl.Audiences.Sign)
  173. if err != nil {
  174. return nil, errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeSign")
  175. }
  176. // NOTE: This is for backwards compatibility with older versions of cli
  177. // and certificates. Older versions added the token subject as the only SAN
  178. // in a CSR by default.
  179. if len(claims.SANs) == 0 {
  180. claims.SANs = []string{claims.Subject}
  181. }
  182. // Certificate templates
  183. data := x509util.CreateTemplateData(claims.Subject, claims.SANs)
  184. if v, err := unsafeParseSigned(token); err == nil {
  185. data.SetToken(v)
  186. }
  187. // The X509 certificate will be available using the template variable
  188. // AuthorizationCrt. For example {{ .AuthorizationCrt.DNSNames }} can be
  189. // used to get all the domains.
  190. x5cLeaf := claims.chains[0][0]
  191. data.SetAuthorizationCertificate(x5cLeaf)
  192. templateOptions, err := TemplateOptions(p.Options, data)
  193. if err != nil {
  194. return nil, errs.Wrap(http.StatusInternalServerError, err, "jwk.AuthorizeSign")
  195. }
  196. // Wrap provisioner if the token is an RA token.
  197. var self Interface = p
  198. if claims.Step != nil && claims.Step.RA != nil {
  199. self = &raProvisioner{
  200. Interface: p,
  201. raInfo: claims.Step.RA,
  202. }
  203. }
  204. // Check the fingerprint of the certificate request if given.
  205. var fingerprint string
  206. if claims.Confirmation != nil {
  207. fingerprint = claims.Confirmation.Fingerprint
  208. }
  209. return []SignOption{
  210. self,
  211. templateOptions,
  212. // modifiers / withOptions
  213. newProvisionerExtensionOption(TypeX5C, p.Name, "").WithControllerOptions(p.ctl),
  214. profileLimitDuration{
  215. p.ctl.Claimer.DefaultTLSCertDuration(),
  216. x5cLeaf.NotBefore, x5cLeaf.NotAfter,
  217. },
  218. // validators
  219. csrFingerprintValidator(fingerprint),
  220. commonNameValidator(claims.Subject),
  221. newDefaultSANsValidator(ctx, claims.SANs),
  222. defaultPublicKeyValidator{},
  223. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  224. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  225. p.ctl.newWebhookController(
  226. data,
  227. linkedca.Webhook_X509,
  228. webhook.WithX5CCertificate(x5cLeaf),
  229. webhook.WithAuthorizationPrincipal(x5cLeaf.Subject.CommonName),
  230. ),
  231. }, nil
  232. }
  233. // AuthorizeRenew returns an error if the renewal is disabled.
  234. func (p *X5C) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  235. return p.ctl.AuthorizeRenew(ctx, cert)
  236. }
  237. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  238. func (p *X5C) AuthorizeSSHSign(_ context.Context, token string) ([]SignOption, error) {
  239. if !p.ctl.Claimer.IsSSHCAEnabled() {
  240. return nil, errs.Unauthorized("x5c.AuthorizeSSHSign; sshCA is disabled for x5c provisioner '%s'", p.GetName())
  241. }
  242. claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHSign)
  243. if err != nil {
  244. return nil, errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeSSHSign")
  245. }
  246. if claims.Step == nil || claims.Step.SSH == nil {
  247. return nil, errs.Unauthorized("x5c.AuthorizeSSHSign; x5c token must be an SSH provisioning token")
  248. }
  249. opts := claims.Step.SSH
  250. signOptions := []SignOption{
  251. // validates user's SSHOptions with the ones in the token
  252. sshCertOptionsValidator(*opts),
  253. // validate users's KeyID is the token subject.
  254. sshCertOptionsValidator(SignSSHOptions{KeyID: claims.Subject}),
  255. }
  256. // Default template attributes.
  257. certType := sshutil.UserCert
  258. keyID := claims.Subject
  259. principals := []string{claims.Subject}
  260. // Use options in the token.
  261. if opts.CertType != "" {
  262. if certType, err = sshutil.CertTypeFromString(opts.CertType); err != nil {
  263. return nil, errs.BadRequestErr(err, "%s", err.Error())
  264. }
  265. }
  266. if opts.KeyID != "" {
  267. keyID = opts.KeyID
  268. }
  269. if len(opts.Principals) > 0 {
  270. principals = opts.Principals
  271. }
  272. // Certificate templates.
  273. data := sshutil.CreateTemplateData(certType, keyID, principals)
  274. if v, err := unsafeParseSigned(token); err == nil {
  275. data.SetToken(v)
  276. }
  277. // The X509 certificate will be available using the template variable
  278. // AuthorizationCrt. For example {{ .AuthorizationCrt.DNSNames }} can be
  279. // used to get all the domains.
  280. x5cLeaf := claims.chains[0][0]
  281. data.SetAuthorizationCertificate(x5cLeaf)
  282. templateOptions, err := TemplateSSHOptions(p.Options, data)
  283. if err != nil {
  284. return nil, errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeSSHSign")
  285. }
  286. signOptions = append(signOptions, templateOptions)
  287. // Add modifiers from custom claims
  288. t := now()
  289. if !opts.ValidAfter.IsZero() {
  290. signOptions = append(signOptions, sshCertValidAfterModifier(cast.Uint64(opts.ValidAfter.RelativeTime(t).Unix())))
  291. }
  292. if !opts.ValidBefore.IsZero() {
  293. signOptions = append(signOptions, sshCertValidBeforeModifier(cast.Uint64(opts.ValidBefore.RelativeTime(t).Unix())))
  294. }
  295. return append(signOptions,
  296. p,
  297. // Checks the validity bounds, and set the validity if has not been set.
  298. &sshLimitDuration{p.ctl.Claimer, x5cLeaf.NotAfter},
  299. // Validate public key.
  300. &sshDefaultPublicKeyValidator{},
  301. // Validate the validity period.
  302. &sshCertValidityValidator{p.ctl.Claimer},
  303. // Require all the fields in the SSH certificate
  304. &sshCertDefaultValidator{},
  305. // Ensure that all principal names are allowed
  306. newSSHNamePolicyValidator(p.ctl.getPolicy().getSSHHost(), p.ctl.getPolicy().getSSHUser()),
  307. // Call webhooks
  308. p.ctl.newWebhookController(
  309. data,
  310. linkedca.Webhook_SSH,
  311. webhook.WithX5CCertificate(x5cLeaf),
  312. webhook.WithAuthorizationPrincipal(x5cLeaf.Subject.CommonName),
  313. ),
  314. ), nil
  315. }