Prevenir ataques DDoS com Apache mod_evasive

# yum install httpd-devel
# yum install mod_evasive

* É necessário ativar o repositório EPEL

Reinicia-se o Apache para ativar o módulo

# /etc/init.d/httpd restart
Stopping httpd: [ OK ]
Starting httpd: [ OK ]

Verificar que o módulo está ativo

# php -r 'phpinfo();' | grep -i evasive
^ Loaded Modules | core prefork http_core mod_so mod_auth_basic mod_auth_digest mod_authn_file mod_authn_alias mod_authn_anon mod_authn_dbm mod_authn_default mod_authz_host mod_authz_user mod_authz_owner mod_authz_groupfile mod_authz_dbm mod_authz_default util_ldap mod_authnz_ldap mod_include mod_log_config mod_logio mod_env mod_ext_filter mod_mime_magic mod_expires mod_deflate
mod_headers mod_usertrack mod_setenvif mod_mime mod_dav mod_status mod_autoindex mod_info mod_dav_fs mod_vhost_alias mod_negotiation mod_dir mod_actions mod_speling mod_userdir mod_alias mod_rewrite mod_proxy mod_proxy_balancer mod_proxy_ftp mod_proxy_http mod_proxy_connect mod_cache mod_suexec mod_disk_cache mod_file_cache mod_mem_cache mod_cgi mod_version mod_evasive20 mod_perl mod_php5 mod_proxy_ajp mod_python mod_ssl |

Agora vamos configurar o módulo. Esta é a configuração que estou a testar de momento, parece funcionar bem mesmo num servidor partilhado com muitos acessos.

Editar o ficheiro /etc/httpd/conf.d/mod_evasive.conf:

<IfModule mod_evasive20.c>
   DOSHashTableSize 3097
   DOSPageCount 6
   DOSSiteCount 100
   DOSPageInterval 2
   DOSSiteInterval 2
   DOSBlockingPeriod 600
</IfModule>

Reinicia-se novamente o Apache para recarregar as configurações:

# /etc/init.d/httpd restart
Stopping httpd: [ OK ]
Starting httpd: [ OK ]

Moodle: DragMath não funciona no Windows XP

Em vários sites o DragMath não funcionava quando se acedia através do Windows XP. Depois de muitas voltas, dei conta que o applet estava a ser bloqueado pelo mod_security. Na lista de robots existia uma string “windows xp 5” e o header do cliente era “Mozilla/4.0 (Windows XP 5.1) Java/1.7.0_04”.

Consegui dar com o problema porque reparei que os acessos ao .jar e ao .applet estavam a ser devolvidos com 403.

ModSecurity: Access denied with code 403 (phase 2). Matched phrase "windows xp 5" at REQUEST_HEADERS:User-Agent. [file "/etc/httpd/modsecurity.d/base_rules/modsecurity_crs_35_bad_robots.conf"] [line "26"] [id "990012"] [rev "2.1.2"] [msg "Rogue web site crawler"] [data "windows xp 5"] [severity "WARNING"] [tag "AUTOMATION/MALICIOUS"] [tag "WASCTC/WASC-21"] [tag "OWASP_TOP_10/A7"] [tag "PCI/6.5.10"] [hostname "xxxx.pt"] [uri "/lib/DragMath/applet/Display/MainApplet/class.class"]

Para resolver isto tive que alterar o ficheiro /etc/httpd/modsecurity.d/base_rules/modsecurity_35_bad_robots.data e eliminar a linha com a string “windows xp 5”.

OSSEC: Desativar alertas de email para determinadas regras

Tal como referi num post atrás um dos servidores estava a dar erros de ACPI. Como tenho um IDS instalado na máquina (ossec) de 10 em 10 minutos recebia um mail a avisar do erro. Obviamente que esta frequência de emails é muito chata e portanto tinha que arranjar uma forma de desativar o alerta por email deste erro específico.

