Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 482/582: Computer Security

Similar presentations


Presentation on theme: "CSC 482/582: Computer Security"— Presentation transcript:

1 CSC 482/582: Computer Security
Secure Programming CSC 482/582: Computer Security

2 Topics Robust and Secure Programming
Race Conditions and TOCTOU vulnerabilities Error Handling Securing Secrets in Memory Secure Programming References CSC 482/582: Computer Security

3 Robust Code Principles
Paranoia Assume all input is evil. Check all function calls for errors or exceptions. Check all input to ensure it is not malformed. Assumption of Stupidity Don’t assume coders or users read documentation. All functions should handle incorrect, missing, and malformed parameters. CSC 482/582: Computer Security

4 Robust Code Principles
Avoid Dangerous Implements Any data that code expects to remain consistent is a “dangerous implement”. Assume any data controlled by caller can change unexpectedly. Can Happen Object creation can fail due to lack of memory. Closing a file can fail when a USB drive is removed. Command line arguments can be NULL. CSC 482/582: Computer Security

5 Assumptions Know what assumptions your code makes
Assumptions that certain properties are true. Text is UTF-8 encoded text Data is properly formatted XHTML Temperature is an integer between 32 and 212. Assumptions that other properties are false. Input is never longer than X bytes Input is never zero bytes. Input is never a negative number. Then check that those assumptions are true. CSC 482/582: Computer Security

6 Secure Code Secure Code is Implicit security properties often include
Robust Code that Satisfies (implicit or explicit) security properties. Implicit security properties often include Absence of well known types of vulnerabilities. Protection of CIA properties in certain states. Explicit security properties Ensure developer knows what to protect. Ensure user knows that assets are protected. CSC 482/582: Computer Security

7 Who do you trust? Client users Operating system Calling program Vendor
example: encryption key embedded in client Operating system example: dynamicly loaded libraries Calling program example: environment variables Vendor example: Borland Interbase backdoor , only discovered when program made open source CSC 482/582: Computer Security

8 Trust is Transitive If you call another program, you are trusting the entities that it trusts. Processes you spawn run with your privileges. Did you run the program you think you did? PATH and IFS environment variables What input format does it use? Shell escapes in editors and mailers What output does it send you? CSC 482/582: Computer Security

9 What is a Race Condition?
Incorrect behavior arising from unexpected dependency on relative timing of events. Timing of events on multitasking system depends on system load. Events generally happen in the expected order. On multitasking system, processes can be interrupted between any two instructions. Private resources (memory) are protected. Shared resources (filesystem, network) can be modified by interrupting process. Race conditions are always a reliability issue, but sometimes also a security flaw. CSC 482/582: Computer Security

10 Java Servlet Hit Counter
// Example from BSS, pp public class Counter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest in, HttpServletResponse out) throws ServletException, IOException { out.setContentType("text/plain"); Printwriter p = out.getWriter(); count++; p.println(count + " hits so far!"); } Calculates number of times web page has been accessed. CSC 482/582: Computer Security

11 Analysis of Hit Counter
Assumes variable count does not change between incrementing and printing. What if users A + B hit page at approximately the same time? A is first, count = 1 B is second, before println occurs, count = 2 A sees “2 hits so far” B sees “2 hits so far” Cannot be fixed by expressing the two statements as one: p.println(++count + “ hits so far!”) It requires multiple JVM byte code instructions to execute the statement. CSC 482/582: Computer Security

12 Window of Vulnerability
Period of time when violating assumption about order of events will produce incorrect behavior. Generally <1s under ordinary conditions. What if web site is popular? What if attacker can send many requests? CSC 482/582: Computer Security

13 Window of Vulnerability
Attacker can increase increase size of window by slowing down system. Attacker can increase window size by controlling execution with SIGSTOP/SIGCONT. Attacker can attempt exploit many times. 1 in 1,000,000 odds make the bug hard to find for you, but are very good for the attacker with an automated exploit. CSC 482/582: Computer Security

