x5c.go 8.2 KB

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