authorize.go 17 KB

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