eXtreme Development

Apache HTTPd - hardening

Umas das primeiras coisas a fazer após a instalação do Apache ou de qualquer serviço é limitar as opções de acesso. No caso do Apache faremos isso editando o arquivo /etc/apache2/sites-available/default.

Verifique a seção abaixo: Options FollowSymLinks AllowOverride None

Esta seção controla como o Apache tratará o diretório raiz do sistema de arquivos e todos os arquivos contidos nele. Edite esta seção adcionando as seguintes linhas:

Order Deny,Allow Deny from all Options None AllowOverride None

Isto fará com que o Apache não exiba qualquer arquivo do sistema de arquivos, não permitindo opções especiais (como symlinking, includes, ou scripts cgi), nem que sobreescrevam os arquivos .htaccess nos diretórios. No entanto, uma vez que queremos que o Apache acesse arquivos a partir do diretório /var/www/, nós precisamos editar a seção abaixo:

Options FollowSymLinks MultiViews Order allow,deny Allow from all

Isto permite que o Apache disponibilize páginas contidas em /var/www e removendo Indexes, isto significa que os usuários não serão capazes de acessar o conteúdo dos diretórios na web.

É necessário reiniciar o Apache para que as efetuar as mudanças. Ocultando a versão do servidor

Agora iremos configurar o Apache para ocultar informações sobre o sistema. Estas informações surgem quando ocorre uma tela de erro, como abaixo: Para ocultar as informações do sistema edite o arquivo /etc/apache2/apache2.conf. Mudando a seguinte linha:

ServerTokens Full

para

ServerTokens Prod

Reinicie o Apache e faça o teste acessando uma página que não existe. Instalando o Mod_Security

O módulo de segurança, o mod_security, é um módulo do Apache que será instalado para bloquear o monitoramento de requisições e respostas HTTP tanto quanto a negação de pacotes suspeitos.

Inicialmente instale as dependências necessárias

aptitude install libxml2-dev apache2-prefork-dev

Download Mod_Security

código fonte Pacotes pré-compilados para diversas distribuições Pacote Debian

Instalação e Compilação

Se você optou por baixar o source execute os seguintes passos para compilar o módulo

tar zxvf modsecurity-apache_2.5.7.tar.gz cd modsecurity-apache_2.5.7/apache2/ ./configure && make && make install ( como root! )

Configurando o Apache

Agora acesse o diretório /etc/apache2/mods-available, acesse o arquivo modsecurity2.load e adicione as seguintes linhas:

LoadFile /usr/lib/libxml2.so LoadModule security2_module /usr/lib/apache2/modules/mod_security2.so

Agora vá para um diretório acima, no caso o mods-enabled e crie um link simbólico para os arquivo editado anteriormente e para o arquivo mod_unique_id:

cd ../mods-enabled ln -s ../mods-available/modsecurity2.load ln -s ../mods-available/unique_id.load

Após reiniciar o Apache, verifique o aquivo de log que está em /var/log/apache2/error.log. Deverá existir a seguinte linha:

Wed Dec 03 16:54:25 [notice] ModSecurity for Apache/2.5.2 (http://www.modsecurity.org/) configured.

Configurando o Mod_security

Primeiro, as regras necessárias para inciar o funcionamento deste módulo encontra-se no diretório /modsecurity-apache_2.5.7/rules, copie estas regras para o diretório /var/lib/modsecurity/

cp modsecurity_crs_* /var/lib/modsecurity/

Informe ao Apache onde encontram-se a regras criando o arquivo /etc/apache2/conf.d/modsecurity2.conf e adicionando as seguintes linhas:

Include /var/lib/modsecurity/*.conf

Reinicie o Apache para efetivar as mudanças Testando o Mod_security

Agora que o módulo já está configurado e rodando podemos realizar um teste simples usando o wget:

wget -O - -U ngsecurity analyzer http://

Se o mod_security estiver funcionando, será informado o erro 404:

alexos@cypher:~$ wget -O - -U ngsecurity analyzer http:// 19:13:17 http:// => `- Resolving meu_webtestserver X.X.X.X Connecting to meu_webtestserver|X.X.X.X|:80 connected. HTTP request sent, awaiting response 404 Not Found 19:13:17 ERROR 404: Not Found.

No servidor web execute o comando abaixo

tail /var/log/apache2/debug.log

ou

tail /var/log/apache2/audit.log

Vejam o que apareceu para mim!

03/Dec/2008:17:18:17 [matrix/sid#855d8f0][rid#87357f8][/][1] Access denied with code 404 (phase 2). Pattern match (?:\b(?:m(?:ozilla\/4\.0 \ (compatible\)|etis)|ngsecurity analyzer|pmafind)\b|n(?:-stealth|sauditor| essus|ikto)|b(?:lack ?widow|rutus|ilbo)|(?:jaascoi|paro)s|webinspect|\.nasl) at REQUEST_HEADERS:User-Agent. [file "/var/lib/modsecurity/modsecurity_crs_35_bad_robots.conf"] [line "19"] [id "990002"] [msg "Request Indicates a Security Scanner Scanned the Site"] [severity "CRITICAL"] [tag "AUTOMATION/SECURITY_SCANNER"]

Porque surgiu na expressão regular acima o ngsecurity analyzer , a requisição para o arquivo foi negada, mostrando que o mod_security está funcionando.

Hardening - É um processo de mapeamento das ameaças, mitigação dos riscos e execução das atividades corretivas - com foco na infra-estrutura e objetivo principal de torná-la preparada para enfrentar tentativas de ataque. (Wikipedia)

http://www.kyplex.com/docs/apache-security.html 10 Apache Security and Hardening Tips

The Apache web server is a crucial part of the website infrastructure. It has a number of built in features that can improve your website resistance to attacks. The following document covers a number of steps that will help you to achieve this goal. This document is largely based on the knowledge gathered by our security team and by statistics information revealed by our security scanner. Tip No. 1: Disable Apache Signature and/or Apache Banner

Apache Signature or Apache Banner is basically the same thing. It is an application name together with version name that is printed when performing a web request. Nobody actually needs this information at all, but it is enabled by default. You need to alter the Apache configuration file to disable it.

ServerSignature Off ServerTokens ProductOnly

In Ubuntu, you need to change the following file: /etc/apache2/apache2.conf

Double check that ServerSignature and ServerTokens configuration settings are not enabled in some other parts of the configuration file. Tip No. 2: The Trace HTTP Request

HTTP TRACE request is used to echo back all received information. It can be tricked to print HTTP cookies and as a result steal HTTP session. Basically this request can be used as part of the Cross Site Scripting attack, or XSS. It is recommended to disable it as a security precaution.

Add the following to the web-server's configuration file. For example alter the following file in Ubuntu: /etc/apache2/apache2.conf .

TraceEnable off

Tip 3: Remove PHP scripts that print debug info using phpinfo()

The built-in PHP function phpinfo() prints a lot of interesting internal information about the PHP environment. It can include list of which PHP modules are enabled, and the location of various files on the web-server and other sensitive information. Our web security scanner finds a lot of such files. It is recommended to remove these test files from a production website.

Here is a tip hpw to find such files. Look for the files with the following name: test.php, info.php, i.php and phpinfo.php in your website directory and remove them. Tip 4: Disable directory indexing

Directory indexing is a features found in every web-server by default. When directory indexing is enabled, the web-site prints a list of files found in the website directories when the default page does not exists (for example index.php). Directories reported can be viewed by any visitor. It is vulnerable in the sense that these directories can contain configuration, private and backup files which can be used by the attackers to take your server under control.

You can fix this problem by disabling the Apache autoindex module. In some Apache installations it is called mod_autoindex.so. In Ubuntu, you just need to remove the following files:

/etc/apache2/mods-enabled/autoindex.load /etc/apache2/mods-enabled/autoindex.conf

So you can do it running the following commands:

rm -f /etc/apache2/mods-enabled/autoindex.load rm -f /etc/apache2/mods-enabled/autoindex.conf

Tip 5: Disable WebDAV

WebDAV is a file access protocol created over HTTP protocol. It allows you to upload and download files, and change file contents from the website. This service is required only in very rare cases. From our experience, this feature was only required to run SVN server (link). Make sure that WebDAV is disabled in production websites. When WebDAV is enabled, the following commands are supported by Apache: OPTIONS, PROPFIND, etc. These commands are sensitive from computer security point of view.

You can fix this problem by disabling Apache dav, dav_fs and dav_lock modules. In Ubuntu you just need to remove the following files:

/etc/apache2/mods-enabled/dav.load /etc/apache2/mods-enabled/dav_fs.conf /etc/apache2/mods-enabled/dav_fs.load /etc/apache2/mods-enabled/dav_lock.load

So you can do it running the following commands:

rm -f /etc/apache2/mods-enabled/dav.load rm -f /etc/apache2/mods-enabled/dav_fs.conf rm -f /etc/apache2/mods-enabled/dav_fs.load rm -f /etc/apache2/mods-enabled/dav_lock.load

Tip 6: Create a chroot'ed Apache environment

Chroot is a kind of virtual environment supported operating systems such as Linux and FreeBSD. When an application is executed in chrooted environment it has no access to the parent disk and to other recources.

This is a good solution if you want to protect your website from malicious users. The action steps required to create chroot Apache was already covered in a number of websites. For example: http://www.linux.com/archive/feed/36331

The main hidden issue with chrooted environment is that this environment protects the websites from accessing the operating system's files. It does not protect one site from another. In other words, if a malicious script located in one site it can access files located on other site because they are located on the same chrooted environment.

A solution to this problem is the following. Create a number of apache instances, each one hosting one website running each one if different chrooted directory. These apache instances will not be able to share IP addresses. You will have to configure different IP for each Apache instance you run. Tip 7: Enable PHP basedir

PHP has built in a kind of chroot environment. It is called “basedir”. You can configure PHP scripts to access files only in specific directory similar to chroot. Basically you can configure each site to access only files located in that site directory which is a very good idea from the security point of view.

You can add the following lines to the website configuration file or to .htaccess file to enable PHP basedir:

Php_value open_basedir /var/www/foo.bar/:/usr/local/php/

This will specify that your PHP scripts can access only specified directories. Tip 8: Web Stats

Some webmasters install open source tools on their website that analyze web requests and create statistical reports. Access to these webstat scrips is almost never secured with a password. So any visitor can basically view such reports. For example some webmasters install in in the /stats directory accessible by http://www.my-site.com/stats .

Statistical reports contain a lot of sensitive information. For example it can contain hidden file names and directory names, full web requests, search engine keywords, etc... All this information can be used by the malicious users and/or your competitors.

Instead of running a statistics script on your website we recommend that you use Google Analytics. It is a free-of-charge and quality service. Tip 9: Use Google

Most of the webmasters use common web scripts and CMS or blog software. We recommend you to frequently search for security updates using Google and register for security news at your blog/CMS website. Tip 10: Additional Steps

If your webserver runs together with MySQL server it brings additional potential security problem. MySQL can read any files located on you server including the one located in different chrooted environments. It happens because of the FILE permission. By default only MySQL root has it. For more info about MySQL security take a look at this article ( link to GreenSQL) .

http://xianshield.org/guides/apache2.0guide.html Configure the Apache server

Configure the file permissions and runtime settings of the Apache server. It’s important that you place your htdocs, cgi-bin, and logs directories on separately mounted filesystems.

6.1 Configure httpd.conf

Set the following in your httpd.conf file. You can also download an example httpd.conf with these settings here.

Directive and setting Description/rationale ServerSignature Off

Prevents server from giving version info on error pages. ServerTokens Prod

Prevents server from giving version info in HTTP headers Listen 80 (remove)

Remove the “Listen” directive – we’ll set this directive only in ssl.conf, so that it will only be available over https. User webserv (or whatever you created in step 2 above)

Ensure that the child processes run as unprivileged user Group webserv (or whatever you created in step 2 above)

Ensure that the child processes run as unprivileged group ErrorDocument 404 errors/404.html ErrorDocument 500 errors/500.html

etc.

To further obfuscate the web server and version, this will redirect to a page that you should create, rather than using the default Apache pages. ServerAdmin <hostname>-webmaster@xianco.com

Use a mail alias – never use a person’s email address here. UserDir disabled root

Remove the UserDir line, since we disabled this module. If you do enable user directories, you’ll need this line to protect root’s files. <Directory /> Order Deny, Allow deny from all </Directory>

Deny access to the root file system. <Directory /opt/apache2/htdocs"> <LimitExcept GET POST> deny from all </LimitExcept>

Options -FollowSymLinks -Includes -Indexes -MultiViews AllowOverride None Order allow,deny Allow from all </Directory>

LimitExcept prevents TRACE from allowing attackers to find a path through cache or proxy servers. The “-“ before any directive disables that option.

FollowSymLinks allows a user to navigate outside the doc tree, and Indexes will reveal the contents of any directory in your doc tree.

Includes allows .shtml pages, which use server-side includes (potentially allowing access to the host). If you really need SSI, use IncludesNoExec instead.

AllowOverride None will prevent developers from overriding these specifications in other parts of the doc tree. AddIcon (remove) IndexOptions (remove) AddDescription (remove) ReadmeName (remove) HeaderName (remove) IndexIgnore (remove)

Remove all references to these directives, since we disabled the fancy indexing module. Alias /manual (remove)

Don’t provide any accessible references to the Apache manual, it gives attackers too much info about your server.

You should familiarize yourself with the following parameters. Unless you are running a high-volume web site, you can safely leave the settings at their default values. If you are running a high-volume web site, you’ll want to adjust these directives upward to better withstand denial-of-service attacks.

* StartServers * MinSpareServers * MaxSpareServers * Timeout * Keepalive * MaxKeepAliveRequests * KeepAliveTimeout * MaxClients * MaxRequestsPerChild

6.2 Configure ssl.conf

Set the following in your ssl.conf file. You can also download an example ssl.conf with these settings here. Directive and setting Description/rationale SSLCertificateChainFile /opt/apache2/conf/ssl.crt/ca.crt (Find this line and uncomment it). This points to the Certificate Authority file for your chained certificate.

6.3 Remove default Apache files It’s important to remove default files such as .html files and CGI scripts (yes, even the Apache manual). This will help obfuscate the server you’re running, targetted attacks against your web server. You’ll probably want to build a simple index.html page to place in the htdocs directory, just so you know the web server is working when you start it. ~> sudo rm –fr /opt/apache2/htdocs/* ~> sudo rm –fr /opt/apache2/cgi-bin/* ~> sudo rm –fr /opt/apache2/icons

To test that your web server is running, you can now place this file in your htdocs directory – it’s just a simple index.html file. Make sure you set the permissions to world-readable.

6.4 Set directory and file permissions for the server

To protect the directories on your server, it’s important that you protect the directories themselves. * bin is where the executable portion of the Apache web server is. It should be readable/executable only by members of the webadmin group, but only writable by root. ~> sudo chown –R root:webadmin /opt/apache2/bin ~> sudo chmod –R 770 /opt/apache2/bin

* conf is where your web server configuration files are and needs to be read/writable only by the webadmin group. ~> sudo chown –R root:webadmin /opt/apache2/conf ~> sudo chmod –R 770 /opt/apache2/conf

* logs is where your access and error logs will go. It should be readable only by the webadmin group. ~> sudo chown –R root:webadmin /opt/apache2/logs ~> sudo chmod –R 755 /opt/apache2/logs

* htdocs is where your HTML files are and needs to be world readable, but writable only by root (you should copy content in from a staging server). ~> sudo chown –R root /opt/apache2/htdocs ~> sudo chmod –R 775 /opt/apache2/htdocs

* cgi-bin is where your executable scripts are and needs to be world read/executable, but writable only by root (you should copy content in from a staging server). ~> sudo chown –R root /opt/apache2/cgi-bin ~> sudo chmod –R 775 /opt/apache2/cgi-bin

7. Make final configuration and start server Lastly, we need to modify the startup configuration for Apache and restart the server.

7.1 Modify Apache startup script so that it will notify you when it’s restarted. As a failsafe measure, you should notify your webmaster alias any time this server is restarted. That way, you’ll be notified of any unauthorized attempt. Open /opt/apache/bin/apachectl and add something like this to the file: tail /opt/apache2/logs/error_log | /bin/mail -s 'Apache web server has restarted' <hostname>-webmaster@xianco.com

7.2 Test your configuration by starting the server sudo /opt/apache2/bin/apachectl startssl

7.3 Keep your web server patched Check web sites for Apache and all modules regularly and apply important patches. Apache web server: http://nagoya.apache.org/dist/httpd/patches/ OpenSSL: http://www.openssl.org/source OpenLDAP: http://www.openldap.org/

8. Configure authentication against an LDAP directory.

In this final section, we’ll configure the Apache httpd.conf file so that resources are authenticated against an LDAP server. This step really can’t be run until you’ve installed the web server. Once you’ve got your web server installed, just add the LDAP authentication directives to any directory (or httpd.conf file) where you want password protection with CEC credentials. Here’s an example of protecting a directory named “Internal”

<Location "/internal"> AuthName CEC AuthType Basic AuthLDAPURL ldap://ldap.xianco.com:389/ou=employees,ou=people,o=xianco.com?uid?sub?(objectclass=xiancoPerson) require valid-user </Location>


# StartServers: quantidade de processos que o serviço cria ao iniciar # MinSpareServers: quantidade mínima de processos que o serviço mantêm # MaxSpareServers: quantidade máxima de processos que o serviço mantêm # ServerLimit: limite de processos do serviço # MaxClients: quantidade máxima de processos que o serviço pode vir a ter # MaxRequestsPerChild: quantidade máxima de requisições que cada processo pode processar

Além disso, esse link (Danke schöen Gelder-san!) pode ajudar a dimensionar o MPM no Apache http://rudd-o.com/linux-and-free-software/tuning-an-apache-server-in-5-minutes



SourceForge BootStrap