x5c.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "net/http"
  7. "time"
  8. "github.com/pkg/errors"
  9. "go.step.sm/crypto/jose"
  10. "go.step.sm/crypto/sshutil"
  11. "go.step.sm/crypto/x509util"
  12. "github.com/smallstep/certificates/errs"
  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, p.Options)
  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. // Wrap provisioner if the token is an RA token.
  192. var self Interface = p
  193. if claims.Step != nil && claims.Step.RA != nil {
  194. self = &raProvisioner{
  195. Interface: p,
  196. raInfo: claims.Step.RA,
  197. }
  198. }
  199. return []SignOption{
  200. self,
  201. templateOptions,
  202. // modifiers / withOptions
  203. newProvisionerExtensionOption(TypeX5C, p.Name, ""),
  204. profileLimitDuration{
  205. p.ctl.Claimer.DefaultTLSCertDuration(),
  206. claims.chains[0][0].NotBefore, claims.chains[0][0].NotAfter,
  207. },
  208. // validators
  209. commonNameValidator(claims.Subject),
  210. defaultSANsValidator(claims.SANs),
  211. defaultPublicKeyValidator{},
  212. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  213. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  214. }, nil
  215. }
  216. // AuthorizeRenew returns an error if the renewal is disabled.
  217. func (p *X5C) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  218. return p.ctl.AuthorizeRenew(ctx, cert)
  219. }
  220. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  221. func (p *X5C) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  222. if !p.ctl.Claimer.IsSSHCAEnabled() {
  223. return nil, errs.Unauthorized("x5c.AuthorizeSSHSign; sshCA is disabled for x5c provisioner '%s'", p.GetName())
  224. }
  225. claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHSign)
  226. if err != nil {
  227. return nil, errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeSSHSign")
  228. }
  229. if claims.Step == nil || claims.Step.SSH == nil {
  230. return nil, errs.Unauthorized("x5c.AuthorizeSSHSign; x5c token must be an SSH provisioning token")
  231. }
  232. opts := claims.Step.SSH
  233. signOptions := []SignOption{
  234. // validates user's SSHOptions with the ones in the token
  235. sshCertOptionsValidator(*opts),
  236. // validate users's KeyID is the token subject.
  237. sshCertOptionsValidator(SignSSHOptions{KeyID: claims.Subject}),
  238. }
  239. // Default template attributes.
  240. certType := sshutil.UserCert
  241. keyID := claims.Subject
  242. principals := []string{claims.Subject}
  243. // Use options in the token.
  244. if opts.CertType != "" {
  245. if certType, err = sshutil.CertTypeFromString(opts.CertType); err != nil {
  246. return nil, errs.BadRequestErr(err, err.Error())
  247. }
  248. }
  249. if opts.KeyID != "" {
  250. keyID = opts.KeyID
  251. }
  252. if len(opts.Principals) > 0 {
  253. principals = opts.Principals
  254. }
  255. // Certificate templates.
  256. data := sshutil.CreateTemplateData(certType, keyID, principals)
  257. if v, err := unsafeParseSigned(token); err == nil {
  258. data.SetToken(v)
  259. }
  260. // The X509 certificate will be available using the template variable
  261. // AuthorizationCrt. For example {{ .AuthorizationCrt.DNSNames }} can be
  262. // used to get all the domains.
  263. data.SetAuthorizationCertificate(claims.chains[0][0])
  264. templateOptions, err := TemplateSSHOptions(p.Options, data)
  265. if err != nil {
  266. return nil, errs.Wrap(http.StatusInternalServerError, err, "x5c.AuthorizeSSHSign")
  267. }
  268. signOptions = append(signOptions, templateOptions)
  269. // Add modifiers from custom claims
  270. t := now()
  271. if !opts.ValidAfter.IsZero() {
  272. signOptions = append(signOptions, sshCertValidAfterModifier(opts.ValidAfter.RelativeTime(t).Unix()))
  273. }
  274. if !opts.ValidBefore.IsZero() {
  275. signOptions = append(signOptions, sshCertValidBeforeModifier(opts.ValidBefore.RelativeTime(t).Unix()))
  276. }
  277. return append(signOptions,
  278. p,
  279. // Checks the validity bounds, and set the validity if has not been set.
  280. &sshLimitDuration{p.ctl.Claimer, claims.chains[0][0].NotAfter},
  281. // Validate public key.
  282. &sshDefaultPublicKeyValidator{},
  283. // Validate the validity period.
  284. &sshCertValidityValidator{p.ctl.Claimer},
  285. // Require all the fields in the SSH certificate
  286. &sshCertDefaultValidator{},
  287. // Ensure that all principal names are allowed
  288. newSSHNamePolicyValidator(p.ctl.getPolicy().getSSHHost(), p.ctl.getPolicy().getSSHUser()),
  289. ), nil
  290. }