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.HostKey
@@ -13,6 +13,8 @@ import java.security.MessageDigest
import java.util.Base64
import java.util.Properties
private const val CONNECT_TIMEOUT_MS = 5000
class SSHManager {
@Volatile var lastSeenFingerprint: String? = null
@@ -23,62 +25,7 @@ class SSHManager {
knownFingerprint: String? = null,
sshKey: String = "",
execTimeoutMs: Int = 30_000
): String = withContext(Dispatchers.IO) {
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()
}
}
): String = exec(ip, port, user, pass, command, null, knownFingerprint, sshKey, execTimeoutMs)
suspend fun executeWithStdin(
ip: String, port: Int, user: String, pass: String,
@@ -86,55 +33,79 @@ class SSHManager {
knownFingerprint: String? = null,
sshKey: String = "",
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) {
val tofu = TofuHostKeyRepository(knownFingerprint)
var tempSession: Session? = null
var session: 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)
tempSession.timeout = execTimeoutMs
session = connectSession(ip, port, user, pass, sshKey, tofu)
lastSeenFingerprint = verifyConnectedFingerprint(knownFingerprint, tofu.capturedFingerprint)
session.timeout = execTimeoutMs
runCommand(session, command, stdin, execTimeoutMs)
} catch (e: Exception) {
mitmOrError(e, tofu, knownFingerprint)
} finally {
session?.disconnect()
}
}
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
val sanitized = command.replace("\r\n", "\n").replace("\r", "\n")
channel.setCommand("exec 2>&1\n$sanitized")
val stdinLf = stdin.replace("\r\n", "\n").replace("\r", "\n")
channel.inputStream = ByteArrayInputStream(stdinLf.toByteArray(Charsets.UTF_8))
private fun runCommand(
session: Session, command: String, stdin: String?, execTimeoutMs: Int
): String {
val channel = session.openChannel("exec") as ChannelExec
// 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
channel.connect(execTimeoutMs)
val output = inStream.bufferedReader().use { reader ->
buildString {
var line: String?
while (reader.readLine().also { line = it } != null) {
append(line).append("\n")
}
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" +
}
channel.disconnect()
return output.trim()
}
private fun mitmOrError(e: Exception, tofu: TofuHostKeyRepository, knownFingerprint: String?): String {
val isMitm = tofu.capturedFingerprint != null &&
knownFingerprint != null &&
tofu.capturedFingerprint != knownFingerprint
return if (isMitm) {
"ERROR: Отпечаток сервера изменился - возможна MITM-атака\n" +
"Ожидался: $knownFingerprint\n" +
"Получен: ${tofu.capturedFingerprint}"
} else {
"ERROR: ${e.message}"
}
} finally {
tempSession?.disconnect()
} else {
"ERROR: ${e.message}"
}
}
@@ -150,17 +121,38 @@ class SSHManager {
}
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"
return withTrailingNl.toByteArray(Charsets.UTF_8)
}
}
/**
* TOFU (Trust On First Use) репозиторий хостов.
* null = первое подключение, несовпадение = CHANGED (JSchException).
*/
private class TofuHostKeyRepository(
private fun String.toLf(): String = replace("\r\n", "\n").replace("\r", "\n")
internal fun configureTofuHostKeyChecking(
session: Session,
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?
) : HostKeyRepository {
@@ -170,9 +162,9 @@ private class TofuHostKeyRepository(
override fun check(host: String, key: ByteArray): Int {
capturedFingerprint = sha256Fingerprint(key)
return when {
knownFingerprint == null -> HostKeyRepository.OK
knownFingerprint == null -> 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)
}
}
@@ -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)
}
}
}