secure code reviews
TRANSCRIPT
33rd CSI Conference, Orlando, Florida
1
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Secure Code Reviews
Marco MoranaSenior Consultant
Foundstone, A Division of McAfee
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
33rd CSI Conference, Orlando, Florida
2
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Agenda• Introduction
– What Secure Code Reviews Are Not– Why We Need Secure Code Reviews ?– Code Reviews
• Concepts and Strategies– Secure Code Reviews in the SDLC– Threat Modeling– Methodology– Coding Mistakes – Tools
• Tips And Tricks• Resources
33rd CSI Conference, Orlando, Florida
3
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
DisclaimersSecure code reviews are not:1. A stand alone activity separate from the SDLC2. A process that just relies on tools:
– Managed programming language– Automated code analysis
3. A method to rate un-attackable code– Not being scrutinized by security experts– False sense of security (i.e. false negatives)
33rd CSI Conference, Orlando, Florida
4
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Why we need secure code reviews ?1. Compliance with governing policies2. Assurance that code follows security best
practices3. Security assessment before releasing to
QA and production4. Measurement of adequacy of security
controls to mitigate known threats
33rd CSI Conference, Orlando, Florida
5
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Code Reviews• One to One (peer to peer)
– Part of the sign-off before handing off to QA– Integrated with the check-in process
• Group (team-driven)– Advantage of many eye-balls– Team members take different roles
Both need preparation and organization
33rd CSI Conference, Orlando, Florida
6
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Code Reviews - Team Code Review Approach
• Optimal scenario: A team of 4 people in a conference room with a whiteboard and projector
• Team Roles– Lead Reviewer– Narrator– Author– Subject Matter Experts
33rd CSI Conference, Orlando, Florida
7
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Agenda• Introduction
– What Secure Code Reviews Are Not– Why We Need Secure Code Reviews ?– Code Reviews
• Concepts and Strategies– Secure Code Reviews in the SDLC– Threat Modeling– Methodology– Coding Mistakes – Tools
• Tips And Tricks• Resources
33rd CSI Conference, Orlando, Florida
8
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Secure Code Reviews in the SDLC
33rd CSI Conference, Orlando, Florida
9
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Code reviews in the Software Security Life Cycle
The economics of security defects
33rd CSI Conference, Orlando, Florida
10
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Agenda• Introduction
– What Secure Code Reviews Are Not– Why We Need Secure Code Reviews ?– Code Reviews
• Concepts and Strategies– Secure Code Reviews in the SDLC– Threat Modeling– Methodology– Coding Mistakes – Tools
• Tips And Tricks• Resources
33rd CSI Conference, Orlando, Florida
11
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Methodology – Secure Code Review Process1. Build a Threat Model
– Identify, evaluate and mitigate risks for the particular application
2. Build an Attack Plan– Prioritize threats based on criticality– Map threats to code artifacts– Determine which high risk areas to focus the efforts
based upon man-hours and costs3. Code Review
– Document each vulnerability under bugs or flaws– Review each section of the code for vulnerability
categories
33rd CSI Conference, Orlando, Florida
12
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
What Is Threat Modeling?• Goal: Identify the threats against the system and
the appropriate countermeasures to mitigate the risk they pose
• Model the system as an attacker will see it:• Where are the entry points?• Which assets are targets?
• Recognize the attacker’s advantage and defender’s dilemma:
• Developers need to get the code 100 % correct, 100% of the time with limited resources and development time
• Attackers need to find just one hole and can spend as much time finding it as they want
33rd CSI Conference, Orlando, Florida
13
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Methodology - Secure Code Reviews Best Practices• Have clear goals
– Tactical and strategic scenarios (e.g. new release vs. production)– Be specific on what must be accomplished
• Decide which analysis style works best– Depth first vs. breadth first approach
• Prioritize and simplify– Prioritize based upon critical areas– Break system complexity
• Be methodical– Annotate the code you are reviewing (e.g. comments, IDE task
lists)– Use checklists
33rd CSI Conference, Orlando, Florida
14
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Methodology - Secure Code Reviews
• Reduce complexity– Threat modeling– Rapid scan
• Review critical sections of the code– Correlate and annotate – Use IDE tools (e.g. Visual Studio, Eclipse)
• Categorize security defects– Threat categorization– Check lists– Bugs vs. flaws
33rd CSI Conference, Orlando, Florida
15
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Methodology - Security Defects Categorization
Can be categorized as:• Security Bugs
– An implementation level software security problem (e.g. buffer overflows, SQL injection)
• Security Flaws– A design level software security problem (e.g.
an insecure authorization model or data access layer)
33rd CSI Conference, Orlando, Florida
16
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Methodology - Threat Categorization
Un-secure code because of the following threats:• STRIDE: Spoofing, Tampering, Repudiation,
Information Disclosure, Denial of Service, and Elevation of Privilege
Secure code by mapping to security controls:• CIA: Confidentiality, Integrity, Availability
33rd CSI Conference, Orlando, Florida
17
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Methodology - Security Frame Categorization
• Configuration Management– Issues stemming from insecure deployment and administration
• Data Protection in Storage and Transit– Lack of adequate protection for secrets and other sensitive data
• Authentication– Lack of strong protocols to verify the identity of a component
outside the trust boundary• Authorization
– Lack of mechanisms to enforce access controls on protected resources within the system
33rd CSI Conference, Orlando, Florida
18
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Methodology – Security Frame Categorization
• User and Session Management– Lack of mechanisms to maintain session independence between
multiple logged-on users and insecure user provisioning and de-provisioning policies
• Data Validation– Lack of input and output validation when data crosses system or
trust boundaries• Error handling and Exception Management
– Failure to deal with exceptions effectively and in a secure manner, resulting unauthorized disclosure of information
• Logging and Auditing– Failure to maintain detailed and accurate application logs that can
allow for traceability and non-repudiation
33rd CSI Conference, Orlando, Florida
19
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Methodology - Secure Code Review Findings
• Sections:– Bug vs. Flaws– Threat Categorization– Risk Rating– Module and LOC range– Code Snippet– Commendation or Recommendation
• Recommendations are often not limited to the code but also the design and the deployment environment as well!
33rd CSI Conference, Orlando, Florida
20
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Agenda• Introduction
– What Secure Code Reviews Are Not– Why We Need Secure Code Reviews ?– Code Reviews
• Concepts and Strategies– Secure Code Reviews in the SDLC– Threat Modeling– Methodology– Coding Mistakes– Tools
• Tips And Tricks• Resources
33rd CSI Conference, Orlando, Florida
21
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Configuration Management
1. # credentials for the application database2. datasource.name=jdbc_13. datasource.url=jdbc:oracle:thin:@dhs:1521:ORA14. datasource.classname=oracle.jdbc.driver.OracleDriver5. datasource.username=scott
6. datasource.password=tiger
33rd CSI Conference, Orlando, Florida
22
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Configuration Management
1. <pages validateRequest=“false”/>2. <!– DYNAMIC DEBUG COMPILATION……..…-->
3. <compilation defaultLanguage=“c#” debug=“true”/> 4. <!– CUSTOM ERROR MESSAGES……-- >
5. <customErrors mode=“Off”/>6. <!– APPLICATION-LEVEL TRACE LOGGING….. -- >
7. <trace enabled=“true” requiredLimit=“10”pageOutpur=“true”tracemode=“SortByTime”localOnly=“false”/>
33rd CSI Conference, Orlando, Florida
23
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Data Protection in Storage and Transit1.final public static byte key[] =2.{(byte) 0x31, (byte) 0xAB, (byte) 0x05, (byte) 0xF7,3.(byte) 0x45, (byte) 0x65, (byte) 0x98, (byte) 0xAB};
4.try 5.{6. encryptor.setKey(key);7. plainText = new String(encryptor.decrypt(text));8.}9.catch (Throwable te) 10.{11. […]12.}
33rd CSI Conference, Orlando, Florida
24
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Data Protection in Storage and Transit
1.public static String digest(String password) {2.MessageDigest md5 =MessageDigest.getInstance(“MD5");3. byte[] hash = md5.update(password.getBytes());4. return makeStringFromBytes(hash);}
5.public static String makeStringFromBytes(byte[] bytes) {
6. String result = ""; 7. for (int i=0; i<bytes.length; ++i) {8. int n = bytes[i];9. result = result + " " + Integer.toHexString(n);
}10. return result;}
33rd CSI Conference, Orlando, Florida
25
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Authentication1. Http Cookie MyCookie;2. MyCookie = Request.Cookies [“CookiesLoginAttempts”];3. MyCookie.Expires=now.AddHours(10);4. //decrement5. int
logInAtt=Convert.ToInt32(MyCookie.Value.ToString());6. CookieVal=int.Parse (MyCookie.Value.ToString());7. If (CookieVal >0)8. CookieVal-=1;9. //store in response cookie10. HttpCookie AttemptCntCookie = new HttpCookie
(“CookieLoginAttempts”);11. AttemptCntCookie.Value =CookieVal.ToString();
33rd CSI Conference, Orlando, Florida
26
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Authorization1. <input value=”true” type=”HIDDEN”
bean=”thisFormHandler.verifyCreditCardNumber”/>2. <input value=”true” type=”HIDDEN”3. bean=”thisFormHandler.validatePrice”/>4. <FORM method=post action="http://www.acme.com/cgi-
bin/shop/shoppingcart.exe/products/telephonedevices">
5. <b><font size="5">Sale Price $169.95!</font></b><BR>
6. <input type="HIDDEN" name="ID" value="PESL100">7. <input type="HIDDEN" name="Describe" 8. value="Pro Series Telephone Analyzer">9. <input name="Qty" size=3 value=""> Quantity <BR>10.<input type="HIDDEN" name="Price" VALUE="169.95">
33rd CSI Conference, Orlando, Florida
27
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Authorization1. if (sess.getCurrentUser().isCSR()) {2. URLList.add(“View Customer Details",3. "/jsp/Customer.do?action=view&id=“ + custId));4. URLList.add(“Edit Customer Details",5. "/jsp/Customer.do? action=edit&id=“ + custId));6. URLList.add(“Delete Customer",7. "/jsp/Customer.do?action=delete&id=“ +
custId));8. } else {
9. URLList.add(“View Customer Details",10. "/jsp/Customer.do?action=view&id=“ + custId));
11. }
33rd CSI Conference, Orlando, Florida
28
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - User and Session Management1. HTTP/1.1 302 Found2. Date: Tue, 21 Feb 2006 19:16:08 GMT3. Server: Apache/2.0.46 (Red Hat)4. Accept-Ranges: bytes5. X-Powered-By: PHP/4.3.26. Expires: Thu, 19 Nov 1981 08:52:00 GMT7. Cache-Control: no-store, no-cache, must-revalidate, post-
check=0, pre-check=08. Pragma: no-cache
9. Set-Cookie: userid=mmorana; expires=Thu, 01-Jun-2006 19:16:08 GMT; path=/
10.Set-Cookie: password=xxxxxxx; expires=Thu, 01-Jun-2006 19:16:08 GMT; path=/
11.Set-Cookie: communityid=202; expires=Thu, 01-Jun-2006 19:16:08 GMT; path=/
33rd CSI Conference, Orlando, Florida
29
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Data Validation
1. public List getProductsByTitleKeyWords(String[] keywords)
2. {3. JdbcTemplate jt = new JdbcTemplate(getDataSource());
4. String query = "select * from products where "+ createCriteria(keywords);
5. List list = jt.query(query, new
6. ProductRowMapper());7. Iterator iter = list.iterator();8. while (iter.hasNext()) {
Product prod = (Product) iter.next();9. prod.setFeedback(getFeedBacks(prod));10. }11. return list;12. }
33rd CSI Conference, Orlando, Florida
30
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Error Handling And Exception Handling
1. try2. { 3. ElevatePrivilege(); 4. ReadSecretFile();5. LowerPrivilege();6. }7. catch(Exception e)8. {9. ReportException();10. }
33rd CSI Conference, Orlando, Florida
31
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Error Handling And Exception Handling
Error Message:executeRSProcedure Exception:Java.sql.SQLException: ORA-
06502:PL/SQL:numeric or value error: character to number conversion error
Server Name: host1.acme.comServer Info: IBM WebSphere Application
Server/5.1Remote Address: 192.168.12.34
33rd CSI Conference, Orlando, Florida
32
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Error Handling And Exception Handling
• “The password is invalid for the account”
• “The username does not exist”• “The DOB you entered is invalid”• “Your account has been locked due to too
many invalid attempts”
33rd CSI Conference, Orlando, Florida
33
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Coding Mistakes - Logging And Auditing1. private void btnLogin_Click(object
sender, System.EventArgs e) {2. //..3. LogString(“User” + txtUserName.Text + “
with password “ + txtPassword.Text + “logged in at “+ DateTime.Now.ToString());
4. //..5. DataSet ds = GetUserTable();6. //..7. Logdata(ds);8. //..9. }
33rd CSI Conference, Orlando, Florida
34
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Agenda• Introduction
– What Secure Code Reviews Are Not– Why We Need Secure Code Reviews ?– Code Reviews
• Concepts and Strategies– Secure Code Reviews in the SDLC– Threat Modeling– Methodology– Coding Mistakes– Tools
• Tips And Tricks• Resources
33rd CSI Conference, Orlando, Florida
35
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Tools - Tools for Static Code Analysis
Advantages:• Perform preliminary scanning of large code
sets in little time• Provide consistent results• Can be used as secure code check-in gateway• Identify common coding bugs (low hanging
fruits)
33rd CSI Conference, Orlando, Florida
36
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Tools - Tools for Static Code Analysis
Common bugs identified by static parsers:• Un-secure functions• Lack of proper input validation and output
filtering• Weak crypto algorithms• Exception handling errors• Hard coded passwords, keys, connection strings
33rd CSI Conference, Orlando, Florida
37
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Tools - Tools for Static Code Analysis
Disadvantages:• Do not identify security flaws• Generate a large amount of false positives• Provide a false sense of securityExamples:• ITS4• RATS• FlawFinder• CodeAssure• PreFIX/PreFAST• Foundstone CodeScout
33rd CSI Conference, Orlando, Florida
38
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Tools - Tools for Dynamic Analysis
Advantages:• Integrate with Debuggers and IDE• Monitor Access to Resources (Files, Libraries, Data,
Registry Keys)• Monitor Network Access• Help Identify Data FlowsExamples:• CLR Profiler• NProf• Sysinternals Tools – FileMon, RegMon• Foundstone .NETMon
33rd CSI Conference, Orlando, Florida
39
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Tips And Tricks1. Have a plan
– Focus on clear objectives– Organize the team– Review incrementally
2. Follow a methodology – Identify threats and countermeasures– Use vulnerability check lists and tools– Categorize security defects
33rd CSI Conference, Orlando, Florida
40
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Tips And Tricks3. Integrate With Other Activities in the S-SDLC
– Information risk management– Metrics and measurements– Training and awareness
4. Revise the Plan and the Process– Threats and vulnerabilities– New techniques– People, process and technology
33rd CSI Conference, Orlando, Florida
41
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Questions ?
33rd CSI Conference, Orlando, Florida
42
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Resources• Software Security Code Review: Code Inspection
Finds Problems, R. Araujo and M. Curphey– http://www.softwaremag.com
• A Process for Performing Security Code Reviews, M. Howard– http://www.computer.org
• How To: Perform a Security Code Review for Managed Code, Microsoft Patterns & Practices– http://msdn.microsoft.com
33rd CSI Conference, Orlando, Florida
43
Marco MoranaSecure Code Reviews
DEV-7 November 7th, 2006
Contact Information • Presenter Email:
– [email protected]• Foundstone Software Application Security
Services (SASS) – www.foundstone.com/sass
• Foundstone Training– www.foundstone.com/education