Para desativar este alerta editamos o ficheiro local_rules.xml e adicionamos a seguinte regra:

  <rule id="100101" level="0">
    <if_sid>1002</if_sid>
    <match>ACPI Error</match>
    <options>no_email_alert</options>
    <description>Ignored messages.</description>
  </rule>

Basicamente o que acontece aqui é que sempre que a regra 1002 for disparada, se o alerta do log contiver a mensagem “ACPI Error” então é disparada a regra 100101 com o nível 0 e não é enviado nenhum email. A diretiva <options> serve unicamente de exemplo pois na minha configuração só são enviados alertas de email para regras de níveis superiores a 7.

HP DL585 G7 a correr o Webmin no CentOs 6 causa erros de ACPI

Ao instalar o webmin num HP DL585 G7 a correr o CentOs 6 o servidor dá mensagens de erro ACPI de 10 em 10minutos. Segundo o site da HP este é um erro normal neste modelo quando se utiliza RHEL 6 e que não causa problemas.

May  4 18:01:57 ccems-web5 kernel: ACPI Error: SMBus or IPMI write requires Buffer of length 42, found length 20 (20090903/exfield-286)
May  4 18:01:57 ccems-web5 kernel: ACPI Error (psparse-0537): Method parse/execution failed [\_SB_.PMI0._PMM] (Node ffff88043b101448), AE_AML_BUFFER_LIMIT
May  4 18:01:57 ccems-web5 kernel: ACPI Exception: AE_AML_BUFFER_LIMIT, Evaluating _PMM (20090903/power_meter-341)

Apesar de ser um erro normal é muito chato receber mails de 10 em 10mins com as mensagens de erro…

A solução passa por desativar o ACPI. Existem duas formas de o fazer, retirando o serviço do arranque e parando-o ou alterando o grub para desligar o ACPI na kernel.

Desligar o ACPI Soft-Off com o chkconfig no arranque:

chkconfig --level 2345 acpid off
service acpid stop

Ou então desativar completamente o ACPI editando o grub.conf:

vim /boot/grub/grub.conf

Acrescentar acpi=off aos parâmetros de boot da kernel. Exemplo:

kernel /vmlinuz-2.6.18-36.el5 ro root=/dev/VolGroup00/LogVol00 console=ttyS0,115200n8 acpi=off

 

Fonte:
http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=c02642731&lang=en&cc=us&taskId=101&prodSeriesId=4194641&prodTypeId=15351
http://www.centos.org/docs/5/html/5.1/Cluster_Administration/s2-apci-disable-boot-CA.html
http://www.centos.org/docs/5/html/5.1/Cluster_Administration/s2-apci-disable-chkconfig-CA.html
http://sites.google.com/site/boxxit/linux-server/myserver (ACIP fails with “ACPI Error (psparse-0537)” so it has to be disabled.)

CentOs 6 erros no NetworkManager

Ao fazer boot o message log do servidor apresentava alguns erros no NetworkManager.

May  4 14:55:30 ccems-web5 NetworkManager[4445]: <error> [1336139730.352197] [nm-manager.c:1360] user_proxy_init(): could not init user settings proxy: (3) Could not get owner of name 'org.freedesktop.NetworkManagerUserSettings': no such name
May  4 14:55:30 ccems-web5 NetworkManager[4445]: <error> [1336139730.525895] [nm-manager.c:1360] user_proxy_init(): could not init user settings proxy: (3) Could not get owner of name 'org.freedesktop.NetworkManagerUserSettings': no such name

Depois de ler algumas páginas concluí que a causa do problema do NetworkManager foi, provavelmente, por ter mexido nas definições das placas de rede (/etc/sysconfig/network-scripts/ifcfg-eth[01]) sem ser através do gestor de rede.

Para gerir a rede da forma normal é necessário alterar os ficheiros de configuração ifcfg e adicionar:

NM_CONTROLLED="no"

e depois desligar o NetworkManager e ligar a network:

chkconfig NetworkManager off
chkconfig network on
service NetworkManager stop
service network start

 

Fonte:

https://www.centos.org/modules/newbb/viewtopic.php?topic_id=36992

Using the Webmin YUM repository

If you like to install and update Webmin via RPM, create the /etc/yum.repos.d/webmin.repo file containing :

[Webmin]
 name=Webmin Distribution Neutral
 #baseurl=http://download.webmin.com/download/yum
 mirrorlist=http://download.webmin.com/download/yum/mirrorlist
 enabled=1

You should also fetch and install my GPG key with which the packages are signed, with the commands :

wget http://www.webmin.com/jcameron-key.asc
rpm --import jcameron-key.asc

You will now be able to install with the command :

yum install webmin

All dependencies should be resolved automatically.

Implementar quotas de disco

First do:

yum install quota

Also you have to edit the edit the /etc/fstab and add:

usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0

If you do not need to set quotas for groups then omit the grpjquota=aquota.group, then in my fstab I have this:

UUID=b4a0be80-3a47-4609-af72-a30b7102593b /                       ext4    defaults        1 1
UUID=8f7f1ed5-4726-471f-a48e-76088180c099 /boot                   ext4    defaults        1 2
UUID=11315782-76c7-4380-b968-0bcef2f4b832 /home                   ext4    defaults,usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0        1 2
UUID=4dcacd31-c789-4406-8a71-fe1579ac5f4f swap                    swap    defaults        0 0
tmpfs                   /dev/shm                tmpfs   defaults,nosuid,noexec,rw         0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0
/var/tempFS             /tmp                    ext4    loop,nosuid,noexec,rw   0 0

To create the quota files (aquota.user and aquota.group) on the file system, use the -c option of the quotacheck command. For example, if user and group quotas are enabled for the /home file system, create the files in the /home directory:

quotacheck -cug /home

The -c option specifies that the quota files should be created for each file system with quotas enabled, the -u option specifies to check for user quotas, and the -g option specifies to check for group quotas.

If neither the -u or -g options are specified, only the user quota file is created. If only -g is specified, only the group quota file is created.

 

After the files are created, run the following command to generate the table of current disk usage per file system with quotas enabled:

quotacheck -avugm

The options used are as follows:

  • a — Check all quota-enabled, locally-mounted file systems
  • v — Display verbose status information as the quota check proceeds
  • u — Check user disk quota information
  • g — Check group disk quota information

After quotacheck has finished running, the quota files corresponding to the enabled quotas (user and/or group) are populated with data for each quota-enabled locally-mounted file system such as /home

quotaon -avug

if you need to turn the quotas off then do:

quotaoff /home

or the equivalent

quotaon -f /home

The quota system is ready to go, now we have to set the quotas for every user:

edquota -u username

And we get:

Disk quotas for user username (uid 501):

  Filesystem                   blocks       soft       hard     inodes     soft     hard
  /dev/mapper/vg_aguila-lv_root         36        0          0         10        0        0

The system automatically uses the default editor.

If we want to set 5MB of quota for username then we edit the file to:

Disk quotas for user username (uid 501):

  Filesystem                   blocks       soft       hard     inodes     soft     hard
  /dev/mapper/vg_aguila-lv_root         36       5000          0         10        0        0

 

Gestão

Basics

Use this command to check for quotas on a specific partition:

# repquota /home

Use this command to check for all quotas that apply to a user:

# quota -u $USER

for groups;

# quota -g $GROUP

Copying quota settings

To copy quota from one user or group to the other, use this command:

# edquota -p user1 user2

User1 is the user you copy from, user2 is the user you copy quota to. Of course you can replace user with group, when necessary.

Multiple users

The idea is to make a temporary user acount, modify the quota settings for that user, and then copy the generated quota files for all users to use. After setting quota settings for quotauser, copy the settings:

# edquota -p quotauser `awk -F: '$3 > 999 {print $1}' /etc/passwd`

This applies the settings to users with a UID equal to or greater than 1000.

