miércoles, 15 de enero de 2014

Firewall en Solaris 10 (ipfilter)

Vemos que el servicio de ipfilter está bajo:

# svcs -a |grep filter
offline 12:12:30 svc:/network/ipfilter:default


Editamos el archivo de configuración:

# vi /etc/ipf/ipf.conf


Colocamos dentro del archivo lo que deseamos bloquear, en mi caso todas las conexiones icmp, tcp y udp desde el server local donde corremos las reglas al remote_server (debe estar la ip en el /etc/hosts)


block return-rst out proto icmp from any to remote_server
block return-rst out proto tcp/udp from any to remote_server



Habilitamos el servicio de ipfilter:

# svcadm restart svc:/network/ipfilter:default


Verificamos que esté online:

# svcs -a |grep filter
online         12:12:30 svc:/network/ipfilter:default


Probamos hacer un telnet, ssh, ping, etc al equipo remoto y vemos que no recibimos respuesta.

NOTA: Tener en cuenta cuando reiniciamos ó habilitamos el servicio ver que no tire ningún error el log:


# tail -f /var/svc/log/network-ipfilter:default.log 
[ Jan 15 12:12:30 Stopping because service restarting. ]
[ Jan 15 12:12:30 Executing stop method ("/lib/svc/method/ipfilter stop") ]
[ Jan 15 12:12:30 Method "stop" exited with status 0 ]
[ Jan 15 12:12:30 Executing start method ("/lib/svc/method/ipfilter start") ]
[ Jan 15 12:12:30 Method "start" exited with status 0 ]



jueves, 9 de enero de 2014

Logins erroneos en Windows Event Viewer

Inicio -> Ejecutar y tipeamos gpedit.msc


Local Computer Policy -> Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> Audit Policy.

Sobre el panel derecho clickeamos sobre "Audit logon events":


En la solapa "Local Security Setting" tildamos "Success" y "Failure":


Probamos conectarnos al servidor con un password incorrecto y nos aparecerá "Failure Audit" en la solapa Security del Visor de Eventos, como muestra el cuadro en rojo:



viernes, 3 de enero de 2014

Chequear Visor de Sucesos Windows con Nagios

Descargué el script check_wmi_eventid de:
 http://exchange.nagios.org/directory/Plugins/Operating-Systems/Windows/WMI/Check-eventlog-2Feventid-by-WMI/details


Damos permisos de ejecución al script:
# chmod a+x ./check_wmi_eventid


Lo ejecutamos sin parámetros para ver la ayuda:

# ./check_wmi_eventid
usage: ./check_wmi_eventid options
check_wmi_eventid is a script to check windows event log , for a certian eventid..
Simple example : check application log , for eventtype error(-t) and  eventid 9003(-e) with in the last 60 mins(-m60),
set warning (-w) if greater than 1 ,and set error(-c) if greater than 3
check_wmi_eventid  -H 172.10.10.10 -u domain/user -p password -l application -e 9003  -w 1 -c 3  -t1 -m60
Adv. example : same as above , but with arguments -O -W -C, these are custom plugin output for OK,Warning and Critical
Marco ITEMCOUNt,LASTSTR , can be used!!
check_wmi_eventid  -H 172.10.10.10 -u domain/user -p password -l application -e 9003  -w 1 -c 3  -t1 -m60 -O "Every thing is OK"
-W "Warning : something is not right" -C "It is totaly bad , found ITEMCOUNT events"
Try it out :)
If you find any error , please let me know
OPTIONS:
   -h      Show this message
   -H      Host/Ip
   -u      Domain/user
   -p      password
   -l      Name of the log eg "System" or "Application" or any other Event log as shown in the Windows "Event Viewer".
   -t      Eventtype: # 1=error , 2=warning , 3=Information,4=Security Audit Success,5=Security Audit Failure
   -e      Eventid
   -s      Sting search for string in message
   -m      Number of past min to check for events.
   -w      Warning
   -W      Custom waring string    - ITEMCOUNT,LASTSTR marco can be used  ex. -W "ITEMCOUNT Wanings  with in the LASTSTR"
   -c      Critical
   -C      Custom critical string  - ITEMCOUNT,LASTSTR marco can be used  ex. -W "ITEMCOUNT Critical  with in the LASTSTR"
   -O      Custom ok sting         - ITEMCOUNT,LASTSTR marco can be used  ex. -W "Everything ok with in the LASTSTR"
   -U      CUstom unknown string   - ITEMCOUNT,LASTSTR marco can be used  ex. -W "ITEMCOUNT  Unknowns  with in the LASTSTR"
   -d      Debug
   -v      Version


