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


Incredible PBX


Incredible PBX 2027 with Debian 11

Reset the hostname and password:

# Set the hostname
hostnamectl set-hostname <your-FQDN-name>

# Set the password
passwd              # for Root
admin-pw-change     # for FreePBX
apache-pw-change    # for Reminders and AsteriDex

Set Gmail as an SMTP Smarthost:

Create an App password for your Gmail account: 


Stop Webmin

systemctl stop webmin
systemctl disable webmin


Official URLs



Speech Recognition (Speech to Text)


Secure SIP Server
SIP Monitoring
Auto Provisioning
HA with DRBD

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.

FXO 不會正確地傳送 Answer 至 IP 端

當透過 Gateway 撥打外線時 (IP to PSTN),不管 PSTN 端是否接起電話,Gateway 總是傳送 Answer 至 IP 端。這個對於一般電話操作不會有影響,不過,若是要對通話進行計費時,就會造成很大問題。


Polarity Reversal (極性反轉):電信商提供用戶交換機外線通話開始及結束之確認訊號,以利用戶電話 計費系統進行話務計費 (適用旅館業者)

The issue:

The VoIP gateway is sending an answer signal to the IP side, even when the call is not picked up on the PSTN side. This is not the expected behavior, as the gateway should only send an answer signal when the call is actually answered by the called party.

Possible causes:

  1. Improper FXO port configuration: The FXO port on the gateway might not be configured correctly, leading to the gateway sending an answer signal prematurely.
  2. PSTN line issues: There could be issues with the PSTN line, such as noise or electrical interference, that are causing the gateway to misinterpret the call status.
  3. Polarity Reversal Detection not functioning correctly: The Polarity Reversal Detection feature on the gateway might not be working as expected, which could be contributing to the issue.
Polarity Reversal Detection:

Polarity Reversal Detection is a feature used to detect when a call is answered or hung up on the PSTN side. When a call is answered, the polarity of the PSTN line reverses, and the gateway can detect this change to determine the call status. If the Polarity Reversal Detection is not functioning correctly, the gateway may not be able to accurately determine the call status.

How Polarity Reversal Detection works:

When a call is made from the IP side to the PSTN side, the gateway monitors the PSTN line for a polarity reversal. When the called party answers, the PSTN line polarity reverses, and the gateway detects this change. The gateway then sends an answer signal to the IP side, indicating that the call has been answered.

Troubleshooting steps:

  1. Verify FXO port configuration: Check the FXO port configuration on the gateway to ensure it is set up correctly. Consult the gateway's documentation or contact the manufacturer for guidance.
  2. Check PSTN line quality: Verify that the PSTN line is clean and free of noise or electrical interference. You can use a line tester or consult with the PSTN provider to troubleshoot line issues.
  3. Verify Polarity Reversal Detection settings: Ensure that the Polarity Reversal Detection feature is enabled and configured correctly on the gateway. Consult the gateway's documentation or contact the manufacturer for guidance.
  4. Monitor gateway logs: Check the gateway logs to see if there are any errors or anomalies related to the Polarity Reversal Detection feature.
  5. Test with a different PSTN line: If possible, test the VoIP gateway with a different PSTN line to isolate the issue.
By following these troubleshooting steps, you should be able to identify and resolve the issue causing the VoIP gateway to send an answer signal prematurely.

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,如果有內容輸出表示模組載入成功。






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


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.
G.729 Codec


OSS Endpoint Manager


Incredible PBX 2027

cd /var/www/html/admin/modules
tar zxvf ossepm16.tgz
rm -f ossepm16.tgz
rm -f /tmp/*
fwconsole ma install endpointman
fwconsole reload



Package Server

FreePBX GUI > Settings > OSS Endpoint Manager > Settings 

FreePBX GUI > Settings > OSS Endpoint Manager > Package Manager



Additional brands (Grandstream & Yeallink V80)

FreePBX GUI > Settings > OSS Endpoint Manager > Settings > Package Import/Export


IP & NTP & Type

FreePBX GUI > Settings > OSS Endpoint Manager > Settings

如果以後有修改 Settings 的內容,或者 Template Editor,完成變更後,還要到 Extension Mapping,選擇 Selected Phone Options 或者 Global Phone Options,按下 Rebuild,這樣才會套用更新到所有裝置的佈署檔。

Extension Provisioning

Add Device: Linksys PAP2T

FreePBX GUI > Settings > OSS Endpoint Manager > Package Manager

Create Template: my-pap2t

注意:預設的部署檔會將 PAP2T 的管理網頁界面關閉,新增一個部署設定檔 my-pap2t。

技巧:如果 template 內容如果有修改過,必須到 Extension Mapping 選擇分機後,重新執行一次 Save,這樣新的設定才會被套用。

FreePBX GUI > Settings > OSS Endpoint Manager > Template Manager

Edit the template: my-pap2t

注意:編輯 template 時,不要使用 Edit Global Setting Overrides,這個可能會弄壞 template。如果不小心 弄壞 template,只要將 template 移除後重建即可。

技巧:template 或者原始設定檔 (spa$mac.xml) 有修改過參數,要如何在設備部署前做驗證?以 HTTP 為例,瀏覽這段網址 http://freepbx-ip-addr/provisioning/p.php/spaxxxxxxx.xml,xxxxxxx 是設備的 MAC address (必須是小寫),可以下載部署設定檔。 

Extension Mapping

FreePBX GUI > Settings > OSS Endpoint Manager > Extension Mapping

PAP2T 設置

登入 PAP2T 管理界面 (advanced view) > Provisioning


Provisioning Template Files


File: spa$mac.xml

將檔案複製到目錄 /var/www/html/admin/modules/_ep_phone_modules/endpoint/cisco/linksysata/ 


  1. 移除日光節約的時間設定
  2. 移除 LAN 關閉 DHCP(SPA3102 必須啟用)
  3. 移除部署主機位址的設定(目前只能支援 tftp 方式)

SIP Response Codes

180 v.s. 183
Code 180 and 183 are both SIP response codes used to indicate the progress of a call. While they may seem similar, they have distinct differences in their meanings and usage.

Code 180: Ringing
Code 183: Session Progress
Key differences:

In summary, while both 180 and 183 response codes indicate call progress, 180 specifically indicates that the called party's phone is ringing, whereas 183 indicates that the call is in progress, but the called party has not yet answered.