SlideShare a Scribd company logo
OWASP Community
                  Lviv
                  SQL – injections for Dummies




Bohdan Serednytskyi, Security Engineer, R&D Team, SoftServe
August, 2012
Easy to exploit!   Severe impact!




       Common in Web Apps!
SQL-Injection


 The ability to inject SQL commands into the
 database engine through an existing application.
SQL-Injection Impact
Data Leakage
Data Modification
Denial of Access
Data Loss
Sql Injection V.2
Complete host takeover
SQL-Injection
Vulnerable request can
handle Insert, Update,
Delete

                               Almost all SQL databases and
                               programming languages are
                               potentially vulnerable
It is a flaw in "web
application" development,
it is not a DB or web server
problem
SQL-Injection Anatomy
                SQL-injection


SQL-injection                      Blind SQL-injection




                 Blind SQL-injection       Double blind SQL-injection
Scenario
          http://example.com/app/accountView?id='
          %' or ‘0’=‘0’ union select null, version() #




                                                         База даних
   Attacker                         WEB-server              DB


  SELECT first_name, last_name FROM users WHERE
  user_id = '%' or ‘0’=‘0’ union select null, version() #;
Example
private void queryDB(String u_name)
{
      string sql = “select * from users where name = „ “
+ u_name + “ ‟ ”;
      doQuery(sql);
}




1) select * from users where name = „Jerry‟

2) select * from users where name = „Jerry‟ or „1‟ =„1‟
Example Blind
SQL-injection
 1) http://newspaper.com/items.php?id=2 and 1=2

 SELECT title, description, body FROM items WHERE
 ID = 2 and 1=2



 2) http://newspaper.com/items.php?id=2 and 1=1
Detection
Discovery of Vulnerabilities


Fields in web form

Script parameters in URL
query strings

Values stored in cookies or
hidden fields
Fuzzing

Character sequence: ' " ) # || + >

SQL reserved words with white space
delimiters


Delay query: ' waitfor delay '0:0:10'--
Protection
Use of Prepared Statements
(Parameterized Queries)

String custname = request.getParameter("customerName");
String query = "SELECT account_balance FROM user_data WHERE
user_name = ? ";

PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, custname);
ResultSet results = pstmt.executeQuery( );
Use of Stored Procedures
 String custname = request.getParameter("customerName");
 try {
        CallableStatement cs = connection.prepareCall("{call
        sp_getAccountBalance(?)}");
        cs.setString(1, custname);
        ResultSet results = cs.executeQuery();
 // … result set handling
     }

 catch (SQLException se) {
 // … logging and error handling
     }
Escaping all User Supplied Input




        OWASP Enterprise Security API
Web Application Firewall

A security solution on the
web application level
which does not depend
on the application itself
Additional Defenses



                               IDS, IPS

                        Least Privilege

            White List Input Validation
Sql Injection V.2

More Related Content

PDF
Sql Injection - Vulnerability and Security
PPTX
03. sql and other injection module v17
PDF
How to identify and prevent SQL injection
PDF
Sql Injection and XSS
PDF
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
PPT
Sql injection
PPTX
SQL Injection Attacks cs586
PPTX
Time-Based Blind SQL Injection
Sql Injection - Vulnerability and Security
03. sql and other injection module v17
How to identify and prevent SQL injection
Sql Injection and XSS
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
Sql injection
SQL Injection Attacks cs586
Time-Based Blind SQL Injection

What's hot (20)

PPTX
SQL INJECTION
PPTX
SQL Injection attack
PPT
Web application attacks using Sql injection and countermasures
PDF
SQL Injection Tutorial
PPTX
seminar report on Sql injection
PPTX
SQL Injection Defense in Python
PPTX
SQL Injection in action with PHP and MySQL
PPTX
Sql injection
PPTX
Sql injection attack
PDF
Time-Based Blind SQL Injection Using Heavy Queries
PPT
Time-Based Blind SQL Injection using Heavy Queries
PPTX
Ppt on sql injection
PDF
Advanced SQL Injection: Attacks
PDF
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
DOCX
Types of sql injection attacks
PPTX
SQL Injections (Part 1)
PPT
Sql injection
PPT
Sql injection
PDF
SQL Injection
PPTX
Sql injection
SQL INJECTION
SQL Injection attack
Web application attacks using Sql injection and countermasures
SQL Injection Tutorial
seminar report on Sql injection
SQL Injection Defense in Python
SQL Injection in action with PHP and MySQL
Sql injection
Sql injection attack
Time-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection using Heavy Queries
Ppt on sql injection
Advanced SQL Injection: Attacks
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
Types of sql injection attacks
SQL Injections (Part 1)
Sql injection
Sql injection
SQL Injection
Sql injection
Ad

