Kamailio Security

Security is Critical for a VoIP platform as it is susceptible to hacks , misuse , eavesdropping or just sheer misuse of the system by making robotic flood calls . Kamailio SIP Server provides some key features to meet these challenges which will be discussed in this blog .

Sanity checks for incoming SIP requests

Being a gateway on the VOIP system permiter is a challenging task due to the security threast it posses. It is must to configure per request initial checks for all incoming SIP request. This ideally should be the first step in routing clock before any other processing.

Exmaple programs https://github.com/altanai/kamailioexamples/blob/2039639275a33a2ba2435ae0b781e6f9dd51220e/Barebone_SIPServer/kamailio.cfg

request_route {
    // proceed with routing 

Pointers for functionality

For replies coming from local users , usually behind NAT , do not open a new TCP connection on each reply


For indialog requests also close connection after forwarding the request.

if(has_totag()) {

Check if any IP is flooding the server with messages and block for some time ( ANTI-FLOOD and pike decsribed later in the article ).
Ofcourse exclude self IP . sample to do blocking using hastable’s psedi variable ipban

if(src_ip!=myself) {
    if (!pike_check_req()) {
        $sht(ipban=>$si) = 1;

Friendly-scanners are type of botnets probing and scanning known IP ranges(5060,5061..) for SIP server, softswitches, cloud PBX. Once they detect a suitably open server they use brute force tactic to send all commonly/default username/passwords accounts. The prime purpose is to extract all vulenrable accounts for creating fradulent calls such as crating DOS attacks using high tarffic and consuming all bandwidth from good calls, free internation calls or imposter/scam calls.

Among some obvious ways to block the flood of packets by these scanner are

  • imply strict firewalls rules for allowing only known client IP’s
  • changing default SIP port from 5060 to some other non standard port in network
  • checking User agent for known attackes such as (sipcli , sipvicious , sip-scan , sipsak , sundayddr , friendly-scanner , iWar , CSipSimple , SIVuS , Gulp , sipv , smap , friendly-request , VaxIPUserAgent , VaxSIPUserAgent , siparmyknife , Test Agent)
if($ua =~ "friendly-scanner|sipcli|sipvicious|VaxSIPUserAgent") {
  • track unsuccesfull quick/consecutive attempts from an IP and block its access temporatliy or permamntly. Such as failing to REGISTER / autehticate for 3 consecutive time should block it .

Track if the message is hopping too many times within the server server , intra or inter networks not reaching the destination . mf_process_maxfwd_header(maxvalue). Note maxvalue is added is no Max-Forward header is found in the message.


Sanity is a complete module by itself to perform various checks and validation such as

  • ruri sip version – (1) – checks if the SIP version in the request URI is supported, currently only 2.0
  • ruri scheme – (2) – checks if the URI scheme of the request URI is supported (sip[s]|tel[s])
  • required headers – (4) -checks if the minimum set of required headers to, from, cseq, callid and via is present in the request
  • via sip version – (8) – disabled
  • via protocol – (16) – disabled
  • Cseq method – (32) – checks if the method from the Cseq header is equal to the request method
  • Cseq value – (64) – checks if the number in the Cseq header is a valid unsigned integer
  • content length – (128) – checks if the size of the body matches with the value from the content length header
  • expires value – (256) – checks if the value of the expires header is a valid unsigned integer
  • proxy require – (512) – checks if all items of the proxy require header are present in the list of the extensions from the module parameter proxy_require.
  • parse uri’s – (1024) – checks if the specified URIs are present and parseable by the Kamailio parsers
  • digest credentials (2048) – Check all instances of digest credentials in a message
  • duplicated To/From tags (4096) – checks for the presence of duplicated tags in To/From headers.
  • authorization header (8192) – checks if the Authorization is valid if the scheme in “digest” always returns success for other schemes.
    sample for URI checks for list of parsed URIs: Request URI (1), From URI (2) and To URI (4).

Full route[REQINIT] block

route[REQINIT] {

if(has_totag()) {

if(src_ip!=myself) {
    if (!pike_check_req()) {
        $sht(ipban=>$si) = 1;

if($ua =~ "friendly-scanner|sipcli|sipvicious|VaxSIPUserAgent") {

if (!mf_process_maxfwd_header("10")) {
    sl_send_reply("483","Too Many Hops");

if(is_method("OPTIONS") && uri==myself && $rU==$null) {

if(!sanity_check("17895", "7")) {
    xlog("Malformed SIP request from $si:$sp\n");

Access Control Lists and Permissions

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

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

sample programs to check for allowed access in LUA programing o Kamailio along when acting as registrar – https://github.com/altanai/kamailioexamples/blob/master/Lua%20-%20kamailio%20Registrar%20permission%20auth/kamailio.cfg


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

Hiding Topology Details

Stripping the SIP routing headers that show topology details involves steps such as hiding the local IP address of user agent , hiding path taken to reach the server , obscuring the core SIP server’s ip and details etc . Some headers which giave away information are

  • top most Via header
  • contact address
  • Record-Route headers
  • sometimes the Call-ID header

This goes a long way in helping to keep the inner network topology secure from malacious exploiters, expecially to protect IP of the PSTN gateways which could let to an costly mess or gensrally from attackers and reverse engineering.

Topoh module hides the network topology by removing the internal IP addresa and instead add ing them in encrypted form the same sip packet. Diff server using the same shared secret key can encode decode the encrypted addresses.

This way it doesnt not even have to store the state of the call and is transpoarent to all call routing logic

sample program for kamailio sip server to provide topology hiding – https://github.com/altanai/kamailioexamples/tree/abcc7b06c00fee12252133614187b0451757fcf2/Topology_hiding

loadmodule topoh.so

modparam("topoh", "mask_key", "somekey")
modparam("topoh", "mask_ip", "")
modparam("topoh", "mask_callid", 1)

topoh module

Primarily it does these things
hide the addresses of PSTN gateways
protect your internal network topology
interconnection provider – to keep the details of connected parties secret to the other, to prevent a bypass of its service in the future

loadmodule topoh.so
modparam("topoh", "mask_key", "YouDoHaveToChangeThisKey")
modparam("topoh", "mask_ip", "")
modparam("topoh", "mask_callid", 1)


mask_key (str)
mask_ip (str)
mask_callid (integer)
uparam_name (str)
uparam_prefix (str)
vparam_name (str)
vparam_prefix (str)
callid_prefix (str)
sanity_checks (integer)
uri_prefix_checks (integer)
event_callback (str)

Primarily tis module uses mask key to code the trimmed via header information and insert them into pre specified param names with prefixes. Hence it can work with stageful or stateless proxy and can also work if server is restarted in between

topos module

Offers topology hiding by stripping the SIP routing headers that show topology details.

It requires 2 modules rr module since server must perform record routing to ensure in-dialog requests are encoded/decoded and database module to store the data for topology stripping and restoring.

Params :
storage (str) – could be redis or database backend

modparam("topos", "storage", "redis")

db_url (str)

modparam("topos", "db_url", "dbdriver://username:password@dbhost/dbname") 
modparam("topos", "db_url", "mysql://kamailio:kamailiorw@localhost/kamailio”

mask_callid (int) – Whether to replace or not the Call-ID with another unique id generated by Kamailio. ( present with topoh)
sanity_checks (int) – with sanity module to perform checks before encoding /decoding
branch_expire (int)
dialog_expire (int)
clean_interval (int)
event_callback (str) – callback event

modparam("topos", "event_callback", "ksr_topos_event")
function ksr_topos_event(evname)
 KSR.info("===== topos module triggered event: " .. evname .. "\n");
 return 1;

event route :

loadmodule "topos.so"
loadmodule "topos_redis.so"

//topos params 
modparam("topos", "storage", "redis")
//branch_expire is 10 min
modparam("topos", "branch_expire", 10800)
// dialog_expire is 1 day
modparam("topos", "dialog_expire", 10800)
modparam("topos", "sanity_checks", 1)


To save from the automatic port scans that attackers carry out to hack into the system use the script below

:CHECK_TCP - [0:0]
:ICMP - [0:0]
:PRIVATE - [0:0]
:PSD - [0:0]
:SERVICES - [0:0]
-A INPUT -i lo -j ACCEPT 
-A INPUT -i eth0 -p ipv6 -j ACCEPT 
-A OUTPUT -o lo -j ACCEPT 
-A CHECK_TCP -p tcp -m tcp ! --tcp-flags SYN,RST,ACK SYN -m state --state NEW -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,ACK -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags FIN,ACK FIN -m state --state INVALID,NEW,RELATED -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags SYN,RST SYN,RST -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags FIN,RST FIN,RST -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags PSH,ACK PSH -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags ACK,URG URG -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-option 64 -j DROP 
-A CHECK_TCP -p tcp -m tcp --tcp-option 128 -j DROP 
-A ICMP -p icmp -m icmp --icmp-type 11/1 -m limit --limit 5/sec -m state --state NEW -j ACCEPT 
-A ICMP -p icmp -m icmp --icmp-type 11/0 -m limit --limit 5/sec -m state --state NEW -j ACCEPT 
-A ICMP -p icmp -m icmp --icmp-type 3 -m limit --limit 10/sec -m state --state NEW -j ACCEPT 
-A ICMP -p icmp -m icmp --icmp-type 8 -m limit --limit 10/sec --limit-burst 10 -m state --state NEW -j ACCEPT 
-A ICMP -p icmp -j DROP 
-A PSD -p tcp -m statistic --mode random --probability 0.050000 -j REJECT --reject-with icmp-port-unreachable 
-A PSD -p tcp -m statistic --mode random --probability 0.050000 -j TARPIT  --reset 
-A PSD -p tcp -m statistic --mode random --probability 0.500000 -j TARPIT  --tarpit 
-A PSD -p udp -m statistic --mode random --probability 0.050000 -j REJECT --reject-with icmp-port-unreachable 
-A PSD -m statistic --mode random --probability 0.050000 -j REJECT --reject-with icmp-host-unreachable  
-A SERVICES -p icmp -m state --state INVALID -j DROP 
-A SERVICES -p icmp -j ICMP 
-A SERVICES -p udp -m udp --dport 123 -m state --state NEW -j ACCEPT 
-A SERVICES -p udp -m udp --dport 53 -m state --state NEW -j ACCEPT 
-A SERVICES -p tcp -m tcp --dport 53 -m state --state NEW -j ACCEPT 
-A SERVICES -p tcp -m udp -m multiport --dports 5060 -m state --state NEW -j ACCEPT 
-A SERVICES -p tcp -m udp -m multiport --dports 5061 -m state --state NEW -j ACCEPT 
-A SERVICES -i eth0 -j PSD 

Update/Remove Server and User Agent Headers

Rewrite server header to save the exact version of server from hackers

server_header="Server: Simple Server"

or completely rmemove it from traces



user_agent_header="User-Agent: My SIP Server"

Remove Server warnings from traces and log file

Warnings expose the vulnerabilities of system and it is best to remove them in production enviornment

user_agent_header="User-Agent: My SIP Server"

Anti Flood

During Auth or logging there is a fair chance of leaking credentials or the fact that users opt for weak password themselves compromising the system via bruteforcing username/password . Or attacker may be bruteforcing prefixes to understand config and routing logic
Random unnecessary flood of SIP requests can consume CPU and make it slow or unavailable for others as Denial of Service . These situations can be made less daunting via pike module

pike modules

tracks the number of SIP messages per source IP address, per period.

loadmodule "pike.so"

// pike params 
modparam("pike", "sampling_time_unit", 2)
modparam("pike", "reqs_density_per_unit", 20)
modparam("pike", "remove_latency", 4)

//routing logic inclusion
route {
  if (!pike_check_req()) {
    xlog("L_ALERT","ALERT: pike block $rm from $fu (IP:$si:$sp)\n");

Pike module implementation in LUa on kamailio https://github.com/altanai/kamailioexamples/tree/ead84a684108600ad930027a3dcc6ab7442f139c/Lua%20-%20kamailio%20Registrar%20permission%20auth


can syslog files for specific messages based on regular expressions and act upon matching by banning IP addresses.

Traffic Monitoring and Detection

Secfilter module

offer an additional layer of security over our communications. It can perform

  • Blacklisting user agents, IP addresses, countries, domains and users.
  • Whitelisting user agents, IP addresses, countries, domains and users.
  • Blacklist of destinations where the called number is not allowed.
  • SQL injection attacks prevention.

Digest Authetication

Digest is a cryptographic function based on symmetrical encryption.

Sample kamailio exmaple with Auth https://github.com/altanai/kamailioexamples/blob/5fb6c6d0bb7416b3698e657612f016e70145a638/simple%20relay%20with%20flags/kamailio_relay_with_auth.cfg

Read more


SIPp UAC / UAS on TLS to generate traffic to check secruity of Kamailio SIP server

sipp is a powerful traffic generate for SIP applications and is widely used to test call flow routing applications in white box envrionmenet as well as stress or load testing. Read more about sipp https://telecom.altanai.com/2018/02/01/sipp/

General syntax is

sipp -sn uas -p 5060 -t l1 -tls_key key.pem  -tls_cert cert.pem  -i

More on compiling sipp from source to include ssl behavious and self generate certificates for tls can be read from https://github.com/altanai/kamailioexamples/tree/master/sipp

Ref :

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.