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
+97 -19
View File
@@ -46,12 +46,27 @@ import (
const (
generatedCLIFlagUsage = "generated"
// TURNMaxTTLSeconds is the operational maximum for TURN credential TTLs (24 hours).
// It bounds credential lifetime and prevents time.Duration overflow when multiplying
// by time.Second (values above ~9.2e9 seconds wrap on 64-bit builds).
TURNMaxTTLSeconds = 24 * 60 * 60
// DefaultTURNTTLSeconds is the default TTL for embedded TURN credentials, and the
// fallback used when a configured TTL is <= 0.
DefaultTURNTTLSeconds = 300
// DefaultExternalTURNTTLSeconds is the default TTL applied to external TURN
// (static-auth-secret) credentials when the configured TTL is left at 0.
DefaultExternalTURNTTLSeconds = 14400
)
var (
ErrKeyFileIncorrectPermission = errors.New("key file others permissions must be set to 0")
ErrTURNSecretFileIncorrectPermission = errors.New("turn secret file others permissions must be set to 0")
ErrKeysNotSet = errors.New("one of key-file or keys must be provided")
ErrTURNSecretEmpty = errors.New("turn secret is empty")
ErrTURNServerNoCredentials = errors.New("turn server has no usable credentials: set a non-empty secret/secret_file for dynamic auth, or username and credential for static auth")
)
type Config struct {
@@ -174,7 +189,8 @@ type TURNServer struct {
// File containing the secret
SecretFile string `yaml:"secret_file,omitempty"`
// TTL is the time-to-live in seconds for generated credentials when using Secret.
// Defaults to 14400 seconds (4 hours) if not specified
// Defaults to 14400 seconds (4 hours) when 0. Negative values fall back to the 5m
// default and large values are capped at TURNMaxTTLSeconds.
TTL int `yaml:"ttl,omitempty"`
}
@@ -252,7 +268,8 @@ type TURNConfig struct {
RelayPortRangeEnd uint16 `yaml:"relay_range_end,omitempty"`
ExternalTLS bool `yaml:"external_tls,omitempty"`
BindAddresses []string `yaml:"bind_addresses,omitempty"`
// TTL of the TURN credentials in seconds - defaults to 300
// TTL of the TURN credentials in seconds - defaults to 300. Values <= 0 fall back to the
// 300s (5m) default and large values are capped at TURNMaxTTLSeconds.
TTLSeconds int `yaml:"ttl_seconds,omitempty"`
// list of restricted peer CIDRs (loopback, link-local (unicast, multicast), multicast, private, unspecified) to allow access to.
// By default (i. e. empty list), all restricted peer CIDRs are denied access.
@@ -521,7 +538,7 @@ var DefaultConfig = Config{
TURN: TURNConfig{
Enabled: false,
BindAddresses: []string{"0.0.0.0"},
TTLSeconds: 300,
TTLSeconds: DefaultTURNTTLSeconds,
},
NodeSelector: NodeSelectorConfig{
Kind: "any",
@@ -580,6 +597,8 @@ func NewConfig(confString string, strictMode bool, c *cli.Command, baseFlags []c
return nil, fmt.Errorf("could not validate RTC config: %v", err)
}
conf.NormalizeTURNTTLs()
// expand env vars in filenames
file, err := homedir.Expand(os.ExpandEnv(conf.KeyFile))
if err != nil {
@@ -734,30 +753,89 @@ func (conf *Config) ValidateKeys() error {
func (conf *Config) LoadTURNSecrets() error {
var otherFilter os.FileMode = 0o007
for i, s := range conf.RTC.TURNServers {
if s.SecretFile == "" {
continue
}
if s.Secret != "" {
// trim first so a blank inline secret falls back to secret_file rather than being treated as set
inlineSecret := strings.TrimSpace(s.Secret)
switch {
case s.SecretFile != "" && inlineSecret != "":
logger.Warnw("both secret and secret_file are set for TURN server, the hardcoded secret will be used", nil,
"host", s.Host, "port", s.Port)
continue
conf.RTC.TURNServers[i].Secret = inlineSecret
case s.SecretFile != "":
st, err := os.Stat(s.SecretFile)
if err != nil {
return err
}
if st.Mode().Perm()&otherFilter != 0o000 {
return ErrTURNSecretFileIncorrectPermission
}
data, err := os.ReadFile(s.SecretFile)
if err != nil {
return fmt.Errorf("reading turn secret file %q: %w", s.SecretFile, err)
}
secret := strings.TrimSpace(string(data))
if secret == "" {
return fmt.Errorf("turn server %q secret file %q: %w", s.Host, s.SecretFile, ErrTURNSecretEmpty)
}
conf.RTC.TURNServers[i].Secret = secret
default:
conf.RTC.TURNServers[i].Secret = inlineSecret
}
st, err := os.Stat(s.SecretFile)
if err != nil {
return err
// validate credential mode as an explicit union rather than inferring it from a
// post-load empty secret (which would silently fall back to static credentials)
s := conf.RTC.TURNServers[i]
hasDynamic := s.Secret != ""
hasStatic := s.Username != "" && s.Credential != ""
if !hasDynamic && !hasStatic {
return fmt.Errorf("turn server %q: %w", s.Host, ErrTURNServerNoCredentials)
}
if st.Mode().Perm()&otherFilter != 0o000 {
return ErrTURNSecretFileIncorrectPermission
}
data, err := os.ReadFile(s.SecretFile)
if err != nil {
return fmt.Errorf("reading turn secret file %q: %w", s.SecretFile, err)
}
conf.RTC.TURNServers[i].Secret = strings.TrimSpace(string(data))
}
return nil
}
// ClampTURNTTLSeconds bounds a TURN credential TTL to [DefaultTURNTTLSeconds, TURNMaxTTLSeconds]:
// non-positive values (which would otherwise produce already-expired credentials) fall back to
// the 5m default and overflowing values clamp to the max. The second return value reports whether
// the input was out of range.
func ClampTURNTTLSeconds(ttlSeconds int) (int, bool) {
switch {
case ttlSeconds <= 0:
return DefaultTURNTTLSeconds, true
case ttlSeconds > TURNMaxTTLSeconds:
return TURNMaxTTLSeconds, true
default:
return ttlSeconds, false
}
}
// NormalizeTURNTTLs clamps configured TURN TTLs to the safe range, warning on any
// adjustment. Safe to call more than once.
func (conf *Config) NormalizeTURNTTLs() {
if clamped, changed := ClampTURNTTLSeconds(conf.TURN.TTLSeconds); changed {
logger.Warnw(
"turn.ttl_seconds out of range, using safe value", nil,
"configured", conf.TURN.TTLSeconds,
"clamped", clamped,
"max", TURNMaxTTLSeconds,
)
conf.TURN.TTLSeconds = clamped
}
for i := range conf.RTC.TURNServers {
// external TTL of 0 means "use the default", so only cap the upper bound here;
// non-positive values fall back to the default when credentials are generated
if ttl := conf.RTC.TURNServers[i].TTL; ttl > TURNMaxTTLSeconds {
logger.Warnw(
"turn_servers ttl out of range, using safe value", nil,
"host", conf.RTC.TURNServers[i].Host,
"configured", ttl,
"clamped", TURNMaxTTLSeconds,
"max", TURNMaxTTLSeconds,
)
conf.RTC.TURNServers[i].TTL = TURNMaxTTLSeconds
}
}
}
func GenerateCLIFlags(existingFlags []cli.Flag, hidden bool) ([]cli.Flag, error) {
defaultConfig := &DefaultConfig
flags := make([]cli.Flag, 0)
+124
View File
@@ -15,6 +15,8 @@
package config
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
@@ -83,3 +85,125 @@ func TestGeneratedFlags(t *testing.T) {
func TestYAMLTag(t *testing.T) {
require.NoError(t, configtest.CheckYAMLTags(Config{}))
}
func TestClampTURNTTLSeconds(t *testing.T) {
cases := []struct {
name string
in int
want int
changed bool
}{
{"negative falls back to default", -1, DefaultTURNTTLSeconds, true},
{"large negative falls back to default", -1 << 40, DefaultTURNTTLSeconds, true},
{"zero falls back to default", 0, DefaultTURNTTLSeconds, true},
{"in range preserved", 600, 600, false},
{"max preserved", TURNMaxTTLSeconds, TURNMaxTTLSeconds, false},
{"over max clamps to max", TURNMaxTTLSeconds + 1, TURNMaxTTLSeconds, true},
{"overflowing value clamps to max", 1<<62 + 1, TURNMaxTTLSeconds, true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, changed := ClampTURNTTLSeconds(c.in)
require.Equal(t, c.want, got)
require.Equal(t, c.changed, changed)
})
}
}
func TestNormalizeTURNTTLs(t *testing.T) {
conf, err := NewConfig("", true, nil, nil)
require.NoError(t, err)
conf.TURN.TTLSeconds = -5
conf.RTC.TURNServers = []TURNServer{
{Host: "over", TTL: TURNMaxTTLSeconds + 100},
{Host: "negative", TTL: -1},
{Host: "default", TTL: 0},
{Host: "ok", TTL: 600},
}
conf.NormalizeTURNTTLs()
// embedded TTL <= 0 falls back to the 5m default
require.Equal(t, DefaultTURNTTLSeconds, conf.TURN.TTLSeconds)
// external TTLs: only the upper bound is capped at load; 0/negative keep their
// "use the default" meaning and are resolved when credentials are generated
require.Equal(t, TURNMaxTTLSeconds, conf.RTC.TURNServers[0].TTL)
require.Equal(t, -1, conf.RTC.TURNServers[1].TTL)
require.Equal(t, 0, conf.RTC.TURNServers[2].TTL)
require.Equal(t, 600, conf.RTC.TURNServers[3].TTL)
}
func TestNewConfigNormalizesTURNTTL(t *testing.T) {
const content = `turn:
ttl_seconds: -10`
conf, err := NewConfig(content, true, nil, nil)
require.NoError(t, err)
require.Equal(t, DefaultTURNTTLSeconds, conf.TURN.TTLSeconds)
}
func writeSecretFile(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "secret")
require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
return path
}
func TestLoadTURNSecrets(t *testing.T) {
t.Run("empty secret file is rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", SecretFile: writeSecretFile(t, "")}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNSecretEmpty)
})
t.Run("whitespace-only secret file is rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", SecretFile: writeSecretFile(t, " \n\t ")}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNSecretEmpty)
})
t.Run("valid secret file is loaded and trimmed", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", SecretFile: writeSecretFile(t, " topsecret\n")}}
require.NoError(t, conf.LoadTURNSecrets())
require.Equal(t, "topsecret", conf.RTC.TURNServers[0].Secret)
})
t.Run("inline whitespace secret without static creds is rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Secret: " "}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNServerNoCredentials)
})
t.Run("no credentials at all is rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h"}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNServerNoCredentials)
})
t.Run("static credentials are accepted", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Username: "u", Credential: "c"}}
require.NoError(t, conf.LoadTURNSecrets())
})
t.Run("partial static credentials are rejected", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Username: "u"}}
require.ErrorIs(t, conf.LoadTURNSecrets(), ErrTURNServerNoCredentials)
})
t.Run("inline secret takes precedence and is trimmed", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Secret: " inline ", SecretFile: writeSecretFile(t, "fromfile")}}
require.NoError(t, conf.LoadTURNSecrets())
require.Equal(t, "inline", conf.RTC.TURNServers[0].Secret)
})
t.Run("blank inline secret falls back to secret file", func(t *testing.T) {
conf := &Config{}
conf.RTC.TURNServers = []TURNServer{{Host: "h", Secret: " ", SecretFile: writeSecretFile(t, "fromfile")}}
require.NoError(t, conf.LoadTURNSecrets())
require.Equal(t, "fromfile", conf.RTC.TURNServers[0].Secret)
})
}