configuration.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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/event_bus.dart';
  7. import 'package:ente_auth/events/signed_in_event.dart';
  8. import 'package:ente_auth/events/signed_out_event.dart';
  9. import 'package:ente_auth/models/key_attributes.dart';
  10. import 'package:ente_auth/models/key_gen_result.dart';
  11. import 'package:ente_auth/models/private_key_attributes.dart';
  12. import 'package:ente_auth/store/authenticator_db.dart';
  13. import 'package:ente_auth/utils/crypto_util.dart';
  14. import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  15. import 'package:flutter_sodium/flutter_sodium.dart';
  16. import 'package:logging/logging.dart';
  17. import 'package:path_provider/path_provider.dart';
  18. import 'package:shared_preferences/shared_preferences.dart';
  19. import 'package:tuple/tuple.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. final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
  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, loginKey);
  161. }
  162. Future<Tuple2<KeyAttributes, Uint8List>> getAttributesForNewPassword(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. final loginKey = await CryptoUtil.deriveLoginKey(derivedKeyResult.key);
  173. // Encrypt the key with this derived key
  174. final encryptedKeyData =
  175. CryptoUtil.encryptSync(masterKey!, derivedKeyResult.key);
  176. final existingAttributes = getKeyAttributes();
  177. final updatedAttributes = existingAttributes!.copyWith(
  178. kekSalt: Sodium.bin2base64(kekSalt),
  179. encryptedKey: Sodium.bin2base64(encryptedKeyData.encryptedData!),
  180. keyDecryptionNonce: Sodium.bin2base64(encryptedKeyData.nonce!),
  181. memLimit: derivedKeyResult.memLimit,
  182. opsLimit: derivedKeyResult.opsLimit,
  183. );
  184. return Tuple2(updatedAttributes, loginKey);
  185. }
  186. // decryptSecretsAndGetLoginKey decrypts the master key and recovery key
  187. // with the given password and save them in local secure storage.
  188. // This method also returns the keyEncKey that can be used for performing
  189. // SRP setup for existing users.
  190. Future<Uint8List> decryptSecretsAndGetKeyEncKey(
  191. String password,
  192. KeyAttributes attributes,
  193. {
  194. Uint8List? keyEncryptionKey,
  195. }
  196. ) async {
  197. _logger.info('Start decryptAndSaveSecrets');
  198. keyEncryptionKey ??= await CryptoUtil.deriveKey(
  199. utf8.encode(password) as Uint8List,
  200. Sodium.base642bin(attributes.kekSalt),
  201. attributes.memLimit,
  202. attributes.opsLimit,
  203. );
  204. _logger.info('user-key done');
  205. Uint8List key;
  206. try {
  207. key = CryptoUtil.decryptSync(
  208. Sodium.base642bin(attributes.encryptedKey),
  209. keyEncryptionKey,
  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. return keyEncryptionKey;
  235. }
  236. Future<void> recover(String recoveryKey) async {
  237. // check if user has entered mnemonic code
  238. if (recoveryKey.contains(' ')) {
  239. if (recoveryKey.split(' ').length != mnemonicKeyWordCount) {
  240. throw AssertionError(
  241. 'recovery code should have $mnemonicKeyWordCount words',
  242. );
  243. }
  244. recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
  245. }
  246. final attributes = getKeyAttributes();
  247. Uint8List masterKey;
  248. try {
  249. masterKey = await CryptoUtil.decrypt(
  250. Sodium.base642bin(attributes!.masterKeyEncryptedWithRecoveryKey),
  251. Sodium.hex2bin(recoveryKey),
  252. Sodium.base642bin(attributes.masterKeyDecryptionNonce),
  253. );
  254. } catch (e) {
  255. _logger.severe(e);
  256. rethrow;
  257. }
  258. await setKey(Sodium.bin2base64(masterKey));
  259. final secretKey = CryptoUtil.decryptSync(
  260. Sodium.base642bin(attributes.encryptedSecretKey),
  261. masterKey,
  262. Sodium.base642bin(attributes.secretKeyDecryptionNonce),
  263. );
  264. await setSecretKey(Sodium.bin2base64(secretKey));
  265. final token = CryptoUtil.openSealSync(
  266. Sodium.base642bin(getEncryptedToken()!),
  267. Sodium.base642bin(attributes.publicKey),
  268. secretKey,
  269. );
  270. await setToken(
  271. Sodium.bin2base64(token, variant: Sodium.base64VariantUrlsafe),
  272. );
  273. }
  274. String getHttpEndpoint() {
  275. return endpoint;
  276. }
  277. String? getToken() {
  278. _cachedToken ??= _preferences.getString(tokenKey);
  279. return _cachedToken;
  280. }
  281. bool isLoggedIn() {
  282. return getToken() != null;
  283. }
  284. Future<void> setToken(String token) async {
  285. _cachedToken = token;
  286. await _preferences.setString(tokenKey, token);
  287. Bus.instance.fire(SignedInEvent());
  288. }
  289. Future<void> setEncryptedToken(String encryptedToken) async {
  290. await _preferences.setString(encryptedTokenKey, encryptedToken);
  291. }
  292. String? getEncryptedToken() {
  293. return _preferences.getString(encryptedTokenKey);
  294. }
  295. String? getEmail() {
  296. return _preferences.getString(emailKey);
  297. }
  298. Future<void> setEmail(String email) async {
  299. await _preferences.setString(emailKey, email);
  300. }
  301. int? getUserID() {
  302. return _preferences.getInt(userIDKey);
  303. }
  304. Future<void> setUserID(int userID) async {
  305. await _preferences.setInt(userIDKey, userID);
  306. }
  307. Future<void> setKeyAttributes(KeyAttributes attributes) async {
  308. await _preferences.setString(keyAttributesKey, attributes.toJson());
  309. }
  310. KeyAttributes? getKeyAttributes() {
  311. final jsonValue = _preferences.getString(keyAttributesKey);
  312. if (jsonValue == null) {
  313. return null;
  314. } else {
  315. return KeyAttributes.fromJson(jsonValue);
  316. }
  317. }
  318. Future<void> setKey(String? key) async {
  319. _key = key;
  320. if (key == null) {
  321. await _secureStorage.delete(
  322. key: keyKey,
  323. iOptions: _secureStorageOptionsIOS,
  324. );
  325. } else {
  326. await _secureStorage.write(
  327. key: keyKey,
  328. value: key,
  329. iOptions: _secureStorageOptionsIOS,
  330. );
  331. }
  332. }
  333. Future<void> setSecretKey(String? secretKey) async {
  334. _secretKey = secretKey;
  335. if (secretKey == null) {
  336. await _secureStorage.delete(
  337. key: secretKeyKey,
  338. iOptions: _secureStorageOptionsIOS,
  339. );
  340. } else {
  341. await _secureStorage.write(
  342. key: secretKeyKey,
  343. value: secretKey,
  344. iOptions: _secureStorageOptionsIOS,
  345. );
  346. }
  347. }
  348. Future<void> setAuthSecretKey(String? authSecretKey) async {
  349. _authSecretKey = authSecretKey;
  350. if (authSecretKey == null) {
  351. await _secureStorage.delete(
  352. key: authSecretKeyKey,
  353. iOptions: _secureStorageOptionsIOS,
  354. );
  355. } else {
  356. await _secureStorage.write(
  357. key: authSecretKeyKey,
  358. value: authSecretKey,
  359. iOptions: _secureStorageOptionsIOS,
  360. );
  361. }
  362. }
  363. Uint8List? getKey() {
  364. return _key == null ? null : Sodium.base642bin(_key!);
  365. }
  366. Uint8List? getSecretKey() {
  367. return _secretKey == null ? null : Sodium.base642bin(_secretKey!);
  368. }
  369. Uint8List? getAuthSecretKey() {
  370. return _authSecretKey == null ? null : Sodium.base642bin(_authSecretKey!);
  371. }
  372. Uint8List getRecoveryKey() {
  373. final keyAttributes = getKeyAttributes()!;
  374. return CryptoUtil.decryptSync(
  375. Sodium.base642bin(keyAttributes.recoveryKeyEncryptedWithMasterKey),
  376. getKey()!,
  377. Sodium.base642bin(keyAttributes.recoveryKeyDecryptionNonce),
  378. );
  379. }
  380. // Caution: This directory is cleared on app start
  381. String getTempDirectory() {
  382. return _tempDirectory;
  383. }
  384. String getThumbnailCacheDirectory() {
  385. return _thumbnailCacheDirectory;
  386. }
  387. String getOldSharedMediaCacheDirectory() {
  388. return _sharedTempMediaDirectory;
  389. }
  390. String getSharedMediaDirectory() {
  391. return _sharedDocumentsMediaDirectory;
  392. }
  393. bool hasConfiguredAccount() {
  394. return getToken() != null && _key != null;
  395. }
  396. bool shouldShowLockScreen() {
  397. if (_preferences.containsKey(keyShouldShowLockScreen)) {
  398. return _preferences.getBool(keyShouldShowLockScreen)!;
  399. } else {
  400. return false;
  401. }
  402. }
  403. Future<void> setShouldShowLockScreen(bool value) {
  404. return _preferences.setBool(keyShouldShowLockScreen, value);
  405. }
  406. void setVolatilePassword(String? volatilePassword) {
  407. _volatilePassword = volatilePassword;
  408. }
  409. String? getVolatilePassword() {
  410. return _volatilePassword;
  411. }
  412. Future<void> _migrateSecurityStorageToFirstUnlock() async {
  413. final hasMigratedSecureStorageToFirstUnlock =
  414. _preferences.getBool(hasMigratedSecureStorageKey) ?? false;
  415. if (!hasMigratedSecureStorageToFirstUnlock &&
  416. _key != null &&
  417. _secretKey != null) {
  418. await _secureStorage.write(
  419. key: keyKey,
  420. value: _key,
  421. iOptions: _secureStorageOptionsIOS,
  422. );
  423. await _secureStorage.write(
  424. key: secretKeyKey,
  425. value: _secretKey,
  426. iOptions: _secureStorageOptionsIOS,
  427. );
  428. await _preferences.setBool(
  429. hasMigratedSecureStorageKey,
  430. true,
  431. );
  432. }
  433. }
  434. }