php sql注入与防注入经典案例分析
对于sql注入与防注入其实就是一个攻与防的,今天我们要告诉大家最基本的注入和防止方法,原理都是利用了php或mysql的一些特性而我们没注意所造成的.
一个简单的SQL注入攻击案例
假如我们有一个公司网站,在网站的后台数据库中保存了所有的客户数据等重要信息,假如网站登录页面的代码中有这样一条命令来读取用户信息,代码如下:
<?php $q = "SELECT `id` FROM `users` WHERE `username`= ' " . $_GET['username'] . " ' AND `password`= ' " . $_GET['password'] . " ' "; ?>
现在有一个黑客想攻击你的数据库,他会尝试在此登录页面的用户名的输入框中输入以下代码:;SHOW TABLES;点击登陆键,这个页面就会显示出数据库中的所有表,如果他现在使用下面这行命令:;DROP TABLE [table name];这样他就把一张表删除了.
当然,这只是一个很简单的例子,实际的SQL注入方法比这个要复杂得多,黑客也愿意花大量的时间来不断尝试来攻击你的代码,有一些程序软件也可以自动地来不断尝试SQL注入攻击,了解了SQL注入的攻击原理后,我们来看一下如何防范SQL注入攻击.
magic_quotes_gpc = On 时的注入攻击
当 magic_quotes_gpc = On 时,攻击者无法对字符型的字段进行 SQL 注入,这并不代表这就安全了,这时,可以通过数值型的字段进行SQL注入.
在最新版的 MYSQL 5.x 中,已经严格了数据类型的输入,已默认关闭自动类型转换。数值型的字段,不能是引号标记的字符型。也就是说,假设 uid 是数值型的,在以前的 mysql 版本中,这样的语句是合法的,代码如下:
INSERT INTO tbl_user SET uid="1";SELECT * FROM tbl_user WHERE uid="1";
在最新的 MYSQL 5.x 中,上面的语句不是合法的,必须写成这样,代码如下:
INSERT INTO tbl_user SET uid=1;SELECT * FROM tbl_user WHERE uid=1;
这样我认为是正确的,因为作为开发者,向数据库提交正确的符合规则的数据类型,这是最基本的要求.
那么攻击者在 magic_quotes_gpc = On 时,他们怎么攻击呢?很简单,就是对数值型的字段进行 SQL 注入,以下列的 php 脚本为例,代码如下:
<?php if (isset($_POST["f_login"])) { // 连接数据库... // ...代码略... // 检查用户是否存在 $t_strUid = $_POST["f_uid"]; $t_strPwd = $_POST["f_pwd"]; $t_strSQL = "SELECT * FROM tbl_users WHERE uid=$t_strUid AND password = '$t_strPwd' LIMIT 0,1"; if ($t_hRes = mysql_query($t_strSQL)) { // 成功查询之后的处理. 略... } } ?> <html><head><title>sample test</title></head> <body> <form method=post action=""> User ID: <input type="text" name="f_uid" size=30><br> Password: <input type=text name="f_pwd" size=30><br> <input type="submit" name="f_login" value="登录"> </form> </body>
上面这段脚本要求用户输入 userid 和 password 登入,一个正常的语句,用户输入 1001和abc123,提交的 sql 语句如下:
SELECT * FROM tbl_users WHERE userid=1001 AND password = 'abc123' LIMIT 0,1
如果攻击者在 userid 处,输入:1001 OR 1 =1 #,则注入的sql语句如下:
SELECT * FROM tbl_users WHERE userid=1001 OR 1 =1 # AND password = 'abc123' LIMIT 0,1,攻击者达到了目的.
防范SQL注入 - 使用mysql_real_escape_string()函数,在数据库操作的代码中用这个函数mysql_real_escape_string()可以将代码中特殊字符过滤掉,如引号等,如下例:
<?php $q = "SELECT `id` FROM `users` WHERE `username`= ' " . mysql_real_escape_string($_GET['username']) . " ' AND `password`= ' " . mysql_real_escape_string($_GET['password']) . " ' "; ?>
防范SQL注入 - 使用mysql_query()函数
mysql_query()的特别是它将只执行SQL代码的第一条,而后面的并不会执行,回想在最前面的例子中,黑客通过代码来例后台执行了多条SQL命令,显示出了所有表的名称,所以mysql_query()函数可以取到进一步保护的作用,我们进一步演化刚才的代码就得到了下面的代码:
<?php //connection $database = mysql_connect("localhost", "username", "password"); //db selection mysql_select_db("database", $database); $q = mysql_query("SELECT `id` FROM `users` WHERE `username`= ' " . mysql_real_escape_string($_GET['username']) . " ' AND `password`= ' " . mysql_real_escape_string($_GET['password']) . " ' ", $database); ?>
除此之外,我们还可以在PHP代码中判断输入值的长度,或者专门用一个函数来检查输入的值,所以在接受用户输入值的地方一定要做好输入内容的过滤和检查,当然学习和了解最新的SQL注入方式也非常重要,这样才能做到有目的的防范,如果使用的是平台式的网站系统如Wordpress,要注意及时打上官方的补丁或升级到新的版本,如果有讲得不对的地方或不理解的请在评论区留言.
php.ini 中的 display_errors 选项,应该设为 display_errors = off,这样 php 脚本出错之后,不会在 web 页面输出错误,以免让攻击者分析出有作的信息.
调用 mysql_query 等 mysql 函数时,前面应该加上 @,即 @mysql_query(...),这样 mysql 错误不会被输出,同理以免让攻击者分析出有用的信息,另外,有些程序员在做开发时,当 mysql_query出错时,习惯输出错误以及 sql 语句,代码如下:
<?php $t_strSQL = "SELECT a from b...."; if (mysql_query($t_strSQL)) { // 正确的处理 } else { echo "错误! SQL 语句:$t_strSQL \r\n错误信息" . mysql_query(); exit; } ?>
这种做法是相当危险和愚蠢的,如果一定要这么做,最好在网站的配置文件中,设一个全局变量或定义一个宏,设一下 debug 标志.
全局配置文件中,代码如下:
define("DEBUG_MODE",0); // 1: DEBUG MODE; 0: RELEASE MODE
调用脚本中,代码如下:
<?php $t_strSQL = "SELECT a from b...."; if (mysql_query($t_strSQL)) { // 正确的处理 } else { if (DEBUG_MODE) echo "错误! SQL 语句:$t_strSQL \r\n错误信息" . mysql_query(); exit; } ?>
永久链接:
转载随意!带上文章地址吧。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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

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,

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

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 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.
