authorize.go 17 KB

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