Comandos linux

Ligações activas

netstat -ant

Contar nº de ligações na porta 80

netstat -ant | grep ":80" | wc -l

Contar nº de ligações na porta 3306

netstat -ant | grep ":3306" | wc -l

Verificar a natureza das ligações activas

netstat -ant | awk '{print $6}' | sort | uniq -c | sort -n

Indica o nº de tipo de ligações activas

netstat -ant | grep 80 | awk '{print $6}' | sort | uniq -c | sort -n

Fail2ban reiniciava durante a rotação diária de logs e nem toda as chains eram carregadas

Here is what I had to do to make fail2ban work with centos 6, fail2ban
from epel
This is a long letter and no html to make it read better.
It deals with failed jails during start, loss of ban/unban after systems
logrotates files, errors in jails,
sasl errors, logging file correctly to work with fail2ban and logwatch,
fail2ban logrotate.

I hope this helps others, it was a real bear and the first program/rpm I
used that really does not work very well as set up.
(a update was pushed a few weeks back, not sure how this affects
anything below…mine still works as is.)
Forgive me if I left something out.

first I added these programs to the EPEL repo ( I do not allow any
except those I use, so I use the following to limit the repo.)

includepkgs= fail2ban shorewall shorewall-core python-inotify gamin-python

Fail2ban has recently been updated on the epel repo and shorewall-core
is now needed too, this is new.
How the new updates affects any of the below is beyond me, but I doubt
it changed anything.

1st issue
——————
/etc/fail2ban/jail.conf
change line 39 to
backend = gamin

Without this fail2ban will ignore log rotations by logrotate and stay on
the old file in your jails.
This was needed or it failed. No errors, nothing.
Force log rotate did not make this happen, only the program running each
morning did it.
I changed mine to a daily rotate of /var/log/secure,vsftpd.log, etc…
to test this.
Without gamin it failed every time.

(also you need to add this)
line 16 (add your ip (or ip block?) after the 127 ip) Use a space
between them all.
ignoreip = 127.0.0.1 yourip

2nd issue
——————-
with more than one jail you can (and will) get chances of errors when
starting fail2ban. Some people seem to attribute it centos 6
having an older version of netfilter. The program goes to fast for
iptables and chokes setting up the chains.
Sometimes they all go on, most times I would lose one to two chains
during each restart of fail2ban.

You have to have debug with at least ‘info’ to see these errors. When
stopping you will get a ton of these errors too, but they seem
to have no effect on anything.

To stop these errors and allow all jails to start properly you have to
add a sleep line deep in the code.
I have not tested since the update to see if this was overwritten but
will do that this week.

/usr/bin/fail2ban-client

Find the following code and add the time.sleep(0.1) in there as I have.
You need to press the tab 3 times to indent it, python pays attention to
white space, it will choke if you do not do this.

add sleep command into the following, (tab three times)
starts at line 142
def __processCmd(self, cmd, showRet = True):
beautifier = Beautifier()
for c in cmd:
time.sleep(0.1)
beautifier.setInputCmd(c)
try:

This lets netfilter catch up with the fail2ban client and allows all
jails to get started properly.
If you only use one jail this would not be needed, but each one after
that offers a chance of not being turned on.

3rd issue
——————-
The whole log thing is borked.
if you try to use fail2ban.log, fail2ban itself will choke on it.
If you try to use the repo’s set up of using /var/log/messages than
logwatch will get borked on it.
However, if you set it all to /var/log/fail2ban as the log file, it will
work.

No matter which way you want it, logwatch, fail2ban, and logrotate all
point to different files for logging and it is a real mess.

Here is what I did to make it log and allow logrotate to work with it.

/etc/fail2ban/fail2ban.conf
line 25
logtarget = /var/log/fail2ban

/etc/logrotate.d/fail2ban
Below I changed the logtarget and stopped the ‘restart’ the repo wanted.
Thus it will keep running day after day.

/var/log/fail2ban {
missingok
notifempty
rotate 7
create 0600 root root
postrotate
/usr/bin/fail2ban-client set logtarget /var/log/fail2ban 2>
/dev/null || true
endscript
}

