x5c.go 8.2 KB

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