Home  >  Article  >  Operation and Maintenance  >  How to keep the web safe

How to keep the web safe

王林
王林forward
2021-03-09 09:51:384146browse

How to keep the web safe

1. Foreword

In the early days of the development of the Internet, it was still the era of the IE browser. At that time, the purpose of everyone surfing the Internet was to share information and obtain news through the browser. With the rapid development of the Internet, web pages can do more and more things. You can not only read news and play games, but also shop and chat. These functions have greatly enriched our lives.

As the functions of web pages gradually increase, some black hats have begun to appear, and they try to make profits through some technical means. For example, Trojan viruses can monitor your keyboard and send the content you type on the keyboard to the hacker's machine. By analyzing the content, the hacker can easily obtain your game account and password. After that, some anti-virus software was born, dedicated to solving various viruses on the Internet. With continuous development, anti-virus software has become an indispensable software for a computer.

Why does such a security problem occur?

Security is ultimately a matter of trust. If everyone goes online according to normal procedures and does not seek personal gain, there will be no security issues to discuss.

The foundation of security lies in trust, but it is easier said than done to make everyone trust each other. At the current stage, what we can do is: continue to improve security protection, make loopholes less and less, and illegal attacks become more and more difficult. This will gradually reduce the number of black hats and reduce virus creators.

1. How to do a good job in security

To do a good job in security, you must first understand the attributes of security issues. Through countless practices, predecessors finally summarized the attributes of security into three elements of security, which are: :

1) Confidentiality

Protect data content from being leaked. Encryption methods are usually used.

2) Integrity

Protect that the data content is complete and has not been tampered with. Usually digital signature method is used.

3) Availability.

Data can be used at any time. Usually defending against DOS.

2. Security Assessment

After having the 3 elements of security, we can evaluate security issues.

1) Asset level classification

Find out the most important data. Find out the hosting space of the most important data, such as in a database, then the database must focus on defense. Find out the hosting space of the database, for example: on a server, then this server must provide secondary defense. Find out the host space of the server, such as: at the OSI network level, then you have to do general defense at the network level.

2) Threat analysis

Find out threats (sources that may cause harm). Find out the risks (possible losses are called risks).

3) Risk analysis

adopts multi-criteria decision-making analysis, that is: risk = threat level * threat feasibility. Calculate all threats, rank the final risks, and prioritize issues with higher risks.

4) Confirm the solution

Find out the unsafe implementation and determine the solution. The solution should not change the original intention of the business requirement. The solution needs to be transparent to users and not change their habits.

After completing the security assessment, we will have a security solution. For subsequent security work, we only need to follow this plan and there will be no problems.

3. Safety principles

After having a safety solution, we can also formulate some safety principles. Following the principles can help us get twice the result with half the effort.

1) Blacklist and whitelist principles

The whitelist solution refers to authorizing safe resources. Blacklisting scheme refers to disabling unsafe resources. We should give priority to using the whitelist solution, because the blacklist usually cannot count all unsafe resources. For example, there are many ways to attack XSS, including script, css, image tags, etc. Even if you add these tags to the blacklist, there is no guarantee that other tags will not have XSS attack risks.

2) Principle of least privilege

Only grant necessary permissions, do not over-authorize, and reduce the chance of errors. For example: Linux users with ordinary permissions can only operate directories under the ~ folder. If someone wants to delete the library and run away, when executing rm -rf /, it will prompt that there is no permission.

3) Defense in depth principle

This principle is similar to the barrel theory. The safety level often depends on the shortest board. That is: don’t leave any shortcomings. Black hats can often use shortcomings as a breakthrough point to dig out larger loopholes.

4) Principle of separation of data and code

When user data is executed as code, the boundaries between data and code are confused, leading to security issues. For example: XSS uses this to attack.

5) Principle of Unpredictability

This principle is to increase the attack threshold and effectively prevent attacks based on tampering and forgery. For example, using uuid instead of number-type auto-incrementing primary key in the database can prevent the id from being guessed by attackers, allowing batch operations to be performed. Token also takes advantage of unpredictability. The attacker cannot construct the token and cannot attack.

With these security principles in mind, let’s introduce several common attack and defense cases.

2. Security Attack and Defense Cases

There are many security attack and defense cases. Here we mainly introduce a few security issues with a relatively high appearance rate.

(1) Client attack

Mainly include: XSS attacks, CSRF attacks, and click hijacking.

1.

##As shown in the picture, we registered a user name of <script>alert(document.cookie)</script>, and everyone can see this user name On every page, the cookie of the current browser will pop up. If the logic of the code is to send the cookie to the attacker's website, the attacker can log in pretending to be the current user. How to keep the web safe

There are many ways to attack XSS. XSS attacks may exist wherever users interact. For example:

All input boxes.
  • window.location.
  • window.name.
  • document.referrer.
  • document.cookie.
  • localstorage.
  • ...
  • Since there are so many places on the page to interact with users, there must be some XSS attack methods that have not been discovered. Once discovered by a black hat, it may have serious consequences, so we must pay attention to it.
1) Impact of XSS attacks

After a successful XSS attack, the attacker can obtain a large amount of user information, such as:

Identify user UA. Identify user browser extensions. Identify the websites a user has visited. (Via the CSS Visited property.) Get the user’s real IP. (Via WebRTC, etc.) Stealing cookies (forging user logins, stealing user information.) XSS phishing. (Inject a login pop-up window into the page, making the user think it is a login pop-up window within the website (actually from a phishing website). Once the user logs in, the account and password are leaked to the phishing website.)

2) XSS Attack Defense

Currently, XSS has attracted the attention of the Internet industry, and many development frameworks have built-in secure HTML rendering methods.

We can also customize some security configurations.

Configure the http-only header in HTTP so that front-end JS cannot operate cookies. Input checking, using XssFilter to filter out unsafe data when users submit data. Output inspection, filter out dangerous data when the page is rendered.

Simply means: prohibit js from operating cookies, check html when submitting, check html when output (can be transcoded)

2, CSRF attack

CSRF (Cross -site request forgery) Cross-site request forgery is a method of using the user's identity to perform operations that are not intended by the user.

For example:

The user first logged in to server B, and then accessed server C. Server C uses a malicious script to pretend to be A to call a certain function on server B. For server B, it thinks this is a request initiated by A and treats it as a normal request.

Just imagine, if C pretends to be A and makes a transfer, it will definitely cause a lot of economic losses.

1) CSRF defense methods

There are mainly the following ways to defend against CSRF:

a. Verification code Referer check

Requires the user for every request Verification to ensure the request is authentic. That is: taking advantage of the fact that malicious scripts cannot recognize complex verification codes to ensure that every request is legal.

b. Referer check

Check whether the server that initiated the request is the target server. That is: the Referer header in the HTTP request passes the domain name of the current request. If this domain name is the domain name of an illegal server, access needs to be prohibited.

c, Token

Using the principle of unpredictability, each request must carry a random code. This random code is saved by normal users. Black hats do not know the random code and cannot A request was made pretending to be a user.

(Learning video sharing:

php video tutorial

)

3. Click hijacking

Click hijacking is a visual deception attack method. The attacker embeds the website that needs to be attacked into his own web page through iframe nesting, sets the iframe to transparent, and reveals a button on the page to induce users to click.

It’s like a picture with a layer of transparent paper on it. What you see is the attacker’s page, but in fact this page is only at the bottom, and what you actually click on is the attacker’s page. of another web page.

1) Click hijacking defense

Since click hijacking mainly passes through iframe, the defense is mainly based on iframe.

Option 1: frame busting

if (self !== top) {  // 跳回原页面
  top.location = self.location;
}

Normal websites use JS scripts to determine whether they are embedded by malicious websites. For example, if a blog website detects that it is opened by an iframe, it will automatically jump to the normal page. .

Option 2: Use the x-frame-options header in HTTP to control the loading of iframe. It has 3 optional values:

DENY, which means that the page is not allowed to be displayed through iframe. . SAMEORIGIN means that the page can be displayed through iframe under the same domain name. ALLOW-FROM means that the page can be displayed in an iframe from the specified source.

配置 iframe 的 sandbox 属性:sandbox = "allow-same-origin" ,则只能加载与主站同域的资源。

(二)服务端攻击

服务器端的攻击的方式也非常多,这里列举几个常见的。

