| 1 |
/* |
| 2 |
Package csrf (gorilla/csrf) provides Cross Site Request Forgery (CSRF) |
| 3 |
prevention middleware for Go web applications & services. |
| 4 |
|
| 5 |
It includes: |
| 6 |
|
| 7 |
* The `csrf.Protect` middleware/handler provides CSRF protection on routes |
| 8 |
attached to a router or a sub-router. |
| 9 |
|
| 10 |
* A `csrf.Token` function that provides the token to pass into your response, |
| 11 |
whether that be a HTML form or a JSON response body. |
| 12 |
|
| 13 |
* ... and a `csrf.TemplateField` helper that you can pass into your `html/template` |
| 14 |
templates to replace a `{{ .csrfField }}` template tag with a hidden input |
| 15 |
field. |
| 16 |
|
| 17 |
gorilla/csrf is easy to use: add the middleware to individual handlers with |
| 18 |
the below: |
| 19 |
|
| 20 |
CSRF := csrf.Protect([]byte("32-byte-long-auth-key")) |
| 21 |
http.HandlerFunc("/route", CSRF(YourHandler)) |
| 22 |
|
| 23 |
... and then collect the token with `csrf.Token(r)` before passing it to the |
| 24 |
template, JSON body or HTTP header (you pick!). gorilla/csrf inspects the form body |
| 25 |
(first) and HTTP headers (second) on subsequent POST/PUT/PATCH/DELETE/etc. requests |
| 26 |
for the token. |
| 27 |
|
| 28 |
Note that the authentication key passed to `csrf.Protect([]byte(key))` should be |
| 29 |
32-bytes long and persist across application restarts. Generating a random key |
| 30 |
won't allow you to authenticate existing cookies and will break your CSRF |
| 31 |
validation. |
| 32 |
|
| 33 |
Here's the common use-case: HTML forms you want to provide CSRF protection for, |
| 34 |
in order to protect malicious POST requests being made: |
| 35 |
|
| 36 |
package main |
| 37 |
|
| 38 |
import ( |
| 39 |
"fmt" |
| 40 |
"html/template" |
| 41 |
"net/http" |
| 42 |
|
| 43 |
"github.com/gorilla/csrf" |
| 44 |
"github.com/gorilla/mux" |
| 45 |
) |
| 46 |
|
| 47 |
var form = ` |
| 48 |
<html> |
| 49 |
<head> |
| 50 |
<title>Sign Up!</title> |
| 51 |
</head> |
| 52 |
<body> |
| 53 |
<form method="POST" action="/signup/post" accept-charset="UTF-8"> |
| 54 |
<input type="text" name="name"> |
| 55 |
<input type="text" name="email"> |
| 56 |
<!-- |
| 57 |
The default template tag used by the CSRF middleware . |
| 58 |
This will be replaced with a hidden <input> field containing the |
| 59 |
masked CSRF token. |
| 60 |
--> |
| 61 |
{{ .csrfField }} |
| 62 |
<input type="submit" value="Sign up!"> |
| 63 |
</form> |
| 64 |
</body> |
| 65 |
</html> |
| 66 |
` |
| 67 |
|
| 68 |
var t = template.Must(template.New("signup_form.tmpl").Parse(form)) |
| 69 |
|
| 70 |
func main() { |
| 71 |
r := mux.NewRouter() |
| 72 |
r.HandleFunc("/signup", ShowSignupForm) |
| 73 |
// All POST requests without a valid token will return HTTP 403 Forbidden. |
| 74 |
// We should also ensure that our mutating (non-idempotent) handler only |
| 75 |
// matches on POST requests. We can check that here, at the router level, or |
| 76 |
// within the handler itself via r.Method. |
| 77 |
r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST") |
| 78 |
|
| 79 |
// Add the middleware to your router by wrapping it. |
| 80 |
http.ListenAndServe(":8000", |
| 81 |
csrf.Protect([]byte("32-byte-long-auth-key"))(r)) |
| 82 |
// PS: Don't forget to pass csrf.Secure(false) if you're developing locally |
| 83 |
// over plain HTTP (just don't leave it on in production). |
| 84 |
} |
| 85 |
|
| 86 |
func ShowSignupForm(w http.ResponseWriter, r *http.Request) { |
| 87 |
// signup_form.tmpl just needs a {{ .csrfField }} template tag for |
| 88 |
// csrf.TemplateField to inject the CSRF token into. Easy! |
| 89 |
t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{ |
| 90 |
csrf.TemplateTag: csrf.TemplateField(r), |
| 91 |
}) |
| 92 |
} |
| 93 |
|
| 94 |
func SubmitSignupForm(w http.ResponseWriter, r *http.Request) { |
| 95 |
// We can trust that requests making it this far have satisfied |
| 96 |
// our CSRF protection requirements. |
| 97 |
fmt.Fprintf(w, "%v\n", r.PostForm) |
| 98 |
} |
| 99 |
|
| 100 |
Note that the CSRF middleware will (by necessity) consume the request body if the |
| 101 |
token is passed via POST form values. If you need to consume this in your |
| 102 |
handler, insert your own middleware earlier in the chain to capture the request |
| 103 |
body. |
| 104 |
|
| 105 |
You can also send the CSRF token in the response header. This approach is useful |
| 106 |
if you're using a front-end JavaScript framework like Ember or Angular, or are |
| 107 |
providing a JSON API: |
| 108 |
|
| 109 |
package main |
| 110 |
|
| 111 |
import ( |
| 112 |
"github.com/gorilla/csrf" |
| 113 |
"github.com/gorilla/mux" |
| 114 |
) |
| 115 |
|
| 116 |
func main() { |
| 117 |
r := mux.NewRouter() |
| 118 |
|
| 119 |
api := r.PathPrefix("/api").Subrouter() |
| 120 |
api.HandleFunc("/user/:id", GetUser).Methods("GET") |
| 121 |
|
| 122 |
http.ListenAndServe(":8000", |
| 123 |
csrf.Protect([]byte("32-byte-long-auth-key"))(r)) |
| 124 |
} |
| 125 |
|
| 126 |
func GetUser(w http.ResponseWriter, r *http.Request) { |
| 127 |
// Authenticate the request, get the id from the route params, |
| 128 |
// and fetch the user from the DB, etc. |
| 129 |
|
| 130 |
// Get the token and pass it in the CSRF header. Our JSON-speaking client |
| 131 |
// or JavaScript framework can now read the header and return the token in |
| 132 |
// in its own "X-CSRF-Token" request header on the subsequent POST. |
| 133 |
w.Header().Set("X-CSRF-Token", csrf.Token(r)) |
| 134 |
b, err := json.Marshal(user) |
| 135 |
if err != nil { |
| 136 |
http.Error(w, err.Error(), 500) |
| 137 |
return |
| 138 |
} |
| 139 |
|
| 140 |
w.Write(b) |
| 141 |
} |
| 142 |
|
| 143 |
If you're writing a client that's supposed to mimic browser behavior, make sure to |
| 144 |
send back the CSRF cookie (the default name is _gorilla_csrf, but this can be changed |
| 145 |
with the CookieName Option) along with either the X-CSRF-Token header or the gorilla.csrf.Token form field. |
| 146 |
|
| 147 |
In addition: getting CSRF protection right is important, so here's some background: |
| 148 |
|
| 149 |
* This library generates unique-per-request (masked) tokens as a mitigation |
| 150 |
against the BREACH attack (http://breachattack.com/). |
| 151 |
|
| 152 |
* The 'base' (unmasked) token is stored in the session, which means that |
| 153 |
multiple browser tabs won't cause a user problems as their per-request token |
| 154 |
is compared with the base token. |
| 155 |
|
| 156 |
* Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods |
| 157 |
(GET, HEAD, OPTIONS, TRACE) are the *only* methods where token validation is not |
| 158 |
enforced. |
| 159 |
|
| 160 |
* The design is based on the battle-tested Django |
| 161 |
(https://docs.djangoproject.com/en/1.8/ref/csrf/) and Ruby on Rails |
| 162 |
(http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html) |
| 163 |
approaches. |
| 164 |
|
| 165 |
* Cookies are authenticated and based on the securecookie |
| 166 |
(https://github.com/gorilla/securecookie) library. They're also Secure (issued |
| 167 |
over HTTPS only) and are HttpOnly by default, because sane defaults are |
| 168 |
important. |
| 169 |
|
| 170 |
* Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens |
| 171 |
and the one-time-pad used for masking them. |
| 172 |
|
| 173 |
This library does not seek to be adventurous. |
| 174 |
|
| 175 |
*/ |
| 176 |
package csrf |