x5c.go 11 KB

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