Analysis of Six Common Web Security Attacks and Defense

  Front end, java, javascript, node.js, Programmer

Preface

In the Internet era, data security and personal privacy have been challenged unprecedentedly, and various novel attack technologies emerge in endlessly. How can we better protect our data? This article mainly focuses on analyzing several common attack types and defense methods.

If you want to read more high-quality original articles, please stamp them fiercely.GitHub blog

I. XSS

XSS (Cross-Site Scripting), a cross-site scripting attack, can only be called XSS because abbreviations and CSS overlap. Cross-site scripting attack refers to an attack by running illegal HTML tags or JavaScript in the browser of registered users through a Web site with security vulnerabilities.

Cross-site scripting attacks can have the following effects:

  • Using false input forms to defraud users of personal information.
  • The script is used to steal the Cookie value of the user, and the victim helps the attacker to send malicious requests without knowing it.
  • Show fake articles or pictures.

The principle of XSS is that malicious attackers insert malicious executable Web script code into the Web page. When users browse the page, the script code embedded in the web will be executed, thus achieving the purpose of attackers stealing user information or other violations of user security and privacy..

XSS attacks vary widely, but they can still be roughly divided into several types.

1. Non-persistent XSS (reflective XSS)

Non-persistent XSS vulnerabilities are usually sent to othersURL with malicious script code parametersWhen the URL address is opened, the unique malicious code parameters are parsed and executed by HTML.


For example, the page contains the following code:

<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>

Attackers can use the URL directly (similar to:https://xxx.com/xxx? default=<script>alert(document.cookie)</script>Inject executable script code. However, some browsers such as Chrome have built-in XSS filters to prevent most reflective XSS attacks.

Non-persistent XSS vulnerability attacks have the following characteristics:

  • Instant, it can complete an attack directly through HTTP GET and POST requests without server storage and get the user’s private data.
  • Attackers need to trick clicks, which must be initiated by users clicking on links.
  • The feedback rate is low, so it is difficult to find and respond to repair.
  • Stealing sensitive and confidential information of users

In order to prevent non-persistent XSS vulnerabilities, there are several things to ensure:

  • All content or data rendered by a Web page must come from the server.
  • Try not to followURL,document.referrer,document.formsSuch as the DOM API to obtain data for direct rendering.
  • Try not to use iteval,new Function(),document.write(),document.writeln(),window.setInterval(),window.setTimeout(),innerHTML,document.createElement()Such as executable string method.
  • If you can’t do the above, you must escape the string parameters passed in by methods involving DOM rendering.
  • Escape escape encoding is required for any field during front-end rendering.

2. Persistent XSS (Storage XSS)

Persistent XSS vulnerabilities generally exist in interactive functions such as Form form submission, such as article comments, submission of text information, etc. Hackers use XSS vulnerabilities to submit content into the database for persistent storage through normal functions. When the front-end page obtains the injected code read from the database by the back-end, it just renders and executes it.

For example, for the comment function, it is necessary to guard against persistent XSS attacks, because I can enter the following in the comment

The main way to inject pages is similar to non-persistent XSS vulnerabilities, except that persistent ones do not come from URL, referer, forms, etc., but fromData read by the backend from the database. Persistent XSS attacks don’t need to trick clicks; hackers only need to inject forms where they are submitted, but the cost of such XSS attacks is relatively high.

The success of the attack requires the following conditions to be met at the same time:

  • POST request submitted form back-end is directly put into storage without escape.
  • The back end takes out the data from the database and directly outputs it to the front end without escaping.
  • The front end gets the back end data and renders it directly into DOM without escaping.

Persistent XSS has the following characteristics:

  • Persistence, embedded in database
  • Stealing sensitive and private information of users
  • The harm is extensive.

How to defend

There are usually two ways to defend against XSS attacks.

1) CSP

CSP is essentially a whitelist. Developers explicitly tell browsers 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.

CSP can usually be turned on in two ways:

  • Set Content-Security-Policy in HTTP Header
  • How to set meta tag < metahttp-equiv = “content-security-policy” >

Here’s an example of setting the HTTP Header:

  • Only the resources of this site are allowed to be loaded.
Content-Security-Policy: default-src 'self'
  • Only HTTPS protocol pictures are allowed to be loaded
Content-Security-Policy: img-src https://*
  • Allow loading of any source frame
Content-Security-Policy: child-src 'none'

For more information on attributes, please seeContent-Security-Policy document

For this way, as long as the developer has configured the correct rules, even if the website has vulnerabilities, the attacker cannot execute its attack code, and CSP compatibility is good.

2) escape character

The user’s input can never be trusted. The most common way is to escape the input and output contents, 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
 }

However, for displaying rich text, it is obviously impossible to escape all characters by the above method, because it will also filter out the required format. In this case, the white list filtering method is usually adopted, and of course, the black list filtering method can also be adopted, but considering that there are too many tags and tag attributes to be filtered, the white list method is more recommended.

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)

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

3) HttpOnly Cookie。

