authorize.go 5.4 KB

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