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'"

viernes, 22 de febrero de 2013

Monitoring Resource Utilization with Cacti on Ubuntu 10.04 (Lucid)

From: http://library.linode.com/server-monitoring/cacti/ubuntu-10.04-lucid

Prerequisites

Set the Timezone

Begin by setting the timezone of your server if it isn't already set. Set your server to your timezone or to that of the bulk of your users. If you're unsure which timezone would be best, consider using Universal Coordinated Time (or UTC, ie. Greenwich Mean Time). Keep in mind that Cacti uses the timezone set on the monitoring machine when generating its graphs. Run the following command to set the timezone:
 
dpkg-reconfigure tzdata

Enable the Universe Repositories

First, make sure you have the universe repositories enabled on your system. Your /etc/apt/sources.list should resemble the following (you may have to uncomment or add the universe lines):
File:/etc/apt/sources.list
 
## main & restricted repositories
deb http://us.archive.ubuntu.com/ubuntu/ lucid main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid main restricted

deb http://security.ubuntu.com/ubuntu lucid-security main restricted
deb-src http://security.ubuntu.com/ubuntu lucid-security main restricted

## universe repositories - uncomment to enable
deb http://us.archive.ubuntu.com/ubuntu/ lucid universe
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid universe

deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates universe
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-updates universe

deb http://security.ubuntu.com/ubuntu lucid-security universe
deb-src http://security.ubuntu.com/ubuntu lucid-security universe

If you had to enable new repositories, issue the following command to update your package lists:
 
apt-get update
apt-get upgrade

Installing Dependencies

Before installing Cacti we must install a few basic dependencies that are critical to the installation of Cacti. Cacti uses the Simple Network Management Protocol (SNMP) to poll the devices it tracks. We'll need to install the snmpd and snmp packages to allow Cacti to use SNMP. Cacti's web interface requires a database, web server, and PHP to be installed. Issue the following command to install these prerequisites:
 
apt-get install snmpd snmp mysql-server apache2 libapache2-mod-php5 \
php5-mysql php5-cli php5-snmp

You will need to create a password for the root user of your MySQL database during the installation. After the installation completes, be sure to run mysql_secure_installation to disable some of MySQL's less secure components. Also consider reading our MySQL installation guide for configuration recommendations.
The above command will additionally install the Apache web server. Consider our documentation on installing the Apache HTTP server for more information regarding this server. Additionally Cacti can function with alternate web server configurations, including Apache with PHP running as a CGI process and with nginx running PHP as a FastCGI process.

Configuring SNMPD

SNMPD binds to localhost by default. If you only plan on using Cacti to monitor your Linode, you do not need to modify /etc/default/snmpd. However, if you'd like to use Cacti to monitor more than one host, you'll need to edit the /etc/default/snmpd file. Open the file and find the line that starts with SNMPDOPTS= and remove 127.0.0.1 at the end. This line should now look like this:
 File:/etc/default/snmpd
 
SNMPDOPTS='-Lsd -Lf /dev/null -u snmp -g snmp -I -smux -p /var/run/snmpd.pid'

At this point SNMPD is configured to listen on all interfaces. Now we'll open /etc/snmp/snmpd.conf to establish which host is trusted to receive data.
We'll create an SNMP "community" to help identify our group of devices for Cacti. In this instance, our hostname is "bucknell.org", so we've named the community "Bucknell". The community name choice is up to the user. Locate the section of snmpd.conf that begins with com2sec and make sure the readonly line is the only uncommented line. This section of the file should now look like this:
File:/etc/snmp/snmpd.conf

#com2sec paranoid  default         public
com2sec readonly  localhost        Bucknell
#com2sec readwrite default         private

If you want a remote machine to connect to Cacti, replace "localhost" with the IP address of the remote machine.
You need to restart snmpd any time /etc/snmp/snmpd.conf is modified. Run the following command after closing the file:
/etc/init.d/snmpd restart

Installing Cacti

To install the Cacti package from the distribution software repositories, issue the following command:
apt-get install cacti
You will be presented with several prompts during this installation. On the "libphp-adodb" prompt you can safely select "Ok". During the "Configuring Cacti" prompt, make sure to select "Apache2". You will be presented with an additional "Configuring cacti" prompt that will ask if you'd like to configure your database with dbconfig-common. Select "Yes" and continue. On the MySQL prompt, enter the root password you created earlier. On the next screen, either create your own password for cacti's database access, or leave it blank for it to automatically generate one for you.
From here we'll continue configuring Cacti through the browser. Visit the domain you have pointed at your Linode or your Linode's IP address, and add /cacti. Follow the instructions shown on each page. Make sure to select RRDTool 1.2.x in the "RRDTool Utility Version" drop down. You should be able to continue through these pages into the login page without alteration.
At the login screen, enter admin/admin for the username/password combination. You'll be prompted to change your password on the next screen. At this point, Cacti is installed and ready to be configured.

Configuring Cacti

At this point Cacti will contain an entry for localhost, which we'll need to modify. Click the "Console" tab in the top left corner, and select "Create Devices for network". Click the "Localhost" entry to begin making the needed changes. Select the Host Template drop down and pick the "ucd/net SNMP Host". Scroll down to SNMP Options and click the drop down box for SNMP Version, picking "Version 1". Enter "Bucknell" (or the community name you created above) in the box for the "SNMP Community" field. The "Associated Graph Templates" section allows you to add additional graphs. Hit "Save" to keep the changes.
Click "Settings" under "Configuration" and set your "SNMP Version" to "Version 1" in the drop down box. Type the name of your community for the "SNMP Community" (in this example, "Bucknell") and save.

Configuring Client Machines

This section is optional and for those looking to use Cacti to monitor additional devices. These steps are written for Debian-based distributions, but with modification, they will work on any flavor of Linux. You will need to follow these instructions for each client machine you'd like to monitor with Cacti. Client machines need an SNMP daemon in order to serve Cacti information. First, install snmp and snmpd on the client:
apt-get install snmp snmpd
Next we'll need to modify the /etc/snmp/snmpd.conf file with the name of our community. Run the following commands to backup your existing snmpd.conf file and replace the contents with the name of your community:
mv /etc/snmp/snmpd.conf /etc/snmp/old.snmpd.conf
echo "rocommunity mycommunity" > /etc/snmp/snmpd.conf
Note that the format is "rocommunity community_name", where community_name is the name of the community you originally used with Cacti. Next, we'll open the /etc/default/snmpd file and remove the binding on localhost. Like the "Configuring SNMP" section above, you'll want to find the line that begins with SNMPDOPTS and remove the reference to 127.0.0.1 at the end. This line should now resemble the one below:
File:/etc/default/snmpd
SNMPDOPTS='-Lsd -Lf /dev/null -u snmp -g snmp -I -smux -p /var/run/snmpd.pid'
Finally, restart the SNMP daemon to push the changes you've made to these files:
/etc/init.d/snmpd restart
At this point your machine is ready for polling. Go into the Cacti interface to add the new "Device". Under the "Console" tab, select "New Graphs" and then "Create New Host". Enter the pertinent information in the fields required. Make sure to select "Ping" for "Downed Device Detection". Additionally, ensure that you've typed the right community name in the "SNMP Community" field. Click the "create" button to save your configuration. On the "save successful" screen, select your newly created device and from the drop down next to "Choose an Action" select "Place on a Tree" and then click "go". Hit "yes" on the next screen. On the "New Graphs" screen, you'll be able to create several different types of graphs of your choice. Follow the on-screen instructions to add these graphs to your tree.

Using the Spine Polling Daemon

By default, Cacti uses a PHP script to poll the devices it tracks. "Spine" is a faster replacement for the default polling script written in C++. Installing Spine is relatively easy and a good idea if you plan on keeping track of many hosts. Begin the Spine installation by running the following command
apt-get install cacti-spine
After the installation completes, go back to the Cacti administrative panel and click "Settings" under "Configuration". Click the "Paths" tab and check to see that Cacti found your spine binary correctly. Click the "Poller" tab and choose "Spine" from the drop-down for "Poller Type". Click "Save" to keep these changes. You are now successfully using Spine.