secure code: threats and counter measures malek kemmou technology architect, application platform...
TRANSCRIPT
Secure code: Threats and counter measures
Malek Kemmou
Technology Architect, Application Platform
Microsoft Middle East and Africa
Agenda
• Introduction• Borderline vulnerabilities• Communication• Components and services• Failing safely• Threat Modeling• Best Practices …
Things we hear …
• I am secure, we have a great security team managing the firewalls
• I have no time to think about it, I am busy designing and coding features
• No one would do that, why would they ?• We’ve never been attacked• That’s the way we’ve always done it, and it
works fine
Wrong
Intro
• I am not crying Wolf !– How long do you think a web site will stay
undiscovered ?– Do you think viruses get in by themselves ?– Internet is a needed hostile environment
• It is usually there even when your application doesn’t use it
• You’ll see how easy it is to defeat a system
Intro
• A little quiz for you– What is the most dangerous HTML tag ?
<INPUT TYPE=“TEXT”> – What is the most dangerous control in a rich client
Form?
TextBox
• Simple Script InjectionSimple Script Injection
How do injections function
<%=Request.Form(« Name")%>
<INPUT TYPE="hidden"
VALUE=<%=Request.Form("Name")%>>
<% str=Request.Form(« Name")
If Instr(str,"<" ) <>-1) OR Ìnstr(str, ">" ) <>-1) Then str="" %>
<INPUT TYPE="TEXT"
VALUE = "<%=str%> ">
<script>alert(document.cookie);</script>
‘ ‘><script>alert(document.cookie);</script
" onmouseover= "alert(document.cookie);
• SQL Injections
Preventing injections
• Developer mind set :– The user is not the one I think he is …
• Validate the input– Regular Expressions– Test for what you want, not what you want to
prevent– Test on server side …– Stored Procedures (SQL injections)
• Comforting and helpful, best practice in many cases• Not fully secure : depends on how you call them
• Preventing Injections
Address = Address = xxxxxxxxxxxx
Variable XVariable X XX
Vicious codeVicious code
Return address = xxxxxxReturn address = xxxxxxAddress = yyyyyyyyyyAddress = yyyyyyyyyy
yyyyyyyyyyyyyyyyyyyy
Buffer overflow
Example : Stack Overflow
foofoo
mainmain
ABCDEFGHIJABCDEFGHIJ
ABCDEFGHIJABCDEFGHIJ
Example : Stack Overflow
foofoo
mainmain
ABCDEFGHIJKLABCDEFGHIJKLyyyyyyyyyy
barbar
yyyyyyyyyy
yyyyyyyyyy
#include <stdio.h>
#include <string.h>
void foo(const char* input)
{
char buf[10];
printf(“initial stack :
\n%p\n%p\n%p\n%p\n%p\n%p\n\n");
strcpy(buf, input);
printf("%s\n",buf);
printf(“actual stack : \n%p\n%p\n%p\n%p\n%p\n%p\n\n");
}
void bar(void)
{
printf(“damn, I’m hacked");
}
int main(int argc, char* argv[])
{
printf("Adresse de foo =
%p\n",foo);
printf("Adresse de bar =
%p\n",bar);
foo(argv[1]);
return 0;
}
StaticOverrun.exe
Preventing Buffer overruns
• Use managed code• Careful on unmanaged calls (C++, unsafe code in
C#, PInvoke)– Types– Sizes– Encoding (ASCII/ANSI vs Unicode …)
• C++ code:– Compile with /gs (prevents some Buffer overflows)– Dangerous APIs (strcopy, …)
Protecting secrets
“If you think cryptography can solve the problem, you probably don’t understand the problem”
• Random generation issues• Measure correctly the cipher strength
– log2(numChars^length)
• Managing the keys (the no win game)• Stream cipher issues• encrypting, hashing, Signing
• Known algorithms are much better than what I can roll on my own
Don’t play hide and seek
Storing secrets
• Do I have to store it ?– Hash– Salted hash– Get it from the user
• If I do :– DPAPI (Win2K and later)– Crypto APIs + ACL (Win NT/ Win 2k / Win 2k3)– Win9x, WIN CE
• Derive from hardware• Maybe removable storage
Securing Components
• Business components
• Data Access Components
• Web Services
Components
Public DataRow fetchCustomer(string name){
…Cmd.ComandText=“select * from customers ”+
“where name=‘” +name+”’”;…
}
Server side testingServer side testing
SpoofSpoof
Name = “a’; Drop Table Customers --”Name = “a’; Drop Table Customers --”
Cmd.ComandText=“select * from customers”
“where name=‘a’; Drop Table Customers - - ’ ”;
Protecting components
• identity
Trust zone
External user id
Internal user id
SpoofSpoof
External user id
Protecting Components
Public DataRow fetchCustomer(string name){
…Cmd.ComandText=“select * from clients”+
“nom=‘” +name+”’”;…
}
Server side testingServer side testing
SpoofSpoof
Name = “a’; Drop Table client - -”Name = “a’; Drop Table client - -”
Cmd.ComandText=“select * from clients”+“nom=‘a’; Drop Table Clients -
- ’ ”;Weak idDenied
Protecting components
• Privilege– Every task needs some kind of privilege– Most tasks need low privileges
• Don’t confuse ACL with privilege !!!– ACL manage rights to access resources– Privilege is used for machine/domain wide rights
Protecting components
• Run with least privilege !!!– Identities like ASPNET, Local Service, Network
Service– Use needed ACLs– Use application security (SQL authorization, IIS
authorization, …)
– Don’t use unneeded privilege !!!
Protecting components
• Code Access security– Control over code rights– Centrally manageable
– Use WMI for setup or scripted deployment
Canonical Representation
• An application making a decision on a non canonical representation of a name– Easiest form (1st apache version on MAC OSX)
• Directory protection based on the name• Apache is case sensitive, HFS+ is not
• Some common canonical representation issues– Filenames (DOS long filenames, NTFS alternate streams, Trailing
characters, directory traversal, absolute vs relative, case-sensitivity, mailslots and named pipes, device names, …etc)
– Web (trailing characters, escape characters (“%xx”, “&xxxx;” dot less IP address, UTF-8 variable-width, double escape …)
– carriage return (is it one or two lines ?)
Don’t tell too much
Don’t tell too much
try{
//execution}catch (Exception ex){
#if (DEBUG) Label_Erreur.Text = ex.ToString();
#elseLabel_Erreur.Text = “An error has occured while processing your request“ ;logException(ex.ToString()) ;
#endif}…private void logException(string error){
Try {EventLog log = new EventLog("Applifcation") ;log.Source=”Customers Site”;log.WriteEntry(error, EventLogEntryType.Warning);
} catch (Exception e){writeToFile(error, e.ToString()) ;
}}
Mind set
• Think of the application as a fortress– Define secure vs. insecure (publicly accessible) zones– At the gates
• Authenticate and authorize before allowing entry
• Check the bags (validate all input)
– Vigilance inside• Authorize actions
• Use lowest possible privilege for action
– Secure communication• Authenticate messages (signing and hashing)
• Code messages (crypto)
– Train personnel to resist interrogation (don’t tell too much)
Mind set
• Secure code is quality code
• Secure code is not more code
• Secure code is less and easier maintenance
Brief summary of forms of attacks
• Spoofing Identity
• Tampering with Data
• Repudiation
• Information disclosure
• Denial of Service
• Elevation of privilege
STRIDE
Threat modeling
• No use to try to be 100% secure,
it is (sadly) not possible• Procedure to model threats
– Analyze known threats (STRIDE)– Classify Threats by decreasing risk (DREAD Model)
• Damage potential, Reproducibility, Exploitability, Affected users, Discoverability
• Risk = (D+R+E+A+D)/5
Responding to Threats
• Choose the appropriate response– Fix the problem– Remove the problem
• Instead of shipping with a flaw, sometimes the right choice is to pull the feature off
– Inform the user of threat• Usually a bad choice, unless for certain user profiles, and
then, make audible and logged warnings.• Remember : users don’t read docs, users click “OK” on
warnings !!
– Do Nothing : very rarely the right choice• Chances >0 that it will be discovered
Best Practices
• Essentials– My user is not who I think he is– Every input is guilty until proven innocent– Think : “What input do I want”, not “What input I don’t want”– Client side validation is not security, it is merely a way to help
end user and avoid unneeded load– The code being executed is not what I think it is, if I use
privilege, attackers will use it too– Known algorithms are better than my own– Crypto is only as good as the key used– Crypto is no good if the key is not protected– Less functionality is better than risking failure or security breach
Best Practices
It is not just your application that is at stake …
• Good citizenship of the fortress– Protect the user– Protect the user’s confidential data– Don’t tell the attacker anything– Use impersonation with great caution– Use assertions with great caution– Don’t be afraid of denying permissions– Use strong passwords (don’t go too far, you’ll end up with
password stickers on keyboards)– Use least privilege
• For services, use Network Service, Local Service (not System Service unless necessary)
• Use normal accounts (or lower privilege accounts), not admin/SA
Find more info
Microsoft Developer Networkhttp://msdn.microsoft.com/security
Patterns and Practices Guideshttp://www.microsoft.com/patternsWriting Secure Code 2
Michael Howard & David LeBlanc
Microsoft Press
Writing Secure Code 2Michael Howard & David LeBlanc
Microsoft Press
© 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only.MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.