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)