Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.dp
import androidx.fragment.app.FragmentActivity
Expand Down Expand Up @@ -43,10 +44,11 @@ fun KeyEnrolmentSection(
) {
val scope = rememberCoroutineScope()
var busy by remember { mutableStateOf(false) }
// Plain `remember`: this holds the private key, which must not land in saved instance state.
var pushedKey by remember { mutableStateOf<GeneratedKey?>(null) }
var result by remember { mutableStateOf<String?>(null) }
var failed by remember { mutableStateOf(false) }
var switched by remember { mutableStateOf(false) }
var result by rememberSaveable { mutableStateOf<String?>(null) }
var failed by rememberSaveable { mutableStateOf(false) }
var switched by rememberSaveable { mutableStateOf(false) }

Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
Expand Down Expand Up @@ -120,11 +122,16 @@ fun KeyEnrolmentSection(
) { Text("Use this key for this host") }
}
}
result?.let {
// The private key is not saved across rotation, so a restored success has nothing left to switch to.
val keyLost = result != null && !failed && !switched && pushedKey == null
val shown =
if (keyLost) "The key was installed on the host, but this screen no longer has it. Push a new key to use it."
else result
shown?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary,
color = if (failed || keyLost) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,25 @@ internal const val ENROLMENT_FAIL_MARKER = "SHELLWAVE_ENROLL_FAIL"

data class KeyEnrolmentResult(val success: Boolean, val message: String)

/**
* `authorized_keys` may not end in a newline, and appending to such a file would glue the new key
* onto the last entry and corrupt both. `tail -c1 | grep -q .` only succeeds when the last byte is
* not a newline (an empty file has no byte at all), so a newline is only added when the file ends
* mid-line.
*
* sshd runs the command through the account's login shell, which can be csh or tcsh, so it sticks
* to syntax both csh and POSIX sh accept: `&&`, `||`, `|`, `;` and `( )` subshells, but no command
* substitution, braces or `[ ]` tests.
*/
internal fun enrolmentCommand(key: String): String {
val quotedKey = posixQuote(key)
val file = "~/.ssh/authorized_keys"
return "mkdir -p ~/.ssh && chmod 700 ~/.ssh && touch $file && chmod 600 $file && " +
"(grep -qxF -- $quotedKey $file || " +
"(tail -c1 $file | grep -q . && echo >> $file; printf '%s\\n' $quotedKey >> $file)) && " +
"grep -qxF -- $quotedKey $file && echo $ENROLMENT_OK_MARKER || echo $ENROLMENT_FAIL_MARKER"
}

/**
* `ssh-copy-id` over an already-authenticated session: one POSIX shell command through
* [ScriptRunner.runCapture] rather than a second exec path. Nothing sshj-specific lives here.
Expand Down Expand Up @@ -42,11 +61,7 @@ constructor(private val scriptRunner: ScriptRunner) {
): KeyEnrolmentResult {
val key = publicKeyLine.trim()
require(key.isNotEmpty() && !key.contains('\n')) { "publicKeyLine must be a single non-blank line" }
val quotedKey = posixQuote(key)
val command =
"mkdir -p ~/.ssh && chmod 700 ~/.ssh && touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && " +
"(grep -qxF -- $quotedKey ~/.ssh/authorized_keys || printf '%s\\n' $quotedKey >> ~/.ssh/authorized_keys) && " +
"grep -qxF -- $quotedKey ~/.ssh/authorized_keys && echo $ENROLMENT_OK_MARKER || echo $ENROLMENT_FAIL_MARKER"
val command = enrolmentCommand(key)

val result =
scriptRunner.runCapture(runLabel, hostname, port, username, authMethod, command, hops)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package io.github.lordofpolls.shellwave.ssh

import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File

/**
* Runs the real command through `sh` against a throwaway `$HOME`, since the append logic only
* exists as shell. Skipped where no `sh` is available.
*/
class KeyEnrolmentCommandTest {

@get:Rule
val home = TemporaryFolder()

private val key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAItest shellwave"

private fun authorizedKeys() = File(home.root, ".ssh/authorized_keys")

private fun run(): String {
assumeTrue(File("/bin/sh").canExecute())
val process = ProcessBuilder("/bin/sh", "-c", enrolmentCommand(key))
.redirectErrorStream(true)
.apply { environment()["HOME"] = home.root.absolutePath }
.start()
val output = process.inputStream.bufferedReader().readText()
process.waitFor()
return output
}

private fun seed(content: String) {
authorizedKeys().parentFile.mkdirs()
authorizedKeys().writeText(content)
}

@Test
fun missingFile_getsTheKeyAndATrailingNewline() {
assertTrue(ENROLMENT_OK_MARKER in run())
assertEquals("$key\n", authorizedKeys().readText())
}

@Test
fun emptyFile_getsNoBlankLine() {
seed("")
run()
assertEquals("$key\n", authorizedKeys().readText())
}

@Test
fun fileWithTrailingNewline_getsNoBlankLine() {
seed("ssh-rsa AAAAold other\n")
run()
assertEquals("ssh-rsa AAAAold other\n$key\n", authorizedKeys().readText())
}

@Test
fun fileWithoutTrailingNewline_keepsTheLastEntryIntact() {
seed("ssh-rsa AAAAold other")
assertTrue(ENROLMENT_OK_MARKER in run())
assertEquals("ssh-rsa AAAAold other\n$key\n", authorizedKeys().readText())
}

@Test
fun alreadyPresentKey_isNotAppendedAgain() {
seed("$key\n")
run()
assertEquals("$key\n", authorizedKeys().readText())
}

@Test
fun command_usesOnlySyntaxThatCshAlsoAccepts() {
val command = enrolmentCommand(key)
listOf("$(", "`", "{", "}", "[").forEach { assertTrue("contains $it", it !in command) }
}
}
Loading