authorize.go 18 KB

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