SQL 注入攻击文件上传漏洞登录认证攻击应用层拒绝服务攻击webServer 配置安全

1、SQL 注入攻击

SQL 注入和 XSS 一样,都是违背了数据和代码分离原则导致的攻击方式。

如图所示,我们利用 SQL 注入,就能在不需要密码的情况下,直接登录管理员的账号。

How to keep the web safe

攻击的前提是:后端只用了简单的拼接 SQL 的方式去查询数据。

// 拼接出来的 sql 如下:select * from user where username = &#39;admin&#39; or 1=1 and password = &#39;xxx&#39;
// 无论密码输入什么,这条 sql 语句都能查询到管理员的信息

除此之外,SQL 注入还有以下几种方式:

a、使用 SQL 探测,猜数据库表名,列名。

通过 MySQL 内置的 benchmark 探测数据库字段。如:一段伪代码 select database as current if current[0]==='a',benchmark(10000,'猜对了') 如果表明猜对了,就延迟 10 s 并返回成功。

b、使用存储过程执行系统命令

通过内置的方法或存储过程执行 shell 脚本。如:xp_cmdshell、sys_eval、sys_exec 等。

c、字符串截断

如:MySQL 在处理超长的字符串时,会显示警告,但会执行成功。注册一个 admin + 50 个空格的用户,会触发截断,最终新增一个 admin 用户,这样就能拥有管理员权限了。

1)SQL 注入防御

防止 SQL 注入的最好的办法就是,不要手动拼接 SQL 语句。

最佳方案,使用预编译语句绑定变量:通常是指框架提供的拼接 SQL 变量的方法。这样的语义不会发生改变,变量始终被当成变量。严格限制数据类型,如果注入了其他类型的数据,直接报错,不允许执行。使用安全的存储过程和系统函数。

2、CRLF 注入

在注入攻击中,换行符注入也是非常常见的一种攻击方式。

如果在 HTTP 请求头中注入 2 个换行符,会导致换行符后面的所有内容都被解析成请求实体部分。攻击者通常在 Set-Cookie 时,注入换行符,控制请求传递的内容。

3、文件上传漏洞

上传文件是网页开发中的一个常见功能,如果不加处理,很容易就会造成攻击。

How to keep the web safe

如图所示,攻击者上传了一个木马文件,并且通过返回的 URL 进行访问,就能控制服务器。

通常我们会控制上传文件的后缀名,但也不能完全解决问题,攻击者还可以通过以下方式进行攻击:

  • 伪造正常文件

  • 将木马文件伪装成正常的后缀名进行上传。

  • 如果要避免这个问题,我们可以继续判断上传文件的文件头前 10 个字节。

  • Apache 解析方式是从后往前解析,直到找到一个认识的后缀名为止

  • 如:上传一个 abc.php.rar.rar.rar 能绕过后缀名检查,但在执行时,被当成一个 php 文件进行执行。

  • IIS 会截断分号进行解析

  • 如:abc.asp;xx.png 能绕过后缀名检查,但在执行时,被当成一个 asp 文件进行执行。

  • HTTP PUT 方法允许将文件上传到指定位置

  • 通过 HTTP MOVE 方法,还能修改上传的文件名。

  • 通过二者配合,就能先上传一个正常的后缀名,然后改为一个恶意的后缀名。

  • PHP CGI 路径问题

  • 执行 http://abc.com/test.png/xxx.php 时,会把 test.png 当做 php 文件去解析。

  • 如果用户正好是把一段恶意的 php 脚本当做一张图片进行上传,就会触发这个攻击。

1)文件上传漏洞防御

防御文件上传漏洞,可以从以下几点考虑:

将文件上传的目录设置为不可执行。判断文件类型检查 MIME Type,配置白名单。检查后缀名,配置白名单。使用随机数改写文件名和文件路径上传文件后,随机修改文件名,让攻击者无法执行攻击。单独设置文件服务器的域名单独做一个文件服务器,并使用单独的域名,利用同源策略,规避客户端攻击。通常做法是将静态资源存放在 CDN 上。

4、登录认证攻击

