What is AJAX?

AJAX is an acronym for Asynchronous javascript and XML, in which javascript is used to manipulate XML (and now JSON) in an Asynchronous manner.

  • With the advent of Google Maps, the ability to communicate with servers without a page refresh quickly became known.

  • In the traditional Web model, the client sends a request to the server, and the server returns the entire page.

  • The way we learned about transferring data from a form form is in the traditional Web model. When we click the Submit button, the entire page is refreshed.

  • The form has three important properties: Method, Action, and encType.

  • Method, usually get or post;

  • Action is the address to which we want to send the data;

  • Enctype is whether to encode data.

  • The default value for encType is “application/ X-www-from-urlencoded”, that is, all characters are coded before sending, and this attribute value is coded even if we don’t write it.

  • However, when using a form that contains a file upload control, this value must be changed to “multipart/ FROm-data”, meaning that no characters are encoded.

  • In the AJAX model, data is transferred independently between the client and the server, and the server does not return the entire page.

AJAX advantages

  • 1, the page is not refreshed, in the page content and server communication, to the user’s experience is good
  • 2. Communicate with the server asynchronously without interrupting user operations, providing better user experience
  • 3. Lighten the server load
  • 4. No plug-ins and applets

AJAX shortcomings

1. Browser backing is not supported. 2. Security problems, XSS cross-site scripting attack, SQL injection attack. 3. Poor SEO support for search engines. 4. Mobile devices are not supported. 5. Defeat the purpose of URLS and resource targeting.Copy the code

Common Web attack methods: SQL injection, XSS cross-site scripting attack, CSRF cross-site request forgery

1. SQL injection

The principle of

SQL injection is to use SQL commands to insert query strings into web forms to submit or input domain names or page requests, and ultimately to trick the server into executing malicious SQL commands. SQL:

  • Select * from student where username= ‘username’ and password= ‘username’

  • Enter user name –> ‘or ‘1’ = ‘1’ or ‘1’ = ‘1’

  • Enter the password –> 1 ‘or ‘1 ‘=’ 1′

  • select * from student where username=” or ‘1’ = ‘1’ or ‘1’ = ‘1’ and password= “

  • select * from student where username=” and password=’1′ or ‘1’=’1′

The WHERE condition of the above two SQL statements is always true, so validation is always valid.

Enter the user name –> Tom ‘; drop table student- –

  • select * from student where username=’tom’ ; drop table student–‘ and password=”
  • Alter table student drop (double hyphens indicate comments);

defense

1, do not trust the user’s input, the user’s input can be verified through regular expressions (must be numbers, specific string, phone, email re), or limit the length; Convert single quotes and double “-“, etc

2, never use dynamic assembled SQL, can use parameterized SQL or directly use stored procedures for data query ‘ ‘access. Prepare PreparedStatement with placeholders, even if the parameter is a constant. For example, “Select * from table where comment like?” .

Note: If the parameter is not used as a placeholder, it is not precompiled when executed in a PreparedStatement.

3. Never connect to a database with administrator privileges

Use a separate authorized database connection for each application to reduce the risk of database password leakage.

4. Do not store confidential information directly

Encrypt or hash out passwords and sensitive information; For example, database connection passwords, user passwords, and device passwords must be encrypted and stored.

2 XSS cross-site scripting attacks

2.1 the principle

XSS(Cross Site Scripting) Cross-site Scripting attacks

  • Refers to when the attacker isA web pageThe embeddedClient-side scripts (such as JavaScript)
  • When the user browses the page, the script is inExecute on user's browserIn order to achieve the purpose of attackers, such as access to users’ cookies, navigation to malicious websites, carrying Trojan horses and so on.

1. Dom-based XSS vulnerability

Dom-based XSS, that is, the Web Server is not involved, just the browser’s XSS. The Search. JSP page in test.com has XSS vulnerability. The Search.

<html>
    <title></title> 
	<body> 
    	Results  for  <%=request.getParameter("term")%>...  
	</body>  
</html> 
Copy the code

