Intermittent TLS inbound failure behind HAProxy, Kamailio opens new TCP to HAProxy ephemeral port and gets RST
Hello, We see an intermittent issue in our on premise deployments with Kamailio behind HAProxy. After several hours of idle time, some mobile clients cannot receive inbound calls, although they remain registered and can place outbound calls. Topology: Mobile Client → Internet → Customer Firewall → HAProxy → Kamailio Transport is SIP over TLS. HAProxy works in TCP mode and terminates nothing. It forwards TLS to Kamailio. Client behavior • REGISTER with Expires 600 seconds • Re-register every 7 minutes • TLS connection from client to HAProxy stays up • Outbound calls from client work • During the failure window, client continues to send REGISTER and receives 200 OK Failure scenario • Several devices placed idle overnight • In the morning, some cannot receive inbound calls • Kamailio tries to send INVITE to the contact • Kamailio opens a new TCP connection to HAProxy IP and an ephemeral port • HAProxy responds with RST Example log from Kamailio: INFO: request_route: method [INVITE] from [sip:UE_2@domain.com] to [sip:UE_1@domain.com] ERROR: tcpconn_1st_send(): connect 10.233.124.50:40398 failed (RST) Connection refused ERROR: tcpconn_1st_send(): 10.233.124.50:40398: connect & send failed WARNING: t_send_branch(): sending request on branch 0 failed PCAP confirms: • Kamailio sends SYN to 10.233.124.50:40398 • HAProxy replies RST, ACK Important observations 1. usrloc contact host and port match the peer address seen in tls.list (src_ip + src_port). 2. At the time of failure, the client is still able to send REGISTER and get 200 OK. 3. If the same client initiates a call, the call is established successfully. It looks like Kamailio sometimes fails to match the stored contact to an existing TLS connection and attempts to open a new TCP connection to the Contact host:port. In our case, Contact host resolves to HAProxy IP and port. Questions 1. Under which conditions does Kamailio decide to open a new TCP connection to the Contact instead of reusing an existing TLS connection? 2. If connection ID lookup fails, is fallback to active connect the expected behavior? Environment • Kamailio versions: 5.8.5, 6.0.5 (reproduced on both) • HAProxy: TCP mode, no TLS termination • Clients uses TLS only, no UDP Kamailio relevant configuration: tcp_connection_lifetime=605 modparam("registrar", "max_expires", 600) modparam("registrar", "use_path", 1) modparam("usrloc", "handle_lost_tcp", 1) modparam("usrloc", "close_expired_tcp", 1) HAProxy configuration: frontend client-kamailio-sip mode tcp option tcpka timeout client 600 default_backend server-kamailio-sip backend server-kamailio-sip from haproxytech mode tcp option tcpka timeout connect 30s timeout server 600s timeout tunnel 600s Any guidance on correct architectural pattern or configuration for SIP TLS behind HAProxy would be appreciated. Thank you. Joey.
Questions 1. Under which conditions does Kamailio decide to open a new TCP connection to the Contact instead of reusing an existing TLS connection? 2. If connection ID lookup fails, is fallback to active connect the expected behavior? ``` route[LOCATION] { if (!lookup("location")) { $var(rc) = $rc; t_newtran(); switch ($var(rc)) { case -1: case -3: send_reply("404", "Not Found"); exit; case -2: send_reply("405", "Method Not Allowed"); exit; } } set_forward_no_connect(); # here you are route(RELAY); exit; } ``` But this might not help you. The key point is why the TCP connection between HAProxy and Kamailio gets disconnected—who sent the TCP disconnect. Han
I did a test. kamcmd ul.lookup location 1000@abc.com { AoR: 1000 Contacts: { Contact: { Address: sip:1000@192.168.42.35:7894;rinstance=d11ff2e6f5be86d5;transport=TCP Expires: 1631 Q: -1 Call-ID: NGMyMmZiMzZhOTZmZDEwOTUyNGI2ODU0M2I5YTA3NzE. CSeq: 1 User-Agent: eyeBeam release 1011d stamp 40820 Received: sip:192.168.42.100:37194;transport=tcp Path: [not set] State: CS_NEW Flags: 0 CFlags: 64 Socket: tcp:192.168.42.100:5060 Methods: 5087 Ruid: uloc-698ec22d-d75-1 Instance: [not set] Reg-Id: 0 Server-Id: 0 Tcpconn-Id: 8 Keepalive: 1 Last-Keepalive: 1770964020 KA-Roundtrip: 0 Last-Modified: 1770964020 } } } Receiveds is 'sip:192.168.42.100:37194;transport=tcp' Next run : netstat -ant | grep 192.168.42.100:37194 tcp 0 0 192.168.42.100:37194 192.168.42.100:5060 ESTABLISHED tcp 0 0 192.168.42.100:5060 192.168.42.100:37194 ESTABLISHED
Hi Han, Thanks for your reply. Following up with additional findings from debugging. I've identified what's happening but not why, and I'm hoping someone can help explain the root cause. I placed 10 mobile devices on a table, all registered through the same setup, and left them idle for a few hours. After that period, 1 out of the 10 could no longer receive inbound calls, while still being registered and able to place outbound calls. After enabling DEBUG logs, I compared _tcpconn_find() behavior: For 9 out of 10 connections: _tcpconn_find(): found connection by peer address (id: X) appears consistently. INVITEs to these users succeed. For connection 137 (the failing one): zero occurrences of "found connection by peer address". INVITEs fail with tcp_send(): no open tcp connection found, opening new one, followed by connect failed (RST) Connection refused. At the same time, I checked and the connection is alive, healthy (CONN_OK), timeout is refreshing, and the client continues to re-REGISTER with incrementing CSeq over this connection. The kamcmd core.tcp_list, tls.list, and ul.dump output for this connection looks identical before and after the problem appears. The connection's src_port: 48996 and Tcpconn-Id: 137 remain unchanged. Everything looks normal from the outside. The issue is that the peer-address alias entry (the mapping from 10.42.106.41:48996 to connection ID 137 in the internal TCP alias hash table) is missing for this connection, while it exists for all others. What I don't understand (root cause) is why does this specific connection lose its peer-address alias (or never get one) while the other 9 connections are fine? Under what conditions are TCP connection aliases created and removed in the core? Is there a known scenario where an alias can be lost while the connection itself remains active? Could there be a hash collision or race condition in the alias hash table that causes some entries to be evicted? Workaround I'm testing: I found that lookup() in the registrar module already sets msg->otcpid to the contact's tcpconn_id. The TM module will use dst.id = msg->otcpid in t_fwd.c but only if the FL_USE_OTCPID flag is set on the message. When dst.id is set, tcp_send() finds the connection by ID directly, bypassing the alias hash table entirely. Adding tcp_set_otcpid_flag(1) from the tcpops module after lookup() completes this chain. I'm checking now if this works around the problem by skipping the alias lookup, but it doesn't explain why the alias goes missing in the first place. Any insights would be greatly appreciated. Thanks, Joey
Hi again, Following up with root cause analysis from a second reproduction (10 devices idle for ~24 hours, single Kamailio instance behind HAProxy). Kamailio listens on two TLS ports: 5061 (SIP) and 50443 (WebSocket) HAProxy proxies SIP traffic to 5061 and runs HTTP health checks (GET /health) against 50443 10 mobile clients registered via SIP/TLS through HAProxy Root cause The problem is caused by HAProxy's HTTP health checks to port 50443 colliding with existing SIP client connections on port 5061 in Kamailio's internal TCP alias hash table. The alias hash table is keyed on (source_ip, source_port) only. it does not consider the destination port. When HAProxy opens a health check connection from the same ephemeral source port that's already in use for a SIP client connection, the two connections map to the same alias bucket. The health check connection's alias overwrites the SIP connection's alias. When the health check completes and the connection is destroyed, the alias entry is deleted, leaving the original SIP connection permanently unreachable by peer address. This is valid at the TCP level because the full 4-tuple differs (same source, different destination port), but Kamailio's alias lookup only considers the source side. Proof from logs: connection 5 (port 37190) Step 0: SIP client connection established at startup: tcpconn_new(): on port 37190, type 3, socket 81 tcpconn_add(): hashes: 2726:2132:2998, 5 Connection 5 created: 10.42.106.41:37190 → 10.42.106.25:5061. Alias added to hash bucket 2132. Step 1: Alias works normally for hours: _tcpconn_find(): found connection by peer address (id: 5) In-dialog requests look up 10.42.106.41:37190, find connection 5 via alias. Delivered successfully. Step 2: HAProxy health check arrives from the same source port: tcpconn_new(): on port 37190, type 3, socket 81 tcpconn_add(): hashes: 2726:2132:3285, 384 send2child(): ... for activity on [tls:10.42.106.25:50443] tls_accept: new connection from 10.42.106.41:37190 using TLSv1.3 New incoming connection 384: 10.42.106.41:37190 → 10.42.106.25:50443. Same alias hash bucket (2132). Connection 5's alias is overwritten. Step 3: It's a health check, immediately closed: parse_msg(): method: <GET> parse_msg(): uri: </health> xhttp_handler(): new fake msg created: <GET /health HTTP/1.1 Via: SIP/2.0/TLS 10.42.106.41:37190 connection: close> ... tls_h_tcpconn_close_f(): Closing SSL connection handle_io(): removing from list ... ([10.42.106.41]:37190 -> [10.42.106.41]:50443) Connection 384 is destroyed. Alias entry for 10.42.106.41:37190 is deleted from bucket 2132. Connection 5's alias is gone permanently. Step 4: Next request to this user fails: tcpconn_1st_send(): connect 10.42.106.41:37190 failed (RST) Connection refused Kamailio can't find connection 5 by peer address. Opens a new outgoing connection to 10.42.106.41:37190, which HAProxy rejects with RST. Questions 1. Is the alias hash table intentionally keyed on (source_ip, source_port) only, without considering the destination port? If so, is there a reason the destination side is excluded? 2. When a new incoming connection is added to a hash bucket that already contains an alias for the same (source_ip, source_port), does Kamailio replace the existing alias entry? The logs suggest it does, but I'd like to confirm. 3. Would it make sense to include the destination port (or the full 4-tuple) in the alias key to prevent this class of collision? 4. Regardless of the alias issue, does it make sense to keep tcp_set_otcpid_flag(1) after lookup() as a general best practice for deployments behind a TCP load balancer? It seems more robust to route by connection ID (which lookup() already populates via msg->otcpid) rather than relying on the alias hash table. Or are there downsides/edge cases where this flag should not be used? Thanks, Joey
Hello, have you set this core parameter: - https://www.kamailio.org/wikidocs/cookbooks/devel/core/#tcp_connection_match Cheers, Daniel On 17.02.26 14:42, Joey via sr-users wrote:
Hi again,
Following up with root cause analysis from a second reproduction (10 devices idle for ~24 hours, single Kamailio instance behind HAProxy). Kamailio listens on two TLS ports: 5061 (SIP) and 50443 (WebSocket) HAProxy proxies SIP traffic to 5061 and runs HTTP health checks (GET /health) against 50443 10 mobile clients registered via SIP/TLS through HAProxy
Root cause The problem is caused by HAProxy's HTTP health checks to port 50443 colliding with existing SIP client connections on port 5061 in Kamailio's internal TCP alias hash table. The alias hash table is keyed on (source_ip, source_port) only. it does not consider the destination port. When HAProxy opens a health check connection from the same ephemeral source port that's already in use for a SIP client connection, the two connections map to the same alias bucket. The health check connection's alias overwrites the SIP connection's alias. When the health check completes and the connection is destroyed, the alias entry is deleted, leaving the original SIP connection permanently unreachable by peer address. This is valid at the TCP level because the full 4-tuple differs (same source, different destination port), but Kamailio's alias lookup only considers the source side.
Proof from logs: connection 5 (port 37190) Step 0: SIP client connection established at startup: tcpconn_new(): on port 37190, type 3, socket 81 tcpconn_add(): hashes: 2726:2132:2998, 5 Connection 5 created: 10.42.106.41:37190 → 10.42.106.25:5061. Alias added to hash bucket 2132.
Step 1: Alias works normally for hours: _tcpconn_find(): found connection by peer address (id: 5) In-dialog requests look up 10.42.106.41:37190, find connection 5 via alias. Delivered successfully.
Step 2: HAProxy health check arrives from the same source port: tcpconn_new(): on port 37190, type 3, socket 81 tcpconn_add(): hashes: 2726:2132:3285, 384 send2child(): ... for activity on [tls:10.42.106.25:50443] tls_accept: new connection from 10.42.106.41:37190 using TLSv1.3 New incoming connection 384: 10.42.106.41:37190 → 10.42.106.25:50443. Same alias hash bucket (2132). Connection 5's alias is overwritten.
Step 3: It's a health check, immediately closed: parse_msg(): method: <GET> parse_msg(): uri: </health> xhttp_handler(): new fake msg created: <GET /health HTTP/1.1 Via: SIP/2.0/TLS 10.42.106.41:37190 connection: close> ... tls_h_tcpconn_close_f(): Closing SSL connection handle_io(): removing from list ... ([10.42.106.41]:37190 -> [10.42.106.41]:50443)
Connection 384 is destroyed. Alias entry for 10.42.106.41:37190 is deleted from bucket 2132. Connection 5's alias is gone permanently.
Step 4: Next request to this user fails: tcpconn_1st_send(): connect 10.42.106.41:37190 failed (RST) Connection refused Kamailio can't find connection 5 by peer address. Opens a new outgoing connection to 10.42.106.41:37190, which HAProxy rejects with RST.
Questions 1. Is the alias hash table intentionally keyed on (source_ip, source_port) only, without considering the destination port? If so, is there a reason the destination side is excluded?
2. When a new incoming connection is added to a hash bucket that already contains an alias for the same (source_ip, source_port), does Kamailio replace the existing alias entry? The logs suggest it does, but I'd like to confirm.
3. Would it make sense to include the destination port (or the full 4-tuple) in the alias key to prevent this class of collision?
4. Regardless of the alias issue, does it make sense to keep tcp_set_otcpid_flag(1) after lookup() as a general best practice for deployments behind a TCP load balancer? It seems more robust to route by connection ID (which lookup() already populates via msg->otcpid) rather than relying on the alias hash table. Or are there downsides/edge cases where this flag should not be used?
Thanks, Joey __________________________________________________________ Kamailio - Users Mailing List - Non Commercial Discussions -- sr-users@lists.kamailio.org To unsubscribe send an email to sr-users-leave@lists.kamailio.org Important: keep the mailing list in the recipients, do not reply only to the sender!
-- Daniel-Constantin Mierla (@ asipto.com) twitter.com/miconda -- linkedin.com/in/miconda Kamailio Consultancy, Training and Development Services -- asipto.com Kamailio World Conference, May 7-8, 2026 - Berlin, Germany -- kamailioworld.com
Hi Daniel, No but it can give it a try. Can you tell If it only changes the lookup but the alias hash still stores entries keyed on (remote_ip, remote_port) only? If so, connections would still be overwritten on entry added, and delete it when destroyed In addition, can you say if it makes sense to keep tcp_set_otcpid_flag(1) after lookup() as a general best practice for deployments behind a TCP load balancer or it should be used for different purposes? Thanks, Joey.
Hi Again Daniel, I tested with tcp_connection_match=1 set in kamailio.cfg. The alias overwrites and deletions still occur. Connections are still lost. After reviewing the source code, this is expected. tcp_connection_match=1 only affects the lookup path in tcp_send() and msg_send_buffer(). it makes tcpconn_lookup() first attempt a match including the local port. It does not change how aliases are stored or deleted. Any ideas what else can I do or try? Thanks, Joey.
Hi again, Following up with additional findings and a proposed fix. I tested with tcp_connection_match=1. The alias overwrites and deletions still occur, and connections are still lost. After reviewing the source code, this is expected. tcp_connection_match=1 only affects the lookup path in tcp_send() and msg_send_buffer(). It does not change how aliases are stored or how collisions are handled during alias creation. The root of the problem is in _tcpconn_add_alias_unsafe() in tcp_main.c. When a new connection is added via tcpconn_add(), it creates 3 aliases at increasing specificity: Alias 0: (peer_ip, peer_port, 0.0.0.0, 0) - wildcard, find any connection to this peer Alias 1: (peer_ip, peer_port, local_ip, 0) - find connection to this peer from this local IP Alias 2: (peer_ip, peer_port, local_ip, local_port) - fully specified Aliases 0 and 1 are created with l_port=0. The hash function tcp_addr_hash() includes l_port in the XOR computation, so when two connections share the same peer IP:port but differ in local port (e.g., 5061 vs 50443), their aliases 0 and 1 hash to the same bucket (because l_port=0 for both), while alias 2 hashes to different buckets. From my logs: SIP conn 5: tcpconn_add(): hashes: 2726:2132:2998, 5 (local port 5061) Health check: tcpconn_add(): hashes: 2726:2132:3285, 384 (local port 50443) Buckets 2726 and 2132 are shared. Bucket 2998 vs 3285 differ (alias 2). The collision detection in _tcpconn_add_alias_unsafe() is: if((a->parent->state != S_CONN_BAD) && (port == a->port) && ((l_port == 0) || (l_port == a->parent->rcv.dst_port)) && (ip_addr_cmp(&c->rcv.src_ip, &a->parent->rcv.src_ip)) && (is_local_ip_any || ip_addr_cmp(&a->parent->rcv.dst_ip, l_ip))) { The condition (l_port == 0) acts as a wildcard. it matches any existing connection regardless of destination port. Combined with the default new_conn_alias_flags = TCP_ALIAS_REPLACE, the health check connection's wildcard aliases replace the SIP connection's wildcard aliases. When the health check closes, the aliases are deleted, and the SIP connection becomes permanently unreachable by peer address. Proposed fix When tcp_connection_match=1 (strict matching), tighten the collision detection in _tcpconn_add_alias_unsafe() so that two connections from the same peer but to different local ports are not considered collisions: if((a->parent->state != S_CONN_BAD) && (port == a->port) && ((l_port == 0) || (l_port == a->parent->rcv.dst_port)) && (ip_addr_cmp(&c->rcv.src_ip, &a->parent->rcv.src_ip)) && (is_local_ip_any || ip_addr_cmp(&a->parent->rcv.dst_ip, l_ip)) && (tcp_connection_match != TCPCONN_MATCH_STRICT || c->rcv.dst_port == 0 || a->parent->rcv.dst_port == 0 || c->rcv.dst_port == a->parent->rcv.dst_port)) { The added condition: When tcp_connection_match=0 (default): no behavior change: the new condition is always true When tcp_connection_match=1: a collision is only detected if both connections have the same destination port (or either has dst_port=0 as a safety guard) This means the health check connection (dst_port=50443) would no longer replace the SIP connection's aliases (dst_port=5061). Both sets of aliases coexist in the same hash bucket. When the health check closes, only its own aliases are removed. The SIP connection's aliases remain intact. The change is ~3 lines in _tcpconn_add_alias_unsafe() in tcp_main.c, guarded behind the existing tcp_connection_match=1 opt-in, so default behavior is completely unchanged. I am happy to submit a PR if this approach makes sense. Any feedback or comments would be appreciated. Thanks, Joey.
participants (3)
-
13715209697@139.com -
Daniel-Constantin Mierla -
joeygo@gmail.com