Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 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
42
Embed
Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Broadening Expertise in Critical Infrastructure Protection
Defensive Programming ModuleFunded through NSF Grant Award # DUE-1303269
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
Overview
• Defensive Programming Defined• The Need• Common Misconceptions and Errors• Best Practices• Lab: You Try!
DEFENSIVE PROGRAMMING DEFINED
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”
THE NEED
“The whole point of defensive programming is guarding against errors you don’t expect.”Steve McConnell, Code Complete
Costly Mistakes
• Ariane 5 rocket's ill-fated first launch, 1996– http://www.youtube.com/watch?v=gp_D8r-2hwk
• 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)6
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 */
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
X
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
X
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
X
About Input Validation
• Critical to application security• Process of validating all input to an application
before using the input– Two common approaches
1. Blacklist validation: detect unauthorized input like attack characters and patterns
2. Whitelist validation (best way!): compare input against list of all authorized input often using regular expressions (specify type, length, and range of values)
Poor Input Validation Example
• See http://jsfiddle.net/HWba4/1/• 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)
• 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
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
if($userLoggedIn) { /* Hundreds of lines of code */ }else{ exit(); }
?>
<?php
if(!$userLoggedIn) { exit(); }
/* Hundreds of lines of code */
VS
Common Programming Error #4
• Not reusing code
VS
Common Programming Error #5
• Not heeding compiler warning– Can be indicative of coding errors
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:– www.somesite.com/Hello+World.doc– www.somesite.com/hello+world.doc– www.somesite.com/Hello%20World.doc
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
Errors Common to Threaded Environments
• Deadlocks– a situation where two or more threads are blocked
forever, waiting for each other
Errors Common to Threaded Environments
• Race condition– occurs when two threads access a shared variable
at the same time
BEST PRACTICES
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
Standards• No magic numbers
– Use constants (e.g. KILOGRAMS_PER_POUND = 0.454 instead of hardcoding 0.454 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)
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
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)
Lab Exercises
• You try!• During these exercises, ask yourself:
• What are the known errors?• What are the assumptions?
Helpful Resources
• CWE/SANS Top 25 Most Dangerous Software Errors– http://cwe.mitre.org/top25/
• Open Web Application Security Project– https://www.owasp.org
Resources• Defensive programming. (2014, August 7). In Wikipedia, The
Free Encyclopedia. Retrieved 16:59, August 19, 2014, from http://en.wikipedia.org/w/index.php?title=Defensive_programming&oldid=620243055
• Bird, J. (2012, March 14). Defensive Programming: Being Just-Enough Paranoid. Retrieved March 12, 2014, from Building Real Software: http://swreflections.blogspot.com/2012/03/defensive-programming-being-just-enough.html
• Shaw, Z. A. (2010). Learn C The Hard Way. Retrieved March 3, 2014, from Exercise 27: Creative And Defensive Programming: http://c.learncodethehardway.org/book/ex27.html