The Web Server is a crucial part of web-based applications. Having misconfigured and the default configuration can expose sensitive information, and that’s a risk.
As a website owner or administrator, you should regularly perform security scans against your website to find for online threats so you can take action before a hacker does.
Let’s go through essential configurations to keep your Apache webserver.
Following all configuration is in httpd.conf
of your apache instance.
Note: take a backup of the necessary configuration file before modification, so restoration is easy when things go wrong.
The Web Server is a crucial part of web-based applications. Apache Web Server is often placed at the edge of the network hence it becomes one of the most vulnerable services to attack.
Having default configuration supply much sensitive information which may help hacker to prepare for an attack the applications. The majority of web application attacks are through XSS, Info Leakage, Session Management and SQL Injection attacks which are due to weak programming code and failure to sanitize web application infrastructure.
Interesting research by Positive Technologies reveals, 52% of the scanned application had high vulnerabilities.
In this article, I will talk about some of the best practices to secure Apache HTTP server on Linux platform.
Following are tested on Apache 2.4.x version.
This is designed for Middleware Administrator, Application Support, System Analyst, or anyone working or eager to learn Hardening & Security guidelines.
Fair knowledge of Apache Web Server & UNIX command is mandatory.
Notes
You require some tool to examine HTTP Headers for some of the implementation verification. There are two ways to do this.
I would say this is one of the first things to consider, as you don’t want to expose what web server version you are using. Exposing version means you are helping hacker to speedy the reconnaissance process.
The default configuration will expose Apache Version and OS type as shown below.
ServerTokens Prod
ServerSignature Off
ServerSignature
will remove the version information from the page generated by Apache.
ServerTokens
will change Header to production only, i.e., Apache
As you can see below, version & OS information is gone.
Disable directory listing in a browser, so the visitor doesn’t see what all file and folders you have under root or subdirectory.
Let’s test how does it look like in default settings.
# mkdir test
# touch hi
# touch hello
Now, let’s try to access Apache by http://localhost/test
As you could see it reveals what all file/folders you have and I am sure you don’t want to expose that.
httpd.conf
using vi<Directory /opt/apache/htdocs>
Options -Indexes
</Directory>
(or)
<Directory /opt/apache/htdocs>
Options None
</Directory>
Note: if you have multiple Directory directives in your environment, you should consider doing the same for all.
Now, let’s try to access Apache by http://localhost/test
As you could see, it displays a forbidden error instead of showing test folder listing.
It allows remote attackers to obtain sensitive information like inode number, multipart MIME boundary, and child process through Etag header.
To prevent this vulnerability, let’s implement it as below. This is required to fix for PCI compliance.
FileETag None
A default installation runs as nobody or daemon. Using a separate non-privileged user for Apache is good.
The idea here is to protect other services running in case of any security hole.
# groupadd apache
# useradd –G apache apache
# chown –R apache:apache /opt/apache
User apache
Group apache
grep for running http process and ensure it’s running with apache user
# ps –ef |grep http
You should see one process is running with root. That’s because Apache is listening on port 80 and it has to be started with root.
By default, permission for binary and configuration is 755 that means any user on a server can view the configuration. You can disallow another user to get into conf and bin folder.
# chmod –R 750 bin conf
In a default installation, users can override apache configuration using .htaccess. If you want to stop users from changing your apache server settings, you can add AllowOverride
to None
as shown below.
This must be done at the root level.
<Directory />
Options -Indexes
AllowOverride None
</Directory>
HTTP 1.1 protocol support many request methods which may not be required and some of them are having potential risk.
Typically you may need GET, HEAD, POST request methods in a web application, which can be configured in the respective Directory directive.
Default configuration support OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT method in HTTP 1.1 protocol.
<LimitExcept GET POST HEAD>
deny from all
</LimitExcept>
By default Trace method is enabled in Apache web server.
Having this enabled can allow Cross Site Tracing attack and potentially giving an option to a hacker to steal cookie information. Let’s see how it looks like in default configuration.
#telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
TRACE / HTTP/1.1 Host: test
HTTP/1.1 200 OK
Date: Sat, 31 Aug 2013 02:13:24 GMT
Server: Apache
Transfer-Encoding: chunked
Content-Type: message/http 20
TRACE / HTTP/1.1
Host: test
0
Connection closed by foreign host.
#
As you could see in above TRACE request, it has responded my query. Let’s disable it and test it.
TraceEnable off
Do a telnet web server IP with listen port and make a TRACE
request as shown below
#telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
TRACE / HTTP/1.1 Host: test
HTTP/1.1 405 Method Not Allowed
Date: Sat, 31 Aug 2013 02:18:27 GMT
Server: Apache Allow:Content-Length: 223Content-Type: text/html; charset=iso-8859-1 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head>
<title>405 Method Not Allowed</title> </head><body>
<h1>Method Not Allowed</h1>
<p>The requested method TRACE is not allowed for the URL /.</p> </body></html>
Connection closed by foreign host.
#
As you could see in above TRACE request, it has blocked my request with HTTP 405 Method Not Allowed.
Now, this web server doesn’t allow TRACE request and help in blocking Cross Site Tracing attack.
You can mitigate most of the common Cross Site Scripting attack using HttpOnly and Secure flag in a cookie. Without having HttpOnly and Secure, it is possible to steal or manipulate web application session and cookies, and it’s dangerous.
Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
Clickjacking is a well-known web application vulnerabilities.
Header always append X-Frame-Options SAMEORIGIN
X-Frame-Options also support two more options which I explained here.
Server Side Include (SSI) has a risk of increasing the load on the server. If you have shared the environment and heavy traffic web applications you should consider disabling SSI by adding Includes in Options directive.
SSI attack allows the exploitation of a web application by injecting scripts in HTML pages or executing codes remotely.
<Directory /opt/apache/htdocs>
Options –Indexes -Includes
Order allow,denyAllow from all
</Directory>
Note: if you have multiple Directory directives in your environment, you should consider doing the same for all.
Cross Site Scripting (XSS) protection can be bypassed in many browsers. You could apply this protection for a web application if it was disabled by the user. This is used by a majority of giant web companies like Facebook, Twitter, Google, etc.
Header set X-XSS-Protection "1; mode=block"
As you can see, XSS-Protection is the injected in the response header.
When we talk about security, we should protect as much we can. So why do we use older HTTP version of the protocol, let’s disable them as well?
HTTP 1.0 has security weakness related to session hijacking. We can disable this by using the mod_rewrite module.
RewriteEngine On
RewriteCond %{THE_REQUEST} !HTTP/1.1$
RewriteRule .* - [F]
By default, Apache time-out value is 300 seconds, which can be a victim of Slow Loris attack and DoS. To mitigate this, you can lower the timeout value to maybe 60 seconds.
Timeout 60
Having SSL is an additional layer of security you are adding into Web Application. However, default SSL configuration leads to certain vulnerabilities, and you should consider tweaking those configurations.
Breaching SSL key is hard, but not impossible. It’s just a matter of computational power and time.
As you might know, using a 2009-era PC cracking away for around 73 days you can reverse engineer a 512-bit key.
So the higher key length you have, the more complicated it becomes to break SSL key. The majority of giant Web Companies use 2048 bit key, as below so why don’t we?
You can use OpenSSL to generate CSR with 2048 bit as below.
openssl req -out geekflare.csr -newkey rsa:2048 -nodes -keyout geekflare.key
It will generate a CSR which you will need to send to a certificate authority to sign it. Once you receive the signed certificate file, you can add them in httpd-ssl.conf file
SSLCertificateFile #Certificate signed by authority
SSLCertificateChainFile #Certificate signer given by authority
SSLCertificateKeyFile #Key file which you generated above
SSL Cipher is an encryption algorithm, which is used as a key between two computers over the Internet. Data encryption is the process of converting plain text into secret ciphered codes.
It’s based on your web server SSL Cipher configuration the data encryption will take place. So it’s important to configure SSL Cipher, which is stronger and not vulnerable.
SSLCipherSuite HIGH:!MEDIUM:!aNULL:!MD5:!RC4
Note: if you have many weak ciphers in your SSL auditing report, you can quickly reject them adding ! at the beginning.
SSL v2 & v3 has many security flaws, and if you are working towards penetration test or PCI compliance, then you are expected to close security finding to disable SSL v2/v3.
Any SSL v2/v3 communication may be vulnerable to a Man-in-The-Middle attack that could allow data tampering or disclosure.
Let’s implement apache web server to accept only latest TLS and reject SSL v2/v3 connection request.
SSLProtocol –ALL +TLSv1.2
Once you are done with SSL configuration, it’s a good idea to test your web application with online SSL/TLS Certificate tool to find any configuration error.
Mod Security is an open-source Web Application Firewall, which you can use with Apache.
It comes as a module which you have to compile and install. If you can’t afford a commercial web application firewall, this would be an excellent choice to go for it.
To provide generic web applications protection, the Core Rules use the following techniques:
Following prerequisites must be installed on the server where you wish to use Mod Security with Apache. If any one of these doesn’t exist then Mod Security compilation will fail. You may use yum install on Linux or Centos to install these packages.
Now, let’s download the latest stable version of Mod Security 2.7.5 from here
# gunzip –c modsecurity-apache_2.7.5.tar.gz | tar xvf –
# cd modsecurity-apache_2.7.5
# ./configure –with-apxs=/opt/apache/bin/apxs
# make
# make install
Now this concludes, you have installed Mod Security module in existing Apache web server.
To use Mod security feature with Apache, we have to load mod security module in httpd.conf. The mod_unique_id module is pre-requisite for Mod Security.
This module provides an environment variable with a unique identifier for each request, which is tracked and used by Mod Security.
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule security2_module modules/mod_security2.so
Mod Security is now installed!
Next thing you have to do is to install Mod Security core rule to take full advantage of its feature.
Latest Core Rule can be downloaded from following a link, which is free. https://github.com/SpiderLabs/owasp-modsecurity-crs/zipball/master
Now, let’s enable these rules to get it working with Apache web server.
<IfModule security2_module>
Include conf/crs/modsecurity_crs_10_setup.confInclude conf/crs/base_rules/*.conf
</IfModule>
In the above configuration, we are loading Mod Security main configuration file modsecurity_crs_10_setup.conf and base rules base_rules/*.conf provided by Mod Security Core Rules to protect web applications.
You have successfully configured Mod Security with Apache!
Well done. Now, Apache Web server is protected by Mod Security web application firewall.
Let’s get it started with some of the critical configurations in Mod Security to harden & secure web applications.
In this section, we will do all configuration modification in /opt/apache/conf/crs/modsecurity_crs_10_setup.conf.
We will refer /opt/apache/conf/crs/modsecurity_crs_10_setup.conf as setup.conf in this section for example purpose.
It’s important to understand what are the OWASP rules are provided for free. There are two types of rules provided by OWASP.
Base Rules – these rules are heavily tested, and probably false alarm ratio is less.
Experimental Rules – these rules are for an experimental purpose, and you may have a high false alarm. It’s important to configure, test and implement in UAT before using these in a production environment.
Optional Rules – these optional rules may not be suitable for the entire environment. Based on your requirement you may use them.
If you are looking for CSRF, User tracking, Session hijacking, etc. protection, then you may consider using optional rules. We have the base, optional and experimental rules after extracting the downloaded crs zip file from OWASP download page.
These rules configuration file is available in crs/base_rules, crs/optional_rules and crs/experimental_rules folder. Let’s get familiar with some of the base rules.
Logging is one of the first things to configure so you can have logs created for what Mod Security is doing. There are two types of logging available; Debug & Audit log.
Debug Log: this is to duplicate the Apache error, warning and notice messages from the error log.
Audit Log: this is to write the transaction logs that are marked by Mod Security rule Mod Security gives you the flexibility to configure Audit, Debug or both logging.
By default configuration will write both logs. However, you can change based on your requirement. The log is controlled in SecDefaultAction
directive. Let’s look at default logging configuration in setup.conf
SecDefaultAction “phase:1,deny,log”
To log Debug, Audit log – use “log” To log only audit log – use “nolog,auditlog” To log only debug log – use “log,noauditlog” You can specify the Audit Log location to be stored which is controlled by SecAuditLog directive.
Let’s write audit log into /opt/apache/logs/modsec_audit.log by adding as shown below.
SecAuditLog /opt/apache/logs/modsec_audit.log
By default Engine Rule is Off that means if you don’t enable Rule Engine you are not utilizing all the advantages of Mod Security.
Rule Engine enabling or disabling is controlled by SecRuleEngine
directive.
SecRuleEngine On
There are three values for SecRuleEngine:
Once Rule Engine is on – Mod Security is ready to protect with some of the common attack types.
Now web server is ready to protect with common attack types like XSS, SQL Injection, Protocol Violation, etc. as we have installed Core Rule and turned on Rule Engine. Let’s test a few of them.
XSS Attack
You will notice Mod Security blocks request as it contains <script> tag which is the root of XSS attack.
Directory Traversal Attack:- Directory traversal attacks can create a lot of damage by taking advantage of this vulnerabilities and access system related file. Ex – /etc/passwd, .htaccess, etc.
http://localhost/?../.../boot
Earlier in this guide, you learned how to remove Apache and OS type, version help of ServerTokens directive.
Let’s go one step ahead, how about keeping server name whatever you wish? It’s possible with SecServerSignature
directive in Mod Security. You see it’s interesting.
Note: to use Mod Security to manipulate Server Banner from a header, you must set ServerTokesn to Full in httpd.conf of Apache web server.
SecServerSignature YourServerName
Ex:
[/opt/apache/conf/crs] #grep SecServer modsecurity_crs_10_setup.conf
SecServerSignature geekflare.com
[/opt/apache/conf/crs] #
Let’s check out some of the general configurations as best practice.
When you have multiple interfaces and IP’s on a single server, it’s recommended to have Listen directive configured with absolute IP and Port number.
When you leave apache configuration to Listen on all IP’s with some port number, it may create the problem in forwarding HTTP request to some other web server. This is quite common in the shared environment.
Listen 10.10.10.1:80
It’s essential to configure access log properly in your web server. Some of the important parameter to capture in the log would be the time taken to serve the request, SESSION ID.
By default, Apache is not configured to capture these data. You got to configure them manually as follows.
LogFormat "%h %l %u %t "%{sessionID}C" "%r" %>s %b %T" common
You can refer http://httpd.apache.org/docs/2.2/mod/mod_log_config.html for a complete list of parameter supported in LogFormat directive in Apache Web Server.
If you have compiled and installed with all modules, then there are high chances you will have many modules loaded in Apache, which may not be required.
Best practice is to configure Apache with required modules in your web applications. Following modules have security concerns, and you might be interested in disabling in httpd.conf of Apache Web Server.
WebDAV (Web-based Distributed Authoring and Versioning) This module allows remote clients to manipulate files on the server and subject to various denial-of-service attacks. To disable comment following in httpd.conf
#LoadModule dav_module modules/mod_dav.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
#Include conf/extra/httpd-dav.conf
Info Module The mod_info module can leak sensitive information using .htaccess once this module is loaded. To disable comment following in httpd.conf
#LoadModule info_module modules/mod_info.so