Working on a new project, I have recently been reading about security issues as I obviously want my application to be as secure as it can be. I was aware of issues when it comes to SQL injections and XSS a little, and I think I should be relatively safe on that side, using a function like the following one before treating any data from the "outside" :
Code: Select all
function ensure_type($type, $value)
{
switch ($type)
{
case 'string':
$value = htmlentities(trim((string)$value));
break;
case 'bool':
$value = ($value) ? TRUE : FALSE;
break;
case 'int':
default:
$value = (int)$value;
break;
}
return $value;
}I found that my app was not protected against such attacks at the moment, and decided to add the use of what I call a "session token." The idea would be that any request would need to have a valid session token include to be treated, otherwise resulting on a "invalid session" error. This token would be a randomly generated hash stored on server for like 15 minutes.
So when a user visits the site, he would first asks for a new session token, which then would be included in later requests. If a request doesn't have such a token, or after 15 minutes of inactivity and that token has been "dropped" by server/became invalid, no action could be done without first asking for a new session token to be generated. That way, for a request to be allowed to do some action, the server would need a valid POST request with the right user-authentication cookie as well as a recently server-generated session token, which from what I understand should prevent most (or a good deal) of possible CSRF attacks.
However, when thinking about it and how I would implement dealing with this whole thing for my users, it seemed to me that if an attacker was able to manage to get a user of the site to click on a malicious link from the attacker's page or something (which is pretty much at the start of all/most CSRF attacks if I got it right), it could still be "bypassed" using a little Ajax : when the user clicks on the link, an Ajax request is generated to the server, asking for a new session token. It then gets said token, and sends another request which then, unless I'm missing something, could be POST, have a valid session token, and since generated by Ajax from the user's browser would include the user's cookies for my site... in other words, on my end (server) it looks like a perfectly valid request that should be processed.
Leading to my question : am I wrong/missing something in that scenario, making it actually impossible to happen ? And if not, I can't seem to find of a good way to prevent that, since it can't come (from what I'm seeing) from either a cookie of a recently generated random hash (my "session token"), so what else could/should I do?
Thanks for any help/information,
-jacky