1 / 78

Secure Programming: Code Reviews & Static Analysis

Learn about the importance of code reviews in computer security, their process, common problems found, and the use of static analysis tools.

mattesont
Download Presentation

Secure Programming: Code Reviews & Static Analysis

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. CSC 382 Secure Programming CSC 382: Computer Security

  2. Topics • Code Reviews. • Integer Overflows. • Race Conditions. • Secure File Usage. • Canonicalization. CSC 382: Computer Security

  3. Code Auditing Why code reviews? • HP and AT&T claim 20-30X more effective than testing alone. • IBM discovers 82% of defects in reviews before testing. Code reviews are good for finding • Requirements errors. • Design flaws. CSC 382: Computer Security

  4. Code Reviews: People • Moderator • Manages meeting; follows up on issues. • Reader • Paraphrases code during meeting. • Not the author. • Recorder • Records bugs discovered. • Author • Provides context for code; answers questions. • Makes corrections after code review. CSC 382: Computer Security

  5. Code Review: Process • Initiation • Author submits code for review. • Code must compile (w/o warnings), pass unit tests. • Preparation • Reviewers read code and mark concerns. • Meeting • 150-200 lines/hour. • Rework • Author makes corrections based on bugs found in review. • Followup • Moderator checks corrections. • Code sent to testing if corrections good. CSC 382: Computer Security

  6. Code Review: Checklists Security reviews should include checklists of common problems, including: • buffer overflows • integer overflows • input validation • checking return values • resource name canonicalization • race conditions CSC 382: Computer Security

  7. Code Review: Problems • Requires substantial expertise in area of coding and security to be effective. • Human readers are fallible, and will miss mistakes. CSC 382: Computer Security

  8. Static Analyis Solution: Let a program analyze your source code for security flaws. Range of approaches • Standard compiler warnings and type checking. • Lexing source checkers that look for bad names like strcpy() and gets(). • Parsing source code checkers. • Parsing checkers with annotations. • Formal proof based program verification. CSC 382: Computer Security

  9. Static Analysis Tools Lexing source code checkers. • flawfinder • ITS4 • RATS Parsing checkers + annotation. • cqual • Fortify • splint CSC 382: Computer Security

  10. login.c int validatePassword(const char *plain_pass) { return !strcmp( cipher_pass, crypt(plain_pass, cipher_pass) ); } int login() { int nAttempts=0;int maxAttempts=3;char password[64];int success=0; do { printf( "\npassword: " ); gets( password ); success = validatePassword( password ); if( success ) break; } while( ++nAttempts < maxAttempts ); return success; } void main(int argc, char *argv[]) { int success = 0; char username[64]; strcpy( username, argv[1] ); success = login(); if( success ) printf( "Login successful, %s!\n", username ); else printf( "Too many failed login attempts.\n" ); return( success ); } CSC 382: Computer Security

  11. login.c: splint output Splint 3.1.1 --- 15 Jun 2004 login.c: (in function validatePassword) login.c:22:13: Operand of ! is non-boolean (int): !strcmp(cipher_pass, crypt(plain_pass, cipher_pass)) The operand of a boolean operator is not a boolean. Use +ptrnegate to allow ! to be used on pointers. (Use -boolops to inhibit warning) login.c:22:12: Return value type boolean does not match declared type int: !strcmp(cipher_pass, crypt(plain_pass, cipher_pass)) To make bool and int types equivalent, use +boolint. CSC 382: Computer Security

  12. login.c: splint output login.c: (in function login) login.c:34:9: Use of gets leads to a buffer overflow vulnerability. Use fgets instead: gets Use of function that may lead to buffer overflow. (Use -bufferoverflowhigh to inhibit warning) login.c:34:9: Return value (type char *) ignored: gets(password) Result returned by function call is not used. If this is intended, can cast result to (void) to eliminate message. (Use -retvalother to inhibit warning) login.c:36:13: Test expression for if not boolean, type int: success Test expression type is not boolean or int. (Use -predboolint to inhibit warning) CSC 382: Computer Security

  13. login.c: splint output login.c:43:6: Function main declared to return void, should return int The function main does not match the expected type. (Use -maintype to inhibit warning) login.c: (in function main) login.c:51:9: Test expression for if not boolean, type int: success login.c:56:11: Return expression from function declared void: (success) Types are incompatible. (Use -type to inhibit warning) CSC 382: Computer Security

  14. login.c: splint output login.c:19:6: Variable exported but not used outside login: cipher_pass A declaration is exported, but not used outside this module. Declaration can use static qualifier. (Use -exportlocal to inhibit warning) login.c:21:5: Function exported but not used outside login: validatePassword login.c:23:1: Definition of validatePassword login.c:25:5: Function exported but not used outside login: login login.c:41:1: Definition of login Finished checking --- 12 code warnings CSC 382: Computer Security

  15. splint: Annotations Annotations encoded as special comments. • /*@annotation@*/ Types of annotations • Add or suppress warning messages. • NULL pointer checking via /*@notnull@*/ • Bounds checking: • strcpy: /*@requires maxSet(s1) >= maxRead(s2) @*/ • User-defined • /*@tainted@*/ attribute CSC 382: Computer Security

  16. What’s an Integer Overflow? An integer overflow is when integer operations produce a value that exceeds the computer’s maximum integer value, causing the value to “wrap around” to a negative value or zero. CSC 382: Computer Security

  17. Are Integer Overflows Important? Broward County November 2004 election • Amendment 4 vote was reported as tied. • Software from ES&S Systems reported a large negative number of votes. • Discovery revealed that Amendment 4 had passed by a margin of over 60,000 votes. CSC 382: Computer Security

  18. Computer Integers Computer integers aren’t math integers • Limited precision: 8-bit to 64-bit • See limits.h for min and max values. • ISO C99 does not specify what happens when you store a value too large or too small. • Most compilers ignore. Two’s Complement Signed Integers • –x = (complement x) + 1 • High bit is the sign bit. • Range: -2n .. 2n - 1 CSC 382: Computer Security

  19. 32-bit Integer Quiz • What two non-zero integers x and y satisfy the equation x * y = 0? • What negative integer (-x) has no corresponding positive integer (x)? • List two integers x and y, such that x + y < 0. • What is the unique negative integer x that has the propery x + x = 0? CSC 382: Computer Security

  20. Quiz Answers • 65536 * 65536 = 0 or 256 * 16777256 = 0 or any x * y = 232 2. -2147483648 • 2147483647 + 1 = -2147483648 • -2147483648 + -2147483648 = 0 CSC 382: Computer Security

  21. Why are Integer Overflows Dangerous? • Difficult to detect after they’ve happened. • C/C++ compilers generally ignore them. • Assembly code can check carry flag, but C/C++ cannot without calling to assembly code. • Difficult to avoid. • Subtle bugs can result in integer overflows. • Often used to bypass security checks. • To permit buffer overflow attacks. CSC 382: Computer Security

  22. Integer Comparisons What’s wrong with the following code? int safeStringCopy(char *str, int size) { char buf[64]; if(size < sizeof(buf)) strcpy(buf, str); return buf; } CSC 382: Computer Security

  23. Integer Multiplication What’s wrong with the following code? int copyArray(int *array, int len){ int *myarray, i; myarray = malloc(len * sizeof(int)); if(myarray == NULL) return -1; for(i = 0; i < len; i++) myarray[i] = array[i]; return myarray; } CSC 382: Computer Security

  24. Integer Addition What’s wrong with the following code? char *safeStrCat(char *s1, size_t len1, char *s2, size_t len2) { if( len1 + len2 + 1 > 512 ) return NULL; char *out=(char*)malloc(len1+len2+1); strcpy(out, s1); strcat(out, s2); return out; } CSC 382: Computer Security

  25. MS JScript Overflow Attack • JScript sparse arrays var arr = new Array(); arr[1] = 1; arr[2] = 2; arr[0x40000001] = 3; • C++ code that implements sort method buf = (Element *)malloc(ElementCount * sizeof(Element)); • What happens ? 0x40000001 * 0x00000014 = 0x00000014 Only 20 bytes allocated for buffer. CSC 382: Computer Security

  26. Integer Overflow Defence • Safe unsigned addition (x+y) • Test if x + y > MAX_INT • How can we do the test and avoid overflows? • x > MAX_INT - y • Safe unsigned subtraction (x-y) • Check if x < y • Safe unsigned multiplication (x*y) • Check if x > MAX_INT/y • Signed arithmetic more complex CSC 382: Computer Security

  27. Integer Overflow Defence Use a safer language • Most languages (C/C++, Java, etc) vulnerable. • Python is not vulnerable. Use a safe library • David LeBlanc’s SafeInt class for C++ CSC 382: Computer Security

  28. 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. CSC 382: Computer Security

  29. Java Servlet Hit Counter // Example from BSS, pp. 210-211 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!"); } } CSC 382: Computer Security

  30. 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” CSC 382: Computer Security

  31. 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 382: Computer Security

  32. 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. CSC 382: Computer Security

  33. Window of Vulnerability You must reduce the window of vulnerability to zero for system to be secure. CSC 382: Computer Security

  34. 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 382: Computer Security

  35. 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!"); } } CSC 382: Computer Security

  36. 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 382: Computer Security

  37. 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); } } CSC 382: Computer Security

  38. Analysis • Window of Vulnerability • Time between access() and open() • Exploit: rebind filename • Give filename as argument: /tmp/x • After access(), • delete /tmp/x • create link named /tmp/xpointing at root-owned file like /etc/passwd, /.rhosts • Example: xterm log file race condition CSC 382: Computer Security

  39. 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 ptmpfiles; renames ptmp to passwd CSC 382: Computer Security

  40. ex: passwd (cont.) Attacker Goal: rewrite /user/.rhosts • 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 CSC 382: Computer Security

  41. 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 382: Computer Security

  42. 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 382: Computer Security

  43. 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 382: Computer Security

  44. passwd: step by step • passwd program closes link/.rhosts + ptmp • passwd program renames ptmptolink/.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 382: Computer Security

  45. 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 CSC 382: Computer Security

  46. 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 382: Computer Security

  47. TOCTOU Binding Flaws Solution: use calls that use file descriptors • fchmod() instead of chmod() • fchown() instead of chown() • fstat()instead ofstat() Problem: sometimes no alternative to pathnames • link(), unlink(), symlink() • mkdir(), rmdir() CSC 382: Computer Security

  48. Safe File Open • lstat()file before opening, saving stat structure • open()file, obtaining file descriptor • use O_CREAT | O_EXCL flags • specify permissions in open() call or use safe umask • fstat() on file descriptor, saving stat structure • Compare permissions (st_mode), inode (st_ino), and device (st_dev) of two stat structures. If identical, we know lstat() happened on file we opened and that we did not follow a link. CSC 382: Computer Security

  49. Safe setuid File Operations • access() is insecure, what else is there? • Change process EUID/EGID to the real UID/GID we want to use for check • setreuid( EUID, UID ) • Perform file operations (access checks will apply as normal to EUID/EGID). • Change back to privileged EUID/EGID when privileges needed again • setreuid( UID, EUID ) CSC 382: Computer Security

  50. When you have to use pathnames • Keep files in their own, safe directory. • only UID of program can access • Ensure attacker cannot modify parent directories. • mkdir safe directory • chdir safe directory • chdir .. + check permissions until reach root CSC 382: Computer Security

More Related