The issue of Web security is a platitude. As the layer closest to the user, we should reach out a little further.
Our most common Web security attacks are the following:
XSS
Cross-site scripting attacksCSRF
Cross-site request forgeryURL
Jump holesClickJacking
Hit Hijack/UI-override attackSQL Injection
SQL injectionOS Command Injection
OS Command Injection
A, XSS
XSS (Cross Site Script) Originally abbreviated as CSS, it is called XSS in the security world to distinguish it from Cascading Style Sheets.
Malicious attackers insert malicious Script codes into Web pages. When users browse the page, the Script codes embedded in the Web will be executed, so as to achieve the purpose of malicious attacks on users.
XSS attacks can be divided into three categories:
- Reflective – Non-persistent
Reflected XSS
- Storage – Persistent
Stored XSS
- DOM based or native XSS
DOM-based or local XSS
1. The 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.
Pretend I'm a malicious link (Click Me~)
const http = require('http');
// Start the HTTP service
const server = http.createServer(function (req, res) {
res.setHeader('Access-Control-Allow-Origin'.The '*');
res.writeHead(200, {'Content-Type': 'text/html; charset=UTF-8'});
res.write('');
res.end();
});
server.listen('8000');
Copy the code
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.
2. The storage type
Stored XSS “stores” user-input data on the server, 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.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Type stored XSS</title>
</head>
<body>
<div>The Try Me:<input type="text" id="input"></div>
<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:8000/save', {
method: 'POST'.body: val
});
}, false);
</script>
</body>
</html>
Copy the code
const http = require('http');
let userInput = ' ';
function handleReequest (req, res) {
const method = req.method;
res.setHeader('Access-Control-Allow-Origin'.The '*');
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); res.end(); }}// Start the HTTP service
const server = http.createServer((req, res) = > {
handleReequest(req, res)
});
server.listen('8000');
Copy the code
3. Based on DOM
Dom-based or native XSS is actually a special type of reflective XSS that is a vulnerability based on the DOM document object model. Page content can be modified dynamically through the DOM, fetching data from the DOM from the client and performing it locally. Based on this feature, you can use JS scripts to exploit XSS vulnerabilities.
<body>
<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}>Try Me~</a>`
}, false);
</script>
</body>
Copy the code
Summary: The essence of an XSS attack is to execute the attack script in the target user’s browser by any means.
Defense: All user input, output, and client output are not trusted. When data is added to the DOM or the DOM API is executed, HtmlEncode or JavaScriptEncode is required for the content to prevent XSS attacks.
Mainstream browsers now have built-in safeguards against XSS, for exampleContent Security Policy (CSP). But it is also important for developers to find reliable solutions to prevent XSS attacks.
Second, the CSRF
Cross-site Request Forgery (CSRF), also known as One Click Attack or Session Riding, is a malicious exploitation of a website.
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.
For details about the browser Cookie policy, see HTTP Cookie.
1. CSRF attacks are performed using cookies
Suppose you have a BBS site http://www.a.com:
-
Res.setheader (‘ set-cookie ‘, [‘user= William; Expires =Fri, 23 Mar 2019 00:00:00 GMT;’])
-
When a logged-in user initiates a http://www.a.com/delete?id=666666 request, the post with id 666666 will be deleted.
-
When a logged-in user visits the attacker’s site B, a request is made to www.a.com to remove the user’s post. If the user refreshes the post page after switching to www.a.com, the user will find that the post with ID 666666 has been deleted.
To complete a CSRF attack, the victim must complete two steps in sequence:
- Log in to trusted website A and generate cookies locally.
- Visit dangerous site B without logging out of A.
2. CSRF attack defense
1. Verify the HTTP Referer field. 2. Verification codeCopy the code
Although CSRF sounds like cross-site scripting (XSS), it is very different from XSS, which exploits trusted users within a site, and CSRF exploits trusted sites by masquerading requests from trusted users.
Compared with XSS attacks, CSRF attacks tend to be less popular (and therefore have relatively few resources to defend against them) and difficult to guard against, so they are considered to be more dangerous than XSS and often commit crimes together with XSS!
URL redirect vulnerability
Security problems caused by unauthenticated URL jumps that direct applications to insecure third party areas.
When the user clicks, after the server or browser parsing, it will jump to malicious sites.
http://a.baidu.com/index?act=go&url=http://evil.cn/
http://b.baidu.com/safecheck.html?id=1&url=http://evil.cn/
http://c.baidu.com/f/user/passport?jumpUrl=http://evil.cn/
Copy the code
1. Implementation method
- META Indicates an internal hop
- Javascript to jump
- The Header first jump
GET or POST the URL to jump to, and then jump to the target URL by using one of the above methods. On the one hand, the user’s input will enter Meta, javascript, HTTP headers, so the corresponding context vulnerability may occur, such as XSS, etc. But at the same time, even the URL jump itself has a defect, because it will direct the user’s browser from the trusted site to the untrusted site. At the same time, sensitive data may be leaked to an untrusted third party if there is sensitive data during the jump.
2. Defense plan
(1) Restriction of referer If the source of URL parameter entry is determined, we can realize security restriction in this way to ensure the validity of the URL and avoid malicious users to generate jump links by themselves
(2) add validation Token we ensure that all links are generated from our trusted domain, by the user is added to generate links in uncontrolled Token to check the link, can avoid the users to generate their own malicious links to be used, but if function itself requires more open, may lead to a certain limit.
Fourth, the ClickJacking
ClickJacking, also known as a UI overlay attack, involves an attacker using one or more transparent or opaque layers to trick the user into clicking on a button without the user’s knowledge.
1. The iframe coverage
The key to this attack is that you can implement the
There are two main ways to prevent clickjacking:
-
X-FRAME-OPTIONS
X-frame-options is an HTTP response header proposed by Microsoft that indicates that the browser does not allow views from other domains. X-frame-options is designed to defend against clickjacking attacks using nested iframes. It works well with IE8, Firefox3.6, Chrome4 and beyond.
DENY: denies any domain loading
SAMEORIGIN: allows loading in the SAMEORIGIN domain
Allow-from: allows the page address to be loaded by frame
-
The top judge
Use defensive code in the UI to ensure that the current frame is the topmost window, such as: Top! = self || top.location ! = self.location || top.location ! = location
2. Picture overlay
Cross Site Image Overlaying attack (Cross Site Image Overlaying attack). An attacker overlays one or more images on a web page using the style of the images or the CSS that can be controlled, thus creating click hijacking. Of course, the information carried by the picture itself may have the meaning of deception, so that users do not need to click, but also to achieve the purpose of deception.
<a href="http://www.a.com/delete?id=666666">
<img src="~ ~ ~" style="~ ~ ~" />
</a>
Copy the code
Solution: When defending against image overwriting attacks, you need to check whether the style attribute of the IMG tag in the HTML code submitted by the user can cause the image to surface.
Fifth, SQL Injection
SQL Injection vulnerability is one of the most common security vulnerabilities in Web development. It can be used to obtain sensitive information from the database, or use the characteristics of the database to perform a series of malicious operations such as adding users, exporting files, and even obtain the highest authority of the database and system users.
Principle 1.
SQL injection attacks is by constructing a special input as a parameter to a Web application, and some combination of these input is mostly in the SQL syntax, by executing the SQL statement, in turn, execution of the attacker’s to operation, its main reason is that the program did not carefully to filter the user input data, the illegal data into the system.
According to relevant technical principles, SQL injection can be divided into platform layer injection and code layer injection. The former is caused by insecure database configuration or database platform vulnerabilities; The latter is mainly due to the programmer not filtering the input carefully and thus performing illegal data queries. Based on this, THE reasons for SQL injection are usually shown in the following aspects:
① Improper type of treatment;
② Insecure database configuration;
③ Unreasonable query set processing;
(4) improper error handling;
(5) Improper handling of escape characters;
⑥ Multiple submissions are processed improperly.
2. The attack
SQL injection attacks occur when applications use input to construct dynamic SQL statements to access a database. SQL injection also occurs if the code uses stored procedures that are passed as strings containing unfiltered user input. SQL injection can cause an attacker to use application logins to execute commands in the database. Related SQL injection can be done through the test tool Pangolin.
3. The protective
① Never trust user input. Verify user input, either through regular expressions or by limiting the length; Converts single quotes to double “-” and so on.
② Never use dynamic assembled SQL, instead use parameterized SQL or use poll access directly.
③ Never use database connections with administrator privileges. Use separate database connections with limited privileges for each application.
Don’t store confidential information directly, encrypt or hash passwords and sensitive information.
(5) The exception message of the application should provide as few prompts as possible. It is better to use custom error messages to wrap the original error message.
The detection method of SQL injection generally takes auxiliary software or website platform to detect, software generally uses SQL injection detection tool JSKY, website platform has YI Si website security platform detection tool MDCSOFT SCAN and so on. Mdcsoft-ips can effectively defend against SQL injection and XSS attacks.
6. OS command injection
OS injection attack refers to the scenario where the program provides functions that directly execute Shell commands. When the attacker uses them improperly and the developer does not consider security factors for user parameters, malicious command calls will be executed and exploited by the attacker.
The principle of OS command injection is similar to SQL injection, but the scenario is different. Exec () can be used to execute commands in Node.js by passing in a string of commands and passing an error or command processing result back to the callback function.
1. exec
let userInput = "user input";
child_process.exec('ls -l ' + userInput, (err, data) => {
console.log(data);
});
Copy the code
An attacker can use a semicolon “;” To end the command and start a new call, they can run the subcommand using backquotes or $(). And there is plenty of potential for abuse.
Under the child_process.exec engine, “/bin/sh” will be called to execute. Not the target program. The sent command is simply passed to a new ‘/bin/sh’ process to execute the shell. The name child_process.exec is somewhat misleading – this is a bash interpreter, not a startup program. This means that all the shell characters can have devastating consequences if the user-entered parameters are executed directly.
2. execFile/spawn
In addition to exec(), two methods execFile() and spawn() can also be used to execute system commands in Node.js. The difference between them and exec() is that exec() directly passes a command string to /bin/sh, while exec() provides an array as a parameter container. The parameters are passed directly to C’s command execution method execve(), making it difficult to execute additional parameters.
<! --child_process.execFile -->let path = "user input";
child_process.execFile('/bin/ls'['-l', path], (err, result) => {
console.log(result)
});
Copy the code
<! --child_process.spawn-->let path = "user input";
let ls = child_process.spawn('/bin/ls'['-l', path])
ls.stdout.on('data', data => {
console.log(data.toString());
});
Copy the code
Note: Using spawn or execFile is not always safe. For example, running /bin/find and passing in user input parameters could still cause the system to be compromised. The find command has options that allow you to read/write arbitrary files.
- Avoid child_process.exec, especially if you need to include user-entered parameters.
- Try to avoid having the user pass in parameters; it’s much better to use options than to have the user directly enter strings.
- If the user must be allowed to enter parameters, refer to the parameters of the command to determine which options are secure and create a whitelist.
Reference article:
- Six common Web security attacks and defenses are analyzed
- Three offensive and defensive positions for Web security
- Three offensive and defensive positions on Web security