Fixing Application Security Issues the Right...
Transcript of Fixing Application Security Issues the Right...
Fixing Application Security Issues the Right Way
Ravi Prakash Venkata Burlagadda | 10/28/2010
Agenda
Top Web Application Security Attacks
Vulnerability Categories – Top 5
Common blunders while fixing
Right way to fix at first attempt
Security Tools
Secu
rity
Talk
3
Microsoft Confidential | Do not distribute externally
Top Web Application Security Attacks
What are they?
• XSS, CSRF, SQL Injection, file Canonicalization, file upload, DoS attack, Elevation of Privileges, Clear Text Secrets, Weak Cryptography etc
Why they exist?
Problem patterns – vulnerability categories
Secu
rity
Talk
4
Microsoft Confidential | Do not distribute externally
Vulnerability Categories
Input Validation
Output Encoding
Dynamic SQL
Cryptography
Configuration
Authentication/Authorization
Session handling
Secu
rity
Talk
5
Microsoft Confidential | Do not distribute externally
Input Validation – Common blunders
What it is? - cause for many attacks
Use blacklist (exclusions) approachisValid = ServerValidation.ValidateInput(txtSearch.Text.Trim(), @"^([^<>]*)$"); // not allowed to enter '<' and '>' characters
Regex rxNil = new Regex("(?:javascript|jscript|vbscript|>|<|\")",RegexOptions.IgnoreCase|RegexOptions.Compiled);
Treat as trusted input data – but actually not
From custom data sources, web services
Rely or assume that it is taken care at different layer
Use one generic validator for all kinds of inputFunction ValidateInput(ByVal bDoQueryString, ByVal bDoForms) As If bDoQueryString And Current.Request.QueryString.Count > 0 Then
For i = 0 To Current.Request.QueryString.Count - 1
RegEV = New System.Text.RegularExpressions.Regex("[a-zA-Z0-9'.%][xp_sp_<>*]*") 'Add text to be allowed in QueryString to the first [] & to restrict any characters, enter them to second bracket([])
....
Secu
rity
Talk
6
Microsoft Confidential | Do not distribute externally
Input Validation – Common blunders …
Not aware that it is user controllable
• Eg: Hidden variables, labels, cookies etc.
Use invalid regular expressions
We do output encoding. Do you still need it?
Do sanitization only
Regex badCharReplace = new Regex(@"([<>""'%;()&])"); //TODO:
string goodChars = badCharReplace.Replace(input, "");
return goodChars;
Ignore totally
• For eg: feedback, comments, description, search strings etc.
Secu
rity
Talk
7
Microsoft Confidential | Do not distribute externally
Input Validation – Right way to fixNever rely on client side validation – server side validation is mustTreat all user controlled input as maliciousConstrain the data - validate data for type, length, format and rangeSanitize when allowable input cannot guarantee it as SafeChoose whitelist approach – inclusions list
// Validate the supplied nameif ( !RegEx.Match(Request.Form["name"],@"[A-Za-z'\- ]",
RegexOptions.None).Success)
Leverage platform featuresValidateRequest, ValidationControls, RegularExpressionValidator, String.Length, Regex for pattern matching, RangeValidator (typed data comparsions) etc
Use proven Regular expressions instead of customNumberic data eg: SSN regExPattern = \d{3}-\d{2}-\d{4}Email regExPattern = \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
Little overhead changes overall security of the applicationperformance impactExtra effort to construct RegEx to validate good data
Demo
Input Validation
Secu
rity
Talk
9
Microsoft Confidential | Do not distribute externally
Demoprivate static string RegEx1 = @"(<\s*(script|object|img|applet|embed|form|input|\/script|\/object|\/applet|\/embed|\/form|\/input))|onabort|onafterprint|onafterupdate|onbeforecopy|onbeforecut|onbeforeeditfocus|onbeforefocusenter|onbeforefocusleave|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror|onerrorupdate|onfilterchange|onfinish|onfocus|onfocusenter|onfocusleave|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmouseout|onmouseover|onmouseup|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizeend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectiontypechange|onselectstart|onstart|onstop|onsubmit|onunload|(<.*>)|eval\s*\(|(event\s*=)|\<\%";
private static string RegEx2 = @"(<\s*(script|object|img|applet|embed|form|input|\/script|\/object|\/applet|\/embed|\/form|\/input))|(<.*>)|eval\s*\(|(event\s*=)|\<\%";
public static void ValidateInput(string Value){
try{
Regex xssRegex1 = new Regex(RegEx1);Regex xssRegex2 = new Regex(RegEx2);
if (!String.IsNullOrEmpty(Value))if (xssRegex1.IsMatch(Value.ToLower()))
if (xssRegex2.IsMatch(Value.ToLower()))throw new Exception("InputValidation Error:");
}catch (Exception){
throw;}
}protected void Page_Load(object sender, EventArgs e){
try{
ValidateInput(InputTextBox.Text);Response.Write(InputTextBox.Text);//ValidateInput(InputData);//Response.Write(InputData);
}catch (Exception ex){
Response.Write(ex.Message);}
Secu
rity
Talk
10
Microsoft Confidential | Do not distribute externally
Output Encoding – Common blunders
What it is? How it helps?
Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML
Use exclusions list - HttpUtility.HtmlEncode & other methods
Encodes only 4 chars -- <, >, &, ‘
sb.Append(HttpContext.Current.Server.HtmlEncode(this.returnToTenantXmlPost));
DataFilePath = HttpUtility.HtmlEncode(DataFilePath);
Lack of awareness – controls do not perform encoding when displaying data
Eg: DataGrid, DataList, RadioButtonList and CheckBoxList
Treat as trusted data – but actually not
From custom data sources, web services
Not aware of damage
Use of innerHTML property
this.contentratingobject.options.questionnode.innerHTML = message;//message contains user controllable data
Secu
rity
Talk
11
Microsoft Confidential | Do not distribute externally
Output Encoding – Right way to fixSet the correct character encoding
<meta http-equiv="Content Type" content="text/html; charset=ISO-8859-1" />
Enable ASP.Net ValidateRequest option
<pages validateRequest=“true"/>
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="true"Make sure to install URLScan (ISAPI filter) at IISUse HttpOnly Cookie option
<httpCookies httpOnlyCookies="true" …> //In web.configHttpCookie myCookie = new HttpCookie("myCookie"); //C# code
myCookie.HttpOnly = true; Response.AppendCookie(myCookie); Use <frame> Security attribute
<frame security="restricted“ src="http://www.xxx.com/page.htm"> </frame> //Restricted sites zone doesn't support script execution
Change to innerText property from InnerHTMLnode.InnerText = fileName.ToString();keyNode.InnerText = xPath.Key.Trim();
Use inclusion list approach – AntiXSS library -- demolblShippingAddress.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(cust.ShippingAddress);
Use appropriate encoding methods
Demo
Output Encoding
Secu
rity
Talk
13
Microsoft Confidential | Do not distribute externally
Dynamic SQL – Common blundersWhat it is?
Main culprit for SQL injection attacksAttacker can send SQL input that alters the intended query or executes completely new query
Construct SQL statements dynamically
var Shipcity; ShipCity = Request.form("ShipCity");var sql = "select * from OrdersTable where ShipCity = '" + ShipCity + "'";
Rely on replace single quot - blacklist approach
private string SafeSqlLiteral(string inputSQL) { return inputSQL.Replace("'", "''"); }
Rely on replace exec with sp_executesql
Sp_excecutesql (@sql)Moving dynamic SQL into a stored procedure
ALTER Procedure [dbo].[CMRC_ProductsByCategory]( @CategoryID VARCHAR(4000) )ASDECLARE @query NVARCHAR(4000);SELECT @query = 'SELECT ProductID, ModelName, UnitCost, ProductImage FROM CMRC_Products WHERE CategoryID = ' + @CategoryID + ' ORDER BY ModelName, ModelNumber';EXEC (@query);SqlCommand myCommand = new SqlCommand("EXEC CMRC_ProductsByCategory” + categoryID, myConnection);
Access DB with high privileges
Sysadmin roleExtensive use of high privileged stored procs – for eg: xp_cmdshell
Secu
rity
Talk
14
Microsoft Confidential | Do not distribute externally
Dynamic SQL – Right way to fixValidate All input – Type, Length, Format & range
SqlParameter parm = myCommand.SelectCommand.Parameters.Add("@LoginID", SqlDbType.VarChar, 11); parm.Value = Login.Text;
Try to abandon dynamic SQL at all layersUse parameterized SQL queries
Avoid string concatenation // Add Parameters to SPROC SqlParameter parameterCategoryID = new SqlParameter("@CategoryID", SqlDbType.Int, 4); //parameterCategoryID.Value = categoryID;myCommand.Parameters.Add(parameterCategoryID);
Use stored proceduresAvoid using Exec () withinMake use of QUOTENAME() or REPLACE()
Use SQL Execute-Only permissionsONLY Grant execute permissions on stored procs
Access DB with least privilegesUse proxy accounts to elevate privileges temporarily
Secu
rity
Talk
16
Microsoft Confidential | Do not distribute externally
Cryptography – Common blundersWhat it is? How it helps?
Helps to secure credentials, clear text secrets, provide confidentiality etc.Custom encryption methods or use encoding methods
UGFzc3cwcmQhMjM=NTA2MTczNzM3NzMwNzI2NDIxMzIzMw==
Weak cryptography – eg: RC4, 40 bitvoid RSA32API rc4_key(struct RC4_KEYSTRUCT *pKS, unsigned intdwLen, unsigned char *pbKey);/* rc4()
clear text credentials at sourceDatabase credentials, encryption keys<add name="Atlas" providerName="System.Data.SqlClient" connectionString="server=vlab-2;database=dev_atlas;user=sa;password=***" /><add key="EncryptionKey" value="zkvh6RjjvYB/PIx8pZTEyw==" />
Lack of awareness – misuseSymmetric vs asymmetric – AES, 3DES vs RSA
No password or easy to guessDigital certificate with private keys but no password
Secu
rity
Talk
17
Microsoft Confidential | Do not distribute externally
Cryptography – Right way to fixUse proven and publicly recognized algorithms
3DES or AES with min 128 bit key strengthRSA – min 1024 bitsNo need to secure IV
Securing the secretsRSA – RSAProtectedConfigurationProvider
aspnet_regiis -pe "connectionStrings" -app "/MachineRSA"
DPAPI – DPAPIProtectedConfigurationProvideraspnet_regiis -pe "connectionStrings" -app "/MachineDPAPI" -prov"DataProtectionConfigurationProvider"
Aspnet_setreg.exeaspnet_setreg.exe -k:SOFTWARE\MY_SECURE_APP\identity -u:"yourdomainname\username" -p:"password“userName="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,userName"password="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,password
Secu
rity
Talk
18
Microsoft Confidential | Do not distribute externally
Configuration – Common blundersWhat are those?
Debug, Custom Errors, Authentication settings, Authorization settings, Log files and Audit, App specific key/pair values, Default file/buffer sizes, Documentation handlers, Service accounts etc
Use default settings<compilation debug="true"><customErrors mode="RemoteOnly“ and so on
Operations team will take care offTo get it work – go for full ACLsServices – generic/reusable
Re-authentication/authorization missingbuffer sizes
<basicHttpBinding><binding name="WebServiceProxyBinding" closeTimeout="00:03:00"
openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00"allowCookies="false" bypassProxyOnLocal="false"
hostNameComparisonMode="StrongWildcard"maxBufferSize="2147483647" maxBufferPoolSize="524288"
maxReceivedMessageSize="2147483647"messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647“ maxArrayLength="2147483647" maxBytesPerRead="2147483647"
axNameTableCharCount="2147483647" />
Secu
rity
Talk
19
Microsoft Confidential | Do not distribute externally
Configuration – right way to fix
Harden the settings – checklist & WACA tool
Define business specific file/buffer sizeFile size: 2MB
Disable documentation handler<webServices> <protocols>
<remove name="Documentation"/>
</protocols> </webServices>
Disable anonymous access
Define proper ACLs
Explicit authorization check
Define allowed file extensions
Secu
rity
Talk
20
Microsoft Confidential | Do not distribute externally
Summary and Conclusion
Top 5 vulnerability categories
Know the impact
Know what they are
Know how to find
Know how to fix the right way
Leverage available resources
CAT.NET, Web Protection Library and WACA
Lessons learned are applicable and hold on Windows Azure platform
Secu
rity
Talk
21
Microsoft Confidential | Do not distribute externally
Questions & Answers
• Submit text questions using the “Ask” button.
• Send us your feedback and content ideas in the survey.
• Replay of this webcast will be available in 24 hours.
• Get the latest developer content (webcasts, podcasts, videos, virtual labs) at: www.Microsoft.com/Events/Series/
• For more security webcasts: www.microsoft.com/events/series/securitytalk
• Check out Windows Azure Subscriptions: bit.ly/TryAzure
© 2008Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing marketconditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.