forked from yuxki/dyocsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_handler.go
266 lines (231 loc) · 7.64 KB
/
cache_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package dyocsp
import (
"crypto"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"time"
"github.com/justinas/alice"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/yuxki/dyocsp/pkg/cache"
"github.com/yuxki/dyocsp/pkg/date"
"github.com/yuxki/dyocsp/pkg/db"
"golang.org/x/crypto/ocsp"
)
const GETMethodMaxRequestSize = 255
func handleHTTPMethod(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
case http.MethodGet:
if r.ContentLength > int64(GETMethodMaxRequestSize) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
h.ServeHTTP(w, r)
})
}
func handleOverMaxRequestBytes(max int) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if max > 0 {
if r.ContentLength > int64(max) {
w.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
}
h.ServeHTTP(w, r)
})
}
}
// CacheHandler is an implementation of the http.Handler interface.
// It is used to handle OCSP requests.
type CacheHandler struct {
cacheStore *cache.ResponseCacheStoreRO
responder *Responder
// spec CacheHandlerSpec
now date.Now
maxRequestBytes int
maxAge int
logger *zerolog.Logger
}
// CacheHandlerOption is type of an functional option for dyocsp.CacheHandler.
type CacheHandlerOption func(*CacheHandler)
// MaxRequestBytes defines the maximum size of a request in bytes. If the content
// of a request exceeds this parameter, the handler will respond with
// http.StatusRequestEntityTooLarge. Default value is 0, and if 0 or less than 0 is
// set, this option is ignored.
func WithMaxRequestBytes(max int) func(*CacheHandler) {
return func(c *CacheHandler) {
c.maxRequestBytes = max
}
}
// MaxAge defines the maximum age, in seconds, for a cached response as
// specified in the Cache-Control max-age directive.
// If the duration until the nextUpdate of a cached response exceeds MaxAge,
// the handler sets the response's Cache-Control max-age directive to that duration.
// Default value is 0. If less than 0 is set, the default value is used.
func WithMaxAge(max int) func(*CacheHandler) {
return func(c *CacheHandler) {
c.maxAge = max
}
}
// WithHandlerLogger sets logger. If not set, global logger is used.
func WithHandlerLogger(logger *zerolog.Logger) func(*CacheHandler) {
return func(c *CacheHandler) {
c.logger = logger
}
}
const (
DefaultMaxAge = 0
)
// NewCacheHandler creates a new instance of dyocsp.CacheHandler.
// It chains the following handlers before the handler that sends the OCSP response.
// (It uses 'https://github.com/justinas/alice' to chain the handlers.)
// - Send http.StatusMethodNotAllowed unless the request method is POST or Get.
// - Send http.StatusRequestEntityTooLarge if the size of the request
// exceeds the value of the variable spec.MaxRequestBytes..
func NewCacheHandler(
cacheStore *cache.ResponseCacheStoreRO,
responder *Responder,
chain alice.Chain,
opts ...CacheHandlerOption,
) http.Handler {
handler := CacheHandler{
cacheStore: cacheStore,
responder: responder,
now: date.NowGMT,
}
for _, opt := range opts {
opt(&handler)
}
if handler.maxAge < 0 {
handler.maxAge = DefaultMaxAge
}
if handler.logger == nil {
handler.logger = &log.Logger
}
chain = chain.Append(handleHTTPMethod)
chain = chain.Append(handleOverMaxRequestBytes(handler.maxRequestBytes))
return chain.Then(handler)
}
type invalidIssuerError struct {
reason string
}
func (e invalidIssuerError) Error() string {
return "Invalid issuer in request: " + e.reason
}
func verifyIssuer(req *ocsp.Request, responder *Responder) error {
// Check issuer is collect
switch req.HashAlgorithm {
case crypto.SHA1:
if !reflect.DeepEqual(req.IssuerNameHash, responder.IssuerNameHash.SHA1) {
return invalidIssuerError{fmt.Sprintf("IssuerNameHash not matched:%x", req.IssuerNameHash)}
}
if !reflect.DeepEqual(req.IssuerKeyHash, responder.IssuerKeyHash.SHA1) {
return invalidIssuerError{fmt.Sprintf("SubjectPublicKeyHash not matched:%x", req.IssuerKeyHash)}
}
default:
return invalidIssuerError{fmt.Sprintf("Unsupported hash algorithm:%d", req.HashAlgorithm)}
}
return nil
}
func addSuccessOCSPResHeader(w http.ResponseWriter, cache *cache.ResponseCache, nowT time.Time, cacheCtlMaxAge int) {
// Configured max-age cannot be over nextUpdate
maxAge := cacheCtlMaxAge
durToNext := cache.Template().NextUpdate.Sub(nowT)
if durToNext < time.Second*time.Duration(cacheCtlMaxAge) {
maxAge = int(durToNext / time.Second)
}
w.Header().Add("Cache-Control", fmt.Sprintf("max-age=%d, public, no-transform, must-revalidate", maxAge))
w.Header().Add("Last-Modified", cache.Template().ProducedAt.Format(http.TimeFormat))
w.Header().Add("Expires", cache.Template().NextUpdate.Format(http.TimeFormat))
w.Header().Add("Date", nowT.Format(http.TimeFormat))
w.Header().Add("ETag", cache.SHA1HashHexString())
}
var ErrUnexpectedHTTPMethod = errors.New("unexpected HTTP method")
// ServeHTTP handles an OCSP request with following steps.
// - Verify that the request is in the correct form of an OCSP request.
// If the request is Malformed, it sends ocsp.MalformedRequestErrorResponse.
// - Check if the issuer is correct.
// If the issuer is not valid, it sends ocsp.UnauthorizedErrorRespons.
// - Searche for a response cache using the serial number from the request.
// If the cache is not found, it sends ocsp.UnauthorizedErrorRespons.
//
// This Handler add headers Headers introduced in RFC5019.
// (https://www.rfc-editor.org/rfc/rfc5019#section-5)
func (c CacheHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Set logger attributes same as access log
logger := c.logger.With().Str("ip", r.RemoteAddr).Str("user_agent", r.UserAgent()).Logger()
var body []byte
var err error
switch r.Method {
case http.MethodGet:
reqPath := strings.TrimPrefix(r.URL.Path, "/")
logger.Debug().Err(err).Str("ocsp-request-path", reqPath).Msg("")
body, err = base64.StdEncoding.DecodeString(reqPath)
case http.MethodPost:
body, err = io.ReadAll(r.Body)
default:
err = ErrUnexpectedHTTPMethod
}
if err != nil {
logger.Error().Err(err).Msg("")
return
}
// Handle as OCSP request
w.Header().Add("Content-Type", "application/ocsp-response")
ocspReq, err := ocsp.ParseRequest(body)
if err != nil {
logger.Debug().Err(err).Bytes("ocsp-request-bytes", body).Msg("")
_, err = w.Write(ocsp.MalformedRequestErrorResponse)
if err != nil {
logger.Error().Err(err).Msg("")
}
return
}
logger = logger.With().Str("serial", ocspReq.SerialNumber.Text(db.SerialBase)).Logger()
logger.Debug().Msg("Received OCSP Request.")
// Check issuer is collect
err = verifyIssuer(ocspReq, c.responder)
if err != nil {
logger.Error().Err(err).Msg("")
_, err = w.Write(ocsp.UnauthorizedErrorResponse)
if err != nil {
logger.Error().Err(err).Msg("")
}
return
}
cache, ok := c.cacheStore.Get(ocspReq.SerialNumber)
if !ok {
logger.Error().Msgf("Request serial not matched.")
_, err = w.Write(ocsp.UnauthorizedErrorResponse)
if err != nil {
logger.Error().Err(err).Msg("")
}
return
}
nowT := c.now()
if nowT.After(cache.Template().NextUpdate) {
logger.Error().Msgf("nextUpdate of found cache is set in the past.")
_, err = w.Write(ocsp.UnauthorizedErrorResponse)
if err != nil {
logger.Error().Err(err).Msg("")
}
return
}
addSuccessOCSPResHeader(w, cache, nowT, c.maxAge)
_, err = cache.Write(w)
if err != nil {
logger.Error().Err(err).Msg("")
}
}