This is the most effective defense against XSS attacks stealing user cookie. When a Web application sets a cookie, its attribute is set to HttpOnly, which can prevent the cookie of the web page from being stolen by malicious JavaScript of the client and protect the cookie information of the user.

Ii. CSRF

CSRF(Cross Site Request Forgery), or Cross Site Request Forgery, is a common Web attack that uses the user’s logged-in identity to complete illegal operations on behalf of the user without the user’s knowledge.

1. Principle of 1.CSRF Attack

Let’s first introduce the principle of CSRF attack:

There are three conditions to complete CSRF attack:

  • The user has logged in to site a and recorded a cookie locally.
  • Under the condition that the user does not log out of site a (that is, when the cookie is valid), the user visited the luring dangerous site b provided by the malicious attacker (site b requires to visit site a).
  • Site a did not do any CSRF defense.

Let’s look at an example: when we log on to the transfer page, our eyes suddenly shine.The link “XXX Private Photos, Never Regret Your Lifetime Without Looking” was shocked., can’t resist inner agitation, immediately click on the dangerous website (page code as shown in the figure below), but when the page is loaded, it will be executedsubmitFormThis method is used to submit the transfer request, thus transferring 10 pieces to the hacker.

2. How to defend

The following rules can be followed to prevent CSRF attacks:

  • Get request does not modify data
  • Do not allow third-party websites to access user Cookie
  • Prevent third-party websites from requesting interfaces
  • The request is accompanied by verification information, such as verification code or Token.

1) SameSite

You can set the SameSite property on Cookie. This attribute indicates that Cookie are not sent with cross-domain requests, which can greatly reduce CSRF attacks, but this attribute is not compatible with all browsers at present.

2) Referer Check

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

However, in some cases, such as jumping from https to http, the browser is in security consideration and will not send referer, so the server cannot check. If other websites in the same domain as the website have XSS vulnerabilities, the attacker can inject malicious scripts into other websites, and the victim will also be attacked if he enters the website of this similar domain. For the above reasons, it is impossible to completely rely on referrcheck as the main defense against CSRF. However, the occurrence of CSRF attacks can be monitored by referrcheck.

3) Anti CSRF Token

At present, a relatively perfect solution is to add Anti-CSRF-Token. That is, when sending the request, a randomly generated token is added to the HTTP request in the form of parameters, and an interceptor is established at the server to verify the token. The server reads the token value in the browser’s current domain cookie and checks whether the token value in the request and the token value in the cookie both exist and are equal before it considers this a legitimate request. Otherwise, the request is considered illegal and the service is refused.

This method is much safer than Referer inspectionThe 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 and compares it with the token in this request. Due to the existence of token, attackers can no longer construct a complete URL to implement CSRF attacks. However, when dealing with the coexistence of multiple pages, when one page consumes the token, the form of other pages still stores the consumed token, and the token error will occur when the form of other pages is submitted.

4) verification code

In the process of interaction between the application program and the user, especially in the core step of account transaction, the user is forced to enter a verification code to complete the final request. Under normal circumstances, CAPTCHA can well contain CSRF attacks.However, adding verification codes reduces the experience of users, and websites 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 service points.

III. clickjacking

Clickjacking is a visual deception attack. The attacker embeds the website to be attacked into his own webpage through the nested way of iframe, sets iframe to be transparent, and gives out a button in the page to induce the user to click.

1. Characteristics

  • High concealment, defrauding users of operations
  • “UI- Overwrite Attack”
  • Use iframe or other tag attributes

2. The principle of clickjacking

After logging into the system of website a, the user was lured by the attacker to open the third-party website, and the third-party website introduced the page content of website a through iframe. when the user clicks a button (decorated button) in the third-party website, he actually clicks the button of website a.
Next, let’s give an example: I have released many videos in Youku. 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 > click strip < /button >
 <img src="http://pic1.win4000.com/wallpaper/2018-03-19/5aaf2bf0122d2.jpg">
 <iframe src="http://i.youku.com/u/UMjA0NTg4Njcy" scrolling="no"></iframe>


As can be seen from the above figure, the attacker used the picture as the background of the page to hide the real user interface. When you click the button out of curiosity, what you really click is the subscription button of the hidden page, and then you will subscribe without your knowledge.

How to defend

1)X-FRAME-OPTIONS

X-FRAME-OPTIONSIt is an HTTP response header and has a good support in modern browsers. This HTTP response header is designed to protect against clickjacking attacks nested with iframe.

The response header has three optional values, namely

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

2)JavaScript defense

For some ancient browsers, the above method is not supported, so we have to defend clickjacking through JS.

<head>
 <style id="click-jack">
 html {
 display: none !  important;
 }
 </style>
 </head>
 <body>
 <script>
 if (self == top) {
 var style = document.getElementById('click-jack')
 document.body.removeChild(style)
 } else {
 top.location = self.location
 }
 </script>
 </body>

The function of the above code is that when the page is loaded via iframe, the attacker’s webpage will not display all the contents directly.

IV. URL Jump Vulnerability

