refactor(obf): локальная генерация obf-ключа вместо SSH

Ключ — просто 32 случайных байта, генерим SecureRandom на клиенте.
Команда gen-obf-key и SSH round-trip выпилены. Кнопка regen теперь
заполняет черновик, рестарт — по общей кнопке «Применить».
This commit is contained in:
samosvalishe committed 2026-06-11 02:44:15 +03:00
1 parent 82234c204f
commit 4f7e1f7c97
8 files changed
+36 -105

No files matched your search

-12
View File
@@ -592,17 +592,6 @@ cmd_logs() {
trap - EXIT trap - EXIT
} }
cmd_gen_obf_key() {
local bin key
bin=$(binpath)
[ -x "$bin" ] || die "server binary not installed"
key=$("$bin" -gen-obf-key 2>/dev/null | grep -oE '[0-9a-fA-F]{64}' | head -n1)
[ -n "$key" ] || die "binary did not return obf-key"
emit OBFKEY "$key"
echo "RESULT=ok"
trap - EXIT
}
main() { main() {
[ $# -ge 1 ] || die "no subcommand" [ $# -ge 1 ] || die "no subcommand"
local sub=$1 local sub=$1
@@ -613,7 +602,6 @@ main() {
start) cmd_start "$@" ;; start) cmd_start "$@" ;;
stop) cmd_stop ;; stop) cmd_stop ;;
logs) cmd_logs "$@" ;; logs) cmd_logs "$@" ;;
gen-obf-key) cmd_gen_obf_key ;;
*) die "unknown subcommand: $sub" ;; *) die "unknown subcommand: $sub" ;;
esac esac
} }
@@ -11,6 +11,7 @@ import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import java.io.IOException import java.io.IOException
import java.security.SecureRandom
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_prefs") private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_prefs")
@@ -47,6 +48,10 @@ object ObfProfile {
/** Ключ -obf-key, который примет ядро (DecodeKey). Единая проверка для argv, UI и regen. */ /** Ключ -obf-key, который примет ядро (DecodeKey). Единая проверка для argv, UI и regen. */
fun isValidKey(key: String): Boolean = key.matches(KEY_REGEX) fun isValidKey(key: String): Boolean = key.matches(KEY_REGEX)
/** Новый случайный obf-ключ (32 байта → 64-hex). Ядру важен только формат. */
fun generateKey(): String =
ByteArray(32).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
} }
/** /**
@@ -2,7 +2,6 @@ package com.freeturn.app.domain
import android.content.Context import android.content.Context
import com.freeturn.app.SSHManager import com.freeturn.app.SSHManager
import com.freeturn.app.data.ObfProfile
import com.freeturn.app.data.SshConfig import com.freeturn.app.data.SshConfig
import com.freeturn.app.domain.server.CmdResult import com.freeturn.app.domain.server.CmdResult
import com.freeturn.app.domain.server.ServerCommand import com.freeturn.app.domain.server.ServerCommand
@@ -147,11 +146,7 @@ class SshRepository(
} }
} }
/** /** Идемпотентная установка: скрипт сам решает, скачивать или нет (по sha256). */
* Идемпотентная установка: скрипт сам решает, скачивать или нет (по sha256).
* После downloaded автоматически генерим obf-ключ — он понадобится при
* первом start с включённой обфускацией. Возвращаемое значение — true при успехе.
*/
suspend fun installServer(): InstallOutcome { suspend fun installServer(): InstallOutcome {
val cfg = activeSshConfig ?: return InstallOutcome.Failed("not connected") val cfg = activeSshConfig ?: return InstallOutcome.Failed("not connected")
if (cfg.ip.isEmpty()) return InstallOutcome.Failed("no SSH config") if (cfg.ip.isEmpty()) return InstallOutcome.Failed("no SSH config")
@@ -241,16 +236,6 @@ class SshRepository(
} }
} }
/** Просит сервер сгенерировать новый obf-key. Возвращает hex или null. */
suspend fun generateObfKey(): String? {
val cfg = activeSshConfig ?: return null
if (cfg.ip.isEmpty()) return null
return when (val r = runCmd(cfg, "Генерация obf-key", ServerCommand.GenObfKey)) {
is CmdResult.Err -> null
is CmdResult.Ok -> r.kv["OBFKEY"]?.takeIf { ObfProfile.isValidKey(it) }
}
}
fun updateServerState(state: ServerState) { fun updateServerState(state: ServerState) {
_serverState.value = state _serverState.value = state
} }
@@ -9,7 +9,6 @@ sealed class ServerCommand {
data object Install : ServerCommand() data object Install : ServerCommand()
data class Start(val opts: ServerOptions) : ServerCommand() data class Start(val opts: ServerOptions) : ServerCommand()
data object Stop : ServerCommand() data object Stop : ServerCommand()
data object GenObfKey : ServerCommand()
data class FetchLogs(val lines: Int = 80) : ServerCommand() data class FetchLogs(val lines: Int = 80) : ServerCommand()
fun toArgv(): List<String> = when (this) { fun toArgv(): List<String> = when (this) {
@@ -29,7 +28,6 @@ sealed class ServerCommand {
} }
} }
is Stop -> listOf("stop") is Stop -> listOf("stop")
is GenObfKey -> listOf("gen-obf-key")
is FetchLogs -> listOf("logs", "--tail=$lines") is FetchLogs -> listOf("logs", "--tail=$lines")
} }
} }
@@ -22,8 +22,6 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
@@ -31,7 +29,6 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import com.freeturn.app.R import com.freeturn.app.R
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.CircularWavyProgressIndicator
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.ExtendedFloatingActionButton
@@ -107,10 +104,8 @@ fun ServerManagementScreen(
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle() val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val clientCfg by settingsViewModel.clientConfig.collectAsStateWithLifecycle() val clientCfg by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val serverOpts by serverViewModel.serverOpts.collectAsStateWithLifecycle() val serverOpts by serverViewModel.serverOpts.collectAsStateWithLifecycle()
val isRegen by serverViewModel.isRegeneratingObfKey.collectAsStateWithLifecycle() // Источник серверных черновиков: активный сервер рулит живым конфигом,
// неактивный — снимком by-id (sync OFF, клиент-локально).
// Источник серверных черновиков: активный сервер рулит живым конфигом (его
// обновляет regen на сервере), неактивный — снимком by-id (sync OFF, клиент-локально).
val effClient = if (isActive) clientCfg else (server?.client ?: clientCfg) val effClient = if (isActive) clientCfg else (server?.client ?: clientCfg)
val effServer = if (isActive) serverOpts else (server?.opts ?: serverOpts) val effServer = if (isActive) serverOpts else (server?.opts ?: serverOpts)
@@ -144,12 +139,10 @@ fun ServerManagementScreen(
tcpDraft != effClient.tcpForward || tcpDraft != effClient.tcpForward ||
obfDraft != effServer.obfProfile || obfDraft != effServer.obfProfile ||
keyDraft != effServer.obfKey keyDraft != effServer.obfKey
// Ключ валиден для применения: обфускация выкл, 64 hex, либо пусто при живом SSH // Ключ валиден для применения: обфускация выкл, 64 hex, либо пусто — тогда apply
// и sync ON — только тогда applyServerConfig сгенерит ключ на сервере. Иначе пустой // оставит сохранённый ключ, а если его нет, сгенерирует новый локально.
// ключ блокирует apply: в конфиг уехала бы обфускация без ключа, которую CoreArgs val keyOkForApply = obfDraft == ObfProfile.NONE || keyDraft.isBlank() ||
// молча отбросит при запуске клиента. ObfProfile.isValidKey(keyDraft)
val keyOkForApply = obfDraft == ObfProfile.NONE || ObfProfile.isValidKey(keyDraft) ||
(keyDraft.isBlank() && isConnected && syncOn)
// Плавающий «Применить» виден только когда есть что применять: фиксирует весь черновик // Плавающий «Применить» виден только когда есть что применять: фиксирует весь черновик
// одним рестартом и уходит назад в хаб. Невалидный/занятый стейт — FAB просто прячется // одним рестартом и уходит назад в хаб. Невалидный/занятый стейт — FAB просто прячется
@@ -393,7 +386,8 @@ fun ServerManagementScreen(
} }
} }
SettingsRowDivider() SettingsRowDivider()
// obf-ключ (черновик) + регенерация на сервере (живая SSH-операция). // obf-ключ (черновик); регенерация лишь заполняет черновик —
// рестарт случится по общей кнопке «Применить».
if (obfDraft != ObfProfile.NONE) { if (obfDraft != ObfProfile.NONE) {
SettingsFieldSlot { SettingsFieldSlot {
OutlinedTextField( OutlinedTextField(
@@ -403,8 +397,7 @@ fun ServerManagementScreen(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
readOnly = privacyMode, readOnly = privacyMode,
singleLine = true, singleLine = true,
isError = (keyDraft.isNotBlank() && !ObfProfile.isValidKey(keyDraft)) || isError = keyDraft.isNotBlank() && !ObfProfile.isValidKey(keyDraft),
(keyDraft.isBlank() && !(isConnected && syncOn)),
trailingIcon = { trailingIcon = {
if (effServer.obfKey.isNotBlank() && !privacyMode) { if (effServer.obfKey.isNotBlank() && !privacyMode) {
IconButton(onClick = { IconButton(onClick = {
@@ -421,14 +414,6 @@ fun ServerManagementScreen(
}, },
supportingText = { supportingText = {
when { when {
keyDraft.isBlank() && !isConnected -> Text(
stringResource(R.string.obf_key_manual_hint),
color = MaterialTheme.colorScheme.error
)
keyDraft.isBlank() && !syncOn -> Text(
stringResource(R.string.obf_key_empty_hint),
color = MaterialTheme.colorScheme.error
)
keyDraft.isBlank() -> Text(stringResource(R.string.obf_key_empty_hint)) keyDraft.isBlank() -> Text(stringResource(R.string.obf_key_empty_hint))
!ObfProfile.isValidKey(keyDraft) -> Text( !ObfProfile.isValidKey(keyDraft) -> Text(
stringResource(R.string.obf_key_invalid_hint), stringResource(R.string.obf_key_invalid_hint),
@@ -437,22 +422,15 @@ fun ServerManagementScreen(
} }
} }
) )
if (isConnected && !privacyMode) { if (!privacyMode) {
TextButton( TextButton(
onClick = { onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK) HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
serverViewModel.regenerateObfKey() keyDraft = ObfProfile.generateKey()
}, },
enabled = !isRegen,
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
if (isRegen) { Text(stringResource(R.string.obf_key_regen))
CircularWavyProgressIndicator(modifier = Modifier.size(20.dp))
Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.obf_key_regen_in_progress))
} else {
Text(stringResource(R.string.obf_key_regen))
}
} }
} }
} }
@@ -4,15 +4,14 @@ import android.content.Context
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.ObfProfile
import com.freeturn.app.data.ServerOpts import com.freeturn.app.data.ServerOpts
import com.freeturn.app.data.SshConfig import com.freeturn.app.data.SshConfig
import com.freeturn.app.domain.ProxyOrchestrator import com.freeturn.app.domain.ProxyOrchestrator
import com.freeturn.app.domain.SshRepository import com.freeturn.app.domain.SshRepository
import com.freeturn.app.ui.HapticUtil import com.freeturn.app.ui.HapticUtil
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
@@ -40,9 +39,6 @@ class ServerViewModel(
val sshConfig: StateFlow<SshConfig> = prefs.sshConfigFlow val sshConfig: StateFlow<SshConfig> = prefs.sshConfigFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig())
private val _isRegeneratingObfKey = MutableStateFlow(false)
val isRegeneratingObfKey: StateFlow<Boolean> = _isRegeneratingObfKey.asStateFlow()
/** /**
* Сводный статус АКТИВНОГО сервера для хаба — одна модель из 2 потоков. Server-контекст * Сводный статус АКТИВНОГО сервера для хаба — одна модель из 2 потоков. Server-контекст
* (активность сервера, наличие SSH) добавляет экран. Промежуточные фазы коллапсятся в * (активность сервера, наличие SSH) добавляет экран. Промежуточные фазы коллапсятся в
@@ -97,13 +93,8 @@ class ServerViewModel(
viewModelScope.launch { viewModelScope.launch {
val outcome = sshRepository.installServer() val outcome = sshRepository.installServer()
if (outcome is com.freeturn.app.domain.InstallOutcome.Success) { if (outcome is com.freeturn.app.domain.InstallOutcome.Success) {
if (outcome.stage == "downloaded") { if (outcome.stage == "downloaded" && prefs.serverOptsFlow.first().obfKey.isBlank()) {
if (prefs.serverOptsFlow.first().obfKey.isBlank()) { prefs.updateActiveServer { it.copy(opts = it.opts.copy(obfKey = ObfProfile.generateKey())) }
val key = sshRepository.generateObfKey()
if (!key.isNullOrBlank()) {
prefs.updateActiveServer { it.copy(opts = it.opts.copy(obfKey = key)) }
}
}
} }
if (outcome.needsRestart) { if (outcome.needsRestart) {
startServer() startServer()
@@ -141,20 +132,4 @@ class ServerViewModel(
} }
fun clearSshLog() = sshRepository.clearSshLog() fun clearSshLog() = sshRepository.clearSshLog()
fun regenerateObfKey() {
viewModelScope.launch {
if (_isRegeneratingObfKey.value) return@launch
_isRegeneratingObfKey.value = true
try {
val key = sshRepository.generateObfKey() ?: return@launch
prefs.updateActiveServer { it.copy(opts = it.opts.copy(obfKey = key)) }
if (prefs.clientConfigFlow.first().syncServerSwitches) orchestrator.restartServerIfRunning()
orchestrator.restartProxyIfRunning()
} finally {
_isRegeneratingObfKey.value = false
}
}
}
} }
@@ -228,7 +228,7 @@ class SettingsViewModel(
* Атомарно применяет конфиг сервера (proxy-адреса + tcp-проброс + профиль обфускации * Атомарно применяет конфиг сервера (proxy-адреса + tcp-проброс + профиль обфускации
* + obf-ключ) одной транзакцией и перезапускает сервер/прокси РОВНО один раз — для * + obf-ключ) одной транзакцией и перезапускает сервер/прокси РОВНО один раз — для
* apply-модели «Настроек сервера» (натыкали черновик → Применить). Если включается * apply-модели «Настроек сервера» (натыкали черновик → Применить). Если включается
* обфускация без ключа в sync-режиме, ключ генерируется на сервере (SSH, вне mutex). * обфускация без ключа, ключ генерируется локально.
*/ */
fun applyServerConfig( fun applyServerConfig(
listen: String, listen: String,
@@ -240,12 +240,12 @@ class SettingsViewModel(
viewModelScope.launch { viewModelScope.launch {
val sync = prefs.clientConfigFlow.first().syncServerSwitches val sync = prefs.clientConfigFlow.first().syncServerSwitches
val trimmedKey = obfKey.trim() val trimmedKey = obfKey.trim()
val generatedKey: String? =
if (obfProfile != ObfProfile.NONE && trimmedKey.isBlank() && sync)
sshRepository.generateObfKey()?.takeIf { it.isNotBlank() }
else null
val changed = prefs.updateActiveServer { s -> val changed = prefs.updateActiveServer { s ->
val effKey = trimmedKey.ifBlank { generatedKey ?: s.opts.obfKey } val effKey = trimmedKey.ifBlank {
s.opts.obfKey.ifBlank {
if (obfProfile != ObfProfile.NONE) ObfProfile.generateKey() else ""
}
}
s.copy( s.copy(
proxyListen = listen, proxyListen = listen,
proxyConnect = connect, proxyConnect = connect,
@@ -263,8 +263,8 @@ class SettingsViewModel(
/** /**
* Apply-модель «Настроек сервера» для НЕактивного сервера (sync OFF): серверные * Apply-модель «Настроек сервера» для НЕактивного сервера (sync OFF): серверные
* параметры тут клиент-локальны, поэтому пишем только снимок сервера по id — * параметры тут клиент-локальны, поэтому пишем только снимок сервера по id —
* рантайм (SSH/прокси активного сервера) не трогаем. Без живого SSH obf-ключ * рантайм (SSH/прокси активного сервера) не трогаем. Пустой obf-ключ при
* на сервере не генерим: пустой остаётся пустым (клиент стартует как есть). * включённой обфускации генерируется локально.
*/ */
fun updateServerConfig( fun updateServerConfig(
id: String, id: String,
@@ -276,7 +276,11 @@ class SettingsViewModel(
) { ) {
viewModelScope.launch { viewModelScope.launch {
prefs.updateServer(id) { target -> prefs.updateServer(id) { target ->
val effKey = obfKey.trim().ifBlank { target.opts.obfKey } val effKey = obfKey.trim().ifBlank {
target.opts.obfKey.ifBlank {
if (obfProfile != ObfProfile.NONE) ObfProfile.generateKey() else ""
}
}
target.copy( target.copy(
proxyListen = listen, proxyListen = listen,
proxyConnect = connect, proxyConnect = connect,
+2 -4
View File
@@ -71,9 +71,8 @@
<string name="obf_none">Выкл</string> <string name="obf_none">Выкл</string>
<string name="obf_rtpopus">rtpopus</string> <string name="obf_rtpopus">rtpopus</string>
<string name="provider_vk">VK Calls</string> <string name="provider_vk">VK Calls</string>
<string name="obf_key_empty_hint">Ключ не сгенерирован - нажмите кнопку ниже</string> <string name="obf_key_empty_hint">Пусто - ключ сгенерируется при применении</string>
<string name="obf_key_invalid_hint">Неверный формат - нужны 64 hex-символа</string> <string name="obf_key_invalid_hint">Неверный формат - нужны 64 hex-символа</string>
<string name="obf_key_regen_in_progress">Генерация ключа…</string>
<string name="server_sync_section">Синхронные настройки сервера</string> <string name="server_sync_section">Синхронные настройки сервера</string>
<string name="sync_server_switches">Синхронизировать с сервером</string> <string name="sync_server_switches">Синхронизировать с сервером</string>
<string name="sync_off_banner">Sync с сервером выключен. Следите за совпадением вручную.</string> <string name="sync_off_banner">Sync с сервером выключен. Следите за совпадением вручную.</string>
@@ -94,7 +93,6 @@
<string name="dns_custom_invalid">Часть значений не похожа на DNS-адреса — они будут пропущены</string> <string name="dns_custom_invalid">Часть значений не похожа на DNS-адреса — они будут пропущены</string>
<string name="obf_select_profile_hint">Выберите профиль rtpopus, чтобы задать ключ обфускации.</string> <string name="obf_select_profile_hint">Выберите профиль rtpopus, чтобы задать ключ обфускации.</string>
<string name="obf_key_manual_hint">Без SSH-подключения введите/вставьте 64-hex ключ вручную.</string>
<!-- LogsScreen --> <!-- LogsScreen -->
<string name="logs_title">Логи</string> <string name="logs_title">Логи</string>
@@ -116,7 +114,7 @@
<string name="server_install">Установить</string> <string name="server_install">Установить</string>
<string name="server_update">Обновить</string> <string name="server_update">Обновить</string>
<string name="server_obf_key_label">Obf-ключ (64 hex)</string> <string name="server_obf_key_label">Obf-ключ (64 hex)</string>
<string name="obf_key_regen">Сгенерировать новый ключ на сервере</string> <string name="obf_key_regen">Сгенерировать новый ключ</string>
<string name="start_server">Запустить сервер</string> <string name="start_server">Запустить сервер</string>
<string name="stop_server">Остановить сервер</string> <string name="stop_server">Остановить сервер</string>
<string name="ssh_log_title">SSH-лог</string> <string name="ssh_log_title">SSH-лог</string>