feat(server): настройка пейсинга обфускации

This commit is contained in:
samosvalishe committed 2026-08-25 16:29:08 +03:00
1 parent 92c1afcfb0
commit d16772da88
18 files changed
+121 -11

No files matched your search

@@ -136,7 +136,8 @@ fun ClientConfig.toCoreJson(
obf = CoreConfigJson.Obf(
profile = if (obfOn) srv.obfProfile else ObfProfile.NONE,
key = if (obfOn) srv.obfKey else "",
timingMs = 0,
// Без профиля ядро отвергает ненулевой пейсинг.
timingMs = if (obfOn) srv.obfTimingMs else 0,
),
dns = CoreConfigJson.Dns(mode = dnsMode, servers = dnsServers),
log = CoreConfigJson.Log(debug = debugMode),
@@ -21,6 +21,12 @@ object ObfProfile {
const val RTPOPUS3 = "rtpopus3"
val VALUES = listOf(NONE, RTPOPUS, RTPOPUS2, RTPOPUS3)
// Пейсинг (-obf-timing), мс. 20 = ptime Opus, эталон для мимикрии; выше 60 поток
// уже не похож на живой звонок и упирается в потолок ~1 пакет на интервал.
const val TIMING_OFF = 0
const val TIMING_MAX = 60
const val TIMING_STEP = 5
private val KEY_REGEX = Regex("^[0-9a-fA-F]{64}$")
fun isValidKey(key: String): Boolean = key.matches(KEY_REGEX)
@@ -74,6 +74,7 @@ internal object ServerJson {
put("opts", JSONObject().apply {
put("obfProfile", p.opts.obfProfile)
put("obfKey", p.opts.obfKey)
put("obfTimingMs", p.opts.obfTimingMs)
put("proxyMode", p.opts.proxyMode)
put("kcp", encodeKcp(p.opts.kcp))
})
@@ -137,6 +138,7 @@ internal object ServerJson {
if (it in ObfProfile.VALUES) it else ObfProfile.NONE
},
obfKey = optsO.optString("obfKey", ""),
obfTimingMs = optsO.optInt("obfTimingMs", 0).coerceIn(0, ObfProfile.TIMING_MAX),
proxyMode = optsO.optString("proxyMode", ProxyMode.UDP).let {
if (it in ProxyMode.VALUES) it else ProxyMode.UDP
},
@@ -10,6 +10,8 @@ data class ServerOpts(
val obfProfile: String = ObfProfile.NONE,
/** 64-hex obf-ключ (-obf-key). Должен совпадать на клиенте и сервере. */
val obfKey: String = "",
/** Межпакетная задержка мимикрии (-obf-timing), мс; 0 - выкл. Требует профиля. */
val obfTimingMs: Int = 0,
/** Режим проброса (-mode). Сервер отвергает сессию с другим режимом. */
val proxyMode: String = ProxyMode.UDP,
/** ARQ tcp-режима (-kcp-*); в udp не используется. */
@@ -46,6 +46,7 @@ class ProxyOrchestrator(
kcp = opts.kcp,
obfProfile = if (opts.obfEnabled) opts.obfProfile else "none",
obfKey = if (opts.obfEnabled) opts.obfKey else "",
obfTimingMs = opts.obfTimingMs,
clientId = prefs.ownClientId()
)
}
@@ -59,6 +59,8 @@ sealed class ServerCommand {
if (opts.obfProfile != "none" && opts.obfKey.isNotBlank()) {
add("--obf-profile=${opts.obfProfile}")
add("--obf-key=${opts.obfKey}")
// Пейсинг без профиля ядро отвергает - только внутри этой ветки.
if (opts.obfTimingMs > 0) add("--obf-timing=${opts.obfTimingMs}ms")
}
if (opts.clientId.isNotBlank()) add("--client-id=${opts.clientId}")
}
@@ -96,6 +98,7 @@ data class ServerStartOptions(
val kcp: KcpProfile = KcpProfile.DEFAULT,
val obfProfile: String = "none",
val obfKey: String = "",
val obfTimingMs: Int = 0,
val clientId: String = ""
)
@@ -191,6 +191,7 @@ class SshRepository(
kcp: KcpProfile = KcpProfile.DEFAULT,
obfProfile: String = "none",
obfKey: String = "",
obfTimingMs: Int = 0,
clientId: String = ""
): Boolean = mutex.withLock {
val cfg = activeSshConfig ?: return@withLock false
@@ -207,6 +208,7 @@ class SshRepository(
kcp = kcp,
obfProfile = obfProfile,
obfKey = obfKey,
obfTimingMs = obfTimingMs,
clientId = clientId
)
)
@@ -38,6 +38,7 @@ import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
@@ -100,6 +101,7 @@ fun ServerManagementScreen(
var tcpDraft by rememberSaveable(effServer.tcpMode) { mutableStateOf(effServer.tcpMode) }
var obfDraft by rememberSaveable(effServer.obfProfile) { mutableStateOf(effServer.obfProfile) }
var keyDraft by rememberSaveable(effServer.obfKey) { mutableStateOf(effServer.obfKey) }
var timingDraft by rememberSaveable(effServer.obfTimingMs) { mutableIntStateOf(effServer.obfTimingMs) }
val context = LocalContext.current
@@ -115,7 +117,8 @@ fun ServerManagementScreen(
val configDirty = proxyDirty ||
tcpDraft != effServer.tcpMode ||
obfDraft != effServer.obfProfile ||
keyDraft != effServer.obfKey
keyDraft != effServer.obfKey ||
timingDraft != effServer.obfTimingMs
val keyOkForApply = obfDraft == ObfProfile.NONE || keyDraft.isBlank() ||
ObfProfile.isValidKey(keyDraft)
val addressesOk = HostPort.isValid(listenFull) && HostPort.isValid(proxyConnect)
@@ -131,11 +134,13 @@ fun ServerManagementScreen(
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
// Активный - apply в живой рантайм (один рестарт). Неактивный - пишем только снимок сервера.
val mode = if (tcpDraft) ProxyMode.TCP else ProxyMode.UDP
// Пейсинг без профиля ядро отвергает.
val timing = if (obfDraft == ObfProfile.NONE) 0 else timingDraft
if (isActive) {
settingsViewModel.applyServerConfig(listenFull, proxyConnect, mode, obfDraft, keyDraft)
settingsViewModel.applyServerConfig(listenFull, proxyConnect, mode, obfDraft, keyDraft, timing)
} else {
// !isActive ⇒ serverId != null (см. isActive выше) - smart cast.
settingsViewModel.updateServerConfig(serverId, listenFull, proxyConnect, mode, obfDraft, keyDraft)
settingsViewModel.updateServerConfig(serverId, listenFull, proxyConnect, mode, obfDraft, keyDraft, timing)
}
onBack()
}
@@ -285,6 +290,8 @@ fun ServerManagementScreen(
keyDraft = keyDraft,
onKeyDraft = { keyDraft = it },
savedObfKey = effServer.obfKey,
timingMs = timingDraft,
onTimingMs = { timingDraft = it },
privacyMode = privacyMode,
onCopyKey = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
@@ -293,7 +300,8 @@ fun ServerManagementScreen(
onRegenKey = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
keyDraft = ObfProfile.generateKey()
}
},
onTick = { HapticUtil.perform(context, HapticUtil.Pattern.SELECTION) }
)
}
@@ -29,8 +29,10 @@ import com.freeturn.app.ui.components.SettingsCard
import com.freeturn.app.ui.components.SettingsControlLabel
import com.freeturn.app.ui.components.SettingsFieldSlot
import com.freeturn.app.ui.components.SettingsRowDivider
import com.freeturn.app.ui.components.SettingsSliderRow
import com.freeturn.app.ui.components.UdpTcpSegmented
import com.freeturn.app.ui.util.redact
import kotlin.math.roundToInt
/**
* Синхронные серверные настройки (apply-модель): проброс UDP/TCP, профиль обфускации и
@@ -47,9 +49,12 @@ internal fun ServerSyncCard(
keyDraft: String,
onKeyDraft: (String) -> Unit,
savedObfKey: String,
timingMs: Int,
onTimingMs: (Int) -> Unit,
privacyMode: Boolean,
onCopyKey: () -> Unit,
onRegenKey: () -> Unit
onRegenKey: () -> Unit,
onTick: () -> Unit
) {
SectionLabel(stringResource(R.string.server_sync_section))
SettingsCard {
@@ -107,6 +112,25 @@ internal fun ServerSyncCard(
}
}
}
SettingsRowDivider()
SettingsFieldSlot {
SettingsSliderRow(
valueLabel = if (timingMs == ObfProfile.TIMING_OFF) {
stringResource(R.string.obf_timing_off)
} else {
stringResource(R.string.obf_timing_format, timingMs)
},
hint = stringResource(R.string.obf_timing_hint),
value = timingMs.toFloat(),
valueRange = 0f..ObfProfile.TIMING_MAX.toFloat(),
// Шаг 5 мс: разницу в 1 мс на глаз не отличить, а слайдер дёрганый.
onValueChange = { v ->
val step = ObfProfile.TIMING_STEP
onTimingMs((v / step).roundToInt() * step)
},
onTick = onTick
)
}
} else {
// obfProfile == NONE - подсказка выбрать профиль.
SettingsFieldSlot {
@@ -292,7 +292,8 @@ private fun serverCommandLine(server: Server, privacy: Boolean): String {
proxyMode = server.opts.proxyMode,
kcp = server.opts.kcp,
obfProfile = if (server.opts.obfEnabled) server.opts.obfProfile else ObfProfile.NONE,
obfKey = if (server.opts.obfEnabled) server.opts.obfKey else ""
obfKey = if (server.opts.obfEnabled) server.opts.obfKey else "",
obfTimingMs = server.opts.obfTimingMs
)
// Серверные флаги в форме --flag=value: маскируем хвост после '=' у секретов.
val shown = ServerCommand.Start(opts).toArgv().joinToString(" ") { tok ->
@@ -121,6 +121,7 @@ class ServerViewModel(
kcp = opts.kcp,
obfProfile = if (opts.obfEnabled) opts.obfProfile else "none",
obfKey = if (opts.obfEnabled) opts.obfKey else "",
obfTimingMs = opts.obfTimingMs,
clientId = prefs.ownClientId()
)
}
@@ -338,7 +338,8 @@ class SettingsViewModel(
connect: String,
proxyMode: String,
obfProfile: String,
obfKey: String
obfKey: String,
obfTimingMs: Int
) {
viewModelScope.launch {
val sync = prefs.clientConfigFlow.first().syncServerSwitches
@@ -352,7 +353,12 @@ class SettingsViewModel(
s.copy(
proxyListen = listen,
proxyConnect = connect,
opts = s.opts.copy(proxyMode = proxyMode, obfProfile = obfProfile, obfKey = effKey)
opts = s.opts.copy(
proxyMode = proxyMode,
obfProfile = obfProfile,
obfKey = effKey,
obfTimingMs = obfTimingMs
)
)
}
if (changed) {
@@ -373,7 +379,8 @@ class SettingsViewModel(
connect: String,
proxyMode: String,
obfProfile: String,
obfKey: String
obfKey: String,
obfTimingMs: Int
) {
viewModelScope.launch {
prefs.updateServer(id) { target ->
@@ -385,7 +392,12 @@ class SettingsViewModel(
target.copy(
proxyListen = listen,
proxyConnect = connect,
opts = target.opts.copy(proxyMode = proxyMode, obfProfile = obfProfile, obfKey = effKey)
opts = target.opts.copy(
proxyMode = proxyMode,
obfProfile = obfProfile,
obfKey = effKey,
obfTimingMs = obfTimingMs
)
)
}
}
+3
View File
@@ -207,6 +207,9 @@
<string name="tcp_forward_mode">Режим</string>
<string name="tcp_blocked_by_tunnel">Туннель работает только поверх UDP-проброса</string>
<string name="obf_profile_title">Обфускация</string>
<string name="obf_timing_off">Пейсинг: выкл</string>
<string name="obf_timing_format">Пейсинг: %1$d мс</string>
<string name="obf_timing_hint">Пауза между пакетами на обеих сторонах. 20 мс - как у голосового звонка; чем больше, тем ниже потолок скорости.</string>
<string name="obf_none">Выкл</string>
<string name="obf_rtpopus">rtpopus</string>
<string name="obf_rtpopus2">rtpopus2</string>
@@ -121,6 +121,17 @@ class CoreConfigJsonTest {
assertEquals(key, ok["key"]!!.jsonPrimitive.content)
}
// Пейсинг без профиля ядро отвергает - и с невалидным ключом профиль тоже гаснет.
@Test
fun obfTimingNeedsProfile() {
val key = "a".repeat(64)
val on = parse(base, ServerOpts(obfProfile = ObfProfile.RTPOPUS, obfKey = key, obfTimingMs = 20))
assertEquals(20, on["obf"]!!.jsonObject["timingMs"]!!.jsonPrimitive.content.toInt())
val off = parse(base, ServerOpts(obfTimingMs = 20))
assertEquals(0, off["obf"]!!.jsonObject["timingMs"]!!.jsonPrimitive.content.toInt())
}
@Test
fun magicTurnOnlyWithSwitch() {
val off = parse(base.copy(magicTurn = "turn.example:3478"))["turn"]!!.jsonObject
@@ -1,6 +1,7 @@
package com.freeturn.app.data.server
import com.freeturn.app.data.config.KcpProfile
import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.config.ProxyMode
import org.junit.Assert.assertEquals
import org.junit.Test
@@ -29,6 +30,18 @@ class ServerJsonTest {
assertEquals(KcpProfile.DEFAULT, decoded.opts.kcp)
}
@Test
fun `obf timing round trip and clamp`() {
val srv = Server(name = "s", opts = ServerOpts(obfTimingMs = 20))
assertEquals(20, ServerJson.decodeList(ServerJson.encodeList(listOf(srv))).single().opts.obfTimingMs)
val raw = """[{"id":"1","name":"s","opts":{"obfTimingMs":9000}}]"""
assertEquals(
ObfProfile.TIMING_MAX,
ServerJson.decodeList(raw).single().opts.obfTimingMs
)
}
@Test
fun `unknown mode falls back to udp`() {
val raw = """[{"id":"1","name":"s","opts":{"proxyMode":"quic"}}]"""
+3
View File
@@ -130,6 +130,8 @@ _write_args_file() {
if [ "$ARG_OBF_PROFILE" != "none" ] && [ -n "$ARG_OBF_KEY" ]; then
echo "-obf-profile"; echo "$ARG_OBF_PROFILE"
echo "-obf-key"; echo "$ARG_OBF_KEY"
# Пейсинг без профиля ядро отвергает - только внутри этой ветки.
if [ -n "$ARG_OBF_TIMING" ]; then echo "-obf-timing"; echo "$ARG_OBF_TIMING"; fi
fi
# Авторизация включается только когда владелец передал cid (cmd_start уже
# посадил его в allowlist - иначе lockout самого себя).
@@ -195,6 +197,7 @@ _rt_start_nohup() {
if [ "$ARG_OBF_PROFILE" != "none" ] && [ -n "$ARG_OBF_KEY" ]; then
( umask 077; printf '%s' "$ARG_OBF_KEY" > "$OBFFILE" ); chmod 600 "$OBFFILE"
args+=(-obf-profile "$ARG_OBF_PROFILE" -obf-key "$ARG_OBF_KEY")
[ -n "$ARG_OBF_TIMING" ] && args+=(-obf-timing "$ARG_OBF_TIMING")
fi
( cd "$PREFIX" && nohup "$bin" "${args[@]}" >"$LOGFILE" 2>&1 & echo $! > "$PIDFILE" )
local pid
+4
View File
@@ -5,6 +5,7 @@ ARG_MODE="udp"
ARG_KCP=()
ARG_OBF_PROFILE="none"
ARG_OBF_KEY=""
ARG_OBF_TIMING=""
ARG_TAIL=80
ARG_WG_PORT=""
ARG_WG_ENDPOINT=""
@@ -43,6 +44,9 @@ parse_args() {
--obf-profile=*)
ARG_OBF_PROFILE="${1#*=}"
[[ "$ARG_OBF_PROFILE" =~ ^(none|rtpopus|rtpopus2|rtpopus3)$ ]] || fail bad_arg "bad --obf-profile" ;;
--obf-timing=*)
ARG_OBF_TIMING="${1#*=}"
[[ "$ARG_OBF_TIMING" =~ ^[0-9]{1,5}ms$ ]] || fail bad_arg "bad --obf-timing (need <N>ms)" ;;
--obf-key=*)
ARG_OBF_KEY="${1#*=}"
[[ "$ARG_OBF_KEY" =~ ^[0-9a-fA-F]{64}$ ]] || fail bad_arg "bad --obf-key (need 64 hex)" ;;
+13
View File
@@ -35,6 +35,19 @@ setup() {
[[ "$output" == *'-kcp-acknodelay=false'* ]]
}
@test "run.args: -obf-timing только вместе с профилем" {
ARG_OBF_TIMING="20ms"
_write_args_file
run cat "$ARGSFILE"
[[ "$output" != *"-obf-timing"* ]]
ARG_OBF_PROFILE="rtpopus3"
ARG_OBF_KEY=$(printf 'a%.0s' {1..64})
_write_args_file
run cat "$ARGSFILE"
[[ "$output" == *$'-obf-timing\n20ms'* ]]
}
@test "parse_args: --kcp-interval -> argv-пара" {
parse_args --listen=0.0.0.0:56000 --connect=127.0.0.1:443 --mode=tcp --kcp-interval=40
[ "$ARG_MODE" = "tcp" ]