# mod_security and jailed apache HELP PLEASE !!

## dcreatorx

Hi everybody ! I'm at job and I need help with this issue. I followed step by step the WIKI: http://gentoo-wiki.com/Apache_chroot:_the_mod_security_way

But if I enable mod_security the server returns a 403 : Forbidden. The user and group for the jail is apache:apache I'll post all the configs here so maybe somebody can detect the error. Note that I only followed that manual, nothing more. Note too that in the mod security Core Rule set I only modified the SecChroot directive and the destination of logs, nothing more so don't spend lots of time looking for an error on that file. Thanks.

```

# ---------------------------------------------------------------

# Core ModSecurity Rule Set

# Copyright (C) 2006 Breach Security Inc. All rights reserved.

#

# The ModSecuirty Core Rule Set is distributed under GPL version 2

# Please see the enclosed LICENCE file for full details.

# ---------------------------------------------------------------

# Configuration contained in this file should be customized

# for your specific requirements before deployment.

#

# Next to each rule there is a description of what it does. Each

# location where customization is needed is marked with "TODO". It

# is recommended that you:

#

#  1) Keep a copy of the original file. This will allow you to use

#     the "diff" command to quickly see the changes. It will also

#     make upgrades to future rule sets easier.

#

#  2) Document your changes thoroughly.

#

# You are advised to start with ModSecurity in detection mode only.

# Switch to protection when you are comfortable with your rule set.

# For maximum protection monitor your logs on daily basis (or

# better).

#

# TODO You may want to provide an error friendly message to your

#      users when you start rejecting requests. You can do this using

#      the Apache ErrorDocument directive. You should also add

#      mod_unique_id to your configuration and display the unique

#      request ID on the error page. This would allow your users to

#      report the request ID back to you so that you can investigate

#      the false positive (if that's what it is). A nice error page

#      usually reduces the impact of false positives on the users.

#

#      The drawback of this user friendly approach is that it is

#      easier for the attackers to figure out there is an web

#      application firewall protecting the application.

#

#      ErrorDocument 403 /path/to/error_document.php

#

#      For more information see 

#      http://httpd.apache.org/docs-2.0/custom-error.html

## -- Configuration ----------------------------------------------------------

# Turn ModSecurity on ("On"), set to monitoring only 

# ("DetectionOnly") or turn off ("Off").

#

SecRuleEngine On

SecChrootDir /wwwjail

# Define which part of the HTTP transaction to inspect.

#

# Inspecting request body (SecRequestBodyAccess) should probably be always set

# to "on". Only very high volume sites that never use POST requests might want 

# to set it to "off" to optimize performance.

#

# Inspecting response body is useful for monitoring for information leaks, 

# or for signs of intrusion. However, it does require all responses to be 

# buffered in memory. For most sites this should not be a problem, but special

# care must be taken to avoid buffering file downloads (through

# MIME type selection, as shown below).

#

# TODO If you decide to enable output filtering make sure to

#      review the list of scanned MIME types. If pages of the types specified 

#      for outbound inspection are smaller than 512K in you application

#      (which is usually the case) you may reduce the SecResponseBodyLimit 

#      to protect from potential denial of service attacks.

#

SecRequestBodyAccess On

SecResponseBodyAccess On

SecResponseBodyMimeType (null) text/html text/plain text/xml

SecResponseBodyLimit 524288

# What to do when an error is encountered.

#

# The default is to log the error and let the request go through.

# This is a reasonable setting to start with because you do not

# want to reject legitimate requests with an untuned rule set.

#

# If, after monitoring the performance of the rule set after a

# sufficient period, you determine the rules never (or rarely

# trigger on legitimate requests) you can change to something

# else, such as "log,deny,status:500". You can also leave the

# default setting here as is, but use per rule action configuration

# to only configure some rules to reject requests, leaving most

# of them to work in detection mode.

#

#SecDefaultAction "phase:2,log,pass,status:500"

# Set web server identification string

#

# TODO In case you use Apache, you may want specify a simple server signature

#      instead of the detailed Apache default signature that list most modules

#      used on the specific Apache deployment:

#      "Apache/2.2.0 (Fedora)"   

#

SecServerSignature "Apache/2.2.0 (Fedora)"

## -- File uploads configuration -----------------------------------------------

# Temporary file storage path.

#

# TODO Change the temporary folder setting to a path where only

#      the web server has access.

#

SecUploadDir /tmp

# Whether or not to keep the stored files.

#

# In most cases you don't want to keep the uploaded files (especially

# when there is a lot of them). It may be useful to change the setting

# to "RelevantOnly", in which case the files uploaded in suspicious

# requests will be stored.

#

SecUploadKeepFiles Off

# Inspect uploaded files.

#

# TODO If there is a danger of attack through uploaded files then it

#      is possible to configure an external script to inspect each file

#      before it is seen by the application. An example script is

#      included with ModSecurity (/util/modsec-clamscan.pl).

#

#      Inspecting uploaded files is especially important in a hosting,  

#      community or blogging environments where uploading files is permitted. 

#

# NOTE the t:none action is required in order not to process the files names 

#      passed to the script based on previously defined actions in a 

#      SecDefaultAction directive.

#

# SecRule FILES_TMPNAMES "@inspectFile /opt/apache/bin/inspect_script.pl" \

#       "t:none"

## -- Logging ----------------------------------------------------------------

# Whether to log requests to the forensic log.

#

# By default, only requests that trigger a ModSecurity events (as detected 

# by) or a serer error are logged ("RelevantOnly"). This is a reasonable 

# setting. Full logging can be set by using # "on". If the system is used 

# for protection only and no logging is desired (not reccomended) logging can 

# be turned of using "off"

#

# NOTE It is also possible to configure forensic logging on the

#      per request basis using the "auditlog" and "noauditlog" rule

#      actions.

#

# TODO The default rule set logs requests that generate a 404 "file not found"

#      response. These events are interesting, but may log a lot of information.

#      you may consider removing it by setting SecAuditLogRelevantStatus

#      to "^(?:5|4\d[^4])".

#

SecAuditEngine RelevantOnly

SecAuditLogRelevantStatus "^[45]"

# Log files structure

#

# You can select to log all events to a single log file (set SecAuditLogType to 

# "Serial") or to log each request to a separate file (set it to "Concurrent"). 

# The former is usually easier to use, but if full logging is required or if 

# the protected system supports a large transaction volume the later may

# be a better option.

#

# TODO Set the SecAuditLog (for "Serial" logging) or SecAuditLogStorageDir (for

#      "Concurrent" logging).

#

# TODO If you change from "Serial" to "Concurrent" uncomment the 

#      SecAuditLogStorageDir directive and make sure the direcory specified 

#      exists and has write permissions for the Apache user. 

SecAuditLogType Serial

SecAuditLog /var/log/apache2/modsec_audit.log

# SecAuditLogStorageDir logs/modsec_audit

# Select what portions of the request to log

#

# Modify the string by adding any of the letter below to it:

# A - audit log header (mandatory)

# B - request headers

# C - request body (present only if the request body exists and ModSecurity is 

#     configured to intercept it)

# E - intermediary response body (present only if ModSecurity is configured to 

#     intercept response bodies, and if the audit log engine is configured to 

#     record it). Intermediary response body is the same as the actual response 

#     body unless ModSecurity intercepts the intermediary response body, in 

#     which case the actual response body will contain the error message 

#     (either the Apache default error message, or the ErrorDocument page).

# F - final response headers (excluding the Date and Server headers, which are 

#     always added by Apache in the late stage of content delivery).

# H - audit log trailer

# I - This part is a replacement for part C. It will log the same data as C in 

#     all cases except when multipart/form-data encoding in used. In this case 

#     it will log a fake application/x-www-form-urlencoded body that contains 

#     the information about parameters but not about the files. This is handy 

#     if you don't want to have (often large) files stored in your audit logs.

# Z - final boundary, signifies the end of the entry (mandatory)

SecAuditLogParts "ABIFHZ"

# Create a separate log to monitor performance.

#

# TODO Performance monitoring only works with Apache 2.x. You need

#      to add mod_unique_id and mod_logio to your configuration. Then

#      uncomment the following two lines.

#

# LogFormat "%V %h %t %{UNIQUE_ID}e \"%r\" %>s %X | %I %O | %<{mod_security-time1}n %<{mod_security-time2}n %<{mod_security-time3}n %D" mperformance

# CustomLog logs/modsec_performance.log mperformance

# Custom application access log.

#

# TODO You should consider creating a custom access log. It could contain

#      the performance metrics from above, but should also record the

#      session ID for every request. That would make it possible to

#      list all requests performed as part of a session.

#

#      One custom log should be used per application but if you want

#      multiple applications to share one log file make sure each

#      line includes a unique application ID (unless the hostname is

#      sufficient for differentiation).

## -- Tuning and debugging

# This section include tuning and debugging directives that usually require no

# modifications unless 

 

# Parameters separator

#

# Specifies which character to use as separator for 

# application/x-www-form-urlencoded content. 

# Defaults to "&". Applications are sometimes (very rarely) written to use 

# a semicolon (";").

#

# NOTE Changing the value for this directive has significant influence on how

#      ModSecurity works. Make the change only if you are absolutely sure it

#      is required.

SecArgumentSeparator "&" 

# Selects the cookie format that will be used in the current configuration 

# context. 

#

# Possible values are:

# 0 - use version 0 (Netscape) cookies. This is what most applications use. 

#     It is the default value.

# 1 - use version 1 cookies.

SecCookieFormat 0

# Maximum size of the request body to keep in memory

# 

# A higher value requires more server memory while a lower number would slow

# the server due to additional disk access. By default the limit is 128 KB:

SecRequestBodyInMemoryLimit 131072

# Whether to send ModSecurity messages to a separate debug log.

#

# Debug messages are very useful for, well, debugging. The default

# setting here copies (they always appear in the Apache error log)

# only the most important messages (errors and warnings).

#

# NOTE Debug logging is generally very slow. You should never

#      use values greater than "3" in production.

#

SecDebugLog             /var/log/apache2/modsec_debug.log

SecDebugLogLevel        3

# Path where persistent data (e.g. IP address data, session data, etc) is to

# be stored. Must be writable by the web server user.

#

# TODO It is advisable to create a directory structure for ModSecurity such as

#      /var/log/msa and create sub directories for SecDataDir, SecTmpDir,

#      SecUploadDir, SecAuditLog and SecAuditLogStorageDir

#      underneath it and set the permission for read and write only by the

#      Apache user.

SecDataDir /tmp

# Configures the directory where temporary files will be created.

SecTmpDir /tmp

# Loades the variable collection relating to the requested resource

# NOTE: We will not initiate a collection if there was an error (To prevent overloading)

SecRule RESPONSE_STATUS "!^(?:30[12]|[45]\d\d)$" "phase:3,pass,nolog,initcol:resource=%{REQUEST_FILENAME}"

```

