1. xss

XSS stands for Cross Site Script. Originally abbreviated as CSS, it is called XSS in the security world to distinguish it from Cascading Style Sheets.

XSS attack refers to an attack in which an attacker injects malicious client code into a website and tampers the client’s web page through malicious scripts, so as to control the user’s browser or obtain the user’s private data when browsing the web page.

Malicious scripts that attackers inject into client web pages usually include JavaScript, but sometimes also HTML and Flash. There are many ways to carry out XSS attacks, but they all have in common: sending private data such as cookies and sessions to the attacker, redirecting the victim to a website controlled by the attacker, and performing malicious operations on the victim’s machine.

XSS attacks can be divided into three categories: reflective (non-persistent), storage (persistent), and DOM based.

1.1 reflective

Reflective XSS simply “reflects” the data entered by the user back to the browser. This type of attack usually requires the attacker to trick the user into clicking on a malicious link, or submitting a form, or injecting a script into a malicious site when entering it.

Look at an example. I will prepare a static page as follows:

The malicious link addresses localhost:8001/? Q = 111 & p = 222. Then, I start a simple Node service to handle requests for malicious links:

const http = require('http'); function handleReequest(req, res) { res.setHeader('Access-Control-Allow-Origin', '*'); res.writeHead(200, {'Content-Type': 'text/html; charset=UTF-8'}); Res.write ('<script>alert(" reflex XSS attack ")</script>'); res.end(); } const server = new http.Server(); Server. Listen (8001, '127.0.0.1); server.on('request', handleReequest);Copy the code

When the user clicks the malicious link, the page is redirected to the page prepared by the attacker, and the js script is executed on the attacker’s page:

This creates a reflexive XSS attack. Depending on the attacker’s purpose, an attacker can inject any malicious script to attack, either a hoax script or a script that can capture a user’s private data, such as cookies.

1.2 the storage type

Stored XSS “stores” user-input data on the server side, where scripts are returned and executed when the browser requests the data. This XSS attack is very stable.

A common scenario is that an attacker writes an article or comment on a community or forum that contains malicious JavaScript code. After the article or comment is published, all users who visit the article or comment will execute the malicious JavaScript code in their browser.

Take an example.

Prepare an input page:

<input type="text" id="input"> <button id="btn">Submit</button> <script> const input = document.getElementById('input');  const btn = document.getElementById('btn'); let val; input.addEventListener('change', (e) => { val = e.target.value; },false); btn.addEventListener('click', (e) => { fetch('http://localhost:8001/save', { method: 'POST', body: val }); }, false); </script>Copy the code

Start a Node service to listen for save requests. To simplify, use a variable to hold user input:

const http = require('http'); let userInput = ''; function handleReequest(req, res) { const method = req.method; res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type') if (method === 'POST' && req.url === '/save'){ let body = ''; req.on('data',chunk => { body += chunk; }); req.on('end', () => { if (body) { userInput = body; } res.end(); }); } else { res.writeHead(200, {'Content-Type': 'text/html; charset=UTF-8'}); res.write(userInput); // Return the input script content to the front-end page res.end(); } } const server = new http.Server(); Server. Listen (8001, '127.0.0.1); server.on('request', handleReequest);Copy the code

When the user clicks the submit button to submit the input to the server, the server saves the input through the userInput variable. When the user accesses http://localhost:8001/${id}, the server returns the content corresponding to the ID (this example simplifies processing). If a user enters malicious script content, the malicious script will be executed on the browser side when other users access the content:

1.3 based on DOM

Dom-based XSS attacks are client-side attacks that modify the DOM structure of a page through malicious scripts.

Look at the following code:

<h2>XSS: </h2>
<input type="text" id="input">
<button id="btn">Submit</button>
<div id="div"></div>
<script>
    const input = document.getElementById('input');
    const btn = document.getElementById('btn');
    const div = document.getElementById('div');
    let val;
    input.addEventListener('change', (e) => {
        val = e.target.value;
    }, false);
    btn.addEventListener('click', () => {
        div.innerHTML = `<a href=${val}>testLink</a>`
    }, false);
</script>
Copy the code

Clicking the Submit button inserts a link to the current page with the user’s input. If the user constructs the following as input:

'' onclick=alert(/xss/)
Copy the code

After the user submits, the page code becomes:

<a href onlick="alert(/xss/)">testLink</a>
Copy the code

At this point, the user clicks on the generated link and the corresponding script is executed:

2.XSS attack defense

Mainstream browsers now have built-in safeguards against XSS, such as CSP. But it is also important for developers to find reliable solutions to prevent XSS attacks.

2.1 HttpOnly prevents Cookie hijacking

HttpOnly was first proposed by Microsoft and has since become a standard. The browser will prohibit the page’s Javascript from accessing the Cookie with the HttpOnly attribute.

As mentioned above, attackers can obtain users’ Cookie information by injecting malicious scripts. Cookies usually contain user login credentials. After obtaining cookies, attackers can launch Cookie hijacking attacks. So, strictly speaking, HttpOnly does not prevent XSS attacks, but rather prevents cookiehijacking attacks after XSS attacks.

2.2 Input Check

Don’t trust any input from the user. Any input from the user is checked, filtered, and escaped. Creates a trusted whitelist of characters and HTML tags, and filters or encodes characters or tags that are not in the whitelist.

In XSS defense, input check is generally used to check whether special characters such as <, > are contained in the data entered by users. If so, special characters are filtered or encoded. This method is also called XSS Filter.

In some front-end frameworks, there is a decodingMap, which is used to encode or filter special characters or tags contained in user input, such as <, >, script, to prevent XSS attacks:

Const decodingMap = {'&lt; const decodingMap = {'&lt; const decodingMap = {'&lt; ': '<', '&gt; ': '>', '&quot; ': '"', '&amp; ': '&', ' ': '\n' }Copy the code

2.3 Output Check

There will be problems with the user’s input, and problems with the server’s output. In general, with the exception of rich text output, you can use encoding or escaping to defend against XSS attacks when a variable is output to an HTML page. For example, sanitize-HTML is used to filter the output regularly and then output it to the page.

3.CSRF

CSRF, or Cross Site Request Forgery, is an attack that jacks a trusted user to send an unexpected Request to the server.

Under normal circumstances, CSRF attack means that the attacker uses the victim’s Cookie to win the trust of the server and sends forged requests to the attacked server in the victim’s name without the victim’s knowledge, so as to perform operations under permission protection without authorization.

Before I give you an example, let’s talk about the browser’s Cookie policy

3.1 Cookie Policy of the Browser

A Cookie is a small piece of data that the server sends to the user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server. Cookies are mainly used for the following three aspects:

  • Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
  • Personalization (such as user-defined Settings, themes, etc.)
  • Personalization (such as user-defined Settings, themes, etc.)

There are two types of cookies held by browsers:

  • Session Cookie: The Session Cookie is the simplest Cookie. It does not need to specify an expiration date or max-age. It is only valid during the Session and is automatically deleted after the browser closes.
  • Permanent Cookie: Unlike session cookies, persistent cookies can specify a specific expiration time (Expires) or max-age.
res.setHeader('Set-Cookie', ['mycookie=222', 'test=3333; expires=Sat, 21 Jul 2018 00:00:00 GMT;']);
Copy the code

The code above creates two cookies: mycookie, a session-duration Cookie, and Test, a persistent Cookie. When we look at cookie-related attributes, different browsers have different values for the Expires attribute of the session Cookie:

In addition, each Cookie has a field associated with it, the scope of which is typically specified through the Donmain property. If the domain of the Cookie is the same as the domain of the page, then we call the Cookie a first-party Cookie. If the domain of the Cookie is different from the domain of the page, It is called a third-party Cookie. When a page contains images or resources (such as images) stored in other domains, first-party cookies are also sent only to the server that set them.

3.2 CSRF Attacks Using Cookies

Suppose there is a BBS site: www.c.com. When a user initiates the following GET request, the post with the specified ID will be deleted:

http://www.c.com:8002/content/delete/:id
Copy the code

As a www.c.com:8002/content/del… On request, the post with ID 87343 is deleted. After the user logs in, the following cookies will be set:

res.setHeader('Set-Cookie', ['user=22333; expires=Sat, 21 Jul 2018 00:00:00 GMT;']);
Copy the code

The value of user is the user ID. Then construct A page A:

Sites prepared by CSRF attackers:

< p > CSRF attacks are preparing website: < / p > < img SRC = "http://www.c.com:8002/content/delete/87343" >Copy the code

Page A uses an IMG tag whose address points to A link to delete the user’s post:

As you can see, when the logged-in user visits the attacker’s site, a request is made to www.c.com to remove the user’s post. If the user refreshes the post page after switching to www.c.com, the user will find that the post ID 87343 has been deleted.

Because cookies contain user authentication information, attackers can launch CSRF attacks on servers when users access the attack environment prepared by attackers. In this attack, the attacker uses the victim’s Cookie to defraud the server of trust, but cannot get the Cookie or see the content of the Cookie. The result returned by the server cannot be parsed by the attacker due to the same origin policy of the browser. Therefore, the attacker gets nothing from the returned result, and all he can do is send a request to the server to execute the command described in the request, changing the value of the data directly on the server side, rather than stealing the data from the server.

However, if the target of CSRF attack does not need to use cookies, you do not need to worry about the browser’s Cookie policy.

4.CSRF attack defense

Currently, the following methods are used to defend against CSRF attacks.

4.1 authentication code

Captchas are considered to be the simplest and most effective defense against CSRF attacks.

As you can see from the examples above, CSRF attacks often construct network requests without the user’s knowledge. Captcha forces the user to interact with the application in order to complete the final request. In general, captchas are a good deterrent against CSRF attacks.

But captcha is not a panacea, because for the sake of users, you can’t add captcha to every operation on the site. Therefore, captchas can only be used as an adjunct to CSRF defense, not as a primary solution.

4.2 Referer Check

According to the HTTP protocol, there is a field in the HTTP header called Referer that records the source address of the HTTP request. With the Referer Check, you can Check whether the request is from a legitimate “source.”

For example, if a user wants to delete a post, he or she should go to www.c.com, find the corresponding page, and initiate a request to delete the post. At this point, the value of Referer is www.c.com; When the request is initiated from www.a.com, the Referer value is www.a.com. Therefore, to defend against CSRF attacks, it is only necessary to verify the Referer value of each deletion request. If the domain name starts with www.c.com, it indicates that the request is from the website itself and is legitimate. If the Referer is any other site, it could be a CSRF attack and the request could be rejected.

For the example above, you can add the following code on the server side:

if (req.headers.referer ! = = 'http://www.c.com:8002/') {res. Write (' CSRF attacks'); return; }Copy the code

Referer Check is not only used to prevent CSRF attacks, but also to prevent image theft.

4.3 Adding Token Authentication (Token == Token)

The reason why CSRF attack can be successful is that the attacker can completely forge the user’s request, and all the user authentication information in the request is in the Cookie, so the attacker can directly use the user’s own Cookie to pass the security authentication without knowing the authentication information. The key to defending against CSRF is to put information in the request that an attacker cannot forge and that does not exist in a Cookie. A randomly generated token can be added to the HTTP request as a parameter, and an interceptor can be established on the server side to verify the token. If there is no token in the request or the token content is incorrect, the request may be rejected as a CSRF attack.

conclusion

This paper mainly introduces the attack principle and defense measures of XSS and CSRF. Of course, in the field of Web security, in addition to these two common attacks, there are other attacks such as SQL injection