Internet Security

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

Internet Security [1]

VU 188.366

Web Application Security (1/2)


Paolo Milani Comparetti, Christian Platzer, Gilbert Wondracek, Markus Huber, Edgar Weippl [email protected]

News from the Lab


Int. Secure Systems Lab Vienna University of Technology

About 88 people solved Challenge 1


good work!

Challenge 2 will start tomorrow


start of challenge scheduled at 10:00 SQL Injection

Internet Security 1

Overview
Int. Secure Systems Lab Vienna University of Technology

Web Application Security (I + II)


basics the (2010) OWASP Top Ten Web application vulnerabilities SQL injections parameter injections broken authentication Cross Site Scripting web-based buffer overflows / mitigation insecure storage DoS attacks

Internet Security 1

Web Application Security


Int. Secure Systems Lab Vienna University of Technology

Web Application very short definition: a program that runs on a server, accepts input from outside via the web, processes it, and finally returns some answer Typical setting a web application is deployed it accepts HTTP requests from about anyone. this means that your web application code is part of your security perimeter

Internet Security 1

Web Application Security


Int. Secure Systems Lab Vienna University of Technology

Perimeter based security controlling access on all entry / exit points of the network

Internet Security 1

Web Application Security


Int. Secure Systems Lab Vienna University of Technology

Perimeter based security controlling access on all entry / exit points of the network

Internet

mail server mail server db server db server ... server ... server web server web server client host client host client host client host client host client host client host client host
6

Internet Security 1

Web Application Security


Int. Secure Systems Lab Vienna University of Technology

Perimeter based security controlling access on all entry / exit points of the network

Internet

mail server mail server db server db server ... server ... server web server web server client host client host client host client host client host client host client host client host
7

Internet Security 1

On a typical Web server


Int. Secure Systems Lab Vienna University of Technology

Your host has port 80 open Some server-side software is running


OS web server main application (e.g., Apache) plugins servlets script interpreters (CGI Common Gateway Interface, Perl, ...) big vulnerability surface attacks that are hidden in valid HTTP requests often pass firewalls without notice
Internet Security 1 8

HTTP and Web Application Basics


Int. Secure Systems Lab Vienna University of Technology

HTTP protocol used to talk to web applications (request web site, send data, receive response) HTTP transactions follow the same general format 3 part client request / server response request or response line header section entity body client initiates a transaction as follows:
GET/index.html?param=valueHTTP/1.0 GET/index.html?param=valueHTTP/1.0

Internet Security 1

HTTP and Web Application Basics


Int. Secure Systems Lab Vienna University of Technology

All HTTP transactions follow the same general format 3 part client request / server response request or response line header section no entity body client initiates a transaction as follows:
GET/search?q=searchtermHTTP/1.1 GET/search?q=searchtermHTTP/1.1 Host:www.google.at Host:www.google.at UserAgent:Mozilla/5.0Firefox/3.5.8 UserAgent:Mozilla/5.0Firefox/3.5.8 Accept:text/html,... Accept:text/html,... AcceptLanguage:enus,en;q=0.5 AcceptLanguage:enus,en;q=0.5 AcceptEncoding:gzip,deflate AcceptEncoding:gzip,deflate AcceptCharset:ISO88591,utf8;q=0.7,*;q=0.7 AcceptCharset:ISO88591,utf8;q=0.7,*;q=0.7
Internet Security 1 10

HTTP and Web Application Basics


Int. Secure Systems Lab Vienna University of Technology

All HTTP transactions follow the same general format 3 part client request / server response request or response line header section entity body server replies to a transaction as follows:
HTTP/1.1200OK HTTP/1.1200OK Date:Fri,09Apr201012:40:23GMT Date:Fri,09Apr201012:40:23GMT ContentType:text/html;charset=UTF8 ContentType:text/html;charset=UTF8 <html><head> <html><head> <title>searchtermGoogleSearch</title> <title>searchtermGoogleSearch</title> </head><bodybgcolor="#e5eecc"> </head><bodybgcolor="#e5eecc">
Internet Security 1 11

