x5c.go 9.6 KB

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