Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded...

42
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

Transcript of Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded...

Page 1: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 2: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Overview

• Defensive Programming Defined• The Need• Common Misconceptions and Errors• Best Practices• Lab: You Try!

Page 3: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

DEFENSIVE PROGRAMMING DEFINED

Page 4: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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”

Page 5: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

THE NEED

“The whole point of defensive programming is guarding against errors you don’t expect.”Steve McConnell, Code Complete

Page 6: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 7: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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.

Page 8: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 9: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 10: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Malicious Attacks

• Office 365 suffered from a serious Cross Site Scripting (XSS) vulnerability– Gave access to email and SharePoint content of

every employee in the company• Fixed by Microsoft in December 2013

Page 11: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

COMMON MISCONCEPTIONS AND ERRORS

“To err is human;”Alexander Pope, Essay on Criticism

Page 12: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 13: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

CWE/SANS Top 25 Most Dangerous Software Errors

Page 14: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Simple XSS Attack

Page 15: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Vulnerability: Cross Site Scripting (XSS)

Image Source: http://www.digitalnewsasia.com/sites/default/files/images/digital%20economy/HP%20XSS.jpg

Page 16: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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 loginsWHERE username = ‘$username’AND password = ‘$password’

Instead becomes

SELECT *FROM loginsWHERE username = ‘` OR 1=1; /*’AND password = ‘*/--’

Page 17: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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 */

Page 18: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 19: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 20: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 21: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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)

Page 22: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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)

Page 23: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Poor Input Validation Example

• See http://ideone.com/xH9n1r• Note common issues:

– User can exceed value for data type, cause memory overflow

Page 24: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

About Sanitization

• Changes the user input into an acceptable format– Two common approaches

1. Blacklist sanitization: characters not part of approved list can be removed, encoded, or replaced

2. Whitelist sanitization (best way!): eliminate or translate characters in an effort to make input safe

Page 25: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Good Sanitization Example

• See http://jsfiddle.net/HNQvd/– Note that the HTML characters and treated as text

by the browser, not HTML tags

Page 26: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 27: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 28: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Common Programming Error #3

• Unnecessarily complicated code– “Complexity breeds bugs.”

<?php

if($userLoggedIn) { /* Hundreds of lines of code */ }else{ exit(); }

?>

<?php

if(!$userLoggedIn) { exit(); }

/* Hundreds of lines of code */

VS

Page 29: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Common Programming Error #4

• Not reusing code

VS

Page 30: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Common Programming Error #5

• Not heeding compiler warning– Can be indicative of coding errors

Page 31: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 32: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 33: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Errors Common to Threaded Environments

• Deadlocks– a situation where two or more threads are blocked

forever, waiting for each other

Page 34: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Errors Common to Threaded Environments

• Race condition– occurs when two threads access a shared variable

at the same time

Page 35: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

BEST PRACTICES

Page 36: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 37: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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)

Page 38: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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

Page 39: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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)

Page 40: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Lab Exercises

• You try!• During these exercises, ask yourself:

• What are the known errors?• What are the assumptions?

Page 41: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

Helpful Resources

• CWE/SANS Top 25 Most Dangerous Software Errors– http://cwe.mitre.org/top25/

• Open Web Application Security Project– https://www.owasp.org

Page 42: Broadening Expertise in Critical Infrastructure Protection Defensive Programming Module Funded through NSF Grant Award # DUE-1303269 Any opinions, findings,

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