The Kamailio Pike Anti-Flood Trap: Why Failover Bursts Ban
calricon / field note
When upstream carrier gateways or Session Border Controllers
The Kamailio Pike Anti-Flood Trap: Why Failover Bursts Ban Legitimate SIP Trunks
In carrier-grade telecommunications backbones, wholesale SIP termination networks, and multi-tenant cloud PBX architectures running Kamailio, deploying perimeter defense mechanisms is essential for protecting internal media servers and softswitches from distributed denial-of-service (DDoS) attacks, brute-force registration scans, and signaling floods. To mitigate volumetric attacks at the edge, telephony engineers standardly configure Kamailio's pike module in tandem with htable memory structures. The Pike module inspects incoming SIP request density per source IP address over sliding sampling intervals (configured via sampling_time_unit and reqs_density_per_unit). Under normal distributed traffic patterns, Pike silently and efficiently detects rogue scanning scripts, temporarily blocking offending IP addresses with stateless 403 Forbidden responses or immediate packet drops. However, in enterprise environments routing high-density carrier interconnects, a catastrophic false-positive failure routinely strikes: following a momentary upstream network partition, cloud zone failover, or carrier Session Border Controller (SBC) maintenance restart, thousands of queued customer calls and registrations flood Kamailio within a two-second window over a single carrier IP address. Rather than absorbing the surge, pike_check_req() misidentifies the legitimate carrier gateway as a volumetric attacker, immediately blacklisting the entire trunk IP. Thousands of incoming enterprise calls are dropped instantaneously, and upstream wholesale carriers trigger catastrophic trunk outage alarms. The root cause is the Kamailio Pike Anti-Flood Trap: an architectural routing oversight where rigid, unauthenticated sliding-window request density tracking lacks trusted peer exemptions, in-dialog awareness, and burst-tolerant pacing.
The operational failure stems from how Kamailio executes the main routing block (request_route) when incoming UDP packets arrive on network interfaces. In standard boilerplate configurations, administrators place the anti-flooding inspection block (route[ANTIFLOOD]) at the very top of request_route to reject malicious traffic with minimal CPU consumption before executing complex routing logic. When an upstream carrier SBC fails over from a primary to a secondary node, it releases hundreds of buffered SIP INVITE, ACK, and REGISTER messages in an unthrottled micro-burst. If Pike is configured with standard limits—such as thirty requests per two seconds (sampling_time_unit = 2, reqs_density_per_unit = 30)—the incoming burst from the carrier IP exceeds the density threshold within milliseconds. pike_check_req() returns a negative code, signaling that the source IP has breached the threshold. The routing script responds by inserting the carrier IP into an in-memory hash table (htable) with a multi-minute ban duration (e.g., 300 seconds) and dropping all subsequent packets. Because the anti-flood check executes before the proxy verifies whether the source IP belongs to a trusted carrier trunk, Kamailio severs communication with its primary voice partner. Furthermore, because legitimate in-flight calls attempt to send in-dialog ACK and BYE packets to tear down or acknowledge sessions, these packets are also blocked by the ban rule, stranding active channels on internal media servers and leaving call accounting records in a corrupted state.
Problem Diagnosis and Root Cause Architecture
Diagnosing Pike false-positive trunk bans requires analyzing how packet filtering, memory hash tables, and SIP dialog states interact during traffic surges:
- Unconditional Execution Before Trusted Peer Validation: Default configurations invoke
route[ANTIFLOOD]prior to querying thepermissionsmodule (allow_trusted()). Consequently, trusted wholesale carrier gateways handling tens of thousands of subscribers are evaluated using the exact same aggressive thresholds designed for single untrusted IP endpoints. - Rigid Sliding-Window Density Without Burst Tolerance: Pike calculates request density using discrete, fixed sampling units without support for burst accumulation or leaky capacity buckets. A legitimate burst of 50 calls in 500 milliseconds triggers a ban, even if the trunk averaged zero calls over the preceding ten minutes.
- Indiscriminate In-Dialog Packet Dropping: Standard anti-flood blocks do not distinguish between unauthenticated initial transactions (initial INVITE or REGISTER) and established in-dialog signaling (ACK, PRACK, BYE). Blacklisting an IP drops mid-dialog signaling, preventing calls from terminating cleanly and causing channel state bloat on downstream media proxies.
Executing generic volumetric rate limiting against carrier interconnects without trusted peer bypasses is an operational failure. When an upstream SBC fails over, a rigid Pike configuration turns a momentary network hiccup into a prolonged, self-inflicted telecommunications outage.
Why Standard Implementations Fail
Enterprise Kamailio deployments repeatedly suffer from false-positive trunk blacklisting due to three common configuration mistakes:
1. Placing Anti-Flood Checks Ahead of the Trusted IP Table
Architects frequently position route[ANTIFLOOD] at the very entrance of request_route under the assumption of optimizing performance. Evaluating high-capacity carrier gateways through untrusted anti-flood rules guarantees blacklisting during any sudden traffic spike.
2. Conflating Carrier Aggregators with Single Endpoints
Configurations apply global Pike parameters uniformly across all incoming interfaces. While thirty requests per two seconds is appropriate for an individual SIP desk phone or softphone, an enterprise carrier SBC routinely delivers hundreds of concurrent call setups per second during business peaks.
3. Using Static Blacklist Tables Without Tiered Rate Limiting
When an IP exceeds the Pike density limit, standard scripts insert the IP into an htable that drops one hundred percent of subsequent traffic for five minutes. Banning an entire carrier trunk rather than applying progressive rate shaping or queue delay converts a brief volume spike into a total communications collapse.
Authenticated Step-by-Step Resolution Playbook
Eliminating false-positive Pike blacklists while preserving bulletproof perimeter defense requires validating trusted carrier peers, exempting in-dialog transactions, implementing progressive rate limiting via ratelimit.so, and configuring auto-healing monitoring commands:
Step 1: Configure Trusted Carrier Gateway Definitions in permissions.conf
Define all trusted wholesale carrier gateways, upstream SBCs, and internal PBX IP ranges in Kamailio's permissions database table or local cache to ensure they are recognized before anti-flood evaluation:
# /etc/kamailio/kamailio.cfg
loadmodule "permissions.so"
# Configure permissions module parameters
modparam("permissions", "db_url", "mysql://https://www.google.com/url?q=http://kamailio:fs_user@10.0.1.20/kamailio&source=gmail&ust=1793734475192000&sa=E (https://www.google.com/url?q=https://www.google.com/url?q%3Dhttp://kamailio:fs_user@10.0.1.20/kamailio%26amp;source%3Dgmail%26amp;ust%3D1793733198397000%26amp;sa%3DE)%26quot&source=gmail&ust=1793734475192000&sa=E;)
modparam("permissions", "db_mode", 1) # Cache trusted peers in memory
modparam("permissions", "peer_tag_mode", 1)Populate the trusted table with your upstream carrier interconnect IP addresses:
# Insert upstream carrier gateway into permissions database
kamctl trusted add 198.51.100.10 any 5060 any "Wholesale Carrier Primary"
kamctl trusted add 198.51.100.11 any 5060 any "Wholesale Carrier Secondary"
kamctl permissions reloadCaching carrier IPs in memory allows Kamailio to identify trusted interconnects in sub-microsecond lookup times without querying backend databases.
Step 2: Restructure request_route with Trusted Peer and Dialog Bypass
In kamailio.cfg, restructure the core routing logic so that in-dialog transactions and authenticated carrier peers bypass aggressive Pike inspection entirely:
# /etc/kamailio/kamailio.cfg
request_route {
# Perform preliminary sanity checks
route(REQINIT);
# Handle established in-dialog traffic immediately
# NEVER apply anti-flood drops to in-dialog signaling (ACK, BYE, re-INVITE)
if (has_totag()) {
if (loose_route()) {
route(RELAY);
exit;
}
}
# Check if incoming request originates from a trusted carrier trunk
if (allow_trusted()) {
# Apply specialized high-capacity carrier rate shaping
route(CARRIER_RATE_LIMIT);
} else {
# Apply strict Pike anti-flood defense to untrusted public endpoints
route(ANTIFLOOD);
}
# Proceed to primary dispatch routing
route(DISPATCH);
}Exempting in-dialog packets guarantees that active customer conversations can always terminate cleanly via BYE and establish media via ACK, even during upstream signaling surges.
Step 3: Implement Tiered Carrier Rate Shaping with ratelimit.so
Rather than applying binary drop-or-ban logic to carrier trunks, deploy ratelimit.so using a capacity bucket algorithm to pace incoming carrier traffic smoothly during failover surges:
# /etc/kamailio/kamailio.cfg
loadmodule "ratelimit.so"
# Configure rate-limiting parameters
modparam("ratelimit", "timer_interval", 1)
modparam("ratelimit", "default_algorithm", "TAILDROP")
route[CARRIER_RATE_LIMIT] {
# Enforce progressive capacity bucket rate limit for trusted trunks
# Allow up to 300 initial call attempts per second before soft throttling
if (!rl_check("trunk_pipe", 300, "TAILDROP")) {
# Respond with standard SIP congestion response rather than silent drops
sl_send_reply("503", "Trunk Capacity Exceeded - Retry Later");
exit;
}
}
route[ANTIFLOOD] {
# Standard Pike check strictly for untrusted public traffic
if (!pike_check_req()) {
$sht(ipban=>$si) = $Ts + 300;
sl_send_reply("403", "Request Rate Denied");
exit;
}
}Using rl_check() absorbs micro-bursts of hundreds of calls during carrier failovers while signaling upstream SBCs to pace retransmissions via 503 Service Unavailable instead of blacklisting the trunk.
Step 4: Verify Active Trusted Lists and Monitor Rate Pacing in Production
Monitor real-time anti-flood decisions, verify that trusted trunks are recognized, and manage active blacklist memory tables without restarting Kamailio:
# Inspect active trusted IP rules cached in Kamailio memory
kamcmd permissions.trustedList
# Verify that no carrier IPs are trapped in the anti-flood blacklist table
kamcmd htable.dump ipban
# Remove an accidentally banned IP address from memory immediately
kamcmd htable.delete ipban 198.51.100.10
# Monitor live rate-limiting pipe metrics and throughput
kamcmd ratelimit.get_pipe trunk_pipe
# Trace anti-flood log triggers during peak traffic periods
grep -i "pike" /var/log/kamailio.log | sed 30qConfirm via kamcmd permissions.trustedList that carrier IP blocks are active and matched. The htable.dump ipban command should confirm that trusted carrier IPs remain completely absent from the blacklist table.
Robust edge defense in enterprise telecommunications requires nuanced discrimination between malicious flood attacks and legitimate carrier failover surges. By validating trusted peer databases ahead of anti-flood checks, exempting in-dialog transactions, and replacing binary bans with capacity-bucket rate shaping, engineering teams eliminate false-positive blacklists and ensure continuous, uninterrupted trunk availability across carrier Kamailio deployments.
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.