登录认证攻击可以理解为一种破解登录的方法。攻击者通常采用以下几种方式进行破解:

  • 彩虹表

  • The attacker collects a large number of correspondences between plaintext and MD5 to crack the MD5 ciphertext to find the original text.

  • For the MD5 password in the rainbow table, we can add salt and perform secondary encryption to avoid being cracked.

  • Session Fixation attack

  • Use the application system’s SessionID fixed mechanism on the server to obtain authentication and authorization with the help of others using the same SessionID.

  • After the attacker fails to log in, the backend returns the SessionID. The attacker gives the SessionID to a normal user to log in. After the login is successful, the attacker can use this SessionID to pretend to be a normal user to log in. .

  • This problem can be avoided if the browser refreshes the SessionID every time you log in.

  • Session Keep Attack

  • Sometimes, for the sake of user experience, the backend will not let the user as long as the user is still alive. The Session is invalid.

  • An attacker can keep this Session alive by constantly making requests.

1) Login authentication defense method

Multi-factor authentication password is used as the first line of defense, but after the password verification is successful, we can continue to verify: dynamic password, Digital certificates, SMS verification codes, etc. to ensure user security. Since SMS and web pages are two completely independent systems, it is difficult for an attacker to obtain the SMS verification code and thus cannot carry out attacks.

5. Application layer denial of service attack

Application layer denial of service attack, also called DDOS attack, refers to the use of a large number of requests to cause resource overload, causing the server to become unavailable.

How to keep the web safe

Usually there are the following DDOS attack methods:

  • SYN Flood flood attack

  • Use the HTTP 3-way handshake mechanism to consume server connection resources.

  • For example: an attacker initiates a large number of HTTP requests, but does not complete 3 handshakes, but only 2 handshakes. At this time, the server will continue to wait until timeout. At this time, the server will be busy processing a large number of garbage requests and has no time to take care of normal requests.

  • Slowloris attack

  • Sends HTTP request headers at a very slow rate, consuming server connection resources.

  • For example: an attacker sends a large number of HTTP requests, but each request header is sent very slowly, sending one character every 10 seconds. In order to wait for data, the server must not always maintain the connection, so As soon as it started, the number of server connections was quickly taken up.

  • HTTP POST DOS

  • When sending HTTP, specify a very large Content-Length and then send it at long intervals, consuming server connections resource.

  • CC attack

  • Continuously initiates requests for some very resource-consuming pages.

  • For example: Some pages in the page require a lot of calculations on the back end, or very time-consuming database queries. Under a large number of requests, the server's CPU, memory and other resources may be occupied.

  • Server Limit DOS

  • Inject an overly long cookie through XSS, causing the Request Header length to exceed the capacity of the web server. The server side This service will be denied.

  • ReDOS

  • Aiming at some defective regular expressions, a large number of requests are initiated and system resources are consumed.

1) Application layer denial of service attack defense

There is currently no particularly perfect solution for application layer denial of service attacks, but we can still make some optimizations.

Optimize the performance of the application code and rationally use caching solutions such as Redis and Memcache to reduce CPU resource usage. Optimize the network architecture and build load balancing on the backend. Static resources are managed using a CDN. Limiting the request frequency The server calculates the request frequency of all IP addresses and filters out abnormal IPs for disabling. You can use the LRU algorithm to cache the IP addresses of the first 1,000 requests. If an IP request frequency is too high, disable it.

In fact, the core idea of ​​dealing with DDOS is to disable untrusted users and ensure that resources are used by normal users.

3. WebServer configuration security

When we deploy web applications, we often use Nginx, Apache, IIS, Tomcat, Jboss and other web servers. These servers themselves also have some security risks. , if configured improperly, it is easy to be attacked.

When configuring the Web server, you can refer to the following points:

1. Run the Web server with user permissions

Follow the principle of least privileges and run the Web server with the least privileges , restrict the permissions after being invaded.

2. Delete the visual backend

When running Web servers such as Tomcat and Jboss, a visual operation backend will be enabled by default, running on port 8080, and the first access will not be authenticated.

An attacker can use the visual background to remotely load a war package or upload a Trojan file for control, so we need to delete the visual platform.

3. Update the version in time

Major web servers will fix some vulnerabilities every once in a while, so remember to update the version in time.

Related recommendations: web server security

The above is the detailed content of How to keep the web safe. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete