Fix Kamailio NAT Routing With add_contact_alias and
calricon / field note
Calling fix_nated_contact() in Kamailio mutates the SIP Contact
Fix Kamailio NAT Routing With add_contact_alias and handle_ruri_alias
In production Kamailio SIP proxy deployments, calls behind symmetric NAT frequently establish cleanly on the initial INVITE and 200 OK, only to fail 32 seconds later when the ACK never reaches the callee or an in-dialog BYE or re-INVITE is rejected with 404 Not Found or 403 Forbidden. On TCP and TLS trunks, Kamailio may also open redundant outbound socket attempts toward unreachable private IP addresses instead of reusing the active client connection.
The root cause is calling fix_nated_contact() on requests and replies from NATed User Agents (UAs). Because fix_nated_contact() overwrites the host and port inside the SIP Contact URI with the observed public source socket, it violates RFC 3261 dialog-target rules. Strict SIP clients, B2BUAs such as Asterisk or FreeSWITCH, and TLS endpoints reject subsequent in-dialog requests whose Request-URI no longer matches the Contact URI they originally advertised.
Problem Diagnosis & Root Cause Architecture
To route in-dialog SIP requests through NAT without breaking endpoint state, Kamailio must separate the logical dialog target from the physical network destination:
- Destructive Contact Rewriting (
fix_nated_contact()): Replaces the original private IP and port in theContactline (for example,https://www.google.com/url?q=https://www.google.com/url?q%3Dhttp://sip:1001@192.168.1.50:5060%26source%3Dgmail%26ust%3D1795448387543000%26sa%3DE&source=gmail&ust=1795449092408000&sa=E) with the NAT router's public IP and ephemeral port. Downstream B2BUAs store this mutated URI as the remote target, and strict UAs drop incomingACKorBYEpackets because the Request-URI does not match their local binding. - Standards-Compliant Aliasing (
add_contact_alias()): Preserves the client's originalContacthost and port intact and appends an;alias=ip~port~transportURI parameter containing the observed public source IP, port, and transport protocol. - Destination URI Resolution (
handle_ruri_alias()): Inspects incoming in-dialog requests (ACK,BYE,re-INVITE) for an;alias=parameter in the Request-URI, strips the parameter so the Request-URI matches the UA's originalContact, and populates Kamailio's internal destination URI ($du) so the packet routes over the exact NATed socket or existing TCP/TLS connection.
Architectural Reality: Never alter the host or port of a SIPContactURI when a standards-compliant alternative exists. Appending;alias=viaadd_contact_alias()keeps the dialog target intact for strict UAs while giving Kamailio full visibility into the NATed transport socket via$du.
Why Standard Implementations Fail
1. Strict User Agents Reject Mutated Request-URIs
Enterprise SIP phones, WebRTC gateways, and carrier SBCs validate that the Request-URI on an incoming ACK or BYE matches the Contact URI they sent in their INVITE or 200 OK. When fix_nated_contact() rewrites that URI, the UA treats the request as misrouted, causing 32-second call drops due to unacknowledged 200 OK timers.
2. Broken TCP and TLS Connection Reuse
When a SIP client registers or initiates a call over TLS or TCP from behind NAT, it cannot accept inbound connections on its public NAT port. If fix_nated_contact() strips or alters the original URI without preserving transport metadata cleanly, or if handle_ruri_alias() is omitted during loose routing, Kamailio attempts a fresh outbound TCP/TLS handshake to a blocked port instead of reusing the existing persistent socket.
3. Misusing Contact Aliasing on Local Registrars
Applying fix_nated_contact() or set_contact_alias() indiscriminately to REGISTER requests on a local Kamailio registrar can cause certain SIP clients to echo stale ;alias= parameters back in later 200 OK replies after a network port change. Local registrars should use fix_nated_register() for REGISTER messages and reserve add_contact_alias() for dialog-forming requests and replies.
Step-by-Step Resolution Playbook
Step 1: Verify NAT Detection and Module Parameters
Ensure the nathelper module is loaded in kamailio.cfg with an explicit received_avp for REGISTER handling and optional keepalive pinging for UDP endpoints:
loadmodule "nathelper.so"
modparam("nathelper", "natping_interval", 30)
modparam("nathelper", "ping_nated_only", 1)
modparam("nathelper", "sipping_bflag", FLB_NATSIPPING)
modparam("nathelper", "sipping_from", "sip:pinger@proxy.example")
modparam("registrar|nathelper", "received_avp", "$avp(RECEIVED)")Step 2: Replace fix_nated_contact() in the NATDETECT Route
Update your NATDETECT route so REGISTER requests continue using fix_nated_register() while all other NATed requests (such as initial INVITE and SUBSCRIBE) call add_contact_alias() instead of fix_nated_contact():
route[NATDETECT] {
force_rport();
if (nat_uac_test("19")) {
if (is_method("REGISTER")) {
fix_nated_register();
} else {
if (is_first_hop()) {
set_contact_alias();
}
}
setflag(FLT_NATS);
}
return;
}Using is_first_hop() ensures Kamailio only appends the alias when it is the edge proxy directly facing the NATed UA, avoiding duplicate aliases when requests traverse internal proxies.
Step 3: Resolve Aliases in the WITHINDLG Route
Inside your in-dialog routing block (WITHINDLG), invoke handle_ruri_alias() before t_relay() when loose_route() succeeds. This extracts the ;alias= parameter into $du and restores the clean Request-URI:
route[WITHINDLG] {
if (!has_totag()) return;
if (loose_route()) {
route(DLGURI);
if (is_method("BYE")) {
setflag(FLT_ACC);
setflag(FLT_ACCFAILED);
} else if (is_method("ACK")) {
route(NATMANAGE);
}
route(RELAY);
exit;
}
sl_send_reply("404", "Not here");
exit;
}
route[DLGURI] {
if (!isdsturiset()) {
handle_ruri_alias();
}
return;
}Step 4: Apply Contact Aliasing to NATed Replies
When a NATed callee answers an incoming call with 200 OK, its Contact URI also contains a private IP. Update your NATMANAGE route (called from both request_route and onreply_route) to call add_contact_alias() on replies when the transaction originated behind NAT:
route[NATMANAGE] {
if (is_request()) {
if (has_totag()) {
if (check_route_param("nat=yes")) {
setbflag(FLB_NATB);
}
}
}
if (!(isflagset(FLT_NATS) || isbflagset(FLB_NATB))) return;
if (is_request()) {
if (!has_totag()) {
if (t_is_branch_route()) {
add_rr_param(";nat=yes");
}
}
}
if (is_reply()) {
if (isbflagset(FLB_NATB)) {
if (is_first_hop()) {
set_contact_alias();
}
}
}
return;
}Step 5: Validate Configuration Syntax and Reload Kamailio
Test the updated kamailio.cfg before reloading production workers:
kamailio -c -f /etc/kamailio/kamailio.cfg
systemctl reload kamailioStep 6: Verify Alias Injection and In-Dialog Routing Live
Trace a live call across NAT using sngrep or tshark to verify that the outbound Contact preserves the client's original host while carrying ;alias=, and that the subsequent ACK and BYE arrive at the public NAT socket with a clean Request-URI:
sngrep -d any port 5060
kamcmd tm.statsConfirm that 200 OK retransmissions drop to zero and in-dialog ACK and BYE transactions complete with 200 OK on both UDP and TCP/TLS endpoints.
Experiencing this issue in your production systems?
Calricon conducts senior-level VoIP, SIP trunking, Asterisk, and cloud infrastructure audits. We review your live configs, identify packet drops or contention bottlenecks, and provide exact remediation runbooks.