search

Home  >  Q&A  >  body text

javascript - xss vulnerability problem

I would like to ask how to deal with the front-end issue of xss vulnerabilities?

PHPzPHPz2751 days ago713

reply all(5)I'll reply

  • 迷茫

    迷茫2017-05-16 13:10:53

    XSS (Cross-Site Script) attack is also called cross-site scripting attack. It is essentially an injection attack. Its principle is to use various means to add malicious code to the web page and let the victim execute it. script.

    xss attack method

    According to the attack methods, it can be divided into

    • Reflective type

    • Storage type

    • Document type

    This classification method is somewhat outdated. For a long time, people have believed that there are three types of XSS classifications, but in actual situations they often cannot be distinguished. Therefore, a more clear classification method can be divided into the following two categories:

    • client(client type)

    • server(server type)

    When the XSS code on one end is inserted on the server side, then this is server-side XSS. Similarly, if the code is inserted on the client side, it is client-side XSS.

    Prevent xss attacks

    escape

    Whether it is server-side or client-side XSS, two conditions are required to achieve the attack

    • Code is injected

    • The code is executed

    In fact, as long as you do a good job to ensure that the code is not executed under any circumstances, you can completely eliminate xss attacks.

    In short, do not insert untrusted data directly into any location in the dom at any time, be sure to escape it.

    For some locations, escaping untrusted data can ensure security

    • General tag attribute values

    • p body’s internal html

    For some positions, even if they are escaped, they are still unsafe

    • script tag

    • Annotating

    • Attribute name of table tag

    • tag name

    • css tag

    Use JSON.parse instead of eval, the content-type of the request must be specified as Content-Type: application/json;

    If part of the linked URL is dynamically generated, it must be escaped.

    Use the xss-filter that comes with the browser

    You can control whether to open xss-filter through http header, the default is open.

    Normally, adding the following fields to the http header means enabling xss-filter.

    X-XSS-Protection:1 (默认)
    X-XSS-Protection:1;mode=block (强制不渲染, chrome跳空白页,IE展示一个#号)

    If you need to disable xss-filter, set

    to 0.X-XSS-Protection

    As mentioned above, modern browsers have a certain degree of defense against reflected XSS. The principle is to check the correlation of elements in the URL and DOM. But this does not completely prevent reflective Door: XSS Test Page.

    In addition, browsers are not resistant to stored

    Content Security Policy

    Content Security Policy, namely content security policy, referred to as csp.

    In order to alleviate a large part of potential cross-site scripting problems, the browser extension system introduces CSP. CSP manages the content that the website is allowed to load, and uses a whitelist mechanism to act on the resources loaded or executed by the website. In the web page , such a policy is defined through HTTP header information or meta elements.

    CSP is not used to prevent XSS attacks, but to minimize the damage caused by XSS. In fact, apart from developers escaping XSS themselves, there is no other way to prevent XSS from happening. CSP can be said It is the most affordable thing that HTML5 brings to web security. So how to introduce CSP?

    1. via response header

    Only allow scripts to load Content-Security-Policy from the source: script-src ‘self’

    1. via HTML’s META tag

    Same as above<meta http-equiv=”Content-Security-Policy” content=”script-src ‘self’”>

    So besides restricting script-src, what else can CSP restrict?

    base-uri: limit the uri of this document

    child-src: Limit the source of child windows (iframe, pop-up windows, etc.), replacing frame-src

    connect-src: Limit the sources that the script can access

    font-src : limit font source

    form-action: Limit the sources to which the form can be submitted

    frame-ancestors: Limits which pages the current page can be loaded by iframe, frame, object, etc.

    frame-src: deprecated with child-src, which limits which sources the current page can load, corresponding to frame-ancestors

    img-src : Limit which sources images can be loaded from

    media-src: Limit which sources video, audio, source, and track can be loaded from

    object-src : Limits which sources plugins can be loaded from

    sandbox: Force open sandbox mode

    It can be seen that CSP is a powerful strategy that can limit the source of almost all resources that can be used. Using CSP well can greatly reduce the risks caused by XSS.

    In addition, CSP also provides a reporting header field Content-Security-Policy-Report-Only. Using this header field, the browser will report the CSP status to the server.

    Content-Security-Policy-Report-Only: script-src 'self'; report-uri http://cspReport/

    Using the above settings, if there is inline js on the page, it will still be executed, but the browser will send a post request containing the following information.

    { 
      "csp-report":
          { 
          "document-uri": "http://cspReport/test.php",
          "referrer": "",
          "violated-directive": "script-src 'self'",
          "original-policy": "script-src 'self'; report-uri http://cspReport/",
          "blocked-uri": ""
        }
    }

    CSP currently has two versions, CSP1 and CSP2. The support status of the two versions can be found at http://caniuse.com/#search=csp. As follows:

    CSP1 support

    CSP2 support

    Although CSP provides powerful security protection, it also causes the following problems: Eval and related functions are disabled, embedded JavaScript code will not be executed, and remote scripts can only be loaded through the whitelist.

    X-Frame-Options

    The

    X-Frame-Options response header is a tag used to indicate to the browser whether a page can be displayed in tags such as frame, iframe 或者 object. Websites can use this function to ensure that the content of their own website is not embedded in other people's websites. This also avoids clickjacking attacks. But it may be replaced by CSP frame-ancestors in the future. The current state of support is better than CSP frame-ancestors.

    X-Frame-Options has three values:

    • DENY means this page is not allowed to be loaded in frame

    • SAMEORIGIN means that this page is only allowed to be loaded by pages from the same source

    • ALLOW-FROM uri indicates that this page can only be loaded by a specific domain

    Server configuration

    java code:

    response.addHeader("x-frame-options","SAMEORIGIN");

    Nginx configuration:

    addheader X-Frame-Options SAMEORIGIN

    Apache configuration:

    Header always append X-Frame-Options SAMEORIGIN

    Browser Compatibility

    Features Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support 4.1.249.1042 3.6.9 (1.9.2.9) 8.0 10.5 4.0
    ALLOW-FROM support Not supported 18.0 8.0? ? Not supported

    Http-Only

    After using http-only, js can be prohibited from reading and writing cookies, which ensures that even if xss occurs, the user's cookies are safe.

    iframe sandbox environment

    HTML5 provides the security attribute sandbox for iframe, thereby limiting the capabilities of iframe. As follows:

    <iframe src="untrusted.html" sandbox="allow-scripts allow-forms"></iframe>

    Other security-related HTTP headers

    X-Content-Type-Options

    X-Content-Type-Options prevents the browser from content-type sniffing, which can prevent type sniffing attacks.

    This header is mainly used to prevent MIME type confusion attacks in IE9, Chrome and Safari. Usually the browser can determine what type it is by sniffing the content itself, rather than looking at the content-type value in the response. By Set X-Content-Type-Options: If the content-type matches the expected type, no sniffing is required and only resources of a certain type can be loaded from the outside. For example, if a stylesheet is loaded, then the MIME The type can only be text/css. For script resources in IE, the following content types are valid:

    application/ecmascript  
    application/javascript  
    application/x-javascript  
    text/ecmascript  
    text/javascript  
    text/jscript  
    text/x-javascript  
    text/vbs  
    text/vbscript  

    For chrome, the following MIME types are supported:

    text/javascript  
    text/ecmascript  
    application/javascript  
    application/ecmascript  
    application/x-javascript  
    text/javascript1.1  
    text/javascript1.2  
    text/javascript1.3  
    text/jscript  
    text/live script
    

    Correct settings

    nosniff – 这个是唯一正确的设置.

    Often incorrect settings

    ‘nosniff’ – 引号是不允许的
    : nosniff – 冒号也是错误的

    How to detect

    Open the developer tools in IE and chrome, and observe the difference in the output between nosniff configured and no nosniff configured in the console.

    HPKP(Public Key Pinning)

    HPKP is a response header, used to detect whether the public key of a certificate has changed to prevent man-in-the-middle attacks.

    We know that there are hundreds of trusted CAs (certificate authorities), and they have become a large attack surface in the entire website identity authentication process. The biggest problem with the existing certificate trust chain mechanism is that any one is trusted All CAs can issue site certificates for any website, and these certificates are legal in the eyes of browsers.

    HPKP technology gives us the right to proactively choose to trust the CA. Its working principle is to tell the browser the certificate fingerprint of the current website through the response header or the <meta> tag, as well as other information such as the expiration time. In the future, the browser will again Accessing this website must verify the certificate fingerprint in the certificate chain. If it does not match the previously specified value, even if the certificate itself is legitimate, the connection must be disconnected.

    The official HPKP document can be found in RFC7469, which is currently supported by Firefox 35+ and Chrome 38+. Its basic format is as follows:

    Public-Key-Pins: pin-sha256="base64=="; max-age=expireTime [; includeSubdomains][; report-uri="reportURI"]
    HSTS (HTTP Strict-Transport-Security)

    HSTS is a new Web security protocol being promoted by the International Internet Engineering Organization IETE, which can be used to resist man-in-the-middle attacks. It forces the browser to use TSL as the data channel, that is, it forces the use of HTTPS to create a connection with the server.

    The way for the server to enable HSTS is that when the client makes a request through HTTPS, the Strict-Transport-Security field is included in the Hypertext Transfer Protocol response header returned by the server. The HSTS field set during non-encrypted transmission is invalid.

    For example, the response header of https://xxx contains Strict-Transport-Security: max-age=31536000; includeSubDomains. This means two things:

    In the next year (that is, 31536000 seconds), whenever the browser sends an HTTP request to xxx or its subdomain name, it must use HTTPS to initiate the connection. For example, the user clicks a hyperlink or enters http:// in the address bar. xxx/, the browser should automatically convert http to https, and then send the request directly to https://xxx/.

    In the next year, if the TLS certificate sent by the xxx server is invalid, the user cannot ignore the browser warning and continue to access the website.

    The disadvantage is that the first time the user visits the website is not protected by HSTS. This is because the HSTS has not been received for the first time. There are two solutions. One is to preset the HSTS domain name list in the browser, which is implemented by Google Chrome, Firefox and Internet Explorer. This solution. The second is to add HSTS information to the domain name system record.

    Front-end xss filtering

    Finally, we provide a front-end xss filtering method

    function xssCheck(str,reg){
      return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
        if(b){
          return a;
        }else{
          return {
            '<':'<',
            '&':'&amp;',
            '"':'&quot;',
            '>':'>',
            "'":'&#39;',
          }[a]
        }
      }) : '';
    }

    You can directly read the original text of my blog for a better experience. A brief discussion on xss attack and defense

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:10:53

    What language is used to implement the server side? It is to replace the strings related to <script> in the content of the form

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:10:53

    -.- This must be processed by the backend. It seems to be the function htmlspecialchars in the frontend if it is written in js. It's best to wrap it in quotes. Prevent execution of js code.

    In addition, when passing parameters, you must be fault-tolerant and give a default value.

    reply
    0
  • PHPz

    PHPz2017-05-16 13:10:53

    The xss vulnerability is actually that the backend is injected or hijacked, and the frontend gets the malicious code to execute.

    The key is still the back-end problem. The front-end can do limited work.

    1. Just don’t eval things casually, especially when using jsonp across domains.

    2. Filter and adjust tags for user input. Of course, this backend is best filtered twice.

    3. Verify the requested data to prevent tampering.

    4. If you can use https, use it. This basically guarantees that the data will not be tampered with.

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 13:10:53

    Remember this sentence, security issues should never be done on the front end! ! !

    reply
    0
  • Cancelreply