π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Authenticate Cast receivers without Google SDK
Neeraj Gupta55effd6ddcd4
diff --git a/mobile/apps/photos/plugins/ente_cast/android/src/main/kotlin/io/ente/cast/EnteCastPlugin.kt b/mobile/apps/photos/plugins/ente_cast/android/src/main/kotlin/io/ente/cast/EnteCastPlugin.ktindex 20c83a12ec..c9b1caeaa6 100644--- a/mobile/apps/photos/plugins/ente_cast/android/src/main/kotlin/io/ente/cast/EnteCastPlugin.kt+++ b/mobile/apps/photos/plugins/ente_cast/android/src/main/kotlin/io/ente/cast/EnteCastPlugin.kt@@ -5,9 +5,18 @@ import android.net.wifi.WifiManagerimport io.flutter.embedding.engine.plugins.FlutterPluginimport io.flutter.plugin.common.MethodCallimport io.flutter.plugin.common.MethodChannel+import java.io.ByteArrayInputStream+import java.security.Signature+import java.security.interfaces.RSAPublicKey+import java.security.cert.CertPathValidator+import java.security.cert.CertificateFactory+import java.security.cert.PKIXParameters+import java.security.cert.TrustAnchor+import java.security.cert.X509Certificateclass EnteCastPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {- private lateinit var channel: MethodChannel+ private lateinit var multicastChannel: MethodChannel+ private lateinit var authChannel: MethodChannelprivate lateinit var lock: WifiManager.MulticastLockprivate var holderCount = 0@@ -17,8 +26,10 @@ class EnteCastPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {lock = wifiManager.createMulticastLock("ente_cast_discovery").apply {setReferenceCounted(false)}- channel = MethodChannel(binding.binaryMessenger, CHANNEL)- channel.setMethodCallHandler(this)+ multicastChannel = MethodChannel(binding.binaryMessenger, MULTICAST_CHANNEL)+ multicastChannel.setMethodCallHandler(this)+ authChannel = MethodChannel(binding.binaryMessenger, AUTH_CHANNEL)+ authChannel.setMethodCallHandler(this)}override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {@@ -36,19 +47,110 @@ class EnteCastPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {}result.success(null)}+ "verifyDeviceCredentials" -> {+ try {+ verifyDeviceCredentials(call)+ result.success(null)+ } catch (error: Exception) {+ result.error(+ "CAST_AUTH_FAILED",+ error.message ?: "Cast device authentication failed",+ null,+ )+ }+ }else -> result.notImplemented()}}override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {- channel.setMethodCallHandler(null)+ multicastChannel.setMethodCallHandler(null)+ authChannel.setMethodCallHandler(null)holderCount = 0if (lock.isHeld) {lock.release()}}+ private fun verifyDeviceCredentials(call: MethodCall) {+ val certificateFactory = CertificateFactory.getInstance("X.509")+ val leaf = certificateFactory.parseCertificate(call.bytes("clientAuthCertificate"))+ val rootBytes = call.byteArrays("trustAnchors")+ val roots = rootBytes.map { certificateFactory.parseCertificate(it) }+ require(roots.isNotEmpty()) { "Cast trust store is empty" }++ val intermediates = call.byteArrays("intermediateCertificates")+ .filterNot { candidate -> rootBytes.any(candidate::contentEquals) }+ .map { certificateFactory.parseCertificate(it) }+ val certificatePath = certificateFactory.generateCertPath(+ listOf(leaf) + intermediates,+ )+ val parameters = PKIXParameters(+ roots.mapTo(mutableSetOf()) { TrustAnchor(it, null) },+ ).apply {+ isRevocationEnabled = false+ }+ CertPathValidator.getInstance("PKIX").validate(certificatePath, parameters)++ leaf.checkValidity()+ require(leaf.basicConstraints < 0) {+ "Cast device authentication certificate must not be a CA"+ }+ require(leaf.keyUsage?.firstOrNull() == true) {+ "Cast device certificate cannot sign"+ }+ val extendedKeyUsage = leaf.extendedKeyUsage+ require(extendedKeyUsage?.contains(CLIENT_AUTH_OID) == true) {+ "Cast device certificate is not valid for client authentication"+ }+ val publicKey = leaf.publicKey+ require(publicKey is RSAPublicKey) {+ "Cast device authentication key is not RSA"+ }+ require(publicKey.modulus.bitLength() >= MIN_RSA_KEY_BITS) {+ "Cast device authentication key is too small"+ }++ val verifier = Signature.getInstance(+ when (call.argument<Int>("hashAlgorithm")) {+ HASH_SHA1 -> "SHA1withRSA"+ HASH_SHA256 -> "SHA256withRSA"+ else -> throw IllegalArgumentException(+ "Unsupported Cast signature hash algorithm",+ )+ },+ )+ verifier.initVerify(publicKey)+ verifier.update(call.bytes("signatureInput"))+ require(verifier.verify(call.bytes("signature"))) {+ "Cast device signature is invalid"+ }+ }++ private fun CertificateFactory.parseCertificate(bytes: ByteArray): X509Certificate {+ return generateCertificate(ByteArrayInputStream(bytes)) as X509Certificate+ }++ private fun MethodCall.bytes(name: String): ByteArray {+ return argument<ByteArray>(name)+ ?: throw IllegalArgumentException("Missing $name")+ }++ private fun MethodCall.byteArrays(name: String): List<ByteArray> {+ val values = argument<List<*>>(name)+ ?: throw IllegalArgumentException("Missing $name")+ return values.map {+ it as? ByteArray+ ?: throw IllegalArgumentException("$name contains a non-byte value")+ }+ }+private companion object {- const val CHANNEL = "io.ente.cast/multicast"+ const val MULTICAST_CHANNEL = "io.ente.cast/multicast"+ const val AUTH_CHANNEL = "io.ente.cast/auth"+ const val HASH_SHA1 = 0+ const val HASH_SHA256 = 1+ const val MIN_RSA_KEY_BITS = 2048+ const val CLIENT_AUTH_OID = "1.3.6.1.5.5.7.3.2"}}diff --git a/mobile/apps/photos/plugins/ente_cast/ios/Classes/EnteCastPlugin.swift b/mobile/apps/photos/plugins/ente_cast/ios/Classes/EnteCastPlugin.swiftindex 9f0bb1335a..9a4286f670 100644--- a/mobile/apps/photos/plugins/ente_cast/ios/Classes/EnteCastPlugin.swift+++ b/mobile/apps/photos/plugins/ente_cast/ios/Classes/EnteCastPlugin.swift@@ -1,6 +1,7 @@import Darwinimport Flutterimport Foundation+import Securitypublic final class EnteCastPlugin: NSObject, FlutterPlugin {private var discoveries: [UUID: BonjourDiscovery] = [:]@@ -10,16 +11,41 @@ public final class EnteCastPlugin: NSObject, FlutterPlugin {name: "io.ente.cast/discovery",binaryMessenger: registrar.messenger())+ let authChannel = FlutterMethodChannel(+ name: "io.ente.cast/auth",+ binaryMessenger: registrar.messenger()+ )let instance = EnteCastPlugin()registrar.addMethodCallDelegate(instance, channel: channel)+ registrar.addMethodCallDelegate(instance, channel: authChannel)}public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {- guard call.method == "searchDevices" else {+ switch call.method {+ case "searchDevices":+ searchDevices(call, result: result)+ case "verifyDeviceCredentials":+ do {+ try verifyDeviceCredentials(call)+ result(nil)+ } catch {+ result(+ FlutterError(+ code: "CAST_AUTH_FAILED",+ message: error.localizedDescription,+ details: nil+ )+ )+ }+ default:result(FlutterMethodNotImplemented)- return}+ }+ private func searchDevices(+ _ call: FlutterMethodCall,+ result: @escaping FlutterResult+ ) {let arguments = call.arguments as? [String: Any]let timeoutMilliseconds =(arguments?["timeoutMilliseconds"] as? NSNumber)?.doubleValue ?? 7_000@@ -44,6 +70,136 @@ public final class EnteCastPlugin: NSObject, FlutterPlugin {discoveries[discoveryID] = discoverydiscovery.start()}++ private func verifyDeviceCredentials(_ call: FlutterMethodCall) throws {+ guard let arguments = call.arguments as? [String: Any] else {+ throw CastAuthError("Missing authentication arguments")+ }+ let leafData = try bytes("clientAuthCertificate", in: arguments)+ let intermediateData = try byteArrays(+ "intermediateCertificates",+ in: arguments+ )+ let rootData = try byteArrays("trustAnchors", in: arguments)+ guard !rootData.isEmpty else {+ throw CastAuthError("Cast trust store is empty")+ }++ let roots = try rootData.map(certificate)+ let chainData = [leafData] + intermediateData.filter { candidate in+ !rootData.contains(candidate)+ }+ let certificates = try chainData.map(certificate)+ var trust: SecTrust?+ let createStatus = SecTrustCreateWithCertificates(+ certificates as CFArray,+ SecPolicyCreateSSL(false, nil),+ &trust+ )+ guard createStatus == errSecSuccess, let trust else {+ throw CastAuthError("Unable to create Cast certificate trust")+ }+ guard SecTrustSetAnchorCertificates(trust, roots as CFArray)+ == errSecSuccess else {+ throw CastAuthError("Unable to configure Cast trust anchors")+ }+ guard SecTrustSetAnchorCertificatesOnly(trust, true) == errSecSuccess else {+ throw CastAuthError("Unable to restrict Cast trust anchors")+ }+ guard SecTrustSetNetworkFetchAllowed(trust, false) == errSecSuccess else {+ throw CastAuthError("Unable to disable certificate network fetches")+ }+ var trustError: CFError?+ guard SecTrustEvaluateWithError(trust, &trustError) else {+ let message = trustError.map { CFErrorCopyDescription($0) as String }+ ?? "Cast certificate chain is untrusted"+ throw CastAuthError(message)+ }++ guard let publicKey = SecTrustCopyKey(trust) else {+ throw CastAuthError("Cast device certificate has no public key")+ }+ let hashAlgorithm =+ (arguments["hashAlgorithm"] as? NSNumber)?.intValue+ let algorithm: SecKeyAlgorithm+ switch hashAlgorithm {+ case 0:+ algorithm = .rsaSignatureMessagePKCS1v15SHA1+ case 1:+ algorithm = .rsaSignatureMessagePKCS1v15SHA256+ default:+ throw CastAuthError("Unsupported Cast signature hash algorithm")+ }+ guard SecKeyIsAlgorithmSupported(publicKey, .verify, algorithm) else {+ throw CastAuthError("Cast device authentication key is not RSA")+ }+ let keyAttributes = SecKeyCopyAttributes(publicKey) as? [CFString: Any]+ let keySize = keyAttributes?[kSecAttrKeySizeInBits] as? NSNumber+ guard let keySize, keySize.intValue >= 2_048 else {+ throw CastAuthError("Cast device authentication key is too small")+ }++ let signature = try bytes("signature", in: arguments)+ let signatureInput = try bytes("signatureInput", in: arguments)+ var signatureError: Unmanaged<CFError>?+ guard SecKeyVerifySignature(+ publicKey,+ algorithm,+ signatureInput as CFData,+ signature as CFData,+ &signatureError+ ) else {+ let message = signatureError+ .map { CFErrorCopyDescription($0.takeRetainedValue()) as String }+ ?? "Cast device signature is invalid"+ throw CastAuthError(message)+ }+ }++ private func certificate(_ data: Data) throws -> SecCertificate {+ guard let certificate = SecCertificateCreateWithData(nil, data as CFData)+ else {+ throw CastAuthError("Unable to parse Cast certificate")+ }+ return certificate+ }++ private func bytes(+ _ name: String,+ in arguments: [String: Any]+ ) throws -> Data {+ guard let value = arguments[name] as? FlutterStandardTypedData else {+ throw CastAuthError("Missing \(name)")+ }+ return value.data+ }++ private func byteArrays(+ _ name: String,+ in arguments: [String: Any]+ ) throws -> [Data] {+ guard let values = arguments[name] as? [Any] else {+ throw CastAuthError("Missing \(name)")+ }+ return try values.map { value in+ guard let bytes = value as? FlutterStandardTypedData else {+ throw CastAuthError("\(name) contains a non-byte value")+ }+ return bytes.data+ }+ }+}++private struct CastAuthError: LocalizedError {+ init(_ message: String) {+ self.message = message+ }++ let message: String++ var errorDescription: String? {+ message+ }}private final class BonjourDiscovery: NSObject {diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_device_auth.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_device_auth.dartnew file mode 100644index 0000000000..eb8ed9d07e--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_device_auth.dart@@ -0,0 +1,235 @@+import "dart:async";+import "dart:io";+import "dart:math";++import "package:ente_cast/src/cast/cast_message_codec.dart";+import "package:ente_cast/src/cast/cast_trust_anchors.dart";+import "package:ente_cast/src/cast/simple_protobuf.dart";+import "package:flutter/services.dart";++const castDeviceAuthNamespace = "urn:x-cast:com.google.cast.tp.deviceauth";+const castPlatformSenderID = "sender-0";+const castPlatformReceiverID = "receiver-0";++const _sha1 = 0;+const _sha256 = 1;+const _nonceLength = 16;+const _maxPeerCertificateLifetime = Duration(days: 4);+const _authChannel = MethodChannel("io.ente.cast/auth");++final class CastAuthenticationException implements Exception {+ const CastAuthenticationException(this.message);++ final String message;++ @override+ String toString() => "Cast authentication failed: $message";+}++final class CastAuthResponse {+ const CastAuthResponse({+ required this.signature,+ required this.clientAuthCertificate,+ required this.intermediateCertificates,+ required this.senderNonce,+ required this.hashAlgorithm,+ });++ final Uint8List signature;+ final Uint8List clientAuthCertificate;+ final List<Uint8List> intermediateCertificates;+ final Uint8List senderNonce;+ final int hashAlgorithm;+}++final class CastDeviceAuthenticator {+ CastDeviceAuthenticator({+ Future<void> Function(Map<String, Object?> arguments)? verifyCredentials,+ Uint8List Function()? createNonce,+ }) : _verifyCredentials = verifyCredentials ?? _verifyNatively,+ _createNonce = createNonce ?? _secureNonce;++ final Future<void> Function(Map<String, Object?> arguments)+ _verifyCredentials;+ final Uint8List Function() _createNonce;++ Future<void> authenticate({+ required X509Certificate peerCertificate,+ required Stream<CastEnvelope> envelopes,+ required void Function(Uint8List payload) sendChallenge,+ required Future<void> Function() flush,+ required Duration timeout,+ }) async {+ _verifyPeerCertificateValidity(peerCertificate);+ final nonce = _createNonce();+ if (nonce.length != _nonceLength) {+ throw const CastAuthenticationException("Invalid sender nonce");+ }++ final responseFuture = envelopes+ .firstWhere(+ (envelope) =>+ envelope.namespace == castDeviceAuthNamespace &&+ envelope.binaryPayload != null,+ )+ .timeout(+ timeout,+ onTimeout: () => throw const CastAuthenticationException(+ "The receiver did not answer the authentication challenge",+ ),+ );+ sendChallenge(encodeCastAuthChallenge(nonce));+ await flush();++ final envelope = await responseFuture;+ final response = decodeCastAuthResponse(envelope.binaryPayload!);+ if (response.senderNonce.isNotEmpty &&+ !_constantTimeEquals(response.senderNonce, nonce)) {+ throw const CastAuthenticationException("Sender nonce mismatch");+ }++ final signatureInput =+ Uint8List(response.senderNonce.length + peerCertificate.der.length)+ ..setRange(0, response.senderNonce.length, response.senderNonce)+ ..setRange(+ response.senderNonce.length,+ response.senderNonce.length + peerCertificate.der.length,+ peerCertificate.der,+ );++ try {+ await _verifyCredentials({+ "clientAuthCertificate": response.clientAuthCertificate,+ "intermediateCertificates": response.intermediateCertificates,+ "signature": response.signature,+ "signatureInput": signatureInput,+ "hashAlgorithm": response.hashAlgorithm,+ "trustAnchors": castTrustAnchors,+ });+ } on PlatformException catch (error) {+ throw CastAuthenticationException(+ error.message ?? "Device credentials were rejected",+ );+ }+ }++ static Future<void> _verifyNatively(Map<String, Object?> arguments) =>+ _authChannel.invokeMethod<void>("verifyDeviceCredentials", arguments);++ static Uint8List _secureNonce() {+ final random = Random.secure();+ return Uint8List.fromList(+ List.generate(_nonceLength, (_) => random.nextInt(256)),+ );+ }++ static void _verifyPeerCertificateValidity(X509Certificate certificate) {+ final now = DateTime.now();+ if (certificate.startValidity.isAfter(now)) {+ throw const CastAuthenticationException(+ "TLS certificate is not valid yet",+ );+ }+ if (certificate.endValidity.isBefore(now)) {+ throw const CastAuthenticationException("TLS certificate has expired");+ }+ if (certificate.endValidity.isAfter(now.add(_maxPeerCertificateLifetime))) {+ throw const CastAuthenticationException(+ "TLS certificate lifetime exceeds four days",+ );+ }+ }+}++Uint8List encodeCastAuthChallenge(Uint8List nonce) {+ if (nonce.length != _nonceLength) {+ throw ArgumentError.value(nonce.length, "nonce", "Must be 16 bytes");+ }+ final challenge = ProtoWriter()+ ..writeBytes(2, nonce)+ ..writeVarint(3, _sha256);+ return (ProtoWriter()..writeBytes(1, challenge.takeBytes())).takeBytes();+}++CastAuthResponse decodeCastAuthResponse(Uint8List payload) {+ Uint8List? responsePayload;+ int? errorType;+ final message = ProtoReader(payload);+ while (message.hasNext) {+ final field = message.readField();+ if (field.number == 2 && field.bytes != null) {+ responsePayload = field.bytes;+ } else if (field.number == 3 && field.bytes != null) {+ final error = ProtoReader(field.bytes!);+ while (error.hasNext) {+ final errorField = error.readField();+ if (errorField.number == 1) {+ errorType = errorField.varint;+ }+ }+ }+ }+ if (errorType != null) {+ throw CastAuthenticationException("Receiver returned error $errorType");+ }+ if (responsePayload == null) {+ throw const CastAuthenticationException(+ "Receiver returned no authentication response",+ );+ }++ Uint8List? signature;+ Uint8List? clientCertificate;+ final intermediateCertificates = <Uint8List>[];+ var senderNonce = Uint8List(0);+ var hashAlgorithm = _sha1;+ final response = ProtoReader(responsePayload);+ while (response.hasNext) {+ final field = response.readField();+ switch (field.number) {+ case 1:+ signature = field.bytes;+ case 2:+ clientCertificate = field.bytes;+ case 3:+ if (field.bytes case final certificate?) {+ intermediateCertificates.add(certificate);+ }+ case 5:+ senderNonce = field.bytes ?? Uint8List(0);+ case 6:+ hashAlgorithm = field.varint ?? _sha1;+ }+ }+ if (signature == null || signature.isEmpty) {+ throw const CastAuthenticationException("Missing device signature");+ }+ if (clientCertificate == null || clientCertificate.isEmpty) {+ throw const CastAuthenticationException(+ "Missing device authentication certificate",+ );+ }+ if (hashAlgorithm != _sha1 && hashAlgorithm != _sha256) {+ throw CastAuthenticationException(+ "Unsupported signature hash algorithm $hashAlgorithm",+ );+ }+ return CastAuthResponse(+ signature: signature,+ clientAuthCertificate: clientCertificate,+ intermediateCertificates: intermediateCertificates,+ senderNonce: senderNonce,+ hashAlgorithm: hashAlgorithm,+ );+}++bool _constantTimeEquals(Uint8List first, Uint8List second) {+ if (first.length != second.length) {+ return false;+ }+ var difference = 0;+ for (var index = 0; index < first.length; index++) {+ difference |= first[index] ^ second[index];+ }+ return difference == 0;+}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_message_codec.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_message_codec.dartindex b798ed4c32..32f7f336b4 100644--- a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_message_codec.dart+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_message_codec.dart@@ -1,13 +1,20 @@import "dart:convert";import "dart:typed_data";+import "package:ente_cast/src/cast/simple_protobuf.dart";+const maxCastFrameLength = 64 * 1024;final class CastEnvelope {final String namespace;- final String payload;-- const CastEnvelope({required this.namespace, required this.payload});+ final String? payload;+ final Uint8List? binaryPayload;++ const CastEnvelope({+ required this.namespace,+ required this.payload,+ required this.binaryPayload,+ });}Uint8List encodeCastEnvelope({@@ -16,14 +23,30 @@ Uint8List encodeCastEnvelope({required String namespace,required String payload,}) {- final output = BytesBuilder(copy: false);- _writeVarintField(output, 1, 0);- _writeStringField(output, 2, sourceID);- _writeStringField(output, 3, destinationID);- _writeStringField(output, 4, namespace);- _writeVarintField(output, 5, 0);- _writeStringField(output, 6, payload);- return output.takeBytes();+ return _encodeCastEnvelope(+ sourceID: sourceID,+ destinationID: destinationID,+ namespace: namespace,+ payloadType: 0,+ payloadField: 6,+ payload: utf8.encode(payload),+ );+}++Uint8List encodeBinaryCastEnvelope({+ required String sourceID,+ required String destinationID,+ required String namespace,+ required Uint8List payload,+}) {+ return _encodeCastEnvelope(+ sourceID: sourceID,+ destinationID: destinationID,+ namespace: namespace,+ payloadType: 1,+ payloadField: 7,+ payload: payload,+ );}Uint8List encodeCastFrame({@@ -38,49 +61,63 @@ Uint8List encodeCastFrame({namespace: namespace,payload: payload,);- if (envelope.length > maxCastFrameLength) {- throw const FormatException("Cast message exceeds the frame limit");- }+ return _frame(envelope);+}- final frame = Uint8List(envelope.length + 4);- ByteData.sublistView(frame).setUint32(0, envelope.length, Endian.big);- frame.setRange(4, frame.length, envelope);- return frame;+Uint8List encodeBinaryCastFrame({+ required String sourceID,+ required String destinationID,+ required String namespace,+ required Uint8List payload,+}) {+ final envelope = encodeBinaryCastEnvelope(+ sourceID: sourceID,+ destinationID: destinationID,+ namespace: namespace,+ payload: payload,+ );+ return _frame(envelope);}CastEnvelope decodeCastEnvelope(Uint8List bytes) {- final cursor = _Cursor();String? namespace;- String? payload;-- while (cursor.offset < bytes.length) {- final tag = _readVarint(bytes, cursor);- final field = tag >> 3;- final wireType = tag & 7;- if (wireType == 2) {- final length = _readVarint(bytes, cursor);- final end = cursor.offset + length;- if (end > bytes.length) {- throw const FormatException("Truncated Cast message field");- }- if (field == 4 || field == 6) {- final value = utf8.decode(bytes.sublist(cursor.offset, end));- if (field == 4) {- namespace = value;- } else {- payload = value;+ int? payloadType;+ Uint8List? stringPayload;+ Uint8List? binaryPayload;+ final reader = ProtoReader(bytes);+ while (reader.hasNext) {+ final field = reader.readField();+ switch (field.number) {+ case 4:+ if (field.bytes case final value?) {+ namespace = utf8.decode(value);}- }- cursor.offset = end;- } else {- _skipField(bytes, cursor, wireType);+ case 5:+ payloadType = field.varint;+ case 6:+ stringPayload = field.bytes;+ case 7:+ binaryPayload = field.bytes;}}-- if (namespace == null || payload == null) {+ if (namespace == null || payloadType == null) {throw const FormatException("Incomplete Cast message");}- return CastEnvelope(namespace: namespace, payload: payload);+ if (payloadType == 0 && stringPayload != null) {+ return CastEnvelope(+ namespace: namespace,+ payload: utf8.decode(stringPayload),+ binaryPayload: null,+ );+ }+ if (payloadType == 1 && binaryPayload != null) {+ return CastEnvelope(+ namespace: namespace,+ payload: null,+ binaryPayload: binaryPayload,+ );+ }+ throw const FormatException("Cast payload type does not match its field");}final class CastFrameDecoder {@@ -123,57 +160,30 @@ final class CastFrameDecoder {}}-void _writeVarintField(BytesBuilder output, int field, int value) {- _writeVarint(output, field << 3);- _writeVarint(output, value);-}--void _writeStringField(BytesBuilder output, int field, String value) {- final bytes = utf8.encode(value);- _writeVarint(output, (field << 3) | 2);- _writeVarint(output, bytes.length);- output.add(bytes);-}--void _writeVarint(BytesBuilder output, int value) {- var remaining = value;- while (remaining >= 0x80) {- output.addByte((remaining & 0x7f) | 0x80);- remaining >>= 7;- }- output.addByte(remaining);-}--int _readVarint(Uint8List bytes, _Cursor cursor) {- var value = 0;- var shift = 0;- while (cursor.offset < bytes.length && shift <= 63) {- final byte = bytes[cursor.offset++];- value |= (byte & 0x7f) << shift;- if (byte & 0x80 == 0) {- return value;- }- shift += 7;- }- throw const FormatException("Invalid Cast message varint");+Uint8List _encodeCastEnvelope({+ required String sourceID,+ required String destinationID,+ required String namespace,+ required int payloadType,+ required int payloadField,+ required List<int> payload,+}) {+ return (ProtoWriter()+ ..writeVarint(1, 0)+ ..writeString(2, sourceID)+ ..writeString(3, destinationID)+ ..writeString(4, namespace)+ ..writeVarint(5, payloadType)+ ..writeBytes(payloadField, payload))+ .takeBytes();}-void _skipField(Uint8List bytes, _Cursor cursor, int wireType) {- switch (wireType) {- case 0:- _readVarint(bytes, cursor);- case 1:- cursor.offset += 8;- case 5:- cursor.offset += 4;- default:- throw FormatException("Unsupported Cast wire type $wireType");- }- if (cursor.offset > bytes.length) {- throw const FormatException("Truncated Cast message field");+Uint8List _frame(Uint8List envelope) {+ if (envelope.length > maxCastFrameLength) {+ throw const FormatException("Cast message exceeds the frame limit");}-}--final class _Cursor {- int offset = 0;+ final frame = Uint8List(envelope.length + 4);+ ByteData.sublistView(frame).setUint32(0, envelope.length, Endian.big);+ frame.setRange(4, frame.length, envelope);+ return frame;}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_trust_anchors.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_trust_anchors.dartnew file mode 100644index 0000000000..6b66cac066--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/cast_trust_anchors.dart@@ -0,0 +1,55 @@+import "dart:convert";+import "dart:typed_data";++final List<Uint8List> castTrustAnchors = [+ base64Decode(_castRootCA),+ base64Decode(_eurekaRootCA),+];++// CN=Cast Root CA, valid until 2034-03-28.+const _castRootCA =+ "MIIDxTCCAq2gAwIBAgIBAjANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQGEwJVUzET"+ "MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzETMBEG"+ "A1UECgwKR29vZ2xlIEluYzENMAsGA1UECwwEQ2FzdDEVMBMGA1UEAwwMQ2FzdCBS"+ "b290IENBMB4XDTE0MDQwMjE3MzQyNloXDTM0MDMyODE3MzQyNlowdTELMAkGA1UE"+ "BhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZp"+ "ZXcxEzARBgNVBAoMCkdvb2dsZSBJbmMxDTALBgNVBAsMBENhc3QxFTATBgNVBAMM"+ "DENhc3QgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALrZ"+ "ZZ3aOdPBd/bU0K6PWAhoOUqV7XDP/XkIqarl6binLaBnR4qeyc9wswWHaRHscJiX"+ "w+bDw+u9xrA9/E/BXjif2s9zMAZbeTfBXoyHR5SaQZIq1pXEcVwnXQixgMaSvRvj"+ "QZeh7HWfVZ4+n48cx2VkB9OzlqEEn5HE3gp7bNnIwHgxoBlCqeiD48788c7CLi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plugins/ente_cast/lib/src/cast/chromecast_channel.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_channel.dartindex 1f86f5a806..2e85a57948 100644--- a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_channel.dart+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/chromecast_channel.dart@@ -3,6 +3,7 @@ import "dart:convert";import "dart:io";import "dart:typed_data";+import "package:ente_cast/src/cast/cast_device_auth.dart";import "package:ente_cast/src/cast/cast_message_codec.dart";final class ChromecastMessage {@@ -15,6 +16,7 @@ final class ChromecastMessage {final class ChromecastChannel {final SecureSocket _socket;final _messages = StreamController<ChromecastMessage>.broadcast();+ final _envelopes = StreamController<CastEnvelope>.broadcast();final _frameDecoder = CastFrameDecoder();var _requestID = 0;Future<void>? _closeFuture;@@ -23,10 +25,14 @@ final class ChromecastChannel {_socket.listen(_receive,onError: (Object error, StackTrace stackTrace) {+ _envelopes.addError(error, stackTrace);_messages.addError(error, stackTrace);unawaited(close());},- onDone: _messages.close,+ onDone: () {+ _envelopes.close();+ _messages.close();+ },cancelOnError: false,);}@@ -55,6 +61,7 @@ final class ChromecastChannel {final attemptTimeout = Duration(microseconds: remaining.inMicroseconds ~/ addressesLeft,);+ final attemptDeadline = DateTime.now().add(attemptTimeout);try {final socket = await SecureSocket.connect(uniqueAddresses[index],@@ -62,7 +69,30 @@ final class ChromecastChannel {timeout: attemptTimeout,onBadCertificate: (_) => true,);- return ChromecastChannel._(socket);+ final certificate = socket.peerCertificate;+ if (certificate == null) {+ await socket.close();+ throw const CastAuthenticationException(+ "Receiver supplied no TLS certificate",+ );+ }+ final channel = ChromecastChannel._(socket);+ try {+ final authenticationTimeout = attemptDeadline.difference(+ DateTime.now(),+ );+ if (authenticationTimeout <= Duration.zero) {+ throw TimeoutException(+ "Timed out authenticating Cast device",+ attemptTimeout,+ );+ }+ await channel._authenticate(certificate, authenticationTimeout);+ return channel;+ } catch (_) {+ await channel.close();+ rethrow;+ }} catch (error, stackTrace) {lastError = error;lastStackTrace = stackTrace;@@ -103,7 +133,12 @@ final class ChromecastChannel {void _receive(Uint8List chunk) {try {for (final envelope in _frameDecoder.add(chunk)) {- final decoded = jsonDecode(envelope.payload);+ _envelopes.add(envelope);+ final payload = envelope.payload;+ if (payload == null) {+ continue;+ }+ final decoded = jsonDecode(payload);if (decoded is! Map) {throw const FormatException("Cast payload is not an object");}@@ -115,8 +150,31 @@ final class ChromecastChannel {);}} catch (error, stackTrace) {+ _envelopes.addError(error, stackTrace);_messages.addError(error, stackTrace);unawaited(close());}}++ Future<void> _authenticate(+ X509Certificate peerCertificate,+ Duration timeout,+ ) {+ return CastDeviceAuthenticator().authenticate(+ peerCertificate: peerCertificate,+ envelopes: _envelopes.stream,+ timeout: timeout,+ sendChallenge: (payload) {+ _socket.add(+ encodeBinaryCastFrame(+ sourceID: castPlatformSenderID,+ destinationID: castPlatformReceiverID,+ namespace: castDeviceAuthNamespace,+ payload: payload,+ ),+ );+ },+ flush: _socket.flush,+ );+ }}diff --git a/mobile/apps/photos/plugins/ente_cast/lib/src/cast/simple_protobuf.dart b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/simple_protobuf.dartnew file mode 100644index 0000000000..d7d7fed1df--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/lib/src/cast/simple_protobuf.dart@@ -0,0 +1,104 @@+import "dart:convert";+import "dart:typed_data";++final class ProtoField {+ const ProtoField.varint(this.number, this.varint) : bytes = null;++ const ProtoField.bytes(this.number, this.bytes) : varint = null;++ const ProtoField.skipped(this.number) : varint = null, bytes = null;++ final int number;+ final int? varint;+ final Uint8List? bytes;+}++final class ProtoReader {+ ProtoReader(this._bytes);++ final Uint8List _bytes;+ var _offset = 0;++ bool get hasNext => _offset < _bytes.length;++ ProtoField readField() {+ final tag = _readVarint();+ final number = tag >> 3;+ if (number == 0) {+ throw const FormatException("Invalid protobuf field number");+ }+ final wireType = tag & 7;+ switch (wireType) {+ case 0:+ return ProtoField.varint(number, _readVarint());+ case 1:+ _skip(8);+ return ProtoField.skipped(number);+ case 2:+ final length = _readVarint();+ final end = _offset + length;+ if (length < 0 || end > _bytes.length) {+ throw const FormatException("Truncated protobuf field");+ }+ final value = Uint8List.fromList(_bytes.sublist(_offset, end));+ _offset = end;+ return ProtoField.bytes(number, value);+ case 5:+ _skip(4);+ return ProtoField.skipped(number);+ default:+ throw FormatException("Unsupported protobuf wire type $wireType");+ }+ }++ int _readVarint() {+ var value = 0;+ var shift = 0;+ while (_offset < _bytes.length && shift <= 63) {+ final byte = _bytes[_offset++];+ value |= (byte & 0x7f) << shift;+ if (byte & 0x80 == 0) {+ return value;+ }+ shift += 7;+ }+ throw const FormatException("Invalid protobuf varint");+ }++ void _skip(int length) {+ _offset += length;+ if (_offset > _bytes.length) {+ throw const FormatException("Truncated protobuf field");+ }+ }+}++final class ProtoWriter {+ final _output = BytesBuilder(copy: false);++ void writeVarint(int field, int value) {+ _writeVarint(field << 3);+ _writeVarint(value);+ }++ void writeBytes(int field, List<int> value) {+ _writeVarint((field << 3) | 2);+ _writeVarint(value.length);+ _output.add(value);+ }++ void writeString(int field, String value) {+ writeBytes(field, utf8.encode(value));+ }++ Uint8List takeBytes() => _output.takeBytes();++ void _writeVarint(int value) {+ var remaining = value;+ while (remaining >= 0x80) {+ _output.addByte((remaining & 0x7f) | 0x80);+ remaining >>= 7;+ }+ _output.addByte(remaining);+ }+}diff --git a/mobile/apps/photos/plugins/ente_cast/test/cast_device_auth_test.dart b/mobile/apps/photos/plugins/ente_cast/test/cast_device_auth_test.dartnew file mode 100644index 0000000000..7dcbb75ba9--- /dev/null+++ b/mobile/apps/photos/plugins/ente_cast/test/cast_device_auth_test.dart@@ -0,0 +1,233 @@+import "dart:async";+import "dart:io";+import "dart:typed_data";++import "package:ente_cast/src/cast/cast_device_auth.dart";+import "package:ente_cast/src/cast/cast_message_codec.dart";+import "package:ente_cast/src/cast/simple_protobuf.dart";+import "package:flutter_test/flutter_test.dart";++void main() {+ test("encodes a SHA-256 challenge with a sender nonce", () {+ final nonce = Uint8List.fromList(List.generate(16, (index) => index));++ expect(encodeCastAuthChallenge(nonce), [10, 20, 18, 16, ...nonce, 24, 1]);+ });++ test("decodes the device credentials from an auth response", () {+ final nonce = Uint8List.fromList(List.filled(16, 7));++ final response = decodeCastAuthResponse(+ _authResponse(+ signature: [1, 2],+ clientCertificate: [3, 4],+ intermediates: [+ [5],+ [6],+ ],+ nonce: nonce,+ hashAlgorithm: 1,+ ),+ );++ expect(response.signature, [1, 2]);+ expect(response.clientAuthCertificate, [3, 4]);+ expect(response.intermediateCertificates, [+ [5],+ [6],+ ]);+ expect(response.senderNonce, nonce);+ expect(response.hashAlgorithm, 1);+ });++ test(+ "verifies the nonce and TLS certificate signed by the receiver",+ () async {+ final nonce = Uint8List.fromList(List.generate(16, (index) => index));+ final envelopes = StreamController<CastEnvelope>.broadcast();+ Map<String, Object?>? verification;+ final authenticator = CastDeviceAuthenticator(+ createNonce: () => nonce,+ verifyCredentials: (arguments) async {+ verification = arguments;+ },+ );+ Uint8List? challenge;++ final authentication = authenticator.authenticate(+ peerCertificate: _FakeCertificate(Uint8List.fromList([8, 9])),+ envelopes: envelopes.stream,+ sendChallenge: (payload) {+ challenge = payload;+ envelopes.add(+ CastEnvelope(+ namespace: castDeviceAuthNamespace,+ payload: null,+ binaryPayload: _authResponse(+ signature: [1],+ clientCertificate: [2],+ intermediates: const [],+ nonce: nonce,+ hashAlgorithm: 1,+ ),+ ),+ );+ },+ flush: () async {},+ timeout: const Duration(seconds: 1),+ );++ await authentication;++ expect(challenge, encodeCastAuthChallenge(nonce));+ expect(verification?["signatureInput"], [...nonce, 8, 9]);+ await envelopes.close();+ },+ );++ test("supports legacy responses that omit the sender nonce", () async {+ final nonce = Uint8List.fromList(List.filled(16, 1));+ final envelopes = StreamController<CastEnvelope>.broadcast();+ Map<String, Object?>? verification;+ final authenticator = CastDeviceAuthenticator(+ createNonce: () => nonce,+ verifyCredentials: (arguments) async {+ verification = arguments;+ },+ );++ final authentication = authenticator.authenticate(+ peerCertificate: _FakeCertificate(Uint8List.fromList([8, 9])),+ envelopes: envelopes.stream,+ sendChallenge: (_) {+ envelopes.add(+ CastEnvelope(+ namespace: castDeviceAuthNamespace,+ payload: null,+ binaryPayload: _authResponse(+ signature: [1],+ clientCertificate: [2],+ intermediates: const [],+ nonce: const [],+ hashAlgorithm: 0,+ ),+ ),+ );+ },+ flush: () async {},+ timeout: const Duration(seconds: 1),+ );++ await authentication;++ expect(verification?["signatureInput"], [8, 9]);+ await envelopes.close();+ });++ test("rejects a mismatched sender nonce", () async {+ final nonce = Uint8List.fromList(List.filled(16, 1));+ final envelopes = StreamController<CastEnvelope>.broadcast();+ final authenticator = CastDeviceAuthenticator(+ createNonce: () => nonce,+ verifyCredentials: (_) async {},+ );++ final authentication = authenticator.authenticate(+ peerCertificate: _FakeCertificate(Uint8List.fromList([1])),+ envelopes: envelopes.stream,+ sendChallenge: (_) {+ envelopes.add(+ CastEnvelope(+ namespace: castDeviceAuthNamespace,+ payload: null,+ binaryPayload: _authResponse(+ signature: [1],+ clientCertificate: [2],+ intermediates: const [],+ nonce: List.filled(16, 2),+ hashAlgorithm: 1,+ ),+ ),+ );+ },+ flush: () async {},+ timeout: const Duration(seconds: 1),+ );++ await expectLater(+ authentication,+ throwsA(isA<CastAuthenticationException>()),+ );+ await envelopes.close();+ });++ test("rejects a TLS certificate valid for more than four days", () async {+ final authenticator = CastDeviceAuthenticator(+ createNonce: () => Uint8List(16),+ verifyCredentials: (_) async {},+ );++ await expectLater(+ authenticator.authenticate(+ peerCertificate: _FakeCertificate(+ Uint8List.fromList([1]),+ endValidity: DateTime.now().add(const Duration(days: 5)),+ ),+ envelopes: const Stream.empty(),+ sendChallenge: (_) {},+ flush: () async {},+ timeout: const Duration(seconds: 1),+ ),+ throwsA(isA<CastAuthenticationException>()),+ );+ });+}++Uint8List _authResponse({+ required List<int> signature,+ required List<int> clientCertificate,+ required List<List<int>> intermediates,+ required List<int> nonce,+ required int hashAlgorithm,+}) {+ final response = ProtoWriter()+ ..writeBytes(1, signature)+ ..writeBytes(2, clientCertificate);+ for (final intermediate in intermediates) {+ response.writeBytes(3, intermediate);+ }+ response+ ..writeBytes(5, nonce)+ ..writeVarint(6, hashAlgorithm);+ return (ProtoWriter()..writeBytes(2, response.takeBytes())).takeBytes();+}++final class _FakeCertificate implements X509Certificate {+ _FakeCertificate(this.der, {DateTime? endValidity})+ : _endValidity = endValidity;++ @override+ final Uint8List der;++ final DateTime? _endValidity;++ @override+ DateTime get endValidity =>+ _endValidity ?? DateTime.now().add(const Duration(days: 1));++ @override+ String get issuer => "issuer";++ @override+ String get pem => "";++ @override+ Uint8List get sha1 => Uint8List(0);++ @override+ DateTime get startValidity =>+ DateTime.now().subtract(const Duration(days: 1));++ @override+ String get subject => "subject";+}diff --git a/mobile/apps/photos/plugins/ente_cast/test/cast_message_codec_test.dart b/mobile/apps/photos/plugins/ente_cast/test/cast_message_codec_test.dartindex 3fa5d5d145..0cb2118207 100644--- a/mobile/apps/photos/plugins/ente_cast/test/cast_message_codec_test.dart+++ b/mobile/apps/photos/plugins/ente_cast/test/cast_message_codec_test.dart@@ -48,6 +48,22 @@ void main() {expect(decoded.namespace, "urn:x-cast:pair-request");expect(decoded.payload, '{"collectionID":42}');+ expect(decoded.binaryPayload, isNull);+ });++ test("encodes and decodes binary Cast fields", () {+ final encoded = encodeBinaryCastEnvelope(+ sourceID: "sender-0",+ destinationID: "receiver-0",+ namespace: "urn:x-cast:com.google.cast.tp.deviceauth",+ payload: Uint8List.fromList([0, 1, 255]),+ );++ final decoded = decodeCastEnvelope(encoded);++ expect(decoded.namespace, "urn:x-cast:com.google.cast.tp.deviceauth");+ expect(decoded.payload, isNull);+ expect(decoded.binaryPayload, [0, 1, 255]);});test("rejects a truncated Cast message", () {