Home php教程 php手册 PHP+MYSQL网站SQL Injection攻防

PHP+MYSQL网站SQL Injection攻防

Jun 21, 2016 am 08:56 AM
nbsp quot select sql

程序员们写代码的时候讲究TDD(测试驱动开发):在实现一个功能前,会先写一个测试用例,然后再编写代码使之运行通过。其实当黑客SQL Injection时,同样是一个TDD的过程:他们会先尝试着让程序报错,然后一点一点的修正参数内容,当程序再次运行成功之时,注入也就随之成功了。

进攻:

假设你的程序里有类似下面内容的脚本:

$sql = "SELECT id, title, content FROM articles WHERE id = {$_GET['id']}";

正常访问时其URL如下:

/articles.php?id=123

当黑客想判断是否存在SQL Injection漏洞时,最常用的方式就是在整形ID后面加个单引号:

/articles.php?id=123'

由于我们没有过滤$_GET['id']参数,所以必然会报错,可能会是类似下面的信息:

supplied argument is not a valid MySQL result resource in ...

这些信息就足以说明脚本存在漏洞了,我们可以再耍点手段:

/articles.php?id=0 union select 1,2,3

之所以select 1,2,3是因为union要求两边的字段数一致,前面是id,title,content三个字段,后面1,2,3也是三个,所以不会报语法错误,还有设置id=0是一条不存在的记录,那么查询的结果就是1,2,3,反映到网页上,原本显示id的地方会显示1,显示title的地方会显示2,显示content的地方会显示3。

至于如何继续利用,还要看magic_quotes_gpc的设置:

当magic_quotes_gpc为off时

/articles.php?id=0 union select 1,2,load_file('/etc/passwd')

如此一来,/etc/passwd文件的内容就会显示在原本显示content的地方。

当magic_quotes_gpc为on时

此时如果直接使用load_file('/etc/passwd')就无效了,因为单引号被转义了,但是还有办法:

/articles.php?id=0 union select 1,2,load_file(char(47,101,116,99,47,112,97,115,115,119,100))

其中的数字就是/etc/passwd字符串的ASCII:字符串每个字符循环输出ord(...)

除此以为,还可以使用字符串的十六进制:字符串每个字符循环输出dechex(ord(...))

/articles.php?id=0 union select 1,2,load_file(0x2f6574632f706173737764)

这里仅仅说了数字型参数的几种攻击手段,属于冰山一角,字符串型参数等攻击手段看后面的文档链接。

防守:

网络上有一些类似SQL Injection Firewall的软件可供使用,比如说GreenSQL,如果网站已经开始遭受SQL Injection攻击,那么使用这样的快捷工具往往会救你一命,不过这样的软件在架构上属于一个Proxy的角色,多半会影响网站并发性能,所以在选择与否这个问题上最好视客观条件来慎重决定。很多时候专业的软件并不是必须的,还有很多轻量级解决方案,下面演示一下如何使用awk来检测可能的漏洞。

创建detect_sql_injection.awk脚本,内容如下(如果要拷贝一下内容的话记得不要包括行号):

01 #!/bin/gawk -f
02
03 /\$_(GETPOSTCOOKIEREQUEST)\s*\[/ {
04     IGNORECASE = 1
05     if (match($0, /\$.*(sqlquery)/)) {
06         IGNORECASE = 0
07         output()
08         next
09     }
10 }
11
12 function output()
13 {
14     $1 = $1
15     print "CRUD: " $0 "\nFILE: " FILENAME "\nLINE: " FNR "\n"
16 }


此脚本可匹配出类似如下的问题代码,想要扩展匹配模式也容易,只要照猫画虎写if match语句即可。

1:$sql = "SELECT * FROM users WHERE username = '{$_POST['username']}'";
2:$res = mysql_query("SELECT * FROM users WHERE username = '{$_POST['username']}'");


使用前别忘了先chmod +x detect_sql_injection.awk,有两种调用方法:

1:./detect_sql_injection.awk /path/to/php/script/file
2:find /path/to/php/script/directory -name "*.php" xargs ./detect_sql_injection.awk


会把有问题的代码信息显示出来,样子如下:

CRUD: $sql = "SELECT * FROM users WHERE username = '{$_POST['username']}'";
FILE: /path/to/file.php
LINE: 123


现实环境中有很多应用这个脚本的方法,比如说通过CRON定期扫描程序源文件,或者在SVN提交时通过钩子方法自动匹配。

使用专业工具也好,检测脚本亦罢,都是被动的防守,问题的根本始终取决于在程序员头脑里是否有必要的安全意识,下面是一些必须要牢记的准则:

1:数字型参数使用类似intval,floatval这样的方法强制过滤。
2:字符串型参数使用类似mysql_real_escape_string这样的方法强制过滤,而不是简单的addslashes。
3:最好抛弃mysql_query这样的拼接SQL查询方式,尽可能使用PDO的prepare绑定方式。
4:使用rewrite技术隐藏真实脚本及参数的信息,通过rewrite正则也能过滤可疑的参数。
5:关闭错误提示,不给攻击者提供敏感信息:display_errors=off。
6:以日志的方式记录错误信息:log_errors=on和error_log=filename,定期排查,Web日志最好也查。
7:不要用具有FILE权限的账号(比如root)连接MySQL,这样就屏蔽了load_file等危险函数。
8:......

网站安全其实并不复杂,总结出来就是一句话:过滤输入,转义输出。其中,我们上面一直讨论的SQL Injection问题就属于过滤输入问题,至于转义输出问题,其代表是Cross-site scripting,但它不属于本文的范畴,就不多说了。

文档:

addslashes() Versus mysql_real_escape_string()
SQL Injection with MySQL
Advanced SQL Injection with MySQL
MySQL注入中导出字段内容的研究——通过注入导出WebShell



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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks 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)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to turn off private browsing authentication for iPhone in Safari? How to turn off private browsing authentication for iPhone in Safari? Nov 29, 2023 pm 11:21 PM

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode

Usage of division operation in Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Win10/11 digital activation script MAS version 2.2 re-supports digital activation Win10/11 digital activation script MAS version 2.2 re-supports digital activation Oct 16, 2023 am 08:13 AM

The famous activation script MAS2.2 version supports digital activation again. The method originated from @asdcorp and the team. The MAS author calls it HWID2. Download gatherosstate.exe (not original, modified) from https://github.com/massgravel/Microsoft-Activation-Scripts, run it with parameters, and generate GenuineTicket.xml. First take a look at the original method: gatherosstate.exePfn=xxxxxxx;DownlevelGenuineState=1 and then compare with the latest method: gatheros

What does the identity attribute in SQL mean? What does the identity attribute in SQL mean? Feb 19, 2024 am 11:24 AM

What is Identity in SQL? Specific code examples are needed. In SQL, Identity is a special data type used to generate auto-incrementing numbers. It is often used to uniquely identify each row of data in a table. The Identity column is often used in conjunction with the primary key column to ensure that each record has a unique identifier. This article will detail how to use Identity and some practical code examples. The basic way to use Identity is to use Identit when creating a table.

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

See all articles