authorize.go 19 KB

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