Initial commit: FreePBX 17 VoIP setup for horux360, consultoria-as, nexus

This commit is contained in:
2026-04-29 06:30:49 +00:00
commit 4e4a120e9b
12 changed files with 2427 additions and 0 deletions

82
README.md Normal file
View File

@@ -0,0 +1,82 @@
# VoIP FreePBX 17 - Setup Completo
Repositorio con la instalación, configuración y documentación del sistema VoIP on-premise para las 3 empresas del grupo.
## 🏢 Empresas
- **Horux360** → Extensiones `100-199`
- **Consultoria-AS** → Extensiones `200-299`
- **Nexus** → Extensiones `300-399`
## 📁 Estructura del Repositorio
```
├── scripts/
│ ├── install-freepbx17-ubuntu2404.sh # Instalación completa desde cero
│ └── setup-extensions-ivr.sh # Crear extensiones e IVR post-install
├── configs/
│ ├── asterisk-manager.conf # Configuración AMI (Odoo)
│ ├── jail.local # Fail2Ban
│ ├── freepbx.conf # VirtualHost Apache
│ ├── odbc.ini # Conexión CDR a MySQL
│ └── odbcinst.ini # Drivers ODBC
├── docs/
│ └── DOCUMENTACION_VOIP.md # Guía completa de uso
└── sql/
├── asterisk_schema.sql # Esquema BD principal
└── asteriskcdrdb_schema.sql # Esquema BD CDR
```
## 🚀 Instalación Rápida
En un servidor Ubuntu 24.04 LTS limpio:
```bash
git clone https://git.consultoria-as.com/ialcarazsalazar/voip-freepbx-setup.git
cd voip-freepbx-setup
chmod +x scripts/*.sh
sudo ./scripts/install-freepbx17-ubuntu2404.sh
sudo ./scripts/setup-extensions-ivr.sh
```
## 🔧 Requisitos
- Ubuntu 24.04 LTS
- 4 vCPUs, 8GB RAM, 50GB disco (mínimo recomendado)
- Acceso root
- Conexión a internet
## 🌐 Accesos por Defecto
| Servicio | URL / Credencial |
|----------|------------------|
| Panel Admin FreePBX | `http://IP-SERVIDOR/admin` |
| Usuario Admin | `admin` / `FreePBX2026!` |
| AMI (Odoo) | `odoo` / `OdooAMI2026!` |
## 📞 Extensiones Configuradas
| Ext | Empresa | Secret |
|-----|---------|--------|
| 100 | Horux360 | `Horux100!` |
| 200 | Consultoria-AS | `Consult200!` |
| 300 | Nexus | `Nexus300!` |
## 📊 Dashboard
Accede a `Reports → CDR Reports` desde el panel admin para ver:
- Historial de llamadas
- Grabaciones
- Métricas por extensión y empresa
## 🔌 Integración Odoo
1. Instalar módulos de [OCA/connector-telephony](https://github.com/OCA/connector-telephony)
2. Configurar servidor Asterisk en Odoo:
- IP: `IP_DEL_SERVIDOR_VOIP`
- Puerto: `5038`
- Usuario/Pass: `odoo` / `OdooAMI2026!`
## 📝 Licencia
Configuración propietaria del grupo. Uso interno únicamente.

View File

@@ -0,0 +1,44 @@
;--------------------------------------------------------------------------------;
; Do NOT edit this file as it is auto-generated by FreePBX. All modifications to ;
; this file must be done via the web gui. There are alternative files to make ;
; custom modifications (manager_custom.conf). ;
;--------------------------------------------------------------------------------;
;*******************************************************************************
; AUTO-GENERATED AND CUSTOM USER MANAGER INCLUDED HERE *
;*******************************************************************************
;
; AMI - Asterisk Manager interface
;
; FreePBX needs this to be enabled. Note that if you enable it on a different IP, you need
; to assure that this can't be reached from un-authorized hosts with the ACL settings (permit/deny).
; Also, remember to configure non-default port or IP-addresses in FreePBX Advanced Setting.
;
; The AMI connection is used both by the portal and the operator's panel in FreePBX.
;
; FreePBX assumes an AMI connection to 0.0.0.0:5038 by default.
;
[general]
enabled = yes
port = 5038
bindaddr = 0.0.0.0
displayconnects=no
[a8e9fc7b6dadf70e61ca49c69040f2ec]
secret = 68206dce315dce448e4cf8e863d0cfac
deny=0.0.0.0/0.0.0.0
permit=127.0.0.1/255.255.255.0
read = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originate,message
write = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originate,message
writetimeout = 5000
#include manager_additional.conf
#include manager_custom.conf
[odoo]
secret = OdooAMI2026!
deny = 0.0.0.0/0.0.0.0
permit = 192.168.10.0/255.255.255.0
read = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan
write = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan
writetimeout = 5000

View File

@@ -0,0 +1,32 @@
;--------------------------------------------------------------------------------;
; Do NOT edit this file as it is auto-generated by FreePBX. ;
;--------------------------------------------------------------------------------;
; For information on adding additional paramaters to this file, please visit the ;
; FreePBX.org wiki page, or ask on IRC. This file was created by the new FreePBX ;
; BMO - Big Module Object. Any similarity in naming with BMO from Adventure Time ;
; is totally deliberate. ;
;--------------------------------------------------------------------------------;
[0]
#include pjsip_custom.conf
#include pjsip.transports.conf
#include pjsip.transports_custom_post.conf
#include pjsip.endpoint.conf
#include pjsip.endpoint_custom_post.conf
#include pjsip.aor.conf
#include pjsip.aor_custom_post.conf
#include pjsip.auth.conf
#include pjsip.auth_custom_post.conf
#include pjsip.registration.conf
#include pjsip.registration_custom_post.conf
#include pjsip.identify.conf
#include pjsip.identify_custom_post.conf
[global]
type=global
user_agent=FPBX-17.0.28(21.12.2)
use_callerid_contact=no
keep_alive_interval=90
taskprocessor_overload_trigger=pjsip_only
#include pjsip_custom_post.conf

11
configs/freepbx.conf Normal file
View File

@@ -0,0 +1,11 @@
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/freepbx-error.log
CustomLog ${APACHE_LOG_DIR}/freepbx-access.log combined
</VirtualHost>

31
configs/jail.local Normal file
View File

@@ -0,0 +1,31 @@
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
backend = auto
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
[asterisk]
enabled = true
port = 5060,5061
filter = asterisk
logpath = /var/log/asterisk/full
maxretry = 5
[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/*error.log
[apache-badbots]
enabled = true
port = http,https
filter = apache-badbots
logpath = /var/log/apache2/*error.log
maxretry = 2

17
configs/odbc.ini Normal file
View File

@@ -0,0 +1,17 @@
[asteriskcdrdb]
Description=MySQL connection to asteriskcdrdb database
Driver=MariaDB Unicode
SERVER=localhost
PORT=3306
DATABASE=asteriskcdrdb
OPTION=3
CHARSET=utf8
[MySQL-asteriskcdrdb]
Description=MySQL connection to asteriskcdrdb database
Driver=MariaDB Unicode
SERVER=localhost
PORT=3306
DATABASE=asteriskcdrdb
OPTION=3
CHARSET=utf8

6
configs/odbcinst.ini Normal file
View File

@@ -0,0 +1,6 @@
[MariaDB Unicode]
Driver=libmaodbc.so
Description=MariaDB Connector/ODBC(Unicode)
Threading=0
UsageCount=1

239
docs/DOCUMENTACION_VOIP.md Normal file
View File

@@ -0,0 +1,239 @@
# Documentación del Sistema VoIP - FreePBX 17
## Información General
- **Servidor:** Ubuntu 24.04 LTS
- **IP del Servidor:** `192.168.10.114`
- **PBX:** FreePBX 17.0.28
- **Asterisk:** 21.12.2
- **Empresas:** Horux360, Consultoria-AS, Nexus
---
## Accesos Principales
### Panel Web FreePBX (Administración)
- **URL:** http://192.168.10.114/admin
- **Usuario:** `admin`
- **Contraseña:** `FreePBX2026!`
### Panel de Usuario (UCP - User Control Panel)
- **URL:** http://192.168.10.114/ucp
- Las extensiones pueden acceder aquí para ver sus grabaciones, voicemail y llamadas.
---
## Extensiones Configuradas
| Extensión | Empresa | Nombre | Contraseña SIP | Grabación |
|-----------|---------|--------|----------------|-----------|
| 100 | Horux360 | Horux360 - Admin | `Horux100!` | Siempre |
| 200 | Consultoria AS | Consultoria AS - Admin | `Consult200!` | Siempre |
| 300 | Nexus | Nexus - Admin | `Nexus300!` | Siempre |
### Softphones Recomendados
- **Windows:** MicroSIP (https://www.microsip.org)
- **Mac:** Telephone (App Store)
- **Móvil:** Zoiper (iOS/Android)
- **WebRTC:** UCP incluye teléfono web
### Configuración de Softphone
- **Servidor/SIP Domain:** `192.168.10.114`
- **Puerto:** `5060` (UDP)
- **Transporte:** UDP
- **Usuario:** Número de extensión (ej. `100`)
- **Contraseña:** Según tabla arriba
---
## IVR (Menú Principal)
- **Nombre:** MenuPrincipal
- **Contexto Asterisk:** `ivr-1`
- **Opciones:**
- `1` → Horux360 (Extensión 100)
- `2` → Consultoria AS (Extensión 200)
- `3` → Nexus (Extensión 300)
Para asignar una llamada entrante al IVR, configura la ruta entrante (Inbound Route) con destino `IVR → MenuPrincipal`.
---
## Grabación de Llamadas
- **Estado:** Activada para todas las extensiones
- **Almacenamiento:** `/var/spool/asterisk/monitor/`
- **Formato:** WAV (por defecto)
- **Acceso:** Panel web FreePBX → Reports → CDR Reports (incluye link a grabaciones)
- **Retención:** Configurable en FreePBX. Actualmente sin límite de rotación.
---
## Dashboard de Métricas (CDR)
- **URL:** http://192.168.10.114/admin → Reports → CDR Reports
- **Datos disponibles:**
- Historial de llamadas (entrantes/salientes)
- Duración
- Estado (contestada, perdida, ocupada)
- Grabaciones asociadas
- Filtrado por fecha, extensión, número, etc.
---
## Base de Datos
### MariaDB
- **Root Password:** `FreePBXRoot2026!`
- **FreePBX User:** `asteriskuser`
- **FreePBX Password:** `AsteriskDB2026!`
- **Bases de datos:** `asterisk` (configuración), `asteriskcdrdb` (registro de llamadas)
---
## Firewall (UFW)
Puertos abiertos:
- `22/tcp` - SSH
- `80/tcp` - HTTP (FreePBX)
- `443/tcp` - HTTPS
- `5060/tcp+udp` - SIP
- `5061/tcp+udp` - SIPS
- `10000-20000/udp` - RTP (audio de llamadas)
- `8088/tcp` - Asterisk HTTP
- `8089/tcp` - Asterisk HTTPS
- `5038/tcp` - AMI (Asterisk Manager Interface)
---
## Seguridad
### Fail2Ban
- **Estado:** Activo
- **Jails:** sshd, asterisk, apache-auth, apache-badbots
- **Bantime:** 3600 segundos (1 hora)
- **Max retry:** 5 intentos
### AMI (Integración Odoo)
- **Usuario AMI:** `odoo`
- **Contraseña AMI:** `OdooAMI2026!`
- **Permisos:** Lectura/Escritura completa
- **Acceso permitido:** Red local `192.168.10.0/24`
- **Puerto:** `5038`
---
## Integración con Odoo
### Módulos Requeridos (Odoo Community)
1. Instalar desde https://github.com/OCA/connector-telephony:
- `base_phone`
- `asterisk_click2dial`
- `crm_phone` (opcional, para pop-up en CRM)
### Configuración en Odoo
1. Ir a **Settings → Asterisk Server**
2. Agregar servidor:
- **Name:** FreePBX VoIP
- **IP:** `192.168.10.114`
- **Port:** `5038`
- **Login:** `odoo`
- **Password:** `OdooAMI2026!`
3. Configurar prefijo de marcado si es necesario
### Funcionalidades
- **Click-to-Call:** Click en cualquier número de teléfono en Odoo para llamar
- **Pop-up de Cliente:** Al recibir llamada, Odoo busca el número y abre la ficha
- **Historial:** Registro de llamadas en la ficha del cliente
---
## Troncal SIP (PSTN)
- **Estado actual:** No configurado
- **Próximo paso:** Contratar troncal SIP con proveedor recomendado
### Proveedores Recomendados
| Proveedor | Ventaja |
|-----------|---------|
| **Twilio** | Confiable, fácil API, soporte global |
| **Telnyx** | Precios bajos, buena calidad |
| **VozTelecom** | Si operan en España |
| **OVH** | Buena cobertura Europa/Latam |
### Configuración General
1. FreePBX → Connectivity → Trunks → Add Trunk → Add SIP (chan_pjsip) Trunk
2. Ingresar datos del proveedor (host, usuario, contraseña)
3. Configurar Outbound Routes (rutas salientes)
4. Configurar Inbound Routes (rutas entrantes) → apuntar a IVR
---
## Comandos Útiles
```bash
# Estado de Asterisk
asterisk -rvx "core show uptime"
# Estado de extensiones PJSIP
asterisk -rvx "pjsip show endpoints"
# Recargar configuración FreePBX
fwconsole reload
# Reiniciar todo el servicio
fwconsole restart
# Estado de Fail2Ban
fail2ban-client status
# Ver logs de Asterisk
tail -f /var/log/asterisk/messages.log
# Ver logs de FreePBX/web
tail -f /var/log/apache2/freepbx-error.log
```
---
## Multi-Tenant (3 Empresas)
- **Enfoque:** Un solo FreePBX con prefijos de extensión por empresa
- `100-199` → Horux360
- `200-299` → Consultoria AS
- `300-399` → Nexus
- **IVR:** Un menú principal con opciones por empresa
- **CID Saliente:** Configurable por ruta/trunk cuando se contrate troncal
---
## Respaldo y Mantenimiento
### Backup Automático
- Instalar módulo `backup` en FreePBX (ya instalado)
- Configurar en Admin → Backup & Restore
- Recomendado: Backup diario de configuración + grabaciones
### Actualizaciones
```bash
# Actualizar módulos FreePBX
fwconsole ma updateall
fwconsole reload
# Actualizar sistema operativo
apt update && apt upgrade
```
---
## Notas Importantes
1. **Cambiar contraseñas por defecto** antes de poner en producción pública
2. **Configurar HTTPS** (Let's Encrypt) para acceso seguro al panel
3. **NAT:** Si el servidor está detrás de router/firewall, configurar "NAT = Yes" en Settings → Asterisk SIP Settings
4. **RTP:** Asegurar que el rango UDP 10000-20000 esté abierto en el router/firewall externo
5. **Sonidos:** Los sonidos en inglés están instalados. Para español, instalar `sounds-es` desde FreePBX → Admin → Sound Languages
---
## Soporte
- **FreePBX Wiki:** https://sangomakb.atlassian.net/wiki/spaces/FP/overview
- **Asterisk Docs:** https://docs.asterisk.org/
- **Comunidad:** https://community.freepbx.org/
---
*Documento generado el 2026-04-29*
*Implementación realizada por Kimi Code CLI*

View File

@@ -0,0 +1,294 @@
#!/bin/bash
# Script de instalación automatizada de FreePBX 17 en Ubuntu 24.04 LTS
# Autor: Kimi Code CLI
# Fecha: 2026-04-29
# Empresas: horux360.com, consultoria-as.com, nexus.consultoria-as.com
set -e
# ============================================
# CONFIGURACIÓN
# ============================================
DB_ROOT_PASS="${DB_ROOT_PASS:-FreePBXRoot2026!}"
DB_USER="${DB_USER:-asteriskuser}"
DB_PASS="${DB_PASS:-AsteriskDB2026!}"
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_PASS="${ADMIN_PASS:-FreePBX2026!}"
AMI_USER="${AMI_USER:-odoo}"
AMI_PASS="${AMI_PASS:-OdooAMI2026!}"
TIMEZONE="${TIMEZONE:-America/Mexico_City}"
SERVER_IP="$(hostname -I | awk '{print $1}')"
echo "================================================"
echo "Instalación FreePBX 17 en Ubuntu 24.04"
echo "IP Detectada: $SERVER_IP"
echo "================================================"
# ============================================
# 1. ACTUALIZACIÓN E INSTALACIÓN DE DEPENDENCIAS
# ============================================
echo "[1/9] Instalando dependencias del sistema..."
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y \
git curl wget vim nano sudo \
apache2 mariadb-server mariadb-client \
php8.3 php8.3-cli php8.3-common php8.3-curl php8.3-gd php8.3-mbstring \
php8.3-mysql php8.3-xml php8.3-bcmath php8.3-zip php8.3-intl \
php8.3-sqlite3 php8.3-opcache php8.3-readline php8.3-soap php8.3-xmlrpc \
libapache2-mod-php8.3 \
sox libncurses5-dev libssl-dev libmysqlclient-dev libxml2-dev libnewt-dev \
libsqlite3-dev libjansson-dev libasound2-dev libogg-dev libvorbis-dev \
libcurl4-openssl-dev libical-dev libneon27-dev libsrtp2-dev libspandsp-dev \
libtool libtool-bin libbsd-dev libcorosync-common-dev libcpg-dev libedit-dev \
libgmime-3.0-dev libunbound-dev libldap2-dev libpq-dev lua5.2 liblua5.2-dev \
liburiparser-dev libspeex-dev libspeexdsp-dev libcodec2-dev libiksemel-dev \
libresample1-dev unixodbc-dev subversion build-essential ffmpeg mpg123 \
cron postfix flite fail2ban nodejs npm odbc-mariadb ufw
# ============================================
# 2. CONFIGURACIÓN DE MARIADB
# ============================================
echo "[2/9] Configurando MariaDB..."
systemctl enable mariadb
systemctl start mariadb
mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$DB_ROOT_PASS';"
mysql -e "CREATE DATABASE IF NOT EXISTS asterisk CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -e "CREATE DATABASE IF NOT EXISTS asteriskcdrdb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -e "CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';"
mysql -e "GRANT ALL PRIVILEGES ON asterisk.* TO '$DB_USER'@'localhost';"
mysql -e "GRANT ALL PRIVILEGES ON asteriskcdrdb.* TO '$DB_USER'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"
# ============================================
# 3. CONFIGURACIÓN PHP Y APACHE
# ============================================
echo "[3/9] Configurando PHP y Apache..."
for ini in /etc/php/8.3/cli/php.ini /etc/php/8.3/apache2/php.ini; do
sed -i "s/^memory_limit = .*/memory_limit = 256M/" "$ini"
sed -i "s/^max_execution_time = .*/max_execution_time = 300/" "$ini"
sed -i "s/^max_input_vars = .*/max_input_vars = 3000/" "$ini"
sed -i "s/^upload_max_filesize = .*/upload_max_filesize = 64M/" "$ini"
sed -i "s/^post_max_size = .*/post_max_size = 64M/" "$ini"
sed -i "s|^;date.timezone =.*|date.timezone = $TIMEZONE|" "$ini"
sed -i "s|^date.timezone =.*|date.timezone = $TIMEZONE|" "$ini"
done
a2enmod rewrite headers ssl
cat > /etc/apache2/sites-available/freepbx.conf << EOF
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog \${APACHE_LOG_DIR}/freepbx-error.log
CustomLog \${APACHE_LOG_DIR}/freepbx-access.log combined
</VirtualHost>
EOF
a2ensite freepbx
a2dissite 000-default 2>/dev/null || true
# Cambiar Apache para correr como asterisk
sed -i 's/^export APACHE_RUN_USER=.*/export APACHE_RUN_USER=asterisk/' /etc/apache2/envvars
sed -i 's/^export APACHE_RUN_GROUP=.*/export APACHE_RUN_GROUP=asterisk/' /etc/apache2/envvars
systemctl enable apache2
systemctl restart apache2
# ============================================
# 4. CONFIGURACIÓN FIREWALL
# ============================================
echo "[4/9] Configurando Firewall..."
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 5060/tcp
ufw allow 5060/udp
ufw allow 5061/tcp
ufw allow 5061/udp
ufw allow 10000:20000/udp
ufw allow 8088/tcp
ufw allow 8089/tcp
ufw allow 5038/tcp
ufw --force enable
# ============================================
# 5. COMPILAR E INSTALAR ASTERISK 21
# ============================================
echo "[5/9] Descargando y compilando Asterisk 21..."
useradd -m -s /bin/bash asterisk 2>/dev/null || true
usermod -aG audio,dialout asterisk
mkdir -p /usr/src/asterisk
cd /usr/src/asterisk
curl -fsSL http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-21-current.tar.gz -o asterisk-21.tar.gz
tar -xzf asterisk-21.tar.gz --strip-components=1
./configure --with-pjproject-bundled --with-jansson-bundled --prefix=/usr --libdir=/usr/lib/x86_64-linux-gnu --with-crypto --with-ssl=ssl --with-srtp
make -j$(nproc)
make install
make samples
make config
ldconfig
# Instalar sonidos
cd /usr/src/asterisk
mkdir -p sounds
cd sounds
curl -fsSL http://downloads.asterisk.org/pub/telephony/sounds/asterisk-core-sounds-en-wav-current.tar.gz -o core-en.tar.gz
curl -fsSL http://downloads.asterisk.org/pub/telephony/sounds/asterisk-extra-sounds-en-wav-current.tar.gz -o extra-en.tar.gz
curl -fsSL http://downloads.asterisk.org/pub/telephony/sounds/asterisk-moh-opsound-wav-current.tar.gz -o moh.tar.gz
tar -xzf core-en.tar.gz -C /var/lib/asterisk/sounds
tar -xzf extra-en.tar.gz -C /var/lib/asterisk/sounds
tar -xzf moh.tar.gz -C /var/lib/asterisk/moh
# Permisos Asterisk
chown -R asterisk:asterisk /etc/asterisk /var/spool/asterisk /var/log/asterisk /var/run/asterisk /var/lib/asterisk
sed -i 's/;runuser = asterisk/runuser = asterisk/' /etc/asterisk/asterisk.conf
sed -i 's/;rungroup = asterisk/rungroup = asterisk/' /etc/asterisk/asterisk.conf
systemctl enable asterisk
systemctl start asterisk
# ============================================
# 6. INSTALAR FREEPBX 17
# ============================================
echo "[6/9] Instalando FreePBX 17..."
cd /var/www/html
git clone -b release/17.0 --depth 1 https://github.com/FreePBX/framework.git freepbx
cd freepbx
./install --dbuser "$DB_USER" --dbpass "$DB_PASS" --user asterisk --group asterisk --webroot /var/www/html
# Mover contenido al webroot
cd /var/www/html
mv freepbx/* . 2>/dev/null || true
mv freepbx/.* . 2>/dev/null || true
rm -rf freepbx
chown -R asterisk:asterisk /var/www/html
# ============================================
# 7. INSTALAR MÓDULOS ESENCIALES
# ============================================
echo "[7/9] Instalando módulos de FreePBX..."
fwconsole ma downloadinstall core dashboard sipsettings voicemail recordings cdr cel ivr callrecording music backup ucp webrtc queues 2>/dev/null || true
fwconsole reload
# ============================================
# 8. CONFIGURACIÓN POST-INSTALACIÓN
# ============================================
echo "[8/9] Configurando sistema post-instalación..."
# Crear usuario admin en base de datos
HASH=$(php -r "echo password_hash('$ADMIN_PASS', PASSWORD_BCRYPT);")
mysql -u "$DB_USER" -p"$DB_PASS" asterisk -e "
INSERT INTO userman_users (auth, authid, username, description, password, default_extension, primary_group, fname, lname, displayname, email)
VALUES ('freepbx', '1', '$ADMIN_USER', 'System Administrator', '$HASH', 'none', 1, 'Admin', 'User', 'Administrator', 'admin@consultoria-as.com')
ON DUPLICATE KEY UPDATE password='$HASH';
"
# Configurar SIP Settings
mysql -u "$DB_USER" -p"$DB_PASS" asterisk -e "
INSERT INTO sipsettings (keyword, seq, type, data) VALUES
('bindaddr', 0, 0, '0.0.0.0'),
('bindport', 1, 0, '5060'),
('rtpstart', 2, 0, '10000'),
('rtpend', 3, 0, '20000'),
('tcpenable', 4, 0, 'no'),
('udpbindport', 5, 0, '5060')
ON DUPLICATE KEY UPDATE data=VALUES(data);
"
# Configurar ODBC para CDR
cat > /etc/odbc.ini << EOF
[asteriskcdrdb]
Description=MySQL connection to asteriskcdrdb database
Driver=MariaDB Unicode
SERVER=localhost
PORT=3306
DATABASE=asteriskcdrdb
OPTION=3
CHARSET=utf8
[MySQL-asteriskcdrdb]
Description=MySQL connection to asteriskcdrdb database
Driver=MariaDB Unicode
SERVER=localhost
PORT=3306
DATABASE=asteriskcdrdb
OPTION=3
CHARSET=utf8
EOF
# Crear usuario AMI para Odoo
cat >> /etc/asterisk/manager.conf << EOF
[$AMI_USER]
secret = $AMI_PASS
deny = 0.0.0.0/0.0.0.0
permit = 192.168.10.0/255.255.255.0
read = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan
write = system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan
writetimeout = 5000
EOF
# Configurar Fail2Ban
cat > /etc/fail2ban/jail.local << EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
backend = auto
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
[asterisk]
enabled = true
port = 5060,5061
filter = asterisk
logpath = /var/log/asterisk/full
maxretry = 5
[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/*error.log
[apache-badbots]
enabled = true
port = http,https
filter = apache-badbots
logpath = /var/log/apache2/*error.log
maxretry = 2
EOF
mkdir -p /var/log/asterisk
touch /var/log/asterisk/full
chown -R asterisk:asterisk /var/log/asterisk
systemctl enable fail2ban
systemctl restart fail2ban
# ============================================
# 9. RECARGAR TODO
# ============================================
echo "[9/9] Recargando configuración..."
fwconsole reload
fwconsole restart
echo ""
echo "================================================"
echo "INSTALACIÓN COMPLETADA"
echo "================================================"
echo "Panel Admin: http://$SERVER_IP/admin"
echo "Usuario: $ADMIN_USER"
echo "Password: $ADMIN_PASS"
echo "AMI (Odoo): $AMI_USER / $AMI_PASS"
echo "================================================"

View File

@@ -0,0 +1,183 @@
#!/bin/bash
# Script para crear extensiones e IVR en FreePBX 17 (post-instalación)
# Empresas: Horux360 (100), Consultoria-AS (200), Nexus (300)
DB_USER="${DB_USER:-asteriskuser}"
DB_PASS="${DB_PASS:-AsteriskDB2026!}"
echo "Creando extensiones PJSIP..."
# Extension 100 - Horux360
mysql -u "$DB_USER" -p"$DB_PASS" asterisk -e "
DELETE FROM devices WHERE id='100';
DELETE FROM users WHERE extension='100';
DELETE FROM sip WHERE id='100';
INSERT INTO devices (id, tech, dial, devicetype, user, description, emergency_cid)
VALUES ('100', 'pjsip', 'PJSIP/100', 'fixed', '100', 'Horux360 - Admin', '');
INSERT INTO users (extension, password, name, voicemail, ringtimer, recording, outboundcid, sipname, mohclass)
VALUES ('100', 'Pass100!', 'Horux360 - Admin', 'default', 20, 'dontcare', '', '', 'default');
INSERT INTO sip (id, keyword, data, flags) VALUES
('100', 'account', '100', 0),
('100', 'accountcode', '', 0),
('100', 'allow', 'ulaw,alaw,g722,opus', 0),
('100', 'avpf', 'no', 0),
('100', 'callerid', 'Horux360 Admin <100>', 0),
('100', 'context', 'from-internal', 0),
('100', 'device_state_busy_at', '0', 0),
('100', 'direct_media', 'no', 0),
('100', 'disallow', '', 0),
('100', 'dtlsenable', 'no', 0),
('100', 'dtmfmode', 'rfc4733', 0),
('100', 'email', '', 0),
('100', 'emergency_cid', '', 0),
('100', 'encryption', 'no', 0),
('100', 'force_rport', 'yes', 0),
('100', 'icesupport', 'no', 0),
('100', 'mailboxes', '100@device', 0),
('100', 'match', '', 0),
('100', 'max_contacts', '1', 0),
('100', 'media_encryption', 'no', 0),
('100', 'media_use_received_transport', 'no', 0),
('100', 'message_context', '', 0),
('100', 'namedcallgroup', '', 0),
('100', 'namedpickupgroup', '', 0),
('100', 'outbound_proxy', '', 0),
('100', 'qualifyfreq', '60', 0),
('100', 'record_in', 'Always', 0),
('100', 'record_out', 'Always', 0),
('100', 'rtp_symmetric', 'yes', 0),
('100', 'secret', 'Horux100!', 0),
('100', 'send_connected_line', 'yes', 0),
('100', 'send_rpid', 'no', 0),
('100', 'sipdriver', 'chan_pjsip', 0),
('100', 'transport', '0.0.0.0-udp', 0),
('100', 'trust_rpid', 'no', 0),
('100', 'type', 'friend', 0),
('100', 'vmexten', '*97', 0);
"
# Extension 200 - Consultoria AS
mysql -u "$DB_USER" -p"$DB_PASS" asterisk -e "
DELETE FROM devices WHERE id='200';
DELETE FROM users WHERE extension='200';
DELETE FROM sip WHERE id='200';
INSERT INTO devices (id, tech, dial, devicetype, user, description, emergency_cid)
VALUES ('200', 'pjsip', 'PJSIP/200', 'fixed', '200', 'Consultoria AS - Admin', '');
INSERT INTO users (extension, password, name, voicemail, ringtimer, recording, outboundcid, sipname, mohclass)
VALUES ('200', 'Pass200!', 'Consultoria AS - Admin', 'default', 20, 'dontcare', '', '', 'default');
INSERT INTO sip (id, keyword, data, flags) VALUES
('200', 'account', '200', 0),
('200', 'accountcode', '', 0),
('200', 'allow', 'ulaw,alaw,g722,opus', 0),
('200', 'avpf', 'no', 0),
('200', 'callerid', 'Consultoria AS Admin <200>', 0),
('200', 'context', 'from-internal', 0),
('200', 'device_state_busy_at', '0', 0),
('200', 'direct_media', 'no', 0),
('200', 'disallow', '', 0),
('200', 'dtlsenable', 'no', 0),
('200', 'dtmfmode', 'rfc4733', 0),
('200', 'email', '', 0),
('200', 'emergency_cid', '', 0),
('200', 'encryption', 'no', 0),
('200', 'force_rport', 'yes', 0),
('200', 'icesupport', 'no', 0),
('200', 'mailboxes', '200@device', 0),
('200', 'match', '', 0),
('200', 'max_contacts', '1', 0),
('200', 'media_encryption', 'no', 0),
('200', 'media_use_received_transport', 'no', 0),
('200', 'message_context', '', 0),
('200', 'namedcallgroup', '', 0),
('200', 'namedpickupgroup', '', 0),
('200', 'outbound_proxy', '', 0),
('200', 'qualifyfreq', '60', 0),
('200', 'record_in', 'Always', 0),
('200', 'record_out', 'Always', 0),
('200', 'rtp_symmetric', 'yes', 0),
('200', 'secret', 'Consult200!', 0),
('200', 'send_connected_line', 'yes', 0),
('200', 'send_rpid', 'no', 0),
('200', 'sipdriver', 'chan_pjsip', 0),
('200', 'transport', '0.0.0.0-udp', 0),
('200', 'trust_rpid', 'no', 0),
('200', 'type', 'friend', 0),
('200', 'vmexten', '*97', 0);
"
# Extension 300 - Nexus
mysql -u "$DB_USER" -p"$DB_PASS" asterisk -e "
DELETE FROM devices WHERE id='300';
DELETE FROM users WHERE extension='300';
DELETE FROM sip WHERE id='300';
INSERT INTO devices (id, tech, dial, devicetype, user, description, emergency_cid)
VALUES ('300', 'pjsip', 'PJSIP/300', 'fixed', '300', 'Nexus - Admin', '');
INSERT INTO users (extension, password, name, voicemail, ringtimer, recording, outboundcid, sipname, mohclass)
VALUES ('300', 'Pass300!', 'Nexus - Admin', 'default', 20, 'dontcare', '', '', 'default');
INSERT INTO sip (id, keyword, data, flags) VALUES
('300', 'account', '300', 0),
('300', 'accountcode', '', 0),
('300', 'allow', 'ulaw,alaw,g722,opus', 0),
('300', 'avpf', 'no', 0),
('300', 'callerid', 'Nexus Admin <300>', 0),
('300', 'context', 'from-internal', 0),
('300', 'device_state_busy_at', '0', 0),
('300', 'direct_media', 'no', 0),
('300', 'disallow', '', 0),
('300', 'dtlsenable', 'no', 0),
('300', 'dtmfmode', 'rfc4733', 0),
('300', 'email', '', 0),
('300', 'emergency_cid', '', 0),
('300', 'encryption', 'no', 0),
('300', 'force_rport', 'yes', 0),
('300', 'icesupport', 'no', 0),
('300', 'mailboxes', '300@device', 0),
('300', 'match', '', 0),
('300', 'max_contacts', '1', 0),
('300', 'media_encryption', 'no', 0),
('300', 'media_use_received_transport', 'no', 0),
('300', 'message_context', '', 0),
('300', 'namedcallgroup', '', 0),
('300', 'namedpickupgroup', '', 0),
('300', 'outbound_proxy', '', 0),
('300', 'qualifyfreq', '60', 0),
('300', 'record_in', 'Always', 0),
('300', 'record_out', 'Always', 0),
('300', 'rtp_symmetric', 'yes', 0),
('300', 'secret', 'Nexus300!', 0),
('300', 'send_connected_line', 'yes', 0),
('300', 'send_rpid', 'no', 0),
('300', 'sipdriver', 'chan_pjsip', 0),
('300', 'transport', '0.0.0.0-udp', 0),
('300', 'trust_rpid', 'no', 0),
('300', 'type', 'friend', 0),
('300', 'vmexten', '*97', 0);
"
echo "Creando IVR principal..."
mysql -u "$DB_USER" -p"$DB_PASS" asterisk -e "
DELETE FROM ivr_entries WHERE ivr_id=1;
DELETE FROM ivr_details WHERE id=1;
INSERT INTO ivr_details (id, name, description, announcement, directdial, invalid_loops, invalid_retry_recording, invalid_destination, timeout_enabled, invalid_recording, retvm, timeout_time, timeout_recording, timeout_retry_recording, timeout_destination, timeout_loops, timeout_append_announce, invalid_append_announce, timeout_ivr_ret, invalid_ivr_ret, alertinfo, rvolume, strict_dial_timeout, accept_pound_key)
VALUES (1, 'MenuPrincipal', 'IVR Principal - 3 Empresas', NULL, 'disabled', '3', 'default', 'app-blackhole,hangup,1', NULL, 'default', '0', 10, 'default', 'default', 'app-blackhole,hangup,1', '3', 1, 1, 0, 0, '', '', 2, 0);
INSERT INTO ivr_entries (ivr_id, selection, dest, ivr_ret) VALUES
(1, '1', 'from-did-direct,100,1', 0),
(1, '2', 'from-did-direct,200,1', 0),
(1, '3', 'from-did-direct,300,1', 0);
"
echo "Recargando FreePBX..."
fwconsole reload
echo "Extensiones e IVR creadas correctamente."

1381
sql/asterisk_schema.sql Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,107 @@
/*M!999999\- enable the sandbox mode */
-- MariaDB dump 10.19 Distrib 10.11.14-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: asteriskcdrdb
-- ------------------------------------------------------
-- Server version 10.11.14-MariaDB-0ubuntu0.24.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `cdr`
--
DROP TABLE IF EXISTS `cdr`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `cdr` (
`calldate` datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
`clid` varchar(80) NOT NULL DEFAULT '',
`src` varchar(80) NOT NULL DEFAULT '',
`dst` varchar(80) NOT NULL DEFAULT '',
`dcontext` varchar(80) NOT NULL DEFAULT '',
`channel` varchar(80) NOT NULL DEFAULT '',
`dstchannel` varchar(80) NOT NULL DEFAULT '',
`lastapp` varchar(80) NOT NULL DEFAULT '',
`lastdata` varchar(80) NOT NULL DEFAULT '',
`duration` int(11) NOT NULL DEFAULT 0,
`billsec` int(11) NOT NULL DEFAULT 0,
`disposition` varchar(45) NOT NULL DEFAULT '',
`amaflags` int(11) NOT NULL DEFAULT 0,
`accountcode` varchar(20) NOT NULL DEFAULT '',
`uniqueid` varchar(32) NOT NULL DEFAULT '',
`userfield` varchar(255) NOT NULL DEFAULT '',
`did` varchar(50) NOT NULL DEFAULT '',
`recordingfile` varchar(255) NOT NULL DEFAULT '',
`cnum` varchar(80) NOT NULL DEFAULT '',
`cnam` varchar(80) NOT NULL DEFAULT '',
`outbound_cnum` varchar(80) NOT NULL DEFAULT '',
`outbound_cnam` varchar(80) NOT NULL DEFAULT '',
`dst_cnam` varchar(80) NOT NULL DEFAULT '',
`linkedid` varchar(32) NOT NULL DEFAULT '',
`peeraccount` varchar(80) NOT NULL DEFAULT '',
`sequence` int(11) NOT NULL DEFAULT 0,
KEY `calldate` (`calldate`),
KEY `dst` (`dst`),
KEY `accountcode` (`accountcode`),
KEY `uniqueid` (`uniqueid`),
KEY `did` (`did`),
KEY `recordingfile` (`recordingfile`),
KEY `dstchannel` (`dstchannel`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `cel`
--
DROP TABLE IF EXISTS `cel`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `cel` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`eventtype` varchar(30) NOT NULL,
`eventtime` datetime NOT NULL,
`cid_name` varchar(80) NOT NULL,
`cid_num` varchar(80) NOT NULL,
`cid_ani` varchar(80) NOT NULL,
`cid_rdnis` varchar(80) NOT NULL,
`cid_dnid` varchar(80) NOT NULL,
`exten` varchar(80) NOT NULL,
`context` varchar(80) NOT NULL,
`channame` varchar(80) NOT NULL,
`appname` varchar(80) NOT NULL,
`appdata` varchar(1024) DEFAULT NULL,
`amaflags` int(11) NOT NULL,
`accountcode` varchar(20) NOT NULL,
`uniqueid` varchar(32) NOT NULL,
`linkedid` varchar(32) NOT NULL,
`peer` varchar(255) NOT NULL,
`userdeftype` varchar(255) NOT NULL,
`extra` varchar(512) NOT NULL,
PRIMARY KEY (`id`),
KEY `uniqueid_index` (`uniqueid`),
KEY `linkedid_index` (`linkedid`),
KEY `context_index` (`context`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2026-04-29 6:27:00