BetaONE will rise again!


Reply
  #1  
Old 25th Jun 03, 05:04 PM
JacKDynne's Avatar
JacKDynne JacKDynne is offline
Administrator
 
Join Date: Oct 2001
Location: The Past Through Tomorrow
Posts: 1,591
JacKDynne will become famous soon enoughJacKDynne will become famous soon enough
Send a message via MSN to JacKDynne
Hope this helps some

Quote:
Securing Apache: Step-by-Step
by Artur Maj
last updated May 14, 2003

--------------------------------------------------------------------------------

This article shows in a step-by-step fashion, how to install and configure the Apache 1.3.x Web server in order to mitigate or avoid successful break-in when new vulnerabilities in this software are found.

Functionality

Before we start securing Apache, we must specify what functionality we expect from the server. Variety of Apache's use makes it difficult to write a universal procedure to secure the server in every case. That's why in this article we'll base on the following functionality:

The Web server will be accessible from the Internet; and,
Only static HTML pages will be served
the server will support name-based virtual hosting mechanism
specified Web pages can be accessible only from selected IP addresses or users (basic authentication)
the server will log all the Web requests (including information about Web browsers)
It is worth emphasizing that the above model doesn't support PHP, JSP, CGI or any other technologies that make it possible to interact with Web services. The use of such technologies may pose a large security threat, so that even a small, inconspicuous script can radically decrease the server's security level. Why? Primarily, ASP/CGI applications may contain security vulnerabilities (e.g. SQL injection, cross-site-scripting). Secondarily, the technology itself can be dangerous (vulnerabilities in PHP, Perl modules etc.). That's why I strongly recommend using such technologies only when an interaction with a Web site is absolutely necessary.

Security Assumptions

One of the most important elements of every computer project is the specification of security assumptions. This must be fulfilled before the project is implemented. The security assumptions for our Web server are as follows:

The operating system must be hardened as much as possible, both against local and remote attacks;
The server must not offer any network services except HTTP: (80/TCP);
Remote access to the server must be controlled by a firewall, which should block all outbound connections, and allow inbound connections only to the 80/TCP port of the Web server;
The Apache Web server must be the only service available on the system;
Only absolutely necessary Apache modules should be enabled;
Any diagnostic Web pages and automatic directory indexing service must be turned off;
The server should disclose the least amount of information about itself (security by obscurity);
The Apache server must run under a unique UID/GID, not used by any other system process;
Apache's processes must have limited access to the file systems (chrooting); and,
No shell programs can be present in the Apache's chrooted environment (/bin/sh, /bin/csh etc.).
Installing the Operating System

Before installing Apache we must choose an operating system, upon which the server will run. We've got a broad choice here, because Apache can be compiled and installed on almost every operating system. The rest of the article instructs how to secure the Apache Web server on FreeBSD (4.7), however the described methods are possible to apply in case of most UNIX/Linux systems. The only operating system I do not recommend using is MS Windows - mainly because of the limited capabilities of securing the Apache.

The first step in securing the Web server is hardening the operating system. A discussion of hardening the operating system is beyond the scope of this article. However, there are a lot of documents on the Net describing how to perform that. Readers are encouraged to conduct their own issue on this topic.

After the system is installed and hardened, we have to add a new group and regular user called "apache" like this (an example from FreeBSD):

pw groupadd apache
pw useradd apache -c "Apache Server" -d /dev/null -g apache -s /sbin/nologin

By default, Apache processes run with privileges of user nobody (except the main process, which runs with root privileges) and GID of group nogroup. This might pose a significant security threat. In case of successful break-in, the intruder can obtain access to all other processes that run under the same UID/GID. Hence, the optimum solution is to run Apache under the UID/GID of a unique regular user/group, dedicated to that software.

Preparing the Software

The next step is to download the latest version of the Apache Web server. Some of Apache's options can be enabled only during compilation time, thus it is important to download the source code instead of the binary version.

After downloading the software, we must unpack it. Then we must decide which modules should remain enabled. A short description of all modules available in the latest version of Apache 1.3.x (1.3.27) can be found at http://httpd.apache.org/docs/mod/.

Apache's Modules

The choice of modules is one of the most important steps of securing Apache. We should go by the rule: the less the better. To fulfill the functionality and security assumptions, the following modules must remain enabled:

Module's name Description
httpd_core The core Apache features, required in every Apache installation.
mod_access Provides access control based on client hostname, IP address, or other characteristics of the client request. Because this module is needed to use "order", "allow" and "deny" directives, it should remain enabled.
mod_auth Required in order to implement user authentication using text files (HTTP Basic Authentication), which was specified in functionality assumptions.
mod_dir Required to search and serve directory index files: "index.html", "default.htm", etc.
mod_log_config Required to implement logging of the requests made to the server.
mod_mime Required to set the character set, content- encoding, handler, content-language, and MIME types of documents.

All other Apache's modules must be disabled. We can safely turn them off, mainly because we do not need them. By disabling unneeded modules, we can avoid potential break-ins when new security vulnerabilities are found in one of them.

It is also worth to note that two of Apache's modules can be more dangerous than others: mod_autoindex and mod_info. The first module provides for automatic directory indexing, and is enabled by default. It is very easy to use this module in order to check if Apache runs on a server (e.g. http://server_name/icons/) and to get the content of the Web server's directories, when no index files are found in them. The second module, mod_info, should never be accessible from the Internet, mainly because it reveals the Apache server's configuration.

The next question is how to compile modules. The static method seems to be a better choice. If new vulnerabilities in Apache are found, we will probably recompile not just the vulnerable modules, but the whole software. By choosing the static method, we eliminate the need of one more module - mod_so.

Compiling the software

First of all - if exist - any security patches must be applied. Then, the server should be compiled and installed as follows:

./configure --prefix=/usr/local/apache --disable-module=all --server-
    uid=apache --server-gid=apache --enable-module=access --enable-
    module=log_config --enable-module=dir --enable-module=mime --enable-module=auth

make
su
umask 022
make install
chown -R root:sys /usr/local/apache

Chrooting the server

The next step is to limit Apache processes' access to the filesystems. We can achieve that by chrooting it's main daemon (httpd). Generally, the chrooting technique means creating a new root directory structure, moving all daemon files to it, and running the proper daemon in that new environment. Thanks to that, the daemon (and all child processes) will have access only to the new directory structure.

We'll start this process by creating a new root directory structure under the /chroot/httpd directory:

mkdir -p /chroot/httpd/dev
mkdir -p /chroot/httpd/etc
mkdir -p /chroot/httpd/var/run
mkdir -p /chroot/httpd/usr/lib
mkdir -p /chroot/httpd/usr/libexec
mkdir -p /chroot/httpd/usr/local/apache/bin
mkdir -p /chroot/httpd/usr/local/apache/logs
mkdir -p /chroot/httpd/usr/local/apache/conf
mkdir -p /chroot/httpd/www

The owner of all above directories must be root, and the access rights should be set to the 0755. Next, we'll create the special device file: /dev/null:

ls -al /dev/null
  crw-rw-rw-  1  root wheel  2,  2 Mar 14 12:53 /dev/null
mknod /chroot/httpd/dev/null c 2 2
chown root:sys /chroot/httpd/dev/null
chmod 666 /chroot/httpd/dev/null

A different method must be used to create a /chroot/httpd/dev/log device, which is also needed for the server to work properly. In case of the FreeBSD system, the following line should be added to the /etc/rc.conf:

syslogd_flags="-l /chroot/httpd/dev/log"

We must restart the system or the syslogd daemon itself for the changes to take effect. In order to create a /chroot/httpd/dev/log device on other operating systems, we must take a look at the proper manuals (man syslogd).