14 Window of Vulnerability
You must reduce the window of vulnerability to zero for system to be secure. 1 in 1,000,000 odds make the bug hard to find for you, but are very good for the attacker with an automated exploit. CSC 482/582: Computer Security

15 Critical Sections Segment of code which may only be executed by one thread at a time. Critical Section executes atomically from viewpoint of other threads. Performance Impact Other threads must wait for thread in critical section to finish executing. Limit critical section size. CSC 482/582: Computer Security

16 Synchronized Hit Counter
// Example from BSS, p. 213 public class Counter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest in, HttpServletResponse out) throws ServletException, IOException { int mycount; out.setContentType("text/plain"); Printwriter p = out.getWriter(); synchronized(this) { mycount = ++count; } p.println(mycount + " hits so far!"); Java provides synchronized keyword for critical sections. Note limitation of critical section to only required code. CSC 482/582: Computer Security

17 Time of Check, Time of Use
TOCTOU Security Flaw: Check security of resource. Use resource. What if attacker invalidates security After security check Before use CSC 482/582: Computer Security

18 UNIX Example int main( int argc, char *argv[] ) {
if(access( argv[1], W_OK ) == 0) fd = open( argv[1], O_WRONLY ); writeFile(fd); } else { perror(“Permission denied.\n”); exit(1); } Kernel performs access checks based on EUID/EGID, so setuid root program can always open() a file regardless of permissions. Access() function checks based on real UID/GID. Sounds useful in SETUID programs, but access() always insecure because of race condition. Ignore advice to use in Stevens, p. 82. CSC 482/582: Computer Security

19 Analysis Window of Vulnerability Exploit: rebind filename
Time between access() and open() Exploit: rebind filename Give filename as argument: /tmp/x After access(), delete /tmp/x create link named /tmp/x pointing at root-owned file like /etc/passwd, /.rhosts Example: xterm log file race condition Developer’s Invalid Assumption: filename refers to the same object in both access() and open() calls. CSC 482/582: Computer Security

20 ex: passwd [Bishop, 1996] passwd: allows user-specified passwd file
Normal functioning opens passwd file + reads user entry; closes creates + opens temp file ptmp in same directory opens passwd file again, then copies contents to ptmp with user changes closes both passwd and ptmp files; renames ptmp to passwd Doesn’t modify passwd in place to avoid problems with programs reading partially modified passwd file. UNIX move action is atomic. CSC 482/582: Computer Security

21 ex: passwd (cont.) Attacker Goal: rewrite /user/.rhosts Plan of Attack
contents: localhost attacker ::::: exploit: rlogin –l user localhost Plan of Attack Create exploit .rhosts file in attack directory Specify passwd file to be in attack directory steps 1 + 3: directory containing passwd file is attack directory steps 2 + 4: directory containing passwd:/user Attack directory can be any directory attacker has write access to. CSC 482/582: Computer Security

22 passwd attack setup mkdir attackdir
echo “localhost attacker :::::” > attack/.rhosts # want link to point to attackdir for step 1 ln –s attackdir link # specify password file using symlink dir passwd link/.rhosts CSC 482/582: Computer Security

23 passwd: step by step passwd program opens + reads link/.rhosts
actual file: attackdir/.rhosts Attacker changes link to point to /user passwd program creates + opens link/ptmp actual file: /user/ptmp Attacker changes link to point to attackdir CSC 482/582: Computer Security

24 passwd: step by step passwd program opens link/.rhosts
actual file: attackdir/.rhosts passwd program copies contents to ptmp actual file: /user/ptmp Attacker changes link to point to /user CSC 482/582: Computer Security

25 passwd: step by step passwd program closes link/.rhosts + ptmp
passwd program renames ptmp to link/.rhosts actual file: /user/.rhosts “Password” file is now target user’s .rhosts We can now rlogin to their account without needing a password CSC 482/582: Computer Security

