SlideShare une entreprise Scribd logo
1  sur  61
libinjection
            and SQLi Obfuscation



OWASP NY
New York, NY
September 20, 2102



                Nick Galbreath
                @ngalbreath
                nickg@client9.com
http://client9.com/20120920
                Follow along at
                your own pace
libinjection first presented at
Black Hat USA 2012
http://client9.com/20120725




                                 iSEC Partners party at Bellagio
SQLi Obfuscation first presented at
DEFCON 20
http://client9.com/20120727/
All photos where taken by me last week
on Martha's Vineyard, MA or from
previous conferences.

Unless it's a picture of a clown

Or otherwise noted.

Then it came from The Internet.
   Thanks Internet!
The Next 30 Minutes

• Why detecting SQLi is Important
• SQL you didn't know about
• Why detecting SQLi is a hard problem
• Why current solutions aren't so good
• The libinjection algorithm and library
Why Detect SQLi

• Even if you know 100% of your queries
  are parameterized...

• Knowing who and how often SQLi
  attacks is still good to know

• Graph the attacks!   Make security
  visible! Great internal PR.
So Let's Detect SQLi !!!!
It's Easy to Get Started
with Regular Expressions

       s/UNIONs+(ALL)?/i

              ‣ At least two open source WAF
                use regular expressions.
              ‣ Failure cases in closed-source
                WAFs also indicate regexp.
1992 SQL Spec
625 pages plain text
2003 SQL Spec
128 pages pure BNF
NULL
MySQL NULL Alias

MySQL NULL can written as N
case sensitive. n is not a null.

      This means any WAF that does a
      "to_lower" on the user input and
     looks for "null" will miss this case.
Numbers
Integer Forms
• [0-9]+
• 0x[0-9a-fA-F]+   0xDEADbeef
   MySQL, MSSQL
   0x is case sensitive

• 0x MSSQL only
• x'DEADbeef' PgSQL
• b'10101010' MySQL,   PgSQL

• 0b010101 MySQL
Floating Point
•   digits

•   digits[.]

•   digits[.]digits                                       http://bit.ly/Qp6KTu




•   digits[eE]digits                •   digits[.]digits[eE]digits

•   digits[eE][+-]digits            •   [.]digits

•   digits[.][eE]digits             •   [.]digits[eE]digits

•   digits[.]digits[eE][+-]digits   •   [.]digits[eE][+-]digits

             Optional leading unary operator [+-]
Floating Point, Oracle
• Everyone of the previous formats can
  have a trailing [dDfF]

• But why use numbers as all?
   Special literals, maybe case sensitive:

 • binary_double_infinity
 • binary_double_nan
 • binary_float_infinity
 • binary_float_nan
MSSQL Money Literals
 • -$45.12
 • $123.0
 • +$1,000,000.00 Commas ignored
 • Other "monetary symbols" ignored
 • Autocasts to everything
Parser Differences
• 1. AND 2 vs.
• 1.AND 2 vs.
• 1.AND2
   (no space between "1." "AND" and "2")
• some parsers accept (MySQL), some don't
  (sqlite3)
Comments
MySQL # Comment
• '#' signals an till-end-of-line Comment
• Well used in SQLi attacks
• However... '#' is an operator in PgSQL.
  Beware that s/#.*n// will delete
  code that needs inspecting.

• Lots of other MySQL comment
  oddities:
  http://dev.mysql.com/doc/refman/5.6/
  en/comments.html
PGSQL Comments
• Besides the usual '--' comment
• PgSQL has nested C-Style Comments
•/* foo /* bar */ */
• Careful! What happens when you
  'remove comments' in
   /* /* */ UNION ALL /* */ */
Strings
C-Style String Merging
• C-Style consecutive strings are merged into
  one.
• SELECT 'foo' 'bar';
• SELECT 'foo' "bar"; (mysql)
• SQL Spec and PgSQL requires a newline
  between literals:
  SELECT 'foo'
    'bar';
Standard Unicode

• N'....' or n'...'
• MSSQL Case-sensitive 'N'
• Not sure on escaping rules.
MySQL Ad-Hoc
          Charset

• _charset'....'
• _latin1'.....'
• _utf8'....'
PGSQL Dollar Quoting
From http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS


A dollar-quoted string constant consists of a dollar sign
($), an optional "tag" of zero or more characters, another
dollar sign, an arbitrary sequence of characters that
makes up the string content, a dollar sign, the same tag
that began this dollar quote, and a dollar sign. For
example, here are two different ways to specify the
string "Dianne's horse" using dollar quoting:

$$Dianne's horse$$
$SomeTag$Dianne's horse$SomeTag$

          Want more fun? They can be nested!
PGSQL Unicode
From http://www.postgresql.org/docs/9.1/static/sql-syntax-
lexical.html emphasis mine:

... This variant starts with U& (upper or lower case U followed by ampersand) immediately before the
opening double quote, without any spaces in between, for example U&"foo". (Note that this creates an
ambiguity with the operator &. Use spaces around the operator to avoid this problem.) Inside the quotes,
Unicode characters can be specified in escaped form by writing a backslash followed by the four-digit
hexadecimal code point number or alternatively a backslash followed by a plus sign followed by a six-digit
hexadecimal code point number. For example, the identifier "data" could be written as

U&"d0061t+000061"

The following less trivial example writes the Russian word "slon" (elephant)
in Cyrillic letters:
U&"0441043B043E043D"

If a different escape character than backslash is
desired, it can be specified using the UESCAPE clause
after the string, for example:
U&"d!0061t!+000061" UESCAPE '!'
Oracle Q String
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/
fundamentals.htm#autoId6


q'!...!' notation allows use of single quotes inside literal

string_var := q'!I'm a string!';

You can use delimiters [, {, <, and (, pair them with ], }, >, and ),
pass a string literal representing a SQL statement to a
subprogram, without doubling the quotation marks around
'INVALID' as follows:
func_call(q'[SELECT index_name FROM user_indexes
  WHERE status ='INVALID']');
Operators and
 Expressions
Ridiculous Operators
•   != not equals, standard   •   ||/ cube root (pgsql)

•   <=> (mysql)               •   ** exponents (oracle

•   <> (mssql)

•   ^= (oracle)

•   !>, !< not less than
    (mssql)

•   / oracle

•   !! factorial (pgsql)

•   |/ sqaure root (pgsql)
Expressions!
• Using the common query extension of
  "OR 1=1"
• Besides using literals, one can use functions:
 •COS(0) = SIN(PI()/2)
 •COS(@VERSION) = -
    SIN(@VERSION + PI()/2)
EXCEPT (mssql)
    MINUS (Oracle)
• Like UNION, UNION ALL
• But returns all results from first query
  minus/except the ones from the
  second query

• There is also INTERSECT and MINUS
  as well.

• I think someone clever could use these,
  typically not in WAF rules.
Side Note: "IN" lists
• e.g. ....WHERE id IN (1,2,3,4) ....
• These have to be manually created.
• There is no API or parameter binding
  for this construct in any
  platform,framework or language.

• There is no consistent, safe way to
  make this (other than convention,
What happens when
regular expressions are used to
     capture these rules?
(?:)s*whens*d+s*then)|(?:"s*(?:#|--|{))|(?:/*!s?d+)|(?:ch(?:a)?rs*(s*d)|(?:(?:(n?and|x?or|
not)s+||||&&)s*w+()
(?:[s()]cases*()|(?:)s*likes*()|(?:havings*[^s]+s*[^ws])|(?:ifs?([dw]s*[=<>~])
(?:"s**.+(?:or|id)W*"d)|(?:^")|(?:^[ws"-]+(?<=ands)(?<=ors)(?<=xors)(?<=nands)(?<=nots)(?<=|
|)(?<=&&)w+()|(?:"[sd]*[^ws]+W*dW*.*["d])|(?:"s*[^ws?]+s*[^ws]+s*")|(?:"s*[^ws]+
s*[Wd].*(?:#|--))|(?:".**s*d)|(?:"s*ors[^d]+[w-]+.*d)|(?:[()*<>%+-][w-]+[^ws]+"[^,])
(?:d"s+"s+d)|(?:^admins*"|(/*)+"+s?(?:--|#|/*|{)?)|(?:"s*or[ws-]+s*[+<>=(),-]s*[d"])|
(?:"s*[^ws]?=s*")|(?:"W*[+=]+W*")|(?:"s*[!=|][ds!=+-]+.*["(].*$)|(?:"s*[!=|][ds!=]+.*d+$)|
(?:"s*likeW+[w"(])|(?:siss*0W)|(?:wheres[sw.,-]+s=)|(?:"[<>~]+")
(?:unions*(?:all|distinct|[(!@]*)?s*[([]*s*select)|(?:w+s+likes+")|(?:likes*"%)|(?:"s*like
W*["d])|(?:"s*(?:n?and|x?or|not ||||&&)s+[sw]+=s*w+s*having)|(?:"s**s*w+W+")|(?:"s*[^?
ws=.,;)(]+s*[(@"]*s*w+W+w)|(?:selects*[[]()sw.,"-]+from)|(?:find_in_sets*()
(?:ins*(+s*select)|(?:(?:n?and|x?or|not ||||&&)s+[sw+]+(?:regexps*(|soundss+likes*"|[=d]
+x))|("s*ds*(?:--|#))|(?:"[%&<>^=]+ds*(=|or))|(?:"W+[w+-]+s*=s*dW+")|(?:"s*iss*d.+"?w)|
(?:"|?[w-]{3,}[^ws.,]+")|(?:"s*iss*[d.]+s*W.*")
(?:[dW]s+ass*["w]+s*from)|(?:^[Wd]+s*(?:union|select|create|rename|truncate|load|alter|delete|
update|insert|desc))|(?:(?:select|create|rename|truncate|load|alter|delete|update|insert|desc)s+(?:
(?:group_)concat|char|load_file)s?(?)|(?:ends*);)|("s+regexpW)|(?:[s(]load_files*()
(?:@.+=s*(s*select)|(?:d+s*ors*d+s*[-+])|(?:/w+;?s+(?:having|and|or|select)W)|(?:ds+group
s+by.+()|(?:(?:;|#|--)s*(?:drop|alter))|(?:(?:;|#|--)s*(?:update|insert)s*w{2,})|(?:[^w]SETs*@w
+)|(?:(?:n?and|x?or|not ||||&&)[s(]+w+[s)]*[!=+]+[sd]*["=()])
(?:"s+ands*=W)|(?:(s*selects*w+s*()|(?:*/from)|(?:+s*d+s*+s*@)|(?:w"s*(?:[-+=|@]+s*)+
[d(])|(?:coalesces*(|@@w+s*[^ws])|(?:W!+"w)|(?:";s*(?:if|while|begin))|(?:"[sd]+=s*d)|
(?:orders+bys+ifw*s*()|(?:[s(]+cased*W.+[tw]hen[s(])
(?:(select|;)s+(?:benchmark|if|sleep)s*?(s*(?s*w+)
(?:creates+functions+w+s+returns)|(?:;s*(?:select|create|rename|truncate|load|alter|delete|update|
insert|desc)s*[[(]?w{2,})
(?:alters*w+.*characters+sets+w+)|(";s*waitfors+times+")|(?:";.*:s*goto)
(?:procedures+analyses*()|(?:;s*(declare|open)s+[w-]+)|(?:creates+(procedure|function)s*w+s*
(s*)s*-)|(?:declare[^w]+[@#]s*w+)|(execs*(s*@)
(?:selects*pg_sleep)|(?:waitfors*delays?"+s?d)|(?:;s*shutdowns*(?:;|--|#|/*|{))
(?:sexecs+xp_cmdshell)|(?:"s*!s*["w])|(?:fromW+information_schemaW)|(?:(?:(?:current_)?user|
database|schema|connection_id)s*([^)]*)|(?:";?s*(?:select|union|having)s*[^s])|(?:wiifs*()|
(?:execs+master.)|(?:union select @)|(?:union[w(s]*select)|(?:select.*w?user()|(?:into[s+]+
(?:dump|out)files*")
(?:merge.*usings*()|(executes*immediates*")|(?:W+d*s*havings*[^s-])|(?:matchs*[w(),+-]+
s*againsts*()
(?:,.*[)da-f"]"(?:".*"|Z|[^"]+))|(?:Wselect.+W*from)|((?:select|create|rename|truncate|load|alter|
delete|update|insert|desc)s*(s*spaces*()
(?:[$(?:ne|eq|lte?|gte?|n?in|mod|all|size|exists|type|slice|or)])
(?:(sleep((s*)(d*)(s*))|benchmark((.*),(.*))))
Unicorn Alert!


‣ At Black Hat USA 2005,
  Hanson and Patterson presented:
  Guns and Butter: Towards Formal Axioms
  of Validation (http://bit.ly/OBe7mJ)
‣ …formally proved that for any regex validator,
  we could construct either a safe query which
  would be flagged as dangerous, or a dangerous
  query which would be flagged as correct.
‣ (summary from libdejector documentation)
Can we do better?
libinjection
Key Insight
‣ A SQLi attack must be parsed as SQL within
  the original query.
‣ SQL has a rigid syntax
  ‣ it works, or it's a syntax error.
  ‣ Compare this to HTML/XSS rules
‣ "Is it a SQLi attack?" becomes
  "Could it be a SQL snippet?"
Only 3 Contexts
User input is only "injected" into SQL in three
ways:
‣ As-Is
‣ Inside a single quoted string
‣ Inside a double quoted string
Means we have to parse input three times.
Compare to XSS
Identification of
         SQL snippets
    without context is hard
‣   1-917-660-3400 my phone number or
    ... an arithmetic expression in SQL?
‣   @ngalbreath my twitter account or
    ... a SQL variable?
‣ English-like syntax and common keywords:
    union, group, natural, left, right, join, top,
    table, create, in, is, not, before, begin, between
Existing SQL Parsers

‣ Only parse their flavor of SQL
‣ Not well designed to handle snippets
‣ Hard to extend
‣ Worried about correctness
                ... so I wrote my own!
                       ... so I wrote my own!
Tokenization


‣ Converts input into a stream of tokens
‣ Uses "master list" of keywords and functions
  across all databases.
‣ Handles comments, string, literals, weirdos.
5000224' UNION USER_ID>0--


[ ('...500224', string),
  ('UNION', union operator),
  ('USER_ID', name),
  ('>', operator),
  ('0', number),
  ('--.....', comment) ]
Meet the Tokens
‣ none/name          ‣ group-like operation
‣ variable           ‣ union-like operator
‣ string             ‣ logical operator
‣ regular operator   ‣ function
‣ unknown            ‣ comma
‣ number             ‣ semi-colon
‣ comment            ‣ left parens
‣ keyword            ‣ right parens
Merging,
        Specialization,
        Disambiguation
‣ "IS", "NOT" ==> "IS NOT" (single op)
‣ "NATURAL", "JOIN" => "NATURAL JOIN"
‣ ("+", operator) -> ("+", unary operator)
‣ (COS, function), (1, number) ==>
   (COS, name), (1, number)
   functions must be followed with a
  parenthesis!
Folding


‣ This step actually isn't needed to detect, but
                           Text
  is needed to reduce false positives.
‣ Converts simple arithmetic expressions into a
  single value, and does not try to evaluate.
‣ 1-917-660-3400 -> "1"



                                pics courtesy The Internet
                                pics
Knows nothing about SQLi
 ‣ So far this is purely a parsing problem.
 ‣ Knows nothing about SQLi (which is evolving)
 ‣ Can be 100% tested against any SQL input
   (not SQLi) for correctness.
 ‣ Language independent test cases
$ cat test-tokens-numbers-floats-003.txt
--TEST--
floating-point parsing test
--INPUT--
SELECT .0;
--EXPECTED--
k SELECT
1 .0
; ;
Fingerprints
‣ The token types of a user input form a hash or
  a fingerprint.
  ‣   -6270" UNION ALL SELECT   5594,   5594, 5594, 5594,   5594,   5594,
      5594, 5594, 5594, 5594,   5594,   5594, 5594, 5594,   5594,   5594,
      5594, 5594, 5594, 5594,   5594,   5594, 5594, 5594,   5594,   5594,
      5594, 5594, 5594, 5594,   5594,   5594, 5594, 5594,   5594,   5594,
      5594, 5594, 5594, 5594,   5594#   AND "JWWQ"="JWWQ

  ‣ becomes "sUk1,1,1,1,1,1,1,1,&"

‣ Now let's generate fingerprints from
  Real World Data.
‣ Can we distinguish between SQLi and benign
  input?
                        pics courtesy The Internet
Training on SQLi
‣ Parse known SQLi attacks from
  ‣ SQLi vulnerability scanners
  ‣ Published reports
  ‣ SQLi How-Tos and Cheet Sheets
‣ > 32,000 total
‣ Since Black Hat, donations from
  ‣ modsecurity
  ‣ Qualys
‣ > 50,000 total
Training on Real Input
‣ 100s of Millions of user inputs from Etsy's
  access logs were also parsed.
‣ Large enough to get a good sample (Top 50
  USA site)
‣ Old enough to have lots of odd ways of query
  string formatting.
‣ Full text search with an diverse subject
  domain
How many tokens are
needed to determine if
user input is SQLi or not?
no matter how long the input
632 out of 1,048,576 are SQLi
&1o1U   &f()o   &f(1)   1&((f   1&((k   1&(1)   1&(1,   1&(1o   1&(f(   1&(k(   1&(k1   1&(kf   1&(kk   1&(kn   1&(ko   1&(v)   1&1Bf   1&1Uk   1&1f(   1&1o(
1&1o1   1&1of   1&1ok   1&1on   1&1oo   1&1ov   1&f((   1&f()   1&f(1   1&f(f   1&f(k   1&f(n   1&f(v   1&k(1   1&k(f   1&k1k   1&kUk   1&kk1   1&n()   1&no1
1&nos   1&o(1   1&o1o   1&sU(   1&so1   1&sos   1)&(1   1)&(f   1)&(k   1)&(n   1)&1B   1)&1U   1)&1f   1)&1o   1)&f(   1)&o(   1)()s   1))&(   1))&1   1))&f
1))&o   1)))&   1))))   1)));   1)))B   1)))U   1)))k   1)))o   1));k   1))B1   1))Uk   1))Un   1))k1   1))kk   1))o(   1))o1   1))of   1))ok   1))on   1),(1
1);k&   1);k(   1);kf   1);kk   1);kn   1);ko   1)B1    1)B1&   1)B1c   1)B1o   1)U(k   1)Uk1   1)Ukf   1)Ukk   1)Ukn   1)Unk   1)k1    1)k1c   1)k1o   1)kks
1)o(1   1)o(k   1)o(n   1)o1B   1)o1f   1)o1k   1)o1o   1)of(   1)ok(   1)ok1   1)on&   1)ono   1,(f(   1,(k(   1,(k1   1,(kf   1,1),   1,1)o   1,1B1   1,1Uk
1,f(1   1,s),   1;k&k   1;k((   1;k(1   1;k(o   1;k1,   1;kf(   1;kks   1;kn(   1;kn,   1;knc   1;ko(   1;kok   1B1     1B1,1   1B1,n   1B1Uk   1B1c    1B1k1
1B1ks   1Bf(1   1Bf(f   1Bk(1   1Bn,n   1Bnk1   1U((k   1U(k1   1U(kf   1U(kn   1U1,1   1Uc     1Uk     1Uk(1   1Uk(k   1Uk(n   1Uk1    1Uk1,   1Uk1c   1Uk1f
1Uk1k   1Uk1n   1Uk1o   1Ukf    1Ukf(   1Ukf,   1Ukk(   1Ukk,   1Ukk1   1Ukkk   1Ukkn   1Ukn&   1Ukn(   1Ukn,   1Ukn1   1Uknc   1Uknk   1Ukno   1Ukns   1Uko1
1Ukok   1Uks,   1Uksc   1Ukv    1Ukv,   1Ukvc   1Un,1   1Un1,   1Unk(   1Unk1   1Unkf   1Uon1   1f()k   1k1U(   1k1Uk   1k1c    1kU1,   1kf(1   1kk(1   1kksc
1knkn   1n&f(   1nUk1   1nUkn   1nk1c   1nkf(   1o(((   1o((1   1o((f   1o(1)   1o(1o   1o(f(   1o(k(   1o(k1   1o(kf   1o(kn   1o(kv   1o(n)   1o(s)   1o1)&
1o1)o   1o1Bf   1o1Uk   1o1f(   1o1kf   1o1o(   1o1o1   1o1of   1o1oo   1o1ov   1of()   1of(1   1of(f   1of(n   1of(s   1ok(1   1ok(k   1ok1    1ok1,   1ok1c
1ok1k   1okf(   1oks,   1oksc   1okv,   1onos   1oso1   ;kknc   Uk1,1   Uk1,f   Uk1,n   Ukkkn   f((k(   f((kf   f()&f   f()of   f(1)&   f(1)o   f(1,f   f(1o1
f(f()   f(f(1   f(k()   f(k,(   f(k,n   f(n()   f(v,1   k()ok   k(1)U   k(ok(   k(vv)   k1,1,   k1,1c   k1,1k   k1,f(   k1k(k   k1o(s   k;non   kf(1)   kf(1,
kf(f(   kf(n,   kf(o)   kf(v:   kk(f(   kk1f(   kk1fn   kk1kk   kk1nk   kk1vk   kk1vn   kn1kk   kn1vk   kn1vn   ko(k(   ko(kf   kok(k   kv)     kvk(1   n&(1)
n&(k1   n&(o1   n&1f(   n&1o(   n&1o1   n&1of   n&1oo   n&f(1   n&f(f   n&k(1   n&o1o   n)&(k   n)&1f   n)&1o   n)&f(   n))&(   n))&1   n))&f   n)))&   n)));
n)))k   n)))o   n));k   n))kk   n))o(   n))o1   n))of   n))ok   n);k&   n);k(   n);kf   n);kk   n);kn   n);ko   n)k1o   n)kks   n)o(k   n)o1&   n)o1f   n)o1o
n)of(   n)ok(   n,(f(   n,(k(   n,(k1   n,(kf   n,f(1   n:o1U   n;k&k   n;k((   n;k(1   n;kf(   n;kks   n;kn(   n;ko(   n;kok   nUk(k   nUk1,   nUkn,   nUnk(
nk1Uk   nkf(1   nkksc   nnn)U   nno1U   no(k1   no(o1   no1&1   no1Uk   no1f(   no1o(   no1o1   no1of   no1oo   nof(1   nok(1   nok(k   o1kf(   oUk1,   of()o
of(1)   ok1o1   okkkn   ook1,   s&(1)   s&(1,   s&(1o   s&(f(   s&(k)   s&(k1   s&(kf   s&(ko   s&1Bf   s&1Uk   s&1c    s&1f(   s&1o(   s&1o1   s&1of   s&1on
s&1oo   s&1os   s&1ov   s&f((   s&f()   s&f(1   s&f(f   s&f(v   s&k&s   s&k(1   s&k(o   s&k1o   s&kc    s&knk   s&ko(   s&ko1   s&kok   s&kos   s&n&s   s&no1
s&nos   s&o(1   s&o(k   s&o1o   s&okc   s&oko   s&os    s&sos   s&v:o   s&vos   s&vso   s)&(1   s)&(k   s)&1B   s)&1f   s)&1o   s)&f(   s)&o(   s))&(   s))&1
s))&f   s))&n   s))&o   s)))&   s)));   s)))B   s)))U   s)))k   s)))o   s));k   s))B1   s))Uk   s))Un   s))k1   s))kk   s))o(   s))o1   s))of   s))ok   s),(1
s);k&   s);k(   s);kf   s);kk   s);kn   s);ko   s)B1    s)B1&   s)B1c   s)B1o   s)U(k   s)Uk1   s)Unk   s)k1    s)k1c   s)k1o   s)kks   s)o(1   s)o(k   s)o1B
s)o1f   s)o1k   s)o1o   s)of(   s)ok(   s)ok1   s,1),   s;k&k   s;k((   s;k(1   s;k(o   s;k1,   s;k1o   s;k;    s;k[k   s;k[n   s;kf(   s;kkn   s;kks   s;kn(
s;knk   s;knn   s;ko(   s;kok   s;kvc   s;kvk   s;n:k   sB1     sB1&s   sB1Uk   sB1c    sB1os   sU((k   sU(k(   sU(kk   sU(kn   sU(ks   sUk(k   sUk1    sUk1&
sUk1,   sUk1c   sUk1k   sUk1o   sUkf(   sUkk1   sUkkk   sUkn(   sUkn,   sUkn1   sUknk   sUkok   sUkv,   sUkvc   sUn(k   sUnk1   sUnkf   sUno1   sf(1)   sf(n,
sf(s)   sk)&(   sk)&1   sk)&f   sk);k   sk)B1   sk)Uk   sk)Un   sk)k1   sk)kk   sk)o(   sk)o1   sk)of   sk)ok   sk1&1   sk1Uk   sk1c    sk1o1   sk1os   skU1,
skks    skksc   sn,f(   sno1U   so(((   so((k   so((s   so(1)   so(1o   so(f(   so(k)   so(k1   so(kk   so(kn   so(ko   so(ks   so(os   so(s)   so1&1   so1&o
so1&s   so1Bf   so1Uk   so1c    so1f(   so1kf   so1o(   so1o1   so1of   so1ok   so1oo   so1os   so1ov   sof()   sof(1   sof(f   sof(k   sok&s   sok(1   sok(k
sok(o   sok(s   sok1    sok1,   sok1c   sok1o   sokc    sokf(   sokn,   soknk   soko(   soko1   sokok   sokos   sonk1   sono1   sonos   sos     sos&(   soso(
sosos   sov&1   sov&s   sov:o   sovo1   sovok   sovos   sovov   sovso   v:o1)   vUk1,   vok1,



                                                                                                 as of 2012-09-20
The Library
On GitHub Now
~500 Lines of Code
One file + data
No memory allocation
No threads
No external dependencies
Fixed stack size
>100k checks a second
tada
#include "sqlparse.h"
#include <string.h>
int main()
{
    const char* ucg = "1 OR 1=1";
    // input should be normalized, upper-cased
    //   You can use sqli_normalize
    //   if you don't have your own function
    sfilter sf;
    return is_sqli(&sf, ucg, strlen(ucg));
}

$ gcc -Wall -Wextra sample.c sqlparse.c
$ ./a.out
$ echo $?
1
Work in
Progress
What's Next?
• Change API to allow passing in
  fingerprint data or a function. Allows
  upgrades without code changes.

• Can we reduce the number of tokens?
  String, variables, numbers are all just
  values.

• Folding of comma-separated values?
  1,2,3,4 => 1

• Can we just eliminate all parenthesis?
Help!
• More SQLi from the field please!
• False positives welcome
• More test cases with exotic SQL to test
  parser.

• Ports to other languages (the language-
  neutral test framework should make
  this easier).

• Compiling on Windows (mostly tested
  on Mac OS X and Linux)
Do you have a
  commercial WAF?

• Set up a dead page and let me poke it.
• Curious on false positives and false
  negatives.
Slides and Source Code:
http://www.client9.com/libinjection/

Nick Galbreath
@ngalbreath
nickg@client9.com




       Oct 25, OWASP USA, Austin, Texas
        Continuous Deployment and Security

Contenu connexe

Tendances

Ln monitoring repositories
Ln monitoring repositoriesLn monitoring repositories
Ln monitoring repositoriessnyff
 
Defcon CTF quals
Defcon CTF qualsDefcon CTF quals
Defcon CTF qualssnyff
 
Harder Faster Stronger
Harder Faster StrongerHarder Faster Stronger
Harder Faster Strongersnyff
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in productionMartijn Dashorst
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!Ortus Solutions, Corp
 
Owasp tds
Owasp tdsOwasp tds
Owasp tdssnyff
 
Entomology 101
Entomology 101Entomology 101
Entomology 101snyff
 
Bsidesvienna sentinel v0.4
Bsidesvienna sentinel v0.4Bsidesvienna sentinel v0.4
Bsidesvienna sentinel v0.4nibod
 
Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...
Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...
Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...Codemotion
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaScala Italy
 
PHP7 - The New Engine for old good train
PHP7 - The New Engine for old good trainPHP7 - The New Engine for old good train
PHP7 - The New Engine for old good trainXinchen Hui
 
Php Debugging from the Trenches
Php Debugging from the TrenchesPhp Debugging from the Trenches
Php Debugging from the TrenchesSimon Jones
 
The secret of PHP7's Performance
The secret of PHP7's Performance The secret of PHP7's Performance
The secret of PHP7's Performance Xinchen Hui
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyWen-Tien Chang
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksJuho Vepsäläinen
 
How to analyze your codebase with Exakat using Docker - Longhorn PHP
How to analyze your codebase with Exakat using Docker - Longhorn PHPHow to analyze your codebase with Exakat using Docker - Longhorn PHP
How to analyze your codebase with Exakat using Docker - Longhorn PHPDana Luther
 
JavaOne 2017 - Choosing a NoSQL API and Database to Avoid Tombstones and Drag...
JavaOne 2017 - Choosing a NoSQL API and Database to Avoid Tombstones and Drag...JavaOne 2017 - Choosing a NoSQL API and Database to Avoid Tombstones and Drag...
JavaOne 2017 - Choosing a NoSQL API and Database to Avoid Tombstones and Drag...Leonardo De Moura Rocha Lima
 

Tendances (20)

Ln monitoring repositories
Ln monitoring repositoriesLn monitoring repositories
Ln monitoring repositories
 
Defcon CTF quals
Defcon CTF qualsDefcon CTF quals
Defcon CTF quals
 
Harder Faster Stronger
Harder Faster StrongerHarder Faster Stronger
Harder Faster Stronger
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Owasp tds
Owasp tdsOwasp tds
Owasp tds
 
Entomology 101
Entomology 101Entomology 101
Entomology 101
 
Bsidesvienna sentinel v0.4
Bsidesvienna sentinel v0.4Bsidesvienna sentinel v0.4
Bsidesvienna sentinel v0.4
 
Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...
Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...
Francesco Strazzullo - Frameworkless Frontend Development - Codemotion Milan ...
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
 
PHP7 - The New Engine for old good train
PHP7 - The New Engine for old good trainPHP7 - The New Engine for old good train
PHP7 - The New Engine for old good train
 
Old code doesn't stink
Old code doesn't stinkOld code doesn't stink
Old code doesn't stink
 
Php Debugging from the Trenches
Php Debugging from the TrenchesPhp Debugging from the Trenches
Php Debugging from the Trenches
 
The secret of PHP7's Performance
The secret of PHP7's Performance The secret of PHP7's Performance
The secret of PHP7's Performance
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
 
How to analyze your codebase with Exakat using Docker - Longhorn PHP
How to analyze your codebase with Exakat using Docker - Longhorn PHPHow to analyze your codebase with Exakat using Docker - Longhorn PHP
How to analyze your codebase with Exakat using Docker - Longhorn PHP
 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
 
JavaOne 2017 - Choosing a NoSQL API and Database to Avoid Tombstones and Drag...
JavaOne 2017 - Choosing a NoSQL API and Database to Avoid Tombstones and Drag...JavaOne 2017 - Choosing a NoSQL API and Database to Avoid Tombstones and Drag...
JavaOne 2017 - Choosing a NoSQL API and Database to Avoid Tombstones and Drag...
 
How to-node-core
How to-node-coreHow to-node-core
How to-node-core
 

Similaire à libinjection and sqli obfuscation, presented at OWASP NYC

DEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq liteDEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq liteFelipe Prado
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsIvan Novikov
 
SQL Tips + Tricks for Developers
SQL Tips + Tricks for DevelopersSQL Tips + Tricks for Developers
SQL Tips + Tricks for DevelopersVictorSzoltysek
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoPichaya Morimoto
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07AnusAhmad
 
Presto Meetup 2016 Small Start
Presto Meetup 2016 Small StartPresto Meetup 2016 Small Start
Presto Meetup 2016 Small StartHiroshi Toyama
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaKazuhiro Sera
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionChema Alonso
 
SPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic librarySPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic libraryAdaCore
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrationstakezoe
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
Hack your db before the hackers do
Hack your db before the hackers doHack your db before the hackers do
Hack your db before the hackers dofangjiafu
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
When to no sql and when to know sql javaone
When to no sql and when to know sql   javaoneWhen to no sql and when to know sql   javaone
When to no sql and when to know sql javaoneSimon Elliston Ball
 

Similaire à libinjection and sqli obfuscation, presented at OWASP NYC (20)

PHP - Introduction to Advanced SQL
PHP - Introduction to Advanced SQLPHP - Introduction to Advanced SQL
PHP - Introduction to Advanced SQL
 
DEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq liteDEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq lite
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application Firewalls
 
SQL Tips + Tricks for Developers
SQL Tips + Tricks for DevelopersSQL Tips + Tricks for Developers
SQL Tips + Tricks for Developers
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07
 
Presto Meetup 2016 Small Start
Presto Meetup 2016 Small StartPresto Meetup 2016 Small Start
Presto Meetup 2016 Small Start
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL InjectionShmooCON 2009 : Re-playing with (Blind) SQL Injection
ShmooCON 2009 : Re-playing with (Blind) SQL Injection
 
SPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic librarySPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic library
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrations
 
Asp
AspAsp
Asp
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Hack your db before the hackers do
Hack your db before the hackers doHack your db before the hackers do
Hack your db before the hackers do
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Erik_van_Roon.pdf
Erik_van_Roon.pdfErik_van_Roon.pdf
Erik_van_Roon.pdf
 
When to no sql and when to know sql javaone
When to no sql and when to know sql   javaoneWhen to no sql and when to know sql   javaone
When to no sql and when to know sql javaone
 

Plus de Nick Galbreath

Making operations visible - devopsdays tokyo 2013
Making operations visible  - devopsdays tokyo 2013Making operations visible  - devopsdays tokyo 2013
Making operations visible - devopsdays tokyo 2013Nick Galbreath
 
Faster Secure Software Development with Continuous Deployment - PH Days 2013
Faster Secure Software Development with Continuous Deployment - PH Days 2013Faster Secure Software Development with Continuous Deployment - PH Days 2013
Faster Secure Software Development with Continuous Deployment - PH Days 2013Nick Galbreath
 
Fixing security by fixing software development
Fixing security by fixing software developmentFixing security by fixing software development
Fixing security by fixing software developmentNick Galbreath
 
DevOpsDays Austin 2013 Reading List
DevOpsDays Austin 2013 Reading ListDevOpsDays Austin 2013 Reading List
DevOpsDays Austin 2013 Reading ListNick Galbreath
 
Care and Feeding of Large Scale Graphite Installations - DevOpsDays Austin 2013
Care and Feeding of Large Scale Graphite Installations - DevOpsDays Austin 2013Care and Feeding of Large Scale Graphite Installations - DevOpsDays Austin 2013
Care and Feeding of Large Scale Graphite Installations - DevOpsDays Austin 2013Nick Galbreath
 
Rebooting Software Development - OWASP AppSecUSA
Rebooting Software Development - OWASP AppSecUSA Rebooting Software Development - OWASP AppSecUSA
Rebooting Software Development - OWASP AppSecUSA Nick Galbreath
 
Continuous Deployment - The New #1 Security Feature, from BSildesLA 2012
Continuous Deployment - The New #1 Security Feature, from BSildesLA 2012Continuous Deployment - The New #1 Security Feature, from BSildesLA 2012
Continuous Deployment - The New #1 Security Feature, from BSildesLA 2012Nick Galbreath
 
Time tested php with libtimemachine
Time tested php with libtimemachineTime tested php with libtimemachine
Time tested php with libtimemachineNick Galbreath
 
Data Driven Security, from Gartner Security Summit 2012
Data Driven Security, from Gartner Security Summit 2012Data Driven Security, from Gartner Security Summit 2012
Data Driven Security, from Gartner Security Summit 2012Nick Galbreath
 
Slide show font sampler, black on white
Slide show font sampler, black on whiteSlide show font sampler, black on white
Slide show font sampler, black on whiteNick Galbreath
 
Fraud Engineering, from Merchant Risk Council Annual Meeting 2012
Fraud Engineering, from Merchant Risk Council Annual Meeting 2012Fraud Engineering, from Merchant Risk Council Annual Meeting 2012
Fraud Engineering, from Merchant Risk Council Annual Meeting 2012Nick Galbreath
 
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012Nick Galbreath
 
DevOpsSec: Appling DevOps Principles to Security, DevOpsDays Austin 2012
DevOpsSec: Appling DevOps Principles to Security, DevOpsDays Austin 2012DevOpsSec: Appling DevOps Principles to Security, DevOpsDays Austin 2012
DevOpsSec: Appling DevOps Principles to Security, DevOpsDays Austin 2012Nick Galbreath
 

Plus de Nick Galbreath (13)

Making operations visible - devopsdays tokyo 2013
Making operations visible  - devopsdays tokyo 2013Making operations visible  - devopsdays tokyo 2013
Making operations visible - devopsdays tokyo 2013
 
Faster Secure Software Development with Continuous Deployment - PH Days 2013
Faster Secure Software Development with Continuous Deployment - PH Days 2013Faster Secure Software Development with Continuous Deployment - PH Days 2013
Faster Secure Software Development with Continuous Deployment - PH Days 2013
 
Fixing security by fixing software development
Fixing security by fixing software developmentFixing security by fixing software development
Fixing security by fixing software development
 
DevOpsDays Austin 2013 Reading List
DevOpsDays Austin 2013 Reading ListDevOpsDays Austin 2013 Reading List
DevOpsDays Austin 2013 Reading List
 
Care and Feeding of Large Scale Graphite Installations - DevOpsDays Austin 2013
Care and Feeding of Large Scale Graphite Installations - DevOpsDays Austin 2013Care and Feeding of Large Scale Graphite Installations - DevOpsDays Austin 2013
Care and Feeding of Large Scale Graphite Installations - DevOpsDays Austin 2013
 
Rebooting Software Development - OWASP AppSecUSA
Rebooting Software Development - OWASP AppSecUSA Rebooting Software Development - OWASP AppSecUSA
Rebooting Software Development - OWASP AppSecUSA
 
Continuous Deployment - The New #1 Security Feature, from BSildesLA 2012
Continuous Deployment - The New #1 Security Feature, from BSildesLA 2012Continuous Deployment - The New #1 Security Feature, from BSildesLA 2012
Continuous Deployment - The New #1 Security Feature, from BSildesLA 2012
 
Time tested php with libtimemachine
Time tested php with libtimemachineTime tested php with libtimemachine
Time tested php with libtimemachine
 
Data Driven Security, from Gartner Security Summit 2012
Data Driven Security, from Gartner Security Summit 2012Data Driven Security, from Gartner Security Summit 2012
Data Driven Security, from Gartner Security Summit 2012
 
Slide show font sampler, black on white
Slide show font sampler, black on whiteSlide show font sampler, black on white
Slide show font sampler, black on white
 
Fraud Engineering, from Merchant Risk Council Annual Meeting 2012
Fraud Engineering, from Merchant Risk Council Annual Meeting 2012Fraud Engineering, from Merchant Risk Council Annual Meeting 2012
Fraud Engineering, from Merchant Risk Council Annual Meeting 2012
 
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
 
DevOpsSec: Appling DevOps Principles to Security, DevOpsDays Austin 2012
DevOpsSec: Appling DevOps Principles to Security, DevOpsDays Austin 2012DevOpsSec: Appling DevOps Principles to Security, DevOpsDays Austin 2012
DevOpsSec: Appling DevOps Principles to Security, DevOpsDays Austin 2012
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Dernier (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

libinjection and sqli obfuscation, presented at OWASP NYC

  • 1. libinjection and SQLi Obfuscation OWASP NY New York, NY September 20, 2102 Nick Galbreath @ngalbreath nickg@client9.com
  • 2. http://client9.com/20120920 Follow along at your own pace
  • 3. libinjection first presented at Black Hat USA 2012 http://client9.com/20120725 iSEC Partners party at Bellagio
  • 4. SQLi Obfuscation first presented at DEFCON 20 http://client9.com/20120727/
  • 5. All photos where taken by me last week on Martha's Vineyard, MA or from previous conferences. Unless it's a picture of a clown Or otherwise noted. Then it came from The Internet. Thanks Internet!
  • 6. The Next 30 Minutes • Why detecting SQLi is Important • SQL you didn't know about • Why detecting SQLi is a hard problem • Why current solutions aren't so good • The libinjection algorithm and library
  • 7. Why Detect SQLi • Even if you know 100% of your queries are parameterized... • Knowing who and how often SQLi attacks is still good to know • Graph the attacks! Make security visible! Great internal PR.
  • 8. So Let's Detect SQLi !!!! It's Easy to Get Started with Regular Expressions s/UNIONs+(ALL)?/i ‣ At least two open source WAF use regular expressions. ‣ Failure cases in closed-source WAFs also indicate regexp.
  • 9. 1992 SQL Spec 625 pages plain text
  • 10. 2003 SQL Spec 128 pages pure BNF
  • 11. NULL
  • 12. MySQL NULL Alias MySQL NULL can written as N case sensitive. n is not a null. This means any WAF that does a "to_lower" on the user input and looks for "null" will miss this case.
  • 14. Integer Forms • [0-9]+ • 0x[0-9a-fA-F]+ 0xDEADbeef MySQL, MSSQL 0x is case sensitive • 0x MSSQL only • x'DEADbeef' PgSQL • b'10101010' MySQL, PgSQL • 0b010101 MySQL
  • 15. Floating Point • digits • digits[.] • digits[.]digits http://bit.ly/Qp6KTu • digits[eE]digits • digits[.]digits[eE]digits • digits[eE][+-]digits • [.]digits • digits[.][eE]digits • [.]digits[eE]digits • digits[.]digits[eE][+-]digits • [.]digits[eE][+-]digits Optional leading unary operator [+-]
  • 16. Floating Point, Oracle • Everyone of the previous formats can have a trailing [dDfF] • But why use numbers as all? Special literals, maybe case sensitive: • binary_double_infinity • binary_double_nan • binary_float_infinity • binary_float_nan
  • 17. MSSQL Money Literals • -$45.12 • $123.0 • +$1,000,000.00 Commas ignored • Other "monetary symbols" ignored • Autocasts to everything
  • 18. Parser Differences • 1. AND 2 vs. • 1.AND 2 vs. • 1.AND2 (no space between "1." "AND" and "2") • some parsers accept (MySQL), some don't (sqlite3)
  • 20. MySQL # Comment • '#' signals an till-end-of-line Comment • Well used in SQLi attacks • However... '#' is an operator in PgSQL. Beware that s/#.*n// will delete code that needs inspecting. • Lots of other MySQL comment oddities: http://dev.mysql.com/doc/refman/5.6/ en/comments.html
  • 21. PGSQL Comments • Besides the usual '--' comment • PgSQL has nested C-Style Comments •/* foo /* bar */ */ • Careful! What happens when you 'remove comments' in /* /* */ UNION ALL /* */ */
  • 23. C-Style String Merging • C-Style consecutive strings are merged into one. • SELECT 'foo' 'bar'; • SELECT 'foo' "bar"; (mysql) • SQL Spec and PgSQL requires a newline between literals: SELECT 'foo' 'bar';
  • 24. Standard Unicode • N'....' or n'...' • MSSQL Case-sensitive 'N' • Not sure on escaping rules.
  • 25. MySQL Ad-Hoc Charset • _charset'....' • _latin1'.....' • _utf8'....'
  • 26. PGSQL Dollar Quoting From http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS A dollar-quoted string constant consists of a dollar sign ($), an optional "tag" of zero or more characters, another dollar sign, an arbitrary sequence of characters that makes up the string content, a dollar sign, the same tag that began this dollar quote, and a dollar sign. For example, here are two different ways to specify the string "Dianne's horse" using dollar quoting: $$Dianne's horse$$ $SomeTag$Dianne's horse$SomeTag$ Want more fun? They can be nested!
  • 27. PGSQL Unicode From http://www.postgresql.org/docs/9.1/static/sql-syntax- lexical.html emphasis mine: ... This variant starts with U& (upper or lower case U followed by ampersand) immediately before the opening double quote, without any spaces in between, for example U&"foo". (Note that this creates an ambiguity with the operator &. Use spaces around the operator to avoid this problem.) Inside the quotes, Unicode characters can be specified in escaped form by writing a backslash followed by the four-digit hexadecimal code point number or alternatively a backslash followed by a plus sign followed by a six-digit hexadecimal code point number. For example, the identifier "data" could be written as U&"d0061t+000061" The following less trivial example writes the Russian word "slon" (elephant) in Cyrillic letters: U&"0441043B043E043D" If a different escape character than backslash is desired, it can be specified using the UESCAPE clause after the string, for example: U&"d!0061t!+000061" UESCAPE '!'
  • 28. Oracle Q String http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/ fundamentals.htm#autoId6 q'!...!' notation allows use of single quotes inside literal string_var := q'!I'm a string!'; You can use delimiters [, {, <, and (, pair them with ], }, >, and ), pass a string literal representing a SQL statement to a subprogram, without doubling the quotation marks around 'INVALID' as follows: func_call(q'[SELECT index_name FROM user_indexes WHERE status ='INVALID']');
  • 30. Ridiculous Operators • != not equals, standard • ||/ cube root (pgsql) • <=> (mysql) • ** exponents (oracle • <> (mssql) • ^= (oracle) • !>, !< not less than (mssql) • / oracle • !! factorial (pgsql) • |/ sqaure root (pgsql)
  • 31. Expressions! • Using the common query extension of "OR 1=1" • Besides using literals, one can use functions: •COS(0) = SIN(PI()/2) •COS(@VERSION) = - SIN(@VERSION + PI()/2)
  • 32. EXCEPT (mssql) MINUS (Oracle) • Like UNION, UNION ALL • But returns all results from first query minus/except the ones from the second query • There is also INTERSECT and MINUS as well. • I think someone clever could use these, typically not in WAF rules.
  • 33. Side Note: "IN" lists • e.g. ....WHERE id IN (1,2,3,4) .... • These have to be manually created. • There is no API or parameter binding for this construct in any platform,framework or language. • There is no consistent, safe way to make this (other than convention,
  • 34. What happens when regular expressions are used to capture these rules?
  • 35. (?:)s*whens*d+s*then)|(?:"s*(?:#|--|{))|(?:/*!s?d+)|(?:ch(?:a)?rs*(s*d)|(?:(?:(n?and|x?or| not)s+||||&&)s*w+() (?:[s()]cases*()|(?:)s*likes*()|(?:havings*[^s]+s*[^ws])|(?:ifs?([dw]s*[=<>~]) (?:"s**.+(?:or|id)W*"d)|(?:^")|(?:^[ws"-]+(?<=ands)(?<=ors)(?<=xors)(?<=nands)(?<=nots)(?<=| |)(?<=&&)w+()|(?:"[sd]*[^ws]+W*dW*.*["d])|(?:"s*[^ws?]+s*[^ws]+s*")|(?:"s*[^ws]+ s*[Wd].*(?:#|--))|(?:".**s*d)|(?:"s*ors[^d]+[w-]+.*d)|(?:[()*<>%+-][w-]+[^ws]+"[^,]) (?:d"s+"s+d)|(?:^admins*"|(/*)+"+s?(?:--|#|/*|{)?)|(?:"s*or[ws-]+s*[+<>=(),-]s*[d"])| (?:"s*[^ws]?=s*")|(?:"W*[+=]+W*")|(?:"s*[!=|][ds!=+-]+.*["(].*$)|(?:"s*[!=|][ds!=]+.*d+$)| (?:"s*likeW+[w"(])|(?:siss*0W)|(?:wheres[sw.,-]+s=)|(?:"[<>~]+") (?:unions*(?:all|distinct|[(!@]*)?s*[([]*s*select)|(?:w+s+likes+")|(?:likes*"%)|(?:"s*like W*["d])|(?:"s*(?:n?and|x?or|not ||||&&)s+[sw]+=s*w+s*having)|(?:"s**s*w+W+")|(?:"s*[^? ws=.,;)(]+s*[(@"]*s*w+W+w)|(?:selects*[[]()sw.,"-]+from)|(?:find_in_sets*() (?:ins*(+s*select)|(?:(?:n?and|x?or|not ||||&&)s+[sw+]+(?:regexps*(|soundss+likes*"|[=d] +x))|("s*ds*(?:--|#))|(?:"[%&<>^=]+ds*(=|or))|(?:"W+[w+-]+s*=s*dW+")|(?:"s*iss*d.+"?w)| (?:"|?[w-]{3,}[^ws.,]+")|(?:"s*iss*[d.]+s*W.*") (?:[dW]s+ass*["w]+s*from)|(?:^[Wd]+s*(?:union|select|create|rename|truncate|load|alter|delete| update|insert|desc))|(?:(?:select|create|rename|truncate|load|alter|delete|update|insert|desc)s+(?: (?:group_)concat|char|load_file)s?(?)|(?:ends*);)|("s+regexpW)|(?:[s(]load_files*() (?:@.+=s*(s*select)|(?:d+s*ors*d+s*[-+])|(?:/w+;?s+(?:having|and|or|select)W)|(?:ds+group s+by.+()|(?:(?:;|#|--)s*(?:drop|alter))|(?:(?:;|#|--)s*(?:update|insert)s*w{2,})|(?:[^w]SETs*@w +)|(?:(?:n?and|x?or|not ||||&&)[s(]+w+[s)]*[!=+]+[sd]*["=()]) (?:"s+ands*=W)|(?:(s*selects*w+s*()|(?:*/from)|(?:+s*d+s*+s*@)|(?:w"s*(?:[-+=|@]+s*)+ [d(])|(?:coalesces*(|@@w+s*[^ws])|(?:W!+"w)|(?:";s*(?:if|while|begin))|(?:"[sd]+=s*d)| (?:orders+bys+ifw*s*()|(?:[s(]+cased*W.+[tw]hen[s(]) (?:(select|;)s+(?:benchmark|if|sleep)s*?(s*(?s*w+) (?:creates+functions+w+s+returns)|(?:;s*(?:select|create|rename|truncate|load|alter|delete|update| insert|desc)s*[[(]?w{2,}) (?:alters*w+.*characters+sets+w+)|(";s*waitfors+times+")|(?:";.*:s*goto) (?:procedures+analyses*()|(?:;s*(declare|open)s+[w-]+)|(?:creates+(procedure|function)s*w+s* (s*)s*-)|(?:declare[^w]+[@#]s*w+)|(execs*(s*@) (?:selects*pg_sleep)|(?:waitfors*delays?"+s?d)|(?:;s*shutdowns*(?:;|--|#|/*|{)) (?:sexecs+xp_cmdshell)|(?:"s*!s*["w])|(?:fromW+information_schemaW)|(?:(?:(?:current_)?user| database|schema|connection_id)s*([^)]*)|(?:";?s*(?:select|union|having)s*[^s])|(?:wiifs*()| (?:execs+master.)|(?:union select @)|(?:union[w(s]*select)|(?:select.*w?user()|(?:into[s+]+ (?:dump|out)files*") (?:merge.*usings*()|(executes*immediates*")|(?:W+d*s*havings*[^s-])|(?:matchs*[w(),+-]+ s*againsts*() (?:,.*[)da-f"]"(?:".*"|Z|[^"]+))|(?:Wselect.+W*from)|((?:select|create|rename|truncate|load|alter| delete|update|insert|desc)s*(s*spaces*() (?:[$(?:ne|eq|lte?|gte?|n?in|mod|all|size|exists|type|slice|or)]) (?:(sleep((s*)(d*)(s*))|benchmark((.*),(.*))))
  • 36. Unicorn Alert! ‣ At Black Hat USA 2005, Hanson and Patterson presented: Guns and Butter: Towards Formal Axioms of Validation (http://bit.ly/OBe7mJ) ‣ …formally proved that for any regex validator, we could construct either a safe query which would be flagged as dangerous, or a dangerous query which would be flagged as correct. ‣ (summary from libdejector documentation)
  • 37. Can we do better?
  • 39. Key Insight ‣ A SQLi attack must be parsed as SQL within the original query. ‣ SQL has a rigid syntax ‣ it works, or it's a syntax error. ‣ Compare this to HTML/XSS rules ‣ "Is it a SQLi attack?" becomes "Could it be a SQL snippet?"
  • 40. Only 3 Contexts User input is only "injected" into SQL in three ways: ‣ As-Is ‣ Inside a single quoted string ‣ Inside a double quoted string Means we have to parse input three times. Compare to XSS
  • 41. Identification of SQL snippets without context is hard ‣ 1-917-660-3400 my phone number or ... an arithmetic expression in SQL? ‣ @ngalbreath my twitter account or ... a SQL variable? ‣ English-like syntax and common keywords: union, group, natural, left, right, join, top, table, create, in, is, not, before, begin, between
  • 42. Existing SQL Parsers ‣ Only parse their flavor of SQL ‣ Not well designed to handle snippets ‣ Hard to extend ‣ Worried about correctness ... so I wrote my own! ... so I wrote my own!
  • 43. Tokenization ‣ Converts input into a stream of tokens ‣ Uses "master list" of keywords and functions across all databases. ‣ Handles comments, string, literals, weirdos.
  • 44. 5000224' UNION USER_ID>0-- [ ('...500224', string), ('UNION', union operator), ('USER_ID', name), ('>', operator), ('0', number), ('--.....', comment) ]
  • 45. Meet the Tokens ‣ none/name ‣ group-like operation ‣ variable ‣ union-like operator ‣ string ‣ logical operator ‣ regular operator ‣ function ‣ unknown ‣ comma ‣ number ‣ semi-colon ‣ comment ‣ left parens ‣ keyword ‣ right parens
  • 46. Merging, Specialization, Disambiguation ‣ "IS", "NOT" ==> "IS NOT" (single op) ‣ "NATURAL", "JOIN" => "NATURAL JOIN" ‣ ("+", operator) -> ("+", unary operator) ‣ (COS, function), (1, number) ==> (COS, name), (1, number) functions must be followed with a parenthesis!
  • 47. Folding ‣ This step actually isn't needed to detect, but Text is needed to reduce false positives. ‣ Converts simple arithmetic expressions into a single value, and does not try to evaluate. ‣ 1-917-660-3400 -> "1" pics courtesy The Internet pics
  • 48. Knows nothing about SQLi ‣ So far this is purely a parsing problem. ‣ Knows nothing about SQLi (which is evolving) ‣ Can be 100% tested against any SQL input (not SQLi) for correctness. ‣ Language independent test cases $ cat test-tokens-numbers-floats-003.txt --TEST-- floating-point parsing test --INPUT-- SELECT .0; --EXPECTED-- k SELECT 1 .0 ; ;
  • 49. Fingerprints ‣ The token types of a user input form a hash or a fingerprint. ‣ -6270" UNION ALL SELECT 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594, 5594# AND "JWWQ"="JWWQ ‣ becomes "sUk1,1,1,1,1,1,1,1,&" ‣ Now let's generate fingerprints from Real World Data. ‣ Can we distinguish between SQLi and benign input? pics courtesy The Internet
  • 50. Training on SQLi ‣ Parse known SQLi attacks from ‣ SQLi vulnerability scanners ‣ Published reports ‣ SQLi How-Tos and Cheet Sheets ‣ > 32,000 total ‣ Since Black Hat, donations from ‣ modsecurity ‣ Qualys ‣ > 50,000 total
  • 51. Training on Real Input ‣ 100s of Millions of user inputs from Etsy's access logs were also parsed. ‣ Large enough to get a good sample (Top 50 USA site) ‣ Old enough to have lots of odd ways of query string formatting. ‣ Full text search with an diverse subject domain
  • 52. How many tokens are needed to determine if user input is SQLi or not?
  • 53. no matter how long the input
  • 54. 632 out of 1,048,576 are SQLi &1o1U &f()o &f(1) 1&((f 1&((k 1&(1) 1&(1, 1&(1o 1&(f( 1&(k( 1&(k1 1&(kf 1&(kk 1&(kn 1&(ko 1&(v) 1&1Bf 1&1Uk 1&1f( 1&1o( 1&1o1 1&1of 1&1ok 1&1on 1&1oo 1&1ov 1&f(( 1&f() 1&f(1 1&f(f 1&f(k 1&f(n 1&f(v 1&k(1 1&k(f 1&k1k 1&kUk 1&kk1 1&n() 1&no1 1&nos 1&o(1 1&o1o 1&sU( 1&so1 1&sos 1)&(1 1)&(f 1)&(k 1)&(n 1)&1B 1)&1U 1)&1f 1)&1o 1)&f( 1)&o( 1)()s 1))&( 1))&1 1))&f 1))&o 1)))& 1)))) 1))); 1)))B 1)))U 1)))k 1)))o 1));k 1))B1 1))Uk 1))Un 1))k1 1))kk 1))o( 1))o1 1))of 1))ok 1))on 1),(1 1);k& 1);k( 1);kf 1);kk 1);kn 1);ko 1)B1 1)B1& 1)B1c 1)B1o 1)U(k 1)Uk1 1)Ukf 1)Ukk 1)Ukn 1)Unk 1)k1 1)k1c 1)k1o 1)kks 1)o(1 1)o(k 1)o(n 1)o1B 1)o1f 1)o1k 1)o1o 1)of( 1)ok( 1)ok1 1)on& 1)ono 1,(f( 1,(k( 1,(k1 1,(kf 1,1), 1,1)o 1,1B1 1,1Uk 1,f(1 1,s), 1;k&k 1;k(( 1;k(1 1;k(o 1;k1, 1;kf( 1;kks 1;kn( 1;kn, 1;knc 1;ko( 1;kok 1B1 1B1,1 1B1,n 1B1Uk 1B1c 1B1k1 1B1ks 1Bf(1 1Bf(f 1Bk(1 1Bn,n 1Bnk1 1U((k 1U(k1 1U(kf 1U(kn 1U1,1 1Uc 1Uk 1Uk(1 1Uk(k 1Uk(n 1Uk1 1Uk1, 1Uk1c 1Uk1f 1Uk1k 1Uk1n 1Uk1o 1Ukf 1Ukf( 1Ukf, 1Ukk( 1Ukk, 1Ukk1 1Ukkk 1Ukkn 1Ukn& 1Ukn( 1Ukn, 1Ukn1 1Uknc 1Uknk 1Ukno 1Ukns 1Uko1 1Ukok 1Uks, 1Uksc 1Ukv 1Ukv, 1Ukvc 1Un,1 1Un1, 1Unk( 1Unk1 1Unkf 1Uon1 1f()k 1k1U( 1k1Uk 1k1c 1kU1, 1kf(1 1kk(1 1kksc 1knkn 1n&f( 1nUk1 1nUkn 1nk1c 1nkf( 1o((( 1o((1 1o((f 1o(1) 1o(1o 1o(f( 1o(k( 1o(k1 1o(kf 1o(kn 1o(kv 1o(n) 1o(s) 1o1)& 1o1)o 1o1Bf 1o1Uk 1o1f( 1o1kf 1o1o( 1o1o1 1o1of 1o1oo 1o1ov 1of() 1of(1 1of(f 1of(n 1of(s 1ok(1 1ok(k 1ok1 1ok1, 1ok1c 1ok1k 1okf( 1oks, 1oksc 1okv, 1onos 1oso1 ;kknc Uk1,1 Uk1,f Uk1,n Ukkkn f((k( f((kf f()&f f()of f(1)& f(1)o f(1,f f(1o1 f(f() f(f(1 f(k() f(k,( f(k,n f(n() f(v,1 k()ok k(1)U k(ok( k(vv) k1,1, k1,1c k1,1k k1,f( k1k(k k1o(s k;non kf(1) kf(1, kf(f( kf(n, kf(o) kf(v: kk(f( kk1f( kk1fn kk1kk kk1nk kk1vk kk1vn kn1kk kn1vk kn1vn ko(k( ko(kf kok(k kv) kvk(1 n&(1) n&(k1 n&(o1 n&1f( n&1o( n&1o1 n&1of n&1oo n&f(1 n&f(f n&k(1 n&o1o n)&(k n)&1f n)&1o n)&f( n))&( n))&1 n))&f n)))& n))); n)))k n)))o n));k n))kk n))o( n))o1 n))of n))ok n);k& n);k( n);kf n);kk n);kn n);ko n)k1o n)kks n)o(k n)o1& n)o1f n)o1o n)of( n)ok( n,(f( n,(k( n,(k1 n,(kf n,f(1 n:o1U n;k&k n;k(( n;k(1 n;kf( n;kks n;kn( n;ko( n;kok nUk(k nUk1, nUkn, nUnk( nk1Uk nkf(1 nkksc nnn)U nno1U no(k1 no(o1 no1&1 no1Uk no1f( no1o( no1o1 no1of no1oo nof(1 nok(1 nok(k o1kf( oUk1, of()o of(1) ok1o1 okkkn ook1, s&(1) s&(1, s&(1o s&(f( s&(k) s&(k1 s&(kf s&(ko s&1Bf s&1Uk s&1c s&1f( s&1o( s&1o1 s&1of s&1on s&1oo s&1os s&1ov s&f(( s&f() s&f(1 s&f(f s&f(v s&k&s s&k(1 s&k(o s&k1o s&kc s&knk s&ko( s&ko1 s&kok s&kos s&n&s s&no1 s&nos s&o(1 s&o(k s&o1o s&okc s&oko s&os s&sos s&v:o s&vos s&vso s)&(1 s)&(k s)&1B s)&1f s)&1o s)&f( s)&o( s))&( s))&1 s))&f s))&n s))&o s)))& s))); s)))B s)))U s)))k s)))o s));k s))B1 s))Uk s))Un s))k1 s))kk s))o( s))o1 s))of s))ok s),(1 s);k& s);k( s);kf s);kk s);kn s);ko s)B1 s)B1& s)B1c s)B1o s)U(k s)Uk1 s)Unk s)k1 s)k1c s)k1o s)kks s)o(1 s)o(k s)o1B s)o1f s)o1k s)o1o s)of( s)ok( s)ok1 s,1), s;k&k s;k(( s;k(1 s;k(o s;k1, s;k1o s;k; s;k[k s;k[n s;kf( s;kkn s;kks s;kn( s;knk s;knn s;ko( s;kok s;kvc s;kvk s;n:k sB1 sB1&s sB1Uk sB1c sB1os sU((k sU(k( sU(kk sU(kn sU(ks sUk(k sUk1 sUk1& sUk1, sUk1c sUk1k sUk1o sUkf( sUkk1 sUkkk sUkn( sUkn, sUkn1 sUknk sUkok sUkv, sUkvc sUn(k sUnk1 sUnkf sUno1 sf(1) sf(n, sf(s) sk)&( sk)&1 sk)&f sk);k sk)B1 sk)Uk sk)Un sk)k1 sk)kk sk)o( sk)o1 sk)of sk)ok sk1&1 sk1Uk sk1c sk1o1 sk1os skU1, skks skksc sn,f( sno1U so((( so((k so((s so(1) so(1o so(f( so(k) so(k1 so(kk so(kn so(ko so(ks so(os so(s) so1&1 so1&o so1&s so1Bf so1Uk so1c so1f( so1kf so1o( so1o1 so1of so1ok so1oo so1os so1ov sof() sof(1 sof(f sof(k sok&s sok(1 sok(k sok(o sok(s sok1 sok1, sok1c sok1o sokc sokf( sokn, soknk soko( soko1 sokok sokos sonk1 sono1 sonos sos sos&( soso( sosos sov&1 sov&s sov:o sovo1 sovok sovos sovov sovso v:o1) vUk1, vok1, as of 2012-09-20
  • 55. The Library On GitHub Now ~500 Lines of Code One file + data No memory allocation No threads No external dependencies Fixed stack size >100k checks a second
  • 56. tada #include "sqlparse.h" #include <string.h> int main() { const char* ucg = "1 OR 1=1"; // input should be normalized, upper-cased // You can use sqli_normalize // if you don't have your own function sfilter sf; return is_sqli(&sf, ucg, strlen(ucg)); } $ gcc -Wall -Wextra sample.c sqlparse.c $ ./a.out $ echo $? 1
  • 58. What's Next? • Change API to allow passing in fingerprint data or a function. Allows upgrades without code changes. • Can we reduce the number of tokens? String, variables, numbers are all just values. • Folding of comma-separated values? 1,2,3,4 => 1 • Can we just eliminate all parenthesis?
  • 59. Help! • More SQLi from the field please! • False positives welcome • More test cases with exotic SQL to test parser. • Ports to other languages (the language- neutral test framework should make this easier). • Compiling on Windows (mostly tested on Mac OS X and Linux)
  • 60. Do you have a commercial WAF? • Set up a dead page and let me poke it. • Curious on false positives and false negatives.
  • 61. Slides and Source Code: http://www.client9.com/libinjection/ Nick Galbreath @ngalbreath nickg@client9.com Oct 25, OWASP USA, Austin, Texas Continuous Deployment and Security

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n