In the Internet era, data security and personal privacy have been challenged like never before, and various novel attack technologies have emerged one after another. How can we better protect our data? This article mainly focuses on analyzing several common types of attacks and how to defend against them.
XSS (Cross-Site Scripting), a cross-site scripting attack, can only be called XSS because the abbreviation and CSS overlap. A cross-site scripting attack is an attack that runs an illegal HTML tag or j**ascript in the browser of a web**registered user with a security vulnerability.
Cross-site scripting attacks have the potential to have the following effects:
Fraudulent entry forms are used to deceive users into obtaining personal information. Scripts are used to steal the user's cookie value, and the victim unknowingly helps the attacker send malicious requests. Displays fake articles or **. The principle of XSS is that a malicious attacker inserts a malicious executable web script** into a web page, and when the user browses the page, the script embedded in the web will be executed, so that the attacker can steal user information or otherwise violate the user's security and privacy
XSS attacks are very varied, but they can be broadly broken down into several types.
Non-persistent XSS vulnerabilities, usually by sending them to someone elseURLs with malicious script parametersWhen the URL address is opened, the unique malicious parameter is parsed and executed by the HTML.
As an example, let's say a page contains the following:
Attackers can directly access URLs (like:
) to inject executable scripts. However, some browsers, such as Chrome, have built-in XSS filters that prevent most reflective XSS attacks.
Non-persistent XSS exploits have the following characteristics:
Immediacy, without going through the server storage, you can complete an attack directly through HTTP get and post requests, and get the user's private data. Attackers need to trick clicks, and the user must click on the link to initiate a low feedback rate, so it is difficult to find and respond to fix the theft of sensitive confidential information of usersIn order to prevent the emergence of non-persistent XSS vulnerabilities, there are several things that need to be ensured:
All content rendered by a web page or data rendered must come from the server. Try not to start withurl
document.referrer
document.forms
and so on in this DOM API to get the data directly rendered. Try not to use iteval
new function()
document.write()
document.writeln()
window.setinterval()
window.settimeout()
innerhtml
document.createelement()
and other executable strings. If you can't do that, you must escape the string arguments passed in to the methods involved in the DOM rendering. Any field needs to be escaped encoded during front-end rendering. Persistent XSS vulnerabilities generally exist in interactive functions such as form submission, such as article comments, submission of text messages, etc., hackers exploit XSS vulnerabilities to submit content into the database through normal functions for persistent storage, and when the front-end page gets the injection ** read from the database by the back-end, it happens to be rendered and executed.
For example, for the reviewer, it is necessary to protect against persistent XSS attacks, because I can type the following in the comment.
The main injection method is similar to that of non-persistent XSS vulnerabilities, except that the persistent type is not **url, referer, forms, etc.), but **Data read from the database by the backend。Persistent XSS attacks don't need to trick clicks, and hackers only need to inject where the form is submitted, but the cost of this XSS attack is relatively high.
A successful attack requires the following conditions to be met:
The backend of the post request submission form is not escaped and directly stored in the warehouse. The backend takes the data from the database and outputs it directly to the frontend without escaping. The front-end gets the back-end data and doesn't escape it, and it is directly rendered into the dom. Persistent XSS has the following features:
Persistence, embedded in the database to steal users' sensitive and private information, there are generally two ways to defend against XSS attacks.
1) CSPCSP is essentially a whitelist where the developer explicitly tells the browser which external resources can be loaded and executed. We just need to configure the rules, and how to block them is up to the browser itself. In this way, we can minimize XSS attacks.
There are usually two ways to turn on CSP:
Set the content-security-policy in the http header, and set the meta tag in the way to set the http header as an example
Only the resources of this site are allowed to be loaded.
content-security-policy: default-src 'self'
Only the HTTPS protocol is allowed to be loaded**content-security-policy: img-src https://*
Any frame is allowed to be loadedcontent-security-policy: child-src 'none'
For more information, check out the content-security-policy documentation For this approach, as long as the developer configures the correct rules, an attacker cannot execute an attack even if there is a vulnerability, and CSP compatibility is good.
2) Escaping charactersThe user's input can never be trusted, and the most common way is to escape the content of the input and output, escaping quotation marks, angle brackets, and slashes.
function escape(str)
But for displaying rich text, it is obviously not possible to escape all the characters in the above way, because this will filter out the required formatting as well. In this case, whitelist filtering is usually used, and of course, blacklist filtering can also be used, but considering that there are too many tags and tag attributes that need to be filtered, it is more recommended to use whitelist.
const xss = require('xss')let html = xss('')// ->script>alert("xss");console.log(html)
The above example is implemented using js-xss, and 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 cookies. When setting cookies, the web application can set its attribute to httponly, which can prevent the cookie of the web page from being stolen by the malicious j**ascript of the client and protect the user's cookie information.
Cross Site Request Forgery (CSRF) is a common web attack that uses the user's logged-in identity to perform illegal operations on the user's behalf without the user's knowledge.
There are three conditions that must be met to complete a CSRF attack:
The user has logged in to site A and has logged the cookie locally, and without the user logging out of site A (i.e., if the cookie is active), they have visited site B (site B asks to visit site A) provided by a malicious attacker. Site A doesn't do any CSRF defense, let's look at an example: When we log in to the transfer page, suddenly our eyes light upSurprised"xxx privacy**, don't regret it for a lifetime"link, I couldn't resist the inner restlessness, and immediately clicked on the dangerous ** (page** as shown in the figure below), but when this page is loaded, it will be executedsubmitform
This method submits a transfer request, thus transferring 10 blocks to the hacker.
There are a few rules that can be followed to protect against CSRF attacks:
The get request does not modify the data, does not allow third parties to access the user's cookies, prevents third parties from requesting the interface, and the request comes with verification information, such as a verification code or token1) samesite can set the samesite attribute to the cookie. This attribute indicates that cookies are not sent with cross-origin requests, which can greatly reduce CSRF attacks, but this attribute is not currently compatible with all browsers.
2) Referer CheckHTTP The 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 to, so that the server can obtain some information for processing. CSRF attacks can be defended against by inspecting the ** of the request. The referer of a normal request has a certain pattern, for example, the referer that submits the form must be the request initiated on this page. SoCheck whether the value of the HTTP header referer is this page to determine whether it is a CSRF attack
However, in some cases, such as jumping from https to http, the browser is on security and will not send a referer, and the server will not be able to check. If there is an XSS vulnerability in other domains with that one, an attacker can inject malicious scripts into the other ones, and the victim will also be attacked if they enter such one same domain. For these reasons, Referer Check cannot be relied upon as the primary means of defense against CSRF. However, CSRF attacks can be monitored through Referer Check.
3) Anti CSRF Token: The current perfect solution is to add Anti-CSRF-Token. That is, when sending a request, add a randomly generated token in the form of a parameter to the http request, and establish a *** on the server to verify the token. The server reads the token value in the cookie in the current domain of the browser, and verifies whether the token in the request and the token value in the cookie are both present and equal, and then considers this a legitimate request. Otherwise, the request is considered illegal and the service is denied.
This method is much safer than a referer checkThe 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 every time the user logs in and compares it with the token in this request. Due to the existence of the token, the attacker can no longer construct a complete URL to carry out a CSRF attack. However, when dealing with the coexistence of multiple pages, when a page consumes a token, the forms of other pages are still saved with the consumed token, and a token error will appear when the forms of other pages are submitted.
4) During the interaction between the captcha application and the user, especially the core step of account transactions, the user is forced to enter the captcha in order to complete the final request. In general, CAPTCHAs are good enough to contain CSRF attacks. However, adding a captcha reduces the user's experience, and it is not possible to add a captcha to all operations。Therefore, the captcha can only be used as an auxiliary means to set the captcha at key business points.
Clickjacking is a visual deceptive attack vector. The attacker embeds the ** that needs to be attacked into its own web page through iframe nesting, and sets the iframe to be transparent, revealing a button in the page to induce users to click.
It is highly concealed and deceives users to operate"ui - overlay attack"After the user logs in to A's system, the attacker opens a third party, and the third party introduces the content of A's page through the iframe, and the user clicks a button (decorated button) in the third party, which actually clicks A's button.
Let's take an example: I have posted a lot of ** on Youku, and if I want more people to pay attention to it, I can achieve it through clickjacking.
iframe button ..Click **
The attacker uses ** as the page background,Hide the real interface of the user's operation,When you press the button that can't help but be curious,The real click is actually the subscription button of the hidden page,And then you will subscribe without your knowledge。
1)x-frame-optionsx-frame-options
is an HTTP response header that has a good support in modern browsers. This HTTP response header is designed to defend against clickjacking attacks nested with iframes.
There are three values to choose from for this header, which are:
deny, which means that the page is not allowed to display sameorigin in the form of iframe, means that the page can display allow-from in the form of iframe under the same domain name, and means that the page can be displayed in the iframe of specified **2) j**ascript defense For some ancient browsers, the above method cannot be supported, so we can only defend against clickjacking through JS.
The effect of the above ** is that when the page is loaded by iframe, the attacker's web page will not display all the content.
Definition: A security issue that results from directing an application to an unsecured third-party region with the help of an unauthenticated URL redirect.
Hackers exploit the URL jump vulnerability to induce users with low security awareness to click, resulting in user information leakage or loss of funds. The principle is that hackers build malicious links (links need to be disguised to confuse as much as possible) and post them in QQ groups or post them in a post bar forum with a lot of views.
Users with low security awareness click on it, and after being parsed by the server or browser, they jump to the malicious **.
Malicious links need to be disguised, and it is often done to add a malicious ** after the familiar link, so as to confuse users.
For example, if you disguise something like the following, will you be able to identify it as malicious?
header head jump j**ascript jump meta tag jump here we give a header head jump implementation:
Here the user will thinkwww.wooyun.org
are all credible, but clicking on the said link will lead to an end visit by the userwww.evil.com
This malicious**.
1) Referer Restriction If the ** input of the URL parameter is determined, we can implement the security restriction in this way to ensure the validity of the URL and avoid malicious users from generating jump links by themselves.
2) Add validity verification tokenWe ensure that all generated links are from our trusted domain, and by adding tokens that are uncontrollable to users in the generated links to verify the generated links, users can avoid generating their own malicious links and being exploited, but if the function itself is relatively open, it may lead to certain restrictions.
SQL injection is a common web security vulnerability that can be exploited by attackers to access or modify data, or exploit potential database vulnerabilities.
Let's start with an example of *** to illustrate how it works:
The SQL statement on the backend might look something like this:
let querysql = ` select * from user where username='$' and psw='$'`;The next step is to execute the SQL statement.
This is a login page that we often see, but if there is a malicious attacker entering the username isadmin' --
Enter the password at will, and you can log in to the system directly. why!- That's SQL injection.
The SQL statement we had in mind was:
select * from user where username='admin' and psw='password'
But a malicious attacker uses a strange username to turn your SQL statement into something like this:
select * from user where username='admin' --' and psw='xxxx'
In SQL,
is the meaning of closure and comment,-- is the meaning of 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 exploiting SQL injection.
The process of a SQL injection consists of the following processes:
Get the user request parameters and concatenate them into **, in which the SQL statement is executed successfully according to the semantics of the parameters we constructedPrerequisites for SQL Injection:
1.You can control the data you enter.
2.The ** that the server wants to perform stitches together the data that is controlled.
We will find that the SQL injection process is similar to the normal request server, except that the hacker takes control of the data and constructs the SQL query, while the normal request does not SQL query this stepThe essence of SQL injection: the data is not separated, that is, the data is executed as such.
Obtain database information: username and password of the administrator background to obtain other sensitive database information: user name, password, mobile phone number, ID card, bank card information, ......The entire database: Take off your pants to obtain server permissions, implant webshells, and obtain server backdoors to read sensitive server filesSeverely restrict the web app's database operation permissionsto provide the user with the least privileges that can only be used for their work, thereby minimizing the harm to the database from injection attacks.
Backend checks that the data entered is as expected, which strictly restricts the type of variable, such as using regular expressions for some matching processing.
Special characters () for entering the database',", , etc.), etc.), or encoding conversion。Almost all backend languages have a way to escape strings, such as lodashescapehtmlchar library.
It is recommended to use the parameterized query interface provided by the database for all query statements, parameterized statements use arguments instead of embedding user input variables into SQL statements, i.e., do not directly splice SQL statements. For example, node?. in the query method of the mysqljs library in jsPlaceholder parameters.
OS command injection is similar to SQL injection, except that SQL injection is for the database, while OS command injection is for the operating system. An OS command injection attack is the execution of illegal operating system commands through a web application. Wherever shell functions can be called, there is a risk of attack. If there is an omission in invoking the shell, the inserted illegal command can be executed.
A command injection attack can send commands to the shell to launch a program from the command line of a Windows or Linux operating system. In other words, a command injection attack can execute various programs installed on the operating system.
The hacker crafts the command and submits it to the web application, and the web application extracts the hacker-constructed command and splices it into the executed command, because the hacker injects the command to break the original command structure, causing the web application to execute additional commands, and finally the web application outputs the execution result to the response page.
Let's illustrate this with an example, if you need to implement a requirement: the user submits some content to the server, and then executes some system command on the server to return a result to the user.
Take nodejs for example, if you need to specify repoconst exec = require() from github ** user in the interface'mz/child_process').exec;let params = ;exec(`git clone $ /some/path`);
Ifparams.repo
Incoming is:
It does go from **on the specified git repo to what you want**.
But ifparams.repo
Incoming is:&&rm -rf /* &
It just so happens that your service is rooted, and that's bad.
The backend imposes rule restrictions on front-end submissions (e.g., regular expressions). Command line argument escape filtering is performed on all incoming parameters before invoking system commands. Do not directly splice command statements, but use some tools to do splicing and escaping preprocessing, such as nodejsshell-escape npm
Package: Common Web Security Attack and Defense Summary: Front-end Interview: ** How much do you know about httpweb security, clickjacking, url redirect, jump vulnerability, NetEase web white hat.