A Preparation: 1, stolen information website badboy.com 2, malicious URL: test.com/search.asp?…

Method: (email, QQ) and other methods to user B. Little B clicks on the URL, the malicious Javascript code embedded in the URL will be executed in little B’s browser, and little B’s cookie on test.com will be sent to badboy. So little B’s information on Test.com was stolen by Little A

2, Stored XSS vulnerability

For example, an application queries data from the database and displays it on the page. After the attacker inputs malicious script data on the page, users may be attacked when browsing such pages, making all users accessing the page face the possibility of information leakage.

Little C discovered an XSS vulnerability on Website A that allowed the attack code to be saved in the database, so little C published an article with malicious JavaScript code embedded in it. When other people like Little D visit this article, the malicious Javascript code embedded in the article will be executed in little D’s browser, and its session cookies or other information will be stolen by little C.

Dom-based XSS vulnerability threatens individual users, while stored XSS vulnerability threatens a large number of users.

Defensive measures

1. Mark important cookies as HTTP only. If the HttpOnly attribute is set in cookies, then js scripts will not be able to read cookie information, which can effectively prevent XSS attacks and steal cookie content, thus increasing the security of cookies. Don’t store important information in cookies, either.

2. Input filtering verification, verify the validity of data submitted by users, and only accept content submitted within the specified length and in accordance with our expected format. Filter common sensitive characters such as < > ‘” & # \; Filter or remove special Html tags, such as <script>, <iframe>, < for <, > for >, “for”; Filter JavaScript event tags, such as “οnclick=”, “onfocus”, and so on. Here in addition to the foreground to do data verification, also want to do background.

3, DOM type XSS attack defense to output variables to the page to do the relevant coding escape work. To output to <script>, you can encode JS; To output to HTML content or attributes, the HTML encoding is processed. Different coding methods are adopted according to different contexts.

3 CSRF cross-site request forgery

Cross-site Request Forgery (CSRF) although it sounds a lot like an XSS cross-site scripting attack, CSRF masquerades a user’s request to access a site that the user has authenticated to perform specific operations without authorization. CSRF attacks are less prevalent and harder to defend against than XSS, and therefore more dangerous than XSS.

To guard against

1. The current mainstream approach is to use CSRF Token to defend against CSRF attacks. Add a randomly generated Token value to each HTTP request, usually named _cSRF and hidden, and then verify it by the server.

Note: the token value of _cSRF is usually placed in the request parameter or request header, and cannot be placed in the cookie, because the cookie can be obtained in the browser. In addition, we usually carry the CSRF Token in the update operation, so that it will not affect the external query operation to visit our website, and it is not easy to cause the leakage of the Token. Note that the update operation of the CSRF Token should be designed to be idempotent.

2. Another emerging approach is to use the SameSite property of the cookie, which is the set-cookie specified property that cannot be carried when a request comes from outside the cookie. Such as

Set-Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly; SameSite=Lax

  • 1 SameSite has two values:
  • Strict – fromAll requests for the same siteHave to carry cookies,Any other external requestsCan’t carry cookies.
  • Lax – When fromThe same siteOr top-level navigation requests, and the request isIdempotent times carry cookies, otherwise no other request can carry cookies.

In this way, we can carry the cookie of JSESSIONID when we browse the secure bank website and send the request, while the request from the external malicious website cannot carry the cookie, and the server will reject the request after verification.

Question:

  • In an email linkJump to a social networking siteWhen,Cookie cannot be carriedWill ask youTo log in again, bringing inconvenience to users. And some older browsers may not support itSameSiteProperties. Therefore, SameSite is not recommended as the only way to protect against CSRF.

If the service provides requests for non-browser users, do not enable CSRF defense.

Principles and prevention of HTTP network hijacking and DNS hijacking

