SlideShare a Scribd company logo
1 of 64
Download to read offline
PHP Web Application Security
28/03/2012
Softjourn Inc.




PHP Web Application Security

               Anatoliy Okhotnikov
                  Softjourn Inc.
PHP Web Application Security
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
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
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")
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.
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")
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")
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
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")
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")
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")
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
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
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
ZF: Authentication
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
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
ZF: Accessing Request Parameters
ZF: Validation
 Validation with Zend_Validate
 Zend-Framework comes with

  a set of validators
    Alnum, 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
ZF: Filtering
 Filtering with Zend_Filter
 Zend-Framework comes with

  a set of pre defined filters
    Alnum, 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
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
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
ZF: SQL Security
   Zend-Framework offers different APIs for
    handling queries
      Zend_Db
      Zend_Db_Statement
      Zend_Db_Select
      Zend_Db_Table
ZF: Queries & Escaping




  Be aware: both put strings in quotes
* SQL-injection is still possible
ZF: Zend_Db_Select
 Used to dynamically build
  SELECT statements
 Uses partially prepared
  statements
 SQL-injection still possible
  when wrongly used
    Vulnerable through:
     WHERE / ORDER BY
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
ZF: Token Algorithm
 Token algorithm
  could be improved
    Avoid mt_rand()
    More entropy
 But it is safe
  enough (for now)
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();
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
ZF: Session Validation
   Zend-Framework supports session validators
    to validate sessions, like:
     Zend_Session_Validator_HttpUserAgent

   Be aware of troubles
     UA HTTP header check dead Since IE 8
     Accept HTTP header always been a
      problem with MS IE
     Client IP is a problem on big proxy farms
       Possible to limit to C/B/A networks
       But useful for SSL applications
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
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
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)
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
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 code
    CGI scripts
    underlying Operating System
    etc.
 Keep your system software updated
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
Apache: Server Side Includes
 Potential security risks
    increased load on the server
    using the exec cmd element
 Ways to enhance the security of SSI
    enable suexec to isolate the damage
    SSI-enabled files should have a separate
     extension, such as the conventional
     .shtml
    disable the ability to run scripts and
     programs from SSI pages
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
Apache: Non Script Aliased CGI
   Allowing users to execute CGI scripts in
    any directory should only be considered if
      You 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
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 CGI
    but 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
Apache: Other sources of dynamic
                content
 Embedded scripting options
    mod_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
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
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"
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
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
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
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)
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
MySQL: Security-Related mysqld Options
    http://dev.mysql.com/doc/refman
     /5.1/en/privileges-options.html
       allow-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
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
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 dir

  ownership to selected user
    chown -R user_name
     /path/to/mysql/datadir
 Start server a selected user
    --user=user_name option
    [mysqld] user=user_name
PHP Security Tools
 Pixy
 Suhosin
 PHP-IDS
 Sandcat Code
 OWASP WebScarab
 Spike PHP Security Audit
 PHPSecInfo
 General purpose security tools
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
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
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
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
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
Tools: Spike PHPSecAudit Tool
   is an OSS solution for doing static analysis
    of PHP code — search for exploits
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
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
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?
            Copyright © 2000-2011 Softjourn, Inc. All rights reserved
    from=Sandcat.4PHP
Questions & discussion
“Anatoliy Okhotnikov”
<aokhotnikov@softjourn.com>




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

More Related Content

What's hot

Art of Web Backdoor - Pichaya Morimoto
Art of Web Backdoor - Pichaya MorimotoArt of Web Backdoor - Pichaya Morimoto
Art of Web Backdoor - Pichaya MorimotoPichaya Morimoto
 
Ten Commandments of Secure Coding
Ten Commandments of Secure CodingTen Commandments of Secure Coding
Ten Commandments of Secure CodingMateusz Olejarka
 
Application and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental EditionApplication and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental EditionDaniel Owens
 
Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧Orange Tsai
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Ivan Piskunov
 
[UniteKorea2013] Protecting your Android content
[UniteKorea2013] Protecting your Android content[UniteKorea2013] Protecting your Android content
[UniteKorea2013] Protecting your Android contentWilliam Hugo Yang
 
Web Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or SucceedWeb Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or SucceedPrathan Phongthiproek
 
