Can this tool crack or forge Flask session cookies?
What Flask session formats are supported?
Is Flask Unsign the same as the flask-unsign Python package?
The cookie value is quoted by the Werkzeug library to be safe for use in Cookie headers; this includes quoting any commas, semicolons, double quotes and backslashes:
cookie_quoting_map = {
b',' : b'\\054',
b';' : b'\\073',
b'"' : b'\\"',
b'\\' : b'\\\\',
}
Anything else outside of letters, digits and the characters !#%&'~_`><@,:/$*+-.^|)(?}{= is encoded to an octal codepoint as well. If there are any escaped values in the cookie, the whole cookie is also surrounded by double quotes.
If you need access to the cookie value in JavaScript, you'll have to decode this again. Values that start with a slash and 3 digits are octal values; a String.replace() call should do:
function decode_flask_cookie(val) {
if (val.indexOf('\\') === -1) {
return val; // not encoded
}
val = val.slice(1, -1).replace(/\\"/g, '"');
val = val.replace(/\\(\d{3})/g, function(match, octal) {
return String.fromCharCode(parseInt(octal, 8));
});
return val.replace(/\\\\/g, '\\');
}
Demo:
> // recreate properly escaped value
> var cookie = "\"{\\\"message\\\": \\\"hello\\\"\\054 \\\"type\\\": \\\"success\\\"}\""
> cookie
""{\"message\": \"hello\"\054 \"type\": \"success\"}""
> decode_flask_cookie(cookie)
"{"message": "hello", "type": "success"}"
> JSON.parse(decode_flask_cookie(cookie))
Object {message: "hello", type: "success"}
Dealing with the same issue today, but it seems the facts on the ground have changed.
First of all, sending the cookie back is as simple as:
cookie_str = json.dumps(mydictionary, separators=(',', ':'))
resp.set_cookie('cookiename', cookie_str, None, None, '/')
On the Javascript side, in browser, I read the cookie as follows using the js-cookies project:
var cookie2 = Cookies.noConflict();
var cookiejs = cookie2.getJSON('cookiename');
var one = ca.field1;
var two = ca.field2;
It does appear that the curly's are not getting escaped properly in my case. As a result, I have to find and replace the curley's with escaped versions \{ and \}. However, after that, instead of using getJSON, I had to resort to jquery's $.parseJSON() function, which returns a usable json object.
Still haven't figured out how to get the cookie json string to behave correctly without re-escaping the curley's on the javascript side. The escaping and jquery method is a little hacky... but it works.
Also I'm using Zappa-Flask in AWS Lambda, not sure if that is messing up my cookie.
» pip install flask-session-decoder
» pip install flask-cookie-decode