responder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // Package ocsp implements an OCSP responder based on a generic storage backend.
  2. // It provides a couple of sample implementations.
  3. // Because OCSP responders handle high query volumes, we have to be careful
  4. // about how much logging we do. Error-level logs are reserved for problems
  5. // internal to the server, that can be fixed by an administrator. Any type of
  6. // incorrect input from a user should be logged and Info or below. For things
  7. // that are logged on every request, Debug is the appropriate level.
  8. package ocsp
  9. import (
  10. "crypto/sha256"
  11. "encoding/base64"
  12. "encoding/hex"
  13. "errors"
  14. "fmt"
  15. "io/ioutil"
  16. "net/http"
  17. "net/url"
  18. "regexp"
  19. "time"
  20. "github.com/cloudflare/cfssl/certdb"
  21. "github.com/cloudflare/cfssl/log"
  22. "github.com/jmhodges/clock"
  23. "golang.org/x/crypto/ocsp"
  24. )
  25. var (
  26. malformedRequestErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x01}
  27. internalErrorErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x02}
  28. tryLaterErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x03}
  29. sigRequredErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x05}
  30. unauthorizedErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x06}
  31. // ErrNotFound indicates the request OCSP response was not found. It is used to
  32. // indicate that the responder should reply with unauthorizedErrorResponse.
  33. ErrNotFound = errors.New("Request OCSP Response not found")
  34. )
  35. // Source represents the logical source of OCSP responses, i.e.,
  36. // the logic that actually chooses a response based on a request. In
  37. // order to create an actual responder, wrap one of these in a Responder
  38. // object and pass it to http.Handle. By default the Responder will set
  39. // the headers Cache-Control to "max-age=(response.NextUpdate-now), public, no-transform, must-revalidate",
  40. // Last-Modified to response.ThisUpdate, Expires to response.NextUpdate,
  41. // ETag to the SHA256 hash of the response, and Content-Type to
  42. // application/ocsp-response. If you want to override these headers,
  43. // or set extra headers, your source should return a http.Header
  44. // with the headers you wish to set. If you don't want to set any
  45. // extra headers you may return nil instead.
  46. type Source interface {
  47. Response(*ocsp.Request) ([]byte, http.Header, error)
  48. }
  49. // An InMemorySource is a map from serialNumber -> der(response)
  50. type InMemorySource map[string][]byte
  51. // Response looks up an OCSP response to provide for a given request.
  52. // InMemorySource looks up a response purely based on serial number,
  53. // without regard to what issuer the request is asking for.
  54. func (src InMemorySource) Response(request *ocsp.Request) ([]byte, http.Header, error) {
  55. response, present := src[request.SerialNumber.String()]
  56. if !present {
  57. return nil, nil, ErrNotFound
  58. }
  59. return response, nil, nil
  60. }
  61. // DBSource represnts a source of OCSP responses backed by the certdb package.
  62. type DBSource struct {
  63. Accessor certdb.Accessor
  64. }
  65. // NewDBSource creates a new DBSource type with an associated dbAccessor.
  66. func NewDBSource(dbAccessor certdb.Accessor) Source {
  67. return DBSource{
  68. Accessor: dbAccessor,
  69. }
  70. }
  71. // Response implements cfssl.ocsp.responder.Source, which returns the
  72. // OCSP response in the Database for the given request with the expiration
  73. // date furthest in the future.
  74. func (src DBSource) Response(req *ocsp.Request) ([]byte, http.Header, error) {
  75. if req == nil {
  76. return nil, nil, errors.New("called with nil request")
  77. }
  78. aki := hex.EncodeToString(req.IssuerKeyHash)
  79. sn := req.SerialNumber
  80. if sn == nil {
  81. return nil, nil, errors.New("request contains no serial")
  82. }
  83. strSN := sn.String()
  84. if src.Accessor == nil {
  85. log.Errorf("No DB Accessor")
  86. return nil, nil, errors.New("called with nil DB accessor")
  87. }
  88. records, err := src.Accessor.GetOCSP(strSN, aki)
  89. // Response() logs when there are errors obtaining the OCSP response
  90. // and returns nil, false.
  91. if err != nil {
  92. log.Errorf("Error obtaining OCSP response: %s", err)
  93. return nil, nil, fmt.Errorf("failed to obtain OCSP response: %s", err)
  94. }
  95. if len(records) == 0 {
  96. return nil, nil, ErrNotFound
  97. }
  98. // Response() finds the OCSPRecord with the expiration date furthest in the future.
  99. cur := records[0]
  100. for _, rec := range records {
  101. if rec.Expiry.After(cur.Expiry) {
  102. cur = rec
  103. }
  104. }
  105. return []byte(cur.Body), nil, nil
  106. }
  107. // NewSourceFromFile reads the named file into an InMemorySource.
  108. // The file read by this function must contain whitespace-separated OCSP
  109. // responses. Each OCSP response must be in base64-encoded DER form (i.e.,
  110. // PEM without headers or whitespace). Invalid responses are ignored.
  111. // This function pulls the entire file into an InMemorySource.
  112. func NewSourceFromFile(responseFile string) (Source, error) {
  113. fileContents, err := ioutil.ReadFile(responseFile)
  114. if err != nil {
  115. return nil, err
  116. }
  117. responsesB64 := regexp.MustCompile("\\s").Split(string(fileContents), -1)
  118. src := InMemorySource{}
  119. for _, b64 := range responsesB64 {
  120. // if the line/space is empty just skip
  121. if b64 == "" {
  122. continue
  123. }
  124. der, tmpErr := base64.StdEncoding.DecodeString(b64)
  125. if tmpErr != nil {
  126. log.Errorf("Base64 decode error %s on: %s", tmpErr, b64)
  127. continue
  128. }
  129. response, tmpErr := ocsp.ParseResponse(der, nil)
  130. if tmpErr != nil {
  131. log.Errorf("OCSP decode error %s on: %s", tmpErr, b64)
  132. continue
  133. }
  134. src[response.SerialNumber.String()] = der
  135. }
  136. log.Infof("Read %d OCSP responses", len(src))
  137. return src, nil
  138. }
  139. // A Responder object provides the HTTP logic to expose a
  140. // Source of OCSP responses.
  141. type Responder struct {
  142. Source Source
  143. clk clock.Clock
  144. }
  145. // NewResponder instantiates a Responder with the give Source.
  146. func NewResponder(source Source) *Responder {
  147. return &Responder{
  148. Source: source,
  149. clk: clock.Default(),
  150. }
  151. }
  152. func overrideHeaders(response http.ResponseWriter, headers http.Header) {
  153. for k, v := range headers {
  154. if len(v) == 1 {
  155. response.Header().Set(k, v[0])
  156. } else if len(v) > 1 {
  157. response.Header().Del(k)
  158. for _, e := range v {
  159. response.Header().Add(k, e)
  160. }
  161. }
  162. }
  163. }
  164. // A Responder can process both GET and POST requests. The mapping
  165. // from an OCSP request to an OCSP response is done by the Source;
  166. // the Responder simply decodes the request, and passes back whatever
  167. // response is provided by the source.
  168. // Note: The caller must use http.StripPrefix to strip any path components
  169. // (including '/') on GET requests.
  170. // Do not use this responder in conjunction with http.NewServeMux, because the
  171. // default handler will try to canonicalize path components by changing any
  172. // strings of repeated '/' into a single '/', which will break the base64
  173. // encoding.
  174. func (rs Responder) ServeHTTP(response http.ResponseWriter, request *http.Request) {
  175. // By default we set a 'max-age=0, no-cache' Cache-Control header, this
  176. // is only returned to the client if a valid authorized OCSP response
  177. // is not found or an error is returned. If a response if found the header
  178. // will be altered to contain the proper max-age and modifiers.
  179. response.Header().Add("Cache-Control", "max-age=0, no-cache")
  180. // Read response from request
  181. var requestBody []byte
  182. var err error
  183. switch request.Method {
  184. case "GET":
  185. base64Request, err := url.QueryUnescape(request.URL.Path)
  186. if err != nil {
  187. log.Infof("Error decoding URL: %s", request.URL.Path)
  188. response.WriteHeader(http.StatusBadRequest)
  189. return
  190. }
  191. // url.QueryUnescape not only unescapes %2B escaping, but it additionally
  192. // turns the resulting '+' into a space, which makes base64 decoding fail.
  193. // So we go back afterwards and turn ' ' back into '+'. This means we
  194. // accept some malformed input that includes ' ' or %20, but that's fine.
  195. base64RequestBytes := []byte(base64Request)
  196. for i := range base64RequestBytes {
  197. if base64RequestBytes[i] == ' ' {
  198. base64RequestBytes[i] = '+'
  199. }
  200. }
  201. // In certain situations a UA may construct a request that has a double
  202. // slash between the host name and the base64 request body due to naively
  203. // constructing the request URL. In that case strip the leading slash
  204. // so that we can still decode the request.
  205. if len(base64RequestBytes) > 0 && base64RequestBytes[0] == '/' {
  206. base64RequestBytes = base64RequestBytes[1:]
  207. }
  208. requestBody, err = base64.StdEncoding.DecodeString(string(base64RequestBytes))
  209. if err != nil {
  210. log.Infof("Error decoding base64 from URL: %s", string(base64RequestBytes))
  211. response.WriteHeader(http.StatusBadRequest)
  212. return
  213. }
  214. case "POST":
  215. requestBody, err = ioutil.ReadAll(request.Body)
  216. if err != nil {
  217. log.Errorf("Problem reading body of POST: %s", err)
  218. response.WriteHeader(http.StatusBadRequest)
  219. return
  220. }
  221. default:
  222. response.WriteHeader(http.StatusMethodNotAllowed)
  223. return
  224. }
  225. b64Body := base64.StdEncoding.EncodeToString(requestBody)
  226. log.Debugf("Received OCSP request: %s", b64Body)
  227. // All responses after this point will be OCSP.
  228. // We could check for the content type of the request, but that
  229. // seems unnecessariliy restrictive.
  230. response.Header().Add("Content-Type", "application/ocsp-response")
  231. // Parse response as an OCSP request
  232. // XXX: This fails if the request contains the nonce extension.
  233. // We don't intend to support nonces anyway, but maybe we
  234. // should return unauthorizedRequest instead of malformed.
  235. ocspRequest, err := ocsp.ParseRequest(requestBody)
  236. if err != nil {
  237. log.Infof("Error decoding request body: %s", b64Body)
  238. response.WriteHeader(http.StatusBadRequest)
  239. response.Write(malformedRequestErrorResponse)
  240. return
  241. }
  242. // Look up OCSP response from source
  243. ocspResponse, headers, err := rs.Source.Response(ocspRequest)
  244. if err != nil {
  245. if err == ErrNotFound {
  246. log.Infof("No response found for request: serial %x, request body %s",
  247. ocspRequest.SerialNumber, b64Body)
  248. response.Write(unauthorizedErrorResponse)
  249. return
  250. }
  251. log.Infof("Error retrieving response for request: serial %x, request body %s, error: %s",
  252. ocspRequest.SerialNumber, b64Body, err)
  253. response.WriteHeader(http.StatusInternalServerError)
  254. response.Write(internalErrorErrorResponse)
  255. return
  256. }
  257. parsedResponse, err := ocsp.ParseResponse(ocspResponse, nil)
  258. if err != nil {
  259. log.Errorf("Error parsing response for serial %x: %s",
  260. ocspRequest.SerialNumber, err)
  261. response.Write(unauthorizedErrorResponse)
  262. return
  263. }
  264. // Write OCSP response to response
  265. response.Header().Add("Last-Modified", parsedResponse.ThisUpdate.Format(time.RFC1123))
  266. response.Header().Add("Expires", parsedResponse.NextUpdate.Format(time.RFC1123))
  267. now := rs.clk.Now()
  268. maxAge := 0
  269. if now.Before(parsedResponse.NextUpdate) {
  270. maxAge = int(parsedResponse.NextUpdate.Sub(now) / time.Second)
  271. } else {
  272. // TODO(#530): we want max-age=0 but this is technically an authorized OCSP response
  273. // (despite being stale) and 5019 forbids attaching no-cache
  274. maxAge = 0
  275. }
  276. response.Header().Set(
  277. "Cache-Control",
  278. fmt.Sprintf(
  279. "max-age=%d, public, no-transform, must-revalidate",
  280. maxAge,
  281. ),
  282. )
  283. responseHash := sha256.Sum256(ocspResponse)
  284. response.Header().Add("ETag", fmt.Sprintf("\"%X\"", responseHash))
  285. if headers != nil {
  286. overrideHeaders(response, headers)
  287. }
  288. // RFC 7232 says that a 304 response must contain the above
  289. // headers if they would also be sent for a 200 for the same
  290. // request, so we have to wait until here to do this
  291. if etag := request.Header.Get("If-None-Match"); etag != "" {
  292. if etag == fmt.Sprintf("\"%X\"", responseHash) {
  293. response.WriteHeader(http.StatusNotModified)
  294. return
  295. }
  296. }
  297. response.WriteHeader(http.StatusOK)
  298. response.Write(ocspResponse)
  299. }