authorize.go 15 KB

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