ModSecurity: Part Two

ModSecurity

Configuring site proxies in ModSecurity under pfSense 2.1.5.

In the previous article, we covered installation of ModSecurity and began configuration. In this article, we continue our look at configuration.

We had covered the first five settings on the “Proxy Server Settings” tab. The next setting, the “Use mod_mem_cache” checkbox, enables mod_mem_cache, which stores cached documents in memory. In the next edit box, “mod_mem_cache memory usage”, you can set the memory usage in megabytes. The next setting, the “Use mod_disk_cache” checkbox, implements a disk-based storage manager if checked. The memory usage (in KB) can be specified in the next edit box.

The next setting is to limit the number of POSTS accepted from the same IP address. The purpose of this setting is to help prevent the effects of a Slowloris type of attack. The Slowloris tool provides a means of executing a DoS attack on a web server by not sending a complete set of HTTP request headers. The request will omit the final carriage return/line feed (CRLF) that tells the destination web server that the request has completed so the web server dutifully waits for more request data until it reaches its timeout setting. Now Slowloris can keep it in perpetual waiting mode by sending new requests just before the web server’s timeout setting is reached. Obviously, one of the ways of mitigating the effects of such an attack is to limit the number of POSTS allowed from a single IP address, and this is the objective here.


The next edit box configures the maximum request body size ModSecurity will store in memory. Anything over this limit will be rejected with status code 413 Request Entity Too Large. The next edit box sets the maximum request body size ModSecurity will accept for buffering. The default value is 128 KB.

The next check box, “Enable mod_security protection”, enables mod_security protection for all sites being proxied. The dropbox below that configures the audit logging engine. Possible values are: “On” – log all transactions by default; “Off” – do not log transactions by default; “RelevantOnly” – by default, only log transactions that have triggered a warning or error, or have a status code that is considered to be relevant. The last two edit boxes allow you to specify a custom ErrorDocument and to enter custom ModSecurity rules.

ModSecurity: Configuring Site Proxies

The next tab is “Site Proxies”. By clicking on the “plus” sign on the right side of the page, you can add to the list of sites that will use the ModSecurity Apache proxy. Once you do, you can enter the site name, site webmaster e-mail address, and protocol (HTTP or HTTPS). If you specify HTTPS, then you must specify the “Certificate File”, “Certificate Key File”, and “Certificate Chain File” next. If the “Preserve Proxy hostname” check box is checked, it will pass the “Host:” line from the incoming request to the proxied host instead of the backend IP address. At “Primary site hostname”, you can enter the fully qualified domain name (FQDN) for the website. Finally, you can also specify backend web servers for this site, as well as additional site hostnames.

The third tab, “Logs”, allows you to view the Apache ModSecurity proxy server logs. Pressing the “Clear log” button deletes the log.


External Links:

Mitigating Slow HTTP DoS Attacks at blog.spiderlabs.com – This blog contains a lot of useful information about computer security, especially ModSecurity

Slowloris HTTP DoS – official site for the Slowloris tool

ModSecurity Reference Manual

Apache Server Hardening: Part Six

Apache server

Additional Directives

Within the directive is a subdirective called Options that controls functionality for the directory structures specified in the directive. The available options are listed below.

Option Functionality
All Default setting; includes all options except MultiViews
ExecCGI Permits CGI script execution through mod_cgi
FollowSymLinks Allows Apache to follow OS file symlinks
Includes Permits SSI through mod_include
IncludeNOEXEC Permits SSI but denies exec and exec cgi
Indexes Allows autoindexing using mod_autoindex if no configured index file is present
MultiViews Permits content negotiation using mod_negotiation
SimLinksIfOwnerMatch Allows Apache to follow OS file system symlinks but only if the link and target file have the same owner

Many of the listed options are not relevant to our installation, since we disabled Includes and CGI during compile time. Regardless, here is a good default directive disabling most options:

<Directory “/usr/local/apache/htdocs”>
Order allow,deny
Allow from all
Options -FollowSysLinks -ExecCGI -Includes -Indexes \
-MultiViews
AllowOverride None

</Directory>