httpd.conf

```

# This is a modification of the default Apache 2.2 configuration file

# for Gentoo Linux.

#

# Support:

#   http://www.gentoo.org/main/en/lists.xml   [mailing lists]

#   http://forums.gentoo.org/                 [web forums]

#   irc://irc.freenode.net#gentoo-apache      [irc chat]

#

# Bug Reports:

#   http://bugs.gentoo.org                    [gentoo related bugs]

#   http://httpd.apache.org/bug_report.html   [apache httpd related bugs]

#

#

# This is the main Apache HTTP server configuration file.  It contains the

# configuration directives that give the server its instructions.

# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.

# In particular, see

# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>

# for a discussion of each configuration directive.

#

# Do NOT simply read the instructions in here without understanding

# what they do.  They're here only as hints or reminders.  If you are unsure

# consult the online docs. You have been warned.

#

# Configuration and logfile names: If the filenames you specify for many

# of the server's control files begin with "/" (or "drive:/" for Win32), the

# server will use that explicit path.  If the filenames do *not* begin

# with "/", the value of ServerRoot is prepended -- so "var/log/apache2/foo.log"

# with ServerRoot set to "/usr" will be interpreted by the

# server as "/usr/var/log/apache2/foo.log".

# ServerRoot: The top of the directory tree under which the server's

# configuration, error, and log files are kept.

#

# Do not add a slash at the end of the directory path.  If you point

# ServerRoot at a non-local disk, be sure to point the LockFile directive

# at a local disk.  If you wish to share the same ServerRoot for multiple

# httpd daemons, you will need to change at least LockFile and PidFile.

ServerRoot "/usr/lib64/apache2"

# Dynamic Shared Object (DSO) Support

#

# To be able to use the functionality of a module which was built as a DSO you

# have to place corresponding `LoadModule' lines at this location so the

