configuration.dart 15 KB

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