今天,一基友问我一个问题说:为什么SQL注入要加单引号,这个当时我一时也回答不上,怪就怪自己理论太菜,不过回去仔细思考了一下,觉得这个问题也是蛮简单的。

首先大家应该明白的一点就是SQL注入的目的:加单引号是为了让后台SQL语句执行的时候报错,这样,我们就可以初步判断单引号被放在SQL语句中执行了,只是执行的语句因为有单引号而出错了,这里我都有点啰嗦了,笑。

要防御这种单引号攻击,服务器有3种办法:

1、  将单引号过滤或者替换 – 一般程序都是这样做的

2、  将单引号转义 – 所谓转义就是让它成为一个普通的字符,而不具备执行功能,php常用addslashes()函数完成这一功能

3、  将服务器设置为不允许爆错或者爆404 not found

下面详细的介绍一下SQL注入的基本原理

SQL注入是什么?

引用老外的话来说,SQL注入是这样描述的:

SQL injection is a code injection technique, used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker).SQL injection must exploit a security vulnerability in an application's software, for example, when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database.

SQL injection (SQLI) is considered one of the top 10 web application vulnerabilities of 2007 and 2010 by the Open Web Application Security Project. In 2013, SQLI was rated the number one attack on the OWASP top ten.

There are five main sub-classes of SQL injection:

1:Classic SQLI

2:Blind or Inference SQL injection

3:Database management system-specific SQLI

4:Compounded SQLI

5:The Storm Worm is one representation of Compounded SQLI

哎,其实这些描述我也看不大懂,怪就只能怪自己英语没认真学啊!

接下来,看看实例代码

1:权限绕过

statement = "SELECT * FROM users WHERE name ='" + userName + "';"

大家觉得这条语句有SQL注入没?

答案是:有SQL注入

如果我们在web中提交:
 
' or '1'='1
 
' or '1'='1' -- 
 
' or '1'='1' ({ 
 
' or '1'='1' /* 

那么,SQL查询逻辑就变成这样子了:

SELECT * FROM users WHERE name = '' OR '1'='1';
SELECT * FROM users WHERE name = '' OR '1'='1' -- ';

如果这些SQL查询放在权限验证的代码中,那么该代码就会爆权限绕过了。

2:多语句执行

例如:我们在web中,对name这个变量提交SQL查询:

a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't

在完整SQL代码中就是这个样子的:

SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't';
 
这段SQL语句执行的结果是:users表被删除了,userinfo表的内容被完全展示出来!
 



 
Tips:
 
While most SQL server implementations allow multiple statements to be executed with one call in this way, some SQL APIs such as PHP's mysql_query() function do not allow this for security reasons. This prevents attackers from injecting entirely separate queries, but doesn't stop them from modifying queries.
 
这个意思最完美,我没翻译,怕翻译出错,呵呵!
 
3:数据类型没有验证
 
例如:SQL语句本来是这样:
 
statement := "SELECT * FROM userinfo WHERE id =" + a_var + ";"
 
这个a_var按正常逻辑来说是int型数据 <虽然用户提交的数据都被server识别为字符 or 字符串>
 
但是,如果Hacker提交如下payload,SQL语句执行结果将会怎样呢?
 
1;DROP TABLE users
 
那么,我们的SQL语句就变成这个样子了:
 
SELECT * FROM userinfo WHERE id=1;DROP TABLE users;

SQL执行的结果是:users表被删除了!

其实,仔细想来,这个地方还是多语句执行造成的,但问题的关键还是programmer没有对用户提交的数据类型做严格检查。

4:SQL盲注

下面科普一下SQL盲注:

Blind SQL Injection is used when a web application is vulnerable to an SQL injection but the results of the injection are not visible to the attacker. The page with the vulnerability may not be one that displays data but will display differently depending on the results of a logical statement injected into the legitimate SQL statement called for that page. This type of attack can become time-intensive because a new statement must be crafted for each bit recovered. There are several tools that can automate these attacks once the location of the vulnerability and the target information has been established.

例如:

Server端SQL查询是这样的:

SELECT * FROM bookreviews WHERE ID = 'Value(ID)';

但是,我们可以将它变成这样:

SELECT * FROM bookreviews WHERE ID = '1' AND '1'='1';
 
SELECT * FROM bookreviews WHERE ID = '1' AND '1'='2';

如果AND 1=1返回正常页面并且AND 1=2返回错误页面,那么,我们就说这个web页面<当然是后台页面>存在SQL盲注,准确一点是基于布尔型的SQL盲注<Boolean-based SQLBI>。

什么time-based SQLBI、error-based SQLBI,这里就不再细说了。

5:二次注入

二次注入的定义:

Second order SQL injection occurs when submitted values contain malicious commands that are stored rather than executed immediately. In some cases, the application may correctly encode a SQL statement and store it as valid SQL. Then, another part of that application without controls to protect against SQL injection might execute that stored SQL statement. This attack requires more knowledge of how submitted values are later used. Automated web application security scanners would not easily detect this type of SQL injection and may need to be manually instructed where to check for evidence that it is being attempted.

具体实例also see:

http://zone.wooyun.org/content/3565

6:十六进制转换,可以防御SQL注入攻击

这个不怎么好描述,我举几个实例,大家应该就明白了:

具体实例also see:

http://www.cnblogs.com/mincyw/archive/2011/02/10/1950733.html

实例代码:

File: test.php
<?php
 
    include_once( "dosql.php" );
#
#   Put your own database information here.  I'm using my log file's data.
#
    $host = "myhost";
    $usr = "myUser";
    $pwd = "myPassword";
    $db = "myDatabase";
 
    $mysqli = new mysqli( $host, $usr, $pwd, $db );
 
    if( $mysqli->connect_errno ){
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
        exit;
        }
    echo "SQL INJECTION - Plain\n";
    $sql = "select * from log where log_id='2' or 1=1; #'";
    $res = dosql( $sql );
    foreach( $res[0] as $k=>$v ){
        echo "RES[$k] = $v\n";
        }
 
    echo "\n\nSQL INJECTION = Hexadecimal\n";
    $sql = "select * from log where log_id=unhex('" . bin2hex("2' or 1=1; #") . "')";
    $res = dosql( $sql );
    foreach( $res[0] as $k=>$v ){
        echo "RES[$k] = $v\n";
        }
 
    exit;
?>
 
File: dosql.php
<?php
 
################################################################################
#   dosql(). Do the SQL command.
################################################################################
function dosql( $sql )
{
    global $mysqli;
 
    $cmd = "insert into log (date,entry) values (NOW(),unhex('" . bin2hex($sql) . "'))";
    $res = $mysqli->query( $cmd );
 
    $res = $mysqli->query( $sql );
    if( !$res ){
        $ary = debug_backtrace();
        if( isset($ary[1]) ){ $a = $ary[1]['line']; }
            else if( isset( $ary[0]) ){ $a = $ary[0]['line']; }
            else { $a = "???"; }
 
        echo "ERROR @ " . $a . " : (" .  $mysqli->errno . ")\n" . $mysqli->error . "\n\n";
        echo "SQL = $sql\n";
        exit;
        }
 
    if( preg_match("/insert/i", $sql) ){ return $mysqli->insert_id; }
    if( preg_match("/delete/i", $sql) ){ return null; }
    if( !is_object($res) ){ return null; }
 
    $cnt = -1;
    $ary = array();
    $res->data_seek(0);
    while( $row = $res->fetch_assoc() ){
        $cnt++;
        foreach( $row as $k=>$v ){ $ary[$cnt][$k] = $v; }
        }
 
    return $ary;
}
 
This outputs:
 
SQL INJECTION - PLAIN
RES[log_id] = 1
RES[date] = 2015-03-25 10:40:18
RES[entry] = show full columns from log
 
SQL INJECTION = Hexadecimal
RES[log_id] = 2
RES[date] = 2015-03-25 10:40:18
RES[entry] = select * from log order by title asc

自己好好去琢磨一下!

Tips:

Note that the PLAIN SQL injection actually works - the first record is returned and not the second. But with the hexadecimal put in the correct record is returned. Thus, by using the BIN2HEX and UNHEX commands you no longer have to worry about SQL Injection attacks.

Additionally, overall, the usage of BIN2HEX and UNHEX requires less time to execute than any of the other methods.

This is NOT to say that you shouldn't do checks of whatever you get back from the browser before you put it in to the database. This isn't a magic wand that will fix everything that has ever been wrong with your database or programs. It does though, make it so you do not have to worry about the kinds of SQL injections presented at the beginning of this webpage. Those it will stop.

