Hosted IP-PBX and SBC

SBC ( Session Borde Controllers ) are basically gateways that provide interconnectivity between the hosted IP-PBX of the enterprise to the outside world endpoints such as telco service provider, PSTN/ TDM , SIP trunking providers or even third party OTT provider apps like skype for business etc. If you have a hosted IPPBX or PBX in your data-centre or on premise and you need controlled but heavy outflowing traffic, it is a good idea to integrate a resilient and efficient SBC to provide seamless interconnectivity.

Hosted PBX

For an enterprises such as an Trading floor or warehouse with multiple phone types , softphones , hardphones , turrets etc distributed across various geographies and zones a device agnostic architectural setup is prime . Listing the essentials for setting up such a system. Note supplementary services are data-services , logging , licensing etc are important but kept out of scope to keep focus on functional aspects .

An enterprise application usually is structured in tiers or layers

  • Client tier – the networks clients communication to the central java programs . Runs on client machines
  • web tier – state full communication between client and business tier . Runs in server machine.
  • business tier- handles the logic of the application. The business tier uses the Enterprise Java Bean (EJB) container, which manages the execution of the beans
  • data tier – encompasses DB drivers . Runs on separate machines for database storage

Event services for Line status notifications

providers lines status notification across enterprise for inter zone and softphone to hardphone .

Routing services

routing calls within enterprise and hardphone sites read more about resource zones later in the article

Call Control Manager (CCM)

Consolidated set of all service and component that make up the VOIP platform besides media handlers. It includes SIP adapters, bridge managers, call processing frameworks, API frameworks, healthchecks etc.

Call processing framework ( CPF)

Signalling and call routing logic, mostly in SIP and trunks. Manages identities such as Call Line information, Called Party Information, line status etc in shared memory.

Multiple shared Lines and their statuses

Incases where there is a need to process multiple calls from a single User agent device such as a softphone or hardphone ( common scenario for a turret phone) , the design involves assigning it multiple sip uris and each sip uri will establish a line. When caller calls callee , the line is said to be BUSY , otherwise said to be IDLE. Transition of a shared sip line from IDLE to BUSY is transmitted to others via SIP PUBLISH as other UAs holding the same sip Similarly any other event like transfer is propagated to other via SIP UPDATE

Clustering Call control managers

A Call Communication manager (CCM) from various zones should be able to cowork on call and session management and advanced features such as routing from home guest zone to home zone , call transfer , refer , barge etc. Designing a clustered setup will also provide elasticity , fail-over and high availability. Can use clustered , HA compliant framework such as Oracle Communication Application Server , suited for enterprise level deployments.

Call Replication and distributed memory management

A node will store two types of data: active sessions and passive sessions. The active sessions are used by the node and stored in cache. The passive sessions are the replicas from the other nodes’ active sessions. The passives sessions are stored on a persistent storage.

Controlling Line Calls using AOR and Resource Zones

When dealing with many SIP endpoints , now referred to as resource, it is best to assign the resources to their respective zones. Thus a resource’s status updates will be only updated by its active resource zone while can be read by any resource zone.

Incoming request Zone vs Active Resource Zone

For an Incoming request such a INVITE , check whether the zone sending the request is its active resource zone or not .If the Active Resource Zone is the same zone on which the INVITE came in, then the call is handled by that zone. If the Active Resource Zone is a different zone, then the call needs to be forwarded to the Active Resource Zone.

Bridges for Local Media connections

Although call signalling is handled by a resources active resource zone only, we can still create media bridges in local zone of the resource .

Local MM bridges are used to auto answer an incoming sip line call and create trunk , especially from hardphones which do not support provisional responses.

Interzone proxy Handler

proxies call control messages between active and non active resource zones. Primarily mapping the sip messages with all custom headers inbetween the communication device interfaces.

Dial Trunk using multiple dedicated SIP lines and connect via Media Bridge

To save up on call routing /connection time and to support te ability to add as many users on call at runtime , a dedicated media bridge is established for every call.

  • A sip line activated is auto-answered by MM , creates a trunk and waits for other endpoint to join the bridge. The flow is as follows :
  • As INVITE arrives for an IDLE sip line , it is connected to a trunk and auto answered by a local MM bridge .
  • Since the call is already answered , when caller dials number for callee , collect the DTMF digits over RTP using RFC 2833 DTMF events.
  • Run inter-digit timer for digit collection and detect end of dialing on timeout.
  • The dialed trunk connection is made and call is added to media bridge
  • When provisional responses are received on the trunk connection, generate in-band call progress tones (ringing, proceeding etc) via the MM
  • When the line answers, the progress tones have to be stopped and the called party gets bridged to the calling party via the media bridge.

Call Diversion involves forwarding calls from zone to another zone. joinjed parties get call UPDATE status and forward response.

Call barge is the processing of joining an ongoing call . The barge event is usually propagated to joined parities via SIP INFO. Private lines do not allow barge in and are exclusively reserved for only few users.

Interconnectivity provided by an SBC ( Session Border Controller)

Hold-Resume and Music on Hold in multi-line evironment

While a regular p2p call involves simple reinvite based hold and resume with varrying SDP, the scenario is slightly more detailed for hold resume on bridged trunk connection , as explained below.

As the calls made are on bridge , a hold signal involves a RE-INIVITE with held-SDP to media manager (MM). If hold status on trunk is 200 OK the hold status will be sent to other call interfaces connected on the trunk. Else if hold is denied, 403 is sent back to hold-initiates.

Music on hold is an one way RTP mostly from media server.

For a bridged scenarios , separate Music on hold bridges are kept on Media Managers. When an UA has to hold , it is removed from original bridge and place on music on hold bridge. To be unhold/ resume it is placed back into the orignal bridge from music on hold bridge.


user initiates conference, the conference feature can execute on the zone where the user was logged on, irrespective of zones where the other conference attendees join from . The Call processing framework of originators zone completes the SDP exchange to establish two-way speech path among all the parties.

Incases there are multiple connections from a zone , a local MM conference bridge can be created for them which would connect back to originators MM conf bridge . this two part conf bridge will be transparent to the sip line sand users .

For provisioning inputs and settings setup a Diagnostics , Administration and Configuration platform which can process APIs for data services , licences , alarms or do remote device control such as using SNMP.

Session Border Controllers (SBC) role for PBX

At network level SBC operations include

  • bridging multiple interfaces in different networks even between the IPv4 and IPv6 networks
  • auto NAT discovery and STUN
  • protocol conversion such as TLS to UDP etc
  • Flood detection and IP filtering

For SIP specific functionalities, SBC does

  • SIP validation involving checks on syntax and message contents also consistency checks are performed.
  • stateful and call aware. tracing, monitoring and checking for validitya and health of all the SIP messages
  • Topology hiding
  • Traffic filtering
  • Codec filtering , reordering , media pinning, transcoding, or call recording
  • Data replication brings High Availability (HA) with hot backups or even Active-Active solutions.

Traffic sharing and routing roles of SBC can include

  • IP-based and Digest-based authentication
  • limiting traffic by number of concurrent calls or calling rate.
  • Dialplan and/or Custom routing
  • Dispatching/Load-balancing to a backend cluster of servers

SBC’s can be physical hardware boxes or software based applications, as the name suggests their purpose is to control the session at border between the enterprise and external service provider. They can be used for various roles such as

  • SIP to PSTN – SIP is an IP protocol whereas PSTN is a TDM one , achieving interoperability is also the KRA of an SBC
  • SIP trunking – SBC provide a secure sip connectivity to connect calls to sip trunks which provide bulk calls functionality at a flat pricing.
  • support for various fixed or mobile endpoints – SBC ensure they are RFC compliant and can extend SIP to any kind of telecom endpoint like PSTN , GSM, fax , Skype , sipphone , IP phones etc.
  • NAT (Network address translator) – To meet the packet routing challenges across a firewall or even during private -public mapping. A combo of DHCP servers and NAT provider comes very handy to reroute or perform hole punching such that signalling and media packets are not dropped and meet the required endpoint. More about NAT here – NAT traversal using STUN and TURN.
  • Load balancing – Reverse proxies and Load balancers is a much adopted industry practise to mask the inner IPs of the VoIP platform and also route traffic appropriately between control and media server .
  • Security, QoS and Regulatory compliance – since SBCs are required to typically support a large array of clients they adhere to regulatory and industry accepted standards ,which also involves security features like AAA, TLS/SSL and other means for quality of assurance like logging and fault detection, preventing DDoS etc . In many cases SBC can also encrypt / decrypt RTP streams for probing , tapping or lawful inspection .

Terminating at carriers, PSTN and IP gateways

There are 2 ways to integrate IP calls to telecom provider endpoints such as GSM or LTE phones.

  • PRI lines
  • SIP trunks

Additional SBC features

Inaddition to above it is good to have if an SBC provides extra features like forking , emergency number dialing ( 911 ) or active directory integration . Real Time Analysis and monitoring of call and metrics are also expected from a SBC since they reside on edge of the network and are more vulnerable to threats . For example Dialogic Mediant SBC’s and gateways , Audio Codes SBCs

With the shift from on premise PBXs to cloud based VM or microservice architecture , SBC vendors adopt a lager umbrella of services also including automation scripts for checks , reporting tools / consoles , developer friendly APIs to manage sessions via SBC and even WebRTC gateways to connect browser endpoints.

PBX connection to IMS systems

Typical VOIP/SIP scenario without IMS

A basic enterprise VoIP/SIP solution is illustrated in Figure. The key element is a soft switch (SIP PBX) which might be implemented as a combination of several SIP entities, such as SIP registrar, proxy server, redirect server, forking server, Back-To-Back User Agent (B2BUA) etc. SIP clients can be SIP hard-phones or soft-phones on PCs, PDAs etc. A PSTN gateway links the enterprise SIP PBX to the public PSTN. Enterprise applications, media servers, presence servers, and the VoIP/SIP PBX are interconnected through a company intranet.

VoIP System with IMS : With IMS, applications will be able to establish sessions across different access networks, with guaranteed QoS, flexible charging & AAA support. Call control, user’s database and services, which are the typical functions of softswitch, are controlled by separate units in IMS. CSCF (Call Session Control Function) handles session establishment, modification and release of IP multimedia sessions using the SIP/SDP protocol suite. Services features are separated from call control and handled by application servers. Subscriber’s database function is separated from service logic function and handled by HSS using open subscriber directory interface.

Link registration using subscribe-notify can be handled via Enterprise App server in PBX.

Forking proxy Setup of PBX : The enterprises SIP PBX can work as a forking proxy during call setup to redirect the calls.

Other usecases can involve presence sharing between different enterprise PBX with both domains interconnect their presence servers.

UseCase Scenarios

Any VOIP dependant system which deals with bulksome voice / video traffic from external endpoints is a usages scenarios. Listing few

  • provision of pre-defined enterprise based SIP URI.
  • Contact Call centres
  • Remote work / offsite monitoring
  • CRM solution for sales/marketing
  • Connecting webrtc click to dial from webpage to enterprise representatives
  • connecting enterprise UCC clients to PSTN endpoints

The There are many more features and usecases for an IP-PBX solution for an enterprise. The features of modern IP PBX systems are a big addon to internal secure telecom channel in an company and accross its various office.

Future of IP PBX

There has been a significant shift in replacing hard PBX systems with software-based IP PBX such as using Freeswitch, Asterisk or other commercial-grade SIP servers which seamlessly integrate into other business software such as CRM systems, task force management systems.
In recent times cloud telephony providers, particularly CPaaS platforms have revolutionized the IP telecommunication landscape with lightweight and feature-rich communication agents( web, native platform) and services such as programmable API to control call logic and services such as recording, IVR announcements, call parking, Automatic Queueing so on.



Opensips Modules

If you are new are opensips you cab read Over view of Opensisp SIP server here


Due to its very flexible and customisable routing engine it can be used in number of scenarios such as an SIP proxy or a router and due to its high throughput it is widely recommended as an enterprise grade inbound/outbound proxy server.

This article talks about modules and subparts of Opensips and their role in defining the purpose and application of Opensips which can be as an lighweight proxy to loadbalancer or even as AAA server.

Dispatcher Module

This modules implements a dispatcher for destination addresses. It computes hashes over parts of the request and selects an address from a destination set. The selected address is used then as outbound proxy.
The module can be used as a stateless load balancer, having no guarantee of fair distribution.

Path to the file with destination sets by default is “/etc/opensips/dispatcher.list” or “/usr/local/etc/opensips/dispatcher.list”.

modparam("dispatcher", "list_file", "/var/run/opensips/dispatcher.list")

db_url is used to load the sets of gateways from the database

modparam("dispatcher", "db_url", "mysql://user:passwb@localhost/database")

table_name loads the sets of gateways from the database. Default value is “dispatcher”.

modparam("dispatcher", "table_name", "my_dispatcher")

setid_col (string) – storing the gateway’s group id. Default value is “setid”.

modparam("dispatcher", "setid_col", "groupid")

destination_col (string) – destination’s sip uri.

modparam("dispatcher", "destination_col", "uri")

flags_col (string) – The column’s name in the database storing the flags for destination uri.

modparam("dispatcher", "flags_col", "dstflags")

force_dst (int) – If set to 1, force overwriting of destination address when that is already set. Default value is “0”.

modparam("dispatcher", "force_dst", 1)

flags (int) – affect dispatcher’s behaviour. Default value is “0”.

  • If flag 1 is set only the username part of the uri will be used when computing an uri based hash.
  • If no flags are set the username, hostname and port will be used The port is used only if different from 5060 (normal sip uri) or 5061 (in the sips case).
  • If flag 2 is set, then the failover support is enabled. The functions exported by the module will store the rest of addresses from the destination set in AVP, and use these AVPs to contact next address when the current-tried fails.
modparam("dispatcher", "flags", 3)

use_default (int) – If the parameter is set to 1, the last address in destination set is used as last option to send the message. For example, it is good when wanting to send the call to an anouncement server saying: “the gateways are full, try later”. Default value is “0”.

modparam("dispatcher", "use_default", 1)

dst_avp (str) – The name of the avp which will hold the list with addresses, in the order they have been selected by the chosen algorithm.

modparam("dispatcher", "dst_avp", "$avp(i:271)")

If use_default is 1, the value of last dst_avp_id is the last address in destination set. The first dst_avp_id is the selected destinations. All the other addresses from the destination set will be added in the avp list to be able to implement serial forking.

grp_avp (str) – The name of the avp storing the group id of the destination set. Good to have it for later usage or checks. Default is null.

modparam("dispatcher", "grp_avp", "$avp(i:272)")

cnt_avp (str) – The name of the avp storing the number of destination addresses kept in dst_avp avps.

modparam("dispatcher", "cnt_avp", "$avp(i:273)")

hash_pvar (str) – String with PVs used for the hashing algorithm like to do hashing over custom message parts.Default value is “null” – disabled.

modparam("dispatcher", "hash_pvar", "$avp(i:273)")

setid_pvar (str) – name of the PV where to store the set ID (group ID) when calling ds_is_from_list() with no parameter.

modparam("dispatcher", "setid_pvar", "$var(setid)")

ds_ping_method (string) – With this Method you can define, with which method you want to probe the failed gateways. This method is only available, if compiled with the probing of failed gateways enabled. Default value is “OPTIONS”.

modparam("dispatcher", "ds_ping_method", "INFO")

ds_ping_from (string) – With this Method you can define the “From:”-Line for the request, sent to the failed gateways. This method is only available, if compiled with the probing of failed gateways enabled. Default value is “sip:dispatcher@localhost”.

modparam("dispatcher", "ds_ping_from", "")

ds_ping_interval (int – With this Method you can define the interval for sending a request to a failed gateway. This parameter is only used, when the TM-Module is loaded. If set to “0”, the pinging of failed requests is disabled.Default value is “10”.

modparam("dispatcher", "ds_ping_interval", 30)

ds_probing_threshhold (int) – If you want to set a gateway into probing mode, you will need a specific number of requests until it will change from “active” to probing. The number of attempts can be set with this parameter. Default value is “3”.

modparam("dispatcher", "ds_probing_threshhold", 10)

ds_probing_mode (int) – Controls what gateways are tested to see if they are reachable.

  • If set to 0, only the gateways with state PROBING are tested,
  • if set to 1, all gateways are tested. If set to 1 and the response is 407 (timeout), an active gateway is set to PROBING state. Default value is “0”.
modparam("dispatcher", "ds_probing_mode", 1)

options_reply_codes (str) – The codes defined here will be considered as valid reply codes for OPTIONS messages used for pinging, apart for 200. Default value is “NULL”.

modparam("dispatcher", "options_reply_codes", "501, 403")

ds_select_dst(set, alg) – The method selects a destination from addresses set. Algorithm used to select the destination address can be :

  • “0” – hash over callid
  • “1” – hash over from uri.
  • “2” – hash over to uri.
  • “3” – hash over request-uri.
  • “4” – round-robin (next destination).
  • “5” – hash over authorization-username (Proxy-Authorization or “normal” authorization). If no username is found, round robin is used.
  • “6” – random (using rand()).
  • “7” – hash over the content of PVs string. Note: This works only when the parameter hash_pvar is set.
  • “X” – if the algorithm is not implemented, the first entry in set is chosen.
ds_select_dst("1", "0");

You can use ‘ds_next_dst()’ to use next address to achieve serial forking to all possible destinations. This function can be used from REQUEST_ROUTE.

ds_select_domain(set, alg) – selects a destination from addresses set and rewrites the host and port from R-URI. This function can be used from REQUEST_ROUTE.

ds_next_dst() – Takes the next destination address from the AVPs with id ‘dst_avp_id’ and sets the dst_uri (outbound proxy address). This function can be used from FAILURE_ROUTE.

ds_next_domain() – Takes the next destination address from the AVPs with id ‘dst_avp_id’ and sets the domain part of the request uri. This function can be used from FAILURE_ROUTE.

ds_mark_dst() – Mark the last used address from destination set as inactive, in order to be ingnored in the future. In this way it can be implemented an automatic detection of failed gateways. When an address is marked as inactive, it will be ignored by ‘ds_select_dst’ and ‘ds_select_domain’. This function can be used from FAILURE_ROUTE.

ds_mark_dst(“s”) – Mark the last used address from destination set as :

  • inactive (“i”/”I”/”0”),
  • active (“a”/”A”/”1”) or
  • probing (“p”/”P”/”2”).

With this function, an automatic detection of failed gateways can be implemented. When an address is marked as inactive or probing, it will be ignored by ‘ds_select_dst’ and ‘ds_select_domain’.

ds_is_from_list() – This function returns true, if the current request comes from a host from the dispatcher-list; otherwise false. This function can be used from REQUEST_ROUTE, FAILURE_ROUTE, BRANCH_ROUTE and ONREPLY_ROUTE.

ds_is_from_list(“group”) – This function returns true, if the current request comes from a host in the given group of the dispatcher-list; otherwise false.


Exported MI Functions

ds_set_state – Sets the status for a destination address (can be use to mark the destination as active or inactive).
state : state of the destination address
“a”: active
“i”: inactive
“p”: probing
group: destination group id
address: address of the destination in the group

MI FIFO Command Format:

ds_list – It lists the groups and included destinations.

MI FIFO Command Format:

ds_reload – reloads the groups and included destinations.

MI DATAGRAM Command Format:


Installation and Running

Destination List File – Each destination point must be on one line. First token is the set id, followed by destination address. Optionally, the third field can be flags value (1 – destination inactive, 2 – destination in probing mod — you can do bitwise OR to set both flags). The set id must be an integer value. Destination address must be a valid SIP URI. Empty lines or lines starting with “#” are ignored.

Exmaple of a dispatcher list file
line format
setit(integer) destination(sip uri) flags (integer, optional)

2 sip:
2 sip:

1 sip:
1 sip:
1 sip:

OpenSIPS config file

sample config file for dispatcher module

debug=9            debug level (cmd line: -dddddddddd)
log_stderror=yes  (cmd line: -E)

check_via=no      (cmd. line: -v)
dns=off           (cmd. line: -r)
rev_dns=off       (cmd. line: -R)

module loading

loadmodule ""
loadmodule ""
loadmodule ""

setting module-specific parameters

dispatcher params

modparam("dispatcher", "list_file", "../etc/dispatcher.list")
// modparam("dispatcher", "force_dst", 1)

if ( !mf_process_maxfwd_header("10") )
sl_send_reply("483","To Many Hops");
ds_select_dst("2", "0");
// t_relay();

db_text Module

Implementation for a simplified database engine based on text files. It can be used by OpenSIPS DB interface instead of other database module (like MySQL). It keeps everything in memory.

The db_text database system architecture contains

  • a database is represented by a directory in the local file system. NOTE: when you use db_text in OpenSIPS, the database URL for modules must be the path to the directory where the table-files are located, prefixed by “text://”,
    e.g., “text:///var/dbtext/opensips”.
  • a table is represented by a text file inside database directory.

Internal format of a db_text table

column definition name(type,attr) where types can be int , double , str and attributes be auto , null ,
* each other line is a row with data. The line ends with “\n”.
* the fields are separated by “:”.
* no value between two ‘:’ (or between ‘:’ and start/end of a row) means “null” value.
* next characters must be escaped in strings: “\n”, “\r”, “\t”, “:”.
* 0 — the zero value must be escaped too.

Sample of a db_text table ,

id(int,auto) name(str) flag(double) desc(str,null)
1:nick:0.34:a\tgood\: friend

Minimal OpenSIPS location db_text table definition

username(str) contact(str) expires(int) q(double) callid(str) cseq(int)

Minimal OpenSIPS subscriber db_text table example

username(str) password(str) ha1(str) domain(str) ha1b(str)

This database interface don’t support the data insertion with default values. All such values specified in the database
template are ignored.

db_mode (integer) – Set caching mode (0 – default) or non-caching mode (1). In caching mode, data is loaded at startup. In non-caching mode, the module check every time a table is requested whether the correspondingfile on disk has changed, and if yes, will re-load table from file.

modparam("db_text", "db_mode", 1)

Exported MI Functions

dbt_dump – Write back to hard drive modified tables.

opensipsctl fifo dbt_dump

dbt_reload – Causes db_text module to reload cached tables from disk. Parameters:
1 db_name (optional) – database name to reload.
2 table_name (optional, but cannot be present without the
db_name parameter) – specific table to reload.

MI FIFO Command Format:
opensipsctl fifo dbt_reload
opensipsctl fifo dbt_reload /path/to/dbtext/database
opensipsctl fifo dbt_reload /path/to/dbtext/database table_name

Installation and Running

Compile the module and load it instead of mysql or other DB modules.

Load the db_text module

loadmodule "/path/to/opensips/modules/"
modparam("module_name", "database_URL", "text:///path/to/dbtext/database

Using db_text with basic OpenSIPS configuration

Definition of ‘subscriber’ table (one line)

username(str) domain(str) password(str) first_name(str) last_name(str) phone(str) email_address(str) datetime_created(int) datetime_modified(int) confirmation(str) flag(str) sendnotification(str) greeting(str) ha1(str) ha1b(str) perms(str) allow_find(str) timezone(str,null) rpid(str,null)

Definition of ‘location’ and ‘aliases’ tables (one line)

username(str) domain(str,null) contact(str,null) received(str) expires(i
nt,null) q(double,null) callid(str,null) cseq(int,null) last_modified(st
r) flags(int) user_agent(str) socket(str)

Definition of ‘version’ table and sample records

table_name(str) table_version(int)

Configuration file using dbtext databse for oersistant storage . Also using auth


check_via=no    # (cmd. line: -v)
dns=no          # (cmd. line: -r)
rev_dns=no      # (cmd. line: -R)

loadmodule "modules/dbtext/"
loadmodule "modules/sl/"
loadmodule "modules/tm/"
loadmodule "modules/rr/"
loadmodule "modules/maxfwd/"
loadmodule "modules/usrloc/"
loadmodule "modules/registrar/"
loadmodule "modules/textops/"
loadmodule "modules/textops/"
loadmodule "modules/auth/"
loadmodule "modules/auth_db/"

setting module-specific parameters and making initial sanity checks — messages with max_forwards==0, or excessively long requests

-- mi_fifo params --

modparam("mi_fifo", "fifo_name", "/tmp/opensips_fifo")

-- usrloc params --

modparam("usrloc", "db_mode", 2)
modparam("usrloc|auth_db", "db_url", "text:///tmp/opensipsdb")

modparam("auth_db", "calculate_ha1", 1)
modparam("auth_db", "password_column", "password")
modparam("auth_db", "user_column", "username")
modparam("auth_db", "domain_column", "domain")

    if (!mf_process_maxfwd_header("10")) {
        sl_send_reply("483","Too Many Hops");
    if ($ml >=  65535 ) {
        sl_send_reply("513", "Message too big");

if (!$rm=="REGISTER") record_route();

//if the request is for other domain use UsrLoc 
if (is_myself("$rd")) {
    if ($rm=="REGISTER") {
        # digest authentication
        if (!www_authorize("", "subscriber")) {
            www_challenge("", "0");

    if (!is_myself("$rd")) {
        append_hf("P-hint: outbound alias\r\n");

    # native SIP destinations are handled using our USRLOC DB
    if (!lookup("location")) {
        sl_send_reply("404", "Not Found");
append_hf("P-hint: usrloc applied\r\n");

   if (!t_relay()) {

After the starting of a transaction such as REGISTER or INVITE we ensure that subsequent messages withing a dialog should take the path determined by record-routing using “record_route” function.

Combination of opensips working scenarios scripts with code is at

Kamailio as Inbound/Outbound proxy or Session Border Controller (SBC)

SBC ( Session Border Controller )

A typical voice core network consists of a B2BUA SIP server with media proxy and media processing units/servers along with components for billing, user profile management, shared memory/ cache, transcoders, call routing logic etc. However, a VOIP provider would not want to interface these critical servers to the outside world directly. An SBC ( Session Border Controller ) helps to abstract the core VoIP platform from public access and traffic.

The role of an SBC is to shield the core network from external entities such as user agent’s, carrier networks (topology hiding) while also providing security, auth and accounting services. In many cases, SBC also provides NAT traversal and policy control features ( such as rate-limiting, ACL etc ). In advanced cases, transcoding, topology concealment and load balancing are also achievable via an SBC such as Kamailio.

SBC interfaces

Following sections are usecases / features kamailio can extend to. Routing scripts at

Block user based on excessive REGISTER request  till an expiry time

For instance to block DDOS attacks, kamailio can check for the number of register requests a user sends and block above a threshold number subsequently .

    $var(block) = $Ts - 900;
    $var(expire) = $Ts - 300;

    if($sht(auth_block_list=>$au::last_block) > $var(block)){
        xlog("L_INFO", "$fU@$fd - REGISTER - $au User Already Blocked for Exceeded Register Requests.\n");
        sl_send_reply("403", "Already Blocked Forbidden");
    } else if($sht(auth_block_list=>$au::last_auth) > $var(expire)) {
        $sht(auth_block_list=>$au::last_block) = $Ts;
        xlog("L_INFO", "$fU@$fd - REGISTER - $au User Blocked for Exceeded Register Requests.\n");
        sl_send_reply("403", "Blocked Forbidden");
    } else {
        $sht(auth_block_list=>$au::auth_count) = 0;

More information on kamailio security can be found on It includes Sanity checks for incoming SIP requests ,Access Control Lists and Permissions, Hiding Topology Details, Anti Flood and Traffic Monitoring and Detection.

Anti Flood with Pike Module

To be on edge of a voip pltform, a SIP server must keep track of all incoming request and their sources. Blocking the ones which exceed the limit or appear like a dos attack. Pike module reports high traffic from an IP if detected.

A sample script to detect high traffic from an IP and add it to ban list for a while . But exclude the known IP sources such as PSTN gateways etc

loadmodule ""
loadmodule ""
# ----- pike params -----
modparam("pike", "sampling_time_unit", 2)
modparam("pike", "reqs_density_per_unit", 16)
modparam("pike", "remove_latency", 4)
route[REQINIT] {
if(src_ip!=myself) {
	if($sht(ipban=>$si)!=$null) {
		# ip is already blocked
		xdbg("request from blocked IP - $rm from $fu (IP:$si:$sp)\n");
	if (!pike_check_req()) {
		xlog("L_ALERT","ALERT: pike blocking $rm from $fu (IP:$si:$sp)\n");
		$sht(ipban=>$si) = 1;

Access Control List with Permission Module

permission module handles ACL by storing permission rules in plaintext configuration files , hosts.allow and hosts.deby by tcpd.

loadmodule ""
# ----- permissions params -----
modparam("permissions", "db_url", DBURL)
modparam("permissions", "db_mode", 1)
    if((!is_method("REGISTER")) && allow_source_address()) {
        # source IP allowed

Call Routing Functions

if (allow_routing("rules.allow", "rules.deny")) {

Registration permissions

if (method=="REGISTER") {
    if (allow_register("register")) {
    } else {
        sl_send_reply("403", "Forbidden");

URI permissions

if (allow_uri("basename", "$rt")) {  // Check Refer-To URI

Address permissions

// check if sourec ip/port is in group 1
if (!allow_address("1", "$si", "$sp")) {
    sl_send_reply("403", "Forbidden");

Trusted Requests

if (allow_trusted("$si", "$proto")) {

Checks protocols which could be one of the “any”, “udp, “tcp”, “tls”, “ws”, “wss” and “sctp”.

Perform Load Balancing with Dispatcher Module

Load balancing is critical to a production ready system to provide High availability and load sharing among available servers. This could be either stateless or stateful where they use call state tracking

Dispatcher module in Kamailio lends capabilities of SIP traffic dispatcher to it. It can load routes to gateways or destination sets from any storage source such as mysql , psql database or even plain text file (modparam("dispatcher", "db_url", <datasource_name>).

It can also assign priority for routing sip traffic to it ( modparam("dispatcher", "priority_col", "dstpriority"))

To discover active of inactive gateways it uses TM module. One can choose one among many algorithms to share the load , like

  • 0 – hash over callid
  • 1 – hash over from URI
  • 2 – hash over to URI
  • 3 – hash over request-URI
  • 4 – round-robin (next destination)
  • 5 – hash over authorization-username
  • 6 – random destination (using rand())
  • 7 – hash over the content of PVs string
  • 8 – select destination sorted by priority attribute value (serial forking ordered by priority).
  • 9 – use weight based load distribution . Needs attribute ‘weight’ per each address
  • 10 – call load distribution ie route to one that has the least number of calls associated
  • 11 – relative weight based load distribution(rweight)
  • 12 – dispatch to all destination in setid at once (parallel forking).
  • x – if the algorithm is not implemented, the first entry in set is chosen.

Some attributes passed with each destination set

  • duid – identify a destination (gateway address). Practically the load within the group is associated with this value.
  • maxload – upper limit of active calls per destination
  • weight – percent of calls to be sent to that gateways
  • rweight – relative weight based load distribution.
  • socket – sending socket for the gateway including keepalives
  • ping_from – from URI in OPTIONS keepalives

Active host usage probability is, rweight/(SUM of all active host rweights in destination group). recalculation is fired as host enables or disables.

Every destination has congestion threshold(weight) and after enabling c (congestion control), rweight is also used to control congestion tolerance lowering the weight by 1 as congestion is detected.

EWMA ( exponential weighted moving average ) is speed at which the older samples are dampened.

idunsigned int10noprimaryauto
setidintnot specified0no
flagintnot specified“”no
priorityintnot specified0no

To insert into dispatcher

INSERT INTO "dispatcher" VALUES(1,1,'sip:',0,12,'rweight=50;weight=50;cc=1;','');

set ping gateway once per second

modparam("dispatcher", "ds_ping_interval", 1)

enabling congestion metrics

modparam("dispatcher", "ds_ping_latency_stats", 1)

latency estimator

modparam("dispatcher", "ds_latency_estimator_alpha", 900)
loadmodule ""
# ----- dispatcher params ----- 
modparam("dispatcher", "db_url", DBURL) 
modparam("dispatcher", "table_name", "dispatcher") modparam("dispatcher", "flags", 2) 
modparam("dispatcher", "dst_avp", "$avp(AVP_DST)") modparam("dispatcher", "grp_avp", "$avp(AVP_GRP)") modparam("dispatcher", "cnt_avp", "$avp(AVP_CNT)") modparam("dispatcher", "sock_avp", "$avp(AVP_SOCK)")

request_route {
# do checks , indialog etc ...
# dispatch destinations 

# Dispatch requests
route[DISPATCH] {
     # round robin dispatching on gateways group '1'
     if(!ds_select_dst("1", "4")) {
         send_reply("404", "No destination");
     xlog("L_DBG", "--- SCRIPT: going to <$ru> via <$du>\n");

# Try next destinations in failure route, except if session gets cancelled 
failure_route[RTF_DISPATCH] {
     if (t_is_canceled()) {
     # next DST - only for 500 or local timeout
     if (t_check_status("500") or (t_branch_timeout() and !t_branch_replied())) {
         if(ds_next_dst()) {

More on Kamailio Call routing and Control

Kamailio basic setup as proxy for FreeSWITCH

I have added a detailed description of how kamalio based SIP servers can function as proxy / SBC for SIP Application server which could be an enterprise PBX or a full fledged Telecom Application Server such as Asterix , Freeswitch , Oracle Weblogic, telestax sip server etc

Kamailio basic setup as proxy for FreeSWITCH


Session Border Controller (SBC) for WebRTC

  • B2BUA
  • Features
    • Security
      • Topology hiding
    • Connectivity
      • Least Cost Routing based on MoS
      • Protocol translations
      • Automatic Rerouting
    • QoS
    • Regulatory
    • Media services
      • NAT
    • Statistics and billing information
  • Gateways vs SBC
  • Building a SBC

Unified communication services build around WebRTC should be vendor agnostic and multi-tenant and be supported by other Communication Service Providers (CSPs), SIP trunks, PBXs, Telecom Equipment Manufacturers (TEMs), and Communication Platform as a Service (CPaaS). This can happen if all endpoints adhere to SIP standards in most updated RFC. However since not all are on the boat , Session border controllers are a great way to mitigate the differences and provide seamless connectivity to signalling and media , which could be between WebRTC, SIP or PSTN, from TDM to IP .

Session Border Controllers ( SBC )  assist in controlling the signalling and usually also the media streams involved in calls and sessions. They are often part of a VOIP network on the border where there are 2 peer networks of service providers such as backbone network and access network of corporate communication system which is behind firewall.

A more complex example is that of a large corporation where different departments have security needs for each location and perhaps for each kind of data. In this case, filtering routers or other network elements are used to control the flow of data streams. It is the job of a session border controller to assist policy administrators in managing the flow of session data across these borders.

– wikipedia

SBC act like a SIP-aware firewall with proxy/B2BUA.

What is B2BUA?

A Back to back user agent ( B2BUA ) is a proxy-like server that splits a SIP transaction in two pieces:

  • on the side facing User Agent Client (UAC), it acts as server;
  • on the side facing User Agent Server (UAS) it acts as a client.

SBC mostly have public url address  for teleworkers and a internal IP for enterprise/ inner LAN . This enables users connected to enterprise LAN ( who do not have public address ) to make a call to user outside of their network. During this process SBC takes care of following while relaying packets .

  1. Security
  2. Connectivity
  3. Qos
  4. Regulatory
  5. Media Services
  6. Statistics and billing information

Explaining the functions of SBC in detail

1. Security

SBCs provide security features such as encryption, authentication, and firewall capabilities to protect the network from unauthorized access and attacks. SBCs are often used by corporations along with firewalls and intrusion prevention systems (IPS) to enable VoIP calls to and from a protected enterprise network. VoIP service providers use SBCs to allow the use of VoIP protocols from private networks with Internet connections using NAT, and also to implement strong security measures that are necessary to maintain a high quality of service. The security features includes :

  • Prevent malicious attacks on network such as DOS, DDos.
  • Intrusion detection
  • cryptographic authentication
  • Identity/URL based access control
  • Blacklisting bad endpoints
  • Malformed packet protection
  • Encryption of signaling (via TLS and IPSec) and media (SRTP)
  • Stateful signalling and Validation
  • Toll Fraud – detect who is intending to use the telecom services without paying up

Topology hiding

SBC hides and anonymize secure information like IP ports before forwarding message to outside world . This helps protect the internal node of Operators such as PSTN gateways or SIP proxies from revealing outside.

2. Connectivity

As SBC offers IP-to-IP network boundary, it recives SIP request from users like REGISTER , INVITE  and routes them towards destination, making their IP. During this process it performs various operations like

  • NAT traversal
  • IPv4 to IPv6 inter-working
  • VPN connectivity
  • SIP normalization via SIP message and header manipulation
  • Multi vendor protocol normalization

Further Routing features includes  :

Least Cost Routing based on MoS ( Mean Opinion Score ) : Choosing a path based on MoS is better than chooisng any random path . 

Protocol translations SBCs can bridge WebRTC calls with other communication protocols such as SIP, H.323, and PSTN to enable communication between different systems and networks.

In essence SBC achieve interoperability, overcoming some of the problems that firewalls and network address translators (NATs) present for VoIP calls.

Automatic Rerouting

Connectivity loss from UA for whole branch is detected by timeouts . But they can also be detected by audio trough SIP OPTIONS by SBC .  In such connectivity loss , SBC decides rerouting or sending back 504 to caller .

SBC 2 (1)

4. QoS

To introduce performance optimization and business rules in call management QoS is very important. This includes the following:

  • Traffic policing
  • Resource allocation
  • Rate limiting
  • Call Admission Control (CAC)
  • ToS/DSCP bit setting
  • Recording and Audit of messages , voice calls , files

System and event logging

SBCs can log call information and statistics, and provide real-time monitoring capabilities to troubleshoot and diagnose issues with WebRTC calls.

5. Regulatory

Govt policies ( such as ambulance , police ) and/ or enterprise policies may require some calls to be holding priority over others . This can also be configured under SBC as emergency calls and prioritization.

Some instances may require communication provider to comply with lawful bodies and provide session information or content , this is also called as Lawful interception (LI) . This enables security officials to collect specific information rather than examining all the traffic that passes through a particular router. This is also part of SBC.

6. Media services

Many of the new generation of SBCs also provide built-in digital signal processors (DSPs) to enable them to offer border-based media control and services such as- DTMF relay , Media transcoding , Tones and announcements etc.

WebRTC enabled SBC’s also provide conversion between DTLS-SRTP, to and from RTCP/RTP. Also transcoding for Opus into G7xx codecs and ability to relay VP8/VP9 and H.264 codecs.

Network Address Translation (NAT)

SBCs can handle Network Address Translation (NAT) to allow WebRTC clients behind a NAT to connect to other clients outside of the NAT.

7. Statistics and billing information

SBC have an interface with and OSS/BSS systems for billing process , as almost all traffic that pass through the edge of the network passes via SBC. For this reason it is also used to gather Statistics and usage-based information like bandwidth, memory and CPU.  PCAP traces of both signaling and media information of specific sessions .

New feature rich SBCs also have built-in digital signal processors (DSPs). Thus able to provide more control over session’s media/voice. They also add services like Relay and Interworking, Media Transcoding, Tones and Announcements, DTMF etc.

SBCs act as a security gateway and traffic manager for WebRTC sessions, ensuring that the communication is secure, of good quality, and can traverse different networks and protocols.

Session Border Controller (SBC)
Session Border Controller for WebRTC , SIP , PSTN , IP PBX and Skype for business .

Diagram Component Description

Gateways vs SBC

Gateways provide compression or decompression, control signaling, call routing, and packetizing.

PSTN Gateway : Converts analog to VOIP and vice versa . Only audio no support for rich multimedia .

VOIP Gateway : A VoIP Gateway acts like a translator converting digital telecom lines to VoIP . VOIP gateway often also include voice and fax. They also have interfaces to Soft switches and network management systems.

WebRTC Gateway : They help in providing NAT with ICE-lite and STUN connectivity for peers behind policies and Firewall .

SIP trunking : Enterprises save on significant operation cost by switching to IP /SIP trunking in place of TDM (Time Division Multiplexing). Read more on SIP trunk and VPN  here. 

SIP Server : A Telecom application server ( SIP Server ) is useful for building VAS ( Value Added Services ) and other fine grained policies on real time services . Read more on SIP Servers here . 

VOIP/SIP service Provider :   There are many Worldwide SIP Service providers such as Verizon in USA , BT in europe, Swisscom in Switzerland etc .

Building a SBC

The latest trends in Telecommunications industry demand an open standardized SBC to cater to growing and large array of SIP Trunking, Unified Multimedia Communications UC&C, VoLTE, VoWi-Fi, RCS and OTT services worldwide . Building an SBC requires that it meet the following prime requirements :

  • software centric
  • Cloud Deploybale
  • Rich multimedia (audio , video , files etc) processing
  • open interfaces
  • The end product should be flexible to be deployed as COTS ( Commercial Off the shelf) product or as a virtual network function in the NFV cloud.
  • Multi Configuration , should be supported such as Hosted or Cloud deployed .
  • Overcome inconsistencies in SIP from different Vendors
  • Security and Lawful Interception
  • Carrier Grade Scaling

Flow Diagram 


Thus we see how SBC became important part of comm systems developed over SIP and MGCP. SBC offer B2BUA ( Back to Back user agent) behavior to control both signalling and media traffic.