ModSecurity uses can help block potential attack attempts from malicious users, but sometimes it can also block legitimate requests.

Note: Using SecRuleEngine Off in your modsecurity configuration, you won’t want to put that in your ModSecurity configuration file. As that completely turns off ModSecurity. The SecRuleRemoveById setting is used instead to only disable one specific rule.

If you are seeing errors in you apache log files for a domain such as:


[Sat Jul 25 16:34:57 2015] [error] [client ??.7.??.??] ModSecurity: Access denied with code 406 (phase 2). Pattern match "(?:\\\\b(?:(?:type\\\\b\\\\W*?\\\\b(?:text\\\\b\\\\W*?\\\\b(?:j(?:ava)?|ecma|vb)|application\\\\b\\\\W*?\\\\bx-(?:java|vb))script|c(?:opyparentfolder|reatetextrange)|get(?:special|parent)folder|iframe\\\\b.{0,100}?\\\\bsrc)\\\\b|on(?:(?:mo(?:use(?:o(?:ver|ut)|down|move|up)|ve)| ..." at REQUEST_FILENAME. [file "/usr/local/apache/conf/modsec2.user.conf"] [line "111"] [id "1234123404"] [msg "Cross-site Scripting (XSS) Attack"] [data ".cookie"][severity "CRITICAL"] [tag "WEB_ATTACK/XSS"] [hostname "domain.com"] [uri "/skin/frontend/base/default/js/cadence/lib/jquery.cookie.js"] [unique_id "VbQdIdg3u9IAAB9DPQkAAAAH"]

Mod _security is doing its job. If this is a valid script, you can make a change and allow it.
Run the following from ssh:

# grep ModSecurity /usr/local/apache/logs/error_log | sed -e 's#^.*\[id "\([0-9]*\).*hostname "\([a-z0-9\-\_\.]*\)"\].*uri "#\1 \2 #' | cut -d\" -f1 | sort -n | uniq -c | sort -n

The results will look like this:

 # 100 1234123404 www.domain.com /skin/frontend/base/default/js/cadence/lib/jquery.cookie.js

ModSecurity rule ID 1234123404 has been triggered at least 100 times when accessing /skin/frontend/base/default/js/cadence/lib/jquery.cookie.js file.

In order to disable just the specific ModSecurity rule for the 1234123404 rule, run the following command:


# echo "SecRuleRemoveById 1234123404" >> /usr/local/apache/conf/userdata/std/2/userna5/domain.com/modsec.conf

You can also search for the rule in WHM/cPanel at Home »Security Center »ModSecurity™ Tools » Rules List

Note the error in the log file – the ID:

# [id "1234123404"]

This is the rule. Search for this at Home »Security Center »ModSecurity™ Tools » Rules List.

rules

You can click disable to allow the script.

disable

Edit the /etc/httpd/conf/httpd.conf file.
Change the ‘UserDir disabled’ line to ‘UserDir enabled ’.
Uncomment the ‘UserDir public_html’ line.
Also uncomment the whole ‘’ section until the ‘’.
Apply the proper permissions:


# chmod 711 ~<username>


# chmod 755 -R ~<username>/public_html/

<IfModule mod_userdir.c>
 #
 # UserDir is disabled by default since it can confirm the presence
 # of a username on the system (depending on home directory
 # permissions).
 #
UserDir enabled unixmenuser

 #
 # To enable requests to /~user/ to serve the user's public_html
 # directory, remove the "UserDir disabled" line above, and uncomment
 # the following line instead:
 #
 UserDir public_html

</IfModule>

