+ All Categories
Home > Documents > Maquet Avo Ip Manual

Maquet Avo Ip Manual

Date post: 03-Oct-2015
Category:
Upload: venuss-vega
View: 256 times
Download: 8 times
Share this document with a friend
Description:
Instalar VOIP
Popular Tags:
49
INSTALACIÓN DE UNA MAQUETA DE VOIP OPENSIPS+ASTERISK AUTENTICANDO CONTRA UN ENTORNO RADIUS+LDAP >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>> INTRODUCCION <<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Veremos como configurar una maqueta consistente en un entorno de telefonía IP (VoIP) basado en opensips + ASTERISK, autenticando contra un servidor RADIUS (elegimos FreeRadius) que a su vez usara otro LDAP (elegimos OpenLdap), montaje típico en cierto tipo de instalaciones. En principio instalaremos los cuatro servidores en la misma máquina como maqueta de pruebas para conocer a fondo su funcionamiento y todos los aspectos implicados, desde los puramente relacionados con VoIP y el protocolo SIP, su conexión con un entorno de telefonía analógica tradicional, y la autenticación y gestión de usuarios/extensiones del sistema. Los usuarios/extensiones realizarán el registro SIP principalmente en el servidor opensips. No obstante también contemplaremos el caso de que algunas extensiones realicen el registro en la PBX ASTERISK, como una prueba de concepto para explorar la posibilidad de que un rango de extensiones de nuestro plan de numeración (correspondientes por ejemplo a hardphones SIP) se registren directamente en ASTERISK, y aun así serán accesibles tanto desde el mundo SIP, como desde el analógico, y tendrán a su vez acceso a ambos. Para el registro en opensips basta que el usuario este definido de una de las tres formas siguientes: - fichero plano "users" del servidor FREERADIUS. - tablas correspondientes de la bd "radius" que definiremos en el mismo servidor, ya que lo dotaremos de soporte MySQL. - bd del servidor LDAP. El registro en ASTERISK necesitará que el usuario esté definido de una de las siguientes formas: - Localmente en el servidor ASTERISK configurando adecuadamente los ficheros "extensions.conf" y "sip.conf". - En la tabla "sipfriends" de la bd asterisk, ya que tambien activaremos en este servidor el soporte MySQL. Las password para ambos casos pueden residir en el entorno RADIUS-LDAP de alguna de las formas expresadas para opensips. El registro directo em ASTERISK puede ser útil como prueba de concepto de la posibilidad de integración con opensips de entornos donde tengamos una PBX propietaria como solución para hardphones VoIP, y queramos gestionar softphones SIP (u otros clientes) desde Internet con opensips: para ello sería necesario poder definir un SIP trunk en condiciones parecidas a lo que haremos con ASTERISK. Aunque es posible que quien utilice esta guía ya disponga de servidor/es radius/ldap, vamos a instalar en primer lugar la piedra angular de la solución de autenticación, un servidor LDAP y como frontend del mismo un servidor RADIUS. Esto nos ayudará a entender el mecanismo del Digest-HA1 utilizado para generar y comparar las passwords de los clientes de telefonía IP, así como los mecanismos de conexión entre el servidor radius y el ldap. Esto sería útil caso de tener ya funcionado el servidor LDAP, y necesitar configurar el servidor RADIUS, o para modificar el servidor LDAP si fuera necesario para integrar el entorno. Posteriormente realizaremos la instalación de un servidor opensips y luego la PBX ASTERISK. En ésta añadiremos la funcionalidad de los buzones de voz, con notificación al usuario cuando reciba un mensaje de voz. Por último hemos untilizado un mediagateway vyda para realizar las pruebas de interacción de todo el sistema. Con cuatro puertos analógicos, hemos configurado uno para conectar un teléfono convencional, y otro para conectar una extensión telefónica. Así hemos probados llamadas tanto entrantes como slientes SIP<->Analógicos.
Transcript
  • INSTALACIN DE UNA MAQUETA DE VOIP OPENSIPS+ASTERISK AUTENTICANDO CONTRA UN ENTORNO RADIUS+LDAP

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> INTRODUCCION >>>>>>>>>>>>>>>>>>>>>>>>>>>

    Veremos como configurar una maqueta consistente en un entorno de telefona IP (VoIP) basado en opensips + ASTERISK, autenticando contra un servidor RADIUS (elegimos FreeRadius) que a su vez usara otro LDAP (elegimos OpenLdap), montaje tpico en cierto tipo de instalaciones. En principio instalaremos los cuatro servidores en la misma mquina como maqueta de pruebas para conocer a fondo su funcionamiento y todos los aspectos implicados, desde los puramente relacionados con VoIP y el protocolo SIP, su conexin con un entorno de telefona analgica tradicional, y la autenticacin y gestin de usuarios/extensiones del sistema.

    Los usuarios/extensiones realizarn el registro SIP principalmente en el servidor opensips. No obstante tambin contemplaremos el caso de que algunas extensiones realicen el registro en la PBX ASTERISK, como una prueba de concepto para explorar la posibilidad de que un rango de extensiones de nuestro plan de numeracin (correspondientes por ejemplo a hardphones SIP) se registren directamente en ASTERISK, y aun as sern accesibles tanto desde el mundo SIP, como desde el analgico, y tendrn a su vez acceso a ambos.

    Para el registro en opensips basta que el usuario este definido de una de las tres formas siguientes:- fichero plano "users" del servidor FREERADIUS.- tablas correspondientes de la bd "radius" que definiremos en el mismo servidor, ya que lo dotaremos de soporte MySQL.- bd del servidor LDAP.

    El registro en ASTERISK necesitar que el usuario est definido de una de las siguientes formas:- Localmente en el servidor ASTERISK configurando adecuadamente los ficheros "extensions.conf" y "sip.conf".- En la tabla "sipfriends" de la bd asterisk, ya que tambien activaremos en este servidor el soporte MySQL.Las password para ambos casos pueden residir en el entorno RADIUS-LDAP de alguna de las formas expresadas para opensips.

    El registro directo em ASTERISK puede ser til como prueba de concepto de la posibilidad de integracin con opensips de entornos donde tengamos una PBX propietaria como solucin para hardphones VoIP, y queramos gestionar softphones SIP (u otros clientes) desde Internet con opensips: para ello sera necesario poder definir un SIP trunk en condiciones parecidas a lo que haremos con ASTERISK.

    Aunque es posible que quien utilice esta gua ya disponga de servidor/es radius/ldap, vamos a instalar en primer lugar la piedra angular de la solucin de autenticacin, un servidor LDAP y como frontend del mismo un servidor RADIUS. Esto nos ayudar a entender el mecanismo del Digest-HA1 utilizado para generar y comparar las passwords de los clientes de telefona IP, as como los mecanismos de conexin entre el servidor radius y el ldap. Esto sera til caso de tener ya funcionado el servidor LDAP, y necesitar configurar el servidor RADIUS, o para modificar el servidor LDAP si fuera necesario para integrar el entorno.

    Posteriormente realizaremos la instalacin de un servidor opensips y luego la PBX ASTERISK. En sta aadiremos la funcionalidad de los buzones de voz, con notificacin al usuario cuando reciba un mensaje de voz.

    Por ltimo hemos untilizado un mediagateway vyda para realizar las pruebas de interaccin de todo el sistema. Con cuatro puertos analgicos, hemos configurado uno para conectar un telfono convencional, y otro para conectar una extensin telefnica. As hemos probados llamadas tanto entrantes como slientes SIPAnalgicos.

  • Este es el esquema que queremos montar:

  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>AUTENTICACION>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    >>>>>>>>>>>>INSTALACION DE UN SERVIDOR LDAP CON SASL

  • # security ssf=1 update_ssf=112 simple_bind=64

    # Sample access control policy:# Root DSE: allow anyone to read it# Subschema (sub)entry DSE: allow anyone to read it# Other DSEs:# Allow self write access# Allow authenticated users read access# Allow anonymous users to authenticate# Directives needed to implement policy:# access to dn.base="" by * read# access to dn.base="cn=Subschema" by * read# access to *# by self write# by users read# by anonymous auth## if no access controls are present, the default policy# allows anyone and everyone to read anything but restricts# updates to rootdn. (e.g., "access to * by * read")## rootdn can always read and write EVERYTHING!

    TLSCipherSuite HIGH:MEDIUM:+SSLv2:+SSLv3:RSATLSCACertificateFile /usr/local/etc/openldap/cacerts/server.pemTLSCertificateFile /usr/local/etc/openldap/cacerts/server.pemTLSCertificateKeyFile /usr/local/etc/openldap/cacerts/server.keyTLSVerifyClient allow

    ######################################################################## BDB database definitions#######################################################################

    databasebdbsuffix "dc=tipx,dc=domain,dc=es"rootdn "cn=Manager,dc=tipx,dc=domain,dc=es"# Cleartext passwords, especially for the rootdn, should# be avoid. See slappasswd(8) and slapd.conf(5) for details.# Use of strong authentication encouraged.#rootpw {crypt}woasFTat5jTRYrootpw # The database directory MUST exist prior to running slapd AND # should only be accessible by the slapd and slap tools.# Mode 700 recommended.directory /usr/local/var/openldap-data# Indices to maintainindex objectClass eq---------------------------------------------------------------

    vi ldap.conf## LDAP Defaults#

    # See ldap.conf(5) for details# This file should be world readable but not world writable.

    BASE dc=tipx,dc=domain,dc=esURI ldap://localhost/

  • TLS_REQCERT neverTLS_CACERT /usr/local/etc/openldap/server.pem

    #SIZELIMIT 12#TIMELIMIT 15#DEREF never-------------------------------------------------Generar certificado autofirmado y clave RSA para servidor ldap:(Resaltar que:- Es muy importante usar como subject del certificado el DN del administrador del dominio LDAP en el formato especificado, si no, freeradius tendra problemas a la hora de autenticar.)

    mkdir cacertscd cacertsopenssl req -x509 -nodes -days 365 -subj '/DC=es/DC=domain/DC=tipx/CN=Manager'

    -newkey rsa:1024 -keyout server.key -out server.pemComprobar certificado

    openssl x509 -text -in server.pem-------------------------------------------------Poblar la base de datos de LDAPPor ejemplo, en /home/jose/ldap, crear los ficheros

    vi backend.tipx.local.ldif# Load dynamic backend modulesdn: cn=module,cn=configobjectClass: olcModuleListcn: moduleolcModulepath: /usr/lib/ldapolcModuleload: back_hdb

    # Database settingsdn: olcDatabase=hdb,cn=configobjectClass: olcDatabaseConfigobjectClass: olcHdbConfigolcDatabase: {1}hdbolcSuffix: dc=tipx,dc=domain,dc=esolcDbDirectory: /var/lib/ldapolcRootDN: cn=Manager,dc=tipx,dc=domain,dc=esolcRootPW: olcDbConfig: set_cachesize 0 2097152 0olcDbConfig: set_lk_max_objects 1500olcDbConfig: set_lk_max_locks 1500olcDbConfig: set_lk_max_lockers 1500olcDbIndex: objectClass eqolcLastMod: TRUEolcDbCheckpoint: 512 30olcAccess: to attrs=userPassword by dn="cn=admin,dc=tipx,dc=domain,dc=es" write by anonymous auth by self write by * noneolcAccess: to attrs=shadowLastChange by self write by * readolcAccess: to dn.base="" by * readolcAccess: to * by dn="cn=admin,dc=tipx,dc=domain,dc=es" write by * read

    vi frontend.tipx.local.ldif# Create top-level object in domaindn: dc=tipx,dc=domain,dc=esobjectClass: topobjectClass: dcObjectobjectclass: organizationo: Telefonia IP domain

  • dc: tipxdescription: LDAP Example

    # Admin user.dn: cn=Manager,dc=tipx,dc=domain,dc=esobjectClass: simpleSecurityObjectobjectClass: organizationalRolecn: Managerdescription: LDAP administratoruserPassword:

    dn: ou=people,dc=tipx,dc=domain,dc=esobjectClass: organizationalUnitou: people

    dn: ou=groups,dc=tipx,dc=domain,dc=esobjectClass: organizationalUnitou: groups

    dn: uid=jose,ou=people,dc=tipx,dc=domain,dc=esobjectClass: inetOrgPersonobjectClass: posixAccountuid: josesn: lopezgivenName: Josecn: JosedisplayName: JoseuidNumber: 1000gidNumber: 10000userPassword: gecos: Jose Jmail: [email protected]: 519961homePhone: 91-624-9961title: System Administratorinitials: JJhomeDirectory: /home/jose

    dn: cn=eps,ou=groups,dc=tipx,dc=domain,dc=esobjectClass: posixGroupcn: epsgidNumber: 10000---------------------------------

    En /usr/local/var/openldap-data/ copiar fichero DB_CONFIG.example como DB_CONFIG para evitar un warning/errorcd /usr/local/var/openldap-data/cp DB_CONFIG.example DB_CONFIG

    Creamos la base de datos LDAP:

    cd /home/jose/ldapldapadd -x -D "cn=Manager,dc=tipx,dc=domain,dc=es" -W -f backend.tipx.local.ldifldapadd -x -D "cn=Manager,dc=tipx,dc=domain,dc=es" -W -f frontend.tipx.local.ldif

    (NOTA: el hecho de usar /home/jose como directorio de trabajo no tiene relacin con que el usuario que definimos en LDAP se llame igual).

    Ejecutar el demonio online para depuracin:

  • /usr/local/libexec/slapd -d -1 -h "ldap://localhost/"

    Probamos a bajarnos el rbol:

    ldapsearch -x -b '' -s base '(objectclass=*)' namingContextsldapsearch -x -b 'dc=tipx,dc=domain,dc=es' '(objectclass=*)'ldapsearch -x -b 'dc=tipx,dc=domain,dc=es' '(objectclass=jose)'ldapsearch -x -b 'dc=tipx,dc=domain,dc=es' '(objectclass=inetOrgPerson)'

    Para el arranque normal como demonio:

    /usr/local/libexec/slapd -h "ldap://localhost/"

    >>>>>>>>>>>>>>>>INSTALACION DE UN GESTOR WEB PARA LDAP

  • /* Array of base DNs of your LDAP server. Leave this blank to have phpLDAPadmin auto-detect it for you. */$servers->setValue('server','base',array('dc=tipx,dc=domain,dc=es'));

    /* Four options for auth_type: 1. 'cookie': you will login via a web form, and a client-side cookie will store your login dn and password. 2. 'session': same as cookie but your login dn and password are stored on the web server in a persistent session variable. 3. 'http': same as session but your login dn and password are retrieved via HTTP authentication. 4. 'config': specify your login dn and password here in this config file. No login will be required to use phpLDAPadmin for this server.

    Choose wisely to protect your authentication information appropriately for your situation. If you choose 'cookie', your cookie contents will be encrypted using blowfish and the secret your specify above as session['blowfish']. */$servers->setValue('login','auth_type','http');

    ?>

  • >>>>>>>>>>>>>>>>>INSTALACION DE UN SERVIDOR FREERADIUS
  • # tipx.domain.es users#realm "tipx.domain.es" { # nostrip}

    ## This realm is for requests which don't have an explicit realm# prefix or suffix. User names like "bob" will match this one.#realm NULL { # nostrip}

    ## This realm is used mainly to cancel proxying. You can have# the "realm suffix" module configured to proxy all requests for# a realm, and then later cancel the proxying, based on other# configuration.## For example, you want to terminate PEAP or EAP-TTLS locally,# you can add the following to the "users" file:## DEFAULT EAP-Type == PEAP, Proxy-To-Realm := LOCAL#realm LOCAL { # nostrip}

    ## This realm is for ALL OTHER requests.#realm DEFAULT {

    #nostrip}

    * En el fichero de clientes autorizamos las peticiones que llegarn al servidor RADIUS desde la misma mquina, ya que en ella instalaremos los clientes de RADIUS de opensips y ASTERISK:

    vi /etc/freeradius/clients.conf...client {

    secret = shortname = localhost

    }

    La direccin IP que deber figurar en , ser la IP de la mquina donde est instalado opensips y asterisk (si estn en mquinas separadas habr dos entradas como la anterior).En nuestro caso como todo est en la misma mquina es la direccin IP del interfaz de red activo.----------------------------------------------------------- vi /etc/freeradius/dictionary...$INCLUDE /etc/freeradius/dictionary.ser

    * dictionary.ser hay que bajarlo de internet (ver http://www.kamailio.org/docs/opensips-radius-1.0.x.html), el que viene por defecto da problemas, as que cogemos ese que contiene las extensiones de Schulzrinne/Sterman (lo hemos metido tambin en /etc/opensips/dictionary.radius).

  • vi /etc/freeradius/dictionary.ser## SIP RADIUS attributes## Schulzrinne indicates attributes according to# draft-schulzrinne-sipping-radius-accounting-00## Sterman indicates attributes according to# draft-sterman-aaa-sip-00## Proprietary indicates an attribute that hasn't# been standardized## Check out http://www.iana.org/assignments/radius-types# for up-to-date list of standard RADIUS attributes# and values#

    ## NOTE: All standard (IANA registered) attributes are # commented out except those that are missing in # the default dictionary of the radiusclient-ng # library.#

    #### Attributes ####ATTRIBUTE User-Name 1 string # RFC2865#ATTRIBUTE Service-Type 6 integer # RFC2865#ATTRIBUTE Called-Station-Id 30 string # RFC2865, acc#ATTRIBUTE Calling-Station-Id 31 string # RFC2865, acc#ATTRIBUTE Acct-Status-Type 40 integer # RFC2865, acc#ATTRIBUTE Acct-Session-Id 44 string # RFC2865, accATTRIBUTE Sip-Method 101 integer # Schulzrinne, accATTRIBUTE Sip-Response-Code 102 integer # Schulzrinne, accATTRIBUTE Sip-Cseq 103 string # Schulzrinne, accATTRIBUTE Sip-To-Tag 104 string # Schulzrinne, accATTRIBUTE Sip-From-Tag 105 string # Schulzrinne, accATTRIBUTE Sip-Translated-Request-URI 107 string # Proprietary, accATTRIBUTE Sip-Src-IP 108 string # Proprietary, accATTRIBUTE Sip-Src-Port 109 string # Proprietary, accATTRIBUTE Digest-Response 206 string # Sterman, auth_radiusATTRIBUTE Sip-Uri-User 208 string # Proprietary, auth_radiusATTRIBUTE Sip-Group 211 string # Proprietary, group_radiusATTRIBUTE Sip-Rpid 213 string # Proprietary, auth_radiusATTRIBUTE SIP-AVP 225 string # Proprietary, avp_radiusATTRIBUTE Digest-Realm 1063 string # Sterman, auth_radiusATTRIBUTE Digest-Nonce 1064 string # Sterman, auth_radiusATTRIBUTE Digest-Method 1065 string # Sterman, auth_radiusATTRIBUTE Digest-URI 1066 string # Sterman, auth_radiusATTRIBUTE Digest-QOP 1067 string # Sterman, auth_radiusATTRIBUTE Digest-Algorithm 1068 string # Sterman, auth_radiusATTRIBUTE Digest-Body-Digest 1069 string # Sterman, auth_radiusATTRIBUTE Digest-CNonce 1070 string # Sterman, auth_radiusATTRIBUTE Digest-Nonce-Count 1071 string # Sterman, auth_radiusATTRIBUTE Digest-User-Name 1072 string # Sterman, auth_radius

    #Atributos para recuperar perfiles de usuario

  • ATTRIBUTE UserPresenceID 1073 string # Sterman, auth_radiusATTRIBUTE AliasMail 1074 string # Sterman, auth_radius

    ### CISCO Vendor Specific Attributes ####VENDOR Cisco 9#ATTRIBUTE Cisco-AVPair 1 string Cisco # VSA, auth_radius

    ### Acct-Status-Type Values ####VALUE Acct-Status-Type Start 1 # RFC2866, acc#VALUE Acct-Status-Type Stop 2 # RFC2866, accVALUE Acct-Status-Type Failed 15 # RFC2866, acc

    ### Service-Type Values ###VALUE Service-Type Call-Check 10 # RFC2865, uri_radiusVALUE Service-Type Group-Check 12 # Proprietary, group_radiusVALUE Service-Type Sip-Session 15 # Schulzrinne, acc, auth_radiusVALUE Service-Type SIP-Caller-AVPs 30 # Proprietary, avp_radiusVALUE Service-Type SIP-Callee-AVPs 31 # Proprietary, avp_radius

    VALUE Sip-Method INVITE 1 # Proprietary, accVALUE Sip-Method CANCEL 2 # Proprietary, accVALUE Sip-Method ACK 4 # Proprietary, accVALUE Sip-Method BYE 8 # Proprietary, acc

    >>>>>>>>>>>>> INSTALAR MYSQL >>>>>>>>>>>>

    apt-get install mysql-serverapt-get install mysql-client

    ...

    >>>>>>>>>>>INSTALAR GESTOR PHPMYADMIN DE MYSQL DESDE WEB>>>>> SOPORTE MYSQL PARA RADIUS

  • Ejecutar:mysql -uroot -p radius < /etc/freeradius/sql/mysql/admin.sql

    Cambiar el password por defecto en:vi /etc/freeradius/sql.conf

    sqltrace=yes si queremos depurar los comandos sql.

    Descomentar las lineas # sql envi /etc/freeradius/sites-enabled/default

    Descomentar # $INCLUDE sql.conf en: vi /etc/freeradius/radiusd.conf

    $INCLUDE sql.conf

    mysql -uroot -p radius < /etc/freeradius/sql/mysql/nas.sql

    mysql -u radius -pEnter password: Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 275Server version: 5.1.41-3ubuntu12.10 (Ubuntu)

    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

    mysql> use radiusReading table information for completion of table and column namesYou can turn off this feature to get a quicker startup with -A

    Database changedmysql> show tables;+------------------+| Tables_in_radius |+------------------+| nas || radacct || radcheck || radgroupcheck || radgroupreply || radpostauth || radreply || radusergroup |+------------------+8 rows in set (0.00 sec)

    Para meter el usuario ejemplo podemos usar phpmyadmin o bien hacerlo a base de "insert" en las tablas.Supongamos hemos usado phpmyadmin. Nos debe quedar algo como:

    mysql> select * from nas;+----+----------+-----------+-------+-------+--------+-----------+---------------+| id | nasname | shortname | type | ports | secret | community | description |+----+----------+-----------+-------+-------+--------+-----------+---------------+| 1 | josejuan | josejuan | other | NULL | secret | NULL | RADIUS Client |+----+----------+-----------+-------+-------+--------+-----------+---------------+1 row in set (0.00 sec)

    mysql> select * from radcheck;+----+-----------------------+--------------------+----+----------+| id | username | attribute | op | value |

  • +----+-----------------------+--------------------+----+----------+| 1 | [email protected] | Cleartext-Password | := | |+----+-----------------------+--------------------+----+----------+1 row in set (0.00 sec)

    donde debemos cambiarla por la password en claro del usuario.

    mysql> select * from radgroupcheck;+----+-----------+-----------+----+--------+| id | groupname | attribute | op | value |+----+-----------+-----------+----+--------+| 1 | static | Auth-Type | := | DIGEST |+----+-----------+-----------+----+--------+1 row in set (0.00 sec)

    mysql> select * from radusergroup;+-----------------------+-----------+----------+| username | groupname | priority |+-----------------------+-----------+----------+| [email protected] | static | 1 |+-----------------------+-----------+----------+1 row in set (0.00 sec)

    Probaremos el usuario cuando tengamos instalada la maqueta de telefona IP.

    >>>>>>>>>>>>> SOPORTE LDAP PARA RADIUS

  • # etc_smbpasswd# daily# checkval

    expirationlogintimepap

    # Autz-Type Status-Server {## }}

    authenticate {Auth-Type PAP {

    pap}Auth-Type CHAP {

    chap}Auth-Type MS-CHAP {

    mschap}digest

    # pamunix

    # Auth-Type LDAP {# ldap# }

    eap# Auth-Type eap {# eap {# handled = 1 # }# if (handled && (Response-Packet-Type == Access-Challenge)) {# attr_filter.access_challenge.post-auth# handled # override the "updated" code from attr_filter# }# }}

    preacct {preprocess

    # update request {# FreeRADIUS-Acct-Session-Start-Time = "%{expr: %l - %{%{Acct-Session-Time}:-0}- %{%{Acct-Delay-Time}:-0}}"# }

    acct_unique# IPASS

    suffix# ntdomain

    files}

    accounting {detail

    # dailyunixradutmp

    # sradutmp

  • # main_poolsql

    # if (noop) {# ok# }# sql_log# pgsql-voip

    attr_filter.accounting_response# Acct-Type Status-Server {## }}

    session {radutmpsql

    }

    post-auth {# main_pool# reply_log

    sql# sql_log# ldap

    exec# wimax

    Post-Auth-Type REJECT {attr_filter.access_reject

    }}

    pre-proxy {# attr_rewrite# files# attr_filter.pre-proxy# pre_proxy_log}

    post-proxy {# post_proxy_log# attr_rewrite# attr_filter.post-proxy

    eap# Post-Proxy-Type Fail {# detail# }

    }--------------------------------------------------------Vamos a configurar SASL para hablar con el servidor LDAP a travs del puerto estndar de ldap (no ldaps)Usaremos certificados autofirmados, por lo que como certificado de la CA usaremos el del propio servidor LDAP.Tambin hemos usado como certificados del servidor los mismos que el de LDAP.En una implementacin real esto debe ser tenido en cuenta ya que tendrn que diferenciarse.Ojo con el subject de los certificados (ver apartado de instalacion del servidor LDAP con SASL la parte de generacin de los certificados).

  • vi /etc/freeradius/modules/ldap

    # -*- text -*-## $Id$

    # Lightweight Directory Access Protocol (LDAP)## This module definition allows you to use LDAP for# authorization and authentication.## See raddb/sites-available/default for reference to the# ldap module in the authorize and authenticate sections.## However, LDAP can be used for authentication ONLY when the# Access-Request packet contains a clear-text User-Password# attribute. LDAP authentication will NOT work for any other# authentication method.## This means that LDAP servers don't understand EAP. If you# force "Auth-Type = LDAP", and then send the server a# request containing EAP authentication, then authentication# WILL NOT WORK.## The solution is to use the default configuration, which does# work.## Setting "Auth-Type = LDAP" is ALMOST ALWAYS WRONG. We# really can't emphasize this enough.#ldap {

    ## Note that this needs to match the name in the LDAP# server certificate, if you're using ldaps.

    server = "localhost" identity = "cn=Manager,dc=tipx,dc=domain,dc=es" password = basedn = "ou=people,dc=tipx,dc=domain,dc=es"

    filter = "(uid=%{%{Stripped-User-Name}:-%{User-Name}})"#base_filter = "(objectclass=radiusprofile)"

    # How many connections to keep open to the LDAP server.# This saves time over opening a new LDAP socket for# every authentication request.ldap_connections_number = 5

    # seconds to wait for LDAP query to finish. default: 20timeout = 20

    # seconds LDAP server has to process the query (server-side# time limit). default: 20## LDAP_OPT_TIMELIMIT is set to this value.timelimit = 20

  • ## seconds to wait for response of the server. (network# failures) default: 10## LDAP_OPT_NETWORK_TIMEOUT is set to this value.net_timeout = 10

    ## This subsection configures the tls related items# that control how FreeRADIUS connects to an LDAP# server. It contains all of the "tls_*" configuration# entries used in older versions of FreeRADIUS. Those# configuration entries can still be used, but we recommend# using these.#

    tls {# Set this to 'yes' to use TLS encrypted connections# to the LDAP database by using the StartTLS extended# operation.## The StartTLS operation is supposed to be# used with normal ldap connections instead of# using ldaps (port 689) connectionsstart_tls = yes

    cacertdir = /etc/freeradius/certs/ldapcerts cacertfile = ${cacertdir}/server.pem certfile = ${cacertdir}/server.pem keyfile = ${cacertdir}/server.key randfile = /dev/urandom

    # Certificate Verification requirements. Can be:# "never" (don't even bother trying)# "allow" (try, but don't fail if the cerificate# can't be verified)# "demand" (fail if the certificate doesn't verify.)## The default is "allow"# require_cert = "demand"

    }

    # default_profile = "cn=radprofile,ou=dialup,o=My Org,c=UA"# profile_attribute = "radiusProfileDn"# access_attr = "dialupAccess"

    # Mapping of RADIUS dictionary attributes to LDAP# directory attributes.dictionary_mapping = ${confdir}/ldap.attrmap

    # Set password_attribute = nspmPassword to get the# user's password from a Novell eDirectory# backend. This will work ONLY IF FreeRADIUS has been# built with the --with-edir configure option.## See also the following links:## http://www.novell.com/coolsolutions/appnote/16745.html

  • # https://secure-support.novell.com/KanisaPlatform/Publishing/558/3009668_f.SAL_Public.html## Novell may require TLS encrypted sessions before returning# the user's password.##password_attribute = userPassword

    # Un-comment the following to disable Novell# eDirectory account policy check and intruder# detection. This will work *only if* FreeRADIUS is# configured to build with --with-edir option.#edir_account_policy_check = no

    ## Group membership checking. Disabled by default.## groupname_attribute = cn# groupmembership_filter = "(|(&(objectClass=GroupOfNames)(member=%{control:Ldap-UserDn}))

    (&(objectClass=GroupOfUniqueNames)(uniquemember=%{control:Ldap-UserDn})))"# groupmembership_attribute = radiusGroupName

    # compare_check_items = yes# do_xlat = yes# access_attr_used_for_allow = yes

    ## The following two configuration items are for Active Directory# compatibility. If you see the helpful "operations error"# being returned to the LDAP module, uncomment the next# two lines.## chase_referrals = yes# rebind = yes

    ## By default, if the packet contains a User-Password,# and no other module is configured to handle the# authentication, the LDAP module sets itself to do# LDAP bind for authentication.## THIS WILL ONLY WORK FOR PAP AUTHENTICATION.## THIS WILL NOT WORK FOR CHAP, MS-CHAP, or 802.1x (EAP). ## You can disable this behavior by setting the following# configuration entry to "no".## allowed values: {no, yes}set_auth_type = no

    # ldap_debug: debug flag for LDAP SDK# (see OpenLDAP documentation). Set this to enable# huge amounts of LDAP debugging on the screen.# You should only use this if you are an LDAP expert.## default: 0x0000 (no debugging messages)# Example:(LDAP_DEBUG_FILTER+LDAP_DEBUG_CONNS)

  • #ldap_debug = 0x0028 }----------------------------------------Copiar certificados autofirmados de ldap donde espera freeradius encontrarlos: (podriamos configurar el mismo directorio para el servidor ldap y el freeradius, pero hemos preferido dejarlo asi, para separarlos si fuera necesario)

    cd /etc/freeradius/certs/mkdir ldapcertscd ldapcerts/cp /usr/local/etc/openldap/cacerts/* .

    ----------------------------------------Arrancar freeradius para depurar:

    freeradius -X

    Arrancar freeradius para funcionamiento normal:/etc/init.d/freeradius start

    >>>>>>>>>>>>>>>>PROBAR FREERADIUS

  • title: System Administratorinitials: JJhomeDirectory: /home/jose------------------------------Ahora hay que hacer ese cambio efectivo en la base de datos de LDAP.Se puede borrar la entrada uid=jose con phpldapadminy luego ejecutar

    ldapadd -x -D "cn=Manager,dc=tipx,dc=domain,dc=es" -W -f frontend.tipx.local.ldifasi aade una entrada limpia.------------------------------

  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MAQUETA DE VOIP>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    >>>>>>>>> ALTA EN DNS DE NUESTRO ROUTER SIP

  • STANDARD_MODULES y EXTRA_MODULES. Para empezar lo que hay en el ejemplo es suficiente, pero para ciertos modulos puede ser necesario anyadir la entrada correspondiente.)

    # $Id: opensipsctlrc 7337 2010-10-28 22:02:46Z osas $## The OpenSIPS configuration file for the control tools.## Here you can set variables used in the opensipsctl and opensipsdbctl setup# scripts. Per default all variables here are commented out, the control tools# will use their internal default values.

    ## your SIP domain# SIP_DOMAIN=opensips.orgSIP_DOMAIN=tip2.uc3m.es

    ## chrooted directory# $CHROOT_DIR="/path/to/chrooted/directory"

    ## database type: MYSQL, PGSQL, ORACLE, DB_BERKELEY, or DBTEXT, ## by default none is loaded# If you want to setup a database with opensipsdbctl, you must at least specify# this parameter.DBENGINE=MYSQL

    ## database hostDBHOST=localhost

    ## database name (for ORACLE this is TNS name)DBNAME=opensips

    # database path used by dbtext or db_berkeley# DB_PATH="/usr/local/etc/opensips/dbtext"

    ## database read/write userDBRWUSER=opensips

    ## password for database read/write user# DBRWPW="opensipsrw"DBRWPW="mb.4818"

    ## database read only userDBROUSER=opensipsro

    ## password for database read only user# DBROPW=opensipsroDBROPW=mb.4818

    ## database super user (for ORACLE this is 'scheme-creator' user)DBROOTUSER="root"

    # user name column# USERCOL="username"

    # SQL definitions# If you change this definitions here, then you must change them # in db/schema/entities.xml too.# FIXME# FOREVER="2020-05-28 21:32:15"

  • # DEFAULT_ALIASES_EXPIRES=$FOREVER# DEFAULT_Q="1.0"# DEFAULT_CALLID="Default-Call-ID"# DEFAULT_CSEQ="13"# DEFAULT_LOCATION_EXPIRES=$FOREVER

    # Program to calculate a message-digest fingerprint # MD5="md5sum"

    # awk tool# AWK="awk"

    # grep tool# GREP="grep"

    # sed tool# SED="sed"

    # Describe what additional tables to install. Valid values for the variables# below are yes/no/ask. With ask (default) it will interactively ask the user# for an answer, while yes/no allow for automated, unassisted installs.## If to install tables for the modules in the EXTRA_MODULES variable.# INSTALL_EXTRA_TABLES=ask

    # If to install presence related tables.# INSTALL_PRESENCE_TABLES=ask

    # Define what module tables should be installed.# If you use the postgres database and want to change the installed tables,# then you must also adjust the STANDARD_TABLES or EXTRA_TABLES variable # accordingly in the opensipsdbctl.base script.

    # opensips standard modulesSTANDARD_MODULES="standard acc lcr domain group permissions registrar usrloc msilo alias_db uri_db speeddial avpops auth_db pdt dialog dispatcher dialplan drouting nathelper load_balancer"

    # opensips extra modules# EXTRA_MODULES="imc cpl siptrace domainpolicy carrierroute userblacklist b2b"

    ## type of aliases used: DB - database aliases; UL - usrloc aliases## - default: none# ALIASES_TYPE="DB"

    ## control engine: FIFO or UNIXSOCK## - default FIFO# CTLENGINE=xmlrpcCTLENGINE="FIFO"

    ## path to FIFO fileOSIPS_FIFO="/tmp/opensips_fifo"

    ## MI_CONNECTOR control engine: FIFO, UNIXSOCK, UDP, XMLRPCMI_CONNECTOR=FIFO:/tmp/opensips_fifo# MI_CONNECTOR=UNIXSOCK:/tmp/opensips.sock# MI_CONNECTOR=UDP:192.168.2.133:8000# MI_CONNECTOR=XMLRPC:192.168.2.133:8000

  • ## check ACL names; default on (1); off (0)# VERIFY_ACL=1

    ## ACL names - if VERIFY_ACL is set, only the ACL names from below list## are accepted# ACL_GROUPS="local ld int voicemail free-pstn"

    ## verbose - debug purposes - default '0'# VERBOSE=1

    ## do (1) or don't (0) store plaintext passwords## in the subscriber table - default '1'# STORE_PLAINTEXT_PW=0

    ## OPENSIPS START Options## PID file path - default is: /var/run/opensips.pidPID_FILE=/var/run/opensips.pid

    ## Extra start options - default is: not set# example: start opensips with 64MB share memory: STARTOPTIONS="-m 64"

    # STARTOPTIONS=

    --------------------------------------------------------------

    * Creamos la base de datos :/usr/local/sbin/opensipsdbctl create

    Aadir los dominios tip2.uc3m.es y 163.117.131.33 a la base de datos domain de opensips, por ejemplo con phpmyadmin.

    * Instalamos cliente radius:apt-get install libradiusclient-ng-devapt-get install libradiusclient-ng2

    * Editamos ficheros de configuracin del cliente radius:vi /etc/radiusclient-ng/radiusclient.conf

    aadimosauthserver acctserver

    vi /etc/radiusclient-ng/serversaadimos

    vi /etc/radiusclient-ng/dictionaryaadimos$INCLUDE /etc/radiusclient-ng/dictionary.seres el mismo que se copia en el servidor (ver ms arriba).--------------------------------------------------------------

    El cdigo de como se va a comportar el SIP Express Router (OPENSIPS) est en:/usr/local/etc/opensips/opensips.cfg:Quizs sea mejor empezar con un opensips.cfg sencillo (p.ej: el que viene por defecto) e irlo complicando. Para ello hay info en Internet suficiente. Esta propuesta est ms "cocinada" y ya incorpora varias funcionalidades interesantes.

  • Todos estos elementos se contemplan en el opensips.cfg propuesto:

    -autenticacin contra radius.-persistencia en bd mysql.-sip trunk con asterisk.-acceso a buzones de voz en asterisk: *981[esperar]XXXX (dejar mensaje a XXXX), *98[esperar]XXXX (escuchar mensajes de XXXX). -cdrs (accounting) extendidos.-las extensiones numricas 51XXXX se registraran en opensips (usuarios de "movilidad"), las extensiones XXXX se reservan para la pbx asterisk (las 4XXX), y para el mundo analgico el resto (al cual se accedera por una mediagateway conectada a asterisk a tarvs de la red de datos).-evidentemente se permiten usuarios alfanumricos en opensips (seran del tipo @tipx.domain.es).

    Ponemos a escuchar opensips en el puerto 5062 para que coexista en la maqueta con asterisk en el 5060Esto hay que tenerlo en cuenta en los softphones al configurar el cliente sip.

    Los logs que deja cada llamada a xlog nos ayudarn a entender como funciona opensips, y a depurarlo.

    vi /usr/local/etc/opensips/opensips.cfg## $Id: opensips.cfg 2011-05-30 jj $## OpenSIPS basic configuration script# by Anca Vamanu ## Please refer to the Core CookBook at:# http://www.opensips.org/index.php?n=Resources.DocsCookbooks# for a explanation of possible statements, functions and parameters.######## Global Parameters #########debug=3log_stderror=nolog_facility=LOG_LOCAL0fork=yeschildren=4/* uncomment the following lines to enable debugging */#debug=6#fork=no#log_stderror=yes/* uncomment the next line to disable TCP (default on) */#disable_tcp=yes/* uncomment the next line to enable the auto temporary blacklisting of not available destinations (default disabled) */#disable_dns_blacklist=no/* uncomment the next line to enable IPv6 lookup after IPv4 dns lookup failures (default disabled) */#dns_try_ipv6=yes/* uncomment the next line to disable the auto discovery of local aliases based on revers DNS on IPs (default on) */#auto_aliases=no/* uncomment the following lines to enable TLS support (default off) */#disable_tls = no#listen = tls:your_IP:5061#tls_verify_server = 1#tls_verify_client = 1#tls_require_client_certificate = 0#tls_method = TLSv1#tls_certificate = "/usr/local/etc/opensips/tls/user/user-cert.pem"

  • #tls_private_key = "/usr/local/etc/opensips/tls/user/user-privkey.pem"#tls_ca_list = "/usr/local/etc/opensips/tls/user/user-calist.pem"#port=5060/* uncomment and configure the following line if you want opensips to bind on a specific interface/port/proto (default bind on all available) */listen=udp:163.117.131.33:5062#listen=udp:192.168.1.34:5062####### Modules Section #########set module pathmpath="/lib/opensips/modules/"/* uncomment next line for MySQL DB support */loadmodule "db_mysql.so"loadmodule "signaling.so"loadmodule "sl.so"loadmodule "tm.so"loadmodule "rr.so"loadmodule "maxfwd.so"loadmodule "usrloc.so"loadmodule "registrar.so"loadmodule "textops.so"loadmodule "mi_fifo.so"#loadmodule "uri_db.so"loadmodule "uri.so"#loadmodule "xlog.so"loadmodule "acc.so"/* uncomment next lines for MySQL based authentication support NOTE: a DB (like mysql) module must be also loaded */loadmodule "auth.so"#loadmodule "auth_db.so"#loadmodule "auth_radius.so"loadmodule "auth_aaa.so"loadmodule "aaa_radius.so"/* uncomment next line for aliases support NOTE: a DB (like mysql) module must be also loaded */#loadmodule "alias_db.so"/* uncomment next line for multi-domain support NOTE: a DB (like mysql) module must be also loaded NOTE: be sure and enable multi-domain support in all used modules (see "multi-module params" section ) */loadmodule "domain.so"/* uncomment the next two lines for presence server support NOTE: a DB (like mysql) module must be also loaded */#loadmodule "presence.so"#loadmodule "presence_xml.so"# ----------------- setting module-specific parameters ---------------# ----- mi_fifo params -----modparam("mi_fifo", "fifo_name", "/tmp/opensips_fifo")# ----- rr params -----# add value to ;lr param to cope with most of the UAsmodparam("rr", "enable_full_lr", 1)# do not append from tag to the RR (no need for this script)modparam("rr", "append_fromtag", 0)# ----- rr params -----#modparam("registrar", "method_filtering", 1)/* uncomment the next line to disable parallel forking via location */# modparam("registrar", "append_branches", 0)/* uncomment the next line not to allow more than 10 contacts per AOR */#modparam("registrar", "max_contacts", 10)

  • # ----- uri_db params -----/* by default we disable the DB support in the module as we do not need it in this configuration */#modparam("uri_db", "use_uri_table", 0)#modparam("uri_db", "db_url", "")# ----- acc params -----/* disable RADIUS support */#modparam("acc", "radius_config", "")#modparam("acc", "radius_config", "/etc/radiusclient-ng/radiusclient.conf")modparam("acc", "aaa_url", "radius:/etc/radiusclient-ng/radiusclient.conf")/* what sepcial events should be accounted ? */modparam("acc", "early_media", 1)modparam("acc", "report_ack", 1)modparam("acc", "report_cancels", 1)/* by default ww do not adjust the direct of the sequential requests. if you enable this parameter, be sure the enable "append_fromtag" in "rr" module */modparam("acc", "detect_direction", 0)/* account triggers (flags) */modparam("acc", "failed_transaction_flag", 3)modparam("acc", "log_flag", 1)modparam("acc", "log_missed_flag", 2)/* uncomment the following lines to enable DB accounting also */modparam("acc", "db_flag", 1)modparam("acc", "db_missed_flag", 2)modparam("acc", "db_url",

    "mysql://opensips:mb.4818@localhost/opensips")/* extra accounting: */modparam("acc", "db_extra", "src_user=$fU;src_domain=$fd;dst_user=$rU;dst_domain=$rd;src_ip=$si")# ----- usrloc params -----#modparam("usrloc", "db_mode", 0)/* uncomment the following lines if you want to enable DB persistency for location entries */modparam("usrloc", "db_mode", 2)modparam("usrloc", "db_url",

    "mysql://opensips:mb.4818@localhost/opensips")# ----- auth_db params -----/* uncomment the following lines if you want to enable the DB based authentication */#modparam("auth_db", "calculate_ha1", yes)#modparam("auth_db", "password_column", "password")#modparam("auth_db", "db_url",# "mysql://opensips:mb.4818@localhost/opensips")#modparam("auth_db", "load_credentials", "")# radius#modparam("auth_radius","radius_config","/etc/radiusclient-ng/radiusclient.conf")#modparam("auth_radius","service_type",15)modparam("auth_aaa","aaa_url","radius:/etc/radiusclient-ng/radiusclient.conf")#modparam("auth_aaa","service_type",15)modparam("aaa_radius", "radius_config", "/etc/radiusclient-ng/radiusclient.conf")# ----- alias_db params -----/* uncomment the following lines if you want to enable the DB based aliases */#modparam("alias_db", "db_url",# "mysql://opensips:opensipsrw@localhost/opensips")# ----- domain params -----/* uncomment the following lines to enable multi-domain detection

  • support */modparam("domain", "db_url",

    "mysql://opensips:mb.4818@localhost/opensips")modparam("domain", "db_mode", 1) # Use caching# ----- multi-module params -----/* uncomment the following line if you want to enable multi-domain support in the modules (default off) */#modparam("alias_db|auth_db|usrloc|uri_db", "use_domain", 1)modparam("usrloc|uri_db", "use_domain", 1)# ----- presence params -----/* uncomment the following lines if you want to enable presence */#modparam("presence|presence_xml", "db_url",# "mysql://opensips:opensipsrw@localhost/opensips")#modparam("presence_xml", "force_active", 1)#modparam("presence", "server_address", "sip:192.168.1.2:5060")

    ####### Routing Logic ######### main request routing logicroute{

    xlog("L_NOTICE","Llamada a opensips From ($fu)\n");# initial sanity checks -- messages with# max_forwards==0, or excessively long requestsif (!mf_process_maxfwd_header("10")) {

    sl_send_reply("483","Too Many Hops");exit;

    }if (msg:len >= 2048 ) {

    sl_send_reply("513", "Message too big");exit;

    };if (has_totag()) {

    xlog("L_NOTICE","has to tag\n");# sequential request withing a dialog should# take the path determined by record-routingif (loose_route()) {

    xlog("L_NOTICE","loose route\n");if (is_method("BYE")) {

    setflag(1); # do accouting ...setflag(3); # ... even if the transaction fails

    }route(1);

    } else {/* uncomment the following lines if you want to enable presence */##if (is_method("SUBSCRIBE") && $rd == "your.server.ip.address") {## # in-dialog subscribe requests## route(2);## exit;##}if ( is_method("ACK") ) {

    if ( t_check_trans() ) {# non loose-route, but stateful ACK; must be an ACK after a 487 or e.g. 404 from upstream server

    t_relay();exit;

    } else {# ACK without matching transaction ... ignore and discard.\n");exit;

    }}

  • sl_send_reply("404","Not here");}exit;

    }#initial requests# CANCEL processingif (is_method("CANCEL")){

    xlog("L_NOTICE","method CANCEL\n");if (t_check_trans())

    t_relay();exit;

    }xlog("L_NOTICE","Llama a t_check_trans\n");t_check_trans();xlog("L_NOTICE","Vuelve de t_check_trans\n");# authenticate if from local subscriber (uncomment to enable auth)##if (!(method=="REGISTER") && from_uri==myself)##{## if (!proxy_authorize("", "subscriber")) {## proxy_challenge("", "0");## exit;## }## if (!db_check_from()) {## sl_send_reply("403","Forbidden auth ID");## exit;## }#### consume_credentials();## # caller authenticated##}# record routingif (!is_method("REGISTER|MESSAGE")) {

    xlog("L_NOTICE","record route\n");record_route();

    }# account only INVITEsif (is_method("INVITE")) {

    xlog("L_NOTICE","INVITE: set flag accounting\n");setflag(1); # do accouting

    }##if (!uri==myself)/* replace with following line if multi-domain support is used */if (!is_uri_host_local()){

    #xlog("L_NOTICE","not uri host local From ($fu)\n");append_hf("P-hint: outbound\r\n"); # if you have some interdomain connections via TLS##if($rd=="tls_domain1.net") {## t_relay("tls:domain1.net");## exit;##} else if($rd=="tls_domain2.net") {## t_relay("tls:domain2.net");## exit;##}route(1);

    }xlog("L_NOTICE","uri host local From ($fu)\n");

  • # requests for my domain/* uncomment this if you want to enable presence server and comment the next 'if' block NOTE: uncomment also the definition of route[2] from below */##if( is_method("PUBLISH|SUBSCRIBE"))## route(2);if (is_method("PUBLISH")){

    xlog("L_NOTICE","PUBLISH unavailable\n");sl_send_reply("503", "Service Unavailable");exit;

    }

    if (is_method("REGISTER")){

    # authenticate the REGISTER requests (uncomment to enable auth)#if (!www_authorize("partoX.uc3m.es", "subscriber"))#{# www_challenge("partoX.uc3m.es", "0");# exit;#}xlog("L_NOTICE","Register ($fu)\n");# athenticate the REGISTER request against RADIUSif (!aaa_www_authorize("tip2.uc3m.es")){

    xlog("L_NOTICE","no radius www authorize -> www challenge\n");www_challenge("tip2.uc3m.es", "0");exit;

    }

    if (!db_check_to()) {

    xlog("L_NOTICE","Forbidden auth ID\n");sl_send_reply("403","Forbidden auth ID");exit;

    }if (!save("location")) {

    xlog("L_NOTICE","no save location\n");sl_reply_error();

    }xlog("L_NOTICE","saved location\n");exit;

    }if ($rU==NULL) {

    # request with no Username in RURIxlog("L_NOTICE","request with no Username in RURI\n");sl_send_reply("484","Address Incomplete");exit;

    }# apply DB based aliases (uncomment to enable)##alias_db_lookup("dbaliases");# requests for Media serverif(is_method("INVITE") && !has_totag() && uri=~"sip:\*9") {

    xlog("L_NOTICE","INVITE, no has to tag y *9 -> voicemail");route(3);exit;

    }if (is_method("INVITE") && (uri=~"^sip:[0-9]{4}") && !(uri=~"^sip:51[0-9]{4}") && is_from_local()) {

  • xlog("L_NOTICE","INVITE, es extension numerica (no 51XXXX), is from local, from ($fu) to ($ruri) -> reencaminamos al Asterisk\n"); #rewriting the host allows the registrar to know that the message is destined for it rewritehostport("163.117.131.33:5060"); if(!t_relay("udp:163.117.131.33:5060")) { sl_reply_error(); };

    xlog("L_NOTICE","t_relayed ($rm) from $fu to $ruri\n");exit;

    }if (!lookup("location")) {

    switch ($retcode) {case -1:case -3:

    xlog("L_NOTICE","case -1,-3:($ruri) no registrado en sip server del dominio\n"); if (is_method("INVITE")) {

    rewritehostport("163.117.131.33:5060");append_branch();## Activamos el flag 10 para evitar buclesxlog("L_NOTICE","$fu---> Redirigiendo al Voicemail--->$ruri\n");setflag(10);route(1);

    }exit;

    # t_newtran();# t_reply("404", "Not Found");# exit;case -2:

    xlog("L_NOTICE","case -2:($ruri) no registrado en sip server del dominio\n");sl_send_reply("405", "Method Not Allowed");exit;

    }xlog("L_NOTICE","case otros:($ruri) no registrada en sip server del dominio\n");

    }# when routing via usrloc, log the missed calls alsoxlog("L_NOTICE","missed call: log it\n");setflag(2);route(1);

    }

    route[1] {# for INVITEs enable some additional helper routesif (is_method("INVITE")) {

    xlog("L_NOTICE","route[1]: INVITE, t_on_branch(2) and t_on_reply(2)\n");t_on_branch("2");t_on_reply("2");## Comprobamos si no esta marcado el flag 10, ## para si da error mandar la llamada al voicemailif(!isflagset(10)) {

    xlog("L_NOTICE","route[1]: is flag set to 10, t_on_failure(1)\n");t_on_failure("1");

    }}if (!t_relay()) {

    xlog("L_NOTICE","route[1]: t_relay error\n");sl_reply_error();

    };xlog("L_NOTICE","route[1]: exit\n");

  • exit;}# Presence route/* uncomment the whole following route for enabling presence NOTE: do not forget to enable the call of this route from the main route */##route[2]##{## if (!t_newtran())## {## sl_reply_error();## exit;## };#### if(is_method("PUBLISH"))## {## handle_publish();## t_release();## }## else## if( is_method("SUBSCRIBE"))## {## handle_subscribe();## t_release();## }#### exit;##}# voicemail access# - *981 - listen voice messages, being promted for mailbox and pin# - *98XXXX! - Voice message to XXXX! #route[3] { # direct voicemail

    xlog("L_NOTICE","voicemail from ($fu) to ($ruri)\n");if (uri =~ "sip:\*981@" ) {

    xlog("L_NOTICE","voicemail *981\n"); strip(4);

    rewriteuser("11");} else if (uri =~ "sip:\*98.+@" ) {

    xlog("L_NOTICE","voicemail *98\n"); strip(3);

    prefix("1");} else {

    xlog("L_NOTICE","unknown media extension $rU\n");sl_send_reply("404", "Unknown media service");exit;

    }# route to Asterisk Media Serverrewritehostport("163.117.131.33:5060");route(1);

    }branch_route[2] {

    xlog("L_NOTICE","new branch at $ru\n");}onreply_route[2] {

    xlog("L_NOTICE","incoming reply\n");}

  • failure_route[1] {xlog("L_NOTICE","failure route\n");if (t_was_cancelled()) {

    exit;}xlog("L_NOTICE","failure route, t was not cancelled\n");# uncomment the following lines if you want to block client # redirect based on 3xx replies.##if (t_check_status("3[0-9][0-9]")) {##t_reply("404","Not found");## exit;##}# uncomment the following lines if you want to redirect the failed # calls to a different new destination##if (t_check_status("486|408")) {## sethostport("192.168.2.100:5060");## append_branch();## # do not set the missed call flag again## t_relay();##}if (t_check_status("486|408|480")) {

    rewritehostport("163.117.131.33:5060");append_branch();## Activamos el flag 10 para evitar buclesxlog("L_NOTICE","Appended branch, Set flag 10, $fu---> Redirigiendo al Voicemail--->$ruri\n");setflag(10);route(1);exit;

    }}

    * Para arrancar opensips:opensipsctl start

    * Para ver usuarios registrados:opensipsctl ul show

    * Para parar opensips:opensipsctl stop

    ---------------------------------------------------------------------------* Probar con dos sofphones registrados con identificadores como los usados en los ejemplos: joselocal, jose, josejuan (aadiendo @tipx.domain.es). Probar extensiones numricas como usuario (51XXXX) .Recomendamos Twinkle.Como sipserver configurar :5062. Recordemos que hemos puesto opensips en este puerto para dejar asterisk en el 5060. Comprobar con:

    netstat -nlp--------------------------------------------------------------------------->>>>>>>>>>>>>>>>>>AADIR ACCOUNTING CON CDRs

  • -> `to_tag` varchar(64) NOT NULL default '', -> `callid` varchar(128) NOT NULL default '', -> `sip_code` char(3) NOT NULL default '', -> `sip_reason` varchar(32) NOT NULL default '', -> `time` datetime NOT NULL default '0000-00-00 00:00:00', -> `src_ip` varchar(64) NOT NULL default '', -> `dst_user` varchar(64) NOT NULL default '', -> `dst_domain` varchar(128) NOT NULL default '', -> `src_user` varchar(64) NOT NULL default '', -> `src_domain` varchar(128) NOT NULL default '', -> `cdr_id` integer NOT NULL default '0', -> INDEX acc_callid (`callid`), -> PRIMARY KEY (`id`) -> );Query OK, 0 rows affected (0.00 sec)mysql> CREATE TABLE `missed_calls` ( -> `id` int(10) unsigned NOT NULL auto_increment, -> `method` varchar(16) NOT NULL default '', -> `from_tag` varchar(64) NOT NULL default '', -> `to_tag` varchar(64) NOT NULL default '', -> `callid` varchar(128) NOT NULL default '', -> `sip_code` char(3) NOT NULL default '', -> `sip_reason` varchar(32) NOT NULL default '', -> `time` datetime NOT NULL default '0000-00-00 00:00:00', -> `src_ip` varchar(64) NOT NULL default '', -> `dst_user` varchar(64) NOT NULL default '', -> `dst_domain` varchar(128) NOT NULL default '', -> `src_user` varchar(64) NOT NULL default '', -> `src_domain` varchar(128) NOT NULL default '', -> `cdr_id` integer NOT NULL default '0', -> INDEX mc_callid (`callid`), -> PRIMARY KEY (`id`) -> );Query OK, 0 rows affected (0.00 sec)mysql> CREATE TABLE `cdrs` ( -> `cdr_id` bigint(20) NOT NULL auto_increment, -> `src_username` varchar(64) NOT NULL default '', -> `src_domain` varchar(128) NOT NULL default '', -> `dst_username` varchar(64) NOT NULL default '', -> `dst_domain` varchar(128) NOT NULL default '', -> `call_start_time` datetime NOT NULL default '0000-00-00 00:00:00', -> `duration` int(10) unsigned NOT NULL default '0', -> `sip_call_id` varchar(128) NOT NULL default '', -> `sip_from_tag` varchar(128) NOT NULL default '', -> `sip_to_tag` varchar(128) NOT NULL default '', -> `src_ip` varchar(64) NOT NULL default '', -> `created` datetime NOT NULL, -> PRIMARY KEY (`cdr_id`), -> UNIQUE KEY `uk_cft` (`sip_call_id`,`sip_from_tag`,`sip_to_tag`) -> );Query OK, 0 rows affected (0.05 sec)mysql> quit

    *Creamos un procedure mysql para gestionar los cdrs:

    vi /usr/local/etc/opensips/cdrs.sql

    DELIMITER //

  • CREATE PROCEDURE `kamailio_cdrs`()BEGIN DECLARE done INT DEFAULT 0; DECLARE bye_record INT DEFAULT 0; DECLARE v_src_user,v_src_domain,v_dst_user,v_dst_domain,v_callid,v_from_tag, v_to_tag,v_src_ip VARCHAR(64); DECLARE v_inv_time, v_bye_time DATETIME; DECLARE inv_cursor CURSOR FOR SELECT src_user, src_domain, dst_user, dst_domain, time, callid,from_tag, to_tag, src_ip FROM opensips.acc where method='INVITE' and cdr_id='0'; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; OPEN inv_cursor; REPEAT FETCH inv_cursor INTO v_src_user, v_src_domain, v_dst_user, v_dst_domain, v_inv_time, v_callid, v_from_tag, v_to_tag, v_src_ip; IF NOT done THEN SET bye_record = 0; SELECT 1, time INTO bye_record, v_bye_time FROM opensips.acc WHERE method='BYE' AND callid=v_callid AND ((from_tag=v_from_tag AND to_tag=v_to_tag) OR (from_tag=v_to_tag AND to_tag=v_from_tag)) ORDER BY time ASC LIMIT 1; IF bye_record = 1 THEN INSERT INTO opensips.cdrs (src_username,src_domain,dst_username, dst_domain,call_start_time,duration,sip_call_id,sip_from_tag, sip_to_tag,src_ip,created) VALUES (v_src_user,v_src_domain, v_dst_user,v_dst_domain,v_inv_time, UNIX_TIMESTAMP(v_bye_time)-UNIX_TIMESTAMP(v_inv_time), v_callid,v_from_tag,v_to_tag,v_src_ip,NOW()); UPDATE acc SET cdr_id=last_insert_id() WHERE callid=v_callid AND from_tag=v_from_tag AND to_tag=v_to_tag; END IF; SET done = 0; END IF; UNTIL done END REPEAT;END//DELIMITER ;

    * Metemos el procedure en la tabla correspondiente de opensips:

    /usr/bin/mysql opensips -uopensips -pmb.4818 < /etc/opensips/cdrs.sql

    * Aadir al crontab

    1 * * * * /usr/bin/mysql opensips -uopensips -pmb.4818 -e"call kamailio_cdrs()"

    >>>>>>>>>>>>>>>>>>INSTALACION BASICA DE PBX ASTERISK

  • Primero vamos a hacer una instalacin elemental de asterisk 1.4.8, haremos alguna prueba y configuraremos ms funcionalidades.

    Traer los fuentes de http://downloads.asterisk.org/pub/telephony/asterisk/old-releases/ cd /usr/local/src/tar zxvf asterisk-1.4.8.tar.gzcd asterisk-1.4.8./configure

    make make install

    vi /etc/asterisk/sip.confAadir al final;-------------------------; EXTENSIONES LOCALES;-------------------------[4961]type=friendusername=4961host=dynamiccontext=sip-localsecret =

    [4962]type=friendusername=4962host=dynamiccontext=sip-localsecret =

    vi /etc/asterisk/extensions.confAadir al final nuestro pequeo dialplan para probar[sip-local]exten => 4961,1,Dial(SIP/4961)exten => 4962,1,Dial(SIP/4962)

    * Arrancar demonio de asteriskasterisk

    * Conectar consola a demonio para supervisinasterisk -vvvr

    * Enla consola podemos ver extensiones registradas en asterisk con:sip show peers

    Probar con dos sofphones registrados con esos identificadores (4961 y 4962).Recomendamos Twinkle, por simplicidad de configuracin.Como sipserver configurar , para registrar directamente en asterisk.

    ----------------------------------------->>>>>>>INSTALACION DE PBX ASTERISK CON SOPORTE MYSQL

  • root@server:/usr/local/src/asterisk-addons-1.4.8# diff formats/format_mp3.c \formats/format_mp3.c.orig

    99c99< struct mp3_private *p = s->private;---> struct mp3_private *p = s->_private;116c116< struct mp3_private *p = s->private;---> struct mp3_private *p = s->_private;124c124< struct mp3_private *p = s->private;---> struct mp3_private *p = s->_private;143c143< struct mp3_private *p = s->private;---> struct mp3_private *p = s->_private;155c155< struct mp3_private *p = s->private;---> struct mp3_private *p = s->_private;200c200< struct mp3_private *p = s->private;---> struct mp3_private *p = s->_private;256c256< struct mp3_private *p = s->private;---> struct mp3_private *p = s->_private;296c296< struct mp3_private *p = s->private;---> struct mp3_private *p = s->_private;

    ./configure make make install

    Ahora vamos a aadir soporte MySQL a asterisk, asi como un sip trunk para hablar con opensips, y otro trunk para hablar con un mediagateway VYDA:

    cp /usr/share/doc/asterisk-mysql/examples/res_mysql.conf.sample /etc/asterisk/res_mysql.conf

    vi /etc/asterisk/res_mysql.conf[general]dbhost = 127.0.0.1dbname = asteriskdbuser = asteriskdbpass = asteriskdbport = 3306;dbsock = /tmp/mysql.sockdbsock = /var/run/mysqld/mysqld.sock

    vi /etc/asterisk/modules.conf

    En [modules] insertar

  • preload => app_addon_sql_mysql.sopreload => res_config_mysql.sopreload => cdr_addon_mysql.so

    vi /etc/asterisk/sip.confEn algn lugar de [general] insertar:;-------------------------------------------------------------------------------------------;---------------- DATABASE MySQL -----------------------------------------------------------;-------------------------------------------------------------------------------------------dbasename=asteriskdbhost=localhostdbuser=asteriskdbpass=asterisk

    vi /etc/asterisk/extconfig.confEn [settings] tener una lnea como:

    sippeers => mysql,asterisk,sipfriends

    mysql -u root -pmysql> create database asterisk;mysql> use asterisk;mysql> CREATE TABLE `sipfriends` ( `name` varchar(80) NOT NULL default '', `username` varchar(10) NOT NULL default '', `host` varchar(31) NOT NULL default 'dynamic', `nat` varchar(5) NOT NULL default 'yes', `type` enum('user','peer','friend') NOT NULL default 'friend', `canreinvite` char(3) NOT NULL default 'no', `context` varchar(80) NOT NULL, `dtmfmode` varchar(7) NOT NULL, `qualify` char(3) NOT NULL, `secret` varchar(80) NOT NULL, `disallow` varchar(100) NOT NULL default 'all', `allow` varchar(100) NOT NULL default 'g729;ilbc;gsm;ulaw;alaw', `port` smallint(5) unsigned NOT NULL default '5060', `lastms` int(11) default '0', `ipaddr` varchar(15) NOT NULL default '', `regseconds` int(11) default '0', `fullcontact` varchar(35) NOT NULL default '', `regserver` varchar(20) NOT NULL default '', `useragent` varchar(20) NOT NULL default '', UNIQUE KEY `name` (`name`), KEY `name_2` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;

    En otras versiones de asterisk useragent es un varchar(21)

    mysql> grant all privileges on 'asterisk'.* to 'asterisk'@'localhost' identified by 'asterisk';

    En otras versiones de mysql el primer asterisk es sin comillas : asterisk.*

    mysql> insert sipfriends (name,host,secret,context) values (4963,"dynamic","","sip-local")

    * En otras versiones de asterisk (p.ej. la 1.6.2 si hemos instalado desde el paquete),apt-get build-dep asterisk-mysqlapt-get -b source asterisk-mysqldpkg -i asterisk-mysql_1.6.2.0-1_amd64.deb

  • Con la 1.6.2 no tenemos parche para soporte de radius.

    si no, no carga el mysql engine por problema de versiones.

    * La columna username en la versin 1.6.2 se llama defaultuser, y cambia la tabla "ligeramente":ver https://voztovoice.org/?q=node/324

    * Rearrancar asterisk:

    pkill -9 asteriskasterisk

    * Hasta que no se registra un tfno no aparece en la bd:

    mysql> select * from sipfriends;+------+----------+---------+-----+--------+-------------+-----------+----------+---------+---------+----------+-------------------------+------+--------+---------+------------+-------------+-----------+-----------+| name | username | host | nat | type | canreinvite | context | dtmfmode | qualify | secret | disallow | allow | port | lastms | ipaddr | regseconds | fullcontact | regserver | useragent |+------+----------+---------+-----+--------+-------------+-----------+----------+---------+---------+----------+-------------------------+------+--------+---------+------------+-------------+-----------+-----------+| 4963 | 4963 | dynamic | yes | friend | no | sip-local | | | | all | gsm;ulaw;alaw | 0 | 0 | 0.0.0.0 | 1301312596 | | | |+------+----------+---------+-----+--------+-------------+-----------+----------+---------+---------+----------+-------------------------+------+--------+---------+------------+-------------+-----------+-----------+1 row in set (0.00 sec)

    vi /etc/asterisk/extensions.conf[globals]....; Asterisk RealTime Database Connection Settings; Use these variables to specify the connection to the Asterisk; Realtime Database.realdb_host=localhostrealdb_user=asteriskrealdb_pass=asteriskrealdb_db=asterisk

    ;[sip-local];exten => 4961,1,Dial(SIP/4961);exten => 4962,1,Dial(SIP/4962)

    [from-opensips] include => sip-local [sip-local] include => asterisk-out ;; Llamadas entre extensiones locales ;; Llamadas hacia PSTN exten => _4XXX,1,Log(NOTICE, Local Dialing out from ${CALLERID(all)} to ${EXTEN}) exten => _X.,1,Log(NOTICE, PSTN Dialing out from ${CALLERID(all)} to ${EXTEN}) exten => _4XXX,2,Dial(SIP/${EXTEN},20,Ttr) exten => _X.,2,Dial(SIP/${EXTEN}@vyda) exten => _4XXX,n,Hangup()

    [asterisk-out]

  • ;; Llamadas hacia OpenSIPS exten => _.,1,Log(NOTICE, Llamada hacia Opensips from ${CALLERID(all)} to ${EXTEN}) exten => _.,2,NoOp(Llamada hacia Opensips) exten => _.,n,Dial(SIP/${EXTEN}@)

    vi /etc/asterisk/sip.conf

    registro ante opensips:

    ;; REGISTRO ANTE OPENSIPS register => [email protected]:@:5062/51999 registertimeout=20 registerattempts=10

    ....

    ;-----------------------------------------------------; EXTENSIONES LOCALES;-------------------------[4961]type=friendusername=4961secret=host=dynamiccontext=sip-local

    [4962]type=friendusername=4962secret=host=dynamiccontext=sip-local

    ;; EXTENSION QUE FUNCIONARA COMO TRONCAL SIP[51999];type=friendtype=peersecret=context=from-opensips;callerid="Asterisk OpenSIPS" ;username=51999;fromuser=51999fromdomain=host=;call-limit=1outboundproxy=port=5060insecure=port,invite

    ;; VYDA[vyda]type=peer ; Default value for calls outbound to a SIP server context=from-opensipsdirectmedia=no ; El asterisk se queda en medio de los flujos RTPhost= ; IP address VyDa ------------------------

    * Rearrancar asterisk:

  • pkill -9 asteriskasterisk

    Probar con sofphone registrado con el identificador 4963.Como sipserver configurar Probamos a hacer llamadas a extensiones 51XXXX, y desde estas registradas en opensips a las 4XXX de asterisk.

    -------------------------------------------------------------------------------------->>>>>>>>>>>>>>>>>>>SOPORTE RADIUS PARA ASTERISK

  • ;RADIUS_Server=localhostRADIUS_Secret=;; NAS_IP_Address attribute to send in requests;NAS_IP_Address=;

    ......

    ;----------------; EXTENSIONES LOCALES;-------------------------[4961]...auth_type=pamsecret = radius:

    [4962]...auth_type=pamsecret = radius:

    Y/O en la tabla de sipfriends (base de datos asterisk) usando phpmyadmin.Son las dos formas de definir usuarios en asterisk.

    mysql> select * from sipfriends;+------+----------+---------+-----+--------+-------------+-----------+----------+---------+---------+----------+-------------------------+------+--------+---------+------------+-------------+-----------+-----------+| name | username | host | nat | type | canreinvite | context | dtmfmode | qualify | secret | disallow | allow | port | lastms | ipaddr | regseconds | fullcontact | regserver | useragent |+------+----------+---------+-----+--------+-------------+-----------+----------+---------+---------+----------+-------------------------+------+--------+---------+------------+-------------+-----------+-----------+| 4963 | 4963 | dynamic | yes | friend | no | sip-local | | | radius: | all | gsm;ulaw;alaw | 0 | 0 | 0.0.0.0 | 1301312596 | | | |+------+----------+---------+-----+--------+-------------+-----------+----------+---------+---------+----------+-------------------------+------+--------+---------+------------+-------------+-----------+-----------+1 row in set (0.00 sec)

    * Arrancar demonio de asteriskasterisk

    * Conectar consola a demonio para supervisinasterisk -vvvr

    ----------------------------------------------->>>>>>>>>>>>>>>>>>>>VOICEMAIL EN ASTERISK

  • ...; Who the e-mail notification should appear to come [email protected]...; Should the email contain the voicemail as an attachmentattach=yes...; You can override the default program to send e-mail if you wish, too;;mailcmd=/usr/sbin/sendmail -tmailcmd=cat >> /tmp/asteriskvm-mail ...

    * Preparar sonidos en espaol:instalar paquete asterisk-prompt-es

    apt-get install asterisk-prompt-escp -r /usr/share/asterisk/sounds/* /var/lib/asterisk/sounds/

    vi /etc/asterisk/extconfig.conf...sippeers => mysql,asterisk,sipfriendsvoicemail => mysql,asterisk,voicemail_users

    vi /etc/asterisk/extensions.confContempla el acceso a los buzones (prefijo 11, 14, 151) .Usuarios con identificador alfanumrico del opensips pueden tener asociado un buzn con un identificador numrico.Contempla el reencaminado hacia/desde opensips (extensiones 51XXXX), el media-gateway, y/o extensiones registradas directamente en el asterisk (extensiones 4XXX).Contempla el acceso a la tabla MySQL donde se guardan los PIN de acceso a los buzones.Contempla el accounting de llamadas al mundo analgico a travs del media-gateway.

    Revisar que bajo [globals] tenemos:

    [globals].....; Asterisk RealTime Database Connection Settings; Use these variables to specify the connection to the Asterisk; Realtime Database.realdb_host=localhostrealdb_user=asteriskrealdb_pass=asteriskrealdb_db=asterisk

    .....;;Al final nuestro Dialplan

    [from-opensips] include => sip-local [sip-local] include => to-opensips include => to-pstn

    ;; Llamadas a servicio de voicemail ;; En asterisk 1.6.2 Set(CHANNEL(language))=es) exten => 11,1,Ringing exten => 11,2,Set(LANGUAGE()=es) ; Set language to spanish

  • exten => 11,3,VoicemailMain(@vmlocal) exten => 11,4,Hangup

    ;; Dejar mensajes a extensiones 4XXX (locales asterisk) exten => _14XXX,1,Ringing exten => _14XXX,2,MailboxExists(${EXTEN:1}@vmlocal) exten => _14XXX,3,Set(LANGUAGE()=es) exten => _14XXX,n,Voicemail(${EXTEN:1}@vmlocal) exten => _14XXX,n,Hangup

    ;; Dejar mensajes a extensiones 51XXXX (registradas en opensips) exten => _151XXXX,1,Ringing exten => _151XXXX,2,MailboxExists(${EXTEN:1}@vmlocal) exten => _151XXXX,3,Set(LANGUAGE()=es) exten => _151XXXX,n,Voicemail(${EXTEN:1}@vmlocal) exten => _151XXXX,n,Hangup

    exten => _[a-z].,1,Ringing exten => _[a-z].,2,MYSQL(Connect connid ${realdb_host} ${realdb_user} ${realdb_pass} ${realdb_db}) ;En asterisk 1.6.2 quitar \ de delante de los espacios en el SELECT exten => _[a-z].,3,MYSQL(Query resultid ${connid} SELECT\ mailbox\ from\ voicemail_users\ where\ customer_id\ LIKE\ "${EXTEN}") exten => _[a-z].,4,MYSQL(Fetch fetchid ${resultid} mailbox) exten => _[a-z].,5,MailboxExists(${mailbox}@vmlocal) exten => _[a-z].,6,Set(LANGUAGE()=es) exten => _[a-z].,n,Voicemail(${mailbox}@vmlocal) exten => _[a-z].,n,Hangup

    ;Llamada a extensiones locales exten => _4XXX,1,Log(NOTICE, Local Dialing out from ${CALLERID(all)} to ${EXTEN}) exten => _4XXX,2,Dial(SIP/${EXTEN},20,Ttr) exten => _4XXX,3,Set(LANGUAGE()=es) exten => _4XXX,n,VoiceMail(${EXTEN}@vmlocal) exten => _4XXX,n,Hangup()

    [to-pstn] ;; Llamadas hacia PSTN exten => _[0235-9]XXX!,1,Log(NOTICE, PSTN Dialing out from ${CALLERID(all)} to ${EXTEN}) ;/usr/local/src/asterisk-radius-aaa/ast-rad-acc.pl ? exten => _[0235-9]XXX!,n,Set(CDR(accountcode)=${CALLERID(num)}) exten => _[0235-9]XXX!,n,NoOp(${CALLERID(num)}) exten => _[0235-9]XXX!,n,Dial(SIP/${EXTEN}@vyda) exten => _[0235-9]XXX!,n,Hangup()

    [to-opensips] ;; Llamadas hacia OpenSIPS exten => _51XXXX!,1,Log(NOTICE, Llamada hacia Opensips from ${CALLERID(all)} to ${EXTEN}) exten => _51XXXX!,2,Dial(SIP/${EXTEN}@) exten => _51XXXX!,3,Set(LANGUAGE()=es) exten => _51XXXX!,n,VoiceMail(${EXTEN}@vmlocal) exten => _51XXXX!,n,Hangup()

    * Tabla voicemail_users en base de datos asteriskCrear tabla siguiente:

    mysql> CREATE TABLE `voicemail_users` ( `uniqueid` int(11) NOT NULL auto_increment,

  • `customer_id` varchar(11) NOT NULL default '0', `context` varchar(50) NOT NULL default '', `mailbox` varchar(11) NOT NULL default '0', `password` varchar(5) NOT NULL default '0', `fullname` varchar(150) NOT NULL default '', `email` varchar(50) NOT NULL default '', `pager` varchar(50) NOT NULL default '', `tz` varchar(10) NOT NULL default 'central', `attach` varchar(4) NOT NULL default 'yes', `saycid` varchar(4) NOT NULL default 'yes', `dialout` varchar(10) NOT NULL default '', `callback` varchar(10) NOT NULL default '', `review` varchar(4) NOT NULL default 'no', `operator` varchar(4) NOT NULL default 'no', `envelope` varchar(4) NOT NULL default 'no', `sayduration` varchar(4) NOT NULL default 'no', `saydurationm` tinyint(4) NOT NULL default '1', `sendvoicemail` varchar(4) NOT NULL default 'no', `delete` varchar(4) NOT NULL default 'no', `nextaftercmd` varchar(4) NOT NULL default 'yes', `forcename` varchar(4) NOT NULL default 'no', `forcegreetings` varchar(4) NOT NULL default 'no', `hidefromdir` varchar(4) NOT NULL default 'yes', `stamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`uniqueid`), KEY `mailbox_context` (`mailbox`,`context`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;

    Insertar filas con phpmyadmin:

    +----------+-------------+---------+---------+----------+----------+-----------------+-------+---------+--------+--------+---------+----------+--------+----------+----------+-------------+--------------+---------------+--------+--------------+-----------+----------------+-------------+---------------------+| uniqueid | customer_id | context | mailbox | password | fullname | email | pager | tz | attach | saycid | dialout | callback | review | operator | envelope | sayduration | saydurationm | sendvoicemail | delete | nextaftercmd | forcename | forcegreetings | hidefromdir | stamp |+----------+-------------+---------+---------+----------+----------+-----------------+-------+---------+--------+--------+---------+----------+--------+----------+----------+-------------+--------------+---------------+--------+--------------+-----------+----------------+-------------+---------------------+| 1 | 4963 | vmlocal | 4963 | 0 | | | | central | yes | yes | | | no | no | no | no | 1 | yes | no | yes | no | no | yes | 2011-03-28 17:24:33 || 2 | jose | vmlocal | 519961 | 2500 | | | | central | yes | yes | | | no | no | no | no | 1 | yes | no | yes | no | no | yes | 2011-03-31 17:52:39 || 3 | 519961 | vmlocal | 519961 | 9961 | | [email protected] | | central | yes | yes | | | no | no | no | no | 1 | yes | no | yes | no | no | yes | 2011-03-29 13:45:41 || 4 | 519962 | vmlocal | 519962 | 2500 | | [email protected] | | central | yes | yes | | | no | no | no | no | 1 | yes | no | yes | no | no | yes | 2011-03-30 19:11:45 |+----------+-------------+---------+---------+----------+----------+-----------------+-------+---------+--------+--------+---------+----------+--------+----------+----------+-------------+--------------+---------------+--------+--------------+-----------+----------------+-------------+---------------------+4 rows in set (0.00 sec)

    >>>>>>>>>>>>>>>>>>MEDIAGATEWAY VYDA>>>>>>>>>>>>>>>>>>

    De momento se conecta a travs de una extensin normal al mundo analgico (podran aadirse en el equipo utilizado 2 ms).En el puerto 1 se conecta un telfono analgico para pruebas.

  • Lo suyo es disponer de un primario y un puerto PRI para pruebas ms reales.

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Configuracion VYDA >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>telnet

    *conf

    Config>show conf; Showing System Configuration for access-level 15 ...; VyDa-1M Router 9 50 Version 10.6.50

    log-command-errors no configuration set password add device voip-isdn 100add device voip-dummy 1000global-profiles dial ; -- Dial Profiles Configuration -- profile VoIP default profile VoIP inout profile VoIP isdn-type audio;exit;telephony ; -- Telephony configuration -- dial-peer 2 voice-port description "Llamadas a Ext de pruebas 2222" no vad codec g711alaw destination-pattern 2222 target voice-port voip1/0 1 exit; dial-peer 1 sip description "Llamadas sip que pasa a Asterisk" no vad codec g711alaw destination-pattern 519961 destination-pattern 519962 destination-pattern 4961 destination-pattern 4962 target sip-proxy exit; dial-peer 3 voice-port description "Llamadas a PSTN" no vad codec g711alaw destination-pattern 3.... destination-pattern .... destination-pattern 0T target voice-port voip1/0 2 exit

  • ;exit;;;network voip1/0; -- VoIP interface Configuration -- line 1 interface-type fxs line 1 telephone-number 2222; line 2 interface-type fxo line 2 no auto-answer; line 3 interface-type fxo; line 4 interface-type fxo;exit;;network voip1000; -- VoIP interface Configuration -- line 1 telephone-number 100;exit;event ; -- ELS Config -- enable trace subsystem VOIP ALL enable trace subsystem TLPHY ALL enable trace subsystem ISDN ALL enable trace subsystem SIP ALL enable trace subsystem G703 ALLexit;protocol ip; -- Internet protocol user configuration -- internal-ip-address ; address ethernet0/0 255.255.254.0 address ethernet0/1 192.168.8.22 255.255.255.0;; route 0.0.0.0 0.0.0.0 ;;;exit;;;protocol sip; -- SIP protocol configuration -- application address application gateway application server default .....;

  • proxy default; ......;exit;feature ntp ; -- NTP Protocol user configuration -- protocol peer address 1 exit;dump-command-errors end ; --- end ---

    >>>>>>>>>>>>>>>>>>FIN


Recommended