diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 51232ea..de384b3 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -39,8 +39,8 @@ jobs: "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \ "ndk;$NDK_VERSION" "cmake;$CMAKE_VERSION" "platforms;android-37.0" - - name: OpenSSH (for the SSH interop tests) - run: sudo apt-get install -y -q openssh-client openssh-server && sudo mkdir -p /run/sshd + - name: OpenSSH and PuTTY (for the SSH interop tests) + run: sudo apt-get install -y -q openssh-client openssh-server putty-tools && sudo mkdir -p /run/sshd - name: Build, unit tests, lint run: ./gradlew assembleDebug assembleDebugAndroidTest testDebugUnitTest lintDebug diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/Keys.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/Keys.kt index 83138bc..3ecd171 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ssh/Keys.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/Keys.kt @@ -11,6 +11,7 @@ import net.schmizz.sshj.userauth.keyprovider.KeyPairWrapper import net.schmizz.sshj.userauth.keyprovider.KeyProvider import net.schmizz.sshj.userauth.keyprovider.OpenSSHKeyFile import net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile +import net.schmizz.sshj.userauth.keyprovider.PuTTYKeyFile import net.schmizz.sshj.userauth.password.PasswordFinder import net.schmizz.sshj.userauth.password.Resource import com.hierynomus.sshj.userauth.keyprovider.OpenSSHKeyV1KeyFile @@ -66,8 +67,8 @@ object KeyFormat { } /** - * The app's SSH keys: made here (Ed25519, ECDSA P-256, RSA 3072) or - * imported (OpenSSH's or PKCS#8 PEM, with their passphrase); each private + * The app's SSH keys: made here or imported (OpenSSH's, PuTTY's .ppk or + * PKCS#8 PEM, with their passphrase); each private * key sealed by the [SecretBox] in dir/.key, the list in dir/keys.json. */ class SshKeys(private val dir: File, private val box: SecretBox) { @@ -129,14 +130,17 @@ class SshKeys(private val dir: File, private val box: SecretBox) { override fun shouldRetry(resource: Resource<*>?) = false } val provider: KeyProvider = when { + Ppk.isPpk(text) -> PuTTYKeyFile().apply { init(text, null, finder) } text.contains("BEGIN OPENSSH PRIVATE KEY") -> OpenSSHKeyV1KeyFile().apply { init(text, null, finder) } text.contains("BEGIN") && text.contains("PRIVATE KEY") -> PKCS8KeyFile().apply { init(text, null, finder) } else -> OpenSSHKeyFile().apply { init(text, null, finder) } } - return keep(KeyPair(provider.public, provider.private), name) + // (a .ppk's comment kept as the key's) + return keep(KeyPair(provider.public, provider.private), name, if (Ppk.isPpk(text)) Ppk.comment(text)?.takeIf { it.isNotBlank() } else null) } - private fun keep(pair: KeyPair, name: String, comment: String? = null): SshKey { + private fun keep(given: KeyPair, name: String, comment: String? = null): SshKey { + val pair = withCrt(given) val id = UUID.randomUUID().toString() val sealed = box.seal( JSONObject() @@ -155,6 +159,44 @@ class SshKeys(private val dir: File, private val box: SecretBox) { return k } + /** + * an RSA key given as n and d only (sshj reads PuTTY's that way) made + * whole: its primes found again from n, e and d, so that it can be + * encoded (Android's provider won't encode one without them) + */ + private fun withCrt(kp: KeyPair): KeyPair { + val priv = kp.private as? java.security.interfaces.RSAPrivateKey ?: return kp + if (priv is java.security.interfaces.RSAPrivateCrtKey) return kp + val pub = kp.public as java.security.interfaces.RSAPublicKey + val n = pub.modulus + val e = pub.publicExponent + val d = priv.privateExponent + val one = java.math.BigInteger.ONE + // k = de - 1 = 2^s t; for random g, a square root of 1 other than ±1 among g^t, g^2t, ... splits n + val k = d.multiply(e).subtract(one) + val s = k.lowestSetBit + val t = k.shiftRight(s) + val rnd = java.security.SecureRandom() + var p: java.math.BigInteger? = null + while (p == null) { + val g = java.math.BigInteger(n.bitLength() - 1, rnd).add(java.math.BigInteger.valueOf(2)) + var x = g.modPow(t, n) + for (i in 0 until s) { + val y = x.multiply(x).mod(n) + if (y == one && x != one && x != n.subtract(one)) { + p = x.subtract(one).gcd(n) + break + } + x = y + } + } + val q = n.divide(p) + val spec = java.security.spec.RSAPrivateCrtKeySpec( + n, e, d, p, q, d.mod(p.subtract(one)), d.mod(q.subtract(one)), q.modInverse(p), + ) + return KeyPair(pub, KeyFactory.getInstance("RSA", "BC").generatePrivate(spec)) + } + /** the key's pair, opened: for sshj's authentication */ fun keyPair(id: String): KeyPair { SshSecurity.ensure() @@ -175,6 +217,12 @@ class SshKeys(private val dir: File, private val box: SecretBox) { return KeyGen.openSshPrivate(keyPair(id), comment(k), passphrase) } + /** the private key as PuTTY's .ppk ([version] 3, or 2 for older PuTTY), encrypted with [passphrase] unless it's empty */ + fun exportPpk(id: String, passphrase: String, version: Int = 3): String { + val k = byId(id) ?: throw IllegalArgumentException("no key $id") + return Ppk.write(keyPair(id), comment(k), passphrase, version) + } + /** a new comment on the key's public line (ssh-keygen -c) */ fun setComment(id: String, comment: String) { val clean = comment.replace(Regex("[\\r\\n]"), " ").trim() diff --git a/app/src/main/java/com/neodesktop/dmodem/ssh/Ppk.kt b/app/src/main/java/com/neodesktop/dmodem/ssh/Ppk.kt new file mode 100644 index 0000000..fe5bc71 --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/ssh/Ppk.kt @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.ssh + +import net.schmizz.sshj.common.Buffer +import org.bouncycastle.crypto.generators.Argon2BytesGenerator +import org.bouncycastle.crypto.params.Argon2Parameters +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters +import org.bouncycastle.crypto.util.PrivateKeyFactory +import java.security.KeyPair +import java.security.MessageDigest +import java.security.SecureRandom +import java.security.interfaces.ECPrivateKey +import java.security.interfaces.RSAPrivateCrtKey +import java.util.Base64 +import javax.crypto.Cipher +import javax.crypto.Mac +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * PuTTY's private key files (.ppk), as PuTTYgen writes them: version 3 + * (Argon2id, AES-256-CBC, HMAC-SHA-256; PuTTY 0.75 and on) or version 2 + * (SHA-1, for older PuTTY and the tools that only read it, WinSCP's older + * releases among them). Read back by sshj's PuTTYKeyFile. + */ +object Ppk { + + /** PuTTYgen's Argon2 defaults: 8 MiB, one lane; passes enough for a moment's work */ + data class Argon(val memoryKiB: Int = 8192, val passes: Int = 13, val parallelism: Int = 1) + + fun isPpk(text: String) = text.trimStart().startsWith("PuTTY-User-Key-File-") + + /** the "Comment:" a .ppk carries, if any */ + fun comment(text: String): String? = + text.lineSequence().firstOrNull { it.startsWith("Comment: ") }?.removePrefix("Comment: ")?.trim() + + fun write(kp: KeyPair, comment: String, passphrase: String = "", version: Int = 3, argon: Argon = Argon()): String { + require(version == 2 || version == 3) { "PPK versions 2 and 3 only" } + val alg = KeyFormat.type(kp.public) + val encrypted = passphrase.isNotEmpty() + val encryption = if (encrypted) "aes256-cbc" else "none" + val pub = KeyFormat.blob(kp.public) + var priv = privateBlob(kp) + if (encrypted) { + // padded to the cipher's block, as PuTTY pads it (with the start of the blob's SHA-1) + val pad = (16 - priv.size % 16) % 16 + priv += MessageDigest.getInstance("SHA-1").digest(priv).copyOf(pad) + } + + val headers = StringBuilder() + val cipherKey: ByteArray + val iv: ByteArray + val macKey: ByteArray + val salt = ByteArray(16).also { SecureRandom().nextBytes(it) } + if (version == 3) { + if (encrypted) { + val out = ByteArray(80) + Argon2BytesGenerator().apply { + init( + Argon2Parameters.Builder(Argon2Parameters.ARGON2_id) + .withVersion(Argon2Parameters.ARGON2_VERSION_13) + .withMemoryAsKB(argon.memoryKiB).withIterations(argon.passes) + .withParallelism(argon.parallelism).withSalt(salt).build(), + ) + }.generateBytes(passphrase.toByteArray(), out) + cipherKey = out.copyOfRange(0, 32) + iv = out.copyOfRange(32, 48) + macKey = out.copyOfRange(48, 80) + headers.append("Key-Derivation: Argon2id\n") + headers.append("Argon2-Memory: ${argon.memoryKiB}\n") + headers.append("Argon2-Passes: ${argon.passes}\n") + headers.append("Argon2-Parallelism: ${argon.parallelism}\n") + headers.append("Argon2-Salt: ${hex(salt)}\n") + } else { + cipherKey = ByteArray(0); iv = ByteArray(0); macKey = ByteArray(0) + } + } else { + fun sha1(vararg parts: ByteArray) = MessageDigest.getInstance("SHA-1").run { parts.forEach { update(it) }; digest() } + val p = passphrase.toByteArray() + cipherKey = (sha1(byteArrayOf(0, 0, 0, 0), p) + sha1(byteArrayOf(0, 0, 0, 1), p)).copyOf(32) + iv = ByteArray(16) + macKey = sha1("putty-private-key-file-mac-key".toByteArray(), if (encrypted) p else ByteArray(0)) + } + + val macData = Buffer.PlainBuffer().putString(alg).putString(encryption).putString(comment) + .putBytes(pub).putBytes(priv).compactData + val macAlg = if (version == 3) "HmacSHA256" else "HmacSHA1" + val mac = Mac.getInstance(macAlg).run { + // (an empty key, for an unencrypted v3 file: HMAC's own zero-length key) + init(if (macKey.isEmpty()) EmptyKey(macAlg) else SecretKeySpec(macKey, macAlg)) + doFinal(macData) + } + val privOut = if (encrypted) { + Cipher.getInstance("AES/CBC/NoPadding").run { + init(Cipher.ENCRYPT_MODE, SecretKeySpec(cipherKey, "AES"), IvParameterSpec(iv)) + doFinal(priv) + } + } else { + priv + } + + val sb = StringBuilder() + sb.append("PuTTY-User-Key-File-$version: $alg\n") + sb.append("Encryption: $encryption\n") + sb.append("Comment: $comment\n") + lines(pub).let { sb.append("Public-Lines: ${it.size}\n"); it.forEach { l -> sb.append(l).append('\n') } } + sb.append(headers) + lines(privOut).let { sb.append("Private-Lines: ${it.size}\n"); it.forEach { l -> sb.append(l).append('\n') } } + sb.append("Private-MAC: ${hex(mac)}\n") + return sb.toString() + } + + /** an HMAC key of no bytes (SecretKeySpec won't make one) */ + private class EmptyKey(private val alg: String) : javax.crypto.SecretKey { + override fun getAlgorithm() = alg + override fun getFormat() = "RAW" + override fun getEncoded() = ByteArray(0) + } + + private fun privateBlob(kp: KeyPair): ByteArray { + val b = Buffer.PlainBuffer() + when (val p = kp.private) { + is RSAPrivateCrtKey -> b.putMPInt(p.privateExponent).putMPInt(p.primeP).putMPInt(p.primeQ).putMPInt(p.crtCoefficient) + is ECPrivateKey -> b.putMPInt(p.s) + else -> b.putBytes((PrivateKeyFactory.createKey(p.encoded) as Ed25519PrivateKeyParameters).encoded) + } + return b.compactData + } + + private fun lines(data: ByteArray) = Base64.getEncoder().encodeToString(data).chunked(64) + + private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) } +} diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/SshKeysSection.kt b/app/src/main/java/com/neodesktop/dmodem/ui/SshKeysSection.kt index 75e513a..af08a6c 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/SshKeysSection.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/SshKeysSection.kt @@ -174,7 +174,7 @@ private fun ImportDialog(onDone: () -> Unit) { OutlinedTextField(name, { name = it }, label = { Text("Name") }, singleLine = true) OutlinedButton(onClick = { pick.launch(arrayOf("*/*")) }) { Text("Choose a file…") } OutlinedTextField( - text, { text = it }, label = { Text("…or paste it (BEGIN OPENSSH PRIVATE KEY)") }, + text, { text = it }, label = { Text("…or paste it (OpenSSH, PuTTY .ppk or PEM)") }, textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), minLines = 4, maxLines = 8, ) @@ -279,33 +279,47 @@ internal fun KeyDetailsDialog(k: SshKey, onDelete: () -> Unit, onDone: () -> Uni if (exporting) ExportDialog(k) { exporting = false } } +private enum class ExportFormat(val label: String) { + OPENSSH("OpenSSH (ssh, ssh-keygen)"), + PPK3("PuTTY .ppk (PuTTY 0.75 and on)"), + PPK2("PuTTY .ppk version 2 (older PuTTY, WinSCP)"), +} + /** - * The private key out, in OpenSSH's form (for ssh on a computer), with a - * passphrase (as ssh-keygen would ask for): saved to a file the user picks. + * The private key out, in OpenSSH's form (for ssh on a computer) or + * PuTTY's, with a passphrase (as ssh-keygen or PuTTYgen would ask for): + * saved to a file the user picks. */ @Composable -private fun ExportDialog(k: SshKey, onDone: () -> Unit) { +internal fun ExportDialog(k: SshKey, onDone: () -> Unit) { val context = LocalContext.current val scope = rememberCoroutineScope() var pass by remember { mutableStateOf("") } var again by remember { mutableStateOf("") } + var format by remember { mutableStateOf(ExportFormat.OPENSSH) } val fileName = when { k.publicKey.startsWith("ssh-ed25519") -> "id_ed25519" k.publicKey.startsWith("ecdsa") -> "id_ecdsa" else -> "id_rsa" - } + } + if (format == ExportFormat.OPENSSH) "" else ".ppk" val save = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri -> if (uri != null) { scope.launch { val r = runCatching { withContext(Dispatchers.Default) { - val text = Terminal.keys.exportPrivate(k.id, pass) + val text = when (format) { + ExportFormat.OPENSSH -> Terminal.keys.exportPrivate(k.id, pass) + ExportFormat.PPK3 -> Terminal.keys.exportPpk(k.id, pass, 3) + ExportFormat.PPK2 -> Terminal.keys.exportPpk(k.id, pass, 2) + } context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(text.toByteArray()) } ?: throw java.io.IOException("can't write there") } } Toast.makeText( - context, r.exceptionOrNull()?.let { "Not saved: ${it.message}" } ?: "Saved: chmod 600 it before ssh uses it", + context, + r.exceptionOrNull()?.let { "Not saved: ${it.message}" } + ?: if (format == ExportFormat.OPENSSH) "Saved: chmod 600 it before ssh uses it" else "Saved", Toast.LENGTH_LONG, ).show() onDone() @@ -317,8 +331,9 @@ private fun ExportDialog(k: SshKey, onDone: () -> Unit) { title = { Text("Export ${k.name}") }, text = { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Choice("Format", format.label, ExportFormat.entries.map { it.label to it }) { format = it } Text( - "The private key, in OpenSSH's form: whoever has the file (and its passphrase) can log in as you.", + "The private key: whoever has the file (and its passphrase) can log in as you.", style = MaterialTheme.typography.bodySmall, ) OutlinedTextField( diff --git a/app/src/test/java/com/neodesktop/dmodem/ssh/OpenSshInteropTest.kt b/app/src/test/java/com/neodesktop/dmodem/ssh/OpenSshInteropTest.kt index 487cc2a..bc9b447 100644 --- a/app/src/test/java/com/neodesktop/dmodem/ssh/OpenSshInteropTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/ssh/OpenSshInteropTest.kt @@ -257,7 +257,8 @@ class OpenSshInteropTest { Socket("127.0.0.1", bound(l, later)).use { assertEquals("echo: five", roundTrip(it, "five")) } val p = bound(l, local) l.removeForward(local) - assertTrue("closed", runCatching { Socket("127.0.0.1", p).close() }.isFailure) + // (released: free to listen on again) + ServerSocket().apply { reuseAddress = true; bind(InetSocketAddress("127.0.0.1", p)) }.close() assertTrue(l.forwards.value.none { it.spec == local }) // a port already taken: its error, the others unharmed @@ -336,4 +337,65 @@ class OpenSshInteropTest { assertEquals(1, File(home, "authorized_keys").readLines().count { it.contains(second.publicKey.split(" ")[1]) }) connect(second) } + + // PuTTY + + /** the private key is the public key's: what it signs, that verifies */ + private fun sameKey(priv: java.security.PrivateKey, pub: java.security.PublicKey): Boolean { + val alg = when (pub.algorithm) { "RSA" -> "SHA256withRSA"; "EC", "ECDSA" -> "SHA256withECDSA"; else -> "Ed25519" } + val data = "the same key".toByteArray() + val sig = java.security.Signature.getInstance(alg, "BC").run { initSign(priv); update(data); sign() } + return java.security.Signature.getInstance(alg, "BC").run { initVerify(pub); update(data); verify(sig) } + } + + private fun passFile(p: String) = tmp.newFile().apply { writeText(p) }.path + + @Test + fun ppkAsPuttygenReadsAndWritesThem() { + assumeTrue("puttygen isn't installed", have("puttygen")) + for (kind in KeyKind.entries) { + val k = keys.generate(kind, "test ${kind.name}", comment = "me@phone") + val blob = k.publicKey.split(" ")[1] + val original = keys.keyPair(k.id).public + for (version in listOf(3, 2)) for (pass in listOf("", "correct horse")) { + val what = "$kind v$version '$pass'" + val ppk = tmp.newFile().apply { writeText(keys.exportPpk(k.id, pass, version)) } + assertTrue(what, ppk.readText().startsWith("PuTTY-User-Key-File-$version: ")) + // puttygen opens it (the MAC checked, decrypted): the same public key and comment + val (c1, pub) = run("puttygen", ppk.path, "--old-passphrase", passFile(pass), "-L") + assertEquals("$what: $pub", 0, c1) + assertTrue("$what: $pub", pub.contains(blob) && pub.trim().endsWith("me@phone")) + // its private half: to OpenSSH's form by puttygen, read back here, the same key + val out = tmp.newFile() + val (c2, msg) = run( + "puttygen", ppk.path, "--old-passphrase", passFile(pass), "-O", "private-openssh-new", + "--new-passphrase", passFile(""), "-o", out.path, + ) + assertEquals("$what: $msg", 0, c2) + val back = keys.import(out.readText(), null, "back") + assertTrue(what, sameKey(keys.keyPair(back.id).private, original)) + keys.delete(back.id) + // and this app's own import of it + val again = keys.import(ppk.readText(), pass, "again") + assertEquals(what, k.fingerprint, again.fingerprint) + assertEquals(what, "me@phone", keys.comment(again)) + keys.delete(again.id) + } + keys.delete(k.id) + } + // keys puttygen made, imported: v3 (its default) and v2, with a passphrase + for ((t, bits) in listOf("ed25519" to null, "ecdsa" to "384", "rsa" to "2048")) for (version in listOf(3, 2)) { + val ppk = File(tmp.root, "made-$t-$version.ppk") + val args = mutableListOf("puttygen", "-t", t, "-C", "from puttygen", "--new-passphrase", passFile("hunter2"), "-o", ppk.path, "--ppk-param", "version=$version") + if (bits != null) args.addAll(listOf("-b", bits)) + val (c, msg) = run(*args.toTypedArray()) + assertEquals(msg, 0, c) + val imported = keys.import(ppk.readText(), "hunter2", "made") + val (_, pub) = run("puttygen", ppk.path, "--old-passphrase", passFile("hunter2"), "-L") + assertTrue("$t v$version", pub.contains(imported.publicKey.split(" ")[1])) + assertEquals("from puttygen", keys.comment(imported)) + // the wrong passphrase: refused + assertTrue(runCatching { keys.import(ppk.readText(), "wrong", "x") }.isFailure) + } + } } diff --git a/app/src/test/java/com/neodesktop/dmodem/ui/SshToolsUiTest.kt b/app/src/test/java/com/neodesktop/dmodem/ui/SshToolsUiTest.kt index 72a0857..5a84e9f 100644 --- a/app/src/test/java/com/neodesktop/dmodem/ui/SshToolsUiTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/ui/SshToolsUiTest.kt @@ -193,4 +193,14 @@ class SshToolsDialogsTest { compose.onNodeWithText("[ED25519 256]", substring = true).assertExists() shot("ssh-tools-key") } + + @Test + fun anExportAsPutty() { + val k = Terminal.keys.generate(KeyKind.ED25519, "pixel", comment = "alice@pixel") + compose.setContent { DModemTheme { ExportDialog(k) {} } } + compose.onNodeWithText("OpenSSH (ssh, ssh-keygen)").performClick() + compose.onNodeWithText("PuTTY .ppk (PuTTY 0.75 and on)").performClick() + compose.onNodeWithText("PuTTY .ppk (PuTTY 0.75 and on)").assertExists() + shot("ssh-tools-export-ppk") + } }