# directives contained in it are actually available _before_ they are used.

# Statically compiled modules (those listed by `httpd -l') do not need

# to be loaded here.

#

# Example:

# LoadModule foo_module modules/mod_foo.so

#

# GENTOO: Automatically defined based on apache2-builtin-mods at compile time

#

# The following modules are considered as the default configuration.

# If you wish to disable one of them, you may have to alter other

# configuration directives.

#

# Change these at your own risk!

LoadModule actions_module modules/mod_actions.so

LoadModule alias_module modules/mod_alias.so

LoadModule auth_basic_module modules/mod_auth_basic.so

<IfDefine AUTH_DIGEST>

LoadModule auth_digest_module modules/mod_auth_digest.so

</IfDefine>

LoadModule authn_anon_module modules/mod_authn_anon.so

LoadModule authn_dbd_module modules/mod_authn_dbd.so

LoadModule authn_dbm_module modules/mod_authn_dbm.so

LoadModule authn_default_module modules/mod_authn_default.so

LoadModule authn_file_module modules/mod_authn_file.so

LoadModule authz_dbm_module modules/mod_authz_dbm.so

LoadModule authz_default_module modules/mod_authz_default.so

LoadModule authz_groupfile_module modules/mod_authz_groupfile.so

LoadModule authz_host_module modules/mod_authz_host.so

LoadModule authz_owner_module modules/mod_authz_owner.so

LoadModule authz_user_module modules/mod_authz_user.so

LoadModule autoindex_module modules/mod_autoindex.so

<IfDefine CACHE>

LoadModule cache_module modules/mod_cache.so

</IfDefine>

LoadModule cgi_module modules/mod_cgi.so

<IfDefine DAV>

LoadModule dav_module modules/mod_dav.so

</IfDefine>

<IfDefine DAV>

LoadModule dav_fs_module modules/mod_dav_fs.so

</IfDefine>

<IfDefine DAV>

LoadModule dav_lock_module modules/mod_dav_lock.so

</IfDefine>

LoadModule dbd_module modules/mod_dbd.so

LoadModule deflate_module modules/mod_deflate.so

LoadModule dir_module modules/mod_dir.so

<IfDefine CACHE>

LoadModule disk_cache_module modules/mod_disk_cache.so

</IfDefine>

LoadModule env_module modules/mod_env.so

LoadModule expires_module modules/mod_expires.so

LoadModule ext_filter_module modules/mod_ext_filter.so

<IfDefine CACHE>

LoadModule file_cache_module modules/mod_file_cache.so

</IfDefine>

LoadModule filter_module modules/mod_filter.so

LoadModule headers_module modules/mod_headers.so

LoadModule ident_module modules/mod_ident.so

LoadModule imagemap_module modules/mod_imagemap.so

LoadModule include_module modules/mod_include.so

<IfDefine INFO>

LoadModule info_module modules/mod_info.so

</IfDefine>

LoadModule log_config_module modules/mod_log_config.so

LoadModule logio_module modules/mod_logio.so

<IfDefine CACHE>

LoadModule mem_cache_module modules/mod_mem_cache.so

</IfDefine>

LoadModule mime_module modules/mod_mime.so

LoadModule mime_magic_module modules/mod_mime_magic.so

LoadModule negotiation_module modules/mod_negotiation.so

<IfDefine PROXY>

LoadModule proxy_module modules/mod_proxy.so

</IfDefine>

<IfDefine PROXY>

LoadModule proxy_ajp_module modules/mod_proxy_ajp.so

</IfDefine>

<IfDefine PROXY>

LoadModule proxy_balancer_module modules/mod_proxy_balancer.so

