Home Database Mysql Tutorial 技巧和诀窍:防范SQL注入攻击

技巧和诀窍:防范SQL注入攻击

Jun 07, 2016 pm 03:23 PM
g sql Skill attack injection precaution

Tip/Trick: Guard Against SQL Injection Attacks 【原文发表日期】 Saturday, September 30, 2006 9:11 AM SQL注入攻击是非常令人讨厌的安全漏洞,是所有的web开发人员,不管是什么平台,技术,还是数据层,需要确信他们理解和防止的东西。不幸的是,开发人

Tip/Trick: Guard Against SQL Injection Attacks
【原文发表日期】 Saturday, September 30, 2006 9:11 AM

SQL注入攻击是非常令人讨厌的安全漏洞,是所有的web开发人员,不管是什么平台,技术,还是数据层,需要确信他们理解和防止的东西。不幸的是,开发人员往往不集中花点时间在这上面,以至他们的应用,更糟糕的是,他们的客户极其容易受到攻击。

Michael Sutton 最近发表了一篇非常发人深省的帖子,讲述在公共网上这问题是多么地普遍。他用Google的Search API建了一个C#的客户端程序,寻找那些易受SQL 注入攻击的网站。其步骤很简单:

  1. 寻找那些带查询字符串的网站(例如,查询那些在URL里带有 "id=" 的URL)
  2. 给这些确定为动态的网站发送一个请求,改变其中的id=语句,带一个额外的单引号,来试图取消其中的SQL语句(例如,如 id=6' )
  3. 分析返回的回复,在其中查找象“SQL” 和“query”这样的词,这往往表示应用返回了详细的错误消息(这本身也是很糟糕的)
  4. 检查错误消息是否表示发送到SQL服务器的参数没有被正确加码(encoded),如果如此,那么表示可对该网站进行SQL注入攻击

对通过Google搜寻找到的1000个网站的随机取样测试,他检测到其中的11.3%有易受SQL注入攻击的可能。这非常,非常地可怕。这意味着黑客可以远程利用那些应用里的数据,获取任何没有hashed或加密的密码或信用卡数据,甚至有以管理员身份登陆进这些应用的可能。这不仅对开发网站的开发人员来说很糟糕,而且对使用网站的消费者或用户来说更糟糕,因为他们给网站提供了数据,想着网站是安全的呢。

那么SQL注入攻击到底是什么玩意?

有几种情形使得SQL注入攻击成为可能。最常见的原因是,你动态地构造了SQL语句,却没有使用正确地加了码(encoded)的参数。譬如,考虑这个SQL查询的编码,其目的是根据由查询字符串提供的社会保险号码(social security number)来查询作者(Authors):

 

Dim SSN as String
Dim 
SqlQuery as String

SSN Request.QueryString("SSN")
SqlQuery 
"SELECT au_lname, au_fname FROM authors WHERE au_id = '" + SSN + "'"

 

如果你有象上面这个片断一样的SQL编码,那么你的整个数据库和应用可以远程地被黑掉。怎么会呢?在普通情形下,用户会使用一个社会保险号码来访问这个网站,编码是象这样执行的:

 

' URL to the page containing the above code
http://mysite.com/listauthordetails.aspx?SSN=172-32-9999

' SQL Query executed against the database 
SELECT au_lname, au_fname FROM authors WHERE au_id '172-32-9999'

 

这是开发人员预期的做法,通过社会保险号码来查询数据库中作者的信息。但因为参数值没有被正确地加码,黑客可以很容易地修改查询字符串的值,在要执行的值后面嵌入附加的SQL语句 。譬如,

 

' URL to the page containing the above code
http://mysite.com/listauthordetails.aspx?SSN=172-32-9999';DROP DATABASE pubs --

' SQL Query executed against the database 
SELECT au_lname, au_fname FROM authors WHERE au_id = '';DROP DATABASE pubs --

注意到没有,我可以在SSN查询字符串值的后面添加“ ';DROP DATABASE pubs -- ”,通过 “;”字符来终止当前的SQL语句,然后添加了我自己的恶意的SQL语句,然后把语句的其他部分用“--”字符串注释掉。因为我们是手工在编码里构造SQL语句,我们最后把这个字符串传给了数据库,数据库会先对authors表进行查询,然后把我们的pubs数据库删除。“砰(bang)”的一声,数据库就没了!

万一你认为匿名黑客删除你的数据库的结果很坏,但不幸的是,实际上,这在SQL注入攻击所涉及的情形中算是比较好的。一个黑客可以不单纯摧毁数据,而是使用上面这个编码的弱点,执行一个JOIN语句,来获取你数据库里的所有数据,显示在页面上,允许他们获取用户名,密码,信用卡号码等等。他们也可以添加 UPDATE/INSERT 语句改变产品的价格,添加新的管理员账号,真的搞砸你(screw up your life)呢。想象一下,到月底检查库存时,发现你库房里的实际产品数与你的帐目系统(accounting system)汇报的数目有所不同。。。

那该如何保护你自己?

SQL注入攻击是你需要担心的事情,不管你用什么web编程技术,再说所有的web框架都需要担心这个的。你需要遵循几条非常基本的规则:

1) 在构造动态SQL语句时,一定要使用类安全(type-safe)的参数加码机制。大多数的数据API,包括ADO和ADO.NET,有这样的支持,允许你指定所提供的参数的确切类型(譬如,字符串,整数,日期等),可以保证这些参数被恰当地escaped/encoded了,来避免黑客利用它们。一定要从始到终地使用这些特性。

例如,在ADO.NET里对动态SQL,你可以象下面这样重写上述的语句,使之安全:

Dim SSN as String Request.QueryString("SSN")

Dim cmd As 
new SqlCommand("SELECT au_lname, au_fname FROM authors WHERE au_id = @au_id")
Dim param 
= new SqlParameter("au_id", SqlDbType.VarChar)
param.Value 
SSN
cmd.Parameters.Add(param)

这将防止有人试图偷偷注入另外的SQL表达式(因为ADO.NET知道对au_id的字符串值进行加码),以及避免其他数据问题(譬如不正确地转换数值类型等)。注意,VS 2005内置的TableAdapter/DataSet设计器自动使用这个机制,ASP.NET 2.0数据源控件也是如此。

一个常见的错误知觉(misperception)是,假如你使用了存储过程或ORM,你就完全不受SQL注入攻击之害了。这是不正确的,你还是需要确定在给存储过程传递数据时你很谨慎,或在用ORM来定制一个查询时,你的做法是安全的。

2) 在部署你的应用前,始终要做安全审评(security review)。建立一个正式的安全过程(formal security process),在每次你做更新时,对所有的编码做审评。后面一点特别重要。很多次我听说开发队伍在正式上线(going live)前会做很详细的安全审评,然后在几周或几个月之后他们做一些很小的更新时,他们会跳过安全审评这关,推说,“就是一个小小的更新,我们以后再做编码审评好了”。请始终坚持做安全审评。

3) 千万别把敏感性数据在数据库里以明文存放。我个人的意见是,密码应该总是在单向(one-way )hashed过后再存放,我甚至不喜欢将它们在加密后存放。在默认设置下,ASP.NET 2.0 Membership API 自动为你这么做,还同时实现了安全的SALT 随机化行为(SALT randomization behavior)。如果你决定建立自己的成员数据库,我建议你查看一下我们在这里发表的我们自己的Membership provider的源码。同时也确定对你的数据库里的信用卡和其他的私有数据进行了加密。这样即使你的数据库被人入侵(compromised)了的话,起码你的客户的私有数据不会被人利用。

4) 确认你编写了自动化的单元测试,来特别校验你的数据访问层和应用程序不受SQL注入攻击。这么做是非常重要的,有助于捕捉住(catch)“就是一个小小的更新,所有不会有安全问题”的情形带来的疏忽,来提供额外的安全层以避免偶然地引进坏的安全缺陷到你的应用里去。

5) 锁定你的数据库的安全,只给访问数据库的web应用功能所需的最低的权限。如果web应用不需要访问某些表,那么确认它没有访问这些表的权限。如果web应用只需要只读的权限从你的account payables表来生成报表,那么确认你禁止它对此表的 insert/update/delete 的权限。

如何了解更多的相关知识

微软Prescriptive Architecture Guidance (PAG)产品组发表了许多非常棒的安全指导方针方面的文档,你应该留出些时间来阅读一下:

  • ASP.NET 2.0 安全指定方针
  • ASP.NET 2.0 安全部署清单
  • ASP.NET 2.0 安全实践概述
  • Web应用工程安全索引
  • 如何对托管编码进行安全编码审评
  • ASP.NET 2.0 安全问题列表
  • ASP.NET 2.0 安全培训单元(Training Modules)

此外,还有这些其他的PAG How-To文章对进一步了解如何保护你免受注入攻击大有用处:

  • 如何在ASP.NET里防范表单注入攻击
  • 如何在ASP.NET里防范SQL注入攻击

你还可以在我写的这篇关于安全的博客帖子以及我的ASP.NET 技巧和诀窍页上找到关于ASP.NET安全方面的有用的信息。

更新: Bertrand给我指出了他2年前写的这篇关于SQL注入攻击的非常棒的帖子,非常值得一读。

希望本文对你有所帮助,

Scott

ASP.NET, Security, Tips and Tricks

 

(思归译)  
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

Video Face Swap

Video Face Swap

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

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)

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

Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Mar 27, 2024 pm 02:57 PM

Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

A must-have for veterans: Tips and precautions for * and & in C language A must-have for veterans: Tips and precautions for * and & in C language Apr 04, 2024 am 08:21 AM

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

Win11 Tricks Revealed: How to Bypass Microsoft Account Login Win11 Tricks Revealed: How to Bypass Microsoft Account Login Mar 27, 2024 pm 07:57 PM

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.

In-depth understanding of function refactoring techniques in Go language In-depth understanding of function refactoring techniques in Go language Mar 28, 2024 pm 03:05 PM

In Go language program development, function reconstruction skills are a very important part. By optimizing and refactoring functions, you can not only improve code quality and maintainability, but also improve program performance and readability. This article will delve into the function reconstruction techniques in the Go language, combined with specific code examples, to help readers better understand and apply these techniques. 1. Code example 1: Extract duplicate code fragments. In actual development, we often encounter reused code fragments. At this time, we can consider extracting the repeated code as an independent function to

Instead of fighting, play ball! Introduction to the gameplay of the new mode of 'Eternal Tribulation': Hot-Blooded Fighting Ball Instead of fighting, play ball! Introduction to the gameplay of the new mode of 'Eternal Tribulation': Hot-Blooded Fighting Ball Apr 11, 2024 pm 01:52 PM

Tired of playing ranked? Then come and play ball! Teammates who cooperate tacitly can give opponents a taste of surprise! In the ever-changing battlefield, try to see how you can use your skills to break the situation with one move! "Eternal Tribulation" has launched a new team confrontation mode in the update on April 11. The following is an introduction to the "Eternal Tribulation" hot-blooded fighting ball activity. Overview of how to play the everlasting hot-blooded fighting ball: Use various means to bounce the fighting ball and defeat the enemy. Number of people: 9 people in single row, 6 people in three rows. How to play: Round: 1. The game is divided into multiple rounds. At the beginning of each round, Douqiu will be born in the center of the field and randomly select a player to chase. Players use various means to attack. The ball will speed up the fighting ball, and being hit by the fighting ball will deduct your stamina. 2. Each person in the single row has one point of physical strength each round, and each person in the three rows has one point of physical strength each round.

PHP replacement skills revealed! PHP replacement skills revealed! Mar 28, 2024 am 08:57 AM

Title: PHP replacement skills revealed! PHP, as a popular server-side scripting language, is often used to handle data replacement and manipulation. In daily development, we often encounter situations where strings need to be replaced. This article will reveal some commonly used replacement techniques in PHP and give specific code examples to help readers better master these techniques. 1. Use the str_replace() function The str_replace() function is one of the most commonly used string replacement functions in PHP. it can

BitMEX exchange withdrawal rules and advantages and disadvantages BitMEX exchange withdrawal rules and advantages and disadvantages Feb 21, 2025 pm 10:48 PM

BitMEX exchange currency withdrawal requirements: Two-step verification and identity verification must be completed. The minimum amount of withdrawal varies by currency. The withdrawal process includes logging into the account, entering the withdrawal address, entering the amount and confirming transactions. The advantages of BitMEX withdrawal include fast processing, low handling fees, multiple currency support and strict security measures. However, it also faces shortcomings such as insufficient supervision, risk of hacker attacks, restrictions on withdrawals and account freezes.

See all articles