CNIT 129S: Securing
Web Applications
Ch 9: Attacking Data Stores
 

Part 2 of 2
Updated 3-16-22
Bypassing Filters
Avoiding Blocked
Characters
• To prevent injection, many apps remove or
encode some character
s

• A single quotation mark is not needed for
injection into a numerical
fi
el
d

• You can also use string functions to
dynamically construct a string containing
fi
ltered characters
CHR or CHAR Function
• These queries work on Oracle and MS-SQL,
respectively
Comment Symbol Blocked
• Code i
s

SELECT * from users WHERE name='uname
'

• Try injecting this value for name
:

' or 1=1 -
-

• To creat
e

SELECT * from users WHERE name='' or 1=1 --
'

• But the "--' is blocked
Crafting Correct Syntax
Without a Comment
• Injecting this value for name
:

' or 'a'='
a

• To creat
e

SELECT * from users WHERE name=''
or 'a'='a'
Circumventing Simple
Validation
• If "SELECT" is blocked, try these bypasses:
Using SQL Comments
• If spaces are blocked, use comments instea
d

• MySQL allows comments within keywords
Second-Order SQL Injection
• Many applications handle data safely when it is
fi
rst entered into the databas
e

• But it may later be processed in unsafe ways
App Adds a Second Quote
• Register an account with this name
:

foo
'

• The correct way to insert that value is by adding a
second quote (link Ch 2a
)

INSERT INTO users (username,
password, ID, privs) VALUES
('foo''', 'secret', 2248, 1)
Password Change
• Requires user to input old password, and
compares it to the password retrieved with
:

SELECT password FROM users WHERE
username = 'foo'
'

• This is a syntax error.
Exploit
• Register a new user with this name
:

' or 1 in (SELECT password FROM users
WHERE username = 'admin')-
-

• Perform a password change, and MS-SQL will
return this error, exposing the administrator
password
Advanced Exploitation
• The previous attacks had a ready means of
exposing dat
a

• Adding UNION to a query that returns the
result
s

• Returning data in an error messag
e

• What if the results are not exposed?
Denial of Service
• This attack does not steal dat
a

• It's merely destructiv
e

• Turn off an MS-SQL databas
e

' shutdown-
-

• Drop tabl
e

' drop table users--
Retrieving Data as Numbers
• No strings
fi
elds may be vulnerable, because
single quotes are
fi
ltere
d

• Numeric
fi
elds are vulnerable, but only allow
you to retrieve numerical value
s

• Use functions to convert characters to numbers
Using an Out-of-Band
Channel
• You can inject a query but you can't see the
result
s

• Some databases allow you to make a network
connection inside the query language
MS-SQL 2000 and Earlier
Oracle
• UTL_HTTP makes an HTTP reques
t

• Attacker can use a netcat listener
Oracle
• DNS request is even less likely to be blocked
MySQL
• To retrieve the
fi
le, set up an SMB share on your
serve
r

• Alowing anonymous write access
Leveraging the Operating
System
• Sometimes you can get the ability to execute shell
command
s

• Such as by using a PHP shel
l

• Then you can use built-in commands like
 

• tftp, mail, telne
t

• Or copy data into a
fi
le in the Web root so you can
retrieve it with a browser
9b-1
Conditional Responses:


"Blind SQL Injection"
• Suppose your query doesn't return any data you
can see, an
d

• You can't use an out-of-band channel to
ex
fi
ltrate dat
a

• You can still get data, if there's any detectable
behavior by the database that depends on your
query
Example
• Put in this text for username, and anything for
passwor
d

admin' -
-

• You'll be logged in as admin
True or False?
• This username will log in as admin
:

admin' AND 1=1-
-

• This one will not log i
n

admin' AND 1=2--
Finding One Letter
• This username will log in as admin
:

• This one will not log i
n
Inducing Conditional Errors
• On an Oracle database, this query will produce
an error if the account "DBSNMP" exist
s

• If it doesn't, the "1/0" will never be evaluated
and it won't cause an error
Does User "AAAAA" Exist?
Using Time Delays
• MS-SQL has a built-in WAITFOR comman
d

• This query waits for 5 seconds if the current
database user is 'sa'
Conditional Delays
• You can ask a yes/no question and get the
answer from the delay
Testing Single Bits
• Using bitwise AND operator
&

• And the POWER command
MySQL Delays
• Current versions have a sleep functio
n

• For older versions (prior to 5.0.12), use
benchmark to repeat a calculation many times
Oracle
• No function to cause a delay, but you can use
URL_HTTP to connect to a non-existent serve
r

• Causes a delay until the request times out
Oracle
• This query causes a timeout if the default Oracle
account "DBSNMP" exists
Beyond SQL Injection:


Escalating the Database
Attack
Further Attacks
• SQL injection lets you get the data in the
database, but you can go furthe
r

• If database is shared by other applications,
you may be able to access other application's
dat
a

• Or compromise the OS of the database serve
r

• And then pivot: use the DB server to attack
other servers from inside the network
Further Attacks
• Make network connections back out to your
own computer, to ex
fi
ltrate data and evade
IDS system
s

• Extend database functionality by creating
user-de
fi
ned function
s

• You can reintroduce functionality that has
been removed or disable
d

• This is possible if you get database
administrator privileges
MS-SQL
• xp_cmdshell stored procedur
e

• Allows DBA (Database Administrator) to
execute shell commands
MS-SQL
• Other stored procedures also allow powerful
attack
s

• These read and write to the Registr
y

• xp_regread


• xp_regwrite
Dealing with Default
Lockdowns
• MS-SQL 2005 and later disable xp_cmdshell by
default, but you can just enable it if you are DBA
MySQL
• load_file allows attacker to read a
fi
l
e

• "into out
fi
le" allows attacker to write to a
fi
l
e

• This example makes all hosts trusted on Linux
SQL Exploitation Tools
Algorithm Used by Tools


like SQLMAP
SQLMAP
9b-2
Preventing SQL Injection
Blocking Apostrophes
• Won't stop injection into numerical
fi
eld
s

• If you allow apostrophes into data
fi
elds by
doubling them, you can have second-order SQL
injection vulnerabilities
Stored Procedures
• Makes code re-use easie
r

• But doesn't prevent SQL injection if user input is
included in a parameter
Stored Procedures
• Developer de
fi
nes a procedur
e

• Attacker can still inject with this passwor
d

• Resulting query
Parameterized Queries
Vulnerable Code
• User input inserted into a command, which is
parsed later to match quotes
Parameterized Version
• User input replaces placeholder "?
"

• No parsing required, not vulnerable to SQLi
Provisos
• Use parameterized queries for EVERY quer
y

• Not just the ones that are obviously user-
controllabl
e

• Every item of data should be parameterize
d

• Be careful if user data changes table or column name
s

• Allow only values from an allow-list of known safe
value
s

• You cannot use parameter placeholders for other parts
of the query, such as SORT BY ASC or SORT BY DES
C

• If they must be adjusted, use an allow-list
Defense in Depth
• Application should use low privileges when
accessing the database, not DB
A

• Remove or disable unnecessary functions of D
B

• Apply vendor patche
s

• Subscribe to vulnerability noti
fi
cation
services to work around new, unpatchable
vulnerabilities
Injecting into NoSQL
NoSQL
• Doesn't require structured data like SQ
L

• in SQL,
fi
elds must be de
fi
ned in a Schema,
as Text, Number, etc
.

• In NoSQL, keys and values can be arbitrarily
de
fi
ne
d

• A newer and less mature technology than SQL
Injecting into MongoDB
Example Login Code
Injection
• Log in with this username, and any passwor
d

Marcus'/
/

• Javascript function becomes this:
Another Injection
• Log in with this username, and any passwor
d

• This is always true (link Ch 9b)
Injecting into XPATH
• XML Data 

Store
Injection
• This query retrieves a stored credit card number
from a username and passwor
d

• This injection:
Finding XPATH Injection
Flaws
• These strings usually break the synta
x

• These strings change behavior without breaking
syntax
Preventing XPATH Injection
• Filter inputs with a whitelis
t

• Remove these characters
LDAP
• Lightweight Directory Access Protocol (LDAP
)

• Used to store names, phone numbers, email
addresses, etc
.

• Used in Microsoft Active Director
y

• Also in OpenLDAP
LDAP Queries
• Match a usernam
e

• Match any one of these condition
s

• Match all of these conditions
LDAP Injection Limitations
• Possible, but less exploitable because usually
:

• Logical operators come before user-supplied
data, so attacker can't form "or 1=1
"

• Directory attributes to be returned (like
username) are hard-coded and can't be
manipulate
d

• Applications don't return informative error
messages, so exploitation is "blind"
9b-3

