developing secure code robert seacord

59
© 2008 Carnegie Mellon University Secure Coding 2008 Census Bureau Software Process Improvement Conference Robert C. Seacord

Upload: giap-le

Post on 31-Dec-2015

89 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Developing Secure Code Robert Seacord

© 2008 Carnegie Mellon University

Secure Coding

2008 Census Bureau Software Process Improvement Conference

Robert C. Seacord

Page 2: Developing Secure Code Robert Seacord

2

AgendaSoftware SecurityCERT Secure Coding InitiativeCERT Secure Coding StandardsTop 10 Secure Coding Practices

Page 3: Developing Secure Code Robert Seacord

3

Why Software Security? Developed nations’ economies and defense depend, in large part, on the reliable execution of softwareSoftware is ubiquitous, affecting all aspects of our personal and professional lives.Software vulnerabilities are equally ubiquitous, jeopardizing:

• Personal identities• Intellectual property• Consumer trust• Business services, operations,

& continuity• Critical infrastructures & government

Page 4: Developing Secure Code Robert Seacord

4

Increasing VulnerabilitiesReacting to vulnerabilities in existing systems is not working

Page 5: Developing Secure Code Robert Seacord

5

Deloitte 2007 Global Security Survey• Finding #3: Application security:

generic countermeasures are no longer adequate

• Applications are the primary gateway to sensitive data

• 87% of respondents: poor software development quality is a top threat in the next 12 months

• Application security is the #1 issue for CIOs (Gartner)

Deloitte 2007 Global Security Survey: The Shifting Security Paradigm. Deloitte, September 2007. http://www.deloitte.com/dtt/cda/doc/content/dtt_gfsi_GlobalSecuritySurvey_20070901(1).pdf

Page 6: Developing Secure Code Robert Seacord

6

Vulnerabilities Cost Vendors

A study based on real vulnerability announcements in 1999- 2004 revealed: an average drop of the concerned vendor's stock price of 0.6% after each vulnerability announcement

— Tehang / Wattal, Carnegie Mellon Univerisity, 2004

"Impact of Software Vulnerability Announcements on the Market Value of Software Vendors – an Empirical Investigation"

... not to mention the damage to the vendor's reputation

Page 7: Developing Secure Code Robert Seacord

7

So What Is Software Security?Not the same as security software

• Firewalls, intrusion detection, encryption• Protecting the environment within which the software

operates

Engineering software so that it continues to function under attackThe ability of software to recognize, resist, tolerate, and recover from events that threaten itGoal: Better, defect-free software that can function more robustly in its operational production environment

Page 8: Developing Secure Code Robert Seacord

8

Application Security

Page 9: Developing Secure Code Robert Seacord

9

Sources of Software Insecurity 1Complexity, inadequacy, and changeIncorrect or changing assumptions (capabilities, inputs, outputs)Flawed specifications & designsPoor implementation of software interfaces (input validation, error & exception handling)Inadequate knowledge of secure coding practices

Page 10: Developing Secure Code Robert Seacord

10

Sources of Software Insecurity 2Unintended, unexpected interactions

• with other components• with the software’s execution environment

Absent or minimal consideration of security during all life cycle phasesNot thinking like an attacker

Page 11: Developing Secure Code Robert Seacord

11

Most Vulnerabilities caused by Programming Errors64% of the vulnerabilities in NVD in 2004 are due to programming errors

• 51% of those due to classic errors like buffer overflows, cross-site-scripting, injection flaws

• Heffley/Meunier (2004): Can Source Code Auditing Software Identify Common Vulnerabilities and Be Used to Evaluate Software Security?

Cross-site scripting, SQL injection at top of the statistics (CVE, Bugtraq) in 2006“We wouldn't need so much network security if we didn't have such bad software security”

--Bruce Schneier

Page 12: Developing Secure Code Robert Seacord

12

Coding Securely May Be Harder Than You Think!

char x, y; x = -128; y = -x;

if (x == y) puts("1"); if ((x - y) == 0) puts("2");

if ((x + y) == 2 * x) puts("3");

if (((char)(-x) + x) != 0) puts("4");

if (x != -y) puts("5");

Page 13: Developing Secure Code Robert Seacord

13

W32.Blaster.WormInfected unpatched system connected to the Internet without user involvement.At least eight million Windows systems have been infected by this worm [Lemos 04].Exploits a vulnerability in the DCOM RPC interface of Windows.Propagates via TCP/IP.Economic damage estimated to be at least $525 million.