</IfDefine>

<IfDefine PROXY>

LoadModule proxy_connect_module modules/mod_proxy_connect.so

</IfDefine>

<IfDefine PROXY>

LoadModule proxy_http_module modules/mod_proxy_http.so

</IfDefine>

LoadModule rewrite_module modules/mod_rewrite.so

LoadModule setenvif_module modules/mod_setenvif.so

LoadModule speling_module modules/mod_speling.so

<IfDefine SSL>

LoadModule ssl_module modules/mod_ssl.so

</IfDefine>

<IfDefine INFO>

LoadModule status_module modules/mod_status.so

</IfDefine>

<IfDefine SUEXEC>

LoadModule suexec_module modules/mod_suexec.so

</IfDefine>

LoadModule unique_id_module modules/mod_unique_id.so

<IfDefine USERDIR>

LoadModule userdir_module modules/mod_userdir.so

</IfDefine>

LoadModule usertrack_module modules/mod_usertrack.so

LoadModule vhost_alias_module modules/mod_vhost_alias.so

# If you wish httpd to run as a different user or group, you must run

# httpd as root initially and it will switch.

#

# User/Group: The name (or #number) of the user/group to run httpd as.

# It is usually good practice to create a dedicated user and group for

# running httpd, as with most system services.

User apache

Group apache

# Supplemental configuration

#

# Most of the configuration files in the /etc/apache2/modules.d/ directory can

# be turned on using APACHE2_OPTS in /etc/conf.d/apache2 to add extra features

# or to modify the default configuration of the server.

#

# To know which flag to add to APACHE2_OPTS, look at the first line of the

# the file, which will usually be an <IfDefine OPTION> where OPTIONS is the

# flag to use.

