When you’re done, give it a thumbs up if it works for you

Java latest Xss attack and Protection (full 360° details)


Knowledge map

At the forefront of

Is XSS defense a front-end or back-end responsibility?

  1. XSS defense is the responsibility of the back-end RD (developer), which should escape sensitive characters on all interfaces where users submit data before proceeding to the next step.
  2. All data to be inserted into the page is escaped by a sensitive character filtering function. After filtering out common sensitive characters, the data can be inserted into the page.
  3. Company search page if you are written below. Then it might have Xss injection
<input type="text" value="<%= getParameter("keyword") % >">
<button>search</button>
<div><%= getParameter("keyword") %></div>
Copy the code

1. What is XSS attack?

Xss is called Cross Site Scripting. XSS focuses not on cross-site but on script execution.

1.1 the principle

Malicious code is unfiltered and mixed in with the site’s normal code; Browsers cannot tell which scripts are trusted, causing malicious scripts to be executed. Because it is executed directly on the user’s terminal, malicious code can directly obtain the user’s information, or use this information to impersonate the user to launch the request defined by the attacker to the website.

1.2 classification

Xss attacks are classified into reflective Xss(non-persistent), storage Xss(persistent), and DOM Xss.

1.2.1 Reflective Xss(Understanding)

  • The principle of

    Reflexive XSS usually means that an attacker lures a victim to a URL containing malicious code in a specific way. When the victim clicks on a malicious link URL, the malicious code is executed directly in the browser on the victim’s host.

  • steps

  1. The attacker adds malicious attack code to the parameter after the URL.
  2. When a user opens a URL with malicious code, the web server takes the malicious code out of the URL, splices it into HTML and returns it to the browser.
  3. The user’s browser parses the response and the malicious code is also executed.
  4. Attackers use malicious code to steal user data and send it to the attacker’s website. Attackers will obtain information such as cookies, and then use the information to pretend to be legitimate users, call the target website interface to perform attacks and other operations.
  • demo
<title>CSRF attacks</title>

<a href="http://localhost:3001/xss">XXS attack</a>
<a href="http://localhost:3001/testcookie">Testcookie attack</a>
Copy the code
// The first link can pop up the specified popover
router.get('/xss'.(ctx, next) = > {
  ctx.body = '';
});
// Get all current cookies
router.get('/testcookie'.(ctx, next) = > {
  console.log(ctx.cookies.get('connect.sid'));
  ctx.body = '<script>alert("'+ctx.cookies.get('connect.sid') +'")</script>';
  next();
});
Copy the code

1.2.2 Storage Xss(Understanding)

  • The principle of

Basically, malicious code is uploaded or stored on the server and executed the next time the victim browses a page containing the malicious code.

  • scenario

For example, I now create a blog site, and an attacker publishes an article on it, which reads as follows: ) If I do nothing with the article and save it to the database, the next time another user accesses the article, the server reads it from the database and responds to the client, the browser executes the script, and the attacker gets the user’s cookie. The cookie is then sent to the attacker’s server.

  • steps
  1. The attacker submits malicious code to the target website database.
  2. When a user opens a target site, the site server pulls the malicious code out of the database, splices it into HTML and returns it to the browser.
  3. When the user’s browser receives the response and parses it, the malicious code is also executed.
  4. Then after the malicious code is executed, it can obtain user data, such as the above cookie and other information, and then send the cookie to the attacker’s website. Then the attacker will get the cookie and then pretend to be the user, and call the target website interface and other illegal operations.

1.2.3 DOM-based Xss(Understanding)

  • The principle of

Our client JS can dynamically operate the page DOM node, such as inserting and modifying the content of the page. For example, the client extracts the data from the URL and executes it locally. If the data entered by the user on the client contains malicious JS scripts, but these scripts are not filtered, then our application is vulnerable to DOM-based Xss attacks.

  • steps
  1. An attacker constructs a special URL that may contain malicious code.
  2. The user opens a URL with malicious code.
  3. The user browser parses the response and executes it. The front end uses JS to fetch malicious code from the URL and execute it.
  4. When executed, malicious code steals user data and sends it to the attacker’s website, which then takes the data and impersonates the user. Calls the target web site interface to perform some of the attacker’s operations.
  • Attack code

  • Using document.write direct output causes the browser to parse malicious code

  • Using innerHTML direct output causes the browser to parse malicious code

  • Using the location/location. The href/location. The replace/iframe SRC XSS