Page 14: Developing Secure Code Robert Seacord

14

Blaster Timeline (2003)

August 11: Blaster discovered spreading through the Internet

July 16: Microsoft releases security bulletin

July 25: Xfocus releases exploit

August 2: Indications of attacks sent through Internet Relay Chat (IRC) networks discovered

RPC Vulnerability discovered by Last Stage of Delirium (LSD)

August 12: 336,000 computers infected

August 14: Over 1 million computers infected

August 2-3: Defcon hacker convention

July 17: CERT issues advisory

Page 15: Developing Secure Code Robert Seacord

15

How Blaster WorksChecks to see if the computer is already infected.Runs when Windows starts. Generates a random IP address. Attempts to infect the computer with that address.Sends data on TCP port 135 to exploit the DCOM RPC vulnerability on either Windows XP or Windows 2000.

Page 16: Developing Secure Code Robert Seacord

16

Flawed Logic Exploited by BlasterHRESULT GetServerPath(

WCHAR *pwszPath, WCHAR **pwszServerPath ) {WCHAR *pwszFinalPath = pwszPath;WCHAR wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN+1];hr = GetMachineName(pwszPath, wszMachineName);*pwszServerPath = pwszFinalPath;

}HRESULT GetMachineName(WCHAR *pwszPath,WCHAR wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN+1]) {

pwszServerName = wszMachineName;LPWSTR pwszTemp = pwszPath + 2;while ( *pwszTemp != L'\\' )

*pwszServerName++ = *pwszTemp++;...

}

Unbounded string copy

Page 17: Developing Secure Code Robert Seacord

17

Unexpected Integer Values

Unexpected values are a common source of software vulnerabilities (even when this behavior is correct).

An unexpected value is not one you would expect to get using a pencil and paper

Page 18: Developing Secure Code Robert Seacord

18

Bourne Again Shell 1GNU’s Bourne Again Shell (bash) is a drop-in replacement for the Bourne shell (/bin/sh).

• same syntax as the standard shell but provides additional functionality such as job control, command-line editing, and history.

• most prevalent use is on Linux.

A vulnerability exists in bash versions 1.14.6 and earlier where bash can be tricked into executing arbitrary commands.

Page 19: Developing Secure Code Robert Seacord

19

Bourne Again Shell 2Bash contains an incorrectly declared variable in the yy_string_get() function responsible for parsing the user-provided command line into separate tokens. The error involves the variable string, which has been declared to be of type char *.The string variable is used to traverse the character string containing the command line to be parsed.

Page 20: Developing Secure Code Robert Seacord

20

Bourne Again Shell 3As characters are retrieved from this pointer, they are stored in a variable of type int.For compilers in which the char type defaults to signed char, this value is sign-extended when assigned to the int variable. For character code 255 decimal (-1 in two’s complement form), this sign extension results in the value -1 being assigned to the integer.-1 is used in other parts of the parser to indicate the end of a command.

Page 21: Developing Secure Code Robert Seacord

21

Bourne Again Shell 4The character code 255 decimal (377 octal) serves as an unintended command separator for commands given to bash via the -c option. Example:

• bash -c 'ls\377who'

(where \377 represents the single character with value 255 decimal) executes two commands, ls and who.

Page 22: Developing Secure Code Robert Seacord

22

Integer SecurityIntegers represent a growing and underestimated source of vulnerabilities in programs.Integer range checking has not been systematically applied in the development of most software.

• security flaws involving integers exist• a portion of these are likely to be vulnerabilities

Page 23: Developing Secure Code Robert Seacord

23

AgendaSoftware SecurityCERT Secure Coding InitiativeCERT Secure Coding StandardsTop 10 Secure Coding Practices

Page 24: Developing Secure Code Robert Seacord

24

CERT Vulnerability Analysis

Page 25: Developing Secure Code Robert Seacord

25

CERT Secure Coding InitiativeWork with software developers and software development organizations to eliminate vulnerabilities resulting from coding errors before they are deployed.

• Reduce the number of vulnerabilities to a level where they can be handled by computer security incident response teams (CSIRTs)

• Decrease remediation costs by eliminating vulnerabilities before software is deployed

We don’t make the software you use, we make the software you use run slower.

Page 26: Developing Secure Code Robert Seacord

26

Overall ThrustsAdvance the state of the practice in secure codingIdentify common programming errors that lead to software vulnerabilitiesEstablish standard secure coding practicesEducate software developers

