Validate TURN config to guard against invalid values (#4742)

This commit is contained in:
Raja Subramanian
2026-08-11 20:34:49 +05:30
committed by GitHub
parent c4c356f6ca
commit 7167f91493
7 changed files with 344 additions and 37 deletions
+5 -2
View File
@@ -1096,11 +1096,14 @@ func (r *RoomManager) iceServersForParticipant(apiKey string, participant types.
var username, credential string
if s.Secret != "" {
// Generate dynamic credentials using TURN static auth secrets
// Generate dynamic credentials using TURN static auth secrets.
// 0 means use the default; clamp the rest so a negative or overflowing TTL
// cannot produce a wrong-lifetime credential.
ttl := s.TTL
if ttl == 0 {
ttl = 14400 // Default 4 hours
ttl = config.DefaultExternalTURNTTLSeconds
}
ttl, _ = config.ClampTURNTTLSeconds(ttl)
expiry := time.Now().Add(time.Duration(ttl) * time.Second).Unix()
participantID := string(participant.ID())
+34 -11
View File
@@ -46,6 +46,20 @@ const (
var ErrExpired = errors.New("expired")
// parsePeerCIDRs compiles a list of CIDR strings, failing with a field-specific
// error on any invalid entry so a malformed peer policy is never silently ignored.
func parsePeerCIDRs(field string, cidrs []string) ([]*net.IPNet, error) {
parsed := make([]*net.IPNet, 0, len(cidrs))
for _, cidr := range cidrs {
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return nil, fmt.Errorf("invalid CIDR %q in %s: %w", cidr, field, err)
}
parsed = append(parsed, ipnet)
}
return parsed, nil
}
func NewTurnServer(conf *config.Config, authHandler turn.AuthHandler, standalone bool) (*turn.Server, error) {
turnConf := conf.TURN
if !turnConf.Enabled {
@@ -64,6 +78,17 @@ func NewTurnServer(conf *config.Config, authHandler turn.AuthHandler, standalone
}
}
// parse peer CIDR policies once at startup so a malformed entry fails loudly
// instead of being silently skipped on every permission decision (fail-open)
allowRestrictedPeerCIDRs, err := parsePeerCIDRs("turn.allow_restricted_peer_cidrs", turnConf.AllowRestrictedPeerCIDRs)
if err != nil {
return nil, err
}
denyPeerCIDRs, err := parsePeerCIDRs("turn.deny_peer_cidrs", turnConf.DenyPeerCIDRs)
if err != nil {
return nil, err
}
serverConfig := turn.ServerConfig{
Realm: LivekitRealm,
AuthHandler: authHandler,
@@ -105,12 +130,10 @@ func NewTurnServer(conf *config.Config, authHandler turn.AuthHandler, standalone
peerIP.IsPrivate() ||
peerIP.IsUnspecified() {
allowed := false
for _, cidr := range turnConf.AllowRestrictedPeerCIDRs {
if _, ipnet, err := net.ParseCIDR(cidr); err == nil {
if ipnet.Contains(peerIP) {
allowed = true
break
}
for _, ipnet := range allowRestrictedPeerCIDRs {
if ipnet.Contains(peerIP) {
allowed = true
break
}
}
if !allowed {
@@ -120,11 +143,9 @@ func NewTurnServer(conf *config.Config, authHandler turn.AuthHandler, standalone
// if allowed, check deny list for overrides
}
for _, cidr := range turnConf.DenyPeerCIDRs {
if _, ipnet, err := net.ParseCIDR(cidr); err == nil {
if ipnet.Contains(peerIP) {
return false
}
for _, ipnet := range denyPeerCIDRs {
if ipnet.Contains(peerIP) {
return false
}
}
@@ -206,6 +227,8 @@ func NewTURNAuthHandler(keyProvider auth.KeyProvider) *TURNAuthHandler {
}
func (h *TURNAuthHandler) CreateUsername(apiKey string, pID livekit.ParticipantID, ttlSeconds int) (string, int64) {
// clamp defensively: non-positive TTLs fall back to the default and overflowing ones are capped
ttlSeconds, _ = config.ClampTURNTTLSeconds(ttlSeconds)
expiry := time.Now().Add(time.Duration(ttlSeconds) * time.Second).Unix()
return base62.EncodeToString(fmt.Appendf(nil, "%s|%s|%d", apiKey, pID, expiry)), expiry
}
+74 -2
View File
@@ -18,6 +18,7 @@ import (
"fmt"
"net"
"testing"
"time"
"github.com/jxskiss/base62"
"github.com/pion/stun/v3"
@@ -26,6 +27,8 @@ import (
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/livekit/livekit-server/pkg/config"
)
const (
@@ -75,7 +78,8 @@ func TestTURNAuthHandler_HandleAuth_ExpiredAllocateRejected(t *testing.T) {
h := newTestTurnAuthHandler()
pID := livekit.ParticipantID("PA_expired_alloc")
username, _ := h.CreateUsername(turnTestAPIKey, pID, -60)
expiry := time.Now().Add(-time.Minute).Unix()
username := base62.EncodeToString(fmt.Appendf(nil, "%s|%s|%d", turnTestAPIKey, pID, expiry))
_, _, ok := h.HandleAuth(&turn.RequestAttributes{
Username: username,
Realm: LivekitRealm,
@@ -89,7 +93,8 @@ func TestTURNAuthHandler_HandleAuth_ExpiredNonAllocateAllowed(t *testing.T) {
h := newTestTurnAuthHandler()
pID := livekit.ParticipantID("PA_expired_refresh")
username, expiry := h.CreateUsername(turnTestAPIKey, pID, -60)
expiry := time.Now().Add(-time.Minute).Unix()
username := base62.EncodeToString(fmt.Appendf(nil, "%s|%s|%d", turnTestAPIKey, pID, expiry))
// CreatePassword still enforces ErrExpired on its own, but the server hands
// the same key it generated at allocation time — reproduce that by directly
@@ -206,3 +211,70 @@ func TestTURNAuthHandler_CreatePassword_ZeroExpiryRejected(t *testing.T) {
_, err := h.CreatePassword(turnTestAPIKey, pID, 0)
require.ErrorIs(t, err, ErrExpired)
}
func TestParsePeerCIDRs(t *testing.T) {
t.Run("valid entries are compiled", func(t *testing.T) {
nets, err := parsePeerCIDRs("turn.deny_peer_cidrs", []string{"203.0.113.0/24", "10.0.0.0/8"})
require.NoError(t, err)
require.Len(t, nets, 2)
require.True(t, nets[0].Contains(net.ParseIP("203.0.113.5")))
require.False(t, nets[0].Contains(net.ParseIP("203.0.114.5")))
})
t.Run("empty list is fine", func(t *testing.T) {
nets, err := parsePeerCIDRs("turn.deny_peer_cidrs", nil)
require.NoError(t, err)
require.Empty(t, nets)
})
t.Run("invalid entry is rejected with field context", func(t *testing.T) {
_, err := parsePeerCIDRs("turn.deny_peer_cidrs", []string{"203.0.113.0/33"})
require.Error(t, err)
require.Contains(t, err.Error(), "turn.deny_peer_cidrs")
require.Contains(t, err.Error(), "203.0.113.0/33")
})
}
func TestNewTurnServer_InvalidPeerCIDRFailsStartup(t *testing.T) {
for _, tc := range []struct {
name string
mutID func(c *config.Config)
field string
}{
{
name: "invalid deny cidr",
mutID: func(c *config.Config) { c.TURN.DenyPeerCIDRs = []string{"203.0.113.0/33"} },
field: "turn.deny_peer_cidrs",
},
{
name: "invalid allow cidr",
mutID: func(c *config.Config) { c.TURN.AllowRestrictedPeerCIDRs = []string{"not-a-cidr"} },
field: "turn.allow_restricted_peer_cidrs",
},
} {
t.Run(tc.name, func(t *testing.T) {
conf := &config.Config{}
conf.TURN.Enabled = true
conf.TURN.UDPPort = 3478
tc.mutID(conf)
_, err := NewTurnServer(conf, nil, false)
require.Error(t, err)
require.Contains(t, err.Error(), tc.field)
})
}
}
func TestTURNAuthHandler_CreateUsername_TTLClamped(t *testing.T) {
h := newTestTurnAuthHandler()
pID := livekit.ParticipantID("PA_ttl_clamp")
// An overflowing TTL must not wrap into a past expiry; it clamps to the max.
_, overflowExpiry := h.CreateUsername(turnTestAPIKey, pID, 1<<62+1)
require.Greater(t, overflowExpiry, time.Now().Unix())
require.LessOrEqual(t, overflowExpiry, time.Now().Unix()+int64(config.TURNMaxTTLSeconds)+1)
// A non-positive TTL falls back to the default rather than producing a past/wrapped expiry.
_, negativeExpiry := h.CreateUsername(turnTestAPIKey, pID, -1<<40)
require.InDelta(t, time.Now().Unix()+int64(config.DefaultTURNTTLSeconds), negativeExpiry, 2)
}