HTTP and Web Application Basics


Int. Secure Systems Lab Vienna University of Technology

All HTTP transactions follow the same general format 3 part client request / server response request or response line header section entity body server replies to a transaction as follows:
HTTP/1.1200OK HTTP/1.1200OK Date:Fri,09Apr201012:40:23GMT Date:Fri,09Apr201012:40:23GMT ContentType:text/html;charset=UTF8 ContentType:text/html;charset=UTF8 ContentEncoding:gzip ContentEncoding:gzip e0a e0a .............r...=_.....P.(.*.....6.$.t..tg... .............r...=_.....P.(.*.....6.$.t..tg...
Internet Security 1 12

HTTP and Web Application Basics


Int. Secure Systems Lab Vienna University of Technology

All HTTP transactions follow the same general format 3 part client request / server response request or response line header section entity body After sending the request and headers, the client may send additional data form data mostly used by CGI programs using the POST method for the GET method, the parameters are encoded into the URL
Internet Security 1 13

HTTP and Web Application Basics


Int. Secure Systems Lab Vienna University of Technology

All HTTP transactions follow the same general format 3 part client request / server response request or response line header section entity body client initiates a transaction as follows:
POST/searchHTTP/1.1 GET/search?q=searchtermHTTP/1.1 POST/searchHTTP/1.1 GET/search?q=searchtermHTTP/1.1 Host:www.google.at Host:www.google.at Host:www.google.at Host:www.google.at ... UserAgent:Mozilla/5.0Firefox/3.5.8 ... UserAgent:Mozilla/5.0Firefox/3.5.8 ContentType:application/xwwwformurlencoded Accept:text/html,... ContentType:application/xwwwformurlencoded Accept:text/html,... ContentLength:12 AcceptLanguage:enus,en;q=0.5 ContentLength:12 AcceptLanguage:enus,en;q=0.5 AcceptEncoding:gzip,deflate AcceptEncoding:gzip,deflate q=searchterm AcceptCharset:ISO88591,utf8;q=0.7,*;q=0.7 q=searchterm AcceptCharset:ISO88591,utf8;q=0.7,*;q=0.7
Internet Security 1 14

Web Server Scripting


Int. Secure Systems Lab Vienna University of Technology

HTTP alone is usually not enough to create web apps scripting languages are used to increase the functionality examples: Perl, Python, ASP, JSP, PHP Script interpreters are installed on the Web server usually return HTML output that is then forwarded to the client Template engines are often used to power web sites
e.g., Cold Fusion, Cocoon, Zope these engines often use scripting languages
Internet Security 1 15

Web Application Example


Int. Secure Systems Lab Vienna University of Technology

Objective: Write an application that accepts a username and password and echoes (displays) them First, we write HTML code and use forms
<html><body> <html><body> <formaction=/scripts/login.plmethod=post> <formaction=/scripts/login.plmethod=post> Username:<inputtype=textname=username><br> Username:<inputtype=textname=username><br> Password:<inputtype=passwordname=password><br> Password:<inputtype=passwordname=password><br> <inputtype=submitvalue=Loginname=login> <inputtype=submitvalue=Loginname=login> </form> </form> </body></html> </body></html>
Internet Security 1 16

Web Application Example


Int. Secure Systems Lab Vienna University of Technology

Second, here is the corresponding Perl script that prints the username and password passed to it:
#!/usr/local/bin/perl #!/usr/local/bin/perl usesCGI; usesCGI; $query=newCGI; $query=newCGI; $username=$query>param(username); $username=$query>param(username); $password=$query>param(password); $password=$query>param(password); ... ... print<html><body>Username:$username<br> print<html><body>Username:$username<br> Password:$password<br> Password:$password<br> </body></html>; </body></html>;
Internet Security 1 17

Know Your Enemy


Int. Secure Systems Lab Vienna University of Technology

Most web app users will be benign, but...


even if you think you are too small for hackers to target you, you should expect attacks automated attacks happen all the time
automated SQL injections often hit thousands of websites

even Intranet applications can be vulnerable from outside malicious content delivered through Web browsing can compromise or hijack intranet client nodes and cause them to attack an intranet web application possible measure against insider attacks: Define policies so that internal users cannot access your web application

Internet Security 1

18

OWASP
Int. Secure Systems Lab Vienna University of Technology

Open Web Application Security Project www.owasp.org


dedicated to help organizations understand and improve the security of their web applications and web services. Top Ten vulnerability list was created to point corporations and government agencies to the most serious of these vulnerabilities. web application security has become a hot topic as companies race to make content and services accessible though the web. At the same time, attackers are turning their attention to the common weaknesses created by application developers.
Internet Security 1 19

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A1Injection A1Injection Injection flaws occur when untrusted data is sent to an interpreter as part of a command or query.
Examples: SQL, OS, and LDAP injection,

Vienna University of Technology

Data sent by the attacker is being interpreted as commands in the application context SELECT * FROM T WHERE X=[5] SELECT * FROM T WHERE X=[5; DELETE * FROM T;]
Internet Security 1 20

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A2CrossSite A2CrossSite Scripting(XSS) Scripting(XSS)

Vienna University of Technology

XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation and escaping. XSS allows attackers to execute script in the victims browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.

Internet Security 1

21

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A3BrokenAuth. A3BrokenAuth. andSessionManagement andSessionManagement Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, session tokens, or exploit implementation flaws to assume other users identities.

Vienna University of Technology

Internet Security 1

22

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A4InsecureDirect A4InsecureDirect ObjectReferences ObjectReferences

Vienna University of Technology

A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.

Internet Security 1

23

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A5CrossSite A5CrossSite RequestForgery(CSRF) RequestForgery(CSRF)

Vienna University of Technology

A CSRF attack forces a logged-on victims browser to send a forged HTTP request, including the victims session cookie and any other authentication information, to a vulnerable web application. This allows the attacker to force the victims browser to generate requests the vulnerable application thinks are legitimate requests from the victim.
Internet Security 1 24

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A6Security A6Security Misconfiguration Misconfiguration

Vienna University of Technology

Security depends on having a secure configuration defined for the application, framework, web server, application server, and platform. All these settings should be defined, implemented, and maintained as many are not shipped with secure defaults.

Internet Security 1

25

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A7Insecure A7Insecure CryptographicStorage CryptographicStorage Many web application do not properly protect sensitive data, such as credit cards, SSNs, and authentication credentials, with appropriate encryption or hashing. Attackers may use this weakly protected data to conduct identity theft, credit card fraud, or other crimes.
Internet Security 1

Vienna University of Technology

26

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A8Failureto A8Failureto RestrictURLAccess RestrictURLAccess

Vienna University of Technology

Many web applications check URL access rights before rendering protected links and buttons. However, applications need to perform similar access control checks when these pages are accessed, or attackers will be able to forge URLs to access these hidden pages anyway.

Internet Security 1

27

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A9InsufficientTrans A9InsufficientTrans portLayerProtection portLayerProtection Applications frequently fail to encrypt network traffic when it is necessary to protect sensitive communications. When they do, they sometimes support weak algorithms, use expired or invalid certificates, or do not use them correctly.

Vienna University of Technology

Internet Security 1

28

Top Ten Web Application Vulnerabilities Int. Secure Systems Lab


A10Unvalidated A10Unvalidated RedirectsandForwards RedirectsandForwards

Vienna University of Technology

Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

Internet Security 1

29

More Web Application Vulnerabilities Int. Secure Systems Lab


Former5Buffer Former5Buffer Overflows Overflows

Vienna University of Technology

Buffer overflows: Web application components in languages that do not properly validate input can be crashed and, in some cases, used to take control of a process. These components can include CGI, libraries, drivers, and web application server components.

Internet Security 1

30

More Web Application Vulnerabilities Int. Secure Systems Lab


Former7Improper Former7Improper ErrorHandling ErrorHandling Error conditions that occur during normal operation are not handled properly. If an attacker can cause errors to occur that the web application does not handle, they can gain detailed system information, deny service, cause security mechanisms to fail, or crash the server.

Vienna University of Technology

Internet Security 1

31

More Web Application Vulnerabilities Int. Secure Systems Lab


Former9Denialof Former9Denialof Service(DoS) Service(DoS)

Vienna University of Technology

Attackers can consume web application resources to a point where other legitimate users can no longer access or use the application Attackers can also lock users out of their accounts or even cause the entire application to fail.

Internet Security 1

32

More Web Application Vulnerabilities Int. Secure Systems Lab


Former1Unvalidated Former1Unvalidated Input Input

Vienna University of Technology

Information from web requests is not validated before being used by a web application. Attackers can use these flaws to attack backend components through a web application. Root cause for many attacks current Top 10 more precise on vulnerability classes
Internet Security 1 33

Unvalidated Input
Int. Secure Systems Lab Vienna University of Technology

Web applications use input from HTTP requests (and occasionally files) to determine how to respond.
attackers can tamper with any part of an HTTP request, including the URL, query string, headers, cookies, form fields, and hidden fields, to try to bypass the sites security mechanisms. common input tampering attempts include XSS, SQL injection, hidden field manipulation, parameter injection

Some sites attempt to protect themselves by filtering malicious input.


problem: there are many different ways of encoding information
Internet Security 1 34

Unvalidated Input
Int. Secure Systems Lab Vienna University of Technology

Many web applications rely on client-side mechanisms to validate user input


client side validation mechanisms are easily bypassed, leaving the web application without any protection against malicious parameters

How to determine if you are vulnerable?


the traditional way: have a detailed code review, searching for all the calls where information is extracted from an HTTP request easy to miss code parts, manual effort high

Internet Security 1

35

Unvalidated Input
Int. Secure Systems Lab Vienna University of Technology

Taint analysis can be used to find vulnerabilities


initially, taint (mark) each user provided input. propagate information during code execution:
variable assignments, modifications, etc.

remove taint status when content is sanitized. do not allow tainted data as arguments for security relevant system interaction:
executing commands, accessing database, etc.

Perl
built in support for taint analysis

Pixy
PHP taint engine (http://pixybox.iseclab.org)
Internet Security 1 36

Unvalidated Input
Int. Secure Systems Lab Vienna University of Technology

Perl script that looks for files:


my$arg=shift; my$arg=shift; my$arg_len=length($arg); my$arg_len=length($arg); if($arg_len<=0){ if($arg_len<=0){ print"boring\n"; print"boring\n"; exit(1); exit(1); } } print"displayingfileswithfilter'$arg':\n"; print"displayingfileswithfilter'$arg':\n"; system("ls$arg"); system("ls$arg");

No Validation!

Internet Security 1

37

Unvalidated Input
Int. Secure Systems Lab Vienna University of Technology

Looking for files (revisited), bad sanitation:


my$arg=shift; my$arg=shift; ... ... if($arg=~m/;/){ if($arg=~m/;/){ print"mymothertoldmetosanitizeinput!\n"; print"mymothertoldmetosanitizeinput!\n"; exit(1); exit(1); } } print"displayingfileswithfilter'$arg':\n"; print"displayingfileswithfilter'$arg':\n"; system("ls$arg"); system("ls$arg");

Internet Security 1

38

Unvalidated Input
Int. Secure Systems Lab Vienna University of Technology

How to protect yourself?


the best way to prevent parameter tampering is to ensure that all parameters are validated before they are used. a centralized component or library is likely to be the most effective, as the code performing the checking should be all in one place.

Parameters should be validated against a positive specification that defines:


data type (string, integer, real, etc); allowed character set; minimum and maximum length; if null is allowed; if the parameter is required or not; if duplicates are allowed; numeric range; specific legal values (enumeration); specific patterns (regular expressions) .......

Internet Security 1

39

Unvalidated Input
Int. Secure Systems Lab Vienna University of Technology

Looking for files (once again), better sanitation:


my$arg=shift; my$arg=shift; ... ... if($arg=~m/^[AZaz09_\.*]*\. if($arg=~m/^[AZaz09_\.*]*\. [AZaz09_\.*]*$/){ [AZaz09_\.*]*$/){ print"displayingfileswith print"displayingfileswith filter'$arg':\n";system("ls$arg"); filter'$arg':\n";system("ls$arg"); } } else{ else{ print"mymothertoldmetosanitizeinput!\n"; print"mymothertoldmetosanitizeinput!\n"; } }
Internet Security 1 40

SQL Injections
Int. Secure Systems Lab Vienna University of Technology

Injection flaws allow attackers to relay malicious code through a web application to another system
these attacks include calls to the operating system via system calls, the use of external programs via shell commands, as well as calls to backend databases via SQL

SQL injection is a particularly widespread and dangerous form of injection attack


to exploit a SQL injection flaw, the attacker must find a parameter that the web application uses to construct a database query.

Internet Security 1

41

SQL Injections
Int. Secure Systems Lab Vienna University of Technology

By carefully embedding malicious SQL commands into the content of the parameter, the attacker can trick the web application into forwarding a malicious query to the database The consequences are particularly damaging, as an attacker can obtain, corrupt, or destroy database contents.

Internet Security 1

42

Simple SQL Injection Example


Int. Secure Systems Lab Vienna University of Technology

Perl script that looks up username and password:


... ... $query=newCGI; $query=newCGI; $username=$query>param(username); $username=$query>param(username); $password=$query>param(password); $password=$query>param(password); ... ... $sql_command=select*fromuserswhere $sql_command=select*fromuserswhere username=$usernameandpassword=$password; username=$usernameandpassword=$password; $sth=$dbh>prepare($sql_command) $sth=$dbh>prepare($sql_command) ... ...

No Validation!
Internet Security 1 43

Simple SQL Injection Example 2


Int. Secure Systems Lab Vienna University of Technology

If the user enters a (single quote) as the password, the SQL statement in the script would become:
SELECT*FROMusers WHEREusername=ANDpassword= SQL error message would be generated

If the user enters (injects): orusername=john as the password, the SQL statement in the script would become:
SELECT*FROMusers WHEREusername=ANDpassword= orusername=john hence, a different SQL statement has been injected than what was originally intended by the programmer!
Internet Security 1 44

Obtaining Information using Errors


Int. Secure Systems Lab Vienna University of Technology

Errors returned from the application might help the attacker (e.g., ASP default behavior)
Username: 'unionselectsum(id)fromusers Microsoft OLE DB Provider for ODBC Drivers error '80040e14' [Microsoft] [ODBC SQL Server Driver][SQL Server]Column 'users.id' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. thanks for the /process_login.asp, line 35

info :-) Make sure that you do not display unnecessary debugging and error messages to users.

for debugging, it is always better to use log files (e.g., error log).
Internet Security 1 45

Some SQL Attack Examples


Int. Secure Systems Lab Vienna University of Technology

select*;INSERTINTOuserVALUES(user,h4x0r);
attacker inserts a new user into the database

The attacker could use stored procedures (e.g., in SQL Server)


xp_cmdshell() bulk insert statement to read any file on the server e-mail data to the attackers mail account play around with the registry settings

SELECT*;DROPtableSensitiveData; Appending ; character does not work for all databases. Might depend on the driver (e.g., MySQL)

Internet Security 1

46

Advanced SQL Injection


Int. Secure Systems Lab Vienna University of Technology

Web applications will often escape the and characters (e.g., PHP).
this will prevent many SQL injection attacks but there might still be vulnerabilities

In some applications, database fields might not be strings but numbers. Hence, or characters are not necessary (e.g., WHEREid=1) Attacker might still inject strings into a database by using the char function (e.g., SQL Server):
INSERTINTOusers(id,name) VALUES(666,char(0x63)+char(0x65))
Internet Security 1 47

Blind SQL Injection


Int. Secure Systems Lab Vienna University of Technology

A typical countermeasure is to prohibit the display of error messages. But, is this enough?
no, your application may still be vulnerable to blind SQL injection

Lets look at an example:


suppose there is a news site press releases are accessed with pressRelease.jsp?id=5 SQL query is created and sent to the database: SELECTtitle,description FROMpressReleasesWHEREid=5; any error messages are smartly filtered by the application

Internet Security 1

48

Blind SQL Injection


Int. Secure Systems Lab Vienna University of Technology

How can we inject statements into the application and exploit it?
we do not receive feedback from the application so we can use a trial-and-error approach first, we try to inject pressRelease.jsp?id=5AND1=1 the SQL query is created and sent to the database: SELECTtitle,description FROMpressReleasesWHEREid=5AND1=1 if there is an SQL injection vulnerability, the same press release should be returned if input is validated, id=5AND1=1 should be treated as value

Internet Security 1

49

Blind SQL Injection


Int. Secure Systems Lab Vienna University of Technology

When testing for vulnerability, we know 1=1 is always true


however, when we inject other statements, we do not have any information what we know: If the same record is returned, the statement must have been true for example, we can ask server if the current user is h4x0r: pressRelease.jsp?id=5ANDuser_name()=h4x0r by combining subqueries and functions, we can ask more complex questions (e.g., extract the name of a database character by character)

Internet Security 1

50

Second Order SQL Injection


Int. Secure Systems Lab Vienna University of Technology

SQL is injected into an application, but the SQL statement is invoked at a later point in time
e.g., guestbook, statistics page, etc.

Even if application escapes single quotes, second order SQL injection might be possible
attacker sets user name to: john, application safely escapes value ( is used for expressing comments in SQL Server) at a later point, attacker changes password (and sets a new password for victim john): UPDATEusersSETpassword= WHEREdatabase_handle(username)=john
Internet Security 1 51

SQL Injection Solutions


Int. Secure Systems Lab Vienna University of Technology

Developers must never allow client-supplied data to modify SQL statements


best protection is to isolate application from SQL all SQL statements required by application should be stored procedures on the database server the SQL statements should be executed using safe interfaces such as JDBC CallableStatement or ADOs Command Object both prepared statements and stored procedures compile SQL statements before user input is added

Internet Security 1

52

SQL Injection Solutions


Int. Secure Systems Lab Vienna University of Technology

Let us use pressRelease.jsp as an example. Here our code:


Stringquery=SELECTtitle,descriptionfrom pressReleasesWHEREid=+ request.getParameter(id); Statementstat=dbConnection.createStatement(); ResultSetrs=stat.executeQuery(query);

The first step to secure the code is to take the SQL statements out of the web application and into DB
CREATEPROCEDUREgetPressRelease@idinteger AS SELECTtitle,description FROMpressReleasesWHEREid=@id
Internet Security 1 53

SQL Injection Solutions


Int. Secure Systems Lab Vienna University of Technology

Now, in the application, instead of string-building SQL, call stored procedure:


CallableStatementscs= dbConnection.prepareCall({call getPressRelease(?)}); i=Int.parseInt(request.getParameter(id)) cs.setInt(1,i); ResultSetrs=cs.executeQuery();

In ASP.NET, there is a similar mechanism

Internet Security 1

54

Discovering clues in HTML code


Int. Secure Systems Lab Vienna University of Technology

Developers are notorious for leaving statements like FIXME, Code Broken, Hack, etc... inside the source code. always review the source code for any comments denoting passwords, backdoors, or something doesn't work right. Hidden fields (<inputtype=hidden>) are sometimes used to store temporary values in Web pages. these can be changed with ease (hidden field tampering!) Tools can support, facilitate this task
Firebug (Firefox), Dragonfly (Opera)

Internet Security 1

55

Conclusion
Int. Secure Systems Lab Vienna University of Technology

In this lecture, we took a first look at higher-level security issues.


web applications can have many weaknesses we started with the web and will continue looking at it next week

Don't forget about Challenge 2 Good luck! Next week, we continue with web security Same time, same place

Internet Security 1

56

You might also like