ZCE — PHP Security Quick Notes

Tuyen Vuong
Mar 18 · 4 min read

Configurations:

  • error_reporting = E_ALL & ~E_DEPRECATED; (when coding, enable also E_STRICT)
  • to disable error reporting entirely on the running code (display_errors = off; log_errors = on; error_log=$path;)
  • allow_url_include = off; allow_url_fopen = off (on by default) — network resources will still be accessible through fsockopen or CURL functions.;
  • expose_php= off; in php.ini file, the amount of information available is reduced
  • disable_functions , disable_classes
  • HTTP authentication: pre-defined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE
  • cgi.force_redirect: prevent running PHP as CGI redirect
  • doc_root: make sure no script executed outside this directory
  • user_dir: if NULL when access url ~user/dir/script.php will be open under doc_root, if set “userdir” then the url will refer to home/user/userdir/dir/script.php
  • open_basedir — Restricts PHP’s file access to one or more specified directories, can be tightened at runtime
  • may use .htaccess to parse every file (including .html,etc.) by php so as to hide PHP from possible attackers

Session:

Preventing Session Fixation:

Preventing Session Hijacking:

Cross Site Scripting (XSS)

Omitting untrusted input for the moment [a tag]:

  • There is a URL Context, i.e. the value of the href attribute
  • There is a HTML Attribute Context, i.e. it parents the URL Context.
  • There is a HTML Body Context. i.e. the text between the <a> tags.

Preventing Cross-Site Scripting In PHP:

  • Never pass data from untrusted origins into output without either escaping or sanitising it.
  • Each Context requires a different method of escaping because each Context has different special characters and different escaping needs. You cannot just throw htmlspecialchars() and htmlentities() at everything and pray that your web application is safe.

Cross Site Request Forgeries (CSRF)

Introductions:

  • CSRF is a separate vulnerability from XSS, with a different solution. XSS protections won’t stop CSRF attacks, although XSS are important to solve and should be prioritized
  • Attacks HTML objects, Attacks scripting code, Attacks XML HTTP Request, CSRF with AJAX Attack

Conditions:

  • Page that the attack does not check the source of messages, or HTTP referrer header
  • Web browser allows users faking the header
  • The attacker is in able to specify the victim to open a malicious web links.

Preventing CSRF:

  • Only accept POST
  • Referrer checking
  • Requiring multi-step transactions: CSRF attack can perform each step in order
  • CAPTCHA Systems
  • One-time tokens
  • Same origin policy
  • Reconfirm password
  • XSS Output Filtering (HTML Encoding)

SQL INJECTION

  • Set privileges for each application
  • Prepared statements
  • Stored procedures
  • Principle of least privilege when connecting to DB
  • Validation and filtering
  • Correct PHP and database configuration
  • Good database design
  • Escaping Output

REMOTE CODE INJECTION

Conditions:

  • REMOTE CODE INJECTIONS RUN THE ATTACKER’S CODE ON A SERVER
  • THE eval(), exec(), AND system()FUNCTIONS ARE VULNERABLE TO REMOTE CODE INJECTIONS
  • OTHER VULNERABLE FUNCTIONS: preg_replace WITH THE /e PATTERN MODIFIER; create_function(), include, fopen…

Prevent:

  • CHECK DATA AGAINST A WHITELIST
  • REMOVE PATHS USING basename()
  • SET allow_url_fopen = Off , allow_url_include=Off in php.ini
  • disable_functions = ‘…’
  • escapeshellargs() TO ESCAPE ARGUMENTS
  • escapeshellcmd() TO ESCAPE COMMANDS

EMAIL INJECTION

  • Validation input and Escape Output
  • Use regular expressions to filter user data
  • Use external components and libraries that provide protection against this problem like ZEND mail, PEAR mail and swift mailer.
  • ModSecurity can put a stop to email injection on the server level. With ModSecurity, it is possible to scan the POST or GET body for BCC, CC, or To and reject any request that contains those letters.
  • DO NOT PROVIDE OPEN RELAYS
  • OPEN THE SMTP PORT ONLY IF ESSENTIAL
  • USE A “TARPITS” TECHNIQUE TO SLOW REQUESTS AS A MEANS OF DISSUADING ATTACKS

INPUT FILTERING

  • Never Blacklist; Only Whitelist
  • Blacklisting involves checking if the input contains unacceptable data while whitelisting checks if the input contains acceptable data
  • Filter what you can’t Validate
  • Be Wary Of Context
  • Evade PHP Type Conversion
  • PHP Functions:
  • ctype_*
  • filter_*

INPUT FILTERING

  • Data Type Check
  • Allowed Characters Check
  • Format Check
  • Limit Check (length)
  • Presence Check
  • Verification Check
  • Logic Check
  • Resource Existence Check

ESCAPE OUTPUT

  • Escape HTML, XML, JSON feed, Excel, AJAX
  • Escape output when you’re outputting, not before
  • XML: SimpleXML, DOMDocument
  • HTML: htmlspecialchars, htmlentities, strip_tags
  • JAVASCRIPT: htmlspecialchars, json_encode, quotemeta
  • Characters: < > ‘ “ &

PASSWORD HASHING API

  • Hash Collision: occurs when two different data inputs generate the same resulting hash (hash functions)
  • Rainbow Tables: 10 million password hashes and run auto login (prevented by adding a salt and unique salt)
  • password_hash() — used to hash the password.
  • password_verify() — used to verify a password against its hash.
  • password_needs_rehash() — used when a password needs to be rehashed.
  • password_get_info() — returns the name of the hashing algorithm and various options used while hashing.

FILE UPLOADS

  • Store the file outside of your document root (should not have any “execute” permission.)
  • Check the file size
  • Keep tight control of permissions
  • Limit the number of uploaded files
  • Protecting the upload folder with .htaccess
  • Checking the image header [getimagesize]
  • Mime Type Validation and Extension File. Using White-List for Files’ Extensions
  • Block Dangerous Extensions (.htaccess)
  • Generate a random file name and add the previously generated extension

DATA STORAGE, SSL…