Xchaha20 poly1305 integration (#569)

* Integration of xchacha20-poly1305

* Remove force unwrap from _exportPreferencesJSON

* Deprecate v1 export

* Fix for open backup screen after auth
This commit is contained in:
mkyq 2022-10-26 15:28:27 -04:00 committed by GitHub
parent 33935c9b1d
commit acb03e5530
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 168 additions and 53 deletions

View file

@ -16,6 +16,7 @@ import 'package:cake_wallet/entities/secret_store_key.dart';
import 'package:cw_core/wallet_info.dart'; import 'package:cw_core/wallet_info.dart';
import 'package:cake_wallet/.secrets.g.dart' as secrets; import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/wallet_types.g.dart'; import 'package:cake_wallet/wallet_types.g.dart';
import 'package:cake_backup/backup.dart' as cake_backup;
class BackupService { class BackupService {
BackupService(this._flutterSecureStorage, this._walletInfoSource, BackupService(this._flutterSecureStorage, this._walletInfoSource,
@ -23,9 +24,10 @@ class BackupService {
: _cipher = Cryptography.instance.chacha20Poly1305Aead(), : _cipher = Cryptography.instance.chacha20Poly1305Aead(),
_correctWallets = <WalletInfo>[]; _correctWallets = <WalletInfo>[];
static const currentVersion = _v1; static const currentVersion = _v2;
static const _v1 = 1; static const _v1 = 1;
static const _v2 = 2;
final Cipher _cipher; final Cipher _cipher;
final FlutterSecureStorage _flutterSecureStorage; final FlutterSecureStorage _flutterSecureStorage;
@ -37,13 +39,16 @@ class BackupService {
Future<void> importBackup(Uint8List data, String password, Future<void> importBackup(Uint8List data, String password,
{String nonce = secrets.backupSalt}) async { {String nonce = secrets.backupSalt}) async {
final version = getVersion(data); final version = getVersion(data);
final backupBytes = data.toList()..removeAt(0);
final backupData = Uint8List.fromList(backupBytes);
switch (version) { switch (version) {
case _v1: case _v1:
final backupBytes = data.toList()..removeAt(0);
final backupData = Uint8List.fromList(backupBytes);
await _importBackupV1(backupData, password, nonce: nonce); await _importBackupV1(backupData, password, nonce: nonce);
break; break;
case _v2:
await _importBackupV2(data, password);
break;
default: default:
break; break;
} }
@ -54,20 +59,26 @@ class BackupService {
switch (version) { switch (version) {
case _v1: case _v1:
return await _exportBackupV1(password, nonce: nonce); return await _exportBackupV1(password, nonce: nonce);
case _v2:
return await _exportBackupV2(password);
default: default:
throw Exception('Incorrect version: $version for exportBackup'); throw Exception('Incorrect version: $version for exportBackup');
} }
} }
@Deprecated('Use v2 instead')
Future<Uint8List> _exportBackupV1(String password, Future<Uint8List> _exportBackupV1(String password,
{String nonce = secrets.backupSalt}) async { {String nonce = secrets.backupSalt}) async
=> throw Exception('Deprecated. Export for backups v1 is deprecated. Please use export v2.');
Future<Uint8List> _exportBackupV2(String password) async {
final zipEncoder = ZipFileEncoder(); final zipEncoder = ZipFileEncoder();
final appDir = await getApplicationDocumentsDirectory(); final appDir = await getApplicationDocumentsDirectory();
final now = DateTime.now(); final now = DateTime.now();
final tmpDir = Directory('${appDir.path}/~_BACKUP_TMP'); final tmpDir = Directory('${appDir.path}/~_BACKUP_TMP');
final archivePath = '${tmpDir.path}/backup_${now.toString()}.zip'; final archivePath = '${tmpDir.path}/backup_${now.toString()}.zip';
final fileEntities = appDir.listSync(recursive: false); final fileEntities = appDir.listSync(recursive: false);
final keychainDump = await _exportKeychainDump(password, nonce: nonce); final keychainDump = await _exportKeychainDumpV2(password);
final preferencesDump = await _exportPreferencesJSON(); final preferencesDump = await _exportPreferencesJSON();
final preferencesDumpFile = File('${tmpDir.path}/~_preferences_dump_TMP'); final preferencesDumpFile = File('${tmpDir.path}/~_preferences_dump_TMP');
final keychainDumpFile = File('${tmpDir.path}/~_keychain_dump_TMP'); final keychainDumpFile = File('${tmpDir.path}/~_keychain_dump_TMP');
@ -98,15 +109,13 @@ class BackupService {
final content = File(archivePath).readAsBytesSync(); final content = File(archivePath).readAsBytesSync();
tmpDir.deleteSync(recursive: true); tmpDir.deleteSync(recursive: true);
final encryptedData = await _encrypt(content, password, nonce); return await _encryptV2(content, password);
return setVersion(encryptedData, currentVersion);
} }
Future<void> _importBackupV1(Uint8List data, String password, Future<void> _importBackupV1(Uint8List data, String password,
{required String nonce}) async { {required String nonce}) async {
final appDir = await getApplicationDocumentsDirectory(); final appDir = await getApplicationDocumentsDirectory();
final decryptedData = await _decrypt(data, password, nonce); final decryptedData = await _decryptV1(data, password, nonce);
final zip = ZipDecoder().decodeBytes(decryptedData); final zip = ZipDecoder().decodeBytes(decryptedData);
zip.files.forEach((file) { zip.files.forEach((file) {
@ -123,7 +132,30 @@ class BackupService {
}); });
await _verifyWallets(); await _verifyWallets();
await _importKeychainDump(password, nonce: nonce); await _importKeychainDumpV1(password, nonce: nonce);
await _importPreferencesDump();
}
Future<void> _importBackupV2(Uint8List data, String password) async {
final appDir = await getApplicationDocumentsDirectory();
final decryptedData = await _decryptV2(data, password);
final zip = ZipDecoder().decodeBytes(decryptedData);
zip.files.forEach((file) {
final filename = file.name;
if (file.isFile) {
final content = file.content as List<int>;
File('${appDir.path}/' + filename)
..createSync(recursive: true)
..writeAsBytesSync(content);
} else {
Directory('${appDir.path}/' + filename)..create(recursive: true);
}
});
await _verifyWallets();
await _importKeychainDumpV2(password);
await _importPreferencesDump(); await _importPreferencesDump();
} }
@ -258,12 +290,12 @@ class BackupService {
await preferencesFile.delete(); await preferencesFile.delete();
} }
Future<void> _importKeychainDump(String password, Future<void> _importKeychainDumpV1(String password,
{required String nonce, {required String nonce,
String keychainSalt = secrets.backupKeychainSalt}) async { String keychainSalt = secrets.backupKeychainSalt}) async {
final appDir = await getApplicationDocumentsDirectory(); final appDir = await getApplicationDocumentsDirectory();
final keychainDumpFile = File('${appDir.path}/~_keychain_dump'); final keychainDumpFile = File('${appDir.path}/~_keychain_dump');
final decryptedKeychainDumpFileData = await _decrypt( final decryptedKeychainDumpFileData = await _decryptV1(
keychainDumpFile.readAsBytesSync(), '$keychainSalt$password', nonce); keychainDumpFile.readAsBytesSync(), '$keychainSalt$password', nonce);
final keychainJSON = json.decode(utf8.decode(decryptedKeychainDumpFileData)) final keychainJSON = json.decode(utf8.decode(decryptedKeychainDumpFileData))
as Map<String, dynamic>; as Map<String, dynamic>;
@ -288,6 +320,35 @@ class BackupService {
keychainDumpFile.deleteSync(); keychainDumpFile.deleteSync();
} }
Future<void> _importKeychainDumpV2(String password,
{String keychainSalt = secrets.backupKeychainSalt}) async {
final appDir = await getApplicationDocumentsDirectory();
final keychainDumpFile = File('${appDir.path}/~_keychain_dump');
final decryptedKeychainDumpFileData = await _decryptV2(
keychainDumpFile.readAsBytesSync(), '$keychainSalt$password');
final keychainJSON = json.decode(utf8.decode(decryptedKeychainDumpFileData))
as Map<String, dynamic>;
final keychainWalletsInfo = keychainJSON['wallets'] as List;
final decodedPin = keychainJSON['pin'] as String;
final pinCodeKey = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final backupPasswordKey =
generateStoreKeyFor(key: SecretStoreKey.backupPassword);
final backupPassword = keychainJSON[backupPasswordKey] as String;
await _flutterSecureStorage.write(
key: backupPasswordKey, value: backupPassword);
keychainWalletsInfo.forEach((dynamic rawInfo) async {
final info = rawInfo as Map<String, dynamic>;
await importWalletKeychainInfo(info);
});
await _flutterSecureStorage.write(
key: pinCodeKey, value: encodedPinCode(pin: decodedPin));
keychainDumpFile.deleteSync();
}
Future<void> importWalletKeychainInfo(Map<String, dynamic> info) async { Future<void> importWalletKeychainInfo(Map<String, dynamic> info) async {
final name = info['name'] as String; final name = info['name'] as String;
final password = info['password'] as String; final password = info['password'] as String;
@ -295,9 +356,14 @@ class BackupService {
await _keyService.saveWalletPassword(walletName: name, password: password); await _keyService.saveWalletPassword(walletName: name, password: password);
} }
Future<Uint8List> _exportKeychainDump(String password, @Deprecated('Use v2 instead')
Future<Uint8List> _exportKeychainDumpV1(String password,
{required String nonce, {required String nonce,
String keychainSalt = secrets.backupKeychainSalt}) async { String keychainSalt = secrets.backupKeychainSalt}) async
=> throw Exception('Deprecated');
Future<Uint8List> _exportKeychainDumpV2(String password,
{String keychainSalt = secrets.backupKeychainSalt}) async {
final key = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword); final key = generateStoreKeyFor(key: SecretStoreKey.pinCodePassword);
final encodedPin = await _flutterSecureStorage.read(key: key); final encodedPin = await _flutterSecureStorage.read(key: key);
final decodedPin = decodedPinCode(pin: encodedPin!); final decodedPin = decodedPinCode(pin: encodedPin!);
@ -319,49 +385,48 @@ class BackupService {
'wallets': wallets, 'wallets': wallets,
backupPasswordKey: backupPassword backupPasswordKey: backupPassword
})); }));
final encrypted = await _encrypt( final encrypted = await _encryptV2(
Uint8List.fromList(data), '$keychainSalt$password', nonce); Uint8List.fromList(data), '$keychainSalt$password');
return encrypted; return encrypted;
} }
Future<String> _exportPreferencesJSON() async { Future<String> _exportPreferencesJSON() async {
// FIX-ME: Force unwrap
final preferences = <String, dynamic>{ final preferences = <String, dynamic>{
PreferencesKey.currentWalletName: PreferencesKey.currentWalletName:
_sharedPreferences.getString(PreferencesKey.currentWalletName)!, _sharedPreferences.getString(PreferencesKey.currentWalletName),
PreferencesKey.currentNodeIdKey: PreferencesKey.currentNodeIdKey:
_sharedPreferences.getInt(PreferencesKey.currentNodeIdKey)!, _sharedPreferences.getInt(PreferencesKey.currentNodeIdKey),
PreferencesKey.currentBalanceDisplayModeKey: _sharedPreferences PreferencesKey.currentBalanceDisplayModeKey: _sharedPreferences
.getInt(PreferencesKey.currentBalanceDisplayModeKey)!, .getInt(PreferencesKey.currentBalanceDisplayModeKey),
PreferencesKey.currentWalletType: PreferencesKey.currentWalletType:
_sharedPreferences.getInt(PreferencesKey.currentWalletType)!, _sharedPreferences.getInt(PreferencesKey.currentWalletType),
PreferencesKey.currentFiatCurrencyKey: PreferencesKey.currentFiatCurrencyKey:
_sharedPreferences.getString(PreferencesKey.currentFiatCurrencyKey)!, _sharedPreferences.getString(PreferencesKey.currentFiatCurrencyKey),
PreferencesKey.shouldSaveRecipientAddressKey: _sharedPreferences PreferencesKey.shouldSaveRecipientAddressKey: _sharedPreferences
.getBool(PreferencesKey.shouldSaveRecipientAddressKey)!, .getBool(PreferencesKey.shouldSaveRecipientAddressKey),
PreferencesKey.isDarkThemeLegacy: PreferencesKey.isDarkThemeLegacy:
_sharedPreferences.getBool(PreferencesKey.isDarkThemeLegacy)!, _sharedPreferences.getBool(PreferencesKey.isDarkThemeLegacy),
PreferencesKey.currentPinLength: PreferencesKey.currentPinLength:
_sharedPreferences.getInt(PreferencesKey.currentPinLength)!, _sharedPreferences.getInt(PreferencesKey.currentPinLength),
PreferencesKey.currentTransactionPriorityKeyLegacy: _sharedPreferences PreferencesKey.currentTransactionPriorityKeyLegacy: _sharedPreferences
.getInt(PreferencesKey.currentTransactionPriorityKeyLegacy)!, .getInt(PreferencesKey.currentTransactionPriorityKeyLegacy),
PreferencesKey.allowBiometricalAuthenticationKey: _sharedPreferences PreferencesKey.allowBiometricalAuthenticationKey: _sharedPreferences
.getBool(PreferencesKey.allowBiometricalAuthenticationKey)!, .getBool(PreferencesKey.allowBiometricalAuthenticationKey),
PreferencesKey.currentBitcoinElectrumSererIdKey: _sharedPreferences PreferencesKey.currentBitcoinElectrumSererIdKey: _sharedPreferences
.getInt(PreferencesKey.currentBitcoinElectrumSererIdKey)!, .getInt(PreferencesKey.currentBitcoinElectrumSererIdKey),
PreferencesKey.currentLanguageCode: PreferencesKey.currentLanguageCode:
_sharedPreferences.getString(PreferencesKey.currentLanguageCode)!, _sharedPreferences.getString(PreferencesKey.currentLanguageCode),
PreferencesKey.displayActionListModeKey: PreferencesKey.displayActionListModeKey:
_sharedPreferences.getInt(PreferencesKey.displayActionListModeKey)!, _sharedPreferences.getInt(PreferencesKey.displayActionListModeKey),
PreferencesKey.currentTheme: PreferencesKey.currentTheme:
_sharedPreferences.getInt(PreferencesKey.currentTheme)!, _sharedPreferences.getInt(PreferencesKey.currentTheme),
PreferencesKey.currentDefaultSettingsMigrationVersion: _sharedPreferences PreferencesKey.currentDefaultSettingsMigrationVersion: _sharedPreferences
.getInt(PreferencesKey.currentDefaultSettingsMigrationVersion)!, .getInt(PreferencesKey.currentDefaultSettingsMigrationVersion),
PreferencesKey.bitcoinTransactionPriority: PreferencesKey.bitcoinTransactionPriority:
_sharedPreferences.getInt(PreferencesKey.bitcoinTransactionPriority)!, _sharedPreferences.getInt(PreferencesKey.bitcoinTransactionPriority),
PreferencesKey.moneroTransactionPriority: PreferencesKey.moneroTransactionPriority:
_sharedPreferences.getInt(PreferencesKey.moneroTransactionPriority)!, _sharedPreferences.getInt(PreferencesKey.moneroTransactionPriority),
}; };
return json.encode(preferences); return json.encode(preferences);
@ -374,16 +439,12 @@ class BackupService {
return Uint8List.fromList(bytes); return Uint8List.fromList(bytes);
} }
Future<Uint8List> _encrypt( @Deprecated('Use v2 instead')
Uint8List data, String secretKeySource, String nonceBase64) async { Future<Uint8List> _encryptV1(
final secretKeyHash = await Cryptography.instance.sha256().hash(utf8.encode(secretKeySource)); Uint8List data, String secretKeySource, String nonceBase64) async
final secretKey = SecretKey(secretKeyHash.bytes); => throw Exception('Deprecated');
final nonce = base64.decode(nonceBase64).toList();
final box = await _cipher.encrypt(data.toList(), secretKey: secretKey, nonce: nonce);
return Uint8List.fromList(box.cipherText);
}
Future<Uint8List> _decrypt( Future<Uint8List> _decryptV1(
Uint8List data, String secretKeySource, String nonceBase64, {int macLength = 16}) async { Uint8List data, String secretKeySource, String nonceBase64, {int macLength = 16}) async {
final secretKeyHash = await Cryptography.instance.sha256().hash(utf8.encode(secretKeySource)); final secretKeyHash = await Cryptography.instance.sha256().hash(utf8.encode(secretKeySource));
final secretKey = SecretKey(secretKeyHash.bytes); final secretKey = SecretKey(secretKeyHash.bytes);
@ -395,4 +456,12 @@ class BackupService {
final plainData = await _cipher.decrypt(box, secretKey: secretKey); final plainData = await _cipher.decrypt(box, secretKey: secretKey);
return Uint8List.fromList(plainData); return Uint8List.fromList(plainData);
} }
Future<Uint8List> _encryptV2(
Uint8List data, String passphrase) async
=> cake_backup.encrypt(passphrase, data, version: _v2);
Future<Uint8List> _decryptV2(
Uint8List data, String passphrase) async
=> cake_backup.decrypt(passphrase, data);
} }

View file

@ -1,10 +1,10 @@
import 'dart:io'; import 'dart:io';
import 'package:cake_wallet/palette.dart'; import 'package:cake_wallet/palette.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:flutter_mobx/flutter_mobx.dart';
// import 'package:esys_flutter_share/esys_flutter_share.dart'; import 'package:share_plus/share_plus.dart';
import 'package:cross_file/cross_file.dart';
import 'package:cake_wallet/utils/show_bar.dart'; import 'package:cake_wallet/utils/show_bar.dart';
import 'package:cake_wallet/routes.dart'; import 'package:cake_wallet/routes.dart';
import 'package:cake_wallet/generated/i18n.dart'; import 'package:cake_wallet/generated/i18n.dart';
@ -103,12 +103,14 @@ class BackupPage extends BasePage {
Navigator.of(dialogContext).pop(); Navigator.of(dialogContext).pop();
final backup = await backupViewModelBase.exportBackup(); final backup = await backupViewModelBase.exportBackup();
if (backup == null) {
return;
}
if (Platform.isAndroid) { if (Platform.isAndroid) {
onExportAndroid(context, backup!); onExportAndroid(context, backup);
} else { } else {
// FIX-ME: Share esys_flutter_share.dart await share(backup);
// await Share.file(S.of(context).backup_file, backup.name,
// backup.content, 'application/*');
} }
}, },
actionLeftButton: () => Navigator.of(dialogContext).pop()); actionLeftButton: () => Navigator.of(dialogContext).pop());
@ -136,12 +138,20 @@ class BackupPage extends BasePage {
backup.name, backup.content); backup.name, backup.content);
Navigator.of(dialogContext).pop(); Navigator.of(dialogContext).pop();
}, },
actionLeftButton: () { actionLeftButton: () async {
Navigator.of(dialogContext).pop(); Navigator.of(dialogContext).pop();
// FIX-ME: Share esys_flutter_share.dart await share(backup);
// Share.file(S.of(context).backup_file, backup.name,
// backup.content, 'application/*');
}); });
}); });
} }
Future<void> share(BackupExportFile backup) async {
const mimeType = 'application/*';
final path = await backupViewModelBase.saveBackupFileLocally(backup);
await Share.shareXFiles(<XFile>[XFile(
path,
name: backup.name,
mimeType: mimeType)]);
await backupViewModelBase.removeBackupFileLocally(backup);
}
} }