finally for logwatch
/usr/share/logwatch/default.conf/logfiles/fail2ban.conf
LogFile = fail2ban
Archive = fail2ban-*

——————————————————————————————————————
jails I set up…this is gonna be quick with little info, still writing
notes for the book on this one
I lowered the times in them for this letter, but mine are much higher.
I separated the ports for each for testing and safety. You could make
all the ports blocked if you wanted too.

The first ssh in the repo is enabled by default I think. Make sure if
you use these you check all others to make sure they
are not enabled.

[ssh-iptables]

enabled = true
filter = sshd
action = iptables[name=SSH, port=”22444″, protocol=tcp]
logpath = /var/log/secure
maxretry = 2
bantime = 3600

[apache-tcp]
enabled = true
filter = apache-auth
bantime = 10000
action = iptables[name=ApacheAuth, port=”80″, protocol=tcp]
logpath = /var/log/httpd/error_log
maxretry = 3

[apache-ssl]
enabled = true
filter = apache-auth-ssl
bantime = 10000
action = iptables[name=ApacheAuthSsl, port=”443″, protocol=tcp]
logpath = /var/log/httpd/ssl_error_log
maxretry = 3

[vsftpd-iptables]
enabled = true
filter = vsftpd
action = iptables[name=VSFTPD, port=”5000″, protocol=tcp]
logpath = /var/log/vsftpd.log
maxretry = 3
bantime = 3600

[Dovecot]
enabled = true
filter = dovecot
bantime = 3600
maxretry = 2
action = iptables-multiport[name=DOVECOT, port=”25,465,993,995″,
protocol=tcp]
logpath = /var/log/maillog

[Postfix]
enabled = true
filter = postfix
maxretry = 2
bantime = 3600
findtime = 3600
action = iptables-multiport[name=POSTFIX, port=”25,465,993,995″,
protocol=tcp]
logpath = /var/log/maillog
[Postfix-sasl]
enabled = true
filter = sasl
maxretry = 4
bantime = 3600
findtime = 3600
action = iptables-multiport[name=POSTFIX-SASL, port=”25,465,993,995″,
protocol=tcp]
logpath = /var/log/maillog

There was not one for dovecot, so I had to make one..
I do not think it is needed though, but I added it anyway (both go to
maillog, but I figured I could do things with the jail later)

Here are some files I had to add to make the above jails work.
#####################################
make a new file called dovecot.conf as below
/etc/fail2ban/filter.d/dovecot.conf

[Definition]
# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
# host must be matched by a group named “host”. The tag
“<HOST>” can
# be used for standard IP/hostname matching.
# Values: TEXT
#

