How to interconnect Asterisk servers using PJSIP

In the world of VoIP communication, interconnecting Asterisk servers is a game-changer for small ISPs, businesses, or remote offices looking to build scalable phone systems. As someone who works daily with Asterisk for VoIP set-ups, I’ve seen how this open-source PBX can transform a simple server into a powerful trunk provider – and also a money maker. Whether you’re providing SIP trunks to customers or would like to link branch offices seamlessly, this guide walks you through using Asterisk PJSIP configuration and dial plan logic to create reliable interconnections. We’ll cover everything from basics to hands-on set-up, optimized for VoIP trunking and SIP endpoint management.

If you’re searching for “how to set up Asterisk trunks” or “PJSIP interconnection tutorial,” you’ve come to the right place. Let’s dive in and make your Asterisk server interconnection straightforward and efficient.

What is Asterisk?

Asterisk is the world’s leading open-source software for building communications applications, often called the Swiss Army knife of telephony as it comes with really a lot of features. From simple telephony soft switch to a complex media handling in a SBC, Asterisk is just amazing. Developed by Digium (now part of Sangoma), it powers companies from simple PBXs to complex call centers. Nevertheless Asterisk handles voice calls, video, and messaging over IP networks, making it ideal for VoIP server setups.

Why choose Asterisk for interconnecting servers? It’s free, highly customizable, and supports modern protocols like PJSIP — a lightweight, standards-compliant SIP stack that’s replaced the older chan_sip module. PJSIP offers better performance, NAT traversal, and security features, perfect for SIP trunk provisioning in distributed environments. In a small ISP scenario, like the one I work in, Asterisk lets you act as a central hub, routing calls between customer endpoints and external providers without breaking a sweat.

For those new to telephony, think of Asterisk as the brain behind your phone system: it processes incoming calls, applies rules via dial plans, and bridges connections across networks.

Understanding Trunks

In telephony, a trunk refers to a communication pathway capable of handling multiple simultaneous calls – like an highway for phone calls. Historically, trunks were physical lines like E1 in Europe or T1 in the US, managed by telecom giants such as France Telecom (now Orange). These could carry dozens of channels, forming the core of traditional PSTN networks. Of course, with time, things thankfully changed.

With the rise of the internet, VoIP revolutionized this. Trunks evolved into virtual connections using IP protocols, allowing unlimited scalability at a fraction of the cost. In Asterisk trunk configuration, a trunk is essentially a logical link between your server and another endpoint, like a remote office or customer PBX. This set-up enables seamless Asterisk interconnections, where calls flow bidirectionally without quality loss.

Key benefits for VoIP trunking:

  • Cost Savings: No need for expensive hardware; just IP bandwidth.
  • Scalability: Handle 10 or 10,000 calls by adding server resources. Perfect for call centers.
  • Flexibility: Route calls based on rules, like time of day or caller ID.

If you’re optimizing for “Asterisk SIP trunk set-up,” trunks are your starting point for reliable, multi-site VoIP deployments.

What is SIP? The Protocol Powering Modern VoIP

SIP, or Session Initiation Protocol, is the standard (RFC 3261) for initiating, maintaining, and terminating real-time sessions in VoIP. Pronounced “sip,” it’s a protocol that sets up a phone call over the internet. SIP handles signalling—think invitations, acceptances, and goodbyes—while leaving the actual voice data to other protocols.

In PJSIP for Asterisk, SIP is implemented efficiently for server-to-server interconnections. For example, when two Asterisk servers connect via a trunk, SIP messages negotiate the call parameters, such as codecs and endpoints. Common SIP methods include INVITE (to start a call), ACK (to confirm), and BYE (to end it).

What is Media? Handling the Audio in Your Calls

It’s not easy in the first time to understand what is “Media” in VoIP. As explained before, SIP is a signalling protocol and does not handle media (voice, video, etc.). Asterisk can seamlessly handle media with SIP. While SIP manages the “who” and “when” of a call, media is the actual content—the voice, video, or data streams. In VoIP, media travels via RTP (Real-time Transport Protocol) over UDP, separate from SIP signalling for efficiency. Codecs like G.711 (high-quality, bandwidth-heavy) or Opus (adaptive, low-latency) compress and transmit this data.

In Asterisk media handling, you configure trunks to bridge media streams securely, often using RTPEngine for NAT traversal in interconnected setups. Without proper media routing, calls might suffer from one-way audio or jitter—common pitfalls in multi-server VoIP architectures.

Pro tip: For optimal Asterisk PJSIP media setup, enable direct media (re-INVITE) between endpoints to bypass the server, saving CPU and bandwidth in large-scale trunks.

Step-by-Step: Configure a Trunk in Asterisk for Interconnections

Now, let’s get practical. We’ll configure two Asterisk servers: Server A (your main ISP hub, acting as the remote endpoint) and Server B (a customer or branch office PBX). This PJSIP trunk tutorial assumes Asterisk 16+ with PJSIP enabled (check via module show like pjsip in CLI).

Prerequisites for Successful Setup

  • Both servers on stable networks with public IPs or STUN/TURN for NAT.
  • Firewall ports open: 5060 UDP/TCP (SIP), 10000-20000 UDP (RTP media).
  • Install PJSIP: dnf install asterisk-pjsip (CentOS) or equivalent.
  • Backup configs: cp /etc/asterisk/pjsip.conf /etc/asterisk/pjsip.conf.bak.

Reload after changes: asterisk -rx "pjsip reload".

Server A: Configuring the Remote Endpoint (ISP Side)

On Server A (e.g., IP: 192.0.2.1), create a trunk to accept connections from Server B. Edit /etc/asterisk/pjsip.conf:

[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0:5060

[trunk-customer-b]
type=endpoint
transport=transport-udp
context=from-trunk  ; Dialplan context for incoming calls
disallow=all
allow=ulaw,alaw,gsm  ; Supported codecs for VoIP quality
auth=trunk-customer-b-auth
aors=trunk-customer-bdirect_media=no  ; Force media through server for recording/security

[trunk-customer-b-auth]
type=auth
auth_type=userpass
username=trunkuser  ; Shared secret with Server B
password=strongpass123
realm=192.0.2.1

[trunk-customer-b-aor]
type=aorcontact=sip:192.0.2.2:5060  ; Server B's IP

This sets up Server A as a secure SIP trunk provider. The auth section enforces username/password for PJSIP authentication in Asterisk, preventing unauthorized access.

Now, add dialplan rules in /etc/asterisk/extensions.conf for routing calls from the trunk:

[from-trunk]
exten => _X.,1,NoOp(Incoming from trunk) 
same => n,Dial(PJSIP/${EXTEN}@local-extension)  ; Route to internal users same => n,Hangup()

This handles incoming calls, forwarding them to local extensions. For outbound to Server B, we’ll cover in the next section.

Server B: Configuring the Customer Endpoint (Branch Office Side)

On Server B (e.g., IP: 192.0.2.2), register to Server A as a trunk client. In /etc/asterisk/pjsip.conf:

[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0:5060
local_net=192.168.0.0/16  ; Your internal network for NAT

[trunk-isp-a]
type=endpoint
transport=transport-udp
context=from-isp  ; Context for calls from Server A
disallow=all
allow=ulaw,alaw,gsm
auth=trunk-isp-a-auth
aors=trunk-isp-a-aor
outbound_auth=trunk-isp-a-auth
from_user=trunkuser
from_domain=192.0.2.1

[trunk-isp-a-auth]
type=auth
auth_type=userpass
username=trunkuser
password=strongpass123realm=192.0.2.1

[trunk-isp-a-aor]
type=aor
contact=sip:192.0.2.1:5060

Here, Server B authenticates to Server A, enabling bidirectional VoIP trunking. For outbound calls to the ISP trunk:

In /etc/asterisk/extensions.conf:

[from-internal]
exten => _9NXXNXXXXXX,1,NoOp(Outbound to ISP) 
same => n,Set(CALLERID(num)=${CALLERID(num)})  ; Preserve caller ID 
same => n,Dial(PJSIP/${EXTEN:1}@trunk-isp-a)  ; Strip 9 prefix, dial via trunk 
same => n,Hangup()

[from-isp] 
exten => _X.,1,NoOp(Incoming from ISP trunk) 
same => n,Dial(Local/${EXTEN}@internal-extensions)  ; Route to local users same => n,Hangup()

Test the setup: From Server B, dial an extension on Server A (e.g., Dial(PJSIP/100@trunk-isp-a)). Use pjsip show endpoints in Asterisk CLI to verify registration.

Troubleshooting Common Issues in Asterisk PJSIP Interconnections

  • One-Way Audio: Enable direct_media=yes or check RTP ports/firewalls.
  • Registration Fails: Verify auth credentials and realms match.
  • Codec Mismatch: Align allow/disallow on both ends.

For advanced Asterisk troubleshooting, enable debug logging: pjsip set logger on.

Best Practices for Secure and Scalable VoIP Trunks

  • Use TLS for SIP (add protocol=tls in transports) to encrypt signalling.
  • Implement ACLs in pjsip.conf to restrict IPs.
  • Monitor with tools like sngrep for SIP traffic analysis.
  • Scale with multiple trunks for load balancing in multi-Asterisk environments.

By following this Asterisk PJSIP interconnection guide, you’ll have a robust VoIP trunk up and running.

How to setup FreeRadius with SQL and Rest

In modern network environments, managing user access securely and efficiently is pain (in th harsh). Whether for a large enterprise, a university campus, or an ISP, manually configuring credentials on individual network devices simply doesn’t scale. This is where the AAA frameworkAuthentication, Authorisation, and Accounting—comes into play, and the RADIUS protocol is one of its most robust and widely adopted implementations in the industry.

RADIUS enables users to join a network based on various credentials, such as a username/password combination or a device’s MAC address. More importantly, it allows network administrators to enforce policies, controlling everything from assigned IP addresses and VLAN memberships to bandwidth limits and session durations.

In this article, we will explore how to implement a centralized authentication system using FreeRADIUS. We will cover how to integrate it with a centralised database like MariaDB using SQL module and how to extend its functionality by connecting to an external API with the rlm_rest module (trust me, this one is a pain but we will try to see how we can set it up).

Automating customer access with Radius

This guide is motivated by a real-world scenario. The project involves an ISP that delivers internet access to business customers via fiber and radio links, presenting each customer’s connection as a unique stateful tunnel. The current process lacks automated authentication. When an user subscribe to the ISP, we define manually the PPPoE password combination in the BNG where the subscriber get Internet. It’s not simple and it’s not the best way to do it as it requires manual intervention on the network equipment. That’s where FreeRADIUS is useful.

The goal is to build a centralised, self-service system where:

  • New customers can find their credentials in their personal dashboard on the website (not developed in this article).
  • Upon first connection, their credentials are automatically authenticated.
  • The system assigns the correct network policies (IP, VLAN, bandwidth) without manual intervention from the ISP’s operations team.

What is RADIUS?

RADIUS (Remote Authentication Dial-In User Service) is a networking protocol that provides centralised Authentication, Authorisation, and Accounting (AAA) management. Originally defined in RFC 2058 and updated in RFC 2865, it operates on a client-server model. Great! But what’s next? Why do I need RADIUS and why it’s a good point to have a server able to talk RADIUS?

AAA is the benefits of using RADIUS and it means :

  • Authentication: Verifies the identity of a user or device (e.g., “Is this username/password correct?”).
  • Authorisation: Determines what an authenticated user is allowed to do (e.g., “This user gets a static IP and 100Mbps bandwidth”).
  • Accounting: Tracks the consumption of network resources for billing, auditing, or reporting purposes (e.g., “User X consumed 15GB of data this month”).

RADIUS act as a back-end for network devices. End-user devices does not directly talk with the RADIUS server. Instead, they make a request (using PPPoE, DHCP, or whatever) to a Network Access Server (the BNG or the Wi-Fi access point, etc.) in the middle.

Why RADIUS is so critical?

For a small home network, adding a user to a router is trivial. But managing thousands or millions of subscribers, ensuring revoked access is immediate, and applying complex policy rules is impossible without a centralized system. RADIUS is the solution, finding essential use cases in:

  • Internet Service Providers (ISPs): Managing subscriber access over PPPoE, DHCP, or captive portals.
  • Enterprise Networks & Wi-Fi: Securing employee access to corporate WLANs and internal systems.
  • VPNs (Virtual Private Networks): Authenticating remote users before granting access to corporate resources.
  • Universities: Providing secure, credential-based WiFi access for students and staff.

Setup FreeRADIUS

FreeRADIUS is the open-source implementation of the RADIUS protocol. It is used by some of the world’s largest ISPs and enterprises and guest what ? It’s free and open source. Developed in C, this software is almost available on all major GNU/Linux distributions as Ubuntu, Debian, Fedora or OpenSUSE.

1. Installation

Installation is straightforward on most Linux distributions. On Ubuntu 22.04, you can install it with:

$ sudo apt update
$ sudo apt install freeradius freeradius-mysql freeradius-utils

Note: The package and configuration directory may vary. On Debian/Ubuntu, the server is called freeradius and configuration files are in /etc/freeradius/ (versions 3.0+), while older guides may reference radiusd and /etc/raddb/.

Configure FreeRADIUS

Basic configuration

The main configuration files are located in /etc/freeradius/. Before integrating a database, test the basic setup using the default file-based authentication.

  • Edit the client configuration (/etc/freeradius/clients.conf) to define your network device (NAS – e.g., your BNG or router) and a shared secret for secure communication.
  • Start the FreeRADIUS server in debug mode to see detailed logs:
  • In a new terminal, test authentication using the built-in radtest tool and a default user listed in /etc/freeradius/mods-config/files/authorize:
sudo systemctl stop freeradiussudo freeradius -X
radtest testing password localhost 0 testing123

You should see the server respond with an Access-Accept message in the debug output, indicating a successful test.

Configure with MariaDB (or MySQL)

For a dynamic, scalable user database, integrating SQL is essential.

  • Install MariaDB: sudo apt install mariadb-server
  • Configure Database: Secure the installation and create a database schema for FreeRADIUS. You can use the official schema provided in /etc/freeradius/mods-config/sql/main/mysql/schema.sql.
  • Configure FreeRADIUS SQL Module: Enable and configure the sql module by editing /etc/freeradius/mods-available/sql. Point the connection details to your MariaDB instance and database.
  • Update Sites: Ensure the sql module is being called in your virtual server configuration (typically in /etc/freeradius/sites-available/default).
sudo ln -s /etc/freeradius/mods-available/sql /etc/freeradius/mods-enabled/

Configure with RLM REST API

For ultimate flexibility, you can have FreeRADIUS authenticate against your existing customer API or user dashboard using the rlm_rest module. This allows you to:

  • Validate credentials against a web application’s database.
  • Dynamically generate custom RADIUS reply attributes based on API responses.
  • Integrate with modern authentication providers.

Configuration involves enabling the rest module and defining the endpoint URL, HTTP method, and how to translate the RADIUS request into API parameters and vice-versa.

Conclusion

Implementing FreeRADIUS moves network authentication from a manual, decentralised chore to an automated, centralised strategy. By leveraging its powerful SQL integration, you can manage thousands of users dynamically. Furthermore, the REST module opens doors to nearly limitless integration possibilities, allowing you to weave RADIUS authentication directly into your existing business logic and user management systems.

Whether you’re building a new ISP network or securing a large enterprise, FreeRADIUS provides the robust, scalable AAA foundation you need to ensure secure and manageable network access.