Best way to safely read query string parameters?

前端 未结 5 1710
余生分开走
余生分开走 2020-12-30 16:58

We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assig

相关标签:
5条回答
  • 2020-12-30 17:29

    you can use javascript's escape() and unescape() functions.

    0 讨论(0)
  • 2020-12-30 17:32

    Using a whitelist-approach would be better I guess. Avoid only stripping out "bad" things. Strip out anything except for what you think is "safe".

    Also I'd strongly encourage to do a HTMLEncode the Parameters. There should be plenty of Javascript functions that can this.

    0 讨论(0)
  • 2020-12-30 17:33

    Don't use escape and unescape, use decodeURIComponent. E.g.

    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;
    }
    

    and pass in document.location.search.

    As far as turning < into &lt;, that is not sufficient to make sure that the content can be safely injected into HTML without allowing script to run. Make sure you escape the following <, >, &, and ".

    It will not guarantee that the parameters were not spoofed. If you need to verify that one of your servers generated the URL, do a search on URL signing.

    0 讨论(0)
  • 2020-12-30 17:39

    Several things you should be doing:

    • Strictly whitelist your accepted values, according to type, format, range, etc
    • Explicitly blacklist certain characters (even though this is usually bypassable), IF your whitelist cannot be extremely tight.
    • Encode the values before output, if youre using Anti-XSS you already know that a simple HtmlEncode is not enough
    • Set the src property through the DOM - and not by generating HTML fragment
    • Use the dynamic value only as a querystring parameter, and not for arbitrary sites; i.e. hardcode the name of the server, target page, etc.
    • Is your site over SSL? If so, using a frame may cause inconsistencies with SSL UI...
    • Using named frames in general, can allow Frame Spoofing; if on a secure site, this may be a relevant attack vector (for use with phishing etc.)
    0 讨论(0)
  • 2020-12-30 17:44

    You can use regular expressions to validate that you have a P followed by 9 integers and that you have 15 alphanumeric values. I think that book that I have at my desk of RegEx has some examples in JavaScript to help you.

    Limiting the charset to only ASCII values will help, and follow all the advice above (whitelist, set src through DOM, etc.)

    0 讨论(0)
提交回复
热议问题