lunes, 12 de mayo de 2014

Mikrotik Wan FailOver

Texto extraido de: http://www.arg-wireless.com.ar/index.php?topic=1226.0

Failover (Conmutación por error) cuando un enlace deja de funcionar por cualquier motivo y automáticamente cambia al enlace de backup o redundancia para seguir funcionando.

En este caso tendríamos dos proveedores de servicio (Por ejemplo Arnet+Fibertel), y por un X motivo el primer servicio deja de funcionar, automáticamente se redireccionara todo al servicio secundario o backup.

Configuración Funcional a partir de Mikrotik RouterOS v3.30 (Versión Actual v5.24)

Paso a Paso:

Para iniciar con la configuración correspondiente vamos a primero crear reglas de salidas de Internet en IP ► Firewall ► NAT, configuraremos las interfaces correspondientes con las direcciones IP correspondientes.

/ip firewall nat 
add chain=srcnat out-interface="1-DIGICEL" action=masquerade comment="Internet - Proveedor Principal" 
add chain=srcnat out-interface="2-CABLEONDA" action=masquerade comment="Internet - Proveedor Secundario (Backup)"
 
Luego podemos por ejemplo llevar un conteo de las caídas de conexión con
 la opción de enviar un mail si se encuentra la misma (Mails de Alerta),
 configuración para:

Hotmail:
 
/tool e-mail 
set server=65.55.96.11 username="MAIL HOTMAIL" password="CONTRASEÑA" from=
 
Gmail:
 
/tool e-mail 
set server=74.125.134.108 username="MAIL GMAIL" password="CONTRASEÑA" from=
 
Luego continuaremos creando una serie de script, vamos a ir a System ► Scripts ► "+"

Name= ISP1-UP 
Policy= read,write,policy,test 
Source=
     
/ip firewall nat set [find comment="Internet - ISP1"] disabled=no 
/ip firewall nat set [find comment="Internet - ISP2"] disabled yes 
: log info "::::::::::::::: TRAFICO SALIENDO POR PROVEEDOR PRINCIPAL 1 :::::::::::::::" 

 
Name= ISP2-UP 
Policy= read,write,policy,test 
Source= 
 
/ip firewall nat set [find comment="Internet - ISP1"] disabled=yes 
/ip firewall nat set [find comment="Internet - ISP2"] disabled=no 
: log info "::::::::::::::: TRAFICO SALIENDO POR PROVEEDOR SECUNDARIO :::::::::::::::" 
 
Name= ISP1-DOWN 
Policy= read,write,policy,test 
Source= 
 
/ip firewall nat set [find comment="Internet - ISP1"] disabled=yes 
/ip firewall nat set [find comment="Internet - ISP2"] disabled=no 
: log info "::::::::::::::: TRAFICO SALIENDO POR PROVEEDOR SECUNDARIO, PROVEEDOR PRIMARIO FUERA DE SERVICIO :::::::::::::::" 
/tool netwatch set [find comment="SALIDA ISP1"] disabled=yes 
/tool netwatch set [find comment="SALIDA ISP2"] disabled=no 
/tool e-mail send to="DIRECCION DE MAIL" subject="Proveedor 1 Fuera de Servicio" body="Proveedor principal dejo de funcionar" 
:log info "::::::::::::::: ALERTA ENVIADA :::::::::::::::" 
 
Name= ISP2-DOWN 
Policy= read,write,policy,test 
Source= 
 
/ip firewall nat set [find comment="Internet - ISP1"] disabled=no 
/ip firewall nat set [find comment="Internet - ISP2"] disabled=yes 
: log info "::::::::::::::: TRAFICO SALIENDO POR PROVEEDOR PRINCIPAL, PROVEEDOR SECUNDARIO FUERA DE SERVICIO :::::::::::::::" 
/tool netwatch set [find comment="SALIDA ISP2"] disabled=yes 
/tool netwatch set [find comment="SALIDA ISP1"] disabled=no 
/tool e-mail send to="DIRECCION DE MAIL" subject="Proveedor 2 Fuera de Servicio" body="Proveedor 2 Dejo de funcionar" 
:log info "::::::::::::::: ALERTA ENVIADA :::::::::::::::" 
 
Luego para terminar creamos las reglas de Netwatch:
 
/tool netwatch 
add comment="SALIDA ISP1" host=74.125.47.104 down-script="ISP1-DOWN" up-script="ISP1-UP" 
add comment="SALIDA ISP2" host=98.139.183.24 down-script="ISP2-DOWN" up-script="ISP2-UP"      

viernes, 11 de abril de 2014

Mikrotik Dynamic DNS Update Script for No-IP DNS


1. Create a new script named no-ip_ddns_update
The following permissions are required for this script to run:
  • write
  • test
  • read

2. Paste the source code that appears below. Edit the user, password, hostname and interface info to match your setup.

# No-IP automatic Dynamic DNS update

#--------------- Change Values in this section to match your setup ------------------

# No-IP User account info
:local noipuser "your_no-ip_user"
:local noippass "your_no-ip_pass"

# Set the hostname or label of network to be updated.
# Hostnames with spaces are unsupported. Replace the value in the quotations below with your host names.
# To specify multiple hosts, separate them with commas.
:local noiphost "hostname.no-ip.net"

# Change to the name of interface that gets the dynamic IP address
:local inetinterface "your_external_interface"

#------------------------------------------------------------------------------------
# No more changes need

:global previousIP

:if ([/interface get $inetinterface value-name=running]) do={
# Get the current IP on the interface
   :local currentIP [/ip address get [find interface="$inetinterface" disabled=no] address]

# Strip the net mask off the IP address
   :for i from=( [:len $currentIP] - 1) to=0 do={
       :if ( [:pick $currentIP $i] = "/") do={ 
           :set currentIP [:pick $currentIP 0 $i]
       } 
   }

   :if ($currentIP != $previousIP) do={
       :log info "No-IP: Current IP $currentIP is not equal to previous IP, update needed"
       :set previousIP $currentIP

# The update URL. Note the "\3F" is hex for question mark (?). Required since ? is a special character in commands.
       :local url "http://dynupdate.no-ip.com/nic/update\3Fmyip=$currentIP"
       :local noiphostarray
       :set noiphostarray [:toarray $noiphost]
       :foreach host in=$noiphostarray do={
           :log info "No-IP: Sending update for $host"
           /tool fetch url=($url . "&hostname=$host") user=$noipuser password=$noippass mode=http dst-path=("no-ip_ddns_update-" . $host . ".txt")
           :log info "No-IP: Host $host updated on No-IP with IP $currentIP"
       }
   }  else={
       :log info "No-IP: Previous IP $previousIP is equal to current IP, no update needed"
   }
} else={
   :log info "No-IP: $inetinterface is not currently running, so therefore will not update."
}
 
 
 
3. Create a new scheduler entry to run this script every 5 mins. 
 
/system scheduler add comment="Update No-IP DDNS" disabled=no interval=5m \
name=no-ip_ddns_update on-event=no-ip_ddns_update policy=read,write,test 

martes, 18 de marzo de 2014

Comprobar Conecciones SIP

Para comprobar conecciones SIP con NMAP utilizamos el siguiente comando en Linux

$ sudo nmap -v -sU 192.168.5.9 -p 5060


