Asterisk Logwatch


publicado por Víctor Villarreal en

3 comentarios

Introducción

En Asterisk pueden producirse variados eventos: algunos son informativos, otros son advertencias, y hasta pueden producirse errores. Todos estos eventos son registrados en ficheros log, como lo haría cualquier otro software.

Si bien, toda la información sobre los eventos se encuentra centralizada en un solo lugar, no es útil si estos ficheros no se revisan regularmente. Y es verdad que también es poco práctico tener que acceder a ellos y leerlos en busca de algo interesante.

Este artículo brinda la información necesaria y presenta un procedimiento para obtener un informe, resumen estadístico de prácticamente cualquier fichero log de un sistema, de forma periódica y por correo electrónico.

Al finalizar este artículo, Ud. podrá: Instalar, y configurar un sistema de análisis y reporte de logs, en sistemas GNU/Linux utilizando Logwatch; Personalizar o extender este software con el objetivo de agregar al informe, estadísticas de seguridad de Asterisk.

Materiales

Logwatch es un sistema personalizable de analisis de logs, desarrollado en Perl. Recorre todos y cada uno de los ficheros logs que se le especifiquen, mientras los parsea; al finalizar genera un reporte del analisis tipo resumen y hasta puede enviarlo por mail. Funciona sin problemas en la mayoria de los sistemas y en general viene preinstalado de base en muchas distribuciones de Linux. Esta es la página del proyecto.

Procedimiento

Para instalarlo en un sistema GNU/Linux basado en Debian, basta con ejecutar # apt-get install logwatch.

Si bien este software trae soporte de base para muchos servicios comunes como Login, Apache2, SSH, etc; es relativamente sencillo extenderlo para dar soporte a un servicio nuevo. La estructura básica de sus directorios y ficheros es como se muestra a continuación:

etc
| logwatch
|-- conf
|---- logfiles
|       asterisk.conf
|---- services
|       asterisk.conf
|-- scripts
|---- services
|       asterisk

Para comenzar, y situados en la carpeta /etc/logwatch creamos el fichero conf/logfiles/asterisk.conf.

# What actual file?  Defaults to LogPath if not absolute path....
#LogFile = /var/log/asterisk/full
LogFile = /var/log/asterisk/messages

# If the archives are searched, here is one or more line
# (optionally containing wildcards) that tell where they are...
#If you use a "-" in naming add that as well -mgt
#Archive = /var/log/asterisk/messages.*
#Archive = /var/log/asterisk/full.*

# Expand the repeats (actually just removes them now)
*ExpandRepeats

Luego, creamos el archivo conf/services/asterisk.conf.

# You can put comments anywhere you want to.  They are effective for the
# rest of the line.

# this is in the format of  = .  Whitespace at the beginning
# and end of the lines is removed.  Whitespace before and after the = sign
# is removed.  Everything is case *insensitive*.

# Yes = True  = On  = 1
# No  = False = Off = 0

Title = "asterisk"

# Which logfile group...
LogFile = asterisk

*RemoveHeaders

Por último, creamos el fichero scripts/services/asterisk.

#!/usr/bin/perl
# Copyright header...

use strict;
use Logwatch ':all';

my $Debug = $ENV{'LOGWATCH_DEBUG'} || 0;
my $Detail = $ENV{'LOGWATCH_DETAIL_LEVEL'} || 0;
my $IgnoreHost = $ENV{'asterisk_ignore_host'} || "";
my $DebugCounter = 0;

#
# Service check...
#
# No sense in running if 'asterisk' doesn't even exist on this system...
#unless (( -f "/usr/sbin/asterisk" ) or ( -f "/usr/local/sbin/asterisk")) {
#       exit (0);
#}

#
# some local vars...
#
my $LineCount = 0;
my %RegFailed = ();
my %RegSIP = ();
my %RegIAX = ();
my %Unreachables = ();

if ( $Debug >= 5 ) {
        print STDERR "\n\nDEBUG: Inside asterisk Filter \n\n";
        $DebugCounter = 1;
}

#
# Parsing routine...
#
while (defined(my $ThisLine = <STDIN>)) {
        if ( $Debug >= 5 ) {
        print STDERR "DEBUG($DebugCounter): $ThisLine";
                $DebugCounter++;
        }
        chomp($ThisLine);

        if ( my ($Exten,$User,$Host) = ($ThisLine =~ m/Registration from '"(\S+)" (\S+) failed for '(\S+)'/) ) {
                $RegFailed{$Host}{$Exten}++;
        }
        elsif ( my ($Peer) = ($ThisLine =~ m/Peer '(\S+)' is now UNREACHABLE!/) ) {
                $Unreachables{$Peer}++;
        }
        elsif ( my ($Peer,$Host) = ($ThisLine =~ m/Registered SIP '(\S+)' at (\S+)/) ) {
                $RegSIP{$Peer}{$Host}++;
        }
        elsif ( my ($Peer,$Host,$Port) = ($ThisLine =~ m/Registered IAX2 '(\S+)' \(AUTHENTICATED\) at (\S+):(\S+)/) ) {
                $RegIAX{$Peer}{$Host}++;
        }
}

#
# Printing results...
#
if (keys %RegSIP) {
        print "\nSIP Registrations :\n";
        foreach my $ThisHost (keys %RegSIP) {
                print "    $ThisHost:\n";
                foreach my $ThisUser (keys %{$RegSIP{$ThisHost}}) {
                        print "        $ThisUser: $RegSIP{$ThisHost}{$ThisUser} Time(s)\n";
                }
        }
}

if (keys %RegIAX) {
        print "\nIAX2 Registrations :\n";
        foreach my $ThisHost (keys %RegIAX) {
                print "    $ThisHost:\n";
                foreach my $ThisUser (keys %{$RegIAX{$ThisHost}}) {
                        print "        $ThisUser: $RegIAX{$ThisHost}{$ThisUser} Time(s)\n";
                }
        }
}

if (keys %RegFailed) {
        print "\nRegistrations failed from :\n";
        foreach my $ThisHost (keys %RegFailed) {
                print "    $ThisHost:\n";
                foreach my $ThisUser (keys %{$RegFailed{$ThisHost}}) {
                        print "        $ThisUser: $RegFailed{$ThisHost}{$ThisUser} Time(s)\n";
                }
        }
}

if (keys %Unreachables) {
        print "\nUnreachables peers:\n";
        foreach my $ThisPeer (keys %Unreachables) {
                print "    $ThisPeer: $Unreachables{$ThisPeer} Time(s)\n";
        }
}

Pruebas y resultados

Si todo ha ido bien, podremos ejecutar:

root@asterisk:/etc/logwatch# logwatch --print --logfile asterisk
  ################### Logwatch 7.3.1 (09/15/06) ####################
        Processing Initiated: Sun Mar  4 02:37:04 2012
        Date Range Processed: yesterday
                              ( 2012-Mar-03 )
                              Period is day.
      Detail Level of Output: 5
              Type of Output: unformatted
           Logfiles for Host: asterisk
  ##################################################################

 --------------------- asterisk Begin ------------------------

 SIP Registrations :
     PT015:
         192.168.10.60: 1 Time(s)
     8009:
         192.168.10.90: 1 Time(s)
     PT014:
         192.168.10.69: 2 Time(s)
     8008:
         192.168.10.99: 1 Time(s)
     8011:
         192.168.10.90: 1 Time(s)
     PT009:
         192.168.10.75: 1 Time(s)
     PT101:
         192.168.10.30: 1 Time(s)
     quadro6l:
         200.xxx.xxx.51: 1 Time(s)

 IAX2 Registrations :
     200:
         127.0.0.1: 3141 Time(s)

 Registrations failed from :
     188.138.112.31:
         8120: 3522 Time(s)

 Unreachables peers:
     8009: 1 Time(s)
     pbx-desarrollo: 1 Time(s)
     PT011: 1 Time(s)
     8010: 1 Time(s)
     PT007: 1 Time(s)
     PT012: 1 Time(s)
     PT008: 2 Time(s)
     RCP002: 1 Time(s)
     PT013: 1 Time(s)
     PT019: 2 Time(s)
     8011: 1 Time(s)
     RCP001: 1 Time(s)
     PT005: 1 Time(s)
     PT009: 2 Time(s)
     PT002: 2 Time(s)
     PT015: 2 Time(s)
     PT003: 2 Time(s)
     PT017: 2 Time(s)
     PT014: 2 Time(s)
     8008: 1 Time(s)
     PT101: 2 Time(s)
     PT004: 2 Time(s)
     PT010: 1 Time(s)
     PT006: 2 Time(s)
     PT001: 1 Time(s)
     PT016: 2 Time(s)

 ---------------------- asterisk End -------------------------


 ###################### Logwatch End #########################

 root@asterisk:/etc/logwatch#

Vemos los cuatro informes que devuelve nuestro script: 'SIP Registrations' que es un listado con las extensiones que se registraron, desde que IP y cuantas veces; 'IAX2 registrations' que es el mismo listado anterior, pero para extensiones con tecnología IAX2; 'Registrations Failed' que es un listado de las IP que intentaron registrarse y fallaron en nuestra PBX, con qué extensiones y cuantas veces.

Notas

Por una cuestion de practicidad, compilamos todos los fichero anteriores en un archivo comprimido. Para instalarlos en vuestro sistema, solo tenemos que situarnos en la carpeta /etc/logwatch/ y ejecutar # tar -xzf asterisk-logwatch.tar.gz. Luego, solo tenemos que personalizarlo segun nuestras necesidades y deseos.

Descargar asterisk-logwatch.tar.gz

La configuración está fuera del 'scope' de este artículo. Por favor, para mas información sobre el uso de Logwatch visita la página web del proyecto o ejecuta # man logwatch.

Para asegurarnos que el script pueda generar todas las estadísticas, verificar que los mensajes ERROR, WARNING, NOTICE y VERBOSE se estén escribiendo en el fichero de log de Asterisk.

Basado en el artículo "Monitor Asterisk with Logwatch" de Mark Berry.

3 comentarios

Deja un comentario