XSS
An overview of the
XSS (Cross Site Script) refers to cross-site scripting attacks. It was originally abbreviated CSS, but changed to XSS to distinguish it from cascading Style Sheet abbreviation (CSS).
attacks
Attackers inject malicious scripts (usually JavaScript) into web pages and tamper with client web pages to steal information. In essence, data is executed as a program.
Injection point for XSS
- HTML node content or attributes that exist to read inputable data
- Javascript code that has variables injected by the background or information entered by the user
- The rich text
XSS hazards
- Steal cookies through Document. cookie
- Using JS or CSS to break the normal structure and style of the page
- Traffic hijacking (by accessing a segment with window.location.href to locate another page:
<script>window.location.href="www.baidu.com"; </script>
) - Dos attack: The use of reasonable client requests to occupy too many server resources, so that legitimate users cannot get a response from the server
- Use iframe, Frame, XMLHttpRequest, or the above Flash method to perform administrative actions as the (attacked) user, or perform general operations such as tweeting, adding friends, and sending private messages
- By taking advantage of the fact that the domain that can be attacked is trusted by other domains, the trusted source requests some operations that are not normally allowed, such as improper voting activities
- Stealing arbitrary data, user data, etc
The types of XSS
Reflective (non-persistent)
Reflective XSS, also known as non-persistent XSS, means that when a request occurs, the XSS code appears in the request URL and is submitted as a parameter to the server, which parses and responds. The response contains XSS code, which is returned to the browser for parsing and execution. This process is like a reflection, so it is called reflective XSS.
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.
This mode only passes through the server, not the database.
Example: When a user searches, click the search button to return to the following link
http://xxx.com/search?keyword= "> < script > alert (' XSS attacks'); </script>Copy the code
When the browser requests, the server parses the keyword parameter and gets “>, spliced into HTML and returned to the browser as follows:
<input type="text" value="" />
<script>
alert('XSS attacks')
</script>
">
<button>search</button>
<div>Your search keywords are: "><script>
alert('XSS attacks')
</script>
</div>
Copy the code
So it was executed.
Storage type (persistent)
Stored XSS, also known as persistent XSS, basically sends XSS code to the server, from which the script is returned and executed when the browser requests data. The difference with reflective XSS is that the submitted code is stored on the server side and no XSS code is submitted the next time the target page is requested.
A common scenario is the message board of a web page. An attacker writes an offensive script code on the message board. After the message is published, all users who visit the message are found to have XSS code after the message content is parsed from the server, so it is executed as normal HTML and JS parsing, and XSS attack occurs.
This approach goes through the server as well as the database.
The DOM model
Dom-based XSS attacks refer to malicious scripts that modify the DOM structure of the page, write the attack script in the URL, and induce the user to click the URL. If the URL is parsed, the attack script will be run. The difference between the previous two XSS attacks is as follows: Taking out and executing malicious code is completed by the browser side without passing through the server side, which belongs to the security vulnerability of front-end JavaScript itself, while the other two XSS belong to the security vulnerability of the server side mainly lies in DOM attacks.
This example is from the DOM attack example
<h2>XSS:</h2>
<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}>testLink</a>`
},
false
)
</script>
Copy the code
Clicking the Submit button inserts a link to the current page with the user’s input. If the user constructs the following as input:
'' onclick=alert(/xss/)
Copy the code
After the user submits, the page code becomes:
<a href onlick="alert(/xss/)">testLink</a>
Copy the code
At this point, the user clicks on the generated link and the corresponding script is executed.
How do I protect against XSS
The general idea is that user input cannot be stored directly to the server, requiring special processing of some data
Set the HttpOnly
HttpOnly is a property that sets whether a cookie can be read by javasript scripts. The browser prevents the page’s Javascript from accessing the cookie with the HttpOnly property.
Strictly speaking, this approach is not to defend against XSS, but to prevent the user from obtaining Cookie data after being attacked by XSS.
CSP content security policy
Content Security Policy (CSP) is an additional security layer used to detect and weaken certain types of attacks, including cross-site scripting (XSS) and data injection attacks.
CSP can configure a Content Security Policy for a page through HTTP headers (Content-security-policy) or elements to control which resources the browser can obtain for that page. For example, a page that can upload files and display images should allow images to come from anywhere, but limit the action attribute of the form to the specified endpoint.
Mainstream browsers now have built-in measures to prevent XSS. Enabling CSP, that is, enabling the whitelist, prevents the loading and running of resources that are not on the whitelist
Input inspection
Encode, decode, and filter any input from the user:
- Encoding: can not keep the user input content as is, the user input data for character entity encoding escape
- Decode: The original display of the content must be decoded, otherwise the content will not be displayed
- Filter: the input of some illegal things are filtered out to ensure security. For example, remove DOM attributes uploaded by users, such as onerror, and remove Style nodes, iframe and Script nodes uploaded by users
Encodes or filters special characters or tags contained in user input, such as <, >, script, to prevent XSS attacks
function escHTML(str) {
if(! str)return ' '
return str
.replace(/&/g.'& ')
.replace(/</g.'< ')
.replace(/>/g.'> ')
.replace(/x27/g.'the & # 039; ')
.replace(/x22/g.'&quto; ')}Copy the code
Output check
There will be problems with the user’s input, and problems with the server’s output. In general, with the exception of rich text output, you can use encoding or escaping to defend against XSS attacks when a variable is output to an HTML page. For example, sanitize-HTML is used to filter the output regularly and then output it to the page.
Input length control
Untrusted input should be limited to a reasonable length. While you can’t completely prevent XSS from happening, you can make XSS attacks more difficult.
Verification code
Prevent scripts from posing as users to submit dangerous operations.
CSRF
An overview of the
Cross Site Request Forgery (CSRF) refers to cross-site Request Forgery, which hijacks trusted users to send unexpected requests to the server. Cross-domain means that the request comes from another site, forgery means that it is not the user’s own intention.
attacks
The attacker lures the victim to a third-party site, where a cross-site request is sent to the targeted site. Using the victim in the attacked website has obtained the registration certificate, bypassing the background user authentication, to impersonate the user to perform a certain operation on the attacked website.
Different from XSS attack: XSS is an injection attack by the attacker directly to our website A, while CSRF is A forged request to our website A through website B.
Example: You log in to the shopping website A and click on A malicious link B. B requests the ordering interface of website A. As A result, an order is generated in website A’s account. The principle behind this is that website B forges the request of website A through forms and GET requests. At this time, the request will carry the cookies of website A. If the login state is saved in cookies, the forgery attack is implemented.
Cross-site requests can be made in a variety of ways: image urls, hyperlinks, CORS, Form submissions, and more. Part of the request can be directly embedded in third party forums, articles.
CSRF harm
- The login status of the user is stolen
- Impersonating a user to perform operations or modify data
The type of CSRF
CSRF of the GET type
This example is introduced from the GET CSRF example
Consider A scenario where target site A(www.a.com), malicious site B(www.b.com)
The domain names of the two sites are different. The target site A has A function to delete articles. Usually, the specified articles will be deleted when the user clicks the ‘Delete Articles’ link. The link is www.a.com/blog/del?id=1, with ids representing different articles. You’re essentially making a GET request
- You cannot make GET requests using Ajax. Because CSRF requests are cross-domain, Ajax has same-origin policy restrictions
- GET requests can be initiated by statically or dynamically creating tags such as IMG and script on malicious website B. The SRC attribute points to
www.a.com/blog/del?id=1
. The same origin policy does not restrict requests that are initiated using tags - Finally, users who have logged in to target website A will be tricked to visit malicious website B, so they will send A request to the background of website A with the login credentials of the source of website A, so that the attack occurs
CSRF attacks have the following key points:
- The request is cross-domain, and you can see that the request was sent from the malicious site B
- Make a GET request with tags img, script, etc., because these tags are not restricted by the same origin policy
- The request made is authenticated
CSRF of the POST type
If the target site A has the ability to publish an article, we can dynamically create A form tag and change the title of the article.
In site B:
function setForm() {
var form = document.createElement('form')
form.action = 'www.a.com/blog/article/update'
form.methods = 'POST'
var input = document.createElement('input')
input.type = 'text'
input.value = 'CSFR attack! '
input.id = 'title'
form.appendChild(input)
document.body.appendChild(form)
form.submit()
}
setForm()
Copy the code
As can be seen from the above code, the form form is dynamically created, and then the submit method is called, and the title of an article on the target website A can be modified through the cross-domain forgery request.
This is usually done with automatically submitted forms
<form action="http://xxx.com/money" method="post">
<input type="hidden" name="account" value="jacky" />
<input type="hidden" name="amount" value="10000" />
</form>
<script>
document.forms[0].submit()
</script>
Copy the code
CSRF of link type
Link-type CSRFS are uncommon and require the user to click a link to trigger them, compared to the other two cases where the user opens the page and is caught. This type usually involves embedding malicious links in the pictures published in the forum, or inducing users to be lured in the form of advertisements. Attackers usually trick users into clicking with exaggerated words, such as:
<a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" taget="_blank">Big news!!</a>
Copy the code
How to prevent CSRF
Verification code
Because CSRF attack forgery request will not pass through the attacked website, we can add verification code in the website, so that the request must pass the verification code, effectively curb CSRF request.
However, this approach is not a panacea, not every request to add captcha, so the user experience will be very bad, only in part of the request to add, as an auxiliary means of defense.
Verify the Referer
In HTTP protocol, there is a Referer field in the header, which records the source address of the HTTP request. By checking this field, you can know whether the request is legitimate. However, the request header is also easy to forge.
Set the cookie SameSite
Set SameSite: Set the SameSite value of the cookie to strict, so that only requests from same-origin sites carry cookies. In this way, cookies cannot be used by other domain sites, thus achieving the purpose of defense.
Adding token Authentication
When the browser requests the server, the server returns a token. Each request must contain both the token and the cookie to be considered a valid request
This is a relatively mature solution. The key to defending against CSRF is to put information in the request that an attacker cannot forge and that does not exist in a Cookie. The token is randomly generated on the server side, added in the form of parameters in the HTTP request, and an interceptor is established on the server side to verify the token. If there is no token in the request or the token content is incorrect, the request may be considered as a CSRF attack and rejected.
Change the login mode scheme
Because CSRF essentially forgery requests to carry information stored in cookies, it is disadvantageous to the login state of session mechanism. If JWT (JSON Web Token) scheme is replaced, its Token information is generally set to the HTTP header. Therefore, it can defend against CSRF attacks.
reference
- WEB Front-end security — XSS and CSRF
- Ps: Personal technology blog Github repository, welcome star