Original text: blog.csdn.net/weixin_3436…

  • DNS hijacking DNS servers are assigned by carriers, so carriers can do whatever they want on this node. Access jiankang.qq.com/index.html, for example, DNS should return to tencent’s IP, and DNS hijacking, returns an operator in the middle of the server IP. A visit to this server consistently returns 302, redirecting the user’s browser to a pre-processed page with ads, where iframe opens the user’s original address.

  • DNS hijacking returns 302 to redirect the user’s browser to another address. (This is what phishing sites do.)

  • HTTP hijacking is performed on the router node of the carrier, and protocol detection is configured. If HTTP requests and HTML requests are found, they are intercepted and processed. There are two common types:

    • Insert JS or DOM nodes into the HTML data returned by the server (ads)

What about being hijacked?

  • For users, the most direct is to complain to the operator.
  • Add to the HTML<meta http-equiv="Cache-Control" content="no-siteapp"> <meta http-equiv="Cache-Control" content="no-transform " />Baidu officialTranscoding statement is disabled.
  • The most useful way to useHTTPS, don’t let the data so obvious streaking. HTTPS plus SSLData encryption.
  • Add it to the developed web pageCode filtering, the general idea is to use JavaScript code to checkAll the outer chainsWhether to belong toWhite list.

There are all kinds of hijacking methods: 1. Directly return an HTML with an advertisement 2. Insert JS in the original HTML, and then insert ads through JS script; 3. Iframe displays the original normal web page.

  • Js actually against the original: www.cnblogs.com/kenkofox/p/… 1. For DIV injection, you can check all HTML code at initialization. 2. For JS injection, you can listen for DOMNodeInserted event at window. 3. In the case of iframe, it is very simple to check if self and top are the same.

Return to ajax

AJAX’s two most important objects

  • New XMLHttpRequest() is supported by mainstream browsers
  • New ActiveXObject(‘ microsoft.xmlhttp ‘) Forever, god.

Three important methods on the object

