Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / whatsapp / Y3WaSocketTransportTest.kt

Y3WaSocketTransportTest.kt176 lines · 9.1 KiBRaw
1package com.vayunmathur.communicate.whatsapp
2
3import android.util.Base64
4import com.google.protobuf.ByteString
5import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData
6import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol
7import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppHandshakeProto
8import com.vayunmathur.communicate.data.whatsapp.buildFramedMessage
9import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket
10import java.io.ByteArrayOutputStream
11import javax.crypto.spec.SecretKeySpec
12import kotlin.test.Test
13import kotlin.test.assertEquals
14import kotlin.test.assertFalse
15import kotlin.test.assertTrue
16import kotlinx.coroutines.async
17import kotlinx.coroutines.flow.first
18import kotlinx.coroutines.runBlocking
19import kotlinx.coroutines.withTimeoutOrNull
20import org.junit.runner.RunWith
21import org.robolectric.RobolectricTestRunner
22
23/**
24 * Y3: WhatsAppSocket transport internals, driven reflectively because the
25 * real endpoint is a raw-TCP Noise server: ClientHello framing, ServerHello
26 * processing up to the (unforgeable) WhatsApp root-cert check, frame
27 * reassembly in ingestBytes, and post-handshake Noise encrypt/decrypt
28 * round-trips through send()/messages.
29 */
30@RunWith(RobolectricTestRunner::class)
31class Y3WaSocketTransportTest {
32
33 private fun b64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)
34
35 private val auth = WhatsAppAuthData(
36 phoneNumber = "+15550001", pushName = "Tester", wid = "[email protected]",
37 noisePrivateKey = b64(ByteArray(32) { 1 }), noisePublicKey = b64(ByteArray(32) { 2 }),
38 identityPrivateKey = b64(ByteArray(32) { 3 }), identityPublicKey = b64(ByteArray(32) { 4 }),
39 registrationId = 14, signedPreKeyId = 5,
40 signedPreKeyPublic = b64(ByteArray(32) { 5 }), signedPreKeyPrivate = b64(ByteArray(32) { 6 }),
41 signedPreKeySignature = b64(ByteArray(64) { 7 }), lid = "12345@lid",
42 )
43
44 private fun field(obj: Any, name: String): Any? {
45 val f = obj.javaClass.getDeclaredField(name); f.isAccessible = true; return f.get(obj)
46 }
47 private fun setField(obj: Any, name: String, value: Any?) {
48 val f = obj.javaClass.getDeclaredField(name); f.isAccessible = true; f.set(obj, value)
49 }
50 private fun socketWithOutput(): Pair<WhatsAppSocket, ByteArrayOutputStream> {
51 val socket = WhatsAppSocket(auth, host = "127.0.0.1", port = 9)
52 val out = ByteArrayOutputStream()
53 setField(socket, "output", out)
54 return socket to out
55 }
56
57
58 private fun startReading(socket: WhatsAppSocket, bytes: ByteArray) {
59 setField(socket, "input", java.io.ByteArrayInputStream(bytes))
60 val m = WhatsAppSocket::class.java.getDeclaredMethod("startReadLoop"); m.isAccessible = true
61 m.invoke(socket)
62 }
63
64 @Test fun clientHelloIsFramedAndHandshakeStateSeeded() {
65 val (socket, out) = socketWithOutput()
66 val m = WhatsAppSocket::class.java.getDeclaredMethod("startNoiseHandshake"); m.isAccessible = true
67 m.invoke(socket)
68 val framed = out.toByteArray()
69 assertTrue(framed.size > 4)
70 // WA_CONN_HEADER prefix, then 3-byte length, then a ClientHello with a 32-byte ephemeral.
71 assertEquals('W'.code.toByte(), framed[0]); assertEquals('A'.code.toByte(), framed[1])
72 val payload = framed.copyOfRange(4 + 3, framed.size)
73 val hello = WhatsAppHandshakeProto.HandshakeMessage.parseFrom(payload)
74 assertEquals(32, hello.clientHello.ephemeral.size())
75 assertTrue(field(socket, "noiseHandshake") != null)
76 assertEquals(32, (field(socket, "ephemeralPrivateKey") as ByteArray).size)
77 }
78
79 @Test fun serverHelloWithForgedCertFailsVerificationAndCloses() = runBlocking {
80 val (socket, out) = socketWithOutput()
81 val start = WhatsAppSocket::class.java.getDeclaredMethod("startNoiseHandshake"); start.isAccessible = true
82 start.invoke(socket)
83 val clientHello = WhatsAppHandshakeProto.HandshakeMessage.parseFrom(
84 out.toByteArray().copyOfRange(4 + 3, out.size()))
85 val clientEph = clientHello.clientHello.ephemeral.toByteArray()
86
87 // Mirror the server side of Noise_XX with our own static key + a forged cert payload.
88 val server = WhatsAppProtocol.NoiseHandshake()
89 server.start(WhatsAppProtocol.NOISE_START_PATTERN, WhatsAppProtocol.WA_CONN_HEADER)
90 server.authenticate(clientEph)
91 val (serverEphPriv, serverEphPub) = WhatsAppProtocol.generateX25519KeyPair()
92 server.authenticate(serverEphPub)
93 server.mixSharedSecretIntoKey(serverEphPriv, clientEph)
94 val (_, serverStaticPub) = WhatsAppProtocol.generateX25519KeyPair()
95 val staticCt = server.encrypt(serverStaticPub)
96 server.mixSharedSecretIntoKey(serverEphPriv, serverStaticPub)
97 val certCt = server.encrypt(byteArrayOf(1, 2, 3)) // not a WA cert chain: must fail verify
98
99 val serverHello = WhatsAppHandshakeProto.HandshakeMessage.newBuilder()
100 .setServerHello(
101 WhatsAppHandshakeProto.HandshakeMessage.ServerHello.newBuilder()
102 .setEphemeral(ByteString.copyFrom(serverEphPub))
103 .setStatic(ByteString.copyFrom(staticCt))
104 .setPayload(ByteString.copyFrom(certCt)))
105 .build().toByteArray()
106
107 val framed = WhatsAppProtocol.buildFramedMessage(serverHello, WhatsAppProtocol.WA_CONN_HEADER)
108 startReading(socket, framed)
109 // Cert verification fails -> closeInternal runs on the socket scope and clears the
110 // handshake state; the handshake never completes.
111 val deadline = System.currentTimeMillis() + 5_000
112 while (field(socket, "noiseHandshake") != null && System.currentTimeMillis() < deadline) {
113 Thread.sleep(25)
114 }
115 assertTrue(field(socket, "noiseHandshake") == null, "expected closeInternal after cert failure")
116 assertFalse(field(socket, "isHandshakeComplete") as Boolean)
117 socket.disconnect()
118 }
119
120 @Test fun invalidServerHelloSizesAreRejected() = runBlocking {
121 val (socket, _) = socketWithOutput()
122 val start = WhatsAppSocket::class.java.getDeclaredMethod("startNoiseHandshake"); start.isAccessible = true
123 start.invoke(socket)
124 val bad = WhatsAppHandshakeProto.HandshakeMessage.newBuilder()
125 .setServerHello(
126 WhatsAppHandshakeProto.HandshakeMessage.ServerHello.newBuilder()
127 .setEphemeral(ByteString.copyFrom(ByteArray(10)))
128 .setStatic(ByteString.copyFrom(ByteArray(4)))
129 .setPayload(ByteString.copyFrom(ByteArray(4))))
130 .build().toByteArray()
131 startReading(socket, WhatsAppProtocol.buildFramedMessage(bad, WhatsAppProtocol.WA_CONN_HEADER))
132 val deadline2 = System.currentTimeMillis() + 5_000
133 while (field(socket, "noiseHandshake") != null && System.currentTimeMillis() < deadline2) {
134 Thread.sleep(25)
135 }
136 assertFalse(field(socket, "isHandshakeComplete") as Boolean)
137 socket.disconnect()
138 }
139
140 @Test fun postHandshakeFramesDecryptToMessagesAndSendEncrypts() = runBlocking {
141 val (socket, out) = socketWithOutput()
142 // Install a NoiseSocket with known keys, as sendClientFinish would after a real handshake.
143 val noiseClass = Class.forName(
144 "com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket\$NoiseSocket")
145 val ctor = noiseClass.getDeclaredConstructor(SecretKeySpec::class.java, SecretKeySpec::class.java)
146 ctor.isAccessible = true
147 val key = SecretKeySpec(ByteArray(32) { (it * 3 + 1).toByte() }, "AES")
148 val noise = ctor.newInstance(key, key)
149 setField(socket, "noiseSocket", noise)
150 setField(socket, "isConnected", true)
151 setField(socket, "isHandshakeComplete", true)
152
153 assertTrue(socket.send(byteArrayOf(9, 8, 7)))
154 assertTrue(out.size() > 3)
155
156 // A peer NoiseSocket with the same keys encrypts a frame we then ingest (split across reads).
157 val peerNoise = ctor.newInstance(key, key)
158 val encrypt = noiseClass.getDeclaredMethod("encrypt", ByteArray::class.java); encrypt.isAccessible = true
159 // Advance peer counter past our send (counters are independent per direction in this harness,
160 // both start at 0; our socket's read counter starts at 0, peer encrypt counter at 0 -> matches).
161 val frame = encrypt.invoke(peerNoise, "hello noise".toByteArray()) as ByteArray
162 val framed = WhatsAppProtocol.buildFramedMessage(frame, WhatsAppProtocol.WA_CONN_HEADER)
163 val garbage = WhatsAppProtocol.buildFramedMessage(byteArrayOf(1, 2, 3, 4), null)
164 val collector = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined).async { socket.messages.first() }
165 startReading(socket, framed + garbage)
166 val msg = withTimeoutOrNull(5_000) { collector.await() }
167 assertEquals("hello noise", msg?.decodeToString())
168 socket.disconnect()
169 }
170
171 @Test fun sendFailsClosedWhenNotConnected() {
172 val socket = WhatsAppSocket(auth, host = "127.0.0.1", port = 9)
173 assertFalse(socket.send(byteArrayOf(1)))
174 socket.disconnect()
175 }
176}