OWASP San Diego Training Presentation
OWASP San Diego Training PresentationOWASP San Diego Training Presentation
OWASP San Diego Training Presentationowaspsd
 
Exploit development 101 - Part 1 - Null Singapore
Exploit development 101 - Part 1 - Null SingaporeExploit development 101 - Part 1 - Null Singapore
Exploit development 101 - Part 1 - Null SingaporeMohammed A. Imran
 
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...Jakub Kałużny
 
Think Like a Hacker - Database Attack Vectors
Think Like a Hacker - Database Attack VectorsThink Like a Hacker - Database Attack Vectors
Think Like a Hacker - Database Attack VectorsMark Ginnebaugh
 
Shytikov on NTLM Authentication
Shytikov on NTLM AuthenticationShytikov on NTLM Authentication
Shytikov on NTLM Authenticationshytikov
 
Post XSS Exploitation : Advanced Attacks and Remedies
Post XSS Exploitation : Advanced Attacks and RemediesPost XSS Exploitation : Advanced Attacks and Remedies
Post XSS Exploitation : Advanced Attacks and RemediesAdwiteeya Agrawal
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with phpMohmad Feroz
 
Attacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkAttacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkChris Gates
 
Triển khai Modsecurity vào hệ thống NMS - Quan Minh Tâm
Triển khai Modsecurity vào hệ thống NMS - Quan Minh TâmTriển khai Modsecurity vào hệ thống NMS - Quan Minh Tâm
Triển khai Modsecurity vào hệ thống NMS - Quan Minh TâmSecurity Bootcamp
 
Implementing security routines with zf2
Implementing security routines with zf2Implementing security routines with zf2
Implementing security routines with zf2Er Galvão Abbott
 
Wordpress security
Wordpress securityWordpress security
Wordpress securityMehmet Ince
 

What's hot (20)

Art of Web Backdoor - Pichaya Morimoto
Art of Web Backdoor - Pichaya MorimotoArt of Web Backdoor - Pichaya Morimoto
Art of Web Backdoor - Pichaya Morimoto
 
Hack and Slash: Secure Coding
Hack and Slash: Secure CodingHack and Slash: Secure Coding
Hack and Slash: Secure Coding
 
Ten Commandments of Secure Coding
Ten Commandments of Secure CodingTen Commandments of Secure Coding
Ten Commandments of Secure Coding
 
Application and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental EditionApplication and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental Edition
 
Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
 
[UniteKorea2013] Protecting your Android content
[UniteKorea2013] Protecting your Android content[UniteKorea2013] Protecting your Android content
[UniteKorea2013] Protecting your Android content
 
Web Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or SucceedWeb Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or Succeed
 
OWASP San Diego Training Presentation
OWASP San Diego Training PresentationOWASP San Diego Training Presentation
OWASP San Diego Training Presentation
 
Exploit development 101 - Part 1 - Null Singapore
Exploit development 101 - Part 1 - Null SingaporeExploit development 101 - Part 1 - Null Singapore
Exploit development 101 - Part 1 - Null Singapore
 
Flashack
FlashackFlashack
Flashack
 
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
 
Think Like a Hacker - Database Attack Vectors
Think Like a Hacker - Database Attack VectorsThink Like a Hacker - Database Attack Vectors
Think Like a Hacker - Database Attack Vectors
 
Shytikov on NTLM Authentication
Shytikov on NTLM AuthenticationShytikov on NTLM Authentication
Shytikov on NTLM Authentication
 
Post XSS Exploitation : Advanced Attacks and Remedies
Post XSS Exploitation : Advanced Attacks and RemediesPost XSS Exploitation : Advanced Attacks and Remedies
Post XSS Exploitation : Advanced Attacks and Remedies
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with php
 
Attacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit FrameworkAttacking Oracle with the Metasploit Framework
Attacking Oracle with the Metasploit Framework
 
Triển khai Modsecurity vào hệ thống NMS - Quan Minh Tâm
Triển khai Modsecurity vào hệ thống NMS - Quan Minh TâmTriển khai Modsecurity vào hệ thống NMS - Quan Minh Tâm
Triển khai Modsecurity vào hệ thống NMS - Quan Minh Tâm
 
Implementing security routines with zf2
Implementing security routines with zf2Implementing security routines with zf2
Implementing security routines with zf2
 