26 UNIX File Binding UNIX provides two forms of naming pathname
universal mapping of names to objects indirect: requires parent directories to identify file mapping can be changed by another process file descriptor per-process mapping of identifiers to objects direct: file descriptor points directly to object mapping cannot be changed by another process File descriptors are initially obtained using a system call with a pathname. CSC 482/582: Computer Security

27 TOCTOU Binding Flaws Occur with two sequential system calls:
both refer to same object by pathname: insecure one binds file descriptor to pathname, other uses that file descriptor: secure one uses file descriptor, other uses pathname: insecure Solution: use calls that use file descriptors Problem: sometimes no alternative to pathnames CSC 482/582: Computer Security

28 TOCTOU Binding Flaws Solution: use calls that use file descriptors
fchmod() instead of chmod() fchown() instead of chown() fstat() instead of stat() Problem: sometimes no alternative to pathnames link(), unlink(), symlink() mkdir(), rmdir() CSC 482/582: Computer Security

29 Security Impact of Error Handling
Information leakage Stack traces Database errors Resource leakage Return on error without de-allocation Exceptions bypass de-allocation CSC 482/582: Computer Security

30 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. CSC 482/582: Computer Security

31 Error Handling 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 Multiple techniques: Combinations of the above. CSC 482/582: Computer Security

32 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. CSC 482/582: Computer Security

33 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 int c; while (((c = getchar()) != '\n') && !feof(stdin) && !ferror(stdin)) Example from CSC 482/582: Computer Security

34 Resource Leaks Resources leak due to early returns Example 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 482/582: Computer Security

35 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 482/582: Computer Security

36 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 482/582: Computer Security

37 Exceptions Advantages of exceptions Disadvantages 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 482/582: Computer Security

38 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 482/582: Computer Security

39 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 482/582: Computer Security

40 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 482/582: Computer Security

41 Destructor De-Allocation
Resource Acquisition Is Initialization 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 482/582: Computer Security

42 Finally A finally block is 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 482/582: Computer Security

43 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 Figure 11.2 from Chess & West. Data lifetime of 64MB of sensitive information in freed memory. CSC 482/582: Computer Security

44 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 482/582: Computer Security

45 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 482/582: Computer Security

46 Erasing Secrets Securely
Garbage collecting languages 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 482/582: Computer Security

47 Secure Programming References
CERT Secure Coding Standards for C, C++, Java, Perl Microsoft Writing Secure Code Secure Programming for UNIX/Linux HOWTO SAFECode Open Web Application Security Project (OWASP) OWASP Code Review Project CSC 482/582: Computer Security

48 Secure Programming Books
CSC 482/582: Computer Security

49 Key Points Validate input from all sources.
CLI args, env vars, config files, database, etc. Use the strongest possible technique. Indirect Selection Whitelist Blacklist Reject bad input, don’t attempt to fix it. Trust is transitive. Architect for validation: establish trust boundaries, wrap dangerous functions. CSC 482/582: Computer Security

50 References Brian Chess and Jacob West, Secure Programming with Static Analysis, Addison-Wesley, 2007. Steve McConnell, Code Complete, 2/e, Microsoft Press, 2004. Gary McGraw, Software Security, Addison-Wesley, 2006. PCI Security Standards Council, PCI DSS Requirements and Security Assessment Procedures, v1.2, 2008. Mark Graff and Kenneth van Wyk, Secure Coding: Principles & Practices, O’Reilly, 2003. Michael Howard and David LeBlanc, Writing Secure Code, 2nd edition, Microsoft Press, 2003. Michael Howard, David LeBlanc, and John Viega, 19 Deadly Sins of Software Security, McGraw-Hill Osborne, 2005. John Viega, and Gary McGraw, Building Secure Software, Addison-Wesley, 2002. David Wheeler, Secure Programming for UNIX and Linux HOWTO, CSC 482/582: Computer Security


Download ppt "CSC 482/582: Computer Security"

Similar presentations


Ads by Google