failregex = (?: pop3-login|imap-login): (?:Authentication
failure|Aborted login \(auth failed|Aborted login \(tried to use
disabled|Disconnected \(auth failed).*rip=(?P<host>\S*),.*

# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =

####################################

for my apache auth I added this one from someone online too

#######################
make a new file
/etc/fail2ban/filter.d/apache-auth-ssl.conf
# Fail2Ban configuration file
#
# Author: Cyril Jaquier
#
# $Revision: 728 $
#

[Definition]

# Option: failregex
# Notes.: regex to match the password failure messages in the logfile. The
# host must be matched by a group named “host”. The tag
“<HOST>” can
# be used for standard IP/hostname matching and is only an
alias for
# (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values: TEXT
#
failregex = [[]client <HOST>[]] user .* authentication failure
[[]client <HOST>[]] user .* not found
[[]client <HOST>[]] user .* password mismatch

# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =
###############################

for postfix I had to add somethings to block spam. I had made some
errors to default to 550 to lower spam attempts too.

/etc/fail2ban/filter.d/postfix.conf
failregex = reject: RCPT from (.*)\[<HOST>\]: 554
reject: RCPT from (.*)\[<HOST>\]: 550
reject: RCPT from (.*)\[<HOST>\]: 504

(still need to add a 501 in there too for invalid names)

#############################################
for the sasl/postfix to work properly some changes were made, this is my
file. The one that came with the repo will not work.
At least it did not work for me.

/etc/fail2ban/filter.d/sasl.conf

this is my file

# Fail2Ban configuration file
#
# Author: Yaroslav Halchenko
#
# $Revision: 728 $
#

[Definition]

# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
# host must be matched by a group named “host”. The tag
“<HOST>” can
# be used for standard IP/hostname matching and is only an
alias for
# (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values: TEXT
#
failregex = (?i): warning: [-._\w]+\[<HOST>\]: SASL
(?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed(:
[A-Za-z0-9+/]*={0,2})?$
(?i): warning: [-._\w]+\[<HOST>\]: SASL
(?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed: Invalid
authentication mechanism
(?i): warning: [-._\w]+\[<HOST>\]: SASL
(?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed.*
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =

###################################################

here is my iptables with some things taken out for security…lol

##############################################
[root@ ~]# iptables -L -n

Chain INPUT (policy ACCEPT)
target prot opt source destination
fail2ban-VSFTPD tcp — 0.0.0.0/0 0.0.0.0/0 tcp
dpt:xx
fail2ban-DOVECOT tcp — 0.0.0.0/0 0.0.0.0/0
multiport dports 25,465,993,995
fail2ban-POSTFIX tcp — 0.0.0.0/0 0.0.0.0/0
multiport dports 25,465,993,995
fail2ban-ApacheAuthSsl tcp — 0.0.0.0/0
0.0.0.0/0 tcp dpt:443
fail2ban-ApacheAuth tcp — 0.0.0.0/0 0.0.0.0/0
tcp dpt:80
fail2ban-SSH tcp — 0.0.0.0/0 0.0.0.0/0 tcp
dpt:22444
fail2ban-POSTFIX-SASL tcp — 0.0.0.0/0 0.0.0.0/0
multiport dports 25,465,993,995
ACCEPT all — 0.0.0.0/0 0.0.0.0/0 state
RELATED,ESTABLISHED
ACCEPT icmp — 0.0.0.0/0 0.0.0.0/0
ACCEPT all — 0.0.0.0/0 0.0.0.0/0
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state NEW
tcp dpt:25
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state NEW
tcp dpt:80
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state NEW
tcp dpt:443
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state NEW
tcp dpt:465
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state NEW
tcp dpt:993
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state NEW
tcp dpt:995
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state NEW
tcp dpt:xx
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state
RELATED,ESTABLISHED tcp dpt:xx
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 state
NEW,ESTABLISHED tcp dpt:xx
ACCEPT tcp — 0.0.0.0/0 0.0.0.0/0 tcp dpts:xx:xx
REJECT all — 0.0.0.0/0 0.0.0.0/0 reject-with
icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
target prot opt source destination
REJECT all — 0.0.0.0/0 0.0.0.0/0 reject-with
icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

Chain fail2ban-ApacheAuth (1 references)
target prot opt source destination
RETURN all — 0.0.0.0/0 0.0.0.0/0

Chain fail2ban-ApacheAuthSsl (1 references)
target prot opt source destination
RETURN all — 0.0.0.0/0 0.0.0.0/0

Chain fail2ban-DOVECOT (1 references)
target prot opt source destination
RETURN all — 0.0.0.0/0 0.0.0.0/0

Chain fail2ban-POSTFIX (1 references)
target prot opt source destination
RETURN all — 0.0.0.0/0 0.0.0.0/0

Chain fail2ban-POSTFIX-SASL (1 references)
target prot opt source destination
RETURN all — 0.0.0.0/0 0.0.0.0/0

Chain fail2ban-SSH (1 references)
target prot opt source destination
RETURN all — 0.0.0.0/0 0.0.0.0/0

Chain fail2ban-VSFTPD (1 references)
target prot opt source destination
RETURN all — 0.0.0.0/0 0.0.0.0/0

 

SOURCE: http://grokbase.com/t/centos/centos/126fs478gp/update-on-spam-postfix-fail2ban-centos-6

Configurar DELL OpenManage (OMSA) para enviar alertas por email

First, we must create a simple shell script to send the email.

/usr/local/bin/om-alert.sh

#!/bin/sh
HOST=`hostname`
EMAIL="my_admin@my_network.net"
echo "There has been an OpenManage ALERT detected on $HOST. Please login to the web interface to see details." | mail $EMAIL -s "OM ALERT $HOST"

 

We can set individual alerts:

# chmod +x /usr/local/bin/om-alert.sh
# omconfig system alertaction
# omconfig system alertaction -?
# omconfig system alertaction event=powersupply execappath=/usr/local/bin/om-alert.sh
# omconfig system alertaction event=storagesyswarn alert=true broadcast=true execappath=/usr/local/bin/om-alert.sh
# omreport system alertaction

 

Or we can set console, broadcast and email for all alerts.

# for I in `omconfig system alertaction | sed 's/ *(.*)//; s/>.*//; s/.*[: echo $I;
omconfig system alertaction event=$I alert=true broadcast=true execappath="/usr/local/bin/om-alert.sh"
done

Fonte: http://idolinux.blogspot.pt/2011/02/quick-dell-openmanage-email-alerts.html

 

Mais info:

http://folk.uio.no/trondham/software/check_openmanage.html

MySQL: Replicação Master-Slave no CentOS 6

Master Server: 192.168.22.56
Slave Server: 192.168.22.73
MySQL Data path: /var/lib/mysql
MySQL slave user named slave_user

[Master]

Configurar o servidor Master.

# vim /etc/my.cnf

# [mysqld] section
# Start Modification
# First line is probably already there
datadir = /var/lib/mysql
server-id = 1
relay-log = /var/lib/mysql/mysql-relay-bin
relay-log-index = /var/lib/mysql/var/mysql-relay-bin.index
log-error = /var/lib/mysql/mysql.err
master-info-file = /var/lib/mysql/mysql-master.info
relay-log-info-file = /var/lib/mysql/mysql-relay-log.info
log-bin = /var/lib/mysql/mysql-bin
# Stop Modification

Reiniciar o MySQL para carregar as alterações

# service mysqld restart

[Slave]

A mesma coisa para o servidor Slave

# vim /etc/my.cnf

# [mysqld] section
# Start Modification
# First line is probably already there
datadir = /var/lib/mysql
server-id = 2
relay-log = /var/lib/mysql/mysql-relay-bin
relay-log-index = /var/lib/mysql/mysql-relay-bin.index
log-error = /var/lib/mysql/var/mysql.err
master-info-file = /var/lib/mysql/mysql-master.info
relay-log-info-file = /var/lib/mysql/mysql-relay-log.info
# Stop Modification

Reiniciar o MySQL para carregar as alterações

# service mysqld restart

[Master]

Vamos criar o utilizador que vai ser usado na replicação e dar-lhe as permissões. Neste caso permitimos a replicação a partir de qualquer host mas poderia ser limitado.

# mysql -u root -p
mysql> STOP SLAVE;
mysql> GRANT REPLICATION SLAVE ON *.* TO 'slave_user'@'%' IDENTIFIED BY 'slave_password';
mysql> FLUSH PRIVILEGES;

Agora vamos bloquear a escrita nas tabelas e obter a posição do log de onde o Slave vai começar a replicar.

mysql> USE mysql; # pode ser qualquer base de dados
mysql> FLUSH TABLES WITH READ LOCK;
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+
| File             | POSITION | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      334 |              |                  |
+------------------+----------+--------------+------------------+
1 ROW IN SET (0.00 sec)

[Slave]

Vamos então configurar o Slave para ler o log do Master, a começar na posição que vimos em cima.

mysql> CHANGE MASTER TO MASTER_HOST='192.168.22.56', MASTER_USER='slave_user', MASTER_PASSWORD='slave_password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=334;
mysql> START SLAVE;
mysql> SHOW SLAVE STATUS\G;

Basta confirmar que as variáveis de saída têm estes valores:
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

 

Se não conseguirem que os servidores comuniquem (a variável Slave_IO_Running estará a No, a Slave_IO_State apresenta uma tentativa de ligação e o ERROR apresenta uma mensagem de ligação falhada) então provavelmente falta abrir a porta do MySQL na firewall.

# iptables -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT

 

Para quem usar hostnames em vez de IPs, no caso de mudar de hostname poderá ter que fazer FLUSH HOSTS em ambos os servidores. No caso de usarem o ficheiro /etc/hosts então é certo que têm que o fazer.

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.