Skip to content

Commit

Permalink
Make regex to find cookie value more restrictive (#138)
Browse files Browse the repository at this point in the history
The Javascript library searches `document.cookie` to find the CSRF token
value associated with the cookie named after the constant `CSRFP_TOKEN`
(in practice, this is `csrfp_token`). However, the regex does not define
what values may precede the token's name, meaning that a cookie such as
`BNES_csrfp_token` (as was set by the Barracuda WAF) set on the same
domain can be erroneously picked up instead of the correct `csrfp_token`
value.

This commit restricts the regex to only match if it is preceded by
either the start of the string (i.e. nothing) or a semicolon followed by
(a) any amount of whitespace, or (b) nothing, followed by the cookie's
name. This allows it to match if it is the only/first cookie in
`document.cookie` as well as if it follows another cookie in
`document.cookie`.
  • Loading branch information
johnmaguire committed Oct 16, 2020
1 parent cbd7f63 commit df629c8
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion js/csrfprotector.js
Expand Up @@ -44,7 +44,7 @@ var CSRFP = {
* @return {String} auth key from cookie.
*/
_getAuthKey: function () {
var regex = new RegExp(`${CSRFP.CSRFP_TOKEN}=([^;]+)(;|$)`);
var regex = new RegExp(`(?:^|;\s*)${CSRFP.CSRFP_TOKEN}=([^;]+)(;|$)`);
var regexResult = regex.exec(document.cookie);
if (regexResult === null) {
return null;
Expand Down

2 comments on commit df629c8

@pdziuba
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a missing backslash before 's' which makes the regexp fail if token is not at the start of the string.
IMHO this line should look like follows:
var regex = new RegExp((?:^|;\\s*)${CSRFP.CSRFP_TOKEN}=([^;]+)(;|$));

@JackyWong88
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also had an issue with this line as well. I added a backslash to fix the issue just as pdziuba stated.

Please sign in to comment.