configuration.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import 'dart:convert';
  2. import 'dart:io' as io;
  3. import 'dart:typed_data';
  4. import 'package:bip39/bip39.dart' as bip39;
  5. import 'package:ente_auth/core/constants.dart';
  6. import 'package:ente_auth/core/errors.dart';
  7. import 'package:ente_auth/core/event_bus.dart';
  8. // ignore: import_of_legacy_library_into_null_safe
  9. import 'package:ente_auth/events/signed_in_event.dart';
  10. import 'package:ente_auth/events/signed_out_event.dart';
  11. import 'package:ente_auth/models/key_attributes.dart';
  12. import 'package:ente_auth/models/key_gen_result.dart';
  13. import 'package:ente_auth/models/private_key_attributes.dart';
  14. import 'package:ente_auth/store/authenticator_db.dart';
  15. import 'package:ente_auth/utils/crypto_util.dart';
  16. import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  17. import 'package:flutter_sodium/flutter_sodium.dart';
  18. import 'package:logging/logging.dart';
  19. import 'package:path_provider/path_provider.dart';
  20. import 'package:shared_preferences/shared_preferences.dart';
  21. class Configuration {
  22. Configuration._privateConstructor();
  23. static final Configuration instance = Configuration._privateConstructor();
  24. static const endpoint = String.fromEnvironment(
  25. "endpoint",
  26. defaultValue: kDefaultProductionEndpoint,
  27. );
  28. static const emailKey = "email";
  29. static const keyAttributesKey = "key_attributes";
  30. static const keyKey = "key";
  31. static const keyShouldShowLockScreen = "should_show_lock_screen";
  32. static const lastTempFolderClearTimeKey = "last_temp_folder_clear_time";
  33. static const secretKeyKey = "secret_key";
  34. static const authSecretKeyKey = "auth_secret_key";
  35. static const tokenKey = "token";
  36. static const encryptedTokenKey = "encrypted_token";
  37. static const userIDKey = "user_id";
  38. static const hasMigratedSecureStorageToFirstUnlockKey =
  39. "has_migrated_secure_storage_to_first_unlock";
  40. final kTempFolderDeletionTimeBuffer = const Duration(days: 1).inMicroseconds;
  41. static final _logger = Logger("Configuration");
  42. String? _cachedToken;
  43. late String _documentsDirectory;
  44. String? _key;
  45. late SharedPreferences _preferences;
  46. String? _secretKey;
  47. String? _authSecretKey;
  48. late FlutterSecureStorage _secureStorage;
  49. late String _tempDirectory;
  50. late String _thumbnailCacheDirectory;
  51. // 6th July 22: Remove this after 3 months. Hopefully, active users
  52. // will migrate to newer version of the app, where shared media is stored
  53. // on appSupport directory which OS won't clean up automatically
  54. late String _sharedTempMediaDirectory;
  55. late String _sharedDocumentsMediaDirectory;
  56. String? _volatilePassword;
  57. final _secureStorageOptionsIOS =
  58. const IOSOptions(accessibility: KeychainAccessibility.first_unlock);
  59. // const IOSOptions(accessibility: IOSAccessibility.first_unlock);
  60. Future<void> init() async {
  61. _preferences = await SharedPreferences.getInstance();
  62. _secureStorage = const FlutterSecureStorage();
  63. _documentsDirectory = (await getApplicationDocumentsDirectory()).path;
  64. _tempDirectory = _documentsDirectory + "/temp/";
  65. final tempDirectory = io.Directory(_tempDirectory);
  66. try {
  67. final currentTime = DateTime.now().microsecondsSinceEpoch;
  68. if (tempDirectory.existsSync() &&
  69. (_preferences.getInt(lastTempFolderClearTimeKey) ?? 0) <
  70. (currentTime - kTempFolderDeletionTimeBuffer)) {
  71. await tempDirectory.delete(recursive: true);
  72. await _preferences.setInt(lastTempFolderClearTimeKey, currentTime);
  73. _logger.info("Cleared temp folder");
  74. } else {
  75. _logger.info("Skipping temp folder clear");
  76. }
  77. } catch (e) {
  78. _logger.warning(e);
  79. }
  80. tempDirectory.createSync(recursive: true);
  81. final tempDirectoryPath = (await getTemporaryDirectory()).path;
  82. _thumbnailCacheDirectory = tempDirectoryPath + "/thumbnail-cache";
  83. io.Directory(_thumbnailCacheDirectory).createSync(recursive: true);
  84. _sharedTempMediaDirectory = tempDirectoryPath + "/ente-shared-media";
  85. io.Directory(_sharedTempMediaDirectory).createSync(recursive: true);
  86. _sharedDocumentsMediaDirectory = _documentsDirectory + "/ente-shared-media";
  87. io.Directory(_sharedDocumentsMediaDirectory).createSync(recursive: true);
  88. if (!_preferences.containsKey(tokenKey)) {
  89. await _secureStorage.deleteAll(iOptions: _secureStorageOptionsIOS);
  90. } else {
  91. _key = await _secureStorage.read(
  92. key: keyKey,
  93. iOptions: _secureStorageOptionsIOS,
  94. );
  95. _secretKey = await _secureStorage.read(
  96. key: secretKeyKey,
  97. iOptions: _secureStorageOptionsIOS,
  98. );
  99. _authSecretKey = await _secureStorage.read(
  100. key: authSecretKeyKey,
  101. iOptions: _secureStorageOptionsIOS,
  102. );
  103. if (_key == null) {
  104. await logout(autoLogout: true);
  105. }
  106. await _migrateSecurityStorageToFirstUnlock();
  107. }
  108. }
  109. Future<void> logout({bool autoLogout = false}) async {
  110. await _preferences.clear();
  111. await _secureStorage.deleteAll(iOptions: _secureStorageOptionsIOS);
  112. await AuthenticatorDB.instance.clearTable();
  113. _key = null;
  114. _cachedToken = null;
  115. _secretKey = null;
  116. _authSecretKey = null;
  117. Bus.instance.fire(SignedOutEvent());
  118. }
  119. Future<KeyGenResult> generateKey(String password) async {
  120. // Create a master key
  121. final masterKey = CryptoUtil.generateKey();
  122. // Create a recovery key
  123. final recoveryKey = CryptoUtil.generateKey();
  124. // Encrypt master key and recovery key with each other
  125. final encryptedMasterKey = CryptoUtil.encryptSync(masterKey, recoveryKey);
  126. final encryptedRecoveryKey = CryptoUtil.encryptSync(recoveryKey, masterKey);
  127. // Derive a key from the password that will be used to encrypt and
  128. // decrypt the master key
  129. final kekSalt = CryptoUtil.getSaltToDeriveKey();
  130. final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
  131. utf8.encode(password) as Uint8List,
  132. kekSalt,
  133. );
  134. // Encrypt the key with this derived key
  135. final encryptedKeyData =
  136. CryptoUtil.encryptSync(masterKey, derivedKeyResult.key);
  137. // Generate a public-private keypair and encrypt the latter
  138. final keyPair = await CryptoUtil.generateKeyPair();
  139. final encryptedSecretKeyData =
  140. CryptoUtil.encryptSync(keyPair.sk, masterKey);
  141. final attributes = KeyAttributes(
  142. Sodium.bin2base64(kekSalt),
  143. Sodium.bin2base64(encryptedKeyData.encryptedData!),
  144. Sodium.bin2base64(encryptedKeyData.nonce!),
  145. Sodium.bin2base64(keyPair.pk),
  146. Sodium.bin2base64(encryptedSecretKeyData.encryptedData!),
  147. Sodium.bin2base64(encryptedSecretKeyData.nonce!),
  148. derivedKeyResult.memLimit,
  149. derivedKeyResult.opsLimit,
  150. Sodium.bin2base64(encryptedMasterKey.encryptedData!),
  151. Sodium.bin2base64(encryptedMasterKey.nonce!),
  152. Sodium.bin2base64(encryptedRecoveryKey.encryptedData!),
  153. Sodium.bin2base64(encryptedRecoveryKey.nonce!),
  154. );
  155. final privateAttributes = PrivateKeyAttributes(
  156. Sodium.bin2base64(masterKey),
  157. Sodium.bin2hex(recoveryKey),
  158. Sodium.bin2base64(keyPair.sk),
  159. );
  160. return KeyGenResult(attributes, privateAttributes);
  161. }
  162. Future<KeyAttributes> updatePassword(String password) async {
  163. // Get master key
  164. final masterKey = getKey();
  165. // Derive a key from the password that will be used to encrypt and
  166. // decrypt the master key
  167. final kekSalt = CryptoUtil.getSaltToDeriveKey();
  168. final derivedKeyResult = await CryptoUtil.deriveSensitiveKey(
  169. utf8.encode(password) as Uint8List,
  170. kekSalt,
  171. );
  172. // Encrypt the key with this derived key
  173. final encryptedKeyData =
  174. CryptoUtil.encryptSync(masterKey!, derivedKeyResult.key);
  175. final existingAttributes = getKeyAttributes();
  176. return existingAttributes!.copyWith(
  177. kekSalt: Sodium.bin2base64(kekSalt),
  178. encryptedKey: Sodium.bin2base64(encryptedKeyData.encryptedData!),
  179. keyDecryptionNonce: Sodium.bin2base64(encryptedKeyData.nonce!),
  180. memLimit: derivedKeyResult.memLimit,
  181. opsLimit: derivedKeyResult.opsLimit,
  182. );
  183. }
  184. Future<void> decryptAndSaveSecrets(
  185. String password,
  186. KeyAttributes attributes,
  187. ) async {
  188. _logger.info('Start decryptAndSaveSecrets');
  189. // validatePreVerificationStateCheck(
  190. // attributes,
  191. // password,
  192. // getEncryptedToken(),
  193. // );
  194. _logger.info('state validation done');
  195. final kek = await CryptoUtil.deriveKey(
  196. utf8.encode(password) as Uint8List,
  197. Sodium.base642bin(attributes.kekSalt),
  198. attributes.memLimit,
  199. attributes.opsLimit,
  200. ).onError((e, s) {
  201. _logger.severe('deriveKey failed', e, s);
  202. throw KeyDerivationError();
  203. });
  204. _logger.info('user-key done');
  205. Uint8List key;
  206. try {
  207. key = CryptoUtil.decryptSync(
  208. Sodium.base642bin(attributes.encryptedKey),
  209. kek,
  210. Sodium.base642bin(attributes.keyDecryptionNonce),
  211. );
  212. } catch (e) {
  213. _logger.severe('master-key failed, incorrect password?', e);
  214. throw Exception("Incorrect password");
  215. }
  216. _logger.info("master-key done");
  217. await setKey(Sodium.bin2base64(key));
  218. final secretKey = CryptoUtil.decryptSync(
  219. Sodium.base642bin(attributes.encryptedSecretKey),
  220. key,
  221. Sodium.base642bin(attributes.secretKeyDecryptionNonce),
  222. );
  223. _logger.info("secret-key done");
  224. await setSecretKey(Sodium.bin2base64(secretKey));
  225. final token = CryptoUtil.openSealSync(
  226. Sodium.base642bin(getEncryptedToken()!),
  227. Sodium.base642bin(attributes.publicKey),
  228. secretKey,
  229. );
  230. _logger.info('appToken done');
  231. await setToken(
  232. Sodium.bin2base64(token, variant: Sodium.base64VariantUrlsafe),
  233. );
  234. }
  235. Future<void> recover(String recoveryKey) async {
  236. // check if user has entered mnemonic code
  237. if (recoveryKey.contains(' ')) {
  238. if (recoveryKey.split(' ').length != mnemonicKeyWordCount) {
  239. throw AssertionError(
  240. 'recovery code should have $mnemonicKeyWordCount words',
  241. );
  242. }
  243. recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
  244. }
  245. final attributes = getKeyAttributes();
  246. Uint8List masterKey;
  247. try {
  248. masterKey = await CryptoUtil.decrypt(
  249. Sodium.base642bin(attributes!.masterKeyEncryptedWithRecoveryKey),
  250. Sodium.hex2bin(recoveryKey),
  251. Sodium.base642bin(attributes.masterKeyDecryptionNonce),
  252. );
  253. } catch (e) {
  254. _logger.severe(e);
  255. rethrow;
  256. }
  257. await setKey(Sodium.bin2base64(masterKey));
  258. final secretKey = CryptoUtil.decryptSync(
  259. Sodium.base642bin(attributes.encryptedSecretKey),
  260. masterKey,
  261. Sodium.base642bin(attributes.secretKeyDecryptionNonce),
  262. );
  263. await setSecretKey(Sodium.bin2base64(secretKey));
  264. final token = CryptoUtil.openSealSync(
  265. Sodium.base642bin(getEncryptedToken()!),
  266. Sodium.base642bin(attributes.publicKey),
  267. secretKey,
  268. );
  269. await setToken(
  270. Sodium.bin2base64(token, variant: Sodium.base64VariantUrlsafe),
  271. );
  272. }
  273. String getHttpEndpoint() {
  274. return endpoint;
  275. }
  276. String? getToken() {
  277. _cachedToken ??= _preferences.getString(tokenKey);
  278. return _cachedToken;
  279. }
  280. Future<void> setToken(String token) async {
  281. _cachedToken = token;
  282. await _preferences.setString(tokenKey, token);
  283. Bus.instance.fire(SignedInEvent());
  284. }
  285. Future<void> setEncryptedToken(String encryptedToken) async {
  286. await _preferences.setString(encryptedTokenKey, encryptedToken);
  287. }
  288. String? getEncryptedToken() {
  289. return _preferences.getString(encryptedTokenKey);
  290. }
  291. String? getEmail() {
  292. return _preferences.getString(emailKey);
  293. }
  294. Future<void> setEmail(String email) async {
  295. await _preferences.setString(emailKey, email);
  296. }
  297. int? getUserID() {
  298. return _preferences.getInt(userIDKey);
  299. }
  300. Future<void> setUserID(int userID) async {
  301. await _preferences.setInt(userIDKey, userID);
  302. }
  303. Future<void> setKeyAttributes(KeyAttributes attributes) async {
  304. await _preferences.setString(keyAttributesKey, attributes.toJson());
  305. }
  306. KeyAttributes? getKeyAttributes() {
  307. final jsonValue = _preferences.getString(keyAttributesKey);
  308. if (jsonValue == null) {
  309. return null;
  310. } else {
  311. return KeyAttributes.fromJson(jsonValue);
  312. }
  313. }
  314. Future<void> setKey(String? key) async {
  315. _key = key;
  316. if (key == null) {
  317. await _secureStorage.delete(
  318. key: keyKey,
  319. iOptions: _secureStorageOptionsIOS,
  320. );
  321. } else {
  322. await _secureStorage.write(
  323. key: keyKey,
  324. value: key,
  325. iOptions: _secureStorageOptionsIOS,
  326. );
  327. }
  328. }
  329. Future<void> setSecretKey(String? secretKey) async {
  330. _secretKey = secretKey;
  331. if (secretKey == null) {
  332. await _secureStorage.delete(
  333. key: secretKeyKey,
  334. iOptions: _secureStorageOptionsIOS,
  335. );
  336. } else {
  337. await _secureStorage.write(
  338. key: secretKeyKey,
  339. value: secretKey,
  340. iOptions: _secureStorageOptionsIOS,
  341. );
  342. }
  343. }
  344. Future<void> setAuthSecretKey(String? authSecretKey) async {
  345. _authSecretKey = authSecretKey;
  346. if (authSecretKey == null) {
  347. await _secureStorage.delete(
  348. key: authSecretKeyKey,
  349. iOptions: _secureStorageOptionsIOS,
  350. );
  351. } else {
  352. await _secureStorage.write(
  353. key: authSecretKeyKey,
  354. value: authSecretKey,
  355. iOptions: _secureStorageOptionsIOS,
  356. );
  357. }
  358. }
  359. Uint8List? getKey() {
  360. return _key == null ? null : Sodium.base642bin(_key!);
  361. }
  362. Uint8List? getSecretKey() {
  363. return _secretKey == null ? null : Sodium.base642bin(_secretKey!);
  364. }
  365. Uint8List? getAuthSecretKey() {
  366. return _authSecretKey == null ? null : Sodium.base642bin(_authSecretKey!);
  367. }
  368. Uint8List getRecoveryKey() {
  369. final keyAttributes = getKeyAttributes()!;
  370. return CryptoUtil.decryptSync(
  371. Sodium.base642bin(keyAttributes.recoveryKeyEncryptedWithMasterKey),
  372. getKey(),
  373. Sodium.base642bin(keyAttributes.recoveryKeyDecryptionNonce),
  374. );
  375. }
  376. // Caution: This directory is cleared on app start
  377. String getTempDirectory() {
  378. return _tempDirectory;
  379. }
  380. String getThumbnailCacheDirectory() {
  381. return _thumbnailCacheDirectory;
  382. }
  383. String getOldSharedMediaCacheDirectory() {
  384. return _sharedTempMediaDirectory;
  385. }
  386. String getSharedMediaDirectory() {
  387. return _sharedDocumentsMediaDirectory;
  388. }
  389. bool hasConfiguredAccount() {
  390. return getToken() != null && _key != null;
  391. }
  392. bool shouldShowLockScreen() {
  393. if (_preferences.containsKey(keyShouldShowLockScreen)) {
  394. return _preferences.getBool(keyShouldShowLockScreen)!;
  395. } else {
  396. return false;
  397. }
  398. }
  399. Future<void> setShouldShowLockScreen(bool value) {
  400. return _preferences.setBool(keyShouldShowLockScreen, value);
  401. }
  402. void setVolatilePassword(String volatilePassword) {
  403. _volatilePassword = volatilePassword;
  404. }
  405. String? getVolatilePassword() {
  406. return _volatilePassword;
  407. }
  408. Future<void> _migrateSecurityStorageToFirstUnlock() async {
  409. final hasMigratedSecureStorageToFirstUnlock =
  410. _preferences.getBool(hasMigratedSecureStorageToFirstUnlockKey) ?? false;
  411. if (!hasMigratedSecureStorageToFirstUnlock &&
  412. _key != null &&
  413. _secretKey != null) {
  414. await _secureStorage.write(
  415. key: keyKey,
  416. value: _key,
  417. iOptions: _secureStorageOptionsIOS,
  418. );
  419. await _secureStorage.write(
  420. key: secretKeyKey,
  421. value: _secretKey,
  422. iOptions: _secureStorageOptionsIOS,
  423. );
  424. await _preferences.setBool(
  425. hasMigratedSecureStorageToFirstUnlockKey,
  426. true,
  427. );
  428. }
  429. }
  430. }