Starting Nmap 6.40 ( http://nmap.org ) at 2014-03-18 15:22 EST
Initiating Ping Scan at 15:22
Scanning 192.168.5.9 [4 ports]
Completed Ping Scan at 15:22, 0.11s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 15:22
Completed Parallel DNS resolution of 1 host. at 15:22, 0.06s elapsed
Initiating UDP Scan at 15:22
Scanning 192.168.5.9 [1 port]
Completed UDP Scan at 15:22, 0.77s elapsed (1 total ports)
Nmap scan report for 192.168.5.9
Host is up (0.074s latency).
PORT     STATE         SERVICE
5060/udp open|filtered sip


Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 1.01 seconds
           Raw packets sent: 6 (208B) | Rcvd: 1 (28B)


miércoles, 6 de noviembre de 2013

Zoneminder Repair Logs Table.

En Consola Entrar a la base se datos Mysql zm

# mysql -u root -p -D zm

CHECK TABLE Logs;

REPAIR TABLE Logs;


exit

reboot

martes, 22 de octubre de 2013

Configurar FAIL2BAN Elastix 2.4


Gracias, muy completo tutorial.
fail2ban
Hola amigos, ahora veremos un tema muy importante de seguridad para aminorar un poco el riesgo de hackeo en nuestros conmutadores basados en Elastix con extensiones SIP remotas sin VPN.
La solución se llama fail2ban y funciona muy sencilla pero inteligentemente. Fail2ban revisa los registros de las aplicaciones y si encuentra alguna condición que parezca un ataque de fuerza bruta, adivinar al azar usuario y contraseña, agregará una línea de bloqueo en nuestro iptables para negarle la conexión a la IP que nos intenta hackear. ¡Muy sencillo, pero efectivo!
Dicho lo anterior, tenemos 4 cosas importantes por hacer:
  1. Revisar que iptables esté funcionado
  2. Configurar Asterisk para que guarde logs en un archivo específico
  3. Configurar y ejecutar fail2ban
  4. Probar que funcione

Como root en tu sistema, deberás de revisar que iptables esté funcionado y que esté configurado para arrancar en cada momento.
service iptables status
El cortafuegos está detenido.
Lo anterior quiere decir que el firewall está detenido. Si acabas de instalar tu sistema recomiendo que revises que no existan reglas cargadas y que la política esté en ACCEPT.
iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Si tienes una salida parecida a la anterior, quiere decir que no hay reglas y que estás permitiendo todo el tráfico.
Ahora tendremos que guardar esas reglas y encender el firewall
service iptables save
Guardando las reglas del cortafuegos a /etc/sysconfig/iptab[ OK ]
service iptables start
Expurgar reglas del cortafuegos: [ OK ]
Configuración de cadenas a la política ACCEPT: filter [ OK ]
Descargando módulos iptables: [ OK ]
Aplicando reglas del cortafuegos iptables: [ OK ]
Ahora ya están cargadas las reglas en los archivos del sistema y podemos consultarlas de la siguiente forma:
service iptables status
Tabla: filter
Chain INPUT (policy ACCEPT)
num target prot opt source destination
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
Finalmente le decimos al sistema que vuelva a cargar estas reglas tras un posible reinicio.
chkconfig iptables on

Asterisk puede cambiar la forma en la que reporta los eventos, esto se realiza en el archivo/etc/asterisk/logger.conf. Deberás editarlo y agregar las siguientes líneas:
Justo arriba de la sección [logfiles] poner las siguientes dos líneas que cambian el formato de la hora reportada:
[general]
dateformat=%F %T
Al final del archivo, dentro de la sección [logfiles], deberás de colocar la siguiente línea:
fail2ban => notice
Posteriormente guardas y le pides a asterisk que refresque la configuración:
asterisk -rx 'module reload logger'

Ésta es la parte más interesante. Fail2ban ya se encuentra instalado en un sistema Elastix 2.4, y si no está lo puedes instalar vía yum. Lo primero que tenemos que hacer es configurar el archivo/etc/fail2ban/filter.d/asterisk.conf
Éste es el contenido:
# /etc/fail2ban/filter.d/asterisk.conf
# Fail2Ban configuration file
#
#
# $Revision: 250 $
#
[INCLUDES]
# Read common prefixes. If any customizations available — read them from
# common.local
#before = common.conf
[Definition]
#_daemon = asterisk
# 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 “” can
# be used for standard IP/hostname matching and is only an alias for
# (?:::f{4,6}:)?(?P\S+)
# Values: TEXT
#
failregex = NOTICE.* .*: Registration from ‘.*’ failed for ” – Wrong password
NOTICE.* .*: Registration from ‘.*’ failed for ‘:.*’ – No matching peer found
NOTICE.* .*: Registration from ‘.*’ failed for ” – No matching peer found
NOTICE.* .*: Registration from ‘.*’ failed for ” – Username/auth name mismatch
NOTICE.* .*: Registration from ‘.*’ failed for ” – Device does not match ACL
NOTICE.* .*: Registration from ‘.*’ failed for ” – Peer is not supposed to register
NOTICE.* .*: Registration from ‘.*’ failed for ” – ACL error (permit/deny)
NOTICE.* .*: Registration from ‘.*’ failed for ” – Device does not match ACL
NOTICE.* failed to authenticate as ‘.*’$
NOTICE.* .*: No registration for peer ‘.*’ \(from \)
NOTICE.* .*: Host failed MD5 authentication for ‘.*’ (.*)
NOTICE.* .*: Failed to authenticate user .*@.*
NOTICE.* .*: Sending fake auth rejection for device .*\;tag=.*
# In Asterisk 1.8 use the same as above, but after add :.* before the single quote. This is because in Asterisk 1.8, the log file includes a port number which 1.4 did not.
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =
Si gustas puedes descargar el archivo completo desde aquí:
Ahora podemos configurar el archivo /etc/fail2ban/jail.conf para que active la inspección de la regla de asterisk. Busca el final de la sección [Default] y el inicio de la sección [ssh-iptables]. Deberás copiar y pegar este bloque de justo en ese lugar:
.
.
.
backend = auto
[asterisk-iptables]
enabled = true
filter = asterisk
action = iptables-allports[name=ASTERISK, protocol=all]
sendmail-whois[name=ASTERISK, dest=root, sender=fail2ban@localhost]
logpath = /var/log/asterisk/fail2ban
# This jail corresponds to the standard configuration in Fail2ban 0.6.
# The mail-whois action send a notification e-mail with a whois request
# in the body.
[ssh-iptables]
.
.
.
Si no te gustar estar editando, descarga el archivo ya completo:
Ahora iniciemos fail2ban y validemos que no existan errores de configuración:
service fail2ban start
Starting fail2ban: [ OK ]
Configura su arranque tras un reinicio:
chkconfig fail2ban on
Para saber si está corriendo fail2ban, podemos mostrar las reglas iptables y veremos secciones nuevas con la leyenda fail2ban:
service iptables status
Tabla: filter
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 fail2ban-SSH tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
2 fail2ban-ASTERISK all -- 0.0.0.0/0 0.0.0.0/0
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
Chain fail2ban-ASTERISK (1 references)
num target prot opt source destination
1 RETURN all — 0.0.0.0/0 0.0.0.0/0
Chain fail2ban-SSH (1 references)
num target prot opt source destination
1 RETURN all — 0.0.0.0/0 0.0.0.0/0

Ahora sí, ¿cómo saber que todo lo que hicimos tuvo un propósito? Bien, pues tendremos que probarlo. Descarga un softphone a una computadora cualquiera para realizar una prueba. Por lo general yo uso Zoiper, puedes usar la versión gratuita o bien adquirir la versión con el codec g.729.
Te recomiendo que lo instales en otra máquina diferente a la que estás usando en este momento porque, si todo funciona, perderás conexión con el servidor Elastix.
En el servidor Elastix puedes ejecutar el siguiente codiguito que te mostrará en pantalla cada 2 segundos las reglas iptables. De esta forma nos daremos cuenta cuando nos hayan bloqueado.
while [ true ] ; do clear ; service iptables status ; sleep 2 ; done
Ahora si, desde el equipo de pruebas, da click en la configuración de una cuenta SIP y escribe la ip de tu servidor. El usuario y password llénalos con teclazos al azar y listo, dale varias veces click en el botón de register.
Después de realizar el tercer intento de registro, ya no podrás alcanzar el servidor desde ese equipo, aun cuando le tires un ping.
Puedes ver cómo fail2ban agregó una línea bloqueando la ip de la máquina que usaste como atacante:
service iptables status
Tabla: filter
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 fail2ban-ASTERISK all -- 0.0.0.0/0 0.0.0.0/0
2 fail2ban-SSH tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
Chain fail2ban-ASTERISK (1 references)
num target prot opt source destination
1 DROP all — 192.168.2.52 0.0.0.0/0
2 RETURN all — 0.0.0.0/0 0.0.0.0/0
Chain fail2ban-SSH (1 references)
num target prot opt source destination
1 RETURN all — 0.0.0.0/0 0.0.0.0/0


Lindo, ¿no? Espero que les haya gustado esta guía, y sobre todo, ¡que les sea de mucha utilidad!

martes, 10 de septiembre de 2013

Nortel BCM Interoperability SIP - Asterisk

Using the following setup, I have sucessfully added a link between a BCM400 and TRIXBox via SIP

Cavaet: No "security" ie. passwords etc has been tested - this is an "internal" configuration.

BCM400
IP Address: 192.168.100.253
ViOP GW Licesnes (licensed for SIP/H323)
A station to make/recieve calls on - I used the example of ext 3185

BCM Element manager:
Resources/Telephony Resources/IP Trunks
Routing table
Name: Trixbox
Destination Digits: 83
Destination IP: 192.168.100.252
GW Type: Other
GW protocol: None
VoIP Protocol: SIP

SIP Settings:
Domain name: - this will append to the SIP URI "unknown" name
Call Signalling Port: 5060
Outgoing Transport: UDP

URI Map:
Unknown/Unknown = 3100 (this will add to the domain name in call setup for the call context ie. call-context=3100@test.domain.com)

Telephony/Lines/Active VoIP Lines
Set all lines to be part of Line Pool "C"

Telephone/LinePools
Pool C: add DN 3185 (to allow 3185 to be allowed to use that pool)

Telephony/Dialing Plan/
Routing
Route: 083
External number: 83
Pool: C

Destination Code:83
Normal Route: 083
Absorb Length: all

That is all that needs to be set to allow VoIP Calls to be made or recieved



Trix Box 2.2
Running on VMware-Server 1.0.3
Default installation
1x SIP phone connected via XLITE - ext8301
IP: 192.168.100.252

Add SIP Trunk:
Trunk Name: BCM400
Outbound Caller ID: 8300
Outgoing Dialing Rules: 31XX (dial this trunk for any call to extensions 31XX)
Outgoing Peer Details:
  • host=192.168.100.253
  • type=peer
Incomming Settings
User Context: from-trunk
User Details:
context=from-trunk
host=192.168.100.253
type=peer

Add an outbound route to send anything 31XX to BCM400 trunk

Add an inbound route to send anything from BCM400 trunk to extension 8301



Once this is done you will be able to call from the Trixbox extensions to the Nortel extensions
CLID will display correctly.

  • however*

making inbound calls from the BCM to the TRIX box will require you to allow all anonymous inbound connections
FreePBX/General Settings
Allow Anonymous Inbound Sip Calls = YES.

otherwise you will only get the IVR advising the number you have called is not in service.

martes, 6 de agosto de 2013

Change Elastix Web Admin Password

/usr/bin/sqlite3 /var/www/db/acl.db "UPDATE acl_user SET md5_password = '`echo -n newpass|md5sum|cut -d ' ' -f 1`' WHERE name = 'admin'"