Debian Codegraph @

helpers.go

raw
1 package csrf
2
3 import (
4 "crypto/rand"
5 "crypto/subtle"
6 "encoding/base64"
7 "fmt"
8 "html/template"
9 "net/http"
10 "net/url"
11 )
12
13 // Token returns a masked CSRF token ready for passing into HTML template or
14 // a JSON response body. An empty token will be returned if the middleware
15 // has not been applied (which will fail subsequent validation).
16 func Token(r *http.Request) string {
17 if val, err := contextGet(r, tokenKey); err == nil {
18 if maskedToken, ok := val.(string); ok {
19 return maskedToken
20 }
21 }
22
23 return ""
24 }
25
26 // FailureReason makes CSRF validation errors available in the request context.
27 // This is useful when you want to log the cause of the error or report it to
28 // client.
29 func FailureReason(r *http.Request) error {
30 if val, err := contextGet(r, errorKey); err == nil {
31 if err, ok := val.(error); ok {
32 return err
33 }
34 }
35
36 return nil
37 }
38
39 // UnsafeSkipCheck will skip the CSRF check for any requests. This must be
40 // called before the CSRF middleware.
41 //
42 // Note: You should not set this without otherwise securing the request from
43 // CSRF attacks. The primary use-case for this function is to turn off CSRF
44 // checks for non-browser clients using authorization tokens against your API.
45 func UnsafeSkipCheck(r *http.Request) *http.Request {
46 return contextSave(r, skipCheckKey, true)
47 }
48
49 // TemplateField is a template helper for html/template that provides an <input> field
50 // populated with a CSRF token.
51 //
52 // Example:
53 //
54 // // The following tag in our form.tmpl template:
55 // {{ .csrfField }}
56 //
57 // // ... becomes:
58 // <input type="hidden" name="gorilla.csrf.Token" value="<token>">
59 func TemplateField(r *http.Request) template.HTML {
60 if name, err := contextGet(r, formKey); err == nil {
61 fragment := fmt.Sprintf(`<input type="hidden" name="%s" value="%s">`,
62 name, Token(r))
63
64 return template.HTML(fragment) // #nosec G203
65 }
66
67 return template.HTML("")
68 }
69
70 // mask returns a unique-per-request token to mitigate the BREACH attack
71 // as per http://breachattack.com/#mitigations
72 //
73 // The token is generated by XOR'ing a one-time-pad and the base (session) CSRF
74 // token and returning them together as a 64-byte slice. This effectively
75 // randomises the token on a per-request basis without breaking multiple browser
76 // tabs/windows.
77 func mask(realToken []byte, _ *http.Request) string {
78 otp, err := generateRandomBytes(tokenLength)
79 if err != nil {
80 return ""
81 }
82
83 // XOR the OTP with the real token to generate a masked token. Append the
84 // OTP to the front of the masked token to allow unmasking in the subsequent
85 // request.
86 return base64.StdEncoding.EncodeToString(append(otp, xorToken(otp, realToken)...))
87 }
88
89 // unmask splits the issued token (one-time-pad + masked token) and returns the
90 // unmasked request token for comparison.
91 func unmask(issued []byte) []byte {
92 // Issued tokens are always masked and combined with the pad.
93 if len(issued) != tokenLength*2 {
94 return nil
95 }
96
97 // We now know the length of the byte slice.
98 otp := issued[tokenLength:]
99 masked := issued[:tokenLength]
100
101 // Unmask the token by XOR'ing it against the OTP used to mask it.
102 return xorToken(otp, masked)
103 }
104
105 // requestToken returns the issued token (pad + masked token) from the HTTP POST
106 // body or HTTP header. It will return nil if the token fails to decode.
107 func (cs *csrf) requestToken(r *http.Request) ([]byte, error) {
108 // 1. Check the HTTP header first.
109 issued := r.Header.Get(cs.opts.RequestHeader)
110
111 // 2. Fall back to the POST (form) value.
112 if issued == "" {
113 issued = r.PostFormValue(cs.opts.FieldName)
114 }
115
116 // 3. Finally, fall back to the multipart form (if set).
117 if issued == "" && r.MultipartForm != nil {
118 vals := r.MultipartForm.Value[cs.opts.FieldName]
119
120 if len(vals) > 0 {
121 issued = vals[0]
122 }
123 }
124
125 // Return nil (equivalent to empty byte slice) if no token was found
126 if issued == "" {
127 return nil, nil
128 }
129
130 // Decode the "issued" (pad + masked) token sent in the request. Return a
131 // nil byte slice on a decoding error (this will fail upstream).
132 decoded, err := base64.StdEncoding.DecodeString(issued)
133 if err != nil {
134 return nil, err
135 }
136
137 return decoded, nil
138 }
139
140 // generateRandomBytes returns securely generated random bytes.
141 // It will return an error if the system's secure random number generator
142 // fails to function correctly.
143 func generateRandomBytes(n int) ([]byte, error) {
144 b := make([]byte, n)
145 _, err := rand.Read(b)
146 // err == nil only if len(b) == n
147 if err != nil {
148 return nil, err
149 }
150
151 return b, nil
152
153 }
154
155 // sameOrigin returns true if URLs a and b share the same origin. The same
156 // origin is defined as host (which includes the port) and scheme.
157 func sameOrigin(a, b *url.URL) bool {
158 return (a.Scheme == b.Scheme && a.Host == b.Host)
159 }
160
161 // compare securely (constant-time) compares the unmasked token from the request
162 // against the real token from the session.
163 func compareTokens(a, b []byte) bool {
164 // This is required as subtle.ConstantTimeCompare does not check for equal
165 // lengths in Go versions prior to 1.3.
166 if len(a) != len(b) {
167 return false
168 }
169
170 return subtle.ConstantTimeCompare(a, b) == 1
171 }
172
173 // xorToken XORs tokens ([]byte) to provide unique-per-request CSRF tokens. It
174 // will return a masked token if the base token is XOR'ed with a one-time-pad.
175 // An unmasked token will be returned if a masked token is XOR'ed with the
176 // one-time-pad used to mask it.
177 func xorToken(a, b []byte) []byte {
178 n := len(a)
179 if len(b) < n {
180 n = len(b)
181 }
182
183 res := make([]byte, n)
184
185 for i := 0; i < n; i++ {
186 res[i] = a[i] ^ b[i]
187 }
188
189 return res
190 }
191
192 // contains is a helper function to check if a string exists in a slice - e.g.
193 // whether a HTTP method exists in a list of safe methods.
194 func contains(vals []string, s string) bool {
195 for _, v := range vals {
196 if v == s {
197 return true
198 }
199 }
200
201 return false
202 }
203
204 // envError stores a CSRF error in the request context.
205 func envError(r *http.Request, err error) *http.Request {
206 return contextSave(r, errorKey, err)
207 }