authorize.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. package authority
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/pkg/errors"
  14. "github.com/smallstep/certificates/authority/admin"
  15. "github.com/smallstep/certificates/authority/provisioner"
  16. "github.com/smallstep/certificates/errs"
  17. "go.step.sm/crypto/jose"
  18. "go.step.sm/linkedca"
  19. "golang.org/x/crypto/ssh"
  20. )
  21. // Claims extends jose.Claims with step attributes.
  22. type Claims struct {
  23. jose.Claims
  24. SANs []string `json:"sans,omitempty"`
  25. Email string `json:"email,omitempty"`
  26. Nonce string `json:"nonce,omitempty"`
  27. }
  28. type skipTokenReuseKey struct{}
  29. // NewContextWithSkipTokenReuse creates a new context from ctx and attaches a
  30. // value to skip the token reuse.
  31. func NewContextWithSkipTokenReuse(ctx context.Context) context.Context {
  32. return context.WithValue(ctx, skipTokenReuseKey{}, true)
  33. }
  34. // SkipTokenReuseFromContext returns if the token reuse needs to be ignored.
  35. func SkipTokenReuseFromContext(ctx context.Context) bool {
  36. m, _ := ctx.Value(skipTokenReuseKey{}).(bool)
  37. return m
  38. }
  39. // getProvisionerFromToken extracts a provisioner from the given token without
  40. // doing any token validation.
  41. func (a *Authority) getProvisionerFromToken(token string) (provisioner.Interface, *Claims, error) {
  42. tok, err := jose.ParseSigned(token)
  43. if err != nil {
  44. return nil, nil, fmt.Errorf("error parsing token: %w", err)
  45. }
  46. // Get claims w/out verification. We need to look up the provisioner
  47. // key in order to verify the claims and we need the issuer from the claims
  48. // before we can look up the provisioner.
  49. var claims Claims
  50. if err := tok.UnsafeClaimsWithoutVerification(&claims); err != nil {
  51. return nil, nil, fmt.Errorf("error unmarshaling token: %w", err)
  52. }
  53. // This method will also validate the audiences for JWK provisioners.
  54. p, ok := a.provisioners.LoadByToken(tok, &claims.Claims)
  55. if !ok {
  56. return nil, nil, fmt.Errorf("provisioner not found or invalid audience (%s)", strings.Join(claims.Audience, ", "))
  57. }
  58. return p, &claims, nil
  59. }
  60. // authorizeToken parses the token and returns the provisioner used to generate
  61. // the token. This method enforces the One-Time use policy (tokens can only be
  62. // used once).
  63. func (a *Authority) authorizeToken(ctx context.Context, token string) (provisioner.Interface, error) {
  64. p, claims, err := a.getProvisionerFromToken(token)
  65. if err != nil {
  66. return nil, errs.UnauthorizedErr(err)
  67. }
  68. // TODO: use new persistence layer abstraction.
  69. // Do not accept tokens issued before the start of the ca.
  70. // This check is meant as a stopgap solution to the current lack of a persistence layer.
  71. if a.config.AuthorityConfig != nil && !a.config.AuthorityConfig.DisableIssuedAtCheck {
  72. if claims.IssuedAt != nil && claims.IssuedAt.Time().Before(a.startTime) {
  73. return nil, errs.Unauthorized("token issued before the bootstrap of certificate authority")
  74. }
  75. }
  76. // Store the token to protect against reuse unless it's skipped.
  77. // If we cannot get a token id from the provisioner, just hash the token.
  78. if !SkipTokenReuseFromContext(ctx) {
  79. if err := a.UseToken(token, p); err != nil {
  80. return nil, err
  81. }
  82. }
  83. return p, nil
  84. }
  85. // AuthorizeAdminToken authorize an Admin token.
  86. func (a *Authority) AuthorizeAdminToken(r *http.Request, token string) (*linkedca.Admin, error) {
  87. jwt, err := jose.ParseSigned(token)
  88. if err != nil {
  89. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error parsing x5c token")
  90. }
  91. verifiedChains, err := jwt.Headers[0].Certificates(x509.VerifyOptions{
  92. Roots: a.rootX509CertPool,
  93. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  94. })
  95. if err != nil {
  96. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err,
  97. "adminHandler.authorizeToken; error verifying x5c certificate chain in token")
  98. }
  99. leaf := verifiedChains[0][0]
  100. if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {
  101. return nil, admin.NewError(admin.ErrorUnauthorizedType, "adminHandler.authorizeToken; certificate used to sign x5c token cannot be used for digital signature")
  102. }
  103. // Using the leaf certificates key to validate the claims accomplishes two
  104. // things:
  105. // 1. Asserts that the private key used to sign the token corresponds
  106. // to the public certificate in the `x5c` header of the token.
  107. // 2. Asserts that the claims are valid - have not been tampered with.
  108. var claims jose.Claims
  109. if err := jwt.Claims(leaf.PublicKey, &claims); err != nil {
  110. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error parsing x5c claims")
  111. }
  112. prov, err := a.LoadProvisionerByCertificate(leaf)
  113. if err != nil {
  114. return nil, err
  115. }
  116. // Check that the token has not been used.
  117. if err := a.UseToken(token, prov); err != nil {
  118. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error with reuse token")
  119. }
  120. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  121. // more than a few minutes.
  122. if err := claims.ValidateWithLeeway(jose.Expected{
  123. Time: time.Now().UTC(),
  124. }, time.Minute); err != nil {
  125. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "x5c.authorizeToken; invalid x5c claims")
  126. }
  127. // validate audience: path matches the current path
  128. if !matchesAudience(claims.Audience, a.config.Audience(r.URL.Path)) {
  129. return nil, admin.NewError(admin.ErrorUnauthorizedType, "x5c.authorizeToken; x5c token has invalid audience claim (aud)")
  130. }
  131. // validate issuer: old versions used the provisioner name, new version uses
  132. // 'step-admin-client/1.0'
  133. if claims.Issuer != "step-admin-client/1.0" && claims.Issuer != prov.GetName() {
  134. return nil, admin.NewError(admin.ErrorUnauthorizedType, "x5c.authorizeToken; x5c token has invalid issuer claim (iss)")
  135. }
  136. if claims.Subject == "" {
  137. return nil, admin.NewError(admin.ErrorUnauthorizedType, "x5c.authorizeToken; x5c token subject cannot be empty")
  138. }
  139. var (
  140. ok bool
  141. adm *linkedca.Admin
  142. )
  143. adminFound := false
  144. adminSANs := append([]string{leaf.Subject.CommonName}, leaf.DNSNames...)
  145. adminSANs = append(adminSANs, leaf.EmailAddresses...)
  146. for _, san := range adminSANs {
  147. if adm, ok = a.LoadAdminBySubProv(san, prov.GetName()); ok {
  148. adminFound = true
  149. break
  150. }
  151. }
  152. if !adminFound {
  153. return nil, admin.NewError(admin.ErrorUnauthorizedType,
  154. "adminHandler.authorizeToken; unable to load admin with subject(s) %s and provisioner '%s'",
  155. adminSANs, claims.Issuer)
  156. }
  157. if strings.HasPrefix(r.URL.Path, "/admin/admins") && (r.Method != "GET") && adm.Type != linkedca.Admin_SUPER_ADMIN {
  158. return nil, admin.NewError(admin.ErrorUnauthorizedType, "must have super admin access to make this request")
  159. }
  160. return adm, nil
  161. }
  162. // UseToken stores the token to protect against reuse.
  163. //
  164. // This method currently ignores any error coming from the GetTokenID, but it
  165. // should specifically ignore the error provisioner.ErrAllowTokenReuse.
  166. func (a *Authority) UseToken(token string, prov provisioner.Interface) error {
  167. if reuseKey, err := prov.GetTokenID(token); err == nil {
  168. if reuseKey == "" {
  169. sum := sha256.Sum256([]byte(token))
  170. reuseKey = strings.ToLower(hex.EncodeToString(sum[:]))
  171. }
  172. ok, err := a.db.UseToken(reuseKey, token)
  173. if err != nil {
  174. return errs.Wrap(http.StatusInternalServerError, err, "failed when attempting to store token")
  175. }
  176. if !ok {
  177. return errs.Unauthorized("token already used")
  178. }
  179. }
  180. return nil
  181. }
  182. // Authorize grabs the method from the context and authorizes the request by
  183. // validating the one-time-token.
  184. func (a *Authority) Authorize(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  185. var opts = []interface{}{errs.WithKeyVal("token", token)}
  186. switch m := provisioner.MethodFromContext(ctx); m {
  187. case provisioner.SignMethod:
  188. signOpts, err := a.authorizeSign(ctx, token)
  189. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  190. case provisioner.RevokeMethod:
  191. return nil, errs.Wrap(http.StatusInternalServerError, a.authorizeRevoke(ctx, token), "authority.Authorize", opts...)
  192. case provisioner.SSHSignMethod:
  193. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  194. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  195. }
  196. signOpts, err := a.authorizeSSHSign(ctx, token)
  197. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  198. case provisioner.SSHRenewMethod:
  199. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  200. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  201. }
  202. _, err := a.authorizeSSHRenew(ctx, token)
  203. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  204. case provisioner.SSHRevokeMethod:
  205. return nil, errs.Wrap(http.StatusInternalServerError, a.authorizeSSHRevoke(ctx, token), "authority.Authorize", opts...)
  206. case provisioner.SSHRekeyMethod:
  207. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  208. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  209. }
  210. _, signOpts, err := a.authorizeSSHRekey(ctx, token)
  211. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  212. default:
  213. return nil, errs.InternalServer("authority.Authorize; method %d is not supported", append([]interface{}{m}, opts...)...)
  214. }
  215. }
  216. // authorizeSign loads the provisioner from the token and calls the provisioner
  217. // AuthorizeSign method. Returns a list of methods to apply to the signing flow.
  218. func (a *Authority) authorizeSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  219. p, err := a.authorizeToken(ctx, token)
  220. if err != nil {
  221. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSign")
  222. }
  223. signOpts, err := p.AuthorizeSign(ctx, token)
  224. if err != nil {
  225. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSign")
  226. }
  227. return signOpts, nil
  228. }
  229. // AuthorizeSign authorizes a signature request by validating and authenticating
  230. // a token that must be sent w/ the request.
  231. //
  232. // Deprecated: Use Authorize(context.Context, string) ([]provisioner.SignOption, error).
  233. func (a *Authority) AuthorizeSign(token string) ([]provisioner.SignOption, error) {
  234. ctx := NewContext(context.Background(), a)
  235. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  236. return a.Authorize(ctx, token)
  237. }
  238. // authorizeRevoke locates the provisioner used to generate the authenticating
  239. // token and then performs the token validation flow.
  240. func (a *Authority) authorizeRevoke(ctx context.Context, token string) error {
  241. p, err := a.authorizeToken(ctx, token)
  242. if err != nil {
  243. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRevoke")
  244. }
  245. if err := p.AuthorizeRevoke(ctx, token); err != nil {
  246. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRevoke")
  247. }
  248. return nil
  249. }
  250. // authorizeRenew locates the provisioner (using the provisioner extension in the cert), and checks
  251. // if for the configured provisioner, the renewal is enabled or not. If the
  252. // extra extension cannot be found, authorize the renewal by default.
  253. //
  254. // TODO(mariano): should we authorize by default?
  255. func (a *Authority) authorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  256. serial := cert.SerialNumber.String()
  257. var opts = []interface{}{errs.WithKeyVal("serialNumber", serial)}
  258. isRevoked, err := a.IsRevoked(serial)
  259. if err != nil {
  260. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRenew", opts...)
  261. }
  262. if isRevoked {
  263. return errs.Unauthorized("authority.authorizeRenew: certificate has been revoked", opts...)
  264. }
  265. p, err := a.LoadProvisionerByCertificate(cert)
  266. if err != nil {
  267. var ok bool
  268. // For backward compatibility this method will also succeed if the
  269. // certificate does not have a provisioner extension. LoadByCertificate
  270. // returns the noop provisioner if this happens, and it allows
  271. // certificate renewals.
  272. if p, ok = a.provisioners.LoadByCertificate(cert); !ok {
  273. return errs.Unauthorized("authority.authorizeRenew: provisioner not found", opts...)
  274. }
  275. }
  276. if err := p.AuthorizeRenew(ctx, cert); err != nil {
  277. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRenew", opts...)
  278. }
  279. return nil
  280. }
  281. // authorizeSSHCertificate returns an error if the given certificate is revoked.
  282. func (a *Authority) authorizeSSHCertificate(_ context.Context, cert *ssh.Certificate) error {
  283. var err error
  284. var isRevoked bool
  285. serial := strconv.FormatUint(cert.Serial, 10)
  286. if lca, ok := a.adminDB.(interface {
  287. IsSSHRevoked(string) (bool, error)
  288. }); ok {
  289. isRevoked, err = lca.IsSSHRevoked(serial)
  290. } else {
  291. isRevoked, err = a.db.IsSSHRevoked(serial)
  292. }
  293. if err != nil {
  294. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHCertificate", errs.WithKeyVal("serialNumber", serial))
  295. }
  296. if isRevoked {
  297. return errs.Unauthorized("authority.authorizeSSHCertificate: certificate has been revoked", errs.WithKeyVal("serialNumber", serial))
  298. }
  299. return nil
  300. }
  301. // authorizeSSHSign loads the provisioner from the token, checks that it has not
  302. // been used again and calls the provisioner AuthorizeSSHSign method. Returns a
  303. // list of methods to apply to the signing flow.
  304. func (a *Authority) authorizeSSHSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  305. p, err := a.authorizeToken(ctx, token)
  306. if err != nil {
  307. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.authorizeSSHSign")
  308. }
  309. signOpts, err := p.AuthorizeSSHSign(ctx, token)
  310. if err != nil {
  311. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.authorizeSSHSign")
  312. }
  313. return signOpts, nil
  314. }
  315. // authorizeSSHRenew authorizes an SSH certificate renewal request, by
  316. // validating the contents of an SSHPOP token.
  317. func (a *Authority) authorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  318. p, err := a.authorizeToken(ctx, token)
  319. if err != nil {
  320. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRenew")
  321. }
  322. cert, err := p.AuthorizeSSHRenew(ctx, token)
  323. if err != nil {
  324. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRenew")
  325. }
  326. return cert, nil
  327. }
  328. // authorizeSSHRekey authorizes an SSH certificate rekey request, by
  329. // validating the contents of an SSHPOP token.
  330. func (a *Authority) authorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error) {
  331. p, err := a.authorizeToken(ctx, token)
  332. if err != nil {
  333. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRekey")
  334. }
  335. cert, signOpts, err := p.AuthorizeSSHRekey(ctx, token)
  336. if err != nil {
  337. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRekey")
  338. }
  339. return cert, signOpts, nil
  340. }
  341. // authorizeSSHRevoke authorizes an SSH certificate revoke request, by
  342. // validating the contents of an SSHPOP token.
  343. func (a *Authority) authorizeSSHRevoke(ctx context.Context, token string) error {
  344. p, err := a.authorizeToken(ctx, token)
  345. if err != nil {
  346. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRevoke")
  347. }
  348. if err = p.AuthorizeSSHRevoke(ctx, token); err != nil {
  349. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRevoke")
  350. }
  351. return nil
  352. }
  353. // AuthorizeRenewToken validates the renew token and returns the leaf
  354. // certificate in the x5cInsecure header.
  355. func (a *Authority) AuthorizeRenewToken(_ context.Context, ott string) (*x509.Certificate, error) {
  356. var claims jose.Claims
  357. jwt, chain, err := jose.ParseX5cInsecure(ott, a.rootX509Certs)
  358. if err != nil {
  359. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token"))
  360. }
  361. leaf := chain[0][0]
  362. if err := jwt.Claims(leaf.PublicKey, &claims); err != nil {
  363. return nil, errs.InternalServerErr(err, errs.WithMessage("error validating renew token"))
  364. }
  365. p, err := a.LoadProvisionerByCertificate(leaf)
  366. if err != nil {
  367. return nil, errs.Unauthorized("error validating renew token: cannot get provisioner from certificate")
  368. }
  369. if err := a.UseToken(ott, p); err != nil {
  370. return nil, err
  371. }
  372. if err := claims.ValidateWithLeeway(jose.Expected{
  373. Subject: leaf.Subject.CommonName,
  374. Time: time.Now().UTC(),
  375. }, time.Minute); err != nil {
  376. switch {
  377. case errors.Is(err, jose.ErrInvalidIssuer):
  378. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: invalid issuer claim (iss)"))
  379. case errors.Is(err, jose.ErrInvalidSubject):
  380. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: invalid subject claim (sub)"))
  381. case errors.Is(err, jose.ErrNotValidYet):
  382. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token not valid yet (nbf)"))
  383. case errors.Is(err, jose.ErrExpired):
  384. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token is expired (exp)"))
  385. case errors.Is(err, jose.ErrIssuedInTheFuture):
  386. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token issued in the future (iat)"))
  387. default:
  388. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token"))
  389. }
  390. }
  391. audiences := a.config.GetAudiences().Renew
  392. if !matchesAudience(claims.Audience, audiences) && !isRAProvisioner(p) {
  393. return nil, errs.InternalServerErr(jose.ErrInvalidAudience, errs.WithMessage("error validating renew token: invalid audience claim (aud)"))
  394. }
  395. // validate issuer: old versions used the provisioner name, new version uses
  396. // 'step-ca-client/1.0'
  397. if claims.Issuer != "step-ca-client/1.0" && claims.Issuer != p.GetName() {
  398. return nil, admin.NewError(admin.ErrorUnauthorizedType, "error validating renew token: invalid issuer claim (iss)")
  399. }
  400. return leaf, nil
  401. }
  402. // matchesAudience returns true if A and B share at least one element.
  403. func matchesAudience(as, bs []string) bool {
  404. if len(bs) == 0 || len(as) == 0 {
  405. return false
  406. }
  407. for _, b := range bs {
  408. for _, a := range as {
  409. if b == a || stripPort(a) == stripPort(b) {
  410. return true
  411. }
  412. }
  413. }
  414. return false
  415. }
  416. // stripPort attempts to strip the port from the given url. If parsing the url
  417. // produces errors it will just return the passed argument.
  418. func stripPort(rawurl string) string {
  419. u, err := url.Parse(rawurl)
  420. if err != nil {
  421. return rawurl
  422. }
  423. u.Host = u.Hostname()
  424. return u.String()
  425. }