450 likes | 614 Views
Whitelist is the New Black. Damian Profancik @ integrisec. $ whoami. Damian Profancik Application Security Consultant Trustwave SpiderLabs dprofancik@trustwave.com @ integrisec. Agenda. Input Validation Approaches Blacklists vs. Whitelists Approach bypasses Best practice.
E N D
Whitelist is the New Black Damian Profancik @integrisec
$whoami Damian Profancik • Application Security Consultant • Trustwave SpiderLabs • dprofancik@trustwave.com • @integrisec
Agenda • Input Validation • Approaches • Blacklists vs. Whitelists • Approach bypasses • Best practice
Input Validation var _0x32b4=["\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21","\x0A","\x4F\x4B"];var a=_0x32b4[0];function MsgBox(_0x41d7x3){alert(_0x41d7x3+_0x32b4[1]+a);} ;MsgBox(_0x32b4[2]);
Input Validation var a="Hello World!"; function MsgBox(msg) { alert(msg+"\n"+a); } MsgBox("OK");
Why? • This is THE hardest part of security, and subsequently the most important. • Most vulnerabilities are a result of user-controlled data not being validated, or not being validated appropriately.
What? • The process of verifying the correctness of data supplied to an application before using that data • Input should be validated for: • Data Type • Size/length/bounds • Character set • Format
When? • All the input your application accepts MUSTbe validated • HTTP parameters • HTTP headers (HOST, USER-AGENT, COOKIE, etc.) • API results • Database results • Cross-application results
Goals • In order to validate input properly, you must be able to answer two questions: • Where is it going? • What are you protecting it from? • Encoding is the recommended utility for display level protections.
Client-Side Validation • Restriction and validation is only performed client-side • HTML form fields • JavaScript • Flash files (SWF) • Anything on the client-side can be manipulated or disabled • Should only be used for performance reasons
Encoding Input • Encoding the input prior to its use or storing in database <script> => <script&rt; • Encoding is context sensitive • HTML, HTML attributes, JavaScript, CSS, etc. • Encoding should be used for output
Escaping Input • Escaping certain characters to remove their special meaning in the usage’s context • JavaScript • JSON • SQL
Escaping Input • If a single quote is escaped by doubling up • ' or 1=1-- => '' or 1=1-- • The attacker can add a \ before quote • \' or 1=1-- => \'' or 1=1-- • In MySQL the \ is the escape character • This will result in the added quote being escaped and the SQL injection working as planned.
Escaping Input • If a quotes are escaped by a • ";alert(/XSS/);// => \";alert(/XSS/);// • The attacker can add a \ before quote • \";alert(/XSS/);// => \\";alert(/XSS/);// • In JavaScript the \ is the escape character • This will result in the escape charaterbeing escaped and the XSS working as planned.
Type Casting • Casting an input to a particular variable type • Integer • String • Boolean • What if the input is supposed to be a string? …or if the type is correct but invalid?
Rely on External Protections • Some language frameworks do the “heavy lifting” for you, such as ASP.Net • Most browsers provide XSS protections • Protections may be disabled • Protections may not be complete • HTTP headers • Persistent XSS • In ASP.Net, not everything gets automatically encoded, such as the Label and Literal controls • There are often ways of bypassing protections
Rely on External Protections • ASP.Net Request Validation <%tag style="x:expression(alert('XSS'))"> (IE <= 7) • Browser XSS Filters <script type ='text/javascript'>alert('XSS')</script> (FF <= 12) <script>/*///*/alert('XSS')</script> (FF <= 12, Chrome <= 19) cookie%3dvalue;%0d%0aX-XSS-Protection:0%0d%0a%0d%0a<html><body><script>alert('XSS')</script></body></html> (IE <= 8, FF <=12)
Blacklist • Blocking known bad characters and keywords • Must enumerate all the possible bad input • Typically can be defeated
Blacklist • Blocking <script> tags <input onfocus="alert('XSS')" autofocus> <imgsrc="1" onerror="alert('XSS')"> • Stripping keywords <scr<script>ipt>alert('XSS')</scr<script>ipt> ' UNunionIONSELselectECT… • Case Sensitivity <ScRiPt>alert('XSS')</sCrIpT> ' UnIoNsElEcT…
Blacklist • Removing whitespace <img/src="1"/onerror="alert('XSS')"> <img%0Asrc="1"%0Aonerror="alert('XSS')"> (0)union(select(0),database(),(0))# 0/**/union/**/select/**/0,database(),0# • Filtering angle brackets (<>) " autofocus onfocus="alert('XSS') ";alert('XSS');//
Blacklist • Filtering JavaScript event handlers <imgsrc="1" onerror ="alert('XSS')"> <style onreadystatechange="alert('XSS')"> <div style="x:expression(alert('XSS'))"> • Filtering or escaping single quote (') 1 and 1=0 union select null,group_concat(column_name),null from information_schema.columns where table_name=0x7573657273#
Blacklist • Filtering or escaping single quote (') 1 and 1=0 union select null,group_concat(column_name),null from information_schema.columns where table_name=concat(char(117),char(115),char(101),char(114),char(115))# 1;declare @s varchar(4000);set @s=cast(0x77616974666f722064656c6179202730303a30303a3330273b as varchar(4000));exec @s;-- • Filtering SQL comments (--, #) ' or 1=(case when (select user())='sa' then 1 else 2 end) or 'a'='b
Blacklist • Keyword blocking <script>alert('XSS'); <imgsrc="1" onerror="alert('XSS')" <script >alert('XSS')</script > <imgsrc="1" onerror="confirm('XSS')"> <div style="x:expre/**/ssion(alert('XSS'))"> <svgonload="alert('XSS')"> <math href="javascript:alert('XSS')" style="position:absolute;top:0;left:0;width:5000px;height:5000px;">CLICKME</math> " autofocus onfocus="alert('XSS')
Blacklist • Keyword blocking <object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk7PC9zY3JpcHQ+"> <meta charset="x-imap4-modified-utf7">&ADz&AGn&AG0&AEf&ACA&AHM&AHI&AGO&AD0&AGn&ACA&AG8Abg&AGUAcgByAG8AcgA9AGEAbABlAHIAdAAoADEAKQ&ACAAPABi ' union ALL select… ' or 777=777-- ' or 'a' like 'a'-- ?FNAME=<svg&LNAME=onload%3D"alert('XSS')">
Whitelist • Only allowing input that matches expected value • Second strongest method (“known good”) • Typically uses Regular Expressions to match known good patterns • Works well when you have a lot of possible inputs in a certain format • Phone numbers • Must know all possible inputs • Make sure to anchor beginning and end of lines
Whitelist • Regular expressionsmay be used to verify input is in a correct format containing only the characters expected • A regular expression is a string used to describe a set of strings according to regular expression syntax • Simple language to compare strings • Matches ASCII text, not binary • Built into most languages
Whitelist • Basic Regex Operators • Can be plain text - “word” • Literal Characters are important • ^ - Matches characters at the beginning of the line or string • $ - Matches characters at the end of the line or string • . – matches exactly one character of any type (except cr+lf) • [ ] – matches a single character within the brackets • [a] – matches “a” • [abc] – matches “a” or “b” or “c” • [a-c] – matches “a” or “b” or “c” • The hyphen is treated as literal if it is the first or last character, or if it is escaped with a \
Whitelist • Basic RegEx operators continued • [^ ] – matches any character not in the brackets • [^a-c] – will match any character that is not “a” or “b” or “c” • \xXX - \x0D \x0A - matches based on hex values • \b – word boundary \bword\b will match only “word” not “awordb” • ? – matches a character zero or one time • * - matches a character zero or more times • + - matches a character one or more times
Whitelist • RegEx Examples • .at – matches “cat” “hat” “bat”, etc. • [hc]at – matches “hat” or “cat” • [^b]at – matches “hat” “cat” NOT “bat” • [a-zA-Z0-9] – matches alphanumeric words • ((\(\d{3}\) ?)|(\d{3}[- \.]))?\d{3}[- \.]\d{4}(\s(x\d+)?){0,1}$ – matches phone numbers • ^[a-zA-Z0-9%_\.]+@[a-zA-Z0-9\.-]+.[a-zA-Z]{2,6} – matches email addresses
Whitelist • Blacklist Example function isAlphaNumberic(ANStr) Dim re, results set re = New RegExp re.Pattern = "^[^/\.,\\!\^\-\|\~\$\*\+\?@#%&; `\(\);:\[\]\{\}=""']+$" 'accepts all numbers and letters only re.Global = True re.IgnoreCase = True results = re.Test(ANStr) If results Then 'valid isAlphaNumberic = TRUE Else 'invalid isAlphaNumberic = FALSE End If
Whitelist • Example Code of Black Listing: re.Pattern = "^[^/\.,\\!\^\-\|\~\$\*\+\?@#%&; `\(\);:\[\]\{\}=""']+$" • Example of the same code in white listing form: re.Pattern = "^[a-zA-Z0-9]+$" • Less Complicated, more reliable
ASP.NetExample <%@ language="C#" %> <form id="form1" runat="server"> <asp:TextBox ID="txtName" runat="server"/> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> <asp:RegularExpressionValidator ID="regexpName" runat="server" ErrorMessage="Error: invalid name" ControlToValidate="txtName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$" /> </form>
Java Example import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegExValidator { public static void main(String args[]) { String txtName= request.getParameter("txtName"); String pattern = "^[a-zA-Z'.\s]{1,40}$"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(txtName); if (!m.find( )) { System.out.println("Error: invalid name"); } } }
PHP Example <?php $txtName= $_GET["txtName"]; if(!preg_match("/^[a-zA-Z'.\s]{1,40}$/", $txtName)) { echo "Error: invalid name"; } ?>
OWASP Projects • AntiSamy https://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project • Enterprise Security API (ESAPI) https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API
Exact Match • All inputs are compared to a list of known good values • States • Zip codes • Highest level of validation available • Time consuming, difficult to maintain • Exact match is the most secure method of validation
Magic Sandwich • Validate ALL input • Check type • Cast type • Check size, length, bounds • Whitelist with regular expressions and exact Escape as necessary • Use the input in the code • Validate ALL output • Check output again as before • Encode/escape output
Bad Input Handling • Input validation must do something with the data • Reject the data out of hand • Escape the dangerous characters • Input that fails validation should always be rejected • Minimize the risk from unexpected malicious characters • Error message should inform the user of the proper format
Resources • Customizable Vulnerability Testbeds: • SQLol, XSSmh, ShelLOL, XMLmao, CryptOMG https://github.com/SpiderLabs • Download the Global Security Report: http://www.trustwave.com/GSR • Read our Blog: http://blog.spiderlabs.com • Follow us on Twitter: @SpiderLabs
$whoami Damian Profancik • Application Security Consultant • Trustwave SpiderLabs • dprofancik@trustwave.com • @integrisec