Secure Coding James Walden Northern Kentucky University.

Slides:



Advertisements
Similar presentations
Lectures on File Management
Advertisements

Introduction to Memory Management. 2 General Structure of Run-Time Memory.
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
Yoshi
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Failure to handle errors correctly
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Stack-Based Buffer Overflows Attacker – Can take over a system remotely across a network. local malicious users – To elevate their privileges and gain.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Chapter 6 Buffer Overflow. Buffer Overflow occurs when the program overwrites data outside the bounds of allocated memory It was one of the first exploited.
Natalia Yastrebova What is Coverity? Each developer should answer to some very simple, yet difficult to answer questions: How do I find new.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Introduction to Exception Handling and Defensive Programming.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Error Handling James Walden Northern Kentucky University.
Overflow Examples 01/13/2012. ACKNOWLEDGEMENTS These slides where compiled from the Malware and Software Vulnerabilities class taught by Dr Cliff Zou.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception Handling Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Design Principles and Common Security Related Programming Problems
Project: Simulated Encrypted File System (SEFS) Omar Chowdhury Fall 2015CS526: Information Security1.
Security Attacks Tanenbaum & Bo, Modern Operating Systems:4th ed., (c) 2013 Prentice-Hall, Inc. All rights reserved.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
Exceptions Lecture 11 COMP 401, Fall /25/2014.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Beyond Stack Smashing: Recent Advances In Exploiting Buffer Overruns Jonathan Pincus and Brandon Baker Microsoft Researchers IEEE Security and.
Chapter 10 Chapter 10 Implementing Subprograms. Implementing Subprograms  The subprogram call and return operations are together called subprogram linkage.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Eighth Lecture Exception Handling in Java
CSC 482/582: Computer Security
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
CS 2704 Object Oriented Software Design and Construction
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Protecting Memory What is there to protect in memory?
Exceptions David Rabinowitz.
Protecting Memory What is there to protect in memory?
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Protecting Memory What is there to protect in memory?
Defensive Programming
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointers, Dynamic Data, and Reference Types
Focus of the Course Object-Oriented Software Development
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling.
Presentation transcript:

Secure Coding James Walden Northern Kentucky University

Topics 1.Error Handling 2.Return Codes 3.Exceptions 4.Logging 5.Memory Allocation 6.Using and Storing Passwords 7.Protecting Secrets in Memory

CSC 666: Secure Software Engineering Security Impact of Error Handling Information leakage  Stack traces  Database errors Resource leakage  Return on error without de-allocation  Exceptions bypass de-allocation

CSC 666: Secure Software Engineering Error Handling Techniques Return a neutral value: return a value that’s known to be harmless, i.e. a negative number, zero, or “”. Substitute the next piece of data: continue reading from hardware or file until a valid record is found. Return same answer as last time: don’t keep reading; instead return the last valid answer. Substitute closest legal value: if velocity has a range of , show a 0 when backing up. Log a warning message: Write a warning to a log, then continue on, perhaps using one of the other techniques. Terminate program: Terminate program execution. Return an error code: Report error by  Setting the value of a status variable (errno)  Return status as the function’s return value  Throw an exception

CSC 666: Secure Software Engineering Return Codes Use function return code to indicate error.  Easy to ignore. Simply ignore return code.  Error handling logic is mixed with logic processing normal return codes.  No universal convention for error codes. Common return code patterns.  Negative values when nonnegative expected.  NULL values for pointer return codes.

Example: character get functions fgetc(), getc(), getchar() read char, return int Use int to represent EOF error code. Incorrect example: return value is declared as a char char buf[BUFSIZ]; char c; int i = 0; while ( (c = getchar()) != '\n' && c != EOF ) if (i < BUFSIZ-1) { buf[i++] = c; } buf[i] = '\0'; /* terminate NTBS */ Correct example char buf[BUFSIZ]; int c; int i = 0; while (((c = getchar()) != '\n') && !feof(stdin) && !ferror(stdin)) if (i < BUFSIZ-1) { buf[i++] = c; } buf[i] = '\0'; /* terminate NTBS */

