Apache and PHP Security

53 %
47 %
Information about Apache and PHP Security

Published on August 14, 2007

Author: ozh

Source: slideshare.net

Description

A .ppt I found

Apache and PHP Security

Abbreviated Talk Outline… Basic machine lockdown Apache Configuration and Hardening PHP Configuration and Hardening Secure Practices for PHP Development Secure Configuration of Common PHP Applications

Basic machine lockdown

Apache Configuration and Hardening

PHP Configuration and Hardening

Secure Practices for PHP Development

Secure Configuration of Common PHP Applications

Before taking action understand the Role of the Server Who will have physical access? Who will have shell access? Will apache write to the filesystem? Will you need perl, python etc. within the OS or for apache? If possible can you limit what kind of post/get/cookie/file payloads can be transmitted?

Who will have physical access?

Who will have shell access?

Will apache write to the filesystem?

Will you need perl, python etc. within the OS or for apache?

If possible can you limit what kind of post/get/cookie/file payloads can be transmitted?

Basic Lockdown Turn off unused services, update the machine regularly, use recommended configuration files etc. Enable logwatch or logcheck and actually read the reports. Enable a well configured file integrity checker Configure iptables – Ports 22, 80, 443 tomcat?

Turn off unused services, update the machine regularly, use recommended configuration files etc.

Enable logwatch or logcheck and actually read the reports.

Enable a well configured file integrity checker

Configure iptables – Ports 22, 80, 443 tomcat?

Lockdown Continued Possibly survive a SYN flood attack In /etc/sysctl.conf set net.ipv4.tcp_syncookies = 1 More Information: http://cr.yp.to/syncookies.html Restrict cron and at access using cron.allow and at.allow. chmod/chown /etc/cron* and /var/spool/cron

Possibly survive a SYN flood attack

In /etc/sysctl.conf set

net.ipv4.tcp_syncookies = 1

More Information:

http://cr.yp.to/syncookies.html

Restrict cron and at access using cron.allow and at.allow. chmod/chown /etc/cron* and /var/spool/cron

Lockdown Continued Configure NTP for logfile accuracy. Filesystem lockdown: If possible set quota to “1” for apache. Especially /tmp and /var. Sessions can write to a user configured directory OR preferably a database. /var, /data, /home should be mounted nosuid,nodev,rw Is it reasonable to make /usr or /usr/local ro?

Configure NTP for logfile accuracy.

Filesystem lockdown:

If possible set quota to “1” for apache. Especially /tmp and /var.

Sessions can write to a user configured directory OR preferably a database.

/var, /data, /home should be mounted nosuid,nodev,rw

Is it reasonable to make /usr or /usr/local ro?

Securing Apache

Configuring Apache Turn off any unnecessary capabilities. Unfortunately many things are on by default. Before making changes, research potential exploits …especially in the context of the machine’s services. Look into alternatives Example: If running php, use it instead of server side includes. <?php include ‘footer.html’; ?> XBitHack not necessary

Turn off any unnecessary capabilities. Unfortunately many things are on by default.

Before making changes, research potential exploits …especially in the context of the machine’s services.

Look into alternatives

Example: If running php, use it instead of server side includes.

<?php include ‘footer.html’; ?>

XBitHack not necessary

More Configuration Options Remove /var/www/ directories to protect identity. Create custom /var/www/error files

Remove /var/www/ directories to protect identity.

Create custom /var/www/error files

mod_dosevasive Easy to configure Can help evade DoS attacks by blocking ip addresses or URLs temporarily. Blocks if: Requests are made for the same page more than X times per second per host More than X concurrent requests on the same child per second are made First sends 403 error then blacklists. Can log to syslog and send email. Can also communicate with firewall or router and execute system commands.

Easy to configure

Can help evade DoS attacks by blocking ip addresses or URLs temporarily.

Blocks if:

Requests are made for the same page more than X times per second per host

More than X concurrent requests on the same child per second are made

First sends 403 error then blacklists.

Can log to syslog and send email.

Can also communicate with firewall or router and execute system commands.

Example Configuration LoadModule dosevasive20_module modules/mod_dosevasive20.so <IfModule mod_dosevasive20.c> DOSHashTableSize 3097 DOSPageCount 2 DOSPageInterval 1 DOSSiteCount 50 DOSSiteInterval 1 DOSBlockingPeriod 10 DOSEmailNotify [email_address] DOSLogDir &quot;/tmp/mod_dosevasive“ (make writable by apache only) </IfModule>

