Top Banner
OWASP PHP Security phpsec.owasp.org
59
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: PHPSEC Presentation Slides

OWASP PHP Securityphpsec.owasp.org

Page 2: PHPSEC Presentation Slides

A more interactive sessionWe would like to know your background.

So, if you have any means to click on this link and provide your information, please do so now.

https://www.surveymonkey.com/s/WJGC3PR

If you want to discuss some topic related to this presentation, you can discuss it here:

https://groups.google.com/forum/#!forum/appsecphpsec

Page 3: PHPSEC Presentation Slides

OWASP Meets PHP

Page 4: PHPSEC Presentation Slides

If you still don’t get the name, its abbreviation for PHP Security.

Page 5: PHPSEC Presentation Slides

Please don’t be afraid to ask questions in between.

Remember, I am more afraid of you, than you are right now. So just go ahead

and ASK.:P

Page 6: PHPSEC Presentation Slides

Who we are ?PHPSEC was started in Google Summer of Code 2013. After that

many open-source contributors showed interest, and eventually participated in it. Some of us whom you can contact for further information are:

1. Abbas Naderi: Current chapter leader of Iran, and a mentor in this project.

2. Rahul Chaudhary: GSOC 13 final candidate for this project. (E-Mail: [email protected])

Click our names for more info or scan the QR codes.

Page 7: PHPSEC Presentation Slides

Intended Audience• Security Guys : Anyone who is interested in web-application

security.

• Web Users: Anyone who uses web should know about general security stuff so that they can be aware of where things go WRONG!

• PHP Developers: Though the concepts are same across any platform, the codes are written in PHP, and the project is intended to be applied in PHP applications. So, I guess PHP guys will benefit more than NON-PHP guys.

Page 8: PHPSEC Presentation Slides

Disclaimer

Page 9: PHPSEC Presentation Slides

Disclaimer• PHPSEC, is intended to be used in PHP web-applications only.

Though the concepts used in PHPSEC will be almost the same throughout all the platforms.

• PHPSEC, is a 5 months old baby. It has not been tested thoroughly (but it will be), so even though we hate to say it, Please use it at your own RISK!

• And Though we will be extremely sad, we are not liable if the libraries / framework are vulnerable in real world. Instead tell us about the hacks and we will try to resolve it.

• Don’t be disappointed though, they are pretty robust and we’re updating them frequently!

Page 10: PHPSEC Presentation Slides

Similar Libraries• We know of three other libraries that work on the same principles, are open-source,

and are for PHP:

• jframework: Similar library as ours (courtesy of Abbas Naderi). jframework was built on top of PHPSEC, so they both are same in concepts, but has a lot more of what an actual PHP framework has (aside from security).

• phpSec: phpSec is open-sourced software licensed under the MIT License.

Link: https://github.com/phpsec/phpSec

• PHP-Security-Library: This library is similar to our “crypto” library.

Link: https://github.com/kaisellgren/PHP-Security-Library

Page 11: PHPSEC Presentation Slides

Brief Introduction• PHPSEC is a collection of security libraries and a combined

framework designed to mitigate the major security risks cited by OWASP in their yearly Top 10 list. Read more about the Top 10 list in the link below:

https://www.owasp.org/index.php/Top_10_2013-Top_10

• The libraries are a collection of secure functions which can be used by PHP developers to mitigate common risks while developing web applications.

Page 12: PHPSEC Presentation Slides

Brief Introduction (Cont.)• The framework is the general web structure made for any web-

application based on the MVC design. The framework implements some common functions such as login, signup, remember-me, forgot-password, etc based on the libraries.

PHPSEC

CONTROLLER

MODEL

VIEW

REQUEST

RESPONSE

Page 13: PHPSEC Presentation Slides

Overview

Page 14: PHPSEC Presentation Slides

List of Damages Mitigated using PHPSEC• Brute Force Attacks.

• Secure implementation of most common and most targeted functions such as “temporary password” and “remember-me”.

• Various functions to ensure security in passwords and to generate hard to guess captcha codes and generation of strong passwords.

• A secure and central time library.

• A secure Pseudorandom number generator (PRNG).

• Introduction to XSS safe output functions.

• XSS and code injection attacks.

Page 15: PHPSEC Presentation Slides

List of Damages Mitigated using PHPSEC (Cont.)

• Use of encryption within codes to encrypt sensitive information in configuration files such as login name and password of database connection, applications used and their version numbers etc.

• Safe passage to database which means NO SQL Injection attacks.

• Capability to mark suspicious strings and disallowing developers to use them. (Using tainted library)

• Static Scanner Library to scan the files to look for security holes.

• Numerous test cases to ensure the proper running of the project.

• A model framework showing the correct use of these libraries in a real world web-application.

Page 16: PHPSEC Presentation Slides

List of Damages Mitigated using PHPSEC (Cont.)

• A logs library to log every important event.

• Safe implementation of sessions by making them safe against:o Session Fixationo Session Guessingo Session Hijacking (Mitigation techniques used but no complete

eradication of the problem)o Incorrect Access to privilege levels (using session rolling i.e. changing

the session)

Page 17: PHPSEC Presentation Slides

Basic Password Library

Fool !!I’m Safe :)

Page 18: PHPSEC Presentation Slides

Basic Password Library• Why? Password is the only authentication method ruling in web-

apps.

• What? Keep Them Safe

• How? Entropy + No Ordered character + No personal info. in the password + Randomness + Hashing.

• If you know another method, contribute!

Page 19: PHPSEC Presentation Slides

Basic Password Library (Cont.)• Hey! my name is Tom and if I can concatenate my name with my

zip code, it seems a fairly strong password. BUZZZZER...WRONG!! This way you not only have exposed a weak password, but have also told attacker where you live.

• Among all user authentication methods, passwords are the most famous ones. Others also exist such as biometrics, smart cards, etc. but for web-applications, passwords is the only method ruling. So, we need to keep our passwords safe.

Page 20: PHPSEC Presentation Slides

Basic Password Library (Cont.)• In real world, the attackers have lots of nasty ways to break or

guess your passwords and this thing most people underestimate.

• But out there when you are creating your account in some random webpage, who is there to look for weak passwords. Some big companies know the risks, and so they enforce strong passwords. Some even enforce a password change policy after a certain period. But still not many websites. Most of them just store the passwords, and if some noob developers are pretty smart, they will hash it. Its NOT ENOUGH.

★ And this is where our PHPSEC’s Password Library kicks in ... Yayy!!

Page 21: PHPSEC Presentation Slides

Basic Password Library (Cont.)● There are many new features in our library that will help the

developers implement a strong method of ensuring strong passwords. Below is a comprehensive list :○ Entropy: It is the measure of randomness in a string. We made an

entropy function that does not allows passwords with an entropy below the given threshold.

○ Ordered Characters: People tend to use characters such as “abcd”, “1234”, etc. a lot. This sequence is pretty much easy to guess. Our functions not only checks for ordered characters in english alphabet, but also checks for strings such as “qwert”, “asdf”, etc. They are ordered characters in keyboard.

Page 22: PHPSEC Presentation Slides

Basic Password Library (Cont.)● Feature list (cont.) :

○ Phone No. and Dates: Phone numbers are dates are common passwords and their presence can be checked using our functions.

○ A strength function that uses all the above checks to calculate the strength of a password in the range between 0 and 1.

○ Function to generate a strong and random password which is hard to guess.

○ Secure Hashing: As indicated earlier, simple hashes are no more secure. They have their faults. But adding salt makes them even stronger. We have methods in this library that not only adds a static salt, but also dynamic salts on the passwords and then hash it to make it even securer.

Page 23: PHPSEC Presentation Slides

Basic Password Library (Cont.)● With these functions, password guessing is still not eradicated. The

mighty brute force is still there. But now at least you have some degree of protection.

And hey!

if you know some other way, PHPSEC is open source.

PLEASE DO ADD MORE FUNCTIONS.

THE MORE, THE BETTER.

Page 24: PHPSEC Presentation Slides

Advanced Password Library• Its predecessor, Basic Password Library works on making

passwords strong. This library is an extension to that. Here are the list of things it does:o Checks for “Brute Force Attacks” and if detected, notifies the

developers using logs, emails, exceptions, etc.o Supports sign-ups and activation of accounts (locked accounts)o Has functions to implement the “generation & validation” of temporary

passwords.

Page 25: PHPSEC Presentation Slides

User Library & Management• Every meaningful web-applications needs registered users for

personalizing the app for them. PHPSEC presents you with a fully loaded user library that can do almost all the basic tasks in a secure manner (the list is not exhaustive. Many more functions can be found there):o User Registrationo User Deletiono Password Updateso Account Lock/Inactiveo Password Agingo REMEMBER-ME functionality”, etc.

Page 26: PHPSEC Presentation Slides

Crypto Library

We took this image at random from the internet, and it is hilarious.

How cool would it be if everyone was this crazy !!

Page 27: PHPSEC Presentation Slides

• Any web application source code often contains sensitive information such as DB credentials, application configurations, etc. These are usually stored in some configuration files, which when hacked are easily stolen, putting the whole application and the organization in serious danger, via bypassing the whole application security measures.

Here we provide a way to mitigate that risk.

The crypto library encrypts all your sensitive data in run-time.

Crypto Library

Page 28: PHPSEC Presentation Slides

Crypto Library (Cont.)• The process is very easy. You mark the things that you think are

sensitive, and this library would encrypt those strings in run-time.o And replace them in your source code!

• Then it automatically decrypts it before use.

• The benefit is that even if your web server gets attacked, the credentials and the codes would still be encrypted and (probably) safe.

:UtfUYRF5867F=CRYPTO>>>>>>>

SENSITIVE DATA

NORMAL DATA

Page 29: PHPSEC Presentation Slides

Crypto Library (Cont.)Here is an example:Original File (Attacker can steal this):

$config[‘username’] = “root”;

$config[‘password’] = “mydogisfat”;

If PHPSEC used (Before first run):

$config[‘username’] = confidentialString(“root”);

$config[‘password’] = confidentialString(“mydogisfat”);

After a run, the contents of the source file changes:

$config[‘username’] = confidentialString(':sENSt7jtm5WBRy14P95atM8qa8ttFt0COQwkvyIKca8=');

$config[‘password’] = confidentialString(':G7vkJRN2l0XEoPYpwxG6vAMJczDojOz2vMrVe9SW7Vo=');

Every time the original string is needed back, (e.g. to make a connection to DB), the function confidentialString() will decrypt that data and return the original string to the program.

Page 30: PHPSEC Presentation Slides

Database Library

Page 31: PHPSEC Presentation Slides

Database Library• Secure connection to database and secure use of that channel is

one of the main concern in any organization and is the root to many problems.

• PHPSEC uses “adapter wrappers” to support different databases. In present, PHPSEC wraps three major database adapters, and with time, we hope to have adapters for all major databases.

MySQL PGSQL SQLite

Page 32: PHPSEC Presentation Slides

Database Library (Cont.)• Use of parameterized query and knowledge on how to use it

correctly is necessary which not every developer in the world possesses.

• In PHPSEC, we have developed several layers of functions and finally give the developers a single function SQL() that they can use to execute SQL queries. Internally these functions use parameterized queries in secure manner.

SQL("INSERT INTO `SESSION` (`SESSION_ID`, `DATE_CREATED`, `LAST_ACTIVITY`, `USERID`) VALUES (?, ?, ?, ?)", array($randomValue, time(), time(), $obj->getUserID()));

Page 33: PHPSEC Presentation Slides

Download Manager Library• The download manager library assists the application to serve

some files to the users.

• It overwrites the web server’s behavior, but allows your application to handle the requests and responseso You can authorize it then!

And you should :|o You can manage the bandwidtho And anything else you want

• It supports HTTP Range and almost everything else a webserver can do

Page 34: PHPSEC Presentation Slides

HTTP Library• The HTTP Library contains functions to handle HTTP Requests.

o Information extraction from URL such as internal request, base URL, URI information, host, domain, etc are just to name a few.

o Functions to extract Protocol/Port information, etc.o Functions to determine application type - CLI, GUI.o Information such as server IP, root, HTTP Method, etc.

• Few Examples:o HTTP::isCLI() answers true if the application is being called from

command line. False, if called normally from web interface.o HTTP::ChangeProtocol() changes the current protocol. E.g. HTTP to

HTTPS.

• These are usually done messy, and are roots of many vulnerabilities.

Page 35: PHPSEC Presentation Slides

Tainted Library• Taint tracking is one of the very effective scientific approaches to

software security!

• This unique library has the capability to warn the developers if they are using strings which have not been sanitized, but need to be; and thus can contain maliciousness.

• The tainted library can be used to mark the user input strings. Once marked, this library would produce alerts/exceptions whenever the use of this string is used, without “Decontaminating” it first.

Page 36: PHPSEC Presentation Slides

Tainted Library (Cont.)• E.g.:

$malicious = “<script>alert(‘hacked!’);</script>”;

$taintedObject->contaminate($malicious);

• Now every time this $malicious is used in the project, this error will be thrown:

"Trying to use tainted variable without decontamination.";

• Until and unless, the string has been sanitized and the following function is not run on this string,

$taintedObject->decontaminate($malicious);

the exceptions would continue to be thrown.

Page 37: PHPSEC Presentation Slides

Logs Library• Logs are as we know extremely important to catalog what is

happening in the system. PHPSEC has its own logs library with several functionalities to help the developers keep logs of important actions in the system.

• Logs have the following capabilities:o Capability of logs to use files, DB, EMail, or SYSLog as a storage

medium. E.g: Important logs can be sent to admin’s email.o It also contains easy to use and 100% customizable config files that

makes the classification of logs a piece of cake.o Classification of logs can be of developers choice.

(Example in the following slide)

Page 38: PHPSEC Presentation Slides

Logs Library (Cont.)

• An example of logs stored in library is given:

• Note that each of the column given can be customized according to the developer’s need.

Page 39: PHPSEC Presentation Slides

Session Library: What are Sessions ?• The HTTP protocol is connectionless i.e. every request sent to the

server can be completed on its own and does not requires the server to know what was the last request sent.

• In other words, the requests are atomic. Each request can be completed on its own.

• Infact there is no way for the servers to know whose request is it. For it, every request is same.

• So, for identification you can send your username with each request. But you are smart! you see the problem here. The server will definitely know “whose” request is it; but will not know “who” sent it. Maybe the attacker is sending that request on your behalf.

Page 40: PHPSEC Presentation Slides

Session Library: What are Sessions ?• So, instead of usernames, the server generates a long “random”

string called sessionID and associates this ID with your username in its memory and also sets it in your browser so that you can send it with each request. When the server receives this sessionID, it cross checks this random string to get your userID and this is how the server knows its you who sent it.

• Now the attacker cannot know the string because its random and so they cannot send the request on your behalf.

Page 41: PHPSEC Presentation Slides

Session Library: Problems solved with PHPSEC• There are many problems with sessions using the current HTTP

Protocol.

• PHPSEC has many functions that deals with some of them:o Suggestion to use HTTPS to prevent “Session Hijacking”.o Prevention of “Session Fixation” by cross checking the session

IDs in the server.o Easy to use control layout to control session expiry and

session inactivity time.

Page 42: PHPSEC Presentation Slides

Session Library: Problems solved with PHPSECo OWASP PHPSEC replaces the existing file based session

handling with database based session handling on the server to make it more secure and robust.

o Any session data set by users are also stored in the DB.o Ability of sessions to roll i.e. the developers can change the

session ID if privilege escalation/de-escalation happens. This ensures that the attacker cannot use the same session for all privileged actions. Also this helps in mitigating authentication attacks because low privilege sessions cannot be used to access private contents.

Page 43: PHPSEC Presentation Slides

Core Library• The libraries in PHPSEC are decoupled i.e. they can be used in a

stand-alone manner. However there are certain classes under “core” library that are used in almost all of the other libraries.

• Classes under this library are:a. Time - To provide time.

b. Random - To provide random strings and numbers.

c. Loader - Used internally by the framework.

d. Errors - To convert errors to exceptions in PHP environment.

e. Functions - Functions to sanitize strings of XSS attacks.

Page 44: PHPSEC Presentation Slides

Time Class• Quite often developers need to change the system time, whether for

testing purpose for different time-zones or to trigger time base events inside the php application.

• This can be achieved along with the time() function, which normally gives the developer a hard time using it. Changing the system time could lead to all sets of problems, since it affects the server’s actual time, in worst instance, can corrupt authentication servers such as “Kerberos”.

• Thus, for all the reasons stated above, we strongly felt the need to generate a wrapper for time, so that change of time within an application can be isolated, controlled and must not affect any other application or system outside the scope of the application itself.

Page 45: PHPSEC Presentation Slides

Time Class (Cont.)• This class is a wrapper library for PHPs own "time()" function.

• With the use of this library, our aim was to isolate our system with the "system clock" which is used by the PHP's "time()" function.

• This approach lets us move time forward (future), backwards (past), reset to a different time and that time would be reflected in all of the application, without having to change any other component in the system or application.

Page 46: PHPSEC Presentation Slides

Time Class (Cont.)The time function within the class, accepts 2 parameters, “mode” and

“desired time”:

• “CURR” (default mode) : Used to request current time;

• “SET” : Used to set time to a desired time. The second argument here takes the desired time in unix timestamp format;

• “RESET” : Used to reset time to the original system time;

• “MOV” : Used to move time backward. The second argument here takes the time difference that is to be moved. e.g. 3600 will move the clock backward 3600 seconds;

• SYS: Used to request system time and will return the correct system time irrespective of any changes applied to with within this class.

Page 47: PHPSEC Presentation Slides

Random Class• The need of randomness is crucial in any application, whether with

numbers or strings, these values are essential to provide additional security. E.g. Session ID’s, Shared Private URL’s.

• PHPSEC has a separate central library that can provide random strings of desired length.

• This allows the developers to create secure strings of desired length and can also generate a random integer within a desired range.

Page 48: PHPSEC Presentation Slides

Random Class (Cont.)• To keep consistency between our application and PHP, we created

our "rand()" function with the same name as PHP's "rand()" function. Thus within our library, calling "rand()" function automatically calls PHPSEC's rand() function rather than PHP's rand() function.

• Behind the scenes, we use cryptographically secure PRNG’s such as openssl, mcrypt, etc, infused with some system parameters such as “posix_getpid” and “memory_get_usage”.

Page 49: PHPSEC Presentation Slides

• Every language has it’s own way to manage errors. Some of them are even spread along several categories, which needs special treatment, i.e. a simple error or an exception.

• Since PHP handles errors and exceptions in different ways, it forces the developer to add extra codes to catch it all.

• This introduces many confusion among developers as they are accustomed to treat everything as an "Exception" and expect

them to be thrown automatically.

Error Class

Page 50: PHPSEC Presentation Slides

• The purpose of this class is to provide a simple mechanism to control/register any abnormal problem that could prevent the correct logic flow.

• It could be triggered by:o PHP Error. (E.g. Divide By Zero)o An Exception.o Access to a private property.o Incorrect use/access of a function/class.

Error Class (Cont.)

Page 51: PHPSEC Presentation Slides

• Also it works as an extra layer over the exception/error so that they all can be processed as an exception, this will simplify the developer’s work.

• This class uses PHP mechanism that allows developers to register their own function in case an error is generated. So, PHPSEC Error class, upon requested by the developer, will register it’s own error handling functions to convert normal errors to exception

Error Class (Cont.)

Page 52: PHPSEC Presentation Slides

• enable: This function upon request, will register PHPSEC’s Error function in the PHP mechanism (if not already enabled).

• disable: This function does the exact opposite of the "Enable" function; will revert the error handling back to PHP.

• _shutdown: Allows to catch fatal errors, meaning, the applications will have a last chance to correct the fatal error and to save the application or to handle the error gracefully; Our implementation of this function only considers "E_ERROR", "E_CORE_ERROR", "E_PARSE", "E_COMPILE_ERROR" and "E_USER_ERROR" as fatal and simply warns the user of this error before failing the application.

• _errorToException: This function converts the PHP's error to "Exceptions". The exception that is generated is called "ErrorException".

• dump:It dumps an exception in readable format.

Error Class - How it works?

Page 53: PHPSEC Presentation Slides

Functions Module• Frequently developers write code that does not checks the user

inputs, thus, leaving the application open for any attack vector. While, most developers, are aware of security issues related with XSS, it isn’t an easy task to write codes to mitigate it.

• With this in mind, we have created a set of function to replace some of the most common misuse of PHP’s function when echoing data.

Page 54: PHPSEC Presentation Slides

Functions Module (Cont.)• This library contains a set of functions to help sanitize strings from

XSS attacks:o xss_safe : returns equivalent XSS safe string.

• Provides functions that are XSS safe :o exho, exhos and echo_br : echo replacements.o echof : Replacement for echo, with formatting and ability to dump

extra elements and attributes.o printf, vprintf : Implementation that escapes all arguments.

Page 55: PHPSEC Presentation Slides

Scanner Tool

• PHPSEC intends to provide a huge set of tools to aid the developers find security holes in the project.

• One of such tool is the Scanner Tool. This tool is a static code analyzer which scans the code and looks for particular holes.

• In the first version, this tools checks for PHP tokens such as “echo” and “printf”. Since use of these functions can result in XSS attacks (As discussed in the “Functions Library”), this tools checks for the presence of these keywords and suggests our own functions such as “xss_safe”, “exho”, etc.

Style of display and the format are 100% customizable.

Page 56: PHPSEC Presentation Slides

Scanner Tool (Cont.)

• Scanner Tool by default reports in two different formats:o Normal.o GCC Style.

Page 57: PHPSEC Presentation Slides

Roadmap1. PHP RBAC - Courtesy of OWASP RBAC Project.

Link: http://phprbac.net/

2. Secure Cache Control Library - For cache control

3. Secure i18 Library - For internationalization i.e the process of making an application usable to different locales and languages.

4. Secure Observer Pattern Library - Observer pattern is being used for extensibility in many applications today (e.g Wordpress). Unfortunately this has many side-effects and a secure library needs to handle them.

5. Secure SOAP and REST Library - This library handles web service security for PHP.

6. Depends on YOU!

Page 58: PHPSEC Presentation Slides

Project Code Page:

https://github.com/owasp/phpsec

Project Sample Application Page:

https://github.com/rash805115/rnj

Project Official Website:

(Main): http://phpsec.owasp.org/

(Docs): https://www.owasp.org/index.php/Projects/OWASP_PHP_Security_Project/Roadmap

Project OWASP’s Website:

https://www.owasp.org/index.php/Phpsec

Project Presentation:

https://docs.google.com/presentation/d/1hReOoKa-FxbKhVgH3rrrbHxnOGJe7kpp1gABUDIgeU8/edit?usp=sharing

Links

Page 59: PHPSEC Presentation Slides

Pheewww!! I did it.Thank You.

Last pause to ask Questions!!

Please rate this presentation here.https://www.surveymonkey.com/s/WQBQ3WK