Documentation
¶
Overview ¶
Package securecookie is a fast, efficient and safe cookie value encoder/decoder.
A secure cookie has its value ciphered and signed with a message authentication code. This prevents the remote cookie owner from knowing what information is stored in the cookie or modifying it. It also prevents an attacker from forging a fake securecookie.
What makes this secure cookie package different is that it is fast (faster than the Gorilla secure cookie), and the value encoding and decoding needs no heap allocations.
The intended use is to instantiate all secure cookie objects of your web site at program start up. In the following example "__Host-session" is the cookie name. The key is a byte sequence generated with the GenerateRandomKey() function. The same key must be used to retrieve the value.
obj, err := securecookie.New("__Host-session", key, securecookie.Params{
Path: "/", // cookie received for all URL paths
MaxAge: 3600, // cookie becomes invalid 3600
// seconds after it is set.
HTTPOnly: true, // disallow access by remote
// javascript code.
Secure: true, // cookie received only with HTTPS,
// never with HTTP.
SameSite: securecookie.Lax, // cookie not sent with most
// cross-site requests.
})
if err != nil {
// ...
}
A securecookie can also be instantiated as a global variable with the MustNew function. The function will panic if an error occurs.
var obj = securecookie.MustNew("__Host-session", key, securecookie.Params{
Path: "/",
MaxAge: 3600,
HTTPOnly: true,
Secure: true,
SameSite: securecookie.Lax,
})
A securecookie object is immutable. Its methods can be called from different goroutines. The Delete(), SetValue() and GetValues() methods are independent.
To set a cookie value, call the SetValue() method with a http.ResponseWriter w, and a value val as arguments.
var val = []byte("some value")
if err := obj.SetValue(w, val); err != nil {
// ...
}
A request may contain several cookies with the same name. Securecookie values are retrieved from an http.Request with the GetValues() method. The following example accepts the request only if all the valid values are equal.
var val []byte
var found bool
for _, res := range obj.GetValues(r.Cookies()) {
if res.Error != nil {
continue // ignore invalid or expired values
}
if found && !bytes.Equal(val, res.Value) {
// different valid values: reject the request
}
val, found = res.Value, true
}
if !found {
// no valid value
}
A securecookie is deleted by calling the Delete() method with the http.ResponseWriter w as argument.
if err := obj.Delete(w); err != nil {
// ...
}
Security recommendations ¶
Use the cookie name prefix "__Host-" for authentication or session cookies. User agents only accept such a cookie when it is set with Secure, without Domain, and with Path "/" by the host itself. Another host, like a sibling subdomain, or a network attacker, can then not set a cookie with the same name in the user agent (cookie tossing). Use the prefix "__Secure-" when the cookie must be shared with subdomains. New returns an error when the parameters don't satisfy the prefix requirements.
An attacker can't forge a valid value, but may set in the user agent a valid value obtained from its own session. Use GetValues and reject requests with different valid values, as shown above.
With MaxAge 0, the cookie has no Max-Age attribute and is a session cookie for the user agent. But the value has no expiration on the server side: a copied value is accepted forever. Use a MaxAge greater than 0 for authentication or session cookies.
Keep the key secret. Anyone knowing the key can read and forge values.
Index ¶
- Constants
- func GenerateRandomKey() ([]byte, error)
- func MustGenerateRandomKey() []byte
- type Obj
- func (o *Obj) Delete(w http.ResponseWriter) error
- func (o *Obj) Domain() string
- func (o *Obj) GetValue(dst []byte, r *http.Request) ([]byte, error)deprecated
- func (o *Obj) GetValueAndStamp(dst []byte, r *http.Request) ([]byte, time.Time, error)deprecated
- func (o *Obj) GetValues(cookies []*http.Cookie) []ValueResult
- func (o *Obj) HTTPOnly() bool
- func (o *Obj) MaxAge() int
- func (o *Obj) Name() string
- func (o *Obj) Path() string
- func (o *Obj) SameSite() int
- func (o *Obj) Secure() bool
- func (o *Obj) SetValue(w http.ResponseWriter, v []byte) error
- type Params
- type ValueResult
Constants ¶
const ( Undefined int = iota Lax None Strict )
Keywords used for parameter value.
const KeyLen = 32
KeyLen is the byte length of the key.
Variables ¶
This section is empty.
Functions ¶
func GenerateRandomKey ¶
GenerateRandomKey returns a random key of KeyLen bytes. Use hex.EncodeToString(key) to get the key as hexadecimal string, and hex.DecodeString(keyStr) to convert back from string to byte slice.
func MustGenerateRandomKey ¶ added in v1.1.0
func MustGenerateRandomKey() []byte
MustGenerateRandomKey returns a random key of KeyLen bytes. It calls GenerateRandomKey and panics if it returns an error.
Types ¶
type Obj ¶
type Obj struct {
// contains filtered or unexported fields
}
Obj is a validated cookie object.
func MustNew ¶
MustNew panics if New returns a non-nil error, otherwise returns a cookie object. The intended use is to instantiate the object as a global variable.
func New ¶
New instantiates a validated cookie object with the given cookie name, key and parameters.
A cookie name starting with the prefix "__Secure-" requires Secure to be true. A cookie name starting with the prefix "__Host-" requires Secure to be true, Domain to be empty and Path to be "/". User agents enforce these rules and ignore cookies that don't satisfy them. The prefixes are matched case-insensitively.
func (*Obj) Delete ¶
func (o *Obj) Delete(w http.ResponseWriter) error
Delete adds a request to delete the securecookie to the server response w. The user agent may ignore the request.
func (*Obj) GetValue
deprecated
GetValue returns the value of the first cookie with a matching name. The function uses the dst slice as storage if not nil and big enough.
Deprecated: a request may contain several cookies with the same name, for instance one set by another host (cookie tossing), and GetValue only decodes the first one. Use GetValues instead.
func (*Obj) GetValueAndStamp
deprecated
added in
v1.3.3
GetValueAndStamp appends the decoded securecookie value to dst. dst is allocated if nil, or grown if too small. Returns the value and the time stamp truncated to seconds when the cookie was generated and added to an http response with SetValue.
Deprecated: a request may contain several cookies with the same name, for instance one set by another host (cookie tossing), and GetValueAndStamp only decodes the first one. Use GetValues instead.
func (*Obj) GetValues ¶ added in v1.3.4
func (o *Obj) GetValues(cookies []*http.Cookie) []ValueResult
GetValues returns the values and stamp of cookies with a matching name in cookies, or nil if none. A request may contain multiple cookies with the same name, and cookies is usually r.Cookies(). For each returned value, Error is nil and Value holds the decoded value (nil when the value is empty), or Error is not nil and Value is nil.
func (*Obj) SameSite ¶ added in v1.3.0
SameSite returns the same site field value. Note that the value None is ignored when the cookie is not secure. When SameSite is undefined, the default is Lax.
type Params ¶
type Params struct {
Path string // Optional : URL path to which the cookie will be returned
Domain string // Optional : domain to which the cookie will be returned
MaxAge int // Optional : time offset in seconds from now, must be >= 0, 0 means no expiration on the server side
HTTPOnly bool // Optional : disallow access by remote javascript code
Secure bool // Optional : cookie is only sent through HTTPS connections
SameSite int // Optional : (None, Lax, or Strict) restrict cookie return (None requires Secure)
}
Params holds the optional cookie parameters.