Home / Guides / Guide

SIP Ports & Firewall Configuration for Asterisk

Complete guide to SIP ports, firewall rules, NAT traversal, and security configuration for Asterisk PBX. Configure iptables, UFW, and cloud security groups for reliable VoIP with IPComms SIP trunking.

Sign up now or see the full rate table

Guide · · Updated · 18 min read

1. SIP & VoIP Ports Overview

Every VoIP system relies on a specific set of network ports for signaling, media, and management traffic. Understanding which ports SIP uses -- and why -- is the first step to building a reliable and secure Asterisk firewall. The table below covers every port you will encounter on a typical Asterisk PBX.

Port(s) Protocol Service Purpose
5060UDP / TCPSIP SignalingCall setup, registration, and teardown. The primary SIP port. UDP is the default transport; TCP is used for larger messages or when required by the provider.
5061TCP (TLS)SIP TLS (SIPS)Encrypted SIP signaling over TLS. Required for SRTP-secured calls. Prevents eavesdropping on call metadata and credentials.
10000-20000UDPRTP MediaReal-time audio/video streams. Range is configurable in rtp.conf. Each concurrent call uses two RTP ports (one for audio, one for RTCP).
4569UDPIAX2 (Legacy)Inter-Asterisk eXchange protocol. Multiplexes signaling and media on a single port. Rarely used with SIP trunking providers; included for legacy interoperability.
80 / 443TCPHTTP / HTTPSWeb management interfaces such as FreePBX GUI, Asterisk REST Interface (ARI), and WebRTC (WebSocket) connections.
8088 / 8089TCPAsterisk HTTP/HTTPSAsterisk's built-in HTTP server for ARI and WebSocket connections. Port 8089 is the TLS variant.
5038TCPAMIAsterisk Manager Interface. Used by external applications (dialers, dashboards, billing systems) to control Asterisk. Should never be exposed to the internet.
22TCPSSHSecure Shell for server administration. Restrict to trusted IPs and use key-based authentication.

2. Understanding NAT & SIP

Network Address Translation (NAT) is the single most common cause of VoIP problems. Understanding why NAT breaks SIP is essential before configuring any firewall rules.

The Problem: SIP and Private IPs

SIP was designed before NAT became ubiquitous. When your Asterisk server sits behind a NAT router, two critical issues arise:

  • ● SIP headers contain private IPs: The Contact and Via headers in SIP messages include your server's private IP address (e.g., 192.168.1.100). The remote SIP server tries to send responses to this unreachable address.
  • ● RTP media goes to the wrong address: The SDP body in SIP INVITE messages advertises the private IP for media streams. The remote end sends audio to the private IP, resulting in one-way or no audio.
  • ● Connection tracking timeouts: NAT routers maintain a mapping table for UDP connections. SIP registrations and calls can fail when these mappings expire (typically 30-60 seconds for UDP).

How Asterisk Handles NAT

Asterisk PJSIP provides several settings to work around NAT. These are configured in the transport and endpoint sections of pjsip.conf:

Setting Where What It Does
external_media_addresstransportReplaces private IP in SDP media lines with your public IP so remote endpoints send RTP to the correct address.
external_signaling_addresstransportReplaces private IP in SIP Via/Contact headers with your public IP for signaling responses.
local_nettransportDefines which networks are behind NAT. Asterisk only rewrites addresses when the remote endpoint is outside these ranges.
force_rportendpointForces Asterisk to send SIP responses to the source port of the request (rport), rather than the port in the Via header. Essential for NAT traversal.
rewrite_contactendpointRewrites the Contact header with the actual source IP:port. Ensures subsequent SIP messages reach the endpoint behind NAT.
rtp_symmetricendpointSends RTP back to the address and port from which it was received, rather than the address in the SDP. Fixes one-way audio through NAT.
direct_mediaendpointMust be set to no in NAT environments. Prevents Asterisk from redirecting media to flow directly between endpoints (which fails through NAT).

3. Configuring iptables

iptables is the standard Linux firewall and provides granular control over network traffic. Below is a complete, production-ready iptables ruleset for an Asterisk server connected to IPComms SIP trunking.

Complete iptables Ruleset

#!/bin/bash
# Asterisk PBX Firewall Rules for IPComms SIP Trunking
# Save as /etc/iptables/rules.sh and run with: bash /etc/iptables/rules.sh
# Flush existing rules
iptables -F
iptables -X
iptables -Z
# Set default policies - DROP everything by default
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow loopback interface (required for local services)
iptables -A INPUT -i lo -j ACCEPT
# Allow established and related connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# SSH - rate limited to prevent brute force (adjust port if non-standard)
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update \
    --seconds 60 --hitcount 4 --name SSH -j DROP
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT
# SIP Signaling from IPComms (UDP 5060)
# IPComms SIP servers - replace with current IPs from your portal
iptables -A INPUT -p udp --dport 5060 -s 208.75.152.0/22 -j ACCEPT
# SIP TLS from IPComms (TCP 5061) - if using encrypted signaling
iptables -A INPUT -p tcp --dport 5061 -s 208.75.152.0/22 -j ACCEPT
# RTP Media - must be open to IPComms media servers
# Use the same IP range or open to any if media IPs vary
iptables -A INPUT -p udp --dport 10000:20000 -j ACCEPT
# ICMP (ping) - useful for troubleshooting, rate limited
iptables -A INPUT -p icmp --icmp-type echo-request -m limit \
    --limit 1/second --limit-burst 4 -j ACCEPT
# Optional: FreePBX/Web GUI - restrict to management IPs only
# iptables -A INPUT -p tcp --dport 443 -s YOUR_OFFICE_IP -j ACCEPT
# Optional: AMI - restrict to localhost or specific management apps
# iptables -A INPUT -p tcp --dport 5038 -s 127.0.0.1 -j ACCEPT
# Log dropped packets (optional, useful for debugging)
iptables -A INPUT -m limit --limit 5/min -j LOG \
    --log-prefix "iptables-dropped: " --log-level 4
# Drop everything else (already handled by default policy, explicit for clarity)
iptables -A INPUT -j DROP

View Rules in iptables-save Format

# Display current rules in a saveable format
sudo iptables-save
# Expected output:
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name SSH --mask 255.255.255.255 --rsource
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 --name SSH --mask 255.255.255.255 --rsource -j DROP
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -j ACCEPT
-A INPUT -p udp -m udp --dport 5060 -s 208.75.152.0/22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 5061 -s 208.75.152.0/22 -j ACCEPT
-A INPUT -p udp -m udp --dport 10000:20000 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -m limit --limit 1/sec --limit-burst 4 -j ACCEPT
-A INPUT -j DROP
COMMIT

Persist Rules with iptables-persistent

# Install iptables-persistent to save rules across reboots
sudo apt install -y iptables-persistent
# Save current rules (run after configuring)
sudo netfilter-persistent save
# Rules are saved to:
#   /etc/iptables/rules.v4  (IPv4)
#   /etc/iptables/rules.v6  (IPv6)
# To reload saved rules manually
sudo netfilter-persistent reload

Building this? Your PBX will need a number

Find a phone number for your trunk

Local numbers $1.50 a month, toll-free $2.00, $1.00 one-time setup. Pick one here and it carries into signup.

Enter an area code, or wait a moment for numbers near you.

More numbers, porting and E911 in the portal

Outbound US and Canada
$0.010 /min
Inbound
$0.009 /min
Local number
$1.50 /mo
Per channel
$0 no set limits

Sign up now or see the full rate table. No contracts.

4. Configuring UFW (Uncomplicated Firewall)

UFW is a user-friendly frontend for iptables that ships with Ubuntu and is available on Debian. It provides simpler syntax while generating the same underlying iptables rules.

Install and Enable UFW

# Install UFW (if not already present)
sudo apt install -y ufw
# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

Add Firewall Rules

# SSH access (allow before enabling UFW to avoid lockout!)
sudo ufw allow 22/tcp comment 'SSH'
# SIP signaling from IPComms
sudo ufw allow from 208.75.152.0/22 to any port 5060 proto udp comment 'SIP from IPComms'
# SIP TLS from IPComms
sudo ufw allow from 208.75.152.0/22 to any port 5061 proto tcp comment 'SIP TLS from IPComms'
# RTP media range
sudo ufw allow 10000:20000/udp comment 'RTP Media'
# Optional: Web GUI from specific IP
# sudo ufw allow from YOUR_OFFICE_IP to any port 443 proto tcp comment 'Web GUI'
# Enable UFW
sudo ufw enable

Verify UFW Status

sudo ufw status verbose
# Expected output:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
To                         Action      From
--                         ------      ----
22/tcp                     ALLOW IN    Anywhere                   # SSH
5060/udp                   ALLOW IN    208.75.152.0/22            # SIP from IPComms
5061/tcp                   ALLOW IN    208.75.152.0/22            # SIP TLS from IPComms
10000:20000/udp            ALLOW IN    Anywhere                   # RTP Media

5. Cloud Provider Security Groups

Cloud firewalls operate at the hypervisor level, outside your VM. They are stateful by default, meaning you only need to define inbound rules -- return traffic is automatically allowed. You should still run iptables or UFW inside the VM for defense in depth.

AWS EC2 Security Group

Create or modify a Security Group in the AWS Console (EC2 > Security Groups) with these inbound rules:

Type Protocol Port Range Source Description
SSHTCP22Your IP/32SSH management
Custom UDPUDP5060208.75.152.0/22SIP from IPComms
Custom TCPTCP5061208.75.152.0/22SIP TLS from IPComms
Custom UDPUDP10000-200000.0.0.0/0RTP media

Google Cloud Firewall Rules

Create firewall rules in VPC Network > Firewall or using the gcloud CLI:

# Allow SIP signaling from IPComms
gcloud compute firewall-rules create allow-sip-ipcomms \
    --direction=INGRESS \
    --priority=1000 \
    --network=default \
    --action=ALLOW \
    --rules=udp:5060,tcp:5061 \
    --source-ranges=208.75.152.0/22 \
    --target-tags=asterisk-server
# Allow RTP media
gcloud compute firewall-rules create allow-rtp \
    --direction=INGRESS \
    --priority=1000 \
    --network=default \
    --action=ALLOW \
    --rules=udp:10000-20000 \
    --source-ranges=0.0.0.0/0 \
    --target-tags=asterisk-server

DigitalOcean Cloud Firewall

In the DigitalOcean control panel, navigate to Networking > Firewalls and create these inbound rules:

Type Protocol Ports Sources
SSHTCP22Your IP
CustomUDP5060208.75.152.0/22
CustomTCP5061208.75.152.0/22
CustomUDP10000-20000All IPv4

6. Router / NAT Port Forwarding

If your Asterisk server is on-premises behind a NAT router, you need to forward the appropriate ports from your router's public IP to the Asterisk server's private IP address.

Required Port Forwarding Rules

External Port Protocol Internal IP Internal Port Purpose
5060UDP192.168.1.x5060SIP signaling
5061TCP192.168.1.x5061SIP TLS
10000-20000UDP192.168.1.x10000-20000RTP media

DISABLE SIP ALG Immediately: Most consumer and many business routers include a "SIP Application Layer Gateway" (SIP ALG, sometimes called SIP Helper or SIP Transformations). This feature rewrites SIP packets as they pass through the router, almost always incorrectly. SIP ALG causes registration failures, one-way audio, dropped calls, and phantom ringing. Disable SIP ALG in your router's settings before doing anything else.

How to Disable SIP ALG

The setting location varies by router brand:

  • ● Ubiquiti/UniFi: Settings > Threat Management > turn off SIP ALG
  • ● pfSense/OPNsense: Disabled by default. Verify under System > Advanced > Firewall/NAT > check "Disable NAT-T" is not interfering
  • ● MikroTik: /ip firewall service-port disable sip
  • ● Netgear/Linksys/TP-Link: Usually under WAN settings, NAT settings, or Firewall. Look for "SIP ALG" or "SIP Passthrough" and disable it.
  • ● Linux Router: rmmod nf_nat_sip nf_conntrack_sip and blacklist the modules

Static NAT vs. Port Forwarding

There are two approaches to exposing your Asterisk server through NAT:

Port Forwarding

Forward only the specific ports needed (5060, 10000-20000). More secure because only VoIP traffic reaches the server. Recommended for most deployments.

Static NAT (1:1 NAT)

Maps a dedicated public IP to the Asterisk server's private IP. All ports are forwarded. Use when you have a spare public IP and want simplified configuration. Still use iptables on the server to filter traffic.

7. Asterisk NAT Configuration

With your firewall rules in place, configure Asterisk itself to handle NAT correctly. This section covers the PJSIP transport settings and RTP configuration you need for reliable VoIP through NAT.

PJSIP Transport Configuration

Edit /etc/asterisk/pjsip.conf and configure the transport section:

; ==============================================
; PJSIP Transport - NAT-Aware Configuration
; ==============================================
[transport-udp]
type = transport
protocol = udp
bind = 0.0.0.0:5060
; Replace with your server's public IP address
external_media_address = 203.0.113.50
external_signaling_address = 203.0.113.50
; Define all local/private networks behind NAT
; Asterisk uses this to decide when to apply external addresses
local_net = 192.168.0.0/16
local_net = 10.0.0.0/8
local_net = 172.16.0.0/12
local_net = 169.254.0.0/16
; Optional: TLS transport for encrypted signaling
[transport-tls]
type = transport
protocol = tls
bind = 0.0.0.0:5061
external_media_address = 203.0.113.50
external_signaling_address = 203.0.113.50
local_net = 192.168.0.0/16
local_net = 10.0.0.0/8
local_net = 172.16.0.0/12
cert_file = /etc/asterisk/keys/asterisk.crt
priv_key_file = /etc/asterisk/keys/asterisk.key
method = tlsv1_2

PJSIP Endpoint NAT Settings

Add these NAT-related settings to your IPComms endpoint definition:

[ipcomms-endpoint]
type = endpoint
transport = transport-udp
context = from-ipcomms
disallow = all
allow = ulaw
allow = alaw
allow = g722
outbound_auth = ipcomms-auth
aors = ipcomms-aor
from_user = YOUR_TRUNK_USERNAME
from_domain = sip.ipcomms.net
; NAT settings - all four are essential for NAT traversal
direct_media = no
force_rport = yes
rewrite_contact = yes
rtp_symmetric = yes
ice_support = no

RTP Configuration (rtp.conf)

Edit /etc/asterisk/rtp.conf to define the media port range. This range must match your firewall rules:

[general]
; RTP port range - must match firewall rules
rtpstart = 10000
rtpend = 20000
; Enable strict RTP - only accept media from the expected source
strictrtp = yes
; Disable RTP checksums (saves CPU, most networks are reliable)
rtpchecksums = no
; Disable ICE support unless you specifically need WebRTC
icesupport = no

8. Fail2Ban for SIP Security

Even with tight firewall rules, SIP brute-force attacks are common. Fail2Ban monitors Asterisk logs and automatically bans IPs that show suspicious behavior, such as repeated failed registration attempts.

Install Fail2Ban

sudo apt install -y fail2ban
# Enable and start Fail2Ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

Configure Asterisk Jail

Create a local jail configuration. Never edit jail.conf directly -- it gets overwritten on updates. Create /etc/fail2ban/jail.local instead:

sudo nano /etc/fail2ban/jail.local
[DEFAULT]
# Ban for 1 hour after 3 failures within 10 minutes
bantime  = 3600
findtime = 600
maxretry = 3
# Whitelist your trusted IPs (office, VPN, IPComms servers)
ignoreip = 127.0.0.1/8 ::1 208.75.152.0/22
# Use iptables for banning
banaction = iptables-multiport
[asterisk]
enabled  = true
port     = 5060,5061
protocol = udp
filter   = asterisk
logpath  = /var/log/asterisk/messages
maxretry = 3
findtime = 600
bantime  = 86400
[sshd]
enabled  = true
port     = ssh
maxretry = 5
bantime  = 3600

Verify the Asterisk Filter

Fail2Ban ships with an Asterisk filter at /etc/fail2ban/filter.d/asterisk.conf. Verify it matches your log format:

# Test the filter against your Asterisk log
sudo fail2ban-regex /var/log/asterisk/messages /etc/fail2ban/filter.d/asterisk.conf

Manage Fail2Ban

# Restart Fail2Ban after configuration changes
sudo systemctl restart fail2ban
# Check jail status
sudo fail2ban-client status asterisk
# Unban a specific IP (if accidentally banned)
sudo fail2ban-client set asterisk unbanip 192.168.1.100
# View currently banned IPs
sudo fail2ban-client status asterisk

For comprehensive Asterisk security beyond Fail2Ban, including TLS encryption, SRTP, password policies, and ACLs, see our Asterisk Security Hardening Guide.

9. Testing & Troubleshooting

After configuring your firewall and NAT settings, verify that everything is working correctly before going into production. These commands and techniques will help you diagnose common issues.

Verify Ports Are Open

# Check which ports Asterisk is listening on
sudo ss -tulnp | grep asterisk
# Expected output:
udp   UNCONN  0  0  0.0.0.0:5060   0.0.0.0:*  users:(("asterisk",pid=1234,fd=15))
# Scan your server from a remote machine using nmap
nmap -sU -p 5060 YOUR_SERVER_PUBLIC_IP
# Test UDP connectivity with netcat (from a remote machine)
nc -vzu YOUR_SERVER_PUBLIC_IP 5060
# Check if RTP ports are in the correct range
sudo ss -tulnp | grep -E '1[0-9]{4}'

Test SIP Connectivity

# From the Asterisk CLI, check trunk registration
sudo asterisk -rx "pjsip show registrations"
# Send a SIP OPTIONS ping to IPComms to test connectivity
sudo asterisk -rx "pjsip qualify ipcomms-aor"
# Show detailed transport info
sudo asterisk -rx "pjsip show transport transport-udp"
# Enable SIP debug to see all SIP messages
sudo asterisk -rx "pjsip set logger on"

Common Issues & Solutions

Symptom Likely Cause Solution
One-way audioNAT misconfiguration -- RTP going to private IPVerify external_media_address is set. Enable rtp_symmetric = yes. Check RTP ports are forwarded.
Registration timeoutFirewall blocking UDP 5060Verify iptables/UFW allows 5060 from IPComms IPs. Check cloud security group. Test with nmap -sU -p 5060.
Calls drop after 30 secondsSIP ALG rewriting packetsDisable SIP ALG on router. This is the #1 cause of 30-second call drops.
No audio at allRTP ports blocked by firewallOpen UDP 10000-20000. Verify the range in rtp.conf matches your firewall rules.
Intermittent registration dropsNAT connection tracking timeoutReduce registration expiry to 120s. Set qualify_frequency = 30 on the AOR to send keepalives.
403 Forbidden on outboundIP not authorized or wrong caller IDVerify your server's public IP is whitelisted in the IPComms portal. Check that from_user matches your trunk username.

Debug Commands Quick Reference

# Watch live SIP traffic
sudo asterisk -rx "pjsip set logger on"
sudo tail -f /var/log/asterisk/messages
# Capture SIP packets with tcpdump
sudo tcpdump -i eth0 -n -s 0 port 5060 -w /tmp/sip-capture.pcap
# Capture RTP packets (on a specific call)
sudo tcpdump -i eth0 -n udp portrange 10000-20000 -c 100
# Check current iptables rules and packet counts
sudo iptables -L -n -v
# Check Fail2Ban status for banned IPs
sudo fail2ban-client status asterisk
# Verify Asterisk is running as the correct user
ps aux | grep asterisk

Stop worrying about SIP trunk capacity. We have you covered.

SIP trunking from a US carrier since 2002: $0.009 per minute inbound, $0.010 outbound, numbers from $1.50 a month, $0 per channel, no contracts.

Sign up now or see the full rate table