Eligiendo los parámetros, ejecuté lo siguiente y me aparecía que no encontraba el cliente de WMI (wmic)


# ./check_wmi_eventid -H hostname -u administrator -p password -l application -e 9003 -w 1 -c 3 -t1 -m60
WMIC ERROR : ./check_wmi_eventid: line 252: /bin/wmic: No such file or directory


Descargamos WMIC del siguiente enlace:

http://sourceforge.net/projects/pandora/files/Tools%20and%20dependencies%20%28All%20versions%29/RPM%20CentOS%2C%20RHEL/wmic-4.0.0SVN-2.1.el5.centos.noarch.rpm/download


Lo instalamos con rpm:


# rpm -hiv wmic-4.0.0SVN-2.1.el5.centos.noarch.rpm
warning: wmic-4.0.0SVN-2.1.el5.centos.noarch.rpm: Header V3 DSA signature: NOKEY, key ID 155987ef
Preparing...                ########################################### [100%]
   1:wmic                   ########################################### [100%]


Lo ejecutamos si parámetros para ver los parametros requeridos:


# wmic
Usage: [-?] [-?] [-?] [-?NP] [-?NPV] [-?|--help] [--usage] [-d|--debuglevel DEBUGLEVEL]
        [--debug-stderr] [-s|--configfile CONFIGFILE] [--option=name=value]
        [-l|--log-basename LOGFILEBASE] [--leak-report] [--leak-report-full]
        [-R|--name-resolve NAME-RESOLVE-ORDER]
        [-O|--socket-options SOCKETOPTIONS] [-n|--netbiosname NETBIOSNAME]
        [-S|--signing on|off|required] [-W|--workgroup WORKGROUP]
        [--realm=REALM] [-i|--scope SCOPE] [-m|--maxprotocol MAXPROTOCOL]
        [-U|--user [DOMAIN/]USERNAME[%PASSWORD]] [-N|--no-pass]
        [--password=STRING] [-A|--authentication-file FILE] [-P|--machine-pass]
        [--simple-bind-dn=STRING] [-k|--kerberos STRING] [-V|--version]
        [--namespace=STRING]
        //host query

Example: wmic -U [domain/]adminuser%password //host "select * from Win32_ComputerSystem"



Una vez instalado al querer ejecutar nuevamente el comando, nos tiraba error que no lo encontraba:


# ./check_wmi_eventid -H hostname -u administrator -p password -l application -e 9003 -w 1 -c 3 -t1 -m60
 WMIC ERROR : ./check_wmi_eventid: line 252: /bin/wmic: No such file or directory


Viendo donde fue instalado, vemos que no encontraba la ruta:


# which wmic
/usr/bin/wmic



Editamos el script que descargamos (check_wmi_eventid):


# vim check_wmi_eventid
Cambiar:
WMIC=/bin/wmic
Por:
WMIC=/usr/bin/wmic



Ahora ejecutando el comando nuevamente, todo me devolvía el mismo valor, siempre era = 12:


# ./check_wmi_eventid -H server_name-u administrator -p password -l application -e 9003 -w 20 -c 30 -t1 -m60
OK 12 with Severity Level Error in application with in the last 1 hour|eventid9003=12;20;30;;

# ./check_wmi_eventid -H server_name-u administrator -p password -l security -e 4625 -w 20 -c 30 -t1 -m60
OK 12 with Severity Level Error in application with in the last 1 hour|eventid9003=12;20;30;;



Entonces decidí hacer mi propio script con WMIC, con el siguiente comando (cambiando las variables en rojo por los valores correspondientes):


# wmic -U USUARIO%PASWORD //HOSTNAME "select EventCode,EventIdentifier,EventType,TimeGenerated from Win32_NTLogEvent"


Obtenía algo como lo siguiente:

CLASS: Win32_NTLogEvent
EventCode|EventIdentifier|EventType|Logfile|RecordNumber|TimeGenerated
.....
.....
902|1073742726|0|Application|4506|20100615130231.000000-000
5615|3221231087|0|Application|4507|20100615130239.000000-000
5617|3221231089|0|Application|4508|20100615130243.000000-000
34|1073872930|3|Application|4509|20100615130247.000000-000
4|1073872900|3|Application|4510|20100615130250.000000-000
5|1073872901|3|Application|4511|20100615130251.000000-000
5|1073872901|3|Application|4512|20100615130251.000000-000
5|1073872901|3|Application|4513|20100615130251.000000-000
5|1073872901|3|Application|4514|20100615130251.000000-000
5|1073872901|3|Application|4515|20100615130251.000000-000
5|1073872901|3|Application|4516|20100615130251.000000-000
5|1073872901|3|Application|4517|20100615130251.000000-000
5|1073872901|3|Application|4518|20100615130251.000000-000
5|1073872901|3|Application|4519|20100615130251.000000-000
5|1073872901|3|Application|4520|20100615130251.000000-000
5|1073872901|3|Application|4521|20100615130251.000000-000
34|1073872930|3|Application|4522|20100615130251.000000-000
34|1073872930|3|Application|4523|20100615130251.000000-000
.....

Modificando un poco la query que hacía al server por WMI llegué a obtener todos los Eventos del visor de sucesos de un windows que tuvieran id=4625 (loguin erroneo) del registro de seguridad:

# wmic -U USUARIO%PASSWORD //HOSTNAME "select EventCode,EventIdentifier,EventType,TimeGenerated from Win32_NTLogEvent where EventCode='4625' AND Logfile='security'" 


Pero yo en nagios quería monitorear los loguins erroneos del día actual, entonces quedó así:


#HOY=`date +%d/%m/%Y` 
# wmic -U USUARIO%USUARIO //HOSTNAME "select EventCode,EventIdentifier,EventType,TimeGenerated from Win32_NTLogEvent where EventCode='4625' AND Logfile='security' AND TimeGenerated>='$HOY'"


Inicialmente la consulta comenzaba pero se cortaba, así que borré el visor de sucesos de seguridad de windows e hice un par de logueos erroneos para que aparezcan y aparecieron correctamente:

CLASS: Win32_NTLogEvent
EventCode|EventIdentifier|EventType|Logfile|RecordNumber|TimeGenerated
4625|4625|5|Security|2774019|20140103151300.184621-000
4625|4625|5|Security|2774020|20140103151325.320732-000
4625|4625|5|Security|2774027|20140103151335.353332-000
4625|4625|5|Security|2774047|20140103153339.520120-000
4625|4625|5|Security|2774048|20140103153339.535719-000


Una vez obtenido el comando correcto armamos el script para testear los visores de sucesos de windows con nagios:


# vi check_wmi_eventWindows.sh

#!/bin/bash
#
# Script creado el 03-01-2013 por Hernán Tirado
# Descripción: Chequea por WMI el visor de sucesos de windows del día actual
#              Verifica si hay mas de 10 loguins erroneos en el visor de sucesos => Critical
#              Verifica si hay mas de 5 loguins erroneos en el visor de sucesos => Warning
#
# NOTA:
#       Tener en cuenta que si el visor de suscesos es muy largo la query tarda y se corta
#
#       Setear las variables de entorno antes de ejecutarlo.

################## INICIO DE CONFIGURACION DE VARIABLES
# Ruta de ubicación del comando wmic:
WMIC=/usr/bin/wmic
# Fecha de HOY:
HOY=`date +%d/%m/%Y`
# Usuario administrador del windows:
USER=
# Contraseña del usuario administrador de windows:
PASSWORD=
# Nombre de host ó ip del windows:
HOST=jdeenterprise
# Tipo de Visor de Suceso (Application, Security, Setup, System):
EVENT_TYPE='security'
# Tipo de Evento (Ej: 4625 testea loguins erroneos):
ID_EVENTO=4625
################## FIN DE CONFIGURACION DE VARIABLES

# Ejecución del comando WMIC:
CANT_ERRONEA=`$WMIC -U $USER%$PASSWORD //$HOST "select EventCode,EventIdentifier,EventType,TimeGenerated from Win32_NTLogEvent where EventCode='$ID_EVENTO' AND Logfile='$EVENT_TYPE' AND TimeGenerated>='$HOY'" | grep -v CLASS | grep -v Event | wc -l`
# Testeamos los valores que devuelve, si:
# CANT_ERRONEA <= 5   =>  OK       (exit 0)
# CANT_ERRONEA  > 5   =>  WARNING  (exit 1)
# CANT_ERRONEA  > 10  =>  CRITICAL (exit 2)

if [ $CANT_ERRONEA -lt 5 ]; then
{
 echo OK - Cantidad de Logins Erroneos = $CANT_ERRONEA;
 exit 0;
}
fi
if [ $CANT_ERRONEA -gt 10 ]; then
{
 echo CRITICAL - Cantidad de Logins Erroneos = $CANT_ERRONEA;
 exit 1;
}
fi
if [ $CANT_ERRONEA -gt 4 ]; then
{
 echo WARNING - Cantidad de Logins Erroneos = $CANT_ERRONEA;
 exit 1;
}
fi


En el commands de nagios agregamos lo siguiente:

# vi /etc/nagios/commands.cfg

define command{
command_name check_wmi_eventWindows.sh
command_line $USER1$/check_wmi_eventWindows.sh
}


En el services de nagios agregamos lo siguiente:

# vi /etc/nagios/services.cfg:

define service{
use                                     generic-service,srv-pnp
host_name                          nombre_de_host
service_description             Check_Bad_Logins
check_command                 check_wmi_eventWindows.sh
}


Chequeamos la config de nagios y si no da errores, reiniciamos el servicio:

# bin/nagios -v /etc/nagios.cfg
...
Total Warnings: 0
Total Errors:   0
...

# /etc/init.d/nagios reload
Running configuration check...done.
Reloading nagios configuration...done


NOTA: Tener en cuenta que en Windows debe estar habilitada la auditoría de logins erroneos. En esta entrada del blog les dejo como habilitarlo: http://www.redes-seguridad.com.ar/2014/01/logins-erroneos-en-windows-event-viewer.html


jueves, 2 de enero de 2014

Obtener Serial Number Remoto con wmic

En este post ya hemos visto como obtener el serial number de nuestra pc con wmic: 

http://www.redes-seguridad.com.ar/2011/08/obtener-serial-number-del-server-por.html

También podemos hacer lo mismo para obtener el serial number remoto por WMI con el siguiente comando:

C:\Users\morsa>wmic /user:administrador /node:nombre_pc_remota bios get serialnumber
Escriba la contraseña :**********
SerialNumber
AGXT8T2


lunes, 23 de diciembre de 2013

Script que testea intentos fallidos de SSH

Script en Bash: 
#!/bin/bash
# Script que testea intentos fallidos de
# 0=OK
# 1=WARNING
# 2=CRITICAL
# 3=UNKNOWN
HOY=`date "+%b %d"`
LOG=/var/log/auth.log
CANT_FALLIDOS=`cat $LOG |grep "Authentication failed"|grep "$HOY" | wc -l`
if [ $CANT_FALLIDOS -gt 15 ]; then
{
 echo "CRITICAL - Intentos fallidos:$CANT_FALLIDOS";
 exit 2;
}
fi
if [ $CANT_FALLIDOS -gt 10 ]; then
{
 echo "WARNING - Intentos fallidos:$CANT_FALLIDOS";
 exit 1;
}
fi
echo "OK - Intentos fallidos:$CANT_FALLIDOS";
exit 0;

Monitoreamos NRPE, editamos el services.cfg del server de nagios:

vi /etc/nagios/services.cfg
define service{
use                             generic-service
host_name                  ar-stf-vm-xen-1-crp-3
service_description     SSH_Fail_Login
check_command        check_nrpe!check_ssh_auth
}

Editamos en el server que queremos monitorear el nrpe.conf y luego reiniciamos el servicio:

vi /usr/local/apps/nagios/etc/nrpe.cfg
command[check_ssh_auth]=/usr/local/apps/nagios/libexec/check_ssh_auth

miércoles, 27 de noviembre de 2013

Ruta estática en Linux Centos

Si tenemos configurada la interface eth0, entonces tendremos que agregar el siguiente archivo, si quisieramos agregar una ruta a la eth1 usaríamos lo mismo pero llamarlo route-eth1 y así sucesivaente:

Editamos el archivo y colocamos también dentro de el los siguientes campos: direcciónN, netmaskN, gatewayN, donde N corresponde al número de interface como el siguiente ejemplo:

[root@server ~]# vi /etc/sysconfig/network-scripts/route-eth0
ADDRESS0=192.168.1.0
NETMASK0=255.255.255.0
GATEWAY0=110.120.130.140

Reiniciamos el servicio de red y listo:

[root@server ~]# /etc/init.d/network restart

Probamos la conectividad a la nueva red:

[root@server ~]# ping 192.168.1.1
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=254 time=13.3 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=254 time=9.94 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=254 time=10.4 ms


miércoles, 6 de noviembre de 2013

Remplazando Texto en Unix

Con el comando sed:

sed "s/hola/chau/g" morsa.txt > morsa.tmp; mv morsa.tmp morsa.txt


Con perl:

perl -pi -e 's/hola/chau/g' morsa.txt