leejunyoung5819wayland-android-remote

공개

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

151줄6.1 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 private val OID_COMMON_NAME = byteArrayOf(0x06, 0x03, 0x55, 0x04, 0x03)
103
104 fun build(key: PrivateKey, spki: ByteArray, commonName: String): ByteArray {
105 val serialBytes = ByteArray(16).also { SecureRandom().nextBytes(it) }
106 serialBytes[0] = (serialBytes[0].toInt() and 0x7F).toByte() // 양수
107 val serial = der(0x02, BigInteger(serialBytes).toByteArray())
108 val sigAlg = seq(OID_ECDSA_SHA256)
109 val name = seq(set(seq(OID_COMMON_NAME, der(0x0C, commonName.toByteArray(Charsets.UTF_8)))))
110 val now = Date()
111 val validity = seq(utcTime(Date(now.time - 24L * 3600 * 1000)), utcTime(parseUtc("491231235959Z")))
112 val version = der(0xA0, der(0x02, byteArrayOf(0x02)))
113 val tbs = seq(version, serial, sigAlg, name, validity, name, spki)
114
115 val signer = Signature.getInstance("SHA256withECDSA")
116 signer.initSign(key)
117 signer.update(tbs)
118 val signature = signer.sign()
119 return seq(tbs, sigAlg, der(0x03, byteArrayOf(0x00) + signature))
120 }
121
122 private fun parseUtc(s: String): Date = utcFormat().parse(s)!!
123
124 private fun utcTime(d: Date): ByteArray = der(0x17, utcFormat().format(d).toByteArray(Charsets.US_ASCII))
125
126 private fun utcFormat() = SimpleDateFormat("yyMMddHHmmss'Z'", Locale.US).apply {
127 timeZone = TimeZone.getTimeZone("UTC")
128 }
129
130 private fun seq(vararg parts: ByteArray) = der(0x30, concat(parts))
131 private fun set(vararg parts: ByteArray) = der(0x31, concat(parts))
132
133 private fun concat(parts: Array<out ByteArray>): ByteArray {
134 val out = ByteArrayOutputStream()
135 parts.forEach { out.write(it) }
136 return out.toByteArray()
137 }
138
139 private fun der(tag: Int, content: ByteArray): ByteArray {
140 val out = ByteArrayOutputStream()
141 out.write(tag)
142 val len = content.size
143 when {
144 len < 0x80 -> out.write(len)
145 len < 0x100 -> { out.write(0x81); out.write(len) }
146 else -> { out.write(0x82); out.write(len shr 8); out.write(len and 0xFF) }
147 }
148 out.write(content)
149 return out.toByteArray()
150 }
151}