1 / 41

Error Handling

James Walden Northern Kentucky University. Error Handling. Topics. Error Handling Return Codes Exceptions Logging Survivability. Security Impact of Error Handling. Information leakage Stack traces Database errors Resource leakage Return on error without de-allocation

stacie
Download Presentation

Error Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. James Walden Northern Kentucky University Error Handling

  2. Topics • Error Handling • Return Codes • Exceptions • Logging • Survivability

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

  4. CSC 666: Secure Software Engineering Error Handling Techniques Return a neutral value: return a value that’s known to be harmless, i.e. 0 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 0..100, 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

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

  6. CSC 666: Secure Software Engineering 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 */

  7. CSC 666: Secure Software Engineering Example: sprintf() Incorrect example: sprintf returns -1 on error, count can be out of bounds int i; ssize_t count = 0; for (i = 0; i < 9; ++i) { count += sprintf( buf + count, "%02x ", ((u8 *)&slreg_num)[i] ); } count += sprintf(buf + count, "\n"); Correct example uses sprintf_m function f/ CERT managed string library int i; rsize_t count = 0; errno_t err; for (i = 0; i < 9; ++i) { err = sprintf_m( buf + count, "%02x ", &count, ((u8 *)&slreg_num)[i] ); if (err != 0) { /* Handle print error */ } } err = sprintf_m( buf + count, "%02x ", &count, ((u8 *)&slreg_num)[i] ); if (err != 0) { /* Handle print error */ }

  8. 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 }

  9. CSC 666: Secure Software Engineering Using goto for error handling Problem: 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.

  10. 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; }

  11. 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 }

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

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

  14. 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; }

  15. 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 seperately, instead of ignoring them or handling genericly.

  16. CSC 666: Secure Software Engineering Destructor De-Allocation Resource Aquisition 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_); } }

  17. 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(); } }

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

  19. CSC 666: Secure Software Engineering Survivability • Survivability: Capability of a system to fulfill its functions even when under attack. • Properties of Survivable Systems: • Resistance to attacks • Recognition of damage from attacks • Recovery of full or essential services • Adaptation to reduce effectiveness of future attacks

  20. References • David Abrahams, Exception-Safety in Generic Components. Lecture Notes In Computer Science: 69-79, 2000. • Tom Cargill, Exception Handling: A False Sense of Security, C++ Report, Volume 6, Number 9, November-December 1994. • CERT, Error Handling, https://www.securecoding.cert.org/confluence/download/attachments/3524/error-handling.pdf, 2006. • Brian Chess and Jacob West, Secure Programming with Static Analysis, Addison-Wesley, 2007. • Robert J. Ellison et. al., Survivability: Protecting Your Critical Systems, IEEE Computer, 1999. • Fred Long, CERT Secure Coding Standards: Error Handling, https://www.securecoding.cert.org/confluence/display/cplusplus/12.+Error+Handling+(ERR), 2009. • Steve McConnell, Code Complete, 2nd edition, Microsoft Press, 2004.

  21. CSC 666: Secure Software Engineering Privacy Topics • Regulations • Cryptography • Random numbers • Passwords • Secrets in memory

  22. CSC 666: Secure Software Engineering Regulations Regulations protect private data • Children’s Online Protection Act (COPPA) • Federal Information Security Management Act • Gramm-Leach-Bliley Act (GLBA) • Health Insurance Portability & Accountability Act • Payment Card Industry DSS Personally Identifiable Information (PII) • Credit cards • SSNs and state/driver IDs • Names

  23. CSC 666: Secure Software Engineering Inbound Passwords • Used to authenticate users to application. • Stored in hashed + salted format. • Hashed: one-way encryption. • MD5 • SHA-1 • SHA-2: SHA-224,256,384,512 • Salted: increases time for dictionary attacks • Old UNIX crypt passwords use 12-bit salt. • OpenBSD uses 128-bit salt value.

  24. 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 3.6.6 requires key be split among admins.

  25. CSC 666: Secure Software Engineering Key Generation Choose key from set of K keys at random. • Equivalent to selecting a random number between 0 and K–1 inclusive. • Ensures all keys are equally probable to use. Problem: generating random numbers • Computer generated numbers are pseudo-random, that is, generated by an algorithm. • Need direct or indirect hardware sources to obtain sufficiently random data for key generation.

  26. CSC 666: Secure Software Engineering PRNGs • Computers are deterministic • Can’t produce true random numbers. • Pseudo-random numbers appear to be random to certain statistical tests. • Tests can be derived from compression. • If you can compress sequence, it’s not random. • Software generated pseudo-random sequences are periodic and predictable.

  27. CSC 666: Secure Software Engineering Seeds • Input used to generate initial PR number. • Should be computationally infeasible to predict • Generate seed from random, not PR, data. • Large seed: 32 bits too small; only 232 combinations. • Sequence still repeats, but starts from different point for each different seed. • Identical sequences produced for identical seeds. • Period needs to be large for security.

  28. CSC 666: Secure Software Engineering Linear Congruential Generator nk = (ank–1 + b) mod m m Modulus (a large prime integer) a Multiplier (integer from 2..m-1) bIncrement n0 Sequence initializer (seed) Functions like rand() in C use LCGs.

  29. CSC 666: Secure Software Engineering Hardware Sources Radioactive Decay • Hotbits: 256 bits/s • http://www.fourmilab.ch/hotbits/ Thermal Noise • Comscire QNG Model J1000KU, 1 Mbit/s • Pentium III RNG LavaRnd • SGI used LavaLite; LavaRnd uses lenscapped digicam • http://www.lavarnd.org/ • up to 200 kbits/s

  30. CSC 666: Secure Software Engineering Software Sources Less Secure, More Convenient • Software sufficiently complex to be almost impossible to predict. User Input: Push, don’t Pull • Record time stamp when keystroke or mouse event occurs. • Don’t poll most recent user input every .1s • Far fewer possible timestamps.

  31. CSC 666: Secure Software Engineering Software Sources: /dev/random Idea: use multiple random software sources. • Store randomness in pool for user requests. • Use hash functions (i.e., strong mixing functions) to distill data from multiple sources. /dev/random can use random sources such as • CPU load • disk seeks • kernel interrupts • keystrokes • network packet arrival times • /dev/audio sans microphone

  32. CSC 666: Secure Software Engineering Software Sources: /dev/random /dev/random • each bit is truly random. • blocks unless enough random bits are available. /dev/urandom • supplies requested number of bits immediately. • reuses current state of pool—lower quality randomness.

  33. CSC 666: Secure Software Engineering Poor Entropy: Netscape 1.1 • SSL encryption • generates random 40- or 128-bit session key • Netscape 1.1 seeded PRNG with • time of day • PID and PPID • All visible to attacker on same machine. • Remote attack broke keys in 30 seconds • guessed limited randomness in PID/PPID. • packet sniffing can determine time of day.

  34. CSC 666: Secure Software Engineering Cryptographic APIs • Cryptlib (free for noncommercial) • Crypt++ (public domain) • Crypt:: CPAN modules (various) • Java Cryptography Architecture • Java Cryptography Extension • Microsoft CryptoAPI • Nettle (GPL) • OpenSSL (OpenSSL license)

  35. CSC 666: Secure Software Engineering Supported Ciphers Range of MAC algorithms • Almost all include MD5, SHA-1 Range of symmetric algorithms • Almost all include AES, DES Range of public key algorithms • Almost all include RSA, Diffie-Hellman, DSA

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

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

  38. 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);

  39. CSC 666: Secure Software Engineering Erasing Secrets Securely Garbage collecting languages • Essentially impossible to ensure secrets are erased immediately. Low level languages • Use SecureZeroMemory() in Windows. • Use volatile pointers to prevent compiler from optimizing away memory overwrites.

  40. CSC 666: Secure Software Engineering Erasing Secrets Securely 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; }

  41. CSC 666: Secure Software Engineering References • Brian Chess and Jacob West, Secure Programming with Static Analysis, Addison-Wesley, 2007. • D. Eastlake, “Randomness Recommendations for Security,” RFC 1750, http://www.ietf.org/rfc/rfc1750.txt, 1994. • Ian Goldberg and David Wagner,“Randomness and the Netscape Browser,” Doctor Dobbs’ Journal, 1996. http://www.cs.berkeley.edu/~daw/papers/ddj-netscape.html • Michael Howard and David LeBlanc, Writing Secure Code, 2nd edition, Microsoft Press, 2003. • Alfred J. Menezes, Paul C. van Oorschot and Scott A. Vanstone, Handbook of Applied Cryptography, http://www.cacr.math.uwaterloo.ca/hac/, CRC Press, 1996. • S. K. Park, K. W. Miller, “Random number generators: good ones are hard to find,”  Communications of the ACM,  Volume 31 Issue 10 , October 1988. • Bruce Schneier, Applied Cryptography, 2nd edition, Wiley, 1996. • John Viega and Gary McGraw, Building Secure Software, Addison-Wesley, 2002. • David Wheeler, Secure Programming for UNIX and Linux HOWTO, http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/index.html, 2003.

More Related