470 likes | 488 Views
CSC 382: Computer Security. Trust and Input. Topics. The Nature of Trust Trust is Transitive Validating Input Entry Points Language Features for Input Protection. Trust Relationships. Relationship between multiple entities. Assumptions that certain properties are true.
E N D
CSC 382: Computer Security Trust and Input CSC 382: Computer Security
Topics • The Nature of Trust • Trust is Transitive • Validating Input • Entry Points • Language Features for Input Protection CSC 382: Computer Security
Trust Relationships Relationship between multiple entities. • Assumptions that certain properties are true. • example: input has a certain format • Assumptions that other properties are false. • example: input never longer than X bytes Trustworthy entities satisfy assumptions. CSC 382: Computer Security
Who do you trust? Client users • example: encryption key embedded in client Operating system • example: dynamicly loaded libraries Calling program • example: environment variables Vendor • example: Borland Interbase backdoor 1994-2001, only discovered when program made open source CSC 382: Computer Security
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 382: Computer Security
Validate All Input Never trust input. • Assume dangerous until proven safe. Prefer rejecting data to filtering data. • Difficult to filter out all dangerous input Every component should validate data. • Trust is transitive. • Don’t trust calling component. • Don’t trust called component: shell, SQL CSC 382: Computer Security
Validate All Input: Whitelisting Reject all input not in your valid set. • Whitelist: maintain list of valid inputs. • Don’t blacklist: too easy to forget bad values. • Completely understand your input format. • Beware • special commands: shell escapes in editors/mailers • characters: newlines, /, ., ; • different representations: character sets, escaping CSC 382: Computer Security
Entry Points • Command line arguments • Environment variables • File descriptors • Signal handlers • Format strings • Web application input • Database input • Other input types CSC 382: Computer Security
Command Line Arguments Available to program as **argv. execve() allows user to specify arguments. May be of any length • even program name, argv[0] • argv[0] may even be NULL CSC 382: Computer Security
Environment Variables Default: inherit parent process environment execve() allows you to specify environment variables for exec’d process. • environment variables can be of any length. Telnet environment propagation to server • Server receives client shell’s environment. • Server runs setuid program login. • ssh may use user’s ~/.ssh/environment file. CSC 382: Computer Security
Dangerous Environment Variables LD_PRELOAD • Programs loads functions from library specified in LD_PRELOAD before searching for system libraries. • Can replace any library function. • setuid root programs don’t honor this variable. LD_LIBRARY_PATH • Specify list of paths to search for shared libs. • Store hacked version of library in first directory. • Modern libc implementation disallow for setuid/setgid. CSC 382: Computer Security
Dangerous Environment Variables PATH • Search path for binaries • Attacker puts directory with hacked binary first in PATH so his ls used instead of system ls • Avoid “.” as attacker may place hacked binaries in directory program sets CWD to IFS • Internal field separator for shell • Used to separate command line into arguments • Attacker sets to “/”: /bin/ls becomes “bin” and “ls” CSC 382: Computer Security
Environment Storage Format Access Functions • setenv(), getenv() Internal Storage Format • array of character pointers, NULL terminated • string format: “NAME=value”, NULL term • Multiple env variables can have same name • Did you check the same variable that you fetched? First or last variable that matches? CSC 382: Computer Security
Securing Your Environment /* BSS, pp. 318-319 */ extern char **environ; static char *def_env[] = { “PATH=/bin:/usr/bin”, “IFS= \t\n”, 0 }; static void clean_environment() { int i = -1; while( environ[++i] != 0 ); while(i--) environ[i] = 0; while(def_env[i]) putenv(def_env[i++]); } CSC 382: Computer Security
Securing Your Environment Secure Environment in Shell /usr/bin/env – PATH=/bin:/usr/bin IFS=“ \t\n” command Secure Environment in Perl %ENV = ( PATH => “/bin:/usr/bin”, IFS => “ \t\n” ); CSC 382: Computer Security
File Descriptors • Default: inherited from parent process • stdin, stdout, stderr usually fd’s 0, 1, and 2 • Parent process may have closed or redirected standard file descriptors • Parent may have left some fd’s open • Cannot assume first file opened will have fd 3 • Parent process may not have left enough file descriptors for your program • Check using code from BSS, p. 315 CSC 382: Computer Security
Signal Handlers Default: inherited from parent process /* BSS, p. 316 */ #include <signal.h> int main( int argc, char **argv ) { int i; for(i=0; i<NSIG; i++) signal(I, SIG_DFL); } CSC 382: Computer Security
Format Strings printf() family functions provide a formatting minilanguage • Format string copied to destination (file, string, or terminal). • Percent(%) symbols in string indicate substitutions. Example functions • scanf() • sprintf() • syslog() CSC 382: Computer Security
printf() family dangers User-specified format strings • userstring = “foo %x”; • printf( userstring ); • Where can it find arguments to replace %x? • The Stack: %x reads 4-bytes higher in stack Solution: Use printf( “%s”, userstring ) or fputs( userstring ) CSC 382: Computer Security
printf() family dangers (cont.) Buffer overflows char buf[256]; sprintf( buf, “The data is %s\n”, userstring ); Specify “precision” of string substitution sprintf(buf,“The data is .32%s\n”,userstring ); Use snprintf (C99 standard function) snprintf(buf,255,“The data is %s\n”, userstring ); CSC 382: Computer Security
%n format command Number of characters written so far is stored into the integer indicated by the int * pointer argument. char buf[] = "0123456789"; int *n; printf(“buf=%s%n\n", buf, n); printf("n=%d\n", *n); Output: • buf=0123456789 • n=14 CSC 382: Computer Security
%n format attack Plan of Attack • Find address of variable to overwrite • Place address of variable on stack (as part of format string) so %n will write to that address • Write # of characters equal to value to insert into variable (use precision, e.g., %.64x) Use %n to write anywhere in memory • Address on stack can point to any location CSC 382: Computer Security
Web-based Input Client and Server Perspectives Types of Input • URL parameters • HTML • Cookies • Javascript Cross-Site Scripting CSC 382: Computer Security
Client Perspective Client Perspective • Web page from server may contain bad code • ActiveX • Javascript • Java • Cookies CSC 382: Computer Security
Server Perspective • No data sent to client is secret: • Hidden fields • Cookies • Client is not required to use your HTML forms to submit data. • URL queries can have any format. • POST data can have any format. • Client can send arbitrary cookie data . CSC 382: Computer Security
URL Parameters <proto>://<user>@<host>:<port>/<path>?<qstr> Whitespace marks end of URL “@” separates userinfo from host “?” marks beginning of query string “&” separates query parameters %HH represents character with hex values • ex: %20 represents a space CSC 382: Computer Security
URL Parameters • Client controls query-string • Cannot limit values to those specified in form. • Any character can be URL-encoded. • Any valid format may be used to disguise true destination of URL. CSC 382: Computer Security
HTML Special Characters “<“ begins a tag “>” ends a tag • some browsers will auto-insert matching “<“ “&” begins a character entity • ex: < represents literal “<“ character Quotes(‘ and “) used to enclose attribute values. CSC 382: Computer Security
Character Set Encoding • Default: ISO-8859-1 (Latin-1) • Char sets dictate which chars are special • UTF-8 allows multiple representations • Force Latin-1 encoding of web page with: • <META http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1”> CSC 382: Computer Security
Hidden Fields <input type=“hidden” name=“user” value=“james”> • Used to propagate data between HTTP requests since protocol is stateless. • Clearly visible in HTML source. • Form can be copied, modified to change hidden fields, then used to invoke script. CSC 382: Computer Security
Cookies Parameters • Name • Value • Expiration Date • Domain • Path • Secure Connections Only CSC 382: Computer Security
Cookies Server to Client Content-type: text/html Set-Cookie: foo=bar; path=/; expires Fri, 20-Feb-2004 23:59:00 GMT Client to Server Content-type: text/html Cookie: foo=bar CSC 382: Computer Security
Secure Cookie Authentication • Encrypt cookie so user cannot read • Include expiration time inside cookie • Include client IP address to avoid hijacking • Use another cookie with MAC of first cookie to detect tampering • Use secret key as part of MAC so client does not have necessary information to forge CSC 382: Computer Security
Javascript Input Validation User-friendly • convenient, immediate feedback. Not secure • Client can turn off Javascript. • Client may not use your form. CSC 382: Computer Security
Cross-Site Scripting • Attacker sends HTML to web site (e.g., message board, guestbook), which is used to attack other clients browsing the site • Goals: • Steal Information (cookies) • Redirect Client to Exploit Site CSC 382: Computer Security
Cross-Site Scripting Typical Attack: Javascript redirect • document.location.replace(‘http://evil.com/’) • Javascript can read cookies and pass them as form parameters to new destination. • May be embedded in different ways: • <script> … </script> • onmouseover, onclick attributes of many tags CSC 382: Computer Security
Preventing XSS Disallow HTML • Reject any input with HTML. • Replace HTML special characters • ex: replace < with < and > with > Allow only safe HTML tags • Escape all HTML tags except whitelisted ones. CSC 382: Computer Security
Database Input SQL Injection • Most common flaw in database input parsing. • Don’t pass unvalidated data to database. • Whitelist for known safe character set. • Alphanumerics • How many symbols do you need to accept? CSC 382: Computer Security
Other Inputs Default file permissions • umask(066); Resource Limits • May suffer DoS if parent imposes strict limits on CPU time, # processes, file size, stack size. • Use setrlimit() to limit core dump size to zero if program ever contains confidential data in memory, e.g., unencrypted passwords. CSC 382: Computer Security
Language-Specific Features • Perl • PHP • Eiffel CSC 382: Computer Security
Perl’s Taint Mode Perl monitors all outside input (args, user input, environment vars) and stops when program attempts a dangerous action using that input. #!/usr/bin/perl –T $user = <STDIN>; chomp($user); system(“cat /usr/stats/$user”); CSC 382: Computer Security
Perl’s Taint Mode • On attempt to execute, perl aborts: • Insecure $ENV{PATH} • Add a safe PATH: • $ENV{PATH} = ‘/bin:/usr/bin’; • On attempt to execute new code, aborts: • Insecure dependency in system. • Allow only safe characters: • $user =~ /([A-Za-z0-9]+)/; • $user = $1; CSC 382: Computer Security
PHP magic_quotes_gpc • If set, automatically escapes single quotes, double quotes, backslash(\), and NUL register_globals • If set, auto-creates form arguments as vars <?php $success = validatePassword( $password ); if( $success ) { } ?> • Bypass check by adding “success=1” to query string CSC 382: Computer Security
Eiffel put (x: ELEMENT; key: STRING)is -- Insert x so that it will be retrievable through key. require count <= capacity not key.empty do ... Some insertion algorithm ... ensure has (x) item (key) = x count = old count + 1 end CSC 382: Computer Security
Design by Contract Contract • Preconditions • Invariants • Postconditions Contracts in other languages • assert() in C/C++ • Class::Contract in perl • JMSassert annotations for Java CSC 382: Computer Security
Key Points • Don’t trust that input has expected properties. • Trust is Transitive. • Validate all input using whitelisting. • Avoid blacklisting bad input. • Many entry points exist beyond the obvious. • Language features can help you find or prevent input-based attacks. CSC 382: Computer Security
References • Matt Bishop, Introduction to Computer Security, Addison-Wesley, 2005. • CERT, “Understanding Malicious Content Mitigation for Web Developers,” http://www.cert.org/tech_tips/malicious_code_mitigation.html, Feb. 2000 • Cgisecurity.com, “The Cross Site Scripting FAQ,” http://www.cgisecurity.com/articles/xss-faq.shtml, Aug. 2003. • Eiffel Site, “Building bug-free O-O software: An introduction to Design by Contract,” http://archive.eiffel.com/doc/manuals/technology/contract/ • 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, http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/index.html, 2003. CSC 382: Computer Security