6

If somebody can edit $("#field").val(), can they change the url property here to point to another location?

$.ajax({
  url: "http://mywebsite/script?param=" + $("#field").val(),
  dataType: "jsonp",
  success: function(response) {
      document.write(/*fields from response object*/);
  },
 });

If they can then my page is XSS vulnerable since the malicious location could return script tags in the response object. I want to know if any value of field could be used to change the AJAX url.

Update

My apologies, I have updated the question. The value is actually contained in a javascript variable and is not directly written by php (otherwise there is obviously XSS issues). Sorry.

Kevin
  • 71
  • 1
  • 1
  • 4

1 Answers1

14

Yes it is vulnerable, but not it the way you suspect. The attacker would not try modify the loaded URL, but to execute the code directly. For example:

$_GET['fname'] = '"+(function(){/*any_code_i_like*/})()+"';

will become:

$.ajax({
   url: "http://mywebsite/script?param="+(function(){/*any_code_i_like*/})()+""

and the code will execute even before requesting the URL with ajax. It's just an example, there are other vectors that would work here too. The simplest way to escape the parameter to prevent XSS in this context would be using urlencode() in PHP like this:

$.ajax({
  url: "http://mywebsite/script?param=<?php echo urlencode($_GET["fname"]); ?>"
  dataType: "jsonp",
  success: function(response) {
      document.write(/*fields from response object*/);
  },
 });

Also, take a look at OWASP XSS Prevention Cheat Sheet.

Update: After you updated the question - there is no XSS vulnerability here (you can't e.g. point the request to another domain), but the example is vulnerable to a different beast - HTTP parameter polution. It might not matter in this exact case, but imagine that the given parameter is:

a_valid_value&param=another_param_injected

The attacker is able to inject additional HTTP GET parameters which might be important for your application and might change the execution flow (e.g. parameter admin=1). You should get into habit of escaping/encoding everything coming from user input. In this modified case you should use Javascript encodeURIComponent function which prevents attacker from injecting '&','=' and '?':

"http://mywebsite/script?param=" + encodeURIComponent($("#field").val()),
Krzysztof Kotowicz
  • 4,068
  • 20
  • 30
  • Hi, thanks for answering my question. I actually realised that the input is not directly added by php, see update. – Kevin Jan 19 '12 at 21:57