Ch 9 Attacking Data Stores (Part 2)

  • 1.
    CNIT 129S: Securing WebApplications Ch 9: Attacking Data Stores Part 2 of 2 Updated 3-16-22
  • 2.
  • 3.
    Avoiding Blocked Characters • Toprevent injection, many apps remove or encode some character s • A single quotation mark is not needed for injection into a numerical fi el d • You can also use string functions to dynamically construct a string containing fi ltered characters
  • 4.
    CHR or CHARFunction • These queries work on Oracle and MS-SQL, respectively
  • 5.
    Comment Symbol Blocked •Code i s SELECT * from users WHERE name='uname ' • Try injecting this value for name : ' or 1=1 - - • To creat e SELECT * from users WHERE name='' or 1=1 -- ' • But the "--' is blocked
  • 6.
    Crafting Correct Syntax Withouta Comment • Injecting this value for name : ' or 'a'=' a • To creat e SELECT * from users WHERE name='' or 'a'='a'
  • 7.
    Circumventing Simple Validation • If"SELECT" is blocked, try these bypasses:
  • 8.
    Using SQL Comments •If spaces are blocked, use comments instea d • MySQL allows comments within keywords
  • 9.
    Second-Order SQL Injection •Many applications handle data safely when it is fi rst entered into the databas e • But it may later be processed in unsafe ways
  • 10.
    App Adds aSecond Quote • Register an account with this name : foo ' • The correct way to insert that value is by adding a second quote (link Ch 2a ) INSERT INTO users (username, password, ID, privs) VALUES ('foo''', 'secret', 2248, 1)
  • 11.
    Password Change • Requiresuser to input old password, and compares it to the password retrieved with : SELECT password FROM users WHERE username = 'foo' ' • This is a syntax error.
  • 12.
    Exploit • Register anew user with this name : ' or 1 in (SELECT password FROM users WHERE username = 'admin')- - • Perform a password change, and MS-SQL will return this error, exposing the administrator password
  • 14.
    Advanced Exploitation • Theprevious attacks had a ready means of exposing dat a • Adding UNION to a query that returns the result s • Returning data in an error messag e • What if the results are not exposed?
  • 15.
    Denial of Service •This attack does not steal dat a • It's merely destructiv e • Turn off an MS-SQL databas e ' shutdown- - • Drop tabl e ' drop table users--
  • 16.
    Retrieving Data asNumbers • No strings fi elds may be vulnerable, because single quotes are fi ltere d • Numeric fi elds are vulnerable, but only allow you to retrieve numerical value s • Use functions to convert characters to numbers
  • 18.
    Using an Out-of-Band Channel •You can inject a query but you can't see the result s • Some databases allow you to make a network connection inside the query language
  • 19.
  • 20.
    Oracle • UTL_HTTP makesan HTTP reques t • Attacker can use a netcat listener
  • 21.
    Oracle • DNS requestis even less likely to be blocked
  • 22.
    MySQL • To retrievethe fi le, set up an SMB share on your serve r • Alowing anonymous write access
  • 23.
    Leveraging the Operating System •Sometimes you can get the ability to execute shell command s • Such as by using a PHP shel l • Then you can use built-in commands like • tftp, mail, telne t • Or copy data into a fi le in the Web root so you can retrieve it with a browser
  • 24.
  • 25.
    Conditional Responses: "Blind SQLInjection" • Suppose your query doesn't return any data you can see, an d • You can't use an out-of-band channel to ex fi ltrate dat a • You can still get data, if there's any detectable behavior by the database that depends on your query
  • 26.
    Example • Put inthis text for username, and anything for passwor d admin' - - • You'll be logged in as admin
  • 27.
    True or False? •This username will log in as admin : admin' AND 1=1- - • This one will not log i n admin' AND 1=2--
  • 28.
    Finding One Letter •This username will log in as admin : • This one will not log i n
  • 29.
    Inducing Conditional Errors •On an Oracle database, this query will produce an error if the account "DBSNMP" exist s • If it doesn't, the "1/0" will never be evaluated and it won't cause an error
  • 30.
  • 31.
    Using Time Delays •MS-SQL has a built-in WAITFOR comman d • This query waits for 5 seconds if the current database user is 'sa'
  • 32.
    Conditional Delays • Youcan ask a yes/no question and get the answer from the delay
  • 33.
    Testing Single Bits •Using bitwise AND operator & • And the POWER command
  • 34.
    MySQL Delays • Currentversions have a sleep functio n • For older versions (prior to 5.0.12), use benchmark to repeat a calculation many times
  • 35.
    Oracle • No functionto cause a delay, but you can use URL_HTTP to connect to a non-existent serve r • Causes a delay until the request times out
  • 36.
    Oracle • This querycauses a timeout if the default Oracle account "DBSNMP" exists
  • 37.
  • 38.
    Further Attacks • SQLinjection lets you get the data in the database, but you can go furthe r • If database is shared by other applications, you may be able to access other application's dat a • Or compromise the OS of the database serve r • And then pivot: use the DB server to attack other servers from inside the network
  • 39.
    Further Attacks • Makenetwork connections back out to your own computer, to ex fi ltrate data and evade IDS system s • Extend database functionality by creating user-de fi ned function s • You can reintroduce functionality that has been removed or disable d • This is possible if you get database administrator privileges
  • 40.
    MS-SQL • xp_cmdshell storedprocedur e • Allows DBA (Database Administrator) to execute shell commands
  • 41.
    MS-SQL • Other storedprocedures also allow powerful attack s • These read and write to the Registr y • xp_regread • xp_regwrite
  • 42.
    Dealing with Default Lockdowns •MS-SQL 2005 and later disable xp_cmdshell by default, but you can just enable it if you are DBA
  • 43.
    MySQL • load_file allowsattacker to read a fi l e • "into out fi le" allows attacker to write to a fi l e • This example makes all hosts trusted on Linux
  • 44.
  • 45.
    Algorithm Used byTools like SQLMAP
  • 46.
  • 47.
  • 48.
  • 49.
    Blocking Apostrophes • Won'tstop injection into numerical fi eld s • If you allow apostrophes into data fi elds by doubling them, you can have second-order SQL injection vulnerabilities
  • 50.
    Stored Procedures • Makescode re-use easie r • But doesn't prevent SQL injection if user input is included in a parameter
  • 51.
    Stored Procedures • Developerde fi nes a procedur e • Attacker can still inject with this passwor d • Resulting query
  • 52.
  • 53.
    Vulnerable Code • Userinput inserted into a command, which is parsed later to match quotes
  • 54.
    Parameterized Version • Userinput replaces placeholder "? " • No parsing required, not vulnerable to SQLi
  • 55.
    Provisos • Use parameterizedqueries for EVERY quer y • Not just the ones that are obviously user- controllabl e • Every item of data should be parameterize d • Be careful if user data changes table or column name s • Allow only values from an allow-list of known safe value s • You cannot use parameter placeholders for other parts of the query, such as SORT BY ASC or SORT BY DES C • If they must be adjusted, use an allow-list
  • 56.
    Defense in Depth •Application should use low privileges when accessing the database, not DB A • Remove or disable unnecessary functions of D B • Apply vendor patche s • Subscribe to vulnerability noti fi cation services to work around new, unpatchable vulnerabilities
  • 57.
  • 58.
    NoSQL • Doesn't requirestructured data like SQ L • in SQL, fi elds must be de fi ned in a Schema, as Text, Number, etc . • In NoSQL, keys and values can be arbitrarily de fi ne d • A newer and less mature technology than SQL
  • 60.
  • 61.
    Injection • Log inwith this username, and any passwor d Marcus'/ / • Javascript function becomes this:
  • 62.
    Another Injection • Login with this username, and any passwor d • This is always true (link Ch 9b)
  • 63.
    Injecting into XPATH •XML Data 
 Store
  • 65.
    Injection • This queryretrieves a stored credit card number from a username and passwor d • This injection:
  • 66.
    Finding XPATH Injection Flaws •These strings usually break the synta x • These strings change behavior without breaking syntax
  • 67.
    Preventing XPATH Injection •Filter inputs with a whitelis t • Remove these characters
  • 68.
    LDAP • Lightweight DirectoryAccess Protocol (LDAP ) • Used to store names, phone numbers, email addresses, etc . • Used in Microsoft Active Director y • Also in OpenLDAP
  • 69.
    LDAP Queries • Matcha usernam e • Match any one of these condition s • Match all of these conditions
  • 70.
    LDAP Injection Limitations •Possible, but less exploitable because usually : • Logical operators come before user-supplied data, so attacker can't form "or 1=1 " • Directory attributes to be returned (like username) are hard-coded and can't be manipulate d • Applications don't return informative error messages, so exploitation is "blind"
  • 71.