secure programming lecture 8++: sql injection · 2014. 2. 23. · forms of sql code injected...

48
Secure Programming Lecture 8++: SQL Injection David Aspinall, Informatics @ Edinburgh 13th February 2014

Upload: others

Post on 22-Jan-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Secure Programming Lecture 8++: SQLInjection

David Aspinall, Informatics @ Edinburgh

13th February 2014

Page 2: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 3: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 4: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Recap

Injection attacks use specially crafted inputs tosubvert the intended operation of applications.

É OS Command Injections may execute arbitrarycommands.

É SQL Injections can reveal database contents,affect the results of queries used for authentication;sometimes they can even execute commands.

In this lecture we look at SQL Injections in more detail.

Page 5: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Context

SQL Injection (SQLi) is by some estimates the currentnumber one category of software vulnerability.

As with overflows, there is a large body of craftyexploits made possible by (often small) errors incoding or design.

We will look at:

É SQLi attack types and mechanismsÉ detecting SQLiÉ preventing SQLi

Page 6: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 7: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

How I hacked PacketStorm (1988-2000)

-- Advisory RFP2K01 ------------------------------ rfp.labs ------------

"How I hacked PacketStorm"

A look at hacking wwwthreads via SQL

------------------------------- rain forest puppy / [email protected] ---

É One of the first public examples and explanationÉ Demonstrated retrieval of 800 passwordsÉ See Rain Forest Puppy’s advisory and his earlier

Phrack 54 article

Page 8: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Man steals 130m identities (2009)

Page 9: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Attempted handwritten attack in SwedishElections (2010)

Page 10: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Should know better (2011)

Page 11: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Should know better (2013)

Page 12: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 13: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Typical setting for attacks

[Picture from SQL Injection Attacks and Defense, J. Clarke, Syngress,2012]

Page 14: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Running example: servlet code

1 public class Show extends HttpServlet {2 public ResultSet getuserlnfo(String login, String pin) {3 Connection conn = DriverManager.getConnection("MyDB"};4 Statement stmt = conn.createStatement();5 String queryString = "";6

7 queryString = "SELECT accounts FROM users WHERE ";8 if ((! login.equals("")) && (! pin.equals(""))) {9 queryString += "login=’" + login +

10 "’ AND pin=" + pin;11 } else {12 queryString+="login=’guest’ ";13 }14

15 ResultSet tempSet = stmt.execute(queryString);16 return tempSet;17 }18 }

Page 15: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Normal usage

7 queryString = "SELECT accounts FROM users WHERE ";8 if ((! login.equals("")) && (! pin.equals(""))) {9 queryString += "login=’" + login +

10 "’ AND pin=" + pin;11 } else {12 queryString+="login=’guest’ ";13 }

User submits login="john" and pin="1234"

SQL issued:

SELECT accounts FROM users WHERE login=’john’ AND pin=1234

Page 16: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Malicious usage

7 queryString = "SELECT info FROM users WHERE ";8 if ((! login.equals("")) && (! pin.equals(""))) {9 queryString += "login=’" + login +

10 "’ AND pin=" + pin;11 } else {12 queryString+="login=’guest’ ";13 }

User submits login="admin’ --" and pin="0"

SQL issued:

SELECT accounts FROM users WHERE login=’admin’ --’ AND pin=0

Page 17: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 18: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Classifying SQL injections

There are a wide variety of SQL injection techniques.Sometimes several are used to mount a single attack.

It’s useful to examine:

É route – where injection happensÉ motive — what it aims to achieveÉ SQL code — the form of SQL injected

These slides follow A Classification of SQL Injection Attacks andCountermeasures by Halfond, Viegas and Orso. ISSE 2006.

Page 19: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 20: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Injection routes

É User input e.g., web forms via HTTP GET or POSTÉ Cookies used by web apps to build queriesÉ Server variables logged by web apps (e.g., http

headers)É Second-order injection where injection is

separated from attack

Page 21: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Primary motive of attack

É Extracting dataÉ Adding or modifying dataÉ Mounting a denial of service attackÉ Bypassing authenticationÉ Executing arbitrary commands

Page 22: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Auxiliary motives

É Finding injectable parametersÉ Database server finger-printingÉ Finding database schemaÉ Escalating privilege at the database level

Page 23: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 24: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Forms of SQL code injected

1. Tautologies2. Illegal/incorrect queries3. Union query4. Piggy-backed queries5. Inference pairs6. Stored procedures and other DBMS features

Additionally, the injection may use alternate encodingsto try to defeat sanitization routines that don’t interpretthem (e.g., char(120) instead of x).

Exercise. For each of these types (described next),consider what the primary/secondary motive(s) of theattack could be.

Page 25: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Tautologies

Inject code into condition statement(s) so they alwaysevaluate to true.

SELECT accounts FROM users WHERElogin=’’ or 1=1 -- AND pin=

Blacklisting tautologies is difficult

É Many ways of writing them: 1>0, ’x’ LIKE ’x’, . . .É Quasi tautologies: very often true RAND()>0.01, . . .

Question. Instead of a tautology, can you think of howan attacker might use an always-false condition?

Page 26: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Illegal/incorrect

Cause a run-time error, hoping to learn informationfrom error responses.

SELECT accounts FROM users WHERElogin=’’ AND pin=convert(int,(select top 1 name from

sysobjects where xtype=’u’))

É Supposes MS SQL serverÉ sysobjects is server table of metadata

É Tries to find first user tableÉ Converts name into integer: runtime error

Page 27: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Example response

Microsoft OLE DB Provider for SQL Server (Ox80040E07)Error converting nvarchar value ’CreditCards’to a column of data type int

Tells the attacker:

É SQL Server is runningÉ The first user-defined table is called CreditCards

Page 28: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Union query

Inject a second query using UNION:

SELECT accounts FROM users WHERElogin=” UNION SELECT cardNo from CreditCards whereacctNo=10032 -- AND pin=

É Suppose there are no tuples with login=”É Result: may reveal cardNo for account 10032

Page 29: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Piggy-backed queries

Inject a second, distinct query:

SELECT accounts FROM users WHERElogin=’doe’; drop table users -- ’ AND pin=123

É Database parses second command after ‘;’É Executes second query, deleting users tableÉ NB: some databases don’t need ; character

Page 30: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Inference pairs

Suppose error responses are correctly captured and notseen by the client.

It might still be possible to extract information from thedatabase, by finding some difference between outputsfrom pairs of queries.

É A Blind Injection tries to reveal information byexploiting some visible difference in outputs.

É A Timing Attack tries to reveal information bymaking a difference in response time dependent ona boolean (e.g., via WAITFOR)

Page 31: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Blind injection example

Idea: discover whether login parameter is vulnerablewith two tests.

Step 1. always true:

login=’legalUser’ and 1=1 -- ’

2. always false:

login=’legalUser’ and 1=0 -- ’

Page 32: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Blind injection example

Step 1

SELECT accounts FROM users WHERE login=’legalUser’ and 1=1 -- ’

RESPONSE: INVALID PASSWORD

Attacker reasons:

Perhaps my invalid input was detected andrejected, or perhaps the username query wasexecuted separately from the password check.

Page 33: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Blind injection example

Step 2

SELECT accounts FROM users WHERE login=’legalUser’ and 1=0 -- ’

RESPONSE: INVALID USERNAME AND PASSWORD

Attacker reasons:

Aha, the response is different! Now I can inferthat the login parameter is injectable.

Page 34: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Stored procedures

Stored procedures are custom sub-routines whichcan provide customizable support for additionaloperations.

É May be written in scripting languages.É Can open up additional vulnerabilities.

CREATE PROCEDURE DBO.isAuthenticated@userName varchar2, @pin intASEXEC("SELECT accounts FROM usersWHERE login=’" +@userName+ "’ and pass=’" +@pass+

"’ and pin=" +@pin);GO

[varchar2 is an Oracle datatype for variable length strings]

Page 35: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Stored procedures

This is invoked with something like:

EXEC DBO.isAuthenticated ’david’ ’bananas’ 1234

Page 36: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Stored procedures

Or something like:

EXEC DBO.isAuthenticated(’ ; SHUTDOWN; --’,’’,’’)

which results in:

SELECT accounts FROM users WHERElogin=’doe’ pass=’ ’; SHUTDOWN; -- AND pin=

Page 37: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

An especially dangerous stored procedures

Microsoft SQL Server offers: xp_cmdshell, whichallows operating system commands to be executed.

EXEC master..xp_cmdshell ’format c:’

É Since SQL Server 2005, this is disabled by defaultÉ . . . but can be switched back on by db adminsÉ . . . maybe from inside the db

Page 38: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Other database server features

There are other features offered variously depending onthe DBMS.

For example, queries in MySQL can write files with theidiom:

SELECT INTO outfile.txt ...

Question. Why might writing files be of use to anattacker?

Page 39: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 40: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

How do I repair an SQLi vulnerability?

Mentioned last lecture:

É filtering to sanitize inputsÉ prepared (aka parameterized) queries

Both methods are server, so it is better to use databasedriver libraries whenever possible that abstract awayfrom the underlying DBMS.

In Java, JDBC provides the PreparedStatement class.

[We’ll look at further relevant secure coding issues later lectures; inparticular, ways of managing input and also output filtering.]

Question. What type of SQLi attacks mightPreparedStatements not prevent against?

Page 41: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

How do I prevent SQLi vulnerabilities?

Choice of stages (as usual):

1. eliminate before deployment:É manual code reviewÉ automatic static analysis

2. in testing or deployment:É manual test for vulnerabilitiesÉ or use automatic scanners

3. after deployment:É wait until attacked, manually investigateÉ use dynamic remediation plus alarms (app firewall

or specialised technique)

Some examples follow.

Page 42: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Static prevention: automated analysis

Idea: static code analysis used to warn programmer orprohibit/fix vulnerable code.

Techniques:

É Detect suspicious code patterns, e.g., dynamicquery construction

É Use static taint analysis to detect data-flows frominput parameters to queries

[We’ll look at static analysis in more detail in later lectures]

Page 43: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Dynamic detection tool: AMNESIA

Idea: use static analysis pre-processing to generate adynamic detection tool:

1. Find SQL query-generation points in code2. Build SQL-query model as NDFA which models SQL

grammar, transition labels are tokens3. Instrument application to call runtime monitor4. If monitor detects violation of state machine,

triggers error, preventing SQL query

Page 44: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

State machine for SQL production

É Variable β: matches any string in SQL grammarÉ Spots violation in injectable parameters

É abort query if model not in accepting state

[See Halfond and Orso, AMNESIA: analysis and monitoring forNEutralizing SQL-injection attacks, Automated Software

Engineering, 2005]

Page 45: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Dynamic prevention: SQLrand

Idea: use instruction set randomization to changelanguage dynamically to use opcodes/keywords thatattacker can’t easily guess.

[See Boyd and Keromytis, SQLrand: Preventing SQL InjectionAttacks, Applied Cryptography and Network Security, 2004]

Page 46: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Outline

Overview

Some past attacks

Reminder: basics

Classification

Injection route and motive

Forms of SQL code injected

Prevention and detection

Summary

Page 47: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

Review questions

SQLi classification

É Describe three routes by which SQL injection mayoccur.

É Describe three auxiliary motives that an attackermay have when using SQL injection techniques tolearn about a target.

SQLi prevention and detection

É How would you repair the prototypical exampleSQLi vulnerability?

É Describe an automatic technique for preventingand an automatic technique for detecting SQLivulnerabilities.

Page 48: Secure Programming Lecture 8++: SQL Injection · 2014. 2. 23. · Forms of SQL code injected 1.Tautologies 2.Illegal/incorrect queries 3.Union query 4.Piggy-backed queries 5.Inference

References and credits

Most content in this lecture has been adapted from:

É A Classification of SQL Injection Attacks andCountermeasures by Halfond, Viegas and Orso.ISSE 2006

É SQL Injection Attacks and Defense, Edited by JustinClarke, Syngress. 2nd Edition 2012.