Whilst it is impossible to spoof a Referer
in another user's browser, it is easy to spoof a lack-of-referrer (eg. using a meta-refresh), in addition to some user-agents not sending a Referer at all.
So either you allow missing-referrer and have non-watertight XSRF protection, or you require a referrer that matches your site, in which case you take a big hit to accessibility. That hit might be acceptable if the only person using the script is you, and you know you'll always be using a browser/firewall/proxy/etc combination that passes referrers through reliably. But for anything you expect other people to use, it's generally not a good idea.
Referer
is quite a weak anti-XSRF mechanism. Much better to use a per-user/event token issued by the server that must come back to the server to validate the submission.
$query = "SELECT * FROM users
WHERE name
= '$name'";
Potential SQL injection vulnerability. Please use mysql_real_escape_string
or parameterised queries.
input.setAttribute('name', 'add_bar');
input.setAttribute('value', '');
Don't use setAttribute
on HTML attributes. There are bugs in IE that stop it working in some cases, and there are some attributes that don't do what you think. For example, setting the value
attribute is not the same as setting the value
property. The property holds the current value of the form field; the attribute only holds the ‘default value’ of the field, to which it will be reset if an <input type="reset">
is used. This maps to the defaultValue
property. In some browsers, setting the default value also sets the value, but this is non-standard and not to be relied upon.
Use the DOM Level 1 HTML properties, they're both more readable and more reliable:
input.name= 'add_bar';
input.value= <?php echo json_encode(generate_session_token(), JSON_HEX_TAG); ?>;
Use json_encode
to create values for JavaScript literals. Although you can be sure an MD5-sum will not contain characters special to JS like '
or \
, or the </
sequence that ends a <script>
block (against which the HEX_TAG
argument is protecting), it's not the output template's job to know what the session token may contain. This is a safe way to output any string into a <script>
block.
See this question for an approach to generating anti-XSRF tokens that requires no extra token-storage in the session or database.