At this point, your Apache server should be relatively secure. Now, we move on to configuring logging options.


There are many reasons to configure logging on you Apache server. Whether helping you see top page hits, hours of typical high volume traffic, or simply understanding who is using your system, logging plays an important part of any installation. More importantly, logging can provide a near-real-time and historic forensic toolkit during or after security events.

to ensure that your logging directives are set up correctly, we will provide an example of the logging options in the Apache web server. Apache has many options with which you should familiarize yourself by reading the Apache mod_log_config documentation page. This will help you understand the best output data to record in logs. Also, recall that we compiled Apache with mod_log_forensic, which provides enhanced granularity and logging before and after each successful page request.

An example logging configuration file is shown here:

ErrorLog /var/log/apache/error.log
LogLevel Info
 Logformat “%h %l %u %t \”%r\” %>s %b \”%{Referer}i\” \”%{User-Agent}i\”\”%{forensic-id}n\” %T %v” full
CustomLog /var/log/apache/access.log combined
ForensicLog /var/log/apache/forensic.log

The example provides a customized logging format that includes detailed output and places all the log files in the /var/log/apache directory.

After you have installed and configured your Apache server, you will need to do some quick cleanup of files that could represent a security threat. In general, you should not leave the source code you used to compile Apache on the file system. It is a good idea to tar the files up and move them to a secure server. Once you’ve done so, remove the source code from the Apache web server.

Removing Directories and Setting Permissions

You’ll also want to remove some of the default directories and files installed by the Apache web server. To do so, execute the following commands on your web server. If you have added content into your document root directory, you will want to avoid the first command:

rm -fr /usr/local/apache/htdocs/*
rm -fr /usr/local/apache/cgi-bin
rm -fr /usr/local/apache/icons

After removing files, let’s ensure that our Apache files have proper ownership and permissions before starting our server.

As we discussed previously, the Apache web server should be run as an unprivileged and unique account. In our example, we used the user wwwusr and the group wwwgrp to run our server. Let’s make sure our permissions are properly set by running the following commands:

chown -R root:wwwgrp /usr/local/apache/bin
chmod -R 550 /usr/local/apache/bin
chown -R root:wwwgrp /usr/local/apache/conf
chmod -R 660 /usr/local/apache/conf
chown -R root:wwwgrp /usr/local/apache/logs
chmod -R 664 /usr/local/apache/logs
chown -R root /usr/local/apache/htdocs
chmod -R 664 /usr/local/apache/htdocs

Monitoring Your Server

Even with the best defenses and secure configurations, breeches in your systems and applications could occur. Therefore, you cannot simply set up a hardened Apache web server and walk away thinking that everything will be just fine. Robust and comprehensive monitoring is perhaps the most important part of securely operating servers and applications on the Internet.

In Apache, there are several things to consider that will help you to identify and react to potential threats. Your primary source of data will be through Apache and OS logs. Even with small web sites, however, sifting through this information can be a challenge. One of the first things to consider is intergrating your Apache logs with other tools to help organize and identify potential incidents within the log file. Many open source and commercial products are available to aid you in securing your site. One such open source tool is called Webalizer, available at the http://www.webalizer.org/, which features graphical representation of your Apache log file contents.

SNMP polling and graphing constitute another methodology commonly employed for secure monitoring. Often, it is extremely difficult to gauge the severity or magnitude of an even without visualization of data from logs or SNMP counters. One tool you might consider using is a module called mod_apache_snmp, available at Sourceforge. The module can provide real-time monitoring of various metrics including, but not limited to:

  • Load average
  • Server uptime
  • Number of errors
  • Number of bytes and requests served

You might consider other commercial SNMP-based solutions especially for enterprise-scale deployments. These tools help expedite monitoring deployment and usually include enhanced functionaility to automatically alter you when important thresholds, such as web site concurrent connections, are crossed.

External Links:

The official Apache web site

The official Webalize web site

The official Mod-Apache-Snmp web site

Apache Server Hardening: Part Five

Apache server

Apache User Authentication

Apache also includes several ways in which you can authenticate customers using your web server such as LDAP, SecureID, and basic .htaccess, to name a few examples. To use authentication mechanisms beyond basic .htaccess, you must compile additional functionality when you’re building Apache. Like access control, authentication mechanisms are specified as part of the directive.

The two steps to enabling basic .htaccess user authentication are:

  1. Creating an htpasswd file to store user credentials.
  2. Adding a directive to the httpd.conf file to protect a directory structure.

This is different than adding a login form on a web page and creating your own authentication. Let’s use an example to demonstrate how easy it can be to add authentication. In our example, we will secure a directory called /securedir and permit only customers Homer and Marge access to the files in that directory.


First, let’s create an htpasswd file somewhere not in the web server document root by issuing the following command:

htpasswd -c /usr/local/apache/passwdfile homer
New password: *****
Re-type new password: *****
Adding password for user homer

Next, we’ll add Marge to the list as well. This time we don’t need to use the -c argument, since our htpasswd file already exists:

htpasswd /usr/local/apache/passwdfile marge
New password: *****
Re-type new password: *****
Adding password for user marge

Now that we’ve established our customer accounts, we’ll finish by adding a directive to the httpd.conf file to protect the /securedir directory as follows:

<Directory /usr/local/apache/htdocs/secure>
AuthType Basic
AuthName “Access for authenticated customers only”
AuthUserfile /usr/local/apache/passwdfile
require user marge homer

</Directory>

Now, when anyone attempts to access the /securedir directory, they’ll be prompted for a username and password. Because we specifically require only Marge and Homer, only they will be permitted to use the directory structure, if they authenticate properly.

You can also restrict access based on a domain or IP address. The following directive will do this:

Order deny, allow
Deny from all
Allow from allowable-domain.com
Allow from XXX.XXX.XXX
Deny from evil-domain.com

You can specify the first three (or one or two) octets of an IP address defining the allowable domain.

Although this example involves modifying the httpd.conf file to control directory access, there is another way. You can create an .htaccess and .htpasswd file in the directory to which you want to control access. The .htaccess file should contain the same directive we described above. The .htpasswd file must be created using htpasswd. In the above example, to add access for Homer and Marge, we would first create (or clobber if it already exists) the password file /securedir/.htpasswd:

htpasswd -c .htpasswd homer

Now that we have created .htpasswd, we can add user marge to the existing password file (which contains one user, homer):

htpasswd .htpasswd marge

Within the directive is a subdirective called Options that controls functionality for the directory structures specified in the directive. The available options are listed below:

Option Functionality
All Default setting; includes all options except MultiViews
ExecCGI Permits CGI script execution through mod_cgi
FollowSymLinks Allows Apache to follow OS file system symlinks
Includes Permits SSI through mod_include
IncludesNOExEC Permits SSI but denies exec and exec cgi
Indexes Allows autoindexing using mod_autoindex if no configured index file is present
MultiViews Permits content negotiation using mod_negotiation
SimLinksIfOwnerMatch Allows Apache to follow OS file system symlinks but only if the link and target file have the same owner

Many of the listed options are not relevant to our installation, since we disabled Includes and CGI during compile time. Regardless, a good default directive disabling most options is shown here:

<Directory “/usr/local/apache/htdocs”>
Order, allow, deny
Allow from all
Options -FollowSysLinks -ExecCGI -Includes -Indexes \
-MultiViews
AllowOverride None

</Directory>

At this point, your Apache server should be relatively secure. In the next article, we will discuss some Apache logging directives so that we can better monitor our server.

External Links:

Authentication and Authorization at the official Apache website

Apache Web Login Authentication at yolinux.com

Apache Server Hardening: Part Four (httpd.conf)

httpd.confIn the previous article, we looked at compiling and installing Apache and discussed the benefits of mod_security. In this article, we will cover httpd.conf configuration.

httpd.conf File Configuration

The Apache web server stores all its configuration data in the httpd.conf file located in the $[ApacheServerRoot] directory, which is, in our example, /usr/local/apache. The httpd.conf file includes many directives that can be categorized into the following sections:

  • Server Directives
  • User Directives
  • Performance/Denial of Service directives
  • Server Software Obfuscation Directives
  • Access Control Directives
  • Authentication Mechanisms
  • Directory Functionality Directives
  • Logging Directives

Not all directives play a significant role with regard to security. In this article, we will discuss the directives that impact the security of your Apache server. Furthermore, because we disabled a lot of functionality at compile time, some directives that would normally be dangerous do not need to be removed, since they were not added into the compiled Apache binaries. There may also be other configuration files, called Include files, associated with the httpd.conf file. Since we have enabled mod_security, there is a long list of potential configurations to make in an Include filled called modsecurity.conf, which is usually located in the $[ApacheServerRoot]/conf directory.


In this section, I included the modsecurity.com recommended mod_security configuration. For more information about configuring this file, refer to the mod_security documentation.

Recommended modsecurity.conf file:

# Turn ModSecurity On
SecFilterEngine On

# Reject requests with status 403
SecfilterDefaultAction “deny.log.status.403”

# Some sane defaults
SecFilterScanPOST On
SecFilterCheckURLEncoding On
SecfilterCheckUnicodeEncoding Off

# Accept almost all byte values
SecFilterForceByteRange 1 255

# Server masking is optional
# SecServerSignature “OurServer”

SecUploadDir /tmp
SecUploadKeepFiles Off

# Only record the interesting stuff
SecAuditEngine RelevantOnly
SecAuditLog logs/audit_log

# You normally won’t seed debug logging
SecFilterDebugLevel 0
SecFilterDebug logs/modsec_debug_log

# Only accept request encodings we know how to handle
# we exclude GET requests from this because some (automated)
# clients supply “text/html” as Content-Type
SecFilterSelective REQUEST_METHOD “|^(GET|HEAD)$” chain
SecFilterSelective HTTP_Content-Type \
“|(^application/x-222-form-urlencoded$|^multipart/form-data;)”

# Do not accept GET or HEAD requests with bodies
SecFilterSelective REQUEST_METHOD *^(GET|HEAD)$” chain
SecFilterselective HTTP_content-Length “!^$”

# Require Content-Length to be provided with
# every POST request
SecFilterSelective REQUEST_METHOD “^POST$” chain
SecFilterSelective HTTP_Content-Length ‘^$”

# Don’t accept transfer encodings we know we don’t handle
SecFilterSelective HTTP_Transfer-Encoding “!^$”

There are a couple directives you must configure in the httpd.conf file to ensure that the Apache web server runs using the unprivileged user account we established earlier, among other things. Inspect your httpd.conf file to verify that the following statements appear as show in the following. Recall that we decided to run Apache as wwwusr:wwwgrp.

User wwwusr
Group wwwgrp

Also, configure the serverAdmin directive with a valid alias e-mail address such as the following:

ServerAdmin hostmasteryoursecuredomain.com

This will provide a point of contact for your customers, should they experience problems with your site.

Performance-Tuning Directives in httpd.conf

there are a number of performance-tuning directives in the Apache httpd.conf file. As a security professional, you should interpret those directives as DoS prevention statements, since they control resource allocation for users of the Apache server. The following directives control the performance of an Apache server:

  • Timeout: Configures the time Apache waits to receive GET requests, the time between TCP packets for POST or PUT requests, or the time between TCP ACK statements in responses. The Apache default is 300 seconds (3 mintues), but you might want to consider reducing this timer to 60 seconds to mitigate DoS attacks.
  • KeepAlive: Configures HTTP1.1-compliant persistency for all web requests. By default, this is set to On and should remain as such to streamline web communication.
  • KeepAliveTimeout: Determines the maximum time to wait before closing an inactive, persistent connection. Here we will keep this value att the default of 15 seconds, since raising it can cause performance problems on busy servers and expose you to DoS attacks.
  • StartServers: Designates the number of child processes to start when Apache starts. Setting this value higher than the default of 5 can increase server performance, but use care not to set the value too high, because doing so could saturate system resources.
  • MinSpareServers: This setting, like the MaxSpareServers setting, allows for dynamic adjustment of Apache child processes. MinSpareServers instructs Apache to maintain the specified number of idle processes for new connections. This number should be relatively low except on very busy servers.
  • MaxSpareServers: Maintains Apache idle processes at the specified number. Like MinSpareServers, the value should be low, except for busy sites.
  • MaxClients: As its name implies, this setting determines the maximum number of concurrent requests to the Apache server. We will leave this as the default value of 256.

Once you’ve finished editing this section of your httpd.conf, you should see something similar to the following:
Timeout 60
KeepAlive On
KeepAliveTimeout 15
StartServers 5
MinSpareServers 10
MaxSpareServers 20
MaxClients 256

By default, Apache informs web users of its version number when delivering a 404 (page not found) error. Since it is good practice to limit the information you provide to would-be hackers, we will disable this feature. Recall that we already altered the Apache server signature and that we installed mod_security. Both of these actions should be enough to obfuscate our server because they both alter the default behavior. If you would like to turn off server signatures completely, you can always set the ServerSignature directive to Off and the Server tokens to Prod. this will disable Apache signatures entirely.

The Apache web server includes mechanisms to control access to server pages and functionality. The statement syntax is part of the directive and is fairly straightforward: you specify a directory structure, whether default access is permitted or denied, and the parameters that enable access to the directory if access is denied by default. There are many options for fine-grained control that you should learn by reading the Directory Directive section of the Apache Core Features document in the current version of the Apache documentation.

Regardless of the access you provide to your customers, you should secure the root file system using access control before placing your server into a production environment. In you httpd.conf file, you should create a statement in the access control directives area as follows:

<Directory />

Order, Deny, Allow
deny from all

</Directory>

This statement will deny access to the root file system should someone intentionally or accidentally create a symlink to /.

In the next article, we will discuss further hardening our Apache server using authentication mechanisms.

External Links:

The official Apache website

Apache Server Hardening: Part Two

Apache server hardeningAfter you’ve patched and hardened your OS, you’ll need to accomplish a couple quick tasks prior to obtaining, compiling and installing the Apache software. A critical part of installing Apache is to provide a user account and group that will run the web server. It is important that the user and group you select to be unique and unprivileged to reduce exposure to attack.

It is important not to run your Apache web server as the user Nobody. Although this is often a system administrator favorite and seemingly unprivileged account for running Apache and other services, the Nobody account has historically been used for root-like operations in some OSes and should be avoided.

Configuring Accounts

Choose and configure a user and group account using the following Unix OS steps. In this example, we will use wwwusr and wwwgrp as the Apache username and group, respectively.

  1. As root from the command line, type groupadd wwwgrp to add a group.
  2. Type useradd -d /usr/local/apache/htdocs -g wwwgrp -c “Apache Account” -m wwwusr to add the user.

The second step creates the user account but also creates a home directory for the user in /usr/local/apache/htdocs.

After creating the user and group accounts, you’ll need to lock down the wwwusr user account for use with Apache. By locking the account and providing an unusable shell, this action ensures that no one can actually log into the Web server using the Apache account:

  1. As root from the command line, type passwd -l wwwusr to lock the Apache account.
  2. Type usermod -s /bin/false wwwusr to configure an unusable shell account for the Apache account.

Now you’re ready to get the Apache software and begin installation.

Downloading and Verifying Apache

Because Apache is open-source software, you can freely download the binaries or source code and get going with your installation. Although there are many locations from which you could download the software, it is always best to obtain the Apache software directly from an approved Apache Foundation mirror listed at the mirror list page of official Apache site.


You’ll need to decide whether to install the server using precompiled binaries or to compile the source code yourself. From a security and functionality perspective, it is usually better to obtain the source code and compile the software, since doing so permits fine-tuning of security features and business functionality. perspective, it is usually better to obtain the source code and compile the software, since doing so permits fine-tuning of security features and business functionality. Here we will discuss compiling the Apache server from source code, starting with verifying the integrity of your download.

To verify the checksum, you will need additional software called md5sum that might be part of your OS distribution. If it is not, you can download the software as part of GNU Coreutils available at the Coreutils page of the official GNU Operating System website. To verify the Apache checksum, perform the following steps. In this example, we’ll use Apache version 2.4.9:

  1. As root from the command line, change directories to where you downloaded the Apache source code tarball and checksum file.
  2. Type cat httpd-2.4.9.tar.gz.md5 to see the exact md5 checksum string. You should see something like f72fb1176e2dc7b322be16508isl39d httpd-2.4.9.tar.gz.
  3. from the same directory, type md5sum httpd-2.4.9.tar.gz.md5 to obtain the checksum from the tarball. You should see the identical string shown in Step 2. If you do, the software you downloaded is authentic.

In the next article, we’ll cover compiling Apache.

External Links:

The Official Apache site

The official GNU Operating System site

Network Hardening with Bastille

network hardeningBastille is an open source program that facilitates the network hardening of a system running Linux. It performs many of the tasks discussed in previous articles on this blog such as disabling services and ports. It eases the process of hardening a Linux system, giving you the choice of what to lock down and what not to, depending on your security requirements, and bundles many of the routine tasks done to secure a Linux system into a single package.

Bastille is powerful and can save administrators time from configuring each individual file and program throughout the operating system. Bastille is a set of Perl scripts that run as an interactive program, and instead of configuring files and programs individually, in Bastille the administrator answers a series of “Yes” and “No” questions through an interactive GUI. The program automatically implements the administrator’s preferences based on their answer to the questions, thus streamlining the network hardening process.


Bastille is written specifically for Red Hat Linux and Mandrake Linux, but it can easily be modified to run on most Unixoid systems. The specific Red Hat/Mandrake content has been generalized, and now the formerly hard-coded filenames are represented as variables. These variables are set automatically at runtime. Before you install Bastille on your system, you will want to ensure your Linux version is supported by Bastille. It is known to work with Red Hat, Fedora, SUSE, Debian, Ubuntu, Gentoo, and Mandriva, as well as HP-UX.


Network Hardening with Bastille: Features

More information about each of Bastille’s features is available when the program is run, but here is an overview of the main network hardening features of the program:

  • Apply restrictive permissions on administrator utilities: This allows only the root to read and execute common admin utilities such as ifconfig, linux-conf, ping, traceroute, and runlevel. It also disables the SUID root status for these programs.
  • Disable r-protocols: The r-protocols allow users to log on to remote systems using IP-based authentication. This authentication is based on the IP address, so a hacker could easily create spoofed packets that appear to be from the authorized system.
  • Disable CTRL-ALT-DELETE rebooting: This disallows rebooting the machine by this method.
  • Optimize TCP Wrappers: This choice modifies the inetd.conf and /etc/hosts.allow file so that whenever inetd gets a request, it has to contact TCP Wrappers, which will determine if the requesting IP address is allowed to run the service.
  • Limit system resource usage: If you limit system resource usage, you improve network hardening can reduce the chances of a denial-of-service (DoS) attack. If you limit system resource usage, the following changes will occur:
    • Individual file size is limited to 40 MB.
    • Each individual user is limited to 150 processes.
    • The allowable core files number is configured to zero. Core files are used for system troubleshooting, and can be exploited by hackers if the gain control of them.
  • Restrict console access: Bastille can specify which user accounts are allowed to log on via the console.
  • Additional and remote logging: Enables the admin to add two additional logs to /var/log: /var/log/kernel (for kernel messages) and /var/log/syslog (for error and warning severity messages)
  • Process accounting setup: Allows you to log the commands of all users.
  • Deactivate NFS and Samba: NFS (Network File System) and Samba are services for accessing files from Linux systems on remote systems. Unless the firewall is configured to block the packets or the admin secures these services, Bastille recommends deactivating these services.
  • Harden Apache web server: httpd should be disabled if the service is not required. If Apache is being run, there are also ways of enabling Apache in a manner that ensures maximal network hardening.




Implementing this policy goes a long way towards achieving network hardening. In the next article, we will take a look at the process of implementing Bastille.

External Links:

The official Bastille web site

How to Harden Your Linux Server’s Security with Bastille on www.unixmen.com

Hardening your systems with Bastille Linux at linux.com

© 2013 David Zientara. All rights reserved. Privacy Policy