4
0

authorize.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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(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(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 any error coming from the GetTokenID, but it
  169. // should specifically ignore the error provisioner.ErrAllowTokenReuse.
  170. func (a *Authority) UseToken(token string, prov provisioner.Interface) error {
  171. if reuseKey, err := prov.GetTokenID(token); err == nil {
  172. if reuseKey == "" {
  173. sum := sha256.Sum256([]byte(token))
  174. reuseKey = strings.ToLower(hex.EncodeToString(sum[:]))
  175. }
  176. ok, err := a.db.UseToken(reuseKey, token)
  177. if err != nil {
  178. return errs.Wrap(http.StatusInternalServerError, err, "failed when attempting to store token")
  179. }
  180. if !ok {
  181. return errs.Unauthorized("token already used")
  182. }
  183. }
  184. return nil
  185. }
  186. // Authorize grabs the method from the context and authorizes the request by
  187. // validating the one-time-token.
  188. func (a *Authority) Authorize(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  189. var opts = []interface{}{errs.WithKeyVal("token", token)}
  190. switch m := provisioner.MethodFromContext(ctx); m {
  191. case provisioner.SignMethod, provisioner.SignIdentityMethod:
  192. signOpts, err := a.authorizeSign(ctx, token)
  193. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  194. case provisioner.RevokeMethod:
  195. return nil, errs.Wrap(http.StatusInternalServerError, a.authorizeRevoke(ctx, token), "authority.Authorize", opts...)
  196. case provisioner.SSHSignMethod:
  197. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  198. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  199. }
  200. signOpts, err := a.authorizeSSHSign(ctx, token)
  201. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  202. case provisioner.SSHRenewMethod:
  203. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  204. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  205. }
  206. _, err := a.authorizeSSHRenew(ctx, token)
  207. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  208. case provisioner.SSHRevokeMethod:
  209. return nil, errs.Wrap(http.StatusInternalServerError, a.authorizeSSHRevoke(ctx, token), "authority.Authorize", opts...)
  210. case provisioner.SSHRekeyMethod:
  211. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  212. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  213. }
  214. _, signOpts, err := a.authorizeSSHRekey(ctx, token)
  215. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  216. default:
  217. return nil, errs.InternalServer("authority.Authorize; method %d is not supported", append([]interface{}{m}, opts...)...)
  218. }
  219. }
  220. // authorizeSign loads the provisioner from the token and calls the provisioner
  221. // AuthorizeSign method. Returns a list of methods to apply to the signing flow.
  222. func (a *Authority) authorizeSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  223. p, err := a.authorizeToken(ctx, token)
  224. if err != nil {
  225. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSign")
  226. }
  227. signOpts, err := p.AuthorizeSign(ctx, token)
  228. if err != nil {
  229. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSign")
  230. }
  231. return signOpts, nil
  232. }
  233. // AuthorizeSign authorizes a signature request by validating and authenticating
  234. // a token that must be sent w/ the request.
  235. //
  236. // Deprecated: Use Authorize(context.Context, string) ([]provisioner.SignOption, error).
  237. func (a *Authority) AuthorizeSign(token string) ([]provisioner.SignOption, error) {
  238. ctx := NewContext(context.Background(), a)
  239. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  240. return a.Authorize(ctx, token)
  241. }
  242. // authorizeRevoke locates the provisioner used to generate the authenticating
  243. // token and then performs the token validation flow.
  244. func (a *Authority) authorizeRevoke(ctx context.Context, token string) error {
  245. p, err := a.authorizeToken(ctx, token)
  246. if err != nil {
  247. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRevoke")
  248. }
  249. if err := p.AuthorizeRevoke(ctx, token); err != nil {
  250. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRevoke")
  251. }
  252. return nil
  253. }
  254. // authorizeRenew locates the provisioner (using the provisioner extension in the cert), and checks
  255. // if for the configured provisioner, the renewal is enabled or not. If the
  256. // extra extension cannot be found, authorize the renewal by default.
  257. //
  258. // TODO(mariano): should we authorize by default?
  259. func (a *Authority) authorizeRenew(ctx context.Context, cert *x509.Certificate) (provisioner.Interface, error) {
  260. serial := cert.SerialNumber.String()
  261. var opts = []interface{}{errs.WithKeyVal("serialNumber", serial)}
  262. isRevoked, err := a.IsRevoked(serial)
  263. if err != nil {
  264. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRenew", opts...)
  265. }
  266. if isRevoked {
  267. return nil, errs.Unauthorized("authority.authorizeRenew: certificate has been revoked", opts...)
  268. }
  269. p, err := a.LoadProvisionerByCertificate(cert)
  270. if err != nil {
  271. var ok bool
  272. // For backward compatibility this method will also succeed if the
  273. // certificate does not have a provisioner extension. LoadByCertificate
  274. // returns the noop provisioner if this happens, and it allows
  275. // certificate renewals.
  276. if p, ok = a.provisioners.LoadByCertificate(cert); !ok {
  277. return nil, errs.Unauthorized("authority.authorizeRenew: provisioner not found", opts...)
  278. }
  279. }
  280. if err := p.AuthorizeRenew(ctx, cert); err != nil {
  281. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRenew", opts...)
  282. }
  283. return p, nil
  284. }
  285. // authorizeSSHCertificate returns an error if the given certificate is revoked.
  286. func (a *Authority) authorizeSSHCertificate(_ context.Context, cert *ssh.Certificate) error {
  287. var err error
  288. var isRevoked bool
  289. serial := strconv.FormatUint(cert.Serial, 10)
  290. if lca, ok := a.adminDB.(interface {
  291. IsSSHRevoked(string) (bool, error)
  292. }); ok {
  293. isRevoked, err = lca.IsSSHRevoked(serial)
  294. } else {
  295. isRevoked, err = a.db.IsSSHRevoked(serial)
  296. }
  297. if err != nil {
  298. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHCertificate", errs.WithKeyVal("serialNumber", serial))
  299. }
  300. if isRevoked {
  301. return errs.Unauthorized("authority.authorizeSSHCertificate: certificate has been revoked", errs.WithKeyVal("serialNumber", serial))
  302. }
  303. return nil
  304. }
  305. // authorizeSSHSign loads the provisioner from the token, checks that it has not
  306. // been used again and calls the provisioner AuthorizeSSHSign method. Returns a
  307. // list of methods to apply to the signing flow.
  308. func (a *Authority) authorizeSSHSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  309. p, err := a.authorizeToken(ctx, token)
  310. if err != nil {
  311. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.authorizeSSHSign")
  312. }
  313. signOpts, err := p.AuthorizeSSHSign(ctx, token)
  314. if err != nil {
  315. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.authorizeSSHSign")
  316. }
  317. return signOpts, nil
  318. }
  319. // authorizeSSHRenew authorizes an SSH certificate renewal request, by
  320. // validating the contents of an SSHPOP token.
  321. func (a *Authority) authorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  322. p, err := a.authorizeToken(ctx, token)
  323. if err != nil {
  324. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRenew")
  325. }
  326. cert, err := p.AuthorizeSSHRenew(ctx, token)
  327. if err != nil {
  328. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRenew")
  329. }
  330. return cert, nil
  331. }
  332. // authorizeSSHRekey authorizes an SSH certificate rekey request, by
  333. // validating the contents of an SSHPOP token.
  334. func (a *Authority) authorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error) {
  335. p, err := a.authorizeToken(ctx, token)
  336. if err != nil {
  337. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRekey")
  338. }
  339. cert, signOpts, err := p.AuthorizeSSHRekey(ctx, token)
  340. if err != nil {
  341. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRekey")
  342. }
  343. return cert, signOpts, nil
  344. }
  345. // authorizeSSHRevoke authorizes an SSH certificate revoke request, by
  346. // validating the contents of an SSHPOP token.
  347. func (a *Authority) authorizeSSHRevoke(ctx context.Context, token string) error {
  348. p, err := a.authorizeToken(ctx, token)
  349. if err != nil {
  350. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRevoke")
  351. }
  352. if err = p.AuthorizeSSHRevoke(ctx, token); err != nil {
  353. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRevoke")
  354. }
  355. return nil
  356. }
  357. // AuthorizeRenewToken validates the renew token and returns the leaf
  358. // certificate in the x5cInsecure header.
  359. func (a *Authority) AuthorizeRenewToken(_ context.Context, ott string) (*x509.Certificate, error) {
  360. var claims jose.Claims
  361. jwt, chain, err := jose.ParseX5cInsecure(ott, a.rootX509Certs)
  362. if err != nil {
  363. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token"))
  364. }
  365. leaf := chain[0][0]
  366. if err := jwt.Claims(leaf.PublicKey, &claims); err != nil {
  367. return nil, errs.InternalServerErr(err, errs.WithMessage("error validating renew token"))
  368. }
  369. p, err := a.LoadProvisionerByCertificate(leaf)
  370. if err != nil {
  371. return nil, errs.Unauthorized("error validating renew token: cannot get provisioner from certificate")
  372. }
  373. if err := a.UseToken(ott, p); err != nil {
  374. return nil, err
  375. }
  376. if err := claims.ValidateWithLeeway(jose.Expected{
  377. Subject: leaf.Subject.CommonName,
  378. Time: time.Now().UTC(),
  379. }, time.Minute); err != nil {
  380. switch {
  381. case errors.Is(err, jose.ErrInvalidIssuer):
  382. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: invalid issuer claim (iss)"))
  383. case errors.Is(err, jose.ErrInvalidSubject):
  384. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: invalid subject claim (sub)"))
  385. case errors.Is(err, jose.ErrNotValidYet):
  386. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token not valid yet (nbf)"))
  387. case errors.Is(err, jose.ErrExpired):
  388. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token is expired (exp)"))
  389. case errors.Is(err, jose.ErrIssuedInTheFuture):
  390. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token issued in the future (iat)"))
  391. default:
  392. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token"))
  393. }
  394. }
  395. audiences := a.config.GetAudiences().Renew
  396. if !matchesAudience(claims.Audience, audiences) && !isRAProvisioner(p) {
  397. return nil, errs.InternalServerErr(jose.ErrInvalidAudience, errs.WithMessage("error validating renew token: invalid audience claim (aud)"))
  398. }
  399. // validate issuer: old versions used the provisioner name, new version uses
  400. // 'step-ca-client/1.0'
  401. if claims.Issuer != "step-ca-client/1.0" && claims.Issuer != p.GetName() {
  402. return nil, admin.NewError(admin.ErrorUnauthorizedType, "error validating renew token: invalid issuer claim (iss)")
  403. }
  404. return leaf, nil
  405. }
  406. // matchesAudience returns true if A and B share at least one element.
  407. func matchesAudience(as, bs []string) bool {
  408. if len(bs) == 0 || len(as) == 0 {
  409. return false
  410. }
  411. for _, b := range bs {
  412. for _, a := range as {
  413. if b == a || stripPort(a) == stripPort(b) {
  414. return true
  415. }
  416. }
  417. }
  418. return false
  419. }
  420. // stripPort attempts to strip the port from the given url. If parsing the url
  421. // produces errors it will just return the passed argument.
  422. func stripPort(rawurl string) string {
  423. u, err := url.Parse(rawurl)
  424. if err != nil {
  425. return rawurl
  426. }
  427. u.Host = u.Hostname()
  428. return u.String()
  429. }