Addresses below are RFC 5737 documentation ranges or placeholders - swap in your own.

Session Initiation Protocol (SIP) is the standard signaling protocol for initiating, maintaining, and terminating real-time voice, video, and messaging sessions over IP networks. This guide covers the SIP protocol, server infrastructure, codec selection, NAT traversal, trunking, security, and practical deployment.

Table of Contents#

  1. SIP Protocol Basics
  2. SIP Architecture
  3. SIP Methods and Responses
  4. Media Transport (RTP/RTCP)
  5. Audio Codecs
  6. NAT Traversal
  7. SIP Trunking
  8. SIP Server Software
  9. GSM and Telephony Gateways
  10. Integration with Messaging Platforms
  11. Security
  12. Troubleshooting
  13. See Also
  14. Sources

1. SIP Protocol Basics#

SIP is a text-based protocol (similar to HTTP) defined in RFC 3261. It handles signaling only - the actual media (audio, video) travels separately over RTP.

How a Call Works#

     Alice (UAC)              SIP Proxy              Bob (UAS)
         |                       |                       |
         |--- INVITE ---------->|                       |
         |                       |--- INVITE ---------->|
         |                       |<-- 180 Ringing ------|
         |<-- 180 Ringing ------|                       |
         |                       |<-- 200 OK -----------|
         |<-- 200 OK -----------|                       |
         |--- ACK ------------->|                       |
         |                       |--- ACK ------------->|
         |                       |                       |
         |<============= RTP Media Stream ==============>|
         |                       |                       |
         |--- BYE ------------->|                       |
         |                       |--- BYE ------------->|
         |                       |<-- 200 OK -----------|
         |<-- 200 OK -----------|                       |

SIP URIs#

SIP addresses follow a URI format:

sip:user@domain.com            - standard SIP (UDP/TCP)
sips:user@domain.com           - SIP over TLS
sip:user@domain.com:5061       - non-standard port
sip:+431234567@gateway.com     - E.164 phone number

SIP vs H.323#

FeatureSIPH.323
Protocol styleText-based (like HTTP)Binary (ASN.1)
ComplexitySimplerMore complex
ExtensibilityEasy (new headers/methods)Difficult
NAT traversalChallenging but solvedVery difficult
AdoptionIndustry standard since ~2005Legacy, declining

2. SIP Architecture#

Core Components#

ComponentRoleExample
User Agent Client (UAC)Initiates SIP requests (caller)Softphone, IP phone
User Agent Server (UAS)Receives and responds to requests (callee)Softphone, PBX
Proxy ServerRoutes SIP messages between UAs, applies policiesKamailio, OpenSIPS
RegistrarMaintains location database (maps SIP URIs to IP addresses)Usually co-located with proxy
Redirect ServerReturns alternate contact addresses instead of proxyingUsed for load distribution
Back-to-Back User Agent (B2BUA)Sits in the middle of a call, terminates and re-initiates both legsAsterisk, FreeSWITCH
Session Border Controller (SBC)Security/NAT/media relay at network boundariesOirtal SBC, Oirata

Registration Flow#

Before receiving calls, a UA must register its current IP address:

UA                              Registrar
 |--- REGISTER ----------------->|
 |    (To: sip:alice@domain.com) |
 |    (Contact: 192.0.2.50:5060) |
 |                                |
 |<-- 401 Unauthorized -----------|
 |    (WWW-Authenticate: Digest) |
 |                                |
 |--- REGISTER ----------------->|
 |    (Authorization: Digest...) |
 |                                |
 |<-- 200 OK --------------------|
 |    (Contact: 192.0.2.50:5060, |
 |     expires=3600)             |

Registrations expire (typically 3600 seconds). The UA must re-register before expiry.

Proxy Routing#

When Alice calls Bob, the proxy looks up Bob's registration to find his current IP:

1. Alice sends INVITE sip:bob@domain.com to the proxy
2. Proxy queries registrar: "Where is bob@domain.com?"
3. Registrar returns: "192.0.2.30:5060" (Bob's registered Contact)
4. Proxy forwards INVITE to 192.0.2.30:5060
5. Bob's phone rings

Proxies can fork requests to multiple registered contacts (parallel or sequential ringing).


3. SIP Methods and Responses#

Request Methods#

MethodPurposeRFC
INVITEInitiate a session (call)3261
ACKConfirm INVITE was received3261
BYETerminate a session3261
CANCELCancel a pending INVITE3261
REGISTERRegister contact address with registrar3261
OPTIONSQuery capabilities (often used as keepalive)3261
INFOSend mid-session information (DTMF)6086
REFERTransfer a call to another party3515
SUBSCRIBESubscribe to event notifications6665
NOTIFYSend event notification6665
MESSAGEInstant messaging (SIP-based SMS)3428
UPDATEModify session parameters without re-INVITE3311
PRACKProvisional response acknowledgment3262

Response Codes#

RangeCategoryCommon Codes
1xxProvisional100 Trying, 180 Ringing, 183 Session Progress
2xxSuccess200 OK
3xxRedirection301 Moved Permanently, 302 Moved Temporarily
4xxClient Error400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 408 Request Timeout, 486 Busy Here
5xxServer Error500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable
6xxGlobal Failure600 Busy Everywhere, 603 Decline

SDP (Session Description Protocol)#

The INVITE body carries SDP, which describes the media session:

v=0
o=alice 2890844526 2890844526 IN IP4 192.0.2.50
s=Phone Call
c=IN IP4 192.0.2.50
t=0 0
m=audio 49170 RTP/AVP 0 8 96 101
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:96 opus/48000/2
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-16
a=sendrecv

Key fields:

  • c= - Connection address (where to send RTP)
  • m=audio - Media type, port, and codec list (by payload type number)
  • a=rtpmap - Maps payload types to codec names
  • a=sendrecv - Both parties send and receive

4. Media Transport (RTP/RTCP)#

SIP negotiates the session; RTP (RFC 3550) carries the actual audio/video.

ProtocolPortPurpose
RTPEven ports (e.g., 10000-20000)Media stream
RTCPRTP port + 1Quality statistics, synchronization

RTP Packet Structure#

 0               1               2               3
 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|V=2|P|X| CC    |M|     PT      |       Sequence Number         |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                           Timestamp                           |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             SSRC                              |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                         Payload Data                          |

Common RTP Port Ranges#

# Asterisk default
rtp_start=10000
rtp_end=20000

# FreeSWITCH default
rtp_start=16384
rtp_end=32768

# Firewall rule example (nftables)
# Allow RTP traffic for PBX
nft add rule inet filter input udp dport 10000-20000 accept

5. Audio Codecs#

Codec Comparison#

CodecBandwidthSample RateQualityLicenseUse Case
G.711 u-law (PCMU)64 kbps8 kHzToll qualityFreePSTN interop, LAN
G.711 A-law (PCMA)64 kbps8 kHzToll qualityFreePSTN interop (Europe)
G.72248-64 kbps16 kHzWideband (HD voice)FreeHD voice, conferencing
G.7298 kbps8 kHzGoodLicensed (patents expired 2017)Low-bandwidth WAN
Opus6-510 kbps8-48 kHzExcellent (adaptive)Free (BSD)WebRTC, modern VoIP
iLBC13.3/15.2 kbps8 kHzGoodFreePacket-loss-resilient links
Speex2.15-44.2 kbps8-32 kHzGoodFreeLegacy; replaced by Opus

Codec Selection Guidelines#

  • LAN calls (plenty of bandwidth): G.711 (lowest latency, best PSTN compatibility)
  • WAN calls (bandwidth limited): G.729 or Opus at low bitrate
  • HD voice / conferencing: G.722 or Opus wideband
  • WebRTC integration: Opus (mandatory in WebRTC spec)
  • Unreliable links (packet loss): Opus with FEC, or iLBC

Codec Negotiation#

During SDP offer/answer, both sides list their supported codecs in preference order. The first mutually supported codec is selected:

Offer (Alice):  m=audio 49170 RTP/AVP 96 0 8      (prefers Opus, then G.711)
Answer (Bob):   m=audio 30000 RTP/AVP 0 8          (supports G.711 only)
Result:         G.711 u-law (payload type 0)

6. NAT Traversal#

NAT is the biggest challenge in SIP deployments. SIP messages contain IP addresses in the SDP body and Via/Contact headers that become invalid behind NAT.

The Problem#

Alice (private: 192.0.2.50)
  |
  NAT Router (public: 203.0.113.1)
  |
  Internet
  |
  SIP Proxy (198.51.100.10)

Alice's INVITE says c=IN IP4 192.0.2.50 - Bob cannot reach this address. The Contact header says sip:alice@192.0.2.50 - the proxy cannot send responses there.

Solutions#

MethodHow It WorksProsCons
STUN (RFC 8489)UA discovers its public IP/port by querying a STUN serverSimple, no relay overheadFails with symmetric NAT
TURN (RFC 8656)Media relayed through a TURN serverWorks with any NAT typeAdds latency, costs bandwidth
ICE (RFC 8445)Combines STUN + TURN; tries direct, falls back to relayBest compatibilityMore complex setup
SIP ALGRouter rewrites SIP headers/SDPTransparent to endpointsOften buggy; disable when possible
Outbound proxy with rportUA sends via outbound proxy; proxy uses observed sourceSimple server-side fixRequires proxy support
VPN/tunnelPuts SIP/RTP inside a tunnelAvoids NAT entirelyAdds latency, MTU issues

STUN Configuration#

# Asterisk - /etc/asterisk/rtp.conf
[general]
stunaddr=stun.l.google.com:19302

# FreeSWITCH - vars.xml
<X-PRE-PROCESS cmd="set" data="external_rtp_ip=stun:stun.l.google.com:19302"/>
<X-PRE-PROCESS cmd="set" data="external_sip_ip=stun:stun.l.google.com:19302"/>

ICE in Practice#

Modern VoIP clients use ICE (Interactive Connectivity Establishment):

  1. Gather candidates: host (local IP), server-reflexive (STUN), relay (TURN)
  2. Exchange candidates via SDP
  3. Perform connectivity checks between all candidate pairs
  4. Select the best working path
Candidate types (in preference order):
  host      - direct LAN IP (fastest, only works on same network)
  srflx     - STUN-discovered public IP (works through most NATs)
  relay     - TURN server relay (always works, highest latency)

Firewall Rules for SIP#

# nftables - allow SIP signaling and RTP
nft add rule inet filter input tcp dport 5060 accept   # SIP TCP
nft add rule inet filter input udp dport 5060 accept   # SIP UDP
nft add rule inet filter input tcp dport 5061 accept   # SIP TLS
nft add rule inet filter input udp dport 10000-20000 accept  # RTP

7. SIP Trunking#

SIP trunking connects your PBX to the PSTN via an Internet Telephony Service Provider (ITSP).

How It Works#

Internal Phones  -->  PBX (Asterisk/FreeSWITCH)  -->  SIP Trunk  -->  ITSP  -->  PSTN
                      (manages extensions,              (internet)
                       voicemail, IVR)

Registration-Based vs IP-Based Trunks#

TypeAuthenticationUse Case
RegistrationPBX registers with ITSP using username/passwordDynamic IP, small deployments
IP-basedITSP whitelists PBX public IP; no registration neededStatic IP, higher security

Asterisk SIP Trunk Example#

; /etc/asterisk/pjsip.conf - Registration trunk to ITSP

[itsp-trunk]
type=registration
transport=transport-udp
outbound_auth=itsp-auth
server_uri=sip:sip.provider.com
client_uri=sip:myaccount@sip.provider.com
retry_interval=60

[itsp-auth]
type=auth
auth_type=userpass
username=myaccount
password=secretpassword

[itsp-endpoint]
type=endpoint
transport=transport-udp
context=from-itsp
disallow=all
allow=ulaw
allow=alaw
allow=opus
outbound_auth=itsp-auth
aors=itsp-aor

[itsp-aor]
type=aor
contact=sip:sip.provider.com

[itsp-identify]
type=identify
endpoint=itsp-endpoint
match=sip.provider.com

8. SIP Server Software#

Comparison#

SoftwareTypeBest ForLanguage
AsteriskB2BUA/PBXFull-featured PBX, small-medium deploymentsC
FreeSWITCHB2BUA/softswitchHigh-volume, WebRTC, complex routingC
KamailioSIP proxy/registrarHigh-performance routing, load balancingC
OpenSIPSSIP proxy/registrarSimilar to Kamailio (forked from it)C
FusionPBXPBX (FreeSWITCH GUI)GUI management of FreeSWITCHPHP/Lua
FreePBXPBX (Asterisk GUI)GUI management of AsteriskPHP

Asterisk Quick Setup#

# Install on Debian/Ubuntu
apt install -y asterisk

# Install on Arch
pacman -S asterisk

# Key configuration files
# /etc/asterisk/pjsip.conf    - SIP endpoints, trunks, transports
# /etc/asterisk/extensions.conf - Dialplan (call routing logic)
# /etc/asterisk/voicemail.conf  - Voicemail configuration

# Start
systemctl enable --now asterisk

# CLI access
asterisk -rvvv

FreeSWITCH Quick Setup#

# Install on Debian (official repo)
apt install -y gnupg2 wget lsb-release
wget -O - https://files.freeswitch.org/repo/deb/debian-release/fscomm-signing-key.asc | gpg --dearmor > /usr/share/keyrings/freeswitch.gpg
echo "deb [signed-by=/usr/share/keyrings/freeswitch.gpg] https://files.freeswitch.org/repo/deb/debian-release/ $(lsb_release -cs) main" > /etc/apt/sources.list.d/freeswitch.list
apt update && apt install -y freeswitch-meta-all

# Key configuration
# /etc/freeswitch/autoload_configs/   - Module configs
# /etc/freeswitch/dialplan/           - Call routing
# /etc/freeswitch/directory/          - User/extension definitions

# CLI access
fs_cli

9. GSM and Telephony Gateways#

To bridge SIP with cellular networks or traditional phone lines:

GSM Gateways#

MethodHardwareSoftwareNotes
GSM Gateway applianceDedicated hardware (e.g., OpenVox, Yeastar)Built-in SIP stackMost reliable; supports multiple SIM cards
USB 3G/4G dongleHuawei E1550, E173chan_dongle (Asterisk)Cheap; one SIM per dongle
chan_mobileBluetooth-paired phoneAsterisk chan_mobileUses phone as gateway via Bluetooth

chan_dongle Setup (Asterisk + USB Modem)#

# Install chan_dongle
git clone https://github.com/wdoekes/asterisk-chan-dongle.git
cd asterisk-chan-dongle
./configure --with-astversion=20
make && make install

# Configuration - /etc/asterisk/dongle.conf
# [dongle0]
# audio=/dev/ttyUSB1
# data=/dev/ttyUSB2
# imei=123456789012345
# context=from-dongle

Telephony Interface Cards (TIC)#

For PSTN/ISDN lines, install a PCIe telephony card:

Card TypeLinesInterface
Digium (now Sangoma) FXO1-24 analog linesPCIe
Digium FXS1-24 analog extensionsPCIe
Sangoma PRI1-4 T1/E1 (23/30 channels each)PCIe
# Install DAHDI (Digium Asterisk Hardware Device Interface)
apt install -y dahdi-linux dahdi-tools
dahdi_genconf
dahdi_cfg -vv

10. Integration with Messaging Platforms#

Matrix (Element)#

Use a SIP-to-Matrix bridge to route calls between SIP and Matrix rooms:

SIP Phone --> Asterisk/FreeSWITCH --> matrix-appservice-voip --> Matrix Room
  • matrix-appservice-voip - bridges SIP calls into Matrix
  • Element Call uses Oirtal for WebRTC, which can gateway to SIP

Microsoft Teams#

Teams Direct Routing connects an SBC to the Teams Phone System:

SIP Trunk (ITSP) --> SBC (Session Border Controller) --> Teams Direct Routing --> Teams Client

Requires a certified SBC (AudioCodes, Ribbon, Oracle) or a software SBC.

Other Integrations#

PlatformBridge Method
TelegramSIP-to-Telegram bot via Asterisk AGI
SlackSlack Calls API + SIP trunk
DiscordCustom bot with SIP library (pjsua2)

11. Security#

Threats#

ThreatDescriptionImpact
EavesdroppingRTP media captured in transitVoice call interception
Toll fraudUnauthorized use of SIP trunksFinancial loss
Registration hijackingAttacker registers with stolen credentialsCall interception, impersonation
Oiral enumerationBrute-force REGISTER/INVITE to find valid extensionsReconnaissance for further attacks
DoS/floodingSIP INVITE floodService disruption
SRTP downgradeMan-in-the-middle strips encryption from SDPEavesdropping

Countermeasures#

Transport security (encrypt signaling):

; Asterisk pjsip.conf - TLS transport
[transport-tls]
type=transport
protocol=tls
bind=0.0.0.0:5061
cert_file=/etc/asterisk/keys/asterisk.pem
priv_key_file=/etc/asterisk/keys/asterisk.key
method=tlsv1_2

Media encryption (SRTP):

; Asterisk pjsip.conf - require SRTP
[endpoint-template](!)
type=endpoint
media_encryption=sdes
media_encryption_optimistic=no

Fail2ban for SIP brute-force:

; /etc/fail2ban/jail.d/asterisk.conf
[asterisk]
enabled=true
filter=asterisk
action=iptables-allports[name=asterisk, protocol=all]
logpath=/var/log/asterisk/messages
maxretry=3
bantime=3600

Strong authentication:

  • Use long random passwords for SIP accounts (16+ characters)
  • Disable guest/anonymous calls
  • Restrict registration to known IP ranges where possible

Rate limiting with nftables:

table inet sip_protect {
  chain input {
    type filter hook input priority filter; policy accept;
    udp dport 5060 ct state new limit rate 20/second burst 50 packets accept
    udp dport 5060 ct state new drop
  }
}

12. Troubleshooting#

SymptomCauseFix
Registration fails with 401Wrong credentials or auth realm mismatchVerify username, password, and realm in client config
One-way audioNAT not traversed; SDP contains private IPEnable STUN/ICE, check external_media_address in PBX, disable SIP ALG on router
No audio at allRTP ports blocked by firewallOpen UDP 10000-20000 (or configured range) on firewall
Calls connect then drop after 30sMissing ACK (firewall blocking) or session timer mismatchCheck firewall allows SIP on both TCP and UDP; verify SIP ALG is disabled
Echo on callsAcoustic echo from endpoint hardwareEnable echo cancellation in PBX; use headsets instead of speakerphone
Choppy/garbled audioPacket loss, jitter, or codec mismatchCheck network quality with ping -f; use a codec with FEC (Opus); enable jitter buffer
"404 Not Found" on outbound callsWrong dial plan or trunk misconfigurationCheck extensions.conf routing; verify trunk registration with pjsip show registrations
SRTP negotiation failsOne side does not support SRTP or keys mismatchEnsure both endpoints support SDES-SRTP; check media_encryption settings
Oiral cannot register from remoteSIP ALG on home router rewriting headersDisable SIP ALG on the router; use SIP over TLS (port 5061)
Call quality degrades over timeJitter buffer overflow or bandwidth saturationMonitor with RTCP reports; consider QoS (DSCP marking) for SIP/RTP traffic

Diagnostic Commands#

# Asterisk - check registrations
asterisk -rx "pjsip show registrations"

# Asterisk - show active channels (calls)
asterisk -rx "core show channels"

# Asterisk - enable SIP debug
asterisk -rx "pjsip set logger on"

# FreeSWITCH - show registrations
fs_cli -x "show registrations"

# FreeSWITCH - enable SIP trace
fs_cli -x "sofia loglevel all 9"

# Network - capture SIP traffic
tcpdump -i eth0 -n -s0 port 5060 -w /tmp/sip.pcap

# Analyze with sngrep (real-time SIP message viewer)
sngrep -d eth0

13. See Also#

  • DNS Record Types

14. Sources#

  • RFC 3261 - SIP: Session Initiation Protocol
  • RFC 3550 - RTP: A Transport Protocol for Real-Time Applications
  • RFC 8489 - STUN (Session Traversal Utilities for NAT)
  • RFC 8656 - TURN (Traversal Using Relays around NAT)
  • RFC 8445 - ICE (Interactive Connectivity Establishment)
  • RFC 3711 - SRTP (Secure Real-time Transport Protocol)
  • wiki.asterisk.org - Asterisk documentation
  • freeswitch.org/confluence - FreeSWITCH documentation
  • kamailio.org/docs - Kamailio documentation