Reputation: 311
Can we prevent a XSS attack by using a session every time the user has loaded the page?
This is my PHP code.
session_start();
if (isset($_GET["content"]) && isset($_GET["session"] && isset($_SESSION["code"])) {
if ($_SESSION["code"] == $_GET["session"]) {
echo $_GET["content"];
}
}
$code = rand(1000, 9000);
$_SESSION["code"] = $code;
echo(str_replace("{CODE}", $code, $html);
For example, this is the URL
http://example.com/index.php?content=xxxxx&session=GENERATED_SESSION
Where GENERATED_SESSION is the code added by my JavaScript code.
This is a page that will be loaded more times by a iframe, that code can prevent a XSS?
Upvotes: 1
Views: 497
Reputation: 1913
I think your attempting to prevent CSRF (Cross site request forgery) rather than XSS (Cross site scripting).
XSS is preventing people injecting malicious code into you're application e.g. if you have a blog with a comment form, someone could enter a JS <script></script>
tag into your comment box, so that when their comment is loaded on your blog, the JS is executed.
Your approach is a common approach to prevent CSRF (Although I'm not sure where JS comes into it).
An 'un-guessable' token is generated and stored in the session, the value of this token is rendered in a hidden form element within your form, and when someone submits your form, you should check that the value in the hidden field matches the value in the session, exactly as you are doing (Without the syntax errors :) ).
I would personally use a better mechanism for generating the token though, as the random number you are generating could potentially be "fluked".
On a side note, you should generally only use the GET method for a search/read request, so the CSRF protection wouldn't really protect anything, and you also need to consider what happens when the user refreshes the search.
Whenever you are changing something (i.e. create, update or delete) it's good practice to use the POST form method, but the same CSRF principle applies.
Upvotes: 3