Top 6 Common Web Security Problems - Translation

1. XSS

Cross-Site Scripting (cross-site scripting attack) referred to as XSS (because the abbreviation overlaps with CSS, so it can only be called XSS), is a code injection attack.

Attackers inject malicious scripts on targeted websites to run on users' browsers. Using these malicious scripts, attackers can obtain sensitive user information such as Cookies, SessionID, etc., thereby compromising data security.

1.1 Principle

The principle of XSS is that a malicious attacker inserts malicious executable web script code into a web page. When the user browses the page, the script code embedded in the web will be executed, so that the attacker can steal user information or other violations. The purpose of user security and privacy.

1.2 Classification

type storage area insertion point
Stored XSS backend database HTML
Reflected XSS URL HTML
DOM type XSS Backend database/frontend storage/URL Front-end JavaScript

1.2.1 Reflected XSS

Generally, it sends URLs with malicious script code parameters to others. When the URL address is opened, the unique malicious code parameters are parsed and executed by HTML.

<select>
    <script>
        document.write(''
            + '<option value=1>'
            +     location.href.substring(location.href.indexOf('default=') + 8)
            + '</option>'
        );
        document.write('<option value=2>English</option>');
    </script>
</select>

   
   
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

An attacker can https://xxx.com/xxx?default=<script>alert(document.cookie)</script>inject executable script code directly through a URL (like: ). However, some browsers such as Chrome have some built-in XSS filters that can prevent most reflected XSS attacks.

Reflected XSS attacks have the following characteristics:

  • Immediateness, without server storage, an attack can be completed directly through HTTP GET and POST requests, and user privacy data can be obtained.
  • The attacker needs to trick the click, and the user must click the link to initiate the
  • Feedback rate is low, so it is harder to spot and respond to fixes
  • Steal sensitive and confidential information from users

Precautions:

  • All content or data rendered by a web page must come from the server.
  • Try not to get data directly from DOM API such as URL, document.referrer, document.forms and so on.
  • Try not to use eval, new Function(), document.write(), document.writeln(), window.setInterval(), window.setTimeout(), innerHTML, document.createElement() and other executable string methods.
  • If you can't do the above points, you must also escape the string parameters passed in by the method involving DOM rendering.
    Any field needs to be escaped when rendering at the front end.

1.2.2 Stored XSS

It generally exists in interactive functions such as form form submission, such as posting comments, submitting text information, etc. XSS vulnerabilities exploited by hackers submit the content to the database for permanent storage through normal functions, and the front-end page obtains the injection code read from the database by the back-end , it happens to be rendered and executed.

Stored XSS attacks do not need to trick clicks, hackers only need to complete the injection where the form is submitted.

For the attack to succeed, the following conditions must be met at the same time:

  • The POST request submits the form backend without escaping and directly enters the database.
  • The backend fetches the data from the database and outputs it directly to the frontend without escaping.
  • The front-end gets the back-end data and renders it directly into DOM without escaping.

Stored XSS has the following characteristics:

  • Persistence, embedded in the database
  • Steal sensitive private information from users
  • Wide range of hazards

1.2.3 DOM type XSS

DOM-type XSS attack is actually that the front-end JavaScript code is not rigorous enough, and untrustworthy content is inserted into the page. Be especially careful when using APIs such as .innerHTML, .outerHTML, .appendChild, and document.write(). Do not insert untrustworthy data as HTML into the page. Try to use .innerText, .textContent, .setAttribute(), etc.

1.3 Defense measures

1.3.1 csp(Content-Security-Policy)

CSP essentially establishes a whitelist, and developers explicitly tell the browser which external resources can be loaded and executed. We only need to configure the rules, how to intercept is implemented by the browser itself. We can minimize XSS attacks in this way

1.3.1.1 Open csp mode

There are usually two ways to enable CSP:

  • Set Content-Security-Policy in HTTP Header
// 限制所有的外部资源,都只能从当前域名加载
Content-Security-Policy: default-src 'self'

// default-src is a CSP instruction, multiple instructions are separated by English semicolons; multiple instruction values ​​are separated by English spaces
Content-Security-Policy: default-src https://host1.com https://host2. com ; frame-src 'none' ; object-src 'none'

// Incorrect writing, the second command will be ignored
Content-Security-Policy: script-src https://host1.com ; script-src https://host2.com

// The correct writing is as follows
Content-Security-Policy: script-src https://host1.com https://host2.com

// Use the report-uri command to instruct the browser to send the interception report in JSON format to an address
Content-Security-Policy: default-src 'self' ; . ; report-uri /my_amazing_csp_report_parser ;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • How to set meta tags
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">

 
 
  
  
  • 1

The content security policy configured in the meta tag mode is relatively easy to understand, but if it is configured in the http head mode, can it be configured for any api? This is generally configured on nginx, like this:

		add_header Content-Security-Policy "default-src 'self' static4.segway.com(该地址按需修改) 'unsafe-inline' 'unsafe-eval' blob: data: ;";
        add_header X-Xss-Protection "1;mode=block";
        add_header X-Content-Type-Options nosniff;
  • 1
  • 2
  • 3
  • 4

1.3.1.2 Commonly used CSP instructions

instruction Examples of directives and directive values instruction description
default-src ‘self’ cdn.guangzhul.com default loading strategy
script-src ‘self’ js.guangzhul.com Loading strategy for JavaScript.
style-src ‘self’ css.guangzhul.com Loading strategy for styles.
img-src ‘self’ img.guangzhul.com The loading strategy for images.
connect-src ‘self’ Loading strategy for Ajax, WebSocket, etc. requests. If not allowed, the browser simulates a response with a status of 400.
font-src font.cdn.guangzhul.com Loading strategy for WebFont.
object-src ‘self’ Loading strategy for plug-ins such as flash introduced by tags such as , or .
media-src media.cdn.guangzhul.com Loading strategy for HTML multimedia imported by media.
frame-src ‘self’ The loading strategy for the frame.
report sites report sites Tell the browser to which address to submit log information if the requested resource is not allowed by the policy. Special: If you want the browser to only report logs and not block any content, you can use the Content-Security-Policy-Report-Only header instead.

1.3.2 Escape characters

User input can never be trusted. The most common way is to escape the content of input and output, and escape quotation marks, angle brackets, and slashes.