LoadModule dosevasive20_module modules/mod_dosevasive20.so

<IfModule mod_dosevasive20.c>

DOSHashTableSize 3097

DOSPageCount 2

DOSPageInterval 1

DOSSiteCount 50

DOSSiteInterval 1

DOSBlockingPeriod 10

DOSEmailNotify [email_address]

DOSLogDir &quot;/tmp/mod_dosevasive“ (make writable by apache only)

</IfModule>

mod_security Very Powerful Can be tricky to configure. Lots of testing. Especially useful if web server runs a small amount of applications.

Very Powerful

Can be tricky to configure. Lots of testing.

Especially useful if web server runs a small amount of applications.

mod_security Features Filters requests before apache. Filters all requests including post payloads and SSL. Understands the http protocol, allowing fine tuning. Complete logging, including post data. Custom rules using regular expressions can be applied at the virtual host level.

Filters requests before apache.

Filters all requests including post payloads and SSL.

Understands the http protocol, allowing fine tuning.

Complete logging, including post data.

Custom rules using regular expressions can be applied at the virtual host level.

More mod_security features Upon “catch” can filter, email, log, redirect, send error code, or execute system binary. Can execute action upon file upload. Example – virus scan. Easier and better apache chrooting. No modules or libraries needed. Logs already open. One Line: SecChrootDir /chroot/apache Can use snort web attack signatures Rules are created and posted for web application vulnerabilities. Can change the identity of the web server in the http header without editing the source. Finger printing still works though.

Upon “catch” can filter, email, log, redirect, send error code, or execute system binary.

Can execute action upon file upload. Example – virus scan.

Easier and better apache chrooting. No modules or libraries needed. Logs already open. One Line: SecChrootDir /chroot/apache

Can use snort web attack signatures

Rules are created and posted for web application vulnerabilities.

Can change the identity of the web server in the http header without editing the source. Finger printing still works though.

Example mod_security Configuration <IfModule mod_security.c> SecFilterEngine On # Prevent OS specific keywords #index.php?include=filename SecFilter /etc/passwd # Prevent path traversal (..) attacks SecFilter &quot;../&quot; # Very crude filters to prevent SQL injection attacks SecFilter &quot;delete[[:space:]]+from&quot; SecFilter &quot;insert[[:space:]]+into&quot; SecFilter &quot;select.+from&quot; </IfModule>

<IfModule mod_security.c>

SecFilterEngine On

# Prevent OS specific keywords #index.php?include=filename

SecFilter /etc/passwd

# Prevent path traversal (..) attacks

SecFilter &quot;../&quot;

# Very crude filters to prevent SQL injection attacks

SecFilter &quot;delete[[:space:]]+from&quot;

SecFilter &quot;insert[[:space:]]+into&quot;

SecFilter &quot;select.+from&quot;

</IfModule>

Scanning your server Nmap Nessus www.nessus.org CIS Linux Benchmark Scan http://www.cisecurity.org/bench_linux.html

Nmap

Nessus

www.nessus.org

CIS Linux Benchmark Scan

http://www.cisecurity.org/bench_linux.html

PHP Security

Types of PHP Attacks Command execution and/or writing to the filesystem. Sql injection Session Hijacking Cross Site Scripting (xss) Cross Site Request Forgeries (CSRF) Session reading/predicting

Command execution and/or writing to the filesystem.

Sql injection

Session Hijacking

Cross Site Scripting (xss)

Cross Site Request Forgeries (CSRF)

Session reading/predicting

Securing PHP Default php.ini < V.4.8 ; WARNING ; ; This is the default settings file for new PHP installations. ; By default, PHP installs itself with a configuration suitable for ; development purposes, and *NOT* for production purposes. Newer installs are better. Many php applications are installed with a default php.ini. Therefore vulnerabilities can be exploited.

Default php.ini < V.4.8

; WARNING ;

; This is the default settings file for new PHP installations.

; By default, PHP installs itself with a configuration suitable for

; development purposes, and *NOT* for production purposes.

Newer installs are better.

Many php applications are installed with a default php.ini. Therefore vulnerabilities can be exploited.

