4
0

authorize.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package authority
  2. import (
  3. "crypto/x509"
  4. "encoding/asn1"
  5. "net/http"
  6. "net/url"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/cli/crypto/x509util"
  10. "gopkg.in/square/go-jose.v2/jwt"
  11. )
  12. type idUsed struct {
  13. UsedAt int64 `json:"ua,omitempty"`
  14. Subject string `json:"sub,omitempty"`
  15. }
  16. // Claims extends jwt.Claims with step attributes.
  17. type Claims struct {
  18. jwt.Claims
  19. SANs []string `json:"sans,omitempty"`
  20. }
  21. // matchesAudience returns true if A and B share at least one element.
  22. func matchesAudience(as, bs []string) bool {
  23. if len(bs) == 0 || len(as) == 0 {
  24. return false
  25. }
  26. for _, b := range bs {
  27. for _, a := range as {
  28. if b == a || stripPort(a) == stripPort(b) {
  29. return true
  30. }
  31. }
  32. }
  33. return false
  34. }
  35. // stripPort attempts to strip the port from the given url. If parsing the url
  36. // produces errors it will just return the passed argument.
  37. func stripPort(rawurl string) string {
  38. u, err := url.Parse(rawurl)
  39. if err != nil {
  40. return rawurl
  41. }
  42. u.Host = u.Hostname()
  43. return u.String()
  44. }
  45. // Authorize authorizes a signature request by validating and authenticating
  46. // a OTT that must be sent w/ the request.
  47. func (a *Authority) Authorize(ott string) ([]interface{}, error) {
  48. var (
  49. errContext = map[string]interface{}{"ott": ott}
  50. claims = Claims{}
  51. )
  52. // Validate payload
  53. token, err := jwt.ParseSigned(ott)
  54. if err != nil {
  55. return nil, &apiError{errors.Wrapf(err, "authorize: error parsing token"),
  56. http.StatusUnauthorized, errContext}
  57. }
  58. // Get claims w/out verification. We need to look up the provisioner
  59. // key in order to verify the claims and we need the issuer from the claims
  60. // before we can look up the provisioner.
  61. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  62. return nil, &apiError{err, http.StatusUnauthorized, errContext}
  63. }
  64. kid := token.Headers[0].KeyID // JWT will only have 1 header.
  65. if len(kid) == 0 {
  66. return nil, &apiError{errors.New("authorize: token KeyID cannot be empty"),
  67. http.StatusUnauthorized, errContext}
  68. }
  69. pid := claims.Issuer + ":" + kid
  70. val, ok := a.provisionerIDIndex.Load(pid)
  71. if !ok {
  72. return nil, &apiError{errors.Errorf("authorize: provisioner with id %s not found", pid),
  73. http.StatusUnauthorized, errContext}
  74. }
  75. p, ok := val.(*Provisioner)
  76. if !ok {
  77. return nil, &apiError{errors.Errorf("authorize: invalid provisioner type"),
  78. http.StatusInternalServerError, errContext}
  79. }
  80. if err = token.Claims(p.Key, &claims); err != nil {
  81. return nil, &apiError{err, http.StatusUnauthorized, errContext}
  82. }
  83. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  84. // more than a few minutes.
  85. if err = claims.ValidateWithLeeway(jwt.Expected{
  86. Issuer: p.Name,
  87. }, time.Minute); err != nil {
  88. return nil, &apiError{errors.Wrapf(err, "authorize: invalid token"),
  89. http.StatusUnauthorized, errContext}
  90. }
  91. // Do not accept tokens issued before the start of the ca.
  92. // This check is meant as a stopgap solution to the current lack of a persistence layer.
  93. if a.config.AuthorityConfig != nil && !a.config.AuthorityConfig.DisableIssuedAtCheck {
  94. if claims.IssuedAt > 0 && claims.IssuedAt.Time().Before(a.startTime) {
  95. return nil, &apiError{errors.New("token issued before the bootstrap of certificate authority"),
  96. http.StatusUnauthorized, errContext}
  97. }
  98. }
  99. if !matchesAudience(claims.Audience, a.audiences) {
  100. return nil, &apiError{errors.New("authorize: token audience invalid"), http.StatusUnauthorized,
  101. errContext}
  102. }
  103. if claims.Subject == "" {
  104. return nil, &apiError{errors.New("authorize: token subject cannot be empty"),
  105. http.StatusUnauthorized, errContext}
  106. }
  107. // NOTE: This is for backwards compatibility with older versions of cli
  108. // and certificates. Older versions added the token subject as the only SAN
  109. // in a CSR by default.
  110. if len(claims.SANs) == 0 {
  111. claims.SANs = []string{claims.Subject}
  112. }
  113. dnsNames, ips := x509util.SplitSANs(claims.SANs)
  114. if err != nil {
  115. return nil, err
  116. }
  117. signOps := []interface{}{
  118. &commonNameClaim{claims.Subject},
  119. &dnsNamesClaim{dnsNames},
  120. &ipAddressesClaim{ips},
  121. p,
  122. }
  123. // Store the token to protect against reuse.
  124. if _, ok := a.ottMap.LoadOrStore(claims.ID, &idUsed{
  125. UsedAt: time.Now().Unix(),
  126. Subject: claims.Subject,
  127. }); ok {
  128. return nil, &apiError{errors.Errorf("token already used"), http.StatusUnauthorized,
  129. errContext}
  130. }
  131. return signOps, nil
  132. }
  133. // authorizeRenewal tries to locate the step provisioner extension, and checks
  134. // if for the configured provisioner, the renewal is enabled or not. If the
  135. // extra extension cannot be found, authorize the renewal by default.
  136. //
  137. // TODO(mariano): should we authorize by default?
  138. func (a *Authority) authorizeRenewal(crt *x509.Certificate) error {
  139. errContext := map[string]interface{}{"serialNumber": crt.SerialNumber.String()}
  140. for _, e := range crt.Extensions {
  141. if e.Id.Equal(stepOIDProvisioner) {
  142. var provisioner stepProvisionerASN1
  143. if _, err := asn1.Unmarshal(e.Value, &provisioner); err != nil {
  144. return &apiError{
  145. err: errors.Wrap(err, "error decoding step provisioner extension"),
  146. code: http.StatusInternalServerError,
  147. context: errContext,
  148. }
  149. }
  150. // Look for the provisioner, if it cannot be found, renewal will not
  151. // be authorized.
  152. pid := string(provisioner.Name) + ":" + string(provisioner.CredentialID)
  153. val, ok := a.provisionerIDIndex.Load(pid)
  154. if !ok {
  155. return &apiError{
  156. err: errors.Errorf("not found: provisioner %s", pid),
  157. code: http.StatusUnauthorized,
  158. context: errContext,
  159. }
  160. }
  161. p, ok := val.(*Provisioner)
  162. if !ok {
  163. return &apiError{
  164. err: errors.Errorf("invalid type: provisioner %s, type %T", pid, val),
  165. code: http.StatusInternalServerError,
  166. context: errContext,
  167. }
  168. }
  169. if p.Claims.IsDisableRenewal() {
  170. return &apiError{
  171. err: errors.Errorf("renew disabled: provisioner %s", pid),
  172. code: http.StatusUnauthorized,
  173. context: errContext,
  174. }
  175. }
  176. return nil
  177. }
  178. }
  179. return nil
  180. }