Include /etc/apache2/modules.d/*.conf

# Virtual-host support

#

# Gentoo has made using virtual-hosts easy. In /etc/apache2/vhosts.d/ we

# include a default vhost (enabled by adding -D DEFAULT_VHOST to

# APACHE2_OPTS in /etc/conf.d/apache2).

Include /etc/apache2/vhosts.d/*.conf

# vim: ts=4 filetype=apache

```

```

#Vhost para clientes.invox.es

Listen 80

   <VirtualHost 192.168.0.101:80>

      ServerName   192.168.0.101

      DocumentRoot   "/wwwjail/www/sites/clientes.invox.es/html"

      DirectoryIndex   index.htm, index.php

      ErrorLog   /wwwjail/www/logs/clientes.invox.es_logs/error/error.log

      CustomLog   /wwwjail/www/logs/clientes.invox.es_logs/access/access.log combined

      <Directory "/wwwjail/www/sites/clientes.invox.es/html">

         Options Indexes FollowSymlinks

         AllowOverride All

         Order allow,deny

         Allow from all

      </Directory>

   </VirtualHost>

```

LOG FOR MODSECAUDIT

```

--59771538-A--

[10/Jan/2008:17:11:23 +0100] dhC1ZH8AAAEAACdTA4UAAAAA 192.168.0.100 50148 192.168.0.101 80

--59771538-B--

GET / HTTP/1.1

Host: 192.168.0.101

User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11

Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

Accept-Language: en-us,en;q=0.5

Accept-Encoding: gzip,deflate

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

Keep-Alive: 300

Connection: keep-alive

--59771538-F--

HTTP/1.1 403 Forbidden

Content-Length: 265

Keep-Alive: timeout=15, max=100

Connection: Keep-Alive

Content-Type: text/html; charset=iso-8859-1

--59771538-H--

Apache-Error: [file "mod_authz_host.c"] [line 299] [level 3] client denied by server configuration: /wwwjail

Stopwatch: 1199981483570532 1111 (- - -)

Producer: ModSecurity v2.1.2 (Apache 2.x)

Server: Apache

```

APACHE ERROR.LOG

```

Fri Jan 11 12:42:53 2008] [notice] Apache/2.2.6 (Unix) PHP/5.2.5-pl1-gentoo Apache/2.2.0 (Fedora) configured -- resuming normal operations

[Fri Jan 11 12:55:14 2008] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)

[Fri Jan 11 12:55:15 2008] [error] SecServerSignature: original signature too short. Please set ServerTokens to Full.

[Fri Jan 11 12:55:15 2008] [notice] ModSecurity: chroot checkpoint #1 (pid=7594 ppid=7592)

[Fri Jan 11 12:55:15 2008] [notice] ModSecurity for Apache 2.1.2 configured - Apache

[Fri Jan 11 12:55:16 2008] [error] SecServerSignature: original signature too short. Please set ServerTokens to Full.

[Fri Jan 11 12:55:16 2008] [notice] ModSecurity: chroot checkpoint #2 (pid=7595 ppid=1)

[Fri Jan 11 12:55:16 2008] [notice] ModSecurity: chroot successful, path=/wwwjail

[Fri Jan 11 12:55:16 2008] [warn] pid file /var/run/apache2.pid overwritten -- Unclean shutdown of previous Apache run?

[Fri Jan 11 12:55:16 2008] [notice] Apache/2.2.6 (Unix) PHP/5.2.5-pl1-gentoo Apache/2.2.0 (Fedora) configured -- resuming normal operations

```

CODE FOR ACCESS LOG OF SITE

```

 

[Fri Jan 11 11:55:28 2008] [error] [client 192.168.0.100] client denied by server configuration: /wwwjail

[Fri Jan 11 11:55:29 2008] [error] [client 192.168.0.100] client denied by server configuration: /wwwjail

[Fri Jan 11 11:55:30 2008] [error] [client 192.168.0.100] client denied by server configuration: /wwwjail

[Fri Jan 11 13:02:41 2008] [error] [client 192.168.0.100] client denied by server configuration: /wwwjail

[Fri Jan 11 13:32:54 2008] [error] [client 192.168.0.100] client denied by server configuration: /wwwjail

```

The Jail is at /wwwjail, as I stated in the SecChroot directive. I don't know why it's happening. Thank you very much.

----------

## hanj

I think it's your vhost configuration...

```
DocumentRoot   "/wwwjail/www/sites/clientes.invox.es/html"

      DirectoryIndex   index.htm, index.php

      ErrorLog   /wwwjail/www/logs/clientes.invox.es_logs/error/error.log

      CustomLog   /wwwjail/www/logs/clientes.invox.es_logs/access/access.log combined

      <Directory "/wwwjail/www/sites/clientes.invox.es/html"> 
```

Once in the jail, apache doesn't know it's in a jail, so don't reference the jail portion for DocumentRoot, etc. Maybe try something like this:

```
Listen 80

   <VirtualHost 192.168.0.101:80>

      ServerName   192.168.0.101

      DocumentRoot   "/www/sites/clientes.invox.es/html"

      DirectoryIndex   index.htm, index.php

      ErrorLog   /www/logs/clientes.invox.es_logs/error/error.log

      CustomLog   /www/logs/clientes.invox.es_logs/access/access.log combined

      <Directory "/www/sites/clientes.invox.es/html">

         Options Indexes FollowSymlinks

         AllowOverride All

         Order allow,deny

         Allow from all

      </Directory>

   </VirtualHost> 
```

Also.. these might be useful too:

How to create Chrooted Apache with mod_chroot

Apache/PHP4/Mysql hardening techniques (including chroot)

php's mail() in apache chroot

mod_chroot + cURL and SSL leads to extremely slow performance

hanji

----------

## hanj

Did you get this working?

hanji

----------

## dcreatorx

Hi mate ! Thanks for asking ! The problem is that before you post me the last message ( that was like 2 weeks ago ) I crushed the whole apache tree and even did an update trying to understand what was happening. After that I rode that chrooting apache is not a good option because of the lack of security and the quantity of exploits detected for that system. So I finally decided to use mod_security alone and a good firewall. I know the install was right and I missed just what you said. But it was too late. The best solution is to do gentoo hardened and create a good overall protection for the whole system. Was cool to get the error anyways. Thank you for the response and see you back in some thread.

Cheers.

EDIT: Oh and . . .  I've got that switch at my job. It' s great. I think the electronics and even the IOS copy they sport are from Cisco. Dell is breaking every price out there with more-than-budget hardware.

----------

