Post on 28-Dec-2015
Copyright Microsoft Corp. 2006
Building Secure SoftwareBuilding Secure SoftwareWebcast SeriesWebcast Series
Vineet GuptaVineet GuptaTechnology EvangelistTechnology EvangelistMicrosoft IndiaMicrosoft Indiahttp://spaces.msn.com/vineetgupta/http://spaces.msn.com/vineetgupta/
Copyright Microsoft Corp. 2006
AgendaAgenda
Mar 17: Input Trust IssuesMar 17: Input Trust Issues
Mar 24: Common MistakesMar 24: Common Mistakes
Mar 31: Design PrinciplesMar 31: Design Principles
Apr 07: Crypto BasicsApr 07: Crypto Basics
Apr 14: Web Apps SecurityApr 14: Web Apps Security
Apr 21: .Net Framework SecurityApr 21: .Net Framework Security
Apr 28: Security TestingApr 28: Security Testing
May 05: Threat ModelingMay 05: Threat Modeling
Copyright Microsoft Corp. 2006
Building Secure Software:Building Secure Software:Common MistakesCommon Mistakes
Vineet GuptaVineet GuptaTechnology EvangelistTechnology EvangelistMicrosoft IndiaMicrosoft Indiahttp://spaces.msn.com/vineetgupta/http://spaces.msn.com/vineetgupta/
Copyright Microsoft Corp. 2006
The 19 Deadly Sins of Software SecurityThe 19 Deadly Sins of Software Security
1.1. Buffer overruns Buffer overruns
2.2. Format String Problems Format String Problems
3.3. Integer Overflows Integer Overflows
4.4. SQL Injection SQL Injection
5.5. Command Injection Command Injection
6.6. Failure to Handle Errors Failure to Handle Errors
7.7. Cross-Site Scripting Cross-Site Scripting
8.8. Failure to Protect Network Failure to Protect Network Traffic Traffic
9.9. Use of Magic URLs and Use of Magic URLs and Hidden Forms Hidden Forms
10.10. Improper Use of SSLImproper Use of SSL
11.11. Use of Weak Password-based Use of Weak Password-based Systems Systems
12.12. Failure to Store and Protect Failure to Store and Protect Data Securely Data Securely
13.13. Information Leakage Information Leakage
14.14. Trusting Network Address Trusting Network Address Resolution Resolution
15.15. Improper File Access Improper File Access
16.16. Race Conditions Race Conditions
17.17. Unauthenticated Key Unauthenticated Key Exchange Exchange
18.18. Failure to Use Failure to Use Cryptographically Strong Cryptographically Strong Random Numbers Random Numbers
19.19. Poor UsabilityPoor Usability
Copyright Microsoft Corp. 2006
Buffer OverrunsBuffer Overruns
Copyright Microsoft Corp. 2006
What Is a Buffer Overrun?What Is a Buffer Overrun?
The most common and dangerous security riskThe most common and dangerous security risk
Primarily exists in unmanaged C/C++ codePrimarily exists in unmanaged C/C++ code
Occurs when data exceeds the expected size and Occurs when data exceeds the expected size and overwrites other valuesoverwrites other values
Examples Examples Static buffer overruns; heap overruns; and v-table Static buffer overruns; heap overruns; and v-table function pointer, and exception handler overwritingfunction pointer, and exception handler overwriting
Famous exploitsFamous exploitsThe Internet Worm of 1988The Internet Worm of 1988
The CodeRed WormThe CodeRed Worm
Copyright Microsoft Corp. 2006
How common are BOs?How common are BOs?
Approx 33% of bulletins remedy BOsApprox 33% of bulletins remedy BOsSource: Vendor Web sites, 01Jan03 –31Dec03Source: Vendor Web sites, 01Jan03 –31Dec03
0
20
40
60
80
100
120
140
160
180
200
Microsoft Sun RedHat Debian
Bulletins (2003)
Buffer Overruns
0
20
40
60
80
100
120
140
160
180
200
Microsoft Sun RedHat Debian
Bulletins (2003)
Buffer Overruns
Copyright Microsoft Corp. 2006
Why are they prevalent?Why are they prevalent?Lots of C/C++ code out thereLots of C/C++ code out there
Lots of legacy C/C++ code that’s now hooked to the ‘netLots of legacy C/C++ code that’s now hooked to the ‘net
Most CPUs make no distinction between code Most CPUs make no distinction between code and dataand data
Many data structures jump to codeMany data structures jump to codeStack addresses, function pointers, exception handlers, C++ Stack addresses, function pointers, exception handlers, C++ class v-tables etc.class v-tables etc.
Constantly evolving threatsConstantly evolving threatsFirst there were stack overrunsFirst there were stack overruns
Then heap overrunsThen heap overruns
Then format string overrunsThen format string overruns
Then “one-byte overruns”Then “one-byte overruns”
Now, integer overflowsNow, integer overflows
What’s next?What’s next?
Copyright Microsoft Corp. 2006
Stack Smashing – The IssueStack Smashing – The Issue
A Buffer
Some Data
Add ‘em together!
{
Hope there’s nothingof interest here!
Copyright Microsoft Corp. 2006
Stack Smashing - ExploitStack Smashing - Exploit
Imagine this is a…Imagine this is a…1) function RET address, or1) function RET address, or2) a vtable, or2) a vtable, or3) a SEH address!3) a SEH address!
The attacker just overwrote it!The attacker just overwrote it!
Copyright Microsoft Corp. 2006
Buffer Overrun ResultsBuffer Overrun ResultsIf you’re lucky, you get an Access ViolationIf you’re lucky, you get an Access Violation
Denial of Service against serversDenial of Service against servers
If you’re unlucky, you get instabilityIf you’re unlucky, you get instabilityBest of luck debugging that one!Best of luck debugging that one!
If you’re really unlucky, the attacker injects code If you’re really unlucky, the attacker injects code into your processinto your process
And executes itAnd executes it
And everyone’s an admin :-(And everyone’s an admin :-(
Lesson: Use least privileged accounts to run processesLesson: Use least privileged accounts to run processes
Copyright Microsoft Corp. 2006
Types of exploitsTypes of exploits
Stack smashingStack smashing
Register hijackingRegister hijacking
Local pointer subterfugeLocal pointer subterfuge
V-Table hijackingV-Table hijacking
C++ EH clobberingC++ EH clobbering
SEH clobberingSEH clobbering
Multistage attacksMultistage attacks
Parameter pointer subterfugeParameter pointer subterfuge
Previous function’sPrevious function’sstack framestack frame
Return addressReturn address
EH frameEH frame
Callee saveCallee saveregistersregisters
GarbageGarbage
Local variables andLocal variables andlocally declaredlocally declaredbuffersbuffers
Frame pointerFrame pointer
Function argumentsFunction arguments
Copyright Microsoft Corp. 2006
Visual Studio security optionsVisual Studio security options
/GS /GS
A "speed bump," or cookie, between the buffer A "speed bump," or cookie, between the buffer and the return address. When function exits, the and the return address. When function exits, the cookie is checkedcookie is checked
Helped lower Blaster impact on Win 2003Helped lower Blaster impact on Win 2003
/SAFESEH/SAFESEH
Created in response to CodeRedCreated in response to CodeRed
Verifies the exception handlerVerifies the exception handler
Copyright Microsoft Corp. 2006
VC++ 2005 - Safer CRTVC++ 2005 - Safer CRTHelping to use CRT functions in a safer wayHelping to use CRT functions in a safer way
Reviewing all 2000 C and C++ library Reviewing all 2000 C and C++ library functionsfunctions
Deprecating insecure functions by defaultDeprecating insecure functions by default
#define _CRT_SECURE_NO_DEPRECATE#define _CRT_SECURE_NO_DEPRECATE
Creating around 400 Safer variantsCreating around 400 Safer variants
strcpy -> strcpy_sstrcpy -> strcpy_s
Adding parameter validation mechanismAdding parameter validation mechanism
_invalid_parameter_handler_invalid_parameter_handler
Invokes the Windows Error Reporting in Invokes the Windows Error Reporting in Release. Asserts in Debug. Release. Asserts in Debug.
All of Visual Studio, C++ Libraries use Safer All of Visual Studio, C++ Libraries use Safer CRTCRT
Copyright Microsoft Corp. 2006
Fixing Fixing Buffer Buffer
OverrunsOverruns
Search for ‘risky’ Search for ‘risky’ functions & determine functions & determine
data origindata origin
Defensive CodeDefensive Code Updated libraries(strsafe, Safer CRT)
Fuzz TestsFuzz TestsStatic AnalysisStatic Analysis
/GS, NX /GS, NX & Heap Checking& Heap Checking
Buffer Overruns - CountermeasuresBuffer Overruns - Countermeasures
Copyright Microsoft Corp. 2006
Format String ProblemsFormat String Problems
Copyright Microsoft Corp. 2006
What can go Wrong Here?What can go Wrong Here?#include <stdio.h>
int main(int argc, char* argv[])
{
if (argc > 1) printf(argv[1]);
return 0;
}
What if argv[1] is “%x %x”?
In printf “%x” means read next data as intThis means stack can be read 4 bytes at a time
You get address of stack location followed by code location of where main() will return!
Copyright Microsoft Corp. 2006
Format String IssuesFormat String Issues
What if you are logging input to track What if you are logging input to track activity?activity?
And the attacker provides backspaces in And the attacker provides backspaces in the format string?the format string?
Bottomline: Do not allow user to control Bottomline: Do not allow user to control format stringsformat strings
#include <stdio.h>
int main(int argc, char* argv[])
{
if (argc > 1) printf(“%s”, argv[1]);
return 0;
}
Copyright Microsoft Corp. 2006
Integer OverflowsInteger Overflows
Copyright Microsoft Corp. 2006
What Can Go Wrong Here?What Can Go Wrong Here?
The program is filter an array of int’s to have only ¾ of the original values
int[] filter(uint len,
int[] numbers)
{
uint newLen =
len * 3/4;
int[] buf = new int[newLen];
int j = 0;
for(int i = 0; i < len; i++)
{
if (i % 4 != 0)
buf[j++] = numbers[i];
}
return buf;
}
Problem is that in Problem is that in calculating the value for calculating the value for len, the code first len, the code first computes computes len * 3!len * 3!
Copyright Microsoft Corp. 2006
Integer OverflowsInteger Overflows
Integer overflow is a generic name for Integer overflow is a generic name for a set of common integer arithmetic a set of common integer arithmetic mistakes that can lead to BOsmistakes that can lead to BOs
Overflow and underflow Overflow and underflow
Signed versus unsigned errors Signed versus unsigned errors
TruncationTruncation
They lead to BOsThey lead to BOs
Copyright Microsoft Corp. 2006
Integer OverflowsInteger Overflows
Integer overflows are still possible in Managed Integer overflows are still possible in Managed CodeCode
C# is no different from C in this regardC# is no different from C in this regard
VB.Net will throw System.Overflow exceptionVB.Net will throw System.Overflow exception
Result is often not as severeResult is often not as severe
Integer overflows often result in buffer overflows which Integer overflows often result in buffer overflows which are much less likely with managed codeare much less likely with managed code
They can still lead to system instability issuesThey can still lead to system instability issues
Copyright Microsoft Corp. 2006
Integer Overflows – Hunting Integer Overflows – Hunting ThemThem
Can be insidiously difficult to find!Can be insidiously difficult to find!
Look for repeated actions or loops that may cause an Look for repeated actions or loops that may cause an increase or decrease in a structure or valueincrease or decrease in a structure or value
From a black-box perspective, force the application to From a black-box perspective, force the application to either display the results of a calculation or use that either display the results of a calculation or use that valuevalue
Consequences can be dire and source code scanners Consequences can be dire and source code scanners are notoriously bad at finding these issues in codeare notoriously bad at finding these issues in code
Copyright Microsoft Corp. 2006
Integer Overflows - Integer Overflows - CountermeasuresCountermeasures
Take proper care in checking arithmeticTake proper care in checking arithmetic
Never make assumptions about the largest value a Never make assumptions about the largest value a variable will holdvariable will hold
Take care when executing in a loopTake care when executing in a loopx=x+1 can be bad if executed enoughx=x+1 can be bad if executed enough
Do sanity checks on values before they are usedDo sanity checks on values before they are used
Keep in mind how large or small the result of an Keep in mind how large or small the result of an arithmetic operation can bearithmetic operation can be
Use the /checked compiler flag for C# projectsUse the /checked compiler flag for C# projectsDefault in C# 2.0Default in C# 2.0
Copyright Microsoft Corp. 2006
Remedy: Integer ArithmeticRemedy: Integer Arithmetic
AnyAny calculation used to determine an array calculation used to determine an array offset or memory allocation is suspectoffset or memory allocation is suspect
Use unsigned variables for array indexes Use unsigned variables for array indexes and buffer sizesand buffer sizes
Watch out for: Watch out for:
C4018 & C4389 (signed/unsigned mismatch)C4018 & C4389 (signed/unsigned mismatch)
C4244 warnings (conversion from 'type1' to C4244 warnings (conversion from 'type1' to 'type2', possible loss of data)'type2', possible loss of data)
#pragma and casts that shut the compiler up!#pragma and casts that shut the compiler up!
Copyright Microsoft Corp. 2006
Remedy: Remedy: Integer ArithmeticInteger Arithmetic in C# in C#public Object GetUserData(UInt32 ItemNumber) { checked { return myData[ItemNumber+USER_DATA_START]; }}
Copyright Microsoft Corp. 2006
Failure to Handle ErrorsFailure to Handle Errors
Copyright Microsoft Corp. 2006
Failure to Handle ErrorsFailure to Handle Errors
If your code does fail, make sure it fails If your code does fail, make sure it fails securelysecurely
DWORD dwRet = IsAccessAllowed(…);
if (dwRet == ERROR_ACCESS_DENIED){
// Security check failed.// Inform user that access is denied
}else {
// Security check OK.// Perform task…
}
What if IsAccessAllowed()
returns ERROR_NOT_
ENOUGH_MEMORY?
What if IsAccessAllowed()
returns ERROR_NOT_
ENOUGH_MEMORY?
Copyright Microsoft Corp. 2006
Failure to Handle ErrorsFailure to Handle Errors
If an attacker knows you fail insecurely, the If an attacker knows you fail insecurely, the attacker will make you failattacker will make you fail
Always fail to a secure modeAlways fail to a secure mode
Follow access denied pathsFollow access denied paths
Copyright Microsoft Corp. 2006
Failure to Handle ErrorsFailure to Handle Errors
Yielding too much InformationYielding too much Information
Ignoring ErrorsIgnoring Errors
Misinterpreting ErrorsMisinterpreting Errors
Using Useless Error ValuesUsing Useless Error Values
Handling the Wrong ExceptionsHandling the Wrong Exceptions
Handling all ExceptionsHandling all Exceptions
Copyright Microsoft Corp. 2006
Failure to Handle ErrorsFailure to Handle Errors
Do not:Do not:
Reveal information in error messagesReveal information in error messages
Consume resources for lengthy periods of Consume resources for lengthy periods of time after a failuretime after a failure
Do:Do:
Use exception handling blocks to avoid Use exception handling blocks to avoid propagating errors back to the callerpropagating errors back to the caller
Write suspicious failures to an event logWrite suspicious failures to an event log
<customErrors mode="On"/>
Copyright Microsoft Corp. 2006
Use of Weak Password-based Use of Weak Password-based SystemsSystems
Copyright Microsoft Corp. 2006
Password WeaknessesPassword Weaknesses
Password need not get compromisedPassword need not get compromised
Capture-Replay attacksCapture-Replay attacks
Non-technical ways of password Non-technical ways of password compromisecompromise
Social EngineeringSocial Engineering
Not Changing default passwordsNot Changing default passwords
Key LoggingKey Logging
Client-side password cachingClient-side password caching
Password CapturePassword Capture
Brute-Force, Dictionary AttacksBrute-Force, Dictionary Attacks
Copyright Microsoft Corp. 2006
Password ContentPassword Content
Require a minimum password lengthRequire a minimum password length
Let’ say 8 charactersLet’ say 8 characters
Allow arbitrarily long passwordsAllow arbitrarily long passwords
Make Passwords harder to guessMake Passwords harder to guess
Require symbols and numeralsRequire symbols and numerals
Change Passwords frequentlyChange Passwords frequently
Do not allow previous n passwordsDo not allow previous n passwords
Copyright Microsoft Corp. 2006
Password Resets and ChangesPassword Resets and Changes
Failed Logins should have only one Failed Logins should have only one message irrespective of reason of failuremessage irrespective of reason of failure
Allow logged-in users to change passwords Allow logged-in users to change passwords via a secure channelvia a secure channel
Require passwords to be re-validated!Require passwords to be re-validated!
Automatic Password ResetsAutomatic Password Resets
Avoid ThemAvoid Them
Info required to do this should be unlikely to be Info required to do this should be unlikely to be with hackerswith hackers
Force Password Change on First LoginForce Password Change on First Login
Copyright Microsoft Corp. 2006
Password ProtocolPassword Protocol
Use a standard, well-known protocolUse a standard, well-known protocolZero-Knowledge protocols are good (SRP, PDM)Zero-Knowledge protocols are good (SRP, PDM)
Kerberos is good if used for both auth and encryptionKerberos is good if used for both auth and encryption
Avoid Unix Crypt(), HTTP Digest, CRAM-MD5, MD5-Avoid Unix Crypt(), HTTP Digest, CRAM-MD5, MD5-MCFMCF
If Protocol is not Zero-K, use a Secure ChannelIf Protocol is not Zero-K, use a Secure Channel
If using Challenge-Response, it is important that If using Challenge-Response, it is important that challenge can never repeatchallenge can never repeat
Or you are susceptible to capture-replayOr you are susceptible to capture-replay
Protocol should name the parties of the Exchange Protocol should name the parties of the Exchange and have each party confirm the name to the and have each party confirm the name to the otherother
Copyright Microsoft Corp. 2006
Password Handling and StoragePassword Handling and Storage
Avoid visual representation of lengthAvoid visual representation of length
Don’t Store Passwords in the ClearDon’t Store Passwords in the Clear
Don’t Store Passwords in weakly protected Don’t Store Passwords in weakly protected Permanent StorePermanent Store
Passwords should be stored using a fixed-Passwords should be stored using a fixed-sized outputsized output
Produced by cryptographically strong one-way Produced by cryptographically strong one-way mechanism (like PKCS #5)mechanism (like PKCS #5)
Should not be reversible. As bad as clear textShould not be reversible. As bad as clear text
Include a random salt in the one-way computation. Include a random salt in the one-way computation. 32-bits is good.32-bits is good.
Iterate the algorithm a number of times (10k) to deter Iterate the algorithm a number of times (10k) to deter crack attacks.crack attacks.
Copyright Microsoft Corp. 2006
Password RedemptionsPassword RedemptionsMulti-factor AuthenticationMulti-factor Authentication
Authentication Technology ClassesAuthentication Technology Classes
Things you know: Passwords, PINs, etc.Things you know: Passwords, PINs, etc.
Things you have: Smart Cards, Credit-Cards, Things you have: Smart Cards, Credit-Cards, etc.etc.
Things you are: Bio-MetricsThings you are: Bio-Metrics
All three have pros and consAll three have pros and cons
Use a CombinationUse a Combination
Require ALL = Excellent = Multi-Factor Auth!Require ALL = Excellent = Multi-Factor Auth!
Require ANY = Very bad!!Require ANY = Very bad!!
Copyright Microsoft Corp. 2006
Password RedemptionsPassword RedemptionsStoring and Checking PasswordsStoring and Checking Passwords
Password Storage Function should be one-wayPassword Storage Function should be one-way
Good standard function is PBKDF2Good standard function is PBKDF2Password Based Key Derivation FunctionPassword Based Key Derivation Function
Defined in Public Key Cryptography Std #5Defined in Public Key Cryptography Std #5
DetailsDetailsOne-way, deterministic outputOne-way, deterministic output
Can specify output size (use at least 128-bits)Can specify output size (use at least 128-bits)
Takes a salt (64-bits is good if random)Takes a salt (64-bits is good if random)
Computation can be made to take a relatively long timeComputation can be made to take a relatively long timeDelay of a second is ok for end-userDelay of a second is ok for end-user
Can frustrate an offline dictionary attackCan frustrate an offline dictionary attack
Provided by an iteration count on core functionProvided by an iteration count on core function
Use at-least 10,000 for modern OS, HardwareUse at-least 10,000 for modern OS, Hardware
Copyright Microsoft Corp. 2006
PBKDF2 ImplementationPBKDF2 ImplementationDPAPI provides an implementation with DPAPI provides an implementation with 4000 iterations4000 iterations
Can be easily built using HMACCan be easily built using HMAC
static string GetPBKDF2(string pwd, byte[] salt, int iter){ System.Security.Cryptography.PasswordDeriveBytes p = new PasswordDeriveBytes(pwd, salt, "SHA1", iter);
return p.GetBytes(20);}
Copyright Microsoft Corp. 2006
Password RedemptionsPassword RedemptionsMore GuidelinesMore Guidelines
After authentication, each message should After authentication, each message should atleast be authenticated, if not encryptedatleast be authenticated, if not encrypted
Do not lock accountsDo not lock accountsDoS waiting to happenDoS waiting to happen
InsteadInsteadLimit attempts to say 50 / hourLimit attempts to say 50 / hour
Slow down auth process on getting bad attemptsSlow down auth process on getting bad attempts
Make password resetting impossible for a Make password resetting impossible for a humanhuman
Email the password instead of letting the user Email the password instead of letting the user know there and thenknow there and then
Copyright Microsoft Corp. 2006
Failure to Store and Protect Data Failure to Store and Protect Data SecurelySecurely
Copyright Microsoft Corp. 2006
Storing SecretsStoring Secrets
Software cannot defend itself, therefore:Software cannot defend itself, therefore:
Storing secrets securely in software is Storing secrets securely in software is impossible!impossible!
Embedded ‘secrets’ don’t stay secretEmbedded ‘secrets’ don’t stay secretfor longfor long
Copyright Microsoft Corp. 2006
Do not store secret information on your computer or in your applications unless you Do not store secret information on your computer or in your applications unless you mustmust
Connection information in global.asaxConnection information in global.asax
Do not transmit or store passwords in plaintext; use Do not transmit or store passwords in plaintext; use CryptoAPI, CAPICOM, or CryptoAPI, CAPICOM, or System.Security.Cryptography System.Security.Cryptography to to create a hash, or use Stored User Names and Passwords create a hash, or use Stored User Names and Passwords in Windows XPin Windows XP
connectionString = connectionString = “Provider=SQLOLEDB;Server=(local);Initial “Provider=SQLOLEDB;Server=(local);Initial Catalog = Northwind;UID=Bill;PWD=DaIsY!”;Catalog = Northwind;UID=Bill;PWD=DaIsY!”;
connectionString = connectionString = “Provider=SQLOLEDB;Server=(local);Initial “Provider=SQLOLEDB;Server=(local);Initial Catalog = Northwind;UID=Bill;PWD=DaIsY!”;Catalog = Northwind;UID=Bill;PWD=DaIsY!”;
Client Server
DaSiY!DaSiY!DaSiY!DaSiY!
CryptoAPI
&(Y$g%!&(Y$g%!&(Y$g%!&(Y$g%! &(Y$g%!&(Y$g%!&(Y$g%!&(Y$g%!
Internet
Do not Store SecretsDo not Store Secrets
Copyright Microsoft Corp. 2006
Storing SecretsStoring Secrets
DPAPI is the recommended methodDPAPI is the recommended method
Crypt[Un]ProtectData Crypt[Un]ProtectData Managed wrappers availableManaged wrappers available
Requires Windows 2000 or Windows CE .NET Requires Windows 2000 or Windows CE .NET and laterand later
Preferable to LSA secretsPreferable to LSA secretsEasy!Easy!
You store the encrypted secretYou store the encrypted secretYou can back the data upYou can back the data up
DPAPI provides integrity checkDPAPI provides integrity check
No need to run as adminNo need to run as admin
Account that encrypts the data, decrypts the dataAccount that encrypts the data, decrypts the data
Copyright Microsoft Corp. 2006
Information LeakageInformation Leakage
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 - CountermeasuresInformation Leakage - Countermeasures
Be wary about what you tell remote usersBe wary about what you tell remote users
They may be attackersThey may be attackers
They can use the info to learn more about the They can use the info to learn more about the computercomputer
Tell them enough to diagnose the issueTell them enough to diagnose the issue
Log the issue in more detail locallyLog the issue in more detail locally
For admins onlyFor admins only
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
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
Famous ExploitsFamous ExploitsNapster FiltersNapster Filters
Judge Ordered Napster to Block Certain SongsJudge Ordered Napster to Block Certain SongsBased on FilenamesBased on Filenames
Was Easily BypassedWas Easily Bypassed
America Online Parental ControlsAmerica Online Parental Controls
Used a list of sites that could not be accessedUsed a list of sites that could not be accessed
Bypass: Use an Alternate RepresentationBypass: Use an Alternate Representation
Translators were Available!Translators were Available!
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
Failure to Use Cryptographically Failure to Use Cryptographically Strong Random NumbersStrong Random Numbers
Copyright Microsoft Corp. 2006
Random NumbersRandom Numbers
Random numbers are very importantRandom numbers are very important
CryptographyCryptography
Session IdsSession Ids
GamesGames
And should be used regularlyAnd should be used regularly
However, typical Random number However, typical Random number generators are badgenerators are bad
Copyright Microsoft Corp. 2006
Poor Random NumbersPoor Random Numbers
RandomnessRandomness
Even DistributionEven Distribution
Unpredictable ValuesUnpredictable Values
Long and Complete CyclesLong and Complete Cycles
Most Generators Use Linear Congruential Most Generators Use Linear Congruential FunctionsFunctions
Meet First CriteriaMeet First Criteria
Miserably Fail for SecondMiserably Fail for Second
Don’t Use These for Security PurposesDon’t Use These for Security Purposes
Copyright Microsoft Corp. 2006
Types of Random Number Types of Random Number Generators (RNGs)Generators (RNGs)
Non-Cryptographic Pseudo-Random Non-Cryptographic Pseudo-Random Number Generators (PRNGs)Number Generators (PRNGs)
Example: Rand()Example: Rand()
Cryptographic Pseudo-Random Number Cryptographic Pseudo-Random Number Generators (CRNGs)Generators (CRNGs)
True Random Number Generators True Random Number Generators (TRNGs)(TRNGs)
Also called Entropy GeneratorsAlso called Entropy Generators
Copyright Microsoft Corp. 2006
Random Numbers RedemptionRandom Numbers RedemptionDo not Use PRNGsDo not Use PRNGs
rand()rand() and and System.Random() System.Random()
Use CRNGsUse CRNGs
Consider Consider CryptGenRandom()CryptGenRandom() and and System.Security.CryptographySystem.Security.Cryptography
FIPS-approved (requirement for federal systems)FIPS-approved (requirement for federal systems)
Use at-least 64-bits of entropy, preferably 128 bitsUse at-least 64-bits of entropy, preferably 128 bits
using System.Security.Cryptography;
byte[] b = new byte[32];new RNGCryptoServiceProvider().GetBytes(b);// b now contains 32 bytes of random data
Copyright Microsoft Corp. 2006
Questions?Questions?
Copyright Microsoft Corp. 2006
More Questions?More Questions?
http://spaces.msn.com/vineetgupta/
Copyright Microsoft Corp. 2006
Ready for Big-Time?Ready for Big-Time?Participate in the Microsoft India Security Participate in the Microsoft India Security ShootoutShootouthttp://www.microsoft.com/india/security/securityshootout/http://www.microsoft.com/india/security/securityshootout/
Three roundsThree rounds
Over 7,500 PrizesOver 7,500 Prizes1 x Customized Scorpio Passion1 x Customized Scorpio Passion
3 x Toshiba Tecra M4 Laptops3 x Toshiba Tecra M4 Laptops
10 x Pocket PC with 1 GB memory10 x Pocket PC with 1 GB memory
Lots moreLots more
Contest starts 20Contest starts 20thth Mar Mar
Registration open Now!Registration open Now!
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.