Wordpress security
Wordpress securityWordpress security
Wordpress security
 

Viewers also liked (16)

iPhone Objective-C Development (ukr) (2009)
iPhone Objective-C Development (ukr) (2009)iPhone Objective-C Development (ukr) (2009)
iPhone Objective-C Development (ukr) (2009)
 
ITEvent: Continuous Integration (ukr)
ITEvent: Continuous Integration (ukr)ITEvent: Continuous Integration (ukr)
ITEvent: Continuous Integration (ukr)
 
Jenkins CI (ukr)
Jenkins CI (ukr)Jenkins CI (ukr)
Jenkins CI (ukr)
 
ITIL (ukr)
ITIL (ukr)ITIL (ukr)
ITIL (ukr)
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
 
Ubuntu server wireless access point (eng)
Ubuntu server wireless access point (eng)Ubuntu server wireless access point (eng)
Ubuntu server wireless access point (eng)
 
Debug (ukr)
Debug (ukr)Debug (ukr)
Debug (ukr)
 
Xdebug (ukr)
Xdebug (ukr)Xdebug (ukr)
Xdebug (ukr)
 
Continuous integration (eng)
Continuous integration (eng)Continuous integration (eng)
Continuous integration (eng)
 
ITEvent: Kanban Intro (ukr)
ITEvent: Kanban Intro (ukr)ITEvent: Kanban Intro (ukr)
ITEvent: Kanban Intro (ukr)
 
Db design (ukr)
Db design (ukr)Db design (ukr)
Db design (ukr)
 
Linux introduction (eng)
Linux introduction (eng)Linux introduction (eng)
Linux introduction (eng)
 
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)
Project Management: Burn-Down Chart / OrangeHRM Project MOD (eng)
 
Agile Feedback Loops (ukr)
Agile Feedback Loops (ukr)Agile Feedback Loops (ukr)
Agile Feedback Loops (ukr)
 
Ldap introduction (eng)
Ldap introduction (eng)Ldap introduction (eng)
Ldap introduction (eng)
 
Agile (IF PM Group) v2
Agile (IF PM Group) v2Agile (IF PM Group) v2
Agile (IF PM Group) v2
 

Similar to Php web app security (eng)

Authentication with zend framework
Authentication with zend frameworkAuthentication with zend framework
Authentication with zend frameworkGeorge Mihailov
 
Creating Secure Applications
Creating Secure Applications Creating Secure Applications
Creating Secure Applications guest879f38
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend FrameworkJuan Antonio
 
OWASP Portland - OWASP Top 10 For JavaScript Developers
OWASP Portland - OWASP Top 10 For JavaScript DevelopersOWASP Portland - OWASP Top 10 For JavaScript Developers
OWASP Portland - OWASP Top 10 For JavaScript DevelopersLewis Ardern
 
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...MUG-Lyon Microsoft User Group
 
Playing with php_on_azure
Playing with php_on_azurePlaying with php_on_azure
Playing with php_on_azureCEDRIC DERUE
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare Componentzftalk
 

Similar to Php web app security (eng) (20)

Authentication with zend framework
Authentication with zend frameworkAuthentication with zend framework
Authentication with zend framework
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Creating Secure Applications
Creating Secure Applications Creating Secure Applications
Creating Secure Applications
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
 
OWASP Portland - OWASP Top 10 For JavaScript Developers
OWASP Portland - OWASP Top 10 For JavaScript DevelopersOWASP Portland - OWASP Top 10 For JavaScript Developers
OWASP Portland - OWASP Top 10 For JavaScript Developers
 
Bh Win 03 Rileybollefer
Bh Win 03 RileybolleferBh Win 03 Rileybollefer
Bh Win 03 Rileybollefer
 
Lamp Zend Security
Lamp Zend SecurityLamp Zend Security
Lamp Zend Security
 
