leejunyoung5819wayland-android-remote

공개

Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)

162줄6.8 KB
1package com.androidremote.daemon
2
3import android.system.Os
4import java.io.ByteArrayInputStream
5import java.io.ByteArrayOutputStream
6import java.io.File
7import java.math.BigInteger
8import java.security.KeyFactory
9import java.security.KeyPairGenerator
10import java.security.KeyStore
11import java.security.MessageDigest
12import java.security.PrivateKey
13import java.security.SecureRandom
14import java.security.Signature
15import java.security.cert.CertificateFactory
16import java.security.cert.X509Certificate
17import java.security.spec.ECGenParameterSpec
18import java.security.spec.PKCS8EncodedKeySpec
19import java.text.SimpleDateFormat
20import java.util.Date
21import java.util.Locale
22import java.util.TimeZone
23import javax.net.ssl.KeyManagerFactory
24import javax.net.ssl.SSLContext
25
26/**
27 * 기기 TLS 신원 (기획서 5.5). 최초 실행 시 ECDSA P-256 키와 자체 서명 인증서를 만들어
28 * shell 사용자만 읽을 수 있는 디렉터리에 저장하고, 이후에는 그대로 다시 쓴다.
29 */
30class DeviceIdentity private constructor(
31 private val privateKey: PrivateKey,
32 val certificate: X509Certificate,
33) {
34 /** 인증서 DER의 SHA-256. 호스트가 고정하는 값과 같다. */
35 val fingerprint: ByteArray = MessageDigest.getInstance("SHA-256").digest(certificate.encoded)
36
37 /** 지문 앞 8바이트(Big-Endian u64) % 1,000,000. 호스트 `protocol::confirm_code`와 같은 계산. */
38 val confirmCode: String
39 get() {
40 var v = 0L
41 for (i in 0 until 8) v = (v shl 8) or (fingerprint[i].toLong() and 0xFF)
42 return "%06d".format(java.lang.Long.remainderUnsigned(v, 1_000_000))
43 }
44
45 fun sslContext(): SSLContext {
46 val ks = KeyStore.getInstance("PKCS12")
47 ks.load(null, null)
48 ks.setKeyEntry("device", privateKey, CharArray(0), arrayOf(certificate))
49 val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
50 kmf.init(ks, CharArray(0))
51 val ctx = SSLContext.getInstance("TLSv1.3")
52 ctx.init(kmf.keyManagers, null, SecureRandom())
53 return ctx
54 }
55
56 companion object {
57 private const val KEY_FILE = "device_key.pk8"
58 private const val CERT_FILE = "device_cert.der"
59
60 fun loadOrCreate(dir: File): DeviceIdentity {
61 ensurePrivateDir(dir)
62 val keyFile = File(dir, KEY_FILE)
63 val certFile = File(dir, CERT_FILE)
64 if (keyFile.exists() && certFile.exists()) {
65 val key = KeyFactory.getInstance("EC")
66 .generatePrivate(PKCS8EncodedKeySpec(keyFile.readBytes()))
67 val cert = CertificateFactory.getInstance("X.509")
68 .generateCertificate(ByteArrayInputStream(certFile.readBytes())) as X509Certificate
69 return DeviceIdentity(key, cert)
70 }
71
72 val gen = KeyPairGenerator.getInstance("EC")
73 gen.initialize(ECGenParameterSpec("secp256r1"), SecureRandom())
74 val pair = gen.generateKeyPair()
75 val der = SelfSignedCert.build(pair.private, pair.public.encoded, "android-remote-device")
76 val cert = CertificateFactory.getInstance("X.509")
77 .generateCertificate(ByteArrayInputStream(der)) as X509Certificate
78
79 writePrivate(keyFile, pair.private.encoded)
80 writePrivate(certFile, der)
81 return DeviceIdentity(pair.private, cert)
82 }
83
84 fun ensurePrivateDir(dir: File) {
85 if (!dir.exists() && !dir.mkdirs()) throw IllegalStateException("디렉터리 생성 실패: $dir")
86 Os.chmod(dir.path, "700".toInt(8))
87 }
88
89 fun writePrivate(file: File, bytes: ByteArray) {
90 file.writeBytes(bytes)
91 Os.chmod(file.path, "600".toInt(8))
92 }
93 }
94}
95
96/**
97 * 외부 라이브러리 없이 자체 서명 X.509 v3 인증서를 DER로 만든다.
98 * 호스트는 CA 검증 없이 지문만 비교하므로 확장 필드는 넣지 않는다.
99 */
100object SelfSignedCert {
101 private val OID_ECDSA_SHA256 = byteArrayOf(0x06, 0x08, 0x2A, 0x86.toByte(), 0x48, 0xCE.toByte(), 0x3D, 0x04, 0x03, 0x02)
102 /** sha256WithRSAEncryption (1.2.840.113549.1.1.11) + NULL 매개변수. */
103 private val ALG_RSA_SHA256 = byteArrayOf(
104 0x06, 0x09, 0x2A, 0x86.toByte(), 0x48, 0x86.toByte(), 0xF7.toByte(), 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00,
105 )
106 private val OID_COMMON_NAME = byteArrayOf(0x06, 0x03, 0x55, 0x04, 0x03)
107
108 /** ECDSA P-256 키로 서명한 인증서 (기기 TLS 신원). */
109 fun build(key: PrivateKey, spki: ByteArray, commonName: String): ByteArray =
110 build(key, spki, commonName, seq(OID_ECDSA_SHA256), "SHA256withECDSA")
111
112 /** RSA 키로 서명한 인증서 (동반 앱의 ADB 클라이언트 키). */
113 fun buildRsa(key: PrivateKey, spki: ByteArray, commonName: String): ByteArray =
114 build(key, spki, commonName, seq(ALG_RSA_SHA256), "SHA256withRSA")
115
116 private fun build(key: PrivateKey, spki: ByteArray, commonName: String, sigAlg: ByteArray, sigName: String): ByteArray {
117 val serialBytes = ByteArray(16).also { SecureRandom().nextBytes(it) }
118 serialBytes[0] = (serialBytes[0].toInt() and 0x7F).toByte() // 양수
119 val serial = der(0x02, BigInteger(serialBytes).toByteArray())
120 val name = seq(set(seq(OID_COMMON_NAME, der(0x0C, commonName.toByteArray(Charsets.UTF_8)))))
121 val now = Date()
122 val validity = seq(utcTime(Date(now.time - 24L * 3600 * 1000)), utcTime(parseUtc("491231235959Z")))
123 val version = der(0xA0, der(0x02, byteArrayOf(0x02)))
124 val tbs = seq(version, serial, sigAlg, name, validity, name, spki)
125
126 val signer = Signature.getInstance(sigName)
127 signer.initSign(key)
128 signer.update(tbs)
129 val signature = signer.sign()
130 return seq(tbs, sigAlg, der(0x03, byteArrayOf(0x00) + signature))
131 }
132
133 private fun parseUtc(s: String): Date = utcFormat().parse(s)!!
134
135 private fun utcTime(d: Date): ByteArray = der(0x17, utcFormat().format(d).toByteArray(Charsets.US_ASCII))
136
137 private fun utcFormat() = SimpleDateFormat("yyMMddHHmmss'Z'", Locale.US).apply {
138 timeZone = TimeZone.getTimeZone("UTC")
139 }
140
141 private fun seq(vararg parts: ByteArray) = der(0x30, concat(parts))
142 private fun set(vararg parts: ByteArray) = der(0x31, concat(parts))
143
144 private fun concat(parts: Array<out ByteArray>): ByteArray {
145 val out = ByteArrayOutputStream()
146 parts.forEach { out.write(it) }
147 return out.toByteArray()
148 }
149
150 private fun der(tag: Int, content: ByteArray): ByteArray {
151 val out = ByteArrayOutputStream()
152 out.write(tag)
153 val len = content.size
154 when {
155 len < 0x80 -> out.write(len)
156 len < 0x100 -> { out.write(0x81); out.write(len) }
157 else -> { out.write(0x82); out.write(len shr 8); out.write(len and 0xFF) }
158 }
159 out.write(content)
160 return out.toByteArray()
161 }
162}