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/smallstep/certificates/authority/admin"
  14. "github.com/smallstep/certificates/authority/provisioner"
  15. "github.com/smallstep/certificates/errs"
  16. "go.step.sm/crypto/jose"
  17. "go.step.sm/linkedca"
  18. "golang.org/x/crypto/ssh"
  19. )
  20. // Claims extends jose.Claims with step attributes.
  21. type Claims struct {
  22. jose.Claims
  23. SANs []string `json:"sans,omitempty"`
  24. Email string `json:"email,omitempty"`
  25. Nonce string `json:"nonce,omitempty"`
  26. }
  27. type skipTokenReuseKey struct{}
  28. // NewContextWithSkipTokenReuse creates a new context from ctx and attaches a
  29. // value to skip the token reuse.
  30. func NewContextWithSkipTokenReuse(ctx context.Context) context.Context {
  31. return context.WithValue(ctx, skipTokenReuseKey{}, true)
  32. }
  33. // SkipTokenReuseFromContext returns if the token reuse needs to be ignored.
  34. func SkipTokenReuseFromContext(ctx context.Context) bool {
  35. m, _ := ctx.Value(skipTokenReuseKey{}).(bool)
  36. return m
  37. }
  38. // getProvisionerFromToken extracts a provisioner from the given token without
  39. // doing any token validation.
  40. func (a *Authority) getProvisionerFromToken(token string) (provisioner.Interface, *Claims, error) {
  41. tok, err := jose.ParseSigned(token)
  42. if err != nil {
  43. return nil, nil, fmt.Errorf("error parsing token: %w", err)
  44. }
  45. // Get claims w/out verification. We need to look up the provisioner
  46. // key in order to verify the claims and we need the issuer from the claims
  47. // before we can look up the provisioner.
  48. var claims Claims
  49. if err := tok.UnsafeClaimsWithoutVerification(&claims); err != nil {
  50. return nil, nil, fmt.Errorf("error unmarshaling token: %w", err)
  51. }
  52. // This method will also validate the audiences for JWK provisioners.
  53. p, ok := a.provisioners.LoadByToken(tok, &claims.Claims)
  54. if !ok {
  55. return nil, nil, fmt.Errorf("provisioner not found or invalid audience (%s)", strings.Join(claims.Audience, ", "))
  56. }
  57. return p, &claims, nil
  58. }
  59. // authorizeToken parses the token and returns the provisioner used to generate
  60. // the token. This method enforces the One-Time use policy (tokens can only be
  61. // used once).
  62. func (a *Authority) authorizeToken(ctx context.Context, token string) (provisioner.Interface, error) {
  63. p, claims, err := a.getProvisionerFromToken(token)
  64. if err != nil {
  65. return nil, errs.UnauthorizedErr(err)
  66. }
  67. // TODO: use new persistence layer abstraction.
  68. // Do not accept tokens issued before the start of the ca.
  69. // This check is meant as a stopgap solution to the current lack of a persistence layer.
  70. if a.config.AuthorityConfig != nil && !a.config.AuthorityConfig.DisableIssuedAtCheck {
  71. if claims.IssuedAt != nil && claims.IssuedAt.Time().Before(a.startTime) {
  72. return nil, errs.Unauthorized("token issued before the bootstrap of certificate authority")
  73. }
  74. }
  75. // Store the token to protect against reuse unless it's skipped.
  76. // If we cannot get a token id from the provisioner, just hash the token.
  77. if !SkipTokenReuseFromContext(ctx) {
  78. if err := a.UseToken(token, p); err != nil {
  79. return nil, err
  80. }
  81. }
  82. return p, nil
  83. }
  84. // AuthorizeAdminToken authorize an Admin token.
  85. func (a *Authority) AuthorizeAdminToken(r *http.Request, token string) (*linkedca.Admin, error) {
  86. jwt, err := jose.ParseSigned(token)
  87. if err != nil {
  88. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error parsing x5c token")
  89. }
  90. verifiedChains, err := jwt.Headers[0].Certificates(x509.VerifyOptions{
  91. Roots: a.rootX509CertPool,
  92. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  93. })
  94. if err != nil {
  95. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err,
  96. "adminHandler.authorizeToken; error verifying x5c certificate chain in token")
  97. }
  98. leaf := verifiedChains[0][0]
  99. if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {
  100. return nil, admin.NewError(admin.ErrorUnauthorizedType, "adminHandler.authorizeToken; certificate used to sign x5c token cannot be used for digital signature")
  101. }
  102. // Using the leaf certificates key to validate the claims accomplishes two
  103. // things:
  104. // 1. Asserts that the private key used to sign the token corresponds
  105. // to the public certificate in the `x5c` header of the token.
  106. // 2. Asserts that the claims are valid - have not been tampered with.
  107. var claims jose.Claims
  108. if err := jwt.Claims(leaf.PublicKey, &claims); err != nil {
  109. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error parsing x5c claims")
  110. }
  111. prov, err := a.LoadProvisionerByCertificate(leaf)
  112. if err != nil {
  113. return nil, err
  114. }
  115. // Check that the token has not been used.
  116. if err := a.UseToken(token, prov); err != nil {
  117. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error with reuse token")
  118. }
  119. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  120. // more than a few minutes.
  121. if err := claims.ValidateWithLeeway(jose.Expected{
  122. Time: time.Now().UTC(),
  123. }, time.Minute); err != nil {
  124. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "x5c.authorizeToken; invalid x5c claims")
  125. }
  126. // validate audience: path matches the current path
  127. if !matchesAudience(claims.Audience, a.config.Audience(r.URL.Path)) {
  128. return nil, admin.NewError(admin.ErrorUnauthorizedType, "x5c.authorizeToken; x5c token has invalid audience claim (aud)")
  129. }
  130. // validate issuer: old versions used the provisioner name, new version uses
  131. // 'step-admin-client/1.0'
  132. if claims.Issuer != "step-admin-client/1.0" && claims.Issuer != prov.GetName() {
  133. return nil, admin.NewError(admin.ErrorUnauthorizedType, "x5c.authorizeToken; x5c token has invalid issuer claim (iss)")
  134. }
  135. if claims.Subject == "" {
  136. return nil, admin.NewError(admin.ErrorUnauthorizedType, "x5c.authorizeToken; x5c token subject cannot be empty")
  137. }
  138. var (
  139. ok bool
  140. adm *linkedca.Admin
  141. )
  142. adminFound := false
  143. adminSANs := append([]string{leaf.Subject.CommonName}, leaf.DNSNames...)
  144. adminSANs = append(adminSANs, leaf.EmailAddresses...)
  145. for _, san := range adminSANs {
  146. if adm, ok = a.LoadAdminBySubProv(san, prov.GetName()); ok {
  147. adminFound = true
  148. break
  149. }
  150. }
  151. if !adminFound {
  152. return nil, admin.NewError(admin.ErrorUnauthorizedType,
  153. "adminHandler.authorizeToken; unable to load admin with subject(s) %s and provisioner '%s'",
  154. adminSANs, claims.Issuer)
  155. }
  156. if strings.HasPrefix(r.URL.Path, "/admin/admins") && (r.Method != "GET") && adm.Type != linkedca.Admin_SUPER_ADMIN {
  157. return nil, admin.NewError(admin.ErrorUnauthorizedType, "must have super admin access to make this request")
  158. }
  159. return adm, nil
  160. }
  161. // UseToken stores the token to protect against reuse.
  162. //
  163. // This method currently ignores any error coming from the GetTokenID, but it
  164. // should specifically ignore the error provisioner.ErrAllowTokenReuse.
  165. func (a *Authority) UseToken(token string, prov provisioner.Interface) error {
  166. if reuseKey, err := prov.GetTokenID(token); err == nil {
  167. if reuseKey == "" {
  168. sum := sha256.Sum256([]byte(token))
  169. reuseKey = strings.ToLower(hex.EncodeToString(sum[:]))
  170. }
  171. ok, err := a.db.UseToken(reuseKey, token)
  172. if err != nil {
  173. return errs.Wrap(http.StatusInternalServerError, err,
  174. "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. // NOTE: This method is deprecated and should not be used. We make it available
  233. // in the short term os as not to break existing clients.
  234. func (a *Authority) AuthorizeSign(token string) ([]provisioner.SignOption, error) {
  235. ctx := provisioner.NewContextWithMethod(context.Background(), 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(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(context.Background(), 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(ctx 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(ctx 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 err {
  377. case jose.ErrInvalidIssuer:
  378. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: invalid issuer claim (iss)"))
  379. case jose.ErrInvalidSubject:
  380. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: invalid subject claim (sub)"))
  381. case jose.ErrNotValidYet:
  382. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token not valid yet (nbf)"))
  383. case jose.ErrExpired:
  384. return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token is expired (exp)"))
  385. case 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) {
  393. return nil, errs.InternalServerErr(err, 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. }