Asterisk & FreePBX

Asterisk 是第一套以開放原始碼軟體實作的 用戶交換機 系統。Asterisk 由 Digium 的創辦人馬克·史賓瑟於1999年他還在奧本大學念書時所開發。與其他的用戶交換機系統相同,Asterisk 同樣支援電話撥打另一隻分機,和撥打到公共交換電話網與IP電話系統。 FreePBX is a web-based open-source graphical user interface (GUI) that manages Asterisk, a voice over IP and telephony server.

Installation

Install Asterisk and FreePBX

Installation

Install FreePBX 15 with Asterisk 16 on Debian 10

Install Asterisk 16

Step 1: Update system
sudo apt update && sudo apt upgrade
sudo reboot
Step 2: Install Asterisk 16 LTS dependencies
sudo apt install git curl wget libnewt-dev libssl-dev libncurses5-dev subversion libsqlite3-dev build-essential libjansson-dev libxml2-dev uuid-dev
Step 3: Download Asterisk 16 LTS tarball
cd /usr/src/
sudo curl -O http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-16-current.tar.gz

sudo tar xvf asterisk-16-current.tar.gz
cd asterisk-16*/

# download the mp3 decoder library into the source tree
sudo contrib/scripts/get_mp3_source.sh

# Ensure all dependencies are resolved
sudo contrib/scripts/install_prereq install
Step 4: Build and Install Asterisk 16
sudo ./configure
sudo make menuselect
sudo make
sudo make install
sudo make progdocs
sudo make samples
sudo make config
sudo ldconfig

Create Asterisk User

sudo groupadd asterisk
sudo useradd -r -d /var/lib/asterisk -g asterisk asterisk
sudo usermod -aG audio,dialout asterisk
sudo chown -R asterisk.asterisk /etc/asterisk
sudo chown -R asterisk.asterisk /var/{lib,log,spool}/asterisk
sudo chown -R asterisk.asterisk /usr/lib/asterisk

Set Asterisk default user to asterisk

$ sudo vim /etc/default/asterisk
AST_USER="asterisk"
AST_GROUP="asterisk"

$ sudo vim /etc/asterisk/asterisk.conf
runuser = asterisk ; The user to run as.
rungroup = asterisk ; The group to run as.

Restart asterisk service

sudo systemctl restart asterisk

# Enable asterisk service to start on system boot
sudo systemctl enable asterisk

# Test to see if you can connect to Asterisk CLI
sudo asterisk -rvv

Install FreePBX 15

Step 1:  Install MariaDB Database server
sudo apt update
sudo apt install mariadb-server mariadb-client

# Initial DB setup and set root's password for DB
sudo /usr/bin/mysql_secure_installation
Step 2: Installing Node.js 10 LTS
sudo apt install curl dirmngr apt-transport-https lsb-release ca-certificates
curl -sL https://deb.nodesource.com/setup_10.x | sudo bash
sudo apt update
sudo apt install gcc g++ make
sudo apt install nodejs
Step 3: Install and configure Apache Web Server
sudo apt install apache2

# change Apache user to asterisk and turn on AllowOverride option
sudo cp /etc/apache2/apache2.conf /etc/apache2/apache2.conf_orig
sudo sed -i 's/^\(User\|Group\).*/\1 asterisk/' /etc/apache2/apache2.conf
sudo sed -i 's/AllowOverride None/AllowOverride All/' /etc/apache2/apache2.conf

# Remove default index.html page
sudo rm -f /var/www/html/index.html
Step 4: Install PHP and required extensions
sudo apt install wget php php-pear php-cgi php-common php-curl php-mbstring php-gd php-mysql \
php-gettext php-bcmath php-zip php-xml php-imap php-json php-snmp php-fpm libapache2-mod-php

Change php maximum file upload size

sudo sed -i 's/\(^upload_max_filesize = \).*/\120M/' /etc/php/7.3/apache2/php.ini
sudo sed -i 's/\(^upload_max_filesize = \).*/\120M/' /etc/php/7.3/cli/php.ini
Step 5: Install FreePBX 15
sudo apt install wget
cd /usr/src
wget http://mirror.freepbx.org/modules/packages/freepbx/freepbx-15.0-latest.tgz

tar xfz freepbx-15.0-latest.tgz
rm -f freepbx-15.0-latest.tgz

cd freepbx
sudo ./start_asterisk start
sudo ./install -n --dbuser root --dbpass "yourpassword"

