x5c.go 10 KB

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