Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Apache Security

News

Apache

Recommended Links

Books

Web Server Security

Tutorials and Sample Chapters

mod rewrite mod_security Apache .htaccess file Using deny directive in apache .htaccess HTTP Protocol HTTP Return Codes
Blocking referrer Spam   Requests for non-existing web pages PHP probes HTTP Servers Log Analyses Humor Etc

The main danger with Apache comes from scripts, especially PHP scripts, but server configuration plays important role

Among prudent measures are (see  NSA Secure Configuration of the Apache Web Server, Apache Server Version 1.3.3 on Red Hat Linux 5.1 ):

Apache lets you restrict access to your site based on IP addresses or hostnames. This is done through allow  and deny directives in httpd.conf.  This prevents the use of .htaccess  files in all directories apart from those specifically enabled.

Suppose you don't want anyone who does not have a DNS entry in your company DNS to access the directory /private  You would add these lines to httpd.conf:

<Location /private>
    SetHandler private
    Order deny, allow
    Deny from all
    Allow from mycompany.com
</Location>
In this example we deny everyone, unless the request originates from a host belonging to the domain mycompany.com.  Generally restrictions can be specified in six ways:

Apache Basic Authentication is the most common authentication method used: when someone attempts to access a protected page, Apache asks for a username and a password. It then verifies the username and password and if successful, Apache serves the request. Basic Authentication is implemented with the mod_auth  module; make sure this module is installed. The main deficiency is that the Basic Authentication does not encrypt the password when you type it in and thus you need to select a separate password so that the interception of  the Web password does not lead to compromise of your other accounts.  Basic Authentication requires creation of  a plain-text list of usernames and passwords using htpasswd2, a script included with the Apache2 package.  You should store these passwords away from your main Apache installation directory, for example /etc/httpd/passwd 

Apache Digest Authentication is more secure as it is using SSL/TSL.

To create a new hidden password file, with the first user use:

./htpasswd -c /etc/httpd/.htpasswd joeuser

You'll be prompted twice for this user's password. To add new users to this file, use the same command without the -c  switch (that creates a new file), for example:

./htpasswd /etc/httpd/.htpasswd webuser

You also need to configure Apache to refer to .htpasswd  when serving a protected page iether in httpd.conf or by creating a special dot file (.htaccess) in each protected directory:

Often it is better to use weaker protection based on username only . In this case you can create a group of users with the same level of access, create a group file named .htgroup  in any text editor with the Group Name and a list of users. Save it in the same directory as .htpasswd. The entry in .htgroup  file should look like this:

Members: joeuser,webuser

The concept of the two files are similar to Linux's /etc/passwd  and /etc/group  files; .htpasswd  stores each username and password hash, and .htgroup  aggregates usernames into logical groups. Each group member needs to have a password listed in .htpasswd  before access is allowed.

Now edit your .htaccess  file so that your group has access.

AuthType Basic
AuthName "Members Only"
AuthUserFile /etc/httpd/.htpasswd
AuthGroupFile /etc/httpd/.htgroups
Require group Members

Everyone in the Members group would now have access to all pages with the "Members Only" realm.

Note: You can create as many groups as you want in your .htgroups  file. Each entry is a single line listing all its members together, separated only by a space.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Oct 03, 2014] Everything you need to know about the Shellshock Bash bug

September 25, 2014 | troyhunt.com
Remember Heartbleed? If you believe the hype today, Shellshock is in that league and with an equally awesome name albeit bereft of a cool logo (someone in the marketing department of these vulns needs to get on that). But in all seriousness, it does have the potential to be a biggie and as I did with Heartbleed, I wanted to put together something definitive both for me to get to grips with the situation and for others to dissect the hype from the true underlying risk.

To set the scene, let me share some content from Robert Graham's blog post who has been doing some excellent analysis on this. Imagine an HTTP request like this:

target = 0.0.0.0/0
port = 80
banners = true
http-user-agent = shellshock-scan (http://blog.erratasec.com/2014/09/bash-shellshock-scan-of-internet.html)
http-header = Cookie:() { :; }; ping -c 3 209.126.230.74
http-header = Host:() { :; }; ping -c 3 209.126.230.74
http-header = Referer:() { :; }; ping -c 3 209.126.230.74

Which, when issued against a range of vulnerable IP addresses, results in this:

[Oct 03, 2014] Shellshock (software bug)

en.wikipedia.org

Analysis of the source code history of Bash shows that the vulnerabilities had existed undiscovered since approximately version 1.13 in 1992.[4] The maintainers of the Bash source code have difficulty pinpointing the time of introduction due to the lack of comprehensive changelogs.[1]

In Unix-based operating systems, and in other operating systems that Bash supports, each running program has its own list of name/value pairs called environment variables. When one program starts another program, it provides an initial list of environment variables for the new program.[14] Separately from these, Bash also maintains an internal list of functions, which are named scripts that can be executed from within the program.[15] Since Bash operates both as a command interpreter and as a command, it is possible to execute Bash from within itself. When this happens, the original instance can export environment variables and function definitions into the new instance.[16] Function definitions are exported by encoding them within the environment variable list as variables whose values begin with parentheses ("()") followed by a function definition. The new instance of Bash, upon starting, scans its environment variable list for values in this format and converts them back into internal functions. It performs this conversion by creating a fragment of code from the value and executing it, thereby creating the function "on-the-fly", but affected versions do not verify that the fragment is a valid function definition.[17] Therefore, given the opportunity to execute Bash with a chosen value in its environment variable list, an attacker can execute arbitrary commands or exploit other bugs that may exist in Bash's command interpreter.

The name "shellshock" is attributed[by whom?][not in citation given] to Andreas Lindh from a tweet on 24 September 2014.[18][non-primary source needed]

On October 1st, Zalewski released details of the final bugs, and confirmed that Florian's patch does indeed prevent them. Zalewski says fixed

CGI-based web server attack

When a web server uses the Common Gateway Interface (CGI) to handle a document request, it passes various details of the request to a handler program in the environment variable list. For example, the variable HTTP_USER_AGENT has a value that, in normal usage, identifies the program sending the request. If the request handler is a Bash script, or if it executes one for example using the system(3) call, Bash will receive the environment variables passed by the server and will process them as described above. This provides a means for an attacker to trigger the Shellshock vulnerability with a specially crafted server request.[4] The security documentation for the widely used Apache web server states: "CGI scripts can ... be extremely dangerous if they are not carefully checked."[20] and other methods of handling web server requests are often used. There are a number of online services which attempt to test the vulnerability against web servers exposed to the Internet.[citation needed]

SSH server example

OpenSSH has a "ForceCommand" feature, where a fixed command is executed when the user logs in, instead of just running an unrestricted command shell. The fixed command is executed even if the user specified that another command should be run; in that case the original command is put into the environment variable "SSH_ORIGINAL_COMMAND". When the forced command is run in a Bash shell (if the user's shell is set to Bash), the Bash shell will parse the SSH_ORIGINAL_COMMAND environment variable on start-up, and run the commands embedded in it. The user has used their restricted shell access to gain unrestricted shell access, using the Shellshock bug.[21]

DHCP example

Some DHCP clients can also pass commands to Bash; a vulnerable system could be attacked when connecting to an open Wi-Fi network. A DHCP client typically requests and gets an IP address from a DHCP server, but it can also be provided a series of additional options. A malicious DHCP server could provide, in one of these options, a string crafted to execute code on a vulnerable workstation or laptop.[9]

Note of offline system vulnerability

The bug can potentially affect machines that are not directly connected to the Internet when performing offline processing, which involves the use of Bash.[citation needed]

Initial report (CVE-2014-6271)

This original form of the vulnerability involves a specially crafted environment variable containing an exported function definition, followed by arbitrary commands. Bash incorrectly executes the trailing commands when it imports the function.[22] The vulnerability can be tested with the following command:

env x='() { :;}; echo vulnerable' bash -c "echo this is a test"

In systems affected by the vulnerability, the above commands will display the word "vulnerable" as a result of Bash executing the command "echo vulnerable", which was embedded into the specially crafted environment variable named "x".[23][24]

There was an initial report of the bug made to the maintainers of Bash (Report# CVE-2014-6271). The bug was corrected with a patch to the program. However, after the release of the patch there were subsequent reports of different, yet related vulnerabilities. On 26 September 2014, two open-source contributors, David A. Wheeler and Norihiro Tanaka, noted that there were additional issues, even after patching systems using the most recently available patches. In an email addressed to the oss-sec list and the bash bug list, Wheeler wrote: "This patch just continues the 'whack-a-mole' job of fixing parsing errors that began with the first patch. Bash's parser is certain [to] have many many many other vulnerabilities".[25]
On 27 September 2014, Michal Zalewski announced his discovery of several other Bash vulnerabilities,[26] one based upon the fact that Bash is typically compiled without address space layout randomization.[27] Zalewski also strongly encouraged all concerned to immediately apply a patch made available by Florian Weimer.[26][27]

CVE-2014-6277

CVE-2014-6277 relates to the parsing of function definitions in environment variables by Bash. It was discovered by Michał Zalewski.[26][27][28][29]

This causes a segfault.

() { x() { _; }; x() { _; } <<a; }

CVE-2014-6278

CVE-2014-6278 relates to the parsing of function definitions in environment variables by Bash. It was discovered by Michał Zalewski.[30][29]


() { _; } >_[$($())] { echo hi mom; id; }

CVE-2014-7169

On the same day the bug was published, Tavis Ormandy discovered a related bug which was assigned the CVE identifier CVE-2014-7169.[21] Official and distributed patches for this began releasing on 26 September 2014.[citation needed] Demonstrated in the following code:

env X='() { (a)=>\' sh -c "echo date"; cat echo

which would trigger a bug in Bash to execute the command "date" unintentionally. This would become CVE-2014-7169.[21]

Testing example

Here is an example of a system that has a patch for CVE-2014-6271 but not CVE-2014-7169:

$ X='() { (a)=>\' bash -c "echo date"
bash: X: line 1: syntax error near unexpected token `='
bash: X: line 1: `'
bash: error importing function definition for `X'
$ cat echo
Fri Sep 26 01:37:16 UTC 2014

The patched system displays the same error, notifying the user that CVE-2014-6271 has been prevented. However, the attack causes the writing of a file named 'echo', into the working directory, containing the result of the 'date' call. The existence of this issue resulted in the creation of CVE-2014-7169 and the release patches for several systems.

A system patched for both CVE-2014-6271 and CVE-2014-7169 will simply echo the word "date" and the file "echo" will not be created.

$ X='() { (a)=>\' bash -c "echo date"
date
$ cat echo
cat: echo: No such file or directory

CVE-2014-7186

CVE-2014-7186 relates to an out-of-bounds memory access error in the Bash parser code.[31] While working on patching Shellshock, Red Hat researcher Florian Weimer found this bug.[23]

Testing example

Here is an example of the vulnerability, which leverages the use of multiple "<<EOF" declarations:

bash -c 'true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF' ||
echo "CVE-2014-7186 vulnerable, redir_stack"
A vulnerable system will echo the text "CVE-2014-7186 vulnerable, redir_stack".

CVE-2014-7187

CVE-2014-7187 relates to an off-by-one error, allowing out-of-bounds memory access, in the Bash parser code.[32] While working on patching Shellshock, Red Hat researcher Florian Weimer found this bug.[23]

Testing example

Here is an example of the vulnerability, which leverages the use of multiple "done" declarations:

(for x in {1..200} ; do echo "for x$x in ; do :"; done; for x in {1..200} ; do echo done ; done) | bash ||
echo "CVE-2014-7187 vulnerable, word_lineno"
A vulnerable system will echo the text "CVE-2014-7187 vulnerable, word_lineno".

[Sep 29, 2014] Shellshock: How to protect your Unix, Linux and Mac servers By Steven J. Vaughan-Nichols

Fortunately, all the major Linux vendors quickly issued patches, including Debian, Ubuntu, Suse and Red Hat.
zdnet.com

The only thing you have to fear with Shellshock, the Unix/Linux Bash security hole, is fear itself. Yes, Shellshock can serve as a highway for worms and malware to hit your Unix, Linux, and Mac servers, but you can defend against it.

The real and present danger is for servers. According to the National Institute of Standards (NIST), Shellshock scores a perfect 10 for potential impact and exploitability. Red Hat reports that the most common attack vectors are:

So much for Red Hat's thoughts. Of these, the Web servers and SSH are the ones that worry me the most. The DHCP client is also troublesome, especially if, as it the case with small businesses, your external router doubles as your Internet gateway and DHCP server.

Of these, Web server attacks seem to be the most common by far. As Florian Weimer, a Red Hat security engineer, wrote: "HTTP requests to CGI scripts have been identified as the major attack vector." Attacks are being made against systems running both Linux and Mac OS X.

Jaime Blasco, labs director at AlienVault, a security management services company, ran a honeypot looking for attackers and found "several machines trying to exploit the Bash vulnerability. The majority of them are only probing to check if systems are vulnerable. On the other hand, we found two worms that are actively exploiting the vulnerability and installing a piece of malware on the system."

Other security researchers have found that the malware is the usual sort. They typically try to plant distributed denial of service (DDoS) IRC bots and attempt to guess system logins and passwords using a list of poor passwords such as 'root', 'admin', 'user', 'login', and '123456.'

So, how do you know if your servers can be attacked? First, you need to check to see if you're running a vulnerable version of Bash. To do that, run the following command from a Bash shell:

env x='() { :;}; echo vulnerable' bash -c "echo this is a test"

If you get the result:

vulnerable this is a test

Bad news, your version of Bash can be hacked. If you see:

bash: warning: x: ignoring function definition attempt bash: error importing function definition for `x' this is a test

You're good. Well, to be more exact, you're as protected as you can be at the moment.

Frequently Asked Questions about the Shellshock Bash flaws

Sep 26, 2014 | securityblog.redhat.com

Why are there four CVE assignments?

The original flaw in Bash was assigned CVE-2014-6271. Shortly after that issue went public a researcher found a similar flaw that wasn't blocked by the first fix and this was assigned CVE-2014-7169. Later, Red Hat Product Security researcher Florian Weimer found additional problems and they were assigned CVE-2014-7186 and CVE-2014-7187. It's possible that other issues will be found in the future and assigned a CVE designator even if they are blocked by the existing patches.

... ... ...

Why is Red Hat using a different patch then others?

Our patch addresses the CVE-2014-7169 issue in a much better way than the upstream patch, we wanted to make sure the issue was properly dealt with.
I have deployed web application filters to block CVE-2014-6271. Are these filters also effective against the subsequent flaws?

If configured properly and applied to all relevant places, the "() {" signature will work against these additional flaws.

Does SELinux help protect against this flaw?

SELinux can help reduce the impact of some of the exploits for this issue. SELinux guru Dan Walsh has written about this in depth in his blog.

Are you aware of any new ways to exploit this issue?

Within a few hours of the first issue being public (CVE-2014-6271), various exploits were seen live, they attacked the services we identified at risk in our first post:

We did not see any exploits which were targeted at servers which had the first issue fixed, but were affected by the second issue. We are currently not aware of any exploits which target bash packages which have both CVE patches applied.

Why wasn't this flaw noticed sooner?

The flaws in Bash were in a quite obscure feature that was rarely used; it is not surprising that this code had not been given much attention. When the first flaw was discovered it was reported responsibly to vendors who worked over a period of under 2 weeks to address the issue.

This entry was posted in Vulnerabilities and tagged bash, CVE-2014-6271, CVE-2014-6277, CVE-2014-6278, CVE-2014-7169, CVE-2014-7186, CVE-2014-7187, shellshocked by Huzaifa Sidhpurwala. Bookmark the permalink.

https://securityblog.redhat.com/2014/09/24/bash-specially-crafted-environment-variables-code-injection-attack/

Update 2014-09-25 16:00 UTC

Red Hat is aware that the patch for CVE-2014-6271 is incomplete. An attacker can provide specially-crafted environment variables containing arbitrary commands that will be executed on vulnerable systems under certain conditions. The new issue has been assigned CVE-2014-7169.

We are working on patches in conjunction with the upstream developers as a critical priority. For details on a workaround, please see the knowledgebase article.

Red Hat advises customers to upgrade to the version of Bash which contains the fix for CVE-2014-6271 and not wait for the patch which fixes CVE-2014-7169. CVE-2014-7169 is a less severe issue and patches for it are being worked on.


Bash or the Bourne again shell, is a UNIX like shell, which is perhaps one of the most installed utilities on any Linux system. From its creation in 1980, Bash has evolved from a simple terminal based command interpreter to many other fancy uses.

In Linux, environment variables provide a way to influence the behavior of software on the system. They typically consists of a name which has a value assigned to it. The same is true of the Bash shell. It is common for a lot of programs to run Bash shell in the background. It is often used to provide a shell to a remote user (via ssh, telnet, for example), provide a parser for CGI scripts (Apache, etc) or even provide limited command execution support (git, etc)

Coming back to the topic, the vulnerability arises from the fact that you can create environment variables with specially-crafted values before calling the Bash shell. These variables can contain code, which gets executed as soon as the shell is invoked. The name of these crafted variables does not matter, only their contents. As a result, this vulnerability is exposed in many contexts, for example:

Like "real" programming languages, Bash has functions, though in a somewhat limited implementation, and it is possible to put these Bash functions into environment variables. This flaw is triggered when extra code is added to the end of these function definitions (inside the enivronment variable). Something like:

$ env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
 vulnerable
 this is a test

The patch used to fix this flaw, ensures that no code is allowed after the end of a Bash function. So if you run the above example with the patched version of Bash, you should get an output similar to:

 $ env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
 bash: warning: x: ignoring function definition attempt
 bash: error importing function definition for `x'
 this is a test

We believe this should not affect any backward compatibility. This would, of course, affect any scripts which try to use environment variables created in the way as described above, but doing so should be considered a bad programming practice.

Red Hat has issued security advisories that fixes this issue for Red Hat Enterprise Linux. Fedora has also shipped packages that fixes this issue.

We have additional information regarding specific Red Hat products affected by this issue that can be found at https://access.redhat.com/site/solutions/1207723

Information on CentOS can be found at http://lists.centos.org/pipermail/centos/2014-September/146099.html.

>

http://support.novell.com/security/cve/CVE-2014-6271.html

Updated information on the bash fixes.
Sep 26, 2014 | support.novell.com

We have fixed the critical issue CVE-2014-6271 (http://support.novell.com/security/cve/CVE-2014-6271.html) with updates for all supported and LTSS code streams.

SLES 10 SP3 LTSS, SP4 LTSS, SLES 11 SP1 LTSS, SLES 11 SP2 LTSS, SLES 11 SP3, openSUSE 12.3, 13.1.

The issue CVE-2014-7169 ( http://support.novell.com/security/cve/CVE-2014-7169.html) is less severe (no trivial code execution) but will also receive fixes for above. As more patches are under discussions around the bash parser, we will wait some days to collect them to avoid a third bash update.

Apache Tips & Tricks Deny access to certain file types MDLog-sysadmin

Applies: apache 1.3.x / apache 2.0.x
Required apache module: mod_access
Scope: global server configuration, virtual host, directory, .htaccess
Type: security

Description: How to deny access to certain file types.
Useful: to deny access to certain files that contain private information (log files, source code, password files, etc.).

I a previous tip (Hide a file type from directory indexes) I have showed how we can hide some files from appearing in directory indexes. Even if the files will not appear in directory indexes this will not imply that access to the files will be denied and if a remote user knows the exact location of the file, he will still be able to access the file from a browser… How can someone find out about the location of the private file? well this doesn't really matter too much, but he might see paths, or files, shown in a warning messages, or the files might be browsable (there is no hiding of the files in the directory indexes).
So if there are 'special files' that you want to not be served in any case to remote users then you will have to deny access to them.

In order to achieve this we will be using the standard apache module mod_access that will allow us to define rules for various contexts (<Directory>, <Files>, and <Location> sections). In this case we will be interested in the <Files> section.

Allow/Deny Directive in <Files>

Your apache might contain in the default configuration (or at least it would be nice) a configuration similar to the following one that will deny access from the browser to .htaccess files:

<Files ~ "^\.htaccess">
Order allow,deny
Deny from all
</Files>

This is a simple example of how we can deny access to a single file by its name. If you don't have such a configuration, then it might be a good idea to add it :-) .

Let's see how we can deny access to several files; let's consider that we want to deny access to all files with the extension .inc (includes in our php application). In order to achieve this we will add the following configuration lines in the appropriate context (either global config, or vhost/directory, or from .htaccess):

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

Similar to this we can deny access to whatever files we might need…

20 ways to Secure your Apache Configuration by Pete Freitag

Here are 20 things you can do to make your apache configuration more secure.

Disclaimer: The thing about security is that there are no guarantees or absolutes. These suggestions should make your server a bit tighter, but don't think your server is necessarily secure after following these suggestions.

Additionally some of these suggestions may decrease performance, or cause problems due to your environment. It is up to you to determine if any of the changes I suggest are not compatible with your requirements. In other words proceed at your own risk.

  1. First, make sure you've installed latest security patches

    There is no sense in putting locks on the windows, if your door is wide open. As such, if you're not patched up there isn't really much point in continuing any longer on this list. Go ahead and bookmark this page so you can come back later, and patch your server.

  2. Hide the Apache Version number, and other sensitive information.

    By default many Apache installations tell the world what version of Apache you're running, what operating system/version you're running, and even what Apache Modules are installed on the server. Attackers can use this information to their advantage when performing an attack. It also sends the message that you have left most defaults alone.

  3. There are two directives that you need to add, or edit in your httpd.conf file:
    ServerSignature Off
    ServerTokens Prod

    The ServerSignature appears on the bottom of pages generated by apache such as 404 pages, directory listings, etc.

    The ServerTokens directive is used to determine what Apache will put in the Server HTTP response header. By setting it to Prod it sets the HTTP response header as follows:

    Server: Apache

    If you're super paranoid you could change this to something other than "Apache" by editing the source code, or by using mod_security (see below).

  4. Make sure apache is running under its own user account and group

    Several apache installations have it run as the user nobody. So suppose both Apache, and your mail server were running as nobody an attack through Apache may allow the mail server to also be compromised, and vise versa.

    User apache
    Group apache
  5. Ensure that files outside the web root are not served

    We don't want apache to be able to access any files out side of its web root. So assuming all your web sites are placed under one directory (we will call this /web), you would set it up as follows:

    <Directory />
      Order Deny,Allow
      Deny from all
      Options None
      AllowOverride None
    </Directory>
    <Directory /web>
      Order Allow,Deny
      Allow from all
    </Directory>
    Note that because we set Options None and AllowOverride None this will turn off all options and overrides for the server. You now have to add them explicitly for each directory that requires an Option or Override.
  6. Turn off directory browsing

    You can do this with an Options directive inside a Directory tag. Set Options to either None or -Indexes

    Options -Indexes
  7. Turn off server side includes

    This is also done with the Options directive inside a Directory tag. Set Options to either None or -Includes

    Options -Includes
  8. Turn off CGI execution

    If you're not using CGI turn it off with the Options directive inside a Directory tag. Set Options to either None or -ExecCGI

    Options -ExecCGI
  9. Don't allow apache to follow symbolic links

    This can again can be done using the Options directive inside a Directory tag. Set Options to either None or -FollowSymLinks

    Options -FollowSymLinks
  10. Turning off multiple Options

    If you want to turn off all Options simply use:

    Options None

    If you only want to turn off some separate each option with a space in your Options directive:

    Options -ExecCGI -FollowSymLinks -Indexes
  11. Turn off support for .htaccess files

    This is done in a Directory tag but with the AllowOverride directive. Set it to None.

    AllowOverride None

    If you require Overrides ensure that they cannot be downloaded, and/or change the name to something other than .htaccess. For example we could change it to .httpdoverride, and block all files that start with .ht from being downloaded as follows:

    AccessFileName .httpdoverride
    <Files ~ "^\.ht">
        Order allow,deny
        Deny from all
        Satisfy All
    </Files>
  12. Run mod_security

    mod_security is a super handy Apache module written by Ivan Ristic, the author of Apache Security from O'Reilly press.

    You can do the following with mod_security:

    • Simple filtering
    • Regular Expression based filtering
    • URL Encoding Validation
    • Unicode Encoding Validation
    • Auditing
    • Null byte attack prevention
    • Upload memory limits
    • Server identity masking
    • Built in Chroot support
    • And more
  13. Disable any unnecessary modules

    Apache typically comes with several modules installed. Go through the apache module documentation and learn what each module you have enabled actually does. Many times you will find that you don't need to have the said module enabled.

    Look for lines in your httpd.conf that contain LoadModule. To disable the module you can typically just add a # at the beginning of the line. To search for modules run:

    grep LoadModule httpd.conf

    Here are some modules that are typically enabled but often not needed: mod_imap, mod_include, mod_info, mod_userdir, mod_status, mod_cgi, mod_autoindex.

  14. Make sure only root has read access to apache's config and binaries

    This can be done assuming your apache installation is located at /usr/local/apache as follows:

    chown -R root:root /usr/local/apache
    chmod -R o-rwx /usr/local/apache
  15. Lower the Timeout value

    By default the Timeout directive is set to 300 seconds. You can decrease help mitigate the potential effects of a denial of service attack.

    Timeout 45
  16. Limiting large requests

    Apache has several directives that allow you to limit the size of a request, this can also be useful for mitigating the effects of a denial of service attack.

    A good place to start is the LimitRequestBody directive. This directive is set to unlimited by default. If you are allowing file uploads of no larger than 1MB, you could set this setting to something like:

    LimitRequestBody 1048576

    If you're not allowing file uploads you can set it even smaller.

    Some other directives to look at are LimitRequestFields, LimitRequestFieldSize and LimitRequestLine. These directives are set to a reasonable defaults for most servers, but you may want to tweak them to best fit your needs. See the documentation for more info.

  17. Limiting the size of an XML Body

    If you're running mod_dav (typically used with subversion) then you may want to limit the max size of an XML request body. The LimitXMLRequestBody directive is only available on Apache 2, and its default value is 1 million bytes (approx 1mb). Many tutorials will have you set this value to 0 which means files of any size may be uploaded, which may be necessary if you're using WebDAV to upload large files, but if you're simply using it for source control, you can probably get away with setting an upper bound, such as 10mb:

    LimitXMLRequestBody 10485760
  18. Limiting Concurrency

    Apache has several configuration settings that can be used to adjust handling of concurrent requests. The MaxClients is the maximum number of child processes that will be created to serve requests. This may be set too high if your server doesn't have enough memory to handle a large number of concurrent requests.

    Other directives such as MaxSpareServers, MaxRequestsPerChild, and on Apache2 ThreadsPerChild, ServerLimit, and MaxSpareThreads are important to adjust to match your operating system, and hardware.

  19. Restricting Access by IP

    If you have a resource that should only by accessed by a certain network, or IP address you can enforce this in your apache configuration. For instance if you want to restrict access to your intranet to allow only the 176.16 network:

    Order Deny,Allow
    Deny from all
    Allow from 176.16.0.0/16

    Or by IP:

    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
  20. Adjusting KeepAlive settings

    According to the Apache documentation using HTTP Keep Alive's can improve client performance by as much as 50%, so be careful before changing these settings, you will be trading performance for a slight denial of service mitigation.

    KeepAlive's are turned on by default and you should leave them on, but you may consider changing the MaxKeepAliveRequests which defaults to 100, and the KeepAliveTimeout which defaults to 15. Analyze your log files to determine the appropriate values.

Acknowledgments

I have found the book Apache Security to be a highly valuable resource for securing an apache web server. Some of the suggestions listed above were inspired by this book.

Related Entries

Comments

On 12/06/2005 at 12:20:01 PM MST Steven Erat wrote:

One could obfuscate server programm using error pages of other http server via

ErrorDocument 404 errors/404.html ErrorDocument 500 errors/500.html

polarizers 2cent http://www.codixx.de/polarizer.html

On 12/12/2005 at 12:19:05 PM MST Scorpion wrote:

Hi there, very interestig and useful tutorial. I have found a small error though. In the fourth part, you forgot the slash for the Directory tag. It should be like this: <Directory /> Order Deny,Allow Deny from all Options None AllowOverride None </Directory>

But I was still able to access any files out side of its web root with a simple php script, any ideas?

On 12/12/2005 at 12:24:27 PM MST Pete Freitag wrote:

Yes the apache configuration does not limit what PHP (or any cgi program) can do. I'm not sure if there is any way of limiting that, but I'm not a php guru.

Thanks for pointing out that typo as well, I'll fix it.

On 12/13/2005 at 2:58:49 AM MST polarizer wrote:

> I'm not sure if there is any way

>of limiting that.

What about running apache in a chroot jail.

polarizer http://www.codixx.de/polarizer.html

On 01/20/2006 at 3:19:28 PM MST Brian wrote:

For mod_security, the guys at gotroot.com make a very complete set of rules available that you can download and pop in to protect against all kinds of attacks. They update the rules every few days. An excellent way to help protect your application from known exploits, XSS and other attempts.

Brian

On 04/04/2006 at 6:18:29 PM MDT Fabián Arias wrote:

To restrict php to the web root you have to set the open_basedir variable in php.ini to your web root.

On 01/03/2007 at 5:53:46 AM MST Mueller Martin wrote:

Better way to set open_basedir for every host in apache, because setting in php.ini is global for all defined hosts in apache, so host1 could see directory of host2 and host3 ...

It's mentioned here in Listing2: http://www.linux-magazin.de/Artikel/ausgabe/2004/10/php/php.html (Article in German language)

On 01/05/2007 at 6:07:22 PM MST Jok wrote:

If you don't want to use mod_security, and simply looks for hiding/masking Server: header, there's a tiny third part module that exists to do it on : http://jok.is-a-geek.net/blog/index.php?page=read&id=2006/01/090956

On 01/08/2007 at 5:46:44 AM MST Apache Dude wrote:

Awesome article man, very helpful. Here is a really good post dealing with securing SSL http://www.askapache.com/2006/htaccess/apache-ssl-in-htaccess-examples.html

On 10/23/2007 at 9:19:53 AM MDT cal wrote:

Thank you! :)

On 12/02/2007 at 6:29:10 PM MST Brontojoris wrote:

Hi, I know I'm a bit late to the party, but I just wanted to comment on Renan's query regarding .cfm files not being sent to the correct ErrorDocument location as set in Apache's config.

To have Apache catch .cfm files, instead of Coldfusion displaying an error, you need to update the IfModule mod_jrun22.c portion of the httpd.conf file for Apache. Change the 'JRunConfig Ignoresuffixmap false' to 'JRunConfig Ignoresuffixmap true'

On 05/23/2008 at 2:50:54 PM MDT Mario Barrera A. wrote:

Restricting Access by IP If you have a resource that should only by accessed by a certain network.

chroot isn't a security tool, and was never intended to be one. You can quite easily break out of a chroot jail, so relying on chroot for security is never a good idea.

On 08/01/2008 at 2:16:39 AM MDT Darko Bunic wrote:

Very well article. I would like to add the way you can exclude needless Apache modules. After commenting out needless candidate, run httpd.conf test, not httpd restart because httpd in case of error will not start. You should also comment depend modules. I describe whole procedure on www.redips.net so I hope you will find useful information there.

Debian Administration Intrustion detection and prevention for Apache with mod-security

How-To Apache web server basic security measures Debian-Ubuntu Tips & Tricks

A good start is to avoid displaying the software versions you are using.

Let me explain. When somebody request a page to a HTTP server, this one respond with headers such as Content-Type, Content-Length... as well as Server.

People don't usually see those headers, but if someone wants to hack your box, they might be looking for it. Why? Because known exploits usually work on specific software version.

Lets look at default HTTP headers on my ubuntu dapper box:

~$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Date: Tue, 25 Jul 2006 10:47:13 GMT
Server: Apache/2.0.55 (Ubuntu) PHP/5.1.4-1.dotdeb.2
Last-Modified: Mon, 20 Mar 2006 09:51:25 GMT
ETag: "3057-1f8-1a0f4140"
Accept-Ranges: bytes
Content-Length: 504
Connection: close
Content-Type: text/html; charset=ISO-8859-1

Connection closed by foreign host.

As you can see from this excerpt, my box is running Apache 2.0.55 on an Ubuntu box and php-5.1.4 is used. This is perfect, if I want to hack that box, I simply have to look for known exploit for apache 2.0.55 or php 5.1.4 or even ubuntu.

The idea is to avoid telling too much, so we are going to make apache be less verbose.

2. Apache Configuration File:

In Apache, the ServerTokens directive allow the system administrator to set different type of Server HTTP response header:

By default, ServerTokens is set to Full, on my dapper box at least. To change that value, edit /etc/apache2/apache2.conf and look for the line containing ServerTokens.

Nota: On my ubuntu dapper box, ServerTokens was not set and was therefore taking the default value (Full), in that case, simply add this directive to apache2.conf.

I would recommend setting ServerTokens to Prod by adding this to apache2.conf:

ServerTokens Prod

Reload apache:

$sudo /etc/init.d/apache2 reload

and check for the new headers. Here are the headers sent back by my local server after setting ServerTokens to Prod:

$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Date: Tue, 25 Jul 2006 11:33:09 GMT
Server: Apache
Last-Modified: Mon, 20 Mar 2006 09:51:25 GMT
ETag: "3057-1f8-1a0f4140"
Accept-Ranges: bytes
Content-Length: 504
Connection: close
Content-Type: text/html; charset=ISO-8859-1

Connection closed by foreign host.

As you can see, apache does not tell anymore which version and modules are running

How-To Apache web server basic security measures -- page 2 Debian-Ubuntu Tips & Tricks

3. PHP:

Another way to hide which PHP version you are running can be achieved through php.ini.
Php as a directive of its own in order not to be too verbose, this is the variable called expose_php. Turning this one to Off will avoid php telling that it is running. In the following output, I had ServerTokens set to Full and expose_php to Off:

"Mod_security 1.7 has been released.

Mod_security is an open source intrusion detection and prevention engine for web applications. It operates embedded into the web server, acting as a powerful umbrella - shielding applications from attacks. The latest release adds output scanning to Apache 2.x; the ability to analyze cookies; functionality to change the identity of the web server; several new actions for rule grouping; new null-byte attack anti-evasion code."

A Guide to Building Secure Web Applications and Web Services

LinuxPlanet- Moving The Open Web Application Security Project Out Of The Shadows

Center for Internet Security - Apache Benchmark

eBook Preventing Web Attacks with Apache

Apache can be hacked. As companies have improved perimeter security, hackers have increasingly focused on attacking Apache Web servers and Web applications. Firewalls and SSL won't protect you: you must systematically harden your Web application environment. Preventing Web Attacks with Apache brings together all the information you'll need to do that: step-by-step guidance, hands-on examples, and tested configuration files.

Building on his groundbreaking SANS presentations on Apache security, Ryan C. Barnett reveals why your Web servers represent such a compelling target, how significant exploits are performed, and how they can be defended against. Exploits discussed include: buffer overflows, denial of service, attacks on vulnerable scripts and programs, credential sniffing and spoofing, client parameter manipulation, brute force attacks, web defacements, and more.

Barnett introduces the Center for Internet Security Apache Benchmarks, a set of best-practice Apache security configuration actions and settings he helped to create. He addresses issues related to IT processes and your underlying OS; Apache downloading, installation, and configuration; application hardening; monitoring, and more. He also presents a chapter-length case study using actual Web attack logs and data captured "in the wild."

For every sysadmin, Web professional, and security specialist responsible for Apache or Web application security.

With this book, you will learn to

Solaris 10 Security How To Guides Eliminating Web Page Hijacking

This How to Guide instructs Solaris system administrators and security professionals in the process of securing common Web servers. By the end of the guide, an example configuration will be created that allows Web content to be maintained securely by content owners, while the Web server itself will run with a minimized set of privileges in its own secured Container.

Administrators are guided step-by-step through the process and at the end of the guide should be able to:

This guide is not exhaustive and will not cover all optional features of these technologies. However, the reference section provided at the end of the document provides pointers to where administrators can learn more.

Apache HTTP Server: Security Tips

Some hints and tips on security issues in setting up a web server. Some of the suggestions will be general, others specific to Apache.

Security Tips - Apache HTTP Server

The Apache HTTP Server has a good record for security and a developer community highly concerned about security issues. But it is inevitable that some ...

Apache Week. Apache security

The O'Reilly Network has teamed with Red Hat Apache Week, the leading commercial Apache site to offer comprehensive Apache information and resources.

Apache Security - The Complete Guide to Securing Your Apache Web ...

Apache Security is the complete guide to securing your apache web server.

Security and Apache: An Essential Primer ...

(LinuxPlanet) With Web security becoming a paramount concern in the face of several DoS attacks in prior weeks, securing your Apache/Linux installation should be the ...

ModSecurity (mod_security) - Open Source Web Application Firewall

Apache Security is a comprehensive Apache Security resource, written by Ivan Ristic for O'Reilly. One chapter (Apache Installation and Configuration) is ...

Debian Administration Intrustion detection and prevention for Apache with mod-security

How-To Apache web server basic security measures Debian-Ubuntu Tips & Tricks

A good start is to avoid displaying the software versions you are using.

Let me explain. When somebody request a page to a HTTP server, this one respond with headers such as Content-Type, Content-Length... as well as Server.

People don't usually see those headers, but if someone wants to hack your box, they might be looking for it. Why? Because known exploits usually work on specific software version.

Lets look at default HTTP headers on my ubuntu dapper box:

~$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Date: Tue, 25 Jul 2006 10:47:13 GMT
Server: Apache/2.0.55 (Ubuntu) PHP/5.1.4-1.dotdeb.2
Last-Modified: Mon, 20 Mar 2006 09:51:25 GMT
ETag: "3057-1f8-1a0f4140"
Accept-Ranges: bytes
Content-Length: 504
Connection: close
Content-Type: text/html; charset=ISO-8859-1

Connection closed by foreign host.

As you can see from this excerpt, my box is running Apache 2.0.55 on an Ubuntu box and php-5.1.4 is used. This is perfect, if I want to hack that box, I simply have to look for known exploit for apache 2.0.55 or php 5.1.4 or even ubuntu.

The idea is to avoid telling too much, so we are going to make apache be less verbose.

2. Apache Configuration File:

In Apache, the ServerTokens directive allow the system administrator to set different type of Server HTTP response header:

By default, ServerTokens is set to Full, on my dapper box at least. To change that value, edit /etc/apache2/apache2.conf and look for the line containing ServerTokens.

Nota: On my ubuntu dapper box, ServerTokens was not set and was therefore taking the default value (Full), in that case, simply add this directive to apache2.conf.

I would recommend setting ServerTokens to Prod by adding this to apache2.conf:

ServerTokens Prod

Reload apache:

$sudo /etc/init.d/apache2 reload

and check for the new headers. Here are the headers sent back by my local server after setting ServerTokens to Prod:

$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Date: Tue, 25 Jul 2006 11:33:09 GMT
Server: Apache
Last-Modified: Mon, 20 Mar 2006 09:51:25 GMT
ETag: "3057-1f8-1a0f4140"
Accept-Ranges: bytes
Content-Length: 504
Connection: close
Content-Type: text/html; charset=ISO-8859-1

Connection closed by foreign host.

As you can see, apache does not tell anymore which version and modules are running

How-To Apache web server basic security measures -- page 2 Debian-Ubuntu Tips & Tricks

3. PHP:

Another way to hide which PHP version you are running can be achieved through php.ini.
Php as a directive of its own in order not to be too verbose, this is the variable called expose_php. Turning this one to Off will avoid php telling that it is running. In the following output, I had ServerTokens set to Full and expose_php to Off:

"Mod_security 1.7 has been released.

Mod_security is an open source intrusion detection and prevention engine for web applications. It operates embedded into the web server, acting as a powerful umbrella - shielding applications from attacks. The latest release adds output scanning to Apache 2.x; the ability to analyze cookies; functionality to change the identity of the web server; several new actions for rule grouping; new null-byte attack anti-evasion code."

A Guide to Building Secure Web Applications and Web Services

LinuxPlanet- Moving The Open Web Application Security Project Out Of The Shadows

Recommended Links

Softpanorama hot topic of the month

Softpanorama Recommended

Top articles

Sites

***** Secure Configuration of the Apache Web Server, Apache Server Version 1.3.3 on Red Hat Linux 5.1 (447KB)

How-To: Apache web server basic security measures | Debian/Ubuntu ...

Dot-Com Builder Web Services

Dot-Com Builder Web Services -- Web security

Preventing Cross-site Scripting Attacks Paul Lindner, author of the mod_perl Cookbook, explains how to secure our sites against Cross-Site Scripting attacks using mod_perl and Apache::TaintRequest. [Perl.com]

Tutorials and Sample Chapters

Apache: The Definitive Guide Chapter 11: Security (PDF Format)

Apache: The Definitive Guide, 2nd Edition: Chapter 13 Security

Here we will look at how secure communication is built into Apache. ... You now have a secure version of Apache, httpsd; a site to use it on, site.ssl; ...

www.oreilly.com/catalog/apache2/chapter/ch13.html - 113k - oreilly.com -- Online Catalog: Apache Security, First Edition

This all-purpose guide for locking down Apache arms readers with all the information they need to securely deploy applications.

Apache Security

Apache Security from AZ. Lincoln Stein. Open Source Conference, Version 3. For copies of this tutorial:. http://stein.cshl.org/~lstein ...

THE COMMON SENSE GUIDE TO APACHE SECURITY. As I clearly state in my Site Security Page, you are the biggest threat to your own site! ...



Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: September 12, 2017