From d276d2fa9e4b2b2bebe3be1e1d7a14694487a863 Mon Sep 17 00:00:00 2001 From: samosvalishe Date: Sun, 29 Mar 2026 01:02:53 +0300 Subject: [PATCH] =?UTF-8?q?security:=20=D1=88=D0=B8=D1=84=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20SSH-=D1=81=D0=B5=D0=BA=D1=80?= =?UTF-8?q?=D0=B5=D1=82=D0=BE=D0=B2,=20TOFU=20=D0=B4=D0=BB=D1=8F=20=D1=85?= =?UTF-8?q?=D0=BE=D1=81=D1=82-=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=B9,=20?= =?UTF-8?q?=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=B8=D0=B7=20=D0=B1=D1=8D=D0=BA=D0=B0=D0=BF=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/build.gradle.kts | 1 + .../main/java/com/freeturn/app/SSHManager.kt | 74 ++++++++++++++++++- .../com/freeturn/app/data/AppPreferences.kt | 55 ++++++++++++-- .../freeturn/app/viewmodel/MainViewModel.kt | 25 +++++-- app/src/main/res/xml/backup_rules.xml | 17 ++--- .../main/res/xml/data_extraction_rules.xml | 22 ++---- 6 files changed, 153 insertions(+), 41 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 9d85a59..26ff3d1 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -57,6 +57,7 @@ kotlin { dependencies { implementation("com.github.mwiede:jsch:2.27.9") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + implementation("androidx.security:security-crypto:1.1.0-alpha06") implementation(libs.androidx.core.ktx) implementation(libs.androidx.appcompat) diff --git a/app/src/main/java/com/freeturn/app/SSHManager.kt b/app/src/main/java/com/freeturn/app/SSHManager.kt index 85ab768..a4c375c 100644 --- a/app/src/main/java/com/freeturn/app/SSHManager.kt +++ b/app/src/main/java/com/freeturn/app/SSHManager.kt @@ -1,28 +1,51 @@ package com.freeturn.app import com.jcraft.jsch.ChannelExec +import com.jcraft.jsch.HostKey +import com.jcraft.jsch.HostKeyRepository import com.jcraft.jsch.JSch import com.jcraft.jsch.Session +import com.jcraft.jsch.UserInfo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +import java.security.MessageDigest +import java.util.Base64 import java.util.Properties class SSHManager { + /** Отпечаток, полученный при последнем вызове executeSilentCommand */ + @Volatile var lastSeenFingerprint: String? = null + private set + + /** + * Выполняет команду по SSH и возвращает вывод. + * + * @param knownFingerprint SHA-256 отпечаток хоста из сохранённых настроек. + * - null → первое подключение, принимаем любой ключ и сохраняем отпечаток + * - строка → проверяем совпадение; при расхождении возвращаем ошибку MITM + */ suspend fun executeSilentCommand( - ip: String, port: Int, user: String, pass: String, command: String + ip: String, port: Int, user: String, pass: String, command: String, + knownFingerprint: String? = null ): String = withContext(Dispatchers.IO) { + val tofu = TofuHostKeyRepository(knownFingerprint) var tempSession: Session? = null try { val jsch = JSch() tempSession = jsch.getSession(user, ip, port) tempSession.setPassword(pass) + tempSession.hostKeyRepository = tofu val config = Properties() + // StrictHostKeyChecking = "no" нужен чтобы JSch не требовал known_hosts файл; + // реальную проверку выполняет TofuHostKeyRepository config["StrictHostKeyChecking"] = "no" tempSession.setConfig(config) tempSession.connect(5000) + lastSeenFingerprint = tofu.capturedFingerprint + val channel = tempSession.openChannel("exec") as ChannelExec channel.setCommand(command) channel.inputStream = null // не подключать stdin @@ -42,7 +65,17 @@ class SSHManager { channel.disconnect() output.trim() } catch (e: Exception) { - "ERROR: ${e.message}" + // Если отпечаток изменился — конкретное сообщение об угрозе + val isMitm = tofu.capturedFingerprint != null + && knownFingerprint != null + && tofu.capturedFingerprint != knownFingerprint + if (isMitm) { + "ERROR: Отпечаток сервера изменился — возможна MITM-атака\n" + + "Ожидался: $knownFingerprint\n" + + "Получен: ${tofu.capturedFingerprint}" + } else { + "ERROR: ${e.message}" + } } finally { tempSession?.disconnect() } @@ -52,3 +85,40 @@ class SSHManager { // Все сессии в executeSilentCommand временные и закрываются в finally-блоке } } + +/** + * TOFU (Trust On First Use) репозиторий ключей хостов для JSch. + * + * Логика: + * - knownFingerprint == null → первое подключение, принимаем любой ключ + * - knownFingerprint совпадает → ОК + * - knownFingerprint не совпадает → CHANGED, JSch бросает JSchException + */ +private class TofuHostKeyRepository( + private val knownFingerprint: String? +) : HostKeyRepository { + + var capturedFingerprint: String? = null + private set + + override fun check(host: String, key: ByteArray): Int { + capturedFingerprint = sha256Fingerprint(key) + return when { + knownFingerprint == null -> HostKeyRepository.OK + knownFingerprint == capturedFingerprint -> HostKeyRepository.OK + else -> HostKeyRepository.CHANGED + } + } + + override fun getHostKey(): Array = emptyArray() + override fun getHostKey(host: String, type: String): Array = emptyArray() + override fun getKnownHostsRepositoryID(): String = "TOFU" + override fun add(hostkey: HostKey, ui: UserInfo) {} + override fun remove(host: String, type: String) {} + override fun remove(host: String, type: String, key: ByteArray) {} + + private fun sha256Fingerprint(key: ByteArray): String { + val hash = MessageDigest.getInstance("SHA-256").digest(key) + return "SHA256:" + Base64.getEncoder().withoutPadding().encodeToString(hash) + } +} diff --git a/app/src/main/java/com/freeturn/app/data/AppPreferences.kt b/app/src/main/java/com/freeturn/app/data/AppPreferences.kt index 455f97b..1fbbd13 100644 --- a/app/src/main/java/com/freeturn/app/data/AppPreferences.kt +++ b/app/src/main/java/com/freeturn/app/data/AppPreferences.kt @@ -1,13 +1,19 @@ package com.freeturn.app.data import android.content.Context +import android.content.SharedPreferences import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.* import androidx.datastore.preferences.preferencesDataStore +import androidx.security.crypto.EncryptedSharedPreferences +import androidx.security.crypto.MasterKey +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map +import kotlinx.coroutines.withContext import java.io.IOException +import androidx.core.content.edit private val Context.dataStore: DataStore by preferencesDataStore(name = "app_prefs") @@ -17,7 +23,8 @@ data class SshConfig( val username: String = "root", val password: String = "", val authType: String = "PASSWORD", - val sshKey: String = "" + val sshKey: String = "", + val hostFingerprint: String = "" ) data class ClientConfig( @@ -37,9 +44,8 @@ class AppPreferences(private val context: Context) { val SSH_IP = stringPreferencesKey("ssh_ip") val SSH_PORT = intPreferencesKey("ssh_port") val SSH_USER = stringPreferencesKey("ssh_user") - val SSH_PASS = stringPreferencesKey("ssh_pass") val SSH_AUTH_TYPE = stringPreferencesKey("ssh_auth_type") - val SSH_KEY = stringPreferencesKey("ssh_key") + val SSH_HOST_FP = stringPreferencesKey("ssh_host_fp") val ONBOARDING_DONE = booleanPreferencesKey("onboarding_done") val CLIENT_SERVER_ADDR = stringPreferencesKey("client_server_addr") val CLIENT_VK_LINK = stringPreferencesKey("client_vk_link") @@ -51,6 +57,24 @@ class AppPreferences(private val context: Context) { val CLIENT_RAW_CMD = stringPreferencesKey("client_raw_cmd") val PROXY_LISTEN = stringPreferencesKey("proxy_listen") val PROXY_CONNECT = stringPreferencesKey("proxy_connect") + + // Устаревшие ключи — используются только для миграции + private val SSH_PASS_LEGACY = stringPreferencesKey("ssh_pass") + private val SSH_KEY_LEGACY = stringPreferencesKey("ssh_key") + } + + // Шифрованное хранилище для SSH-пароля и ключа (Android Keystore + AES-256) + private val encryptedPrefs: SharedPreferences by lazy { + val masterKey = MasterKey.Builder(context) + .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) + .build() + EncryptedSharedPreferences.create( + context, + "secure_ssh_prefs", + masterKey, + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM + ) } val sshConfigFlow: Flow = context.dataStore.data @@ -60,9 +84,13 @@ class AppPreferences(private val context: Context) { ip = prefs[SSH_IP] ?: "", port = prefs[SSH_PORT] ?: 22, username = prefs[SSH_USER] ?: "root", - password = prefs[SSH_PASS] ?: "", + // Читаем из зашифрованного хранилища; если пусто — берём из DataStore (миграция) + password = encryptedPrefs.getString("ssh_pass", null) + ?: prefs[SSH_PASS_LEGACY] ?: "", authType = prefs[SSH_AUTH_TYPE] ?: "PASSWORD", - sshKey = prefs[SSH_KEY] ?: "" + sshKey = encryptedPrefs.getString("ssh_key", null) + ?: prefs[SSH_KEY_LEGACY] ?: "", + hostFingerprint = prefs[SSH_HOST_FP] ?: "" ) } @@ -94,16 +122,29 @@ class AppPreferences(private val context: Context) { .map { prefs -> prefs[PROXY_CONNECT] ?: "127.0.0.1:40537" } suspend fun saveSshConfig(config: SshConfig) { + // Чувствительные данные — в зашифрованное хранилище + withContext(Dispatchers.IO) { + encryptedPrefs.edit { + putString("ssh_pass", config.password) + .putString("ssh_key", config.sshKey) + } + } + // Остальное — в DataStore; удаляем устаревшие незашифрованные значения context.dataStore.edit { prefs -> prefs[SSH_IP] = config.ip prefs[SSH_PORT] = config.port prefs[SSH_USER] = config.username - prefs[SSH_PASS] = config.password prefs[SSH_AUTH_TYPE] = config.authType - prefs[SSH_KEY] = config.sshKey + prefs[SSH_HOST_FP] = config.hostFingerprint + prefs.remove(SSH_PASS_LEGACY) + prefs.remove(SSH_KEY_LEGACY) } } + suspend fun saveSshFingerprint(fingerprint: String) { + context.dataStore.edit { prefs -> prefs[SSH_HOST_FP] = fingerprint } + } + suspend fun saveClientConfig(config: ClientConfig) { context.dataStore.edit { prefs -> prefs[CLIENT_SERVER_ADDR] = config.serverAddress diff --git a/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt b/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt index 016dff8..dc68f71 100644 --- a/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt +++ b/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt @@ -50,6 +50,9 @@ sealed class ProxyState { data class Error(val message: String) : ProxyState() } +/** Возвращает сохранённый отпечаток хоста или null при первом подключении */ +private val SshConfig.fp get() = hostFingerprint.ifEmpty { null } + class MainViewModel(application: Application) : AndroidViewModel(application) { private val prefs = AppPreferences(application) @@ -134,9 +137,14 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { _sshState.value = SshConnectionState.Connecting("Проверка SSH...") val result = sshManager.executeSilentCommand( - config.ip, config.port, config.username, config.password, "echo OK" + config.ip, config.port, config.username, config.password, "echo OK", + knownFingerprint = config.fp ) if (result.trim() == "OK") { + // При первом подключении сохраняем отпечаток хоста + if (config.hostFingerprint.isEmpty()) { + sshManager.lastSeenFingerprint?.let { prefs.saveSshFingerprint(it) } + } HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS) _sshState.value = SshConnectionState.Connected(config.ip) checkServerState(config) @@ -165,7 +173,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { """.trimIndent() viewModelScope.launch { - val result = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, checkCmd) + val result = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, checkCmd, + knownFingerprint = cfg.fp) _serverState.value = if (result.startsWith("ERROR")) { ServerState.Error(result.removePrefix("ERROR: ")) } else { @@ -189,7 +198,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { timeout 2 ${'$'}BIN -version 2>&1 | head -1 """.trimIndent() viewModelScope.launch { - val out = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, cmd) + val out = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, cmd, + knownFingerprint = cfg.fp) _serverVersion.value = out.trim().takeIf { it.isNotEmpty() && !it.startsWith("ERROR") } } } @@ -209,7 +219,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { """.trimIndent() viewModelScope.launch { - sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script) + sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script, + knownFingerprint = cfg.fp) delay(1000) checkServerState(cfg) } @@ -231,7 +242,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { """.trimIndent() viewModelScope.launch { - sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script) + sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script, + knownFingerprint = cfg.fp) delay(2000) checkServerState(cfg) } @@ -250,7 +262,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { """.trimIndent() viewModelScope.launch { - sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script) + sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script, + knownFingerprint = cfg.fp) delay(2000) checkServerState(cfg) } diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml index 4df9255..3c2e848 100644 --- a/app/src/main/res/xml/backup_rules.xml +++ b/app/src/main/res/xml/backup_rules.xml @@ -1,13 +1,6 @@ - + + - - \ No newline at end of file + + + diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml index 9ee9997..6a6a03d 100644 --- a/app/src/main/res/xml/data_extraction_rules.xml +++ b/app/src/main/res/xml/data_extraction_rules.xml @@ -1,19 +1,13 @@ - + - + + + + - - \ No newline at end of file +