<Directory /home/*/public_html>
Options Indexes Includes FollowSymLinks
##For  apache 2.2,Please use:

 AllowOverride All
 Allow from all
 Order deny,allow
#For apache >= 2.4,Please  use :
  Require all granted

</Directory>

The mod_deflate module allows the Apache2 web service to compress files and deliver them to clients (browsers) that can handle them. With mod_deflate you can compress HTML, text or XML files by up to 70% of their original sizes. Thus, saving you server traffic and speeding up page loads.

Compressing files will increase load on your server, but it is a small tradeoff considering your client’s connection times will decrease significantly.

This will not exclude users with older browsers that cannot handle compressed content. The browser negotiates with the server before any file is transferred, and if the browser does not have the capability to handle compressed content, the server delivers the files uncompressed.

mod_deflate has replaced Apache 1.3’s mod_gzip in Apache2.

This article shows how to enable mod_deflate globally across all the domains on your DV server. Should you only wish to enable for a single domain you’d need to add the AddOutputFilterByType and BrowserMatch rules below to the VirtualHost section in your configuration.

For Plesk:

Set server wide configuration file in /etc/httpd/conf.d/

Make sure that mod_deflate is enabled on your server. Your DV server should have it enabled by default. If the following command returns a line with a “#” at the beginning you will have to remove(uncomment) the “#” character using vi or the perl command below:


# grep 'mod_deflate' /etc/httpd/conf/httpd.conf

If the result was LoadModule deflate_module modules/mod_deflate.so, you can continue.

If the result was #LoadModule deflate_module modules/mod_deflate.so, please run the following command:


# perl -pi -e 's/# LoadModule mod_deflate/LoadModule mod_deflate/g' /etc/httpd/conf/httpd.conf

Now that we have verified that mod_deflate is in fact being loaded by Apache, we must configure the module. First, backup your existing conf file in case you need to revert back:


# cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.bak 

Using nano, we will edit our Apache conf file and add the following lines at the very bottom of the file, making sure they are separated from any other configurations:


nano /etc/httpd/conf/httpd.conf

     #
     # Deflate output configuration
     #
     AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css
     BrowserMatch ^Mozilla/4 gzip-only-text/html
     BrowserMatch ^Mozilla/4\.0[678] no-gzip
     BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

Save your file. Now, we need to check that Apache likes our changes using the apachectl command:


# /usr/sbin/apachectl -t

You should see a Syntax OK message. If not, please check your file to make sure you modified the file correctly. Next, we need to restart apache using the same apachectl command:


# /usr/sbin/apachectl graceful

You have now enabled mod_deflate on your DV server! You can see whether the changes are in effect using the following tool at http://whatsmyip.org/mod_gzip_test/.


Options ExecCGI FollowSymLinks IncludesNOEXEC Indexes Limit SymLinksIfOwnerMatch
AllowOverride All

results in an error – Syntax error on line 71 of /usr/local/apache/conf/httpd.conf

Based on my understanding, it first disables FollowSymLinks and enables SymLinksIfOwnerMatch at the httpd.conf level and it applies to all the files and subdirectories present inside, /home.

The next directive, AllowOverride. By writing “All”, it allows all the Directives belonging to FileInfo, AuthConfig, Indexes, Limit to be overriden by .htaccess files.

It explicitly mentions the list of Options that can be overriden by the .htaccess files.

So, it allows SymLinksIfOwnerMatch to be overriden by the .htaccess file.

Is my understanding correct?

Why does it allow SymLinksIfOwnerMatch to be overriden by the .htaccess file if it has explicitly mentioned in the line above that the SymLinksIfOwnerMatch is enabled?

1. Introduction

With the size of the Apache configuration file what it is, it can be easier to find and change a virtual host container (configurations) if the settings are in separate files.

This isn’t strictly recommended by the upstream documentation, but is a common manual extension to make the system more manageable.

All manual extensions to your system should be documented for future reference.

There are several places that virtual host source files can be put. This is a complex topic with several major points of view and is not fully addressed in this document.

2. Usual Practice: conf.d/

The most common location for discrete virtual host configuration files is /etc/httpd/conf.d/. The config files can be named to reflect the website(s) to which they refer, provided they don’t conflict with configuration files of existing or future modules. The matching content can be placed under /var/www/ or /var/www/html/ in sub-directories, such as /var/www/example.com/ or /var/www/html/example.com/.

This has the advantage that the parent directories are already created and SELinux is familiar through rule inheritance, as to how to handle access rights. The packaging system leverages this, of course, by dropping the php.conf file into that configurartion directory such that after a package based install of php, and a restart of the webserver, PHP parsed pages ‘just work’

Though placing a vhost configuration file in a directory full of non-vhost related matter, such as: php.conf and mailman.conf, initially appears an out of order jumble, upon closer reading of the documentation, from Apache HTTP Server Version 2.2 – Configuration Sections, we see that: “Most containers are evaluated for each request.”

So, Apache applies the virtual host directives after all non-vhost related stanzas, regardless of the seeming alphabetical sort order position in the configuration file, or in a merged directory full of such config files, in the matter processed.

This is largely a settled area of Systems Administration, such that the most recent documentation from upstream does not appear to include a ‘System Administration Guide’ in the CentOS 5 series. The System Administration Guide from CentOS 4, Chapter 24. Apache HTTP Server Configuration covers the matter in greater depth.

3. Virtual Host Files

Virtual Host container files can be placed in the configuration directory directly or by link. The name must end with .conf to be included. If using links, make sure to update the SELinux properties of the actual file.

3.1. Example

The file should contain the configuration items specific to this host. An example.conf could be…


# file: /etc/http/conf.d/example.conf
# vhost: example.org *.example.org
<VirtualHost *:80>
  ServerName example.org
  ServerAlias *.example.org
  ServerAdmin webmaster@example.org
  ErrorLog /var/log/httpd/example.err
  CustomLog /var/log/httpd/example.log combined
  DocumentRoot /var/www/example.org
  <Directory "/var/www/example.org">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Of course, a virtual host configuration file may refer to more than one URL or DNS result as a single file tree.


[userid@webhost conf.d]$ cat example.conf 
### two domain vhost sites handled here:  
###       example.com and example.org
###
### the .COM
<VirtualHost x.x.x.x >
        ServerAdmin     webmaster@example.com
        DocumentRoot    /var/www/html/example.com/public_html/
        ServerName      example.com
        ServerAlias     www.example.com
        ErrorLog        logs/example.com-error_log
        TransferLog     logs/example.com-access_log
        AccessFileName .htaccess
</VirtualHost>

### the .ORG
<VirtualHost x.x.x.x >
        ServerAdmin     webmaster@example.org
        DocumentRoot    /var/www/html/example.org/public_html/
        ServerName      example.org
        ServerAlias     www.example.org
        ErrorLog        logs/example.org-error_log
        TransferLog     logs/example.org-access_log
        AccessFileName .htaccess
</VirtualHost>

This file sets up the two domains, one the .com and the other the .org. As to each, it would provide the same content at the bare domain name, and also at the www when used either way in a URL for a web browser, which is usually the desired result, but of course possibly differing content between the two TLD variations as the content down the file tree specified.

4. Virtual Host Inclusion

There might be times when it is desirable to disable a virtual host. Since the include in /etc/httpd/conf/httpd.conf specifies *.conf, it is possible to hide a virtual host by changing the configuration file name.

4.1. Disable Virtual Host

Virtual hosts can be disabled by renaming the file so it doesn’t match the *.conf file specification. Adding a disabled extension is one way.


# mv --verbose /etc/httpd/conf.d/example.conf /etc/httpd/conf.d/example.conf.disabled

If less typing is desired, it can be shortened:


# mv -v /etc/httpd/conf.d/example.conf{,_}

4.2. Enable Virtual Host

Virtual hosts can be re-enabled by removing the extra.

To remove the disabled flag:


# mv --verbose /etc/httpd/conf.d/example.conf.disabled /etc/httpd/conf.d/example.conf

For the shorter version:


# mv -v /etc/httpd/conf.d/example.conf{_,}

Enabling or disabling a virtual host using this method will not take effect until the web server is restarted.

5. Restart Apache

To make your changes take effect, restart Apache. Using the graceful option ensures that existing processes are allowed to finish serving the current page, reducing the chance of disrupting a user’s browsing experience.


# service httpd graceful

Apache fails to restart on plesk server on CentOS 6.5

# service httpd restart
Stopping httpd:                                            [FAILED]
Starting httpd: Syntax error on line 55 of /etc/httpd/conf/plesk.conf.d/ip_defalt/domain.com.conf:
SSLCertificateFile: file '/usr/local/psa/var/certificates/cert-6xg952' does notexist or is empty

Solution:

# /usr/local/psa/admin/sbin/httpdmng --reconfigure-all
# service httpd restart

HTTP Strict Transport Security (HSTS) is an opt-in browser security mechanism that lets web site owners declare “Encrypted Communications Only”.

Strict-Transport-Security HTTP header instructs browsers to only communicate with the domain over SSL/TLS for a set period of time (the max-age). HSTS only goes into effect after a browser receives a valid header from the domain. HSTS is to ensure unencrypted communication is not allowed on your domain or site to mitigate attacks such as SSL-stripping.

The HSTS Header


Strict-Transport-Security: max-age:31536000; includeSubDomains 

The max-age parameter value is in seconds; 31536000 seconds equals 365 days. Notice how the above also uses includeSubDomains. This optional parameter informs the browser to force secure communication to the site’s subdomains as well.

Browsers must receive the Strict-Transport-Security header over an HTTPS connection with the domain; HSTS headers over HTTP are not recognized as valid.

Threat Mitigation
HSTS mitigates the following threats.

1. HTTP request to an HTTPS site
For example:
1. User wants to visit SecureSite.com
2. User types SecureSite.com into the address bar
3. Browser automatically appends “http://” making the following request: http://SecureSite.com
4. Server responds with 301 (permanent redirect) to the following location: https://SecureSite.com
5. Browser makes request to above URL

The above scenario allows for a man-in-the-middle attack as a result of the unintentional HTTP request to SecureSite.com. An attacker can leverage a tool such as ssltrip to transparently hijack the HTTP request prior to the 301 redirect. HSTS eliminates this attack window as long as the user previously accessed SecureSite.com over HTTPS and obtained the HSTS header.

Even with HSTS enabled, a user’s initial request to SecureSite.com would remain unprotected from attacks. As a result, both Chrome and Mozilla introduced HSTS preload lists. If SecureSite.com is on Chrome’s HSTS preload list, a freshly installed Chrome browser will only allow secure connections to that site, even if the user never accessed it before.

2. Insecure link referencing an HSTS enabled site

For example:

1. Forum.com includes a link to http://SecureSite.com
2. HSTS will automatically convert the link to HTTPS for the HSTS-enabled site
3. Invalid Certificate
The following would be considered invalid certificates:
– Self-signed and/or untrusted CA signed certificate
– Expired
– Wrong name specified
– …

HSTS displays an error message as shown below. In addition, it will NOT allow the user to override the error message, thus preventing a potential attack by ensuring the victim does not accept the bad certificate.

Enabling HSTS
You can enable HSTS in Apache with mod headers and the following line in your configuration:


<IfModule mod_headers.c>
# this domain should only be contacted in HTTPS for the next 6 months
Header add Strict-Transport-Security "max-age=15768000"
</IfModule> 

Afterwards, restart Apache and test the configuration change:


# curl -si nvisium.com | grep ^Strict
Strict-Transport-Security: max-age=31536000 

In Nginx, update nginx.conf:


# add_header Strict-Transport-Security "max-age=31536000; includeSubDomains"; 

In Rails, HSTS can be enabled with the following:


# config.force_ssl = true 

HSTS Preload Lists
Chrome
Code repository:
https://src.chromium.org/viewvc/chrome/trunk/src/net/http/transport_security_state_static.json

Add your site using using the following:
https://hstspreload.appspot.com

Firefox
Code repository:
http://dxr.mozilla.org/mozillacentral/source/security/manager/boot/src/nsSTSPreloadList.inc

Firefox does not maintain their own list; instead, they use a subset of Google’s. Firefox only accepts sites on Google’s preload list that have a max-age greater than or equal to 18 weeks (10886400 seconds). See https://blog.mozilla.org/security/2012/11/01/preloading-hsts/ for more information.

Testing HSTS
– Leverage an intercepting proxy (e.g. Burp) or browser tools (e.g. Chrome DevTools / Firefox Developer Tools) to examine server responses

– In Chrome, type the below to determine if a host is in your STS cache
chrome://net-internals/#hsts

– In Firefox, you can use the Strict Transport Security Detector add-on to see if the site supports HSTS (https://addons.mozilla.org/en-US/firefox/addon/strict-transport-security-d/)

Source: http://blog.nvisium.com/2014/04/is-your-site-hsts-enabled.html