x5c.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. ID string `json:"-"`
  26. Type string `json:"type"`
  27. Name string `json:"name"`
  28. Roots []byte `json:"roots"`
  29. Claims *Claims `json:"claims,omitempty"`
  30. Options *Options `json:"options,omitempty"`
  31. claimer *Claimer
  32. audiences Audiences
  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) 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. )
  91. for rest != nil {
  92. block, rest = pem.Decode(rest)
  93. if block == nil {
  94. break
  95. }
  96. cert, err := x509.ParseCertificate(block.Bytes)
  97. if err != nil {
  98. return errors.Wrap(err, "error parsing x509 certificate from PEM block")
  99. }
  100. p.rootPool.AddCert(cert)
  101. }
  102. // Verify that at least one root was found.
  103. if len(p.rootPool.Subjects()) == 0 {
  104. return errors.Errorf("no x509 certificates found in roots attribute for provisioner '%s'", p.GetName())
  105. }
  106. // Update claims with global ones
  107. var err error
  108. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  109. return err
  110. }
  111. p.audiences = config.Audiences.WithFragment(p.GetIDForToken())
  112. return nil
  113. }
  114. // authorizeToken performs common jwt authorization actions and returns the
  115. // claims for case specific downstream parsing.
  116. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  117. func (p *X5C) authorizeToken(token string, audiences []string) (*x5cPayload, error) {
  118. jwt, err := jose.ParseSigned(token)
  119. if err != nil {
  120. return nil, errs.Wrap(http.StatusUnauthorized, err, "x5c.authorizeToken; error parsing x5c token")
  121. }
  122. verifiedChains, err := jwt.Headers[0].Certificates(x509.VerifyOptions{
  123. Roots: p.rootPool,
  124. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  125. })
  126. if err != nil {
  127. return nil, errs.Wrap(http.StatusUnauthorized, err,
  128. "x5c.authorizeToken; error verifying x5c certificate chain in token")
  129. }
  130. leaf := verifiedChains[0][0]
  131. if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {
  132. return nil, errs.Unauthorized("x5c.authorizeToken; certificate used to sign x5c token cannot be used for digital signature")
  133. }
  134. // Using the leaf certificates key to validate the claims accomplishes two
  135. // things:
  136. // 1. Asserts that the private key used to sign the token corresponds
  137. // to the public certificate in the `x5c` header of the token.
  138. // 2. Asserts that the claims are valid - have not been tampered with.
  139. var claims x5cPayload
  140. if err = jwt.Claims(leaf.PublicKey, &claims); err != nil {
  141. return nil, errs.Wrap(http.StatusUnauthorized, err, "x5c.authorizeToken; error parsing x5c claims")
  142. }
  143. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  144. // more than a few minutes.
  145. if err = claims.ValidateWithLeeway(jose.Expected{
  146. Issuer: p.Name,
  147. Time: time.Now().UTC(),
  148. }, time.Minute); err != nil {
  149. return nil, errs.Wrapf(http.StatusUnauthorized, err, "x5c.authorizeToken; invalid x5c claims")
  150. }
  151. // validate audiences with the defaults
  152. if !matchesAudience(claims.Audience, audiences) {
  153. return nil, errs.Unauthorized("x5c.authorizeToken; x5c token has invalid audience "+
  154. "claim (aud); expected %s, but got %s", audiences, claims.Audience)
  155. }
  156. if claims.Subject == "" {
  157. return nil, errs.Unauthorized("x5c.authorizeToken; x5c token subject cannot be empty")
  158. }
  159. // Save the verified chains on the x5c payload object.
  160. claims.chains = verifiedChains
  161. return &claims, nil
  162. }
  163. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  164. // revoke the certificate with serial number in the `sub` property.
  165. func (p *X5C) AuthorizeRevoke(ctx context.Context, token string) error {
  166. _, err := p.authorizeToken(token, p.audiences.Revoke)
  167. return errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeRevoke")
  168. }
  169. // AuthorizeSign validates the given token.
  170. func (p *X5C) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  171. claims, err := p.authorizeToken(token, p.audiences.Sign)
  172. if err != nil {
  173. return nil, errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeSign")
  174. }
  175. // NOTE: This is for backwards compatibility with older versions of cli
  176. // and certificates. Older versions added the token subject as the only SAN
  177. // in a CSR by default.
  178. if len(claims.SANs) == 0 {
  179. claims.SANs = []string{claims.Subject}
  180. }
  181. // Certificate templates
  182. data := x509util.CreateTemplateData(claims.Subject, claims.SANs)
  183. if v, err := unsafeParseSigned(token); err == nil {
  184. data.SetToken(v)
  185. }
  186. templateOptions, err := TemplateOptions(p.Options, data)
  187. if err != nil {
  188. return nil, errs.Wrap(http.StatusInternalServerError, err, "jwk.AuthorizeSign")
  189. }
  190. return []SignOption{
  191. templateOptions,
  192. // modifiers / withOptions
  193. newProvisionerExtensionOption(TypeX5C, p.Name, ""),
  194. profileLimitDuration{p.claimer.DefaultTLSCertDuration(),
  195. claims.chains[0][0].NotBefore, claims.chains[0][0].NotAfter},
  196. // validators
  197. commonNameValidator(claims.Subject),
  198. defaultSANsValidator(claims.SANs),
  199. defaultPublicKeyValidator{},
  200. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  201. }, nil
  202. }
  203. // AuthorizeRenew returns an error if the renewal is disabled.
  204. func (p *X5C) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  205. if p.claimer.IsDisableRenewal() {
  206. return errs.Unauthorized("x5c.AuthorizeRenew; renew is disabled for x5c provisioner '%s'", p.GetName())
  207. }
  208. return nil
  209. }
  210. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  211. func (p *X5C) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  212. if !p.claimer.IsSSHCAEnabled() {
  213. return nil, errs.Unauthorized("x5c.AuthorizeSSHSign; sshCA is disabled for x5c provisioner '%s'", p.GetName())
  214. }
  215. claims, err := p.authorizeToken(token, p.audiences.SSHSign)
  216. if err != nil {
  217. return nil, errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeSSHSign")
  218. }
  219. if claims.Step == nil || claims.Step.SSH == nil {
  220. return nil, errs.Unauthorized("x5c.AuthorizeSSHSign; x5c token must be an SSH provisioning token")
  221. }
  222. opts := claims.Step.SSH
  223. signOptions := []SignOption{
  224. // validates user's SSHOptions with the ones in the token
  225. sshCertOptionsValidator(*opts),
  226. // validate users's KeyID is the token subject.
  227. sshCertOptionsValidator(SignSSHOptions{KeyID: claims.Subject}),
  228. }
  229. // Default template attributes.
  230. certType := sshutil.UserCert
  231. keyID := claims.Subject
  232. principals := []string{claims.Subject}
  233. // Use options in the token.
  234. if opts.CertType != "" {
  235. if certType, err = sshutil.CertTypeFromString(opts.CertType); err != nil {
  236. return nil, errs.Wrap(http.StatusBadRequest, err, "x5c.AuthorizeSSHSign")
  237. }
  238. }
  239. if opts.KeyID != "" {
  240. keyID = opts.KeyID
  241. }
  242. if len(opts.Principals) > 0 {
  243. principals = opts.Principals
  244. }
  245. // Certificate templates.
  246. data := sshutil.CreateTemplateData(certType, keyID, principals)
  247. if v, err := unsafeParseSigned(token); err == nil {
  248. data.SetToken(v)
  249. }
  250. templateOptions, err := TemplateSSHOptions(p.Options, data)
  251. if err != nil {
  252. return nil, errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeSSHSign")
  253. }
  254. signOptions = append(signOptions, templateOptions)
  255. // Add modifiers from custom claims
  256. t := now()
  257. if !opts.ValidAfter.IsZero() {
  258. signOptions = append(signOptions, sshCertValidAfterModifier(opts.ValidAfter.RelativeTime(t).Unix()))
  259. }
  260. if !opts.ValidBefore.IsZero() {
  261. signOptions = append(signOptions, sshCertValidBeforeModifier(opts.ValidBefore.RelativeTime(t).Unix()))
  262. }
  263. return append(signOptions,
  264. // Checks the validity bounds, and set the validity if has not been set.
  265. &sshLimitDuration{p.claimer, claims.chains[0][0].NotAfter},
  266. // Validate public key.
  267. &sshDefaultPublicKeyValidator{},
  268. // Validate the validity period.
  269. &sshCertValidityValidator{p.claimer},
  270. // Require all the fields in the SSH certificate
  271. &sshCertDefaultValidator{},
  272. ), nil
  273. }