feat: 控制通道接入 TLS 并按自签证书指纹校验
- rust_core:PinnedTlsStream 增加指纹校验、accept、读超时与关闭;会话层新增客户端连接入口 - rust_core:demo 服务按指纹选择 TLS 或明文(首字节 0x16 判定),新增 ttstd_demo_set_tls_fingerprint(ABI 5) - rust_core:发现结构补齐 tls_fingerprint,mDNS TXT 收发 tls=,信标 JSON 序列化 tls - android_receiver:新增 TlsIdentity 生成并持久化 P-256 自签证书,TlsServerTransport 用 SSLEngine 包装 Socket - android_receiver:被控端反连时窥探首字节决定 TLS/明文,信标与配对码公布 tls 指纹 - flutter_sender:NativeCore 暴露 setTlsFingerprint,连接前按目标设备指纹设置,为空则明文 - docs:README 补充 TLS 角色反转、tls 字段与 fp/tls 的区别
This commit is contained in:
1 parent
9a82766fa2
commit
e2020ab595
20 files changed
+771
-36
No files matched your search
@@ -117,6 +117,7 @@ cap=h264,h265,opus,uibc,clipboard,file
|
||||
res=1920x1080
|
||||
model=Pixel8
|
||||
fp=<证书SHA256前16字节hex>
|
||||
tls=<TLS 自签证书 SHA256 hex,可选;空/缺省表示只支持明文控制通道>
|
||||
sig=<信令服务器URL,可选>
|
||||
```
|
||||
|
||||
@@ -161,12 +162,14 @@ sig=<信令服务器URL,可选>
|
||||
### 4.3 会话握手
|
||||
|
||||
1. 主控端拿到被控 `ip:controlPort`
|
||||
2. TCP 连接 → TLS 握手(被控自签证书)
|
||||
3. 主控端校验证书 SHA-256 == mDNS/信令里公布的 `fp`,不符直接断
|
||||
2. TCP 连接方向是「被控端反连主控端」,所以 **TLS 角色是反的**:主控端(监听侧)发 ClientHello,
|
||||
被控端(拨号侧)出示自签证书
|
||||
3. 主控端按信标/配对二维码里的 `tls` 校验证书 SHA-256,不符直接断;`tls` 为空则退回明文控制通道
|
||||
(被控端用 `PushbackInputStream` 窥探首字节 `0x16` 自动区分,旧版本互操作不受影响)
|
||||
4. ECDH P-256 派生会话密钥 → AES-256-GCM 加密后续控制帧
|
||||
5. 视频/音频 UDP 通道用会话密钥派生子密钥,每包带 4 字节 MAC
|
||||
|
||||
**配对模式**(首次):被控端屏幕显示二维码 `lancast://pair?ip=&port=&fp=`,主控扫码存指纹,后续免扫。
|
||||
**配对模式**(首次):被控端屏幕显示二维码 `lancast://pair?ip=&port=&fp=&tls=`,主控扫码存两个指纹,后续免扫。
|
||||
|
||||
### 4.4 控制通道二进制帧(重点:自定义二进制 + 抽象接口)
|
||||
|
||||
@@ -449,17 +452,23 @@ POST /mirror/request?token= 触发一次投屏确认(便
|
||||
| --- | --- |
|
||||
| 发现 | mDNS TXT 带 `fp` 指纹,防冒充 |
|
||||
| 配对 | 二维码扫码 或 6 位 TOTP PIN(30s 过期) |
|
||||
| 传输 | 控制帧 AES-256-GCM;TLS + 证书 pinning 尚未接入(见下方边界) |
|
||||
| 传输 | 控制通道 TLS 1.3 + 自签证书 pinning(`tls=` 指纹),无指纹时明文;控制帧 AES-256-GCM |
|
||||
| 会话 | ECDH P-256 → AES-256-GCM |
|
||||
| 媒体 | 派生子密钥,每包 4 字节 MAC 防篡改 |
|
||||
| 权限 | 配对时选"仅查看 / 查看+控制 / 全权限(含文件)" |
|
||||
| 信令 | 客户端 pin 信令服务器公钥,防中间人 |
|
||||
| 中继 | 信封 `relay/1`,`hs/hsAck` 只交换 ECDH 公钥,帧内容仍是 AEAD 密文,服务器无法解密 |
|
||||
|
||||
**指纹的真实含义**:当前公布的 `fp` 是**被控端应用签名证书的 SHA-256**(`util/Fingerprint.kt`),
|
||||
绑定的是「应用身份」而不是某次 ECDH 临时公钥。主控端首次连接即记录(TOFU,`lib/core/pin_store.dart`),
|
||||
之后不一致会弹窗要求确认;重装/换签名会变,这属于预期现象。
|
||||
TLS 传输层尚未启用,因此指纹只用于身份比对,不能据此认为链路已加密到 TLS 级别。
|
||||
**指纹的真实含义**:`fp` 和 `tls` 是两件不同的事,别混用。
|
||||
|
||||
- `fp` 是**被控端应用签名证书的 SHA-256**(`util/Fingerprint.kt`),绑定的是「应用身份」而不是某次
|
||||
ECDH 临时公钥。主控端首次连接即记录(TOFU,`lib/core/pin_store.dart`),之后不一致会弹窗要求确认;
|
||||
重装/换签名会变,这属于预期现象。
|
||||
- `tls` 是**控制通道自签 TLS 证书的 SHA-256**(`util/TlsIdentity.kt`,首次启动用 BouncyCastle 生成
|
||||
P-256 自签证书并持久化在应用私有目录)。主控端只比对指纹前缀(≥16 hex),不校验证书链和域名。
|
||||
换证书(清数据/换机)后需要重新配对或扫码,否则握手会失败——这是设计上的 fail-closed。
|
||||
|
||||
`tls` 为空表示对端只支持明文控制通道,主控端会跳过 TLS 直接发帧(兼容旧版被控端)。
|
||||
|
||||
**不用**自写 AES、不用自写 TLS——`rustls` + `ring` 够了。
|
||||
|
||||
|
||||
@@ -72,4 +72,8 @@ dependencies {
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib:2.0.21")
|
||||
// 配对二维码(纯 Java 编码,无额外传递依赖)。
|
||||
implementation("com.google.zxing:core:3.5.4")
|
||||
// 生成/解析 TLS 自签证书(只用于本机身份,不做证书链校验)。
|
||||
implementation("org.bouncycastle:bcprov-jdk18on:1.80.2")
|
||||
implementation("org.bouncycastle:bcutil-jdk18on:1.80.2")
|
||||
implementation("org.bouncycastle:bcpkix-jdk18on:1.80.2")
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
import com.ttstd.lancast.receiver.util.QrCode
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
import java.net.NetworkInterface
|
||||
|
||||
class MainActivity : Activity() {
|
||||
@@ -283,6 +284,7 @@ class MainActivity : Activity() {
|
||||
fingerprint = Fingerprint.of(this),
|
||||
deviceId = DeviceIdentity.of(this),
|
||||
name = "Android Receiver",
|
||||
tlsFingerprint = TlsIdentity.fingerprintOrEmpty(this),
|
||||
)
|
||||
}
|
||||
val pairingText = if (pairingUri.isEmpty()) {
|
||||
|
||||
+2
@@ -24,6 +24,7 @@ import com.ttstd.lancast.receiver.protocol.MirrorAction
|
||||
import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
|
||||
/**
|
||||
* 常驻前台服务。分两个阶段:
|
||||
@@ -280,6 +281,7 @@ class MediaProjectionService : Service() {
|
||||
model = Build.MODEL ?: "Android",
|
||||
resolution = "${metrics.widthPixels}x${metrics.heightPixels}",
|
||||
fingerprint = Fingerprint.of(this),
|
||||
tlsFingerprint = TlsIdentity.fingerprintOrEmpty(this),
|
||||
),
|
||||
).also { it.start() }
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||
import com.ttstd.lancast.receiver.session.ReceiverTransport
|
||||
import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.Executors
|
||||
@@ -70,6 +71,8 @@ class ReceiverSession(
|
||||
private val fingerprint: String = Fingerprint.of(context)
|
||||
/** 稳定的设备 id(首次运行生成后持久化),保证 pinning 能对上同一台设备。 */
|
||||
private val deviceId: String = DeviceIdentity.of(context)
|
||||
/** 控制通道 TLS 自签身份;生成失败时控制通道退回明文。 */
|
||||
private val tlsIdentity: TlsIdentity? = TlsIdentity.of(context)
|
||||
|
||||
@Volatile
|
||||
private var transport: ReceiverTransport? = null
|
||||
@@ -282,6 +285,7 @@ class ReceiverSession(
|
||||
),
|
||||
model = Build.MODEL,
|
||||
resolution = "${size[0]}x${size[1]}",
|
||||
tlsFingerprint = tlsIdentity?.fingerprint ?: "",
|
||||
)
|
||||
// 信令服务器是跨网段兜底:没有配置(空串)时不必启动,避免无谓的失败请求。
|
||||
if (signalingUrl.isNotBlank()) {
|
||||
@@ -317,6 +321,7 @@ class ReceiverSession(
|
||||
fileService,
|
||||
signalingUrl,
|
||||
deviceId,
|
||||
tlsIdentity,
|
||||
)
|
||||
created.onMirrorEvent = { action, message -> onMirrorRequest?.invoke(action, message) }
|
||||
created.onSessionConfig = { json -> applySessionConfig(json) }
|
||||
|
||||
+2
@@ -10,4 +10,6 @@ data class AnnouncedDevice(
|
||||
val capabilities: List<String>,
|
||||
val model: String,
|
||||
val resolution: String,
|
||||
/** TLS 自签证书的 SHA-256;为空表示不支持 TLS。 */
|
||||
val tlsFingerprint: String = "",
|
||||
)
|
||||
@@ -35,6 +35,8 @@ class HostBeacon(
|
||||
val resolution: String,
|
||||
/** 应用签名证书指纹,主控端据此做 TOFU pinning。 */
|
||||
val fingerprint: String = "",
|
||||
/** TLS 自签证书 SHA-256,主控端据此校验控制通道加密。 */
|
||||
val tlsFingerprint: String = "",
|
||||
)
|
||||
|
||||
companion object {
|
||||
@@ -162,6 +164,7 @@ class HostBeacon(
|
||||
put("media", mediaPort)
|
||||
put("audio", audioPort)
|
||||
put("fp", device.fingerprint)
|
||||
if (device.tlsFingerprint.isNotBlank()) put("tls", device.tlsFingerprint)
|
||||
put(
|
||||
"cap",
|
||||
JSONArray(
|
||||
|
||||
+1
@@ -40,6 +40,7 @@ class NsdAdvertiser(private val context: Context, private val device: AnnouncedD
|
||||
setAttribute("res", device.resolution)
|
||||
setAttribute("model", device.model)
|
||||
setAttribute("fp", device.fingerprint)
|
||||
if (device.tlsFingerprint.isNotBlank()) setAttribute("tls", device.tlsFingerprint)
|
||||
setAttribute("cport", device.controlPort.toString())
|
||||
setAttribute("mport", device.mediaPort.toString())
|
||||
device.ip.takeIf { it.isNotBlank() }?.let { setAttribute("ip", it) }
|
||||
|
||||
+1
@@ -52,6 +52,7 @@ class ReceiverAnnouncer(
|
||||
put("mediaPort", device.mediaPort)
|
||||
put("controlPort", device.controlPort)
|
||||
put("fp", device.fingerprint)
|
||||
if (device.tlsFingerprint.isNotBlank()) put("tls", device.tlsFingerprint)
|
||||
put("cap", JSONArray(device.capabilities))
|
||||
put("model", device.model)
|
||||
put("res", device.resolution)
|
||||
|
||||
+45
-2
@@ -9,9 +9,11 @@ import com.ttstd.lancast.receiver.input.InputInjector
|
||||
import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||
import com.ttstd.lancast.receiver.protocol.ControlFrames
|
||||
import com.ttstd.lancast.receiver.protocol.MirrorAction
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
import org.json.JSONObject
|
||||
import java.io.DataInputStream
|
||||
import java.io.DataOutputStream
|
||||
import java.io.PushbackInputStream
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.InetSocketAddress
|
||||
@@ -43,6 +45,8 @@ class ReceiverTransport(
|
||||
private val fileService: FileService,
|
||||
private val signalingUrl: String = "",
|
||||
private val deviceId: String = "",
|
||||
/** 控制通道 TLS 身份;为空时只接受明文对端。 */
|
||||
private val tlsIdentity: TlsIdentity? = null,
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "ReceiverTransport"
|
||||
@@ -58,6 +62,9 @@ class ReceiverTransport(
|
||||
|
||||
/** 中继会话内的轮询间隔。 */
|
||||
private const val RELAY_POLL_MS = 120L
|
||||
|
||||
/** TLS 握手记录(ClientHello)的首字节。 */
|
||||
private const val TLS_HANDSHAKE_RECORD = 0x16
|
||||
}
|
||||
|
||||
/** 握手阶段失败:对端未就绪/已断开,属于可预期情况。 */
|
||||
@@ -167,8 +174,44 @@ class ReceiverTransport(
|
||||
connect(InetSocketAddress(host, controlPort), 5000)
|
||||
}
|
||||
socket = raw
|
||||
output = DataOutputStream(raw.outputStream)
|
||||
val input = DataInputStream(raw.inputStream)
|
||||
// 主控端如果支持 TLS,会直接发 ClientHello(首字节 0x16);老版本先发 ECDH 公钥(0x04)。
|
||||
// 用回推流窥探一个字节,两种对端都能兼容。
|
||||
val rawInput = PushbackInputStream(raw.inputStream, 1)
|
||||
val first = try {
|
||||
rawInput.read()
|
||||
} catch (error: Exception) {
|
||||
throw HandshakeException("读取主控端握手首字节失败", error)
|
||||
}
|
||||
if (first < 0) {
|
||||
throw HandshakeException("主控端在握手阶段关闭了连接", java.io.EOFException())
|
||||
}
|
||||
rawInput.unread(first)
|
||||
val inputStream: java.io.InputStream
|
||||
val outputStream: java.io.OutputStream
|
||||
if (first == TLS_HANDSHAKE_RECORD) {
|
||||
val identity = tlsIdentity
|
||||
if (identity == null) {
|
||||
throw HandshakeException("主控端要求 TLS,但本机证书不可用", java.io.IOException("tls"))
|
||||
}
|
||||
try {
|
||||
val tls = TlsServerTransport(
|
||||
rawInput,
|
||||
raw.outputStream,
|
||||
identity.certificate,
|
||||
identity.privateKey,
|
||||
)
|
||||
inputStream = tls.inputStream
|
||||
outputStream = tls.outputStream
|
||||
Log.i(TAG, "控制通道已启用 TLS(${identity.fingerprint})")
|
||||
} catch (error: Exception) {
|
||||
throw HandshakeException("TLS 握手失败:${error.message}", error)
|
||||
}
|
||||
} else {
|
||||
inputStream = rawInput
|
||||
outputStream = raw.outputStream
|
||||
}
|
||||
output = DataOutputStream(outputStream)
|
||||
val input = DataInputStream(inputStream)
|
||||
|
||||
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
|
||||
// 对端在这期间关闭连接(主控端未开监听、正在重启、或只接受一路连接)都属于
|
||||
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package com.ttstd.lancast.receiver.session
|
||||
|
||||
import android.util.Log
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.security.KeyStore
|
||||
import java.security.PrivateKey
|
||||
import java.security.cert.X509Certificate
|
||||
import javax.net.ssl.KeyManagerFactory
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.SSLEngine
|
||||
import javax.net.ssl.SSLEngineResult
|
||||
import javax.net.ssl.SSLException
|
||||
|
||||
/**
|
||||
* 在**已建立的 TCP 连接**上跑 TLS 服务端(被控端反连主控端,但 TLS 角色是服务端)。
|
||||
*
|
||||
* JSSE 没有「把已连接 Socket 升级成 TLS」的公开 API,所以这里直接用 [SSLEngine]
|
||||
* 手工驱动握手与加解密,并包装成普通 [InputStream]/[OutputStream],
|
||||
* 让上层控制通道的读写代码完全不用关心 TLS。
|
||||
*
|
||||
* 线程模型:读只发生在控制读线程,写可能来自多个发送线程;[engine] 的调用统一加锁,
|
||||
* 但阻塞的 raw 读取放在锁外,避免空闲时把写端一起卡住。
|
||||
*/
|
||||
class TlsServerTransport(
|
||||
private val rawIn: InputStream,
|
||||
private val rawOut: OutputStream,
|
||||
certificate: X509Certificate,
|
||||
privateKey: PrivateKey,
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "TlsServerTransport"
|
||||
private const val HANDSHAKE_TIMEOUT_MS = 10_000L
|
||||
private const val MIN_BUFFER = 64 * 1024
|
||||
}
|
||||
|
||||
private val engine: SSLEngine = createEngine(certificate, privateKey)
|
||||
private var netIn = ByteBuffer.allocate(maxOf(engine.session.packetBufferSize, MIN_BUFFER))
|
||||
private var netOut = ByteBuffer.allocate(maxOf(engine.session.packetBufferSize, MIN_BUFFER))
|
||||
private val appScratch = ByteBuffer.allocate(maxOf(engine.session.applicationBufferSize, MIN_BUFFER))
|
||||
private val engineLock = Any()
|
||||
|
||||
private var pending = ByteArray(0)
|
||||
private var pendingOffset = 0
|
||||
@Volatile
|
||||
private var closed = false
|
||||
|
||||
val inputStream: InputStream = object : InputStream() {
|
||||
override fun read(): Int {
|
||||
val one = ByteArray(1)
|
||||
val read = read(one, 0, 1)
|
||||
return if (read <= 0) -1 else one[0].toInt() and 0xff
|
||||
}
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (length == 0) return 0
|
||||
if (offset < 0 || length < 0 || offset + length > buffer.size) {
|
||||
throw IndexOutOfBoundsException()
|
||||
}
|
||||
while (true) {
|
||||
if (pendingOffset < pending.size) {
|
||||
val count = minOf(length, pending.size - pendingOffset)
|
||||
System.arraycopy(pending, pendingOffset, buffer, offset, count)
|
||||
pendingOffset += count
|
||||
return count
|
||||
}
|
||||
pending = ByteArray(0)
|
||||
pendingOffset = 0
|
||||
if (!unwrapOnce()) return -1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val outputStream: OutputStream = object : OutputStream() {
|
||||
override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)
|
||||
|
||||
override fun write(buffer: ByteArray, offset: Int, length: Int) {
|
||||
if (length == 0) return
|
||||
val source = ByteBuffer.wrap(buffer, offset, length)
|
||||
while (source.hasRemaining()) {
|
||||
netOut.clear()
|
||||
val result = synchronized(engineLock) { engine.wrap(source, netOut) }
|
||||
flushNet()
|
||||
if (result.status == SSLEngineResult.Status.BUFFER_OVERFLOW) {
|
||||
growNetOut()
|
||||
continue
|
||||
}
|
||||
if (result.status == SSLEngineResult.Status.CLOSED) {
|
||||
throw SSLException("TLS 通道已关闭")
|
||||
}
|
||||
}
|
||||
runCatching { rawOut.flush() }
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
handshake()
|
||||
}
|
||||
|
||||
private fun createEngine(certificate: X509Certificate, privateKey: PrivateKey): SSLEngine {
|
||||
val store = KeyStore.getInstance(KeyStore.getDefaultType()).apply { load(null, null) }
|
||||
store.setKeyEntry("ttstd", privateKey, charArrayOf(), arrayOf(certificate))
|
||||
val factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
|
||||
factory.init(store, charArrayOf())
|
||||
val context = SSLContext.getInstance("TLS")
|
||||
context.init(factory.keyManagers, null, null)
|
||||
return context.createSSLEngine().apply {
|
||||
useClientMode = false
|
||||
needClientAuth = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun handshake() {
|
||||
synchronized(engineLock) { engine.beginHandshake() }
|
||||
val deadline = System.currentTimeMillis() + HANDSHAKE_TIMEOUT_MS
|
||||
while (true) {
|
||||
val status = synchronized(engineLock) { engine.handshakeStatus }
|
||||
if (status == SSLEngineResult.HandshakeStatus.FINISHED ||
|
||||
status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING
|
||||
) {
|
||||
Log.d(TAG, "TLS 握手完成")
|
||||
return
|
||||
}
|
||||
if (System.currentTimeMillis() > deadline) {
|
||||
throw SSLException("TLS 握手超时")
|
||||
}
|
||||
when (status) {
|
||||
SSLEngineResult.HandshakeStatus.NEED_WRAP -> wrapPending()
|
||||
SSLEngineResult.HandshakeStatus.NEED_UNWRAP -> {
|
||||
if (!unwrapOnce()) throw SSLException("对端在 TLS 握手阶段断开")
|
||||
}
|
||||
SSLEngineResult.HandshakeStatus.NEED_TASK -> runTasks()
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return false 表示对端已关闭连接。 */
|
||||
private fun unwrapOnce(): Boolean {
|
||||
appScratch.clear()
|
||||
netIn.flip()
|
||||
val result = synchronized(engineLock) { engine.unwrap(netIn, appScratch) }
|
||||
netIn.compact()
|
||||
when (result.status) {
|
||||
SSLEngineResult.Status.CLOSED -> {
|
||||
closed = true
|
||||
return false
|
||||
}
|
||||
SSLEngineResult.Status.BUFFER_UNDERFLOW -> {
|
||||
if (!readRaw()) {
|
||||
closed = true
|
||||
return false
|
||||
}
|
||||
}
|
||||
SSLEngineResult.Status.BUFFER_OVERFLOW -> throw SSLException("TLS 应用缓冲区不足")
|
||||
SSLEngineResult.Status.OK -> {
|
||||
if (appScratch.position() > 0) {
|
||||
appScratch.flip()
|
||||
val produced = ByteArray(appScratch.remaining())
|
||||
appScratch.get(produced)
|
||||
pending = produced
|
||||
pendingOffset = 0
|
||||
}
|
||||
runTasks()
|
||||
if (synchronized(engineLock) { engine.handshakeStatus } ==
|
||||
SSLEngineResult.HandshakeStatus.NEED_WRAP
|
||||
) {
|
||||
wrapPending()
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** 读一段 TLS 记录;返回 false 表示 EOF。 */
|
||||
private fun readRaw(): Boolean {
|
||||
if (!netIn.hasRemaining()) {
|
||||
val bigger = ByteBuffer.allocate(netIn.capacity() * 2)
|
||||
netIn.flip()
|
||||
bigger.put(netIn)
|
||||
netIn = bigger
|
||||
}
|
||||
val read = rawIn.read(netIn.array(), netIn.position(), netIn.remaining())
|
||||
if (read < 0) return false
|
||||
if (read > 0) netIn.position(netIn.position() + read)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun wrapPending() {
|
||||
netOut.clear()
|
||||
var result: SSLEngineResult
|
||||
do {
|
||||
result = synchronized(engineLock) { engine.wrap(ByteBuffer.allocate(0), netOut) }
|
||||
flushNet()
|
||||
} while (result.status == SSLEngineResult.Status.BUFFER_OVERFLOW)
|
||||
if (result.status == SSLEngineResult.Status.CLOSED) closed = true
|
||||
}
|
||||
|
||||
private fun flushNet() {
|
||||
if (netOut.position() == 0) return
|
||||
netOut.flip()
|
||||
rawOut.write(netOut.array(), 0, netOut.limit())
|
||||
rawOut.flush()
|
||||
netOut.clear()
|
||||
}
|
||||
|
||||
private fun growNetOut() {
|
||||
val bigger = ByteBuffer.allocate(netOut.capacity() * 2)
|
||||
netOut.flip()
|
||||
bigger.put(netOut)
|
||||
netOut = bigger
|
||||
}
|
||||
|
||||
private fun runTasks() {
|
||||
while (true) {
|
||||
val task = synchronized(engineLock) { engine.delegatedTask } ?: return
|
||||
task.run()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.ttstd.lancast.receiver.util
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
|
||||
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder
|
||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
|
||||
import java.io.File
|
||||
import java.math.BigInteger
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.MessageDigest
|
||||
import java.security.PrivateKey
|
||||
import java.security.SecureRandom
|
||||
import java.security.cert.CertificateFactory
|
||||
import java.security.cert.X509Certificate
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
import java.security.spec.PKCS8EncodedKeySpec
|
||||
import java.util.Date
|
||||
|
||||
/**
|
||||
* 控制通道 TLS 身份:一台设备一份自签 EC 证书,首次运行生成后持久化。
|
||||
*
|
||||
* 证书只用于**传输加密**,信任来自主控端发现结果里的 `tls` 指纹(TOFU):
|
||||
* 不做 CA 链校验,也不用它替代应用签名指纹 `fp`。
|
||||
*/
|
||||
class TlsIdentity(
|
||||
val certificate: X509Certificate,
|
||||
val privateKey: PrivateKey,
|
||||
) {
|
||||
/** `sha256:<hex>`,与 [Fingerprint] 的格式保持一致。 */
|
||||
val fingerprint: String = fingerprintOf(certificate)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "TlsIdentity"
|
||||
private const val CERT_FILE = "ttstd_tls_cert.pem"
|
||||
private const val KEY_FILE = "ttstd_tls_key.pem"
|
||||
private const val BEGIN_CERT = "-----BEGIN CERTIFICATE-----"
|
||||
private const val END_CERT = "-----END CERTIFICATE-----"
|
||||
private const val BEGIN_KEY = "-----BEGIN PRIVATE KEY-----"
|
||||
private const val END_KEY = "-----END PRIVATE KEY-----"
|
||||
|
||||
@Volatile
|
||||
private var cached: TlsIdentity? = null
|
||||
|
||||
/** 取本机 TLS 身份;生成失败返回 null(此时控制通道退回明文)。 */
|
||||
fun of(context: Context): TlsIdentity? {
|
||||
cached?.let { return it }
|
||||
synchronized(this) {
|
||||
cached?.let { return it }
|
||||
val dir = context.filesDir
|
||||
val identity = runCatching { load(dir) ?: generate(dir) }
|
||||
.onFailure { Log.w(TAG, "TLS 身份不可用,控制通道将不加密", it) }
|
||||
.getOrNull()
|
||||
cached = identity
|
||||
return identity
|
||||
}
|
||||
}
|
||||
|
||||
fun fingerprintOrEmpty(context: Context): String = of(context)?.fingerprint ?: ""
|
||||
|
||||
fun fingerprintOf(certificate: X509Certificate): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(certificate.encoded)
|
||||
return "sha256:" + digest.joinToString("") { byte -> "%02x".format(byte) }
|
||||
}
|
||||
|
||||
private fun load(dir: File): TlsIdentity? {
|
||||
val certFile = File(dir, CERT_FILE)
|
||||
val keyFile = File(dir, KEY_FILE)
|
||||
if (!certFile.exists() || !keyFile.exists()) return null
|
||||
val certificate = CertificateFactory.getInstance("X.509")
|
||||
.generateCertificate(certFile.inputStream()) as? X509Certificate ?: return null
|
||||
val keyBytes = pemBody(keyFile.readText(), BEGIN_KEY, END_KEY) ?: return null
|
||||
val privateKey = KeyFactory.getInstance(certificate.publicKey.algorithm)
|
||||
.generatePrivate(PKCS8EncodedKeySpec(Base64.decode(keyBytes, Base64.DEFAULT)))
|
||||
return TlsIdentity(certificate, privateKey)
|
||||
}
|
||||
|
||||
private fun generate(dir: File): TlsIdentity {
|
||||
val generator = KeyPairGenerator.getInstance("EC").apply {
|
||||
initialize(ECGenParameterSpec("secp256r1"), SecureRandom())
|
||||
}
|
||||
val pair = generator.generateKeyPair()
|
||||
val now = System.currentTimeMillis()
|
||||
val name = org.bouncycastle.asn1.x500.X500Name("CN=TTSTD Receiver")
|
||||
val builder = JcaX509v3CertificateBuilder(
|
||||
name,
|
||||
BigInteger(64, SecureRandom()).abs(),
|
||||
Date(now - 86_400_000L),
|
||||
Date(now + 10L * 365 * 86_400_000L),
|
||||
name,
|
||||
pair.public,
|
||||
)
|
||||
val signer = JcaContentSignerBuilder("SHA256withECDSA").build(pair.private)
|
||||
val certificate = JcaX509CertificateConverter().getCertificate(builder.build(signer))
|
||||
|
||||
File(dir, CERT_FILE).writeText(pem(certificate.encoded, BEGIN_CERT, END_CERT))
|
||||
File(dir, KEY_FILE).writeText(
|
||||
pem(pair.private.encoded, BEGIN_KEY, END_KEY),
|
||||
)
|
||||
Log.i(TAG, "已生成 TLS 自签证书: ${fingerprintOf(certificate)}")
|
||||
return TlsIdentity(certificate, pair.private)
|
||||
}
|
||||
|
||||
private fun pem(der: ByteArray, begin: String, end: String): String =
|
||||
"$begin\n${Base64.encodeToString(der, Base64.NO_WRAP)}\n$end\n"
|
||||
|
||||
private fun pemBody(text: String, begin: String, end: String): String? {
|
||||
val start = text.indexOf(begin)
|
||||
val stop = text.indexOf(end)
|
||||
if (start < 0 || stop <= start) return null
|
||||
return text.substring(start + begin.length, stop).replace("\r", "").replace("\n", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -191,6 +191,8 @@ class SenderBridge {
|
||||
if (native != null) {
|
||||
// 先确保本机控制/媒体端口在监听,再让被控端立刻拨号(不必等它下次广播)。
|
||||
// 监听失败必须显式报错:否则被控端拨号会没人接,界面只能笼统地等到超时。
|
||||
// 指纹要在监听前设好:被控端可能在同一秒内反连,握手时读的就是这个值。
|
||||
native.setTlsFingerprint(device.tlsFingerprint);
|
||||
if (!native.startDemoServer()) {
|
||||
throw Exception('本机监听启动失败(TCP 41001 / UDP 41000、41002 可能被占用)');
|
||||
}
|
||||
|
||||
@@ -103,6 +103,9 @@ class NativeCore {
|
||||
late final DartDemoSendControlFn _demoSendControl = _library
|
||||
.lookup<NativeFunction<NativeDemoSendControlFn>>('ttstd_demo_send_control')
|
||||
.asFunction();
|
||||
/// 老版本 Core 没有这个导出,缺失时按明文连接处理。
|
||||
late final DartDemoSetTlsFingerprintFn? _demoSetTlsFingerprint =
|
||||
_resolveDemoSetTlsFingerprint();
|
||||
/// 老版本 Core 没有这个导出,缺失时降级成「没有上行事件」。
|
||||
late final DartEventNextFn? _eventNext = _resolveEventNext();
|
||||
late final DartFileRequestFn _fileRequest = _library
|
||||
@@ -216,6 +219,18 @@ class NativeCore {
|
||||
return _demoStart(controlPort, videoPort, audioPort) == ok;
|
||||
}
|
||||
|
||||
/// 设置控制通道要求的被控端证书指纹(空串表示明文直连)。
|
||||
///
|
||||
/// 必须在启动监听前调用;切到不支持 TLS 的设备时要显式传空串清掉上一次的值,
|
||||
/// 否则会被旧指纹挡在握手之外。
|
||||
void setTlsFingerprint(String fingerprint) {
|
||||
final set = _demoSetTlsFingerprint;
|
||||
if (set == null) return;
|
||||
final text = fingerprint.trim();
|
||||
final bytes = utf8.encode(text);
|
||||
_withUtf8(text, (ptr) => set(ptr, bytes.length));
|
||||
}
|
||||
|
||||
void stopDemoServer() => _demoStop();
|
||||
|
||||
/// 通过信令服务器建立中继控制会话(只承载控制帧,不支持投屏)。
|
||||
@@ -282,6 +297,15 @@ class NativeCore {
|
||||
}
|
||||
}
|
||||
|
||||
DartDemoSetTlsFingerprintFn? _resolveDemoSetTlsFingerprint() {
|
||||
if (!_library.providesSymbol('ttstd_demo_set_tls_fingerprint')) return null;
|
||||
return _library
|
||||
.lookup<NativeFunction<NativeDemoSetTlsFingerprintFn>>(
|
||||
'ttstd_demo_set_tls_fingerprint',
|
||||
)
|
||||
.asFunction();
|
||||
}
|
||||
|
||||
DartEventNextFn? _resolveEventNext() {
|
||||
if (!_library.providesSymbol('ttstd_event_next')) return null;
|
||||
return _library
|
||||
@@ -518,6 +542,8 @@ typedef NativeDemoStopFn = Void Function();
|
||||
typedef DartDemoStopFn = void Function();
|
||||
typedef NativeDemoStatusFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartDemoStatusFn = int Function(Pointer<Uint8>, int);
|
||||
typedef NativeDemoSetTlsFingerprintFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartDemoSetTlsFingerprintFn = int Function(Pointer<Uint8>, int);
|
||||
typedef NativeEventNextFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartEventNextFn = int Function(Pointer<Uint8>, int);
|
||||
typedef NativeFileRequestFn = Int32 Function(
|
||||
|
||||
@@ -24,6 +24,7 @@ use crate::control::SecureControlChannel;
|
||||
use crate::crypto::{derive_subkey, EphemeralKeyPair};
|
||||
use crate::media::decode_media_packet;
|
||||
use crate::session::relay::{self, RelayChannel, RelayMessage};
|
||||
use crate::session::tls::PinnedTlsStream;
|
||||
|
||||
pub const DEFAULT_CONTROL_PORT: u16 = 41001;
|
||||
pub const DEFAULT_VIDEO_PORT: u16 = 41000;
|
||||
@@ -78,11 +79,12 @@ impl DemoStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// 控制帧写端:直连写 TCP,跨网段写信令中继。
|
||||
/// 控制帧写端:直连写 TCP,跨网段写信令中继,启用 TLS 时写加密流。
|
||||
#[derive(Clone)]
|
||||
enum ControlSink {
|
||||
Tcp(Arc<Mutex<TcpStream>>),
|
||||
Relay(Arc<RelayChannel>),
|
||||
Tls(Arc<Mutex<PinnedTlsStream>>),
|
||||
}
|
||||
|
||||
impl ControlSink {
|
||||
@@ -98,6 +100,12 @@ impl ControlSink {
|
||||
Self::Relay(channel) => channel
|
||||
.send_frame(frame)
|
||||
.map_err(|error| format!("中继下发失败:{}", error)),
|
||||
Self::Tls(stream) => {
|
||||
let mut stream = stream.lock().map_err(|_| "控制写端锁不可用".to_string())?;
|
||||
stream
|
||||
.write_all(frame)
|
||||
.map_err(|error| format!("控制帧下发失败:{}", error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,12 +113,20 @@ impl ControlSink {
|
||||
matches!(self, Self::Relay(_))
|
||||
}
|
||||
|
||||
/// 只对 TCP 生效:打断阻塞中的读,让控制连接尽快退出。
|
||||
/// 只对 TCP/TLS 生效:打断阻塞中的读,让控制连接尽快退出。
|
||||
fn shutdown(&self) {
|
||||
if let Self::Tcp(stream) = self {
|
||||
if let Ok(stream) = stream.lock() {
|
||||
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||||
match self {
|
||||
Self::Tcp(stream) => {
|
||||
if let Ok(stream) = stream.lock() {
|
||||
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||||
}
|
||||
}
|
||||
Self::Tls(stream) => {
|
||||
if let Ok(stream) = stream.lock() {
|
||||
stream.shutdown();
|
||||
}
|
||||
}
|
||||
Self::Relay(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -280,6 +296,23 @@ struct ServerHandle {
|
||||
|
||||
static SERVER: OnceLock<ServerHandle> = OnceLock::new();
|
||||
|
||||
/// 期望的对端 TLS 证书指纹;为空表示对端不支持 TLS(走明文,兼容旧版本)。
|
||||
static EXPECTED_TLS: Mutex<String> = Mutex::new(String::new());
|
||||
|
||||
/// 设置本机作为 TLS 客户端时要求的证书指纹(`sha256:...`,空串表示禁用 TLS)。
|
||||
pub fn set_tls_fingerprint(fingerprint: &str) {
|
||||
if let Ok(mut guard) = EXPECTED_TLS.lock() {
|
||||
*guard = fingerprint.trim().to_string();
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_tls_fingerprint() -> String {
|
||||
EXPECTED_TLS
|
||||
.lock()
|
||||
.map(|guard| guard.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn server_handle() -> &'static ServerHandle {
|
||||
SERVER.get_or_init(|| ServerHandle {
|
||||
shared: Arc::new(Shared::new()),
|
||||
@@ -827,7 +860,7 @@ pub fn config_event(sequence: u16, json: String) -> ControlEvent {
|
||||
fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
|
||||
while shared.running.load(Ordering::Relaxed) {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, address)) => {
|
||||
Ok((stream, address)) => {
|
||||
// 中继会话期间拒绝新的直连:两套密钥同时存在只会互相覆盖。
|
||||
if shared.relay_running.load(Ordering::SeqCst) {
|
||||
shared.push_event(format!("peer-rejected:relay:{}", address));
|
||||
@@ -843,7 +876,7 @@ fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
|
||||
shared.push_event(format!("peer:{}", address));
|
||||
// 握手前给短一点的超时:半开连接不能长时间拖住监听线程(会推迟端口释放)。
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_millis(1200)));
|
||||
handle_peer(&mut stream, &shared);
|
||||
handle_peer(stream, &shared);
|
||||
shared.peer_connected.store(false, Ordering::Relaxed);
|
||||
shared.key_established.store(false, Ordering::Relaxed);
|
||||
if let Ok(mut guard) = shared.sender.lock() {
|
||||
@@ -863,7 +896,25 @@ fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
|
||||
fn handle_peer(stream: TcpStream, shared: &Arc<Shared>) {
|
||||
let fingerprint = expected_tls_fingerprint();
|
||||
if fingerprint.is_empty() {
|
||||
let mut stream = stream;
|
||||
handle_peer_plain(&mut stream, shared);
|
||||
return;
|
||||
}
|
||||
// 被控端先反连本机,但 TLS 角色是本机做客户端、被控端做服务端:
|
||||
// 由本机发 ClientHello,并用发现信息里的 `tls` 指纹校验对端证书。
|
||||
match PinnedTlsStream::accept(stream, &fingerprint) {
|
||||
Ok(tls) => {
|
||||
shared.push_event("tls:handshake-ok".to_string());
|
||||
handle_peer_tls(Arc::new(Mutex::new(tls)), shared);
|
||||
}
|
||||
Err(error) => shared.push_event(format!("error:tls:{}", error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_peer_plain(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
|
||||
let local_pair = match EphemeralKeyPair::generate() {
|
||||
Ok(pair) => pair,
|
||||
Err(_) => {
|
||||
@@ -982,6 +1033,175 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
|
||||
}
|
||||
|
||||
/// 处理一帧已解出的控制事件:把界面要处理的事件入队,并回 `pong`。
|
||||
/// 派生并安装 control/video/audio 三把子密钥,返回 control key。
|
||||
fn install_session_keys(shared: &Shared, shared_secret: &[u8]) -> Option<[u8; 32]> {
|
||||
let control = derive_subkey(shared_secret, b"lancast/control/v1").ok()?;
|
||||
let video = derive_subkey(shared_secret, b"lancast/video/v1").ok()?;
|
||||
let audio = derive_subkey(shared_secret, b"lancast/audio/v1").ok()?;
|
||||
for (slot, key) in [
|
||||
(&shared.control_key, control),
|
||||
(&shared.video_key, video),
|
||||
(&shared.audio_key, audio),
|
||||
] {
|
||||
if let Ok(mut guard) = slot.lock() {
|
||||
*guard = Some(key);
|
||||
}
|
||||
}
|
||||
shared.key_established.store(true, Ordering::Relaxed);
|
||||
shared.push_event("key-established".to_string());
|
||||
Some(control)
|
||||
}
|
||||
|
||||
/// 在 TLS 流上读满指定长度;超时按整体 deadline 计算。
|
||||
fn tls_read_exact(
|
||||
tls: &Arc<Mutex<PinnedTlsStream>>,
|
||||
buffer: &mut [u8],
|
||||
timeout: Duration,
|
||||
) -> bool {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut filled = 0;
|
||||
while filled < buffer.len() {
|
||||
let result = {
|
||||
let Ok(mut guard) = tls.lock() else {
|
||||
return false;
|
||||
};
|
||||
guard.read(&mut buffer[filled..])
|
||||
};
|
||||
match result {
|
||||
Ok(0) => return false,
|
||||
Ok(size) => filled += size,
|
||||
Err(error) if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||||
) =>
|
||||
{
|
||||
if Instant::now() >= deadline {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Err(_) => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// TLS 控制连接:与明文路径逻辑一致,只是读写都在加密流上,且读超时更短以便发心跳。
|
||||
fn handle_peer_tls(tls: Arc<Mutex<PinnedTlsStream>>, shared: &Arc<Shared>) {
|
||||
let local_pair = match EphemeralKeyPair::generate() {
|
||||
Ok(pair) => pair,
|
||||
Err(_) => {
|
||||
shared.push_event("error:ecdh-generate".to_string());
|
||||
return;
|
||||
}
|
||||
};
|
||||
let local_public = local_pair.public_bytes().to_vec();
|
||||
let mut peer_public = [0u8; PUBLIC_KEY_LEN];
|
||||
if !tls_read_exact(&tls, &mut peer_public, Duration::from_secs(5)) {
|
||||
shared.push_event("error:peer-public".to_string());
|
||||
return;
|
||||
}
|
||||
let shared_secret = match local_pair.into_shared_secret(&peer_public) {
|
||||
Ok(secret) => secret,
|
||||
Err(_) => {
|
||||
shared.push_event("error:ecdh-agree".to_string());
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Some(control) = install_session_keys(shared, &shared_secret) else {
|
||||
return;
|
||||
};
|
||||
if let Ok(mut stream) = tls.lock() {
|
||||
if stream.write_all(&local_public).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// 握手完成,改短读超时:空闲时定期发 ping,同时不阻塞其它线程写入。
|
||||
if let Ok(stream) = tls.lock() {
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
|
||||
}
|
||||
|
||||
let channel = Arc::new(SecureControlChannel::new(control));
|
||||
let sink = ControlSink::Tls(Arc::clone(&tls));
|
||||
if let Ok(mut guard) = shared.sender.lock() {
|
||||
*guard = Some(ControlSender {
|
||||
sink: sink.clone(),
|
||||
channel: Arc::clone(&channel),
|
||||
});
|
||||
}
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
let mut keepalive_sequence = 0u16;
|
||||
let mut last_ping = Instant::now();
|
||||
while shared.running.load(Ordering::Relaxed) {
|
||||
let read = {
|
||||
let Ok(mut guard) = tls.lock() else {
|
||||
break;
|
||||
};
|
||||
guard.read(&mut chunk)
|
||||
};
|
||||
match read {
|
||||
Ok(0) => {
|
||||
shared.push_event("control:eof".to_string());
|
||||
break;
|
||||
}
|
||||
Ok(size) => {
|
||||
buffer.extend_from_slice(&chunk[..size]);
|
||||
if buffer.len() > MAX_FRAME {
|
||||
shared.push_event("error:frame-too-large".to_string());
|
||||
break;
|
||||
}
|
||||
loop {
|
||||
match channel.decode(&buffer) {
|
||||
Ok(Some((event, consumed))) => {
|
||||
buffer.drain(..consumed);
|
||||
dispatch_control_event(shared, &event, &channel, &sink);
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
shared.push_event(format!("error:control:{}", error));
|
||||
buffer.clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||||
) =>
|
||||
{
|
||||
if last_ping.elapsed() < Duration::from_secs(2) {
|
||||
continue;
|
||||
}
|
||||
keepalive_sequence = keepalive_sequence.wrapping_add(1);
|
||||
let ping = ControlEvent::new(keepalive_sequence, ControlEventKind::Ping(0));
|
||||
if let Ok(frame) = channel.encode(&ping) {
|
||||
if sink.send(&frame).is_err() {
|
||||
shared.push_event("control:keepalive-write-error".to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
last_ping = Instant::now();
|
||||
}
|
||||
Err(error) => {
|
||||
shared.push_event(format!("control:read-error:{}", error));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(mut guard) = shared.sender.lock() {
|
||||
let is_tls = guard
|
||||
.as_ref()
|
||||
.map(|sender| matches!(&sender.sink, ControlSink::Tls(_)))
|
||||
.unwrap_or(false);
|
||||
if is_tls {
|
||||
*guard = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_control_event(
|
||||
shared: &Shared,
|
||||
event: &ControlEvent,
|
||||
|
||||
@@ -38,6 +38,8 @@ pub struct BeaconDevice {
|
||||
pub media_port: u16,
|
||||
pub audio_port: u16,
|
||||
pub fingerprint: String,
|
||||
/// TLS 自签证书 SHA-256;空串表示对端不支持 TLS。
|
||||
pub tls_fingerprint: String,
|
||||
pub capabilities: Vec<String>,
|
||||
pub model: String,
|
||||
pub resolution: String,
|
||||
@@ -60,6 +62,7 @@ pub fn parse_offer(text: &str, ip: &str) -> Option<BeaconDevice> {
|
||||
media_port: port_field(&value, "media").unwrap_or(41000),
|
||||
audio_port: port_field(&value, "audio").unwrap_or(41002),
|
||||
fingerprint: text_field(&value, "fp").unwrap_or_default(),
|
||||
tls_fingerprint: text_field(&value, "tls").unwrap_or_default(),
|
||||
capabilities: value
|
||||
.get("cap")
|
||||
.and_then(JsonValue::as_array)
|
||||
@@ -170,6 +173,9 @@ pub fn device_json(device: &BeaconDevice) -> JsonValue {
|
||||
value.insert("mediaPort", JsonValue::from(device.media_port as u64));
|
||||
value.insert("audioPort", JsonValue::from(device.audio_port as u64));
|
||||
value.insert("fp", JsonValue::from(device.fingerprint.as_str()));
|
||||
if !device.tls_fingerprint.is_empty() {
|
||||
value.insert("tls", JsonValue::from(device.tls_fingerprint.as_str()));
|
||||
}
|
||||
value.insert(
|
||||
"cap",
|
||||
JsonValue::Array(device.capabilities.iter().map(JsonValue::from).collect()),
|
||||
|
||||
@@ -10,6 +10,8 @@ pub struct DeviceInfo {
|
||||
pub media_port: u16,
|
||||
pub control_port: u16,
|
||||
pub fingerprint: String,
|
||||
/// TLS 自签证书 SHA-256;空串表示对端不支持 TLS。
|
||||
pub tls_fingerprint: String,
|
||||
pub capabilities: Vec<String>,
|
||||
pub model: String,
|
||||
pub resolution: String,
|
||||
@@ -47,6 +49,9 @@ impl DeviceInfo {
|
||||
media_port,
|
||||
control_port,
|
||||
fingerprint,
|
||||
tls_fingerprint: required_string(value, "tls")
|
||||
.or_else(|| required_string(value, "tlsFp"))
|
||||
.unwrap_or_default(),
|
||||
capabilities,
|
||||
model: required_string(value, "model").unwrap_or_default(),
|
||||
resolution: required_string(value, "res").unwrap_or_default(),
|
||||
@@ -63,6 +68,9 @@ impl DeviceInfo {
|
||||
value.insert("controlPort", JsonValue::from(self.control_port as u64));
|
||||
value.insert("mediaPort", JsonValue::from(self.media_port as u64));
|
||||
value.insert("fp", JsonValue::from(self.fingerprint.as_str()));
|
||||
if !self.tls_fingerprint.is_empty() {
|
||||
value.insert("tls", JsonValue::from(self.tls_fingerprint.as_str()));
|
||||
}
|
||||
value.insert(
|
||||
"cap",
|
||||
JsonValue::Array(self.capabilities.iter().map(JsonValue::from).collect()),
|
||||
@@ -83,6 +91,9 @@ impl DeviceInfo {
|
||||
value.insert("mediaPort", JsonValue::from(self.media_port as u64));
|
||||
value.insert("controlPort", JsonValue::from(self.control_port as u64));
|
||||
value.insert("fp", JsonValue::from(self.fingerprint.as_str()));
|
||||
if !self.tls_fingerprint.is_empty() {
|
||||
value.insert("tls", JsonValue::from(self.tls_fingerprint.as_str()));
|
||||
}
|
||||
value.insert(
|
||||
"cap",
|
||||
JsonValue::Array(self.capabilities.iter().map(JsonValue::from).collect()),
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct MdnsTxt {
|
||||
pub resolution: String,
|
||||
pub model: String,
|
||||
pub fingerprint: String,
|
||||
/// TLS 自签证书 SHA-256;空串表示对端不支持 TLS。
|
||||
pub tls_fingerprint: String,
|
||||
pub signaling_url: Option<String>,
|
||||
pub media_port: Option<u16>,
|
||||
/// 设备自己声明的 id(Android 用 UUID),拿不到时退回 mDNS 实例名。
|
||||
@@ -40,6 +42,7 @@ impl MdnsTxt {
|
||||
resolution: "1920x1080".to_string(),
|
||||
model: String::new(),
|
||||
fingerprint: fingerprint.into(),
|
||||
tls_fingerprint: String::new(),
|
||||
signaling_url: None,
|
||||
media_port: None,
|
||||
device_id: None,
|
||||
@@ -63,6 +66,9 @@ impl MdnsTxt {
|
||||
if let Some(port) = self.media_port {
|
||||
records.push(format!("mport={}", port));
|
||||
}
|
||||
if !self.tls_fingerprint.is_empty() {
|
||||
records.push(format!("tls={}", self.tls_fingerprint));
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
@@ -75,6 +81,7 @@ impl MdnsTxt {
|
||||
resolution: String::new(),
|
||||
model: String::new(),
|
||||
fingerprint: String::new(),
|
||||
tls_fingerprint: String::new(),
|
||||
signaling_url: None,
|
||||
media_port: None,
|
||||
device_id: None,
|
||||
@@ -98,6 +105,7 @@ impl MdnsTxt {
|
||||
"res" => result.resolution = value.to_string(),
|
||||
"model" => result.model = value.to_string(),
|
||||
"fp" => result.fingerprint = value.to_string(),
|
||||
"tls" => result.tls_fingerprint = value.to_string(),
|
||||
"sig" => result.signaling_url = Some(value.to_string()),
|
||||
"mport" => result.media_port = Some(parse_u16(value)?),
|
||||
"cport" => result.control_port = Some(parse_u16(value)?),
|
||||
@@ -132,6 +140,7 @@ impl MdnsTxt {
|
||||
media_port: self.media_port.unwrap_or(media_port),
|
||||
control_port,
|
||||
fingerprint: self.fingerprint,
|
||||
tls_fingerprint: self.tls_fingerprint,
|
||||
capabilities: self.capabilities,
|
||||
model: self.model,
|
||||
resolution: self.resolution,
|
||||
|
||||
+22
-1
@@ -399,6 +399,27 @@ pub extern "C" fn ttstd_demo_stop() {
|
||||
crate::demo_server::stop();
|
||||
}
|
||||
|
||||
/// 设置控制通道 TLS 所需的对端证书指纹(空串表示对端不支持 TLS,走明文)。
|
||||
///
|
||||
/// # Safety
|
||||
/// fingerprint 指向长度为 len 的 UTF-8 字节。
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn ttstd_demo_set_tls_fingerprint(
|
||||
fingerprint: *const u8,
|
||||
len: usize,
|
||||
) -> i32 {
|
||||
let bytes = match read_slice(fingerprint, len) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(code) => return code,
|
||||
};
|
||||
let text = match std::str::from_utf8(bytes) {
|
||||
Ok(text) => text,
|
||||
Err(_) => return ERR_INVALID_ARGUMENT,
|
||||
};
|
||||
crate::demo_server::set_tls_fingerprint(text);
|
||||
OK
|
||||
}
|
||||
|
||||
/// 通过信令服务器建立中继控制会话(跨网段、无端口映射时使用)。
|
||||
///
|
||||
/// 中继只承载控制通道,视频/音频仍走 UDP 直连,因此中继模式下不能投屏。
|
||||
@@ -611,5 +632,5 @@ pub extern "C" fn ttstd_discovery_stop() {
|
||||
/// ABI 版本,便于 Dart 侧校验动态库是否匹配。
|
||||
#[no_mangle]
|
||||
pub extern "C" fn ttstd_core_abi_revision() -> i32 {
|
||||
4
|
||||
5
|
||||
}
|
||||
@@ -119,10 +119,7 @@ impl PinnedTlsStream {
|
||||
expected_fingerprint: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<Self, TlsError> {
|
||||
let normalized = normalize_fingerprint(expected_fingerprint);
|
||||
if normalized.len() < 16 || !normalized.bytes().all(|byte| byte.is_ascii_hexdigit()) {
|
||||
return Err(TlsError::Fingerprint("指纹至少需要 16 位十六进制字符".to_string()));
|
||||
}
|
||||
validate_fingerprint(expected_fingerprint)?;
|
||||
|
||||
let address = (host, port)
|
||||
.to_socket_addrs()
|
||||
@@ -133,22 +130,31 @@ impl PinnedTlsStream {
|
||||
socket.set_read_timeout(Some(timeout))?;
|
||||
socket.set_write_timeout(Some(timeout))?;
|
||||
|
||||
let provider = Arc::new(ring::default_provider());
|
||||
let verifier = Arc::new(PinnedVerifier::new(
|
||||
expected_fingerprint,
|
||||
provider.signature_verification_algorithms.clone(),
|
||||
));
|
||||
let config = ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(verifier)
|
||||
.with_no_client_auth();
|
||||
let server_name = ServerName::try_from(host.to_string())
|
||||
.map_err(|error| TlsError::Address(error.to_string()))?;
|
||||
let connection = ClientConnection::new(Arc::new(config), server_name)?;
|
||||
let connection = client_connection(expected_fingerprint, host)?;
|
||||
Ok(Self { connection, socket })
|
||||
}
|
||||
|
||||
/// 在**已建立的连接**上做 TLS 客户端握手。
|
||||
///
|
||||
/// 被控端先反连本机,因此 TCP 监听端(主控端)反而是 TLS 客户端:
|
||||
/// 由它发送 ClientHello,被控端作为 TLS 服务端出示自签证书,指纹由发现信息固定。
|
||||
pub fn accept(socket: TcpStream, expected_fingerprint: &str) -> Result<Self, TlsError> {
|
||||
validate_fingerprint(expected_fingerprint)?;
|
||||
let connection = client_connection(expected_fingerprint, "ttstd.local")?;
|
||||
let mut stream = Self { connection, socket };
|
||||
stream.complete_handshake()?;
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
pub fn set_read_timeout(&self, timeout: Option<Duration>) -> std::io::Result<()> {
|
||||
self.socket.set_read_timeout(timeout)
|
||||
}
|
||||
|
||||
/// 关闭底层 TCP(用于 stop 时打断阻塞中的读)。
|
||||
pub fn shutdown(&self) {
|
||||
let _ = self.socket.shutdown(std::net::Shutdown::Both);
|
||||
}
|
||||
|
||||
pub fn complete_handshake(&mut self) -> Result<(), TlsError> {
|
||||
while self.connection.is_handshaking() {
|
||||
self.connection.complete_io(&mut self.socket)?;
|
||||
@@ -167,6 +173,31 @@ impl PinnedTlsStream {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_fingerprint(fingerprint: &str) -> Result<(), TlsError> {
|
||||
let normalized = normalize_fingerprint(fingerprint);
|
||||
if normalized.len() < 16 || !normalized.bytes().all(|byte| byte.is_ascii_hexdigit()) {
|
||||
return Err(TlsError::Fingerprint("指纹至少需要 16 位十六进制字符".to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 构造只信任指定证书指纹的客户端连接(不校验证书链与域名)。
|
||||
fn client_connection(expected: &str, server_name: &str) -> Result<ClientConnection, TlsError> {
|
||||
let provider = Arc::new(ring::default_provider());
|
||||
let verifier = Arc::new(PinnedVerifier::new(
|
||||
expected,
|
||||
provider.signature_verification_algorithms.clone(),
|
||||
));
|
||||
let config = ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(verifier)
|
||||
.with_no_client_auth();
|
||||
let server_name = ServerName::try_from(server_name.to_string())
|
||||
.map_err(|error| TlsError::Address(error.to_string()))?;
|
||||
Ok(ClientConnection::new(Arc::new(config), server_name)?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in new issue
Block a user