First, XSS attack
1, explain
XSS means that attackers implant malicious code on the web pages of target websites to hijack normal users and obtain their private information.
Case 2,
Imagine a blog site that allows users to enter comments, and then other users can get comments from other users.
Front page:
<! DOCTYPE html><html>
<head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>function addComment() {
var kkk = $("#add").val() $.ajax({
url: "http://localhost:8081/add".type: 'post'.dataType: 'text'.data: kkk,
success: function() {
alert("Submission successful")},error: function(msg) {
alert("error:"+ msg); }})}</script>
</head>
<body>
<h1>xss:</h1>
<div>
<input type="text" id="add" placeholder="Enter comments">
<button type="button" onclick="addComment()">submit</button></div>
</body>
</html>
Copy the code
func main(a) {
// For simplicity, act as a database
var comment string
http.HandleFunc("/get".func(writer http.ResponseWriter, request *http.Request) {
header := writer.Header()
header.Add("Content-Type"."text/html; charset=UTF-8")
header.Add("Access-Control-Allow-Origin"."*")
header.Add("Access-Control-Allow-Methods"."POST,GET")
writer.WriteHeader(http.StatusOK)
_, _ = writer.Write([]byte(comment))
})
http.HandleFunc("/add".func(writer http.ResponseWriter, request *http.Request) {
s,_ := ioutil.ReadAll(request.Body)
comment = string(s)
header := writer.Header()
header.Add("Content-Type"."text/html; charset=UTF-8")
header.Add("Access-Control-Allow-Origin"."*")
header.Add("Access-Control-Allow-Methods"."POST,GET")
writer.WriteHeader(http.StatusOK)
})
http.ListenAndServe(": 8081".nil)}Copy the code
When an attacker comments, enter the following comment content:
Then a normal user via the url (http://localhost:8081/get) to access the review, leads to be attacked
3, to prevent
As you can see from the previous introduction, XSS attacks have two main elements:
-
The attacker submits malicious code.
-
The browser executes malicious code.
So you can take precautions from the following aspects:
1, for the user input parameters and server output to HTML results are checked, necessary escape;
2. Change to pure front-end rendering, separating code from data.
Pure front-end rendering process:
- The browser first loads a static HTML that does not contain any business-related data.
- The browser then executes the JavaScript in the HTML.
- JavaScript loads the business data through Ajax and calls the DOM API to update it to the page.
In a pure front-end rendering, we explicitly tell the browser whether to set a text (.innertext), an attribute (.setAttribute), a style (.style), etc. Browsers can’t easily be tricked into executing unexpected code.
However, pure front-end rendering also needs to avoid DOM-type XSS vulnerabilities (such as onload events and javascript: XXX in href, see section “Preventing DOM-type XSS attacks” below).
3, CSP
Significance of CSP: XSS and other attack weapon. The essence of CSP is whitelisting. The developer clearly tells the client which external resources can be loaded and executed, which is equivalent to providing a whitelist. Its implementation and execution are all done by the browser, and the developer only needs to provide the configuration. CSP greatly enhances the security of web pages. Even if an attacker discovers a vulnerability, he cannot inject scripts unless he also controls a whitelisted trusted host.
CSRF attack
1, explain
Cross-site Request Forgery (CSRF) : An attacker induces the victim to access a third-party website through emails or advertisement links. In a third-party site, an attacker sends a cross-site request to the site being attacked. By using the registration certificate (cookie) that the victim has obtained from the attacked website, general websites directly judge whether the login is legitimate according to the cookie. Since the victim’s cookie has been obtained, the attacked website will consider it as a legitimate user. This accomplishes the purpose of impersonating the user and performing an action against the site being attacked.
A typical CSRF attack has the following flow:
- Li Si logged into the website helloworld.com and kept the login credentials in the browser Cookie.
- Zhang SAN, a fanatic outside the law, lured Li Si to visit the website cSRf.com through mails and small advertisements.
- The outlaw fanatic Zhang SAN sent a request to HelloWorld.com via the website csrf.com: helloworld.com/action=xx. This is…
- After receiving the request, HelloWorld.com authenticates the requester according to the cookie. Since the cookie is legal, HelloWorld.com considers that it is a legitimate user.
- An outlaw fanatic named John carried out the request on behalf of the victim.
- Attack complete, outside the law fanatics Zhang SAN in the victim’s unaware of the situation, posing as the victim to perform the operation. For example, high-risk operations such as money transfers.
Case 2,
First we write a server response:
func main(a) {
var num = 10
http.HandleFunc("/reduce".func(writer http.ResponseWriter, request *http.Request) {
// Verify cookie, success num--
cookie,_ := request.Cookie("id")
if nil == cookie{
writer.WriteHeader(http.StatusOK)
fmt.Fprint(writer,"cookie is nil")}else if cookie.Value == "hahaha"{
num--
writer.WriteHeader(http.StatusOK)
fmt.Fprint(writer,num)
}
})
// This assumes that the user has logged in successfully, and after entering the page, the server has planted a cookie
http.HandleFunc("/view".func(writer http.ResponseWriter, request *http.Request) {
http.SetCookie(writer,&http.Cookie{
Name: "id",
Value: "hahaha",
})
writer.WriteHeader(http.StatusOK)
fmt.Fprint(writer,num)
})
http.ListenAndServe(": 8081".nil)}Copy the code
The first step:
We will be following url = “http://localhost:8081/reduce” sent to be attacked by mail users, assume that the user clicked, the result will be as follows:
Request failed, then assume that the user to access the url = “http://localhost:8081/view”, to access the above link?
We’ve successfully reduced the value by one. We’ve done our job.
3, to prevent
- CSRF (usually) occurs in third party domain names.
- CSRF attackers cannot obtain information such as cookies, but only use.
In view of these two points, we can formulate special protection strategies as follows:
- Block access to unknown outfields
- Homologous detection
- Samesite Cookie
- Submit by asking for additional information that is available only to the local domain
- CSRF Token
- Double Cookie authentication
Homologous detection
Since most CSRFS come from third-party sites, we simply forbid outlands (or untrusted domain names) from making requests to us.
In HTTP, each asynchronous request carries two headers, which mark the domain name of the source:
- Origin Header
- Referer Header
These two headers are carried automatically in most cases when the browser makes a request, and the content cannot be customized by the front end. The server can determine the source domain of the request by resolving the domain names in the two headers.
== Although CSRF is originated from a third-party domain name in most cases, the local domain cannot be excluded. If an attacker has permission to post comments (including links and images, collectively referred to as UGC) in the local domain, it can directly launch attacks in the local domain. In this case, the same-origin policy cannot protect against attacks. = =
CSRF Token
Another feature of CSRF mentioned above is that attackers cannot directly steal the user’s information (cookies, headers, website content, etc.), but only use the information in cookies.
The CSRF attack succeeds because the server mistook the request sent by the attacker for the user’s own request. Then we can require all user requests to carry a Token that a CSRF attacker cannot obtain. By verifying whether the request carries the correct Token, the server can distinguish the normal request from the attack request and defend against CSRF attacks.
The principle of
The CSRF Token defense policy consists of three steps:
1. Output the CSRF Token to the page
2. The request submitted by the page carries this Token
3. The server verifies the Token