security: шифрование SSH-секретов, TOFU для хост-ключей, исключение из бэкапа

This commit is contained in:
samosvalishe committed 2026-03-29 01:02:53 +03:00
1 parent 76b1e22850
commit d276d2fa9e
6 files changed
+151 -39

No files matched your search

+1
View File
@@ -57,6 +57,7 @@ kotlin {
dependencies { dependencies {
implementation("com.github.mwiede:jsch:2.27.9") implementation("com.github.mwiede:jsch:2.27.9")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") 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.core.ktx)
implementation(libs.androidx.appcompat) implementation(libs.androidx.appcompat)
@@ -1,28 +1,51 @@
package com.freeturn.app package com.freeturn.app
import com.jcraft.jsch.ChannelExec import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.HostKey
import com.jcraft.jsch.HostKeyRepository
import com.jcraft.jsch.JSch import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session import com.jcraft.jsch.Session
import com.jcraft.jsch.UserInfo
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.security.MessageDigest
import java.util.Base64
import java.util.Properties import java.util.Properties
class SSHManager { class SSHManager {
/** Отпечаток, полученный при последнем вызове executeSilentCommand */
@Volatile var lastSeenFingerprint: String? = null
private set
/**
* Выполняет команду по SSH и возвращает вывод.
*
* @param knownFingerprint SHA-256 отпечаток хоста из сохранённых настроек.
* - null → первое подключение, принимаем любой ключ и сохраняем отпечаток
* - строка → проверяем совпадение; при расхождении возвращаем ошибку MITM
*/
suspend fun executeSilentCommand( 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) { ): String = withContext(Dispatchers.IO) {
val tofu = TofuHostKeyRepository(knownFingerprint)
var tempSession: Session? = null var tempSession: Session? = null
try { try {
val jsch = JSch() val jsch = JSch()
tempSession = jsch.getSession(user, ip, port) tempSession = jsch.getSession(user, ip, port)
tempSession.setPassword(pass) tempSession.setPassword(pass)
tempSession.hostKeyRepository = tofu
val config = Properties() val config = Properties()
// StrictHostKeyChecking = "no" нужен чтобы JSch не требовал known_hosts файл;
// реальную проверку выполняет TofuHostKeyRepository
config["StrictHostKeyChecking"] = "no" config["StrictHostKeyChecking"] = "no"
tempSession.setConfig(config) tempSession.setConfig(config)
tempSession.connect(5000) tempSession.connect(5000)
lastSeenFingerprint = tofu.capturedFingerprint
val channel = tempSession.openChannel("exec") as ChannelExec val channel = tempSession.openChannel("exec") as ChannelExec
channel.setCommand(command) channel.setCommand(command)
channel.inputStream = null // не подключать stdin channel.inputStream = null // не подключать stdin
@@ -42,7 +65,17 @@ class SSHManager {
channel.disconnect() channel.disconnect()
output.trim() output.trim()
} catch (e: Exception) { } 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 { } finally {
tempSession?.disconnect() tempSession?.disconnect()
} }
@@ -52,3 +85,40 @@ class SSHManager {
// Все сессии в executeSilentCommand временные и закрываются в finally-блоке // Все сессии в 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<HostKey> = emptyArray()
override fun getHostKey(host: String, type: String): Array<HostKey> = 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)
}
}
@@ -1,13 +1,19 @@
package com.freeturn.app.data package com.freeturn.app.data
import android.content.Context import android.content.Context
import android.content.SharedPreferences
import androidx.datastore.core.DataStore import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.* import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore 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.Flow
import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import java.io.IOException import java.io.IOException
import androidx.core.content.edit
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_prefs") private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_prefs")
@@ -17,7 +23,8 @@ data class SshConfig(
val username: String = "root", val username: String = "root",
val password: String = "", val password: String = "",
val authType: String = "PASSWORD", val authType: String = "PASSWORD",
val sshKey: String = "" val sshKey: String = "",
val hostFingerprint: String = ""
) )
data class ClientConfig( data class ClientConfig(
@@ -37,9 +44,8 @@ class AppPreferences(private val context: Context) {
val SSH_IP = stringPreferencesKey("ssh_ip") val SSH_IP = stringPreferencesKey("ssh_ip")
val SSH_PORT = intPreferencesKey("ssh_port") val SSH_PORT = intPreferencesKey("ssh_port")
val SSH_USER = stringPreferencesKey("ssh_user") val SSH_USER = stringPreferencesKey("ssh_user")
val SSH_PASS = stringPreferencesKey("ssh_pass")
val SSH_AUTH_TYPE = stringPreferencesKey("ssh_auth_type") 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 ONBOARDING_DONE = booleanPreferencesKey("onboarding_done")
val CLIENT_SERVER_ADDR = stringPreferencesKey("client_server_addr") val CLIENT_SERVER_ADDR = stringPreferencesKey("client_server_addr")
val CLIENT_VK_LINK = stringPreferencesKey("client_vk_link") 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 CLIENT_RAW_CMD = stringPreferencesKey("client_raw_cmd")
val PROXY_LISTEN = stringPreferencesKey("proxy_listen") val PROXY_LISTEN = stringPreferencesKey("proxy_listen")
val PROXY_CONNECT = stringPreferencesKey("proxy_connect") 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<SshConfig> = context.dataStore.data val sshConfigFlow: Flow<SshConfig> = context.dataStore.data
@@ -60,9 +84,13 @@ class AppPreferences(private val context: Context) {
ip = prefs[SSH_IP] ?: "", ip = prefs[SSH_IP] ?: "",
port = prefs[SSH_PORT] ?: 22, port = prefs[SSH_PORT] ?: 22,
username = prefs[SSH_USER] ?: "root", 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", 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" } .map { prefs -> prefs[PROXY_CONNECT] ?: "127.0.0.1:40537" }
suspend fun saveSshConfig(config: SshConfig) { 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 -> context.dataStore.edit { prefs ->
prefs[SSH_IP] = config.ip prefs[SSH_IP] = config.ip
prefs[SSH_PORT] = config.port prefs[SSH_PORT] = config.port
prefs[SSH_USER] = config.username prefs[SSH_USER] = config.username
prefs[SSH_PASS] = config.password
prefs[SSH_AUTH_TYPE] = config.authType 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) { suspend fun saveClientConfig(config: ClientConfig) {
context.dataStore.edit { prefs -> context.dataStore.edit { prefs ->
prefs[CLIENT_SERVER_ADDR] = config.serverAddress prefs[CLIENT_SERVER_ADDR] = config.serverAddress
@@ -50,6 +50,9 @@ sealed class ProxyState {
data class Error(val message: String) : ProxyState() data class Error(val message: String) : ProxyState()
} }
/** Возвращает сохранённый отпечаток хоста или null при первом подключении */
private val SshConfig.fp get() = hostFingerprint.ifEmpty { null }
class MainViewModel(application: Application) : AndroidViewModel(application) { class MainViewModel(application: Application) : AndroidViewModel(application) {
private val prefs = AppPreferences(application) private val prefs = AppPreferences(application)
@@ -134,9 +137,14 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
_sshState.value = SshConnectionState.Connecting("Проверка SSH...") _sshState.value = SshConnectionState.Connecting("Проверка SSH...")
val result = sshManager.executeSilentCommand( 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 (result.trim() == "OK") {
// При первом подключении сохраняем отпечаток хоста
if (config.hostFingerprint.isEmpty()) {
sshManager.lastSeenFingerprint?.let { prefs.saveSshFingerprint(it) }
}
HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS) HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS)
_sshState.value = SshConnectionState.Connected(config.ip) _sshState.value = SshConnectionState.Connected(config.ip)
checkServerState(config) checkServerState(config)
@@ -165,7 +173,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
""".trimIndent() """.trimIndent()
viewModelScope.launch { 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.value = if (result.startsWith("ERROR")) {
ServerState.Error(result.removePrefix("ERROR: ")) ServerState.Error(result.removePrefix("ERROR: "))
} else { } else {
@@ -189,7 +198,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
timeout 2 ${'$'}BIN -version 2>&1 | head -1 timeout 2 ${'$'}BIN -version 2>&1 | head -1
""".trimIndent() """.trimIndent()
viewModelScope.launch { 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") } _serverVersion.value = out.trim().takeIf { it.isNotEmpty() && !it.startsWith("ERROR") }
} }
} }
@@ -209,7 +219,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
""".trimIndent() """.trimIndent()
viewModelScope.launch { 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) delay(1000)
checkServerState(cfg) checkServerState(cfg)
} }
@@ -231,7 +242,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
""".trimIndent() """.trimIndent()
viewModelScope.launch { 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) delay(2000)
checkServerState(cfg) checkServerState(cfg)
} }
@@ -250,7 +262,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
""".trimIndent() """.trimIndent()
viewModelScope.launch { 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) delay(2000)
checkServerState(cfg) checkServerState(cfg)
} }
+4 -11
View File
@@ -1,13 +1,6 @@
<?xml version="1.0" encoding="utf-8"?><!-- <?xml version="1.0" encoding="utf-8"?>
Sample backup rules file; uncomment and customize as necessary. <!-- Используется на API < 31. На API 31+ применяется data_extraction_rules.xml -->
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content> <full-backup-content>
<!-- <exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<include domain="sharedpref" path="."/> <exclude domain="sharedpref" path="ProxyPrefs.xml"/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content> </full-backup-content>
+7 -13
View File
@@ -1,19 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!-- <?xml version="1.0" encoding="utf-8"?>
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules> <data-extraction-rules>
<cloud-backup> <cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up. <!-- Зашифрованные SSH-учётные данные (пароль, ключ) -->
<include .../> <exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<exclude .../> <!-- Конфиг прокси содержит VK/Yandex ссылку — не бэкапим -->
--> <exclude domain="sharedpref" path="ProxyPrefs.xml"/>
</cloud-backup> </cloud-backup>
<!--
<device-transfer> <device-transfer>
<include .../> <exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<exclude .../> <exclude domain="sharedpref" path="ProxyPrefs.xml"/>
</device-transfer> </device-transfer>
-->
</data-extraction-rules> </data-extraction-rules>