# Enable Apache Rewrite engine 
sudo a2enmod rewrite
sudo systemctl restart apache2
Step 6: Access FreePBX 15 Web Interface

Create the first admin account.

Q & A

Q: Online modules are not available.

Error:

Warning: Error retrieving updates from online repository(s) (https://mirror.freepbx.org 35). Online modules are not available.

A: Change the DNS to 8.8.8.8

vi /etc/resolv.conf

nameserver 8.8.8.8
#nameserver 67.207.67.3
#nameserver 67.207.67.2

 

Reference

 

 

Installation

Install FreePBX 15 with Docker

Reference

FreePBX: fwconsole

Tutorials
Help
fwconsole help

# lists all commands
php /usr/sbin/fwconsole list
Service Start/Stop
# Start Asterisk and run other needed FreePBX commands
fwconsole start

# Stop Asterisk and run other needed FreePBX commands
fwconsole stop
Module Admin
# Check Online Repository
fwconsole ma listonline

# Install a module
fwconsole ma download ivr
fwconsole ma install ivr

# Installing specific module versions with multiple modules
fwconsole ma install foomodule:15.1.3 barmodule:15.0.9

# Upgrade all modules
fwconsole ma listonline | grep "upgrade"
fwconsole ma upgradeall

# Apply the settings changed
fwconsole reload
Database

連線資料庫 asterisk (自動從 /etc/freepbx.conf 取得連線資訊)

fwconsole m

Things to do after FreePBX installation

Set root's password for MySQL
mysql_secure_installation
Log File Rotation

If this is not done the log files will keep growing indefinitely.
Edit /etc/logrotate.d/asterisk

/var/spool/mail/asterisk
/var/log/asterisk/*log
/var/log/asterisk/full
/var/log/asterisk/dtmf
/var/log/asterisk/freepbx_dbug
/var/log/asterisk/fail2ban {
 weekly
 missingok
 rotate 4
 #compress
 notifempty
 sharedscripts
 create 0640 asterisk asterisk
 postrotate
 /usr/sbin/asterisk -rx 'logger reload' > /dev/null 2> /dev/null || true
 endscript
 su root root
}
TFTP

If you plan to use hardware SIP phones you will probably want to set up TFTP.

yum -y install tftp-server
nano /etc/xinetd.d/tftp
change server_args = -s /var/lib/tftpboot
to server_args = -s /tftpboot
change disable=yes
to disable=no
mkdir /tftpboot
chmod 777 /tftpboot
systemctl restart xinetd
firewall-cmd --permanent --zone=public --add-port=69/udp
firewall-cmd --reload
MPG123

This is used in combination with sox to convert uploaded mp3 files to Asterisk compatible wav files.

cd /usr/src
wget http://ufpr.dl.sourceforge.net/project/mpg123/mpg123/1.22.4/mpg123-1.22.4.tar.bz2
tar -xjvf mpg123*
cd mpg123*/
./configure --prefix=/usr --libdir=/usr/lib64 && make && make install && ldconfig
Digum addons

To register digium® licenses.

cd /usr/src
wget http://downloads.digium.com/pub/register/linux/register
chmod +x register
./register

To install the individual addons refer to the README files and ignore the register instructions.

Password protect http access

A simple way to block scanners looking for exploits on apache web servers.

mkdir -p /usr/local/apache/passwd
htpasswd -c /usr/local/apache/passwd/wwwpasswd someusername
htpasswd -c /usr/local/apache/passwd/wwwpasswd someotherusername
nano /var/www/html/.htaccess
# .htaccess files require AllowOverride On in /etc/httpd/conf/httpd.conf
AuthType Basic
AuthName "Restricted Access"
AuthUserFile /usr/local/apache/passwd/wwwpasswd
Require valid-user

Alternatively, the above .htaccess config can be added to /etc/httpd/conf/httpd.conf or as a separate file in /etc/httpd/conf.d/ as follows.

<Directory /var/www/html>
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /usr/local/apache/passwd/wwwpasswd
Require valid-user
</Directory>
Whitelist protect http access

If http access is only required from certain IP addresses.
NOTE: Apache 2.4 以後才支援這功能
Edit /etc/httpd/conf.d/whitelist.conf

<Location />
 <RequireAny>
 ## Uncomment the following line to disable the whitelist
 #Require all granted
 Require ip x.x.x.x
 Require ip x.x.x.x x.x.x.x x.x.x.x
 Require ip x.x
 Require ip x.x.x.0/255.255.255.0
 Require host somedomain.com
 #
 ## See http://httpd.apache.org/docs/2.4/mod/mod_authz_host.html for more examples
 #
 </RequireAny>
</Location>

舊版 Apache 設定
NOTE:確定網站目錄有 AllowOverride All 設定
.htaccess:

order deny,allow
deny from all
# Alang's IPs
allow from 123.123.123.1
allow from 111.222.222.2
allow from 192.168.99.

 

 

 

 

Learning

Speech Recognition (Speech to Text)

Vosk-API

Kamailio
Secure SIP Server
SIP Monitoring

Q & A

CDR Reports 沒有任何紀錄

檢查 MySQL 資料表

# MySQL Credentials
cat /etc/freepbx.conf

# Check the mysql
mysql -u freepbxuser -p asteriskcdrdb -e 'SELECT * FROM cdr ORDER BY calldate DESC LIMIT 4'

檢查 asterisk module

asterisk -rx "module show like odbc"

Module Description Use Count Status Support Level
cdr_adaptive_odbc.so Adaptive ODBC CDR backend 0 Running core
cdr_odbc.so ODBC CDR Backend 0 Running extended
cel_odbc.so ODBC CEL backend 0 Running core
func_odbc.so ODBC lookups 0 Running core
res_config_odbc.so Realtime ODBC configuration 0 Running core
res_odbc.so ODBC resource 6 Running core
res_odbc_transaction.so ODBC transaction resource 1 Running core

重啟服務出現以下錯誤

fwconsole stop
fwconsole start

[2022-06-03 10:38:42] WARNING[32144] res_odbc.c: res_odbc: Error SQLConnect=-1 errno=0 [unixODBC][Driver Manager]Can't open lib '/usr/lib/x86_64-linux-gnu/odbc/libmaodbc.so' : file not f

Solution:

#> locate libmaodbc.so
/usr/lib/i386-linux-gnu/odbc/libmaodbc.so

#> cp /etc/odbcinst.ini /etc/odbcinst.ini.orig
#> vi /etc/odbcinst.ini

# Change this line
Driver = /usr/lib/x86_64-linux-gnu/odbc/libmaodbc.so

重啟服務確認錯誤不再發生

fwconsole stop
fwconsole start
Can't send 10 type frames with SIP write

Frame type '10' is comfort noise (aka CNG) which Asterisk does not support.

However as of 13.18.0 this message will be silenced so you won’t see it anymore.

You can ignore it or disable CNG on all of your endpoints and ask the telecom providers as well to disable the CNG on your trunks.



A2B 與 FreePBX 的連接

A2B 作為 Outbound Trunk 時

Call > FreePBX > A2B > SIP Carrier

在 FreePBX 上的設定範例:
以帳號密碼驗證方式

username=51521171
fromuser=51521171
type=friend
secret=1234567
host=incoming.future-nine.com
insecure=port,invite
nat=yes
qualify=yes
context=from-trunk
allow=ulaw,g729,g726
trustrpid=yes
sendrpid=yes
canreinvite=no

FreePBX 作為 Outbound Trunk 時

Call > A2B > FreePBX > SIP Carrier

在 FreePBX 上)
  1. 新增 SIP extension: 9001
在 A2B PBX)

1. 新增 SIP Trunk: freepbx

[freepbx]
username=9001
type=peer
secret=<ext-secret>
insecure=very
host=<freepbx-ip-addr>
fromuser=9001
qualify=yes

2. 新增 SIP Register String (for incoming call only)

9001:<ext-secret>@<freepbx-ip-addr>/from_freepbx

NOTE: 最後面為甚麼不是 SIP number 而是改用字串(/from_freepbx)呢?這是因為若以 SIP number 199 來作識別,可能會與本地的其他分機的編碼規則造成衝突,所以改用字串可以避免爾後遇到路由的問題。

3. 新增 Outbound Route


A2Billing

URLs
Alternative to A2Billing

Voice Mail Transcription

IBM Watson STT

Creating IBM Watson Credentials
  1. Login to IBM Cloud using your new credentials.
  2. Once logged in, choose IBM Cloud from the Title Bar to display your Dashboard.
  3. Choose Create Resource.
  4. Click Speech to Text from the AI Section.
  5. Name your STT service, choose the desired region, and choose Default resource group.
  6. Select a Pricing Plan:
    • LITE provides 500 minutes/month free. Plan is deleted after 30 days of inactivity.
    • STANDARD is 2¢/minute with no free minutes.
  7. When Speech to Text dialog opens, copy your API Key and URL.
  8. Logout by clicking on image icon in upper right corner of dialog window.
Installing STT Engine

1. Unpack the file

wget http://incrediblepbx.com/sendmailibm-13.tar.gz
tar zxvf sendmailibm-13.tar.gz
cp sendmailmp3.ibm /usr/local/sbin/sendmailmp3
chmod 0755 /usr/local/sbin/sendmailmp3

2. Edit sendmailmp3.ibm and insert your IBM STT API_KEY and URL. Save file.

3. Edit bluemix-test and insert your IBM STT API_KEY and URL. Save the file.

4. Copy the updated sendmailmp3.ibm file to sendmailmp3:

cp sendmailmp3.ibm /usr/local/sbin/sendmailmp3
chmod 0755 /usr/local/sbin/sendmailmp3

5. Test your Bluemix STT setup: bluemix-test

Result should be: we are now transferring you out of the company directory…

FreePBX Setup

Settings > Voicemail Admin > Settings > Email Config > Mail Command: /usr/local/sbin/sendmailmp3

Set up voicemail for an extension and include your email address.

Tutorials

Google STT

Tutorials


Soft Phone

Open Source/Freeware

OpenSIPS

Installation on Debian 10

OpenSIPS 3.3
apt install gnupg2
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 049AD65B

# For Debian 10
echo "deb https://apt.opensips.org buster 3.3-releases" >/etc/apt/sources.list.d/opensips.list
echo "deb https://apt.opensips.org buster cli-nightly" >/etc/apt/sources.list.d/opensips-cli.list
# For Ubuntu 20
echo "deb https://apt.opensips.org focal 3.3-releases" >/etc/apt/sources.list.d/opensips.list
echo "deb https://apt.opensips.org focal cli-nightly" >/etc/apt/sources.list.d/opensips-cli.list

apt update
apt install opensips
apt install opensips-cli

# Install all other modules
apt install opensips-*

# Start opensips and check the status
systemctl start opensips
systemctl status opensips
OpenSIPS Database Support (MySQL)
# Install MySQL Server (MariaDB on Debian 10)
apt install mariadb-server

# Create the database opensips using the OpenSIPS command line interface
opensips-cli -x database create opensips

# Verify if the tables were created
mysql opensips -e "show tables"

# Set the root's password for MariaDB and complete a few secure steps.
MariaDB> alter user 'root'@'localhost' identified by 'newpassword';
MariaDB> flush privileges;
MariaDB> exit
OpenSIPS Control Panel 9.3.3
# Install Apache, PHP and other dependencies
apt-get install apache2 libapache2-mod-php php-curl php php-mysql php-gd php-pear php-cli php-apcu git

# Download the OCP 9.3.3
git clone -b 9.3.3 https://github.com/OpenSIPS/opensips-cp.git /var/www/opensips-cp

Configure Apache

# Remove the default configuration
rm /etc/apache2/sites-enabled/000-default.conf

Edit: /etc/apache2/sites-enabled/opensips.conf

<VirtualHost *:80>
        <Directory /var/www/opensips-cp/web>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Require all granted
        </Directory>

        <Directory /var/www/opensips-cp>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Require all denied
        </Directory>

        Alias /cp /var/www/opensips-cp/web

        <DirectoryMatch "/var/www/opensips-cp/web/tools/.*/.*/(template|custom_actions|lib)/">
                Require all denied
        </DirectoryMatch>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Set the permissions of directories

chown -R www-data:www-data /var/www/opensips-cp/

Creating the OCP tables

# This will create the OCP specific tables into the opensips database and add a first access user, 
# the admin user with the opensips password.
mysql -uroot -p opensips < /var/www/opensips-cp/config/db_schema.mysql

set Cron jobs

cp /var/www/opensips-cp/config/tools/system/smonitor/opensips_stats_cron /etc/cron.d
sed -i 's/\/var\/www\/html\/opensips-cp/\/var\/www\/opensips-cp/g' /etc/cron.d/opensips_stats_cron

Restart Apache

systemctl restart apache2

Visit the OCP Web site: http://server-ip-address/cp , admin / opensips

RTPProxy
apt install build-essential
apt install libucl-dev
cd /usr/src
git clone -b master https://github.com/sippy/rtpproxy.git
git -C rtpproxy submodule update --init --recursive
cd rtpproxy
./configure
make clean all
make install

Configure the systemd

Edit: /etc/systemd/system/rtpproxy.service

[Unit]
Description=RTPProxy media server
After=network.target
Requires=network.target

[Service]
Type=simple
PIDFile=/var/run/rtpproxy/rtpproxy.pid
Environment='OPTIONS= -l 172.16.0.67 -A 154.19.187.227 -m 10000 -M 20000 -d INFO:LOG_LOCAL5'

Restart=always
RestartSec=5

ExecStartPre=-/bin/mkdir /var/run/rtpproxy
ExecStartPre=-/bin/chown opensips:opensips /var/run/rtpproxy

ExecStart=/usr/local/bin/rtpproxy -p /var/run/rtpproxy/rtpproxy.pid -s unix:/var/run/rtpproxy/rtpproxy.sock \
 -u opensips:opensips $OPTIONS
ExecStop=/usr/bin/pkill -F /var/run/rtpproxy/rtpproxy.pid

ExecStopPost=-/bin/rm -R /var/run/rtpproxy

StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=rtpproxy
SyslogFacility=local5

TimeoutStartSec=10
TimeoutStopSec=10

[Install]
WantedBy=multi-user.target

Start the service

systemctl daemon-reload
systemctl start rtpproxy
systemctl enable rtpproxy


Configuration

OpenSIPS

Generate config file

# Install the package required
apt install m4

# -> Residential Script
# --> Configure Residential Script
# ---> Select all options except for TLS, VM_DIVERSION, PRESENCE
/usr/sbin/osipsconfig

mv /etc/opensips/opensips.cfg /etc/opensips/opensips.cfg.orig
mv /etc/opensips/opensips_residential_2023-3-19_6:6:6.cfg /etc/opensips/opensips.cfg
chmod 0644 /etc/opensips/opensips.cfg

# Restart OpenSIPS
systemctl restart opensips

opensips.cfg for server behind the firewall

/* For AWS and OpenStack Environment */
/* WAN IP: 123.123.123.123 */
/* LAN IP: 172.16.0.67
advertised_address="123.123.123.123"
alias="123.123.123.123"

socket=udp:172.16.0.67:5060
socket=tcp:172.16.0.67:5060

opensips.cfg for RTPProxy

### RTPProxy module ###
loadmodule "rtpproxy.so"
## Fixed for ERROR:rtpproxy:send_rtpp_command: proxy <udp:localhost:7890> does not respond, disable it
#modparam("rtpproxy", "rtpproxy_sock", "udp:localhost:7890")
modparam("rtpproxy", "rtpproxy_sock", "unix:/var/run/rtpproxy/rtpproxy.sock")

opensips.cfg for dispatcher

### Dispatcher modules ###
loadmodule "dispatcher.so"
modparam("dispatcher", "db_url", "mysql://opensips:opensipsrw@localhost/opensips")
modparam("dispatcher", "dst_avp", "$avp(271)")
modparam("dispatcher", "attrs_avp", "$avp(272)")
modparam("dispatcher", "grp_avp", "$avp(273)")
modparam("dispatcher", "cnt_avp", "$avp(274)")
modparam("dispatcher", "hash_pvar", "$avp(273)")
modparam("dispatcher", "ds_ping_method", "OPTIONS")
modparam("dispatcher", "ds_ping_from", "sip:sipcheck@outbound_IP:5060")
modparam("dispatcher", "ds_ping_interval", 10)
modparam("dispatcher", "ds_probing_threshhold", 3)
modparam("dispatcher", "ds_probing_mode", 1)
modparam("dispatcher", "options_reply_codes", "501,403,404,400,200")


OpenSIPS Control Panel (OCP)

OCP 管理模組開啟與關閉

編輯: config/modules.inc.php

資料庫連線資訊

編輯: config/db.inc.php

Log file

Edit: /etc/rsyslog.d/opensips.conf

local0.*                        -/var/log/opensips.log

Restart rsyslog

touch /var/log/opensips.log
systemctl restart rsyslog

OpenSIPS CLI

# opensips-cli -x mi version
{
    "Server": "OpenSIPS (3.1.14 (x86_64/linux))"
}

FAQ

OCP 的 dispatcher 頁面出現空白

Solution: 檢查 dispatcher 與 mi_http 模組是否載入成功。驗證方式可以用 OCP 的 MI Commands 執行 ds_list,如果有內容輸出表示模組載入成功。

Dispatcher

CGRateS