`
ihuashao
  • 浏览: 4770440 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

Tip/Trick: Guard Against SQL Injection Attacks

阅读更多

SQL Injection attacks are reallynasty security vulnerabilities, and something all web developers (regardless of platform, technology or data layer) need to make sure they understand and protect themselves against. Unfortunately developers too often neglect putting focused time on this - and leave their applications (and worse their customers) extremely vulnerable.

Michael Sutton recently published a very sobering post about just how widespread this issue is on the public web. He built a C# client application that uses the Google Search API to look for sites vulnerable to SQL Injection Attacks. The steps to achieve this were simple:

  1. Look for sites that have querystring values (example: search for URLs with "id=" in the URL)
  2. Send a request to the sites identified as dynamic with an altered id= statement that adds an extra quote to attempt to cancel the SQL statement (example: id=6')
  3. Parse the response sent back to look for words like "SQL" and "query" - which typically indicate that the app is often sending back detailed error messages (also bad)
  4. Review whether the error message indicates that the parameter sent to SQL wasn't encoded correctly (in which case the site is open to SQL Injection Attacks)

Of a random sampling of 1000 sites he found via his Google search, he detected possible SQL Injection Attack vulnerability with 11.3% of them. That is really, really scary. It means hackers can remotely exploit the data in those applications, retrieve any unhashed/encrypted passwords or credit-card data, andpotentially even log themselves in as administratorsto the application. This is bad not only for the developer who built the application, but even worse for any consumer/user of the application who has provided data to the site thinking it will be secure.

So what the heck is a SQL Injection Attack?

There are a couple of scenarios that make SQL Injection attacks possible. The most common cause are cases where you are dynamically constructing SQL statements without using correctly encoded parameters. For example, consider this SQL query code that searches for Authors based on a social security number provided via a querystring:

DimSSNasString
DimSqlQueryasString

SSN=Request.QueryString("SSN")
SqlQuery="SELECTau_lname,au_fnameFROMauthorsWHEREau_id='"+SSN+"'"

If you have SQL code like the snippet above, then your entire database and application can be hacked remotely. How? Well in the normal scenario users will hit the site using a social security number which will be executed like so:

'URLtothepagecontainingtheabovecode
http://mysite.com/listauthordetails.aspx?SSN=172-32-9999

'SQLQueryexecutedagainstthedatabase
SELECTau_lname,au_fnameFROMauthorsWHEREau_id='172-32-9999'

This does what the developer expected, and searches the database for author information filtered by the social security number. But because the parameter value hasn't been SQL encoded, a hacker could just as easily modify the querystring value to embed additional SQL statements after the value to execute. For example:

'URLtothepagecontainingtheabovecode
http://mysite.com/listauthordetails.aspx?SSN=172-32-9999';DROP DATABASE pubs --

'SQLQueryexecutedagainstthedatabase
SELECTau_lname,au_fnameFROMauthorsWHEREau_id= '';DROPDATABASE pubs --

Notice how I was able to addthe ';DROP DATABASE pubs --clause to the SSN querystring value and use it to terminate the current SQL statement (via the ";" character), and then add my own malicious SQL statement to the string, and then comment out the rest of the statement (via the "--" characters). Because we are just manuallyconcatenating the SQL statement in our code, we will end up passing this to the database - which will execute first the query against the authors table, and then delete our pubs database table. Bang - it is now gone.

In case you think the idea of anonymous hackers deleting your database tables is bad, that is unfortunately actually one of the better scenarios when a SQL Injection Attack is involved. Rather than just destroy data, a hacker could instead use the above code vulnerability to perform a JOIN that retrieves all of the data within your database and displays it on the page (allowing them to retrieve username/passwords/credit-cards).They could also add UPDATE/INSERT statements to modify product prices, add new admin users, and really screw up your life (imagine auditing your inventory at the end of the month, only to discover that the actual number of products in your warehouse is different then what your accounting system reports...).

How do you protect yourself?

SQL Injection Attacks are something you need to worry about regardless of the web programming technology you are using (all web frameworks need to worry about it). A couple of very basic rules you must always follow:

1) Don't construct dynamic SQL Statements without using a type-safe parameter encoding mechanism. Most data APIs (including ADO + ADO.NET) have support for allowing you to specify the exact type of a parameter being provided (for example: string, integer, date) and can ensure that they are escaped/encoded for you to avoid hackers trying to exploit it. Always use these features.

For example, with dynamic SQL using ADO.NET you could re-write the code above like below to make it safe:

DimSSNasString=Request.QueryString("SSN")

DimcmdAsnewSqlCommand("SELECTau_lname,au_fnameFROMauthorsWHEREau_id=@au_id")
Dimparam=newSqlParameter("au_id",SqlDbType.VarChar)
param.Value=SSN
cmd.Parameters.Add(param)

This will prevent someone from trying to sneak inadditional SQL expressions (since ADO.NET above knows to string encode the au_id value), and avoid other data problems (incorrectly type-casting values, etc). Note that the TableAdapter/DataSet designer built-into VS 2005uses this mechanism automatically, asdo the ASP.NET 2.0 data source controls.

One common misperception is that if you are using SPROCs or a ORM you are completely safe from SQL Injection Attacks. This isn't true - you still need to make sure you are careful when you pass values to a SPROC, and/or when you escape or customize a query with an ORM that you do it in a safe way.

2) Always conduct a security review of your application before ever put it in production, and establish a formal security process to review all code anytime you make updates. This later point is super important. Too often I hear of teams that conduct a really detailed security review before going live, then have some "really minor" update they make to the site weeks/months later where they skip doing a security review ("it is just a tiny update - we'll code review it later"). Always do a security review.

3) Never store sensitive data in clear-text within a database. My personal opinion is that passwords should always be one-way hashed (I don't even like to store them encrypted). The ASP.NET 2.0 Membership API does this for you automatically by default (and also implements secure SALT randomization behavior). If you decide to build your own membership database store, I'd recommend checking out the source code for our own Membership provider implementation that we published here. Also make sure to encrypt credit-card and other private data in your database. This way even if your database was compromised, at least your customer private data can't be exploited.

4) Ensure you write automation unittests that specifically verify your data access layer and application against SQL Injection attacks. This is really important to help catch the "it is just a tiny update so I'll be safe" scenario, and provide an additional safety layer to avoid accidentally introducing a bad security bug into your application.

5) Lock down your database to only grant the web application accessing it the minimal set of permissions that it needs to function. If the web application doesn't need access to certain tables, then make sure it doesn't have permissions to them. If it is only read-only generating reports from your account payables table then make sure you disable insert/update/delete access.

How to Learn More

The Microsoft Prescriptive Architecture Guidance (PAG) team has posted a number of really good security guideline documents that you should set aside some time to read:

And these additional PAG How-To articles are useful for learning more about how to protect yourself against injection attacks:

You can also find useful ASP.NET security information from this security blog post of mine, and from my ASP.NET Tips/Tricks page here.

Updated: Bertrand pointed me at a great post he did two years ago on SQL Injection Attacks that is great to read.

Hope this helps,

Scott

分享到:
评论

相关推荐

    C#中的Tostring()用法

    然而,ToString()方法的使用却有很多 trick,需要开发者细心掌握。 1. 日期时间ToString() 在C#中,DateTime类型的ToString()方法可以将日期时间对象转换为字符串类型。例如,使用"y"格式可以将日期时间转换为年份...

    Cross Iframe Trick:the Old New Thing

    标题 "Cross Iframe Trick:the Old New Thing" 暗示了我们将会探讨一个关于跨框架通信的技术,这种技术在Web开发中尤为重要,特别是在处理不同源的页面间交互时。跨框架技巧通常涉及到HTML的`<iframe>`元素,它允许...

    使用ASP.NET 2.0 CSS 控件适配器生成CSS友好的HTML输出

    【原文地址】 Tip/Trick: Use the ASP.NET 2.0 CSS Control Adapters for CSS friendly HTML output 【原文发表日期】 Wednesday, November 29, 2006 11:01 PM 厌烦了内置的ASP.NET服务器端...

    Ecotek Tip&Trick New Tab-crx插件

    Ecotek Tip&Trick New Tab-crx插件是一款针对Chrome浏览器设计的扩展程序,主要功能是替换浏览器的新标签页,将默认的新标签页重定向到Ecotek Tip&Trick的URL。这款插件特别之处在于其越南语界面,为越南用户提供了...

    trick:一些为了小方便而使用的脚本

    "trick:一些为了小方便而使用的脚本"这个标题表明,这个压缩包中可能包含了一系列用Perl编写的实用小脚本,这些脚本可能是为了日常工作中的一些快捷操作或自动化任务而设计的。 Perl脚本通常用于处理文本数据,如...

    trick:特技模拟环境。 Trick提供了一组通用的仿真功能和实用程序,可以自动构建仿真

    由NASA约翰逊航天中心开发的Trick仿真环境是一个功能强大的仿真开发框架,使用户能够为航天器开发的所有阶段构建应用程序。 特里克(Trick)加快了仿真的创建过程,以进行早期飞行器设计,性能评估,飞行软件开发,...

    wda_monitor_trick:PoC

    **标题解析:** "wda_monitor_trick:PoC" 这个标题表明这是一个关于WDA_MONITOR漏洞的证明概念(Proof of Concept,简称PoC)的项目。PoC通常是一段代码或步骤,用于演示特定安全漏洞的存在,而不一定是完整的攻击...

    android环境搭建地址链接

    #### 3.1 Hat-trick与Hattrick adb设备管理 - `Hattrick adb devices`: 显示连接的设备列表。 - `adb push a.out /data`: 将本地文件`a.out`推送到设备的`/data`目录下。 - `adb shell ash`: 进入设备的shell环境。 ...

    db_trick.sql

    db_trick.sql

    CMCC-Trick:招惹CMCC-* WLAN

    Trick-CMCC 利用CMCC公共热点的小漏洞免费上网~~ :) sudo ./conn.sh Notice: 目前只知道我工CMCC有这特色, 其他地区尚不明确 Notice: 脚本适用于使用NetWorkManager网络sds管理工具的系统 Notice: 不必惊讶原理, ...

    21-card-trick:在 React 中完成的 21 张卡片技巧

    React 21 卡技巧一个演示卡片技巧的React应用程序。动机该项目旨在学习如何使用 React 钩子和进行嵌套的 api 调用。 该项目不再进行。怎么玩记住 21 张卡片中的 1 张后,单击完成。 选择您的卡片所在的 3 堆中的哪一...

    藏经阁-Tricks of the Trade.pdf

    Trick 12: SQL vs code SQL vs code 是 Spark 中的一个重要概念。通过 SQL vs code,可以快速确认问题所在,提高生产效率。SQL vs code 可以用于确认 Spark 任务的状态,快速 debug 代码。 通过这些 Trick,可以...

    初一音标巩固练习.pdf

    1. 音标 /au/: 这个音标代表一个长元音,发音时口型较大,类似于"ow"的音。在给出的选项中,A "knock"、C "shout"和D "borrow"中的"o"都发这个音,而B "so"中的"o"发音为短元音。 2. 音标 /ai/: 此音标代表一个短元...

    Trick

    "Trick"这一主题似乎与一套特别的字体资源相关,其中包括多种不同风格的图像文件(.gif)和TrueType字体文件(.TTF)。让我们深入探讨一下这个话题。 首先,.gif 文件是一种常见的图像格式,支持透明度和动画,常...

    Team Spirit Hattrick (TS-H):估计他的 Hattrick 俱乐部在整个赛季中的 TS 变化。-开源

    该文件用于估算在 Hattrick 比赛的整个赛季 (http://www.hattrick.org) 期间贵俱乐部的团队精神 (TS = Team Spirit) 的自然和强制变化。 因此,您可以计划“安静”、“正常”或“赛季最佳”的正式比赛,并查看您的...

    基于Keras搭建深度卷积生成对抗网络DCGAN并训练动漫头像数据集源码+项目说明+数据集.zip

    GAN训练trick:1、输入规范化为-1到1之间2、修改损失函数3、使用标准正态分布的随机噪声更多见项目说明!!!【备注】1.项目代码均经过功能验证,确保稳定可靠运行。欢迎下载食用体验!2.主要针对各个计算机相关专业...

    重修 Slope Trick(看这篇绝对够!).doc

    ### 重修 Slope Trick 技术解析 #### 一、引言 Slope Trick,作为一项优化动态规划(DP)问题的技术手段,在算法竞赛领域里占有重要地位。该技术的核心在于利用函数斜率的变化来简化计算过程,尤其是在面对那些代价...

    Hattrick球场上座率概算

    Hattrick球场上座率概算 Hattrick球场上座率概算

Global site tag (gtag.js) - Google Analytics