In our earlier tutorial on SQL Injection, one way to have prevented the SQL injection attack was by simply having the user input sanitized – which we briefly discussed. Since we are dealing with email addresses in our example, this means that we should be able to safely exclude certain characters which don’t normally appear in email addresses. Here is a list of characters that would normally appear in emails, and anything else should not be allowed inside the database – the user should just receive an error saying something like “Invalid email address” if he tries to input an email address with any characters other than the ones below:

  1. abcdefghijklmnopqrstuvwxyz
  2. ABCDEFGHIJKLMNOPQRSTUVWXYZ
  3. 0123456789
  4. ! $ & * - = ^ ` | ~ # % ' + / ? _ { } @ .

Sanitizing input is not enough to prevent SQL injection

Unfortunately, just sanitizing user inputs is not enough to prevent SQL injection – as you will see in the examples below. So, let’s explore some other options and see what works and why – it’s good to know all the options, so be sure to read everything.

Subscribe to our newsletter for more free interview questions.

What about escaping strings? Shouldn’t this remove the threat of quotes in SQL injection?

In case you forgot what “escaping” means in the context of programming, basically it’s just allowing special characters (like single/double quotes, percent signs, backslashes, etc.) in strings to be saved so that they remain as part of the string, and are not mis-interpreted as something else. For example, if we want to include a single quote in a string that gets output to the browser in PHP (note in the word “it’s” we have a single quote that will be output), then we have to add a backslash to the single quote so that PHP outputs it as a single quote:

  1. echo 'Programmer Interview - It\'s Great!';

So, when this is displayed on a webpage it will look like:

  1. Programmer Interview - It's Great!

This is what’s called escaping strings. If we did not escape the quote in our string then it would not output anything, and would result in a PHP error because the quote is also used to enclose the characters in an echo statement.

Now, how would escaping the quotes have helped in our previous example? Remember our hacker is trying to input this harmful/malicious code into the email form field:

  1. Y';
  2. UPDATE table
  3. SET email = 'hacker@ymail.com'
  4. WHERE email = 'joe@ymail.com';

What if we escape the quotes in the string above before we pass the SQL to the database? Well, that would mean the quotes in the string become a part of the string that is searched for using the Emailinput field – in effect the query is searching for an email address that is equal to that giant string. In other words, the quotes are part of the string literal, and will not be interpreted as SQL. In MySQL, we can escape a quote simply by prepending a quote with another quote – basically 2 single quotes will be interpreted as one quote – which is what we do in the example below. So, the actual SQL that will be run looks like this:

  1. SELECT data
  2. FROM table
  3. WHERE Emailinput = Y''; --the quote after the Y is escaped
  4. UPDATE table SET email = ''hacker@ymail.com'' -- escape quotes
  5. WHERE email = ''joe@ymail.com'' ”; --and, more quotes escaped

The key in the example above is that the quotes are now being treated as part of a string that gets compared to a field in the table, and NOT being translated as actual SQL – it’s very important that you understand the distinction because it is exactly the problem that escaping quotes solves for us.

If we do not escape quotes, it allows those quotes to become part of the SQL, and basically allows the hacker to run 2 statements at once – which is exactly what is so dangerous. The 2nd statement (the “ UPDATE table SET email = ‘hacker@ymail.com’ WHERE email = ‘joe@ymail.com';”) is what really messes things up, because it allows the hacker to change the email address of an existing account to his own email address. And, that 2nd statement is only allowed to run because the quotes are not escaped. Escaping a string is also known as quotesafing, since you are essentially making the SQL query “safe” for quotes.

Just Escaping Strings Does Not Prevent SQL Injection

Although we went through an example in which escaping the string prevented the SQL injection attack, just escaping strings is actually not enough protection against SQL injection attacks. A decent hacker can run another attack, by exploiting the fact that some databases allow people to escape strings in more than just one way. MySQL actually allows you to escape quotes in a variety of different ways – in fact as you can see below in some information pulled straight from the MySQL reference pages, you can easily escape quote characters by preceding them with a backslash – a “\” :

  1. There are several ways to include quote characters within a
  2. string that goes into a MySQL query:
  3. 1.A '” inside a string quoted with “' may be written as ''”.
  4. 2.A "” inside a string quoted with “" may be written as ""”.
  5. 3.Precede the quote character by an escape character (“\”).

Let’s say that we choose to escape quotes manually by just adding a single quote every time a string comes in with a quote. Because, if we have a name field, we want to allow people with quotes in their name to be able to save their name without any issues – for instance, someone with the name Jack O’Leary should be able to be saved in our database without the quote causing any issues.

So, if we are retrieving someone’s name from our database, then the SQL may look like this:

  1. SELECT *
  2. FROM customers
  3. WHERE name = 'Jack O’’Leary'; -- this works great

And this works perfectly fine because the double quotes will be interpreted as a single quote, and MySQL will search for Jack O’Leary (with one quote), and not Jack O’’Leary (with 2 quotes).

 

But, let’s say a clever hacker realizes that you may be running a MySQL database, and knows that MySQL also allows you to escape quotes by preceding the quote character with a backslash – so a quote could also be escaped like this: \’

So, our clever hacker tries to insert a string like this into the email field on our form:

  1. \'; DROP TABLE users;

But after we do our own manual string escaping (by adding the extra quote), that string turns into this:

  1. \''; DROP TABLE users; --

So, the SQL that is run will look like this:

  1. SELECT *
  2. FROM customers
  3. WHERE name = '\''; DROP TABLE users; --';

What happens when this SQL is run? Well, the ‘\’’ gets interpreted by MySQL as a string with a single quote, meaning that the system will just search for a name with a single quote. The 2nd quote (the one that comes after the \’), will allow the hacker to close the first statement, insert a semicolon, and then run another malicious statement (the DROP TABLE users; code).

The hacker essentially fools the system into NOT escaping one of the extra quotes by taking advantage of 2 things here:

  • 1. The application developer is trying to escape quotes himself by just appending an extra quote.
  • 2. MySQL supports escape mechanisms other than just appending a quote. In this case, the hacker also used the backslash escape mechanism to run his malicious code.

Remember, the quotes are key because it allows the hacker to close one statement and run any extra statement of his or her choosing.

Let’s repeat this again: Just escaping quotes is not enough to prevent SQL injection

The lesson here is that escaping quotes is unfortunately not enough to prevent all SQL injection attacks, and also extremely difficult to do correctly on your own. And because of the latter, many languages that provide database interface libraries have a function that will handle escaping strings for you. These functions will handle both parsing of the string and quotesafeing as well – so when you use those functions you have a much better chance of getting things done correctly.

If you are looking for actual examples of those functions, PHP has a function called mysql_real_escape_string and Perl’s DBD module has a function called quote. You absolutely should be using these functions before using form data in your queries.

The best way to prevent SQL Injection – Prepared Statements

But, the best way to prevent SQL injection is to use prepared statements. You can (and should) read about prepared statements and their role in preventing SQL injection here:Prepared Statements and SQL Injection

How to prevent SQL injection attacks?的更多相关文章

  1. Exploiting second-order SQL injection 利用二阶注入获取数据库版本信息 SQL Injection Attacks and Defense Second Edition

    w SQL Injection Attacks and Defense  Second Edition Exploiting second-order SQL injection Virtually ...

  2. 防sql注入之参数绑定 SQL Injection Attacks and Defense

    http://php.net/manual/zh/pdo.prepared-statements.php 预处理语句与存储过程 很多更成熟的数据库都支持预处理语句的概念.什么是预处理语句?可以把它看作 ...

  3. 防sql注入之参数绑定 SQL Injection Attacks and Defense 预处理语句与存储过程

    http://php.net/manual/zh/pdo.prepared-statements.php 预处理语句与存储过程 很多更成熟的数据库都支持预处理语句的概念.什么是预处理语句?可以把它看作 ...

  4. PHP MySQLi Prepared Statements Tutorial to Prevent SQL Injection

    https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection#introduction On ...

  5. SQL injection

    SQL injection is a code injection technique, used to attack data-driven applications, in which malic ...

  6. SQL injection:Summary ,Overview and Classification

    What is SQL injection (SQLi)? SQL注入是一种web安全漏洞,让攻击者干扰应用程序对其数据库的查询. 它通常使得攻击者查看他们通常无法检索的数据. 这可能包括属于其他用户 ...

  7. Blind SQL injection:盲注详解

    什么是盲注? 当应用程序易受SQL注入攻击,但其HTTP响应不包含相关SQL查询的结果或任何数据库错误的详细信息时,就会出现盲SQL注入. 对于盲目SQL注入漏洞,许多技术(如联合攻击)都是无效的,因 ...

  8. SQL injection : UNION attacks

    当应用程序易受SQL注入攻击并且查询结果在应用程序的响应中返回时,可以使用UNION关键字从数据库中的其他表检索数据.这将导致SQL注入联合攻击. UNION关键字允许您执行一个或多个附加的SELEC ...

  9. How to Prevent Cross-Site Scripting Attacks

    How to Prevent Cross-Site Scripting Attacks Reference From: http://resources.infosecinstitute.com/ho ...

随机推荐

  1. SolrCloud-4.10.2源代码启动流程梳理

    SolrCloud-4.10.2源代码 web.xml中filter配置 SolrDispatchFilter <filter-name>SolrRequestFilter</fil ...

  2. 如何在 ejs 模板中使用 helper function 外部函数进行特殊处理?

    一般我们想要在 ejs 模板中使用外部函数用于特殊的处理,比如:<%= ellipsis(title, 30) %> 通常的做法是: 使用 app.locals 来定义: app.loca ...

  3. BZOJ 2957 & 线段树上的查询

    题意: 小A的楼房外有一大片施工工地,工地上有N栋待建的楼房.每天,这片工地上的房子拆了又建.建了又拆.他经常无聊地看着窗外发呆,数自己能够看到多少栋房子. 为了简化问题,我们考虑这些事件发生在一个二 ...

  4. Android ListView item项 显示动画

    (1)使用LayoutAnimation 所谓的布局动画,其实就是为ViewGroup添加显示动画效果,主要用过LayoutAnimationController来控制实现.LayoutAnimati ...

  5. ubifs核心功能 -- 垃圾回收

    可回收空间的分类 垃圾回收的目的是再利用(回收后的空间大小能写入有效的node),如果再利用的价值越低,其回收的必要性越低.为了进行有效的垃圾回收,UBIFS对可回收空间做了2个层次的水线划分: 死空 ...

  6. GO语言练习:组合的用法

    1.代码 2.运行 1.代码 package main import "fmt" type Base struct { Name string } func (base * Bas ...

  7. linux文本操作界面 vi面板如何复制一行

    linux文本操作界面 vi面板如何复制一行 1)把光标移动到要复制的行上2)按yy3)把光标移动到要复制的位置4)按p 在vi里如何复制一行中间的几个字符?如果你要从光标处开始复制 4 个字符,则先 ...

  8. 如何将maven项目导入MyEclipse

    一.安装maven第一步:下载一个免安装版的apache-maven-3.0.3.zip解压后,配置环境变量 新建M2_HOME:   在path后面添加  %M2_HOME%\bin;   第二步: ...

  9. Hadoop.2.x_无秘钥设置

    1.在实际生产环境中为Hadoop配置无秘钥登录非常有必要 # 在没有配置时: [liuwl@linux-66-64 hadoop-2.5.0]$ jps 26163 Jps [liuwl@linux ...

  10. Daily Scrum 10.31

    今天是万圣节,也是编译课程设计第一次作业截至的日子,但由于大家对时间的合理安排,我们还是完成了一定的任务量. 下面是今天的Task统计: 不仅燃尽图和燃速图出不来,连那个所有迭代状态的图也出不来了.. ...