Skip to content
Closed
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
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ jobs:
steps:
- name: 检出代码
uses: actions/checkout@v7
with:
submodules: recursive

- name: 解密KeyStore
if: github.event_name != 'pull_request'
Expand Down
6 changes: 6 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[submodule "app/src/main/cpp/third_party/mbedtls"]
path = libterminal-ssh/src/main/cpp/third_party/mbedtls
url = https://github.com/Mbed-TLS/mbedtls.git
[submodule "app/src/main/cpp/third_party/libssh"]
path = libterminal-ssh/src/main/cpp/third_party/libssh
url = https://github.com/libssh/libssh-mirror.git
10 changes: 2 additions & 8 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ plugins {

android {
namespace = "com.awkoo.terminal"
ndkVersion = "29.0.14206865"

compileSdk {
version = release(37)
Expand Down Expand Up @@ -60,13 +59,6 @@ android {
isCoreLibraryDesugaringEnabled = true
}

externalNativeBuild {
cmake {
path(file("src/main/cpp/CMakeLists.txt"))
version = "4.1.2"
}
}

lint {
disable.add("ProtectedPermissions")
disable.add("ExpiredTargetSdkVersion")
Expand Down Expand Up @@ -110,4 +102,6 @@ dependencies {
implementation(libs.serialization.protobuf)
//implementation(libs.timber)
implementation(project(":libterminal"))
implementation(project(":libterminal-lpty"))
implementation(project(":libterminal-ssh"))
}
3 changes: 0 additions & 3 deletions app/src/main/cpp/pty/CMakeLists.txt

This file was deleted.

86 changes: 86 additions & 0 deletions app/src/main/kotlin/com/awkoo/terminal/core/CredentialCipher.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.awkoo.terminal.core

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import javax.inject.Inject
import javax.inject.Singleton

/**
* SSH 凭据(口令/私钥口令)的落盘加密器。
*
* 使用 Android Keystore 中生成的不可导出 AES/GCM 密钥;密文以
* Base64(iv || ciphertext) 存储,只有本应用可解密。KeyStore 密钥丢失
* (设备重置/恢复)或数据损坏时 [decrypt] 返回 null,调用方须让用户重输。
*/
@Singleton
class CredentialCipher @Inject constructor() {

@Volatile
private var secretKey: SecretKey? = null

fun encrypt(plain: String): String? {
if (plain.isEmpty()) return null
return try {
val cipher = Cipher.getInstance(TRANSFORM)
cipher.init(Cipher.ENCRYPT_MODE, loadKey())
val iv = cipher.iv
val ct = cipher.doFinal(plain.encodeToByteArray())
Base64.encodeToString(iv + ct, Base64.NO_WRAP)
} catch (e: Exception) {
null
}
}

fun decrypt(payload: String): String? {
if (payload.isEmpty()) return null
return try {
val raw = Base64.decode(payload, Base64.NO_WRAP)
val iv = raw.copyOfRange(0, IV_LEN)
val ct = raw.copyOfRange(IV_LEN, raw.size)
val cipher = Cipher.getInstance(TRANSFORM)
cipher.init(Cipher.DECRYPT_MODE, loadKey(), GCMParameterSpec(TAG_LEN_BITS, iv))
String(cipher.doFinal(ct))
} catch (e: Exception) {
null
}
}

private fun loadKey(): SecretKey {
secretKey?.let { return it }
synchronized(this) {
secretKey?.let { return it }
val ks = KeyStore.getInstance(KEYSTORE).apply { load(null) }
(ks.getKey(KEY_ALIAS, null) as? SecretKey)?.let {
secretKey = it
return it
}
val generator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, KEYSTORE
)
generator.init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
)
return generator.generateKey().also { secretKey = it }
}
}

private companion object {
const val KEYSTORE = "AndroidKeyStore"
const val KEY_ALIAS = "terminal_ssh_credentials"
const val TRANSFORM = "AES/GCM/NoPadding"
const val IV_LEN = 12
const val TAG_LEN_BITS = 128
}
}
61 changes: 59 additions & 2 deletions app/src/main/kotlin/com/awkoo/terminal/core/SessionManager.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package com.awkoo.terminal.core

import com.awkoo.libterminal.engine.TerminalSession
import com.awkoo.libterminal.lpty.LibPtyProcess
import com.awkoo.libterminal.lpty.PtyParams
import com.awkoo.libterminal.ssh.SshCredentials
import com.awkoo.libterminal.ssh.SshInfo
import com.awkoo.libterminal.ssh.SshProcess
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
Expand Down Expand Up @@ -66,22 +71,74 @@ class SessionManager @Inject constructor() {
stdin = commandInfo.stdin?.toByteArray(),
maxTranscriptRows = maxTranscriptRows
) { rows, cols, w, h ->
LocalPtyProcess(commandInfo, rows, cols, w, h)
LibPtyProcess(
PtyParams(
executable = commandInfo.executable,
cwd = commandInfo.workingDirectory,
arguments = commandInfo.arguments,
environment = commandInfo.environmentArray
),
rows, cols, w, h
)
}

targetSession.execute()

_sessionList.update { it + targetSession }
currentSessionId.update { targetSession.id }

observeRemoval(targetSession)
}

/**
* 建立 SSH 会话:点击创建即入列并成为当前会话,连接异步进行,
* 失败时按"进程立即退出"结束,不抛出到调用线程。
*
* [sshInfo] 为含密文的持久化记录;解密后的明文凭据只在本调用中
* 构造 [SshCredentials] 交给 libterminal-ssh,不做任何落盘。
*/
fun addSshSession(
sshInfo: PersistedSshInfo,
cipher: CredentialCipher?,
maxTranscriptRows: Int = 5000
) {
val sessionId = idGenerator.incrementAndFetch()
val displayName = sshInfo.name ?: "${sshInfo.user}@${sshInfo.host}"

val targetSession = TerminalSession(
id = sessionId,
sessionName = MutableStateFlow(displayName),
stdin = null,
maxTranscriptRows = maxTranscriptRows
) { rows, cols, _, _ ->
SshProcess(
sshInfo.toSshInfo(),
SshCredentials(
password = sshInfo.passwordCipher?.let { cipher?.decrypt(it) },
keyPassphrase = sshInfo.keyPassphraseCipher?.let { cipher?.decrypt(it) }
),
rows,
cols
)
}

targetSession.execute()

_sessionList.update { it + targetSession }
currentSessionId.update { targetSession.id }

observeRemoval(targetSession)
}

private fun observeRemoval(targetSession: TerminalSession) {
// 使用 combine 联合监听 Session 自身的 isRemove 状态与全局的 _sessionList
// 一旦会话要求移除,或者它已经被外部手段从列表中剔除,first { it } 都会立刻放行
// 随后执行兜底的 removeSession 并自然结束协程,杜绝任何内存泄漏的可能。
scope.launch {
combine(targetSession.isRemove, _sessionList) { isRemove, list ->
isRemove || list.none { it.id == targetSession.id }
}.first { it }

removeSession(targetSession.id)
}
}
Expand Down
141 changes: 141 additions & 0 deletions app/src/main/kotlin/com/awkoo/terminal/core/SshInfoStore.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package com.awkoo.terminal.core

import android.content.Context
import android.util.Base64
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.awkoo.libterminal.ssh.SshInfo
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromByteArray
import kotlinx.serialization.encodeToByteArray
import kotlinx.serialization.protobuf.ProtoBuf
import javax.inject.Inject
import javax.inject.Singleton

private val Context.sshDataStore by preferencesDataStore("SshInfo")

@Serializable
enum class SshAuthType {
PASSWORD,
PRIVATE_KEY
}

/**
* 持久化的 SSH 连接配置(进程参数载体,与 [CommandInfo] 对应)。
*
* 敏感字段(密码、私钥口令)只保存 [CredentialCipher] 加密后的密文;
* 已知会话指纹存于 [hostKeyFingerprint],为 null 表示尚未做首次信任(TOFU)。
*/
@Serializable
data class PersistedSshInfo(
val id: Long = 0,
val name: String? = null,
val host: String,
val port: Int = 22,
val user: String,
val authType: SshAuthType = SshAuthType.PASSWORD,
val passwordCipher: String? = null,
val keyPath: String? = null,
val keyPassphraseCipher: String? = null,
val hostKeyFingerprint: String? = null,
val keepAliveMs: Int = 0,
val timeoutMs: Int = 10000
)

/**
* SSH 连接配置持久化存储。
*
* 依赖既有的 Preferences DataStore + ProtoBuf 模式(同 [com.awkoo.terminal.extrakeys.ExtraKeysConfig]),
* 独立文件 [PersistedSshInfo],损坏条目(解码失败)自动跳过。
*/
@OptIn(ExperimentalSerializationApi::class)
@Singleton
class SshInfoStore @Inject constructor(
@ApplicationContext context: Context
) {
private val datastore = context.sshDataStore

/** 全部连接配置,按 id 升序。损坏条目被剔除。 */
val sshInfoList: Flow<List<PersistedSshInfo>> = datastore.data.map { prefs ->
prefs.asMap()
.filterKeys { it.name.startsWith(KEY_PREFIX) }
.mapNotNull { (key, value) ->
(value as? String)?.let { decode(it) }
}
.sortedBy { it.id }
}

suspend fun get(id: Long): PersistedSshInfo? {
val list = sshInfoList.first()
return list.firstOrNull { it.id == id }
}

/** 分配自增 id 后落盘,返回带 id 的副本。 */
suspend fun insert(input: PersistedSshInfo): PersistedSshInfo {
var assigned = input.id
datastore.edit { prefs ->
if (input.id <= 0) {
assigned = (prefs[nextIdKey] ?: 1).toLong()
prefs[nextIdKey] = assigned.toInt() + 1
}
prefs[infoKey(assigned)] = encode(input.copy(id = assigned))
}
return input.copy(id = assigned)
}

suspend fun upsert(info: PersistedSshInfo) {
if (info.id <= 0) {
insert(info)
return
}
datastore.edit { prefs ->
prefs[infoKey(info.id)] = encode(info)
}
}

suspend fun delete(id: Long) {
datastore.edit { prefs ->
prefs.remove(infoKey(id))
}
}

private fun infoKey(id: Long) = stringPreferencesKey(KEY_PREFIX + id)

private fun encode(info: PersistedSshInfo): String =
Base64.encodeToString(ProtoBuf.encodeToByteArray(info), Base64.NO_WRAP)

private fun decode(encoded: String): PersistedSshInfo? =
try {
ProtoBuf.decodeFromByteArray<PersistedSshInfo>(
Base64.decode(encoded, Base64.NO_WRAP)
)
} catch (e: Exception) {
null
}

companion object {
private const val KEY_PREFIX = "info_"
private val nextIdKey = intPreferencesKey("nextInfoId")
}
}

/** 持久化记录(含密文/标识)→ libterminal-ssh 的纯连接配置。 */
fun PersistedSshInfo.toSshInfo(): SshInfo =
SshInfo(
name = name,
host = host,
port = port,
user = user,
authType = com.awkoo.libterminal.ssh.SshAuthType.valueOf(authType.name),
keyPath = keyPath,
hostKeyFingerprint = hostKeyFingerprint,
keepAliveMs = keepAliveMs,
timeoutMs = timeoutMs
)
Loading
Loading