x5c.go 9.0 KB

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