Reputation: 11
I felt pretty confident with XSS prevention with an older setup we had on our site ... we were using OWASP's XSS mitigation functions for stroking out user supplied data from a database (we inject values into DB directly via prepared statements, no encoding takes place till output time) and printing it via (simplified for readability):
print "<li>";
print "<a href='page?id=".xssafe($row->TRUSTED_VALUE)."'>".xssafe($row->UNTRUSTED_VALUE)."</a>";
print "</li>";
For numerous reasons, scalability, pagination, flexibility, we're switching to an AJAX oriented scheme. Instead of printing out these LI blocks directly, we AJAX them in immediately on page load (technically $(document).ready()) and let the client via javascript & jQuery handle everything. I'm concerned about this approach as I've read a ton on the subject and am still not confident in how to maintain XSS security.
Our new setup is this:
$data['TRUSTED_VALUE'] = $row->TRUSTED_VALUE; // 123
$data['UNTRUSTED_VALUE'] = $row->UNTRUSTED_VALUE; // who knows?
header('Content-Type: application/json');
print json_encode($data);
<script src="show.js"></script>
$.ajax({
url: 'retrive.php',
dataType: 'json',
data: {page: pageNum},
success: loadLI
});
function loadLI() {
data = response.data;
var li = document.createElement('li');
var anchor = document.createElement('a');
anchor.setAttribute('href', 'page?id='+encodeURIComponent(data.TRUSTED_VALUE));
anchor.appendChild(document.createTextNode(data.UNTRUSTED_VALUE));
li.appendChild(anchor);
}
Should I keep the xssafe() wrapper functions in our retrieve.php script, then json_encode, then inject those values via Javascript? Or is our new setup safe? Or is there a better way to do this? Thanks.
Upvotes: 1
Views: 624
Reputation: 33578
What you're doing appears safe.
createTextNode
creates a text node on the page - JavaScript will handle the encoding internally for you.
setAttribute
will set an attribute on the page - the same applies here, the parameter is taken as a strongly typed value and it shouldn't be possible to escape it using malicious code.
Should I keep the xssafe() wrapper functions in our retrieve.php script, then json_encode
So, no.
Upvotes: 2