Similar to Sql Injection V.2 (20)

PPTX
Greensql2007
PPTX
Code injection and green sql
PPTX
ASP.NET Web Security
PDF
Java EE Web Security By Example: Frank Kim
PPTX
SQL Injections - 2016 - Huntington Beach
PDF
Brief introduction into SQL injection attack scenarios
PDF
Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)
PPTX
Sql injection
PPTX
Web security with Eng Ahmed Galal and Eng Ramy saeid
PDF
Php Security - OWASP
ODT
Sql injection
PDF
Web Security 101
PDF
Application Security around OWASP Top 10
PPT
SQL Injection in PHP
PPT
8 sql injection
PDF
Prevention of SQL Injection Attack in Web Application with Host Language
PPTX
SQL Injection in JAVA
PPT
SQLSecurity.ppt
PPT
SQLSecurity.ppt
Greensql2007
Code injection and green sql
ASP.NET Web Security
Java EE Web Security By Example: Frank Kim
SQL Injections - 2016 - Huntington Beach
Brief introduction into SQL injection attack scenarios
Pawel Cygal - SQL Injection and XSS - Basics (Quality Questions Conference)
Sql injection
Web security with Eng Ahmed Galal and Eng Ramy saeid
Php Security - OWASP
Sql injection
Web Security 101
Application Security around OWASP Top 10
SQL Injection in PHP
8 sql injection
Prevention of SQL Injection Attack in Web Application with Host Language
SQL Injection in JAVA
SQLSecurity.ppt
SQLSecurity.ppt
Ad

More from Tjylen Veselyj (11)

PPTX
Web Application Firewall (WAF) DAST/SAST combination
PPTX
Intro to Security in SDLC
PPTX
Welcome to the world of hacking
PPTX
Mobile security services 2012
PPTX
iOS Forensics
PPTX
Virtual Machine Introspection - Future of the Cloud
PPTX
Security hole #5 application security science or quality assurance
PPTX
Sh#3 incident forensics
PPTX
Owasp Community in Lviv
PPTX
Cloud Security vs Security in the Cloud
PPTX
Mobilination Ntymoshyk Personal Mobile Security Final Public
Web Application Firewall (WAF) DAST/SAST combination
Intro to Security in SDLC
Welcome to the world of hacking
Mobile security services 2012
iOS Forensics
Virtual Machine Introspection - Future of the Cloud
Security hole #5 application security science or quality assurance
Sh#3 incident forensics
Owasp Community in Lviv
Cloud Security vs Security in the Cloud
Mobilination Ntymoshyk Personal Mobile Security Final Public

Sql Injection V.2

  • 1. OWASP Community Lviv SQL – injections for Dummies Bohdan Serednytskyi, Security Engineer, R&D Team, SoftServe August, 2012
  • 2. Easy to exploit! Severe impact! Common in Web Apps!
  • 3. SQL-Injection The ability to inject SQL commands into the database engine through an existing application.
  • 11. SQL-Injection Vulnerable request can handle Insert, Update, Delete Almost all SQL databases and programming languages are potentially vulnerable It is a flaw in "web application" development, it is not a DB or web server problem
  • 12. SQL-Injection Anatomy SQL-injection SQL-injection Blind SQL-injection Blind SQL-injection Double blind SQL-injection
  • 13. Scenario http://example.com/app/accountView?id=' %' or ‘0’=‘0’ union select null, version() # База даних Attacker WEB-server DB SELECT first_name, last_name FROM users WHERE user_id = '%' or ‘0’=‘0’ union select null, version() #;
  • 14. Example private void queryDB(String u_name) { string sql = “select * from users where name = „ “ + u_name + “ ‟ ”; doQuery(sql); } 1) select * from users where name = „Jerry‟ 2) select * from users where name = „Jerry‟ or „1‟ =„1‟
  • 15. Example Blind SQL-injection 1) http://newspaper.com/items.php?id=2 and 1=2 SELECT title, description, body FROM items WHERE ID = 2 and 1=2 2) http://newspaper.com/items.php?id=2 and 1=1
  • 17. Discovery of Vulnerabilities Fields in web form Script parameters in URL query strings Values stored in cookies or hidden fields
  • 18. Fuzzing Character sequence: ' " ) # || + > SQL reserved words with white space delimiters Delay query: ' waitfor delay '0:0:10'--
  • 20. Use of Prepared Statements (Parameterized Queries) String custname = request.getParameter("customerName"); String query = "SELECT account_balance FROM user_data WHERE user_name = ? "; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, custname); ResultSet results = pstmt.executeQuery( );
  • 21. Use of Stored Procedures String custname = request.getParameter("customerName"); try { CallableStatement cs = connection.prepareCall("{call sp_getAccountBalance(?)}"); cs.setString(1, custname); ResultSet results = cs.executeQuery(); // … result set handling } catch (SQLException se) { // … logging and error handling }
  • 22. Escaping all User Supplied Input OWASP Enterprise Security API
  • 23. Web Application Firewall A security solution on the web application level which does not depend on the application itself
  • 24. Additional Defenses IDS, IPS Least Privilege White List Input Validation

Editor's Notes

  • #5: 1. Heartland Payment SystemsDate: March 2008Impact: 134 million credit cards exposed through SQL injection to install spyware on Heartland's data systems.A federal grand jury indicted Albert Gonzalez and two unnamed Russian accomplices in 2009. Gonzalez, a Cuban-American, was alleged to have masterminded the international operation that stole the credit and debit cards. In March 2010 he was sentenced to 20 years in federal prison. The vulnerability to SQL injection was well understood and security analysts had warned retailers about it for several years. Yet, the continuing vulnerability of many Web-facing applications made SQL injection the most common form of attack against Web sites at the time.Группа хакеров, называющая себя D33Ds Company, взломала голосовой сервис YahooVoice, похитила около 453 000 аккаунтов и разместила их в интернете. По сообщению экспертов в области безопасности TrustedSec, логины и пароли были получены в результате атаки типа "Внедрение SQL-кода" (SQL Injection) на базу данных Yahoo.Сами хакеры говорят, что во время атаки на YahooVoice не преследовали коммерческую цель, а лишь хотели указать на уязвимые места серверов Yahoo. По словам взломщиков, в работе серверов компании имеется еще несколько "дыр", из-за которых Yahoo может понести гораздо более крупный урон, нежели чем 400 тысяч похищенных профилей YahooVoices.Платформа YahooVoices является продолжением проекта AssociatedContent, который Yahoo приобрела за 100 миллионов долларов в мае 2010 года. В декабре 2011 года разработки AssociatedContent вошли в сервисы Yahoo.В июне 2012 года в свободный доступ попали более чем 6,5 млн аккаунтов деловой социальной сети LinkedIn. Участники сервиса при попытке войти в свои аккаунты обнаружили, что их пароли больше не действительны, а в электронном почтовом ящике нашли сообщение от соцсети с инструкцией по изменению пароля.Утечка паролей Linkedin обошлась компании в кругленькую сумму. Согласно опубликованной форме обязательной финансовой отчётности за II квартал 2012 года, фирма потратила от $500 тыс. до $1 млн на расследование инцидента.Финансовый директор Linkedin Стив Сорделло (SteveSordello) сказал, что в такую сумму обошлись работы по экспертизе и «другие элементы», имеющие отношение к взлому.Миллион долларов на расследование инцидента — только начало. Финансовый директор пообещал потратить ещё два-три миллиона долларов в текущем квартале на «повышение безопасности инфраструктуры и данных». Можно предположить, что львиная доля пойдёт на оплату труда специалистов по безопасности, да и консультации лучших экспертов дорогого стоят.Дополнительной статьёй расходов могут стать выплаты компенсаций по возможным искам со стороны пострадавших пользователей. Хотя это лишь гипотетическая возможность, но пример Yahoo показывает, что её нельзя полностью игнорировать. Если иск будет подан, то суд может признать, что компания предприняла недостаточные меры по обеспечению безопасности информации пользователей, и в этом случае ей придётся выплатить компенсацию. Здесь утечка гораздо более масштабная, чем у Yahoo: 6,5 миллиона паролей, по сравнению с 450 тыс. у Yahoo.Хотя у Linkedin пароли «утекли» не в открытом виде, как у Yahoo, а в виде хэшей SHA-1, подобрать их довольно легко. Эксперты по безопасности упрекают Linkedin, что компания не использовала так называемую «соль», то есть случайное изменение хэша, чтобы затруднить восстановление оригинальных паролей, сравнивая значение с результатом, который выдаёт стандартная хэш-функция. Впоследствии представители Linkedin признали свой промах и сообщили, что начали «солить» хэш, да и вообще, давно собирались сделать это, просто не успели до взлома.
  • #16: Blind SQL InjectionUse time delays or error signatures to determine extract informationAlmost the same things can be done but Blind Injection is much slower and more difficult
  • #17: 0x90.org: home of Absinthe, Mezcal, etc - http://0x90.org/releases.phpSQLiX - http://www.owasp.org/index.php/Category:OWASP_SQLiX_Projectsqlninja: a SQL Server injection and takover tool - http://sqlninja.sourceforge.net/JustinClarke's SQL Brute - http://www.justinclarke.com/archives/2006/03/sqlbrute.htmlBobCat - http://www.northern-monkee.co.uk/projects/bobcat/bobcat.htmlsqlmap - http://sqlmap.sourceforge.net/Scully: SQL Server DB Front-End and Brute-Forcer - http://www.sensepost.com/research/scully/FG-Injector - http://www.flowgate.net/?lang=en&seccion=herramientasPRIAMOS - http://www.priamos-project.com/
  • #18: To find vulnerabilities all parameters in a web form must be checked. SQL Injection can happen in any of the following: Fields in Web Forms Script Parameters in Query Strings sent as part of the URL Values stored in cookies that are sent back to the web application Values sent in hidden fields
  • #19: Character sequence: ' " ) # || + >SQL reserved words with white space delimiters %09select (tab%09, carriage return%13, linefeed%10 and space%32 with and, or, update, insert, exec, etc)Delay query ' waitfor delay '0:0:10'—To find all the different entry points in a web application a web proxy or a fuzzer must be used.With a fuzzer we insert different types of input into each entry point. "Fuzzing" is an automated software testing technique that generates and submits random or sequential data to various entry points of an application in an attempt to uncover security vulnerabilities. We use this technique to send specific string combinations with SQL specific reserved characters and words.We are looking for an application error or changes in the applications behavior or responses due to the insertion of one or several strings. For example, the delay query will make the application respond after 10 seconds if it is vulnerable and executing our command (in this case it would also have to be a MS SQL Server).
  • #21: The use of prepared statements (aka parameterized queries) is how all developers should first be taught how to write database queries. They are simple to write, and easier to understand than dynamic queries. Parameterized queries force the developer to first define all the SQL code, and then pass in each parameter to the query later. This coding style allows the database to distinguish between code and data, regardless of what user input is supplied.Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. In the safe example below, if an attacker were to enter the userID of tom' or '1'='1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string tom' or '1'='1.
  • #22: Stored procedures have the same effect as the use of prepared statements when implemented safely. They require the developer to define the SQL code first, and then pass in the parameters after. The difference between prepared statements and stored procedures is that the SQL code for a stored procedure is defined and stored in the database itself, and then called from the application. Both of these techniques have the same effectiveness in preventing SQL injection so your organization should choose which approach makes the most sense for you.
  • #23: ESAPI (The OWASP Enterprise Security API) is a free, open source, web application security control library that makes it easier for programmers to write lower-risk applications. The ESAPI libraries are designed to make it easier for programmers to retrofit security into existing applications. The ESAPI libraries also serve as a solid foundation for new development.Allowing for language-specific differences, all OWASP ESAPI versions have the same basic design:There is a set of security control interfaces. They define for example types of parameters that are passed to types of security controls.There is a reference implementation for each security control. The logic is not organization‐specific and the logic is not application‐specific. An example: string‐based input validation.There are optionally your own implementations for each security control. There may be application logic contained in these classes which may be developed by or for your organization. An example: enterprise authentication.This project source code is licensed under the BSD license, which is very permissive and about as close to public domain as is possible. The project documentation is licensed under the Creative Commons license. You can use or modify ESAPI however you want, even include it in commercial products.There are reference implementations for each ofthe following security controls: Authentication Access control Input validation Output encoding/escaping Cryptography Error handling and logging Communication security HTTP security Security configuration
  • #24: NAXSI is a WAF for NGINX.The OWASP Stinger Project is not a full blown WAF, but it is a strong Java/J2EE input validation filter that can be put in front of your application. Developers consistently implement sporadic, ad-hoc input validation mechanisms for web applications. Lack of a centralized and well-defined input validation mechanism opens the application to a variety of attacks: including SQL Injection, Cross Site Scripting (XSS), and Command Injection. The OWASP Stinger Project aims to develop a centralized input validation component which can be easily applied to existing or developmental applications. Using a declarative security model, Stinger has the ability to validate all HTTP requests coming into an application. Stinger is such a simplistic yet strong validation engine that organizations have begun integrating it into their software development life-cycle.Well Known Open Source Tools Of This TypeAQTronix - WebKnightTrustwaveSpiderLabs - ModSecurityA recent new project by Qualys led by Ivan Ristic, the original ModSecurity authorQualys - IronbeeCommercial Tools from OWASP Members Of This TypeThese vendors have decided to support OWASP by becoming members. OWASP appreciates the support from these organizations, but cannot endorse any commercial products or services.art of defence - hyperguardTrustwave - WebDefend Web Application FirewallDeny All - rWebFortify Software - DefenderImperva - SecureSphere™Penta Security - WAPPLESBayshore Networks - Application Protection PlatformOther Well Known Commercial Tools Of This TypeApplicure - DotDefenderPort80 Software - ServerDefender VPRadwareAppWallArmorlogic - ProfenseBarracuda Networks - Application FirewallBee-Ware - iSentryBinarySec - Application FirewallBugSec - WebSniperCisco - ACE Web Application FirewallCitrix - Application FirewalleEye Digital Security - SecureIISF5 - Application Security ManagerForum Systems - Xwall, SentrymWEbscurity - webApp.secureErgon - AirlockPrivacyware - ThreatSentry IIS Web Application FirewallProtegrity - Defiance TMS - Web Application FirewallXtradyne - Application FirewallsWeb Application Firewall (WAF) and Intrusion Detection (APIDS) rules and resourcesAPIDS on Wikipedia - http://en.wikipedia.org/wiki/APIDSPHP Intrusion Detection System (PHP-IDS) - http://php-ids.org/ http://code.google.com/p/phpids/dotnetids - http://code.google.com/p/dotnetids/Secure Science InterScout - http://www.securescience.com/home/newsandevents/news/interscout1.0.htmlRemo: whitelist rule editor for mod_security - http://remo.netnea.com/GotRoot: ModSecuirty rules - http://www.gotroot.com/tiki-index.php?page=mod_security+rulesThe Web Security Gateway (WSGW) - http://wsgw.sourceforge.net/mod_security rules generator - http://noeljackson.com/tools/modsecurity/Mod_Anti_Tamper - http://www.wisec.it/projects.php?id=3[TGZ] Automatic Rules Generation for Mod_Security - http://www.wisec.it/rdr.php?fn=/Projects/Rule-o-matic.tgzAQTRONIX WebKnight - http://www.aqtronix.com/?PageID=99Akismet: blog spam defense - http://akismet.com/Samoa: Formal tools for securing web services - http://research.microsoft.com/projects/samoa/
  • #25: Відключення повідомлень про помилки