You are on page 1of 59

Secure Coding

2008 Census Bureau Software Process Improvement Conference


Robert C. Seacord

2008 Carnegie Mellon University

Agenda
Software Security CERT Secure Coding Initiative CERT Secure Coding Standards Top 10 Secure Coding Practices

Why Software Security?


Developed nations economies and defense depend, in large part, on the reliable execution of software Software 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

Increasing Vulnerabilities
Reacting to vulnerabilities in existing systems is not working

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
5

Vulnerabilities Cost Vendors


A study based on real vulnerability announcements in 19992004 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

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 attack The ability of software to recognize, resist, tolerate, and recover from events that threaten it Goal: Better, defect-free software that can function more robustly in its operational production environment
7

Application Security

Sources of Software Insecurity 1


Complexity, inadequacy, and change Incorrect or changing assumptions (capabilities, inputs, outputs) Flawed specifications & designs Poor implementation of software interfaces (input validation, error & exception handling) Inadequate knowledge of secure coding practices

Sources of Software Insecurity 2


Unintended, unexpected interactions
with other components with the softwares execution environment

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

10

Most Vulnerabilities caused by Programming Errors


64% 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
11

Coding Securely May Be Harder Than You Think! char x, y; x = -128; y = -x; if if if if if (x == y) puts("1"); ((x - y) == 0) puts("2"); ((x + y) == 2 * x) puts("3"); (((char)(-x) + x) != 0) puts("4"); (x != -y) puts("5");

12

W32.Blaster.Worm
Infected 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.

13

Blaster Timeline (2003)


RPC Vulnerability discovered by Last Stage of Delirium (LSD) July 25: Xfocus releases exploit August 2-3: Defcon hacker convention August 12: 336,000 computers infected

July 16: Microsoft releases security bulletin

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

August 11: Blaster discovered spreading through the Internet August 14: Over 1 million computers infected

July 17: CERT issues advisory

14

How Blaster Works


Checks 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.

15

Flawed Logic Exploited by Blaster


HRESULT 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; Unbounded string copy LPWSTR pwszTemp = pwszPath + 2; while ( *pwszTemp != L'\\' ) *pwszServerName++ = *pwszTemp++; ... }
16

Unexpected Integer Values


An unexpected value is not one you would expect to get using a pencil and paper
Unexpected values are a common source of software vulnerabilities (even when this behavior is correct).

17

Bourne Again Shell 1


GNUs 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.

18

Bourne Again Shell 2


Bash 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.

19

Bourne Again Shell 3


As 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 twos 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.

20

Bourne Again Shell 4


The 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.

21

Integer Security
Integers 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

22

Agenda
Software Security CERT Secure Coding Initiative CERT Secure Coding Standards Top 10 Secure Coding Practices

23

CERT Vulnerability Analysis

24

CERT Secure Coding Initiative


Work 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 dont make the software you use, we make the software you use run slower.
25

Overall Thrusts
Advance the state of the practice in secure coding Identify common programming errors that lead to software vulnerabilities Establish standard secure coding practices Educate software developers

26

Current Capabilities
Secure Coding in C and C++
Addison-Wesley book Training

Secure coding web pages www.cert.org/secure-coding/ Secure string and integer library development Involvement in international standards activities:
ISO/IEC JTC1/SC22/WG14 C programming language

international standardization working group


ISO/IEC JTC1/SC22 OWG Vulnerabilities

27

Current and Planned Efforts


CERT 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


28

CMU CS 15392 Secure Programming


Offered 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

29

Secure Coding in C/C++ Training


Secure 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

30

Agenda
Software Security CERT Secure Coding Initiative CERT Secure Coding Standards Top 10 Secure Coding Practices

31

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

32

Scope
The 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.

33

Secure Coding Web Site (Wiki)

34

Rules
Coding 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.

35

36

MEM31-C. Compliant Solution

37

Recommendations
Coding 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.

38

MEM00-A. Allocate and free memory in the same module, at the same level of abstraction
Allocating 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 .

39

Non-Compliant Coding Example


void func2(int *list, size_t list_size) { if (size < MIN_SIZE) { If unable to process, list is freed, and free(list); the function returns. return; } If the number of elements in the array is greater /* Process list */ than MIN_SIZE, the array is processed. } void func1 (size_t number) { Array of integers is int *list = malloc(number * sizeof(int)); allocated. if (list == NULL) { /* Handle Allocation Error */ The array and its } size are passed to func2(list, number); func2(). /* Continue Processing list */ free(list); } If the error occurs in func2(), memory referred to by list is freed twice: once in func2() and again in func1()
40

Compliant Solution
void func2(int *list, size_t list_size) { if (size < MIN_SIZE_ALLOWED) { /* Handle Error Condition */ return; } Eliminated free() /* Process list */ in support function. } 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); }

call

41

10

15

20

25

30

35

Preprocessor (PRE) Declarations and Expressions (EXP) Integers (INT) Floating Point (FLP) Arrays (ARR) Strings (STR) Memory Input Output (FIO) Temporary Files Environment (ENV) Signals (SIG) Miscellaneous (MSC) POSIX

C Rule/Recommendation Distribution

77 Rules

99 Recommendations

42

Community Development Process


Rules are solicited from the community Published as candidate rules and recommendations on the CERT Wiki at: www.securecoding.cert.org

Threaded discussions used for public vetting Candidate coding practices are moved into a secure coding standard when consensus is reached

43

Priorities and Levels


High severity, likely, inexpensive to repair flaws L1 P12-P27

L2 P6-P9

L3 P1-P4

Med severity, probable, med cost to repair flaws

Low severity, unlikely, expensive to repair flaws

44

FIO30-C. Exclude user input from format strings

45

CERT Mitigation Information


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

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 .
46

Secure Coding Standard Applications


Establish 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 coding Establish requirements for software analysis tools Certify software systems
47

Software Validation & Verification


Implementing 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

48

Agenda
Software Security CERT Secure Coding Initiative CERT Secure Coding Standards Top 10 Secure Coding Practices

49

Top 10 Secure Coding Practices


1.

2.

3.

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]. Heed compiler warnings. Compile code using the highest warning level available for your compiler and eliminate warnings by modifying the code. 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.
50

Top 10 Secure Coding Practices


4.

5.

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. 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].
51

Top 10 Secure Coding Practices


6.

7.

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]. 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.
52

Top 10 Secure Coding Practices


8.

9.

10.

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]. 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]. Adopt a secure coding standard. Develop and/or apply a secure coding standard for your target development language and platform.

53

Bonus Secure Coding Practices


1.

2.

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. 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].

54

Future Directions
Continue to develop and enhance existing secure coding standards and associated checkers Develop secure coding standards for other languages and programming environments
Java Web Development Language independent Ada, SPARK

Develop secure coding design patterns

55

Key Points
Everyday 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.

56

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.
57

Questions
58

For More Information


Visit CERT web sites:
http://www.cert.org/secure-coding/ https://www.securecoding.cert.org/

Contact Presenter
Robert C. Seacord rcs@cert.org

Contact CERT Coordination Center:


Software Engineering Institute Carnegie Mellon University 4500 Fifth Avenue Pittsburgh PA 15213-3890 USA

Hotline: +1 412 268 7090 CERT/CC personnel answer 24x7, 365 days per year Fax: +1 412 268 6989
Mailto: cert@cert.org

59

You might also like