responder.go 12 KB

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