CSC 666: Secure Software Engineering Resource Leaks Resources leak due to early returns  Memory  Filehandles Example char *getblock(int fd) { char *buf = (char *)malloc(1024); if (!buf) { return NULL; } if (read(fd, buf, 1024) != 1024) { return NULL; } return buf }

CSC 666: Secure Software Engineering Using goto for error handling Problem: need to de-allocate resources on return.  Each return is different since  Different resources allocated at each point. Solution: single de-allocation point  Check if resource is allocated, then  De-allocate if it is, and  Return with appropriate error code. Why goto ?  Avoids deep nesting.  Improves code readability.  Commonly used technique in kernel.

CSC 666: Secure Software Engineering Fixed version with goto char *getblock(int fd) { char *buf = (char *)malloc(1024); if (!buf) { goto ERROR; } if (read(fd, buf, 1024) != 1024) { goto ERROR; } return buf; ERROR: if (buf) { free(buf); } return NULL; }

CSC 666: Secure Software Engineering Exceptions Advantages of exceptions  Cannot be ignored by not checking for errors.  Separate main code from error code. Disadvantages of exceptions  Difficult to avoid resource leaks, as exceptions create many implicit control flow paths.  Can still ignore exceptions try { // code that can throw an exception } catch (AnException e) { // empty catch block }

CSC 666: Secure Software Engineering Checked Exceptions Checked exceptions: Exceptions that the language requires client code to handle.  C++, C#: no checked exceptions  Java: exceptions that inherit from Exception Unchecked exceptions: Exceptions that can be ignored by client code.  C++, C#: all exceptions are unchecked  Java: exceptions that inherit from RuntimeException.

CSC 666: Secure Software Engineering Exception Guarantees Levels of exception safety for a class. Basic Guarantee  No resources are leaked. Strong Guarantee  Exceptions leave state exactly as it was before the operation started. No Throw Guarantee  Component will handle all exceptions itself. No Exception Safety  Component may leak resources and leave object in an inconsistent unusable state.

CSC 666: Secure Software Engineering Exception Safety Example void stack::push(int element) { top++; if( top == size-1 ) { int* buf = new int[size+=32]; if( buf == 0 ) throw “Out of memory”; for(int i = 0; i < top; i++) buf[i] = data[i]; delete [] data; data = buf; } data[top] = element; }

CSC 666: Secure Software Engineering Catch-all Exception Handlers Ensure no information leakage at top level functions. doGet(), doPost (), web service entry points protected void doPost(HttpServletRequest req, HttpServlet Response res) { try { /* function body */ } catch (Throwable t) { logger.error(“Top-level exception caught”, t); } Do not do this in low level code.  Need to deal with individual error types separately, instead of ignoring them or handling generically.

CSC 666: Secure Software Engineering Destructor De-Allocation Resource Acquisition Is Initialization design pattern  Resources acquired during initialization of object, before it can be used.  Resources are de-allocated by the object’s destructor, which occurs even via exceptions. Example file (const char* filename) { file_ = fopen(filename, “w+”); if (!file_) throw std::runtime_error("file open failure"); } ~file() { if (f) { fclose(file_); } }

CSC 666: Secure Software Engineering Finally  Finally block executed regardless of whether an exception is caught or not.  Example Statement stmt = conn.createStatement(); try { stmt.execute(sqlString); } finally { if (stmt != null ) { stmt.close(); } }

CSC 666: Secure Software Engineering Logging Frameworks Use a standard logging framework.  Provide single consistent view of system.  Facilitate changes, such as logging to a new system or to a database. Examples  syslog()  log4j  java.util.logging

Memory Allocation Strategies Static Buffer Allocation  Advantages: simple, easy to know bounds.  Disadvantages: inflexible, wastes memory. Dynamic Buffer Allocation  Advantages: flexible.  Disadvantages: must check for DoS attacks. Track Buffer Sizes typedef struct { char* ptr; size_t bufsize; } buffer; CSC 666: Secure Software Engineering

Common Allocation Errors  Assuming that memory is zeroed.  Allocated memory contains junk, not zeros.  Failure to check that allocation succeeded.  Most C functions return a NULL pointer on failure.  new will throw std::bad_alloc exception on failure.  Unless specify T* p = new(std::nothrow) T ;  Use of invalid pointers.  Dereference NULLs, use after free, double free.  Failure to deallocate memory.  Memory leaks.  Zero-length allocations are implementation defined in C.

Inbound and Outbound Passwords Inbound Passwords  Used to authenticate users to application.  In cleartext only at point of user data entry.  Risks: online and offline password guessing. Outbound Passwords  Used to authenticate application to other systems, such as databases or CC processors.  Must be in cleartext to use.  Risks: information leakage. CSC 666: Secure Software Engineering

Securing Inbound Passwords Slide #21

Offline Password Cracking Password dictionary Usernames + Hashed Passwords word = Next dictionary word word hash = Hash(word) for each (username, hash) word hash == hash False True Store(usernames, word)

Hashing and Salting MD4 (Windows)  Unlimited password length.  Slow MD4 hash, no salt. SHA512crypt (Linux, Mac OS X)  Unlimited password length.  5000 iterations of SHA-512 hash function.  16 character salt. PBKDF2 (Password-Based Key Derivation Function 2)  Framework with configurable hash, iterations, salt. In.NET. Scrypt  Sequential, memory-hard hashing algorithm.  Defense against specialized hardware (GPUs, ASICs, FPGAs) CSC 666: Secure Software Engineering

Outbound Passwords Used by app to auth to db, other systems.  Must be accessible in cleartext at some point. Solutions  Store in source code. -Easy to view in source or binary form.  Store cleartext in a configuration file.  Store encrypted in a configuration file. -Use a good, known algorithm like AES. -Limit ACLs so only app can access.  Require admin enter password on restart. -PCI requires key be split among admins.

CSC 666: Secure Software Engineering Secrets in Memory Attackers can obtain secrets from memory  Remote exploit: buffer overflow or fmt string  Physical attack: direct media access  Accidental leakage: core dumps or page files

CSC 666: Secure Software Engineering Securing Secrets in Memory  Minimize time spent holding secrets.  Decrypt data just before use.  Overwrite data after use.  Share secrets sparingly.  Do not store secrets on the client.  Erase secrets securely.  Explicitly overwrite memory.  Prevent unnecessary duplication.

CSC 666: Secure Software Engineering Locking Pages in Memory Prevent secrets from paging to disk. Does not prevent suspend or hibernate saving pages. Linux page locking mlock(const void *addr, size_t len) munlock(const void *addr, size_t len) Windows page locking VirtualLock(LPVOID lpAddress, SIZE_T dwSize); VirtualUnlock(LPVOID lpAddress, SIZE_T dwSize);

CSC 666: Secure Software Engineering Erasing Secrets Securely Garbage collecting languages  Essentially impossible to ensure secrets are erased immediately. Low level languages  Compiler can optimize away code that overwrites a buffer if buffer contents are not used later.  Use memset_s() if compiler supports C11.  Use SecureZeroMemory() in Windows.  If neither function is available, use volatile pointers to prevent compiler from optimizing away memory overwrites. Some compilers may still cause problems.

CSC 666: Secure Software Engineering Erasing Secrets Securely in C99 void auth_function() { char pass[32]; if (getpass(pass)) { // Do something with password } memset(pass, 0, sizeof(pass)); // Prevent memset from being optimized // away by using volatile pointers. *(volatile char *)pass = *(volatile char *)pass; }

References 1.David Abrahams, Exception-Safety in Generic Components. Lecture Notes In Computer Science: 69-79, 2000.Exception-Safety in Generic Components 2.Tom Cargill, Exception Handling: A False Sense of Security, C++ Report, Volume 6, Number 9, November-December CERT, Error Handling, nts/3524/error-handling.pdf, nts/3524/error-handling.pdf 4.Brian Chess and Jacob West, Secure Programming with Static Analysis, Addison-Wesley, Robert J. Ellison et. al., Survivability: Protecting Your Critical Systems, IEEE Computer, Fred Long, CERT Secure Coding Standards: Error Handling, 2.+Error+Handling+(ERR), Error+Handling+(ERR) 7.Steve McConnell, Code Complete, 2 nd edition, Microsoft Press, 2004.