Other commands

There are several useful commands:

repquota -a      # Shows the status on disk usage
warnquota        # Can be used to warn the users about their quota
setquota         # Non-interactive quota setting--useful for scripting

Lasty, quotastats is used to give thorough information about the quota system:

$ quotastats
Number of dquot lookups: 101289
Number of dquot drops: 101271
Number of still active inodes with quota : 18
Number of dquot reads: 93
Number of dquot writes: 2077
Number of quotafile syncs: 134518740
Number of dquot cache hits: 7391
Number of allocated dquots: 90
Number of free dquots: 2036
Number of in use dquot entries (user/group): -1946

 

Fonte:

http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-disk-quotas.html

http://www.centos.org/docs/5/html/Deployment_Guide-en-US/s1-disk-quotas-managing.html

https://wiki.archlinux.org/index.php/Disk_Quota#Journaled_quota

Utilizar o grep no linux

Copiar todas as linhas que contêm foo no ficheiro file para o ficheiro output.txt

 grep foo file > output.txt

Listar a escrita do ficheiro mas com filtragem por uma determinada expressao

tail -f file | grep --line-buffered my_pattern

Como configurar um servidor NAT de encaminhamento e acesso remoto

Quando os clientes da rede interna enviam um pedido para a Internet, o controlador do protocolo NAT intercepta o pedido e reenvia-o para o servidor da Internet de destino. Todos os pedidos parecem ter origem no endereço IP externo do servidor NAT. Este processo oculta o esquema de endereços IP internos.

Para configurar um servidor NAT de encaminhamento e acesso remoto:

  1. No menu Ferramentas administrativas (Administrative Tools), clique em Encaminhamento e acesso remoto (Routing and Remote Access).
  2. Na MMC Encaminhamento e acesso remoto (Routing and Remote Access) expanda nome_do_servidor (em que nome_do_servidor é o nome do servidor que pretende configurar) e, em seguida, expanda Encaminhamento IP (IP Routing) no painel esquerdo.
  3. Clique com o botão direito do rato em Geral (General) e, em seguida, clique em Novo protocolo de encaminhamento (New Routing Protocol).
  4. Clique para seleccionar a caixa de verificação NAT/Firewall básico (NAT/Basic Firewall) e, em seguida, clique em OK.
  5. Clique com o botão direito do rato em NAT/Firewall básico (NAT/Basic Firewall) no painel esquerdo e, em seguida, clique em Nova interface (New Interface).
  6. Clique na interface que representa a interface da rede interna e, em seguida, clique em OK.
  7. Em Propriedades de tradução de endereços de rede (Network Address Translation Properties), clique em Interface privada ligada a uma rede privada (Private interface connected to private network) e, em seguida, clique em OK.
  8. Clique com o botão direito do rato em NAT/Firewall básico (NAT/Basic Firewall) no painel esquerdo e, em seguida, clique em Nova interface (New Interface).
  9. Clique na interface que representa a interface da rede externa e, em seguida, clique em OK.
  10. Em Propriedades de tradução de endereços de rede (Network Address Translation Properties), clique em Interface pública ligada à Internet (Public interface connected to the Internet).
  11. Clique para seleccionar a caixa de verificação Activar NAT nesta interface (Enable NAT on this interface) e, em seguida, clique em OK.

O servidor NAT pode atribuir automaticamente endereços IP a clientes da rede interna. Poderá pretender utilizar esta funcionalidade se não tiver um servidor de DHCP que já esteja a atribuir informações de endereçamento a clientes na rede interna.

 

Fonte: http://support.microsoft.com/kb/324264/pt

Desactivar mod_security para um virtualhost

Não é possível desactivar o mod_security2 através de um ficheiro .htaccess. É necessário desactivá-lo no virtual host no ficheiro de configuração httpd.conf adicionando as seguintes directivas:

<IfModule mod_security2.c>
 SecRuleEngine Off
</IfModule>