-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
235 lines (214 loc) · 7.86 KB
/
handler.go
File metadata and controls
235 lines (214 loc) · 7.86 KB
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
// Package secure provides security utilities, CSP, HPKP, HSTS and other security wins.
package secure
import (
"bufio"
"fmt"
"net"
"net/http"
"time"
)
// HSTSPreloadMinAge is the lowest max age usable with HSTS preload. See https://hstspreload.org.
const HSTSPreloadMinAge = 10886400
// A handler provides a security handler.
type handler struct {
next http.Handler
options *Options
}
// Options represents security options.
type Options struct {
AllowedHosts []string // AllowedHosts indicates which fully qualified domain names are allowed to point to this server. If none are set, all are allowed.
CSP string // CSP contains Content Security Policy. See http://www.w3.org/TR/CSP and https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_Content_Security_Policy.
Frame string // FrameAllowed indicates whether or not a browser should be allowed to render a page in a frame, iframe or object. Default is FrameSameOrigin.
HPKP *HPKPOptions // HPKP contains the HTTP Public Key Pinning options.
HSTS *HSTSOptions // HPKP contains the HTTP Strict Transport Security options.
ReferrerPolicy string // ReferrerPolicy contains Referrer Policy. See https://www.w3.org/TR/referrer-policy.
XSSProtection string // XSSProtection can stop pages from loading when browser detects an XSS attack. Default is XSSProtectionBlock.
ForceSSL bool // ForceSSL indicates whether an insecure request must be redirected to the secure protocol.
EnvDevelopment bool // EnvDevelopment can be used during development to defuse AllowedHosts, HPKP, HSTS and ForceSSL options.
}
// HPKPOptions represents HTTP Public Key Pinning options.
// See RFC 7469 and https://developer.mozilla.org/en-US/docs/Web/Security/Public_Key_Pinning.
type HPKPOptions struct {
Keys []string // Keys contains the Base64 encoded Subject Public Key Information (SPKI) fingerprints. This field is required.
MaxAge time.Duration // MaxAge indicates how long the browser should remember that this site is only to be accessed using one of the pinned keys. This field is required.
IncludeSubdomains bool // IncludeSubdomains indicates whether HPKP applies to all of the site's subdomains as well.
ReportURI string // ReportURI is the URL at which validation failures are reported to.
}
// HSTSOptions represents HTTP Strict Transport Security options.
// See RFC 6797 and https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security.
type HSTSOptions struct {
MaxAge time.Duration // MaxAge indicates how long the browser should remember that this site is only to be accessed using HTTPS. This field is required.
IncludeSubdomains bool // IncludeSubdomains indicates whether HSTS applies to all of the site's subdomains as well.
Preload bool // Preload indicates whether the browsers must use a secure connection. It's not a standard. See https://hstspreload.appspot.com.
}
// Handle returns a Handler wrapping another http.Handler.
func Handle(h http.Handler, o *Options) http.Handler {
// Validate options (with required fields) from the beginning.
if o != nil {
if o.Frame == "" {
o.Frame = FrameSameOrigin
}
if o.HPKP != nil {
hpkpHeader(o)
}
if o.HSTS != nil {
hstsHeader(o)
}
if o.XSSProtection == "" {
o.XSSProtection = XSSProtectionBlock
}
}
return &handler{h, o}
}
// HandleFunc returns a Handler wrapping an http.HandlerFunc.
func HandleFunc(f http.HandlerFunc, o *Options) http.Handler {
return Handle(f, o)
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.options != nil {
if !h.options.EnvDevelopment {
if len(h.options.AllowedHosts) > 0 {
for _, host := range h.options.AllowedHosts {
if host == r.URL.Host {
goto SSLOptions
}
}
http.NotFound(w, r)
return
}
SSLOptions:
isSSL := r.URL.Scheme == "https" || r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https"
if !isSSL && h.options.ForceSSL {
r.URL.Scheme = "https"
http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently)
return
}
if isSSL && h.options.HPKP != nil {
w.Header().Set("Public-Key-Pins", hpkpHeader(h.options))
}
if h.options.HSTS != nil {
w.Header().Set("Strict-Transport-Security", hstsHeader(h.options))
}
}
if h.options.CSP != "" {
w.Header().Set("Content-Security-Policy", h.options.CSP)
w.Header().Set("X-Content-Security-Policy", h.options.CSP)
w.Header().Set("X-WebKit-CSP", h.options.CSP)
}
if h.options.ReferrerPolicy != "" {
w.Header().Add("Referrer-Policy", h.options.ReferrerPolicy)
}
}
// Good practice headers.
w.Header().Set("X-Frame-Options", string(h.options.Frame))
w.Header().Set("X-XSS-Protection", h.options.XSSProtection)
sw := &secureWriter{
ResponseWriter: w,
}
h.next.ServeHTTP(sw, r)
}
// secureWriter catches header writing to set security headers accordingly.
type secureWriter struct {
http.ResponseWriter
headerWritten bool
}
// Write sets the security headers accordingly to body.
func (sw *secureWriter) Write(b []byte) (int, error) {
if !sw.headerWritten {
if len(b) > 0 {
sw.Header().Set("X-Content-Type-Options", "nosniff")
}
sw.headerWritten = true
}
return sw.ResponseWriter.Write(b)
}
// CloseNotify implements the http.CloseNotifier interface.
// No channel is returned if CloseNotify is not implemented by an upstream response writer.
func (sw *secureWriter) CloseNotify() <-chan bool {
n, ok := sw.ResponseWriter.(http.CloseNotifier)
if !ok {
return nil
}
return n.CloseNotify()
}
// Flush implements the http.Flusher interface.
// Nothing is done if Flush is not implemented by an upstream response writer.
func (sw *secureWriter) Flush() {
f, ok := sw.ResponseWriter.(http.Flusher)
if ok {
f.Flush()
}
}
// Hijack implements the http.Hijacker interface.
// Error http.ErrNotSupported is returned if Hijack is not implemented by an upstream response writer.
func (sw *secureWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
h, ok := sw.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, http.ErrNotSupported
}
return h.Hijack()
}
// Push implements the http.Pusher interface.
// http.ErrNotSupported is returned if Push is not implemented by an upstream response writer or not supported by the client.
func (sw *secureWriter) Push(target string, opts *http.PushOptions) error {
p, ok := sw.ResponseWriter.(http.Pusher)
if !ok {
return http.ErrNotSupported
}
if opts == nil {
opts = new(http.PushOptions)
}
if opts.Header == nil {
opts.Header = make(http.Header)
}
if enc := opts.Header.Get("Accept-Encoding"); enc == "" {
opts.Header.Add("Accept-Encoding", "gzip")
}
return p.Push(target, opts)
}
func hpkpHeader(o *Options) (v string) {
if len(o.HPKP.Keys) == 0 {
panic("secure: at least one key must be set when using HPKP")
}
if o.HPKP.MaxAge == 0 {
panic("secure: max age must be set when using HPKP")
}
for _, key := range o.HPKP.Keys {
if v != "" {
v += "; "
}
v += fmt.Sprintf("pin-sha256=%q", key)
}
v += fmt.Sprintf("; %.f", o.HPKP.MaxAge.Seconds())
if o.HPKP.IncludeSubdomains {
v += "; includeSubdomains"
}
if o.HPKP.ReportURI != "" {
v += fmt.Sprintf("; report-uri=%q", o.HPKP.ReportURI)
}
return
}
func hstsHeader(o *Options) (v string) {
if !o.ForceSSL {
panic("secure: ForceSSL must be true when using HSTS")
}
if o.HSTS.MaxAge == 0 {
panic("secure: max age must be set when using HSTS")
}
if o.HSTS.Preload {
if o.HSTS.MaxAge < HSTSPreloadMinAge {
panic("secure: max age must be at least 18 weeks when using HSTS preload")
}
if !o.HSTS.IncludeSubdomains {
panic("secure: subdomains must be included when using HSTS preload")
}
}
v += fmt.Sprintf("%.f", o.HSTS.MaxAge.Seconds())
if o.HSTS.IncludeSubdomains {
v += "; includeSubdomains"
}
if o.HSTS.Preload {
v += "; preload"
}
return
}