authorize.go 18 KB

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