Learn what is SQL injection, how to use prepared statements, how to escape and write secure stored procedures. Many PHP projects are covered - PDO, Propel, Doctrine, Zend Framework and MDB2. Multiple gotchas included.
The presentation has a quick preamble on SQL injection definition, sqlmap and its key features.
I will then illustrate into details common and uncommon problems and respective solutions with examples that a penetration tester faces when he wants to take advantage of any kind of web application SQL injection flaw on real world web applications, for instance SQL injection in ORDER BY and LIMIT clauses, single entry UNION query SQL injection, specific web application technologies IDS bypasses and more.
These slides have been presented at the 2nd Digital Security Forum in Lisbon on June 27, 2009.
Updated version of http://www.slideshare.net/inquis/sql-injection-not-only-and-11.
Advanced SQL injection to operating system full control (whitepaper)Bernardo Damele A. G.
Over ten years have passed since a famous hacker coined the term "SQL injection" and it is still considered one of the major web application threats, affecting over 70% of web application on the Net. A lot has been said on this specific vulnerability, but not all of the aspects and implications have been uncovered, yet.
It's time to explore new ways to get complete control over the database management system's underlying operating system through a SQL injection vulnerability in those over-looked and theoretically not exploitable scenarios: From the command execution on MySQL and PostgreSQL to a stored procedure's buffer overflow exploitation on Microsoft SQL Server. These and much more will be unveiled and demonstrated with my own tool's new version that I will release at the Conference (http://www.blackhat.com/html/bh-europe-09/bh-eu-09-speakers.html#Damele).
The most massive crime of identity theft in history was perpetrated in 2007 by exploiting an SQL Injection vulnerability. This issue is one of the most common and most serious threats to web application security. In this presentation, you'll see some common myths busted and you'll get a better understanding of defending against SQL injection.
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...Edureka!
(** Cyber Security Course: https://www.edureka.co/cybersecurity-certification-training **)
This ‘SQL Injection Attack’ PPT by Edureka will help you learn one of the most dangerous web application vulnerability – SQL Injection.
Below is the list of topics covered in this session:
Web Application Security
What is SQL Injection Attack?
Types of SQL Injection attacks
Demo – SQL Injection Attack Types
Prevention of SQL Injection Attack
Cyber Security Playlist: https://bit.ly/2N2jlNN
Cyber Security Blog Series: https://bit.ly/2AuULkP
Instagram: https://www.instagram.com/edureka_lea...
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The presentation has a quick preamble on SQL injection definition, sqlmap and its key features.
I will then illustrate into details common and uncommon problems and respective solutions with examples that a penetration tester faces when he wants to take advantage of any kind of web application SQL injection flaw on real world web applications, for instance SQL injection in ORDER BY and LIMIT clauses, single entry UNION query SQL injection, specific web application technologies IDS bypasses and more.
These slides have been presented at the 2nd Digital Security Forum in Lisbon on June 27, 2009.
Updated version of http://www.slideshare.net/inquis/sql-injection-not-only-and-11.
Advanced SQL injection to operating system full control (whitepaper)Bernardo Damele A. G.
Over ten years have passed since a famous hacker coined the term "SQL injection" and it is still considered one of the major web application threats, affecting over 70% of web application on the Net. A lot has been said on this specific vulnerability, but not all of the aspects and implications have been uncovered, yet.
It's time to explore new ways to get complete control over the database management system's underlying operating system through a SQL injection vulnerability in those over-looked and theoretically not exploitable scenarios: From the command execution on MySQL and PostgreSQL to a stored procedure's buffer overflow exploitation on Microsoft SQL Server. These and much more will be unveiled and demonstrated with my own tool's new version that I will release at the Conference (http://www.blackhat.com/html/bh-europe-09/bh-eu-09-speakers.html#Damele).
The most massive crime of identity theft in history was perpetrated in 2007 by exploiting an SQL Injection vulnerability. This issue is one of the most common and most serious threats to web application security. In this presentation, you'll see some common myths busted and you'll get a better understanding of defending against SQL injection.
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...Edureka!
(** Cyber Security Course: https://www.edureka.co/cybersecurity-certification-training **)
This ‘SQL Injection Attack’ PPT by Edureka will help you learn one of the most dangerous web application vulnerability – SQL Injection.
Below is the list of topics covered in this session:
Web Application Security
What is SQL Injection Attack?
Types of SQL Injection attacks
Demo – SQL Injection Attack Types
Prevention of SQL Injection Attack
Cyber Security Playlist: https://bit.ly/2N2jlNN
Cyber Security Blog Series: https://bit.ly/2AuULkP
Instagram: https://www.instagram.com/edureka_lea...
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Web Uygulama Güvenliğinde adını sıkça duyuran, OWASP Top 10'da 1. kategoride yer alan SQL Injection zaafiyetine dair detaylı bir incelemede bulunmak istedim.
These are the slides from a talk "sqlmap - security development in Python" held at EuroPython 2011 conference (Italy / Florence 19th–26th June 2011) by Miroslav Stampar
General Waf detection and bypassing techniques. Main focus to demonstrate that how to take right approach to analyse the behaviour of web application firewall and then create test cases to bypass the same.
Expanding the control over the operating system from the databaseBernardo Damele A. G.
Using a database, either via a SQL injection or via direct connection, as a stepping stone to control the underlying operating system can be achieved.
There is much to say on operating system control by owning a database server: Windows registry access, anti-forensics technique to establish an out-of-band stealth connection, buffer overflow exploitation with memory protections bypass and custom user-defined function injection.
These slides have been presented at SOURCE Conference in Barcelona on September 21, 2009.
These are the slides from a talk "DNS exfiltration using sqlmap" held at PHDays 2012 conference (Russia / Moscow 30th–31st May 2012) by Miroslav Stampar.
It all starts with the ' (SQL injection from attacker's point of view)Miroslav Stampar
These are the slides from a talk "It all starts with the ' (SQL injection from attacker's point of view)" held at FSec 2011 conference (Croatia / Varazdin 22nd September 2011) by Miroslav Stampar
SQLMAP is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers.
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015CODE BLUE
Microsoft's web browsers, Internet Explorer and Edge, have a feature called 'XSS filter' built in which protects users from XSS attacks. In order to deny XSS attacks, XSS filter looks into the request for a string resembling an XSS attack, compares it with the page and finds the appearance of it, and rewrites parts of the string if it appears in the page. This rewriting process of the string - is this done safely? The answer is no. This time, I have found a way to exploit XSS filter not to protect a web page, but to create an XSS vulnerability on a web page that is completely sane and free of XSS vulnerability. In this talk, I will describe technical details about possibilities of XSS attacks exploiting XSS filter and propose what website administrators should do to face this XSS filter nightmare.
Web Uygulama Güvenliğinde adını sıkça duyuran, OWASP Top 10'da 1. kategoride yer alan SQL Injection zaafiyetine dair detaylı bir incelemede bulunmak istedim.
These are the slides from a talk "sqlmap - security development in Python" held at EuroPython 2011 conference (Italy / Florence 19th–26th June 2011) by Miroslav Stampar
General Waf detection and bypassing techniques. Main focus to demonstrate that how to take right approach to analyse the behaviour of web application firewall and then create test cases to bypass the same.
Expanding the control over the operating system from the databaseBernardo Damele A. G.
Using a database, either via a SQL injection or via direct connection, as a stepping stone to control the underlying operating system can be achieved.
There is much to say on operating system control by owning a database server: Windows registry access, anti-forensics technique to establish an out-of-band stealth connection, buffer overflow exploitation with memory protections bypass and custom user-defined function injection.
These slides have been presented at SOURCE Conference in Barcelona on September 21, 2009.
These are the slides from a talk "DNS exfiltration using sqlmap" held at PHDays 2012 conference (Russia / Moscow 30th–31st May 2012) by Miroslav Stampar.
It all starts with the ' (SQL injection from attacker's point of view)Miroslav Stampar
These are the slides from a talk "It all starts with the ' (SQL injection from attacker's point of view)" held at FSec 2011 conference (Croatia / Varazdin 22nd September 2011) by Miroslav Stampar
SQLMAP is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers.
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015CODE BLUE
Microsoft's web browsers, Internet Explorer and Edge, have a feature called 'XSS filter' built in which protects users from XSS attacks. In order to deny XSS attacks, XSS filter looks into the request for a string resembling an XSS attack, compares it with the page and finds the appearance of it, and rewrites parts of the string if it appears in the page. This rewriting process of the string - is this done safely? The answer is no. This time, I have found a way to exploit XSS filter not to protect a web page, but to create an XSS vulnerability on a web page that is completely sane and free of XSS vulnerability. In this talk, I will describe technical details about possibilities of XSS attacks exploiting XSS filter and propose what website administrators should do to face this XSS filter nightmare.
In this presentation we will be looking at:
Common threats to the security of your website.
The various attack surfaces of a website; from the server, down the wire to presentation in the client browser.
Simple approaches to mitigating these threats.
Keeping web applications free from malicious attack is an arms race. From bruteforce attacks against your server through to browser based attacks to your pages once delivered (e.g. XSS, click jacking, cross site request forgery (CSRF)); there are many ways in which your web site is susceptible to attack.
Fortunately there are several established counter measures that are simply (if rarely) implemented that are effective in mitigating such threats.
We will look at the various modes of attack, review some real world examples and see how counter measures can be put in place.
The presentation is aimed at anyone responsible for delivering information over the web regardless of whether they are responsible for the hosting and administration of their web site. Covering measures you can implement yourself and measures you may wish supported by your hosting provider.
Topics covered:
Server hardening through the use of firewalls,
TLS/SSL implementation to protect delivery across the wire and
Secure response headers and Content Security Policies to protect your page once received by the user's browser.
Caution: This is a dated presentation; uploaded for reference. While the principles remain valid, specifics may have changed.
This presentation was made for software developers in Chandigarh - as a part of the NULL & OWASP Chandigarh Chapter activities.
It covers the basics of secure software development and secure coding using OWASP Top 10 as a broad guide.
"Web Application Security" by Lee Christense at Utah Code Camp in March 2014. Covers SQL injection(SQLi), cross-site scripting(XSS), cross-site request forgery(CSRF), and password hashing.
Web security: OWASP project, CSRF threat and solutionsFabio Lombardi
In a society in where we can all see an exponential growth in hacking attacks, this presentation raises awareness of web security vulnerabilities, what web developers can do to protect their web applications and which tools are available to ease the task.
In particular, I'm going to provide an overview on the OWASP top ten vulnerabilities, then focusing on CSRF (Cross-Site Request Forgery) attack, showing how it works, the impacts it can have, and how it is possible to prevent it.
Finally, I will briefly describe the OWASP LAPSE project, a useful Eclipse plugin for detecting vulnerabilities in Java EE applications.
The top two attack vectors for malware are email and web browsers. Watering-hole attacks conceal malware on member-based sites and phishing scams can target individuals with personal details. This PPT describes a different security approach to protect against these threats while achieving business growth, efficiency and lowered expenses. The presentation features Cisco Email, Web and Cloud Web Security and covers basic features, offers, benefits, newest features and product integrations. Watch the webinar: http://cs.co/9004BGqvy
These are the slides from the defcon talk title 'The making of 2nd sql injection worm'. Refer to the video presentations uploaded on www.notsosecure.com.
Palestra apresentada durante a Conferência Internacional de Segurança de Aplicações (AppSec Brasil 2009)
http://www.owasp.org/index.php/AppSec_Brasil_2009
This ppt provide information about:
1. Database basics,
2. Indexes,
3. PHP MyAdmin Connect & Pconnect,
4. MySQL Create,
5. MySQL Insert,
6. MySQL Select,
7. MySQL Update,
8. MySQL Delete,
9. MySQL Truncate,
10. MySQL Drop
Mike Creuzer's presentation from the December, 2009 Suburban Chicago PHP & Web Dev Meetup. The topic is SQL injection in PHP and common PHP content management systems.
Visit Mike's blog at http://mike.creuzer.com/
These are the slides from a talk "Spot the Web Vulnerability" held at Hacktivity 2012 conference (Hungary / Budapest 12th–13th October 2012) by Miroslav Stampar.
PHP classes in mumbai, Introduction to PHP/MYSQL..
best PHP/MYSQL classes in mumbai with job assistance.
our features are:
expert guidance by IT industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
For more Visit: http://vibranttechnologies.co.in/php-classes-in-mumbai.html or http://phptraining.vibranttechnologies.co.in
Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)Krzysztof Kotowicz
18 years have passed since Cross-Site Scripting (XSS) has been identified as a web vulnerability class. Since then, numerous efforts have been proposed to detect, fix or mitigate it. We've seen vulnerability scanners, fuzzers, static & dynamic code analyzers, taint tracking engines, linters, and finally XSS filters, WAFs and all various flavours of Content Security Policy.
Various libraries have been created to minimize or eliminate the risk of XSS: HTML sanitizers, templating libraries, sandboxing solutions - and yet XSS is still one of the most prevalent vulnerabilities plaguing web applications.
It seems like, while we have a pretty good grasp on how to address stored & reflected XSS, "solving" DOM XSS remains an open question. DOM XSS is caused by ever-growing complexity of client-side JavaScript code (see script gadgets), but most importantly - the lack of security in DOM API design.
But perhaps we have a chance this time? Trusted Types is a new browser API that
allows a web application to limit its interaction with the DOM, with the goal of obliterating
DOM XSS. Based on the battle-tested design that prevents XSS in most of the Google web applications, Trusted Types add the DOM XSS prevention API to the browsers. Trusted Types allow to isolate the application components that may potentially introduce DOM XSS into tiny, reviewable pieces, and guarantee that the rest of the code is DOM-XSS free. They can also leverage existing solutions like autoescaping templating libraries, or client-side sanitizers to use them as building blocks of a secure application.
Trusted Types have a working polyfill, an implementation in Chrome and integrate well with existing JS frameworks and libraries. Oddly similar to both XSS filters and CSP, they are also fundamentally different, and in our opinion have a reasonable chance of eliminating DOM XSS - once and for all.
Video recording of the talk: https://connect.ruhr-uni-bochum.de/p3g2butmrt4/
HTML5 is quickly gaining media attention and popularity among browser vendors and web developers. Having tremendous features, together with its sister specifications like Drag & Drop API, File API or Geolocation it allows developers to build rich web applications that easily blend with desktop & mobile environments.
The talk will be focused on finding the weakest link and combining several recent attack techniques to turn a security vulnerability into a successful exploit.
We'll show how to build a successful advanced UI-Redressing attack (also known as clickjacking), presenting the latest findings in this field, including malicious games and quizes. We'll work on file upload functionalities in current web applications and see how attackers might use HTML5 APIs for their advantage. Putting all these building blocks together will enable us to launch an attack and exploit even the otherwise unexploitable vulnerabilities.
Creating, obfuscating and analyzing malware JavaScriptKrzysztof Kotowicz
Malware attacks on unaware Internet users' browsers are becoming more and more common. New techniques for bypassing filters used by security vendors emerge. In turn, the filters are getting better, new analyzing tools are developed - the war continues. At the presentation you will learn how crackers are trying to hamper the work of security engineers, and how reversers are overcoming those problems. Emphasis will be placed on the weaknesses of automated tools - we'll try to avoid detection by jsunpack and Capture-HPC, we'll also trick Dean Edwards' Unpacker.
Tworzenie, zaciemnianie i analiza złośliwego kodu JavaScriptKrzysztof Kotowicz
Ataki malware'u na przeglądarki nieświadomych internautów stają się coraz powszechniejsze. Wciąż powstają nowe techniki pozwalające obejść filtry stosowane przez producentów oprogramowania zabezpieczającego. Z kolei filtry są coraz lepsze, powstają też nowe narzędzia - walka trwa. Na prezentacji dowiecie się, jak włamywacze usiłują utrudnić pracę analizatorom ich kodu i jak reverserzy sobie z tym radzą. Nacisk zostanie położony na słabości narzędzi automatycznych - będziemy usiłowali uniknąć wykrycia przez jsunpack i Capture-HPC, oszukamy też popularny unpacker Deana Edwardsa.
Co to jest SQL injection i jak wyglądają współczesne ataki na serwisy? Dlaczego SQL injection jest takie groźne? Jak w praktyce obronić się przed tą luką w bezpieczeństwie i ocalić swoje dane?
Kompletny przewodnik po SQL injection dla developerów PHP (i nie tylko)Krzysztof Kotowicz
W trakcie prezentacji zademonstrujemy szkody, na jesteście narażeni nie myśląc o SQL injection. Dowiecie się, jak się przed nim bronić - zarówno w teorii, jak i na konkretnych przykładach. Nauczymy się pisać bezpiecznie w PHP 5 - sprawdzimy Zend Framework i Symfony, przenalizujemy Propel, Doctrine, PDO i mdb2. Omówimy wszystkie kruczki i różnice między różnymi systemami baz danych (Oracle, MS SQL Server, MySQL) oraz nauczymy się pisać procedury składowane odporne na SQL injection.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
2. Plan
What is SQL injection?
Why is it so dangerous (demo)?
How to defend?
• Prepared statements
• Escaping
• Stored procedures
• Additional methods
Summary
OWASP 2
4. Discussed PHP projects
PDO – PHP data objects
• Common interface for various RDBMS
Doctrine 1.2
• ORM (Object Relational Mapper) used e.g. in Symfony framework
Propel 1.4
• ORM, like Doctrine
• Used in Symfony
Zend Framework 1.10
• Popular framework MVC for PHP
MDB2 2.4.1
• Database abstraction layer (DBAL)
• Distributed through PEAR
OWASP 4
6. SQL injection – short definition
It is a kind of web application attack, where user-
supplied input coming from:
URL: www.example.com?id=1
Forms: email=a@example.com
Other elements: e.g. cookie, HTTP headers
is manipulated so that vulnerable application
executes SQL commands injected by attacker.
OWASP 6
7. Example – login form
SELECT * FROM users WHERE login = '{$login}' and
password_hash = MD5('{$password}')
$login = "' or 1=1 -- ";
"anything";
$password = "dowolne";
// zamierzalismy osiagnacthis(kod dane)
you wanted to achieve to (code data)
SELECT * FROM users WHERE login = '' or 1=1 -- '
and password_hash = MD5('dowolne')
MD5('anything')
// but server interprets it as
SELECT * FROM users WHERE login = '' or 1=1 -- '
and password_hash = MD5('anything')
User logs in without knowing the login nor password
OWASP 7
9. What are the possible threats?
Unauthorized access to application
Access to whole database / databases on
the server
Denial of service
Database modification
Read / write files on server's filesystem
Code execution
OWASP 9
10. A few facts
Injection vulnerabilities are the 1st on OWASP Top
10 2010 RC
SQLi is responsible for 40–60% cases of data
breach [1] [2]
Modern attack techniques are advanced and
automated
• Vulnerability is not only in WHERE part
• Sometimes it is enough to break a query
Vulnerabilities are found on a daily basis, even in
new applications
OWASP 10
12. How to defend against SQL injection?
Source of vulnerability is mixing code with data
SELECT * FROM users WHERE login = 'login'
Defense methods
Separating code from data
prepared statements
stored procedures
Escaping
OWASP 12
14. Prepared statements – how to use?
1. Preparing SQL command (string)
Put placeholders where data should be
WHERE a = ? ... WHERE a = :col
2. Send command to server PREPARE
3. Attach data to command
4. Execute command EXECUTE
5. Fetch results
3, 4, 5 could be repeated...
6. Clear the command
OWASP 14
16. Prepared statements - advantages
Commands are completely separated from data they
operate on
Injection is not possible
Command is compiled only once - potential speedup
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':sum', $sum, PDO::PARAM_INT);
// petla po danych...
foreach ($do_bazy as $name => $value) {
$stmt->execute();
}
OWASP 16
17. Prepared statements - caveats
Not all commands may be parametrised
You cannot put parameters everywhere
-- error
SELECT * FROM :table
SELECT :function(:column) FROM :view
-- not what you expect
SELECT * FROM table WHERE :column = 1
SELECT * FROM table GROUP BY :column
Just using PS does not enforce using parameters in
them
Sometimes they're emulated (it's a good thing!)
OWASP 17
18. Prepared statements in Doctrine
Uses PDO (emulated for Oracle) and prepared statements
Uses own DQL language instead of SQL
$q = Doctrine_Query::create()
->select('u.id')
->from('User u')
->where('u.login = ?', ‘mylogin');
echo $q->getSqlQuery();
// SELECT u.id AS u__id FROM user u
// WHERE (u.login = ?)
$users = $q->execute();
OWASP 18
19. Prepared statements in Doctrine cont.
It can still bite you
$q = Doctrine_Query::create()
->update('Account')
->set('amount', 'amount + 200')
->where("id > {$_GET['id']}");
Correct this to:
->where("id > ?", (int) $_GET['id']);
NEVER put input data directly into SQL
commands
OWASP 19
20. Prepared statements in Propel
Uses PDO, like Doctrine
// through Criteria
$c = new Criteria();
$c->add(AuthorPeer::FIRST_NAME, "Karl");
$authors = AuthorPeer::doSelect($c);
// through custom SQL (sometimes it's more convenient)
$pdo = Propel::getConnection(BookPeer::DATABASE_NAME);
$sql = "SELECT * FROM complicated_sql
JOIN some_big_join USING something
WHERE column = :col)”;
$stmt = $pdo->prepare($sql);
$stmt->execute(array('col' => 'Bye bye SQLi!');
OWASP 20
21. Prepared statements in Zend Framework
PDO (+ mysqli + oci8 + sqlsrv)
// prepare + execute
$stmt = $db->prepare('INSERT INTO server (key,
value) VALUES (:key,:value)');
$stmt->bindParam('key', $k);
$stmt->bindParam('value', $v);
foreach ($_SERVER as $k => $v)
$stmt->execute();
// prepare + execute in one step
$stmt = $db->query('SELECT * FROM bugs WHERE
reported_by = ? AND bug_status = ?',
array('goofy', 'FIXED'));
while ($row = $stmt->fetch())
echo $row['bug_description'];
OWASP 21
22. Prepared statements in MDB2
Based on different database drivers (mysql,
oci8, mssql, ...)
Emulates PS, if database doesn't support them
$types = array('integer', 'text', 'text');
$stmt = $mdb2->prepare('INSERT INTO numbers
VALUES (:id, :name, :lang)', $types);
$data = array('id' => 1,
'name' => 'one',
'lang' => 'en');
$affectedRows = $stmt->execute($data);
$stmt->free();
OWASP 22
23. Prepared statements - summary
They offer very good protection (if used
properly)
Easy to use, small changes in code
Good support in frameworks
They have their limits
Sometimes they have to be used with other
defense methods
OWASP 23
25. Escaping – how does it work?
Data and commands are still kept in a single variable, but
we try to separate them inline
Numbers
• Cast to (int) / (float) – don't use is_numeric [1]!
Texts are surrounded with single quotes : '
.. WHERE col = 'TEXT DATA' AND ...
• If quote is inside the text, you need a way to distinguish it from
the ending quote
• Prepend a special character e.g. "" to a quote
• Escaping rules depend on context!
OWASP 25
26. Escaping – context
addslashes()
Returns a string with backslashes before characters that need to be quoted in
database queries etc. These characters are single quote ('), double quote ("),
backslash () and NUL (the NULL byte).
/ Source: php.net manual /
$user = addslashes($_GET['u']);
$pass = addslashes($_GET['p']);
$sql = "SELECT * FROM users WHERE username =
'{$user}' AND password = '{$pass}'";
$ret = exec_sql($sql);
Are you safe?
OWASP 26
28. Escaping – context cont.
Different RDBMS have different ways of escaping data
(it also depends on configuration)
addslashes() works just like MySQL only „by chance”
RBDMS PHP function i've got quotes
PDO $pdo->quote($val, $type) n/a (it depends)
MySQL (mysql) mysql_real_escape_string i've got quotes
MySQL (mysqli) mysqli_real_escape_string i've got quotes
Oracle (oci8) n/d - str_replace() i''ve got quotes
SQLite sqlite_escape_string i''ve got quotes
MS SQL (mssql) n/d - str_replace() i''ve got quotes
PostgreSQL pg_escape_string() i''ve got quotes
OWASP 28
29. Escaping – context cont.
// SELECT * FROM users WHERE username =
// '{$user}' AND password = '{$pass}'
$_GET['u'] = "anything'";
$_GET['p'] = " or 1=1 -- ";
// MySQL sees it as :
SELECT * FROM users WHERE username = 'anything''
AND password = ' or 1=1 -- '
// SQLite / MS SQL / Oracle / PostgreSQL:
SELECT * FROM users WHERE username = 'anything''
AND password = ' or 1=1 -- '
Don't use addslashes(), use PHP functions for your
RBDMS
Are you safe now?
OWASP 29
31. Escaping gotchas – charsets
Errors discovered in 2006 in PostgreSQL and
MySQL [1] [2]
In some multibyte charsets despite escaping you
can cause SQL injection
is „swallowed” by multibyte character
Example:
• BF 27 [ ¬ ' ] BF 5C 27 [ ¬ ' ]
• First 2 bytes are character ¿ in GBK charset
• Server will see ¿'
OWASP 31
32. Escaping gotchas – charsets
Some Asian charsets are vulnerable
Luckily - not UTF-8!
In PostgreSQL '' escaping was used (instead
of ')
In mysql_real_escape_string()
escaping is done with respect to current
connection charset
• Doesn't always work! [1] [2]
Charset also defines context
OWASP 32
33. Escaping gotchas – object names
Colum, table, database etc. names
• No common good rule to escape them
• Different reserved words, different maximum
name lengths etc.
If you need to get those names from the user - use
whitelisting (blacklisting if you really can't do
otherwise)
OWASP 33
34. Escaping gotchas – object names cont.
Example - sorting by column
There's a vuln. in $order, but you can't
escape there
$cat_id = (int) $_GET['cid'];
$order = $_GET['column'];
$stmt = $pdo->prepare("SELECT * FROM products WHERE
cid = :cid ORDER BY $order");
$stmt->bindParam(':cid', $cat_id, PDO::PARAM_INT);
if ($stmt->execute()) {
...
}
OWASP 34
35. Escaping gotchas – object names cont.
Whitelisting
$columns = array( // list of allowed columns
'product_name','cid','price',
);
if (!in_array($order, $columns, true))
$order = 'product_name'; // default column
Blacklisting
// only a-z and _
$order = preg_replace('/[^a-z_]/', '', $order);
// max 40 characters
$order = substr($order, 0, 40);
OWASP 35
36. Escaping in PDO
PDO::quote($value, $type, $len)
Length and type are sometimes ignored!
• Cast numbers to (int), (float)
• Texts – cut them manually
$quoted = $pdo->quote($input, PDO::PARAM_STR, 40);
OWASP 36
37. Escaping in Doctrine
Careful with Doctrine quote()!
$q = Doctrine_Query::create();
// not like this!!!
$quoted = $q->getConnection()->quote($input, 'text');
$q->update('User')->set('username', $quoted);
// quote() only changes ' to '' - exploit (MySQL):
$input = 'anything' where 1=1 -- ';
// escape through PDO - getDbh():
$quoted = $q->getConnection()
->getDbh()
->quote($input, PDO::PARAM_STR);
// 'anything ' where 1=1 -- '
OWASP 37
38. Escaping in Propel
Through PDO::quote()
$pdo = Propel::getConnection(UserPeer::DATABASE_NAME);
$c = new Criteria();
$c->add(UserPeer::PASSWORD,
"MD5(".UserPeer::PASSWORD.") "
." = " . $pdo->quote($password),
Criteria::CUSTOM);
OWASP 38
39. Escaping in Zend Framework
Functions quote(), quoteInto()
$name = $db->quote("O'Reilly");
// 'O'Reilly'
// simplified escaping for a single value
$sql = $db->quoteInto("SELECT * FROM products WHERE
product_name = ?", 'any string');
OWASP 39
40. Escaping in MDB
quote()
// quote() function - give type
$query = 'INSERT INTO table (id, itemname,
saved_time) VALUES ('
. $mdb2->quote($id, 'integer') .', '
. $mdb2->quote($name, 'text') .', '
. $mdb2->quote($time, 'timestamp') .')';
$res = $mdb2->exec($query);
OWASP 40
41. Escaping - summary
Looks easy - search and replace
Just looks
• You need to know the context (database, charset)
• There are invalid implementations
Encourages invalid practices
• concatenating strings to form a SQL command
• ignoring numeric parameters
Use only if
• You program for a single RDBMS
• There is no other way
OWASP 41
43. Stored procedures
SQL command(s) is moved to database server and
stored there under a name
Client executes a procedure with input and output
parameters
In output parameters client receives results
Data is formally separated from code
It's NOT enough
OWASP 43
44. Stored procedures cont.
Example for MS SQL – a vulnerable procedure
CREATE PROCEDURE SP_ProductSearch
@prodname varchar(400)
AS
DECLARE @sql nvarchar(4000)
SELECT @sql = 'SELECT ProductID, ProductName,
Category, Price FROM Product Where ProductName
LIKE ''' + @prodname + ''''
EXEC (@sql)
...
It's just like eval()!
OWASP 44
45. Stored procedures cont.
Same vulnerability in Oracle
CREATE OR REPLACE PROCEDURE
SP_ProductSearch(Prodname IN VARCHAR2) AS
sqltext VARCHAR2(80);
BEGIN
sqltext := 'SELECT ProductID, ProductName,
Category, Price FROM Product
WHERE ProductName LIKE '''
|| Prodname || '''';
EXECUTE IMMEDIATE sqltext;
...
END;
OWASP 45
46. Stored procedures – Dynamic SQL
Vulnerability lies in Dynamic SQL
• Data is again mixed with code in one variable
How to defend?
• Separate the code from data
• Escape
OWASP 46
47. Stored procedures in MS SQL
Separating code from data
• use sp_executesql with parameter list
CREATE PROCEDURE SP_ProductSearch @prodname
varchar(400) = NULL AS
DECLARE @sql nvarchar(4000)
SELECT @sql = N'SELECT ProductID, ProductName,
Category, Price FROM Product Where
ProductName LIKE @p'
EXEC sp_executesql @sql,
N'@p varchar(400)',
@prodname
OWASP 47
48. Stored procedures in MS SQL cont.
Escaping character data
Object name QUOTENAME(@v)
Text <= 128 chars QUOTENAME(@v,'''')
Text > 128 chars REPLACE(@v,'''','''''')
Example:
SET @cmd = N'select * from authors where lname=''' +
REPLACE(@lname, '''', '''''') + N''''
Escape only when you must!
(use sp_executesql with parameters)
OWASP 48
49. Stored procedures in Oracle
Oracle - use EXECUTE IMMEDIATE ..
USING
CREATE OR REPLACE PROCEDURE
SP_ProductSearch(Prodname IN VARCHAR2) AS
sqltext VARCHAR2(80);
BEGIN
sqltext := 'SELECT ProductID, ProductName,
Category, Price WHERE
ProductName=:p';
EXECUTE IMMEDIATE sqltext USING Prodname;
...
END;
Escaping - DBMS_ASSERT package
OWASP 49
50. Stored procedures in MySQL
Support for Dynamic SQL only through
prepared statements
It's actually harder to make vulnerable
procedure
Just use placeholders
OWASP 50
51. Stored procedures in MySQL cont.
PREPARE / EXECUTE USING /
DEALLOCATE PREPARE
DELIMITER $$
CREATE PROCEDURE get_users_like (
IN contains VARCHAR(40))
BEGIN
SET @like = CONCAT("%", contains, "%");
SET @sql = "SELECT * FROM users WHERE uname LIKE ?";
PREPARE get_users_stmt from @sql;
EXECUTE get_users_stmt USING @like;
DEALLOCATE PREPARE get_users_stmt;
END$$
DELIMITER ;
OWASP 51
52. Stored procedures in MySQL cont.
Or, even simpler
DELIMITER $$
CREATE PROCEDURE get_users_like (
IN contains VARCHAR(40))
BEGIN
SET @like = CONCAT("%", contains, "%");
SELECT * FROM users WHERE uname LIKE @like;
END$$
DELIMITER ;
Escaping – QUOTE() function
OWASP 52
53. Stored procedures in PHP
Different support level, depending on RDBMS
Common API (e.g. PDO) only for simple calls
• No return from procedure
• Returns scalar value in OUT parameter
Different API (or none at all) for advanced calls
• e.g. cursors, fetching records sets
Almost no support in frameworks
Still some errors...
OWASP 53
54. Stored procedures in PDO
Calling a procedure
// MySQL
$sql = "CALL get_users_like(:contains)";
// MS SQL – EXEC get_users_like :contains
$stmt = $pdo->prepare($sql);
$ret = $stmt->execute(array('contains' => $input));
foreach($stmt->fetchAll() as $users) {
var_dump($users);
}
unset($s);
OWASP 54
56. Stored procedures in MDB2
You need to manually escape all parameters!
$mdb2->loadModule('Function');
$multi_query = $mdb2->setOption('multi_query', true);
if (!PEAR::isError($multi_query)) {
$result = $mdb2->executeStoredProc('get_users_like',
array($mdb2->quote($contains, 'text')));
do {
while ($row = $result->fetchRow()) {
var_dump($row);
}
} while ($result->nextResult());
}
OWASP 56
57. Stored procedures - gotchas
Data length
CREATE PROCEDURE change_password
@loginname varchar(50),
@old varchar(50),
@new varchar(50)
AS
DECLARE @command varchar(120)
SET @command= 'UPDATE users SET password=' +
QUOTENAME(@new, '''') +
' WHERE loginname=' +
QUOTENAME(@loginname, '''') +
' AND password=' +
QUOTENAME(@old, '''')
EXEC (@command)
GO
OWASP 57
58. Stored procedures - summary
Moving SQL logic to server takes time
Code is not easily ported to other RDBMS
You need to use prepared statements or escaping to
write safe stored procedures anyway
If done poorly, you're even more vulnerable
• Both SP code and statement calling SP could be
vulnerable
• SP usually has greater permissions than code
calling it
Bad support in PHP and frameworks
OWASP 58
59. Stored procedures - summary
SPs have many advantages outside our scope
Could be used with different clients (Java/.NET + PHP)
Could have better berformance
and many more...
Conclusion:
You can write secure stored procedures, but they usually
increase the application cost considerably
It is vital to write stored procedures protected against
SQL injection
OWASP 59
61. Validation and filtering
Validate all external data
Validate before processing
Filter INPUT - escape OUTPUT
Different validation rules for each parameter -
check e.g.
• Type
• Scalar / array
• Min / max values
• Character data length! [1]
OWASP 61
62. Additional methods
Complementary to all previously mentioned!
Principle of least privilege when connecting to DB
Removing unused functions, accounts, packages
shipped with database
Routinely updating the system and database software
Correct PHP and database configuration
• magic_quotes_* = false
• display_errors = false
Good database design
OWASP 62
63. Summary
Pay attention to SQL injection - even a single mistake
could cost you!
Prefer complete solutions - e.g. frameworks
Filter and validate all input data
Remeber about data types and lengths
Prefer whitelisting to blacklisting - the latter will fail
one day!
Use prepared statements whenever you can
Try to avoid escaping
In stored procedures double check your Dynamic SQL
OWASP 63