The next step is to copy the main httpd program into the new directory tree with all necessary binaries and libraries. In order to do that, we must prepare the list of all required files. We can make such list by using the following commands (their presence depends on particular operating system):

Command Availability Descript ion
ldd All Lists dynamiic dependencies of executable files or shared libraries
ktrace/ktruss/kdump *BSD Enables kernal process tracing, Displays kernal trace data
sotruss Solaris Traces shared library procedure calls
strace/ltrace Linux Traces system calls and signals
strings All Finds the printable strings in binary files
trace AIX Records selected system events
trace (freeware) HP-UX <10.20 Print system call and kernal traces of processes
truss FreeBSD, Solaris, AIX 5L, SCO Unixware Traces system calls and signals
tusc (freeware) HP-UX>11 Traces the system calls a process invokes in HP-UX 11

Examples of using ldd, strings and truss commands are shown below:

localhost# ldd /usr/local/apache/bin/httpd
/usr/local/apache/bin/httpd:
&nbsp; &nbsp; &nbsp; &nbsp; libcrypt.so.2 => /usr/lib/libcrypt.so.2 (0x280bd000)
&nbsp; &nbsp; &nbsp; &nbsp; libc.so.4 => /usr/lib/libc.so.4 (0x280d6000)

localhost# strings /usr/local/apache/bin/httpd | grep lib
/usr/libexec/ld-elf.so.1
libcrypt.so.2
libc.so.4

localhost# truss /usr/local/apache/bin/httpd | grep open
(...)
open("/var/run/ld-elf.so.hints",0,00)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = 3 (0x3)
open("/usr/lib/libcrypt.so.2",0,027757775370)&nbsp; &nbsp; = 3 (0x3)
open("/usr/lib/libc.so.4",0,027757775370)&nbsp; &nbsp; &nbsp; &nbsp; = 3 (0x3)
open("/etc/spwd.db",0,00)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = 3 (0x3)
open("/etc/group",0,0666)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = 3 (0x3)
open("/usr/local/apache/conf/httpd.conf",0,0666) = 3 (0x3)
(...)

The above commands should be applied not only to the httpd program, but also to all of the libraries and binaries required (libraries often require other libraries). In case of FreeBSD system, the following files have to be copied to the new root directory structure:

cp /usr/local/apache/bin/httpd /chroot/httpd/usr/local/apache/bin/
cp /var/run/ld-elf.so.hints /chroot/httpd/var/run/
cp /usr/lib/libcrypt.so.2 /chroot/httpd/usr/lib/
cp /usr/lib/libc.so.4 /chroot/httpd/usr/lib/
cp /usr/libexec/ld-elf.so.1 /chroot/httpd/usr/libexec/

By using the truss command we can also discover that the following configuration files must be present in the chrooted environment as well:

cp /etc/hosts /chroot/httpd/etc/
cp /etc/host.conf /chroot/httpd/etc/
cp /etc/resolv.conf /chroot/httpd/etc/
cp /etc/group /chroot/httpd/etc/
cp /etc/master.passwd /chroot/httpd/etc/passwords
cp /usr/local/apache/conf/mime.types /chroot/httpd/usr/local/apache/conf/

Note, that from /chroot/httpd/etc/passwords we have to remove all the lines except "nobody" and "apache". In a similar way, we must remove all the lines except "apache" and "nogroup" from /chroot/httpd/etc/group. Next, we have to build the password database as follows:

cd /chroot/httpd/etc
pwd_mkdb -d /chroot/httpd/etc passwords
rm -rf /chroot/httpd/etc/master.passwd

The next step is to test if the httpd server runs correctly in the new chrooted environment. In order to perform that, we have to copy the default Apache configuration file and sample index.html:

cp /usr/local/apache/conf/httpd.conf /chroot/httpd/usr/local/apache/co
nf/
cp /usr/local/apache/htdocs/index.html.en /chroot/httpd/www/index.html