<script type="text/javascript">
    var s = location.search;            // return the query part of the URL (? What follows)
    // For demonstration purposes, let's assume the URL looks like this
    / / http://127.0.0.1/xsstest.html? url=javascript:alert('xsstest');
    // Then the value of s is as follows:
    s = "? url=javascript:alert('xsstest')";
    s = s.substring(1, s.length);       // Return the entire query
    var url = "";                       // Define the variable URL
    if (s.indexOf("url=") > -1) {       // Check whether the URL is empty
      var pos = s.indexOf("url=") + 4;  // Filter out "URL =" characters
      url = s.substring(pos, s.length);  // Get the url parameter in the address bar
    } else {
      url = "Url parameter is empty";
    }
    document.write('url: <a href="' + url + '">"' + url + '"</a>'); 
</script>
Copy the code

2. What is the harm of Xss?

2.1 Hijacked Access

Hijacking access is to insert such code in malicious scripts, so the page will jump to baidu home page. When a non-persistent XSS appears under a domain like QQ.com, phishing links can be sent via [http://qq.com](ht…

2.2 Use cookies to achieve password-free login

Because stolen cookies need to be transmitted back to the attacker, a server is often required to receive stolen cookies.

2.3 Cooperate with CSRF attacks to complete malicious Requests

A Csrf attack is a malicious request made in your name (e.g. password change, bank transfer, etc.) without your permission

2.4 Other Hazards

  1. DOS (Denial of Service) client browser.
  2. Hang a horse
  3. Hijack user Web behavior, or even further infiltrate the Intranet.
  4. Delete target articles, maliciously tamper with data, impute blame.
  5. Worm type hangs a horse to attack, brush advertisement, brush clear amount, destroy online data
  6. Worm DDoS attacks.

3. Prevention measures

3.1 Two elements

XSS attacks have two main elements:

  1. The attacker submits malicious code (input filtering).
  2. The browser executes malicious code.

XSS attacks tend to require long strings for them to work, so some of the expected input can be defended by limiting the length to force truncation.

3.2 Prevention Plan

3.2.1 Input Filtering

  • For input such as
  • The second is coding. Some common symbols, such as <>, are encoded as they are typed, so that the browser does not interpret the tag and does not affect the display.

3.2.2 Preventing storage and reflection Xss attacks

There are two common approaches to prevent these vulnerabilities:

  • Change to pure front-end rendering, separating code from data.
  • Fully escape HTML.
3.2.2.1 Pure front-end rendering

Pure front-end rendering process:

  1. The browser first loads a static HTML that does not contain any business-related data.
  2. The browser then executes the JavaScript in the HTML.
  3. JavaScript loads the business data through Ajax and calls the DOM API to update it to the page.
3.2.2.2 escaped HTML

If concatenating HTML is necessary, you need to use a suitable escape library to adequately escape the insertion points of the HTML template.

There is usually only one rule for HTML escaping, which is to escape & < > “‘ /. This does provide some XSS protection, but it is not perfect:

So to improve Xss safeguards, we need to use more sophisticated escape strategies.

For example, in Java projects, the commonly used escape library is org.owasp. Encoder

3.2.3 Input length control

Untrusted input should be limited to a reasonable length. While you can’t completely prevent Xss from happening, you can make Xss attacks more difficult.

For explicit input types, such as numbers, urls, phone numbers, email addresses, and so on, input filtering is necessary.

3.2.4 Cookie security Settings

  • Http-only Cookie: Disables JavaScript from reading certain sensitive cookies. Attackers cannot steal these cookies after XSS injection.
    • Http-only: Only HTTP or HTTPS requests are allowed to read cookies. JS codes cannot read cookies (Document. Cookie will show that http-only cookies are automatically filtered out). Cookies are automatically sent when a request is sent.
    • Secure-only: only HTTPS requests are allowed to be read. Cookies are automatically sent when requests are sent.
    • Host-only: only websites with the same host domain name and domain Settings are allowed to access the cookie.

3.2.5 Security Verification

  • Verification code: Prevents scripts from posing as users to submit dangerous operations.

3.2.6 Enabling the CSP Webpage Security Policy

Content-security-policy stands for web Security Policy in Chinese,

CSP stands for Content Security Policy. Mainly used to prevent Xss attacks. Content-security-policy is a developer-defined Security Policy statement that specifies trusted sources of Content through responsibilities imposed by the CSP. The developer of a Content-security-Policy page can control the loading and execution of external resources throughout the page. For example, you can control which static resources under domain names can and cannot be loaded by the page. This greatly protects against scripting attacks from cross-site (different domain names)

We just need to set it in the meta property:<meta http-equiv="Content-Security-Policy" content=" default-src http: https: *.xxx.com 'self' 'unsafe-inline' ; style-src 'self' 'unsafe-inline' *.yyy.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' ; ">
Copy the code
  • Default-src sets a default value for all of the following rules
  • Script-src External script
  • Style – the SRC stylesheets
  • Img SRC image
  • Media-src Media files (audio and video)
  • Font-src Font file
  • Object-src plug-ins (such as Flash)
  • The child – SRC frame

3.2.7 Avoiding inline Events

OnLoad =” onLoad (‘{{data}}’)”, onClick=”go(‘{{action}}’)” It is safer to bind in JavaScript via the.addeventListener () event.

4. To summarize

Overall XSS defense is very complex and tedious, and we not only need to escape the data in all the places that need to be escaped. And to prevent redundant and error escape, to avoid normal user input garbled.

Although it is difficult to completely avoid XSS by technical means, we can summarize the following principles to reduce vulnerability:

  • Leveraging the template engineEnable the HTML escape function of the template engine. For example, in EJS, use as much as possible<%= data %>Rather than<%- data %>; In dot.js, use as much as possible{{! data }Rather than{{= data }; In FreeMarker, make sure the engine version is higher than 2.3.24 and the correct one is selectedfreemarker.core.OutputFormat.
  • Avoid inline eventsTry not to useonLoad="onload('{{data}}')",onClick="go('{{action}}')"This concatenation of inline events. It passes in JavaScript.addEventlistener()Event binding is more secure.
  • Avoid concatenated HTMLIt is dangerous to use spliced HTML in the front end. If the framework allows, use itcreateElement,setAttributeAnd so on. Or use a mature rendering framework such as Vue/React.
  • Keep your guard up when inserting DOM properties, links, etc.
  • Increasing the attack difficulty and reducing the attack consequence You can increase the attack difficulty and reduce the attack consequence by using CSP, input length configuration, and interface security measures.
  • Proactive detection and discovery can be used to find potential XSS vulnerabilities using XSS attack strings and automated scanning tools.

5. Real scenario (Search scenario)

One day, the company needs a search page and determines the content of the keywords based on the URL parameters

1. Original version

<input type="text" value="<%= getParameter("keyword") % >">
<button>search</button>
<div><%= getParameter("keyword") %></div>
Copy the code

When performing http://xxx/search? keyword=”>, the server will parse the request parameter keyword, “>, spliced into HTML and returned to the browser, the page will appear as follows, alert will pop up twice.

<input type="text" value=""><script>alert('XSS');</script>">
<button>search</button>
<div>Your search keywords are: "><script>alert('XSS');</script>
</div>
Copy the code

2. Xss escape attack

<input type="text" value="<%= escapeHTML(getParameter("keyword")) %>">
<button>search</button>
<div><%= escapeHTML(getParameter("keyword")) %></div>
Copy the code

EscapeHTML escape () according to the following rules: | | characters escaped character | | – | – | | and | and | | < | < | | > | > | | | “” | | ‘| | | | |

After processing the escape function, the browser finally receives the following response:

<input type="text" value="&quot;&gt;&lt;script&gt;alert(&#x27;XSS&#x27;);&lt;&#x2F;script&gt;">
<button>search</button>
<div>Your search terms are:&quot;&gt;&lt;script&gt;alert(&#x27;XSS&#x27;);&lt;&#x2F;script&gt;
</div>
Copy the code

Conclusion small

  • Typically, a page contains user input in a fixed container or property, which is presented as text.
  • Attackers use fragments of user input from these pages to concatenate specially formatted strings to break through the limitations of original locations and form code fragments.
  • Attackers inject scripts on target websites and make them run on users’ browsers, posing potential risks.
  • XSS attacks can be prevented by HTML escaping.

3. Xss filtering attack

When the request is: http://xxx/? Redirect_to = javascript: alert (‘ XSS)

<a href="<%= escapeHTML(getParameter("redirect_to")) %>"> jump...</a>
Copy the code

When the attack URL is http://xxx/? Redirect_to =javascript:alert(‘XSS’)

<a href="javascript:alert(&#x27;XSS&#x27;)">Jump...</a>
Copy the code

The code doesn’t execute immediately, but once the user clicks on the A TAB, the browser pops up with “XSS.”

Solution filtering

// Disallow urls starting with "javascript:"
xss = getParameter("redirect_to").startsWith('javascript:');
if(! xss) {<a href="<%= escapeHTML(getParameter("redirect_to") % >"> jump...</a>
} else {
  <a href="/ 404">Jump...</a>
}
Copy the code

4. Xss case attacks

When the request is: http://xxx/? Redirect_to = % 20 javascript: alert (‘ XSS)

%20javascript:alert(‘XSS’) becomes javascript:alert(‘XSS’) after URL parsing. This string begins with a space. In this way, the attacker can bypass the keyword rules of the back end and successfully complete the injection.

Solution whitelist

// Filter according to the project situation, prohibit "javascript:" links, illegal schemes, etc
allowSchemes = ["http"."https"];

valid = isValid(getParameter("redirect_to"), allowSchemes);

if (valid) {
  <a href="<%= escapeHTML(getParameter("redirect_to") % >"> jump...</a>
} else {
  <a href="/ 404">Jump...</a>
}
Copy the code

Big conclusion

  • In text embedded in HTML, malicious content is injected as script tags.
  • In inline JavaScript, concatenated data breaks through the original constraints (strings, variables, method names, etc.).
  • In tag attributes, malicious content includes quotes to override attribute values and inject other attributes or tags.
  • In the href, SRC and other attributes of the tag, containsjavascript:Executable code, etc.
  • Inject uncontrolled code in events such as onload, onError, and onClick.
  • In the style attribute and tag, contains similarbackground-image:url("javascript:..." );(newer versions of browsers are already defensible).
  • In the style attribute and tag, contains similarexpression(...)CSS expression code (newer versions of browsers are already defensible).

In short, if a developer inserts text into HTML without filtering it properly, it can easily create an injection vulnerability. Attackers can use vulnerabilities to construct malicious code instructions, and then use malicious code to harm data security.

6. Common XSS attack methods are attached

  • JavaScript injection
<SCRIPT SRC=http://3w.org/XSS/xss.js></SCRIPT>
Copy the code
  • IMG tags XSS
<IMG SRC=http://3w.org/XSS/xss.js/>
Copy the code
  • IMG tag Without semicolons and quotation marks
<IMG SRC=javascript:alert('XSS') >
Copy the code
  • HTML encoding (semicolon required)
<IMG SRC=javascript:alert("XSS") >
Copy the code
  • Swap code for filtered JavaScript
\ "; alert('XSS'); //Copy the code
  • End Title tag
</TITLE><SCRIPT>alert("XSS");</SCRIPT>
Copy the code
  • Iframe
<IFRAME SRC="javascript:alert('XSS');"></IFRAME>
Copy the code
  • DIV background-image
<DIV STYLE="background-image: url(javascript:alert('XSS'))">
Copy the code
  • Save/HTTP:
<A HREF="//www.google.com/">XSS</A>
Copy the code

Note: any improper place please correct