fix(ssh): StrictHostKeyChecking=yes для блокировки MITM

This commit is contained in:
samosvalishe committed 2026-07-14 16:38:03 +03:00
1 parent 0c782c221c
commit ece90902f7
2 files changed
+203 -105

No files matched your search

@@ -1,4 +1,4 @@
package com.freeturn.app.domain.ssh package com.freeturn.app.domain.ssh
import com.jcraft.jsch.ChannelExec import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.HostKey import com.jcraft.jsch.HostKey
@@ -13,6 +13,8 @@ import java.security.MessageDigest
import java.util.Base64 import java.util.Base64
import java.util.Properties import java.util.Properties
private const val CONNECT_TIMEOUT_MS = 5000
class SSHManager { class SSHManager {
@Volatile var lastSeenFingerprint: String? = null @Volatile var lastSeenFingerprint: String? = null
@@ -23,62 +25,7 @@ class SSHManager {
knownFingerprint: String? = null, knownFingerprint: String? = null,
sshKey: String = "", sshKey: String = "",
execTimeoutMs: Int = 30_000 execTimeoutMs: Int = 30_000
): String = withContext(Dispatchers.IO) { ): String = exec(ip, port, user, pass, command, null, knownFingerprint, sshKey, execTimeoutMs)
val tofu = TofuHostKeyRepository(knownFingerprint)
var tempSession: Session? = null
try {
val jsch = JSch()
if (sshKey.isNotBlank()) addKeyIdentity(jsch, sshKey, pass)
tempSession = jsch.getSession(user, ip, port)
if (sshKey.isBlank()) {
tempSession.setPassword(pass)
}
tempSession.hostKeyRepository = tofu
val config = Properties()
config["StrictHostKeyChecking"] = "no"
tempSession.setConfig(config)
tempSession.connect(5000)
// SocketTimeoutException вместо вечного ожидания read().
tempSession.timeout = execTimeoutMs
lastSeenFingerprint = tofu.capturedFingerprint
val channel = tempSession.openChannel("exec") as ChannelExec
// stderr объединяется с stdout для единого ответа управляющего скрипта.
val sanitized = command.replace("\r\n", "\n").replace("\r", "\n")
channel.setCommand("exec 2>&1\n$sanitized")
// JSch требует получить поток до connect().
val inStream = channel.inputStream
channel.connect(execTimeoutMs)
val output = inStream.bufferedReader().use { reader ->
buildString {
var line: String?
while (reader.readLine().also { line = it } != null) {
append(line).append("\n")
}
}
}
channel.disconnect()
output.trim()
} catch (e: Exception) {
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()
}
}
suspend fun executeWithStdin( suspend fun executeWithStdin(
ip: String, port: Int, user: String, pass: String, ip: String, port: Int, user: String, pass: String,
@@ -86,55 +33,79 @@ class SSHManager {
knownFingerprint: String? = null, knownFingerprint: String? = null,
sshKey: String = "", sshKey: String = "",
execTimeoutMs: Int = 180_000 execTimeoutMs: Int = 180_000
): String = exec(ip, port, user, pass, command, stdin, knownFingerprint, sshKey, execTimeoutMs)
private suspend fun exec(
ip: String, port: Int, user: String, pass: String,
command: String, stdin: String?,
knownFingerprint: String?, sshKey: String, execTimeoutMs: Int
): String = withContext(Dispatchers.IO) { ): String = withContext(Dispatchers.IO) {
val tofu = TofuHostKeyRepository(knownFingerprint) val tofu = TofuHostKeyRepository(knownFingerprint)
var tempSession: Session? = null var session: Session? = null
try { try {
val jsch = JSch() session = connectSession(ip, port, user, pass, sshKey, tofu)
if (sshKey.isNotBlank()) addKeyIdentity(jsch, sshKey, pass) lastSeenFingerprint = verifyConnectedFingerprint(knownFingerprint, tofu.capturedFingerprint)
tempSession = jsch.getSession(user, ip, port) session.timeout = execTimeoutMs
if (sshKey.isBlank()) tempSession.setPassword(pass) runCommand(session, command, stdin, execTimeoutMs)
tempSession.hostKeyRepository = tofu } catch (e: Exception) {
val config = Properties() mitmOrError(e, tofu, knownFingerprint)
config["StrictHostKeyChecking"] = "no" } finally {
tempSession.setConfig(config) session?.disconnect()
tempSession.connect(5000) }
tempSession.timeout = execTimeoutMs }
lastSeenFingerprint = tofu.capturedFingerprint private fun connectSession(
ip: String, port: Int, user: String, pass: String,
sshKey: String, tofu: TofuHostKeyRepository
): Session {
val jsch = JSch()
if (sshKey.isNotBlank()) addKeyIdentity(jsch, sshKey, pass)
val session = jsch.getSession(user, ip, port)
if (sshKey.isBlank()) session.setPassword(pass)
configureTofuHostKeyChecking(session, tofu)
try {
session.connect(CONNECT_TIMEOUT_MS)
} catch (e: Exception) {
session.disconnect()
throw e
}
return session
}
val channel = tempSession.openChannel("exec") as ChannelExec private fun runCommand(
val sanitized = command.replace("\r\n", "\n").replace("\r", "\n") session: Session, command: String, stdin: String?, execTimeoutMs: Int
channel.setCommand("exec 2>&1\n$sanitized") ): String {
val stdinLf = stdin.replace("\r\n", "\n").replace("\r", "\n") val channel = session.openChannel("exec") as ChannelExec
channel.inputStream = ByteArrayInputStream(stdinLf.toByteArray(Charsets.UTF_8)) // stderr объединяется с stdout для единого ответа управляющего скрипта.
channel.setCommand("exec 2>&1\n${command.toLf()}")
if (stdin != null) {
channel.inputStream = ByteArrayInputStream(stdin.toLf().toByteArray(Charsets.UTF_8))
}
val inStream = channel.inputStream val inStream = channel.inputStream
channel.connect(execTimeoutMs) channel.connect(execTimeoutMs)
val output = inStream.bufferedReader().use { reader ->
val output = inStream.bufferedReader().use { reader -> buildString {
buildString { var line: String?
var line: String? while (reader.readLine().also { line = it } != null) {
while (reader.readLine().also { line = it } != null) { append(line).append("\n")
append(line).append("\n")
}
} }
} }
channel.disconnect() }
output.trim() channel.disconnect()
} catch (e: Exception) { return output.trim()
val isMitm = tofu.capturedFingerprint != null }
&& knownFingerprint != null
&& tofu.capturedFingerprint != knownFingerprint private fun mitmOrError(e: Exception, tofu: TofuHostKeyRepository, knownFingerprint: String?): String {
if (isMitm) { val isMitm = tofu.capturedFingerprint != null &&
"ERROR: Отпечаток сервера изменился - возможна MITM-атака\n" + knownFingerprint != null &&
tofu.capturedFingerprint != knownFingerprint
return if (isMitm) {
"ERROR: Отпечаток сервера изменился - возможна MITM-атака\n" +
"Ожидался: $knownFingerprint\n" + "Ожидался: $knownFingerprint\n" +
"Получен: ${tofu.capturedFingerprint}" "Получен: ${tofu.capturedFingerprint}"
} else { } else {
"ERROR: ${e.message}" "ERROR: ${e.message}"
}
} finally {
tempSession?.disconnect()
} }
} }
@@ -150,17 +121,38 @@ class SSHManager {
} }
private fun normalizePrivateKey(raw: String): ByteArray { private fun normalizePrivateKey(raw: String): ByteArray {
val lf = raw.replace("\r\n", "\n").replace("\r", "\n").trim() val lf = raw.toLf().trim()
val withTrailingNl = if (lf.endsWith("\n")) lf else "$lf\n" val withTrailingNl = if (lf.endsWith("\n")) lf else "$lf\n"
return withTrailingNl.toByteArray(Charsets.UTF_8) return withTrailingNl.toByteArray(Charsets.UTF_8)
} }
} }
/** private fun String.toLf(): String = replace("\r\n", "\n").replace("\r", "\n")
* TOFU (Trust On First Use) репозиторий хостов.
* null = первое подключение, несовпадение = CHANGED (JSchException). internal fun configureTofuHostKeyChecking(
*/ session: Session,
private class TofuHostKeyRepository( repository: TofuHostKeyRepository
) {
session.hostKeyRepository = repository
session.setConfig(Properties().apply {
setProperty("StrictHostKeyChecking", "yes")
})
}
internal fun verifyConnectedFingerprint(
knownFingerprint: String?,
capturedFingerprint: String?
): String {
val received = checkNotNull(capturedFingerprint) {
"SSH-сервер не предоставил ключ для проверки"
}
check(knownFingerprint == null || knownFingerprint == received) {
"Отпечаток SSH-сервера изменился"
}
return received
}
internal class TofuHostKeyRepository(
private val knownFingerprint: String? private val knownFingerprint: String?
) : HostKeyRepository { ) : HostKeyRepository {
@@ -170,9 +162,9 @@ private class TofuHostKeyRepository(
override fun check(host: String, key: ByteArray): Int { override fun check(host: String, key: ByteArray): Int {
capturedFingerprint = sha256Fingerprint(key) capturedFingerprint = sha256Fingerprint(key)
return when { return when {
knownFingerprint == null -> HostKeyRepository.OK knownFingerprint == null -> HostKeyRepository.OK
knownFingerprint == capturedFingerprint -> HostKeyRepository.OK knownFingerprint == capturedFingerprint -> HostKeyRepository.OK
else -> HostKeyRepository.CHANGED else -> HostKeyRepository.CHANGED
} }
} }
@@ -188,4 +180,3 @@ private class TofuHostKeyRepository(
return "SHA256:" + Base64.getEncoder().withoutPadding().encodeToString(hash) return "SHA256:" + Base64.getEncoder().withoutPadding().encodeToString(hash)
} }
} }
@@ -0,0 +1,107 @@
package com.freeturn.app.domain.ssh
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchChangedHostKeyException
import com.jcraft.jsch.Session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.lang.reflect.InvocationTargetException
class SshHostKeySecurityTest {
@Test
fun firstKeyIsTrustedAndCaptured() {
val repository = TofuHostKeyRepository(knownFingerprint = null)
val session = configuredSession(repository)
invokeJschHostCheck(session, HOST_KEY)
assertEquals(FINGERPRINT, repository.capturedFingerprint)
}
@Test
fun knownKeyIsTrustedAgain() {
val repository = TofuHostKeyRepository(FINGERPRINT)
val session = configuredSession(repository)
invokeJschHostCheck(session, HOST_KEY)
assertEquals(FINGERPRINT, repository.capturedFingerprint)
}
@Test
fun changedKeyIsRejectedAtPreAuthenticationHostCheck() {
val repository = TofuHostKeyRepository(FINGERPRINT)
val session = configuredSession(repository)
val error = assertThrows(InvocationTargetException::class.java) {
invokeJschHostCheck(session, CHANGED_HOST_KEY)
}
assertEquals(JSchChangedHostKeyException::class.java, error.cause?.javaClass)
assertEquals(CHANGED_FINGERPRINT, repository.capturedFingerprint)
}
@Test
fun tofuConfigurationUsesStrictHostKeyChecking() {
val session = configuredSession(TofuHostKeyRepository(null))
assertEquals("yes", session.getConfig("StrictHostKeyChecking"))
}
@Test
fun connectedFingerprintIsCheckedBeforeExecChannelIsOpened() {
assertEquals(FINGERPRINT, verifyConnectedFingerprint(null, FINGERPRINT))
assertEquals(FINGERPRINT, verifyConnectedFingerprint(FINGERPRINT, FINGERPRINT))
assertThrows(IllegalStateException::class.java) {
verifyConnectedFingerprint(FINGERPRINT, CHANGED_FINGERPRINT)
}
assertThrows(IllegalStateException::class.java) {
verifyConnectedFingerprint(FINGERPRINT, null)
}
}
private fun configuredSession(repository: TofuHostKeyRepository): Session =
JSch().getSession("user", HOST, 22).also {
configureTofuHostKeyChecking(it, repository)
}
private fun invokeJschHostCheck(session: Session, key: ByteArray) {
val method = Session::class.java.getDeclaredMethod(
"doCheckHostKey",
String::class.java,
String::class.java,
String::class.java,
String::class.java,
ByteArray::class.java
)
method.isAccessible = true
method.invoke(session, HOST, "ssh-ed25519", "unused", "ssh-ed25519", key)
}
private companion object {
const val HOST = "server.example"
val HOST_KEY = ed25519HostKey(0x11)
val CHANGED_HOST_KEY = ed25519HostKey(0x22)
val FINGERPRINT = fingerprint(0x11)
val CHANGED_FINGERPRINT = fingerprint(0x22)
fun ed25519HostKey(fill: Int): ByteArray = ByteArrayOutputStream().use { output ->
output.writeSshString("ssh-ed25519".toByteArray())
output.writeSshString(ByteArray(32) { fill.toByte() })
output.toByteArray()
}
fun fingerprint(fill: Int): String = TofuHostKeyRepository(null).let { repository ->
repository.check(HOST, ed25519HostKey(fill))
checkNotNull(repository.capturedFingerprint)
}
fun ByteArrayOutputStream.writeSshString(value: ByteArray) {
write(byteArrayOf(0, 0, 0, value.size.toByte()))
write(value)
}
}
}