Skip to content

armgit / ente

Public Imported from GitHub
0

๐Ÿ’š End-to-end encrypted cloud for everything.

[mobile] Add Open Authenticator import (#13191)

neeraj-pilotc33d8637bf57
diff --git a/mobile/apps/auth/changes/open-authenticator-import.md b/mobile/apps/auth/changes/open-authenticator-import.md
new file mode 100644
index 0000000000..0ccb4fa535
--- /dev/null
+++ b/mobile/apps/auth/changes/open-authenticator-import.md
@@ -0,0 +1 @@
+- Added support for importing Open Authenticator backups (@NKjoep).
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart b/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart
index a737e5ff95..3d9e0895d6 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart
@@ -4,6 +4,7 @@ import 'package:ente_auth/ui/settings/data/import/bitwarden_import.dart';
import 'package:ente_auth/ui/settings/data/import/encrypted_ente_import.dart';
import 'package:ente_auth/ui/settings/data/import/google_auth_import.dart';
import 'package:ente_auth/ui/settings/data/import/lastpass_import.dart';
+import 'package:ente_auth/ui/settings/data/import/openauthenticator_import.dart';
import 'package:ente_auth/ui/settings/data/import/otp_auth_import.dart';
import 'package:ente_auth/ui/settings/data/import/plain_text_import.dart';
import 'package:ente_auth/ui/settings/data/import/proton_import.dart';
@@ -50,6 +51,9 @@ class ImportService {
case ImportType.andOTP:
await showAndOTPImportInstruction(context);
return false;
+ case ImportType.openAuthenticator:
+ await showOpenAuthenticatorImportInstruction(context);
+ return false;
case ImportType.otpAuth:
await showOtpAuthImportInstruction(context);
return false;
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/openauthenticator_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/openauthenticator_import.dart
new file mode 100644
index 0000000000..5cbfc7c486
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/data/import/openauthenticator_import.dart
@@ -0,0 +1,71 @@
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
+import 'package:ente_auth/ui/settings/data/import/openauthenticator_import_parser.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_strings/ente_strings.dart';
+import 'package:ente_ui/components/progress_dialog.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:logging/logging.dart';
+
+Future<void> showOpenAuthenticatorImportInstruction(
+ BuildContext context,
+) async {
+ final l10n = context.strings;
+ await showFileImportInstruction(
+ context: context,
+ title: 'Open Authenticator',
+ body: l10n.importOpenAuthenticatorGuide,
+ actionLabel: l10n.selectFile,
+ semanticsIdentifier: 'auth_import_instruction_open_authenticator',
+ onImport: () => _pickBackupFile(context),
+ );
+}
+
+Future<void> _pickBackupFile(BuildContext context) async {
+ await pickAndProcessImportFile(
+ context: context,
+ dialogTitle: context.strings.selectFile,
+ showProgressBeforeProcessing: false,
+ logger: Logger('OpenAuthenticatorImport'),
+ logMessage: 'Exception while processing Open Authenticator import',
+ process: (path, progressDialog) =>
+ _processBackup(context, path, progressDialog),
+ );
+}
+
+Future<int?> _processBackup(
+ BuildContext context,
+ String path,
+ ProgressDialog dialog,
+) async {
+ final backup = decodeOpenAuthenticatorBackup(
+ await readPickedImportFileAsString(path),
+ );
+ while (true) {
+ if (!context.mounted) return null;
+ final password = await promptForImportPassword(
+ context,
+ title: context.strings.passwordForDecryptingExport,
+ );
+ if (password == null) return null;
+
+ await dialog.show();
+ try {
+ final codes = await compute(_decryptBackup, (backup, password));
+ return await saveImportedCodes(codes);
+ } on IncorrectOpenAuthenticatorPasswordException {
+ await dialog.hide();
+ if (!context.mounted) return null;
+ await showErrorDialog(
+ context,
+ context.strings.incorrectPasswordTitle,
+ context.strings.pleaseCheckPasswordAndTryAgain,
+ );
+ }
+ }
+}
+
+List<Code> _decryptBackup((Map<String, dynamic>, String) params) =>
+ decryptOpenAuthenticatorBackup(params.$1, password: params.$2);
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/openauthenticator_import_parser.dart b/mobile/apps/auth/lib/ui/settings/data/import/openauthenticator_import_parser.dart
new file mode 100644
index 0000000000..33ef3a31bf
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/data/import/openauthenticator_import_parser.dart
@@ -0,0 +1,126 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
+import 'package:pointycastle/export.dart';
+
+class IncorrectOpenAuthenticatorPasswordException implements Exception {
+ const IncorrectOpenAuthenticatorPasswordException();
+}
+
+Map<String, dynamic> decodeOpenAuthenticatorBackup(String jsonString) {
+ final backup = jsonDecode(jsonString);
+ if (backup is! Map<String, dynamic> ||
+ backup['salt'] is! String ||
+ backup['passwordSignature'] is! String ||
+ backup['totps'] is! List) {
+ throw const FormatException('Invalid Open Authenticator backup');
+ }
+ if (base64Decode(backup['salt'] as String).length != 32 ||
+ base64Decode(backup['passwordSignature'] as String).length != 32) {
+ throw const FormatException('Invalid Open Authenticator salt or signature');
+ }
+ return backup;
+}
+
+List<Code> decryptOpenAuthenticatorBackup(
+ Map<String, dynamic> backup, {
+ required String password,
+}) {
+ final salt = base64Decode(backup['salt'] as String);
+ final key = _deriveKey(password, salt);
+ final mac = HMac(SHA256Digest(), 64)..init(KeyParameter(key));
+ final signature = mac.process(Uint8List.fromList(utf8.encode(password)));
+ if (base64Encode(signature) != backup['passwordSignature']) {
+ throw const IncorrectOpenAuthenticatorPasswordException();
+ }
+
+ final codes = <Code>[];
+ for (final entry in backup['totps'] as List) {
+ try {
+ codes.add(_decryptEntry(entry as Map<String, dynamic>, key));
+ } catch (error) {
+ throwImportEntryParseError(entry, error);
+ }
+ }
+ return codes;
+}
+
+Code _decryptEntry(Map<String, dynamic> entry, Uint8List key) {
+ final secret = _decryptField(key, _bytes(entry['secret']));
+ final label = entry.containsKey('label')
+ ? _decryptField(key, _bytes(entry['label']))
+ : '';
+ final issuer = entry.containsKey('issuer')
+ ? _decryptField(key, _bytes(entry['issuer']))
+ : '';
+ final account = label.isNotEmpty ? label : (entry['uuid'] as String? ?? '');
+ final digits = entry.containsKey('digits')
+ ? entry['digits']
+ : Code.defaultDigits;
+ if (digits is! int || digits < 1 || digits > 10) {
+ throw FormatException('Invalid OTP digits: $digits');
+ }
+ final algorithm = switch (entry['algorithm']) {
+ final String value => value.toLowerCase(),
+ _ => '',
+ };
+
+ return Code.fromOTPAuthUrl(
+ buildImportOtpUri(
+ kind: 'totp',
+ issuer: Uri.encodeComponent(issuer),
+ account: Uri.encodeComponent(account),
+ secret: Uri.encodeComponent(secret),
+ algorithm: const ['sha1', 'sha256', 'sha512'].contains(algorithm)
+ ? algorithm
+ : 'sha1',
+ digits: digits,
+ period: entry['validity'] is int ? entry['validity'] : null,
+ ),
+ );
+}
+
+Uint8List _deriveKey(String password, Uint8List salt) {
+ final generator = Argon2BytesGenerator()
+ ..init(
+ Argon2Parameters(
+ Argon2Parameters.ARGON2_id,
+ salt,
+ desiredKeyLength: 32,
+ iterations: 3,
+ memory: 4096,
+ lanes: 8,
+ version: Argon2Parameters.ARGON2_VERSION_13,
+ ),
+ );
+ return generator.process(Uint8List.fromList(utf8.encode(password)));
+}
+
+String _decryptField(Uint8List key, Uint8List data) {
+ const nonceLength = 12;
+ const tagLength = 16;
+ if (data.length < nonceLength + tagLength) {
+ throw const FormatException('Truncated encrypted field');
+ }
+ final cipher = GCMBlockCipher(AESEngine())
+ ..init(
+ false,
+ AEADParameters(
+ KeyParameter(key),
+ tagLength * 8,
+ data.sublist(0, nonceLength),
+ Uint8List(0),
+ ),
+ );
+ return utf8.decode(cipher.process(data.sublist(nonceLength)));
+}
+
+Uint8List _bytes(Object? value) {
+ if (value is! List ||
+ value.any((byte) => byte is! int || byte < 0 || byte > 255)) {
+ throw const FormatException('Invalid byte array');
+ }
+ return Uint8List.fromList(value.cast<int>());
+}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import_page.dart b/mobile/apps/auth/lib/ui/settings/data/import_page.dart
index 6197bc15d4..be9d8da8f7 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import_page.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import_page.dart
@@ -15,6 +15,7 @@ enum ImportType {
lastpass,
proton,
andOTP,
+ openAuthenticator,
otpAuth,
}
@@ -27,6 +28,7 @@ class ImportCodePage extends StatelessWidget {
ImportType.twoFas,
ImportType.aegis,
ImportType.andOTP,
+ ImportType.openAuthenticator,
ImportType.bitwarden,
ImportType.googleAuthenticator,
ImportType.proton,
@@ -57,6 +59,8 @@ class ImportCodePage extends StatelessWidget {
return 'Proton Authenticator';
case ImportType.andOTP:
return 'andOTP';
+ case ImportType.openAuthenticator:
+ return 'Open Authenticator';
case ImportType.otpAuth:
return 'OTP Auth';
}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/dummy-open-authenticator.bak b/mobile/apps/auth/test/ui/settings/data/import/fixtures/dummy-open-authenticator.bak
new file mode 100644
index 0000000000..b7df796bfa
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/dummy-open-authenticator.bak
@@ -0,0 +1,36 @@
+{
+ "passwordSignature": "RHf/O9QusiWOCElhxoH8YTGM2kcr26Zc98BAP3PYYA4=",
+ "salt": "Ho1Gh9NGy0FTLLYKuk1m7eNycxT6RRIYVUbTOHGqxw8=",
+ "totps": [
+ {
+ "uuid": "0b6e48d3-4d8e-4012-83df-c075d52728bd",
+ "secret": [44, 157, 161, 31, 5, 242, 128, 189, 163, 194, 3, 127, 216, 248, 108, 1, 20, 173, 74, 193, 206, 45, 53, 214, 120, 1, 228, 127, 180, 231, 112, 7, 160, 168, 104, 121, 241, 131, 4, 113, 180, 5, 57, 46],
+ "label": [60, 102, 205, 230, 72, 45, 106, 53, 149, 114, 159, 28, 43, 154, 55, 72, 6, 47, 195, 46, 239, 3, 121, 101, 57, 64, 209, 185, 71, 233, 172, 78, 195, 183, 186, 149, 105, 66, 75, 238, 130, 83, 254, 144, 79, 78, 121],
+ "issuer": [169, 129, 161, 173, 134, 234, 50, 93, 250, 134, 166, 85, 16, 85, 45, 179, 109, 195, 96, 84, 214, 67, 72, 138, 195, 235, 57, 3, 127, 84, 220, 14, 86, 228, 27],
+ "encryptionSalt": [30, 141, 70, 135, 211, 70, 203, 65, 83, 44, 182, 10, 186, 77, 102, 237, 227, 114, 115, 20, 250, 69, 18, 24, 85, 70, 211, 56, 113, 170, 199, 15],
+ "algorithm": "SHA512",
+ "digits": 8,
+ "validity": 30,
+ "updatedAt": 1790598100041
+ },
+ {
+ "uuid": "8f21e39d-4038-46f1-a3fc-2f38c5ae52d1",
+ "secret": [175, 205, 236, 76, 74, 25, 149, 80, 252, 206, 111, 233, 196, 7, 1, 94, 196, 207, 178, 204, 152, 15, 160, 84, 36, 110, 109, 6, 156, 73, 203, 124, 175, 172, 222, 1, 143, 75, 105, 150, 130, 51, 80, 250],
+ "label": [64, 235, 248, 98, 241, 146, 198, 191, 52, 131, 250, 144, 222, 161, 72, 166, 179, 192, 206, 5, 169, 126, 242, 58, 223, 83, 173, 160, 187, 160, 139, 48, 242, 62, 38, 224, 64, 195, 161, 212, 254, 110, 72, 103],
+ "issuer": [161, 70, 221, 130, 13, 187, 196, 233, 68, 240, 203, 64, 65, 83, 134, 187, 113, 142, 235, 146, 244, 76, 204, 45, 26, 107, 242, 88, 3, 91, 97, 18, 146, 94, 6],
+ "encryptionSalt": [30, 141, 70, 135, 211, 70, 203, 65, 83, 44, 182, 10, 186, 77, 102, 237, 227, 114, 115, 20, 250, 69, 18, 24, 85, 70, 211, 56, 113, 170, 199, 15],
+ "updatedAt": 1790598100041
+ },
+ {
+ "uuid": "5630aee7-d9d3-4285-878b-46aa06837b57",
+ "secret": [242, 20, 26, 243, 51, 247, 7, 76, 104, 81, 58, 60, 26, 205, 216, 87, 1, 15, 75, 141, 215, 61, 247, 72, 120, 157, 59, 141, 57, 6, 240, 209, 237, 178, 159, 237, 95, 29, 209, 57],
+ "label": [91, 19, 133, 16, 234, 241, 129, 248, 218, 232, 225, 255, 222, 214, 247, 155, 22, 51, 208, 14, 109, 243, 127, 69, 62, 92, 210, 38, 116, 253, 222, 103, 136, 119, 131],
+ "issuer": [80, 220, 54, 131, 18, 56, 138, 193, 19, 213, 197, 253, 109, 97, 167, 57, 234, 93, 43, 246, 31, 210, 167, 157, 190, 101, 26, 27, 130, 109, 68, 67, 205, 81],
+ "encryptionSalt": [30, 141, 70, 135, 211, 70, 203, 65, 83, 44, 182, 10, 186, 77, 102, 237, 227, 114, 115, 20, 250, 69, 18, 24, 85, 70, 211, 56, 113, 170, 199, 15],
+ "algorithm": "SHA256",
+ "digits": 8,
+ "validity": 60,
+ "updatedAt": 1790598100041
+ }
+ ]
+}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/openauthenticator_import_parser_test.dart b/mobile/apps/auth/test/ui/settings/data/import/openauthenticator_import_parser_test.dart
new file mode 100644
index 0000000000..ee8b387443
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/openauthenticator_import_parser_test.dart
@@ -0,0 +1,218 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
+import 'package:ente_auth/ui/settings/data/import/openauthenticator_import_parser.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:otp/otp.dart' as otp;
+
+void main() {
+ test('imports an Android 2.1.0 export in a background isolate', () async {
+ final codes = await compute(_decryptFixture, 'dummy');
+ expect(
+ codes.map(
+ (code) => (
+ code.issuer,
+ code.account,
+ code.secret,
+ code.algorithm,
+ code.digits,
+ code.period,
+ ),
+ ),
+ [
+ (
+ 'Example',
+ 'team:alice +@ไพ‹#/%',
+ 'MFRGGZDFMZTWQ2LK',
+ Algorithm.sha512,
+ 8,
+ 30,
+ ),
+ (
+ 'Example',
+ 'JBSWY3DPEHPK3PXP',
+ Algorithm.sha1,
+ 6,
+ 30,
+ ),
+ ('GitHub', 'octocat', 'KRSXG5DSM5UQ', Algorithm.sha256, 8, 60),
+ ],
+ );
+ expect(codes.every((code) => code.type == Type.totp), isTrue);
+ expect(codes.every((code) => !code.display.isCustomIcon), isTrue);
+ expect(
+ [
+ for (final code in codes)
+ for (final seconds in [59, 1111111109])
+ otp.OTP.generateTOTPCodeString(
+ code.secret,
+ seconds * 1000,
+ length: code.digits,
+ interval: code.period,
+ algorithm: otp.Algorithm.values.byName(
+ code.algorithm.name.toUpperCase(),
+ ),
+ isGoogle: true,
+ ),
+ ],
+ ['25413345', '70253442', '996554', '071271', '69151245', '66765760'],
+ );
+ });
+
+ test('preserves colons and URI characters in an issuer-less account', () {
+ final backup = _fixture();
+ final entry = (backup['totps'] as List).first as Map;
+ entry.remove('issuer');
+ final code = decryptOpenAuthenticatorBackup(
+ backup,
+ password: 'dummy',
+ ).first;
+ expect(code.account, 'team:alice +@ไพ‹#/%');
+ expect(code.issuer, isEmpty);
+ });
+
+ test('uses the UUID and defaults for omitted optional fields', () {
+ final backup = _fixture();
+ final entry = (backup['totps'] as List).first as Map;
+ for (final field in [
+ 'label',
+ 'issuer',
+ 'algorithm',
+ 'digits',
+ 'validity',
+ ]) {
+ entry.remove(field);
+ }
+ final code = decryptOpenAuthenticatorBackup(
+ backup,
+ password: 'dummy',
+ ).first;
+ expect(code.account, entry['uuid']);
+ expect(code.issuer, isEmpty);
+ expect(code.algorithm, Algorithm.sha1);
+ expect(code.digits, 6);
+ expect(code.period, 30);
+ });
+
+ test('rejects entries encrypted under another key', () {
+ final backup = _fixture();
+ final entry = (backup['totps'] as List).last as Map;
+ entry.remove('label');
+ entry.remove('issuer');
+ entry['encryptionSalt'] = List.filled(32, 34);
+ entry['secret'] = base64Decode(
+ '0bsWmTM88NTfjCM227siiMmmBf8fhsWO53EyxvN5fJ4CzgIfn60=',
+ );
+ expect(
+ () => decryptOpenAuthenticatorBackup(backup, password: 'dummy'),
+ throwsA(isA<ImportEntryParseException>()),
+ );
+ });
+
+ test('rejects invalid explicit digit counts', () {
+ for (final digits in [null, '6', 0, -1, 11]) {
+ final backup = _fixture();
+ ((backup['totps'] as List).first as Map)['digits'] = digits;
+ expect(
+ () => decryptOpenAuthenticatorBackup(backup, password: 'dummy'),
+ throwsA(isA<ImportEntryParseException>()),
+ reason: 'digits: $digits',
+ );
+ }
+ });
+
+ test(
+ 'reports corrupt encrypted fields with their entry across isolates',
+ () async {
+ for (final field in ['secret', 'label', 'issuer']) {
+ final backup = _fixture();
+ final entry = (backup['totps'] as List).first as Map;
+ final bytes = entry[field] as List;
+ bytes[0] = (bytes[0] as int) ^ 1;
+ await expectLater(
+ compute(_decryptBackup, backup),
+ throwsA(
+ isA<ImportEntryParseException>().having(
+ (error) => error.entry,
+ 'entry',
+ entry,
+ ),
+ ),
+ reason: field,
+ );
+ }
+ },
+ );
+
+ test('rejects malformed entries and byte arrays', () {
+ for (final entry in [
+ null,
+ <String, Object?>{},
+ for (final secret in [
+ null,
+ 'secret',
+ [],
+ [-1],
+ [256],
+ ['0'],
+ ])
+ {'secret': secret},
+ for (final field in ['label', 'issuer'])
+ <String, dynamic>{
+ ...((_fixture()['totps'] as List).first as Map<String, dynamic>),
+ field: null,
+ },
+ ]) {
+ final backup = _fixture()..['totps'] = [entry];
+ expect(
+ () => decryptOpenAuthenticatorBackup(backup, password: 'dummy'),
+ throwsA(isA<ImportEntryParseException>()),
+ );
+ }
+ });
+
+ test('reports an incorrect password across isolates', () async {
+ await expectLater(
+ compute(_decryptFixture, 'not-dummy'),
+ throwsA(isA<IncorrectOpenAuthenticatorPasswordException>()),
+ );
+ });
+
+ test('accepts an empty backup', () {
+ final backup = _fixture()..['totps'] = [];
+ expect(decryptOpenAuthenticatorBackup(backup, password: 'dummy'), isEmpty);
+ });
+
+ test('rejects malformed backups before password verification', () {
+ for (final content in [
+ 'not json',
+ '[]',
+ '{}',
+ jsonEncode(_fixture()..['totps'] = 'invalid'),
+ for (final field in ['salt', 'passwordSignature'])
+ for (final value in [null, 'not-base64', 'AA=='])
+ jsonEncode(_fixture()..[field] = value),
+ ]) {
+ expect(
+ () => decodeOpenAuthenticatorBackup(content),
+ throwsFormatException,
+ );
+ }
+ });
+}
+
+Map<String, dynamic> _fixture() => decodeOpenAuthenticatorBackup(
+ File(
+ 'test/ui/settings/data/import/fixtures/dummy-open-authenticator.bak',
+ ).readAsStringSync(),
+);
+
+List<Code> _decryptFixture(String password) =>
+ decryptOpenAuthenticatorBackup(_fixture(), password: password);
+
+List<Code> _decryptBackup(Map<String, dynamic> backup) =>
+ decryptOpenAuthenticatorBackup(backup, password: 'dummy');
diff --git a/mobile/packages/strings/lib/l10n/arb/strings_en.arb b/mobile/packages/strings/lib/l10n/arb/strings_en.arb
index 9cbfb6e6b2..88bfd52157 100644
--- a/mobile/packages/strings/lib/l10n/arb/strings_en.arb
+++ b/mobile/packages/strings/lib/l10n/arb/strings_en.arb
@@ -1993,6 +1993,7 @@
"importInstruction": "Please select a file that contains a list of your codes in the following format",
"importLabel": "Import",
"importLastpassGuide": "Use the \"Transfer accounts\" option within Lastpass Authenticator Settings and press \"Export accounts to file\". Import the JSON downloaded.",
+ "importOpenAuthenticatorGuide": "Use the options under \"Backups\" in Open Authenticator's Settings to create a backup, then share or export it.\n\nYou will need to enter the backup password you set when creating it.",
"importOtpAuthGuide": "Export an encrypted backup from OTP Auth, then select the .otpauthdb or .otpauthdp file. Single-account .otpauth exports are also supported.",
"importProtonAuthGuide": "Use the \"Export\" option in Proton Authenticator Settings to export your codes.\n\nIf your export is password protected, you will need to enter the password to decrypt it.",
"importRaivoGuide": "Use the \"Export OTPs to Zip archive\" option in Raivo's Settings.\n\nExtract the zip file and import the JSON file.",