After copying the aforementioned files, we must change the DocumentRoot directive as presented below (in /chroot/httpd/usr/local/apache/conf/httpd.conf):

DocumentRoot "/www"

Next, we can try to run the server:

chroot /chroot/httpd /usr/local/apache/bin/httpd

If any problems occur, I recommend analyzing Apache's log files precisely (/chroot/httpd/usr/local/apache/logs). Alternatively, the following command can be used:

truss chroot /chroot/httpd /usr/local/apache/bin/httpd

The truss program should show the cause of the problems. After eliminating any eventual faults, we can configure the Apache server.

Configuring Apache

The first step is to remove the /chroot/httpd/usr/local/apache/conf/httpd.conf file and create a new one in its place, with content similar to the following:

# =================================================
# Basic settings
# =================================================
ServerType standalone
ServerRoot "/usr/local/apache"
PidFile /usr/local/apache/logs/httpd.pid
ScoreBoardFile /usr/local/apache/logs/httpd.scoreboard
ResourceConfig /dev/null
AccessConfig /dev/null

# =================================================
# Performance settings
# =================================================
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
MinSpareServers 5
MaxSpareServers 10
StartServers 5
MaxClients 150
MaxRequestsPerChild 0

# =================================================
# Apache's modules
# =================================================
ClearModuleList
AddModule mod_log_config.c
AddModule mod_mime.c
AddModule mod_dir.c
AddModule mod_access.c
AddModule mod_auth.c

# =================================================
# General settings
# =================================================
Port 80
User apache
Group apache
ServerAdmin Webmaster@www.ebank.lab
UseCanonicalName Off
ServerSignature Off
HostnameLookups Off
ServerTokens Prod
<IfModule mod_dir.c>
&nbsp; &nbsp; DirectoryIndex index.html
</IfModule>
DocumentRoot "/www/vhosts"

# =================================================
# Access control
# =================================================
<Directory />
&nbsp; &nbsp; Options None
&nbsp; &nbsp; AllowOverride None
&nbsp; &nbsp; Order deny,allow
&nbsp; &nbsp; Deny from all
</Directory>
<Directory "/www/vhosts/www.ebank.lab">
&nbsp; &nbsp; Order allow,deny
&nbsp; &nbsp; Allow from all
</Directory>
<Directory "/www/vhosts/www.test.lab">
&nbsp; &nbsp; Order allow,deny
&nbsp; &nbsp; Allow from all
</Directory>

# =================================================
# MIME encoding
# =================================================
<IfModule mod_mime.c>
&nbsp; &nbsp; TypesConfig /usr/local/apache/conf/mime.types
</IfModule>
DefaultType text/plain
<IfModule mod_mime.c>
&nbsp; &nbsp; AddEncoding x-compress Z
&nbsp; &nbsp; AddEncoding x-gzip gz tgz
&nbsp; &nbsp; AddType application/x-tar .tgz
</IfModule>

# =================================================
# Logs
# =================================================
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
ErrorLog /usr/local/apache/logs/error_log
CustomLog /usr/local/apache/logs/access_log combined

# =================================================
# Virtual hosts
# =================================================
NameVirtualHost *
<VirtualHost *>
DocumentRoot "/www/vhosts/www.ebank.lab"
ServerName "www.ebank.lab"
ServerAlias "www.e-bank.lab"
ErrorLog logs/www.ebank.lab/error_log
CustomLog logs/www.ebank.lab/access_log combined
</VirtualHost>
<VirtualHost *>
DocumentRoot "/www/vhosts/www.test.lab"
ServerName "www.test.lab"
ErrorLog logs/www.test.lab/error_log
CustomLog logs/www.test.lab/access_log combined
</VirtualHost>

The above configuration includes only the commands that are necessary to fulfill the functionality and security assumptions. In the configuration presented, there are two virtual hosts supported by the Web server:

- www.ebank.lab (www.e-bank.lab)
- www.test.lab

The content of the above Web sites is physically present in the following directories:

- /chroot/httpd/www/vhosts/www.ebank.lab
- /chroot/httpd/www/vhosts/www.test.lab

Each Web site has its own log files, which are present in the following directories:

- /chroot/httpd/usr/local/apache/logs/www.ebank.lab
- /chroot/httpd/usr/local/apache/logs/www.test.lab

The above directories must be created before running the Apache for the first time - otherwise the Apache will not run correctly. The owner of the above directories should be root:sys, and the rights should be set to 0755.

Compared with the default Apache configuration file, the following changes have been made:

the number of enabled modules has been significantly reduced
Apache doesn't disclose information about its version number (directives: ServerTokens, ServerSignature)
Apache's processes (except the root process) are set to be executed with unique regular user's/group's privileges (directives: User, Group)
Apache will allow access only to the directories, subdirectories and files, which are explicitly specified in the configuration file (directives: Directory, Allow); all other requests will be denied by default
Apache will log more information about HTTP requests
Final steps

At the end we should create a start-up script "apache.sh", the content of which will be similar to the following:

#!/bin/sh

CHROOT=/chroot/httpd/
HTTPD=/usr/local/apache/bin/httpd
PIDFILE=/usr/local/apache/logs/httpd.pid

echo -n " apache"

case "$1" in
start)
/usr/sbin/chroot $CHROOT $HTTPD
;;
stop)
kill `cat ${CHROOT}/${PIDFILE}`
;;
*)
echo ""
echo "Usage: `basename $0` {start|stop}" >&2
exit 64
;;
esac

exit 0

The above script should be copied to the proper directory (depends on particular UNIX system), where by default startup scripts are held. In case of FreeBSD it is the /usr/local/etc/rc.d directory.

Summary

The above method allows achieving a higher security level of the Apache server than the one, offered in the default installation.

Thanks to enabling only the absolutely necessary Apache modules, finding a new vulnerability in one of them doesn't have to indicate that our server is vulnerable. Hiding the Apache's version number, turning off the directory indexing service, chrooting and restricted configuration make a successful break-in very difficult. A chrooted environment has also one more important advantage - immunity to the large number of exploits, mainly because of lack of the shell (/bin/sh, /bin/csh etc.). Even if an intruder will success in executing system commands, escaping the chrooted environment could turn out to be quite a problem.

================================================== ================================================== ====================


Securing PHP: Step-by-step
by Artur Maj
last updated June 23, 2003

--------------------------------------------------------------------------------

In my previous article ("Securing Apache: Step-by-Step") I described the method of securing the Apache web server against unauthorized access from the Internet. Thanks to the described method it was possible to achieve a high level of security, but only when static HTML pages were served. But how can one improve security when interaction with the user is necessary and the users' data must be saved into a local database?

This article shows the basic steps in securing PHP, one of the most popular scripting languages used to create dynamic web pages. In order to avoid repeating information covered in the previous article, only the main differences related to the process of securing Apache will be described.

Operating system

Like in the previous article, the target operating system is FreeBSD 4.7. However, the methods presented should also apply on most modern UNIX and UNIX-like systems. This article also assumes that a MySQL database is installed on the host, and is placed in the "/usr/local/mysql" directory.

Functionality

Generally, functionality will be very similar to the one described in the previous article. However, there are some changes:

The web server must handle the PHP scripting language
The PHP component must be able to read and write users' data in a locally installed MySQL database
Security assumptions

In case of security assumptions, the following have been added:


The PHP configuration should take advantage of built-in security mechanisms
PHP scripts must be executed in a chrooted environment
The Apache server must reject all requests (GET and POST), which contain HTML tags (possible Cross-Site-Scripting attack) or apostrophe/quotation marks (possible SQL Injection attack)
No PHP warning or error messages should be shown to the web application's regular users
It should be possible to store incoming GET and POST requests into a text file which will make it possible to use additional, host-based intruder detection system (HIDS), e.g. swatch.
Preparing the software

First of all, we have to download the source code of the latest version of Apache, PHP and the mod_security module. The module will be used to implement the protection against CSS and SQL injection attacks. Next, the downloaded software must be unpacked and the content of the archive must be placed in the home directory. The source code of mod_security should be placed into the Apache's "src/modules/extra" directory:

gzip -dc apache_1.3.27.tar.gz | tar xvf -
gzip -dc php-4.3.2.tar.gz | tar xvf -
gzip -dc mod_security_1.5.tar.gz | tar xvf -
cp mod_security_1.5/apache1/mod_security.c apache_1.3.27/src/modules/extra/


If any available security patches to the above software exist, they should be downloaded and applied as well.

Before we start compiling the software, we must also decide, which of three methods of PHP installation we'll choose:

as a web server's static module
as a web server's dynamic module
as a CGI interpreter
Each of above methods has its advantages and disadvantages. Compiling PHP as a static module will benefit from improved web server performance, but upgrading to a newer version of PHP later on will require recompilation of the whole web server. The second option, compiling as a dynamic module, hasn't got this disadvantage but the performance of the web server is decreased by approximately 5%. Additionally, one more module would be needed: mod_so. The third method is to install PHP as a CGI interpreter - in conjunction with Apache's suEXEC mechanism this is quite an interesting solution. Unfortunately, when not properly installed it can pose a serious security threat.

From a security and performance point of view, the best choice seems to be compilation as a static module. That's why the rest of this article is based on that method of installation.

Installing PHP

Generally, the installation process of Apache with PHP is very similar to the process of installing Apache without PHP, as described in the previous article. The only difference is the use of two additional modules: mod_php and mod_security.

As in the previous article, we will start by creating an account and group called "apache". Then we must prepare the Apache web server as follows:

cd apache_1.3.27
./configure


and compile the PHP module:

cd ../php-4.3.2
./configure --with-mysql=/usr/local/mysql --with-apache=../apache_1.3.27 --enable-safe-mode
make
su
make install


Next, we move to the directory with Apache source, and continue installation:

cd ../apache_1.3.27
./configure --prefix=/usr/local/apache --disable-module=all --server-uid=apache --server-gid=apache --enable-module=access --enable-module=log_config --enable-module=dir --enable-module=mime --enable-module=auth --activate-module=src/modules/extra/mod_security --enable-module=security --activate-module=src/modules/php4/libphp4.a
make
su
make install
chown -R root:sys /usr/local/apache


In the above "./configure" command, only those modules that are necessary to fulfill functionality and security assumptions are used. The choice of modules was discussed in details of the previous article. Now the next step is to return to the PHP directory and to copy the default PHP configuration file:

cd ../php-4.3.2
mkdir /usr/local/lib
chmod 755 /usr/local/lib
cp php.ini-recommended /usr/local/lib/php.ini
chown root:sys /usr/local/lib/php.ini
chmod 644 /usr/local/lib/php.ini


In order for the PHP scripts to be properly handled by the Apache web server, the following line should be added to /usr/local/apache/conf/httpd.conf:

AddType application/x-httpd-php .php


At this point we can try to run Apache and check if PHP can properly communicate with MySQL. We can achieve this by using the sample "test.php" script with the following content (the "user_name" and "password" values should be changed in accordance with installed database):


<html><body>
<?php
&nbsp; &nbsp; $link = mysql_connect("localhost", "user_name", "password")
&nbsp; &nbsp; &nbsp; or die;
&nbsp; &nbsp; print "Everything works OK!";
&nbsp; &nbsp; mysql_close($link);
?>
</body></html>

The above web page can be viewed by using any Internet browser. If PHP instructions are properly interpreted and a connection to MySQL is established, we can start securing the software. If not - we should analyze the Apache and MySQL log files and eliminate the cause of the problems.

Chrooting the server

The first step of securing the server is to prepare a chrooted environment for the Apache server with PHP module.

