mirror of
https://gitlab.com/futo-org/fcast.git
synced 2025-06-24 21:25:23 +00:00
Added encryption.
This commit is contained in:
parent
b8bd78d90d
commit
9599c1931e
29 changed files with 1016 additions and 1069 deletions
|
@ -20,12 +20,12 @@ if (keystorePropertiesFile.exists()) {
|
|||
|
||||
android {
|
||||
namespace 'com.futo.fcast.receiver'
|
||||
compileSdk 33
|
||||
compileSdk 34
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.futo.fcast.receiver"
|
||||
minSdk 24
|
||||
targetSdk 33
|
||||
targetSdk 34
|
||||
versionCode currentVersionCode
|
||||
versionName currentVersionName
|
||||
|
||||
|
@ -75,17 +75,22 @@ android {
|
|||
kotlinOptions {
|
||||
jvmTarget = '1.8'
|
||||
}
|
||||
buildFeatures {
|
||||
buildConfig true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'androidx.core:core-ktx:1.7.0'
|
||||
implementation 'androidx.core:core-ktx:1.12.0'
|
||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||
implementation 'com.google.android.material:material:1.8.0'
|
||||
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0"
|
||||
implementation 'com.google.android.exoplayer:exoplayer:2.18.6'
|
||||
implementation 'com.google.android.material:material:1.11.0'
|
||||
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2"
|
||||
implementation 'com.google.android.exoplayer:exoplayer:2.19.1'
|
||||
implementation "com.squareup.okhttp3:okhttp:4.11.0"
|
||||
implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
|
||||
implementation 'org.java-websocket:Java-WebSocket:1.5.4'
|
||||
implementation 'org.bouncycastle:bcpkix-jdk18on:1.77'
|
||||
implementation 'org.bouncycastle:bcprov-jdk18on:1.77'
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
|
||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
|
||||
|
|
|
@ -1,113 +0,0 @@
|
|||
package com.futo.fcast.receiver
|
||||
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import kotlinx.serialization.decodeFromString
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
import org.junit.Assert.*
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyPair
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.spec.PKCS8EncodedKeySpec
|
||||
import java.security.spec.X509EncodedKeySpec
|
||||
import javax.crypto.interfaces.DHPrivateKey
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class EncryptionTest {
|
||||
@Test
|
||||
fun testDHEncryptionSelf() {
|
||||
val keyPair1 = FCastSession.generateKeyPair()
|
||||
val keyPair2 = FCastSession.generateKeyPair()
|
||||
Log.i("testDHEncryptionSelf", "privates (1: ${Base64.encodeToString(keyPair1.private.encoded, Base64.NO_WRAP)}, 2: ${Base64.encodeToString(keyPair2.private.encoded, Base64.NO_WRAP)})")
|
||||
|
||||
val keyExchangeMessage1 = FCastSession.getKeyExchangeMessage(keyPair1)
|
||||
val keyExchangeMessage2 = FCastSession.getKeyExchangeMessage(keyPair2)
|
||||
Log.i("testDHEncryptionSelf", "publics (1: ${keyExchangeMessage1.publicKey}, 2: ${keyExchangeMessage2.publicKey})")
|
||||
|
||||
val aesKey1 = FCastSession.computeSharedSecret(keyPair1.private, keyExchangeMessage2)
|
||||
val aesKey2 = FCastSession.computeSharedSecret(keyPair2.private, keyExchangeMessage1)
|
||||
|
||||
assertEquals(Base64.encodeToString(aesKey1.encoded, Base64.NO_WRAP), Base64.encodeToString(aesKey2.encoded, Base64.NO_WRAP))
|
||||
Log.i("testDHEncryptionSelf", "aesKey ${Base64.encodeToString(aesKey1.encoded, Base64.NO_WRAP)}")
|
||||
|
||||
val message = PlayMessage("text/html")
|
||||
val serializedBody = Json.encodeToString(message)
|
||||
val encryptedMessage = FCastSession.encryptMessage(aesKey1, DecryptedMessage(Opcode.Play.value.toLong(), serializedBody))
|
||||
Log.i("testDHEncryptionSelf", Json.encodeToString(encryptedMessage))
|
||||
|
||||
val decryptedMessage = FCastSession.decryptMessage(aesKey1, encryptedMessage)
|
||||
|
||||
assertEquals(Opcode.Play.value.toLong(), decryptedMessage.opcode)
|
||||
assertEquals(serializedBody, decryptedMessage.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testAESKeyGeneration() {
|
||||
val cases = listOf(
|
||||
listOf(
|
||||
//Public other
|
||||
"MIIBHzCBlQYJKoZIhvcNAQMBMIGHAoGBAP//////////yQ/aoiFowjTExmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR7OZTgf//////////AgECA4GEAAKBgEnOS0oHteVA+3kND3u4yXe7GGRohy1LkR9Q5tL4c4ylC5n4iSwWSoIhcSIvUMWth6KAhPhu05sMcPY74rFMSS2AGTNCdT/5KilediipuUMdFVvjGqfNMNH1edzW5mquIw3iXKdfQmfY/qxLTI2wccyDj4hHFhLCZL3Y+shsm3KF",
|
||||
//Private self
|
||||
"MIIBIQIBADCBlQYJKoZIhvcNAQMBMIGHAoGBAP//////////yQ/aoiFowjTExmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR7OZTgf//////////AgECBIGDAoGAeo/ceIeH8Jt1ZRNKX5aTHkMi23GCV1LtcS2O6Tktn9k8DCv7gIoekysQUhMyWtR+MsZlq2mXjr1JFpAyxl89rqoEPU6QDsGe9q8R4O8eBZ2u+48mkUkGSh7xPGRQUBvmhH2yk4hIEA8aK4BcYi1OTsCZtmk7pQq+uaFkKovD/8M=",
|
||||
//AES
|
||||
"7dpl1/6KQTTooOrFf2VlUOSqgrFHi6IYxapX0IxFfwk="
|
||||
),
|
||||
listOf(
|
||||
//Public other
|
||||
"MIIBHzCBlQYJKoZIhvcNAQMBMIGHAoGBAP//////////yQ/aoiFowjTExmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR7OZTgf//////////AgECA4GEAAKBgGvIlCP/S+xpAuNEHSn4cEDOL1esUf+uMuY2Kp5J10a7HGbwzNd+7eYsgEc4+adddgB7hJgTvjsGg7lXUhHQ7WbfbCGgt7dbkx8qkic6Rgq4f5eRYd1Cgidw4MhZt7mEIOKrHweqnV6B9rypbXjbqauc6nGgtwx+Gvl6iLpVATRK",
|
||||
//Private self
|
||||
"MIIBIQIBADCBlQYJKoZIhvcNAQMBMIGHAoGBAP//////////yQ/aoiFowjTExmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR7OZTgf//////////AgECBIGDAoGAMXmiIgWyutbaO+f4UiMAb09iVVSCI6Lb6xzNyD2MpUZyk4/JOT04Daj4JeCKFkF1Fq79yKhrnFlXCrF4WFX00xUOXb8BpUUUH35XG5ApvolQQLL6N0om8/MYP4FK/3PUxuZAJz45TUsI/v3u6UqJelVTNL83ltcFbZDIfEVftRA=",
|
||||
//AES
|
||||
"a2tUSxnXifKohfNocAQHkAlPffDv6ReihJ7OojBGt0Q="
|
||||
)
|
||||
)
|
||||
|
||||
for (case in cases) {
|
||||
val decodedPrivateKey1 = Base64.decode(case[1], Base64.NO_WRAP)
|
||||
val keyExchangeMessage2 = KeyExchangeMessage(1, case[0])
|
||||
|
||||
val keyFactory = KeyFactory.getInstance("DH")
|
||||
val privateKeySpec = PKCS8EncodedKeySpec(decodedPrivateKey1)
|
||||
val privateKey = keyFactory.generatePrivate(privateKeySpec)
|
||||
val aesKey1 = FCastSession.computeSharedSecret(privateKey, keyExchangeMessage2)
|
||||
assertEquals(case[2], Base64.encodeToString(aesKey1.encoded, Base64.NO_WRAP))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDHEncryptionKnown() {
|
||||
val decodedPrivateKey1 = Base64.decode("MIIDJwIBADCCAhgGCSqGSIb3DQEDATCCAgkCggEBAJVHXPXZPllsP80dkCrdAvQn9fPHIQMTu0X7TVuy5f4cvWeM1LvdhMmDa+HzHAd3clrrbC/Di4X0gHb6drzYFGzImm+y9wbdcZiYwgg9yNiW+EBi4snJTRN7BUqNgJatuNUZUjmO7KhSoK8S34Pkdapl1OwMOKlWDVZhGG/5i5/J62Du6LAwN2sja8c746zb10/WHB0kdfowd7jwgEZ4gf9+HKVv7gZteVBq3lHtu1RDpWOSfbxLpSAIZ0YXXIiFkl68ZMYUeQZ3NJaZDLcU7GZzBOJh+u4zs8vfAI4MP6kGUNl9OQnJJ1v0rIb/yz0D5t/IraWTQkLdbTvMoqQGywsCggEAQt67naWz2IzJVuCHh+w/Ogm7pfSLiJp0qvUxdKoPvn48W4/NelO+9WOw6YVgMolgqVF/QBTTMl/Hlivx4Ek3DXbRMUp2E355Lz8NuFnQleSluTICTweezy7wnHl0UrB3DhNQeC7Vfd95SXnc7yPLlvGDBhllxOvJPJxxxWuSWVWnX5TMzxRJrEPVhtC+7kMlGwsihzSdaN4NFEQD8T6AL0FG2ILgV68ZtvYnXGZ2yPoOPKJxOjJX/Rsn0GOfaV40fY0c+ayBmibKmwTLDrm3sDWYjRW7rGUhKlUjnPx+WPrjjXJQq5mR/7yXE0Al/ozgTEOZrZZWm+kaVG9JeGk8egSCAQQCggEAECNvEczf0y6IoX/IwhrPeWZ5IxrHcpwjcdVAuyZQLLlOq0iqnYMFcSD8QjMF8NKObfZZCDQUJlzGzRsG0oXsWiWtmoRvUZ9tQK0j28hDylpbyP00Bt9NlMgeHXkAy54P7Z2v/BPCd3o23kzjgXzYaSRuCFY7zQo1g1IQG8mfjYjdE4jjRVdVrlh8FS8x4OLPeglc+cp2/kuyxaVEfXAG84z/M8019mRSfdczi4z1iidPX6HgDEEWsN42Ud60mNKy5jsQpQYkRdOLmxR3+iQEtGFjdzbVhVCUr7S5EORU9B1MOl5gyPJpjfU3baOqrg6WXVyTvMDaA05YEnAHQNOOfA==", Base64.NO_WRAP)
|
||||
val keyExchangeMessage2 = KeyExchangeMessage(1, "MIIDJTCCAhgGCSqGSIb3DQEDATCCAgkCggEBAJVHXPXZPllsP80dkCrdAvQn9fPHIQMTu0X7TVuy5f4cvWeM1LvdhMmDa+HzHAd3clrrbC/Di4X0gHb6drzYFGzImm+y9wbdcZiYwgg9yNiW+EBi4snJTRN7BUqNgJatuNUZUjmO7KhSoK8S34Pkdapl1OwMOKlWDVZhGG/5i5/J62Du6LAwN2sja8c746zb10/WHB0kdfowd7jwgEZ4gf9+HKVv7gZteVBq3lHtu1RDpWOSfbxLpSAIZ0YXXIiFkl68ZMYUeQZ3NJaZDLcU7GZzBOJh+u4zs8vfAI4MP6kGUNl9OQnJJ1v0rIb/yz0D5t/IraWTQkLdbTvMoqQGywsCggEAQt67naWz2IzJVuCHh+w/Ogm7pfSLiJp0qvUxdKoPvn48W4/NelO+9WOw6YVgMolgqVF/QBTTMl/Hlivx4Ek3DXbRMUp2E355Lz8NuFnQleSluTICTweezy7wnHl0UrB3DhNQeC7Vfd95SXnc7yPLlvGDBhllxOvJPJxxxWuSWVWnX5TMzxRJrEPVhtC+7kMlGwsihzSdaN4NFEQD8T6AL0FG2ILgV68ZtvYnXGZ2yPoOPKJxOjJX/Rsn0GOfaV40fY0c+ayBmibKmwTLDrm3sDWYjRW7rGUhKlUjnPx+WPrjjXJQq5mR/7yXE0Al/ozgTEOZrZZWm+kaVG9JeGk8egOCAQUAAoIBAGlL9EYsrFz3I83NdlwhM241M+M7PA9P5WXgtdvS+pcalIaqN2IYdfzzCUfye7lchVkT9A2Y9eWQYX0OUhmjf8PPKkRkATLXrqO5HTsxV96aYNxMjz5ipQ6CaErTQaPLr3OPoauIMPVVI9zM+WT0KOGp49YMyx+B5rafT066vOVbF/0z1crq0ZXxyYBUv135rwFkIHxBMj5bhRLXKsZ2G5aLAZg0DsVam104mgN/v75f7Spg/n5hO7qxbNgbvSrvQ7Ag/rMk5T3sk7KoM23Qsjl08IZKs2jjx21MiOtyLqGuCW6GOTNK4yEEDF5gA0K13eXGwL5lPS0ilRw+Lrw7cJU=")
|
||||
|
||||
val keyFactory = KeyFactory.getInstance("DH")
|
||||
val privateKeySpec = PKCS8EncodedKeySpec(decodedPrivateKey1)
|
||||
val privateKey = keyFactory.generatePrivate(privateKeySpec)
|
||||
val aesKey1 = FCastSession.computeSharedSecret(privateKey, keyExchangeMessage2)
|
||||
assertEquals("vI5LGE625zGEG350ggkyBsIAXm2y4sNohiPcED1oAEE=", Base64.encodeToString(aesKey1.encoded, Base64.NO_WRAP))
|
||||
|
||||
val message = PlayMessage("text/html")
|
||||
val serializedBody = Json.encodeToString(message)
|
||||
val encryptedMessage = FCastSession.encryptMessage(aesKey1, DecryptedMessage(Opcode.Play.value.toLong(), serializedBody))
|
||||
val decryptedMessage = FCastSession.decryptMessage(aesKey1, encryptedMessage)
|
||||
|
||||
assertEquals(Opcode.Play.value.toLong(), decryptedMessage.opcode)
|
||||
assertEquals(serializedBody, decryptedMessage.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDecryptMessageKnown() {
|
||||
val encryptedMessage = Json.decodeFromString<EncryptedMessage>("{\"version\":1,\"iv\":\"C4H70VC5FWrNtkty9/cLIA==\",\"blob\":\"K6/N7JMyi1PFwKhU0mFj7ZJmd/tPp3NCOMldmQUtDaQ7hSmPoIMI5QNMOj+NFEiP4qTgtYp5QmBPoQum6O88pA==\"}")
|
||||
val aesKey = SecretKeySpec(Base64.decode("+hr9Jg8yre7S9WGUohv2AUSzHNQN514JPh6MoFAcFNU=", Base64.NO_WRAP), "AES")
|
||||
val decryptedMessage = FCastSession.decryptMessage(aesKey, encryptedMessage)
|
||||
assertEquals(Opcode.Play.value.toLong(), decryptedMessage.opcode)
|
||||
assertEquals("{\"container\":\"text/html\"}", decryptedMessage.message)
|
||||
}
|
||||
}
|
|
@ -42,13 +42,10 @@ enum class Opcode(val value: Byte) {
|
|||
VolumeUpdate(7),
|
||||
SetVolume(8),
|
||||
PlaybackError(9),
|
||||
SetSpeed(10),
|
||||
SetSpeed(10),
|
||||
Version(11),
|
||||
KeyExchange(12),
|
||||
Encrypted(13),
|
||||
Ping(14),
|
||||
Pong(15),
|
||||
StartEncryption(16);
|
||||
Ping(12),
|
||||
Pong(13);
|
||||
|
||||
companion object {
|
||||
private val _map = values().associateBy { it.value }
|
||||
|
@ -65,39 +62,9 @@ class FCastSession(outputStream: OutputStream, private val _remoteSocketAddress:
|
|||
private var _packetLength = 0
|
||||
private var _state = SessionState.WaitingForLength
|
||||
private var _outputStream: DataOutputStream? = DataOutputStream(outputStream)
|
||||
private val _keyPair: KeyPair = generateKeyPair()
|
||||
private var _aesKey: SecretKeySpec? = null
|
||||
private val _queuedEncryptedMessages = arrayListOf<EncryptedMessage>()
|
||||
private var _encryptionStarted = false
|
||||
val id = UUID.randomUUID()
|
||||
|
||||
init {
|
||||
send(Opcode.KeyExchange, getKeyExchangeMessage(_keyPair))
|
||||
}
|
||||
|
||||
fun sendVersion(value: VersionMessage) {
|
||||
send(Opcode.Version, value)
|
||||
}
|
||||
|
||||
fun sendPlaybackError(value: PlaybackErrorMessage) {
|
||||
send(Opcode.PlaybackError, value)
|
||||
}
|
||||
|
||||
fun sendPlaybackUpdate(value: PlaybackUpdateMessage) {
|
||||
send(Opcode.PlaybackUpdate, value)
|
||||
}
|
||||
|
||||
fun sendVolumeUpdate(value: VolumeUpdateMessage) {
|
||||
send(Opcode.VolumeUpdate, value)
|
||||
}
|
||||
|
||||
private fun send(opcode: Opcode, message: String? = null) {
|
||||
val aesKey = _aesKey
|
||||
if (_encryptionStarted && aesKey != null && opcode != Opcode.Encrypted && opcode != Opcode.KeyExchange && opcode != Opcode.StartEncryption) {
|
||||
send(Opcode.Encrypted, encryptMessage(aesKey, DecryptedMessage(opcode.value.toLong(), message)))
|
||||
return
|
||||
}
|
||||
|
||||
fun send(opcode: Opcode, message: String? = null) {
|
||||
try {
|
||||
val data: ByteArray = message?.encodeToByteArray() ?: ByteArray(0)
|
||||
val size = 1 + data.size
|
||||
|
@ -129,7 +96,7 @@ class FCastSession(outputStream: OutputStream, private val _remoteSocketAddress:
|
|||
}
|
||||
}
|
||||
|
||||
private inline fun <reified T> send(opcode: Opcode, message: T) {
|
||||
inline fun <reified T> send(opcode: Opcode, message: T) {
|
||||
try {
|
||||
send(opcode, message?.let { Json.encodeToString(it) })
|
||||
} catch (e: Throwable) {
|
||||
|
@ -246,42 +213,7 @@ class FCastSession(outputStream: OutputStream, private val _remoteSocketAddress:
|
|||
Opcode.Seek -> _service.onCastSeek(json.decodeFromString(body!!))
|
||||
Opcode.SetVolume -> _service.onSetVolume(json.decodeFromString(body!!))
|
||||
Opcode.SetSpeed -> _service.onSetSpeed(json.decodeFromString(body!!))
|
||||
Opcode.KeyExchange -> {
|
||||
val keyExchangeMessage: KeyExchangeMessage = json.decodeFromString(body!!)
|
||||
_aesKey = computeSharedSecret(_keyPair.private, keyExchangeMessage)
|
||||
send(Opcode.StartEncryption)
|
||||
|
||||
synchronized(_queuedEncryptedMessages) {
|
||||
for (queuedEncryptedMessages in _queuedEncryptedMessages) {
|
||||
val decryptedMessage = decryptMessage(_aesKey!!, queuedEncryptedMessages)
|
||||
val o = Opcode.find(decryptedMessage.opcode.toByte())
|
||||
handlePacket(o, decryptedMessage.message)
|
||||
}
|
||||
|
||||
_queuedEncryptedMessages.clear()
|
||||
}
|
||||
}
|
||||
Opcode.Ping -> send(Opcode.Pong)
|
||||
Opcode.Encrypted -> {
|
||||
val encryptedMessage: EncryptedMessage = json.decodeFromString(body!!)
|
||||
if (_aesKey != null) {
|
||||
val decryptedMessage = decryptMessage(_aesKey!!, encryptedMessage)
|
||||
val o = Opcode.find(decryptedMessage.opcode.toByte())
|
||||
handlePacket(o, decryptedMessage.message)
|
||||
} else {
|
||||
synchronized(_queuedEncryptedMessages) {
|
||||
if (_queuedEncryptedMessages.size == 15) {
|
||||
_queuedEncryptedMessages.removeAt(0)
|
||||
}
|
||||
|
||||
_queuedEncryptedMessages.add(encryptedMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
Opcode.StartEncryption -> {
|
||||
_encryptionStarted = true
|
||||
//TODO: Send decrypted messages waiting for encryption to be established
|
||||
}
|
||||
else -> { }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
|
@ -292,63 +224,5 @@ class FCastSession(outputStream: OutputStream, private val _remoteSocketAddress:
|
|||
companion object {
|
||||
const val TAG = "FCastSession"
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
fun getKeyExchangeMessage(keyPair: KeyPair): KeyExchangeMessage {
|
||||
return KeyExchangeMessage(1, Base64.encodeToString(keyPair.public.encoded, Base64.NO_WRAP))
|
||||
}
|
||||
|
||||
fun generateKeyPair(): KeyPair {
|
||||
//modp14
|
||||
val p = BigInteger("ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff", 16)
|
||||
val g = BigInteger("2", 16)
|
||||
val dhSpec = DHParameterSpec(p, g)
|
||||
|
||||
val keyGen = KeyPairGenerator.getInstance("DH")
|
||||
keyGen.initialize(dhSpec)
|
||||
|
||||
return keyGen.generateKeyPair()
|
||||
}
|
||||
|
||||
fun computeSharedSecret(privateKey: PrivateKey, keyExchangeMessage: KeyExchangeMessage): SecretKeySpec {
|
||||
val keyFactory = KeyFactory.getInstance("DH")
|
||||
val receivedPublicKeyBytes = Base64.decode(keyExchangeMessage.publicKey, Base64.NO_WRAP)
|
||||
val receivedPublicKeySpec = X509EncodedKeySpec(receivedPublicKeyBytes)
|
||||
val receivedPublicKey = keyFactory.generatePublic(receivedPublicKeySpec)
|
||||
|
||||
val keyAgreement = KeyAgreement.getInstance("DH")
|
||||
keyAgreement.init(privateKey)
|
||||
keyAgreement.doPhase(receivedPublicKey, true)
|
||||
|
||||
val sharedSecret = keyAgreement.generateSecret()
|
||||
Log.i(TAG, "sharedSecret ${Base64.encodeToString(sharedSecret, Base64.NO_WRAP)}")
|
||||
val sha256 = MessageDigest.getInstance("SHA-256")
|
||||
val hashedSecret = sha256.digest(sharedSecret)
|
||||
Log.i(TAG, "hashedSecret ${Base64.encodeToString(hashedSecret, Base64.NO_WRAP)}")
|
||||
|
||||
return SecretKeySpec(hashedSecret, "AES")
|
||||
}
|
||||
|
||||
fun encryptMessage(aesKey: SecretKeySpec, decryptedMessage: DecryptedMessage): EncryptedMessage {
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, aesKey)
|
||||
val iv = cipher.iv
|
||||
val json = Json.encodeToString(decryptedMessage)
|
||||
val encrypted = cipher.doFinal(json.toByteArray(Charsets.UTF_8))
|
||||
return EncryptedMessage(
|
||||
version = 1,
|
||||
iv = Base64.encodeToString(iv, Base64.NO_WRAP),
|
||||
blob = Base64.encodeToString(encrypted, Base64.NO_WRAP)
|
||||
)
|
||||
}
|
||||
|
||||
fun decryptMessage(aesKey: SecretKeySpec, encryptedMessage: EncryptedMessage): DecryptedMessage {
|
||||
val iv = Base64.decode(encryptedMessage.iv, Base64.NO_WRAP)
|
||||
val encrypted = Base64.decode(encryptedMessage.blob, Base64.NO_WRAP)
|
||||
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, aesKey, IvParameterSpec(iv))
|
||||
val decryptedJson = cipher.doFinal(encrypted)
|
||||
return Json.decodeFromString(String(decryptedJson, Charsets.UTF_8))
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
package com.futo.fcast.receiver
|
||||
|
||||
import SslKeyManager
|
||||
import WebSocketListenerService
|
||||
import android.app.*
|
||||
import android.content.Context
|
||||
|
@ -11,13 +12,16 @@ import android.util.Log
|
|||
import android.widget.Toast
|
||||
import androidx.core.app.NotificationCompat
|
||||
import kotlinx.coroutines.*
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider
|
||||
import java.security.Security
|
||||
|
||||
class NetworkService : Service() {
|
||||
private var _discoveryService: DiscoveryService? = null
|
||||
private var _stopped = false
|
||||
private var _tcpListenerService: TcpListenerService? = null
|
||||
private var _tlsListenerService: TlsListenerService? = null
|
||||
private var _webSocketListenerService: WebSocketListenerService? = null
|
||||
private var _scope: CoroutineScope? = null
|
||||
private var _stopped = false
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? {
|
||||
return null
|
||||
|
@ -63,7 +67,7 @@ class NetworkService : Service() {
|
|||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
Log.i(TAG, "Sending version ${session.id}")
|
||||
session.sendVersion(VersionMessage(2))
|
||||
session.send(Opcode.Version, VersionMessage(2))
|
||||
} catch (e: Throwable) {
|
||||
Log.e(TAG, "Failed to send version ${session.id}")
|
||||
}
|
||||
|
@ -75,7 +79,7 @@ class NetworkService : Service() {
|
|||
val updateMessage = generateUpdateMessage()
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
session.sendPlaybackUpdate(updateMessage)
|
||||
session.send(Opcode.PlaybackUpdate, updateMessage)
|
||||
Log.i(TAG, "Update sent ${session.id}")
|
||||
} catch (eSend: Throwable) {
|
||||
Log.e(TAG, "Unhandled error sending update ${session.id}", eSend)
|
||||
|
@ -106,12 +110,18 @@ class NetworkService : Service() {
|
|||
start()
|
||||
}
|
||||
|
||||
val sslKeyManager = SslKeyManager("fcast_receiver")
|
||||
_tlsListenerService = TlsListenerService(this) { onNewSession(it) }.apply {
|
||||
start(sslKeyManager)
|
||||
}
|
||||
|
||||
Log.i(TAG, "Started NetworkService")
|
||||
Toast.makeText(this, "Started FCast service", Toast.LENGTH_LONG).show()
|
||||
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun createNotificationBuilder(): NotificationCompat.Builder {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
|
@ -134,6 +144,9 @@ class NetworkService : Service() {
|
|||
_tcpListenerService?.stop()
|
||||
_tcpListenerService = null
|
||||
|
||||
_tlsListenerService?.stop()
|
||||
_tlsListenerService = null
|
||||
|
||||
try {
|
||||
_webSocketListenerService?.stop()
|
||||
} catch (e: Throwable) {
|
||||
|
@ -170,12 +183,11 @@ class NetworkService : Service() {
|
|||
}
|
||||
}
|
||||
|
||||
fun sendPlaybackError(error: String) {
|
||||
val message = PlaybackErrorMessage(error)
|
||||
_tcpListenerService?.forEachSession { session ->
|
||||
private inline fun <reified T> send(opcode: Opcode, message: T) {
|
||||
val sender: (FCastSession) -> Unit = { session: FCastSession ->
|
||||
_scope?.launch(Dispatchers.IO) {
|
||||
try {
|
||||
session.sendPlaybackError(message)
|
||||
session.send(opcode, message)
|
||||
Log.i(TAG, "Playback error sent ${session.id}")
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to send playback error", e)
|
||||
|
@ -183,64 +195,22 @@ class NetworkService : Service() {
|
|||
}
|
||||
}
|
||||
|
||||
_webSocketListenerService?.forEachSession { session ->
|
||||
_scope?.launch(Dispatchers.IO) {
|
||||
try {
|
||||
session.sendPlaybackError(message)
|
||||
Log.i(TAG, "Playback error sent ${session.id}")
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to send playback error", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
_tcpListenerService?.forEachSession(sender)
|
||||
_webSocketListenerService?.forEachSession(sender)
|
||||
_tlsListenerService?.forEachSession(sender)
|
||||
}
|
||||
|
||||
fun sendPlaybackError(error: String) {
|
||||
val message = PlaybackErrorMessage(error)
|
||||
send(Opcode.PlaybackError, message)
|
||||
}
|
||||
|
||||
fun sendPlaybackUpdate(message: PlaybackUpdateMessage) {
|
||||
_tcpListenerService?.forEachSession { session ->
|
||||
_scope?.launch(Dispatchers.IO) {
|
||||
try {
|
||||
session.sendPlaybackUpdate(message)
|
||||
Log.i(TAG, "Playback update sent ${session.id}")
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to send playback update", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_webSocketListenerService?.forEachSession { session ->
|
||||
_scope?.launch(Dispatchers.IO) {
|
||||
try {
|
||||
session.sendPlaybackUpdate(message)
|
||||
Log.i(TAG, "Playback update sent ${session.id}")
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to send playback update", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
send(Opcode.PlaybackUpdate, message)
|
||||
}
|
||||
|
||||
fun sendCastVolumeUpdate(value: VolumeUpdateMessage) {
|
||||
_tcpListenerService?.forEachSession { session ->
|
||||
_scope?.launch(Dispatchers.IO) {
|
||||
try {
|
||||
session.sendVolumeUpdate(value)
|
||||
Log.i(TAG, "Volume update sent ${session.id}")
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to send volume update", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_webSocketListenerService?.forEachSession { session ->
|
||||
_scope?.launch(Dispatchers.IO) {
|
||||
try {
|
||||
session.sendVolumeUpdate(value)
|
||||
Log.i(TAG, "Volume update sent ${session.id}")
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "Failed to send volume update", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
send(Opcode.VolumeUpdate, value)
|
||||
}
|
||||
|
||||
fun onCastPlay(playMessage: PlayMessage) {
|
||||
|
@ -361,7 +331,7 @@ class NetworkService : Service() {
|
|||
private const val CHANNEL_ID = "NetworkListenerServiceChannel"
|
||||
private const val NOTIFICATION_ID = 1
|
||||
private const val PLAY_NOTIFICATION_ID = 2
|
||||
private const val TAG = "NetworkService"
|
||||
const val TAG = "NetworkService"
|
||||
var activityCount = 0
|
||||
var instance: NetworkService? = null
|
||||
}
|
||||
|
|
|
@ -49,23 +49,4 @@ data class SetVolumeMessage(
|
|||
@Serializable
|
||||
data class VersionMessage(
|
||||
val version: Long
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class KeyExchangeMessage(
|
||||
val version: Long,
|
||||
val publicKey: String
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DecryptedMessage(
|
||||
val opcode: Long,
|
||||
val message: String?
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class EncryptedMessage(
|
||||
val version: Long,
|
||||
val iv: String?,
|
||||
val blob: String
|
||||
)
|
|
@ -0,0 +1,80 @@
|
|||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import org.bouncycastle.asn1.x500.X500Name
|
||||
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo
|
||||
import org.bouncycastle.cert.X509v3CertificateBuilder
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider
|
||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
|
||||
import java.io.FileInputStream
|
||||
import java.math.BigInteger
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.KeyStore
|
||||
import java.security.PrivateKey
|
||||
import java.security.PublicKey
|
||||
import java.util.Calendar
|
||||
import javax.net.ssl.KeyManagerFactory
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.SSLServerSocketFactory
|
||||
import java.security.cert.X509Certificate
|
||||
import javax.net.ssl.TrustManagerFactory
|
||||
|
||||
class SslKeyManager(private val alias: String) {
|
||||
|
||||
fun getSslServerSocketFactory(): SSLServerSocketFactory {
|
||||
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
//if (!keyStore.containsAlias(alias)) {
|
||||
generateKeyPairAndCertificate(keyStore)
|
||||
//}
|
||||
|
||||
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply {
|
||||
init(keyStore)
|
||||
}
|
||||
|
||||
val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply {
|
||||
init(keyStore, null)
|
||||
}
|
||||
|
||||
val sslContext = SSLContext.getInstance("TLS").apply {
|
||||
init(keyManagerFactory.keyManagers, trustManagerFactory.trustManagers, null)
|
||||
}
|
||||
|
||||
return sslContext.serverSocketFactory
|
||||
}
|
||||
|
||||
private fun generateKeyPairAndCertificate(keyStore: KeyStore) {
|
||||
val keyPairGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore")
|
||||
val parameterSpec = KeyGenParameterSpec
|
||||
.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT or KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY)
|
||||
//.setBlockModes(KeyProperties.BLOCK_MODE_ECB)
|
||||
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
|
||||
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
|
||||
.build()
|
||||
|
||||
keyPairGenerator.initialize(parameterSpec)
|
||||
|
||||
val keyPair = keyPairGenerator.generateKeyPair()
|
||||
val privateKey = keyPair.private
|
||||
val publicKey = keyPair.public
|
||||
val cert = generateSelfSignedCertificate(privateKey, publicKey)
|
||||
keyStore.setKeyEntry(alias, privateKey, null, arrayOf(cert))
|
||||
}
|
||||
|
||||
private fun generateSelfSignedCertificate(privateKey: PrivateKey, publicKey: PublicKey): X509Certificate {
|
||||
val start = Calendar.getInstance().time
|
||||
val end = Calendar.getInstance().apply { add(Calendar.YEAR, 1000) }.time
|
||||
|
||||
val certInfo = X509v3CertificateBuilder(
|
||||
X500Name("CN=FCastReceiver"),
|
||||
BigInteger.ONE,
|
||||
start,
|
||||
end,
|
||||
X500Name("CN=FCastReceiver"),
|
||||
SubjectPublicKeyInfo.getInstance(publicKey.encoded)
|
||||
)
|
||||
|
||||
val signer = JcaContentSignerBuilder("SHA256withRSA").build(privateKey)
|
||||
return JcaX509CertificateConverter().getCertificate(certInfo.build(signer))
|
||||
}
|
||||
}
|
|
@ -0,0 +1,134 @@
|
|||
package com.futo.fcast.receiver
|
||||
|
||||
import SslKeyManager
|
||||
import android.util.Log
|
||||
import java.io.BufferedInputStream
|
||||
import java.net.Socket
|
||||
import java.security.KeyStore
|
||||
import java.security.cert.Certificate
|
||||
import javax.net.ssl.KeyManagerFactory
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.SSLServerSocket
|
||||
import javax.net.ssl.TrustManagerFactory
|
||||
|
||||
class TlsListenerService(private val _networkService: NetworkService, private val _onNewSession: (session: FCastSession) -> Unit) {
|
||||
private var _serverSocket: SSLServerSocket? = null
|
||||
private var _stopped: Boolean = false
|
||||
private var _listenThread: Thread? = null
|
||||
private var _clientThreads: ArrayList<Thread> = arrayListOf()
|
||||
private var _sessions: ArrayList<FCastSession> = arrayListOf()
|
||||
|
||||
fun start(sslKeyManager: SslKeyManager) {
|
||||
Log.i(TAG, "Starting TlsListenerService")
|
||||
|
||||
val serverSocketFactory = sslKeyManager.getSslServerSocketFactory()
|
||||
_serverSocket = (serverSocketFactory.createServerSocket(PORT) as SSLServerSocket)
|
||||
|
||||
_listenThread = Thread {
|
||||
Log.i(TAG, "Starting TLS listener")
|
||||
|
||||
try {
|
||||
listenForIncomingConnections()
|
||||
} catch (e: Throwable) {
|
||||
Log.e(TAG, "Stopped TLS listening for connections due to an unexpected error", e)
|
||||
}
|
||||
}
|
||||
|
||||
_listenThread?.start()
|
||||
|
||||
Log.i(TAG, "Started TlsListenerService")
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
Log.i(TAG, "Stopping TlsListenerService")
|
||||
|
||||
_stopped = true
|
||||
|
||||
_serverSocket?.close()
|
||||
_serverSocket = null
|
||||
|
||||
_listenThread?.join()
|
||||
_listenThread = null
|
||||
|
||||
synchronized(_clientThreads) {
|
||||
_clientThreads.clear()
|
||||
}
|
||||
|
||||
Log.i(TAG, "Stopped TlsListenerService")
|
||||
}
|
||||
|
||||
fun forEachSession(handler: (FCastSession) -> Unit) {
|
||||
synchronized(_sessions) {
|
||||
for (session in _sessions) {
|
||||
handler(session)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun listenForIncomingConnections() {
|
||||
Log.i(TAG, "Started TLS listening for incoming connections")
|
||||
|
||||
while (!_stopped) {
|
||||
val clientSocket = _serverSocket?.accept() ?: break
|
||||
|
||||
val clientThread = Thread {
|
||||
try {
|
||||
handleClientConnection(clientSocket)
|
||||
} catch (e: Throwable) {
|
||||
Log.e(TAG, "Failed handle TLS client connection due to an error", e)
|
||||
}
|
||||
}
|
||||
|
||||
synchronized(_clientThreads) {
|
||||
_clientThreads.add(clientThread)
|
||||
}
|
||||
|
||||
clientThread.start()
|
||||
}
|
||||
|
||||
Log.i(TAG, "Stopped TLS listening for incoming connections")
|
||||
}
|
||||
|
||||
private fun handleClientConnection(socket: Socket) {
|
||||
Log.i(TAG, "New TLS connection received from ${socket.remoteSocketAddress}")
|
||||
|
||||
val session = FCastSession(socket.getOutputStream(), socket.remoteSocketAddress, _networkService)
|
||||
synchronized(_sessions) {
|
||||
_sessions.add(session)
|
||||
}
|
||||
_onNewSession(session)
|
||||
|
||||
Log.i(TAG, "Waiting for data from ${socket.remoteSocketAddress}")
|
||||
|
||||
val bufferSize = 4096
|
||||
val buffer = ByteArray(bufferSize)
|
||||
val inputStream = BufferedInputStream(socket.getInputStream())
|
||||
|
||||
var bytesRead: Int
|
||||
while (!_stopped) {
|
||||
bytesRead = inputStream.read(buffer, 0, bufferSize)
|
||||
if (bytesRead == -1) {
|
||||
break
|
||||
}
|
||||
|
||||
session.processBytes(buffer, bytesRead)
|
||||
}
|
||||
|
||||
socket.close()
|
||||
|
||||
synchronized(_sessions) {
|
||||
_sessions.remove(session)
|
||||
}
|
||||
|
||||
synchronized(_clientThreads) {
|
||||
_clientThreads.remove(Thread.currentThread())
|
||||
}
|
||||
|
||||
Log.i(TAG, "Disconnected ${socket.remoteSocketAddress}")
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TAG = "TlsListenerService"
|
||||
const val PORT = 46897
|
||||
}
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
plugins {
|
||||
id 'com.android.application' version '7.4.2' apply false
|
||||
id 'com.android.library' version '7.4.2' apply false
|
||||
id 'com.android.application' version '8.2.0' apply false
|
||||
id 'com.android.library' version '8.2.0' apply false
|
||||
id 'org.jetbrains.kotlin.android' version '1.8.0' apply false
|
||||
}
|
|
@ -20,4 +20,5 @@ kotlin.code.style=official
|
|||
# Enables namespacing of each library's R class so that its R class includes only the
|
||||
# resources declared in the library itself and none from the library's dependencies,
|
||||
# thereby reducing the size of the R class for that library
|
||||
android.nonTransitiveRClass=true
|
||||
android.nonTransitiveRClass=true
|
||||
android.nonFinalResIds=false
|
|
@ -1,6 +1,6 @@
|
|||
#Mon May 01 06:24:43 CDT 2023
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
|
||||
distributionPath=wrapper/dists
|
||||
zipStorePath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue