php web app security (eng)

64
PHP Web Application Security 28/03/2012

Upload: anatoliy-okhotnikov

Post on 14-May-2015

4.158 views

Category:

Technology


1 download

DESCRIPTION

● PHP and the OWASP Top Ten Security Vulnerabilities ● Secure Programming With The Zend Framework ● Apache HTTPD Security ● MySQL Security ● PHP Security Tools

TRANSCRIPT

Page 1: Php web app security (eng)

PHP Web Application Security28/03/2012

Page 2: Php web app security (eng)

Softjourn Inc.

PHP Web Application Security

Anatoliy Okhotnikov

Softjourn Inc.

Page 3: Php web app security (eng)

PHP Web Application Security

Page 4: Php web app security (eng)

3/27/12

Agenda● PHP and the OWASP Top Ten Security

Vulnerabilities

● Secure Programming With The Zend Framework

● Apache HTTPD

Security

● MySQL Security

● PHP Security Tools

Page 5: Php web app security (eng)

PHP and the OWASP Top 10 The Open Web

Application Security Project released a helpful document that lists what they think are the top ten security vulnerabilities in web applications

These vulnerabilities can, of course, exist in PHP applications

Page 6: Php web app security (eng)

1. Unvalidated Parameters Turn off register_globals. Access values from

URLs, forms, and cookies through the superglobal arrays $_GET, $_POST, and $_COOKIE

Before you use values from the superglobal arrays, validate them

Regular expressions are the easiest way Make sure data from client hasn't been tampered

with by sending a hash of the data PHP Cookbook: Recipe 9.7 ("Securing PHP's Form

Processing"), Recipe 14.3 ("Verifying Data with Hashes")

Page 7: Php web app security (eng)

2. Broken Access Control Instead of rolling your own

access control solution, use PEAR modules

Auth does cookie-based authentication and Auth_HTTP does browser-based authentication.

PEAR Packages: Auth, Auth_HTTP.

Page 8: Php web app security (eng)

3. Broken Account and Session Management

Use PHP's built-in session management functions for secure, standardized session management

Be careful how your server is configured to store session information

Session-specific traffic should be sent over SSL

PHP Cookbook: Recipe 8.5 ("Using Session Tracking"), Recipe 8.6 ("Storing Sessions in a Database")

Page 9: Php web app security (eng)

4. Cross-Site Scripting (XSS) Flaws Filter variables(outside data)

before including them in hidden form fields, in query strings, or just plain page output

PHP Manual: htmlspecialchars(), strtr(), strip_tags(), utf8_decode()

PHP Cookbook: Recipe 8.8 ("Building a GET Query String"), Recipe 9.8 ("Escaping Control Characters from User Data")

Page 10: Php web app security (eng)

5. Buffer Overflows No runtime memory allocation No pointers like in C No buffer overflows in your

PHP code Watch out for buffer overflows

in PHP itself (and its extensions) Subscribe to the php-announce

mailing list PHP Mailing Lists:

http://php.net/mailing-lists.php

Page 11: Php web app security (eng)

6. Command Injection Flaws Don't pass unfiltered, unescaped malicious

commands to an external process or database

Always escape user input before passing it Use escapeshellcmd() and escapeshellarg()

Canonicalize pathnames with realpath() addslashes(), mysql_real_escape_string(), DB::quote()

PHP Cookbook: Recipe 18.20 ("Escaping Shell Metacharacters"), Recipe 10.9 ("Escaping Quotes")

Page 12: Php web app security (eng)

7. Error Handling Problems Error messages shouldn't contain any

descriptive system information Tell PHP to put error messages in your

server's error log instead of displaying them to a user

“log_errors=On” and “display_errors=Off” PHP Cookbook: Recipe 8.14 ("Hiding Error

Messages from Users")

Page 13: Php web app security (eng)

8. Insecure Use of Cryptography The mcrypt extension provides a

standardized interface to cryptographic algorithms

Be careful about where (if anywhere) you store encryption keys

Store keys apart from encrypted data Use SSL for prompts and replies for

sensetive data, like encryption keys PHP Cookbook: Recipe 14.7

("Encrypting and Decrypting Data")

Page 14: Php web app security (eng)

9. Remote Administration Flaws When possible, run remote

administration tools over SSL Change the default

administrative user names and passwords

Change the default administrative URL as well

Run administrative tools on a different web server than the public web server

Page 15: Php web app security (eng)

10. Web and Application Server Misconfiguration

Keep on top of PHP patches and security problems

Stay away from the automatic PHP source display handler

Use php.ini-recommended as a base for your site configuration rather then php.ini-dist

PHP Mailing Lists: http://www.php.net/mailing-lists.php

Page 16: Php web app security (eng)

Secure Programming With The Zend Framework

Authentication Input Validation & Filtering SQL Security Cross-Site Request Forgery (CSRF)

Protection Session Management Security Cross-Site Scripting (XSS) Protection

Page 17: Php web app security (eng)

ZF: Authentication

Page 18: Php web app security (eng)

ZF: Authentication Zend-Framework applications

usually a MVC with dispatcher With dispatcher every reachable

script doesn't need to implement or embed authentication

Deriving the Zend_Controller_Action Authentication implemented in init() method Attention: if a controller has an own init()

method then method of the parent class must be called

Page 19: Php web app security (eng)

ZF: Input Validation & Filtering Access via request object Zend_Controller_Request_Http

Either via methods or magic properties Access is unfiltered - only raw data Access via magic property in the following

order: internal parameter array, $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV

Page 20: Php web app security (eng)

ZF: Accessing Request Parameters

Page 21: Php web app security (eng)

ZF: Validation Validation with Zend_Validate Zend-Framework comes with

a set of validatorsAlnum, Alpha, Barcode, Between, Ccnum,

Date, Digits, EmailAddress, Float, GraterThen, Hex, Hostname, Iban, InArray, Int, Ip, LessThen, NotEmpty, Regex, StringLength

For complex validations own validators can be implemented

It is possible to combine validators in chains

Page 22: Php web app security (eng)

ZF: Filtering Filtering with Zend_Filter Zend-Framework comes with

a set of pre defined filtersAlnum, Alpha, BaseName, Callback, Digits,

Dir, Encrypt, Htmlentities, Int, StripNewlines, RealPath, StringToUpper, StringToLower, StringTrim, StripTags

For complex filtering own filters can be implemented

It is possible to combine filters in chains

Page 23: Php web app security (eng)

ZF: ...in Forms ZF-Forms use validators

and filters automatically They are attached to Zend_Form_Element objects

And can be chained as wished

Form is validated in the action handler

Page 24: Php web app security (eng)

ZF: Zend_Filter_Input Is a framework for

validation and filtering complete arrays

Applies defined filter and validation ruleset to supplied data

Allows validation of all user input automatically

Page 25: Php web app security (eng)

ZF: SQL Security Zend-Framework offers different APIs for

handling queriesZend_DbZend_Db_StatementZend_Db_SelectZend_Db_Table

Page 26: Php web app security (eng)

ZF: Queries & Escaping

Be aware: both put strings in quotes* SQL-injection is still possible

Page 27: Php web app security (eng)

ZF: Zend_Db_Select Used to dynamically build

SELECT statements Uses partially prepared

statements SQL-injection still possible

when wrongly usedVulnerable through:

WHERE / ORDER BY

Page 28: Php web app security (eng)

ZF: Cross Site Request Forgery (CSRF) Protection

Zend Framework offers Zend_Form_Element_Hash which is a secret token with built-in validator

Normally protection must be added manually

By deriving Zend_Form it is possible to create an own form class that automatically comes with CSRF protection

Page 29: Php web app security (eng)

ZF: Token Algorithm Token algorithm

could be improvedAvoid mt_rand()More entropy

But it is safe enough (for now)

Page 30: Php web app security (eng)

ZF: Session Management Security Configuration has big influence on security For SSL applications set the secure flag Use own session id for each application Harden the session cookie against XSS with

the httpOnly flag Define the maximal lifetime Zend_Session::setOptions(...); Zend_Session::start();

Page 31: Php web app security (eng)

ZF: Session Fixation & Hijacking Session Fixation

Is harder in case of session validation / strict session handling

But it only stopped by regenerating the session id after each change in status

Zend_Session::regenerateId();Should be added directly into login

Session Hijacking There is onle one real protection — SSL HttpOnly cookies protect against session id theft by XSS Session validation only of limited use

Page 32: Php web app security (eng)

ZF: Session Validation Zend-Framework supports session validators

to validate sessions, like:Zend_Session_Validator_HttpUserAgent

Be aware of troublesUA HTTP header check dead Since IE 8Accept HTTP header always been a

problem with MS IEClient IP is a problem on big proxy farms

Possible to limit to C/B/A networksBut useful for SSL applications

Page 33: Php web app security (eng)

ZF: Cross Site Scripting (XSS) Protection Zend-Framework does not

support automatic output escaping

Preventing XSS is the job of the programmer

XSS occurs in the “view” part Encoding before echoing Encoding when assigning

template variables

Page 34: Php web app security (eng)

ZF: Protecting with Zend_View_Helper Preventing XSS is error prone — one XSS

for every forgotten encoding Automatically scanning for forgotten

escaping is hard Directly echoing variables should be

forbidden (eg. With Bytekit + pre-commit-hook)

Output only viz Zend_View_Helper Preventing XSS becomes a job of Zend_View_Helper

Page 35: Php web app security (eng)

ZF: Automatic Escaping with Zend_View All output goes through Zend_View

Deriving Zend_View allows automatic encoding

eg. by overloading __set() and __get()

Be aware: Encoding must be context sensitive (eg.: javascript: links)

Page 36: Php web app security (eng)

Apache HTTPD Security Keep up to date Permissions on ServerRoot Directories Server Side Includes CGI in General Non Script Aliased CGI Script Aliased CGI Other sources of dynamic content Protect System Settings Protect Server Files by Default Watch Your Logs

Page 37: Php web app security (eng)

Apache: Keep Up to Date Apache HTTP Server Announcements List

http://httpd.apache.org/lists.html#http-announce

Use the service of your Apache distributor Monitor for problems in

add-on codeCGI scriptsunderlying Operating Systemetc.

Keep your system software updated

Page 38: Php web app security (eng)

Apache: Permissions Apache is started by the root

user, and it switches to the user defined by the User directive to serve hits

Protect from modification by non-root users: configuration, binary, logs files & directories

Htdocs directory may be modifiable by non-root users since root never executes any files out of there

Page 39: Php web app security (eng)

Apache: Server Side Includes Potential security risks

increased load on the serverusing the exec cmd element

Ways to enhance the security of SSIenable suexec to isolate the damageSSI-enabled files should have a separate

extension, such as the conventional .shtml

disable the ability to run scripts and programs from SSI pages

Page 40: Php web app security (eng)

Apache: CGI In General You always have to remember

that you must trust the writers of the CGI scripts/programs or your ability to spot potential security holes in CGI, whether they were deliberate or accidental

Use suEXEC to allow scripts to run as different users so they don't conflict

CGIWrap will help to avoid conflict problems as well

Page 41: Php web app security (eng)

Apache: Non Script Aliased CGI Allowing users to execute CGI scripts in

any directory should only be considered ifYou trust your users not to write scripts

which will deliberately or accidentally expose your system to an attack

You consider security at your site to be so feeble in other areas, as to make one more potential hole irrelevant

You have no users, and nobody ever visits your server

Page 42: Php web app security (eng)

Apache: Script Aliased CGI Limiting CGI to special directories gives the

admin control over what goes into those directories

This is inevitably more secure than non script aliased CGIbut only if users with write access to the

directories are trusted or the admin is willing to test each new CGI script/program for potential security holes

Most sites choose this option over the non script aliased CGI approach

Page 43: Php web app security (eng)

Apache: Other sources of dynamic content

Embedded scripting optionsmod_php, mod_perl, mod_tcl,

mod_python, etc. Run under the identity of the

server itself Scripts executed by these engines

potentially can access anything the server user can

Some scripting engines may provide restrictions, but it is better to be safe and assume not

Page 44: Php web app security (eng)

Apache: Protecting Settings & Filesystem Stop users from setting up .htaccess files

can override security features you've configured

Forbid default access to filesystem locations Add appropriate Directory blocks to allow

access only in those areas you wish Pay particular attention to the interactions of

Location and Directory directives Also be wary of playing games with the

UserDir directive

Page 45: Php web app security (eng)

Apache: Watching Your Logs Even though the log files only reports what

has already happened, they will give you some understanding of what attacks is thrown against the server and allow you to check if the necessary level of security is present, for example:

[Thu Jul 11 17:18:39 2002] [error] [client foo.example.com] client denied by server configuration: /usr/local/apache/htdocs/.htpasswd

foo.example.com - - [12/Jul/2002:01:59:13 +0200] "GET /.htpasswd HTTP/1.1"

Page 46: Php web app security (eng)

Apache: modSecurity ModSecurity is a web

application firewall that can work either embedded or as a reverse proxy

Provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring, logging and real-time analysis

Page 47: Php web app security (eng)

MySQL Security General Security Guidelines Password Security in MySQL Making MySQL Secure Against

Attackers Security-Related mysqld

Options Security Issues with LOAD

DATA LOCAL How to Run MySQL as a

Normal User

Page 48: Php web app security (eng)

MySQL: General Security Guidelines Do not ever give anyone access to the user table Learn the MySQL access privilege system Do not store any plaintext passwords in your DB Do not choose passwords from dictionaries Invest in a firewall Do not trust any data entered by users Escape special characters in data values Do not transmit plain (unencrypted) data over the

Internet Learn to use the tcpdump and strings utilities

Page 49: Php web app security (eng)

MySQL: Password Security in MySQL Protect mysql.user, my.cnf,

master.info Watch for passwords in

SQL logs and backup dumps

Do not specify password in the cmd line

Use an option file or MYSQL_PWD The Password column must be wide

enough to hold long hashes (41 bytes)

Page 50: Php web app security (eng)

MySQL: Making Secure Against Attackers Require all MySQL accounts

to have a password Never run the MySQL server

as the Unix root user Do not permit the use of symlinks to tables Only mysqld user account allowed to read

and write Do not grant the PROCESS, SUPER, FILE

privileges to non-administrative users Make plugin_dir read only

Page 51: Php web app security (eng)

MySQL: Security-Related mysqld Options http://dev.mysql.com/doc/refman

/5.1/en/privileges-options.htmlallow-suspicious-udfs,

automatic_sp_privileges, chroot, des-key-file, local-infile, old-passwords, safe-show-database, safe-user-create, secure-auth, secure-file-priv, skip-grant-tables, skip-name-resilve, skip-networking, skip-show-database

Page 52: Php web app security (eng)

MySQL: Security Issues with LOAD DATA LOCAL

The LOAD DATA INFILE statement reads rows from a text file into a table at a very high speed

The LOAD DATA statement can load a file that is located on the server host, or it can load a file that is located on the client host when the LOCAL keyword is specified

Disable if don't need it with --local-infile=0 Use [client] loose-local-infile=1

Page 53: Php web app security (eng)

MySQL: How to Run as a Normal User On Windows, you can run the server as a

Windows service using a normal user account

On Unix change data dirownership to selected userchown -R user_name

/path/to/mysql/datadir Start server a selected user

--user=user_name option [mysqld] user=user_name

Page 54: Php web app security (eng)

PHP Security Tools Pixy Suhosin PHP-IDS Sandcat Code OWASP WebScarab Spike PHP Security Audit PHPSecInfo General purpose security tools

Page 55: Php web app security (eng)

Tools: Pixy XSS and SQLI Scanner for PHP

Programs with full include file resolution

Pixy takes a PHP program as input, and creates a report that lists possible vulnerable points in the program

Provides additional information for understanding the vulnerability

Source code analyzer, static analyzer, PHP security analysis

Page 56: Php web app security (eng)

Tools: Suhosin Is an advanced protection

system for PHP installations Designed to protect servers and users

from known and unknown flaws in PHP applications and the PHP core in 2 parts:

A small patch against the PHP core, that implements a few low-level protections against bufferoverflows or format string vulnerabilities

A powerful PHP extension that implements all the other protections

Page 57: Php web app security (eng)

Tools: PHP-IDS

Is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application

Recognizes when an attacker tries to break your site and reacts in exactly the way you want it to

Could range from simple logging to sending out an emergency mail, displaying a warning for the attacker or ending session

Page 58: Php web app security (eng)

Tools: SandCat Code Source code security

scanner (commercial) Enables developers and QA testers to

automatically scan any kind of PHP application source code for potential security vulnerabilities

Scans for Cross-Site Scripting (XSS), File Inclusion, SQL Injection, Command Execution and weak validation

Helps auditors to perform code reviews by identifying key areas of the code

Page 59: Php web app security (eng)

Tools: OWASP WebScarab Is a framework for analysing

applications that communicate using the HTTP and HTTPS

An intercepting proxy, allowing the operator to review and modify requests created by the browser before they are sent to the server

Review and modify responses returned from the server before they are received by the browser

Page 60: Php web app security (eng)

Tools: Spike PHPSecAudit Tool is an OSS solution for doing static analysis

of PHP code — search for exploits

Page 61: Php web app security (eng)

Tools: PhpSecInfo PhpSecInfo provides an equivalent

to the phpinfo() Reports security information about

the PHP environment Offers suggestions for improvement It is not a replacement for secure

development techniques It does not do any kind of code or

app auditing A bit outdated, but still useful

Page 62: Php web app security (eng)

Tools: Security Tests Metasploit — framework for exploits Nessus — active vulnerability scanner Nikto — web server scanner Oedipus — offline log parser Paros — all HTTP and HTTPS data can

be intercepted and modified Vega — finds SQL injection,

cross-site scripting (XSS), etc. Wireshark — protocol analyzer for

troubleshooting, analysis, software and protocol development and education

Page 63: Php web app security (eng)

Copyright © 2000-2011 Softjourn, Inc. All rights reserved

Links• http://www.sklar.com/page/article/owasp-top-ten• http://www.sitepoint.com/php-security-blunders/• http://www.phpwact.org/security/web_application_security• http://www.suspekt.org/downloads/DPC_Secure_Program

ming_With_The_Zend_Framework.pdf• http://www.php.net/manual/en/security.php• http://httpd.apache.org/docs/2.2/misc/security_tips.html• http://dev.mysql.com/doc/refman/5.1/en/security.html• http://www.hotscripts.com/blog/6-free-php-security-

auditing-tools/• http://www.open-source-developers.com/blog/php-

debugging-testing-tools#security-tools• http://www.opensourcetesting.org/security.php• http://www.noupe.com/php/php-security-tips.html• http://www.syhunt.com/?n=Sandcat.Code?

from=Sandcat.4PHP

Page 64: Php web app security (eng)

Copyright © 2000-2011 Softjourn, Inc. All rights reserved

Questions & discussion“Anatoliy Okhotnikov”

<[email protected]>