I have to pass a jQuery plugin some data. I could either pass it a URL where it will use a GET request to fetch the data, or directly pass it an array which will eliminate one server request. The data in question is user provided and not sanitized upon database entry.
The below script doesn't show the plugin, but does show how I might pass the data to the client so it may be directly passed to the plugin. As seen, the dynamically generated JS approach is suspect to XSS, however, the Ajax/JSON approach doesn't seem to be.
For this scenario, how should the dynamically generated JavaScript approach be secured, and is there risk to the Ajax/JSON approach?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>XSS Testing</title>
<script src="getStuff.php?type=js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
console.log(stuff);
$.get( "getStuff.php", function( data ) {
console.log(data);
},'json');
});
</script>
</head>
<body>
</body>
</html>
getStuff.php
<?php
$getFromDB=array(
'Mary',
'x"];alert(\'xss2\');x=["x',
'John'
);
if(isset($_GET['type']) && $_GET['type']=='js') {
header('Content-Type: application/javascript;');
$s='var stuff=[';
foreach($getFromDB as $row) {
$s.='"'.$row.'",';
}
$s=substr($s, 0, -1).'];';
echo($s);
}
else {
header('Content-Type: application/json;');
echo(json_encode($getFromDB));
}
?>