Apache em chroot

13
Preparando o ambiente Prepare o seu sistema com o seguinte script: http://www.douglas.wiki.br/Downloads/scripts/ConfInicialSqueeze.sh Para que não falte nenhum pacote ou configuração. Vamos primeiro fazer um update de nossos repositórios e a atualização de todo o sistema: # aptitude update && aptitude distupgrade y Agora vamos instalar o Apache, módulo de chroot eo debootstrap para montar a nossa jaula: # aptitude install apache2 libapache2modchroot debootstrap y Montando a nossa jaula: # debootstrap squeeze /var/chroot http://ftp.br.debian.org/debian Copiando a configuração do nosso sistema para a jaula: # cp a /etc/resolv.conf /var/chroot/etc/ # cp a /etc/hosts /var/chroot/etc/ # cp a /etc/mime.types /var/chroot/etc/ # cp a /usr/share/zoneinfo/America/Sao_Paulo /var/chroot/usr/share/zoneinfo/America # cp a /etc/adjtime /var/chroot/etc/ Instalando o Apache dentro da jaula e o locales, pois às vezes temos problemas com idioma, daí já podemos corrigir este problema: # chroot /var/chroot aptget update # chroot /var/chroot aptitude distupgrade y # chroot /var/chroot aptget install apache2.2common apache2utils locales y Acertando o idioma da jaula: # sed i 's/# pt_BR.UTF8 UTF8/pt_BR.UTF8 UTF8/' /var/chroot/etc/locale.gen # chroot /var/chroot localegen Ajustando o PID do Apache por causa de nossa jaula: # mv /var/run/apache2.pid /var/chroot/var/run/apache2.pid

description

Apache em chroot

Transcript of Apache em chroot

Page 1: Apache em chroot

Preparando o ambiente

Prepare o seu sistema com o seguinte script:

http://www.douglas.wiki.br/Downloads/scripts/ConfInicialSqueeze.sh

Para que não falte nenhum pacote ou configuração.

Vamos primeiro fazer um update de nossos repositórios e a atualização de todo o sistema:

# aptitude update && aptitude dist­upgrade ­y

Agora vamos instalar o Apache, módulo de chroot e o debootstrap para montar a nossa jaula:

# aptitude install apache2 libapache2­mod­chroot debootstrap ­y

Montando a nossa jaula:

# debootstrap squeeze /var/chroot http://ftp.br.debian.org/debian

Copiando a configuração do nosso sistema para a jaula:

# cp ­a /etc/resolv.conf /var/chroot/etc/# cp ­a /etc/hosts /var/chroot/etc/# cp ­a /etc/mime.types /var/chroot/etc/# cp ­a /usr/share/zoneinfo/America/Sao_Paulo /var/chroot/usr/share/zoneinfo/America# cp ­a /etc/adjtime /var/chroot/etc/

Instalando o Apache dentro da jaula e o locales, pois às vezes temos problemas com idioma, daí já podemoscorrigir este problema:

# chroot /var/chroot apt­get update# chroot /var/chroot aptitude dist­upgrade ­y# chroot /var/chroot apt­get install apache2.2­common apache2­utils locales ­y

Acertando o idioma da jaula:

# sed ­i 's/# pt_BR.UTF­8 UTF­8/pt_BR.UTF­8 UTF­8/' /var/chroot/etc/locale.gen# chroot /var/chroot locale­gen

Ajustando o PID do Apache por causa de nossa jaula:

# mv /var/run/apache2.pid /var/chroot/var/run/apache2.pid

Page 2: Apache em chroot

# ln ­s /var/chroot/var/run/apache2.pid /var/run/apache2.pid

Configurando o Apache no arquivo /etc/apache2/httpd.conf:

# vim /etc/apache2/httpd.conf

PidFile /var/run/apache2.pidChrootDir /var/chroot/

Copiando os sites para a jaula (caso já tenha algum):

# cp ­Ra /var/www/* /var/chroot/var/www/

Vamos testar o acesso à nossa jaula, vamos editar o index.html da nossa jaula e colocar um valor diferente dopadrão para termos certeza que o Apache está nos mostrando os dados da jaula:

# echo "Teste de chroot no Apache " > /var/chroot/var/www/index.html

Reiniciar o Apache:

# /etc/init.d/apache2 restart

Vamos agora acessar o nosso site:

http://ip_servidor

Vai ter que aparecer a mensagem de teste que colocamos na jaula.

Podemos acompanhar os erros do Apache como exemplo abaixo:

# tail ­f /var/log/apache2/error.log

[Fri Jun 24 09:24:23 2011] [notice] Apache/2.2.16 (Debian) configured ­­ resuming normaloperations[Fri Jun 24 09:35:28 2011] [notice] caught SIGTERM, shutting down[Fri Jun 24 09:35:29 2011] [notice] Apache/2.2.16 (Debian) configured ­­ resuming normaloperations[Fri Jun 24 09:39:09 2011] [notice] caught SIGTERM, shutting down[Fri Jun 24 09:39:10 2011] [notice] Apache/2.2.16 (Debian) configured ­­ resuming normaloperations

A primeira parte já esta OK, o Apache está trabalhando em modo chroot, agora temos que fazer o PHP 5 e oMySQL trabalharem com ele, e vamos também configurar mais alguns módulos para a segurança de nosso

Page 3: Apache em chroot

Apache.

Adicionando suporte ao PHP, suporte ao mod_evasive e ao mod_security

Instalando o PHP5, ele não precisa ficar na jaula:

# aptitude install php5 libapache2­mod­php5 php5­gd php5­ps php5­cli php­pear php5­gd php5­mysqlphp5­imap php5­mcrypt php5­json ­y# aptitude install php5­xmlrpc php5­dev php5­common fail2ban libapache2­mod­security2 vsftpdpostfix mysql­client­5.1 mysql­client ­y# chroot /var/chroot apt­get install imagemagick php5­common ­y

Acertando permissões:

# rm ­rf /var/chroot/dev/*# for SEC in $(echo $(find /var/chroot/ ­type f \( ­perm ­04000 ­o ­perm ­02000 \) ­print)); do chmod ­s$SEC; done# chmod ­x /var/chroot/bin/su# chmod ­x /var/chroot/bin/stty

Configurando o módulo evasive para nos ajudar a prevenir os ataques do tipo DoS:

# apt­get install libapache2­mod­evasive# echo "LoadModule evasive20_module /usr/lib/apache2/modules/mod_evasive20.so" >/etc/apache2/mods­available/evasive.load

Configurando o módulo /etc/apache2/mods­available/evasive.conf:

# vim /etc/apache2/mods­available/evasive.conf

<IfModule mod_evasive.c>DOSHashTableSize 3097 DOSPageCount 2DOSSiteCount 50DOSPageInterval 1DOSSiteInterval 1DOSBlockingPeriod 900 DOSWhitelist 66.249.65.*DOSWhitelist 66.249.66.*# As ultimas são as que o google usa para indexar.</IfModule>

Acertando o idioma do sistema:

Page 4: Apache em chroot

# sed ­i 's/# pt_BR.UTF­8 UTF­8/pt_BR.UTF­8 UTF­8/' /etc/locale.gen# locale­gen

Vamos montar um virtualhost para testarmos o nosso chroot /etc/apache2/sites­available/www.douglas.wiki.br:

# vim /etc/apache2/sites­available/www.douglas.wiki.br

<VirtualHost *:80>ServerName www.douglas.wiki.brServerAlias douglas.wiki.br

DocumentRoot "/var/www/website/frontend/"<Directory "/var/www/website/frontend/">Options ­Indexes FollowSymLinks MultiViewsAllowOverride AllOrder allow,denyallow from all</Directory>

ScriptAlias /cgi­bin/ "/var/www/website/frontend/cgi­bin/"<Directory "/var/www/website/frontend/cgi­bin/">AllowOverride AllOptions ExecCGI ­MultiViews +SymLinksIfOwnerMatchOrder allow,denyAllow from all</Directory>

ErrorLog $APACHE_LOG_DIR/www.douglas.wiki.br­error.logCustomLog $APACHE_LOG_DIR/www.douglas.wiki.br­access.log common

ServerSignature Off

IndexIgnore .??* *~ *# README RCS CVS *,v *,t *

# Possible values include: debug, info, notice, info, error, crit,# alert, emerg.LogLevel info</VirtualHost>

Montar a base do nosso site:

# mkdir ­p /var/chroot/var/www/website/frontend/cgi­bin# mkdir ­p /var/chroot/var/www/website/logs

Page 5: Apache em chroot

# ln ­sf /var/chroot/var/www/website /var/www/website

Criando o arquivo index de teste:

# echo "<?php phpinfo(); ?>" > /var/www/website/frontend/index.php

Incluindo o shell /bin/true para o usuário ftp:

# echo "/bin/true" >> /etc/shells

Criando o usuário ftp para o nosso site:

# useradd ­m ­d /var/www/website ­s /bin/true usuarioftp

Agora vamos definir uma senha para ele:

# passwd usuarioftp

Carregando o nosso site e descarregando os sites defaults:

# a2ensite www.douglas.wiki.br# a2dissite default# a2dissite default­ssl# a2enmod rewrite

Agora vamos configurar o mod_security. Insira no final do arquivo /etc/apache2/apache2.conf o conteúdoabaixo:

# vim /etc/apache2/apache2.conf

[...]#Final do arquivo<IfModule mod_security.c># Turn the filtering engine On or OffSecFilterEngine On

# Make sure that URL encoding is validSecFilterCheckURLEncoding On

# Unicode encoding checkSecFilterCheckUnicodeEncoding Off

# Only allow bytes from this rangeSecFilterForceByteRange 0 255

Page 6: Apache em chroot

# Only log suspicious requestsSecAuditEngine RelevantOnly

# The name of the audit log fileSecAuditLog /var/log/apache2/audit_log

# Debug level set to a minimumSecFilterDebugLog /var/log/apache2/modsec_debug_logSecFilterDebugLevel 0

# Should mod_security inspect POST payloadsSecFilterScanPOST On

# By default log and deny suspicious requests# with HTTP status 500SecFilterDefaultAction "deny,log,status:500"</IfModule>

Reiniciar o Apache:

# /etc/init.d/apache2 restart

Vamos analisar os logs do Apache:

# tail ­f /var/log/apache2/error.log

PHP Deprecated: Comments starting with '#' are deprecated in /etc/php5/apache2/conf.d/ps.inion line 1 in Unknown on line 0[Fri Jun 24 09:50:34 2011] [notice] ModSecurity for Apache/2.5.12 (http:www.modsecurity.org/) configured.[Fri Jun 24 09:50:34 2011] [notice] Apache/2.2.16 (Debian) PHP/5.3.3­7+squeeze1 withSuhosin­Patch configured ­­ resuming normal operations[Fri Jun 24 09:51:55 2011] [notice] Graceful restart requested, doing restartPHP Deprecated: Comments starting with '#' are deprecated in /etc/php5/apache2/conf.d/ps.inion line 1 in Unknown on line 0[Fri Jun 24 09:51:56 2011] [notice] Apache/2.2.16 (Debian) PHP/5.3.3­7+squeeze1 withSuhosin­Patch configured ­­ resuming normal operations[Fri Jun 24 10:44:51 2011] [notice] caught SIGTERM, shutting down[Fri Jun 24 10:44:53 2011] [notice] ModSecurity for Apache/2.5.12 (http:www.modsecurity.org/) configured.PHP Deprecated: Comments starting with '#' are deprecated in /etc/php5/apache2/conf.d/ps.inion line 1 in Unknown on line 0[Fri Jun 24 10:44:54 2011] [notice] Apache/2.2.16 (Debian) PHP/5.3.3­7+squeeze1 withSuhosin­Patch configured ­­ resuming normal operations

Page 7: Apache em chroot

Como pode ser notado, temos um aviso sobre o tipo de comentário no arquivo de configuração do PHP5:/etc/php5/apache2/conf.d/ps.ini. Vamos corrigir isso, só temos que trocar na linha 1 o "#" por ";", que é o tipode comentário para arquivos de configuração do PHP5:

# vim /etc/php5/apache2/conf.d/ps.ini

; configuration for php ps moduleextension=ps.so

Vamos também tirar a assinatura do nosso PHP:

# vim /etc/php5/apache2/php.ini

[...]expose_php = Off[...]

Agora já podemos reiniciar o nosso Apache novamente para ver se vamos ter mais algum aviso ou erro:

# /etc/init.d/apache2 restart

Vamos verificar os logs agora:

# tail ­f /var/log/apache2/error.log

[Fri Jun 24 10:49:12 2011] [notice] caught SIGTERM, shutting down[Fri Jun 24 10:49:14 2011] [notice] ModSecurity for Apache/2.5.12 (http:www.modsecurity.org/) configured.[Fri Jun 24 10:49:15 2011] [notice] Apache/2.2.16 (Debian) PHP/5.3.3­7+squeeze1 withSuhosin­Patch configured ­­ resuming normal operations

Adicionando suporte ao MySQL e configurando o vsftpd

Vamos configurar o nosso MySQL para o Apache ter acesso:

# aptitude install mysql­server­5.1 mysql­client­5.1 php5­mysql ­y

Agora ajustar o MySQL:

Page 8: Apache em chroot

# /etc/init.d/mysql stop# mv /var/run/mysqld /var/chroot/var/run/mysqld# ln ­s /var/chroot/var/run/mysqld /var/run/mysqld

Já podemos inicializar o nosso MySQL:

# /etc/init.d/mysql start

Ajustar as permissões do nosso site:

# chown ­R usuarioftp:www­data /var/chroot/var/www/website

Configurar o logrotate para ir fazendo rotação dos logs do nosso site, arquivo /etc/logrotate.d/websites:

# vim /etc/logrotate.d/websites

#/etc/logrotate.d/websites/var/www/website/logs/*.log weeklymissingokrotate 52compressdelaycompressnotifemptycreate 640 www­data www­datasharedscriptspostrotate/etc/init.d/apache2 reload > /dev/nullendscript

Configurar o vsftdp para podermos subir os arquivos para o site, os usuários somente vão poder ver o seuhome, eles vão ficar presos dentro da jaula. Abra o arquivo /etc/vsftpd.conf:

# vim /etc/vsftpd.conf

#/etc/vsftpd.conflisten=YESlisten_ipv6=NOanonymous_enable=NOlocal_enable=YESwrite_enable=YESlocal_umask=002anon_upload_enable=NOanon_mkdir_write_enable=NO

Page 9: Apache em chroot

dirmessage_enable=YESuse_localtime=YESxferlog_enable=YESconnect_from_port_20=NOxferlog_file=/var/log/vsftpd.logxferlog_std_format=YESidle_session_timeout=600data_connection_timeout=120nopriv_user=ftpftpd_banner=Bem­Vindo ao FTP douglas.wiki.br.deny_email_enable=NOchroot_local_user=YESchroot_list_enable=NObanned_email_file=/etc/vsftpd.banned_emailschroot_list_file=/etc/vsftpd.chroot_listls_recurse_enable=YESsecure_chroot_dir=/var/run/vsftpd/emptypam_service_name=vsftpdrsa_cert_file=/etc/ssl/private/vsftpd.pem

Criando mais alguns arquivos necessáriosNesse arquivos podemos colocar os usuários que vão poder sair da jaula:

# touch /etc/vsftpd.chroot_list

Nesse arquivo podemos colocar os e­mails que vão ser negados pelo vsftpd.

# touch /etc/vsftpd.banned_emails

Vamos reiniciar o nosso serviço:

# /etc/init.d/vsftpd restart

Agora vamos testar o acesso via FTP:

# ftp localhostConnected to localhost.220 Bem­Vindo ao FTP douglas.wiki.br.Name (localhost:root): usuarioftp331 Please specify the password.Password: senha230 Login successful.

Page 10: Apache em chroot

Remote system type is UNIX.Using binary mode to transfer files.ftp> ls200 PORT command successful. Consider using PASV.150 Here comes the directory listing.drwxr­xr­x 3 1001 33 4096 Jun 24 10:41 frontenddrwxr­xr­x 2 1001 33 4096 Jun 24 10:44 logs226 Directory send OK.ftp> quit221 Goodbye.

Como pode ser notado, conseguimos acessar o nosso servidor normalmente com o usuário que criamos.

Configurando o Fail2ban e ajustando o Apache

Agora vamos configurar o Fail2ban para cuidar de nosso servidor:

# vim /etc/fail2ban/jail.conf

#/etc/fail2ban/jail.conf[DEFAULT]ignoreip = 127.0.0.1, 10.0.0.0/23bantime = 600maxretry = 3backend = pollingdestemail = [email protected] = iptables­multiportmta = sendmailprotocol = tcpaction_ = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s]action_mw = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s]%(mta)s­whois[name=%(__name__)s, dest=\"%(destemail)s\", protocol=\"%(protocol)s]action_mwl = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s]%(mta)s­whois­lines[name=%(__name__)s, dest=\"%(destemail)s\", logpath=%(logpath)s]

action = %(action_mwl)s

[ssh]enabled = trueport = sshfilter = sshdlogpath = /var/log/auth.logmaxretry = 3

Page 11: Apache em chroot

[pam­generic]enabled = truefilter = pam­genericport = allbanaction = iptables­allportsport = anyportlogpath = /var/log/auth.logmaxretry = 3

[ssh­ddos]enabled = trueport = sshfilter = sshd­ddoslogpath = /var/log/auth.logmaxretry = 3

[apache]enabled = trueport = http,httpsfilter = apache­authlogpath = /var/log/apache*/*error.logmaxretry = 3

[dominio.com.br]enabled = trueport = http,httpsfilter = apache­authlogpath = /var/www/website/logs/*error.logmaxretry = 3

[vsftpd]enabled = trueport = ftp,ftp­data,ftps,ftps­datafilter = vsftpdlogpath = /var/log/vsftpd.logmaxretry = 3

[postfix]enabled = trueport = smtp,ssmtpfilter = postfixlogpath = /var/log/mail.log

[sasl]

Page 12: Apache em chroot

enabled = trueport = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3sfilter = sasllogpath = /var/log/mail.log

Reiniciar o serviço para que o nosso servidor esteja com um agente analisando os logs e bloqueando quandonecessário:

# /etc/init.d/fail2ban restart

Agora vamos fazer mais alguns ajustes em nosso Apache. Abra e deixe como abaixo o arquivo/etc/apache2/conf.d/security:

# vim /etc/apache2/conf.d/security

[...]ServerTokens Prod[...]ServerSignature Off

E na jaula também:

# vim /var/chroot/etc/apache2/conf.d/security

[...]ServerTokens Prod[...]ServerSignature Off

Agora é só reiniciar o Apache:

# /etc/init.d/apache2 restart

E é só acessar o site em:

http://www.douglas.wiki.br

ReferênciasWelcome to The Apache Software Foundation!Welcome! ­ The Apache HTTP Server ProjectFrontPage ­ Httpd Wiki

Page 13: Apache em chroot

FAQ ­ Httpd WikiReporting Security Problems with Apache ­ The Apache HTTP Server ProjectApache HTTP Server Version 2.2PHP: Installation on Unix systems ­ ManualPHP: Installation and Configuration ­ ManualPHP: Apache 2.x on Unix systems ­ ManualMySQL :: The world's most popular open source databaseMySQL :: MySQL Downloads (Generally Available)MySQL :: Developer ZoneMySQL :: MySQL Documentation: MySQL Reference Manualsvsftpd ­ Secure, fast FTP server for UNIX­like systemsIndex of /users/cevans/untar/vsftpd­2.3.4 on vsftpd.beasts.org:21Manpage of VSFTPD.CONFAurium :: Usando ChrootBest Practices for UNIX chroot() OperationsCriação de ambientes em chrootpt_BR/Debootstrap ­ Debian WikiInstalling new Debian systems with debootstrapFail2ban.orgMANUAL 0 8 ­ Fail2ban

Artigo também publicado em:

Servidor Web Apache Enjaulado + Debian Squeeze ­ douglas.wiki.br