View file

@ -51,6 +51,21 @@ class WalletMenu {
image: Image.asset('assets/images/open_book_menu.png', image: Image.asset('assets/images/open_book_menu.png',
height: 16, width: 16), height: 16, width: 16),
handler: () => Navigator.of(context).pushNamed(Routes.addressBook)), handler: () => Navigator.of(context).pushNamed(Routes.addressBook)),
WalletMenuItem(
title: S.current.backup,
image: Image.asset('assets/images/restore_wallet.png',
height: 16,
width: 16,
color: Palette.darkBlue),
handler: () {
Navigator.of(context).pushNamed(
Routes.auth,
arguments: (bool isAuthenticatedSuccessfully, AuthPageState auth) {
if (isAuthenticatedSuccessfully) {
auth.close(route:Routes.backup);
}
});
}),
WalletMenuItem( WalletMenuItem(
title: S.current.settings_title, title: S.current.settings_title,
image: Image.asset('assets/images/settings_menu.png', image: Image.asset('assets/images/settings_menu.png',

View file

@ -8,6 +8,7 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:mobx/mobx.dart'; import 'package:mobx/mobx.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:cake_wallet/wallet_type_utils.dart'; import 'package:cake_wallet/wallet_type_utils.dart';
import 'package:path_provider/path_provider.dart';
part 'backup_view_model.g.dart'; part 'backup_view_model.g.dart';
@ -71,6 +72,21 @@ abstract class BackupViewModelBase with Store {
} }
} }
Future<String> saveBackupFileLocally(BackupExportFile backup) async {
final appDir = await getApplicationDocumentsDirectory();
final path = '${appDir.path}/${backup.name}';
final backupFile = File(path);
await backupFile.writeAsBytes(backup.content);
return path;
}
Future<void> removeBackupFileLocally(BackupExportFile backup) async {
final appDir = await getApplicationDocumentsDirectory();
final path = '${appDir.path}/${backup.name}';
final backupFile = File(path);
await backupFile.delete();
}
@action @action
void showMasterPassword() => isBackupPasswordVisible = true; void showMasterPassword() => isBackupPasswordVisible = true;

View file

@ -61,6 +61,11 @@ dependencies:
permission_handler: ^10.0.0 permission_handler: ^10.0.0
device_display_brightness: ^0.0.6 device_display_brightness: ^0.0.6
platform_device_id: ^1.0.1 platform_device_id: ^1.0.1
cake_backup:
git:
url: https://github.com/cake-tech/cake_backup.git
ref: main
version: 1.0.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: