Download presentation
Published byGabriel Palmer Modified over 9 years ago
1
Broadening Expertise in Critical Infrastructure Protection
Defensive Programming Module Funded through NSF Grant Award # DUE Any opinions, findings, conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the National Science Foundation
2
Overview Defensive Programming Defined The Need
Common Misconceptions and Errors Best Practices Lab: You Try! Need to walk a fine line here, don’t want to confuse students by more complicated approaches
3
Defensive Programming Defined
4
What is Defensive Programming?
Writing code that should behave in a consistent and predictable manner even when presented with unexpected conditions, such as unexpected user input Programming with Murphy’s Law mind, and therefore defensive techniques put in place Often called “Secure Programming” Hackers can exploit these vulnerabilities Robustness
5
“The whole point of defensive programming is guarding against errors you don’t expect.” Steve McConnell, Code Complete The Need
6
Costly Mistakes Ariane 5 rocket's ill-fated first launch, 1996
Four European Space Agency spacecraft which were launched on the maiden flight of the Ariane 5 rocket, Flight 501 Causes by assertions having been turned off, which in turn caused inadequate protection from integer overflow The failure has become known as one of the most infamous and expensive software bugs in history ($370 Million) Also: Google the Mars Climate Orbiter ($327.6M)
7
Loss/Harm of Human of Life
THERAC – 25: a computer controlled radiation-therapy machine Two cancer patients received fatal overdoses of radiation Software mishandled race condition behavior of software system where the output is dependent on the sequence or timing of other uncontrollable events. Source:
8
Loss of Privacy In 2011 hackers were able to steal details of hundreds of thousands of bank accounts Hackers leapfrogged between accounts once signed in by changing the account information that was present in fields in the URL Proper security controls were missing
9
Loss of Revenue SQL injections used against retailers by their in-store price-check kiosks Converted SQL commands into bar codes, printed them out, and scanned them Could dump the entire contents of their database, and could execute commands on the database Able to change prices of high-ticket items so that they'd ring up at bargain prices at the register
10
Malicious Attacks Office 365 suffered from a serious Cross Site Scripting (XSS) vulnerability Gave access to and SharePoint content of every employee in the company Fixed by Microsoft in December 2013 Source: Video provided to show how this worked
11
Common Misconceptions and Errors
“To err is human;” Alexander Pope, Essay on Criticism Common Misconceptions and Errors
12
Common Misconceptions
Assuming the user will interact with a program/site a certain way Trusting the user and other code Assuming the best Complexity leads to better code Assuming defensive programming is very difficult If you don’t have time to do it right the first time, where are you going to get time the second time? User input is the biggest danger, assume the worst Simple is clearer, more transparent, remove layers that provide abstraction Requires awareness and attention to detail
13
CWE/SANS Top 25 Most Dangerous Software Errors
Accessed July 31st, What Is CWE? Targeted to developers and security practitioners, the Common Weakness Enumeration (CWE) is a formal list of software weakness types created to: Serve as a common language for describing software security weaknesses in architecture, design, or code. Serve as a standard measuring stick for software security tools targeting these weaknesses. Provide a common baseline standard for weakness identification, mitigation, and prevention efforts.
14
Common Programming Error #1
Lack of input validation and sanitization #1 security issue Resulting in several vulnerabilities buffer overflows, SQL and command injections, Cross-Site Scripting (XSS), to name a few Image source: Also information disclosure, DoS attacks, memory leakage Simple XSS Attack
15
Vulnerability: Cross Site Scripting (XSS)
Image Source:
16
Vulnerability: SQL Injection
Common application layer attack techniques used today Takes advantage of improper coding that allows hacker to inject SQL commands Provides ability to view, modify, add, and delete data SELECT * FROM logins WHERE username = ‘$username’ AND password = ‘$password’ Instead becomes WHERE username = ‘` OR 1=1; /*’ AND password = ‘*/--’
17
Vulnerability: OS Command Injection
This example code intends to take the name of a user and list the contents of that user's home directory. // Example Language: PHP $userName = $_POST["user"]; $command = 'ls -l /home/' . $userName; system($command); If $userName variable is not checked for malicious input an arbitrary OS command could be entered. ;rm -rf / Which would result in $command being: ls -l /home/;rm -rf / /* the OS would first execute the ls command, then the rm command, deleting the entire file system */ (taken directly from, only very slightly modified)
18
Vulnerability: Buffer Overflow Example
strcpy writes entire string, overwriting whatever is after the destination string strncpy truncates to the correct length, but with a terminating null character (next character might be read as part of the string) strlcpy truncates and adds terminating null character X
19
Vulnerability: Buffer Overflow Example (cont’d)
strcpy writes entire string, overwriting whatever is after the destination string strncpy truncates to the correct length, but without a terminating null character (next character might be read as part of the string) strlcpy truncates and adds terminating null character X
20
Vulnerability: Buffer Overflow Example (cont’d)
strcpy writes entire string, overwriting whatever is after the destination string strncpy truncates to the correct length, but without a terminating null character (next character might be read as part of the string) strlcpy truncates and adds terminating null character X
21
About Input Validation
Critical to application security Process of validating all input to an application before using the input Two common approaches Blacklist validation: detect unauthorized input like attack characters and patterns Whitelist validation (best way!): compare input against list of all authorized input often using regular expressions (specify type, length, and range of values) # 2 is difficult to use with free text fields but is the preferred method Blacklist is considered a weaker approach (incomplete usually and requires updates)
22
Poor Input Validation Example
See Note common issues: Users can enter nothing, negative values, error values, and inject scripts (Note: jsfiddle has defenses in place against XSS so a simple <script> alert(“hello”) </script> will not get injected here)
23
Poor Input Validation Example
See Note common issues: User can exceed value for data type, cause memory overflow
24
About Sanitization Changes the user input into an acceptable format
Two common approaches Blacklist sanitization: characters not part of approved list can be removed, encoded, or replaced Whitelist sanitization (best way!): eliminate or translate characters in an effort to make input safe Image Source:
25
Good Sanitization Example
See Note that the HTML characters and treated as text by the browser, not HTML tags
26
Buffer Overflow Errors
Another problem is unchecked use of constant-size structures for dynamic-size data Use safe function calls For example, in C instead of using gets() use fgets() to read characters and instead of using strcpy() use strnlcpy() to copy the content of the buffer The problem lies in native C functions, which don't care about doing appropriate buffer length checks.
27
Common Programming Error #2
Not testing early and often Automate testing; build test cases Use unit testing and integration testing Bugs become more costly in later development phases
28
Common Programming Error #3
Unnecessarily complicated code “Complexity breeds bugs.” <?php if($userLoggedIn) { /* Hundreds of lines of code */ }else{ exit(); } ?> if(!$userLoggedIn) { /* Hundreds of lines of code */ VS
29
Common Programming Error #4
Not reusing code VS Duplication of code and data causes many problems. Both code and data tend not to be treated consistently when duplicated, e.g., changes may not be applied to all copies. Image Source: Wikipedia code example
30
Common Programming Error #5
Not heeding compiler warning Can be indicative of coding errors Gets() should also through a warning
31
Common Programming Error #6
Not considering canonicalization Canonicalization (often abbreviated as c14n, where 14 represents the number of letters between the C and the N) is a process for converting data that has more than one possible representation into a "standard", "normal", or canonical form. Example: all the following are the same: Def from wikipedia
32
Other Common Programming Errors
Not handling known errors Handle even if probability is small Not consistently handling errors Use a clear and consistent strategy Not documenting assumptions Don’t document in lieu of coding Trusting outside code Test error handling around external APIs and libraries
33
Errors Common to Threaded Environments
Deadlocks a situation where two or more threads are blocked forever, waiting for each other Image source:
34
Errors Common to Threaded Environments
Race condition occurs when two threads access a shared variable at the same time Image Source:
35
Best Practices
36
Best Practices Perform code reviews or audits
Have someone else perform the review Write with other programmers in mind Comment what you did and why Automate testing Keep it simple Follow standards Use assertions
37
Standards No magic numbers Use proper indenting
Use constants (e.g. KILOGRAMS_PER_POUND = instead of hardcoding in a formula) Use proper indenting Always write {} around compound statements Standardize error handling Add proper parenthesis for better understanding Follow coding standards (e.g. Hungarian Notation, Indian Hill C Style)
38
Assertions Assert statements provide a way of specifying that something should be true at a certain point in a program. Code will stop execution if assertion is false. Helpful in debugging and testing, but not in production code
39
Example Assertion Will fail showing possibility of invalid triangle …
5 int a = -1; int b = 4; int c = 4; 6 assert(a > 0 && b > 0 && c > 0); 7 if (a + b > c || a + c > b || b + c > a) { 8 System.out.println("We have a triangle!"); 9 } else { 10 System.out.println("We do not have a triangle!"); 11 } Result: Exception in thread "main" java.lang.AssertionError at AssertExample.main(AssertExample.java:6)
40
Lab Exercises You try! During these exercises, ask yourself:
What are the known errors? What are the assumptions?
41
Helpful Resources CWE/SANS Top 25 Most Dangerous Software Errors
Open Web Application Security Project
42
Resources Defensive programming. (2014, August 7). In Wikipedia, The Free Encyclopedia. Retrieved 16:59, August 19, 2014, from Bird, J. (2012, March 14). Defensive Programming: Being Just-Enough Paranoid. Retrieved March 12, 2014, from Building Real Software: Shaw, Z. A. (2010). Learn C The Hard Way. Retrieved March 3, 2014, from Exercise 27: Creative And Defensive Programming:
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.