Open (method, url, flag? Setting up a call to the server,

  • Method: get post put**
  • The second parameter url: relative url and absolute URL
  • The third optional parameter is asynchrony and synchronization. Asynchrony is true.

Send (Content) Sends a request to the server

SetRequestHeader (lable, value) specifies the header and calls the open method before setting any header

Object properties

Onreadystatechange statechange trigger

2. ReadyState Object state (request)

Zero means uninitialized and now you've created an XMLHttpRequest object and one means reading, Now the code has called the open method of XMLHttpRequest and the XMLHttpRequest has sent the request 2 means it's read and now the open method has sent a request to the server, 3 indicates that the HTTP response header has been received at this point in the interaction, but the body of the message has not been received. 4 indicates that the response has been fully acceptedCopy the code

ResponseText specifies the text version of the data returned by the responseXML server process.

There are five categories of status codes

  • 1XX (information class status), the received request is being processed
  • 2xx (success status code), the request is accepted
  • 3xx (redirection status code), additional action is required to complete the request
  • 4xx (client error status code), the server cannot request
  • 5xx (server error status code), server processing request error

Common status code

Reference the original status code: www.cnblogs.com/TankXiao/ar…

2xx

  • The 200 OK request has been processed by the server
  • 204 No Content The request was processed successfully, but no resources can be returned
  • 206 Partial Content Indicates that the client made a Range request and the server successfully executed the Partial Content request. Content-range is in the header
3xx
  • 301 Moved Permanently The URL of the Permanently redirected request has been removed. The Response should contain a Location URL that indicates where the resource is now located
  • 302 Found Temporary redirection Similar to 301 The client will resend the HTTP request using the URL given in Location
  • 303 SeeOther Similar to 302
  • The 304 Not Modified client cache resource is up to date and requires the client to use the cache
  • 307 Temporary Redirect Indicates Temporary redirection, which is the same as 302.

4XX Client error

  • 400 Bad Request A Request error exists in the Request packet
  • 401 Unauthorized Unauthorized Authentication information required for HTTP authentication
  • 403 Forbidden Forbidden access to the resource. The server rejects the request. The possible cause is that the token or cookie authentication information is not contained
  • 404 The server does not have the resource

5XX Server error

  • 500 Internal Server Error The Server encounters an Error during the request
  • 503 Service Unavailable The server is down. The server is temporarily overloaded or stopped for maintenance and cannot process requests

Status summary

1xx

2xx

3xx

The redirect status code is used to tell browser clients that the resource they are accessing has been moved, and the Web server sends a redirect status code and an optional Location Header to tell the client where the new resource is located. The browser client automatically resends the new Request with the address provided in Location. This process is transparent to the user.

301 and 302 are very similar in that one is a permanent transfer and the other is a temporary transfer.

(In SEO, if the search engine encounters 301, for example, page A redirects to page B with 301, the search engine can be sure that page A has permanently changed its address, and will take page B as the only valid target)

302,303,307 is the same thing. This is because 302 was defined in HTTP 1.0 and 303,307 is used in HTTP1.1. So in this section, we only need to know 302 and 304.

4xx

5xx

Sometimes the client sends a valid Request and the Web server itself makes an error. Maybe the Web server is running incorrectly, or the Web site is down

Promise based Ajax encapsulation

Cache problems of Internet Explorer of earlier versions

Problem: In earlier versions of Internet Explorer, Ajax requests have serious caching issues, meaning that only the first request is actually sent to the server without the request address changing. Subsequent requests will fetch the result from the browser’s cache, and even if the server updates the data, the client will still get the old data from the cache. Solution: add parameters after the request address to ensure that the value of each request parameter is different

xhr.open("GET","http://xxx.xx? t="+new Date().getTime())Copy the code

Onload/onreadystatechange compatibility

How to interrupt a request

Use the abort() method to abort an asynchronous request in progress. Before using abort(), you should clear the onReadyStatechange event handler. Internet Explorer and Mozilla also activate this event handler after the request abort. If you set the onReadyStatechange property to null, an exception will occur in Internet Explorer. So you can set an empty function for it

 xhr.onreadystatechange = function(){};
 xhr.abort();
Copy the code

AJAX

function ajax(json) { return new Promise((resove, reject) => { let {url, method = 'get', flag, data} = json; let xhr = null; if(window.XMLHttpRequest) { xhr = new window.XMLHttpRequest(); } else { xhr = new ActiveXObject('Mircosoft.XMLHTTP'); } const stringParam = getStringParam(data); if(method == 'get') { url = addQueryToUrl(stringParam, url); xhr.open('get', url, flag) } else { xhr.open('post', url, Onload xhr.onload = function() {const result = {status: xhr.status, statusText: function() {const result = {status: xhr.status, statusText: xhr.statusText, headers: xhr.getAllResponseHeader(), data: xhr.response || xhr.responseText, } if((xhr.status >= 200 $$ xhr.status < 300) || xhr.status === 304) { resolve(result) } else { reject(result); } } xhr.onreadystatechange = function() { if(xhr.readyState === 4 && ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) { const result = { status: xhr.status, statusText: xhr.statusText, headers: xhr.getAllResponseHeader(), data: XHR. Response | | XHR. The responseText} resolve (result)}} XHR. Onerror = function () {reject (nex TypeError (' request error)} Xhr.timeout = function() {reject(new TypeError(' request timeout '))} xhr.onabort = function() {reject(new TypeError(' request timeout ')); xhr.onabort = function() {reject(new TypeError(' request timeout ')); } // Cross-domain with cookie xhr.withCredentials = true; if(method === 'post') { xhr.setRequestHeader("Content-type", "application/x-www-from-urlencoded"); xhr.send(stringParam); }else { xhr.send(); } }) } const addQueryToUrl = function(stringParam, url, isNeedTimestamp) { if(! url) return ''; let _url = url; If (url.indexof ('? ') {// If (url.indexof ('? ') > -1) { _url = url.split('? ') [0]; } let result = '? '; result += stringParam; return `${_url}${result}${isNeedTimestamp ? `&t=new Date().getTime() : ''}` } const getStringParam = (param) { if(! param || ! Object.keys(param).length) return ''; let dataString = ''; for (const key in param) { if(param[key] ! == undefined && param[key] ! == null) { dataString += `${key}=${param[key]}&`; }} // Remove the last & and return dataString.slice(0, -1); }Copy the code