authorize.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package authority
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "github.com/smallstep/certificates/authority/admin"
  11. "github.com/smallstep/certificates/authority/provisioner"
  12. "github.com/smallstep/certificates/errs"
  13. "go.step.sm/crypto/jose"
  14. "go.step.sm/linkedca"
  15. "golang.org/x/crypto/ssh"
  16. )
  17. // Claims extends jose.Claims with step attributes.
  18. type Claims struct {
  19. jose.Claims
  20. SANs []string `json:"sans,omitempty"`
  21. Email string `json:"email,omitempty"`
  22. Nonce string `json:"nonce,omitempty"`
  23. }
  24. type skipTokenReuseKey struct{}
  25. // NewContextWithSkipTokenReuse creates a new context from ctx and attaches a
  26. // value to skip the token reuse.
  27. func NewContextWithSkipTokenReuse(ctx context.Context) context.Context {
  28. return context.WithValue(ctx, skipTokenReuseKey{}, true)
  29. }
  30. // SkipTokenReuseFromContext returns if the token reuse needs to be ignored.
  31. func SkipTokenReuseFromContext(ctx context.Context) bool {
  32. m, _ := ctx.Value(skipTokenReuseKey{}).(bool)
  33. return m
  34. }
  35. // authorizeToken parses the token and returns the provisioner used to generate
  36. // the token. This method enforces the One-Time use policy (tokens can only be
  37. // used once).
  38. func (a *Authority) authorizeToken(ctx context.Context, token string) (provisioner.Interface, error) {
  39. // Validate payload
  40. tok, err := jose.ParseSigned(token)
  41. if err != nil {
  42. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.authorizeToken: error parsing token")
  43. }
  44. // Get claims w/out verification. We need to look up the provisioner
  45. // key in order to verify the claims and we need the issuer from the claims
  46. // before we can look up the provisioner.
  47. var claims Claims
  48. if err = tok.UnsafeClaimsWithoutVerification(&claims); err != nil {
  49. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.authorizeToken")
  50. }
  51. // TODO: use new persistence layer abstraction.
  52. // Do not accept tokens issued before the start of the ca.
  53. // This check is meant as a stopgap solution to the current lack of a persistence layer.
  54. if a.config.AuthorityConfig != nil && !a.config.AuthorityConfig.DisableIssuedAtCheck {
  55. if claims.IssuedAt != nil && claims.IssuedAt.Time().Before(a.startTime) {
  56. return nil, errs.Unauthorized("authority.authorizeToken: token issued before the bootstrap of certificate authority")
  57. }
  58. }
  59. // This method will also validate the audiences for JWK provisioners.
  60. p, ok := a.provisioners.LoadByToken(tok, &claims.Claims)
  61. if !ok {
  62. return nil, errs.Unauthorized("authority.authorizeToken: provisioner "+
  63. "not found or invalid audience (%s)", strings.Join(claims.Audience, ", "))
  64. }
  65. // Store the token to protect against reuse unless it's skipped.
  66. // If we cannot get a token id from the provisioner, just hash the token.
  67. if !SkipTokenReuseFromContext(ctx) {
  68. if err = a.UseToken(token, p); err != nil {
  69. return nil, err
  70. }
  71. }
  72. return p, nil
  73. }
  74. // AuthorizeAdminToken authorize an Admin token.
  75. func (a *Authority) AuthorizeAdminToken(r *http.Request, token string) (*linkedca.Admin, error) {
  76. jwt, err := jose.ParseSigned(token)
  77. if err != nil {
  78. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error parsing x5c token")
  79. }
  80. verifiedChains, err := jwt.Headers[0].Certificates(x509.VerifyOptions{
  81. Roots: a.rootX509CertPool,
  82. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  83. })
  84. if err != nil {
  85. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err,
  86. "adminHandler.authorizeToken; error verifying x5c certificate chain in token")
  87. }
  88. leaf := verifiedChains[0][0]
  89. if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {
  90. return nil, admin.NewError(admin.ErrorUnauthorizedType, "adminHandler.authorizeToken; certificate used to sign x5c token cannot be used for digital signature")
  91. }
  92. // Using the leaf certificates key to validate the claims accomplishes two
  93. // things:
  94. // 1. Asserts that the private key used to sign the token corresponds
  95. // to the public certificate in the `x5c` header of the token.
  96. // 2. Asserts that the claims are valid - have not been tampered with.
  97. var claims jose.Claims
  98. if err = jwt.Claims(leaf.PublicKey, &claims); err != nil {
  99. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error parsing x5c claims")
  100. }
  101. prov, err := a.LoadProvisionerByCertificate(leaf)
  102. if err != nil {
  103. return nil, err
  104. }
  105. // Check that the token has not been used.
  106. if err = a.UseToken(token, prov); err != nil {
  107. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "adminHandler.authorizeToken; error with reuse token")
  108. }
  109. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  110. // more than a few minutes.
  111. if err = claims.ValidateWithLeeway(jose.Expected{
  112. Issuer: prov.GetName(),
  113. Time: time.Now().UTC(),
  114. }, time.Minute); err != nil {
  115. return nil, admin.WrapError(admin.ErrorUnauthorizedType, err, "x5c.authorizeToken; invalid x5c claims")
  116. }
  117. // validate audience: path matches the current path
  118. if r.URL.Path != claims.Audience[0] {
  119. return nil, admin.NewError(admin.ErrorUnauthorizedType,
  120. "x5c.authorizeToken; x5c token has invalid audience "+
  121. "claim (aud); expected %s, but got %s", r.URL.Path, claims.Audience)
  122. }
  123. if claims.Subject == "" {
  124. return nil, admin.NewError(admin.ErrorUnauthorizedType,
  125. "x5c.authorizeToken; x5c token subject cannot be empty")
  126. }
  127. var (
  128. ok bool
  129. adm *linkedca.Admin
  130. )
  131. adminFound := false
  132. adminSANs := append([]string{leaf.Subject.CommonName}, leaf.DNSNames...)
  133. adminSANs = append(adminSANs, leaf.EmailAddresses...)
  134. for _, san := range adminSANs {
  135. if adm, ok = a.LoadAdminBySubProv(san, claims.Issuer); ok {
  136. adminFound = true
  137. break
  138. }
  139. }
  140. if !adminFound {
  141. return nil, admin.NewError(admin.ErrorUnauthorizedType,
  142. "adminHandler.authorizeToken; unable to load admin with subject(s) %s and provisioner '%s'",
  143. adminSANs, claims.Issuer)
  144. }
  145. if strings.HasPrefix(r.URL.Path, "/admin/admins") && (r.Method != "GET") && adm.Type != linkedca.Admin_SUPER_ADMIN {
  146. return nil, admin.NewError(admin.ErrorUnauthorizedType, "must have super admin access to make this request")
  147. }
  148. return adm, nil
  149. }
  150. // UseToken stores the token to protect against reuse.
  151. //
  152. // This method currently ignores any error coming from the GetTokenID, but it
  153. // should specifically ignore the error provisioner.ErrAllowTokenReuse.
  154. func (a *Authority) UseToken(token string, prov provisioner.Interface) error {
  155. if reuseKey, err := prov.GetTokenID(token); err == nil {
  156. if reuseKey == "" {
  157. sum := sha256.Sum256([]byte(token))
  158. reuseKey = strings.ToLower(hex.EncodeToString(sum[:]))
  159. }
  160. ok, err := a.db.UseToken(reuseKey, token)
  161. if err != nil {
  162. return errs.Wrap(http.StatusInternalServerError, err,
  163. "authority.authorizeToken: failed when attempting to store token")
  164. }
  165. if !ok {
  166. return errs.Unauthorized("authority.authorizeToken: token already used")
  167. }
  168. }
  169. return nil
  170. }
  171. // Authorize grabs the method from the context and authorizes the request by
  172. // validating the one-time-token.
  173. func (a *Authority) Authorize(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  174. var opts = []interface{}{errs.WithKeyVal("token", token)}
  175. switch m := provisioner.MethodFromContext(ctx); m {
  176. case provisioner.SignMethod:
  177. signOpts, err := a.authorizeSign(ctx, token)
  178. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  179. case provisioner.RevokeMethod:
  180. return nil, errs.Wrap(http.StatusInternalServerError, a.authorizeRevoke(ctx, token), "authority.Authorize", opts...)
  181. case provisioner.SSHSignMethod:
  182. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  183. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  184. }
  185. signOpts, err := a.authorizeSSHSign(ctx, token)
  186. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  187. case provisioner.SSHRenewMethod:
  188. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  189. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  190. }
  191. _, err := a.authorizeSSHRenew(ctx, token)
  192. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  193. case provisioner.SSHRevokeMethod:
  194. return nil, errs.Wrap(http.StatusInternalServerError, a.authorizeSSHRevoke(ctx, token), "authority.Authorize", opts...)
  195. case provisioner.SSHRekeyMethod:
  196. if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
  197. return nil, errs.NotImplemented("authority.Authorize; ssh certificate flows are not enabled", opts...)
  198. }
  199. _, signOpts, err := a.authorizeSSHRekey(ctx, token)
  200. return signOpts, errs.Wrap(http.StatusInternalServerError, err, "authority.Authorize", opts...)
  201. default:
  202. return nil, errs.InternalServer("authority.Authorize; method %d is not supported", append([]interface{}{m}, opts...)...)
  203. }
  204. }
  205. // authorizeSign loads the provisioner from the token and calls the provisioner
  206. // AuthorizeSign method. Returns a list of methods to apply to the signing flow.
  207. func (a *Authority) authorizeSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  208. p, err := a.authorizeToken(ctx, token)
  209. if err != nil {
  210. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSign")
  211. }
  212. signOpts, err := p.AuthorizeSign(ctx, token)
  213. if err != nil {
  214. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSign")
  215. }
  216. return signOpts, nil
  217. }
  218. // AuthorizeSign authorizes a signature request by validating and authenticating
  219. // a token that must be sent w/ the request.
  220. //
  221. // NOTE: This method is deprecated and should not be used. We make it available
  222. // in the short term os as not to break existing clients.
  223. func (a *Authority) AuthorizeSign(token string) ([]provisioner.SignOption, error) {
  224. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
  225. return a.Authorize(ctx, token)
  226. }
  227. // authorizeRevoke locates the provisioner used to generate the authenticating
  228. // token and then performs the token validation flow.
  229. func (a *Authority) authorizeRevoke(ctx context.Context, token string) error {
  230. p, err := a.authorizeToken(ctx, token)
  231. if err != nil {
  232. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRevoke")
  233. }
  234. if err = p.AuthorizeRevoke(ctx, token); err != nil {
  235. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRevoke")
  236. }
  237. return nil
  238. }
  239. // authorizeRenew locates the provisioner (using the provisioner extension in the cert), and checks
  240. // if for the configured provisioner, the renewal is enabled or not. If the
  241. // extra extension cannot be found, authorize the renewal by default.
  242. //
  243. // TODO(mariano): should we authorize by default?
  244. func (a *Authority) authorizeRenew(cert *x509.Certificate) error {
  245. var opts = []interface{}{errs.WithKeyVal("serialNumber", cert.SerialNumber.String())}
  246. // Check the passive revocation table.
  247. isRevoked, err := a.db.IsRevoked(cert.SerialNumber.String())
  248. if err != nil {
  249. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRenew", opts...)
  250. }
  251. if isRevoked {
  252. return errs.Unauthorized("authority.authorizeRenew: certificate has been revoked", opts...)
  253. }
  254. p, ok := a.provisioners.LoadByCertificate(cert)
  255. if !ok {
  256. return errs.Unauthorized("authority.authorizeRenew: provisioner not found", opts...)
  257. }
  258. if err := p.AuthorizeRenew(context.Background(), cert); err != nil {
  259. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeRenew", opts...)
  260. }
  261. return nil
  262. }
  263. // authorizeSSHSign loads the provisioner from the token, checks that it has not
  264. // been used again and calls the provisioner AuthorizeSSHSign method. Returns a
  265. // list of methods to apply to the signing flow.
  266. func (a *Authority) authorizeSSHSign(ctx context.Context, token string) ([]provisioner.SignOption, error) {
  267. p, err := a.authorizeToken(ctx, token)
  268. if err != nil {
  269. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.authorizeSSHSign")
  270. }
  271. signOpts, err := p.AuthorizeSSHSign(ctx, token)
  272. if err != nil {
  273. return nil, errs.Wrap(http.StatusUnauthorized, err, "authority.authorizeSSHSign")
  274. }
  275. return signOpts, nil
  276. }
  277. // authorizeSSHRenew authorizes an SSH certificate renewal request, by
  278. // validating the contents of an SSHPOP token.
  279. func (a *Authority) authorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  280. p, err := a.authorizeToken(ctx, token)
  281. if err != nil {
  282. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRenew")
  283. }
  284. cert, err := p.AuthorizeSSHRenew(ctx, token)
  285. if err != nil {
  286. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRenew")
  287. }
  288. return cert, nil
  289. }
  290. // authorizeSSHRekey authorizes an SSH certificate rekey request, by
  291. // validating the contents of an SSHPOP token.
  292. func (a *Authority) authorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error) {
  293. p, err := a.authorizeToken(ctx, token)
  294. if err != nil {
  295. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRekey")
  296. }
  297. cert, signOpts, err := p.AuthorizeSSHRekey(ctx, token)
  298. if err != nil {
  299. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRekey")
  300. }
  301. return cert, signOpts, nil
  302. }
  303. // authorizeSSHRevoke authorizes an SSH certificate revoke request, by
  304. // validating the contents of an SSHPOP token.
  305. func (a *Authority) authorizeSSHRevoke(ctx context.Context, token string) error {
  306. p, err := a.authorizeToken(ctx, token)
  307. if err != nil {
  308. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRevoke")
  309. }
  310. if err = p.AuthorizeSSHRevoke(ctx, token); err != nil {
  311. return errs.Wrap(http.StatusInternalServerError, err, "authority.authorizeSSHRevoke")
  312. }
  313. return nil
  314. }