Let's shield Liferay
Let's shield LiferayLet's shield Liferay
Let's shield Liferay
 
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
Global Windows Azure Bootcamp : Cedric Derue playing with php on azure. (spon...
 
Playing with php_on_azure
Playing with php_on_azurePlaying with php_on_azure
Playing with php_on_azure
 
Web Hacking
Web HackingWeb Hacking
Web Hacking
 
first pitch
first pitchfirst pitch
first pitch
 
werwr
werwrwerwr
werwr
 
sdfsdf
sdfsdfsdfsdf
sdfsdf
 
college
collegecollege
college
 
first pitch
first pitchfirst pitch
first pitch
 
Greenathan
GreenathanGreenathan
Greenathan
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare Component
 
first pitch
first pitchfirst pitch
first pitch
 
organic
organicorganic
organic
 

Recently uploaded

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 

Recently uploaded (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 

Php web app security (eng)

  • 1. PHP Web Application Security 28/03/2012
  • 2. Softjourn Inc. PHP Web Application Security Anatoliy Okhotnikov Softjourn Inc.
  • 4. 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
  • 5. 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
  • 6. 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")
  • 7. 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.
  • 8. 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")
  • 9. 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")
  • 10. 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
  • 11. 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")
  • 12. 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")
  • 13. 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")
  • 14. 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
  • 15. 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
  • 16. 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
  • 18. 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
  • 19. 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
  • 20. ZF: Accessing Request Parameters
  • 21. ZF: Validation  Validation with Zend_Validate  Zend-Framework comes with a set of validators  Alnum, 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
  • 22. ZF: Filtering  Filtering with Zend_Filter  Zend-Framework comes with a set of pre defined filters  Alnum, 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
  • 23. 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
  • 24. 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
  • 25. ZF: SQL Security  Zend-Framework offers different APIs for handling queries  Zend_Db  Zend_Db_Statement  Zend_Db_Select  Zend_Db_Table
  • 26. ZF: Queries & Escaping Be aware: both put strings in quotes * SQL-injection is still possible
  • 27. ZF: Zend_Db_Select  Used to dynamically build SELECT statements  Uses partially prepared statements  SQL-injection still possible when wrongly used  Vulnerable through: WHERE / ORDER BY
  • 28. 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
  • 29. ZF: Token Algorithm  Token algorithm could be improved  Avoid mt_rand()  More entropy  But it is safe enough (for now)
  • 30. 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();
  • 31. 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
  • 32. ZF: Session Validation  Zend-Framework supports session validators to validate sessions, like:  Zend_Session_Validator_HttpUserAgent  Be aware of troubles  UA HTTP header check dead Since IE 8  Accept HTTP header always been a problem with MS IE  Client IP is a problem on big proxy farms Possible to limit to C/B/A networks But useful for SSL applications
  • 33. 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
  • 34. 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
  • 35. 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)
  • 36. 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
  • 37. 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 code  CGI scripts  underlying Operating System  etc.  Keep your system software updated
  • 38. 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
  • 39. Apache: Server Side Includes  Potential security risks  increased load on the server  using the exec cmd element  Ways to enhance the security of SSI  enable suexec to isolate the damage  SSI-enabled files should have a separate extension, such as the conventional .shtml  disable the ability to run scripts and programs from SSI pages
  • 40. 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
  • 41. Apache: Non Script Aliased CGI  Allowing users to execute CGI scripts in any directory should only be considered if  You 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
  • 42. 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 CGI  but 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
  • 43. Apache: Other sources of dynamic content  Embedded scripting options  mod_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
  • 44. 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
  • 45. 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"
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. 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)
  • 50. 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
  • 51. MySQL: Security-Related mysqld Options  http://dev.mysql.com/doc/refman /5.1/en/privileges-options.html  allow-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
  • 52. 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
  • 53. 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 dir ownership to selected user  chown -R user_name /path/to/mysql/datadir  Start server a selected user  --user=user_name option  [mysqld] user=user_name
  • 54. PHP Security Tools  Pixy  Suhosin  PHP-IDS  Sandcat Code  OWASP WebScarab  Spike PHP Security Audit  PHPSecInfo  General purpose security tools
  • 55. 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
  • 56. 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
  • 57. 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
  • 58. 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
  • 59. 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
  • 60. Tools: Spike PHPSecAudit Tool  is an OSS solution for doing static analysis of PHP code — search for exploits
  • 61. 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
  • 62. 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
  • 63. 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? Copyright © 2000-2011 Softjourn, Inc. All rights reserved from=Sandcat.4PHP
  • 64. Questions & discussion “Anatoliy Okhotnikov” <aokhotnikov@softjourn.com> Copyright © 2000-2011 Softjourn, Inc. All rights reserved