TR EN DE
GitHub Repository mhrgl.com
Home / Integrations / Microsoft Teams Direct Routing
💼 Enterprise Hybrid Telephony · Microsoft 365

💼 Microsoft Teams Direct Routing & SBC Gateway Integration

Bridge your AiPBX Asterisk 22 telephony infrastructure with Microsoft 365 Teams Phone System. Retain existing local SIP carrier trunks without paying expensive Microsoft Calling Plan fees, seamlessly integrating Teams desktop/mobile clients with internal extensions and call queues.

1. Overview & Why Direct Routing?

While Microsoft Teams dominates enterprise collaboration, Microsoft's native Calling Plans are notoriously expensive and face severe regulatory and porting restrictions across many regions.

AiPBX Direct Routing Gateway acts as a certified-compatible Session Border Controller (SBC) between Microsoft 365 Phone System and your local telecommunications trunks. Key advantages:

  • Carrier Freedom: Retain existing SIP trunks and competitive local telco contracts without vendor lock-in.
  • Up to 70% Cost Reduction: Eliminate per-user monthly Microsoft Calling Plan fees.
  • Hybrid Intercom: Seamless 3 or 4-digit extension-to-extension dialing between Teams users, physical desk phones, WebRTC browser softphones, and native mobile clients.
  • Enterprise PBX Features: Teams users connect directly to AiPBX multi-level IVRs, ACD call center queues (with *22/*23 break codes), encrypted call recording, and T.38 digital faxing.
Feature Matrix Microsoft Native Calling Plan AiPBX Direct Routing (Recommended)
Monthly Telecom Cost $12 - $24 per user / month $0 Extra (Uses existing SIP trunk rates)
Desk Phone & Intercom Only expensive Teams-certified phones All standard SIP hardware (Yealink, Grandstream, etc.) + WebRTC
Call Center & Agent Breaks Basic queues, no granular break codes Full ACD queues, *22/*23 break codes, live wallboard & *90 spy
Inbound/Outbound Fax (T.38) Not supported Full T.38 & SpanDSP digital fax server

2. Architecture & Topology

Microsoft Teams Direct Routing mandates SIP over TLS (Port 5061) for signaling and SRTP (SDES encryption) for audio streams. AiPBX operates as a secure SBC edge gateway interfacing between Microsoft 365 cloud proxies and your enterprise infrastructure:

Direct Routing Network Topology TLS 1.2 · SRTP · Port 5061
┌─────────────────────────────────────────────────────────────────────────────┐
│                    MICROSOFT 365 CLOUD INFRASTRUCTURE                       │
│                                                                             │
│   [ Teams Desktop ]       [ Teams Mobile (iOS/Android) ]      [ Teams Web ]  │
│           │                               │                        │        │
│           └───────────────────────┬───────┴────────────────────────┘        │
│                                   ▼                                         │
│                 Microsoft Teams Phone System Core                           │
│                                   │                                         │
│                sip.pstnhub.microsoft.com (EU / Primary)                     │
│                sip2.pstnhub.microsoft.com (US / Secondary)                  │
│                sip3.pstnhub.microsoft.com (APAC / Tertiary)                 │
└───────────────────────────────────┬─────────────────────────────────────────┘
                                    │
                                    │  SIP over TLS (Port 5061)
                                    │  SRTP Media (UDP 10000-20000)
                                    │  Trusted CA SSL (Let's Encrypt / DigiCert)
                                    ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                    AiPBX SESSION BORDER CONTROLLER (SBC)                    │
│                                                                             │
│   FQDN: sbc.yourdomain.com / IP: 212.147.x.x                                │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │ Asterisk 22 PJSIP Signaling & Media Engine                          │   │
│   │  • TLS Transport (Port 5061) - Strict Cipher Suites (AES256/GCM)    │   │
│   │  • SDES-SRTP Audio Transcoding (SILK, Opus, G.711a, G.711u)         │   │
│   │  • Bi-directional SIP OPTIONS Heartbeat Monitoring (60s Keepalive)  │   │
│   │  • E.164 Inbound/Outbound Route Normalization & Dialplan            │   │
│   └──────────────────────────────────┬──────────────────────────────────┘   │
└──────────────────────────────────────┼──────────────────────────────────────┘
                                       │
           ┌───────────────────────────┼───────────────────────────┐
           ▼                           ▼                           ▼
┌─────────────────────┐     ┌─────────────────────┐     ┌─────────────────────┐
│  OFFICE EXTENSIONS  │     │  CALL CENTER & IVR  │     │   CARRIER TRUNKS    │
│  • Yealink/Fanvil   │     │  • ACD Queues       │     │  • Türk Telekom     │
│  • AiPBX WebRTC Web │     │  • *22/*23 Breaks   │     │  • Turkcell / Voda  │
│  • Android/iOS Apps │     │  • Recording & SLA  │     │  • Any SIP Provider │
└─────────────────────┘     └─────────────────────┘     └─────────────────────┘
💡
SIP OPTIONS Heartbeat Mechanism: Microsoft Teams and AiPBX exchange periodic SIP OPTIONS pings every 60 seconds to evaluate trunk reachability. When configured with qualify_frequency=60 in Asterisk PJSIP, the SBC status turns "Active" in the Teams Admin Center.

3. Prerequisites & Licensing

Ensure the following prerequisites are met prior to configuring AiPBX Direct Routing:

  1. Microsoft 365 Licenses: A Teams Phone Standard add-on license or an encompassing Microsoft 365 E5 license for each user requiring external calling.
  2. Verified FQDN: A dedicated subdomain (e.g. sbc.yourcompany.com) matching a custom domain verified in your Microsoft 365 tenant.
  3. Trusted Public SSL Certificate: Issued by an officially recognized Certificate Authority (DigiCert, Sectigo, GlobalSign, or Let's Encrypt ISRG Root X1). The CN/SAN must match your SBC FQDN.
  4. Static Public IPv4: A persistent static public IP assigned directly or via 1:1 NAT to your AiPBX host.

4. Network & Firewall Rules

Configure your firewall to allow bi-directional traffic between your AiPBX SBC and Microsoft 365 Direct Routing endpoints:

Protocol & Port Source / Destination Traffic Type & Purpose
TCP 5061 52.114.0.0/16, 52.112.0.0/14 SIP over TLS Signaling: Bi-directional call setup and OPTIONS keep-alive with MS PSTN Hub.
UDP 10000:20000 52.112.0.0/14, 52.120.0.0/14 SRTP Media Streams: Encrypted voice payload exchange between Teams clients and PBX.
TCP 443 Genel / Any HTTPS Webhook & SSL: Automated Certbot renewal and outbound Teams channel webhooks.
bash — Ubuntu UFW Firewall Rules
# 1. Microsoft Teams SIP TLS (port 5061) - Microsoft subnets
sudo ufw allow proto tcp from 52.114.0.0/16 to any port 5061 comment 'MS Teams SIP TLS Primary'
sudo ufw allow proto tcp from 52.112.0.0/14 to any port 5061 comment 'MS Teams SIP TLS Secondary'

# 2. Microsoft Teams SRTP voice media (UDP 10000-20000)
sudo ufw allow proto udp from 52.112.0.0/14 to any port 10000:20000 comment 'MS Teams SRTP Media'
sudo ufw allow proto udp from 52.120.0.0/14 to any port 10000:20000 comment 'MS Teams Media Relays'

# 3. Reload the firewall and review its status
sudo ufw reload
sudo ufw status numbered

5. Asterisk 22 & PJSIP Configuration

Asterisk 22 PJSIP natively satisfies Microsoft's strict Direct Routing requirements including TLS 1.2+ mutual authentication, SDES-SRTP media encryption, and E.164 normalization. Add the following snippets to your Asterisk configuration:

A. /etc/asterisk/pjsip.conf — Trunk & Transport Setup

ini — /etc/asterisk/pjsip.conf (Teams Direct Routing)
; ====================================================================
; 1. TLS TRANSPORT (PORT 5061 - Microsoft Teams SBC)
; ====================================================================
[transport-tls-msteams]
type=transport
protocol=tls
bind=0.0.0.0:5061
cert_file=/etc/letsencrypt/live/sbc.yourdomain.com/fullchain.pem
priv_key_file=/etc/letsencrypt/live/sbc.yourdomain.com/privkey.pem
method=tlsv1_2
cipher=ECDHE-RSA-AES256-GCM-SHA384,ECDHE-RSA-AES128-GCM-SHA256,ECDHE-RSA-AES256-SHA384
verify_client=no
verify_server=yes
require_client_cert=no

; ====================================================================
; 2. MS TEAMS ENDPOINT
; ====================================================================
[msteams-trunk]
type=endpoint
transport=transport-tls-msteams
context=from-msteams
disallow=all
allow=alaw,ulaw,opus,g722
direct_media=no
media_encryption=sdes
rtp_symmetric=yes
force_rport=yes
rewrite_contact=yes
trust_id_inbound=yes
send_rpid=yes
send_pai=yes
timers=yes
timers_sess_expires=1800
aors=msteams-aor

; ====================================================================
; 3. MS TEAMS AOR & QUALIFY (OPTIONS heartbeat)
; ====================================================================
[msteams-aor]
type=aor
contact=sip:sip.pstnhub.microsoft.com:5061;transport=tls
qualify_frequency=60
qualify_timeout=3.0

; ====================================================================
; 4. IDENTIFY (match inbound calls to Microsoft IPs)
; ====================================================================
[msteams-identify]
type=identify
endpoint=msteams-trunk
match=52.114.148.0, 52.114.132.74, 52.114.75.24, 52.114.76.76, 52.114.7.24, 52.114.14.70, 52.114.16.74, 52.114.20.29, sip.pstnhub.microsoft.com, sip2.pstnhub.microsoft.com, sip3.pstnhub.microsoft.com

B. /etc/asterisk/extensions.conf — Dialplan Routing

ini — /etc/asterisk/extensions.conf (from-msteams & to-msteams)
; ====================================================================
; 1. CALLS COMING FROM MICROSOFT TEAMS (from-msteams)
; ====================================================================
[from-msteams]
; Teams user dials a 3-4 digit extension (e.g. 105)
exten => _[1-9]XX,1,NoOp(Teams -> Extension: ${CALLERID(num)} -> ${EXTEN})
 same => n,Dial(PJSIP/${EXTEN},30,tTkK)
 same => n,Hangup()

exten => _[1-9]XXX,1,NoOp(Teams -> 4-digit Extension: ${CALLERID(num)} -> ${EXTEN})
 same => n,Dial(PJSIP/${EXTEN},30,tTkK)
 same => n,Hangup()

; Teams user calls the call-center queue (e.g. 800)
exten => 800,1,NoOp(Teams -> Support Queue)
 same => n,Answer()
 same => n,Queue(support_queue,tTkK,,,180)
 same => n,Hangup()

; Teams user dials an external PSTN number (05xx / 02xx / +90...)
exten => _0[2-5]XXXXXXXXX,1,NoOp(Teams -> Carrier Trunk Outbound: ${EXTEN})
 same => n,Dial(PJSIP/${EXTEN}@carrier-trunk,60,tTkK)
 same => n,Hangup()

; ====================================================================
; 2. CALLS FROM AIPBX EXTENSIONS TO TEAMS (to-msteams)
; Routes to the E.164 numbers assigned to Teams users (+90212XXXXXXX)
; ====================================================================
[to-msteams]
exten => _+.,1,NoOp(AiPBX -> Teams Direct Routing: ${EXTEN})
 same => n,Set(CALLERID(num)=+902129990000) ; your company main number
 same => n,Dial(PJSIP/${EXTEN}@msteams-trunk,60,tTkK)
 same => n,Hangup()

; Short code to reach a Teams user (e.g. 7105 -> +902129997105)
exten => _7XXX,1,NoOp(Extension -> Teams User 7${EXTEN:1})
 same => n,Dial(PJSIP/+90212999${EXTEN}@msteams-trunk,45,tTkK)
 same => n,Hangup()
bash — Live-Reload the Asterisk Configuration
# Reload the Asterisk modules live
sudo asterisk -rx "pjsip reload"
sudo asterisk -rx "dialplan reload"

# Verify the Teams trunk status and OPTIONS heartbeat
sudo asterisk -rx "pjsip show endpoints"
sudo asterisk -rx "pjsip show aor msteams-aor"

6. Microsoft 365 PowerShell Setup

Configuring Microsoft 365 Direct Routing is completed via the official MicrosoftTeams PowerShell module. Execute the following sequence with Teams Administrator privileges:

powershell — Microsoft Teams PowerShell Setup
# ====================================================================
# STEP 1: Install the module and connect to your Microsoft 365 tenant
# ====================================================================
Install-Module -Name MicrosoftTeams -Force -AllowClobber
Connect-MicrosoftTeams

# ====================================================================
# STEP 2: Register the AiPBX SBC gateway
# ====================================================================
New-CsOnlinePSTNGateway `
    -Fqdn "sbc.yourdomain.com" `
    -SipSignalingPort 5061 `
    -CodecPriorityList SILK,G711A,G711U `
    -MaxConcurrentSessions 100 `
    -Enabled $true

# ====================================================================
# STEP 3: Create the PSTN usage and voice route
# ====================================================================
# Define a PSTN usage tag
Set-CsOnlinePstnUsage -Identity Global -Usage @{Add="AiPBX-Local"}

# Voice route sending all outbound calls to the AiPBX SBC
New-CsOnlineVoiceRoute `
    -Name "AiPBX-PSTN-Route" `
    -NumberPattern ".*" `
    -OnlinePstnGatewayList "sbc.yourdomain.com" `
    -Priority 1 `
    -OnlinePstnUsages "AiPBX-Local"

# Create the voice routing policy
New-CsOnlineVoiceRoutingPolicy `
    -Identity "AiPBX-Voice-Policy" `
    -OnlinePstnUsages "AiPBX-Local" `
    -Description "AiPBX Direct Routing policy"

# ====================================================================
# STEP 4: Assign a number to the user and apply the policy
# ====================================================================
# Assign an E.164 phone number and enable Enterprise Voice
Set-CsPhoneNumberAssignment `
    -Identity "ahmet.yilmaz@yourdomain.com" `
    -PhoneNumber "+902129991001" `
    -PhoneNumberType DirectRouting

# Attach the AiPBX voice policy to the user
Grant-CsOnlineVoiceRoutingPolicy `
    -Identity "ahmet.yilmaz@yourdomain.com" `
    -PolicyName "AiPBX-Voice-Policy"
✅
Dial Pad Activation: Microsoft 365 cloud propagation typically takes 15 to 30 minutes. Once propagated, the native numeric Dial Pad will appear automatically inside the Teams "Calls" tab.

7. Call Flows & Enterprise Scenarios

Once deployed, AiPBX delivers seamless hybrid routing scenarios between legacy telephony and Teams cloud:

1. Teams ➔ Desk Phone / Extension

Dialing 105 in Teams routes via TLS 5061 to AiPBX, ringing the physical IP phone and native mobile client simultaneously.

2. PSTN Inbound ➔ IVR ➔ Teams

Inbound caller dials your company number, hears the AiPBX IVR menu, presses 1, and is forwarded directly to the sales rep on Microsoft Teams.

3. Teams ➔ Outside World (PSTN Calls)

Teams user dials a mobile number; the call exits via AiPBX through your existing telco SIP trunk at local corporate rates.

4. Teams Users as Queue Agents

Teams agents can join AiPBX ACD queues dynamically, receiving distributed customer calls with full supervisor monitoring.

8. Teams Webhooks & Channel Notifications

Beyond voice routing, AiPBX dispatches rich Adaptive Cards to Microsoft Teams channels via incoming webhooks for missed calls, new faxes, and SLA breach alerts:

bash — Missed-Call Teams Webhook (cURL & Adaptive Card)
curl -X POST -H "Content-Type: application/json" -d '{
  "type": "message",
  "attachments": [
    {
      "contentType": "application/vnd.microsoft.card.adaptive",
      "content": {
        "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
        "type": "AdaptiveCard",
        "version": "1.4",
        "body": [
          {
            "type": "TextBlock",
            "text": "📞 AiPBX — Missed Call Alert",
            "weight": "Bolder",
            "size": "Medium",
            "color": "Attention"
          },
          {
            "type": "FactSet",
            "facts": [
              { "title": "Caller:", "value": "+90 532 123 45 67" },
              { "title": "Target Queue:", "value": "Support Queue (*800)" },
              { "title": "Wait Time:", "value": "48 seconds" },
              { "title": "Time:", "value": "2026-09-18 11:42:15" }
            ]
          }
        ],
        "actions": [
          {
            "type": "Action.OpenUrl",
            "title": "Open in AiPBX",
            "url": "https://aipbx.bid/cdr-reports"
          }
        ]
      }
    }
  ]
}' "https://yourtenant.webhook.office.com/webhookb2/..."

9. Troubleshooting & Diagnostics

Common issues encountered during Direct Routing configuration and their remedies:

Symptom / Error Probable Root Cause Resolution
SIP OPTIONS Unanswered / SBC Down Port 5061 blocked or FQDN does not match SSL CN/SAN. Check UFW rules and ensure Certbot certificate matches SBC FQDN.
488 Not Acceptable Here Codec mismatch or missing SRTP encryption. Verify media_encryption=sdes and G.711/Opus codecs in PJSIP config.
403 Forbidden Voice policy or phone assignment missing in M365. Check user status with Get-CsOnlineUser in PowerShell.
One-Way Audio UDP media ports blocked or NAT external_media_address unset. Add external_media_address to PJSIP transport and verify UDP range.
bash — Watch Live SIP Traffic (Debug)
# Attach to the Asterisk console and enable the PJSIP SIP packet logger
sudo asterisk -rvvv
pjsip set logger on

# To capture only Microsoft Teams traffic, in a shell:
sudo tcpdump -n -i any port 5061 -vv