At this point, we should perform all the steps described in the "Chrooting the server" section of the previous article. In addition, before running Apache in chrooted environment for first time, we must also copy the following libraries (they are needed in order for PHP to run properly):

cp /usr/local/mysql/lib/mysql/libmysqlclient.so.12 /chroot/httpd/usr/lib/
cp /usr/lib/libm.so.2 /chroot/httpd/usr/lib/
cp /usr/lib/libz.so.2 /chroot/httpd/usr/lib/


Additionally, we have to copy the PHP default configuration file:

umask 022
mkdir -p /chroot/httpd/usr/local/lib
cp /usr/local/lib/php.ini /chroot/httpd/usr/local/lib/


and create a /chroot/httpd/tmp directory. The directory owner must be root, and access rights should be set to 1777. After creating the new environment we should test, if Apache runs correctly:

chroot /chroot/httpd /usr/local/apache/bin/httpd


Before we begin to configure PHP we must also take care of one more very important detail - communication between PHP and MySQL. Because PHP communicates locally with MySQL by using the /tmp/mysql.sock socket, placing PHP in the chrooted environment means that they cannot communicate with each other. To solve that problem, each time we run MySQL we must create hard link to the Apache chrooted environment:

ln /tmp/mysql.sock /chroot/httpd/tmp/