SQL注入原理小结的更多相关文章

  1. SQL注入原理及代码分析(一)

    前言 我们都知道,学安全,懂SQL注入是重中之重,因为即使是现在SQL注入漏洞依然存在,只是相对于之前现在挖SQL注入变的困难了.而且知识点比较多,所以在这里总结一下.通过构造有缺陷的代码,来理解常见 ...

  2. SQL注入原理及代码分析(二)

    前言 上一篇文章中,对union注入.报错注入.布尔盲注等进行了分析,接下来这篇文章,会对堆叠注入.宽字节注入.cookie注入等进行分析.第一篇文章地址:SQL注入原理及代码分析(一) 如果想要了解 ...

  3. Java程序员从笨鸟到菜鸟之(一百)sql注入攻击详解(一)sql注入原理详解

    前段时间,在很多博客和微博中暴漏出了12306铁道部网站的一些漏洞,作为这么大的一个项目,要说有漏洞也不是没可能,但其漏洞确是一些菜鸟级程序员才会犯的错误.其实sql注入漏洞就是一个.作为一个菜鸟小程 ...

  4. 回头探索JDBC及PreparedStatement防SQL注入原理

    概述 JDBC在我们学习J2EE的时候已经接触到了,但是仅是照搬步骤书写,其中的PreparedStatement防sql注入原理也是一知半解,然后就想回头查资料及敲测试代码探索一下.再有就是我们在项 ...

  5. 网络对抗课题4.3.1 SQL注入原理与实践

    网络对抗课题4.3.1 SQL注入原理与实践 原理 SQL注入漏洞是指在Web应用对后台数据库查询语句处理存在的安全漏洞.也就是,在输入字符串中嵌入SQL指令,在设计程序中忽略对可能构成攻击的特殊字符 ...

  6. sql注入原理详解(一)

    我们围绕以下几个方面来看这个问题: 1.什么是sql注入? 2.为什么要sql注入? 3.怎样sql注入? 1.什么是sql注入? 所谓SQL注入,就是通过把SQL命令插入到Web表单递交或输入域名或 ...

  7. 1.sql注入原理

    一.什么是sql注入呢?         所谓SQL注入,就是通过把SQL命令插入到Web表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令,比如先前的很多影视网站泄露V ...

  8. SQL注入原理与解决方法代码示例

    一.什么是sql注入? 1.什么是sql注入呢? 所谓SQL注入,就是通过把SQL命令插入到Web表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令,比如先前的很多影视网 ...

  9. sql注入原理及解决方案

    sql注入原理 sql注入原理就是用户输入动态的构造了意外sql语句,造成了意外结果,是攻击者有机可乘 SQL注入攻击指的是通过构建特殊的输入作为参数传入Web应用程序,而这些输入大都是SQL语法里的 ...

随机推荐

  1. matlab 中的textscan

    textread 与textscan的区别  textscan更适合读入大文件: textscan可以从文件的任何位置开始读入,而textread 只能从文件开头开始读入: textscan也可以从上 ...

  2. LeetCode:Single Number II

    题目地址:here 题目大意:一个整数数组中,只有一个数出现一次,其余数都出现3次,在O(n)时间,O(1)空间内找到这个出现一次的数 对于”只有一个数出现一次,其余数出现2次“的情况,很简单,只要把 ...

  3. LeetCode 笔记24 Palindrome Partitioning II (智商碾压)

    Given a string s, partition s such that every substring of the partition is a palindrome. Return the ...

  4. C#基础知识系列一(goto、i++、三元运算符、ref和out、String和string、重载运算符)

    前言 这两天在网上看到的总结很多,尤其是博客园中的,很多很多,也给了我很多的启发,当然自己也总结过,而且有很多人也给与我一些意见和看法.不管怎样,自己还是先把所谓的基础知识加强巩固下吧. 2014年的 ...

  5. 编写高质量代码改善C#程序的157个建议[勿选List<T>做基类、迭代器是只读的、慎用集合可写属性]

    前言 本文已更新至http://www.cnblogs.com/aehyok/p/3624579.html .本文主要学习记录以下内容: 建议23.避免将List<T>作为自定义集合类的基 ...

  6. WCF入门 (14)

    前言 上周去面试,跪了,这一年没什么长进,还是挺惭愧的. 得到的评语是:想的太多,做的太少. 做了一份面试题,最后一题是数据库的,写个查询.要查出Score有两次及两次以上超过79的Name和他的最高 ...

  7. groovyConsole — the Groovy Swing console

    1. Groovy : Groovy Console The Groovy Swing Console allows a user to enter and run Groovy scripts. T ...

  8. 使用Web Deploy进行远程部署

    Web Deploy支持直接从本地Visual Studio的工程文件部署网站到远程服务器,部署的过程中可以对比哪些文件变化了需要拷贝,而不是一股脑的全部拷贝,效率和准确性会更好. 部署的过程主要要注 ...

  9. easyUI icon中文命名图片无法在浏览器中访问处理方法

    本身的原因是Tomcat没有设置URIencoding,导致无法识别 在Tomcat 文件夹 conf 中 server.xml中加 URIEncoding="utf-8"  可以 ...

  10. OpenLayers中地图缩放级别的设置方法

    来源于:http://www.cnblogs.com/sailheart/archive/2011/03/15/1984519.html 一.概述 在OpenLayers中,地图必须具有一个缩放级别的 ...