Home headlines How to prevent web attacks--security issues that PHP beginners need to know

How to prevent web attacks--security issues that PHP beginners need to know

Jul 06, 2017 am 10:01 AM
php web

Common web attacks are divided into two categories: one is to exploit the vulnerabilities of the web server to attack, such as CGI buffer overflow, directory traversal vulnerability exploitation and other attacks; the other is to exploit the security vulnerabilities of the web page itself, such as SQL injection, Cross-site scripting attacks, etc.

Today our php Chinese website will take friends to understand the related security issues of php.

First of all, you can refer to the online tutorial: php Chinese Manual Security.

Must-have PHP video tutorial for beginners: Dugu Jiujian (4)_PHP video tutorial

##SQL Injection

The attacker inserts SQL commands into the input field of the Web form or the string of the page request, tricking the server into executing malicious SQL commands. In some forms, the content entered by the user is directly used to construct (or affect) dynamic SQL commands, or as input parameters for

stored procedures. Such forms are particularly vulnerable to SQL injection attacks.

Common SQL injection attack process categories are as follows:

1. A certain web application has a login page. This login page controls whether the user has To access the application, it requires the user to enter a name and password;


2. The content entered in the login page will be directly used to construct dynamic SQL commands, or directly used as parameters of stored procedures;


For example:

$query = 'SELECT * from Users WHERE login = ' . $username . ' AND password = ' . $password;
Copy after login

3. The attacker enters something like ' or '1' = '1 in the user name and password input box;


4. After the content input by the user is submitted to the server, the server runs the above code to construct a SQL command to query the user. However, because the content input by the attacker is very special, the final SQL command becomes:

SELECT * from Users WHERE login = '' or '1'='1' AND password = '' or '1'='1';
Copy after login

5. The server executes a query or stored procedure to compare the identity information entered by the user with the identity information saved in the server;


6. Since the SQL command has actually been modified by an injection attack, It is no longer possible to truly authenticate the user, so the system incorrectly authorizes the attacker.


If the attacker knows that the application will use the content entered in the form directly for the identity verification query, he will try to enter some special SQL strings to tamper with the query to change its original function and deceive The system grants access.


The system environment is different, and the damage that an attacker may cause is also different. This is mainly determined by the security permissions of the application to access the database. If the user's account has administrator or other relatively advanced rights, the attacker may perform various operations on the database tables that he wants to do, including adding, deleting or updating data, or even directly deleting the table


Prevention method:

1. Check the variable

data type and format

2. Filter special symbols


3. Bind variables and use precompiled statements

Cross Site Scripting (XSS)

The attacker injects malicious code into the web page, and other users will execute the code when loading the web page. The attacker may obtain, but is not limited to, higher permissions (such as performing some operations), Various contents such as private web content, sessions and cookies. These malicious codes are usually JavaScript, HTML and other client-side scripting languages.

For example:

<?php
echo "欢迎您,".$_GET[&#39;name&#39;];
Copy after login

If a script

<script>[code]</script> is passed in, the script will also be executed. Using such a URL will execute the JavaScript alert function and pop up a dialog box: http://localhost/test.php?name=<script>alert(123456)</script>

Commonly used attack methods include:

Steal cookies and obtain sensitive information;


Use iframe, frame, XMLHttpRequest or The above-mentioned Flash and other methods can perform some management actions as the (attacked) user, or perform some general operations such as posting on Weibo, adding friends, sending private messages, etc.;


Use the exploitable The domain is trusted by other domains, and requests some operations that are not normally allowed as a trusted source, such as inappropriate voting activities;


XSS on some pages with a large number of visits can Attack some small websites to achieve the effect of DDoS attack.


Prevention method: Use the

htmlspecialchars function to convert special characters into HTML encoding, and filter the output variables

跨网站请求伪造攻击(Cross Site Request Forgeries, CSRF)

攻击者伪造目标用户的HTTP请求,然后此请求发送到有CSRF漏洞的网站,网站执行此请求后,引发跨站请求伪造攻击。攻击者利用隐蔽的HTTP连接,让目标用户在不注意的情况下单击这个链接,由于是用户自己点击的,而他又是合法用户拥有合法权限,所以目标用户能够在网站内执行特定的HTTP链接,从而达到攻击者的目的。

它与XSS的攻击方法不同,XSS利用漏洞影响站点内的用户,攻击目标是同一站点内的用户者,而CSRF 通过伪装成受害用户发送恶意请求来影响Web系统中受害用户的利益。

例如:

某个购物网站购买商品时,采用shop.com/buy.php?item=watch&num=100
item参数确定要购买什么物品,num参数确定要购买数量,如果攻击者以隐藏的方式发送给目标用户链接那么如果目标用户不小心访问以后,购买的数量就成了100个

防范方法:

1、检查网页的来源

2、检查内置的隐藏变量

3、使用POST,不要使用GET,处理变量也不要直接使用$_REQUEST

Session固定攻击(Session Fixation)

这种攻击方式的核心要点就是让合法用户使用攻击者预先设定的session id来访问被攻击的应用程序,一旦用户的会话ID被成功固定,攻击者就可以通过此session id来冒充用户访问应用程序。

例如:

1.攻击者访问网站bank.com,获取他自己的session id,如:SID=123;
2.攻击者给目标用户发送链接,并带上自己的session id,如:bank.com/?SID=123;
3.目标用户点击了bank.com/?SID=123,像往常一样,输入自己的用户名、密码登录到网站;
4.由于服务器的session id不改变,现在攻击者点击bank.com/?SID=123,他就拥有了目标用户的身份,可以为所欲为了。

防范方法:

1.定期更改session id

session_regenerate_id(TRUE);//删除旧的session文件,每次都会产生一个新的session id。默认false,保留旧的session
Copy after login

2.更改session的名称

session的默认名称是PHPSESSID,此变量会保存在cookie中,如果攻击者不抓包分析,就不能猜到这个名称,阻挡部分攻击

session_name("mysessionid");
Copy after login

3.关闭透明化session id

透明化session id指当浏览器中的http请求没有使用cookie来制定session id时,sessioin id使用链接来传递

int_set("session.use_trans_sid", 0);
Copy after login

4.只从cookie检查session id

int_set("session.use_cookies", 1);//表示使用cookies存放session id
int_set("session.use_only_cookies", 1);//表示只使用cookies存放session id
Copy after login

5.使用URL传递隐藏参数

$sid = md5(uniqid(rand()), TRUE));
$_SESSION["sid"] = $sid;//攻击者虽然能获取session数据,但是无法得知$sid的值,只要检查sid的值,就可以确认当前页面是否是web程序自己调用的
Copy after login

Session劫持攻击(Session Hijacking)

会话劫持是指攻击者利用各种手段来获取目标用户的session id。一旦获取到session id,那么攻击者可以利用目标用户的身份来登录网站,获取目标用户的操作权限。

攻击者获取目标用户session id的方法:

1.暴力破解:尝试各种session id,直到破解为止;

2.计算:如果session id使用非随机的方式产生,那么就有可能计算出来;

3.窃取:使用网络截获,xss攻击等方法获得

防范方法:

      1.定期更改session id

      2.更改session的名称

      3.关闭透明化session id

      4.设置HttpOnly。通过设置Cookie的HttpOnly为true,可以防止客户端脚本访问这个Cookie,从而有效的防止XSS攻击。

文件上传漏洞攻击(File Upload Attack)

文件上传漏洞指攻击者利用程序缺陷绕过系统对文件的验证与处理策略将恶意代码上传到服务器并获得执行服务器端命令的能力。

常用的攻击手段有:

上传Web脚本代码,Web容器解释执行上传的恶意脚本;

上传Flash跨域策略文件crossdomain.xml,修改访问权限(其他策略文件利用方式类似);

上传病毒、木马文件,诱骗用户和管理员下载执行;

上传包含脚本的图片,某些浏览器的低级版本会执行该脚本,用于钓鱼和欺诈。

In general, the uploaded files used are either executable (malicious code) or have the ability to affect server behavior (Configuration file).

Prevention methods:

1. The directory for file upload is set to non-executable;

2. Determine the file type and set a whitelist. For image processing, you can use the compression function or the resize function to destroy the HTML code that may be contained in the image while processing the image;

3. Use random numbers to rewrite the file name and file path: one is to upload Then it will be inaccessible; then files like shell.php.rar.rar and crossdomain.xml will be unable to be attacked due to renaming;

4. Set the domain name of the file server separately: due to Due to the browser's same-origin policy, a series of client-side attacks will be ineffective, such as uploading crossdomain.xml, uploading XSS exploits containing Javascript and other issues will be solved.

Recommended related articles:

1. How to make a highly secure PHP website, summary of security issues that need to be paid attention to when making a website

2. A summary of security issues that need to be paid attention to in php weak types

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.