Page 27: Developing Secure Code Robert Seacord

27

Current CapabilitiesSecure Coding in C and C++

• Addison-Wesley book• Training

Secure coding web pages www.cert.org/secure-coding/Secure string and integer library developmentInvolvement in international standards activities:

• ISO/IEC JTC1/SC22/WG14 C programming language international standardization working group

• ISO/IEC JTC1/SC22 OWG Vulnerabilities

Page 28: Developing Secure Code Robert Seacord

28

Current and Planned EffortsCERT Secure Coding Standards

• C and C++ Programming Language• Community development process

Training courses• Direct offerings• Partnered with industry

Software Validation and Verification• Partner with software tool vendors to validate

conformance to secure coding standards• Partner with software development organizations to

evaluate the application of secure coding standards

Page 29: Developing Secure Code Robert Seacord

29

CMU CS 15392 Secure ProgrammingOffered as an undergraduate elective in the School of Computer Science in S07 and S08

• More of a vocational course than an “enduring knowledge” course.

• Students are interested in taking a class that goes beyond “policy”

Course page including lecture slides (PDF):www.securecoding.cert.org/confluence/display/sci/15392+Secure+Program ming

Page 30: Developing Secure Code Robert Seacord

30

Secure Coding in C/C++ TrainingSecure Coding in C and C++ provides practical guidance on secure programming

• provides a detailed explanation of common programming errors

• describes how errors can lead to vulnerable code• evaluates available mitigation strategies

Useful to anyone involved in developing secure C and C++ programs regardless of the application

Page 31: Developing Secure Code Robert Seacord

31

AgendaSoftware SecurityCERT Secure Coding InitiativeCERT Secure Coding StandardsTop 10 Secure Coding Practices

Page 32: Developing Secure Code Robert Seacord

32

CERT Secure Coding Standards

Identify coding practices that can be used to improve the security of software systems under development

Coding practices are classified as either rules or recommendations

• Rules need to be followed to claim compliance.• Recommendations are guidelines or suggestions.

Development of Secure Coding Standards is a community effort

Page 33: Developing Secure Code Robert Seacord

33

ScopeThe secure coding standards proposed by CERT are based on documented standard language versions as defined by official or de facto standards organizations. Secure coding standards are under development for:

• C programming language (ISO/IEC 9899:1999) • C++ programming language (ISO/IEC 14882-2003 )

Applicable technical corrigenda and documented language extensions such as the ISO/IEC TR 24731 extensions to the C library are also included.

Page 34: Developing Secure Code Robert Seacord

34

Secure Coding Web Site (Wiki)

Page 35: Developing Secure Code Robert Seacord

35

RulesCoding practices are defined as rules when

• Violation of the coding practice will result in a security flaw that may result in an exploitable vulnerability.

• There is an enumerable set of exceptional conditions (or no such conditions) where violating the coding practice is necessary to ensure the correct behavior for the program.

• Conformance to the coding practice can be verified.

Page 36: Developing Secure Code Robert Seacord

36

Page 37: Developing Secure Code Robert Seacord

37

MEM31-C. Compliant Solution

Page 38: Developing Secure Code Robert Seacord

38

RecommendationsCoding practices are defined as recommendations when

• Application of the coding practice is likely to improve system security.

• One or more of the requirements necessary for a coding practice to be considered as a rule cannot be met.

Page 39: Developing Secure Code Robert Seacord

39

MEM00-A. Allocate and free memory in the same module, at the same level of abstractionAllocating and freeing memory in different modules and levels of abstraction burdens the programmer with tracking the lifetime of that block of memory. This may cause confusion regarding when and if a block of memory has been allocated or freed, leading to programming defects such as double-free vulnerabilities, accessing freed memory, or writing to unallocated memory.To avoid these situations, it is recommended that memory be allocated and freed at the same level of abstraction, and ideally in the same code module.Freeing memory in different modules resulted in a vulnerability in MIT Kerberos 5 MITKRB5-SA-2004-002 .

Page 40: Developing Secure Code Robert Seacord

40

Non-Compliant Coding Examplevoid func2(int *list, size_t list_size) {if (size < MIN_SIZE) {free(list);return;

}/* Process list */

}

void func1 (size_t number) {int *list = malloc(number * sizeof(int));if (list == NULL) {/* Handle Allocation Error */

}func2(list, number);/* Continue Processing list */free(list);

}

