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.


Install Asterisk and FreePBX


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

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

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

# 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

$ 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 | 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

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.


Warning: Error retrieving updates from online repository(s) ( 35). Online modules are not available.

A: Change the DNS to

vi /etc/resolv.conf







Install FreePBX 15 with Docker


FreePBX: fwconsole

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

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

fwconsole m

Things to do after FreePBX installation

Set root's password for MySQL
Log File Rotation

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

/var/log/asterisk/fail2ban {
 rotate 4
 create 0640 asterisk asterisk
 /usr/sbin/asterisk -rx 'logger reload' > /dev/null 2> /dev/null || true
 su root root

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

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

cd /usr/src
tar -xjvf mpg123*
cd mpg123*/
./configure --prefix=/usr --libdir=/usr/lib64 && make && make install && ldconfig
Digum addons

To register digium® licenses.

cd /usr/src
chmod +x 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
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 />
 ## 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/
 Require host
 ## See for more examples

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

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






Speech Recognition (Speech to Text)


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 Adaptive ODBC CDR backend 0 Running core ODBC CDR Backend 0 Running extended ODBC CEL backend 0 Running core ODBC lookups 0 Running core Realtime ODBC configuration 0 Running core ODBC resource 6 Running core 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/' : file not f


#> locate

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

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


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 上的設定範例:


FreePBX 作為 Outbound Trunk 時

Call > A2B > FreePBX > SIP Carrier

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

1. 新增 SIP Trunk: freepbx


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


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

3. 新增 Outbound Route


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

tar zxvf sendmailibm-13.tar.gz
cp /usr/local/sbin/sendmailmp3
chmod 0755 /usr/local/sbin/sendmailmp3

2. Edit 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 file to sendmailmp3:

cp /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.


Google STT


Soft Phone

Open Source/Freeware


Installation on Debian 10

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

# For Debian 10
echo "deb buster 3.3-releases" >/etc/apt/sources.list.d/opensips.list
echo "deb buster cli-nightly" >/etc/apt/sources.list.d/opensips-cli.list
# For Ubuntu 20
echo "deb focal 3.3-releases" >/etc/apt/sources.list.d/opensips.list
echo "deb 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 /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 /var/www/opensips-cp>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Require all denied

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

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

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


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

apt install build-essential
apt install libucl-dev
cd /usr/src
git clone -b master
git -C rtpproxy submodule update --init --recursive
cd rtpproxy
make clean all
make install

Configure the systemd

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

Description=RTPProxy media server

Environment='OPTIONS= -l -A -m 10000 -M 20000 -d INFO:LOG_LOCAL5'


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

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

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




Start the service

systemctl daemon-reload
systemctl start rtpproxy
systemctl enable rtpproxy



Generate config file

# Install the package required
apt install m4

# -> Residential Script
# --> Configure Residential Script
# ---> Select all options except for TLS, VM_DIVERSION, PRESENCE

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: */
/* LAN IP:


opensips.cfg for RTPProxy

### RTPProxy module ###
loadmodule ""
## 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 ""
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/


編輯: config/

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 -x mi version
    "Server": "OpenSIPS (3.1.14 (x86_64/linux))"


OCP 的 dispatcher 頁面出現空白

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