x5c.go 10 KB

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