Sunteți pe pagina 1din 49

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 SIP<->Analgicos.

Este es el esquema que queremos montar:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>AUTENTICACION>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>INSTALACION DE UN SERVIDOR LDAP CON SASL<<<<<<<<<<<<<<<<<
Instalar las librerias : libsasl2-modules, libsasl2-dev, libsasl2-2
Buscar los ltimos fuentes de openldap, descargarlos p.ej: en /usr/local/src:
Traer los fuentes de http://www.openldap.org/software/download/
tar zxvf openldap-2.4.25.tgz
cd openldap-2.4.25/
./configure --enable-crypt --with-tls
make depend
make
make install
---------------------------------------------------Editar fichero slapd.conf:
(Resaltar que:
- los schemas cosine, inetorgperson, y nis, que se anyaden slapd.conf, vienen con los fuentes.
- Se anyaden las lineas TLS... para preparar el camino al uso de SASL (cifrado basado en certificados) sobre el puerto ldap
estandar (no ldaps).
- TLSCACertificateFile es igual que TLSCertificateFile porque usamos para las pruebas un certificado autofirmado.
- No usaremos ni tuneles ni ldaps con el servidor freeradius, sino SASL sobre LDAP.)
cd /usr/local/etc/openldap/
vi slapd.conf
#
# See slapd.conf(5) for details on configuration options.
# This file should NOT be world readable.
#
include
/usr/local/etc/openldap/schema/core.schema
include /usr/local/etc/openldap/schema/cosine.schema
include /usr/local/etc/openldap/schema/inetorgperson.schema
include /usr/local/etc/openldap/schema/nis.schema
# Define global ACLs to disable default read access.
# Do not enable referrals until AFTER you have a working directory
# service AND an understanding of referrals.
#referral ldap://root.openldap.org
pidfile
/usr/local/var/run/slapd.pid
argsfile /usr/local/var/run/slapd.args
# Load dynamic backend modules:
# modulepath
/usr/local/libexec/openldap
# moduleload
back_bdb.la
# moduleload
back_hdb.la
# moduleload
back_ldap.la
# Sample security restrictions
#
Require integrity protection (prevent hijacking)
#
Require 112-bit (3DES or better) encryption for updates
#
Require 63-bit encryption for simple bind

# 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:RSA
TLSCACertificateFile /usr/local/etc/openldap/cacerts/server.pem
TLSCertificateFile /usr/local/etc/openldap/cacerts/server.pem
TLSCertificateKeyFile /usr/local/etc/openldap/cacerts/server.key
TLSVerifyClient
allow
#######################################################################
# BDB database definitions
#######################################################################
database bdb
suffix
"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}woasFTat5jTRY
rootpw <pass_del_manager_ldap>
# 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 maintain
index objectClass
eq
--------------------------------------------------------------vi ldap.conf
#
# LDAP Defaults
#
# See ldap.conf(5) for details
# This file should be world readable but not world writable.
BASE
URI

dc=tipx,dc=domain,dc=es
ldap://localhost/

TLS_REQCERT never
TLS_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 cacerts
cd cacerts
openssl req -x509 -nodes -days 365 -subj '/DC=es/DC=domain/DC=tipx/CN=Manager'
-newkey rsa:1024 -keyout server.key -out server.pem
Comprobar certificado
openssl x509 -text -in server.pem
------------------------------------------------Poblar la base de datos de LDAP
Por ejemplo, en /home/jose/ldap, crear los ficheros
vi backend.tipx.local.ldif
# Load dynamic backend modules
dn: cn=module,cn=config
objectClass: olcModuleList
cn: module
olcModulepath: /usr/lib/ldap
olcModuleload: back_hdb
# Database settings
dn: olcDatabase=hdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcHdbConfig
olcDatabase: {1}hdb
olcSuffix: dc=tipx,dc=domain,dc=es
olcDbDirectory: /var/lib/ldap
olcRootDN: cn=Manager,dc=tipx,dc=domain,dc=es
olcRootPW: <pass_del_manager_ldap>
olcDbConfig: set_cachesize 0 2097152 0
olcDbConfig: set_lk_max_objects 1500
olcDbConfig: set_lk_max_locks 1500
olcDbConfig: set_lk_max_lockers 1500
olcDbIndex: objectClass eq
olcLastMod: TRUE
olcDbCheckpoint: 512 30
olcAccess: to attrs=userPassword by dn="cn=admin,dc=tipx,dc=domain,dc=es" write by anonymous aut
h by self write by * none
olcAccess: to attrs=shadowLastChange by self write by * read
olcAccess: to dn.base="" by * read
olcAccess: to * by dn="cn=admin,dc=tipx,dc=domain,dc=es" write by * read
vi frontend.tipx.local.ldif
# Create top-level object in domain
dn: dc=tipx,dc=domain,dc=es
objectClass: top
objectClass: dcObject
objectclass: organization
o: Telefonia IP domain

dc: tipx
description: LDAP Example
# Admin user.
dn: cn=Manager,dc=tipx,dc=domain,dc=es
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: Manager
description: LDAP administrator
userPassword: <pass_del_manager_ldap>
dn: ou=people,dc=tipx,dc=domain,dc=es
objectClass: organizationalUnit
ou: people
dn: ou=groups,dc=tipx,dc=domain,dc=es
objectClass: organizationalUnit
ou: groups
dn: uid=jose,ou=people,dc=tipx,dc=domain,dc=es
objectClass: inetOrgPerson
objectClass: posixAccount
uid: jose
sn: lopez
givenName: Jose
cn: Jose
displayName: Jose
uidNumber: 1000
gidNumber: 10000
userPassword: <pass_del_usuario_jose>
gecos: Jose J
mail: jose@di.domain.es
mobile: 519961
homePhone: 91-624-9961
title: System Administrator
initials: JJ
homeDirectory: /home/jose
dn: cn=eps,ou=groups,dc=tipx,dc=domain,dc=es
objectClass: posixGroup
cn: eps
gidNumber: 10000
--------------------------------En /usr/local/var/openldap-data/ copiar fichero DB_CONFIG.example como DB_CONFIG para evitar un warning/error
cd /usr/local/var/openldap-data/
cp DB_CONFIG.example DB_CONFIG
Creamos la base de datos LDAP:
cd /home/jose/ldap
ldapadd -x -D "cn=Manager,dc=tipx,dc=domain,dc=es" -W -f backend.tipx.local.ldif
ldapadd -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=*)' namingContexts
ldapsearch -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<<<<<<<<<<<<<<<
*Instalar el paquete phpldapadmin.
vi /etc/phpldapadmin/config.php
(Remarcamos en negrita lo que hemos retocado en el fichero original)
<?php
/*********************************************/
/* User-friendly attribute translation
*/
/*********************************************/
/* Use this array to map attribute names to user friendly names. For example, if
you don't want to see "facsimileTelephoneNumber" but rather "Fax". */
$config->custom->appearance['friendly_attrs'] = array(
'facsimileTelephoneNumber' => 'Fax',
'gid'
=> 'Group',
'mail'
=> 'Email',
'telephoneNumber'
=> 'Telephone',
'uid'
=> 'User Name',
'userPassword'
=> 'Password'
);
/*********************************************/
/* Define your LDAP servers in this section */
/*********************************************/
$servers = new Datastore();
/* $servers->NewServer('ldap_pla') must be called before each new LDAP server
declaration. */
$servers->newServer('ldap_pla');
/* A convenient name that will appear in the tree viewer and throughout
phpLDAPadmin to identify this LDAP server to users. */
$servers->setValue('server','name','My LDAP Server');
/* Examples:
'ldap.example.com',
'ldaps://ldap.example.com/',
'ldapi://%2fusr%local%2fvar%2frun%2fldapi'
(Unix socket at /usr/local/var/run/ldap) */
$servers->setValue('server','host','127.0.0.1');

/* 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<<<<<<<<<<<<<<<


apt-get install freeradius
(o bien usar synaptics)
Hay distintas formas de autenticar y dar de alta usuarios en el servidor radius, probaremos las siguientes funcionando a la
vez en el mismo servidor:
- fichero plano de usuarios locales del servidor radius
- base de datos mysql del servidor radius
- contra el servidor ldap y por tanto en la bd del servidor LDAP
----------------------------------------------------------* Creamos un usuario para probar el servidor radius, y una extensin que utilizaremos para el SIP trunk entre asterisk y
opensips:
vi /etc/freeradius/users
...
joselocal Cleartext-Password := "<pass_de_joselocal>"
Reply-Message = "Authenticated",
Sip-Rpid = "4961"
51999 Cleartext-Password := "<secreto_del_sip_trunk>"
...
----------------------------------------------------------vi /etc/freeradius/proxy.conf
proxy server {
default_fallback = no
}
home_server localhost {
type = auth
ipaddr = 127.0.0.1
port = 1812
secret = <secreto_del_servidor_radius>
require_message_authenticator = no
response_window = 20
zombie_period = 40
revive_interval = 120
status_check = status-server
check_interval = 30
num_answers_to_alive = 3
coa {
# Initial retransmit interval: 1..5
irt = 2
# Maximum Retransmit Timeout: 1..30 (0 == no maximum)
mrt = 16
# Maximum Retransmit Count: 1..20 (0 == retransmit forever)
mrc = 5
# Maximum Retransmit Duration: 5..60
mrd = 30
}
}
#

# 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 <ip-nuestro-ciente> {
secret
= <secreto_del_servidor_radius>
shortname
= localhost
}
La direccin IP que deber figurar en <ip-nuestro-cliente>, 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, acc
ATTRIBUTE Sip-Method
101 integer # Schulzrinne, acc
ATTRIBUTE Sip-Response-Code
102 integer # Schulzrinne, acc
ATTRIBUTE Sip-Cseq
103 string # Schulzrinne, acc
ATTRIBUTE Sip-To-Tag
104 string # Schulzrinne, acc
ATTRIBUTE Sip-From-Tag
105 string # Schulzrinne, acc
ATTRIBUTE Sip-Translated-Request-URI 107 string # Proprietary, acc
ATTRIBUTE Sip-Src-IP
108 string # Proprietary, acc
ATTRIBUTE Sip-Src-Port
109 string # Proprietary, acc
ATTRIBUTE Digest-Response 206 string # Sterman, auth_radius
ATTRIBUTE Sip-Uri-User
208 string # Proprietary, auth_radius
ATTRIBUTE Sip-Group
211 string # Proprietary, group_radius
ATTRIBUTE Sip-Rpid
213 string # Proprietary, auth_radius
ATTRIBUTE SIP-AVP
225 string # Proprietary, avp_radius
ATTRIBUTE Digest-Realm
1063 string # Sterman, auth_radius
ATTRIBUTE Digest-Nonce
1064 string # Sterman, auth_radius
ATTRIBUTE Digest-Method
1065 string # Sterman, auth_radius
ATTRIBUTE Digest-URI
1066 string # Sterman, auth_radius
ATTRIBUTE Digest-QOP
1067 string # Sterman, auth_radius
ATTRIBUTE Digest-Algorithm
1068 string # Sterman, auth_radius
ATTRIBUTE Digest-Body-Digest
1069 string # Sterman, auth_radius
ATTRIBUTE Digest-CNonce
1070 string # Sterman, auth_radius
ATTRIBUTE Digest-Nonce-Count
1071 string # Sterman, auth_radius
ATTRIBUTE Digest-User-Name
1072 string # Sterman, auth_radius
#Atributos para recuperar perfiles de usuario

ATTRIBUTE
ATTRIBUTE

UserPresenceID
AliasMail

1073
1074

### CISCO Vendor Specific Attributes ###


#VENDOR Cisco
9
#ATTRIBUTE Cisco-AVPair 1 string Cisco
### Acct-Status-Type Values ###
#VALUE Acct-Status-Type Start
#VALUE Acct-Status-Type Stop
VALUE Acct-Status-Type Failed

1
2
15

string
string

# Sterman, auth_radius
# Sterman, auth_radius

# VSA, auth_radius
# RFC2866, acc
# RFC2866, acc
# RFC2866, acc

### Service-Type Values ###


VALUE Service-Type
Call-Check
10 # RFC2865, uri_radius
VALUE Service-Type
Group-Check
12 # Proprietary, group_radius
VALUE Service-Type
Sip-Session
15 # Schulzrinne, acc, auth_radius
VALUE Service-Type
SIP-Caller-AVPs 30 # Proprietary, avp_radius
VALUE Service-Type
SIP-Callee-AVPs 31 # Proprietary, avp_radius
VALUE Sip-Method
VALUE Sip-Method
VALUE Sip-Method
VALUE Sip-Method

INVITE
CANCEL
ACK
BYE

1
2
4
8

# Proprietary, acc
# Proprietary, acc
# Proprietary, acc
# Proprietary, acc

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


apt-get install mysql-server
apt-get install mysql-client
...
>>>>>>>>>>>INSTALAR GESTOR PHPMYADMIN DE MYSQL DESDE WEB<<<<<<<<<<<
Para facilitar la gestin de las tablas (que sern unas cuantas) recomiendo instalarse esta herramienta.
apt-get install phpmyadmin
mkdir /var/www/phpmyadmin
cd /var/www/phpmyadmin
ln -s /usr/share/phpmyadmin/setup/ setup
activar password
sudo htpasswd /etc/phpmyadmin/htpasswd.setup admin
Con un web browser acceder a : http://localhost/phpmyadmin/setup/
>>>>>>>>>>>>>>> SOPORTE MYSQL PARA RADIUS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<
apt-get install freeradius-mysql
mysql -uroot -p
create database radius;
mysql -uroot -p radius < /etc/freeradius/sql/mysql/schema.sql
Cambiar el password por defecto en:
vi /etc/freeradius/sql/mysql/admin.sql

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 en
vi /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 -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 275
Server version: 5.1.41-3ubuntu12.10 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use radius
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> 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 | josejuan@tipx.domain.es | Cleartext-Password | := | <passw> |
+----+-----------------------+--------------------+----+----------+
1 row in set (0.00 sec)
donde <passw> 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 |
+-----------------------+-----------+----------+
| josejuan@tipx.domain.es | static |
1|
+-----------------------+-----------+----------+
1 row in set (0.00 sec)
Probaremos el usuario cuando tengamos instalada la maqueta de telefona IP.
>>>>>>>>>>>>> SOPORTE LDAP PARA RADIUS <<<<<<<<<<<<<<<<<
apt-get install freeradius-ldap
Es importante aadir el {ok=return} para ldap, y colocar ldap{...}, ..., sql{...},files{...} en el orden del ejemplo. De esta
forma, cuando se busca un usuario, primero se mira en el servidor LDAP, luego en la bd mysql del servidor radius, y
finalmente en el fichero users de ste:
vi /etc/freeradius/sites-enabled/default
authorize {
preprocess
#
auth_log
chap
mschap
digest
#
wimax
#
IPASS
suffix
#
ntdomain
ldap {
ok = return
}
eap {
ok = return
}
unix
sql {
ok = return
}
files {
ok = return
}

#
#
#

#
#
#
}

etc_smbpasswd
daily
checkval
expiration
logintime
pap
Autz-Type Status-Server {
}

authenticate {
Auth-Type PAP {
pap
}
Auth-Type CHAP {
chap
}
Auth-Type MS-CHAP {
mschap
}
digest
#
pam
unix
#
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}- %{%{AcctDelay-Time}:-0}}"
#
}
acct_unique
#
IPASS
suffix
#
ntdomain
files
}
accounting {
detail
#
daily
unix
radutmp
#
sradutmp

#
#
#
#
#
#
#
#
#
}

main_pool
sql
if (noop) {
ok
}
sql_log
pgsql-voip
attr_filter.accounting_response
Acct-Type Status-Server {
}

session {
radutmp
sql
}
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 = <pass_del_manager_ldap>
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: 20
timeout = 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) connections
start_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 ldapcerts
cd 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<<<<<<<<<<<<<<<<<<<<
Contra el usuario de prueba definido en users:
radtest -d /etc/freeradius joselocal <pass_del_usuario_jose> \
localhost 1812 <secreto_del_servidor_radius>
Los usuarios definidos en ldap, o en las tablas mysql de radius, los configuramos en los ejemplos para usar Digest-HA1 en
vez de password en claro viajando por la red, NO pueden probarse con radtest, habra que usar cuando los tengamos listos
directamente los clientes de telefonia IP.
>>>>>>>>>SUSTITUIR PASSWORD EN CLARO EN LDAP POR DIGEST-HA1<<<<<<<<<
Si no queremos almacenar la password en claro:
vi /etc/freeradius/ldap.attrmap
aadir la linea
checkItem
Digest-HA1
userPassword
vi /etc/freeradius/modules/ldap
# password_attribute = userPassword
dejarla comentada.
echo -n 'jose:tipx.domain.es:<pass_del_usuario>' | md5sum
f9aa8d3fb7f4a9d982b2889ffb36dfca Guardar el cdigo md5 en userPassword (ver /home/jose/ldap/frontend.tipx.local.ldif)
cd /home/jose/ldap/
vi frontend.tipx.local.ldif
dn: uid=jose,ou=people,dc=tipx,dc=domain,dc=es
objectClass: inetOrgPerson
objectClass: posixAccount
uid: jose
sn: lopez
givenName: Jose
cn: Jose
displayName: Jose
uidNumber: 1000
gidNumber: 10000
userPassword: f9aa8d3fb7f4a9d982b2889ffb36dfca
gecos: Jose J
mail: jose@di.domain.es
mobile: 519961
homePhone: 91-624-9961

title: System Administrator


initials: JJ
homeDirectory: /home/jose
-----------------------------Ahora hay que hacer ese cambio efectivo en la base de datos de LDAP.
Se puede borrar la entrada uid=jose con phpldapadmin
y luego ejecutar
ldapadd -x -D "cn=Manager,dc=tipx,dc=domain,dc=es" -W -f frontend.tipx.local.ldif
asi aade una entrada limpia.
------------------------------

>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>MAQUETA DE VOIP>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>> ALTA EN DNS DE NUESTRO ROUTER SIP <<<<<<<<<<<<<<
Es recomendable dar de alta en el DNS un registro para dar a conocer el SIP router de nuestro dominio a los clientes SIP
externos distribuidos por Internet. Para ello en el mapa directo de nuestro dominio en el servidor DNS, supesto que
tenemos bind:
....
_sip._udp.tipx.domain.es

IN

SRV

0 0 5062

tipx.domain.es.

A
IN

<ip-servidor-opensips>
CNAME
ejemplo.domain.es.

...

ejemplo
tipx

IN

....
>>>>>>>>>INSTALAR OPENSIPS AUTENTICANDO CONTRA RADIUS<<<<<<<<<<<<
* Instalar paquete flex
(bien con synaptic bien con "apt-get install flex")
* Instalamos OPENSIPS a partir de los fuentes (ltima versin estable 1.6.4):
cd /usr/local/src/
svn co https://opensips.svn.sourceforge.net/svnroot/opensips/branches/1.6 opensips_1_6
cd opensips_1_6
make include_modules="db_mysql" prefix="/" all
make include_modules="db_mysql" prefix="/" install
make modules modules=modules/aaa_radius
cp /usr/local/src/opensips_1_6/modules/aaa_radius/aaa_radius.so /lib/opensips/modules/
* Los mdulos debern cogerse de la librera donde los hemos instalado:
vi /usr/local/sbin/opensipsdbctl
if [ -z "$MYLIBDIR" ] ; then
#
MYLIBDIR="/usr/local/lib64/opensips/opensipsctl"
MYLIBDIR="/lib/opensips/opensipsctl"
if [ ! -d "$MYLIBDIR" ]; then
MYLIBDIR=$MYDIR
fi
fi
*Preparamos la creacin de la bd:
vi /etc/opensips/opensipsctlrc
(Es importante ver que todos los modulos que vayamos a usar tienen sus tablas incluidas en las directivas

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.org
SIP_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 host
DBHOST=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 user
DBRWUSER=opensips
## password for database read/write user
# DBRWPW="opensipsrw"
DBRWPW="mb.4818"
## database read only user
DBROUSER=opensipsro
## password for database read only user
# DBROPW=opensipsro
DBROPW=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 modules
STANDARD_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=xmlrpc
CTLENGINE="FIFO"
## path to FIFO file
OSIPS_FIFO="/tmp/opensips_fifo"
## MI_CONNECTOR control engine: FIFO, UNIXSOCK, UDP, XMLRPC
MI_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.pid
PID_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-dev
apt-get install libradiusclient-ng2
* Editamos ficheros de configuracin del cliente radius:
vi /etc/radiusclient-ng/radiusclient.conf
aadimos
authserver
<ip-servidor-radius>
acctserver
<ip-servidor-radius>
vi /etc/radiusclient-ng/servers
aadimos
<ip-servidor-radius>
<secreto_del_servidor_radius>
vi /etc/radiusclient-ng/dictionary
aadimos
$INCLUDE /etc/radiusclient-ng/dictionary.ser
es 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 <usuario>@tipx.domain.es).
Ponemos a escuchar opensips en el puerto 5062 para que coexista en la maqueta con asterisk en el 5060
Esto 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 <anca@voice-system.ro>
#
# 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=3
log_stderror=no
log_facility=LOG_LOCAL0
fork=yes
children=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 path
mpath="/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 UAs
modparam("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 logic
route{
xlog("L_NOTICE","Llamada a opensips From ($fu)\n");
# initial sanity checks -- messages with
# max_forwards==0, or excessively long requests
if (!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-routing
if (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 processing
if (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 routing
if (!is_method("REGISTER|MESSAGE")) {
xlog("L_NOTICE","record route\n");
record_route();
}
# account only INVITEs
if (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 RADIUS
if (!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 RURI
xlog("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 server
if(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 bucles
xlog("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 also
xlog("L_NOTICE","missed call: log it\n");
setflag(2);
route(1);
}
route[1] {
# for INVITEs enable some additional helper routes
if (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 voicemail
if(!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 Server
rewritehostport("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 bucles
xlog("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 <ip-servidor-opensips>:5062. Recordemos que hemos puesto opensips en este puerto para dejar
asterisk en el 5060. Comprobar con:
netstat -nlp
-------------------------------------------------------------------------->>>>>>>>>>>>>>>>>>AADIR ACCOUNTING CON CDRs<<<<<<<<<<<<<<<<<<<<<<<
* Modificamos las tablas acc y missed_calls de opensips para tener los atributos "extra":
mysql> drop table acc;
Query OK, 0 rows affected (0.00 sec)
mysql> drop table missed_calls
-> ;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE `acc` (
-> `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 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 <<<<<<<<<<<<<<<<
El servidor asterisk actuar como:
- puente hacia el mundo analgico (a travs de un media-gateway vyda de TELDAT).
- gestor de los buzones de voz (voicemail) (usando el prefijo *98).
Elegimos los fuentes de la version 1.4.8 para parchearlos y tener soporte de radius en asterisk,
asi podemos autenticar extensiones directamente en asterisk usando radius igual que opensips.
.

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.gz
cd asterisk-1.4.8
./configure
make
make install
vi /etc/asterisk/sip.conf
Aadir al final
;------------------------; EXTENSIONES LOCALES
;------------------------[4961]
type=friend
username=4961
host=dynamic
context=sip-local
secret = <pass_de_4961>
[4962]
type=friend
username=4962
host=dynamic
context=sip-local
secret = <pass_de_4962>
vi /etc/asterisk/extensions.conf
Aadir al final nuestro pequeo dialplan para probar
[sip-local]
exten => 4961,1,Dial(SIP/4961)
exten => 4962,1,Dial(SIP/4962)
* Arrancar demonio de asterisk
asterisk
* Conectar consola a demonio para supervisin
asterisk -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 <ip-servidor-asterisk>, para registrar directamente en asterisk.
---------------------------------------->>>>>>>INSTALACION DE PBX ASTERISK CON SOPORTE MYSQL<<<<<<<<<<<
Ahora vamos a aadir soporte MySQL:
Traer los fuentes de http://downloads.asterisk.org/pub/telephony/asterisk/old-releases/
tar zxvf asterisk-addons-1.4.8.tar.gz
cd asterisk-addons-1.4.8
vi formats/format_mp3.c
Para evitar errores en la compilacion realizamos los cambios puestos en evidencia por el siguiente comando:

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.1
dbname = asterisk
dbuser = asterisk
dbpass = asterisk
dbport = 3306
;dbsock = /tmp/mysql.sock
dbsock = /var/run/mysqld/mysqld.sock
vi /etc/asterisk/modules.conf
En [modules] insertar

preload => app_addon_sql_mysql.so


preload => res_config_mysql.so
preload => cdr_addon_mysql.so
vi /etc/asterisk/sip.conf
En algn lugar de [general] insertar:
;------------------------------------------------------------------------------------------;---------------- DATABASE MySQL ----------------------------------------------------------;------------------------------------------------------------------------------------------dbasename=asterisk
dbhost=localhost
dbuser=asterisk
dbpass=asterisk
vi /etc/asterisk/extconfig.conf
En [settings] tener una lnea como:
sippeers => mysql,asterisk,sipfriends
mysql -u root -p
mysql> 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","<pass_del_usuario>","sip-local")
* En otras versiones de asterisk (p.ej. la 1.6.2 si hemos instalado desde el paquete),
apt-get build-dep asterisk-mysql
apt-get -b source asterisk-mysql
dpkg -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 asterisk
asterisk
* 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 |
|
| <pass_de_4963> | 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=localhost
realdb_user=asterisk
realdb_pass=asterisk
realdb_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}@<ip-servidor-opensips>)
vi /etc/asterisk/sip.conf
registro ante opensips:
;; REGISTRO ANTE OPENSIPS
register => 51999@tipx.domain.es:<secreto_del_sip_trunk>@<ip-servidor-opensips>:5062/51999
registertimeout=20
registerattempts=10
....
;----------------------------------------------------; EXTENSIONES LOCALES
;------------------------[4961]
type=friend
username=4961
secret=<pass_del_usuario>
host=dynamic
context=sip-local
[4962]
type=friend
username=4962
secret=<pass_del_usuario>
host=dynamic
context=sip-local
;; EXTENSION QUE FUNCIONARA COMO TRONCAL SIP
[51999]
;type=friend
type=peer
secret=<secreto_del_sip_trunk>
context=from-opensips
;callerid="Asterisk OpenSIPS" <51999>
;username=51999
;fromuser=51999
fromdomain=<ip-servidor-opensips>
host=<ip-servidor-opensips>
;call-limit=1
outboundproxy=<ip-servidor-asterisk>
port=5060
insecure=port,invite
;; VYDA
[vyda]
type=peer
; Default value for calls outbound to a SIP server
context=from-opensips
directmedia=no
; El asterisk se queda en medio de los flujos RTP
host=<ip-mediagateway>
; IP address VyDa
-----------------------* Rearrancar asterisk:

pkill -9 asterisk
asterisk
Probar con sofphone registrado con el identificador 4963.
Como sipserver configurar <ip-servidor-asterisk>
Probamos a hacer llamadas a extensiones 51XXXX, y desde estas registradas en opensips a las 4XXX de asterisk.
------------------------------------------------------------------------------------->>>>>>>>>>>>>>>>>>>SOPORTE RADIUS PARA ASTERISK<<<<<<<<<<<<<<<
apt-get install libncurses5-dev
compilar asterisk a partir de los fuentes 1.4.8
tar zxvf asterisk-1.4.8.tar.gz
cd asterisk-1.4.8
./configure
cd channels/
vi chan_iax2.c
Para evitar errores hay que hacer los cambios destacados por el siguiente comando:
root@server:/usr/local/src/asterisk-1.4.8# diff channels/chan_iax2.c channels/chan_iax2.c.orig
1400c1400
<
ifd = open(s, O_RDONLY,0666);
-->
ifd = open(s, O_RDONLY);
1405c1405
<
fd = open(s2, O_RDWR | O_CREAT | O_EXCL, 0666);
-->
fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
10307c10307
<
timingfd = open("/dev/zap/timer", O_RDWR, 0666);
-->
timingfd = open("/dev/zap/timer", O_RDWR);
10310c10310
<
timingfd = open("/dev/zap/pseudo", O_RDWR, 0666);
-->
timingfd = open("/dev/zap/pseudo", O_RDWR);
Bajamos el parche de asterisk+radius:
wget 'https://issues.asterisk.org/file_download.php?file_id=14941&type=bug' -O - | patch -p0
wget 'https://issues.asterisk.org/file_download.php?file_id=14941&type=bug' -o \
parcheasteriskradius
(hemos salvado el parche en parcheasteriskradius por si hay que revisarlo).
cd ../asterisk-1.4.8-radius-1.0a/
cp res/res_auth.c ../asterisk-1.4.8/res/
cp include/asterisk/auth.h ../asterisk-1.4.8/include/asterisk/
cd ../asterisk-1.4.8
make
make install
vi /etc/asterisk/extensions.conf
Aadir bajo [globals]
; RADIUS Client Configuration
; This is defaul configuration

;
RADIUS_Server=localhost
RADIUS_Secret=<secreto_servidor_radius>
;
; NAS_IP_Address attribute to send in requests
;
NAS_IP_Address=<ip-servidor-asterisk>
;
......
;---------------; EXTENSIONES LOCALES
;------------------------[4961]
...
auth_type=pam
secret = radius:
[4962]
...
auth_type=pam
secret = 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 asterisk
asterisk
* Conectar consola a demonio para supervisin
asterisk -vvvr
---------------------------------------------->>>>>>>>>>>>>>>>>>>>VOICEMAIL EN ASTERISK<<<<<<<<<<<<<<<<<<<<<<<<
Buzones de voz en tabla voicemail_users, en asterisk, accedidos desde opensips, con usuarios numricos o alfanumricos,
pero buzones SIEMPRE numricos, si no, asterisk no los entiende (la funcin Voicemail en extensions.conf)
Vamos a configurar la posibilidad de cuando se deja un mensaje en el buzn de voz de un usuario poder enviarle un mensaje
de correo electrnico. Para evitar configurar sendmail, en su lugar lo que hacemos es dejar el mensaje en el directorio (si no
lo hemos cambiado):
/var/spool/asterisk/voicemail/vmlocal/<identificador_de_buzon_de_usuario>
vi /etc/asterisk/voicemail.conf
[general]
format=wav49|gsm|wav

...
; Who the e-mail notification should appear to come from
serveremail=asterisk@tipx.domain.es
...
; Should the email contain the voicemail as an attachment
attach=yes
...
; You can override the default program to send e-mail if you wish, too
;
;mailcmd=/usr/sbin/sendmail -t
mailcmd=cat >> /tmp/asteriskvm-mail
...
* Preparar sonidos en espaol:
instalar paquete asterisk-prompt-es
apt-get install asterisk-prompt-es
cp -r /usr/share/asterisk/sounds/* /var/lib/asterisk/sounds/
vi /etc/asterisk/extconfig.conf
...
sippeers => mysql,asterisk,sipfriends
voicemail => mysql,asterisk,voicemail_users
vi /etc/asterisk/extensions.conf
Contempla 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=localhost
realdb_user=asterisk
realdb_pass=asterisk
realdb_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}@<ip-servidor-opensips>)
exten => _51XXXX!,3,Set(LANGUAGE()=es)
exten => _51XXXX!,n,VoiceMail(${EXTEN}@vmlocal)
exten => _51XXXX!,n,Hangup()
* Tabla voicemail_users en base de datos asterisk
Crear 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 |
| jose@di.domain.es |
| 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 |
| jose@di.domain.es |
| 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 <ip-media-gateway>
<password_acceso_vyda>
*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 <password_acceso_vyda>
add device voip-isdn 100
add device voip-dummy 1000
global-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 ALL
exit
;
protocol ip
; -- Internet protocol user configuration -internal-ip-address <ip-mediagateway>
;
address ethernet0/0 <ip-mediagateway> 255.255.254.0
address ethernet0/1 192.168.8.22 255.255.255.0
;
;
route 0.0.0.0 0.0.0.0 <ip-default-gateway>
;
;
;
exit
;
;
;
protocol sip
; -- SIP protocol configuration -application address <ip-mediagateway>
application gateway
application server default
.....
;

proxy <ip-servidor-asterisk> default


;
......
;
exit
;
feature ntp
; -- NTP Protocol user configuration -protocol
peer address 1 <ip-servidor-ntp>
exit
;
dump-command-errors
end
; --- end -->>>>>>>>>>>>>>>>>>FIN<<<<<<<<<<<<<<<<<<<<<<<<<<

S-ar putea să vă placă și