Note that in order to make communication between PHP and MySQL possible, the "/tmp/mysql.sock" socket and the "/chroot/httpd/tmp" directory must be physically placed on the same filesystem (hard links don't work between filesystems).

Configuring PHP

The process of securing the Apache server was described in the previous article, so as a starting point we'll use the configuration file that was presented there. For Apache to handle PHP scripts, we must add the following lines to httpd.conf:

AddModule mod_php4.c
AddType application/x-httpd-php .php
AddType application/x-httpd-php .inc
AddType application/x-httpd-php .class


It is worth to note that besides "*.php", two extensions have been added as PHP scripts: "*.inc" and "*.class". Programmers often include additional files, with an extension like "*.inc", "*.class" or similar. Because by default those extensions are treated as regular files, the requests to download them will reveal the source code comprised in them. This can lead to revealing passwords or other sensitive information.

A few changes must also be made in the PHP configuration file (/chroot/httpd/usr/local/lib/php.ini). The most important changes that should be made to improve PHP security are as follows:

Parameter Description
safe_mode = On By enabling safe_mode parameter, PHP scripts are able to access files only when their owner is the owner of the PHP scripts. This is one of the most important security mechanisms built into the PHP. Effectively counteracts unauthorized attempts to access system files (e.g. /etc/paswd) and adds many restrictions that make unauthorized access more difficult.
safe_mode_gid = Off When safe_mode is turned on and safe_mode_gid is turned off, PHP scripts are able to access files not only when UIDs are the same, but also when the group of the owner of the PHP script is the same as the group of the owner of the file.
open_basedir = directory[:...] When the open_basedir parameter is enabled, PHP will be able to access only those files, which are placed in the specified directories (and subdirectories).
safe_mode_exec_dir = directory[:...] When safe_mode is turned on, system(), exec() and other functions that execute system programs will refuse to start those programs, if they are not placed in the specified directory.
expose_php = Off Turning off the "expose_php" parameter causes that PHP will not disclose information about itself in HTTP headers that are being sent to clients in responses to web requests.
register_globals = Off When the register_globals parameter is turned on, all the EGPCS (Environment, GET, POST, Cookie and Server) variables are automatically registered as global variables. Because it can pose a serious security threat, it is strongly recommended to turn this parameter off (starting from the version 4.2.0, this parameter is turned off by default)
display_errors = Off If the display_errors parameter is turned off, PHP errors and warnings are not being displayed. Because such warnings often reveal precious information like path names, SQL queries etc., it is strongly recommended to turn this parameter off on production servers.
log_errors = On When log_errors is turned on, all the warnings and errors are logged into the file that is specified by the error_log parameter. If this file is not accessible, information about warnings and errors are logged by the Apache server.
error_log = filename This parameter specifies the name of the file, which will be used to store information about warnings and errors (attention: this file must be writeable by the user or group apache)


In addition, changing the file extension can be taken into account. For example *.php to *.asp, *.dhtml or even *.html. Such a change will make it difficult for any potential intruders to recognize the server-side technology that is being used. In order to change the extensions, all the *.php files should be renamed to *.dhtml (for example), and the following line should be changed in /chroot/httpd/usr/local/apache/conf/httpd.conf:

AddType application/x-httpd-php .php


to the new one:

AddType application/x-httpd-php .dhtml


Thanks to that, web users will not see *.php extension in the URL address which is what immediately suggests that the PHP technology is being used at the server side.

Defending against CSS and SQL Injection attacks

The last step of securing the server is implementing the logging of the GET and POST payloads, and implementing protection against Cross-Site-Scripting and SQL Injection attacks. In order to perform that, we will use the mod_security module, which we enable by adding the following line into httpd.conf:


AddModule mod_security.c

To enable logging of the GET and POST requests, it suffices to add the following section to httpd.conf:


<IfModule mod_security.c>
&nbsp; &nbsp; AddHandler application/x-httpd-php .php

&nbsp; &nbsp; SecAuditEngine On
&nbsp; &nbsp; SecAuditLog logs/audit_log
&nbsp; &nbsp; SecFilterScanPOST On
&nbsp; &nbsp; SecFilterEngine On
</IfModule>

The above commands will enable the Audit Engine, which is responsible for logging requests, and the Filtering POST Engine, which will make it possible to log POST requests. In order to protect web application against CSS attacks, the following lines should also be inserted before "</IfModule>":


&nbsp; &nbsp; SecFilterDefaultAction "deny,log,status:500"
&nbsp; &nbsp; SecFilter "<(.|\n)+>"

The first line causes that the server to return the "Internal Server Error" message when the request contains the search phrase from any SecFilter variable. The second line sets up the filter to search for HTML tags in the GET and POST requests.

One of the typical signatures of SQL Injection attack is the appearance of an apostrophe (') or quotation mark (") in the GET or POST request. By rejecting all the requests containing those characters, we can make the use of SQL Injection technique very difficult:


&nbsp; &nbsp; SecFilter "'"
&nbsp; &nbsp; SecFilter "\""

Note, that although filtering the <, >, ', " characters lets us defend against CSS and SQL Injection attacks, it can lead to the improper functioning of the PHP application. It happens, because regular users cannot use those characters in the HTML forms. To solve that problem, the JavaScript language can be used on the client side, which should replace the prohibited characters with special tags, e.g. < > " etc.

Summary

Achieving a high level of a web server's security using server-side technologies (PHP, ASP, JSP etc.) is a very difficult task in practice. The very nature of interactions with a web server in any significant way decreases the web server's security. That is why server-side scripts should only be used where it is absolutely necessary.

The methods described in this article let us mitigate the risk of a successful break-in when new vulnerabilities in Apache, PHP or even the web application itself are found. Of course, the article doesn't exhaust the subject of securing the PHP technology - only the basic outlines were presented. And although applying them can increase the level of security, we cannot forget that the security of the whole environment depends not only on Apache's or PHP's configuration, but also and foremost - on the web application itself.


/JD
__________________


Reply With Quote
  #2  
Old 25th Jun 03, 08:49 PM
billybob3's Avatar
billybob3 billybob3 is offline
Senior Member
 
Join Date: Apr 2003
Location: Earth
Posts: 577
billybob3
Send a message via AIM to billybob3 Send a message via MSN to billybob3
WOA! That's long. Great info though, thanks!
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump


All times are GMT +1. The time now is 12:05 PM.


Design by Vjacheslav Trushkin for phpBBStyles.com.
Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.