apache and php security
DESCRIPTION
A .ppt I foundTRANSCRIPT
Apache and PHP SecurityApache and PHP Security
Abbreviated Talk Outline…Abbreviated Talk Outline…
A.A. Basic machine lockdownBasic machine lockdown
B.B. Apache Configuration and HardeningApache Configuration and Hardening
C.C. PHP Configuration and HardeningPHP Configuration and Hardening
D.D. Secure Practices for PHP DevelopmentSecure Practices for PHP Development
E.E. Secure Configuration of Common PHP Secure Configuration of Common PHP Applications Applications
Before taking action understand the Before taking action understand the Role of the ServerRole of the Server
Who will have physical access?Who will have physical access?
Who will have shell access?Who will have shell access?
Will apache write to the filesystem?Will apache write to the filesystem?
Will you need perl, python etc. within the Will you need perl, python etc. within the OS or for apache?OS or for apache?
If possible can you limit what kind of If possible can you limit what kind of post/get/cookie/file payloads can be post/get/cookie/file payloads can be transmitted?transmitted?
Basic LockdownBasic Lockdown
Turn off unused services, update the Turn off unused services, update the machine regularly, use recommended machine regularly, use recommended configuration files etc.configuration files etc.Enable logwatch or logcheck and actually Enable logwatch or logcheck and actually read the reports.read the reports.Enable a well configured file integrity Enable a well configured file integrity checkercheckerConfigure iptables – Ports 22, 80, 443 Configure iptables – Ports 22, 80, 443 tomcat? tomcat?
Lockdown ContinuedLockdown Continued
Possibly survive a SYN flood attackPossibly survive a SYN flood attack
In /etc/sysctl.conf set In /etc/sysctl.conf set
net.ipv4.tcp_syncookies = 1net.ipv4.tcp_syncookies = 1
More Information:More Information:
http://cr.yp.to/syncookies.htmlhttp://cr.yp.to/syncookies.html
Restrict cron and at access using cron.allow and Restrict cron and at access using cron.allow and at.allow. chmod/chown /etc/cron* and at.allow. chmod/chown /etc/cron* and /var/spool/cron/var/spool/cron
Lockdown ContinuedLockdown Continued
Configure NTP for logfile accuracy.Configure NTP for logfile accuracy.Filesystem lockdown:Filesystem lockdown:
If possible set quota to “1” for apache. If possible set quota to “1” for apache. Especially /tmp and /var.Especially /tmp and /var.
Sessions can write to a user configured Sessions can write to a user configured directory OR preferably a database.directory OR preferably a database.
/var, /data, /home should be mounted /var, /data, /home should be mounted nosuid,nodev,rw nosuid,nodev,rw
Is it reasonable to make /usr or /usr/local ro?Is it reasonable to make /usr or /usr/local ro?
Securing ApacheSecuring Apache
Configuring ApacheConfiguring Apache
Turn off any unnecessary capabilities. Turn off any unnecessary capabilities. Unfortunately many things are on by default.Unfortunately many things are on by default.Before making changes, research potential Before making changes, research potential exploits …especially in the context of the exploits …especially in the context of the machine’s services.machine’s services.Look into alternativesLook into alternatives
Example: If running php, use it instead of server Example: If running php, use it instead of server side includes. side includes.
<?php include ‘footer.html’; ?><?php include ‘footer.html’; ?>
XBitHack not necessary XBitHack not necessary
More Configuration OptionsMore Configuration Options
Remove /var/www/ directories to protect Remove /var/www/ directories to protect identity.identity.
Create custom /var/www/error filesCreate custom /var/www/error files
mod_dosevasivemod_dosevasive
Easy to configureEasy to configureCan help evade DoS attacks by blocking ip Can help evade DoS attacks by blocking ip addresses or URLs temporarily.addresses or URLs temporarily.
Blocks if:Blocks if:Requests are made for the same page more than X times per second Requests are made for the same page more than X times per second
per hostper hostMore than X concurrent requests on the same child per second are More than X concurrent requests on the same child per second are
mademadeFirst sends 403 error then blacklists.First sends 403 error then blacklists.Can log to syslog and send email.Can log to syslog and send email.Can also communicate with firewall or router and execute system Can also communicate with firewall or router and execute system
commands.commands.
Example ConfigurationExample ConfigurationLoadModule dosevasive20_module modules/mod_dosevasive20.so
<IfModule mod_dosevasive20.c> DOSHashTableSize 3097 DOSPageCount 2 DOSPageInterval 1 DOSSiteCount 50 DOSSiteInterval 1 DOSBlockingPeriod 10 DOSEmailNotify [email protected] DOSLogDir "/tmp/mod_dosevasive“ (make writable by apache only)</IfModule>
mod_securitymod_security
Very Powerful Very Powerful
Can be tricky to configure. Lots of testing.Can be tricky to configure. Lots of testing.
Especially useful if web server runs a Especially useful if web server runs a small amount of applications. small amount of applications.
mod_security Featuresmod_security Features
Filters requests before apache.Filters requests before apache.
Filters all requests including post payloads Filters all requests including post payloads and SSL.and SSL.
Understands the http protocol, allowing Understands the http protocol, allowing fine tuning.fine tuning.
Complete logging, including post data.Complete logging, including post data.
Custom rules using regular expressions Custom rules using regular expressions can be applied at the virtual host level.can be applied at the virtual host level.
More mod_security featuresMore mod_security features
Upon “catch” can filter, email, log, redirect, send error Upon “catch” can filter, email, log, redirect, send error code, or execute system binary.code, or execute system binary.Can execute action upon file upload. Example – virus Can execute action upon file upload. Example – virus scan.scan.Easier and better apache chrooting. No modules or Easier and better apache chrooting. No modules or libraries needed. Logs already open. One Line: libraries needed. Logs already open. One Line: SecChrootDir /chroot/apacheSecChrootDir /chroot/apacheCan use snort web attack signaturesCan use snort web attack signaturesRules are created and posted for web application Rules are created and posted for web application vulnerabilities. vulnerabilities. Can change the identity of the web server in the http Can change the identity of the web server in the http header without editing the source. Finger printing still header without editing the source. Finger printing still works though.works though.
Example mod_security Example mod_security ConfigurationConfiguration
<IfModule mod_security.c> <IfModule mod_security.c> SecFilterEngine On SecFilterEngine On # Prevent OS specific keywords #index.php?# Prevent OS specific keywords #index.php?
include=filenameinclude=filenameSecFilter /etc/passwd SecFilter /etc/passwd
# Prevent path traversal (..) attacks # Prevent path traversal (..) attacks SecFilter "\.\./" SecFilter "\.\./"
# Very crude filters to prevent SQL injection attacks # Very crude filters to prevent SQL injection attacks SecFilter "delete[[:space:]]+from" SecFilter "delete[[:space:]]+from" SecFilter "insert[[:space:]]+into" SecFilter "insert[[:space:]]+into" SecFilter "select.+from" SecFilter "select.+from" </IfModule> </IfModule>
Scanning your serverScanning your server
NmapNmap
NessusNessus
www.nessus.orgwww.nessus.org
CIS Linux Benchmark ScanCIS Linux Benchmark Scan
http://www.cisecurity.org/bench_linux.htmlhttp://www.cisecurity.org/bench_linux.html
PHP SecurityPHP Security
Types of PHP AttacksTypes of PHP AttacksCommand execution and/or writing to the filesystem.Command execution and/or writing to the filesystem.Sql injectionSql injectionSession HijackingSession Hijacking
Cross Site Scripting (xss) Cross Site Scripting (xss) Cross Site Request Forgeries (CSRF)Cross Site Request Forgeries (CSRF) Session reading/predictingSession reading/predicting
Securing PHPSecuring PHP
Default php.ini < V.4.8Default php.ini < V.4.8; WARNING ;; WARNING ;; This is the default settings file for new PHP installations.; This is the default settings file for new PHP installations.; By default, PHP installs itself with a configuration suitable for; By default, PHP installs itself with a configuration suitable for; development purposes, and *NOT* for production purposes.; development purposes, and *NOT* for production purposes.
Newer installs are better.Newer installs are better.Many php applications are installed with a Many php applications are installed with a default php.ini. Therefore vulnerabilities default php.ini. Therefore vulnerabilities can be exploited.can be exploited.
Secure PHP SettingsSecure PHP Settings
Recommended configurationsRecommended configurationsdisplay_errors = Off (turn on with ini_set display_errors = Off (turn on with ini_set
or .htaccess)or .htaccess)log_errors = Onlog_errors = Onerror_reporting = E_ALL (better error reporting)error_reporting = E_ALL (better error reporting)session.save_path=/opt/php/session (Should be session.save_path=/opt/php/session (Should be
specified by the user. Where /opt has no apache specified by the user. Where /opt has no apache quota)quota)
session.gc_maxlifetime=600 (ten minutes of session.gc_maxlifetime=600 (ten minutes of inactivity)inactivity)
More SettingsMore Settings
magic_quotes_gpc = Offmagic_quotes_gpc = Off
Escapes incoming get/post/cookie data, but for Escapes incoming get/post/cookie data, but for what application/database. Broken Crutches.what application/database. Broken Crutches.
Better to use specific php functions.Better to use specific php functions.
More later…More later…
More SettingsMore Settings
register_globals = Off register_globals = Off Never turn onNever turn onToo easy to write insecure codeToo easy to write insecure codeAuto initializes variables from Get/Post/Cookie dataAuto initializes variables from Get/Post/Cookie data
URL= index.php?administrator=xyzURL= index.php?administrator=xyz
<?php<?php
if (isset($administrator))if (isset($administrator)){{ $authorized = true; $authorized = true;}}?>?>
More SettingsMore Settings
safe_mode = On (enable if possible)safe_mode = On (enable if possible)
safe_mode_gid = On (enable if possible)safe_mode_gid = On (enable if possible)
Especially useful in Highly Critical attacks.Especially useful in Highly Critical attacks.
Can not see files not owned by script Can not see files not owned by script owner.owner.
Can not execute files not owned by script Can not execute files not owned by script owner.owner.
Developing Best Practices Developing Best Practices Develop with security and production in mind.Develop with security and production in mind.Form strict policies concerning how data is sanitized and Form strict policies concerning how data is sanitized and at what stage.at what stage.$_GET, $_COOKIE, $_POST should always be sanitized $_GET, $_COOKIE, $_POST should always be sanitized according to where it’s going not where it came from.according to where it’s going not where it came from.
Mysql = mysql_real_escape_string() Mysql = mysql_real_escape_string() Postgres = pg_escape_string ()Postgres = pg_escape_string () The P.E.A.R. DB class handles database data with “?” The P.E.A.R. DB class handles database data with “?”
replacements.replacements. To browser = htmlentities () or strip_tags() To browser = htmlentities () or strip_tags() To Shell = escapeshellcmd()To Shell = escapeshellcmd()
To Remove Javascript and reduce To Remove Javascript and reduce XSS attacksXSS attacks
Use preg_replace() on …Use preg_replace() on …
javascript: onclick ondblclick onmousedown javascript: onclick ondblclick onmousedown onmouseup onmouseover onmouseup onmouseover onmousemove onmouseout onkeypress onmousemove onmouseout onkeypress onkeydown onkeyuponkeydown onkeyup
Developing Best Practices cont.Developing Best Practices cont.
Form strict policies concerning sessions. Form strict policies concerning sessions. (storage, timeouts, session id length, etc.)(storage, timeouts, session id length, etc.)
If on a multiuser machine make a custom If on a multiuser machine make a custom session.save_path or save session data to session.save_path or save session data to a database.a database.
Use session_regenerate_id() to prevent Use session_regenerate_id() to prevent fixation. Especially after privilege fixation. Especially after privilege escalation.escalation.
Developing Best Practices cont. Developing Best Practices cont. Securing IncludesSecuring Includes
Place them outside of document root.Place them outside of document root.ini_set("include_path",".:/home/user/libs");ini_set("include_path",".:/home/user/libs");But, if you have to place them in root…But, if you have to place them in root…
End them in .php, so source is not revealed. Ex. End them in .php, so source is not revealed. Ex. database.inc.phpdatabase.inc.php
<Files ~ "\.inc$"><Files ~ "\.inc$"> Order allow,deny Order allow,deny Deny from all Deny from all
</Files> </Files>
Where to put db_connect.inc.phpWhere to put db_connect.inc.php
Not in document root.Not in document root.
If possible, make it non-world readable. If possible, make it non-world readable. Apache group readable.Apache group readable.
Web ApplicationsWeb Applications
Secure Configuration of Common Secure Configuration of Common PHP ApplicationsPHP Applications
phpMyAdminphpMyAdmin
Protect config.inc.php if db access is Protect config.inc.php if db access is “config”“config”
If possible use mod_casIf possible use mod_cas
If using http authentication force ssl using If using http authentication force ssl using mod_rewritemod_rewrite
RewriteRule ^/$ /index.php RewriteRule ^/$ /index.php RewriteCond %{SERVER_PORT}!443$ RewriteCond %{SERVER_PORT}!443$
RewriteRule ^(.*) https://host.com:443$1 [R=301,L]RewriteRule ^(.*) https://host.com:443$1 [R=301,L]
Secure Configuration of Common Secure Configuration of Common PHP ApplicationsPHP Applications
phpbbphpbbIf configuring remotely via the web, use ssl.If configuring remotely via the web, use ssl.Sanity.A worm attacked a flaw that allowed for system Sanity.A worm attacked a flaw that allowed for system calls to be sent using GET vars.calls to be sent using GET vars.
Evil PHP:Evil PHP:<?php<?php$term = urldecode($_GET['sterm']);$term = urldecode($_GET['sterm']);?> ?>
$_GET is decoded once by php then again by urldecode. $_GET is decoded once by php then again by urldecode. The second time quotes or other harmful symbols can be The second time quotes or other harmful symbols can be decoded and applied to system(). Assuming no magic decoded and applied to system(). Assuming no magic quotes would have prevented the problem using quotes would have prevented the problem using escapecmd().escapecmd().
Secure Configuration of Common Secure Configuration of Common PHP ApplicationsPHP Applications
GalleryGallery
Verify that gallery has written to Verify that gallery has written to the .htaccess and config.php file after the .htaccess and config.php file after install.install.
Then: Then: chmod 644 .htaccess chmod 644 .htaccess
chmod 644 config.php chmod 644 config.php
chmod 400 setupchmod 400 setup
Secure Configuration of Common Secure Configuration of Common PHP ApplicationsPHP Applications
phpnukephpnuke
Move config.php outside of DocumentRootMove config.php outside of DocumentRoot
Edit mainfile.php to path of moved Edit mainfile.php to path of moved config.php.config.php.
Web ApplicationsWeb Applications
When installing free web applications When installing free web applications always be aware of security advisories.always be aware of security advisories.
Maintain a backup of your database.Maintain a backup of your database.
Practice restoring the database.Practice restoring the database.
Be familiar with how to update the Be familiar with how to update the application.application.
If possible always use mod_cas. If possible always use mod_cas. Especially with tools like phpMyAdmin.Especially with tools like phpMyAdmin.
Questions?Questions?