Array of integers is allocated.

The array and its size are passed to func2().

If the number of elements in the array is greater than MIN_SIZE, the array is processed.

If unable to process, list is freed, and the function returns.

If the error occurs in func2(), memory referred to by list is freed twice: once in func2() and again in func1()

Page 41: Developing Secure Code Robert Seacord

41

Compliant Solutionvoid func2(int *list, size_t list_size) {if (size < MIN_SIZE_ALLOWED) {

/* Handle Error Condition */return;

}/* Process list */

}

void func1 (size_t number) {int *list = malloc (number * sizeof(int));if (list == NULL) {/* Handle Allocation Error */

}func2(list,number);/* Continue Processing list */free(list);

}

Eliminated free() call in support function.

Page 42: Developing Secure Code Robert Seacord

42

0

5

10

15

20

25

30

35

Prep

roce

ssor

(PR

E)

Dec

lara

tions

and

Expr

essi

ons

(EXP

)

Inte

gers

(IN

T)

Floa

ting

Poin

t (FL

P)

Arra

ys (A

RR

)

Strin

gs (S

TR)

Mem

ory

Inpu

t Out

put (

FIO

)

Tem

pora

ry F

iles

Envi

ronm

ent (

ENV)

Sign

als

(SIG

)

Mis

cella

neou

s (M

SC)

POSI

X

C Rule/Recommendation Distribution

99 Recommendations

77 Rules

Page 43: Developing Secure Code Robert Seacord

43

Community Development Process

Published as candidate rules and recommendations on the CERT Wiki at:www.securecoding.cert.org

Rules are solicited from the community

Threaded discussions used for public vetting

Candidate coding practices are moved into a secure coding standard when consensus is reached

Page 44: Developing Secure Code Robert Seacord

44

Priorities and Levels

L3 P1-P4

L1 P12-P27

L2 P6-P9

High severity, likely, inexpensive to repair flaws

Low severity, unlikely, expensive to repair flaws

Med severity, probable, med cost to repairflaws

Page 45: Developing Secure Code Robert Seacord

45

FIO30-C. Exclude user input from format strings

Page 46: Developing Secure Code Robert Seacord

46

CERT Mitigation Information

US CERT Technical Alerts

CERT Secure Coding Standard

Examples of vulnerabilities resulting from the violation of this recommendation can be found on the CERT website .

Vulnerability Note VU#649732This vulnerability occurred as a result of failing to comply with rule FIO30-C of the CERT C Programming Language Secure Coding Standard.

Page 47: Developing Secure Code Robert Seacord

47

Secure Coding Standard ApplicationsEstablish secure coding practices within an organization

• may be extended with organization-specific rules • cannot replace or remove existing rules

Train software professionals Certify programmers in secure codingEstablish requirements for software analysis toolsCertify software systems

Page 48: Developing Secure Code Robert Seacord

48

Software Validation & VerificationImplementing checkers for various software analysis tools to verify compliance with CERT secure coding standards

• Fortify SCA• Lawrence Livermore National Laboratory (LLNL)

Compass / ROSE• Coverity Prevent

Page 49: Developing Secure Code Robert Seacord

49

AgendaSoftware SecurityCERT Secure Coding InitiativeCERT Secure Coding StandardsTop 10 Secure Coding Practices

Page 50: Developing Secure Code Robert Seacord

50

Top 10 Secure Coding Practices 1. Validate input. Validate input from all untrusted data

sources. Proper input validation can eliminate the vast majority of software vulnerabilities. Be suspicious of most external data sources, including command line arguments, network interfaces, environmental variables, and user controlled files [Seacord 05].

2. Heed compiler warnings. Compile code using the highest warning level available for your compiler and eliminate warnings by modifying the code.

3. Architect and design for security policies. Create a software architecture and design your software to implement and enforce security policies. For example, if your system requires different privileges at different times, consider dividing the system into distinct intercommunicating subsystems, each with an appropriate privilege set.

Page 51: Developing Secure Code Robert Seacord

51

Top 10 Secure Coding Practices4. Keep it simple. Keep the design as simple and

small as possible [Saltzer 74, Saltzer 75]. Complex designs increase the likelihood that errors will be made in their implementation, configuration, and use. Additionally, the effort required to achieve an appropriate level of assurance increases dramatically as security mechanisms become more complex.

