Best way to read query string parameters safely?

We have a project that generates a piece of code that can be used for various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" iframe attribute.

For example, a page with the URL http: //oursite/Page.aspx? A = 1 & b = 2 will contain JavaScript in it to read the parameters "a" and "b", then JavaScript will set the "src" iframe attribute based on these parameters. For example, "<iframe src =" http: //someothersite/Page.aspx? A = 1 & b = 2 "/>"

We are currently doing this using server-side code that uses the Microsoft Anti Cross-Scripting library to verify settings. However, a new requirement has emerged that we need to use JavaScript and that it cannot use third-party JavaScript tools (such as jQuery or Prototype).

One of the ways I know is to replace any instances of "<", single quote, and double quote from parameters before using them, but for me this doesn't seem safe enough.

One of the parameters is always "P", followed by 9 integers. Another parameter is always 15 alphanumeric characters. (Thanks to Liam for suggesting this.)

Does anyone have any suggestions for us?

Thanks so much for your time.

+3
5

escape unescape, decodeURIComponent. .

function queryParameters(query) {
  var keyValuePairs = query.split(/[&?]/g);
  var params = {};
  for (var i = 0, n = keyValuePairs.length; i < n; ++i) {
    var m = keyValuePairs[i].match(/^([^=]+)(?:=([\s\S]*))?/);
    if (m) {
      var key = decodeURIComponent(m[1]);
      (params[key] || (params[key] = [])).push(decodeURIComponent(m[2]));
    }
  }
  return params;
}

.location.search.

< <, , HTML script. , <, > , &, ".

, . , URL-, URL.

+7

, . "" . , , "".

HTMLEncode . Javascript, .

+4

javascript escape() unescape().

+1

, :

  • , , ..
  • ( ), .
  • , Anti-XSS, , HtmlEncode .
  • src DOM - HTML
  • querystring, ; , ..
  • SSL? , SSL...
  • -; ( ..).
0

, P, 9 , 15 - . , , RegEx, JavaScript, .

Limiting the encoding to ASCII values ​​only will help and will follow all the recommendations above (white list, install src via DOM, etc.)

0
source

Source: https://habr.com/ru/post/1697472/


All Articles