Definition: Security problem caused by guiding the application to an insecure third-party area by means of an unverified URL jump.

1.URL jump vulnerability principle

Hackers use URL jump vulnerabilities to induce users with low security awareness to click, resulting in user information disclosure or loss of funds. The principle is that hackers build malicious links (links need to be disguised and confused as much as possible) and send them to QQ groups or posts/forums with a large number of views.
Users with low security awareness will jump to malicious websites after clicking and parsing by the server or browser.

Malicious links need to be disguised. It is common practice to add a malicious web address to familiar links to confuse users.

Can you identify malicious urls, such as the website disguised as the following?

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

2. Implementation mode:

  • Header header jump
  • Javascript jump
  • META tag jump

Here let’s take a Header header jump implementation:

<?  php
 $url=$_GET['jumpto'];
 header("Location: $url");
 ?  >
http://www.wooyun.org/login.php?  jumpto=http://www.evil.com

Users here will think thatwww.wooyun.orgBoth are trusted, but clicking on the above link will lead to the user’s final access.www.evil.comThis malicious urls.

How to defend

1) restriction of 1)referer

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.

2) Add validation Token

We guarantee that all generated links come from our trusted domain. By adding a Token that is not controllable by the user to the generated links to check the generated links, users can be prevented from generating their own malicious links and thus being utilized. However, if the function itself requires to be relatively open, it may lead to certain restrictions.

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.

1. Principle of 1.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= "login" /></p >
 </form>

The back-end SQL statement might look like this:

let querySQL = `
 SELECT *
 FROM user
 WHERE username='${username}'
 AND psw='${password}'
 `;
 //The next step is to execute sql statements  ...

This is the login page we often see, but if a malicious attacker enters the user name isadmin' --If you enter your password at will, you can log into the system directly. why! -this is SQL injection

The SQL statement we expected before is:

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

But a malicious attacker used a strange username to turn your SQL statement into the following form:

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

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

SELECT * FROM user WHERE username='admin'

The so-called universal password is essentially a way of using SQL injection.

A SQL injection process includes the following procedures:

  • Obtaining user request parameters
  • Splicing into Code
  • The SQL statement was executed successfully according to the semantics of the parameters we constructed.

* * prerequisites for **SQL injection:
1. Can control the input data
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, except that the hacker controls the data and constructs the SQL query, while the normal request does not take the step of SQL query.The essence of SQL injection: data and code are not separated, that is, data is executed as code.

2. Hazards

  • Get database information

    • Administrator background username and password
    • Get sensitive information of other databases: user name, password, mobile phone number, ID card, bank card information …
    • The entire database: pants off
  • Get server permissions
  • Embed Webshell to Get Server Back Door
  • Read sensitive server files

How to defend

  • Strictly restrict the operation authority of the database of Web applicationIn order to minimize the harm of injection attacks on the database, this user is provided with the minimum permissions that can only satisfy his work.
  • The back-end code checks whether the input data meets the expectation, strictly limit the types of variables, such as using regular expressions for some matching processing.
  • For special characters (‘,”,,<, >,&,*,; , etc.) to escape processing, or coding conversion. Basically all back-end languages have methods to escape strings, such as 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 splice SQL statements. For example, in the query method of mysqljs library in Node.js? Placeholder parameters.

VI. OS Command Injection Attack

OS command injection is similar to SQL injection, except that SQL injection is for database, while OS command injection is for operating system. OS command injection attack refers to executing illegal operating system commands through Web applications to achieve the purpose of attack. As long as the Shell function can be called, there is a risk of being attacked. If there are omissions when calling the Shell, the inserted illegal command can be executed.

Command injection attacks can send commands to the Shell to cause the command line of Windows or Linux operating systems to start programs. In other words, various programs installed on the operating system can be executed through command injection attacks.

1. Principle


The hacker constructs the command to submit to the web application program, the web application program extracts the hacker constructs the command, splices into the executed command, because the hacker injects the command to break the original command structure, causes the web application to execute the additional command, finally the web application program outputs the execution result to the response page.

We will illustrate its principle through an example. If a requirement needs to be fulfilled: the user submits some content to the server, and then executes some system commands on the server to return a result to the user.

//Take Node.js for example, if you need to download the user-specified repo from github in the interface
 const exec = require('mz/child_process').exec;
 Let params = {/* parameters entered by the user */};
 exec(`git clone ${params.repo} /some/path`);

Ifparams.repoWhat was introduced washttps://github.com/admin/admin.github.io.gitIt is indeed possible to download the desired code from the specified git repo.
But ifparams.repoWhat was introduced washttps://github.com/xx/xx.git && rm -rf /* &&It happens that your service starts with root permissions, which is bad.

2. How to defend

  • The back end imposes rule restrictions (such as regular expressions) on the content submitted by the front end.
  • Escape and filter all incoming parameters before calling system commands.
  • Don’t splice command statements directly, use some tools to do splicing and escape preprocessing, such as Node.jsshell-escape npmpackage

To recommend a useful BUG monitoring toolFundebug, welcome to try free!

Reference material