function escape(str) {
    
    
  str = str.replace(/&/g, '&amp;')
  str = str.replace(/</g, '&lt;')
  str = str.replace(/>/g, '&gt;')
  str = str.replace(/"/g, '&quto;')
  str = str.replace(/'/g, '&#39;')
  str = str.replace(/`/g, '&#96;')
  str = str.replace(/\//g, '&#x2F;')
  return str
}

 
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

But for displaying rich text, it is obviously impossible to escape all characters through the above method, because this will also filter out the required format. In this case, whitelist filtering is usually used, of course, blacklist filtering is also possible, but considering that there are too many tags and tag attributes that need to be filtered, it is more recommended to use the whitelist method.

const xss = require('xss')
let html = xss('<h1 id="title">XSS Demo</h1><script>alert("xss");</script>')
// -> <h1>XSS Demo</h1>&lt;script&gt;alert("xss");&lt;/script&gt;
console.log(html)

 
 
  
  
  • 1
  • 2
  • 3
  • 4

The above example is implemented using js-xss, you can see that the h1 tag is kept and the script tag is filtered in the output.

1.3.3 HttpOnly Cookie

HttpOnly is a mark added to cookies to tell the browser not to expose cookies to client scripts (document.cookie or others).

When you set the HttpOnly flag on the cookie, the browser will know that this is a special cookie that can only be retrieved by the server, and all access from client-side scripts will be prohibited. Of course, there is a premise: use a new version of the browser.

Set-Cookie: Name=Value; expires=Wednesday, 01-May-2014 12:45:10 GMT; HttpOnly

 
 
  
  
  • 1

JavaScript is prohibited from reading certain sensitive cookies, and attackers cannot steal this cookie after completing XSS injection

2. CSRF

CSRF (Cross-site request forgery) Cross-site request forgery: The attacker induces the victim to enter a third-party website, and in the third-party website, sends a cross-site request to the attacked website. Use the registration credentials that the victim has obtained on the attacked website to bypass the user verification in the background, and achieve the purpose of impersonating the user to perform an operation on the attacked website.

2.1 The principle of the attack

Three conditions must be met to complete a CSRF attack:

  1. The user is already logged into site A, and the cookie is logged locally
  2. In the case that the user does not log out of site A (that is, when the cookie is in effect), he visits the lure dangerous site B provided by the malicious attacker (site B requires access to site A).
  3. Site A does not do any CSRF defense

Below is a typical scenario

  • The victim logs into a.com and keeps the login credentials (cookies).
  • The attacker lures the victim to visit b.com.
  • b.com sends a request to a.com: a.com/act=xx. The browser will carry the cookie information of a.com in the request header
  • After receiving the request, a.com verifies the request and confirms that it is the victim's credentials, mistaking it for the request sent by the victim himself.
  • a.com executed act=xx on behalf of the victim.
  • The attack is completed, and the attacker pretends to be the victim without the victim's knowledge, and makes a.com perform the operation he defined.

2.2 Features

  1. Attacks are usually launched on third-party websites, such as site B in the figure, site A cannot prevent the attack from happening.
  2. The attack uses the login credentials of the victim on the attacked website to impersonate the victim to submit operations; it does not obtain cookie information (cookies have the same-origin policy)
  3. Cross-site requests can be made in various ways: image URL, hyperlink, CORS, Form submission, etc. (links from unknown sources, do not click)

ps: Note that the cookie is stolen, it is impersonation, not acquisition, the cookie is automatically stuffed into the header of the request when the browser sends the request

The browser will attach the corresponding domain name cookie according to the loaded domain name.

That is, if the user logs in on website a and generates authorized cookies, and then visits website b, station b deliberately constructs a request for website a, such as deleting operations, and loads a with script, img or iframe to stand Address, the browser will attach the authorization cookie information of the logged-in user on site a, which constitutes crsf, and will delete the current user's data.

2.3 Category

2.3.1 CSRF of GET type

The use of CSRF of GET type is very simple, only one HTTP request is required, and it is generally used like this:

 <img src="http://bank.example/withdraw?amount=10000&for=hacker" > 

 
 
  
  
  • 1

After the victim visits the page containing this img, the browser will automatically send http://bank.example/withdraw?account=xiaoming&amount=10000&for=hackeran HTTP request to the victim. bank.example will receive a cross-origin request containing the victim's login information.

2.3.2 CSRF of POST type

This type of CSRF is usually exploited using an auto-submitted form, such as:

 <form action="http://bank.example/withdraw" method=POST>
    <input type="hidden" name="account" value="xiaoming" />
    <input type="hidden" name="amount" value="10000" />
    <input type="hidden" name="for" value="hacker" />
</form>
<script> document.forms[0].submit(); </script> 

 
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

After visiting the page, the form will be automatically submitted, which is equivalent to simulating the user completing a POST operation.

POST-type attacks are usually a little stricter than GET, but still not sophisticated. Any personal website, blog, or website that has been uploaded by hackers may be the source of the attack, and the back-end interface cannot rely on the security of only allowing POST.

2.3.3 CSRF of link type

Link-type CSRF is not common. Compared with the other two cases where the user opens the page and is recruited, this kind of situation requires the user to click the link to trigger. This type is usually to embed malicious links in pictures posted on forums, or to induce users to be recruited in the form of advertisements. Attackers usually use exaggerated words to trick users into clicking, for example:

  <a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" taget="_blank">
  重磅消息!!
  <a/>

 
 
  
  
  • 1
  • 2
  • 3

Since the user logged in to the trusted website A before and saved the login status, as long as the user actively visits the above PHP page, the attack is successful.

2.4 Defense

2.4.1 SameSite

In order to solve this problem from the source, Google drafted a draft to improve the HTTP protocol, adding a Samesite attribute to the Set-Cookie response header, which is used to indicate that the cookie is a "same site cookie", and the same site cookie can only be used as the first A one-party cookie cannot be used as a third-party cookie. Samesite has two attribute values, namely Strict and Lax. It is simple to deploy and can effectively defend against CSRF attacks, but there are compatibility issues.

Set-Cookie: CookieName=CookieValue; SameSite=Strict;
// or
Set-Cookie: CookieName=CookieValue; SameSite=Lax;

 
 
  
  
  • 1
  • 2
  • 3
  • Samesite=Strict: It is called strict mode, which indicates that this cookie cannot be used as a third-party cookie under any circumstances, and has the ability to prevent all CSRF attacks. At this time, if we initiate any request to site A under site B, the cookie of site A will not be included in the cookie request header.
  • Samesite=Lax: It is called a loose mode. Compared with Strict, it relaxes the restrictions and allows sending secure HTTP methods with cookies, such as Get / OPTIONS and HEAD requests. However, unsafe HTTP methods, such as: POST , PUT , DELETE requests, cannot be used as cookies for third-party links

2.4.2 Referer Check

The HTTP Referer is a part of the header. When the browser sends a request to the web server, it will usually bring the Referer information to tell the server which page it is linked from, so that the server can obtain some information for processing. CSRF attacks can be defended against by checking the origin of the request. The referer of a normal request has certain rules. For example, the referer submitted to the form must be a request initiated on this page. So by checking whether the value of the referer in the http header is this page, we can judge whether it is a CSRF attack.

But in some cases, such as jumping from https to http, the browser will not send the referer for security reasons, and the server will not be able to check. If other websites in the same domain as the website have XSS vulnerabilities, the attacker can inject malicious scripts in other websites, and the victim will also be attacked when he enters such a website in the same domain. For the above reasons, it is impossible to completely rely on Referer Check as the main means of defense against CSRF. But the occurrence of CSRF attacks can be monitored through Referer Check.

2.4.3 Using Token (mainstream)

The reason why the CSRF attack can be successful is that the server mistakenly regards the request sent by the attacker as the user's own request. Then we can require all user requests to carry a Token that CSRF attackers cannot obtain. The server distinguishes normal requests from attack requests by verifying whether the request carries the correct Token. Similar to the verification code, but the user does not perceive it.

  1. The server generates a token for the user, encrypts it and passes it to the user
  2. When submitting a request, the user needs to carry this token
  3. The server verifies whether the token is correct

This method is much safer than the Referer check. The token can be generated after the user logs in and placed in the session or cookie, and then the server takes the token out of the session or cookie each time it is requested, and it is the same as the token in this request. Compare. Due to the existence of tokens, attackers can no longer construct a complete URL to implement CSRF attacks. However, when dealing with the coexistence of multiple pages, when a certain page consumes the token, the forms of other pages still save the consumed token, and token errors will occur when the forms of other pages are submitted.

I personally feel that this method can prevent 99% of CSRF attacks, so what about 1%... Since the user's cookie is easily stolen due to the XSS vulnerability of the website, this is the other 1%.

2.4.4 Verification code

In the process of interaction between the program and the user, especially the core step of account transaction, the user is forced to enter the verification code to complete the final request. Under normal circumstances, captchas are good enough to contain CSRF attacks. However, adding verification codes reduces the user experience, and the website cannot add verification codes to all operations. Therefore, the verification code can only be used as an auxiliary means to set the verification code at key business points.

3. Clickjacking

Clickjacking is an attack method of visual deception. The attacker embeds the website to be attacked into his own webpage through iframe nesting, sets the iframe to be transparent, and exposes a button on the page to induce users to click.

3.1 Features

  • High concealment, defrauding user operations
  • "UI-overlay attack"
  • Use the attributes of iframe or other tags

3.2 The principle of clickjacking

After the user logs in to the system of website A, he is tempted by the attacker to open a third-party website, and the third-party website introduces the page content of website A through an iframe. When the user clicks a button (decorated button) on the third-party website, the actual The button on the A website is clicked.
Next, let’s give an example: I have posted a lot of videos on Youku, and if I want more people to pay attention to it, I can do it through clickjacking

iframe {
    
    
width: 1440px;
height: 900px;
position: absolute;
top: -0px;
left: -0px;
z-index: 2;
-moz-opacity: 0;
opacity: 0;
filter: alpha(opacity=0);
}
button {
    
    
position: absolute;
top: 270px;
left: 1150px;
z-index: 1;
width: 90px;
height:40px;
}
</style>
......
<button>点击脱衣</button>
<img src="http://pic1.win4000.com/wallpaper/2018-03-19/5aaf2bf0122d2.jpg">
<iframe src="http://i.youku.com/u/UMjA0NTg4Njcy" scrolling="no"></iframe>

 
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

As can be seen from the above figure, the attacker uses the picture as the page background to hide the real interface of the user's operation. When you click the button out of curiosity, what you really click is actually the subscribe button on the hidden page, and then the Subscribed without your knowledge.

3.3 How to defend

3.3.1 X-FRAME-OPTIONS

X-FRAME-OPTIONS is an HTTP response header that has a good support in modern browsers. This HTTP response header is to defend against clickjacking attacks nested with iframes.

The response header has three optional values, which are

  • DENY means that the page is not allowed to be displayed through iframe
  • SAMEORIGIN, indicating that the page can be displayed in an iframe under the same domain name
  • ALLOW-FROM, indicating that the page can be displayed in the iframe of the specified source

4. URL Jump Vulnerability

Definition: With the help of unverified URL redirection, the application is directed to an unsafe third-party area, resulting in security issues.

4.1 The Principle of URL Jump Vulnerability

Hackers use URL redirection vulnerabilities to induce users with low security awareness to click, resulting in leakage of user information or loss of funds. The principle is that hackers build malicious links (links need to be disguised to confuse them as much as possible), and post them in QQ groups or post bars/forums with a lot of views.

Users with low security awareness will jump to malicious websites after being parsed by the server or browser after clicking.

Malicious links need to be disguised. A common practice is to add a malicious URL after a familiar link, so as to confuse users.

For example, can you identify a malicious URL if it is disguised as the following URL?

http://gate.baidu.com/index?act=go&url=http://t.cn/RVTatrd
http://qt.qq.com/safecheck.html?flag=1&url=http://t.cn/RVTatrd
http://tieba.baidu.com/f/user/passport?jumpUrl=http://t.cn/RVTatrd
  • 1
  • 2
  • 3
  • 4

4.2 Implementation

  • Header jump
  • Javascript jump
  • META tag jump

Here we give a header jump implementation method:

<?php
$url=$_GET['jumpto'];
header("Location: $url");
?>

 
 
  
  
  • 1
  • 2
  • 3
  • 4
http://www.wooyun.org/login.php?jumpto=http://www.evil.com

 
 
  
  
  • 1

Here the user will think that www.wooyun.org is credible, but clicking the above link will lead the user to finally visit the malicious website www.evil.com.

4.3 How to defend

4.3.1 Restrictions on referers

If the source of passing URL parameters is determined, we can implement security restrictions in this way to ensure the validity of the URL and prevent malicious users from generating jump links themselves.

4.3.2 Add Validity Verification Token

We guarantee that all generated links are from our trusted domain. By adding a Token that the user cannot control in the generated link to verify the generated link, we can prevent users from generating their own malicious links and being used, but if The function itself is relatively open, which may lead to certain restrictions.

5. SQL Injection

SQL injection is a common web security vulnerability. Attackers can use this vulnerability to access or modify data, or exploit potential database vulnerabilities to attack.

5.1 The principle of SQL injection

Let's first give an example of a master key to illustrate its principle:

<form action="/login" method="POST">
    <p>Username: <input type="text" name="username" /></p>
    <p>Password: <input type="password" name="password" /></p>
    <p><input type="submit" value="登陆" /></p>
</form>

 
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

The backend SQL statement might look like this:

let querySQL = `
    SELECT *
    FROM user
    WHERE username='${
      
      username}'
    AND psw='${
      
      password}'
`;
// 接下来就是执行 sql 语句...

 
 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

This is the login page we often see, but if a malicious attacker enters the username as admin' -- and enters the password at will, he can log in to the system directly. why! ----This is SQL injection

The SQL statement we envisioned earlier is:

SELECT * FROM user WHERE username='admin' AND psw='password'

 
 
  
  
  • 1

But a malicious attacker with a strange username changes your SQL statement to something like this:

SELECT * FROM user WHERE username='admin' --' AND psw='xxxx'

 
 
  
  
  • 1

In SQL, ' -- means closure and comment, -- means the content behind the comment, so the query statement becomes:

SELECT * FROM user WHERE username='admin'

 
 
  
  
  • 1

5.2 Prerequisites for SQL injection

  1. Can control the data entered
  2. The code to be executed by the server splices the control data.

We will find that the SQL injection process is similar to the normal request server, but the hacker controls the data and constructs the SQL query, while the normal request does not go through the SQL query step. The essence of SQL injection: the data and the code are not separated, that is, the data is treated as code to execute.

5.3 Defense

  • Strictly limit the operating authority of the database of the web application, and provide the user with the minimum authority that can only meet his work, thereby minimizing the damage of injection attacks to the database
  • The back-end code checks whether the input data meets expectations, strictly restricts the type of variables, for example, uses regular expressions for some matching processing.
  • Escape or encode the special characters (', ", \, <, >, &, *, ; etc.) entering the database. Basically all back-end languages ​​have escape processing for strings methods, such as the lodash._escapehtmlchar library of lodash.
  • All query statements are recommended to use the parameterized query interface provided by the database. Parameterized statements use parameters instead of embedding user input variables into SQL statements, that is, do not directly concatenate SQL statements. For example, the ? placeholder parameter in the query method of the mysqljs library in Node.js.

6. OS command injection attack

OS command injection is similar to SQL injection, except that SQL injection is aimed at the database, while OS command injection is aimed at the operating system. OS command injection attacks refer to the execution of illegal operating system commands through web applications to achieve the purpose of the attack. As long as the Shell function can be called, there is a risk of being attacked. If there is an omission when invoking the Shell, the inserted illegal command can be executed.

A command injection attack can send commands to the shell, causing the command line of the Windows or Linux operating system to start programs. That is to say, various programs installed on the executable operating system can be attacked through command injection.

6.1 Principle

The command constructed by the hacker is submitted to the web application, and the web application extracts the command constructed by the hacker and splices it into the executed command. Because the command injected by the hacker breaks the original command structure, the web application executes additional commands, and finally the web application The program outputs the result of execution to the response page.

Let's use an example to illustrate its principle. If a requirement needs to be realized: the user submits some content to the server, and then executes some system commands on the server to return a result to the user

// 以 Node.js 为例,假如在接口中需要从 github 下载用户指定的 repo
const exec = require('mz/child_process').exec;
let params = {
    
    /* 用户输入的参数 */};
exec(`git clone ${
      
      params.repo} /some/path`);

 
 
  
  
  • 1
  • 2
  • 3
  • 4

If the params.repo is passed in https://github.com/admin/admin.github.io.git, the desired code can indeed be downloaded from the specified git repo.
But if the params.repo passed in is https://github.com/xx/xx.git && rm -rf /* && it happens that your service starts with root authority, it will be bad.

6.2 How to defend

  • The backend restricts the content submitted by the frontend by rules (such as regular expressions).
  • Perform command-line parameter escape filtering on all incoming parameters before calling the system command.
  • Do not splice command statements directly, use some tools for splicing and escaping preprocessing, such as the shell-escape npm package of Node.js

reference

1. XSS

Cross-Site Scripting (cross-site scripting attack) referred to as XSS (because the abbreviation overlaps with CSS, so it can only be called XSS), is a code injection attack.

Attackers inject malicious scripts on targeted websites to run on users' browsers. Using these malicious scripts, attackers can obtain sensitive user information such as Cookies, SessionID, etc., thereby compromising data security.

1.1 Principle

The principle of XSS is that a malicious attacker inserts malicious executable web script code into a web page. When the user browses the page, the script code embedded in the web will be executed, so that the attacker can steal user information or other violations. The purpose of user security and privacy.

1.2 Classification

type storage area insertion point
Stored XSS backend database HTML
Reflected XSS URL HTML
DOM type XSS Backend database/frontend storage/URL Front-end JavaScript

1.2.1 Reflected XSS

一般是通过给别人发送带有恶意脚本代码参数的 URL,当 URL 地址被打开时,特有的恶意代码参数被 HTML 解析、执行。

<select>
    <script>
        document.write(''
            + '<option value=1>'
            +     location.href.substring(location.href.indexOf('default=') + 8)
            + '</option>'
        );
        document.write('<option value=2>English</option>');
    </script>
</select>

   
   
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

攻击者可以直接通过 URL (类似:https://xxx.com/xxx?default=<script>alert(document.cookie)</script>) 注入可执行的脚本代码。不过一些浏览器如Chrome其内置了一些XSS过滤器,可以防止大部分反射型XSS攻击。

反射型 XSS攻击有下面几个特征:

  • 即时性,不经过服务器存储,直接通过 HTTP 的 GET 和 POST 请求就能完成一次攻击,拿到用户隐私数据。
  • 攻击者需要诱骗点击,必须要通过用户点击链接才能发起
  • 反馈率低,所以较难发现和响应修复
  • 盗取用户敏感保密信息

防范措施:

  • Web 页面渲染的所有内容或者渲染的数据都必须来自于服务端。
  • 尽量不要从 URL,document.referrer,document.forms 等这种 DOM API 中获取数据直接渲染。
  • 尽量不要使用 eval, new Function(),document.write(),document.writeln(),window.setInterval(),window.setTimeout(),innerHTML,document.createElement() 等可执行字符串的方法。
  • 如果做不到以上几点,也必须对涉及 DOM 渲染的方法传入的字符串参数做 escape 转义。
    前端渲染的时候对任何的字段都需要做 escape 转义编码。

1.2.2 存储型 XSS

一般存在于 Form 表单提交等交互功能,如文章留言,提交文本信息等,黑客利用的 XSS 漏洞,将内容经正常功能提交进入数据库持久保存,当前端页面获得后端从数据库中读出的注入代码时,恰好将其渲染执行。

存储型 XSS 攻击不需要诱骗点击,黑客只需要在提交表单的地方完成注入即可。

攻击成功需要同时满足以下几个条件:

  • POST 请求提交表单后端没做转义直接入库。
  • 后端从数据库中取出数据没做转义直接输出给前端。
  • 前端拿到后端数据没做转义直接渲染成 DOM。

存储型 XSS 有以下几个特点:

  • 持久性,植入在数据库中
  • 盗取用户敏感私密信息
  • 危害面广

1.2.3 DOM 型 XSS

DOM 型 XSS 攻击,实际上就是前端 JavaScript 代码不够严谨,把不可信的内容插入到了页面。在使用 .innerHTML、.outerHTML、.appendChild、document.write()等API时要特别小心,不要把不可信的数据作为 HTML 插到页面上,尽量使用 .innerText、.textContent、.setAttribute() 等。

1.3 防御措施

1.3.1 csp(Content-Security-Policy)

CSP 本质上就是建立白名单,开发者明确告诉浏览器哪些外部资源可以加载和执行。我们只需要配置规则,如何拦截是由浏览器自己实现的。我们可以通过这种方式来尽量减少 XSS 攻击

1.3.1.1 开启csp方式

通常可以通过两种方式来开启 CSP:

  • 设置 HTTP Header 中的 Content-Security-Policy
// 限制所有的外部资源,都只能从当前域名加载
Content-Security-Policy: default-src 'self'

Guess you like

Origin blog.csdn.net/Arvin_FH/article/details/132186420