5. Default deny. Base access decisions on permission rather than exclusion. This means that, by default, access is denied and the protection scheme identifies conditions under which access is permitted [Saltzer 74, Saltzer 75].

Page 52: Developing Secure Code Robert Seacord

52

Top 10 Secure Coding Practices6. Adhere to the principle of least privilege. Every process

should execute with the the least set of privileges necessary to complete the job. Any elevated permission should be held for a minimum time. This approach reduces the opportunities an attacker has to execute arbitrary code with elevated privileges [Saltzer 74, Saltzer 75].

7. Sanitize data sent to other systems. Sanitize all data passed to complex subsystems such as command shells, relational databases, and commercial off-the-shelf (COTS) components. Attackers may be able to invoke unused functionality in these components through the use of SQL, command, or other injection attacks. This is not necessarily an input validation problem because the complex subsystem being invoked does not understand the context in which the call is made. Because the calling process understands the context, it is responsible for sanitizing the data before invoking the subsystem.

Page 53: Developing Secure Code Robert Seacord

53

Top 10 Secure Coding Practices8. Practice defense in depth. Manage risk with multiple defensive

strategies, so that if one layer of defense turns out to be inadequate, another layer of defense can prevent a security flaw from becoming an exploitable vulnerability and/or limit the consequences of a successful exploit. For example, combining secure programming techniques with secure runtime environments should reduce the likelihood that vulnerabilities remaining in the code at deployment time can be exploited in the operational environment [Seacord 05].

9. Use effective quality assurance techniques. Good quality assurance techniques can be effective in identifying and eliminating vulnerabilities. Penetration testing, fuzz testing, and source code audits should all be incorporated as part of an effective quality assurance program. Independent security reviews can lead to more secure systems. External reviewers bring an independent perspective; for example, in identifying and correcting invalid assumptions [Seacord 05].

10. Adopt a secure coding standard. Develop and/or apply a secure coding standard for your target development language and platform.

Page 54: Developing Secure Code Robert Seacord

54

Bonus Secure Coding Practices1. Define security requirements. Identify and document

security requirements early in the development life cycle and make sure that subsequent development artifacts are evaluated for compliance with those requirements. When security requirements are not defined, the security of the resulting system cannot be effectively evaluated.

2. Model threats. Use threat modeling to anticipate the threats to which the software will be subjected. Threat modeling involves identifying key assets, decomposing the application, identifying and categorizing the threats to each asset or component, rating the threats based on a risk ranking, and then developing threat mitigation strategies that are implemented in designs, code, and test cases [Swiderski 04].

Page 55: Developing Secure Code Robert Seacord

55

Future DirectionsContinue to develop and enhance existing secure coding standards and associated checkersDevelop secure coding standards for other languages and programming environments

• Java• Web Development• Language independent• Ada, SPARK

Develop secure coding design patterns

Page 56: Developing Secure Code Robert Seacord

56

Key PointsEveryday software defects cause the majority of software vulnerabilities.Software developers are not always properly trained and equipped to program securely.The result is numerous delivered defects, some of which can lead to vulnerabilities.Understanding the sources of vulnerabilities and learning to program securely is imperative to protecting the Internet and ourselves from attack.

Page 57: Developing Secure Code Robert Seacord

57

References[Saltzer 74] Saltzer, J. H. "Protection and the Control of Information Sharing in Multics." Communications of the ACM 17, 7 (July 1974): 388-402.[Saltzer 75] Saltzer, J. H. & Schroeder, M. D. "The Protection of Information in Computer Systems." Proceedings of the IEEE 63, 9 (September 1975), 1278-1308.[Seacord 05] Seacord, R. Secure Coding in C and C++. Upper Saddle River, NJ: Addison-Wesley, 2006 (ISBN 0321335724).[Swiderski 04] Swiderski, F. & Snyder, W. Threat Modeling. Redmond, WA: Microsoft Press, 2004.

Page 58: Developing Secure Code Robert Seacord

58

Questions

Page 59: Developing Secure Code Robert Seacord

59

For More InformationVisit CERT® web sites: http://www.cert.org/secure-coding/https://www.securecoding.cert.org/

Contact PresenterRobert C. Seacord [email protected]

Contact CERT Coordination Center:Software Engineering Institute

Carnegie Mellon University

4500 Fifth Avenue

Pittsburgh PA 15213-3890

USA

Hotline: +1 412 268 7090CERT/CC personnel answer 24x7, 365 days per yearFax: +1 412 268 6989Mailto: [email protected]