Opensips as SIP gateway

OpenSIP provided dispatcher modules which computes hashes over parts of the request and selects an address from a destination set which is then as outbound proxy.

Combination of opensips working scenarios scripts with code is at

In the config of opensips load the file dispatcher.list with destination sets

modparam("dispatcher", "list_file", "/var/run/opensips/dispatcher.list")
 2 sip:
 2 sip:
 1 sip:
 1 sip:
 1 sip:

or one can also load the sets from the database

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

Tthe algorithm used to select the destination address.
“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.

and the state of the destination address can be

“a”: active
“i”: inactive
“p”: probing

Load Balancer

Opensip can function as load balancer , distributing the load between different SIP Application servers .

example of gateway sets file in dbtext/diapatcher.list

id(int,auto) setid(int) destination(string) socket(string,null) state(int) weight(int) priority(int) attrs(string) description(string)
1:1:sip\:\:5060:null:0:1:1:'carrier':'load balancer for OB'
2:2:sip\:\:5060:null:0:1:1:'carrier':'Load balancer for IB'

Health Monitoring

Probing and pinging features in Opensips can detect whether gateways are responding or not . Threshold and probing mode can fine tune the behaviour.

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)
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();

dbtext is an 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.

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.

Set db_mode parameter

modparam(“db_text”, “db_mode”, 1)

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

Subscriber and Location

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

-- 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")

// initial sanity checks -- messages with max_forwards==0, or excessively long requests
if (!mf_process_maxfwd_header("10")) {
sl_send_reply("483","Too Many Hops");
if ($ml >=  65535 ) {
sl_send_reply("513", "Message too big");

// we record-route all messages -- to make sure that subsequent messages will go through this proxy;
if (!$rm=="REGISTER") record_route();
<pre><code>// subsequent messages withing a dialog should take the path determined by record-routing
if (loose_route()) {
    // mark routing logic in request
    append_hf("P-hint: rr-enforced\r\n");

if (!is_myself("$rd")) {
    // mark routing logic in request
    append_hf("P-hint: outbound\r\n");

//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()) {

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

A typical voice core network consists of 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 outside world directly , there for a SBC ( Session Border Controller ) comes into picture .

The role of an SBC is to shield the core network from external entities such as user agent’s , carrier network 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 is also achievable via a SBC such as Kamailio .

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

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

PSTN gateway routing


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