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
+153 -41

No files matched your search

+1
View File
@@ -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)
@@ -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<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
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<Preferences> 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<SshConfig> = 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
@@ -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)
}
+5 -12
View File
@@ -1,13 +1,6 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
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
-->
<?xml version="1.0" encoding="utf-8"?>
<!-- Используется на API < 31. На API 31+ применяется data_extraction_rules.xml -->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>
<exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<exclude domain="sharedpref" path="ProxyPrefs.xml"/>
</full-backup-content>
+8 -14
View File
@@ -1,19 +1,13 @@
<?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.
-->
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
<!-- Зашифрованные SSH-учётные данные (пароль, ключ) -->
<exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<!-- Конфиг прокси содержит VK/Yandex ссылку — не бэкапим -->
<exclude domain="sharedpref" path="ProxyPrefs.xml"/>
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
<exclude domain="sharedpref" path="secure_ssh_prefs.xml"/>
<exclude domain="sharedpref" path="ProxyPrefs.xml"/>
</device-transfer>
-->
</data-extraction-rules>
</data-extraction-rules>