简体   繁体   中英

How to safely XSS encode untrusted data coming from PHP through AJAX injected into the DOM via javascript?

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):

show.php

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:

retrieve.php (I originally still had the xssafe() wrappers, but read that I should just use json_encode())

$data['TRUSTED_VALUE'] = $row->TRUSTED_VALUE; // 123
$data['UNTRUSTED_VALUE'] = $row->UNTRUSTED_VALUE; // who knows?
header('Content-Type: application/json');
print json_encode($data);

show.php

<script src="show.js"></script>

show.js

$.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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM