π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Validate public album keys before caching
Neeraj Guptaf60d27661593
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dartindex fd3759137b..67f0eb1ba0 100644--- a/mobile/apps/photos/lib/services/collections_service.dart+++ b/mobile/apps/photos/lib/services/collections_service.dart@@ -54,6 +54,7 @@ class CollectionsService {static const int kMaximumWriteAttempts = 5;static const int _maxSocialCleanupRetries = 3;+ static const int _collectionKeyLength = 32;final _logger = Logger("CollectionsService");@@ -78,6 +79,7 @@ class CollectionsService {final _cachedPublicAlbumJWT = <int, String>{};final _cachedPublicCollectionID = <int>[];final _cachedPublicAlbumKey = <int, String>{};+ final _cachedPublicCollectionKeys = <int, Uint8List>{};// In-memory list of recently used collection IDs for add/move actions// Most recently used is at the front@@ -214,6 +216,7 @@ class CollectionsService {_cachedPublicCollectionID.clear();_cachedKeys.clear();_cachedPublicAlbumKey.clear();+ _cachedPublicCollectionKeys.clear();}Future<Map<int, int>> getCollectionIDsToBeSynced() async {@@ -1025,6 +1028,14 @@ class CollectionsService {return _cachedKeys[collectionID]!;}+ Uint8List getPublicCollectionKey(int collectionID) {+ final collectionKey = _cachedPublicCollectionKeys[collectionID];+ if (collectionKey == null) {+ throw StateError("public collection key $collectionID is not cached");+ }+ return collectionKey;+ }+String getPublicUrl(Collection c) {final PublicURL url = c.publicURLs.firstOrNull!;Uri publicUrl = Uri.parse(url.url);@@ -1508,6 +1519,48 @@ class CollectionsService {}}+ Uint8List _decodePublicCollectionKey(String albumKey) {+ if (albumKey.isEmpty) {+ throw const FormatException("Missing public collection key");+ }+ final collectionKey = Uint8List.fromList(Base58Decode(albumKey));+ if (collectionKey.length != _collectionKeyLength) {+ throw const FormatException("Invalid public collection key length");+ }+ return collectionKey;+ }++ Future<void> _decryptPublicCollectionFields(+ Collection collection,+ Map<String, dynamic> collectionData,+ Uint8List collectionKey,+ ) async {+ collection.setName(_decryptCollectionNameWithKey(collection, collectionKey));+ if (collectionData['pubMagicMetadata'] != null) {+ final utfEncodedMmd = await CryptoUtil.decryptChaCha(+ CryptoUtil.base642bin(collectionData['pubMagicMetadata']['data']),+ collectionKey,+ CryptoUtil.base642bin(+ collectionData['pubMagicMetadata']['header'],+ ),+ );+ collection.mMdPubEncodedJson = utf8.decode(utfEncodedMmd);+ collection.mMbPubVersion = collectionData['pubMagicMetadata']['version'];+ collection.pubMagicMetadata =+ CollectionPubMagicMetadata.fromEncodedJson(+ collection.mMdPubEncodedJson ?? '{}',+ );+ }+ }++ void _clearPublicCollectionState(int collectionID) {+ _cachedPublicAlbumToken.remove(collectionID);+ _cachedPublicAlbumJWT.remove(collectionID);+ _cachedPublicCollectionID.removeWhere((id) => id == collectionID);+ _cachedPublicAlbumKey.remove(collectionID);+ _cachedPublicCollectionKeys.remove(collectionID);+ }+Future<Collection?> getCollectionFromPublicLink(BuildContext context,Uri uri,@@ -1520,32 +1573,41 @@ class CollectionsService {final collectionData = responseData["collection"];final Collection collection = Collection.fromMap(collectionData);- final Uint8List collectionKey =- Uint8List.fromList(Base58Decode(albumKey));-- _cachedKeys[collection.id] = collectionKey;- _cachedPublicAlbumToken[collection.id] = authToken;- _cachedPublicCollectionID.add(collection.id);- _cachedPublicAlbumKey[collection.id] = albumKey;-- if (collectionData['pubMagicMetadata'] != null) {- final utfEncodedMmd = await CryptoUtil.decryptChaCha(- CryptoUtil.base642bin(collectionData['pubMagicMetadata']['data']),- collectionKey,- CryptoUtil.base642bin(- collectionData['pubMagicMetadata']['header'],- ),+ final existingCollection = getCollectionByID(collection.id);+ final currentUserID = _config.getUserID() ?? -1;+ final shouldUseAuthenticatedKey = collection.isOwner(currentUserID) ||+ (existingCollection != null && !existingCollection.isDeleted);++ if (shouldUseAuthenticatedKey) {+ _clearPublicCollectionState(collection.id);+ final keySourceCollection =+ existingCollection != null && !existingCollection.isDeleted+ ? existingCollection+ : collection;+ final collectionKey = _getAndCacheDecryptedKey(+ keySourceCollection,+ source: "publicLinkExistingCollection",);- collection.mMdPubEncodedJson = utf8.decode(utfEncodedMmd);- collection.mMbPubVersion =- collectionData['pubMagicMetadata']['version'];- collection.pubMagicMetadata =- CollectionPubMagicMetadata.fromEncodedJson(- collection.mMdPubEncodedJson ?? '{}',+ await _decryptPublicCollectionFields(+ collection,+ collectionData,+ collectionKey,);+ return collection;}- collection.setName(_getDecryptedCollectionName(collection));+ final collectionKey = _decodePublicCollectionKey(albumKey);+ await _decryptPublicCollectionFields(+ collection,+ collectionData,+ collectionKey,+ );+ _cachedPublicCollectionKeys[collection.id] = collectionKey;+ _cachedPublicAlbumToken[collection.id] = authToken;+ _cachedPublicCollectionID.removeWhere((id) => id == collection.id);+ _cachedPublicCollectionID.add(collection.id);+ _cachedPublicAlbumKey[collection.id] = albumKey;+ _cachedPublicAlbumJWT.remove(collection.id);return collection;} on PublicCollectionInfoExpiredException catch (e, s) {_logger.warning("Public collection link expired", e, s);@@ -1620,12 +1682,13 @@ class CollectionsService {BuildContext context,int collectionID,) async {- final key = getSharedPublicAlbumKey(collectionID);- if (key.isEmpty) {+ final albumKey = getSharedPublicAlbumKey(collectionID);+ if (albumKey.isEmpty) {throw Exception("Collection key not found");}+ final collectionKey = getPublicCollectionKey(collectionID);final encryptedKey = CryptoUtil.sealSync(- getCollectionKey(collectionID),+ collectionKey,CryptoUtil.base642bin(Configuration.instance.getKeyAttributes()!.publicKey,),@@ -2439,6 +2502,25 @@ class CollectionsService {return _prefs.containsKey(_collectionsSyncTimeKey);}+ String _decryptCollectionNameWithKey(+ Collection collection,+ Uint8List collectionKey,+ ) {+ if (collection.isDeleted) {+ return "Deleted Album";+ }+ if (collection.encryptedName != null &&+ collection.encryptedName!.isNotEmpty) {+ final result = CryptoUtil.decryptSync(+ CryptoUtil.base642bin(collection.encryptedName!),+ collectionKey,+ CryptoUtil.base642bin(collection.nameDecryptionNonce!),+ );+ return utf8.decode(result);+ }+ return collection.displayName;+ }+String _getDecryptedCollectionName(Collection collection) {if (collection.isDeleted) {return "Deleted Album";@@ -2450,12 +2532,7 @@ class CollectionsService {collection,source: "Name",);- final result = CryptoUtil.decryptSync(- CryptoUtil.base642bin(collection.encryptedName!),- collectionKey,- CryptoUtil.base642bin(collection.nameDecryptionNonce!),- );- return utf8.decode(result);+ return _decryptCollectionNameWithKey(collection, collectionKey);} catch (e, s) {_logger.severe("failed to decrypt collection name: ${collection.id}",diff --git a/mobile/apps/photos/lib/services/sync/diff_fetcher.dart b/mobile/apps/photos/lib/services/sync/diff_fetcher.dartindex 93db27d0bd..378e59aabe 100644--- a/mobile/apps/photos/lib/services/sync/diff_fetcher.dart+++ b/mobile/apps/photos/lib/services/sync/diff_fetcher.dart@@ -28,6 +28,8 @@ class DiffFetcher {final sharedFiles = <EnteFile>[];final headers =CollectionsService.instance.publicCollectionHeaders(collectionID);+ final collectionKey =+ CollectionsService.instance.getPublicCollectionKey(collectionID);int sinceTime = 0;do {@@ -60,7 +62,7 @@ class DiffFetcher {if (item["info"] != null) {file.fileSize = item["info"]["fileSize"];}- final fileKey = getFileKey(file);+ final fileKey = getFileKeyWithCollectionKey(file, collectionKey);final encodedMetadata = await CryptoUtil.decryptChaCha(CryptoUtil.base642bin(item["metadata"]["encryptedData"]),fileKey,diff --git a/mobile/apps/photos/lib/services/video_preview_service.dart b/mobile/apps/photos/lib/services/video_preview_service.dartindex 0e20d7995d..dc22e0045e 100644--- a/mobile/apps/photos/lib/services/video_preview_service.dart+++ b/mobile/apps/photos/lib/services/video_preview_service.dart@@ -1018,7 +1018,10 @@ class VideoPreviewService {type: "vid_preview",);}- final encryptionKey = getFileKey(file);+ final encryptionKey =+ collectionsService.isSharedPublicLink(file.collectionID!)+ ? getPublicFileKey(file)+ : getFileKey(file);final playlistData = await decryptAndUnzipJson(encryptionKey,encryptedData: fetchResult.encryptedData,diff --git a/mobile/apps/photos/lib/utils/file_download_util.dart b/mobile/apps/photos/lib/utils/file_download_util.dartindex 0ecd1e3b94..0f3ae42b85 100644--- a/mobile/apps/photos/lib/utils/file_download_util.dart+++ b/mobile/apps/photos/lib/utils/file_download_util.dart@@ -133,7 +133,7 @@ Future<File?> downloadAndDecryptPublicFile(encryptedFilePath,decryptedFilePath,CryptoUtil.base642bin(file.fileDecryptionHeader!),- getFileKey(file),+ getPublicFileKey(file),);fakeProgress?.stop();_logger.info('$logPrefix file saved at $decryptedFilePath');diff --git a/mobile/apps/photos/lib/utils/file_key.dart b/mobile/apps/photos/lib/utils/file_key.dartindex 345c6f6b1d..28464f4af4 100644--- a/mobile/apps/photos/lib/utils/file_key.dart+++ b/mobile/apps/photos/lib/utils/file_key.dart@@ -6,16 +6,39 @@ import "package:photos/models/file/file.dart";import "package:photos/services/collections_service.dart";Uint8List getFileKey(EnteFile file) {- final encryptedKey = CryptoUtil.base642bin(file.encryptedKey!);- final nonce = CryptoUtil.base642bin(file.keyDecryptionNonce!);final collectionKey =CollectionsService.instance.getCollectionKey(file.collectionID!);+ return getFileKeyWithCollectionKey(file, collectionKey);+}++Uint8List getPublicFileKey(EnteFile file) {+ final collectionKey =+ CollectionsService.instance.getPublicCollectionKey(file.collectionID!);+ return getFileKeyWithCollectionKey(file, collectionKey);+}++Uint8List getFileKeyWithCollectionKey(EnteFile file, Uint8List collectionKey) {+ final encryptedKey = CryptoUtil.base642bin(file.encryptedKey!);+ final nonce = CryptoUtil.base642bin(file.keyDecryptionNonce!);return CryptoUtil.decryptSync(encryptedKey, collectionKey, nonce);}Future<Uint8List> getFileKeyUsingBgWorker(EnteFile file) async {final collectionKey =CollectionsService.instance.getCollectionKey(file.collectionID!);+ return getFileKeyWithCollectionKeyUsingBgWorker(file, collectionKey);+}++Future<Uint8List> getPublicFileKeyUsingBgWorker(EnteFile file) async {+ final collectionKey =+ CollectionsService.instance.getPublicCollectionKey(file.collectionID!);+ return getFileKeyWithCollectionKeyUsingBgWorker(file, collectionKey);+}++Future<Uint8List> getFileKeyWithCollectionKeyUsingBgWorker(+ EnteFile file,+ Uint8List collectionKey,+) async {return await Computer.shared().compute(_decryptFileKey,param: <String, dynamic>{diff --git a/mobile/apps/photos/lib/utils/thumbnail_util.dart b/mobile/apps/photos/lib/utils/thumbnail_util.dartindex b2428c5853..7d89d7340b 100644--- a/mobile/apps/photos/lib/utils/thumbnail_util.dart+++ b/mobile/apps/photos/lib/utils/thumbnail_util.dart@@ -201,7 +201,10 @@ Future<void> _downloadAndDecryptThumbnail(FileDownloadItem item) async {if (!_uploadIDToDownloadItem.containsKey(file.uploadedFileID)) {return;}- final thumbnailDecryptionKey = await getFileKeyUsingBgWorker(file);+ final thumbnailDecryptionKey =+ CollectionsService.instance.isSharedPublicLink(file.collectionID!)+ ? await getPublicFileKeyUsingBgWorker(file)+ : await getFileKeyUsingBgWorker(file);Uint8List data;try {data = await CryptoUtil.decryptChaCha(