Secure PHP Settings Recommended configurations display_errors = Off (turn on with ini_set or .htaccess) log_errors = On error_reporting = E_ALL (better error reporting) session.save_path=/opt/php/session (Should be specified by the user. Where /opt has no apache quota) session.gc_maxlifetime=600 (ten minutes of inactivity)

Recommended configurations

display_errors = Off (turn on with ini_set or .htaccess)

log_errors = On

error_reporting = E_ALL (better error reporting)

session.save_path=/opt/php/session (Should be specified by the user. Where /opt has no apache quota)

session.gc_maxlifetime=600 (ten minutes of inactivity)

More Settings magic_quotes_gpc = Off Escapes incoming get/post/cookie data, but for what application/database. Broken Crutches. Better to use specific php functions. More later…

magic_quotes_gpc = Off

Escapes incoming get/post/cookie data, but for what application/database. Broken Crutches.

Better to use specific php functions.

More later…

More Settings register_globals = Off Never turn on Too easy to write insecure code Auto initializes variables from Get/Post/Cookie data URL= index.php?administrator=xyz <?php if (isset($administrator)) {     $authorized = true; } ?>

register_globals = Off

Never turn on

Too easy to write insecure code

Auto initializes variables from Get/Post/Cookie data

URL= index.php?administrator=xyz

<?php if (isset($administrator)) {     $authorized = true; } ?>

More Settings safe_mode = On (enable if possible) safe_mode_gid = On (enable if possible) Especially useful in Highly Critical attacks. Can not see files not owned by script owner. Can not execute files not owned by script owner.

safe_mode = On (enable if possible)

safe_mode_gid = On (enable if possible)

Especially useful in Highly Critical attacks.

Can not see files not owned by script owner.

Can not execute files not owned by script owner.

Developing Best Practices Develop with security and production in mind. Form strict policies concerning how data is sanitized and at what stage. $_GET, $_COOKIE, $_POST should always be sanitized according to where it’s going not where it came from. Mysql = mysql_real_escape_string() Postgres = pg_escape_string () The P.E.A.R. DB class handles database data with “?” replacements. To browser = htmlentities () or strip_tags() To Shell = escapeshellcmd()

Develop with security and production in mind.

Form strict policies concerning how data is sanitized and at what stage.

$_GET, $_COOKIE, $_POST should always be sanitized according to where it’s going not where it came from.

Mysql = mysql_real_escape_string()

Postgres = pg_escape_string ()

The P.E.A.R. DB class handles database data with “?” replacements.

To browser = htmlentities () or strip_tags()

To Shell = escapeshellcmd()

To Remove Javascript and reduce XSS attacks Use preg_replace() on … javascript: onclick ondblclick onmousedown onmouseup onmouseover onmousemove onmouseout onkeypress onkeydown onkeyup

Use preg_replace() on …

javascript: onclick ondblclick onmousedown onmouseup onmouseover onmousemove onmouseout onkeypress onkeydown onkeyup

Developing Best Practices cont. Form strict policies concerning sessions. (storage, timeouts, session id length, etc.) If on a multiuser machine make a custom session.save_path or save session data to a database. Use session_regenerate_id() to prevent fixation. Especially after privilege escalation.

Form strict policies concerning sessions. (storage, timeouts, session id length, etc.)

If on a multiuser machine make a custom session.save_path or save session data to a database.

Use session_regenerate_id() to prevent fixation. Especially after privilege escalation.

Developing Best Practices cont. Securing Includes Place them outside of document root. ini_set(&quot;include_path&quot;,&quot;.:/home/user/libs&quot;); But, if you have to place them in root… End them in .php, so source is not revealed. Ex. database.inc.php <Files ~ &quot;.inc$&quot;>     Order allow,deny     Deny from all </Files>

Place them outside of document root.

ini_set(&quot;include_path&quot;,&quot;.:/home/user/libs&quot;);

But, if you have to place them in root…

End them in .php, so source is not revealed. Ex. database.inc.php

<Files ~ &quot;.inc$&quot;>     Order allow,deny     Deny from all

</Files>

Where to put db_connect.inc.php Not in document root. If possible, make it non-world readable. Apache group readable.

Not in document root.

If possible, make it non-world readable. Apache group readable.

Web Applications

Secure Configuration of Common PHP Applications phpMyAdmin Protect config.inc.php if db access is “config” If possible use mod_cas If using http authentication force ssl using mod_rewrite RewriteRule ^/$ /index.php RewriteCond %{SERVER_PORT}!443$ RewriteRule ^(.*) https://host.com:443$1 [R=301,L]

Protect config.inc.php if db access is “config”

If possible use mod_cas

If using http authentication force ssl using mod_rewrite

RewriteRule ^/$ /index.php RewriteCond %{SERVER_PORT}!443$ RewriteRule ^(.*) https://host.com:443$1 [R=301,L]

Secure Configuration of Common PHP Applications phpbb If configuring remotely via the web, use ssl. Sanity.A worm attacked a flaw that allowed for system calls to be sent using GET vars. Evil PHP: <?php $term = urldecode($_GET['sterm']); ?> $_GET is decoded once by php then again by urldecode. The second time quotes or other harmful symbols can be decoded and applied to system(). Assuming no magic quotes would have prevented the problem using escapecmd().

If configuring remotely via the web, use ssl.

Sanity.A worm attacked a flaw that allowed for system calls to be sent using GET vars.

Evil PHP: <?php $term = urldecode($_GET['sterm']); ?>

$_GET is decoded once by php then again by urldecode. The second time quotes or other harmful symbols can be decoded and applied to system(). Assuming no magic quotes would have prevented the problem using escapecmd().

Secure Configuration of Common PHP Applications Gallery Verify that gallery has written to the .htaccess and config.php file after install. Then: chmod 644 .htaccess chmod 644 config.php chmod 400 setup

Verify that gallery has written to the .htaccess and config.php file after install.

Then:

chmod 644 .htaccess

chmod 644 config.php

chmod 400 setup

Secure Configuration of Common PHP Applications phpnuke Move config.php outside of DocumentRoot Edit mainfile.php to path of moved config.php.

Move config.php outside of DocumentRoot

Edit mainfile.php to path of moved config.php.

Web Applications When installing free web applications always be aware of security advisories. Maintain a backup of your database. Practice restoring the database. Be familiar with how to update the application. If possible always use mod_cas. Especially with tools like phpMyAdmin.

When installing free web applications always be aware of security advisories.

Maintain a backup of your database.

Practice restoring the database.

Be familiar with how to update the application.

If possible always use mod_cas. Especially with tools like phpMyAdmin.

Questions?

Add a comment

Related presentations

Related pages

PHP: Verwendung als Apache-Modul - Manual

Verwendung als Apache-Modul. Wenn PHP als Apache-Modul eingesetzt wird, übernimmt es die Benutzerrechte des Apache (üblicherweise die des Users "nobody").
Read more

Welcome! - The Apache HTTP Server Project

The Apache HTTP Server Project is an effort to develop and ... This version is the latest security and bugfix ... Apache HTTP Server, Apache, ...
Read more

PHP: Installed as an Apache module - Manual

Installed as an Apache module. When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user).
Read more

Welcome to The Apache Software Foundation!

Open. The Apache Software Foundation. provides support for the Apache Community of open-source software projects, which provide software products for the ...
Read more

XAMPP Installers and Downloads for Apache Friends

XAMPP is an easy to install Apache distribution containing MariaDB, PHP and Perl.
Read more

mod security › Apache › Wiki › ubuntuusers.de

Apache-Module sollte man immer ... Man erstellt im document-root des Webservers eine Datei test.php ... Mit der Installation von mod_security werden ...
Read more

Die Apache-Firewall | heise Security

Die Application-Level-Firewall mod_security kann viel differenzierter auf den Inhalt von HTTP-Anfragen und -Antworten reagieren, als es mit herkömmlichen ...
Read more

PHP: Security - Manual

Remember that security risks often ... so in theory a user could secerely mess up a page or even have your server run php scripts ... With Apache for ...
Read more

How to Install and Configure PHP 5 to Run with Apache on ...

Many web developers want to run Apache and PHP on their own computer since it allows them to easily test their scripts and programs before they ...
Read more

Apache Security: The Complete Guide to Securing Your ...

The complete guide to securing your Apache web server ... web applications, PHP and SSL/TLS, and more. “The single best Apache security book in print ...
Read more