x5c.go 11 KB

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