Compare commits

...
419 Commits
Author SHA1 Message Date
Alexander Bakker 506d9efab3 Release v2.1
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2022-11-20 16:19:37 +01:00
Alexander Bakker 5ab36d72a4 Add a test for password and backup password changes 2022-11-20 15:05:11 +01:00
Alexander Bakker ac75c346ec Update translations from Crowdin 2022-11-20 13:23:40 +01:00
Alexander Bakker 5dfdbabf30 Patch scrypt implementation to directly use Java's Integer.rotateLeft
This should improve performance in some rare cases where the wrapper
function that BouncyCastle has for Integer.rotateLeft is not inlined.

See: #1024
2022-11-20 12:54:55 +01:00
Alexander Bakker e7cc3e6ca3 Fix a crash by only creating toasts using Toast.makeText() 2022-11-16 10:48:21 +01:00
Alexander BakkerandGitHub f8d60fb1b7 Merge pull request #1027 from alexbakker/2fas-schema3
Add support for importing 2FAS schema v3 backups
2022-11-15 22:45:18 +01:00
Alexander Bakker f081cfa77b Add support for importing 2FAS schema v3 backups
Fixes #1026
2022-11-15 22:44:13 +01:00
Alexander Bakker 55dc4b22d5 Set RESULT_CANCELED before calling finishAffinity()
This fixes a crash in AuthActivity:

Exception java.lang.IllegalStateException: Can not be called to deliver a result
2022-11-12 11:50:01 +01:00
Alexander Bakker 9f55d4f659 Do not print a trace when calling the private finish() overload fails 2022-11-09 20:42:59 +01:00
Alexander Bakker 715c5112ab Fix a crash caused by ViewHolder.getAdapterPosition returning -1 2022-11-09 20:18:18 +01:00
Alexander Bakker e77df1eee4 Set fallbackLineSpacing to false for the OTP TextView
This prevents any dynamic changes in height that may occur while using
tap to reveal on Android 13 and up.
2022-11-09 18:50:38 +01:00
Alexander Bakker f6f549aaeb Be even more clear about why we can't import from certain apps anymore 2022-11-09 18:50:38 +01:00
Alexander Bakker 2f8d66843f Add vault encryption field back to the new issue template 2022-11-09 18:32:13 +01:00
Alexander Bakker 12dad56fe3 Update test dependencies to stable releases 2022-11-09 15:49:33 +01:00
Alexander Bakker ffbea9ea32 Use the new syntax for GitHub issue forms 2022-11-09 15:32:56 +01:00
Alexander Bakker 286d74b69a Switch comments of tile_open_vault and tile_open_scanner 2022-11-07 21:01:11 +01:00
Alexander Bakker 10ecd513fc Add context to tile_open_vault and tile_open_scanner strings 2022-11-07 21:00:08 +01:00
Alexander BakkerandGitHub 98e802a534 Merge pull request #1019 from beemdevelopment/feature/quick-settings
Add quick setting tiles
2022-11-06 15:34:10 +01:00
Michael Schättgen 6a1e6db486 Add quick setting tiles 2022-11-06 15:21:33 +01:00
Alexander BakkerandGitHub 599be44369 Merge pull request #1017 from orange-elephant/reveal-on-hotp-increment
Reveal hidden code on HOTP increment click
2022-11-06 12:18:40 +01:00
Alexander Bakker b2a98d9799 Release v2.1-beta2
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2022-11-03 22:50:55 +01:00
Alexander Bakker bee490d091 Check for nulls when opening ContentResolver streams 2022-11-03 22:41:30 +01:00
Michael Schättgen 1f69bf558e Temporarily disable failed test output in Github Actions 2022-11-03 13:41:17 +01:00
Michael Schättgen dd88f5bb0c Fix crash when using non latin language 2022-11-03 13:37:15 +01:00
elena af9be15ae0 Reveal hidden code on HOTP increment click 2022-11-02 21:07:37 +00:00
Alexander Bakker 8562fafda7 Release v2.1-beta1
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2022-11-02 17:11:39 +01:00
Alexander Bakker 708a5f4a19 Update translations from Crowdin 2022-11-02 15:45:27 +01:00
Alexander Bakker fcc7b7baa2 Use MaterialDividerItemDecoration for compact view mode
This allows us to disable the divider for the "Showing x entries" footer
2022-11-02 15:18:07 +01:00
Alexander Bakker 7c0b22920d Fix minor entry margin issues
Accidentally introduced with the entry pinning feature

This also moves the favorite field to the vault instead of shared
preference in order to avoid some complexity
2022-11-02 15:14:59 +01:00
Alexander Bakker c27d080a11 Fix call to notifyItemMoved when entry change causes sort change
This fixes an issue introduced in ffcbaffcfc
2022-11-02 15:09:42 +01:00
Alexander Bakker 0ee74bfeb2 Install HAXM before running the instrumented tests 2022-11-02 12:44:29 +01:00
Alexander Bakker 289b8775d3 Update ZXing to 3.5.1 2022-11-02 12:40:20 +01:00
Alexander Bakker c12397a509 Update dependencies 2022-11-01 20:19:00 +01:00
Alexander Bakker 0aef57e610 Add context to favorite strings to indicate that they're verbs 2022-10-27 22:12:49 +02:00
Alexander Bakker 7993142cc5 Show a warning when a separate export/backup password is configured 2022-10-27 22:12:44 +02:00
Alexander BakkerandGitHub 031a11250a Merge pull request #1006 from beemdevelopment/feature/favorites
Add ability to pin/favorite entries
2022-10-26 14:14:51 +02:00
Michael Schättgen 5ec1e33a31 Add ability to favorite/pin entries 2022-10-26 14:07:49 +02:00
Alexander Bakker c58b773878 Rename some things related to plaintext backup warning 2022-10-25 18:38:07 +02:00
Alexander Bakker 681326839c Fix back navigation in preferences when pressing the home action button 2022-10-16 13:27:20 +02:00
Alexander Bakker 3d124d225e Use VaultLockReceiver in a Context-registered manner
Turns out we can't listen from ACTION_SCREEN_OFF from a
manifest-registered broadcast receiver
2022-10-15 20:48:36 +02:00
Alexander Bakker 8292173297 Remove unused code for storage read permission request results 2022-10-12 17:39:40 +02:00
Alexander Bakker 84e179f9d3 Add helper to simplify animation end listeners 2022-10-12 17:36:46 +02:00
Alexander BakkerandGitHub 41eba76b05 Merge pull request #1005 from alexbakker/predictive-back
Add support for predictive back gesture
2022-10-12 17:30:05 +02:00
Alexander Bakker ad77bd687f Add support for predictive back gesture 2022-10-12 17:25:40 +02:00
Alexander Bakker c6888b11df Add an icon to the backup status in preferences 2022-10-10 22:33:42 +02:00
Alexander BakkerandGitHub 427be4d56b Merge pull request #992 from orange-elephant/code-grouping-options
Additional code grouping options
2022-10-10 17:36:53 +02:00
elena c206d4bee8 Additional code grouping options 2022-10-09 21:24:01 +01:00
Alexander Bakker 7de7fba2c8 Disable R8 obfuscation 2022-10-09 18:28:56 +02:00
Alexander Bakker 8ea28327db Optimize APK size by fixing R8 rules and excluding some BC resources 2022-10-09 17:18:13 +02:00
Alexander Bakker 80c37556c7 Prevent double launches of the intro and auth activities
Since API level 33: When opening Aegis right after installing it,
Android will send a configuration change event (CONFIG_ASSETS_PATHS),
causing MainActivity to restart almost immediately. This would also
cause two IntroActivity's to be started on top of eachother.
2022-10-09 16:33:28 +02:00
Alexander Bakker 35d3675561 Update GitHub Actions 2022-10-09 16:33:26 +02:00
Alexander Bakker 7517cfc975 Update dependencies 2022-10-09 12:53:46 +02:00
Alexander Bakker 4198ca3bb7 Update Gradle 2022-10-09 12:51:06 +02:00
Alexander Bakker 3927ddec3e Make vault lock intent used in notifications more explicit
Aegis can display a notification to the user as a reminder that the vault is
unlocked. If the user taps the notification, the vault is locked. CodeQL
reported that Aegis may be vulnerable to CWE-927, because of the use of an
implicit intent wrapped by a PendingIntent in that notification.

This does not appear to be exploitable in our case, because we use
``PendingIntent.getBroadcast`` and explicitly set the action of the wrapped
intent. Aegis also does not read or act on any information from the received
intent. This means that a malicious app cannot launch activities or send a
broadcast with a different action, as is common with these type of weakness. The
worst an app with notification access can do, is lock the vault.

Either way, it's good to make the intent explicit, so this patch addresses that.
Additionally, for API level 23 and up, we've made the wrapped intent immutable a
while back.

We'd like to thank John Rune, who ran a CodeQL scan on the Aegis codebase and
privately disclosed this finding to us.
2022-10-09 11:56:09 +02:00
Alexander Bakker 8c9ab38153 Add a workflow for CodeQL analysis 2022-10-08 20:31:40 +02:00
Alexander BakkerandGitHub 3c10b234ea Merge pull request #1000 from xconverge/fixSomeTypos
Fix some typos in docs
2022-10-08 11:49:59 +02:00
Sean Kelly 8a9a0856fb Fix some typos in docs 2022-10-06 21:34:37 -07:00
Alexander Bakker adc9179364 Always copy VaultFileCredentials when accessing it
This makes sure that mutations to the credentails can only ever be persisted
intentionally.
2022-10-05 19:42:18 +02:00
Alexander Bakker 8ae8130b71 Store and display backup error messages more clearly 2022-10-05 18:21:50 +02:00
Alexander Bakker 4427498d5e Rename the instrumented tests to be more consistent 2022-10-05 13:44:12 +02:00
Alexander Bakker aad6d78750 Move the panic trigger setting to the Security fragment 2022-10-05 13:27:28 +02:00
Alexander Bakker ef2e803e04 Make the entry count text a bit smaller 2022-10-05 13:25:17 +02:00
Alexander Bakker c718ea79c5 Update dependencies 2022-10-03 19:29:06 +02:00
Alexander BakkerandGitHub acc6b9a3de Merge pull request #973 from orange-elephant/entries-shown-count
Add entries showing count
2022-09-28 13:48:35 +02:00
elena 4bf807c46a Add entries showing count 2022-09-23 18:49:23 +01:00
Alexander Bakker e4798703f0 Make the FAB scroll listener a less sensitive
This should help minimize the glitchiness that can occur when scrolling
through the entry list.

Close #963.
2022-09-17 18:27:56 +02:00
Alexander Bakker 80624f844c Perform a version check when importing from the Steam app
Fixes #986.
2022-09-17 18:08:21 +02:00
Alexander BakkerandGitHub 714459c528 Merge pull request #969 from digitalheir/minimize-after-copy
Minimize or Close app after copying OTP #805
2022-09-17 17:55:25 +02:00
Maarten TrompperandAlexander Bakker 78feb25543 Minimize or Close app after copying OTP
Close #805
2022-09-17 17:51:03 +02:00
Alexander Bakker 3bc10bd4b8 Disallow importing empty secrets
Fixes #975

And display "ERROR" for any existing bad entries. This is kind of ugly,
but it's better than crashing, and there are probably very few (or zero)
users who have bad entries anyway.
2022-09-17 17:31:59 +02:00
Alexander BakkerandGitHub 66b7fd38d6 Merge pull request #964 from orange-elephant/google-auth-style-export
Google Authenticator compatible export
2022-09-17 15:46:56 +02:00
elena bc665b6980 Google Authenticator compatible export 2022-09-16 17:57:42 +01:00
Alexander Bakker 06405d10ad Only request the POST_NOTIFICATIONS permission in tests on API 33 2022-09-14 21:36:31 +02:00
Alexander Bakker 1e3ceefeec Request permission to show notifications
This is needed since API 33, because we show a "Vault unlocked"
notification if the user has enabled encryption and has unlocked the
vault.
2022-09-14 20:54:08 +02:00
Alexander Bakker 642864fca1 Mark clipboard data as "sensitive" when copying tokens 2022-09-14 18:33:28 +02:00
Alexander Bakker 3ec6e35011 Update dependencies
This also updates the test dependencies to an alpha version. We have to
use a pre-stable version, because these include some fixes for running
on API 33.
2022-09-14 18:08:47 +02:00
Alexander BakkerandGitHub e19ceb0761 Merge pull request #981 from jas14/monochromatic-icon
Add monochrome launcher icon
2022-09-14 17:33:53 +02:00
Alexander BakkerandGitHub 30b8e35de8 Merge pull request #968 from digitalheir/adaptive-text-size
Text is cutoff because of small display
2022-09-14 16:34:12 +02:00
Joe Stein 012b66fe9b Pin Robolectric target SDKs to 32 2022-09-05 17:09:48 -04:00
Joe Stein 4cd0d2de04 Bump targetSdkVersion to 33 2022-09-05 17:09:43 -04:00
Joe Stein bb3f4d733f Add monochrome adaptive icon for Android 13 2022-09-03 23:08:40 -04:00
Maarten Trompper 05a8c7c51f Fixes #794 2022-08-26 20:31:29 +02:00
Alexander Bakker 029ca81bbf Don't catch the IllegalArgumentException when calling getMissingIndices
We always call isSingleBatch beforehand, so if the exception occurs,
it's a bug.
2022-08-22 19:14:51 +02:00
Alexander BakkerandGitHub 70ceca6a7b Merge pull request #958 from orange-elephant/fix-scan-google-auth-export-from-image
Import Google Authenticator exports by image
2022-08-22 19:06:59 +02:00
elena 2767727ad4 Import google auth export from image 2022-08-21 18:47:54 +01:00
Alexander BakkerandGitHub 2dc01adc48 Merge pull request #925 from alexbakker/intro-import
Add an import button to the intro
2022-08-17 19:24:36 +02:00
Alexander Bakker 79022be3b6 Add an import button to the intro 2022-08-17 19:11:35 +02:00
Alexander Bakker dcda668671 Disable postprocessing for debug builds to speed them up 2022-08-17 12:00:17 +02:00
Alexander BakkerandGitHub ff0cd99170 Merge pull request #961 from orange-elephant/handle-intent-with-text-extra
Enable sharing text to Aegis
2022-08-17 10:44:10 +02:00
elena 5bb32a982b Enable sharing text to Aegis 2022-08-11 21:32:33 +01:00
Alexander BakkerandGitHub 85e230c46a Merge pull request #957 from orange-elephant/add-plaintext-export-warning
Add warning banner after plaintext export
2022-08-11 21:03:20 +02:00
elena 045b8280bf Add warning banner after plaintext export 2022-08-10 17:17:51 +01:00
Alexander Bakker 6fd8a3b6b4 Allow sharing multiple QR code images to Aegis through a single intent
This also refactors the logic for handling incoming intents a bit
2022-08-10 17:48:36 +02:00
Alexander Bakker e46857a26e Add support for importing multiple QR code images in one go
This is also part of the preparation needed for scanning Google
Authenticator Export QR codes from images.
2022-08-10 17:22:09 +02:00
Alexander BakkerandGitHub b875baacef Merge pull request #948 from orange-elephant/Add-mOTP-support
Add MOTP support
2022-08-07 18:31:51 +02:00
elena 3441deee64 Add MOTP support 2022-08-07 16:40:08 +01:00
Alexander Bakker bd3697659f Try harder to find QR codes in image files
And refactor a bit by moving some of the QR scanning related logic to a
separate helper class.
2022-08-07 17:13:58 +02:00
Alexander Bakker 5f12eae678 Add tests for scanning QR codes 2022-08-04 21:47:51 +02:00
Alexander BakkerandGitHub 3b715d58cf Merge pull request #952 from Hovn/master
Set the searchview to occupy all Toolbar widths when it expands
2022-08-04 18:49:59 +02:00
Alexander Bakker 76245677b0 Downgrade ResourceType linter error to a warning 2022-08-03 22:42:56 +02:00
Alexander Bakker f73a64acd6 Update gradle and dependencies 2022-08-03 20:38:10 +02:00
HovnCompany b4f12af23a Set the searchview to occupy all Toolbar widths when it expands 2022-08-01 16:00:40 +08:00
Alexander Bakker 043b17909c Wait for ViewPager to be idle in instrumented tests
This fixes the flakiness issues with the intro tests
2022-06-06 19:07:02 +02:00
Alexander Bakker 5226def653 Run UI tests as part of our CI
Third attempt's the charm? This time we're running the tests on macOS
hosts, which is supposedly more stable.
2022-06-06 19:06:42 +02:00
Alexander Bakker 1dcf56a0fa Capture screenshots of failing instrumented tests 2022-06-06 14:52:17 +02:00
Alexander Bakker fff81b0ee3 Upload APK artifact once CI is done 2022-06-06 14:51:35 +02:00
Alexander Bakker f32ac0e8ab Make ProgressDialog adhere to the "Secure screen" setting 2022-06-06 14:05:16 +02:00
Alexander Bakker 8d3b2e2c9d Rename slot type DERIVED to PASSWORD 2022-06-06 13:55:19 +02:00
Alexander BakkerandGitHub 0cfd78ace1 Merge pull request #926 from alexbakker/backup-password
Add an option to set a separate password for backups and exports
2022-06-06 13:33:22 +02:00
Alexander Bakker 5db365a999 Add instrumented tests for backup and export 2022-06-06 13:19:46 +02:00
Alexander Bakker a492bcbde3 Add an option to set a separate password for backups and exports 2022-06-05 23:03:11 +02:00
Alexander Bakker d40ebf0f67 Use a higher resolution app icon in the intro 2022-06-05 12:33:53 +02:00
Alexander Bakker 1373a67ea0 Only re-sort entry list when not using custom sorting
This fixes a crash introduced in #910.
2022-06-04 19:01:37 +02:00
Alexander BakkerandGitHub 11d7493245 Merge pull request #924 from CristianAUnisa/double-click-copy-crash
Avoid crash when double clicking on "Copy" button
2022-06-04 14:49:22 +02:00
CristianAUnisa d2f0f71be5 Check if there's a selected item after pressing on an Action menu item 2022-06-04 14:48:14 +02:00
Alexander Bakker 49b334ff70 Show dialog when trying to import from a recent Google Auth version 2022-06-04 14:35:36 +02:00
Alexander BakkerandGitHub ac123918c2 Merge pull request #922 from CristianAUnisa/google-auth-ignore-encrypted
Check if Google Authenticator entries are encrypted
2022-06-04 13:02:21 +02:00
CristianAUnisa 4cf0465a32 Check if Google Authenticator entry is encrypted 2022-06-04 12:47:44 +02:00
Alexander BakkerandGitHub 98de86b53e Merge pull request #910 from CristianAUnisa/sort-on-replace
Sort list after editing entry
2022-05-22 13:36:42 +02:00
Alexander Bakker dfa3ae4d4e Reorganize README badges 2022-05-22 13:31:35 +02:00
CristianAUnisa ffcbaffcfc Sort list after editing entry 2022-05-22 13:19:55 +02:00
Alexander Bakker ce9a15b7bc Allow filtering by "No group"
This is a continuation of #830

Close #826, #830
2022-05-22 13:11:34 +02:00
Alexander Bakker e73de453c6 Update Matrix badge 2022-05-22 13:11:34 +02:00
Alexander Bakker 3b1035b5e1 Reset the action bar subtitle when the back button is pressed 2022-05-22 12:02:23 +02:00
Alexander BakkerandGitHub 239d8740be Merge pull request #912 from CristianAUnisa/screen-rotation-bugfix-686
Restore search query on screen rotation
2022-05-22 11:55:01 +02:00
CristianAUnisa 49130cee73 Restore search query on screen rotation 2022-05-07 16:15:30 +02:00
Alexander Bakker 0909341caa Improve QR reader efficiency and support inverted QR codes 2022-05-01 19:22:20 +02:00
Alexander BakkerandGitHub 81d5915969 Merge pull request #908 from CristianAUnisa/bitwarden-remote
Add Bitwarden importer
2022-04-30 13:13:42 +02:00
CristianAUnisa 8d4a687817 Add Bitwarden importer
Added license notice for Simple Flat Mapper

Added Steam secret support to Bitwarden importer

https://bitwarden.com/help/authenticator-keys/#steam-guard-totps

Added tests
2022-04-24 16:55:38 +02:00
Alexander BakkerandGitHub b0e8d041d0 Merge pull request #904 from CristianAUnisa/dont-hide-fab-on-keydown
Don't hide "Add entry" button when a DPad key is pressed
2022-04-21 19:00:52 +02:00
CristianAUnisaandAlexander Bakker ca49cd4df5 Don't hide "Add entry" button when DPAD key is pressed 2022-04-21 18:49:41 +02:00
Alexander Bakker beadf4db8b Use requireContext, requireActivity and requirePreference where possible 2022-04-10 18:44:25 +02:00
Alexander Bakker f7b4cceb81 Remove unused SlotAdapter and SlotHolder 2022-04-10 18:14:00 +02:00
Alexander Bakker 86b86fef10 Pass current values to Dialog functions instead of reading from prefs 2022-04-10 17:48:26 +02:00
Alexander Bakker 927ea50c33 Ignore JSON exceptions in getUsageCounts instead of printing them 2022-04-10 17:12:19 +02:00
Alexander Bakker 339a31b0f3 Show a backup reminder if auto backups are not enabled
If the user doesn't have auto backups enabled, the reminder will pop up
up every time a significant change is made to the vault.

Users can get rid of the reminder by:
- Creating an export
- Enabling automatic backups (either ours or Android backups will do)
2022-04-10 17:12:12 +02:00
Alexander Bakker cf9fbf081c Don't print the exception of readVaultFile if the file was not found 2022-04-10 14:46:41 +02:00
Alexander Bakker d4557065ea Disable the MissingQuantity lint check to fix the build 2022-04-10 14:41:55 +02:00
Alexander Bakker d0c8c5fae4 Update Gradle and dependencies 2022-04-09 18:28:15 +02:00
Alexander Bakker b8fa67304a Release v2.0.3
(cherry picked from commit 32ee0915a7)
2022-03-27 21:58:31 +02:00
Alexander Bakker 903948d57c Stop using dependency injection in AegisBackupAgent
Because the app launches in a restricted mode when restoring a backup,
dependency injection with Dagger Hilt doesn't work inside BackupAgent. This
would cause backup restore operations to fail. This issue got introduced by the
recent switch to Dagger Hilt, which has not been included in a release of Aegis
yet.
2022-03-16 14:43:13 +01:00
Alexander Bakker 71eb6b133c Remove SlotManagerActivity from AndroidManifest 2022-03-06 14:54:36 +01:00
Alexander Bakker 6f66706685 Don't pass MIME type along when selecting icon pack file to import
Fixes #757
2022-03-06 13:55:12 +01:00
Alexander Bakker 6d8a8c066c Remove unused string resources 2022-03-06 13:49:40 +01:00
Alexander Bakker baa3cac5a4 Remove slot manager activity
We don't really use this anymore, and it was only available for debug builds anyway
2022-03-06 13:33:57 +01:00
Alexander Bakker 71f2b54deb Use Dagger Hilt for dependency injection
This gets rid of our own janky dependency injection through the AegisApplication class
2022-03-06 13:06:34 +01:00
Alexander BakkerandGitHub 927f5f2bd5 Merge pull request #845 from Hacker437/Dialog
Updated Delete Dialog
2022-02-27 18:18:56 +01:00
Praveen KumarandAlexander Bakker c0020684de Change the layout of the entry delete dialog and include more info 2022-02-27 17:46:47 +01:00
Alexander Bakker b8066c1925 Use Aegis icon as lock status notification icon 2022-02-18 12:54:30 +01:00
Alexander Bakker 0f3e5c537c Allow customization of password reminder frequency
Close #769
2022-02-17 18:14:08 +01:00
Alexander Bakker 5ce21a94ea Only skip panic trigger signature check if running under a test 2022-02-17 15:47:27 +01:00
Alexander Bakker d1d5df8051 Add tests for the Ripple panic trigger action 2022-02-17 14:25:32 +01:00
Alexander Bakker 43c064bb26 Disable the Crowdin workflow for forks
This was always failing in forks because the Crowdin API key is only available for the upstream repository. As it should be.
2022-02-17 13:29:59 +01:00
Alexander Bakker b9a81bdd75 Always allow D2D transfers in backup agent 2022-02-17 13:16:05 +01:00
Alexander Bakker 0938d3688a Set dataExtractionRules in AndroidManifest for Android 12+ 2022-02-17 13:16:05 +01:00
Alexander Bakker fcb7bf032b Add support for importing 2FAS schema v2 backups 2022-02-10 20:58:06 +01:00
Alexander Bakker acfb70c267 Move Yandex secret validation tests to a different folder 2022-02-06 12:55:02 +01:00
Alexander Bakker 119c3838e1 Silence lint error related to calling private method through reflection 2022-02-04 21:23:35 +01:00
Alexander Bakker 39a5dc3ee8 Update the vault format documentation and improve the diagram 2022-02-04 20:53:08 +01:00
Alexander Bakker 473cb7bfeb Set FLAG_IMMUTABLE on the intent of the lock status notification
This fixes a crash on API 31
2022-02-02 21:06:21 +01:00
Alexander Bakker 3d13117752 Refactor Yandex support a bit and fix some style issues 2022-02-02 17:55:09 +01:00
Alexander BakkerandGitHub 76c89f0fcc Merge pull request #869 from RandomRoot/feature-yandexotp
Feature: Add Yandex OTP support
2022-02-02 13:40:48 +01:00
Alexander Bakker 185e22a82e Downgrade camera-view back to 1.0.0-alpha32
Can't mix and match 1.0.0 and 1.1.0.
2022-01-31 22:07:40 +01:00
Alexander Bakker e88c3ea6db Update dependencies 2022-01-31 21:59:02 +01:00
Alexander Bakker a04020aed0 Add an FAQ document 2022-01-31 21:19:22 +01:00
Mikhail Prokofev af2bf6f683 Add Yandex OTP support 2022-01-26 18:43:55 +03:00
Alexander BakkerandGitHub 72c165749f Merge pull request #875 from moesheyab/aegis-import-message-fix
Fix Aegis import dialog message title
2022-01-22 11:41:54 +01:00
moesheyab f14bd99f63 Fix Aegis import dialog message title 2022-01-16 12:21:18 -08:00
Alexander Bakker e54ac9aba4 Update FUNDING.yml 2022-01-03 21:20:09 +01:00
Alexander Bakker f9b4e8fa3e Use the first grapheme for the TextDrawable icon
Fixes #862
2022-01-03 20:23:04 +01:00
Alexander Bakker 86580e38af Update crowdin-cli to 3.7.2 2021-12-06 23:07:59 +01:00
Alexander Bakker 6955eb10da Add a GitHub Action for uploading sources to Crowdin 2021-12-06 22:31:12 +01:00
Alexander Bakker 153f5e09d8 Update dependencies 2021-12-04 11:54:02 +01:00
Alexander Bakker cf63f5bef2 Fix the build 2021-12-04 11:42:41 +01:00
Alexander Bakker aec639cc53 Add a test for the Duo importer 2021-12-04 11:42:28 +01:00
Alexander BakkerandGitHub 5c196f1ca5 Merge pull request #835 from anibyl/feature-duo
Add DUO importer
2021-12-04 11:09:20 +01:00
Sieva Kimajeŭ 56ddefa246 Add DUO importer. #68 2021-12-02 15:47:43 -08:00
Alexander Bakker 4c977a6371 Disable the PIN keyboard when enabling encryption
Fixes #854
2021-11-28 19:27:40 +01:00
Alexander BakkerandGitHub 07b0b26caf Merge pull request #844 from Hacker437/FocusSearch
Added Focus Search on App Start
2021-11-16 18:47:45 +01:00
Praveen Kumar 0652eaa5cd Added Focus Search on App Start
Renamed key

Removed unnecessary code
2021-11-08 17:34:49 +00:00
Alexander Bakker adfc472a39 Bump target SDK version to 31 and update dependencies 2021-11-03 12:23:06 +01:00
Alexander BakkerandGitHub 9ca4de8b60 Merge pull request #838 from Dar9586/master
Vauld.md inconsistency fix
2021-10-30 11:10:06 +02:00
Dar9586andGitHub 0b104cf285 Update vault.md 2021-10-30 08:35:25 +00:00
Alexander BakkerandGitHub d65982aaa1 Merge pull request #832 from strugee/upgrade-android-gradle-plugin
Upgrade Android Gradle plugin
2021-10-20 21:44:00 +02:00
AJ Jordan fbc390b714 Upgrade to Gradle/Gradle Android plugin 7.x
Additionally, enable some more linting (per the Android plugin release
notes' recommendation) and fix a lint warning.
2021-10-20 12:07:24 -07:00
Michael SchättgenandGitHub a14dd382bf Merge pull request #831 from strugee/checked-filter
Make group chips checked when selected
2021-10-20 13:19:27 +02:00
AJ Jordan a302f3daac Make group chips checked when selected
This brings us in line with upstream Material UI guidelines - apparently
before we were showing "choice chips" and with this change we show
"filter chips".

See https://material.io/components/chips/android#filter-chip.
2021-10-19 23:01:27 -07:00
Alexander Bakker 80960e23fc Release v2.0.2
build / build (push) Canceled after 0s
2021-09-15 15:40:46 +02:00
Alexander Bakker a32ecdaf9b Update translations from Crowdin 2021-09-15 15:32:39 +02:00
Alexander BakkerandGitHub 6967e42ab5 Merge pull request #816 from Hacker437/Chip
Changed the Chip to match the background in Amoled and Dark Mode
2021-09-15 14:23:11 +02:00
Praveen Kumar 385475aa8b Changed the Chip to match the background in Amoled and Dark Mode 2021-09-03 11:24:22 +05:30
Alexander BakkerandGitHub a9d850aa01 Merge pull request #808 from Hacker437/migrate-buttons
Migrate App Compat Buttons To Material Buttons
2021-09-01 18:50:46 +02:00
Praveen Kumar a9806fcfb7 Migrate App Compat Buttons To Material Buttons 2021-08-31 09:40:39 +05:30
Alexander BakkerandGitHub 1e6175854c Merge pull request #793 from modelorona/feature-note_field_annotation
add note text field when editing entry
2021-08-30 21:08:46 +02:00
modelorona 97f28c6089 add note field to entry 2021-08-30 10:21:54 +01:00
Alexander BakkerandGitHub 3464f93c39 Merge pull request #791 from bitscuity/feature-pause
Option to Disable Automatic Refresh for Selected Code
2021-08-11 14:28:34 +02:00
bitscuity 02ee52a31f Added code to pause updating of focused entry 2021-08-11 14:01:24 +02:00
Alexander Bakker 6bafd9e9ae Ensure the issuer textbox and group dropdown have equal height
Fixes #751
2021-07-31 14:01:21 +02:00
Alexander Bakker 74e460d9a9 Update link to aegis-icons 2021-07-29 18:42:31 +02:00
Alexander Bakker 11705866e3 Fix the build by fixing some linter complaints 2021-07-22 22:25:40 +02:00
Alexander Bakker db0452e42a Update gradle 2021-07-22 21:43:51 +02:00
Alexander Bakker 177a964d3a Update dependencies 2021-07-22 21:17:04 +02:00
Alexander Bakker eb4b7b5d61 Accept spaces and dashes in secrets from Microsoft Authenticator
A user reported that importing was failing due to this issue
2021-07-22 21:07:32 +02:00
Alexander Bakker 68eb87b096 Check if searchView is not null before closing it in onLocked
This fixes a crash we've been seeing in the Google Play Console
2021-06-26 14:30:25 +02:00
Alexander Bakker eb22101b02 Release v2.0.1
build / build (push) Canceled after 0s
2021-06-23 18:41:26 +02:00
Alexander Bakker 44f69e755c Update translations from Crowdin 2021-06-23 18:27:04 +02:00
Alexander Bakker 327b7ccbae Perform case changes using Locale.ROOT where applicable
Fixes #777
2021-06-23 18:06:01 +02:00
Alexander BakkerandGitHub 6585513120 Merge pull request #780 from jhenninger/suggested-icons-matching
Improve icon suggestions
2021-06-23 12:33:08 +02:00
Johannes Henninger acbe73834d Improve icon suggestions
Check if the icon issuers contain the token issuer or vice versa.

Fixes #761
2021-06-23 01:31:50 +02:00
Alexander BakkerandGitHub c27c4f0ac5 Merge pull request #760 from michaelschattgen/feature/usage-count
Add usage count to entries
2021-06-17 20:04:51 +02:00
Michael Schättgen 34cd16f240 Add usage count to entries
Update Preferences.java

Fix build error and review improvements
2021-06-16 16:22:11 +02:00
Alexander BakkerandGitHub 78fc37d1e9 Merge pull request #763 from jhenninger/fix-blank-text-delete-dialog
Fix blank text in delete dialog for entries with no issuer
2021-06-06 11:33:50 +02:00
Johannes Henninger df9684a31c Fix blank text in delete dialog for entries with no issuer
Fixes #758
2021-06-04 14:29:53 +02:00
Alexander Bakker 520c587d09 Collapse the search view when locking the app
Addresses part of #750
2021-06-02 18:14:18 +02:00
Alexander Bakker 7506c70236 Release v2.0
build / build (push) Canceled after 0s
2021-05-26 10:50:24 +02:00
Alexander Bakker d1e3224cba Store the group filter as JSON in preferences
This ensures we don't run into issues if the group name contains a ','
2021-05-26 10:46:49 +02:00
Alexander Bakker d2eed8a356 Update translations from Crowdin 2021-05-26 10:37:07 +02:00
Alexander Bakker 668823507d Put the feature list in full_description.txt on a single line
This is an attempt to work around the broken rendering on the F-Droid website
2021-05-26 10:23:40 +02:00
Alexander Bakker 2b83dde58a Update in-app URL to aegis-icons latest release page 2021-05-26 10:18:03 +02:00
Alexander Bakker e97a53bbe9 Force search filter to null if it's empty
Fixes #705
2021-05-22 13:09:52 +02:00
Alexander Bakker 77f59d41ad Add group filter back in the UI tests 2021-05-22 12:45:58 +02:00
Alexander Bakker e2ddc8a80f Try to guess the MIME type if SAF doesn't provide it
This fixes a crash that would occur if SAF doesn't provide a MIME type
2021-05-20 21:46:56 +02:00
Alexander Bakker b6093c2bfa Explicitly disable backups preferences when disabling encryption 2021-05-20 21:25:56 +02:00
Alexander Bakker fc25312d12 Add an option to save the current group filter 2021-05-20 20:58:20 +02:00
Alexander Bakker 51eade900c Fix a number of issues related to updating the group chip after changes 2021-05-19 12:56:35 +02:00
Alexander Bakker d152d13580 Make sure text and radio button are aligned in importer dialog 2021-05-09 11:58:24 +02:00
Alexander Bakker 7dff3fbad1 Release v2.0-beta2
build / build (push) Canceled after 0s
2021-05-08 11:04:59 +02:00
Alexander Bakker 7dc7f6ccc0 Update translations from Crowdin 2021-05-08 10:57:05 +02:00
Alexander Bakker ad0088eca6 Don't rely on the intent action to decide whether to block auto lock 2021-05-08 10:42:04 +02:00
Alexander Bakker 813bf292fa Update dependencies 2021-05-08 10:10:08 +02:00
Alexander Bakker 80bf5bc854 Fix the QR code background color for the light theme 2021-05-07 18:13:46 +02:00
Alexander Bakker e319a2eceb Fix a crash when opening the "Import from app" dialog 2021-05-07 18:13:17 +02:00
Alexander Bakker 0a9bfde438 Hide the keyboard before every slide change in the intro 2021-05-07 18:12:52 +02:00
Alexander Bakker c3c4e1fb4b Reflect changes in the group list to the group filter
Fixes #723
2021-05-07 18:08:39 +02:00
Alexander Bakker 1eff91594f Fix multiple layout issues on small-screen devices
Close #560
2021-05-06 23:17:35 +02:00
Alexander Bakker fddc29880a Add support from importing from 2FAS Authenticator 2021-05-05 10:58:22 +02:00
Alexander BakkerandGitHub 2ccfcd62e1 Merge pull request #734 from EwoutH/gradle
Gradle: Validate wrapper in CI and update to 6.8.3
2021-05-04 22:40:29 +02:00
Ewout ter Hoeven 993b29bd83 Gradle: Update wrapper and scripts to 6.8.3 2021-05-04 21:59:25 +02:00
Ewout ter Hoeven e371485a1b CI: Add step that validates the Gradle wrapper
Validates the gradle-wrapper.jar file on each build, which is a binary blob of executable code. This action ensures it's legit and doesn't execute malicious code.

See https://github.com/gradle/wrapper-validation-action
2021-05-04 21:59:25 +02:00
Alexander Bakker fb58c877d1 Remove padding from Y plane data before passing it to ZXing
Fixes #726
Fixes #657
2021-05-04 19:21:57 +02:00
Alexander BakkerandGitHub a62e474e33 Merge pull request #735 from EwoutH/imgbot
[ImgBot] Optimize images
2021-04-29 21:03:38 +02:00
ImgBotApp 5975b929b7 [ImgBot] Optimize images
*Total -- 569.55kb -> 504.66kb (11.39%)

/app/src/main/res/drawable-xhdpi/ic_qr_code.png -- 3.27kb -> 2.13kb (34.81%)
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png -- 6.07kb -> 3.97kb (34.54%)
/app/src/main/res/drawable-xxhdpi/ic_qr_code.png -- 6.25kb -> 4.32kb (30.86%)
/metadata/en-US/images/icon.png -- 33.36kb -> 23.19kb (30.47%)
/app/src/main/res/drawable-hdpi/ic_qr_code.png -- 2.62kb -> 1.86kb (29.11%)
/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png -- 4.00kb -> 2.95kb (26.2%)
/app/src/main/res/drawable-mdpi/ic_qr_code.png -- 1.55kb -> 1.17kb (24.7%)
/app/src/main/res/drawable/app_icon.png -- 143.85kb -> 113.38kb (21.18%)
/app/src/main/res/drawable/ic_aegis_iconx.png -- 19.38kb -> 15.30kb (21.04%)
/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png -- 2.21kb -> 1.96kb (11.42%)
/metadata/en-US/images/phoneScreenshots/screenshot4.png -- 186.71kb -> 177.50kb (4.93%)
/docs/diagram.svg -- 11.00kb -> 10.58kb (3.85%)
/app/src/main/res/mipmap-hdpi/ic_launcher_background.png -- 1.58kb -> 1.53kb (3.22%)
/metadata/en-US/images/phoneScreenshots/screenshot5.png -- 147.70kb -> 144.82kb (1.95%)

Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
2021-04-28 09:18:59 +00:00
Alexander Bakker a5d3de55a2 Add support for selecting SVG icons through the file selection dialog
Fixes #724
2021-04-14 22:52:00 +02:00
Alexander Bakker b195d0dadd Fix multiple icon rendering issues in card_icon
- Use software rendering on API <= 27
- Use ImageView instead of CircleImageView

Fixes #725
2021-04-14 21:43:59 +02:00
Alexander Bakker 7d3666a5d0 Make the password configuration dialog scrollable
Fixes #722
2021-04-14 17:33:16 +02:00
Alexander Bakker 61ac83b134 Release v2.0-beta1
build / build (push) Canceled after 0s
2021-04-14 13:40:04 +02:00
Alexander Bakker 9c907cf14a Apply top margin to the first entry if there are no groups 2021-04-14 13:33:40 +02:00
Alexander Bakker 5f737582fb Fix syntax issue in arrays.xml 2021-04-14 12:56:31 +02:00
Alexander Bakker 89256dfef5 Update translations from Crowdin 2021-04-14 12:54:21 +02:00
Alexander Bakker 94b4c098de Update icons packs documentation 2021-04-14 12:15:19 +02:00
Alexander Bakker 1d848947d9 Only set the query if its non-empty when switching icon packs
This fixes an issue where the categories would be hidden when switching icon packs
2021-04-13 17:21:10 +02:00
Alexander Bakker 43ebe402ce Fix crash caused by incorrect cast to PreferencesFragment 2021-04-11 13:54:05 +02:00
Alexander BakkerandGitHub ae0b00573f Merge pull request #539 from alexbakker/iconpacks
Introduce support for icon packs
2021-04-10 10:50:36 +02:00
Alexander BakkerandGitHub efb5b10a76 Merge pull request #716 from DerEnderKeks/fix-recent-apps-behavior
Fixed that app vanished from recent apps list after locking
2021-04-09 14:01:58 +02:00
Alexander Bakker 4f38988c0d Introduce support for icon packs 2021-04-07 17:28:08 +02:00
Alexander Bakker c977b9a064 Update dependencies 2021-04-03 11:24:13 +02:00
DerEnderKeks 5353e7c3b1 Changed method to finish activities when locking 2021-04-01 18:03:16 +02:00
DerEnderKeks b999ccc83b Fixed that app vanished from recent apps list after locking 2021-03-31 17:06:39 +02:00
Alexander BakkerandGitHub fea5b8e75a Merge pull request #715 from DerEnderKeks/patch-1
Fixed minor markup irregularities in bug report template
2021-03-31 12:58:47 +02:00
DerEnderKeksandGitHub 6ce661180e Fixed minor markup irregularities in bug report template 2021-03-31 12:50:43 +02:00
Alexander Bakker 230f21b9f0 Update dependencies 2021-03-20 13:11:17 +01:00
Alexander Bakker 801e677928 Silence an overly enthousiastic linker check 2021-03-01 18:44:14 +01:00
Alexander Bakker 143b9a85b4 Update dependencies 2021-03-01 18:21:20 +01:00
Alexander Bakker 71f66e3142 Remove old testdata and update documentation to new location 2021-02-21 17:16:40 +01:00
Alexander Bakker a6ab669811 Don't crash when uiMode is set to UI_MODE_NIGHT_UNDEFINED 2021-02-21 17:08:05 +01:00
Alexander Bakker a519b31bd3 Fix typo in CONTRIBUTING.md 2021-02-18 13:10:26 +01:00
Alexander Bakker c7ef10367f Fix an issue where advanced fields were disabled inadvertently 2021-02-17 12:59:59 +01:00
Alexander BakkerandGitHub 085e8e51dc Merge pull request #688 from jhenninger/feature/receive-shared-image
Add support for creating entries from shared images
2021-02-17 12:01:17 +01:00
Johannes Henninger 167f2d6dad Add support for creating entries from shared images 2021-02-14 16:05:13 +01:00
Alexander Bakker e653e42455 Update dependencies 2021-02-14 16:03:30 +01:00
Alexander Bakker 158eb4609c Remove unused 'stateless' support code from AuthActivity 2021-02-13 19:15:30 +01:00
Alexander Bakker 2242dbc6cd Update build badge for GitHub Actions 2021-02-10 12:56:49 +01:00
Alexander Bakker ca8f3e49ea Hide the vault wipe option in the menu of the import activity
Always showing the dialog can be confusing for users.
2021-02-08 19:11:57 +01:00
Alexander Bakker c3d9ab86c7 Improve the wording of a couple of strings 2021-02-08 18:55:23 +01:00
Alexander Bakker 441a943a9d Update dependencies 2021-02-08 18:46:56 +01:00
Alexander Bakker 293e2ddeb0 When importing, read the file from SAF on a background thread
Fixes issue with importing from Nextcloud. Close #673.
2021-02-07 13:12:41 +01:00
Alexander Bakker 2c8a64f943 Disable some fields if Steam OTP type is selected
Also, move some magic default OTP parameters to constants
2021-01-30 16:41:25 +01:00
Alexander Bakker bc6cb35dc0 Clean up unused variables 2021-01-27 20:44:47 +01:00
Alexander Bakker ad138e4a4c Fix behavior of the new entry highlight in case no scroll is needed 2021-01-27 20:42:39 +01:00
Alexander Bakker f4bdf4645b Hide some entry editing settings by default to reduce user confusion 2021-01-27 20:09:53 +01:00
Alexander Bakker fd9a387b4e Rename Filter -> Sort in menu and remove old references to Filter 2021-01-27 18:32:44 +01:00
Alexander Bakker 778000aa24 Minor fixes for group chips, remove remnants of filter menu item 2021-01-27 18:24:52 +01:00
Alexander Bakker 40fbe39474 Update list of third-party licenses 2021-01-27 14:00:27 +01:00
Alexander Bakker bda1a1d5af Add a dialog for Aegis' license 2021-01-27 13:54:11 +01:00
Alexander Bakker e6e2809c9c Fix the appearance of the toolbar in the scanner activity 2021-01-27 12:36:48 +01:00
Alexander Bakker b91355da47 Remove usage of HtmlCompat 2021-01-24 21:04:25 +01:00
Alexander Bakker 4bb5ee52d9 Fix disabled alert dialog button color by setting alpha using selector 2021-01-24 20:52:24 +01:00
Alexander Bakker de3fcfdb26 Fix the background color of the imported entries list 2021-01-24 20:44:01 +01:00
Alexander Bakker ae71febf10 Move import logic to separate activity to fix a couple of issues
Fixes #456.
Fixes #670.
2021-01-24 20:19:29 +01:00
Alexander Bakker 7be1a74cfd Force higher resolution for analysis and run it on a background thread 2021-01-24 15:02:02 +01:00
Alexander Bakker 22c93bf5c6 Show some additional warning info in the entry deletion dialog
Close #565.
2021-01-24 14:20:29 +01:00
Alexander Bakker 68436fba9c Rewrite layout of EditEntryActivity to not use TableLayout
This prevents excessive overdraw and fixes the UI tests
2021-01-24 12:53:29 +01:00
Alexander Bakker 44ff321f8f Remove pref_tools_group_title from all locales 2021-01-23 19:36:57 +01:00
Alexander Bakker d9d6733878 Improve preference organization and add summaries to the sections 2021-01-23 19:29:41 +01:00
Alexander Bakker eae31ef94b Switch from Appcompat to Material Components theme
Close #354.
2021-01-23 15:23:02 +01:00
Alexander BakkerandGitHub 29ea2df696 Merge pull request #671 from michaelschattgen/feature/chips
Start working on bottomsheet for group chips
2021-01-23 12:08:01 +01:00
Alexander BakkerandMichael Schättgen a6bf3b7c87 Add bottomsheet for chips 2021-01-21 10:53:37 +01:00
Alexander Bakker c6cb390990 Fix the UI tests 2021-01-16 17:43:07 +01:00
Alexander BakkerandGitHub f7a428b8cb Merge pull request #654 from alexbakker/android-backups
Add support for participating in Android's backup system
2021-01-16 16:24:08 +01:00
Alexander Bakker f080eaa8f9 Add support for participating in Android's backup system
This adds an option for participating in Android's backup system. Two items are
backed up: the ``files/aegis.json`` file and the entire ``shared_prefs``
directory. The option is disabled by default and can only be enabled if
encryption is enabled as well.

I tested this with Local Transport and Seedvault. To test with Local Transport,
see: https://developer.android.com/guide/topics/data/testingbackup.
2021-01-16 16:19:25 +01:00
Alexander BakkerandGitHub 07c768893a Merge pull request #666 from alexbakker/separate-prefs
Split preferences into separate fragments
2021-01-16 15:51:26 +01:00
Alexander Bakker ef8c116bdc Split preferences into separate fragments
<img src="https://alexbakker.me/u/5phth0i1ga.png" width="300" />
2021-01-16 15:46:13 +01:00
Alexander BakkerandGitHub 260a3b9c78 Merge pull request #651 from alexbakker/replace-fab
Replace the FAB with a bottom sheet dialog
2021-01-16 15:39:31 +01:00
Alexander BakkerandGitHub a5ec7666ec Merge pull request #647 from alexbakker/more-tests
Add some more tests
2021-01-16 15:39:02 +01:00
Alexander BakkerandGitHub ff450c3edf Merge pull request #644 from alexbakker/remove-acc-name-opt
Remove the "search in account names" option and do so by default
2021-01-16 15:37:08 +01:00
Alexander BakkerandGitHub e6e179307d Merge pull request #663 from alexbakker/fix-650
Explicitly opt out of WebView usage statistics collection
2021-01-16 15:36:36 +01:00
Alexander Bakker 2c0068bea7 Release v1.4.2
Build / build (push) Canceled after 0s
2021-01-16 15:27:00 +01:00
Alexander BakkerandGitHub 6dcde38667 Merge pull request #664 from alexbakker/downgrade-zip4j
Downgrade zip4j to 2.6.0
2021-01-16 15:10:39 +01:00
Michael SchättgenandGitHub ec1913c77a Merge pull request #661 from alexbakker/fix-660
Use name() instead of toString() on StandardCharsets.UTF_8
2021-01-13 20:44:07 +01:00
Michael SchättgenandGitHub 3e40cc9c8f Merge pull request #655 from alexbakker/phonefactor-error
Show a clearer error message when encountering phonefactor:// URI's
2021-01-13 20:24:26 +01:00
Michael SchättgenandGitHub 40d1e22079 Merge pull request #643 from alexbakker/documentsui-error
Simplify the auto lock block logic and show an error if DocumentsUI is missing
2021-01-13 20:22:57 +01:00
Michael SchättgenandGitHub 38bbb60414 Merge pull request #652 from alexbakker/fix-authy-import
Don't rely on accountType to detect proprietary Authy tokens
2021-01-13 20:11:22 +01:00
Alexander Bakker 98d39ee399 Downgrade zip4j to 2.6.0
It looks like we broke the Authenticator Plus importer in
d660fbc6d1 by upgrading zip4j. So this patch
downgrades it again. I couldn't immediately find this issue in their issue
tracker, so it may be worth spending some time reporting this to them later.
2021-01-12 21:27:24 +01:00
Alexander Bakker e324f649ee Replace the FAB with a bottom sheet dialog
This also removes the dependency on ``com.getbase:floatingactionbutton``.
2021-01-10 14:49:24 +01:00
Alexander Bakker 4f8a0b9020 Add some more tests
This adds tests for all of the importers, a new scrypt test and some more OTP tests. More to come.
2021-01-10 14:47:27 +01:00
Alexander Bakker b78b22acbb Explicitly opt out of WebView usage statistics collection 2021-01-09 15:58:21 +01:00
Alexander Bakker 737b9da292 Use name() instead of toString() on StandardCharsets.UTF_8
Apparently toString() doesn't produce the same result on every platform.
2021-01-08 17:38:02 +01:00
Alexander BakkerandGitHub dea13f56f5 Merge pull request #659 from deadmeu/fix-fullscreen-styles
Add dark theme variants of the fullscreen style
2021-01-07 20:11:55 +01:00
deadmeu 1f0c51b45b Add dark theme variants of the fullscreen style 2021-01-08 00:27:16 +10:00
Alexander Bakker 466e296988 Fix indentation of feature list format of the F-Droid app description 2021-01-06 17:47:39 +01:00
Alexander Bakker fb17f48013 Fix feature list format of the F-Droid app description 2021-01-06 17:30:36 +01:00
Alexander Bakker f203eab3ef Update F-Droid app description 2021-01-06 16:28:56 +01:00
Alexander Bakker 1bd9cf3a3f Release v1.4.1
Build / build (push) Canceled after 0s
2021-01-04 18:59:47 +01:00
Michael SchättgenandGitHub a795015487 Merge pull request #626 from alexbakker/update-deps-2
Update dependencies
2021-01-03 23:55:09 +01:00
Alexander Bakker 0a6c89cd9d Show a clearer error message when encountering phonefactor:// URI's
Sometimes users get confused when they're trying to scan a Microsoft Authenticator QR code and think the error occurs because of a bug in Aegis.
2021-01-03 19:58:39 +01:00
Alexander Bakker 951241e95d Don't rely on accountType to detect proprietary Authy tokens 2021-01-02 14:55:26 +01:00
Alexander Bakker ddbe9ccfb7 Fix ADB command in CONTRIBUTING.md 2021-01-01 12:57:20 +01:00
Alexander Bakker 1d44e05866 Remove the "search in account names" option and do so by default 2020-12-27 20:34:04 +01:00
Alexander Bakker 4482a21a54 Simplify the auto lock block logic and show an error if DocumentsUI is missing 2020-12-27 20:24:40 +01:00
Alexander Bakker 15e28abecd Update dependencies
This also disables the Jetifier, because we don't need it anymore.
2020-12-26 16:49:30 +01:00
Alexander Bakker 1748e2221f Release v1.4
Build / build (push) Canceled after 0s
2020-12-26 15:58:18 +01:00
Alexander Bakker b1b4c021cf Update translations from Crowdin 2020-12-26 15:41:34 +01:00
Michael SchättgenandGitHub a27e3c6364 Merge pull request #642 from alexbakker/block-minimize-lock
Fix an issue where the app would lock when showing DocumentsUI
2020-12-26 15:36:48 +01:00
Michael SchättgenandGitHub 8f7b152af4 Merge pull request #641 from alexbakker/fix-593-extra
Use GoogleAuthInfo.parseSecret for secrets from Google Authenticator
2020-12-26 15:23:13 +01:00
Michael SchättgenandGitHub 39f18b79cb Merge pull request #636 from alexbakker/libsu-mount-ns
Run libsu commands inside the global mount namespace
2020-12-26 15:18:28 +01:00
Michael SchättgenandGitHub 9a81cccbe2 Merge pull request #623 from alexbakker/fixup-gauth-proto
Make the Google Authenticator Protobuf parser more complete
2020-12-26 15:18:00 +01:00
Michael SchättgenandGitHub 2c6be39f88 Merge pull request #634 from alexbakker/fix-package-query
Explicitly define which packages (apps) we want to query
2020-12-26 15:15:00 +01:00
Michael SchättgenandGitHub a6299ffb5f Merge pull request #627 from alexbakker/pass-popup-position
Display the password reminder popup on top instead of the bottom
2020-12-26 15:14:06 +01:00
Alexander Bakker 6e5a80a000 Fix an issue where the app would lock when showing DocumentsUI 2020-12-26 13:22:40 +01:00
Alexander Bakker f012c7ce22 Use GoogleAuthInfo.parseSecret for secrets from Google Authenticator 2020-12-26 12:25:43 +01:00
Alexander Bakker 805a9001e1 Run libsu commands inside the global mount namespace
This ensures we're able to access other app's internal storage directories using libsu when running on Android 11 or newer.
2020-12-20 13:53:34 +01:00
Alexander Bakker 884a1d07c4 Explicitly define which packages (apps) we want to query
This is necessary to be able to see if the app a user wants to import from is installed.
See: https://developer.android.com/about/versions/11/privacy/package-visibility
2020-12-19 13:21:21 +01:00
Alexander Bakker e9f6371885 Display the password reminder popup on top instead of the bottom
This prevents the Android's autofill popup from occluding our popup
2020-12-12 13:44:23 +01:00
Michael Schättgen 1f2e45fd12 Add GitHub action and remove Travis config 2020-12-12 11:32:50 +01:00
Alexander Bakker 6a5323b12b Make the Google Authenticator Protobuf parser more complete
I don't think Google Authenticator actually currently supports any of these
extra digit/algorithm options, but they're specified in the proto file, so we
should support them for completeness sake.
2020-12-07 21:28:27 +01:00
Alexander Bakker 735c086726 Release v1.4-beta2 2020-12-04 22:10:04 +01:00
Alexander Bakker d94be2420c Downgrade Android Gradle plugin to 4.0.1 to fix a crash 2020-12-04 22:07:07 +01:00
Alexander Bakker 0b6da5a93c Prevent file provider name collision (for debug builds) 2020-12-04 22:03:58 +01:00
Alexander Bakker d24e1471a7 Release v1.4-beta1 2020-12-04 20:49:51 +01:00
Alexander Bakker 7ca072a29c Update translations from Crowdin 2020-12-04 20:29:55 +01:00
Alexander Bakker d5ac447332 Update Android Gradle plugin to fix the build 2020-12-04 20:08:53 +01:00
Alexander BakkerandGitHub 0067c79dfa Merge pull request #618 from alexbakker/backup-thread
Move the creation of exports/backups to a background thread
2020-12-04 10:48:03 +01:00
Alexander Bakker 4e198d2556 Move the creation of exports/backups to a background thread
This writes exports/backups to the cache directory first and then hands off to a
background thread to pipe the file to SAF. I'm cheating a bit, but it's the
easiest fix with our current architecture. In the future, we should skip the
first step by making VaultManager itself thread-safe.
2020-12-03 22:16:35 +01:00
Michael SchättgenandGitHub f15a0018ef Merge pull request #605 from alexbakker/highlight-on-add
After adding a new entry, scroll to it and highlight it
2020-12-03 21:48:48 +01:00
Alexander Bakker d121139676 After adding a new entry, scroll to it and highlight it 2020-11-30 20:08:09 +01:00
Alexander BakkerandGitHub 98b246ad20 Merge pull request #616 from richardk85/richardk85-tap-to-reveal-min-1
"Tap to reveal": change min duration from 3 to 1
2020-11-24 17:03:26 +01:00
Jay bce0d2c044 "Tap to reveal": change min duration from 3 to 1 2020-11-24 14:26:16 +01:00
Michael SchättgenandGitHub bf91917745 Merge pull request #604 from alexbakker/export-plain
Improve the export functionality in numerous ways
2020-11-08 21:18:50 +01:00
Michael SchättgenandGitHub a91339de73 Merge pull request #603 from alexbakker/resize-qr-image
Resize images to a max res of 640x480 before scanning for QR codes
2020-11-07 21:06:11 +01:00
Michael SchättgenandGitHub 5d9de7ac32 Merge pull request #602 from alexbakker/qr-multi-intent
Combine ACTION_PICK and ACTION_GET_CONTENT when selecting an image to scan
2020-11-07 20:51:26 +01:00
Alexander Bakker 5f2529ea33 Improve the export functionality in numerous ways
This patch improves the export functionality in the following ways:
1. Allow setting a password even if the Aegis vault is not encrypted
2. Display a scary warning when exporting an unencrypted vault
3. Support exporting to a Google Authenticator URI file
4. Option to use Android's share mechanism

<img src="https://alexbakker.me/u/375oh146vz.png" width="300" />
2020-10-30 23:03:10 +01:00
Michael SchättgenandGitHub 61364b5542 Merge pull request #601 from alexbakker/importer-help
Display some help text in the importer selection dialog
2020-10-30 21:10:36 +01:00
Alexander Bakker 69196ddbcc Display some help text in the importer selection dialog 2020-10-30 16:11:53 +01:00
Alexander BakkerandGitHub b21b6dc750 Merge pull request #574 from michaelschattgen/feature/panic-trigger
Add panic trigger which deletes vault
2020-10-30 12:21:58 +01:00
Michael Schättgen e14a61dbf6 Add panic trigger which deletes vault
Add guardianproject fdroid signing key and minor review improvements

Add minor review fixes

Add panic trigger which deletes vault

Add guardianproject fdroid signing key and minor review improvements
2020-10-30 11:46:28 +01:00
Michael SchättgenandGitHub e8f94968c9 Merge pull request #600 from alexbakker/fix-593
Strip " " and "-" when parsing secrets
2020-10-29 22:08:58 +01:00
Michael SchättgenandGitHub 8b7e5d265b Merge pull request #592 from alexbakker/update-deps
Update dependencies
2020-10-29 22:03:26 +01:00
Alexander Bakker 22a70ac626 Resize images to a max res of 640x480 before scanning for QR codes
I'm not sure why this works, but ZXing seems to have trouble with high
resolution images. For example, scanning a 4032x3024 image with a QR code in it
fails, but scanning a resized version of that exact same image works.
2020-10-25 15:01:39 +01:00
Alexander Bakker dd83b74251 Combine ACTION_PICK and ACTION_GET_CONTENT when selecting an image to scan
Also, only scan for QR codes, not all bar codes that ZXing supports.
2020-10-25 14:48:56 +01:00
Alexander Bakker 5a9da45a8e Strip " " and "-" when parsing secrets 2020-10-24 14:25:10 +02:00
Alexander Bakker cac13b082e Bump target SDK to 30 and update dependencies 2020-10-22 15:11:45 +02:00
Alexander BakkerandGitHub 86c3c401ae Merge pull request #595 from orangenbaumblatt/feature/backup-successful-toast
Show toast message if backup was created successfully
2020-10-04 12:52:44 +02:00
orangenbaumblatt 33ff7da7af Show toast message if backup was created successfully 2020-10-04 01:11:21 +02:00
Michael SchättgenandGitHub 0af48f8bfa Merge pull request #591 from alexbakker/fix-pin-on-pass-change
Reset the PIN keyboard option when the password is changed
2020-09-22 16:35:17 +02:00
Alexander Bakker 01885e1fc6 Reset the PIN keyboard option when the password is changed
This fixes an issue where the PIN keyboard was shown after a password change,
regardless of whether it only contained digits or not.
2020-09-21 18:09:07 +02:00
Michael SchättgenandGitHub 52d2713482 Merge pull request #564 from alexbakker/improve-auto-lock
Improve auto lock and make it more customizable
2020-08-26 16:51:40 +02:00
Alexander Bakker d875cb6baa Improve auto lock and make it more customizable
This patch makes the auto lock option more customizable. Users can now choose a
combination of the following: Locking Aegis when
- The back button is pressed
- The app is minimized
- The device is locked

<img src="https://alexbakker.me/u/rlj4y2u8pk.png" width="300">
2020-08-26 14:20:09 +02:00
Alexander BakkerandGitHub 0cdb882991 Merge pull request #573 from michaelschattgen/feature/theme-improvements
Minor color improvements for dark themes
2020-08-16 19:06:10 +02:00
Michael Schättgen 31d382d6ad Minor color improvements for dark themes 2020-08-16 18:22:16 +02:00
Alexander BakkerandGitHub 141f491ca7 Merge pull request #571 from michaelschattgen/feature/wipe-entries
Add checkbox dialog to wipe vault before import
2020-08-16 17:58:21 +02:00
Michael SchättgenandGitHub c0bbe50996 Merge pull request #572 from alexbakker/fix-159
Prevent a crash on rotation while a ProgressDialogTask is still running
2020-08-16 15:59:13 +02:00
Michael SchättgenandGitHub 875c752f78 Merge pull request #570 from alexbakker/fix-double-add-crash
Prevent a crash caused by adding the same entry to the vault twice
2020-08-16 15:41:51 +02:00
Michael SchättgenandGitHub 1d00a2d8d6 Merge pull request #569 from alexbakker/slot-tests
Add tests for the Slot classes
2020-08-16 15:40:37 +02:00
Michael SchättgenandGitHub 14407412bf Merge pull request #568 from alexbakker/deep-link-tests
Add tests for deep links and fix a minor issue
2020-08-16 15:40:16 +02:00
Alexander Bakker bb2716f640 Prevent a crash on rotation while a ProgressDialogTask is still running
This patch ensures ProgressDialogs are dismissed when the ON_PAUSE event is fired.
2020-08-16 15:20:43 +02:00
Michael Schättgen 0f6b0dddbe Add checkbox dialog to wipe vault before import
Only show dialog when vault contains entries

Add improvements from review
2020-08-16 15:20:34 +02:00
Alexander Bakker d43e5e04c7 Prevent a crash caused by adding the same entry to the vault twice
This could happen in rare cases where writing the vault to disk failed.
2020-08-15 18:38:24 +02:00
Alexander Bakker 4c86e154c1 Add tests for the Slot classes 2020-08-15 18:07:34 +02:00
Alexander Bakker a45c834b9c Add UI tests for deep links 2020-08-15 17:10:37 +02:00
Alexander Bakker b746ca0c6e Ignore deep link intents if the given URI is null 2020-08-15 17:10:33 +02:00
Alexander BakkerandGitHub 7d38bc9b71 Merge pull request #567 from michaelschattgen/feature/group-manager-improvement
Add empty state for GroupManagerActivity
2020-08-13 19:18:49 +02:00
Alexander BakkerandGitHub 9557b60c93 Merge pull request #566 from michaelschattgen/feature/fix-fab
Fix hidden FAB when list changes
2020-08-13 19:05:31 +02:00
Michael Schättgen 227b5fd87c Improve GroupManagerActivity 2020-08-13 18:16:23 +02:00
Michael Schättgen 7d063104dd Fix hidden FAB when list changes 2020-08-13 13:06:20 +02:00
Michael SchättgenandGitHub c03d00695d Merge pull request #563 from alexbakker/fix-lint-errors
Replace use of android:tint with app:tint to fix lint errors
2020-08-12 17:32:04 +02:00
Michael SchättgenandGitHub 171c774b21 Merge pull request #562 from alexbakker/activity-test-rule
Don't use deprecated ActivityTestRule in UI tests
2020-08-12 17:31:52 +02:00
Alexander Bakker 97944aac88 Replace use of android:tint with app:tint to fix lint errors 2020-08-12 13:14:37 +02:00
Michael SchättgenandGitHub ca21e0bdd1 Merge pull request #561 from alexbakker/deps
Update Gradle and dependencies
2020-08-12 13:03:34 +02:00
Alexander Bakker 83c1914ddc Don't use deprecated ActivityTestRule in UI tests 2020-08-12 13:00:55 +02:00
Alexander Bakker d660fbc6d1 Update Gradle and dependencies 2020-08-12 12:54:13 +02:00
Alexander Bakker 35b5ce9d17 Release v1.3 2020-08-10 19:10:44 +02:00
Alexander Bakker 762fb9bccd Update translations from Crowdin 2020-08-10 19:08:47 +02:00
Alexander Bakker c3d38c18a3 Update the list of licenses of our dependencies 2020-08-10 18:49:53 +02:00
Michael SchättgenandGitHub 7a3ad11902 Merge pull request #558 from alexbakker/more-plurals
Convert pref_backups_versions_summary to a plurals definition
2020-08-08 12:33:18 +02:00
Alexander Bakker 28fcd68b72 Convert pref_backups_versions_summary to a plurals definition 2020-08-08 12:15:52 +02:00
Michael SchättgenandGitHub c2ed4b4849 Merge pull request #555 from alexbakker/update-contributing
Update contributing guidelines
2020-08-06 12:31:39 +02:00
Michael SchättgenandGitHub 9bbc2886c2 Merge pull request #503 from shihern/master
Improve usability of drag-and-drop feature
2020-08-06 12:13:03 +02:00
Connor Lim 5886462d2c Improve usability of drag-and-drop feature 2020-08-07 00:20:38 +08:00
Michael SchättgenandGitHub 98e8a0d97e Merge pull request #554 from alexbakker/plurals
Replace some string definitions with plurals definitions
2020-08-06 11:05:09 +02:00
Alexander Bakker 0368a992de Update contributing guidelines
This adds a blurb about translations to CONTRIBUTING.md and rewords some
sentences there. I also added a Contributing section to the README.
2020-08-05 16:44:37 +02:00
Alexander Bakker 233eeb6aa1 Replace some string definitions with plurals definitions 2020-08-05 13:28:23 +02:00
Alexander Bakker e5d162be9b Update translations (from Crowdin) 2020-08-05 12:00:08 +02:00
Alexander BakkerandGitHub 718d575a59 Merge pull request #552 from theRealPadster/master
Grammar fix (setup -> set up)
2020-08-04 20:22:02 +02:00
Isaac Maier 59e8c23a01 Grammar fix (setup -> set up) 2020-08-04 14:06:21 -04:00
Michael SchättgenandGitHub 847009d733 Merge pull request #548 from alexbakker/travis-disable-ui-tests
Disable UI tests on Travis CI
2020-08-03 23:37:44 +02:00
Alexander Bakker ce3d674da8 Disable UI tests on Travis CI
Unfortunately, the UI tests are just too unstable, so this patch excludes them
from being run on Travis. The tests run fine on our personal machines, but
produce seemingly random errors on Travis CI.
2020-08-02 21:32:03 +02:00
Alexander Bakker 9e4313e138 Release v1.3-beta2 2020-08-02 12:29:01 +02:00
Alexander Bakker 02e01723b2 Invert PIN keyboard preference if statement 2020-08-02 12:27:25 +02:00
Alexander Bakker 874f5e9058 Remove merge conflict marker from styles.xml 2020-08-01 19:50:18 +02:00
396 changed files with 28640 additions and 7051 deletions
+4 -1
View File
@@ -1 +1,4 @@
custom: ['https://www.buymeacoffee.com/beemdevelopment']
custom:
- "https://www.buymeacoffee.com/beemdevelopment"
- "https://www.blockchain.com/btc/address/bc1q26kyxqjkc6tu477pzy0whagwhs4ypv93qls22n"
- "https://nanocrawler.cc/explorer/account/nano_1aegisc559b1x4p3839egnu579jkd4htpidy14eo9e31gzqmwuafypnj4q94"
-34
View File
@@ -1,34 +0,0 @@
---
name: "Bug report"
about: "Create a report to help us fix a bug"
labels: bug
---
<!-- Please read the [bug reports section of the contribution
guidelines](/CONTRIBUTING.md#bug-reports) before submitting an issue. -->
###### Info
* __Version__:
* __Source__: (Google Play/GitHub/F-Droid/?)
* __Vault encrypted:__ Yes (with biometric unlock)/Yes/No
* __Device:__
* __Android version and ROM:__
###### Steps to reproduce
A detailed list of reproduction steps.
###### What do you expect to happen?
...
###### What happens instead?
...
###### Log
```
If applicable, paste the debug log here.
```
+89
View File
@@ -0,0 +1,89 @@
name: Bug Report
description: Create a report to help us fix a bug
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Please read the [bug reports section of the contribution guidelines](https://github.com/beemdevelopment/Aegis/blob/master/CONTRIBUTING.md#bug-reports) before submitting an issue.
- type: input
id: version
attributes:
label: Version
description: Which version of Aegis are you using?
placeholder: "Example: v2.1"
validations:
required: true
- type: dropdown
id: source
attributes:
label: Source
description: Where did you get Aegis from?
options:
- Google Play
- F-Droid
- GitHub
- Other
validations:
required: true
- type: dropdown
id: encryption
attributes:
label: Vault encryption
description: Do you have encryption enabled for your Aegis vault?
options:
- "Yes (with biometric unlock)"
- "Yes"
- "No"
validations:
required: true
- type: input
id: device
attributes:
label: Device
description: Which device are you using Aegis on?
placeholder: "Example: Pixel 5"
validations:
required: true
- type: input
id: android_version
attributes:
label: Android version
description: Which Android version is running on your device?
placeholder: "Example: Android 13"
validations:
required: true
- type: input
id: rom
attributes:
label: ROM
description: Are you using a custom ROM? If so, which one and which version? If you're using the stock OS that came with your device, you can leave this field empty.
placeholder: "Example: GrapheneOS"
validations:
required: false
- type: textarea
id: reproduction_steps
attributes:
label: Steps to reproduce
description: A detailed list of reproduction steps.
validations:
required: true
- type: textarea
id: expectations
attributes:
label: What do you expect to happen?
validations:
required: true
- type: textarea
id: reality
attributes:
label: What happens instead?
validations:
required: true
- type: textarea
id: log
attributes:
label: Log
description: If applicable, paste the debug log that you captured using ADB here.
validations:
required: false
+57
View File
@@ -0,0 +1,57 @@
name: build
on: [pull_request, push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout the code
uses: actions/checkout@v3
- name: Validate Gradle wrapper
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b
- name: Build the app
run: ./gradlew build
- uses: actions/upload-artifact@v3
with:
name: apk
path: app/build/outputs/apk/debug/app-debug.apk
test:
runs-on: macos-latest
# This is probably pretty expensive for GitHub, so restrict the repositories that this job runs on
if: github.repository == 'beemdevelopment/Aegis' || github.repository == 'alexbakker/Aegis'
steps:
- name: Checkout
uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
java-version: '11'
distribution: 'temurin'
cache: 'gradle'
- name: Install HAXM
run: brew install --cask intel-haxm
- name: Tests
uses: reactivecircus/android-emulator-runner@e790971012b979513b4e2fe70d4079bc0ca8a1ae
with:
api-level: 31
arch: x86_64
profile: pixel_3a
heap-size: 512M
ram-size: 4096M
emulator-options: -memory 4096 -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
disable-animations: true
disk-size: 8G
script: |
mkdir -p artifacts/report
adb logcat -c
adb logcat -G 16M && adb logcat -g
./gradlew connectedCheck || touch tests_failing
adb logcat -d > artifacts/logcat.txt
cp -r app/build/reports/androidTests/connected/* artifacts/report/
if adb shell '[ -e /sdcard/Pictures/screenshots ]'; then adb pull /sdcard/Pictures/screenshots artifacts/; fi
# test ! -f tests_failing
- uses: actions/upload-artifact@v3
if: always()
with:
name: instrumented-test-report
path: |
artifacts/*
if-no-files-found: ignore
+36
View File
@@ -0,0 +1,36 @@
name: codeql
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
schedule:
- cron: '25 16 * * 2'
jobs:
analyze:
name: analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Exclude paths
# The importers are excluded from analysis, because some of the apps Aegis
# can import from don't have such great crypto, which will cause false
# positive security alerts.
run: |
find app/src/main/java/com/beemdevelopment/aegis/importers ! \( -name AegisImporter.java -o -name "DatabaseImporter*" \) -type f -exec rm -f {} +
sed -i '/Importer.class/d' app/src/main/java/com/beemdevelopment/aegis/importers/DatabaseImporter.java
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: java
- name: Build
run: ./gradlew assembleDebug
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{matrix.language}}"
+31
View File
@@ -0,0 +1,31 @@
name: crowdin
on:
push:
branches:
- master
# run sequentially (per branch)
concurrency: "crowdin-upload-${{ github.ref }}"
jobs:
upload-sources:
runs-on: ubuntu-latest
if: github.repository == 'beemdevelopment/Aegis'
steps:
- uses: actions/checkout@v3
- name: Install crowdin-cli
run: |
wget https://github.com/crowdin/crowdin-cli/releases/download/3.7.2/crowdin-cli.zip
echo "ee9f838b819ccedc33c9b2537055e5ba7d7934561b24df1e1a6274cbd6e27f2d crowdin-cli.zip" | sha256sum -c
unzip crowdin-cli.zip -d crowdin-cli
- name: Upload to Crowdin
env:
CROWDIN_TOKEN: "${{ secrets.CROWDIN_TOKEN }}"
run: |
java -jar ./crowdin-cli/3.7.2/crowdin-cli.jar upload sources \
--no-progress \
--token "$CROWDIN_TOKEN" \
--project-id 372633 \
--base-path app/src/main \
--source res/values/strings.xml \
--translation "res/values-%android_code%/%original_file_name%" \
--dest strings.xml \
--branch master
-55
View File
@@ -1,55 +0,0 @@
language: shell
os: linux
dist: bionic
env:
global:
- TERM=dumb
- ABI=x86_64
- EMU_FLAVOR=default
- ADB_INSTALL_TIMEOUT=16
- ANDROID_HOME=${HOME}/android
- ANDROID_SDK_ROOT=${ANDROID_HOME}
- TOOLS=${ANDROID_HOME}/cmdline-tools
- PATH=${ANDROID_HOME}/emulator:${TOOLS}/tools/bin:${ANDROID_HOME}/platform-tools:${PATH}
jobs:
- API=21
- API=23
#- API=25 <- inconsistent
- API=27
- API=28
#- API=29 <- emulator crashes
#- API=R EMU_FLAVOR=google_apis <- too heavy, re-enable when AOSP image is available
before_install:
- mkdir -p ${ANDROID_HOME}/licenses
- echo "8933bad161af4178b1185d1a37fbf41ea5269c55" > ${ANDROID_HOME}/licenses/android-sdk-license
- echo "d56f5187479451eabf01fb78af6dfcb131a6481e" >> ${ANDROID_HOME}/licenses/android-sdk-license
- echo "24333f8a63b6825ea9c5514f83c2829b004d1fee" >> ${ANDROID_HOME}/licenses/android-sdk-license
install:
- mkdir -p ${TOOLS}
- travis_retry wget https://dl.google.com/android/repository/commandlinetools-linux-6514223_latest.zip -O ${TOOLS}/tools.zip
- unzip ${TOOLS}/tools.zip -d ${TOOLS}
- yes | travis_retry sdkmanager "platform-tools" > /dev/null
- yes | travis_retry sdkmanager "tools" > /dev/null
- yes | travis_retry sdkmanager "build-tools;29.0.2" > /dev/null
- yes | travis_retry sdkmanager "platforms;android-29" > /dev/null
- yes | travis_retry sdkmanager "emulator" > /dev/null
- yes | travis_retry sdkmanager "system-images;android-$API;$EMU_FLAVOR;$ABI" > /dev/null
- travis_retry sudo apt-get -yq --no-install-suggests install qemu-kvm
before_script:
- sudo gpasswd -a $USER kvm
script:
- ./gradlew assemble check
- echo no | avdmanager create avd --force -n test -k "system-images;android-$API;$EMU_FLAVOR;$ABI" -d "Nexus 5X" -c 128M
- sudo -E sudo -u $USER -E bash -c "${ANDROID_HOME}/emulator/emulator -verbose -avd test -gpu swiftshader_indirect -no-audio -no-boot-anim -no-snapshot -no-window -camera-back none -camera-front none -selinux permissive -memory 3072 &"
- adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;'
- adb shell settings put global window_animation_scale 0
- adb shell settings put global transition_animation_scale 0
- adb shell settings put global animator_duration_scale 0
- adb reboot
- adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;'
- adb shell input keyevent 82 &
- bash .travis/android-wait-for-launcher.sh
- adb logcat -c
- ./gradlew connectedCheck
after_failure:
- adb logcat -d
-33
View File
@@ -1,33 +0,0 @@
#!/bin/bash
# source: https://gist.github.com/d4vidi/7862d60375b38f8970f824c4ce0ad2a9
echo ""
echo "[Waiting for launcher to start]"
LAUNCHER_READY=
while [[ -z ${LAUNCHER_READY} ]]; do
UI_FOCUS=`adb shell dumpsys activity activities 2>/dev/null | grep -i mResumedActivity`
echo "(DEBUG) Current focus: ${UI_FOCUS}"
case $UI_FOCUS in
*"Launcher"*)
LAUNCHER_READY=true
;;
"")
echo "Waiting for window service..."
sleep 3
;;
*"Not Responding"*)
echo "Detected an ANR! Dismissing..."
adb shell input keyevent KEYCODE_DPAD_DOWN
adb shell input keyevent KEYCODE_DPAD_DOWN
adb shell input keyevent KEYCODE_ENTER
;;
*)
echo "Waiting for launcher..."
sleep 3
;;
esac
done
echo "Launcher is ready :-)"
+32 -14
View File
@@ -1,25 +1,42 @@
# Contributing
There are a couple of ways to contribute to Aegis. This document contains some
general guidelines for each type of contribution.
Looking to contribute to Aegis? That's great! There are a couple of ways to help
out. This document contains some general guidelines for each type of
contribution.
Please review [the FAQ](FAQ.md) before reporting a bug, asking a question or
requesting a feature.
## Translations
We use [Crowdin](https://crowdin.com/project/aegis-authenticator) to crowdsource
translations of Aegis for lots of different languages. __Pull requests that
add/update a translation are no longer accepted.__ Crowdin is our single source
of truth for translations, to keep things easy to maintain.
The top 30 languages are available for translation. It's possible that yours is
not in that list. If that's the case, feel free to send us an email and we'll
add it.
## Pull requests
If you're planning on adding a new feature or making other large changes, please
discuss it with us first through a proposal on GitHub. Discussing your idea with
us first ensures that everyone is on the same page before you start working on
your change. We don't like rejecting pull requests.
discuss it with us first through [a
proposal](https://github.com/beemdevelopment/Aegis/issues/new?labels=proposal&template=feature.md)
on GitHub. Discussing your idea with us first ensures that everyone is on the
same page before you start working on your change. We don't like rejecting pull
requests.
## Bug reports
We use GitHub's issue tracker to track bugs. Bug reports must follow [the
template](.github/ISSUE_TEMPLATE/bug.md). If a bug report does not follow the
template and does not contain enough information, it will be closed without a
response. Duplicate bug reports receive the same treatment.
We use GitHub's issue tracker to track bugs. To make bug reports easier to
follow up on for us, please fill out the form as accurately as possible. If a
bug report does not contain enough information, it will be closed. Duplicate bug
reports receive the same treatment.
Please consider trying to find the root cause yourself first and perhaps even
send us a patch that fixes the issue! We're happy to help you if you get stuck
along the way.
Please consider trying to find the root cause yourself first and include your
analysis of the issue in your report. Perhaps even send us a patch that fixes
it! We're happy to help you if you get stuck along the way.
### Capturing a log with ADB
@@ -81,7 +98,7 @@ __On your PC__:
```
adb logcat -c
adb logcat -f debug.log
adb logcat > debug.log
```
The logcat command captures the full system log by default, which may expose
@@ -91,8 +108,9 @@ __On your PC__:
one below:
```sh
adb logcat --pid=$(adb shell pidof -s com.beemdevelopment.aegis) -f debug.log
adb logcat --pid=$(adb shell pidof -s com.beemdevelopment.aegis) > debug.log
```
_If you are using a debug APK, replace ``com.beemdevelopment.aegis`` with
``com.beemdevelopment.aegis.debug``._
+101
View File
@@ -0,0 +1,101 @@
# FAQ
## General
### How can I contribute?
There are lots of ways! Please refer to our [contributing
guide](https://github.com/beemdevelopment/Aegis/blob/master/CONTRIBUTING.md).
### Why is the latest version not on F-Droid yet?
We don't release new versions of Aegis on F-Droid ourselves. Once we've released
a new version on GitHub, F-Droid will usually kick off their automatic build
process a day later and publish the app to their repository a couple of days
afterwards. It can sometimes take up to a week for a new version to appear on
F-Droid.
### Can you port Aegis to iOS/Windows/MacOS/Browser Extension?
We don't have plans to port Aegis to other platforms.
### Can you add support for Autofill?
On Android, only one app can be active in the Autofill slot at a time, and since
this is typically occupied by the password manager, we don't see much value in
adding support for this feature in Aegis.
### What is the difference between exporting and backing up?
Exporting is done manually and backups are done automatically. The format of the
vault file is exactly the same for both.
## Security
### I can no longer use biometrics to unlock the app. What should I do?
If you could previously unlock Aegis with biometrics, but suddenly can't do so
anymore, this is probably caused by a change made to the security settings of
your device. The app will tell you when this happened in most cases. To resolve
this, unlock the app with your password, disable biometric unlock in the
settings of Aegis and re-enable it.
### Why does Aegis keep prompting me for my password, even though I have enabled biometric authentication?
You're probably encountering the password reminder. Try entering your password
to unlock the vault once. After that, Aegis will prompt for biometrics by
default again until it's time for another password reminder.
Since forgetting your password will result in loss of access to the contents of
the vault, __we do NOT recommend disabling the password reminder__.
### Aegis uses SHA1 for most/all of my tokens. Isn't that insecure?
The hash algorithm is imposed by the service you're setting up 2FA for (e.g.
Google, Facebook, GitHub, etc). There is nothing we can do about that. If we
were to change this on Aegis' end, the tokens would stop working. Furthermore,
when using SHA1 in an HMAC calculation, the currently known issues in SHA1 are
not of concern.
### Why doesn't Aegis support biometric unlock for my device, even though it works with other apps?
The reason for this is pretty technical. In short, since you're not entering
your password when using biometric unlock, Aegis needs some other way to decrypt
the vault. For this purpose, we generate and use a key in the Android Keystore,
telling it to only allow us to use that key if the user authenticates using
their biometrics first. Some devices have buggy implementations of this feature,
resulting in the error displayed to you by Aegis in an error dialog.
If biometrics works with other apps, but not with Aegis, that means those other
apps probably perform a weaker form of biometric authentication.
## Backups
### How can I back up my Aegis vault to the cloud automatically?
Aegis can only automatically back up to the cloud of the app of your cloud
provider is installed on your device and fully participates in the Android
Storage Access Framework. Aegis doesn't have access to the internet and we don't
have plans to change this, so adding support for specific cloud providers in the
app is not possible.
Cloud providers currently known to be supported:
- Nextcloud
Another common setup is to configure Aegis to back up to a folder on local
storage of your device and then have a separate app (like
[Syncthing](https://syncthing.net/)) sync that folder anywhere you want.
## Importing
### When importing from Authenticator Plus, an error is shown claiming that Accounts.txt is missing
Make sure you supply an Authenticator Plus export file obtained through
__Settings -> Backup & Restore -> Export as Text and HTML__. The ``.db`` format
is not supported.
If it still doesn't work, please report the issue to us. As a temporary
workaround, you can try extracting the ZIP archive on a computer, recreating it
without a password and then importing that into Aegis. Another option is
extracting the ZIP archive on a computer and importing the resulting
Accounts.txt file into Aegis with the "Plain text" import option.
+38 -12
View File
@@ -1,7 +1,11 @@
<img align="left" width="80" height="80" src="metadata/en-US/images/icon.png"
alt="App icon">
# Aegis Authenticator [![CI](https://api.travis-ci.org/beemdevelopment/Aegis.svg?branch=master)](https://travis-ci.org/github/beemdevelopment/aegis) [![Crowdin](https://badges.crowdin.net/aegis-authenticator/localized.svg)](https://crowdin.com/project/aegis-authenticator) [![Donate](https://img.shields.io/badge/donate-buy%20us%20a%20beer-%23FF813F)](https://www.buymeacoffee.com/beemdevelopment) [![Matrix](https://img.shields.io/badge/chat-Matrix-blue)](https://matrix.to/#/#aegis:matrix.org)
# Aegis Authenticator
<br>
[![CI](https://img.shields.io/github/workflow/status/beemdevelopment/Aegis/build/master)](https://github.com/beemdevelopment/Aegis/actions/workflows/build-app-workflow.yaml?query=branch%3Amaster) [![Crowdin](https://badges.crowdin.net/aegis-authenticator/localized.svg)](https://crowdin.com/project/aegis-authenticator) [![Donate](https://img.shields.io/badge/donate-buy%20us%20a%20beer-%23FF813F)](https://www.buymeacoffee.com/beemdevelopment) [![Matrix](https://img.shields.io/matrix/aegis:matrix.org?color=blue)](https://matrix.to/#/#aegis:matrix.org)
__Aegis Authenticator__ is a free, secure and open source 2FA app for Android.
It aims to provide a secure authenticator for your online services, while also
@@ -9,6 +13,8 @@ including some features missing in existing authenticator apps, like proper
encryption and backups. Aegis supports HOTP and TOTP, making it compatible with
thousands of services.
For a list of frequently asked questions, please check out [the FAQ](FAQ.md).
The security design of the app and the vault format is described in detail in
[this document](docs/vault.md).
@@ -28,10 +34,10 @@ The security design of the app and the vault format is described in detail in
- Lots of ways to add new entries
- Scan a QR code or an image of one
- Enter details manually
- Import from other authenticator apps: Authenticator Plus, Authy, andOTP,
FreeOTP, FreeOTP+, Google Authenticator, Microsoft Authenticator, Plain
text, Steam, TOTP Authenticator and WinAuth (root access is required for
some of these)
- Import from other authenticator apps: 2FAS Authenticator, Authenticator
Plus, Authy, andOTP, FreeOTP, FreeOTP+, Google Authenticator, Microsoft
Authenticator, Plain text, Steam, TOTP Authenticator and WinAuth (root
access is required for some of these)
- Organization
- Alphabetic/custom sorting
- Custom or automatically generated icons
@@ -103,16 +109,36 @@ Certificate fingerprints:
SHA256: C6:DB:80:A8:E1:4E:52:30:C1:DE:84:15:EF:82:0D:13:DC:90:1D:8F:E3:3C:F3:AC:B5:7B:68:62:D8:58:A8:23
```
### Community
### Icon packs
- [aegis-icons](https://github.com/krisu5/aegis-icons)
Aegis supports icon packs to make it easier to assign icons to the entries in
your vault. There are no official icon packs, but the community maintains a
number of third-party icon packs you may want to check out. To learn how to
create your own Aegis-compatible icon pack, see [the
documentation](docs/iconpacks.md).
While we're still [working on better icon
support](https://github.com/beemdevelopment/Aegis/issues/509) in Aegis, krisu5
has started a third-party repository for icons that you may want to check out.
- [aegis-icons](https://github.com/aegis-icons/aegis-icons)
[<img width=500 alt="Aegis-icons preview"
src="https://raw.githubusercontent.com/krisu5/aegis-icons/master/showcase.png">](https://github.com/krisu5/aegis-icons)
Unofficial monochrome-styled 2FA icons.
[<img width=500 alt="aegis-icons preview"
src="https://raw.githubusercontent.com/aegis-icons/aegis-icons/master/showcase.png">](https://github.com/aegis-icons/aegis-icons)
- [aegis-simple-icons](https://github.com/alexbakker/aegis-simple-icons)
This project periodically generates an icon pack for Aegis based on [Simple
Icons](https://simpleicons.org/). The icons are automatically generated, so
not all of them are as high quality as the ones you'll find in
[aegis-icons](https://github.com/aegis-icons/aegis-icons).
## Contributing
Looking to contribute to Aegis? That's great! There are a couple of ways to help
out. Translations, bug reports and pull requests are all greatly appreciated.
Please refer to our [contributing guidelines](CONTRIBUTING.md) to get started.
Swing by our Matrix room to interact with other contributors:
[#aegis:matrix.org](https://matrix.to/#/#aegis:matrix.org).
## License
+104 -64
View File
@@ -1,5 +1,6 @@
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
apply plugin: 'dagger.hilt.android.plugin'
def getCmdOutput = { cmd ->
def stdout = new ByteArrayOutputStream()
@@ -13,64 +14,82 @@ def getCmdOutput = { cmd ->
def getGitHash = { -> return getCmdOutput(["git", "rev-parse", "--short", "HEAD"]) }
def getGitBranch = { -> return getCmdOutput(["git", "rev-parse", "--abbrev-ref", "HEAD"]) }
def packageName = "com.beemdevelopment.aegis"
def fileProviderAuthority = "${packageName}.fileprovider"
def fileProviderAuthorityDebug = "${packageName}.debug.fileprovider"
android {
compileSdkVersion 29
compileSdkVersion 33
namespace packageName
defaultConfig {
applicationId "com.beemdevelopment.aegis"
applicationId "${packageName}"
minSdkVersion 21
targetSdkVersion 29
versionCode 37
versionName "1.3-beta1"
targetSdkVersion 33
versionCode 55
versionName "2.1"
multiDexEnabled true
buildConfigField "String", "GIT_HASH", "\"${getGitHash()}\""
buildConfigField "String", "GIT_BRANCH", "\"${getGitBranch()}\""
buildConfigField "java.util.concurrent.atomic.AtomicBoolean", "TEST", "new java.util.concurrent.atomic.AtomicBoolean(false)"
testInstrumentationRunner "com.beemdevelopment.aegis.AegisTestRunner"
testInstrumentationRunnerArguments clearPackageData: 'true'
}
lintOptions {
abortOnError true
disable "MissingTranslation"
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
unitTests.all {
useJUnitPlatform()
unitTests {
all {
maxHeapSize "3g"
ignoreFailures false
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
ignoreFailures false
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
showExceptions true
exceptionFormat "full"
showCauses true
showStackTraces true
}
}
includeAndroidResources true
}
}
buildTypes {
debug {
applicationIdSuffix ".debug"
manifestPlaceholders = [title: "AegisDev", iconName: "ic_launcher_debug"]
manifestPlaceholders = [
title: "AegisDev",
iconName: "ic_launcher_debug",
fileProviderAuthority: "${fileProviderAuthorityDebug}"
]
buildConfigField("String", "FILE_PROVIDER_AUTHORITY", "\"${fileProviderAuthorityDebug}\"")
resValue "bool", "pref_secure_screen_default", "false"
postprocessing {
removeUnusedCode true
removeUnusedResources true
obfuscate false
optimizeCode false
proguardFiles getDefaultProguardFile('proguard-defaults.txt'), 'proguard-rules.pro'
}
}
release {
manifestPlaceholders = [title: "Aegis", iconName: "ic_launcher"]
manifestPlaceholders = [
title: "Aegis",
iconName: "ic_launcher",
fileProviderAuthority: "${fileProviderAuthority}"
]
buildConfigField("String", "FILE_PROVIDER_AUTHORITY", "\"${fileProviderAuthority}\"")
resValue "bool", "pref_secure_screen_default", "true"
postprocessing {
removeUnusedCode true
removeUnusedResources true
obfuscate false
optimizeCode true
proguardFiles getDefaultProguardFile('proguard-defaults.txt'), 'proguard-rules.pro'
}
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
// R8 doesn't remove these resources, so exclude them manually. This reduces APK size by 4MB.
resources {
excludes += ['/org/bouncycastle/pqc/**/*.properties']
}
}
@@ -79,6 +98,11 @@ android {
sourceCompatibility 1.8
coreLibraryDesugaringEnabled true
}
lint {
abortOnError true
checkDependencies true
disable 'MissingQuantity', 'MissingTranslation'
}
}
protobuf {
@@ -97,30 +121,40 @@ protobuf {
}
dependencies {
def cameraxVersion = '1.0.0-beta04'
def glideVersion = '4.11.0'
def guavaVersion = '29.0'
def junitVersion = '5.6.2'
def libsuVersion = '2.5.1'
def cameraxVersion = '1.1.0'
def glideVersion = '4.14.2'
def guavaVersion = '31.1'
def hiltVersion = '2.44'
def junitVersion = '4.13.2'
def libsuVersion = '5.0.3'
annotationProcessor 'androidx.annotation:annotation:1.1.0'
annotationProcessor 'androidx.annotation:annotation:1.5.0'
annotationProcessor "com.google.dagger:hilt-compiler:$hiltVersion"
annotationProcessor "com.github.bumptech.glide:compiler:${glideVersion}"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation "androidx.biometric:biometric:1.0.1"
implementation 'androidx.activity:activity:1.6.1'
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation "androidx.biometric:biometric:1.1.0"
implementation "androidx.camera:camera-camera2:$cameraxVersion"
implementation "androidx.camera:camera-lifecycle:$cameraxVersion"
implementation "androidx.camera:camera-view:1.0.0-alpha11"
implementation "androidx.camera:camera-view:1.1.0"
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "androidx.core:core:1.9.0"
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.documentfile:documentfile:1.0.1'
implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation "androidx.lifecycle:lifecycle-process:2.5.1"
implementation ('androidx.preference:preference:1.2.0') {
// See: https://issuetracker.google.com/issues/238425626
exclude group: 'androidx.lifecycle', module:'lifecycle-viewmodel'
exclude group: 'androidx.lifecycle', module:'lifecycle-viewmodel-ktx'
}
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation "androidx.viewpager2:viewpager2:1.0.0"
implementation 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
implementation 'com.getbase:floatingactionbutton:1.10.1'
implementation 'com.github.avito-tech:krop:0.44'
implementation 'com.caverock:androidsvg-aar:1.4'
implementation "com.google.dagger:hilt-android:$hiltVersion"
implementation 'com.github.avito-tech:krop:0.52'
implementation "com.github.bumptech.glide:annotations:${glideVersion}"
implementation "com.github.bumptech.glide:glide:${glideVersion}"
implementation("com.github.bumptech.glide:recyclerview-integration:${glideVersion}") {
@@ -129,30 +163,36 @@ dependencies {
implementation "com.github.topjohnwu.libsu:core:${libsuVersion}"
implementation "com.github.topjohnwu.libsu:io:${libsuVersion}"
implementation "com.google.guava:guava:${guavaVersion}-android"
implementation 'com.google.android.material:material:1.0.0'
implementation 'com.google.protobuf:protobuf-javalite:3.12.1'
implementation 'com.google.zxing:core:3.4.0'
implementation 'com.google.android.material:material:1.7.0'
implementation 'com.google.protobuf:protobuf-javalite:3.21.4'
implementation 'com.google.zxing:core:3.5.1'
implementation "com.mikepenz:iconics-core:3.2.5"
implementation 'com.mikepenz:material-design-iconic-typeface:2.2.0.5@aar'
implementation 'com.nulab-inc:zxcvbn:1.3.0'
implementation 'com.nulab-inc:zxcvbn:1.7.0'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'de.psdev.licensesdialog:licensesdialog:2.1.0'
implementation 'net.lingala.zip4j:zip4j:2.6.0'
implementation 'org.bouncycastle:bcprov-jdk15on:1.65'
implementation 'de.psdev.licensesdialog:licensesdialog:2.2.0'
implementation 'net.lingala.zip4j:zip4j:2.11.2'
implementation 'info.guardianproject.trustedintents:trustedintents:0.2'
implementation 'org.bouncycastle:bcprov-jdk18on:1.72'
implementation "org.simpleflatmapper:sfm-csv:8.2.3"
androidTestImplementation 'androidx.test:core:1.3.0-rc01'
androidTestImplementation 'androidx.test:runner:1.3.0-rc01'
androidTestImplementation 'androidx.test:rules:1.3.0-rc01'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0'
androidTestImplementation 'junit:junit:4.13'
androidTestUtil 'androidx.test:orchestrator:1.3.0-rc01'
androidTestAnnotationProcessor "com.google.dagger:hilt-android-compiler:$hiltVersion"
androidTestImplementation "com.google.dagger:hilt-android-testing:$hiltVersion"
androidTestImplementation 'androidx.test:core:1.5.0'
androidTestImplementation 'androidx.test:runner:1.5.0'
androidTestImplementation 'androidx.test:rules:1.5.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.5.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.5.0'
androidTestImplementation "junit:junit:${junitVersion}"
androidTestUtil 'androidx.test:orchestrator:1.4.2'
testImplementation 'androidx.test:core:1.5.0'
testImplementation "com.google.guava:guava:${guavaVersion}-jre"
testImplementation "org.junit.jupiter:junit-jupiter-api:${junitVersion}"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${junitVersion}"
testImplementation "junit:junit:${junitVersion}"
testImplementation 'org.json:json:20220924'
testImplementation 'org.robolectric:robolectric:4.9'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}
+1
View File
@@ -3,4 +3,5 @@
<issue id="InvalidPackage">
<ignore regexp="X509LDAPCertStoreSpi" />
</issue>
<issue id="ResourceType" severity="Warning" />
</lint>
+4 -21
View File
@@ -1,24 +1,7 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /home/alex/Android/Sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
-keepclasseswithmembers public class androidx.recyclerview.widget.RecyclerView { *; }
-keep class com.beemdevelopment.aegis.ui.fragments.preferences.*
-keep class com.beemdevelopment.aegis.importers.** { *; }
-keep class * extends com.google.protobuf.GeneratedMessageLite { *; }
-keep class !org.bouncycastle.jce.provider.X509LDAPCertStoreSpi { *; }
-dontobfuscate
-dontwarn javax.naming.**
@@ -1,22 +1,162 @@
package com.beemdevelopment.aegis;
import android.Manifest;
import android.os.Build;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.test.espresso.UiController;
import androidx.test.espresso.ViewAction;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.GrantPermissionRule;
import com.beemdevelopment.aegis.crypto.CryptoUtils;
import com.beemdevelopment.aegis.crypto.SCryptParameters;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.SlotException;
import com.beemdevelopment.aegis.vectors.VaultEntries;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import java.lang.reflect.InvocationTargetException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.inject.Inject;
import dagger.hilt.android.testing.HiltAndroidRule;
public abstract class AegisTest {
protected AegisApplication getApp() {
return (AegisApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
public static final String VAULT_PASSWORD = "test";
public static final String VAULT_PASSWORD_CHANGED = "test2";
public static final String VAULT_BACKUP_PASSWORD = "something";
public static final String VAULT_BACKUP_PASSWORD_CHANGED = "something2";
@Rule
public HiltAndroidRule hiltRule = new HiltAndroidRule(this);
@Rule
public final GrantPermissionRule permRule = getGrantPermissionRule();
@Inject
protected VaultManager _vaultManager;
@Inject
protected Preferences _prefs;
@Before
public void init() {
hiltRule.inject();
}
protected VaultManager getVault() {
return getApp().getVaultManager();
private static GrantPermissionRule getGrantPermissionRule() {
List<String> perms = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
perms.add(Manifest.permission.POST_NOTIFICATIONS);
}
return GrantPermissionRule.grant(perms.toArray(new String[0]));
}
protected AegisApplicationBase getApp() {
return (AegisApplicationBase) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
}
protected VaultRepository initEncryptedVault() {
VaultFileCredentials creds = generateCredentials();
return initVault(creds, VaultEntries.get());
}
protected VaultRepository initEmptyEncryptedVault() {
VaultFileCredentials creds = generateCredentials();
return initVault(creds, null);
}
protected VaultRepository initPlainVault() {
return initVault(null, VaultEntries.get());
}
protected VaultRepository initEmptyPlainVault() {
return initVault(null, null);
}
private VaultRepository initVault(@Nullable VaultFileCredentials creds, @Nullable List<VaultEntry> entries) {
VaultRepository vault;
try {
vault = _vaultManager.initNew(creds);
} catch (VaultRepositoryException e) {
throw new RuntimeException(e);
}
if (entries != null) {
for (VaultEntry entry : entries) {
_vaultManager.getVault().addEntry(entry);
}
}
try {
_vaultManager.save();
} catch (VaultRepositoryException e) {
throw new RuntimeException(e);
}
_prefs.setIntroDone(true);
return vault;
}
protected VaultFileCredentials generateCredentials() {
PasswordSlot slot = new PasswordSlot();
byte[] salt = CryptoUtils.generateSalt();
SCryptParameters scryptParams = new SCryptParameters(
CryptoUtils.CRYPTO_SCRYPT_N,
CryptoUtils.CRYPTO_SCRYPT_r,
CryptoUtils.CRYPTO_SCRYPT_p,
salt
);
VaultFileCredentials creds = new VaultFileCredentials();
try {
SecretKey key = slot.deriveKey(VAULT_PASSWORD.toCharArray(), scryptParams);
slot.setKey(creds.getKey(), CryptoUtils.createEncryptCipher(key));
} catch (NoSuchAlgorithmException
| InvalidKeyException
| InvalidAlgorithmParameterException
| NoSuchPaddingException
| SlotException e) {
throw new RuntimeException(e);
}
creds.getSlots().add(slot);
return creds;
}
protected static <T extends OtpInfo> VaultEntry generateEntry(Class<T> type, String name, String issuer) {
return generateEntry(type, name, issuer, 20);
}
protected static <T extends OtpInfo> VaultEntry generateEntry(Class<T> type, String name, String issuer, int secretLength) {
byte[] secret = CryptoUtils.generateRandomBytes(secretLength);
OtpInfo info;
try {
info = type.getConstructor(byte[].class).newInstance(secret);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
return new VaultEntry(info, name, issuer);
}
// source: https://stackoverflow.com/a/30338665
@@ -0,0 +1,7 @@
package com.beemdevelopment.aegis;
import dagger.hilt.android.testing.CustomTestApplication;
@CustomTestApplication(AegisApplicationBase.class)
public interface AegisTestApplication {
}
@@ -1,21 +1,32 @@
package com.beemdevelopment.aegis;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.preference.PreferenceManager;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.runner.AndroidJUnitRunner;
import java.io.File;
import com.beemdevelopment.aegis.util.IOUtils;
public class AegisTestRunner extends AndroidJUnitRunner {
static {
BuildConfig.TEST.set(true);
}
@Override
public Application newApplication(ClassLoader cl, String name, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
return Instrumentation.newApplication(AegisTestApplication_Application.class, context);
}
@Override
public void callApplicationOnCreate(Application app) {
Context context = app.getApplicationContext();
// clear internal storage so that there is no vault file
clearDirectory(context.getFilesDir(), false);
IOUtils.clearDirectory(context.getFilesDir(), false);
// clear preferences so that the intro is started from MainActivity
ApplicationProvider.getApplicationContext().getFilesDir();
@@ -26,21 +37,4 @@ public class AegisTestRunner extends AndroidJUnitRunner {
super.callApplicationOnCreate(app);
}
private static void clearDirectory(File dir, boolean deleteParent) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
clearDirectory(file, true);
} else {
file.delete();
}
}
}
if (deleteParent) {
dir.delete();
}
}
}
@@ -0,0 +1,374 @@
package com.beemdevelopment.aegis;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.pressBack;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.intent.Intents.intending;
import static androidx.test.espresso.intent.matcher.IntentMatchers.isInternal;
import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant;
import static androidx.test.espresso.matcher.ViewMatchers.isRoot;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.net.Uri;
import androidx.annotation.Nullable;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.espresso.intent.Intents;
import androidx.test.espresso.matcher.RootMatchers;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.beemdevelopment.aegis.crypto.CryptoUtils;
import com.beemdevelopment.aegis.crypto.MasterKey;
import com.beemdevelopment.aegis.encoding.Hex;
import com.beemdevelopment.aegis.importers.DatabaseImporter;
import com.beemdevelopment.aegis.importers.DatabaseImporterException;
import com.beemdevelopment.aegis.importers.GoogleAuthUriImporter;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.rules.ScreenshotTestRule;
import com.beemdevelopment.aegis.ui.PreferencesActivity;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultBackupManager;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultFile;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultFileException;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.SlotException;
import com.beemdevelopment.aegis.vault.slots.SlotIntegrityException;
import com.beemdevelopment.aegis.vault.slots.SlotList;
import com.beemdevelopment.aegis.vectors.VaultEntries;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import dagger.hilt.android.testing.HiltAndroidTest;
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
@SmallTest
public class BackupExportTest extends AegisTest {
private final ActivityScenarioRule<PreferencesActivity> _activityRule = new ActivityScenarioRule<>(PreferencesActivity.class);
@Rule
public final TestRule testRule = RuleChain.outerRule(_activityRule).around(new ScreenshotTestRule());
@Before
public void setUp() {
Intents.init();
}
@After
public void tearDown() {
Intents.release();
}
@Test
public void testPlainVaultExportPlainJson() {
initPlainVault();
openExportDialog();
onView(withId(R.id.checkbox_export_encrypt)).perform(click());
onView(withId(android.R.id.button1)).perform(click());
onView(withId(R.id.checkbox_accept)).perform(click());
File file = doExport();
readVault(file, null);
}
@Test
public void testPlainVaultExportPlainTxt() {
initPlainVault();
openExportDialog();
onView(withId(R.id.checkbox_export_encrypt)).perform(click());
onView(withId(R.id.dropdown_export_format)).perform(click());
onView(withText(R.string.export_format_google_auth_uri)).inRoot(RootMatchers.isPlatformPopup()).perform(click());
onView(withId(android.R.id.button1)).perform(click());
onView(withId(R.id.checkbox_accept)).perform(click());
File file = doExport();
readTxtExport(file);
}
@Test
public void testPlainVaultExportEncryptedJson() {
initPlainVault();
openExportDialog();
File file = doExport();
onView(withId(R.id.text_password)).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
readVault(file, VAULT_PASSWORD);
}
@Test
public void testEncryptedVaultExportPlainJson() {
initEncryptedVault();
openExportDialog();
onView(withId(R.id.checkbox_export_encrypt)).perform(click());
onView(withId(android.R.id.button1)).perform(click());
onView(withId(R.id.checkbox_accept)).perform(click());
File file = doExport();
readVault(file, null);
}
@Test
public void testEncryptedVaultExportPlainTxt() {
initEncryptedVault();
openExportDialog();
onView(withId(R.id.checkbox_export_encrypt)).perform(click());
onView(withId(R.id.dropdown_export_format)).perform(click());
onView(withText(R.string.export_format_google_auth_uri)).inRoot(RootMatchers.isPlatformPopup()).perform(click());
onView(withId(android.R.id.button1)).perform(click());
onView(withId(R.id.checkbox_accept)).perform(click());
File file = doExport();
readTxtExport(file);
}
@Test
public void testEncryptedVaultExportEncryptedJson() {
initEncryptedVault();
openExportDialog();
File file = doExport();
readVault(file, VAULT_PASSWORD);
}
@Test
public void testSeparateExportPassword() {
initEncryptedVault();
setSeparateBackupExportPassword();
openExportDialog();
File file = doExport();
readVault(file, VAULT_BACKUP_PASSWORD);
}
@Test
public void testChangeBackupPassword() throws SlotIntegrityException {
initEncryptedVault();
setSeparateBackupExportPassword();
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_section_security_title)), click()));
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_backup_password_change_title)), click()));
onView(withId(R.id.text_password)).perform(typeText(VAULT_BACKUP_PASSWORD_CHANGED), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_BACKUP_PASSWORD_CHANGED), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
onView(isRoot()).perform(pressBack());
VaultFileCredentials creds = _vaultManager.getVault().getCredentials();
assertEquals(creds.getSlots().findRegularPasswordSlots().size(), 1);
assertEquals(creds.getSlots().findBackupPasswordSlots().size(), 1);
for (PasswordSlot slot : creds.getSlots().findBackupPasswordSlots()) {
verifyPasswordSlotChange(creds, slot, VAULT_BACKUP_PASSWORD, VAULT_BACKUP_PASSWORD_CHANGED);
}
for (PasswordSlot slot : creds.getSlots().findRegularPasswordSlots()) {
decryptPasswordSlot(slot, VAULT_PASSWORD);
}
openExportDialog();
File file = doExport();
readVault(file, VAULT_BACKUP_PASSWORD_CHANGED);
}
@Test
public void testChangePasswordHavingBackupPassword() throws SlotIntegrityException {
initEncryptedVault();
setSeparateBackupExportPassword();
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_section_security_title)), click()));
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_set_password_title)), click()));
onView(withId(R.id.text_password)).perform(typeText(VAULT_PASSWORD_CHANGED), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_PASSWORD_CHANGED), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
onView(isRoot()).perform(pressBack());
VaultFileCredentials creds = _vaultManager.getVault().getCredentials();
assertEquals(creds.getSlots().findRegularPasswordSlots().size(), 1);
assertEquals(creds.getSlots().findBackupPasswordSlots().size(), 1);
for (PasswordSlot slot : creds.getSlots().findRegularPasswordSlots()) {
verifyPasswordSlotChange(creds, slot, VAULT_PASSWORD, VAULT_PASSWORD_CHANGED);
}
for (PasswordSlot slot : creds.getSlots().findBackupPasswordSlots()) {
decryptPasswordSlot(slot, VAULT_BACKUP_PASSWORD);
}
openExportDialog();
File file = doExport();
readVault(file, VAULT_BACKUP_PASSWORD);
}
private void setSeparateBackupExportPassword() {
VaultFileCredentials creds = _vaultManager.getVault().getCredentials();
assertEquals(creds.getSlots().findRegularPasswordSlots().size(), 1);
assertEquals(creds.getSlots().findBackupPasswordSlots().size(), 0);
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_section_security_title)), click()));
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_backup_password_title)), click()));
onView(withId(R.id.text_password)).perform(typeText(VAULT_BACKUP_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_BACKUP_PASSWORD), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
onView(isRoot()).perform(pressBack());
creds = _vaultManager.getVault().getCredentials();
assertEquals(creds.getSlots().findRegularPasswordSlots().size(), 1);
assertEquals(creds.getSlots().findBackupPasswordSlots().size(), 1);
for (PasswordSlot slot : creds.getSlots().findBackupPasswordSlots()) {
verifyPasswordSlotChange(creds, slot, VAULT_PASSWORD, VAULT_BACKUP_PASSWORD);
}
}
private void verifyPasswordSlotChange(VaultFileCredentials creds, PasswordSlot slot, String oldPassword, String newPassword) {
assertThrows(SlotIntegrityException.class, () -> decryptPasswordSlot(slot, oldPassword));
MasterKey masterKey;
try {
masterKey = decryptPasswordSlot(slot, newPassword);
} catch (SlotIntegrityException e) {
throw new RuntimeException("Unable to decrypt password slot", e);
}
assertArrayEquals(creds.getKey().getBytes(), masterKey.getBytes());
}
private File doExport() {
File file = getExportFileUri();
Intent resultData = new Intent();
resultData.setData(Uri.fromFile(file));
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
intending(not(isInternal())).respondWith(result);
onView(withId(android.R.id.button1)).perform(click());
return file;
}
private void openExportDialog() {
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_section_import_export_title)), click()));
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_export_title)), click()));
}
private MasterKey decryptPasswordSlot(PasswordSlot slot, String password) throws SlotIntegrityException {
SecretKey derivedKey = slot.deriveKey(password.toCharArray());
try {
Cipher cipher = slot.createDecryptCipher(derivedKey);
return slot.getKey(cipher);
} catch (SlotException e) {
throw new RuntimeException("Unable to decrypt password slot", e);
}
}
private File getExportFileUri() {
String dirName = Hex.encode(CryptoUtils.generateRandomBytes(8));
File dir = new File(getInstrumentation().getTargetContext().getExternalCacheDir(), String.format("export-%s", dirName));
if (!dir.mkdirs()) {
throw new RuntimeException(String.format("Unable to create export directory: %s", dir));
}
VaultBackupManager.FileInfo fileInfo = new VaultBackupManager.FileInfo(VaultRepository.FILENAME_PREFIX_EXPORT);
return new File(dir, fileInfo.toString());
}
private VaultRepository readVault(File file, @Nullable String password) {
VaultRepository repo;
try (InputStream inStream = new FileInputStream(file)) {
byte[] bytes = IOUtils.readAll(inStream);
VaultFile vaultFile = VaultFile.fromBytes(bytes);
VaultFileCredentials creds = null;
if (password != null) {
SlotList slots = vaultFile.getHeader().getSlots();
for (PasswordSlot slot : slots.findAll(PasswordSlot.class)) {
SecretKey derivedKey = slot.deriveKey(password.toCharArray());
Cipher cipher = slot.createDecryptCipher(derivedKey);
MasterKey masterKey = slot.getKey(cipher);
creds = new VaultFileCredentials(masterKey, slots);
break;
}
}
repo = VaultRepository.fromFile(getInstrumentation().getContext(), vaultFile, creds);
} catch (SlotException | SlotIntegrityException | VaultRepositoryException | VaultFileException | IOException e) {
throw new RuntimeException("Unable to read back vault file", e);
}
checkReadEntries(repo.getEntries());
return repo;
}
private void readTxtExport(File file) {
GoogleAuthUriImporter importer = new GoogleAuthUriImporter(getInstrumentation().getContext());
Collection<VaultEntry> entries;
try (InputStream inStream = new FileInputStream(file)) {
DatabaseImporter.State state = importer.read(inStream);
DatabaseImporter.Result result = state.convert();
entries = result.getEntries().getValues();
} catch (DatabaseImporterException | IOException e) {
throw new RuntimeException("Unable to read txt export file", e);
}
checkReadEntries(entries);
}
private void checkReadEntries(Collection<VaultEntry> entries) {
List<VaultEntry> vectors = VaultEntries.get();
assertEquals(vectors.size(), entries.size());
int i = 0;
for (VaultEntry entry : entries) {
VaultEntry vector = vectors.get(i);
String message = String.format("Entries are not equivalent: (%s) (%s)", vector.toJson().toString(), entry.toJson().toString());
assertTrue(message, vector.equivalates(entry));
try {
assertEquals(message, vector.getInfo().getOtp(), entry.getInfo().getOtp());
} catch (OtpInfoException e) {
throw new RuntimeException("Unable to generate OTP", e);
}
i++;
}
}
}
@@ -0,0 +1,68 @@
package com.beemdevelopment.aegis;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static junit.framework.TestCase.assertTrue;
import android.content.Intent;
import android.net.Uri;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import com.beemdevelopment.aegis.otp.GoogleAuthInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.MainActivity;
import com.beemdevelopment.aegis.vault.VaultEntry;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import dagger.hilt.android.testing.HiltAndroidTest;
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
@LargeTest
public class DeepLinkTest extends AegisTest {
@Before
public void before() {
initEmptyEncryptedVault();
}
@Test
public void testDeepLinkIntent() {
VaultEntry entry = generateEntry(TotpInfo.class, "Bob", "Google");
GoogleAuthInfo info = new GoogleAuthInfo(entry.getInfo(), entry.getName(), entry.getIssuer());
launch(info.getUri());
onView(withId(R.id.action_save)).perform(click());
VaultEntry createdEntry = (VaultEntry) _vaultManager.getVault().getEntries().toArray()[0];
assertTrue(createdEntry.equivalates(entry));
}
@Test
public void testDeepLinkIntent_Empty() {
launch(null);
}
@Test
public void testDeepLinkIntent_Bad() {
launch(Uri.parse("otpauth://bad"));
onView(withId(android.R.id.button1)).perform(click());
}
@SuppressWarnings("deprecation")
private void launch(Uri uri) {
Intent intent = new Intent(getApp(), MainActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
// we need to use the deprecated ActivityTestRule class because of https://github.com/android/android-test/issues/143
ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class);
rule.launchActivity(intent);
}
}
@@ -0,0 +1,54 @@
package com.beemdevelopment.aegis;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.rules.ScreenshotTestRule;
import com.beemdevelopment.aegis.ui.MainActivity;
import com.beemdevelopment.aegis.vault.VaultEntry;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import dagger.hilt.android.testing.HiltAndroidTest;
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
@SmallTest
public class EmptySecretTest extends AegisTest {
private ActivityScenario<MainActivity> _scenario;
@Before
public void before() throws OtpInfoException {
initEmptyPlainVault();
_vaultManager.getVault().addEntry(new VaultEntry(new TotpInfo(new byte[0])));
_scenario = ActivityScenario.launch(MainActivity.class);
}
@After
public void after() {
_scenario.close();
}
@Test
public void testVaultEntryEmptySecret() {
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.error_all_caps)), click()));
}
}
@@ -1,43 +1,88 @@
package com.beemdevelopment.aegis;
import androidx.test.espresso.ViewInteraction;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import com.beemdevelopment.aegis.ui.IntroActivity;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.beemdevelopment.aegis.vault.slots.BiometricSlot;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.SlotList;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.intent.Intents.intending;
import static androidx.test.espresso.intent.matcher.IntentMatchers.isInternal;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNull;
import static junit.framework.TestCase.assertTrue;
import static org.hamcrest.Matchers.not;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.net.Uri;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.espresso.IdlingResource;
import androidx.test.espresso.ViewInteraction;
import androidx.test.espresso.intent.Intents;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.viewpager2.widget.ViewPager2;
import com.beemdevelopment.aegis.rules.ScreenshotTestRule;
import com.beemdevelopment.aegis.ui.IntroActivity;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.slots.BiometricSlot;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.SlotList;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import dagger.hilt.android.testing.HiltAndroidTest;
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
@LargeTest
public class IntroTest extends AegisTest {
private static final String _password = "test";
private final ActivityScenarioRule<IntroActivity> _activityRule = new ActivityScenarioRule<>(IntroActivity.class);
private ViewPager2IdlingResource _viewPager2IdlingResource;
@Rule
public final ActivityScenarioRule<IntroActivity> activityRule = new ActivityScenarioRule<>(IntroActivity.class);
public final TestRule testRule = RuleChain.outerRule(_activityRule).around(new ScreenshotTestRule());
@Before
public void setUp() {
Intents.init();
_activityRule.getScenario().onActivity(activity -> {
_viewPager2IdlingResource = new ViewPager2IdlingResource(activity.findViewById(R.id.pager), "viewPagerIdlingResource");
IdlingRegistry.getInstance().register(_viewPager2IdlingResource);
});
}
@After
public void tearDown() {
Intents.release();
IdlingRegistry.getInstance().unregister(_viewPager2IdlingResource);
}
@Test
public void doIntro_None() {
public void testIntro_None() {
assertFalse(_prefs.isIntroDone());
ViewInteraction next = onView(withId(R.id.btnNext));
ViewInteraction prev = onView(withId(R.id.btnPrevious));
@@ -50,15 +95,16 @@ public class IntroTest extends AegisTest {
next.perform(click());
prev.check(matches(not(isDisplayed())));
next.perform(click());
next.perform(click());
VaultManager vault = getVault();
VaultRepository vault = _vaultManager.getVault();
assertFalse(vault.isEncryptionEnabled());
assertNull(getVault().getCredentials());
assertNull(vault.getCredentials());
assertTrue(_prefs.isIntroDone());
}
@Test
public void doIntro_Password() {
public void testIntro_Password() {
assertFalse(_prefs.isIntroDone());
ViewInteraction next = onView(withId(R.id.btnNext));
ViewInteraction prev = onView(withId(R.id.btnPrevious));
@@ -69,10 +115,10 @@ public class IntroTest extends AegisTest {
prev.check(matches(not(isDisplayed())));
next.perform(click());
next.perform(click());
onView(withId(R.id.text_password)).perform(typeText(_password), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(_password + "1"), closeSoftKeyboard());
onView(withId(R.id.text_password)).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_PASSWORD + "1"), closeSoftKeyboard());
next.perform(click());
onView(withId(R.id.text_password_confirm)).perform(replaceText(_password), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(replaceText(VAULT_PASSWORD), closeSoftKeyboard());
prev.perform(click());
prev.perform(click());
prev.check(matches(not(isDisplayed())));
@@ -81,10 +127,102 @@ public class IntroTest extends AegisTest {
next.perform(click());
next.perform(click());
VaultManager vault = getVault();
SlotList slots = getVault().getCredentials().getSlots();
VaultRepository vault = _vaultManager.getVault();
SlotList slots = vault.getCredentials().getSlots();
assertTrue(vault.isEncryptionEnabled());
assertTrue(slots.has(PasswordSlot.class));
assertFalse(slots.has(BiometricSlot.class));
assertTrue(_prefs.isIntroDone());
}
@Test
public void testIntro_Import_Plain() {
assertFalse(_prefs.isIntroDone());
Uri uri = getResourceUri("aegis_plain.json");
Intent resultData = new Intent();
resultData.setData(uri);
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
intending(not(isInternal())).respondWith(result);
ViewInteraction next = onView(withId(R.id.btnNext));
onView(withId(R.id.btnImport)).perform(click());
next.perform(click());
VaultRepository vault = _vaultManager.getVault();
assertFalse(vault.isEncryptionEnabled());
assertNull(vault.getCredentials());
assertTrue(_prefs.isIntroDone());
}
@Test
public void testIntro_Import_Encrypted() {
assertFalse(_prefs.isIntroDone());
Uri uri = getResourceUri("aegis_encrypted.json");
Intent resultData = new Intent();
resultData.setData(uri);
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
intending(not(isInternal())).respondWith(result);
ViewInteraction next = onView(withId(R.id.btnNext));
onView(withId(R.id.btnImport)).perform(click());
onView(withId(R.id.text_input)).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
next.perform(click());
VaultRepository vault = _vaultManager.getVault();
SlotList slots = vault.getCredentials().getSlots();
assertTrue(vault.isEncryptionEnabled());
assertTrue(slots.has(PasswordSlot.class));
assertFalse(slots.has(BiometricSlot.class));
assertTrue(_prefs.isIntroDone());
}
private Uri getResourceUri(String resourceName) {
File targetFile = new File(getInstrumentation().getTargetContext().getExternalCacheDir(), resourceName);
try (InputStream inStream = getClass().getResourceAsStream(resourceName);
FileOutputStream outStream = new FileOutputStream(targetFile)) {
IOUtils.copy(inStream, outStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Uri.fromFile(targetFile);
}
// Source: https://stackoverflow.com/a/32763454/12972657
private static class ViewPager2IdlingResource implements IdlingResource {
private final String _resName;
private boolean _isIdle = true;
private IdlingResource.ResourceCallback _resourceCallback = null;
public ViewPager2IdlingResource(ViewPager2 viewPager, String resName) {
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrollStateChanged(int state) {
_isIdle = (state == ViewPager2.SCROLL_STATE_IDLE || state == ViewPager2.SCROLL_STATE_DRAGGING);
if (_isIdle && _resourceCallback != null) {
_resourceCallback.onTransitionToIdle();
}
}
});
_resName = resName;
}
@Override
public String getName() {
return _resName;
}
@Override
public boolean isIdleNow() {
return _isIdle;
}
@Override
public void registerIdleTransitionCallback(IdlingResource.ResourceCallback resourceCallback) {
_resourceCallback = resourceCallback;
}
}
}
@@ -1,36 +1,7 @@
package com.beemdevelopment.aegis;
import androidx.annotation.IdRes;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.espresso.AmbiguousViewMatcherException;
import androidx.test.espresso.ViewInteraction;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import com.beemdevelopment.aegis.crypto.CryptoUtils;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.SteamInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.MainActivity;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static androidx.test.espresso.Espresso.onData;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
import static androidx.test.espresso.Espresso.openContextualActionModeOverflowMenu;
import static androidx.test.espresso.action.ViewActions.clearText;
import static androidx.test.espresso.action.ViewActions.click;
@@ -39,43 +10,88 @@ import static androidx.test.espresso.action.ViewActions.longClick;
import static androidx.test.espresso.action.ViewActions.pressBack;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant;
import static androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA;
import static androidx.test.espresso.matcher.ViewMatchers.isRoot;
import static androidx.test.espresso.matcher.ViewMatchers.withClassName;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNull;
import static junit.framework.TestCase.assertTrue;
import static org.hamcrest.Matchers.anything;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import androidx.annotation.IdRes;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.espresso.ViewInteraction;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.espresso.matcher.RootMatchers;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.Hex;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.MotpInfo;
import com.beemdevelopment.aegis.otp.SteamInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.otp.YandexInfo;
import com.beemdevelopment.aegis.rules.ScreenshotTestRule;
import com.beemdevelopment.aegis.ui.MainActivity;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import dagger.hilt.android.testing.HiltAndroidTest;
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
@LargeTest
public class OverallTest extends AegisTest {
private static final String _password = "test";
private static final String _groupName = "Test";
private final ActivityScenarioRule<MainActivity> _activityRule = new ActivityScenarioRule<>(MainActivity.class);
@Rule
public final ActivityTestRule<MainActivity> activityRule = new ActivityTestRule<>(MainActivity.class);
public final TestRule testRule = RuleChain.outerRule(_activityRule).around(new ScreenshotTestRule());
@Test
public void doOverallTest() {
public void testOverall() {
ViewInteraction next = onView(withId(R.id.btnNext));
next.perform(click());
onView(withId(R.id.rb_password)).perform(click());
next.perform(click());
onView(withId(R.id.text_password)).perform(typeText(_password), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(_password), closeSoftKeyboard());
onView(withId(R.id.text_password)).perform(click()).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
next.perform(click());
onView(withId(R.id.btnNext)).perform(click());
VaultManager vault = getVault();
VaultRepository vault = _vaultManager.getVault();
assertTrue(vault.isEncryptionEnabled());
assertTrue(vault.getCredentials().getSlots().has(PasswordSlot.class));
assertTrue(_prefs.isIntroDone());
List<VaultEntry> entries = Arrays.asList(
generateEntry(TotpInfo.class, "Frank", "Google"),
generateEntry(HotpInfo.class, "John", "GitHub"),
generateEntry(TotpInfo.class, "Alice", "Office 365"),
generateEntry(SteamInfo.class, "Gaben", "Steam")
generateEntry(SteamInfo.class, "Gaben", "Steam"),
generateEntry(YandexInfo.class, "Ivan", "Yandex", 16),
generateEntry(MotpInfo.class, "Jimmy McGill", "PfSense", 16)
);
for (VaultEntry entry : entries) {
addEntry(entry);
@@ -83,7 +99,8 @@ public class OverallTest extends AegisTest {
List<VaultEntry> realEntries = new ArrayList<>(vault.getEntries());
for (int i = 0; i < realEntries.size(); i++) {
assertTrue(realEntries.get(i).equivalates(entries.get(i)));
String message = String.format("%s != %s", realEntries.get(i).toJson().toString(), entries.get(i).toJson().toString());
assertTrue(message, realEntries.get(i).equivalates(entries.get(i)));
}
for (int i = 0; i < 10; i++) {
@@ -96,8 +113,8 @@ public class OverallTest extends AegisTest {
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(1, longClick()));
onView(withId(R.id.action_edit)).perform(click());
onView(withId(R.id.text_name)).perform(clearText(), typeText("Bob"), closeSoftKeyboard());
onView(withId(R.id.spinner_group)).perform(click());
onData(anything()).atPosition(1).perform(click());
onView(withId(R.id.dropdown_group)).perform(click());
onView(withText(R.string.new_group)).inRoot(RootMatchers.isPlatformPopup()).perform(click());
onView(withId(R.id.text_input)).perform(typeText(_groupName), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
onView(isRoot()).perform(pressBack());
@@ -109,37 +126,38 @@ public class OverallTest extends AegisTest {
changeSort(R.string.sort_alphabetically_reverse);
changeSort(R.string.sort_custom);
changeFilter(_groupName);
changeFilter(R.string.filter_ungrouped);
changeFilter(R.string.all);
changeGroupFilter(_groupName);
changeGroupFilter(null);
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(1, longClick()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(2, click()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(2, longClick()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(3, click()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(4, click()));
onView(withId(R.id.action_share_qr)).perform(click());
onView(withId(R.id.btnNext)).perform(click()).perform(click()).perform(click());
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(2, longClick()));
onView(withId(R.id.action_delete)).perform(click());
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(0, longClick()));
onView(allOf(isDescendantOfA(withClassName(containsString("ActionBarContextView"))), withClassName(containsString("OverflowMenuButton")))).perform(click());
onView(withText(R.string.action_delete)).perform(click());
onView(withId(android.R.id.button1)).perform(click());
openContextualActionModeOverflowMenu();
onView(withText(R.string.lock)).perform(click());
onView(withId(R.id.text_password)).perform(typeText(_password), closeSoftKeyboard());
onView(withId(R.id.text_password)).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.button_decrypt)).perform(click());
vault = getVault();
vault = _vaultManager.getVault();
openContextualActionModeOverflowMenu();
onView(withText(R.string.action_settings)).perform(click());
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_encryption_title)), click()));
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_section_security_title)), click()));
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItemAtPosition(1, click()));
onView(withId(android.R.id.button1)).perform(click());
assertFalse(vault.isEncryptionEnabled());
assertNull(vault.getCredentials());
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_encryption_title)), click()));
onView(withId(R.id.text_password)).perform(typeText(_password), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(_password), closeSoftKeyboard());
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItemAtPosition(1, click()));
onView(withId(R.id.text_password)).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_PASSWORD), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
assertTrue(vault.isEncryptionEnabled());
@@ -151,57 +169,63 @@ public class OverallTest extends AegisTest {
onView(withText(resId)).perform(click());
}
private void changeFilter(String text) {
openContextualActionModeOverflowMenu();
onView(withText(R.string.filter)).perform(click());
onView(withText(text)).perform(click());
}
private void changeFilter(@IdRes int resId) {
changeFilter(ApplicationProvider.getApplicationContext().getString(resId));
private void changeGroupFilter(String text) {
onView(withId(R.id.chip_group)).perform(click());
if (text == null) {
onView(withId(R.id.btnClear)).perform(click());
} else {
onView(withText(text)).perform(click());
onView(isRoot()).perform(pressBack());
}
}
private void addEntry(VaultEntry entry) {
onView(withId(R.id.fab_expand_menu_button)).perform(click());
onView(withId(R.id.fab)).perform(click());
onView(withId(R.id.fab_enter)).perform(click());
onView(withId(R.id.accordian_header)).perform(click());
onView(withId(R.id.text_name)).perform(typeText(entry.getName()), closeSoftKeyboard());
onView(withId(R.id.text_issuer)).perform(typeText(entry.getIssuer()), closeSoftKeyboard());
if (entry.getInfo().getClass() != TotpInfo.class) {
int i = entry.getInfo() instanceof HotpInfo ? 1 : 2;
try {
onView(withId(R.id.spinner_type)).perform(click());
onData(anything()).atPosition(i).perform(click());
} catch (AmbiguousViewMatcherException e) {
// for some reason, clicking twice is sometimes necessary, otherwise the test fails on the next line
onView(withId(R.id.spinner_type)).perform(click());
onData(anything()).atPosition(i).perform(click());
}
String otpType;
if (entry.getInfo() instanceof HotpInfo) {
onView(withId(R.id.text_counter)).perform(typeText("0"), closeSoftKeyboard());
}
if (entry.getInfo() instanceof SteamInfo) {
onView(withId(R.id.text_digits)).perform(clearText(), typeText("5"), closeSoftKeyboard());
otpType = "HOTP";
} else if (entry.getInfo() instanceof SteamInfo) {
otpType = "Steam";
} else if (entry.getInfo() instanceof YandexInfo) {
otpType = "Yandex";
} else if (entry.getInfo() instanceof MotpInfo) {
otpType = "MOTP";
} else if (entry.getInfo() instanceof TotpInfo) {
otpType = "TOTP";
} else {
throw new RuntimeException(String.format("Unexpected entry type: %s", entry.getInfo().getClass().getSimpleName()));
}
onView(withId(R.id.dropdown_type)).perform(click());
onView(withText(otpType)).inRoot(RootMatchers.isPlatformPopup()).perform(click());
}
String secret;
if (Objects.equals(entry.getInfo().getTypeId(), MotpInfo.ID)) {
secret = Hex.encode(entry.getInfo().getSecret());
} else {
secret = Base32.encode(entry.getInfo().getSecret());
}
String secret = Base32.encode(entry.getInfo().getSecret());
onView(withId(R.id.text_secret)).perform(typeText(secret), closeSoftKeyboard());
if (entry.getInfo() instanceof YandexInfo) {
String pin = "123456";
((YandexInfo) entry.getInfo()).setPin(pin);
onView(withId(R.id.text_pin)).perform(typeText(pin), closeSoftKeyboard());
} else if (entry.getInfo() instanceof MotpInfo) {
String pin = "1234";
((MotpInfo) entry.getInfo()).setPin(pin);
onView(withId(R.id.text_pin)).perform(typeText(pin), closeSoftKeyboard());
}
onView(withId(R.id.action_save)).perform(click());
}
private <T extends OtpInfo> VaultEntry generateEntry(Class<T> type, String name, String issuer) {
byte[] secret = CryptoUtils.generateRandomBytes(20);
OtpInfo info;
try {
info = type.getConstructor(byte[].class).newInstance(secret);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
return new VaultEntry(info, name, issuer);
}
}
@@ -0,0 +1,61 @@
package com.beemdevelopment.aegis;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import android.content.Intent;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import androidx.test.rule.ActivityTestRule;
import com.beemdevelopment.aegis.ui.PanicResponderActivity;
import com.beemdevelopment.aegis.vault.VaultRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import dagger.hilt.android.testing.HiltAndroidTest;
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
@SmallTest
public class PanicTriggerTest extends AegisTest {
@Before
public void before() {
initEncryptedVault();
}
@Test
public void testPanicTriggerDisabled() {
assertFalse(_prefs.isPanicTriggerEnabled());
launchPanic();
assertTrue(_vaultManager.isVaultLoaded());
_vaultManager.getVault();
assertFalse(_vaultManager.isVaultFileLoaded());
assertNull(_vaultManager.getVaultFileError());
assertTrue(VaultRepository.fileExists(getApp()));
}
@Test
public void testPanicTriggerEnabled() {
_prefs.setIsPanicTriggerEnabled(true);
assertTrue(_prefs.isPanicTriggerEnabled());
launchPanic();
assertFalse(_vaultManager.isVaultLoaded());
assertThrows(IllegalStateException.class, () -> _vaultManager.getVault());
assertFalse(_vaultManager.isVaultFileLoaded());
assertNull(_vaultManager.getVaultFileError());
assertFalse(VaultRepository.fileExists(getApp()));
}
private void launchPanic() {
Intent intent = new Intent(PanicResponderActivity.PANIC_TRIGGER_ACTION);
// we need to use the deprecated ActivityTestRule class because of https://github.com/android/android-test/issues/143
ActivityTestRule<PanicResponderActivity> rule = new ActivityTestRule<>(PanicResponderActivity.class);
rule.launchActivity(intent);
}
}
@@ -0,0 +1,36 @@
package com.beemdevelopment.aegis.rules;
import android.graphics.Bitmap;
import androidx.test.runner.screenshot.BasicScreenCaptureProcessor;
import androidx.test.runner.screenshot.ScreenCapture;
import androidx.test.runner.screenshot.ScreenCaptureProcessor;
import androidx.test.runner.screenshot.Screenshot;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import java.io.IOException;
import java.util.HashSet;
public class ScreenshotTestRule extends TestWatcher {
@Override
protected void failed(Throwable e, Description description) {
super.failed(e, description);
String filename = description.getTestClass().getSimpleName() + "-" + description.getMethodName();
ScreenCapture capture = Screenshot.capture();
capture.setName(filename);
capture.setFormat(Bitmap.CompressFormat.PNG);
HashSet<ScreenCaptureProcessor> processors = new HashSet<>();
processors.add(new BasicScreenCaptureProcessor());
try {
capture.process(processors);
} catch (IOException e2) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,43 @@
package com.beemdevelopment.aegis.vault;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.beemdevelopment.aegis.AegisTest;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import dagger.hilt.android.testing.HiltAndroidTest;
@RunWith(AndroidJUnit4.class)
@HiltAndroidTest
@SmallTest
public class VaultRepositoryTest extends AegisTest {
@Before
public void before() {
initEncryptedVault();
}
@Test
public void testToggleEncryption() throws VaultRepositoryException {
VaultRepository vault = _vaultManager.getVault();
_vaultManager.disableEncryption();
assertFalse(vault.isEncryptionEnabled());
assertNull(vault.getCredentials());
VaultFileCredentials creds = generateCredentials();
_vaultManager.enableEncryption(creds);
assertTrue(vault.isEncryptionEnabled());
assertNotNull(vault.getCredentials());
assertEquals(vault.getCredentials().getSlots().findAll(PasswordSlot.class).size(), 1);
}
}
@@ -0,0 +1 @@
../../../../../../test/java/com/beemdevelopment/aegis/vectors/VaultEntries.java
@@ -0,0 +1 @@
../../../../../test/resources/com/beemdevelopment/aegis/importers/aegis_encrypted.json
@@ -0,0 +1 @@
../../../../../test/resources/com/beemdevelopment/aegis/importers/aegis_plain.json
+91 -15
View File
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.beemdevelopment.aegis">
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-feature
android:name="android.hardware.camera"
@@ -15,23 +15,29 @@
<application
android:name=".AegisApplication"
android:allowBackup="false"
android:allowBackup="true"
android:fullBackupOnly="true"
android:fullBackupContent="@xml/backup_rules_old"
android:dataExtractionRules="@xml/backup_rules"
android:backupAgent=".AegisBackupAgent"
android:enableOnBackInvokedCallback="true"
android:icon="@mipmap/${iconName}"
android:label="Aegis"
android:supportsRtl="true"
android:theme="@style/AppTheme.NoActionBar"
tools:ignore="GoogleAppIndexingWarning"
tools:replace="android:theme">
android:theme="@style/Theme.Aegis.Launch"
tools:replace="android:theme"
tools:targetApi="tiramisu">
<activity android:name=".ui.TransferEntriesActivity"
android:label="@string/title_activity_transfer" />
<activity
android:name=".ui.AboutActivity"
android:label="@string/title_activity_about" />
<activity
android:name=".ui.SelectEntriesActivity"
android:label="@string/title_activity_select_entries" />
android:name=".ui.ImportEntriesActivity"
android:label="@string/title_activity_import_entries" />
<activity
android:name=".ui.MainActivity"
android:exported="true"
android:label="${title}">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -46,6 +52,13 @@
<data android:scheme="otpauth" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<activity
android:name=".ui.ScannerActivity"
@@ -57,22 +70,85 @@
android:label="@string/title_activity_edit_entry" />
<activity
android:name=".ui.IntroActivity"
android:theme="@style/AppTheme.NoActionBar"
android:screenOrientation="portrait" />
<activity
android:name=".ui.AuthActivity"
android:theme="@style/AppTheme.NoActionBar" />
android:name=".ui.AuthActivity" />
<activity
android:name=".ui.PreferencesActivity"
android:label="@string/title_activity_preferences" />
<activity
android:name=".ui.SlotManagerActivity"
android:label="@string/title_activity_manage_slots" />
<activity
android:name=".ui.GroupManagerActivity"
android:label="@string/title_activity_manage_groups" />
<activity
android:name=".ui.PanicResponderActivity"
android:exported="true"
android:launchMode="singleInstance"
android:noHistory="true"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="info.guardianproject.panic.action.TRIGGER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".ui.ExitActivity" />
<service android:name=".services.NotificationService" />
<service
android:name=".services.LaunchAppTileService"
android:label="@string/tile_open_vault"
android:icon="@drawable/ic_aegis_quicksettings"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
android:exported="true">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
<meta-data android:name="android.service.quicksettings.ACTIVE_TILE"
android:value="true" />
</service>
<service
android:name=".services.LaunchScannerTileService"
android:label="@string/tile_open_scanner"
android:icon="@drawable/ic_aegis_quicksettings"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
android:exported="true">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
<meta-data android:name="android.service.quicksettings.ACTIVE_TILE"
android:value="true" />
</service>
<receiver android:name=".receivers.VaultLockReceiver" android:exported="false">
<intent-filter>
<action android:name="${applicationId}.LOCK_VAULT" />
</intent-filter>
</receiver>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${fileProviderAuthority}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
<meta-data android:name="android.webkit.WebView.MetricsOptOut" android:value="true" />
</application>
</manifest>
<queries>
<package android:name="com.authy.authy" />
<package android:name="org.fedorahosted.freeotp" />
<package android:name="org.liberty.android.freeotpplus" />
<package android:name="com.google.android.apps.authenticator2" />
<package android:name="com.azure.authenticator" />
<package android:name="com.valvesoftware.android.steam.community" />
<package android:name="com.authenticator.authservice2" />
<package android:name="com.duosecurity.duomobile" />
</queries>
</manifest>
+1
View File
@@ -0,0 +1 @@
../../../../LICENSE
+144
View File
@@ -31,6 +31,150 @@
</head>
<body>
<div></div>
<h3>Version 2.1</h3>
<h4>New</h4>
<ul>
<li>Support for mOTP</li>
<li>Support for Yandex OTP (Experimental)</li>
<li>An Adaptive Icon for Material You</li>
<li>Ability to favorite certain entries and pin them to the top of the entry list</li>
<li>Ability to filter by entries that are not in a group</li>
<li>Ability to set a separate password that is used for encrypting backups and exports</li>
<li>Support for predictive back gesture</li>
<li>Improved overview of backup status in preferences</li>
<li>Additional options for code digit grouping</li>
<li>Support for importing from Duo</li>
<li>Support for importing from Bitwarden</li>
<li>Support for importing multiple QR code images in one go</li>
<li>Support for scanning Google Authenticator export QR codes from image files</li>
<li>Display some extra information in the dialog displayed when deleting an entry</li>
<li>An option to export through Google Authenticator export QR code images</li>
<li>An option to import an existing vault file from the first page in the intro</li>
<li>An option to minimize the app after copying a token</li>
<li>A count of the total number of entries is displayed at the bottom of the entry list</li>
<li>A backup reminder is shown if changes were made to the vault, but no backup or export has been created yet since then</li>
<li>A warning is shown after a plaintext export has been made</li>
<li>An option to focus search immediately after the app starts</li>
<li>Allow customization of the frequency of the password reminder</li>
<li>Allow sharing text to Aegis in the format of a Google Authenticator URI to add as a new entry</li>
<li>Always allow D2D (device-to-device) Android backups regardless of backup settings</li>
<li>Mark clipboard data as sensitive when copying tokens so that Android will mask them in the UI</li>
<li>Updated translations for almost all languages</li>
<li>New languages: Asturian, Catalan, Galician</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>Various reliability improvements for the QR code scanner</li>
<li>The floating action button was glitchy when making small entry list scroll movements</li>
<li>The vault unlocked notification was never shown and was still using the old app icon</li>
<li>The automatically generated entry icon was broken if the entry name/issuer is a multi-codepoint character (certain emoji's, for example)</li>
<li>The PIN keyboard was not disabled after enabling encryption</li>
<li>The password prompt message was unclear when importing from a file</li>
<li>The entry list was not sorted correctly if a change to an entry caused its location to change</li>
<li>Quickly double-tapping on the copy button would cause a crash</li>
<li>Importing an entry with an empty secret would cause a crash loop</li>
<li>On certain devices, it was not possible to import icon packs because the .ZIP files would be grayed out</li>
<li>An unclear error message was shown when trying to import from Steam and Google Authenticator</li>
<li>Various other minor UI and stability improvements</li>
</ul>
<h3>Version 2.0.3</h3>
<h4>New</h4>
<ul>
<li>Support for importing 2FAS Authenticator's new backup format</li>
</ul>
<h3>Version 2.0.2</h3>
<h4>New</h4>
<ul>
<li>Add a note field to entries</li>
<li>An option to pause code updating of highlighted entries</li>
<li>New translation: Lithuanian</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>Minor UI and stability improvements</li>
<li>The Microsoft Authenticator importer did not accept spaces and dashes in secrets</li>
</ul>
<h3>Version 2.0.1</h3>
<h4>New</h4>
<ul>
<li>Support for sorting on most used tokens</li>
<li>Some minor UX and stability improvements</li>
<li>New translation: Vietnamese</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>QR code information was decoded incorrectly in some cases if the app was set to a certain language (Turkish, for example)</li>
</ul>
<h3>Version 2.0</h3>
<h4>New</h4>
<ul>
<li>Support for icon packs</li>
<li>Support for participation in Android's backup system (Google Drive, Seedvault)</li>
<li>UI refresh (switched to the Material Components theme)</li>
<li>Bottom sheet with chips to filter on groups</li>
<li>Support for importing from 2FAS Authenticator</li>
<li>Search in account names by default (and remove the setting)</li>
<li>Replaced the FAB with a bottom sheet dialog</li>
<li>Reorganization of settings into separate categories</li>
<li>Ability to 'share' images of QR codes to scan in Aegis</li>
<li>Option to save the current group filter</li>
<li>New translations for Bulgarian, Danish, Latvian, Swedish and Ukranian</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>The QR code scanner had trouble detecting QR codes on some devices due to low resolution image capture</li>
<li>The app would vanish from the recent apps list after locking</li>
<li>When importing from Nextcloud, Aegis would report that the file could not be found.</li>
<li>The biometrics prompt would not appear on some devices</li>
<li>The app would lock when selecting a file/icon on certain devices and configurations</li>
<li>There were multiple layout issues on small screen devices</li>
<li>Various other usability, performance and stability improvements</li>
</ul>
<h3>Version 1.4.2</h3>
<h4>Fixes</h4>
<ul>
<li>The app would crash if DocumentsUI is not present on the device</li>
<li>The app would close when selecting an icon if auto lock on minimize was enabled</li>
<li>Importing from Authy was flaky for entries that have an icon</li>
<li>The dark theme was not properly applied to the QR code scanner view</li>
<li>The app would crash on plain text export on some devices</li>
<li>Importing from Authenticator Plus stopped working</li>
</ul>
<h3>Version 1.4.1</h3>
<h4>Fixes</h4>
<ul>
<li>Scanning QR codes stopped working on certain devices (primarily OnePlus)</li>
</ul>
<h3>Version 1.4</h3>
<h4>New</h4>
<ul>
<li>Optionally delete the vault if a panic trigger is received from Ripple</li>
<li>More customizable auto-lock</li>
<li>More flexible export options
<ul>
<li>Share mechanism</li>
<li>Offer to encrypt even if this feature is disabled in the app</li>
<li>Export to a Google Authenticator URI file</li>
</ul>
</li>
<li>Perform exports/backups on a background thread (automatic backups now work with Nextcloud)</li>
<li>Color improvements to the dark theme (slightly darker)</li>
<li>Offer more locations to select an image/icon from</li>
<li>Display some helpful information when importing from a different app</li>
<li>Minimum tap to reveal timeout changed to 1 second</li>
<li>After an entry is added, scroll to it and highlight it</li>
<li>Updated translations, and new translations for: Basque, Chinese Traditional, Hindi, Indonesian, Japanese, Persian, Romanian, Slovak</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>Scanning large images for QR codes would fail</li>
<li>The FAB would remain hidden under certain circumstances</li>
<li>The app would crash if an entry was added to the vault twice due to an IO error</li>
<li>The app would crash if the device was rotated while a progress dialog was shown</li>
<li>The PIN keyboard would show even if a new non-digit password was set</li>
<li>The password reminder popup would be occluded by the autofill popup</li>
<li>Importing from other apps on Android 11 was broken due to some permission issues</li>
</ul>
<h3>Version 1.3</h3>
<h4>New</h4>
<ul>
+14
View File
@@ -0,0 +1,14 @@
<html>
<head>
<style type="text/css">
body {
background-color: %2$s;
color: %3$s;
font-size: 0.8em;
}
</style>
</head>
<body>
<pre>%1$s</pre>
</body>
</html>
@@ -1,183 +1,8 @@
package com.beemdevelopment.aegis;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import dagger.hilt.android.HiltAndroidApp;
import androidx.annotation.RequiresApi;
@HiltAndroidApp
public class AegisApplication extends AegisApplicationBase {
import com.beemdevelopment.aegis.services.NotificationService;
import com.beemdevelopment.aegis.ui.MainActivity;
import com.beemdevelopment.aegis.vault.Vault;
import com.beemdevelopment.aegis.vault.VaultFile;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.beemdevelopment.aegis.vault.VaultManagerException;
import com.mikepenz.iconics.Iconics;
import com.mikepenz.material_design_iconic_typeface_library.MaterialDesignIconic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class AegisApplication extends Application {
private VaultFile _vaultFile;
private VaultManager _manager;
private Preferences _prefs;
private List<LockListener> _lockListeners;
private static final String CODE_LOCK_STATUS_ID = "lock_status_channel";
private static final String CODE_LOCK_VAULT_ACTION = "lock_vault";
@Override
public void onCreate() {
super.onCreate();
_prefs = new Preferences(this);
_lockListeners = new ArrayList<>();
Iconics.init(this);
Iconics.registerFont(new MaterialDesignIconic());
// listen for SCREEN_OFF events
ScreenOffReceiver receiver = new ScreenOffReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(CODE_LOCK_VAULT_ACTION);
registerReceiver(receiver, intentFilter);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
initAppShortcuts();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
initNotificationChannels();
}
}
public boolean isVaultLocked() {
return _manager == null;
}
/**
* Loads the vault file from disk at the default location, stores an internal
* reference to it for future use and returns it. This must only be called before
* initVaultManager() or after lock().
*/
public VaultFile loadVaultFile() throws VaultManagerException {
if (!isVaultLocked()) {
throw new AssertionError("loadVaultFile() may only be called before initVaultManager() or after lock()");
}
if (_vaultFile == null) {
_vaultFile = VaultManager.readFile(this);
}
return _vaultFile;
}
/**
* Initializes the vault manager by decrypting the given vaultFile with the given
* creds. This removes the internal reference to the raw vault file.
*/
public VaultManager initVaultManager(VaultFile vaultFile, VaultFileCredentials creds) throws VaultManagerException {
_vaultFile = null;
_manager = VaultManager.init(this, vaultFile, creds);
return _manager;
}
/**
* Initializes the vault manager with the given vault and creds. This removes the
* internal reference to the raw vault file.
*/
public VaultManager initVaultManager(Vault vault, VaultFileCredentials creds) {
_vaultFile = null;
_manager = new VaultManager(this, vault, creds);
return _manager;
}
public VaultManager getVaultManager() {
return _manager;
}
public Preferences getPreferences() {
return _prefs;
}
public boolean isAutoLockEnabled() {
return _prefs.isAutoLockEnabled() && !isVaultLocked() && _manager.isEncryptionEnabled() ;
}
public void registerLockListener(LockListener listener) {
_lockListeners.add(listener);
}
public void unregisterLockListener(LockListener listener) {
_lockListeners.remove(listener);
}
public void lock() {
_manager = null;
for (LockListener listener : _lockListeners) {
listener.onLocked();
}
stopService(new Intent(AegisApplication.this, NotificationService.class));
}
@RequiresApi(api = Build.VERSION_CODES.N_MR1)
private void initAppShortcuts() {
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
if (shortcutManager == null) {
return;
}
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("action", "scan");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setAction(Intent.ACTION_MAIN);
ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "shortcut_new")
.setShortLabel(getString(R.string.new_entry))
.setLongLabel(getString(R.string.add_new_entry))
.setIcon(Icon.createWithResource(this, R.drawable.ic_qr_code))
.setIntent(intent)
.build();
shortcutManager.setDynamicShortcuts(Collections.singletonList(shortcut));
}
private void initNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name_lock_status);
String description = getString(R.string.channel_description_lock_status);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(CODE_LOCK_STATUS_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public class ScreenOffReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (isAutoLockEnabled()) {
lock();
}
}
}
public interface LockListener {
void onLocked();
}
}
@@ -0,0 +1,125 @@
package com.beemdevelopment.aegis;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ProcessLifecycleOwner;
import com.beemdevelopment.aegis.receivers.VaultLockReceiver;
import com.beemdevelopment.aegis.ui.MainActivity;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.mikepenz.iconics.Iconics;
import com.mikepenz.material_design_iconic_typeface_library.MaterialDesignIconic;
import com.topjohnwu.superuser.Shell;
import java.util.Collections;
import dagger.hilt.InstallIn;
import dagger.hilt.android.EarlyEntryPoint;
import dagger.hilt.android.EarlyEntryPoints;
import dagger.hilt.components.SingletonComponent;
public abstract class AegisApplicationBase extends Application {
private static final String CODE_LOCK_STATUS_ID = "lock_status_channel";
private VaultManager _vaultManager;
static {
// to access other app's internal storage directory, run libsu commands inside the global mount namespace
Shell.setDefaultBuilder(Shell.Builder.create().setFlags(Shell.FLAG_MOUNT_MASTER));
}
@Override
public void onCreate() {
super.onCreate();
_vaultManager = EarlyEntryPoints.get(this, EntryPoint.class).getVaultManager();
Iconics.init(this);
Iconics.registerFont(new MaterialDesignIconic());
VaultLockReceiver lockReceiver = new VaultLockReceiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
ContextCompat.registerReceiver(this, lockReceiver, intentFilter, ContextCompat.RECEIVER_NOT_EXPORTED);
// lock the app if the user moves the application to the background
ProcessLifecycleOwner.get().getLifecycle().addObserver(new AppLifecycleObserver());
// clear the cache directory on startup, to make sure no temporary vault export files remain
IOUtils.clearDirectory(getCacheDir(), false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
initAppShortcuts();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
initNotificationChannels();
}
}
@RequiresApi(api = Build.VERSION_CODES.N_MR1)
private void initAppShortcuts() {
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
if (shortcutManager == null) {
return;
}
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("action", "scan");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setAction(Intent.ACTION_MAIN);
ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "shortcut_new")
.setShortLabel(getString(R.string.new_entry))
.setLongLabel(getString(R.string.add_new_entry))
.setIcon(Icon.createWithResource(this, R.drawable.ic_qr_code))
.setIntent(intent)
.build();
shortcutManager.setDynamicShortcuts(Collections.singletonList(shortcut));
}
private void initNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name_lock_status);
String description = getString(R.string.channel_description_lock_status);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(CODE_LOCK_STATUS_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private class AppLifecycleObserver implements LifecycleEventObserver {
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_STOP
&& _vaultManager.isAutoLockEnabled(Preferences.AUTO_LOCK_ON_MINIMIZE)
&& !_vaultManager.isAutoLockBlocked()) {
_vaultManager.lock(false);
}
}
}
@EarlyEntryPoint
@InstallIn(SingletonComponent.class)
interface EntryPoint {
VaultManager getVaultManager();
}
}
@@ -0,0 +1,140 @@
package com.beemdevelopment.aegis;
import android.app.backup.BackupAgent;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.app.backup.FullBackupDataOutput;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultFile;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class AegisBackupAgent extends BackupAgent {
private static final String TAG = AegisBackupAgent.class.getSimpleName();
private Preferences _prefs;
@Override
public void onCreate() {
super.onCreate();
// Cannot use injection with Dagger Hilt here, because the app is launched in a restricted mode on restore
_prefs = new Preferences(this);
}
@Override
public synchronized void onFullBackup(FullBackupDataOutput data) throws IOException {
Log.i(TAG, String.format("onFullBackup() called: flags=%d, quota=%d",
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ? data.getTransportFlags() : -1,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? data.getQuota() : -1));
boolean isD2D = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
&& (data.getTransportFlags() & FLAG_DEVICE_TO_DEVICE_TRANSFER) == FLAG_DEVICE_TO_DEVICE_TRANSFER;
if (isD2D) {
Log.i(TAG, "onFullBackup(): allowing D2D transfer");
} else if (!_prefs.isAndroidBackupsEnabled()) {
Log.i(TAG, "onFullBackup() skipped: Android backups disabled in preferences");
return;
}
// We perform a catch of any Exception here to make sure we also
// report any runtime exceptions, in addition to the expected IOExceptions.
try {
fullBackup(data);
_prefs.setAndroidBackupResult(new Preferences.BackupResult(null));
} catch (Exception e) {
Log.e(TAG, String.format("onFullBackup() failed: %s", e));
_prefs.setAndroidBackupResult(new Preferences.BackupResult(e));
throw e;
}
Log.i(TAG, "onFullBackup() finished");
}
private void fullBackup(FullBackupDataOutput data) throws IOException {
// First copy the vault to the files/backup directory
createBackupDir();
File vaultBackupFile = getVaultBackupFile();
try (OutputStream outputStream = new FileOutputStream(vaultBackupFile)) {
VaultFile vaultFile = VaultRepository.readVaultFile(this);
byte[] bytes = vaultFile.exportable().toBytes();
outputStream.write(bytes);
} catch (VaultRepositoryException | IOException e) {
deleteBackupDir();
throw new IOException(e);
}
// Then call the original implementation so that fullBackupContent specified in AndroidManifest is read
try {
super.onFullBackup(data);
} finally {
deleteBackupDir();
}
}
@Override
public synchronized void onRestoreFile(ParcelFileDescriptor data, long size, File destination, int type, long mode, long mtime) throws IOException {
Log.i(TAG, String.format("onRestoreFile() called: dest=%s", destination));
super.onRestoreFile(data, size, destination, type, mode, mtime);
File vaultBackupFile = getVaultBackupFile();
if (destination.getCanonicalFile().equals(vaultBackupFile.getCanonicalFile())) {
try (InputStream inStream = new FileInputStream(vaultBackupFile)) {
VaultRepository.writeToFile(this, inStream);
} catch (IOException e) {
Log.e(TAG, String.format("onRestoreFile() failed: dest=%s, error=%s", destination, e));
throw e;
} finally {
deleteBackupDir();
}
}
Log.i(TAG, String.format("onRestoreFile() finished: dest=%s", destination));
}
@Override
public synchronized void onQuotaExceeded(long backupDataBytes, long quotaBytes) {
super.onQuotaExceeded(backupDataBytes, quotaBytes);
Log.e(TAG, String.format("onQuotaExceeded() called: backupDataBytes=%d, quotaBytes=%d", backupDataBytes, quotaBytes));
}
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException {
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException {
}
private void createBackupDir() throws IOException {
File dir = getVaultBackupFile().getParentFile();
if (dir == null || (!dir.exists() && !dir.mkdir())) {
throw new IOException(String.format("Unable to create backup directory: %s", dir));
}
}
private void deleteBackupDir() {
File dir = getVaultBackupFile().getParentFile();
if (dir != null) {
IOUtils.clearDirectory(dir, true);
}
}
private File getVaultBackupFile() {
return new File(new File(getFilesDir(), "backup"), VaultRepository.FILENAME);
}
}
@@ -0,0 +1,35 @@
package com.beemdevelopment.aegis;
import android.content.Context;
import com.beemdevelopment.aegis.icons.IconPackManager;
import com.beemdevelopment.aegis.vault.VaultManager;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.android.qualifiers.ApplicationContext;
import dagger.hilt.components.SingletonComponent;
@Module
@InstallIn(SingletonComponent.class)
public class AegisModule {
@Provides
@Singleton
public static IconPackManager provideIconPackManager(@ApplicationContext Context context) {
return new IconPackManager(context);
}
@Provides
@Singleton
public static VaultManager provideVaultManager(@ApplicationContext Context context) {
return new VaultManager(context);
}
@Provides
public static Preferences providePreferences(@ApplicationContext Context context) {
return new Preferences(context);
}
}
@@ -1,7 +0,0 @@
package com.beemdevelopment.aegis;
public enum CancelAction {
KILL,
CLOSE
}
@@ -0,0 +1,56 @@
package com.beemdevelopment.aegis;
import androidx.annotation.StringRes;
import java.util.concurrent.TimeUnit;
public enum PassReminderFreq {
NEVER,
WEEKLY,
BIWEEKLY,
MONTHLY,
QUARTERLY;
public long getDurationMillis() {
long weeks;
switch (this) {
case WEEKLY:
weeks = 1;
break;
case BIWEEKLY:
weeks = 2;
break;
case MONTHLY:
weeks = 4;
break;
case QUARTERLY:
weeks = 13;
break;
default:
weeks = 0;
break;
}
return TimeUnit.MILLISECONDS.convert(weeks * 7L, TimeUnit.DAYS);
}
@StringRes
public int getStringRes() {
switch (this) {
case WEEKLY:
return R.string.password_reminder_freq_weekly;
case BIWEEKLY:
return R.string.password_reminder_freq_biweekly;
case MONTHLY:
return R.string.password_reminder_freq_monthly;
case QUARTERLY:
return R.string.password_reminder_freq_quarterly;
default:
return R.string.password_reminder_freq_never;
}
}
public static PassReminderFreq fromInteger(int i) {
return PassReminderFreq.values()[i];
}
}
@@ -7,11 +7,38 @@ import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import androidx.annotation.Nullable;
import com.beemdevelopment.aegis.util.JsonUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class Preferences {
public static final int AUTO_LOCK_OFF = 1 << 0;
public static final int AUTO_LOCK_ON_BACK_BUTTON = 1 << 1;
public static final int AUTO_LOCK_ON_MINIMIZE = 1 << 2;
public static final int AUTO_LOCK_ON_DEVICE_LOCK = 1 << 3;
public static final int[] AUTO_LOCK_SETTINGS = {
AUTO_LOCK_ON_BACK_BUTTON,
AUTO_LOCK_ON_MINIMIZE,
AUTO_LOCK_ON_DEVICE_LOCK
};
private SharedPreferences _prefs;
public Preferences(Context context) {
@@ -26,55 +53,102 @@ public class Preferences {
return _prefs.getBoolean("pref_tap_to_reveal", false);
}
public boolean isSearchAccountNameEnabled() {
return _prefs.getBoolean("pref_search_names", false);
}
public boolean isEntryHighlightEnabled() {
return _prefs.getBoolean("pref_highlight_entry", false);
}
public boolean isPauseFocusedEnabled() {
boolean dependenciesEnabled = isTapToRevealEnabled() || isEntryHighlightEnabled();
if (!dependenciesEnabled) return false;
return _prefs.getBoolean("pref_pause_entry", false);
}
public boolean isPanicTriggerEnabled() {
return _prefs.getBoolean("pref_panic_trigger", false);
}
public void setIsPanicTriggerEnabled(boolean enabled) {
_prefs.edit().putBoolean("pref_panic_trigger", enabled).apply();
}
public boolean isSecureScreenEnabled() {
// screen security should be enabled by default, but not for debug builds
return _prefs.getBoolean("pref_secure_screen", !BuildConfig.DEBUG);
}
public boolean isPasswordReminderEnabled() {
return _prefs.getBoolean("pref_password_reminder", true);
public PassReminderFreq getPasswordReminderFrequency() {
final String key = "pref_password_reminder_freq";
if (_prefs.contains(key) || _prefs.getBoolean("pref_password_reminder", true)) {
int i = _prefs.getInt(key, PassReminderFreq.BIWEEKLY.ordinal());
return PassReminderFreq.fromInteger(i);
}
return PassReminderFreq.NEVER;
}
public void setPasswordReminderFrequency(PassReminderFreq freq) {
_prefs.edit().putInt("pref_password_reminder_freq", freq.ordinal()).apply();
}
public boolean isPasswordReminderNeeded() {
long diff = new Date().getTime() - getPasswordReminderTimestamp().getTime();
long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
return isPasswordReminderEnabled() && days >= 30;
return isPasswordReminderNeeded(new Date().getTime());
}
boolean isPasswordReminderNeeded(long currTime) {
PassReminderFreq freq = getPasswordReminderFrequency();
if (freq == PassReminderFreq.NEVER) {
return false;
}
long duration = currTime - getPasswordReminderTimestamp().getTime();
return duration >= freq.getDurationMillis();
}
public Date getPasswordReminderTimestamp() {
return new Date(_prefs.getLong("pref_password_reminder_counter", 0));
}
void setPasswordReminderTimestamp(long timestamp) {
_prefs.edit().putLong("pref_password_reminder_counter", timestamp).apply();
}
public void resetPasswordReminderTimestamp() {
_prefs.edit().putLong("pref_password_reminder_counter", new Date().getTime()).apply();
setPasswordReminderTimestamp(new Date().getTime());
}
public boolean isAccountNameVisible() {
return _prefs.getBoolean("pref_account_name", true);
}
public int getCodeGroupSize() {
if (_prefs.getBoolean("pref_code_group_size", false)) {
return 2;
} else {
return 3;
}
public CodeGrouping getCodeGroupSize() {
String value = _prefs.getString("pref_code_group_size_string", "GROUPING_THREES");
return CodeGrouping.valueOf(value);
}
public boolean isIntroDone() {
return _prefs.getBoolean("pref_intro", false);
}
private int getAutoLockMask() {
final int def = AUTO_LOCK_ON_BACK_BUTTON | AUTO_LOCK_ON_DEVICE_LOCK;
if (!_prefs.contains("pref_auto_lock_mask")) {
return _prefs.getBoolean("pref_auto_lock", true) ? def : AUTO_LOCK_OFF;
}
return _prefs.getInt("pref_auto_lock_mask", def);
}
public boolean isAutoLockEnabled() {
return _prefs.getBoolean("pref_auto_lock", true);
return getAutoLockMask() != AUTO_LOCK_OFF;
}
public boolean isAutoLockTypeEnabled(int autoLockType) {
return (getAutoLockMask() & autoLockType) == autoLockType;
}
public void setAutoLockMask(int autoLock) {
_prefs.edit().putInt("pref_auto_lock_mask", autoLock).apply();
}
public void setIntroDone(boolean done) {
@@ -113,6 +187,54 @@ public class Preferences {
_prefs.edit().putInt("pref_current_view_mode", viewMode.ordinal()).apply();
}
public Integer getUsageCount(UUID uuid) {
Integer usageCount = getUsageCounts().get(uuid);
return usageCount != null ? usageCount : 0;
}
public void resetUsageCount(UUID uuid) {
Map<UUID, Integer> usageCounts = getUsageCounts();
usageCounts.put(uuid, 0);
setUsageCount(usageCounts);
}
public void clearUsageCount() {
_prefs.edit().remove("pref_usage_count").apply();
}
public Map<UUID, Integer> getUsageCounts() {
Map<UUID, Integer> usageCounts = new HashMap<>();
String usageCount = _prefs.getString("pref_usage_count", "");
try {
JSONArray arr = new JSONArray(usageCount);
for (int i = 0; i < arr.length(); i++) {
JSONObject json = arr.getJSONObject(i);
usageCounts.put(UUID.fromString(json.getString("uuid")), json.getInt("count"));
}
} catch (JSONException ignored) {
}
return usageCounts;
}
public void setUsageCount(Map<UUID, Integer> usageCounts) {
JSONArray usageCountJson = new JSONArray();
for (Map.Entry<UUID, Integer> entry : usageCounts.entrySet()) {
JSONObject entryJson = new JSONObject();
try {
entryJson.put("uuid", entry.getKey());
entryJson.put("count", entry.getValue());
usageCountJson.put(entryJson);
} catch (JSONException e) {
e.printStackTrace();
}
}
_prefs.edit().putString("pref_usage_count", usageCountJson.toString()).apply();
}
public int getTimeout() {
return _prefs.getInt("pref_timeout", -1);
}
@@ -128,7 +250,21 @@ public class Preferences {
}
}
return new Locale(lang);
String[] parts = lang.split("_");
if (parts.length == 1) {
return new Locale(parts[0]);
}
return new Locale(parts[0], parts[1]);
}
public boolean isAndroidBackupsEnabled() {
return _prefs.getBoolean("pref_android_backups", false);
}
public void setIsAndroidBackupsEnabled(boolean enabled) {
_prefs.edit().putBoolean("pref_android_backups", enabled).apply();
setAndroidBackupResult(null);
}
public boolean isBackupsEnabled() {
@@ -137,6 +273,7 @@ public class Preferences {
public void setIsBackupsEnabled(boolean enabled) {
_prefs.edit().putBoolean("pref_backups", enabled).apply();
setBuiltInBackupResult(null);
}
public Uri getBackupsLocation() {
@@ -148,6 +285,14 @@ public class Preferences {
return null;
}
public boolean getFocusSearchEnabled() {
return _prefs.getBoolean("pref_focus_search", false);
}
public void setFocusSearch(boolean enabled) {
_prefs.edit().putBoolean("pref_focus_search", enabled).apply();
}
public void setBackupsLocation(Uri location) {
_prefs.edit().putString("pref_backups_location", location == null ? null : location.toString()).apply();
}
@@ -160,12 +305,91 @@ public class Preferences {
_prefs.edit().putInt("pref_backups_versions", versions).apply();
}
public void setBackupsError(Exception e) {
_prefs.edit().putString("pref_backups_error", e == null ? null : e.toString()).apply();
public void setAndroidBackupResult(@Nullable BackupResult res) {
setBackupResult(false, res);
}
public String getBackupsError() {
return _prefs.getString("pref_backups_error", null);
public void setBuiltInBackupResult(@Nullable BackupResult res) {
setBackupResult(true, res);
}
@Nullable
public BackupResult getAndroidBackupResult() {
return getBackupResult(false);
}
@Nullable
public BackupResult getBuiltInBackupResult() {
return getBackupResult(true);
}
@Nullable
public Preferences.BackupResult getErroredBackupResult() {
Preferences.BackupResult res = getBuiltInBackupResult();
if (res != null && !res.isSuccessful()) {
return res;
}
res = getAndroidBackupResult();
if (res != null && !res.isSuccessful()) {
return res;
}
return null;
}
private void setBackupResult(boolean isBuiltInBackup, @Nullable BackupResult res) {
String json = null;
if (res != null) {
res.setIsBuiltIn(isBuiltInBackup);
json = res.toJson();
}
_prefs.edit().putString(getBackupResultKey(isBuiltInBackup), json).apply();
}
@Nullable
private BackupResult getBackupResult(boolean isBuiltInBackup) {
String json = _prefs.getString(getBackupResultKey(isBuiltInBackup), null);
if (json == null) {
return null;
}
try {
BackupResult res = BackupResult.fromJson(json);
res.setIsBuiltIn(isBuiltInBackup);
return res;
} catch (JSONException e) {
return null;
}
}
private static String getBackupResultKey(boolean isBuiltInBackup) {
return isBuiltInBackup ? "pref_backups_result_builtin": "pref_backups_result_android";
}
public void setIsBackupReminderNeeded(boolean needed) {
if (isBackupsReminderNeeded() != needed) {
_prefs.edit().putBoolean("pref_backups_reminder_needed", needed).apply();
}
}
public boolean isBackupsReminderNeeded() {
return _prefs.getBoolean("pref_backups_reminder_needed", false);
}
public void setIsPlaintextBackupWarningNeeded(boolean needed) {
_prefs.edit().putBoolean("pref_plaintext_backup_warning_needed", needed).apply();
}
public boolean isPlaintextBackupWarningNeeded() {
return !isPlaintextBackupWarningDisabled()
&& _prefs.getBoolean("pref_plaintext_backup_warning_needed", false);
}
public void setIsPlaintextBackupWarningDisabled(boolean disabled) {
_prefs.edit().putBoolean("pref_plaintext_backup_warning_disabled", disabled).apply();
}
public boolean isPlaintextBackupWarningDisabled() {
return _prefs.getBoolean("pref_plaintext_backup_warning_disabled", false);
}
public boolean isPinKeyboardEnabled() {
@@ -183,4 +407,108 @@ public class Preferences {
public boolean isCopyOnTapEnabled() {
return _prefs.getBoolean("pref_copy_on_tap", false);
}
public boolean isMinimizeOnCopyEnabled() {
return _prefs.getBoolean("pref_minimize_on_copy", false);
}
public void setGroupFilter(List<String> groupFilter) {
JSONArray json = new JSONArray(groupFilter);
_prefs.edit().putString("pref_group_filter", json.toString()).apply();
}
public List<String> getGroupFilter() {
String raw = _prefs.getString("pref_group_filter", null);
if (raw == null || raw.isEmpty()) {
return Collections.emptyList();
}
try {
JSONArray json = new JSONArray(raw);
List<String> filter = new ArrayList<>();
for (int i = 0; i < json.length(); i++) {
filter.add(json.isNull(i) ? null : json.optString(i));
}
return filter;
} catch (JSONException e) {
return Collections.emptyList();
}
}
public static class BackupResult {
private final Date _time;
private boolean _isBuiltIn;
private final String _error;
public BackupResult(@Nullable Exception e) {
this(new Date(), e == null ? null : e.toString());
}
private BackupResult(Date time, @Nullable String error) {
_time = time;
_error = error;
}
@Nullable
public String getError() {
return _error;
}
public boolean isSuccessful() {
return _error == null;
}
public Date getTime() {
return _time;
}
public String getHumanReadableTime() {
return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(_time);
}
public boolean isBuiltIn() {
return _isBuiltIn;
}
private void setIsBuiltIn(boolean isBuiltIn) {
_isBuiltIn = isBuiltIn;
}
public String toJson() {
JSONObject obj = new JSONObject();
try {
obj.put("time", _time.getTime());
obj.put("error", _error == null ? JSONObject.NULL : _error);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return obj.toString();
}
public static BackupResult fromJson(String json) throws JSONException {
JSONObject obj = new JSONObject(json);
long time = obj.getLong("time");
String error = JsonUtils.optString(obj, "error");
return new BackupResult(new Date(time), error);
}
}
public enum CodeGrouping {
HALVES(-1),
NO_GROUPING(-2),
GROUPING_TWOS(2),
GROUPING_THREES(3),
GROUPING_FOURS(4);
private final int _value;
CodeGrouping(int value) {
_value = value;
}
public int getValue() {
return _value;
}
}
}
@@ -1,5 +1,6 @@
package com.beemdevelopment.aegis;
import com.beemdevelopment.aegis.helpers.comparators.UsageCountComparator;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.helpers.comparators.AccountNameComparator;
import com.beemdevelopment.aegis.helpers.comparators.IssuerNameComparator;
@@ -12,7 +13,8 @@ public enum SortCategory {
ACCOUNT,
ACCOUNT_REVERSED,
ISSUER,
ISSUER_REVERSED;
ISSUER_REVERSED,
USAGE_COUNT;
private static SortCategory[] _values;
@@ -40,6 +42,9 @@ public enum SortCategory {
case ISSUER_REVERSED:
comparator = Collections.reverseOrder(new IssuerNameComparator());
break;
case USAGE_COUNT:
comparator = Collections.reverseOrder(new UsageCountComparator());
break;
}
return comparator;
@@ -57,6 +62,8 @@ public enum SortCategory {
return R.id.menu_sort_alphabetically;
case ISSUER_REVERSED:
return R.id.menu_sort_alphabetically_reverse;
case USAGE_COUNT:
return R.id.menu_sort_usage_count;
default:
return R.id.menu_sort_custom;
}
@@ -10,14 +10,20 @@ public class ThemeMap {
}
public static final Map<Theme, Integer> DEFAULT = ImmutableMap.of(
Theme.LIGHT, R.style.AppTheme,
Theme.DARK, R.style.AppTheme_Dark,
Theme.AMOLED, R.style.AppTheme_TrueBlack
Theme.LIGHT, R.style.Theme_Aegis_Light_Default,
Theme.DARK, R.style.Theme_Aegis_Dark_Default,
Theme.AMOLED, R.style.Theme_Aegis_TrueDark_Default
);
public static final Map<Theme, Integer> NO_ACTION_BAR = ImmutableMap.of(
Theme.LIGHT, R.style.AppTheme_Light_NoActionBar,
Theme.DARK, R.style.AppTheme_Dark_NoActionBar,
Theme.AMOLED, R.style.AppTheme_TrueBlack_NoActionBar
Theme.LIGHT, R.style.Theme_Aegis_Light_NoActionBar,
Theme.DARK, R.style.Theme_Aegis_Dark_NoActionBar,
Theme.AMOLED, R.style.Theme_Aegis_TrueDark_NoActionBar
);
public static final Map<Theme, Integer> FULLSCREEN = ImmutableMap.of(
Theme.LIGHT, R.style.Theme_Aegis_Light_Fullscreen,
Theme.DARK, R.style.Theme_Aegis_Dark_Fullscreen,
Theme.AMOLED, R.style.Theme_Aegis_TrueDark_Fullscreen
);
}
@@ -2,7 +2,7 @@ package com.beemdevelopment.aegis.crypto;
import android.os.Build;
import org.bouncycastle.crypto.generators.SCrypt;
import com.beemdevelopment.aegis.crypto.bc.SCrypt;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -0,0 +1,255 @@
/*
Copyright (c) 2000-2021 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
package com.beemdevelopment.aegis.crypto.bc;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Integers;
import org.bouncycastle.util.Pack;
/**
* Implementation of the scrypt a password-based key derivation function.
* <p>
* Scrypt was created by Colin Percival and is specified in <a
* href="https://tools.ietf.org/html/rfc7914">RFC 7914 - The scrypt Password-Based Key Derivation Function</a>
*/
public class SCrypt
{
private SCrypt()
{
// not used.
}
/**
* Generate a key using the scrypt key derivation function.
*
* @param P the bytes of the pass phrase.
* @param S the salt to use for this invocation.
* @param N CPU/Memory cost parameter. Must be larger than 1, a power of 2 and less than
* <code>2^(128 * r / 8)</code>.
* @param r the block size, must be &gt;= 1.
* @param p Parallelization parameter. Must be a positive integer less than or equal to
* <code>Integer.MAX_VALUE / (128 * r * 8)</code>.
* @param dkLen the length of the key to generate.
* @return the generated key.
*/
public static byte[] generate(byte[] P, byte[] S, int N, int r, int p, int dkLen)
{
if (P == null)
{
throw new IllegalArgumentException("Passphrase P must be provided.");
}
if (S == null)
{
throw new IllegalArgumentException("Salt S must be provided.");
}
if (N <= 1 || !isPowerOf2(N))
{
throw new IllegalArgumentException("Cost parameter N must be > 1 and a power of 2");
}
// Only value of r that cost (as an int) could be exceeded for is 1
if (r == 1 && N >= 65536)
{
throw new IllegalArgumentException("Cost parameter N must be > 1 and < 65536.");
}
if (r < 1)
{
throw new IllegalArgumentException("Block size r must be >= 1.");
}
int maxParallel = Integer.MAX_VALUE / (128 * r * 8);
if (p < 1 || p > maxParallel)
{
throw new IllegalArgumentException("Parallelisation parameter p must be >= 1 and <= " + maxParallel
+ " (based on block size r of " + r + ")");
}
if (dkLen < 1)
{
throw new IllegalArgumentException("Generated key length dkLen must be >= 1.");
}
return MFcrypt(P, S, N, r, p, dkLen);
}
private static byte[] MFcrypt(byte[] P, byte[] S, int N, int r, int p, int dkLen)
{
int MFLenBytes = r * 128;
byte[] bytes = SingleIterationPBKDF2(P, S, p * MFLenBytes);
int[] B = null;
try
{
int BLen = bytes.length >>> 2;
B = new int[BLen];
Pack.littleEndianToInt(bytes, 0, B);
/*
* Chunk memory allocations; We choose 'd' so that there will be 2**d chunks, each not
* larger than 32KiB, except that the minimum chunk size is 2 * r * 32.
*/
int d = 0, total = N * r;
while ((N - d) > 2 && total > (1 << 10))
{
++d;
total >>>= 1;
}
int MFLenWords = MFLenBytes >>> 2;
for (int BOff = 0; BOff < BLen; BOff += MFLenWords)
{
// TODO These can be done in parallel threads
SMix(B, BOff, N, d, r);
}
Pack.intToLittleEndian(B, bytes, 0);
return SingleIterationPBKDF2(P, bytes, dkLen);
}
finally
{
Clear(bytes);
Clear(B);
}
}
private static byte[] SingleIterationPBKDF2(byte[] P, byte[] S, int dkLen)
{
PBEParametersGenerator pGen = new PKCS5S2ParametersGenerator(new SHA256Digest());
pGen.init(P, S, 1);
KeyParameter key = (KeyParameter)pGen.generateDerivedMacParameters(dkLen * 8);
return key.getKey();
}
private static void SMix(int[] B, int BOff, int N, int d, int r)
{
int powN = Integers.numberOfTrailingZeros(N);
int blocksPerChunk = N >>> d;
int chunkCount = 1 << d, chunkMask = blocksPerChunk - 1, chunkPow = powN - d;
int BCount = r * 32;
int[] blockX1 = new int[16];
int[] blockX2 = new int[16];
int[] blockY = new int[BCount];
int[] X = new int[BCount];
int[][] VV = new int[chunkCount][];
try
{
System.arraycopy(B, BOff, X, 0, BCount);
for (int c = 0; c < chunkCount; ++c)
{
int[] V = new int[blocksPerChunk * BCount];
VV[c] = V;
int off = 0;
for (int i = 0; i < blocksPerChunk; i += 2)
{
System.arraycopy(X, 0, V, off, BCount);
off += BCount;
BlockMix(X, blockX1, blockX2, blockY, r);
System.arraycopy(blockY, 0, V, off, BCount);
off += BCount;
BlockMix(blockY, blockX1, blockX2, X, r);
}
}
int mask = N - 1;
for (int i = 0; i < N; ++i)
{
int j = X[BCount - 16] & mask;
int[] V = VV[j >>> chunkPow];
int VOff = (j & chunkMask) * BCount;
System.arraycopy(V, VOff, blockY, 0, BCount);
Xor(blockY, X, 0, blockY);
BlockMix(blockY, blockX1, blockX2, X, r);
}
System.arraycopy(X, 0, B, BOff, BCount);
}
finally
{
ClearAll(VV);
ClearAll(new int[][]{X, blockX1, blockX2, blockY});
}
}
private static void BlockMix(int[] B, int[] X1, int[] X2, int[] Y, int r)
{
System.arraycopy(B, B.length - 16, X1, 0, 16);
int BOff = 0, YOff = 0, halfLen = B.length >>> 1;
for (int i = 2 * r; i > 0; --i)
{
Xor(X1, B, BOff, X2);
Salsa20Engine.salsaCore(8, X2, X1);
System.arraycopy(X1, 0, Y, YOff, 16);
YOff = halfLen + BOff - YOff;
BOff += 16;
}
}
private static void Xor(int[] a, int[] b, int bOff, int[] output)
{
for (int i = output.length - 1; i >= 0; --i)
{
output[i] = a[i] ^ b[bOff + i];
}
}
private static void Clear(byte[] array)
{
if (array != null)
{
Arrays.fill(array, (byte)0);
}
}
private static void Clear(int[] array)
{
if (array != null)
{
Arrays.fill(array, 0);
}
}
private static void ClearAll(int[][] arrays)
{
for (int i = 0; i < arrays.length; ++i)
{
Clear(arrays[i]);
}
}
// note: we know X is non-zero
private static boolean isPowerOf2(int x)
{
return ((x & (x - 1)) == 0);
}
}
@@ -0,0 +1,118 @@
/*
Copyright (c) 2000-2021 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
package com.beemdevelopment.aegis.crypto.bc;
/**
* Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005
*/
public class Salsa20Engine {
private Salsa20Engine()
{
}
public static void salsaCore(int rounds, int[] input, int[] x)
{
if (input.length != 16)
{
throw new IllegalArgumentException();
}
if (x.length != 16)
{
throw new IllegalArgumentException();
}
if (rounds % 2 != 0)
{
throw new IllegalArgumentException("Number of rounds must be even");
}
int x00 = input[ 0];
int x01 = input[ 1];
int x02 = input[ 2];
int x03 = input[ 3];
int x04 = input[ 4];
int x05 = input[ 5];
int x06 = input[ 6];
int x07 = input[ 7];
int x08 = input[ 8];
int x09 = input[ 9];
int x10 = input[10];
int x11 = input[11];
int x12 = input[12];
int x13 = input[13];
int x14 = input[14];
int x15 = input[15];
for (int i = rounds; i > 0; i -= 2)
{
x04 ^= Integer.rotateLeft(x00 + x12, 7);
x08 ^= Integer.rotateLeft(x04 + x00, 9);
x12 ^= Integer.rotateLeft(x08 + x04, 13);
x00 ^= Integer.rotateLeft(x12 + x08, 18);
x09 ^= Integer.rotateLeft(x05 + x01, 7);
x13 ^= Integer.rotateLeft(x09 + x05, 9);
x01 ^= Integer.rotateLeft(x13 + x09, 13);
x05 ^= Integer.rotateLeft(x01 + x13, 18);
x14 ^= Integer.rotateLeft(x10 + x06, 7);
x02 ^= Integer.rotateLeft(x14 + x10, 9);
x06 ^= Integer.rotateLeft(x02 + x14, 13);
x10 ^= Integer.rotateLeft(x06 + x02, 18);
x03 ^= Integer.rotateLeft(x15 + x11, 7);
x07 ^= Integer.rotateLeft(x03 + x15, 9);
x11 ^= Integer.rotateLeft(x07 + x03, 13);
x15 ^= Integer.rotateLeft(x11 + x07, 18);
x01 ^= Integer.rotateLeft(x00 + x03, 7);
x02 ^= Integer.rotateLeft(x01 + x00, 9);
x03 ^= Integer.rotateLeft(x02 + x01, 13);
x00 ^= Integer.rotateLeft(x03 + x02, 18);
x06 ^= Integer.rotateLeft(x05 + x04, 7);
x07 ^= Integer.rotateLeft(x06 + x05, 9);
x04 ^= Integer.rotateLeft(x07 + x06, 13);
x05 ^= Integer.rotateLeft(x04 + x07, 18);
x11 ^= Integer.rotateLeft(x10 + x09, 7);
x08 ^= Integer.rotateLeft(x11 + x10, 9);
x09 ^= Integer.rotateLeft(x08 + x11, 13);
x10 ^= Integer.rotateLeft(x09 + x08, 18);
x12 ^= Integer.rotateLeft(x15 + x14, 7);
x13 ^= Integer.rotateLeft(x12 + x15, 9);
x14 ^= Integer.rotateLeft(x13 + x12, 13);
x15 ^= Integer.rotateLeft(x14 + x13, 18);
}
x[ 0] = x00 + input[ 0];
x[ 1] = x01 + input[ 1];
x[ 2] = x02 + input[ 2];
x[ 3] = x03 + input[ 3];
x[ 4] = x04 + input[ 4];
x[ 5] = x05 + input[ 5];
x[ 6] = x06 + input[ 6];
x[ 7] = x07 + input[ 7];
x[ 8] = x08 + input[ 8];
x[ 9] = x09 + input[ 9];
x[10] = x10 + input[10];
x[11] = x11 + input[11];
x[12] = x12 + input[12];
x[13] = x13 + input[13];
x[14] = x14 + input[14];
x[15] = x15 + input[15];
}
}
@@ -14,18 +14,7 @@ public class HOTP {
public static OTP generateOTP(byte[] secret, String algo, int digits, long counter)
throws NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec key = new SecretKeySpec(secret, "RAW");
// encode counter in big endian
byte[] counterBytes = ByteBuffer.allocate(8)
.order(ByteOrder.BIG_ENDIAN)
.putLong(counter)
.array();
// calculate the hash of the counter
Mac mac = Mac.getInstance(algo);
mac.init(key);
byte[] hash = mac.doFinal(counterBytes);
byte[] hash = getHash(secret, algo, counter);
// truncate hash to get the HTOP value
// http://tools.ietf.org/html/rfc4226#section-5.4
@@ -37,4 +26,20 @@ public class HOTP {
return new OTP(otp, digits);
}
public static byte[] getHash(byte[] secret, String algo, long counter)
throws NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec key = new SecretKeySpec(secret, "RAW");
// encode counter in big endian
byte[] counterBytes = ByteBuffer.allocate(8)
.order(ByteOrder.BIG_ENDIAN)
.putLong(counter)
.array();
// calculate the hash of the counter
Mac mac = Mac.getInstance(algo);
mac.init(key);
return mac.doFinal(counterBytes);
}
}
@@ -0,0 +1,54 @@
package com.beemdevelopment.aegis.crypto.otp;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import com.beemdevelopment.aegis.encoding.Hex;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MOTP {
private final String _code;
private final int _digits;
private MOTP(String code, int digits) {
_code = code;
_digits = digits;
}
@NonNull
public static MOTP generateOTP(byte[] secret, String algo, int digits, int period, String pin)
throws NoSuchAlgorithmException {
return generateOTP(secret, algo, digits, period, pin, System.currentTimeMillis() / 1000);
}
@NonNull
public static MOTP generateOTP(byte[] secret, String algo, int digits, int period, String pin, long time)
throws NoSuchAlgorithmException {
long timeBasedCounter = time / period;
String secretAsString = Hex.encode(secret);
String toDigest = timeBasedCounter + secretAsString + pin;
String code = getDigest(algo, toDigest.getBytes(StandardCharsets.UTF_8));
return new MOTP(code, digits);
}
@VisibleForTesting
@NonNull
protected static String getDigest(String algo, byte[] toDigest) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algo);
byte[] digest = md.digest(toDigest);
return Hex.encode(digest);
}
@NonNull
@Override
public String toString() {
return _code.substring(0, _digits);
}
}
@@ -5,8 +5,8 @@ import androidx.annotation.NonNull;
public class OTP {
private static final String STEAM_ALPHABET = "23456789BCDFGHJKMNPQRTVWXY";
private int _code;
private int _digits;
private final int _code;
private final int _digits;
public OTP(int code, int digits) {
_code = code;
@@ -0,0 +1,71 @@
package com.beemdevelopment.aegis.crypto.otp;
import androidx.annotation.NonNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class YAOTP {
private static final int EN_ALPHABET_LENGTH = 26;
private final long _code;
private final int _digits;
private YAOTP(long code, int digits) {
_code = code;
_digits = digits;
}
public static YAOTP generateOTP(byte[] secret, String pin, int digits, String otpAlgo, long period)
throws NoSuchAlgorithmException, InvalidKeyException, IOException {
long seconds = System.currentTimeMillis() / 1000;
return generateOTP(secret, pin, digits, otpAlgo, seconds, period);
}
public static YAOTP generateOTP(byte[] secret, String pin, int digits, String otpAlgo, long seconds, long period)
throws NoSuchAlgorithmException, InvalidKeyException, IOException {
byte[] pinWithHash;
byte[] pinBytes = pin.getBytes(StandardCharsets.UTF_8);
try (ByteArrayOutputStream stream = new ByteArrayOutputStream(pinBytes.length + secret.length)) {
stream.write(pinBytes);
stream.write(secret);
pinWithHash = stream.toByteArray();
}
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] keyHash = md.digest(pinWithHash);
if (keyHash[0] == 0) {
keyHash = Arrays.copyOfRange(keyHash, 1, keyHash.length);
}
long counter = (long) Math.floor((double) seconds / period);
byte[] periodHash = HOTP.getHash(keyHash, otpAlgo, counter);
int offset = periodHash[periodHash.length - 1] & 0xf;
periodHash[offset] &= 0x7f;
long otp = ByteBuffer.wrap(periodHash)
.order(ByteOrder.BIG_ENDIAN)
.getLong(offset);
return new YAOTP(otp, digits);
}
@NonNull
@Override
public String toString() {
long code = _code % (long) Math.pow(EN_ALPHABET_LENGTH, _digits);
char[] chars = new char[_digits];
for (int i = _digits - 1; i >= 0; i--) {
chars[i] = (char) ('a' + (code % EN_ALPHABET_LENGTH));
code /= EN_ALPHABET_LENGTH;
}
return new String(chars);
}
}
@@ -0,0 +1,14 @@
package com.beemdevelopment.aegis.crypto.pins;
import info.guardianproject.trustedintents.ApkSignaturePin;
public final class GuardianProjectFDroidRSA2048 extends ApkSignaturePin {
public GuardianProjectFDroidRSA2048() {
fingerprints = new String[]{
"927f7e38b6acbecd84e02dace33efa9a7a2f0979750f28f585688ee38b3a4e28",
};
certificates = new byte[][]{
{48, -126, 3, 95, 48, -126, 2, 71, -96, 3, 2, 1, 2, 2, 4, 28, -30, 107, -102, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 11, 5, 0, 48, 96, 49, 11, 48, 9, 6, 3, 85, 4, 6, 19, 2, 85, 75, 49, 12, 48, 10, 6, 3, 85, 4, 8, 19, 3, 79, 82, 71, 49, 12, 48, 10, 6, 3, 85, 4, 7, 19, 3, 79, 82, 71, 49, 19, 48, 17, 6, 3, 85, 4, 10, 19, 10, 102, 100, 114, 111, 105, 100, 46, 111, 114, 103, 49, 15, 48, 13, 6, 3, 85, 4, 11, 19, 6, 70, 68, 114, 111, 105, 100, 49, 15, 48, 13, 6, 3, 85, 4, 3, 19, 6, 70, 68, 114, 111, 105, 100, 48, 30, 23, 13, 49, 55, 49, 50, 48, 55, 49, 55, 51, 48, 52, 50, 90, 23, 13, 52, 53, 48, 52, 50, 52, 49, 55, 51, 48, 52, 50, 90, 48, 96, 49, 11, 48, 9, 6, 3, 85, 4, 6, 19, 2, 85, 75, 49, 12, 48, 10, 6, 3, 85, 4, 8, 19, 3, 79, 82, 71, 49, 12, 48, 10, 6, 3, 85, 4, 7, 19, 3, 79, 82, 71, 49, 19, 48, 17, 6, 3, 85, 4, 10, 19, 10, 102, 100, 114, 111, 105, 100, 46, 111, 114, 103, 49, 15, 48, 13, 6, 3, 85, 4, 11, 19, 6, 70, 68, 114, 111, 105, 100, 49, 15, 48, 13, 6, 3, 85, 4, 3, 19, 6, 70, 68, 114, 111, 105, 100, 48, -126, 1, 34, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3, -126, 1, 15, 0, 48, -126, 1, 10, 2, -126, 1, 1, 0, -107, -115, -106, 1, -26, 72, -105, -99, 62, 3, -55, 34, 99, -112, -68, -20, -115, 31, 34, 118, -50, 12, -32, -59, 74, -58, -37, -87, 21, 105, 36, -82, 13, -51, 66, 4, 55, -111, 13, -46, -7, -69, -15, 36, 118, -7, 101, -86, 123, -83, -103, 110, 116, -54, 112, 46, 12, 96, -76, -48, -70, -33, -81, 52, 59, 73, 107, -126, -72, -25, 32, 93, 29, -20, 5, -41, -27, 123, -9, 104, -31, -59, -1, -83, -93, 99, 85, -116, -62, -55, 18, -63, 6, -51, -110, 33, 9, 7, -49, 102, -20, -122, -124, -68, 93, -102, 31, 48, 86, 96, -99, 105, -52, 95, 12, 57, 99, 12, -24, 70, 40, -99, -20, -21, -85, -70, -105, 95, 117, -31, 126, -126, -39, 46, -62, 59, -23, -74, 108, -12, -56, -40, -96, 79, -37, -82, 1, 99, -104, 48, -60, 92, 14, 109, 127, -22, 31, 115, -27, 108, 9, 92, 118, -45, 103, 117, 57, -50, -82, 114, -113, 68, -82, 87, 96, 111, 72, 65, -63, 12, 31, -34, -31, -55, -101, 101, 101, 59, 73, -119, -122, 82, 28, 47, -108, -85, 59, 46, 89, -93, -1, 9, -11, -51, 63, -44, 109, -76, -103, -26, -49, -80, 6, 52, -27, 73, -104, 40, 2, -101, -124, 60, -52, -105, -70, -24, -62, 88, 38, 53, -99, -92, 31, 119, 26, 79, 60, -124, 25, -115, -89, -115, -109, 0, 6, 122, -78, 116, 82, 3, 39, -67, 45, -43, 17, -39, 2, 3, 1, 0, 1, -93, 33, 48, 31, 48, 29, 6, 3, 85, 29, 14, 4, 22, 4, 20, 63, 109, -42, -109, 25, 22, 7, -37, -22, -41, -38, 58, -56, 2, -68, -38, -22, 65, -28, -60, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 11, 5, 0, 3, -126, 1, 1, 0, 94, 17, 31, 36, 85, -11, 85, 44, 19, -80, -20, -92, -118, 93, 40, 45, 96, 31, -3, -37, -110, -96, 102, 81, 61, -74, -125, -117, -112, 58, -47, 17, 78, -18, 111, -116, 26, -91, 73, 100, 84, -99, 21, 87, 73, -106, 108, -51, -125, -21, 119, -88, -78, 2, 82, -109, -64, -9, -86, -112, -115, 66, -86, 46, 71, 107, -65, 96, -102, 47, 35, -45, -126, 33, 34, 121, -25, -85, -121, -56, -42, 22, -1, -95, -86, 81, 100, -70, 113, 104, -73, 22, -19, 79, -19, 52, 62, 42, 76, -112, 94, -34, 42, -57, -75, -90, -58, 118, 127, -106, -39, 108, -56, -79, 103, -33, 22, 3, 47, 103, -76, -81, 53, -22, -44, -26, -102, 63, -99, 39, 38, -108, 75, 33, 10, 25, -110, -125, -115, 114, -69, 73, -112, 36, 74, 77, -82, -44, 29, -123, -8, -117, 71, -105, 15, -109, 51, 22, 4, 80, 1, 43, 118, 121, -113, -70, 83, -56, 82, -110, 4, -63, 16, -57, 126, -70, 81, 73, 61, 2, -61, 24, -14, -10, 4, -21, 90, 24, 66, 41, -57, -60, -113, -18, -54, -1, 103, -75, 32, -64, 67, 103, 109, -79, -12, -113, -27, 114, 89, 116, 115, -13, -123, -70, 61, -41, -46, -118, 29, -105, -97, -75, 39, -51, 60, 88, 125, 55, -46, -95, 52, 57, 52, -115, 80, 44, 109, 119, -116, -62, -77, -74, -88, 41, 57, -65, -71, -115, -67, 23, 66, -21, 56, 51, -91, 109},};
}
}
@@ -2,6 +2,9 @@ package com.beemdevelopment.aegis.encoding;
import com.google.common.io.BaseEncoding;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
public class Base32 {
private Base32() {
@@ -9,7 +12,7 @@ public class Base32 {
public static byte[] decode(String s) throws EncodingException {
try {
return BaseEncoding.base32().decode(s.toUpperCase());
return BaseEncoding.base32().decode(s.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new EncodingException(e);
}
@@ -18,4 +21,9 @@ public class Base32 {
public static String encode(byte[] data) {
return BaseEncoding.base32().omitPadding().encode(data);
}
public static String encode(String s) {
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
return encode(bytes);
}
}
@@ -6,4 +6,8 @@ public class EncodingException extends IOException {
public EncodingException(Throwable cause) {
super(cause);
}
public EncodingException(String message) {
super(message);
}
}
@@ -2,6 +2,8 @@ package com.beemdevelopment.aegis.encoding;
import com.google.common.io.BaseEncoding;
import java.util.Locale;
public class Hex {
private Hex() {
@@ -9,7 +11,7 @@ public class Hex {
public static byte[] decode(String s) throws EncodingException {
try {
return BaseEncoding.base16().decode(s.toUpperCase());
return BaseEncoding.base16().decode(s.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new EncodingException(e);
}
@@ -2,8 +2,8 @@ package com.beemdevelopment.aegis.helpers;
import android.content.Context;
import androidx.biometric.BiometricConstants;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
public class BiometricsHelper {
private BiometricsHelper() {
@@ -12,16 +12,16 @@ public class BiometricsHelper {
public static BiometricManager getManager(Context context) {
BiometricManager manager = BiometricManager.from(context);
if (manager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) {
if (manager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS) {
return manager;
}
return null;
}
public static boolean isCanceled(int errorCode) {
return errorCode == BiometricConstants.ERROR_CANCELED
|| errorCode == BiometricConstants.ERROR_USER_CANCELED
|| errorCode == BiometricConstants.ERROR_NEGATIVE_BUTTON;
return errorCode == BiometricPrompt.ERROR_CANCELED
|| errorCode == BiometricPrompt.ERROR_USER_CANCELED
|| errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON;
}
public static boolean isAvailable(Context context) {
@@ -0,0 +1,31 @@
package com.beemdevelopment.aegis.helpers;
import android.graphics.Bitmap;
public class BitmapHelper {
private BitmapHelper() {
}
/**
* Scales the given Bitmap to the given maximum width/height, while keeping the aspect ratio intact.
*/
public static Bitmap resize(Bitmap bitmap, int maxWidth, int maxHeight) {
if (maxHeight <= 0 || maxWidth <= 0) {
return bitmap;
}
float maxRatio = (float) maxWidth / maxHeight;
float ratio = (float) bitmap.getWidth() / bitmap.getHeight();
int width = maxWidth;
int height = maxHeight;
if (maxRatio > 1) {
width = (int) ((float) maxHeight * ratio);
} else {
height = (int) ((float) maxWidth / ratio);
}
return Bitmap.createScaledBitmap(bitmap, width, height, true);
}
}
@@ -0,0 +1,39 @@
package com.beemdevelopment.aegis.helpers;
import android.content.Context;
import android.content.ContextWrapper;
import androidx.activity.ComponentActivity;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import javax.annotation.Nullable;
/**
* ContextHelper contains some disgusting hacks to obtain the Activity/Lifecycle from a Context.
*/
public class ContextHelper {
private ContextHelper() {
}
// source: https://github.com/androidx/androidx/blob/e32e1da51a0c7448c74861c667fa76738a415a89/mediarouter/mediarouter/src/main/java/androidx/mediarouter/app/MediaRouteButton.java#L425-L435
@Nullable
public static ComponentActivity getActivity(@NonNull Context context) {
while (context instanceof ContextWrapper) {
if (context instanceof ComponentActivity) {
return (ComponentActivity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
@Nullable
public static Lifecycle getLifecycle(@NonNull Context context) {
ComponentActivity activity = getActivity(context);
return activity == null ? null : activity.getLifecycle();
}
}
@@ -0,0 +1,27 @@
package com.beemdevelopment.aegis.helpers;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import androidx.annotation.ArrayRes;
import com.beemdevelopment.aegis.R;
import java.util.List;
public class DropdownHelper {
private DropdownHelper() {
}
public static void fillDropdown(Context context, AutoCompleteTextView dropdown, @ArrayRes int textArrayResId) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, textArrayResId, R.layout.dropdown_list_item);
dropdown.setAdapter(adapter);
}
public static <T> void fillDropdown(Context context, AutoCompleteTextView dropdown, List<T> items) {
ArrayAdapter<T> adapter = new ArrayAdapter<>(context, R.layout.dropdown_list_item, items);
dropdown.setAdapter(adapter);
}
}
@@ -9,22 +9,10 @@ public class EditTextHelper {
private EditTextHelper() {
}
public static void clearEditText(EditText text) {
text.getText().clear();
}
public static char[] getEditTextChars(EditText text) {
return getEditTextChars(text, false);
}
public static char[] getEditTextChars(EditText text, boolean removeSpaces) {
String editTextString = text.getText().toString();
if (removeSpaces) {
editTextString = editTextString.replaceAll("\\s","");
}
char[] chars = new char[editTextString.length()];
editTextString.getChars(0, editTextString.length(), chars, 0);
Editable editable = text.getText();
char[] chars = new char[editable.length()];
editable.getChars(0, editable.length(), chars, 0);
return chars;
}
@@ -6,7 +6,6 @@ import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
public class FabScrollHelper {
private View _fabMenu;
@@ -17,7 +16,27 @@ public class FabScrollHelper {
}
public void onScroll(int dx, int dy) {
if (dy > 0 && _fabMenu.getVisibility() == View.VISIBLE && !_isAnimating) {
if (dy > 2 && _fabMenu.getVisibility() == View.VISIBLE && !_isAnimating) {
setVisible(false);
} else if (dy < -2 && _fabMenu.getVisibility() != View.VISIBLE && !_isAnimating) {
setVisible(true);
}
}
public void setVisible(boolean visible) {
if (visible) {
_fabMenu.setVisibility(View.VISIBLE);
_fabMenu.animate()
.translationY(0)
.setInterpolator(new DecelerateInterpolator(2))
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
_isAnimating = false;
super.onAnimationEnd(animation);
}
}).start();
} else {
_isAnimating = true;
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) _fabMenu.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
@@ -32,18 +51,7 @@ public class FabScrollHelper {
super.onAnimationEnd(animation);
}
}).start();
} else if (dy < 0 && _fabMenu.getVisibility() != View.VISIBLE && !_isAnimating) {
_fabMenu.setVisibility(View.VISIBLE);
_fabMenu.animate()
.translationY(0)
.setInterpolator(new DecelerateInterpolator(2))
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
_isAnimating = false;
super.onAnimationEnd(animation);
}
}).start();
}
}
}
@@ -0,0 +1,26 @@
package com.beemdevelopment.aegis.helpers;
import android.os.Build;
import android.widget.ImageView;
import com.beemdevelopment.aegis.icons.IconType;
public class IconViewHelper {
private IconViewHelper() {
}
/**
* Sets the layer type of the given ImageView based on the given IconType. If the
* icon type is SVG and SDK <= 27, the layer type is set to software. Otherwise, it
* is set to hardware.
*/
public static void setLayerType(ImageView view, IconType iconType) {
if (iconType == IconType.SVG && Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) {
view.setLayerType(ImageView.LAYER_TYPE_SOFTWARE, null);
return;
}
view.setLayerType(ImageView.LAYER_TYPE_HARDWARE, null);
}
}
@@ -0,0 +1,14 @@
package com.beemdevelopment.aegis.helpers;
import android.content.Context;
import android.util.DisplayMetrics;
public class MetricsHelper {
private MetricsHelper() {
}
public static int convertDpToPixels(Context context, float dp) {
return (int) (dp * (context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT));
}
}
@@ -1,28 +1,23 @@
package com.beemdevelopment.aegis.helpers;
import static android.graphics.ImageFormat.YUV_420_888;
import android.util.Log;
import android.util.Size;
import androidx.annotation.NonNull;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import java.nio.ByteBuffer;
import static android.graphics.ImageFormat.YUV_420_888;
import static android.graphics.ImageFormat.YUV_422_888;
import static android.graphics.ImageFormat.YUV_444_888;
public class QrCodeAnalyzer implements ImageAnalysis.Analyzer {
private static final String TAG = QrCodeAnalyzer.class.getSimpleName();
public static final Size RESOLUTION = new Size(1200, 1600);
private final QrCodeAnalyzer.Listener _listener;
@@ -33,29 +28,35 @@ public class QrCodeAnalyzer implements ImageAnalysis.Analyzer {
@Override
public void analyze(@NonNull ImageProxy image) {
int format = image.getFormat();
if (format != YUV_420_888 && format != YUV_422_888 && format != YUV_444_888) {
Log.e(TAG, String.format("Expected YUV format, got %d instead", format));
if (format != YUV_420_888) {
Log.e(TAG, String.format("Unexpected YUV image format: %d", format));
image.close();
return;
}
ByteBuffer buf = image.getPlanes()[0].getBuffer();
ImageProxy.PlaneProxy plane = image.getPlanes()[0];
ByteBuffer buf = plane.getBuffer();
byte[] data = new byte[buf.remaining()];
buf.get(data);
buf.rewind();
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(
data, image.getWidth(), image.getHeight(), 0, 0, image.getWidth(), image.getHeight(), false
data,
plane.getRowStride(),
image.getHeight(),
0,
0,
image.getWidth(),
image.getHeight(),
false
);
QRCodeReader reader = new QRCodeReader();
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
Result result = reader.decode(bitmap);
Result result = QrCodeHelper.decodeFromSource(source);
if (_listener != null) {
_listener.onQrCodeDetected(result);
}
} catch (ChecksumException | FormatException | NotFoundException ignored) {
} catch (NotFoundException ignored) {
} finally {
image.close();
@@ -0,0 +1,96 @@
package com.beemdevelopment.aegis.helpers;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import androidx.annotation.ColorInt;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class QrCodeHelper {
private QrCodeHelper() {
}
public static Result decodeFromSource(LuminanceSource source) throws NotFoundException {
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.POSSIBLE_FORMATS, Collections.singletonList(BarcodeFormat.QR_CODE));
hints.put(DecodeHintType.ALSO_INVERTED, true);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
return reader.decode(bitmap, hints);
}
public static Result decodeFromStream(InputStream inStream) throws DecodeError {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeStream(inStream, null, bmOptions);
if (bitmap == null) {
throw new DecodeError("Unable to decode stream to bitmap");
}
// If ZXing is not able to decode the image on the first try, we try a couple of
// more times with smaller versions of the same image.
for (int i = 0; i <= 2; i++) {
if (i != 0) {
bitmap = BitmapHelper.resize(bitmap, bitmap.getWidth() / (i * 2), bitmap.getHeight() / (i * 2));
}
try {
int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
LuminanceSource source = new RGBLuminanceSource(bitmap.getWidth(), bitmap.getHeight(), pixels);
return decodeFromSource(source);
} catch (NotFoundException ignored) {
}
}
throw new DecodeError(NotFoundException.getNotFoundInstance());
}
public static Bitmap encodeToBitmap(String data, int width, int height, @ColorInt int backgroundColor) throws WriterException {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.QR_CODE, width, height);
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ? Color.BLACK : backgroundColor;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
public static class DecodeError extends Exception {
public DecodeError(String message) {
super(message);
}
public DecodeError(Throwable cause) {
super(cause);
}
}
}
@@ -0,0 +1,47 @@
package com.beemdevelopment.aegis.helpers;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.webkit.MimeTypeMap;
import androidx.documentfile.provider.DocumentFile;
public class SafHelper {
private SafHelper() {
}
public static String getFileName(Context context, Uri uri) {
if (uri.getScheme() != null && uri.getScheme().equals("content")) {
try (Cursor cursor = context.getContentResolver().query(uri, new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
int i = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (i != -1) {
return cursor.getString(i);
}
}
}
}
return uri.getLastPathSegment();
}
public static String getMimeType(Context context, Uri uri) {
DocumentFile file = DocumentFile.fromSingleUri(context, uri);
if (file != null) {
String fileType = file.getType();
if (fileType != null) {
return fileType;
}
String ext = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
if (ext != null) {
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
}
return null;
}
}
@@ -0,0 +1,32 @@
package com.beemdevelopment.aegis.helpers;
import android.view.animation.Animation;
public class SimpleAnimationEndListener implements Animation.AnimationListener {
private final Listener _listener;
public SimpleAnimationEndListener(Listener listener) {
_listener = listener;
}
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (_listener != null) {
_listener.onAnimationEnd(animation);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
public interface Listener {
void onAnimationEnd(Animation animation);
}
}
@@ -1,20 +1,23 @@
package com.beemdevelopment.aegis.helpers;
import static androidx.recyclerview.widget.RecyclerView.NO_POSITION;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.ui.views.EntryAdapter;
import com.beemdevelopment.aegis.vault.VaultEntry;
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
private VaultEntry _selectedEntry;
private final ItemTouchHelperAdapter _adapter;
private final EntryAdapter _adapter;
private boolean _positionChanged = false;
private boolean _isLongPressDragEnabled = true;
public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
public SimpleItemTouchHelperCallback(EntryAdapter adapter) {
_adapter = adapter;
}
@@ -28,7 +31,14 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
}
public void setSelectedEntry(VaultEntry entry) {
_selectedEntry = entry;
if (entry == null) {
_selectedEntry = null;
return;
}
if (!entry.isFavorite()) {
_selectedEntry = entry;
}
}
@Override
@@ -37,14 +47,22 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
}
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = 0;
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
// It's not clear when this can happen, but sometimes the ViewHolder
// that's passed to this function has a position of -1, leading
// to a crash down the line.
int position = viewHolder.getAdapterPosition();
EntryAdapter adapter = (EntryAdapter)recyclerView.getAdapter();
if (adapter.getEntryAt(position) != _selectedEntry)
{
if (position == NO_POSITION) {
return 0;
}
int swipeFlags = 0;
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
EntryAdapter adapter = (EntryAdapter) recyclerView.getAdapter();
if (adapter.isPositionFooter(position)
|| adapter.getEntryAt(position) != _selectedEntry
|| !isLongPressDragEnabled()) {
dragFlags = 0;
}
@@ -54,6 +72,9 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
if (target.getAdapterPosition() < _adapter.getShownFavoritesCount()){
return false;
}
_adapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
_positionChanged = true;
return true;
@@ -73,6 +94,4 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
_positionChanged = false;
}
}
}
@@ -0,0 +1,33 @@
package com.beemdevelopment.aegis.helpers;
import android.text.Editable;
import android.text.TextWatcher;
public final class SimpleTextWatcher implements TextWatcher {
private final Listener _listener;
public SimpleTextWatcher(Listener listener) {
_listener = listener;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (_listener != null) {
_listener.afterTextChanged(s);
}
}
public interface Listener {
void afterTextChanged(Editable s);
}
}
@@ -1,31 +0,0 @@
package com.beemdevelopment.aegis.helpers;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.List;
import androidx.annotation.ArrayRes;
public class SpinnerHelper {
private SpinnerHelper() {
}
public static void fillSpinner(Context context, Spinner spinner, @ArrayRes int textArrayResId) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, textArrayResId, android.R.layout.simple_spinner_item);
initSpinner(spinner, adapter);
}
public static <T> void fillSpinner(Context context, Spinner spinner, List<T> items) {
ArrayAdapter adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, items);
initSpinner(spinner, adapter);
}
private static void initSpinner(Spinner spinner, ArrayAdapter adapter) {
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.invalidate();
}
}
@@ -5,6 +5,7 @@ import android.view.View;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.text.BreakIterator;
import java.util.Arrays;
public class TextDrawableHelper {
@@ -48,6 +49,18 @@ public class TextDrawableHelper {
.width(view.getLayoutParams().width)
.height(view.getLayoutParams().height)
.endConfig()
.buildRect(text.substring(0, 1).toUpperCase(), color);
.buildRound(getFirstGrapheme(text).toUpperCase(), color);
}
private static String getFirstGrapheme(String text) {
BreakIterator iter = BreakIterator.getCharacterInstance();
iter.setText(text);
int start = iter.first(), end = iter.next();
if (end == BreakIterator.DONE) {
return "";
}
return text.substring(start, end);
}
}
@@ -0,0 +1,12 @@
package com.beemdevelopment.aegis.helpers.comparators;
import com.beemdevelopment.aegis.vault.VaultEntry;
import java.util.Comparator;
public class FavoriteComparator implements Comparator<VaultEntry> {
@Override
public int compare(VaultEntry a, VaultEntry b) {
return -1 * Boolean.compare(a.isFavorite(), b.isFavorite());
}
}
@@ -0,0 +1,12 @@
package com.beemdevelopment.aegis.helpers.comparators;
import com.beemdevelopment.aegis.vault.VaultEntry;
import java.util.Comparator;
public class UsageCountComparator implements Comparator<VaultEntry> {
@Override
public int compare(VaultEntry a, VaultEntry b) {
return Integer.compare(a.getUsageCount(), b.getUsageCount());
}
}
@@ -0,0 +1,184 @@
package com.beemdevelopment.aegis.icons;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.io.Files;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
public class IconPack {
private UUID _uuid;
private String _name;
private int _version;
private List<Icon> _icons;
private File _dir;
private IconPack(UUID uuid, String name, int version, List<Icon> icons) {
_uuid = uuid;
_name = name;
_version = version;
_icons = icons;
}
public UUID getUUID() {
return _uuid;
}
public String getName() {
return _name;
}
public int getVersion() {
return _version;
}
public List<Icon> getIcons() {
return Collections.unmodifiableList(_icons);
}
/**
* Retrieves a list of icons suggested for the given issuer.
*/
public List<Icon> getSuggestedIcons(String issuer) {
if (issuer == null || issuer.isEmpty()) {
return new ArrayList<>();
}
return _icons.stream()
.filter(i -> i.isSuggestedFor(issuer))
.collect(Collectors.toList());
}
@Nullable
public File getDirectory() {
return _dir;
}
void setDirectory(@NonNull File dir) {
_dir = dir;
}
/**
* Indicates whether some other object is "equal to" this one. The object does not
* necessarily have to be the same instance. Equality of UUID and version will make
* this method return true;
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof IconPack)) {
return false;
}
IconPack pack = (IconPack) o;
return super.equals(pack) || (getUUID().equals(pack.getUUID()) && getVersion() == pack.getVersion());
}
@Override
public int hashCode() {
return Objects.hashCode(_uuid, _version);
}
public static IconPack fromJson(JSONObject obj) throws JSONException {
UUID uuid;
String uuidString = obj.getString("uuid");
try {
uuid = UUID.fromString(uuidString);
} catch (IllegalArgumentException e) {
throw new JSONException(String.format("Bad UUID format: %s", uuidString));
}
String name = obj.getString("name");
int version = obj.getInt("version");
JSONArray array = obj.getJSONArray("icons");
List<Icon> icons = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
Icon icon = Icon.fromJson(array.getJSONObject(i));
icons.add(icon);
}
return new IconPack(uuid, name, version, icons);
}
public static IconPack fromBytes(byte[] data) throws JSONException {
JSONObject obj = new JSONObject(new String(data, StandardCharsets.UTF_8));
return IconPack.fromJson(obj);
}
public static class Icon implements Serializable {
private final String _relFilename;
private final String _category;
private final List<String> _issuers;
private File _file;
protected Icon(String filename, String category, List<String> issuers) {
_relFilename = filename;
_category = category;
_issuers = issuers;
}
public String getRelativeFilename() {
return _relFilename;
}
@Nullable
public File getFile() {
return _file;
}
void setFile(@NonNull File file) {
_file = file;
}
public IconType getIconType() {
return IconType.fromFilename(_relFilename);
}
public String getName() {
return Files.getNameWithoutExtension(new File(_relFilename).getName());
}
public String getCategory() {
return _category;
}
public List<String> getIssuers() {
return Collections.unmodifiableList(_issuers);
}
public boolean isSuggestedFor(String issuer) {
String lowerIssuer = issuer.toLowerCase();
return getIssuers().stream()
.map(String::toLowerCase)
.anyMatch(is -> is.contains(lowerIssuer) || lowerIssuer.contains(is));
}
public static Icon fromJson(JSONObject obj) throws JSONException {
String filename = obj.getString("filename");
String category = obj.isNull("category") ? null : obj.getString("category");
JSONArray array = obj.getJSONArray("issuer");
List<String> issuers = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
String issuer = array.getString(i);
issuers.add(issuer);
}
return new Icon(filename, category, issuers);
}
}
}
@@ -0,0 +1,11 @@
package com.beemdevelopment.aegis.icons;
public class IconPackException extends Exception {
public IconPackException(Throwable cause) {
super(cause);
}
public IconPackException(String message) {
super(message);
}
}
@@ -0,0 +1,14 @@
package com.beemdevelopment.aegis.icons;
public class IconPackExistsException extends IconPackException {
private IconPack _pack;
public IconPackExistsException(IconPack pack) {
super(String.format("Icon pack %s (%d) already exists", pack.getName(), pack.getVersion()));
_pack = pack;
}
public IconPack getIconPack() {
return _pack;
}
}
@@ -0,0 +1,219 @@
package com.beemdevelopment.aegis.icons;
import android.content.Context;
import androidx.annotation.Nullable;
import com.beemdevelopment.aegis.util.IOUtils;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.io.inputstream.ZipInputStream;
import net.lingala.zip4j.model.FileHeader;
import org.json.JSONException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
public class IconPackManager {
private static final String _packDefFilename = "pack.json";
private File _iconsBaseDir;
private List<IconPack> _iconPacks;
public IconPackManager(Context context) {
_iconPacks = new ArrayList<>();
_iconsBaseDir = new File(context.getFilesDir(), "icons");
rescanIconPacks();
}
private IconPack getIconPackByUUID(UUID uuid) {
List<IconPack> packs = _iconPacks.stream().filter(i -> i.getUUID().equals(uuid)).collect(Collectors.toList());
if (packs.size() == 0) {
return null;
}
return packs.get(0);
}
public List<IconPack> getIconPacks() {
return new ArrayList<>(_iconPacks);
}
public void removeIconPack(IconPack pack) throws IconPackException {
try {
File dir = getIconPackDir(pack);
deleteDir(dir);
} catch (IOException e) {
throw new IconPackException(e);
}
_iconPacks.remove(pack);
}
public IconPack importPack(File inFile) throws IconPackException {
try {
// read and parse the icon pack definition file of the icon pack
ZipFile zipFile = new ZipFile(inFile);
FileHeader packHeader = zipFile.getFileHeader(_packDefFilename);
if (packHeader == null) {
throw new IOException("Unable to find pack.json in the root of the ZIP file");
}
IconPack pack;
byte[] defBytes;
try (ZipInputStream inStream = zipFile.getInputStream(packHeader)) {
defBytes = IOUtils.readAll(inStream);
pack = IconPack.fromBytes(defBytes);
}
// create a new directory to store the icon pack, based on the UUID and version
File packDir = getIconPackDir(pack);
if (!packDir.getCanonicalPath().startsWith(_iconsBaseDir.getCanonicalPath() + File.separator)) {
throw new IOException("Attempted to write outside of the parent directory");
}
if (packDir.exists()) {
throw new IconPackExistsException(pack);
}
IconPack existingPack = getIconPackByUUID(pack.getUUID());
if (existingPack != null) {
throw new IconPackExistsException(existingPack);
}
if (!packDir.exists() && !packDir.mkdirs()) {
throw new IOException(String.format("Unable to create directories: %s", packDir.toString()));
}
// extract each of the defined icons to the icon pack directory
for (IconPack.Icon icon : pack.getIcons()) {
File destFile = new File(packDir, icon.getRelativeFilename());
FileHeader iconHeader = zipFile.getFileHeader(icon.getRelativeFilename());
if (iconHeader == null) {
throw new IOException(String.format("Unable to find %s relative to the root of the ZIP file", icon.getRelativeFilename()));
}
// create new directories for this file if needed
File parent = destFile.getParentFile();
if (parent != null && !parent.exists() && !parent.mkdirs()) {
throw new IOException(String.format("Unable to create directories: %s", packDir.toString()));
}
try (ZipInputStream inStream = zipFile.getInputStream(iconHeader);
FileOutputStream outStream = new FileOutputStream(destFile)) {
IOUtils.copy(inStream, outStream);
}
// after successful copy of the icon, store the new filename
icon.setFile(destFile);
}
// write the icon pack definition file to the newly created directory
try (FileOutputStream outStream = new FileOutputStream(new File(packDir, _packDefFilename))) {
outStream.write(defBytes);
}
// after successful extraction of the icon pack, store the new directory
pack.setDirectory(packDir);
_iconPacks.add(pack);
return pack;
} catch (IOException | JSONException e) {
throw new IconPackException(e);
}
}
private void rescanIconPacks() {
_iconPacks.clear();
File[] dirs = _iconsBaseDir.listFiles();
if (dirs == null) {
return;
}
for (File dir : dirs) {
if (!dir.isDirectory()) {
continue;
}
UUID uuid;
try {
uuid = UUID.fromString(dir.getName());
} catch (IllegalArgumentException e) {
e.printStackTrace();
continue;
}
File versionDir = getLatestVersionDir(dir);
if (versionDir != null) {
IconPack pack;
try (FileInputStream inStream = new FileInputStream(new File(versionDir, _packDefFilename))) {
byte[] bytes = IOUtils.readAll(inStream);
pack = IconPack.fromBytes(bytes);
pack.setDirectory(versionDir);
} catch (JSONException | IOException e) {
e.printStackTrace();
continue;
}
for (IconPack.Icon icon : pack.getIcons()) {
icon.setFile(new File(versionDir, icon.getRelativeFilename()));
}
// do a sanity check on the UUID and version
if (pack.getUUID().equals(uuid) && pack.getVersion() == Integer.parseInt(versionDir.getName())) {
_iconPacks.add(pack);
}
}
}
}
private File getIconPackDir(IconPack pack) {
return new File(_iconsBaseDir, pack.getUUID() + File.separator + pack.getVersion());
}
@Nullable
private static File getLatestVersionDir(File packDir) {
File[] dirs = packDir.listFiles();
if (dirs == null) {
return null;
}
int latestVersion = -1;
for (File versionDir : dirs) {
int version;
try {
version = Integer.parseInt(versionDir.getName());
} catch (NumberFormatException ignored) {
continue;
}
if (latestVersion == -1 || version > latestVersion) {
latestVersion = version;
}
}
if (latestVersion == -1) {
return null;
}
return new File(packDir, Integer.toString(latestVersion));
}
private static void deleteDir(File dir) throws IOException {
if (dir.isDirectory()) {
File[] children = dir.listFiles();
if (children != null) {
for (File child : children) {
deleteDir(child);
}
}
}
if (!dir.delete()) {
throw new IOException(String.format("Unable to delete directory: %s", dir));
}
}
}
@@ -0,0 +1,53 @@
package com.beemdevelopment.aegis.icons;
import com.google.common.io.Files;
import java.util.Locale;
public enum IconType {
INVALID,
SVG,
PNG,
JPEG;
public static IconType fromMimeType(String mimeType) {
switch (mimeType) {
case "image/svg+xml":
return SVG;
case "image/png":
return PNG;
case "image/jpeg":
return JPEG;
default:
return INVALID;
}
}
public static IconType fromFilename(String filename) {
switch (Files.getFileExtension(filename).toLowerCase(Locale.ROOT)) {
case "svg":
return SVG;
case "png":
return PNG;
case "jpg":
// intentional fallthrough
case "jpeg":
return JPEG;
default:
return INVALID;
}
}
public String toMimeType() {
switch (this) {
case SVG:
return "image/svg+xml";
case PNG:
return "image/png";
case JPEG:
return "image/jpeg";
default:
throw new RuntimeException(String.format("Can't convert icon type %s to MIME type", this));
}
}
}
@@ -1,14 +1,22 @@
package com.beemdevelopment.aegis.importers;
import android.content.Context;
import android.content.DialogInterface;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.ContextHelper;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.tasks.PasswordSlotDecryptTask;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultEntryException;
import com.beemdevelopment.aegis.vault.VaultFile;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultFileException;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.SlotList;
import com.topjohnwu.superuser.io.SuFile;
@@ -18,6 +26,7 @@ import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class AegisImporter extends DatabaseImporter {
@@ -56,23 +65,66 @@ public class AegisImporter extends DatabaseImporter {
return _file.getHeader().getSlots();
}
public State decrypt(VaultFileCredentials creds) throws VaultFileException {
JSONObject obj = _file.getContent(creds);
return new DecryptedState(obj);
public State decrypt(VaultFileCredentials creds) throws DatabaseImporterException {
JSONObject obj;
try {
obj = _file.getContent(creds);
} catch (VaultFileException e) {
throw new DatabaseImporterException(e);
}
return new DecryptedState(obj, creds);
}
public State decrypt(char[] password) throws DatabaseImporterException {
List<PasswordSlot> slots = getSlots().findAll(PasswordSlot.class);
PasswordSlotDecryptTask.Result result = PasswordSlotDecryptTask.decrypt(slots, password);
VaultFileCredentials creds = new VaultFileCredentials(result.getKey(), getSlots());
return decrypt(creds);
}
@Override
public void decrypt(Context context, DecryptListener listener) {
Dialogs.showPasswordInputDialog(context, R.string.enter_password_aegis_title, 0, (Dialogs.TextInputListener) password -> {
List<PasswordSlot> slots = getSlots().findAll(PasswordSlot.class);
PasswordSlotDecryptTask.Params params = new PasswordSlotDecryptTask.Params(slots, password);
PasswordSlotDecryptTask task = new PasswordSlotDecryptTask(context, result -> {
try {
if (result == null) {
throw new DatabaseImporterException("Password incorrect");
}
VaultFileCredentials creds = new VaultFileCredentials(result.getKey(), getSlots());
State state = decrypt(creds);
listener.onStateDecrypted(state);
} catch (DatabaseImporterException e) {
listener.onError(e);
}
});
Lifecycle lifecycle = ContextHelper.getLifecycle(context);
task.execute(lifecycle, params);
}, (DialogInterface.OnCancelListener) dialog -> listener.onCanceled());
}
}
public static class DecryptedState extends State {
private JSONObject _obj;
private VaultFileCredentials _creds;
private DecryptedState(JSONObject obj) {
this(obj, null);
}
private DecryptedState(JSONObject obj, VaultFileCredentials creds) {
super(false);
_obj = obj;
_creds = creds;
}
@Nullable
public VaultFileCredentials getCredentials() {
return _creds;
}
@Override
@@ -100,7 +152,7 @@ public class AegisImporter extends DatabaseImporter {
private static VaultEntry convertEntry(JSONObject obj) throws DatabaseImporterEntryException {
try {
return VaultEntry.fromJson(obj);
} catch (JSONException | OtpInfoException | EncodingException e) {
} catch (VaultEntryException e) {
throw new DatabaseImporterEntryException(e, obj.toString());
}
}
@@ -3,6 +3,7 @@ package com.beemdevelopment.aegis.importers;
import android.content.Context;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Lifecycle;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.crypto.CryptParameters;
@@ -10,12 +11,13 @@ import com.beemdevelopment.aegis.crypto.CryptResult;
import com.beemdevelopment.aegis.crypto.CryptoUtils;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.helpers.ContextHelper;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.SteamInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.Dialogs;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.tasks.ProgressDialogTask;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
@@ -36,6 +38,7 @@ import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Locale;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
@@ -93,7 +96,7 @@ public class AndOtpImporter extends DatabaseImporter {
_data = data;
}
private DecryptedState decryptData(SecretKey key, int offset) throws DatabaseImporterException {
private DecryptedState decryptContent(SecretKey key, int offset) throws DatabaseImporterException {
byte[] nonce = Arrays.copyOfRange(_data, offset, offset + NONCE_SIZE);
byte[] tag = Arrays.copyOfRange(_data, _data.length - TAG_SIZE, _data.length);
CryptParameters params = new CryptParameters(nonce, tag);
@@ -114,41 +117,59 @@ public class AndOtpImporter extends DatabaseImporter {
}
}
private KeyDerivationParams getKeyDerivationParams(char[] password) throws DatabaseImporterException {
byte[] iterBytes = Arrays.copyOfRange(_data, 0, INT_SIZE);
int iterations = ByteBuffer.wrap(iterBytes).getInt();
if (iterations < 1) {
throw new DatabaseImporterException(String.format("Invalid number of iterations for PBKDF: %d", iterations));
}
byte[] salt = Arrays.copyOfRange(_data, INT_SIZE, INT_SIZE + SALT_SIZE);
return new KeyDerivationParams(password, salt, iterations);
}
protected DecryptedState decryptOldFormat(char[] password) throws DatabaseImporterException {
// WARNING: DON'T DO THIS IN YOUR OWN CODE
// this exists solely to support the old andOTP backup format
// it is not a secure way to derive a key from a password
MessageDigest hash;
try {
hash = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
byte[] keyBytes = hash.digest(CryptoUtils.toBytes(password));
SecretKey key = new SecretKeySpec(keyBytes, "AES");
return decryptContent(key, 0);
}
protected DecryptedState decryptNewFormat(SecretKey key) throws DatabaseImporterException {
return decryptContent(key, INT_SIZE + SALT_SIZE);
}
protected DecryptedState decryptNewFormat(char[] password)
throws DatabaseImporterException {
KeyDerivationParams params = getKeyDerivationParams(password);
SecretKey key = AndOtpKeyDerivationTask.deriveKey(params);
return decryptNewFormat(key);
}
private void decrypt(Context context, char[] password, boolean oldFormat, DecryptListener listener) throws DatabaseImporterException {
if (oldFormat) {
// WARNING: DON'T DO THIS IN YOUR OWN CODE
// this exists solely to support the old andOTP backup format
// it is not a secure way to derive a key from a password
MessageDigest hash;
try {
hash = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
byte[] keyBytes = hash.digest(CryptoUtils.toBytes(password));
SecretKey key = new SecretKeySpec(keyBytes, "AES");
DecryptedState state = decryptData(key, 0);
DecryptedState state = decryptOldFormat(password);
listener.onStateDecrypted(state);
} else {
int offset = INT_SIZE + SALT_SIZE;
byte[] iterBytes = Arrays.copyOfRange(_data, 0, INT_SIZE);
int iterations = ByteBuffer.wrap(iterBytes).getInt();
if (iterations < 1) {
throw new DatabaseImporterException(String.format("Invalid number of iterations for PBKDF: %d", iterations));
}
byte[] salt = Arrays.copyOfRange(_data, INT_SIZE, offset);
AndOtpKeyDerivationTask.Params params = new AndOtpKeyDerivationTask.Params(password, salt, iterations);
AndOtpKeyDerivationTask task = new AndOtpKeyDerivationTask(context, key1 -> {
KeyDerivationParams params = getKeyDerivationParams(password);
AndOtpKeyDerivationTask task = new AndOtpKeyDerivationTask(context, key -> {
try {
DecryptedState state = decryptData(key1, offset);
DecryptedState state = decryptNewFormat(key);
listener.onStateDecrypted(state);
} catch (DatabaseImporterException e) {
listener.onError(e);
}
});
task.execute(params);
Lifecycle lifecycle = ContextHelper.getLifecycle(context);
task.execute(lifecycle, params);
}
}
@@ -170,7 +191,7 @@ public class AndOtpImporter extends DatabaseImporter {
} catch (DatabaseImporterException e) {
listener.onError(e);
}
});
}, dialog1 -> listener.onCanceled());
})
.create());
}
@@ -205,7 +226,7 @@ public class AndOtpImporter extends DatabaseImporter {
private static VaultEntry convertEntry(JSONObject obj) throws DatabaseImporterEntryException {
try {
String type = obj.getString("type").toLowerCase();
String type = obj.getString("type").toLowerCase(Locale.ROOT);
String algo = obj.getString("algorithm");
int digits = obj.getInt("digits");
byte[] secret = Base32.decode(obj.getString("secret"));
@@ -219,7 +240,7 @@ public class AndOtpImporter extends DatabaseImporter {
info = new TotpInfo(secret, algo, digits, obj.getInt("period"));
break;
case "steam":
info = new SteamInfo(secret, algo, digits, obj.optInt("period", 30));
info = new SteamInfo(secret, algo, digits, obj.optInt("period", TotpInfo.DEFAULT_PERIOD));
break;
default:
throw new DatabaseImporterException("unsupported otp type: " + type);
@@ -248,7 +269,7 @@ public class AndOtpImporter extends DatabaseImporter {
}
}
private static class AndOtpKeyDerivationTask extends ProgressDialogTask<AndOtpKeyDerivationTask.Params, SecretKey> {
protected static class AndOtpKeyDerivationTask extends ProgressDialogTask<AndOtpImporter.KeyDerivationParams, SecretKey> {
private Callback _cb;
public AndOtpKeyDerivationTask(Context context, Callback cb) {
@@ -257,20 +278,22 @@ public class AndOtpImporter extends DatabaseImporter {
}
@Override
protected SecretKey doInBackground(AndOtpKeyDerivationTask.Params... args) {
protected SecretKey doInBackground(AndOtpImporter.KeyDerivationParams... args) {
setPriority();
AndOtpKeyDerivationTask.Params params = args[0];
SecretKey key;
AndOtpImporter.KeyDerivationParams params = args[0];
return deriveKey(params);
}
protected static SecretKey deriveKey(KeyDerivationParams params) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(params.getPassword(), params.getSalt(), params.getIterations(), KEY_SIZE);
key = factory.generateSecret(spec);
SecretKey key = factory.generateSecret(spec);
return new SecretKeySpec(key.getEncoded(), "AES");
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new RuntimeException(e);
}
return key;
}
@Override
@@ -279,32 +302,32 @@ public class AndOtpImporter extends DatabaseImporter {
_cb.onTaskFinished(key);
}
public static class Params {
private char[] _password;
private byte[] _salt;
private int _iterations;
public Params(char[] password, byte[] salt, int iterations) {
_iterations = iterations;
_password = password;
_salt = salt;
}
public char[] getPassword() {
return _password;
}
public int getIterations() {
return _iterations;
}
public byte[] getSalt() {
return _salt;
}
}
public interface Callback {
void onTaskFinished(SecretKey key);
}
}
protected static class KeyDerivationParams {
private final char[] _password;
private final byte[] _salt;
private final int _iterations;
public KeyDerivationParams(char[] password, byte[] salt, int iterations) {
_iterations = iterations;
_password = password;
_salt = salt;
}
public char[] getPassword() {
return _password;
}
public int getIterations() {
return _iterations;
}
public byte[] getSalt() {
return _salt;
}
}
}
@@ -2,7 +2,7 @@ package com.beemdevelopment.aegis.importers;
import android.content.Context;
import com.beemdevelopment.aegis.ui.Dialogs;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.util.IOUtils;
import com.topjohnwu.superuser.io.SuFile;
@@ -37,34 +37,41 @@ public class AuthenticatorPlusImporter extends DatabaseImporter {
}
public static class EncryptedState extends DatabaseImporter.State {
private byte[] _data;
private final byte[] _data;
private EncryptedState(byte[] data) {
super(true);
_data = data;
}
protected State decrypt(char[] password) throws DatabaseImporterException {
try (ByteArrayInputStream inStream = new ByteArrayInputStream(_data);
ZipInputStream zipStream = new ZipInputStream(inStream, password)) {
LocalFileHeader header;
while ((header = zipStream.getNextEntry()) != null) {
File file = new File(header.getFileName());
if (file.getName().equals(FILENAME)) {
GoogleAuthUriImporter importer = new GoogleAuthUriImporter(null);
return importer.read(zipStream);
}
}
throw new FileNotFoundException(FILENAME);
} catch (IOException e) {
throw new DatabaseImporterException(e);
}
}
@Override
public void decrypt(Context context, DecryptListener listener) {
Dialogs.showPasswordInputDialog(context, password -> {
try (ByteArrayInputStream inStream = new ByteArrayInputStream(_data);
ZipInputStream zipStream = new ZipInputStream(inStream, password)) {
LocalFileHeader header;
while ((header = zipStream.getNextEntry()) != null) {
File file = new File(header.getFileName());
if (file.getName().equals(FILENAME)) {
GoogleAuthUriImporter importer = new GoogleAuthUriImporter(context);
DatabaseImporter.State state = importer.read(zipStream);
listener.onStateDecrypted(state);
return;
}
}
throw new FileNotFoundException(FILENAME);
} catch (IOException | DatabaseImporterException e) {
try {
DatabaseImporter.State state = decrypt(password);
listener.onStateDecrypted(state);
} catch (DatabaseImporterException e) {
listener.onError(e);
}
});
}, dialog1 -> listener.onCanceled());
}
}
}
@@ -12,7 +12,7 @@ import com.beemdevelopment.aegis.encoding.Hex;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.Dialogs;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.util.JsonUtils;
import com.beemdevelopment.aegis.util.PreferenceParser;
import com.beemdevelopment.aegis.vault.VaultEntry;
@@ -42,6 +42,7 @@ import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AuthyImporter extends DatabaseImporter {
private static final String _subPath = "shared_prefs";
@@ -128,7 +129,7 @@ public class AuthyImporter extends DatabaseImporter {
}
private JSONArray readFile(SuFile file, String key) throws IOException, XmlPullParserException {
try (SuFileInputStream inStream = new SuFileInputStream(file)) {
try (InputStream inStream = SuFileInputStream.open(file)) {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(inStream, null);
@@ -154,47 +155,56 @@ public class AuthyImporter extends DatabaseImporter {
_array = array;
}
protected DecryptedState decrypt(char[] password) throws DatabaseImporterException {
try {
for (int i = 0; i < _array.length(); i++) {
JSONObject obj = _array.getJSONObject(i);
String secretString = JsonUtils.optString(obj, "encryptedSecret");
if (secretString == null) {
continue;
}
byte[] encryptedSecret = Base64.decode(secretString);
byte[] salt = obj.getString("salt").getBytes(StandardCharsets.UTF_8);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_SIZE);
SecretKey key = factory.generateSecret(spec);
key = new SecretKeySpec(key.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(IV);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] secret = cipher.doFinal(encryptedSecret);
obj.remove("encryptedSecret");
obj.remove("salt");
obj.put("decryptedSecret", new String(secret, StandardCharsets.UTF_8));
}
return new DecryptedState(_array);
} catch (JSONException
| EncodingException
| NoSuchAlgorithmException
| InvalidKeySpecException
| InvalidAlgorithmParameterException
| InvalidKeyException
| NoSuchPaddingException
| BadPaddingException
| IllegalBlockSizeException e) {
throw new DatabaseImporterException(e);
}
}
@Override
public void decrypt(Context context, DecryptListener listener) {
Dialogs.showPasswordInputDialog(context, R.string.enter_password_authy_message, password -> {
try {
for (int i = 0; i < _array.length(); i++) {
JSONObject obj = _array.getJSONObject(i);
String secretString = JsonUtils.optString(obj, "encryptedSecret");
if (secretString == null) {
continue;
}
byte[] encryptedSecret = Base64.decode(secretString);
byte[] salt = obj.getString("salt").getBytes(StandardCharsets.UTF_8);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_SIZE);
SecretKey key = factory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
IvParameterSpec ivSpec = new IvParameterSpec(IV);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] secret = cipher.doFinal(encryptedSecret);
obj.remove("encryptedSecret");
obj.remove("salt");
obj.put("decryptedSecret", new String(secret, StandardCharsets.UTF_8));
}
DecryptedState state = new DecryptedState(_array);
DecryptedState state = decrypt(password);
listener.onStateDecrypted(state);
} catch (JSONException
| EncodingException
| NoSuchAlgorithmException
| InvalidKeySpecException
| InvalidAlgorithmParameterException
| InvalidKeyException
| NoSuchPaddingException
| BadPaddingException
| IllegalBlockSizeException e) {
} catch (DatabaseImporterException e) {
listener.onError(e);
}
});
}, dialog1 -> listener.onCanceled());
}
}
@@ -235,7 +245,7 @@ public class AuthyImporter extends DatabaseImporter {
authyEntryInfo.AccountType = JsonUtils.optString(entry, "accountType");
authyEntryInfo.Name = entry.optString("name");
boolean isAuthy = !entry.optString("accountType", "authy").equals("authenticator");
boolean isAuthy = entry.has("secretSeed");
sanitizeEntryInfo(authyEntryInfo, isAuthy);
byte[] secret;
@@ -246,7 +256,7 @@ public class AuthyImporter extends DatabaseImporter {
}
int digits = entry.getInt("digits");
OtpInfo info = new TotpInfo(secret, "SHA1", digits, digits == 7 ? 10 : 30);
OtpInfo info = new TotpInfo(secret, OtpInfo.DEFAULT_ALGORITHM, digits, isAuthy ? 10 : TotpInfo.DEFAULT_PERIOD);
return new VaultEntry(info, authyEntryInfo.Name, authyEntryInfo.Issuer);
} catch (OtpInfoException | JSONException | EncodingException e) {
throw new DatabaseImporterEntryException(e, entry.toString());
@@ -274,6 +284,10 @@ public class AuthyImporter extends DatabaseImporter {
info.Issuer = info.Name;
info.Name = "";
}
if (info.Name.startsWith(": ")) {
info.Name = info.Name.substring(2);
}
}
}
@@ -0,0 +1,117 @@
package com.beemdevelopment.aegis.importers;
import android.content.Context;
import android.net.Uri;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.otp.GoogleAuthInfo;
import com.beemdevelopment.aegis.otp.GoogleAuthInfoException;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.SteamInfo;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.io.SuFile;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simpleflatmapper.csv.CsvParser;
import org.simpleflatmapper.lightningcsv.Row;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BitwardenImporter extends DatabaseImporter {
public BitwardenImporter(Context context) {
super(context);
}
@Override
protected SuFile getAppPath() {
throw new UnsupportedOperationException();
}
@Override
protected State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
String fileString;
try {
fileString = new String(IOUtils.readAll(stream), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new DatabaseImporterException(e);
}
try {
JSONObject obj = new JSONObject(fileString);
JSONArray array = obj.getJSONArray("items");
List<String> entries = new ArrayList<>();
String entry;
for (int i = 0; i < array.length(); i++) {
entry = array.getJSONObject(i).getJSONObject("login").getString("totp");
if (!entry.isEmpty()) {
entries.add(entry);
}
}
return new BitwardenImporter.State(entries);
} catch (JSONException e) {
try {
Iterator<Row> rowIterator = CsvParser.separator(',').rowIterator(fileString);
List<String> entries = new ArrayList<>();
rowIterator.forEachRemaining((row -> {
String entry = row.get("login_totp");
if (entry != null && !entry.isEmpty()) {
entries.add(entry);
}
}));
return new BitwardenImporter.State(entries);
} catch (IOException e2) {
throw new DatabaseImporterException(e2);
}
}
}
public static class State extends DatabaseImporter.State {
private final List<String> _entries;
public State(List<String> entries) {
super(false);
_entries = entries;
}
@Override
public Result convert() {
Result result = new Result();
for (String obj : _entries) {
try {
VaultEntry entry = convertEntry(obj);
result.addEntry(entry);
} catch (DatabaseImporterEntryException e) {
result.addError(e);
}
}
return result;
}
private static VaultEntry convertEntry(String obj) throws DatabaseImporterEntryException {
try {
GoogleAuthInfo info = BitwardenImporter.parseUri(obj);
return new VaultEntry(info);
} catch (GoogleAuthInfoException | EncodingException | OtpInfoException | URISyntaxException e) {
throw new DatabaseImporterEntryException(e, obj);
}
}
}
private static GoogleAuthInfo parseUri(String obj) throws EncodingException, OtpInfoException, URISyntaxException, GoogleAuthInfoException {
Uri uri = Uri.parse(obj);
return uri.getScheme().equals("steam") ? new GoogleAuthInfo(new SteamInfo(Base32.decode(uri.getAuthority())), "Steam account", "Steam") : GoogleAuthInfo.parseUri(uri);
}
}
@@ -3,6 +3,9 @@ package com.beemdevelopment.aegis.importers;
import android.content.Context;
import android.content.pm.PackageManager;
import androidx.annotation.StringRes;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.util.UUIDMap;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.io.SuFile;
@@ -10,60 +13,57 @@ import com.topjohnwu.superuser.io.SuFileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public abstract class DatabaseImporter {
private Context _context;
private static Map<String, Class<? extends DatabaseImporter>> _importers;
private static Map<String, Class<? extends DatabaseImporter>> _appImporters;
private static List<Definition> _importers;
static {
// note: keep these lists sorted alphabetically
_importers = new LinkedHashMap<>();
_importers.put("Aegis", AegisImporter.class);
_importers.put("Authenticator Plus", AuthenticatorPlusImporter.class);
_importers.put("Authy", AuthyImporter.class);
_importers.put("andOTP", AndOtpImporter.class);
_importers.put("FreeOTP", FreeOtpImporter.class);
_importers.put("FreeOTP+", FreeOtpPlusImporter.class);
_importers.put("Google Authenticator", GoogleAuthImporter.class);
_importers.put("Microsoft Authenticator", MicrosoftAuthImporter.class);
_importers.put("Plain text", GoogleAuthUriImporter.class);
_importers.put("Steam", SteamImporter.class);
_importers.put("TOTP Authenticator", TotpAuthenticatorImporter.class);
_importers.put("WinAuth", WinAuthImporter.class);
_appImporters = new LinkedHashMap<>();
_appImporters.put("Authy", AuthyImporter.class);
_appImporters.put("FreeOTP", FreeOtpImporter.class);
_appImporters.put("FreeOTP+", FreeOtpPlusImporter.class);
_appImporters.put("Google Authenticator", GoogleAuthImporter.class);
_appImporters.put("Microsoft Authenticator", MicrosoftAuthImporter.class);
_appImporters.put("Steam", SteamImporter.class);
_appImporters.put("TOTP Authenticator", TotpAuthenticatorImporter.class);
_importers = new ArrayList<>();
_importers.add(new Definition("2FAS Authenticator", TwoFASImporter.class, R.string.importer_help_2fas, false));
_importers.add(new Definition("Aegis", AegisImporter.class, R.string.importer_help_aegis, false));
_importers.add(new Definition("andOTP", AndOtpImporter.class, R.string.importer_help_andotp, false));
_importers.add(new Definition("Authenticator Plus", AuthenticatorPlusImporter.class, R.string.importer_help_authenticator_plus, false));
_importers.add(new Definition("Authy", AuthyImporter.class, R.string.importer_help_authy, true));
_importers.add(new Definition("Bitwarden", BitwardenImporter.class, R.string.importer_help_bitwarden, false));
_importers.add(new Definition("Duo", DuoImporter.class, R.string.importer_help_duo, true));
_importers.add(new Definition("FreeOTP", FreeOtpImporter.class, R.string.importer_help_freeotp, true));
_importers.add(new Definition("FreeOTP+", FreeOtpPlusImporter.class, R.string.importer_help_freeotp_plus, true));
_importers.add(new Definition("Google Authenticator", GoogleAuthImporter.class, R.string.importer_help_google_authenticator, true));
_importers.add(new Definition("Microsoft Authenticator", MicrosoftAuthImporter.class, R.string.importer_help_microsoft_authenticator, true));
_importers.add(new Definition("Plain text", GoogleAuthUriImporter.class, R.string.importer_help_plain_text, false));
_importers.add(new Definition("Steam", SteamImporter.class, R.string.importer_help_steam, true));
_importers.add(new Definition("TOTP Authenticator", TotpAuthenticatorImporter.class, R.string.importer_help_totp_authenticator, true));
_importers.add(new Definition("WinAuth", WinAuthImporter.class, R.string.importer_help_winauth, false));
}
public DatabaseImporter(Context context) {
_context = context;
}
protected Context getContext() {
protected Context requireContext() {
return _context;
}
protected abstract SuFile getAppPath() throws DatabaseImporterException, PackageManager.NameNotFoundException;
protected SuFile getAppPath(String pkgName, String subPath) throws PackageManager.NameNotFoundException {
PackageManager man = getContext().getPackageManager();
PackageManager man = requireContext().getPackageManager();
return new SuFile(man.getApplicationInfo(pkgName, 0).dataDir, subPath);
}
public boolean isInstalledAppVersionSupported() {
return true;
}
protected abstract State read(InputStream stream, boolean isInternal) throws DatabaseImporterException;
public State read(InputStream stream) throws DatabaseImporterException {
@@ -72,7 +72,7 @@ public abstract class DatabaseImporter {
public State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile file = getAppPath();
try (SuFileInputStream stream = new SuFileInputStream(file)) {
try (InputStream stream = SuFileInputStream.open(file)) {
return read(stream, true);
} catch (IOException e) {
throw new DatabaseImporterException(e);
@@ -88,12 +88,42 @@ public abstract class DatabaseImporter {
}
}
public static Map<String, Class<? extends DatabaseImporter>> getImporters() {
return Collections.unmodifiableMap(_importers);
public static List<Definition> getImporters(boolean isDirect) {
if (isDirect) {
return Collections.unmodifiableList(_importers.stream().filter(Definition::supportsDirect).collect(Collectors.toList()));
}
return Collections.unmodifiableList(_importers);
}
public static Map<String, Class<? extends DatabaseImporter>> getAppImporters() {
return Collections.unmodifiableMap(_appImporters);
public static class Definition implements Serializable {
private final String _name;
private final Class<? extends DatabaseImporter> _type;
private final @StringRes int _help;
private final boolean _supportsDirect;
public Definition(String name, Class<? extends DatabaseImporter> type, @StringRes int help, boolean supportsDirect) {
_name = name;
_type = type;
_help = help;
_supportsDirect = supportsDirect;
}
public String getName() {
return _name;
}
public Class<? extends DatabaseImporter> getType() {
return _type;
}
public @StringRes int getHelp() {
return _help;
}
public boolean supportsDirect() {
return _supportsDirect;
}
}
public static abstract class State {
@@ -145,8 +175,9 @@ public abstract class DatabaseImporter {
}
}
public interface DecryptListener {
void onStateDecrypted(State state);
void onError(Exception e);
public static abstract class DecryptListener {
protected abstract void onStateDecrypted(State state);
protected abstract void onError(Exception e);
protected abstract void onCanceled();
}
}
@@ -0,0 +1,99 @@
package com.beemdevelopment.aegis.importers;
import static java.nio.charset.StandardCharsets.UTF_8;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import androidx.annotation.NonNull;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.io.SuFile;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
public class DuoImporter extends DatabaseImporter {
private static final String _pkgName = "com.duosecurity.duomobile";
private static final String _subPath = "files/duokit/accounts.json";
public DuoImporter(Context context) {
super(context);
}
@Override
protected @NonNull SuFile getAppPath() throws DatabaseImporterException, NameNotFoundException {
return getAppPath(_pkgName, _subPath);
}
@Override
protected @NonNull State read(
@NonNull InputStream stream, boolean isInternal
) throws DatabaseImporterException {
try {
String contents = new String(IOUtils.readAll(stream), UTF_8);
return new DecryptedState(new JSONArray(contents));
} catch (JSONException | IOException e) {
throw new DatabaseImporterException(e);
}
}
public static class DecryptedState extends DatabaseImporter.State {
private final JSONArray _array;
public DecryptedState(@NonNull JSONArray array) {
super(false);
_array = array;
}
@Override
public @NonNull Result convert() throws DatabaseImporterException {
Result result = new Result();
try {
for (int i = 0; i < _array.length(); i++) {
JSONObject entry = _array.getJSONObject(i);
try {
result.addEntry(convertEntry(entry));
} catch (DatabaseImporterEntryException e) {
result.addError(e);
}
}
} catch (JSONException e) {
throw new DatabaseImporterException(e);
}
return result;
}
private static @NonNull VaultEntry convertEntry(
@NonNull JSONObject entry
) throws DatabaseImporterEntryException {
try {
String label = entry.optString("name");
JSONObject otpData = entry.getJSONObject("otpGenerator");
byte[] secret = Base32.decode(otpData.getString("otpSecret"));
Long counter = otpData.has("counter") ? otpData.getLong("counter") : null;
OtpInfo otp = counter == null
? new TotpInfo(secret)
: new HotpInfo(secret, counter);
return new VaultEntry(otp, label, "");
} catch (JSONException | OtpInfoException | EncodingException e) {
throw new DatabaseImporterEntryException(e, entry.toString());
}
}
}
}
@@ -23,6 +23,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FreeOtpImporter extends DatabaseImporter {
private static final String _subPath = "shared_prefs/tokens.xml";
@@ -83,7 +84,7 @@ public class FreeOtpImporter extends DatabaseImporter {
private static VaultEntry convertEntry(JSONObject obj) throws DatabaseImporterEntryException {
try {
String type = obj.getString("type").toLowerCase();
String type = obj.getString("type").toLowerCase(Locale.ROOT);
String algo = obj.getString("algo");
int digits = obj.getInt("digits");
byte[] secret = toBytes(obj.getJSONArray("secret"));
@@ -115,30 +116,6 @@ public class FreeOtpImporter extends DatabaseImporter {
}
}
private static List<JSONObject> parseXml(XmlPullParser parser)
throws IOException, XmlPullParserException, JSONException {
List<JSONObject> entries = new ArrayList<>();
parser.require(XmlPullParser.START_TAG, null, "map");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
if (!parser.getName().equals("string")) {
skip(parser);
continue;
}
JSONObject entry = parseXmlEntry(parser);
if (entry != null) {
entries.add(entry);
}
}
return entries;
}
private static byte[] toBytes(JSONArray array) throws JSONException {
byte[] bytes = new byte[array.length()];
for (int i = 0; i < array.length(); i++) {
@@ -146,46 +123,4 @@ public class FreeOtpImporter extends DatabaseImporter {
}
return bytes;
}
private static JSONObject parseXmlEntry(XmlPullParser parser)
throws IOException, XmlPullParserException, JSONException {
parser.require(XmlPullParser.START_TAG, null, "string");
String name = parser.getAttributeValue(null, "name");
String value = parseXmlText(parser);
parser.require(XmlPullParser.END_TAG, null, "string");
if (name.equals("tokenOrder")) {
return null;
}
return new JSONObject(value);
}
private static String parseXmlText(XmlPullParser parser) throws IOException, XmlPullParserException {
String text = "";
if (parser.next() == XmlPullParser.TEXT) {
text = parser.getText();
parser.nextTag();
}
return text;
}
private static void skip(XmlPullParser parser) throws IOException, XmlPullParserException {
// source: https://developer.android.com/training/basics/network-ops/xml.html
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
@@ -34,7 +34,7 @@ public class FreeOtpPlusImporter extends DatabaseImporter {
State state;
if (isInternal) {
state = new FreeOtpImporter(getContext()).read(stream);
state = new FreeOtpImporter(requireContext()).read(stream);
} else {
try {
String json = new String(IOUtils.readAll(stream), StandardCharsets.UTF_8);
@@ -1,11 +1,13 @@
package com.beemdevelopment.aegis.importers;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.otp.GoogleAuthInfo;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
@@ -31,28 +33,44 @@ public class GoogleAuthImporter extends DatabaseImporter {
protected SuFile getAppPath() throws PackageManager.NameNotFoundException {
return getAppPath(_pkgName, _subPath);
}
@Override
public boolean isInstalledAppVersionSupported() {
PackageInfo info;
try {
info = requireContext().getPackageManager().getPackageInfo(_pkgName, 0);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return info.versionCode <= 5000100;
}
@Override
public State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
SqlImporterHelper helper = new SqlImporterHelper(getContext());
final Context context = requireContext();
SqlImporterHelper helper = new SqlImporterHelper(context);
List<Entry> entries = helper.read(Entry.class, stream, "accounts");
return new State(entries);
return new State(entries, context);
}
@Override
public DatabaseImporter.State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile path = getAppPath();
SqlImporterHelper helper = new SqlImporterHelper(getContext());
final Context context = requireContext();
SqlImporterHelper helper = new SqlImporterHelper(context);
List<Entry> entries = helper.read(Entry.class, path, "accounts");
return new State(entries);
return new State(entries, context);
}
public static class State extends DatabaseImporter.State {
private List<Entry> _entries;
private Context _context;
private State(List<Entry> entries) {
private State(List<Entry> entries, Context context) {
super(false);
_entries = entries;
_context = context;
}
@Override
@@ -61,7 +79,7 @@ public class GoogleAuthImporter extends DatabaseImporter {
for (Entry sqlEntry : _entries) {
try {
VaultEntry entry = convertEntry(sqlEntry);
VaultEntry entry = convertEntry(sqlEntry, _context);
result.addEntry(entry);
} catch (DatabaseImporterEntryException e) {
result.addError(e);
@@ -71,9 +89,12 @@ public class GoogleAuthImporter extends DatabaseImporter {
return result;
}
private static VaultEntry convertEntry(Entry entry) throws DatabaseImporterEntryException {
private static VaultEntry convertEntry(Entry entry, Context context) throws DatabaseImporterEntryException {
try {
byte[] secret = Base32.decode(entry.getSecret());
if (entry.isEncrypted()) {
throw new DatabaseImporterException(context.getString(R.string.importer_encrypted_exception_google_authenticator, entry.getEmail()));
}
byte[] secret = GoogleAuthInfo.parseSecret(entry.getSecret());
OtpInfo info;
switch (entry.getType()) {
@@ -102,6 +123,7 @@ public class GoogleAuthImporter extends DatabaseImporter {
private static class Entry extends SqlImporterHelper.Entry {
private int _type;
private boolean _isEncrypted;
private String _secret;
private String _email;
private String _issuer;
@@ -114,12 +136,18 @@ public class GoogleAuthImporter extends DatabaseImporter {
_email = SqlImporterHelper.getString(cursor, "email", "");
_issuer = SqlImporterHelper.getString(cursor, "issuer", "");
_counter = SqlImporterHelper.getLong(cursor, "counter");
_isEncrypted = (cursor.getColumnIndex("isencrypted") != -1 && SqlImporterHelper.getInt(cursor, "isencrypted") > 0);
}
public int getType() {
return _type;
}
public boolean isEncrypted() {
return _isEncrypted;
}
public String getSecret() {
return _secret;
}
@@ -4,9 +4,9 @@ import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.Base64;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.otp.GoogleAuthInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
@@ -34,7 +34,7 @@ public class MicrosoftAuthImporter extends DatabaseImporter {
@Override
public State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
SqlImporterHelper helper = new SqlImporterHelper(getContext());
SqlImporterHelper helper = new SqlImporterHelper(requireContext());
List<Entry> entries = helper.read(Entry.class, stream, "accounts");
return new State(entries);
}
@@ -42,7 +42,7 @@ public class MicrosoftAuthImporter extends DatabaseImporter {
@Override
public DatabaseImporter.State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile path = getAppPath();
SqlImporterHelper helper = new SqlImporterHelper(getContext());
SqlImporterHelper helper = new SqlImporterHelper(requireContext());
List<Entry> entries = helper.read(Entry.class, path, "accounts");
return new State(entries);
}
@@ -81,7 +81,7 @@ public class MicrosoftAuthImporter extends DatabaseImporter {
switch (entry.getType()) {
case TYPE_TOTP:
secret = Base32.decode(entry.getSecret());
secret = GoogleAuthInfo.parseSecret(entry.getSecret());
break;
case TYPE_MICROSOFT:
digits = 8;
@@ -91,7 +91,7 @@ public class MicrosoftAuthImporter extends DatabaseImporter {
throw new DatabaseImporterEntryException(String.format("Unsupported OTP type: %d", entry.getType()), entry.toString());
}
OtpInfo info = new TotpInfo(secret, "SHA1", digits, 30);
OtpInfo info = new TotpInfo(secret, OtpInfo.DEFAULT_ALGORITHM, digits, TotpInfo.DEFAULT_PERIOD);
return new VaultEntry(info, entry.getUserName(), entry.getIssuer());
} catch (EncodingException | OtpInfoException e) {
throw new DatabaseImporterEntryException(e, entry.toString());
@@ -1,5 +1,8 @@
package com.beemdevelopment.aegis.importers;
import static android.database.sqlite.SQLiteDatabase.OPEN_READONLY;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
@@ -18,8 +21,6 @@ import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import static android.database.sqlite.SQLiteDatabase.OPEN_READONLY;
public class SqlImporterHelper {
private Context _context;
@@ -35,7 +36,7 @@ public class SqlImporterHelper {
for (SuFile file : SqlImporterHelper.findDatabaseFiles(path)) {
// create temporary copies of the database files so that SQLiteDatabase can open them
File fileCopy = null;
try (SuFileInputStream inStream = new SuFileInputStream(file)) {
try (InputStream inStream = SuFileInputStream.open(file)) {
fileCopy = new File(dir, file.getName());
try (FileOutputStream out = new FileOutputStream(fileCopy)) {
IOUtils.copy(inStream, out);
@@ -117,10 +118,12 @@ public class SqlImporterHelper {
}
}
@SuppressLint("Range")
public static String getString(Cursor cursor, String columnName) {
return cursor.getString(cursor.getColumnIndex(columnName));
}
@SuppressLint("Range")
public static String getString(Cursor cursor, String columnName, String def) {
String res = cursor.getString(cursor.getColumnIndex(columnName));
if (res == null) {
@@ -129,10 +132,12 @@ public class SqlImporterHelper {
return res;
}
@SuppressLint("Range")
public static int getInt(Cursor cursor, String columnName) {
return cursor.getInt(cursor.getColumnIndex(columnName));
}
@SuppressLint("Range")
public static long getLong(Cursor cursor, String columnName) {
return cursor.getLong(cursor.getColumnIndex(columnName));
}
@@ -1,6 +1,7 @@
package com.beemdevelopment.aegis.importers;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.beemdevelopment.aegis.encoding.Base64;
@@ -39,6 +40,18 @@ public class SteamImporter extends DatabaseImporter {
return files[0];
}
@Override
public boolean isInstalledAppVersionSupported() {
PackageInfo info;
try {
info = requireContext().getPackageManager().getPackageInfo(_pkgName, 0);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return info.versionCode < 7460894;
}
@Override
public State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
try {
@@ -14,7 +14,7 @@ import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.encoding.Hex;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.Dialogs;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.util.PreferenceParser;
import com.beemdevelopment.aegis.vault.VaultEntry;
@@ -104,8 +104,8 @@ public class TotpAuthenticatorImporter extends DatabaseImporter {
List<JSONObject> entries = new ArrayList<>();
for (int i = 0; i < array.length(); ++i) {
String s = array.getString(i);
entries.add(new JSONObject(s));
JSONObject obj = array.getJSONObject(i);
entries.add(obj);
}
return entries;
@@ -119,7 +119,7 @@ public class TotpAuthenticatorImporter extends DatabaseImporter {
_data = data;
}
private DecryptedState decrypt(char[] password) throws DatabaseImporterException {
protected DecryptedState decrypt(char[] password) throws DatabaseImporterException {
try {
// WARNING: DON'T DO THIS IN YOUR OWN CODE
// this is not a secure way to derive a key from a password
@@ -127,7 +127,7 @@ public class TotpAuthenticatorImporter extends DatabaseImporter {
byte[] keyBytes = hash.digest(CryptoUtils.toBytes(password));
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec spec = new IvParameterSpec(IV);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
@@ -159,7 +159,7 @@ public class TotpAuthenticatorImporter extends DatabaseImporter {
.setPositiveButton(R.string.yes, (dialog, which) -> {
Dialogs.showPasswordInputDialog(context, password -> {
decrypt(password, listener);
});
}, dialog1 -> listener.onCanceled());
})
.setNegativeButton(R.string.no, (dialog, which) -> {
decrypt(PASSWORD, listener);
@@ -221,7 +221,7 @@ public class TotpAuthenticatorImporter extends DatabaseImporter {
throw new DatabaseImporterEntryException(String.format("Unsupported secret encoding: base %d", base), obj.toString());
}
TotpInfo info = new TotpInfo(secret, "SHA1", 6, 30);
TotpInfo info = new TotpInfo(secret);
String name = obj.optString("name");
String issuer = obj.optString("issuer");
@@ -0,0 +1,200 @@
package com.beemdevelopment.aegis.importers;
import android.content.Context;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.crypto.CryptoUtils;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.Base64;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.util.JsonUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.io.SuFile;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class TwoFASImporter extends DatabaseImporter {
private static final int ITERATION_COUNT = 10_000;
private static final int KEY_SIZE = 256; // bits
public TwoFASImporter(Context context) {
super(context);
}
@Override
protected SuFile getAppPath() {
throw new UnsupportedOperationException();
}
@Override
public State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
try {
String json = new String(IOUtils.readAll(stream), StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(json);
int version = obj.getInt("schemaVersion");
if (version > 3) {
throw new DatabaseImporterException(String.format("Unsupported schema version: %d", version));
}
String encryptedString = JsonUtils.optString(obj, "servicesEncrypted");
if (encryptedString == null) {
JSONArray array = obj.getJSONArray("services");
List<JSONObject> entries = arrayToList(array);
return new DecryptedState(entries);
}
String[] parts = encryptedString.split(":");
if (parts.length < 3) {
throw new DatabaseImporterException(String.format("Unexpected format of encrypted data (parts: %d)", parts.length));
}
byte[] data = Base64.decode(parts[0]);
byte[] salt = Base64.decode(parts[1]);
byte[] iv = Base64.decode(parts[2]);
return new EncryptedState(data, salt, iv);
} catch (IOException | JSONException e) {
throw new DatabaseImporterException(e);
}
}
private static List<JSONObject> arrayToList(JSONArray array) throws JSONException {
List<JSONObject> list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
list.add(array.getJSONObject(i));
}
return list;
}
public static class EncryptedState extends State {
private final byte[] _data;
private final byte[] _salt;
private final byte[] _iv;
private EncryptedState(byte[] data, byte[] salt, byte[] iv) {
super(true);
_data = data;
_salt = salt;
_iv = iv;
}
private SecretKey deriveKey(char[] password)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password, _salt, ITERATION_COUNT, KEY_SIZE);
SecretKey key = factory.generateSecret(spec);
return new SecretKeySpec(key.getEncoded(), "AES");
}
public DecryptedState decrypt(char[] password) throws DatabaseImporterException {
try {
SecretKey key = deriveKey(password);
Cipher cipher = CryptoUtils.createDecryptCipher(key, _iv);
byte[] decrypted = cipher.doFinal(_data);
String json = new String(decrypted, StandardCharsets.UTF_8);
return new DecryptedState(arrayToList(new JSONArray(json)));
} catch (BadPaddingException | JSONException e) {
throw new DatabaseImporterException(e);
} catch (NoSuchAlgorithmException
| InvalidKeySpecException
| InvalidAlgorithmParameterException
| NoSuchPaddingException
| InvalidKeyException
| IllegalBlockSizeException e) {
throw new RuntimeException(e);
}
}
@Override
public void decrypt(Context context, DecryptListener listener) {
Dialogs.showPasswordInputDialog(context, R.string.enter_password_2fas_message, 0, password -> {
try {
DecryptedState state = decrypt(password);
listener.onStateDecrypted(state);
} catch (DatabaseImporterException e) {
listener.onError(e);
}
}, dialog -> listener.onCanceled());
}
}
public static class DecryptedState extends DatabaseImporter.State {
private final List<JSONObject> _entries;
public DecryptedState(List<JSONObject> entries) {
super(false);
_entries = entries;
}
@Override
public Result convert() {
Result result = new Result();
for (JSONObject obj : _entries) {
try {
VaultEntry entry = convertEntry(obj);
result.addEntry(entry);
} catch (DatabaseImporterEntryException e) {
result.addError(e);
}
}
return result;
}
private static VaultEntry convertEntry(JSONObject obj) throws DatabaseImporterEntryException {
try {
byte[] secret = Base32.decode(obj.getString("secret"));
JSONObject info = obj.getJSONObject("otp");
String issuer = info.optString("issuer");
String name = info.optString("account");
int digits = info.optInt("digits", TotpInfo.DEFAULT_DIGITS);
String algorithm = info.optString("algorithm", TotpInfo.DEFAULT_ALGORITHM);
OtpInfo otp;
String tokenType = JsonUtils.optString(info, "tokenType");
if (tokenType == null || tokenType.equals("TOTP")) {
int period = info.optInt("period", TotpInfo.DEFAULT_PERIOD);
otp = new TotpInfo(secret, algorithm, digits, period);
} else if (tokenType.equals("HOTP")) {
long counter = info.optLong("counter", 0);
otp = new HotpInfo(secret, algorithm, digits, counter);
} else {
throw new DatabaseImporterEntryException(String.format("Unrecognized tokenType: %s", tokenType), obj.toString());
}
return new VaultEntry(otp, name, issuer);
} catch (OtpInfoException | JSONException | EncodingException e) {
throw new DatabaseImporterEntryException(e, obj.toString());
}
}
}
}
@@ -19,7 +19,7 @@ public class WinAuthImporter extends DatabaseImporter {
@Override
public WinAuthImporter.State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
GoogleAuthUriImporter importer = new GoogleAuthUriImporter(getContext());
GoogleAuthUriImporter importer = new GoogleAuthUriImporter(requireContext());
DatabaseImporter.State state = importer.read(stream);
return new State(state);
}
@@ -1,4 +1,4 @@
package com.beemdevelopment.aegis.ui.glide;
package com.beemdevelopment.aegis.licenses;
import android.content.Context;
@@ -0,0 +1,34 @@
package com.beemdevelopment.aegis.licenses;
import android.content.Context;
import com.beemdevelopment.aegis.R;
import de.psdev.licensesdialog.licenses.License;
public class ProtobufLicense extends License {
@Override
public String getName() {
return "Protocol Buffers License";
}
@Override
public String readSummaryTextFromResources(Context context) {
return getContent(context, R.raw.protobuf_license);
}
@Override
public String readFullTextFromResources(Context context) {
return getContent(context, R.raw.protobuf_license);
}
@Override
public String getVersion() {
return null;
}
@Override
public String getUrl() {
return "https://raw.githubusercontent.com/protocolbuffers/protobuf/master/LICENSE";
}
}
@@ -2,17 +2,24 @@ package com.beemdevelopment.aegis.otp;
import android.net.Uri;
import androidx.annotation.NonNull;
import com.beemdevelopment.aegis.GoogleAuthProtos;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.Base64;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.encoding.Hex;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class GoogleAuthInfo implements Serializable {
public class GoogleAuthInfo implements Transferable, Serializable {
public static final String SCHEME = "otpauth";
public static final String SCHEME_EXPORT = "otpauth-migration";
@@ -26,76 +33,42 @@ public class GoogleAuthInfo implements Serializable {
_issuer = issuer;
}
public OtpInfo getOtpInfo() {
return _info;
}
public Uri getUri() {
Uri.Builder builder = new Uri.Builder();
builder.scheme(SCHEME);
if (_info instanceof TotpInfo) {
if (_info instanceof SteamInfo) {
builder.authority("steam");
} else {
builder.authority("totp");
}
builder.appendQueryParameter("period", Integer.toString(((TotpInfo)_info).getPeriod()));
} else if (_info instanceof HotpInfo) {
builder.authority("hotp");
builder.appendQueryParameter("counter", Long.toString(((HotpInfo)_info).getCounter()));
} else {
throw new RuntimeException(String.format("Unsupported OtpInfo type: %s", _info.getClass()));
}
builder.appendQueryParameter("digits", Integer.toString(_info.getDigits()));
builder.appendQueryParameter("algorithm", _info.getAlgorithm(false));
builder.appendQueryParameter("secret", new String(Base32.encode(_info.getSecret())));
if (_issuer != null && !_issuer.equals("")) {
builder.path(String.format("%s:%s", _issuer, _accountName));
builder.appendQueryParameter("issuer", _issuer);
} else {
builder.path(_accountName);
}
return builder.build();
}
public static GoogleAuthInfo parseUri(String s) throws GoogleAuthInfoException {
Uri uri = Uri.parse(s);
if (uri == null) {
throw new GoogleAuthInfoException(String.format("Bad URI format: %s", s));
throw new GoogleAuthInfoException(uri, String.format("Bad URI format: %s", s));
}
return GoogleAuthInfo.parseUri(uri);
}
public static GoogleAuthInfo parseUri(Uri uri) throws GoogleAuthInfoException {
String scheme = uri.getScheme();
if (scheme == null || !scheme.equals(SCHEME)) {
throw new GoogleAuthInfoException("Unsupported protocol");
if (scheme == null || !(scheme.equals(SCHEME) || scheme.equals(MotpInfo.SCHEME))) {
throw new GoogleAuthInfoException(uri, String.format("Unsupported protocol: %s", scheme));
}
// 'secret' is a required parameter
String encodedSecret = uri.getQueryParameter("secret");
if (encodedSecret == null) {
throw new GoogleAuthInfoException("Parameter 'secret' is not present");
throw new GoogleAuthInfoException(uri, "Parameter 'secret' is not present");
}
// decode secret
byte[] secret;
try {
secret = Base32.decode(encodedSecret);
secret = (scheme.equals(MotpInfo.SCHEME)) ? Hex.decode(encodedSecret) : parseSecret(encodedSecret);
} catch (EncodingException e) {
throw new GoogleAuthInfoException("Bad secret", e);
throw new GoogleAuthInfoException(uri, "Bad secret", e);
}
if (secret.length == 0) {
throw new GoogleAuthInfoException(uri, "Secret is empty");
}
// check the otp type
OtpInfo info;
String issuer = "";
try {
String type = uri.getHost();
String type = (scheme.equals(MotpInfo.SCHEME)) ? MotpInfo.ID : uri.getHost();
if (type == null) {
throw new GoogleAuthInfoException(String.format("Host not present in URI: %s", uri.toString()));
throw new GoogleAuthInfoException(uri, String.format("Host not present in URI: %s", uri.toString()));
}
switch (type) {
@@ -119,16 +92,28 @@ public class GoogleAuthInfo implements Serializable {
HotpInfo hotpInfo = new HotpInfo(secret);
String counter = uri.getQueryParameter("counter");
if (counter == null) {
throw new GoogleAuthInfoException("Parameter 'counter' is not present");
throw new GoogleAuthInfoException(uri, "Parameter 'counter' is not present");
}
hotpInfo.setCounter(Long.parseLong(counter));
info = hotpInfo;
break;
case YandexInfo.HOST_ID:
String pin = uri.getQueryParameter("pin");
if (pin != null) {
pin = new String(parseSecret(pin), StandardCharsets.UTF_8);
}
info = new YandexInfo(secret, pin);
issuer = info.getType();
break;
case MotpInfo.ID:
info = new MotpInfo(secret);
break;
default:
throw new GoogleAuthInfoException(String.format("Unsupported OTP type: %s", type));
throw new GoogleAuthInfoException(uri, String.format("Unsupported OTP type: %s", type));
}
} catch (OtpInfoException | NumberFormatException e) {
throw new GoogleAuthInfoException(e);
} catch (OtpInfoException | NumberFormatException | EncodingException e) {
throw new GoogleAuthInfoException(uri, e);
}
// provider info used to disambiguate accounts
@@ -136,7 +121,6 @@ public class GoogleAuthInfo implements Serializable {
String label = path != null && path.length() > 0 ? path.substring(1) : "";
String accountName = "";
String issuer = "";
if (label.contains(":")) {
// a label can only contain one colon
@@ -153,7 +137,9 @@ public class GoogleAuthInfo implements Serializable {
// label only contains the account name
// grab the issuer's info from the 'issuer' parameter if it's present
String issuerParam = uri.getQueryParameter("issuer");
issuer = issuerParam != null ? issuerParam : "";
if (issuer.isEmpty()) {
issuer = issuerParam != null ? issuerParam : "";
}
accountName = label;
}
@@ -168,16 +154,24 @@ public class GoogleAuthInfo implements Serializable {
info.setDigits(Integer.parseInt(digits));
}
} catch (OtpInfoException | NumberFormatException e) {
throw new GoogleAuthInfoException(e);
throw new GoogleAuthInfoException(uri, e);
}
return new GoogleAuthInfo(info, accountName, issuer);
}
/**
* Decodes the given base 32 secret, while being tolerant of whitespace and dashes.
*/
public static byte[] parseSecret(String s) throws EncodingException {
s = s.trim().replace("-", "").replace(" ", "");
return Base32.decode(s);
}
public static Export parseExportUri(String s) throws GoogleAuthInfoException {
Uri uri = Uri.parse(s);
if (uri == null) {
throw new GoogleAuthInfoException("Bad URI format");
throw new GoogleAuthInfoException(uri, "Bad URI format");
}
return GoogleAuthInfo.parseExportUri(uri);
}
@@ -185,17 +179,17 @@ public class GoogleAuthInfo implements Serializable {
public static Export parseExportUri(Uri uri) throws GoogleAuthInfoException {
String scheme = uri.getScheme();
if (scheme == null || !scheme.equals(SCHEME_EXPORT)) {
throw new GoogleAuthInfoException("Unsupported protocol");
throw new GoogleAuthInfoException(uri, "Unsupported protocol");
}
String host = uri.getHost();
if (host == null || !host.equals("offline")) {
throw new GoogleAuthInfoException("Unsupported host");
throw new GoogleAuthInfoException(uri, "Unsupported host");
}
String data = uri.getQueryParameter("data");
if (data == null) {
throw new GoogleAuthInfoException("Parameter 'data' is not set");
throw new GoogleAuthInfoException(uri, "Parameter 'data' is not set");
}
GoogleAuthProtos.MigrationPayload payload;
@@ -203,26 +197,63 @@ public class GoogleAuthInfo implements Serializable {
byte[] bytes = Base64.decode(data);
payload = GoogleAuthProtos.MigrationPayload.parseFrom(bytes);
} catch (EncodingException | InvalidProtocolBufferException e) {
throw new GoogleAuthInfoException(e);
throw new GoogleAuthInfoException(uri, e);
}
List<GoogleAuthInfo> infos = new ArrayList<>();
for (GoogleAuthProtos.MigrationPayload.OtpParameters params : payload.getOtpParametersList()) {
OtpInfo otp;
try {
byte[] secret = params.getSecret().toByteArray();
switch (params.getType()) {
case OTP_HOTP:
otp = new HotpInfo(secret, params.getCounter());
int digits;
switch (params.getDigits()) {
case DIGIT_COUNT_UNSPECIFIED:
// intentional fallthrough
case DIGIT_COUNT_SIX:
digits = TotpInfo.DEFAULT_DIGITS;
break;
case OTP_TOTP:
otp = new TotpInfo(secret);
case DIGIT_COUNT_EIGHT:
digits = 8;
break;
default:
throw new GoogleAuthInfoException(String.format("Unsupported algorithm: %d", params.getType().ordinal()));
throw new GoogleAuthInfoException(uri, String.format("Unsupported digits: %d", params.getDigits().ordinal()));
}
} catch (OtpInfoException e){
throw new GoogleAuthInfoException(e);
String algo;
switch (params.getAlgorithm()) {
case ALGORITHM_UNSPECIFIED:
// intentional fallthrough
case ALGORITHM_SHA1:
algo = "SHA1";
break;
case ALGORITHM_SHA256:
algo = "SHA256";
break;
case ALGORITHM_SHA512:
algo = "SHA512";
break;
default:
throw new GoogleAuthInfoException(uri, String.format("Unsupported hash algorithm: %d", params.getAlgorithm().ordinal()));
}
byte[] secret = params.getSecret().toByteArray();
if (secret.length == 0) {
throw new GoogleAuthInfoException(uri, "Secret is empty");
}
switch (params.getType()) {
case OTP_TYPE_UNSPECIFIED:
// intentional fallthrough
case OTP_TYPE_TOTP:
otp = new TotpInfo(secret, algo, digits, TotpInfo.DEFAULT_PERIOD);
break;
case OTP_TYPE_HOTP:
otp = new HotpInfo(secret, algo, digits, params.getCounter());
break;
default:
throw new GoogleAuthInfoException(uri, String.format("Unsupported algorithm: %d", params.getType().ordinal()));
}
} catch (OtpInfoException e) {
throw new GoogleAuthInfoException(uri, e);
}
String name = params.getName();
@@ -240,6 +271,55 @@ public class GoogleAuthInfo implements Serializable {
return new Export(infos, payload.getBatchId(), payload.getBatchIndex(), payload.getBatchSize());
}
public OtpInfo getOtpInfo() {
return _info;
}
@Override
public Uri getUri() {
Uri.Builder builder = new Uri.Builder();
if (_info instanceof MotpInfo) {
builder.scheme(MotpInfo.SCHEME);
builder.appendQueryParameter("secret", Hex.encode(_info.getSecret()));
} else {
builder.scheme(SCHEME);
if (_info instanceof TotpInfo) {
if (_info instanceof SteamInfo) {
builder.authority("steam");
} else if (_info instanceof YandexInfo) {
builder.authority(YandexInfo.HOST_ID);
} else {
builder.authority("totp");
}
builder.appendQueryParameter("period", Integer.toString(((TotpInfo) _info).getPeriod()));
} else if (_info instanceof HotpInfo) {
builder.authority("hotp");
builder.appendQueryParameter("counter", Long.toString(((HotpInfo) _info).getCounter()));
} else {
throw new RuntimeException(String.format("Unsupported OtpInfo type: %s", _info.getClass()));
}
builder.appendQueryParameter("digits", Integer.toString(_info.getDigits()));
builder.appendQueryParameter("algorithm", _info.getAlgorithm(false));
builder.appendQueryParameter("secret", Base32.encode(_info.getSecret()));
if (_info instanceof YandexInfo) {
builder.appendQueryParameter("pin", Base32.encode(((YandexInfo) _info).getPin()));
}
}
if (_issuer != null && !_issuer.equals("")) {
builder.path(String.format("%s:%s", _issuer, _accountName));
builder.appendQueryParameter("issuer", _issuer);
} else {
builder.path(_accountName);
}
return builder.build();
}
public String getIssuer() {
return _issuer;
}
@@ -248,7 +328,7 @@ public class GoogleAuthInfo implements Serializable {
return _accountName;
}
public static class Export {
public static class Export implements Transferable, Serializable {
private int _batchId;
private int _batchIndex;
private int _batchSize;
@@ -276,5 +356,110 @@ public class GoogleAuthInfo implements Serializable {
public int getBatchId() {
return _batchId;
}
public static List<Integer> getMissingIndices(@NonNull List<Export> exports) throws IllegalArgumentException {
if (!isSingleBatch(exports)) {
throw new IllegalArgumentException("Export list contains entries from different batches");
}
List<Integer> indicesMissing = new ArrayList<>();
if (exports.isEmpty()) {
return indicesMissing;
}
Set<Integer> indicesPresent = exports.stream()
.map(Export::getBatchIndex)
.collect(Collectors.toSet());
for (int i = 0; i < exports.get(0).getBatchSize(); i++) {
if (!indicesPresent.contains(i)) {
indicesMissing.add(i);
}
}
return indicesMissing;
}
public static boolean isSingleBatch(@NonNull List<Export> exports) {
if (exports.isEmpty()) {
return true;
}
int batchId = exports.get(0).getBatchId();
for (Export export : exports) {
if (export.getBatchId() != batchId) {
return false;
}
}
return true;
}
@Override
public Uri getUri() throws GoogleAuthInfoException {
GoogleAuthProtos.MigrationPayload.Builder builder = GoogleAuthProtos.MigrationPayload.newBuilder();
builder.setBatchId(_batchId)
.setBatchIndex(_batchIndex)
.setBatchSize(_batchSize)
.setVersion(1);
for (GoogleAuthInfo info: _entries) {
GoogleAuthProtos.MigrationPayload.OtpParameters.Builder parameters = GoogleAuthProtos.MigrationPayload.OtpParameters.newBuilder()
.setSecret(ByteString.copyFrom(info.getOtpInfo().getSecret()))
.setName(info.getAccountName())
.setIssuer(info.getIssuer());
switch (info.getOtpInfo().getAlgorithm(false)) {
case "SHA1":
parameters.setAlgorithm(GoogleAuthProtos.MigrationPayload.Algorithm.ALGORITHM_SHA1);
break;
case "SHA256":
parameters.setAlgorithm(GoogleAuthProtos.MigrationPayload.Algorithm.ALGORITHM_SHA256);
break;
case "SHA512":
parameters.setAlgorithm(GoogleAuthProtos.MigrationPayload.Algorithm.ALGORITHM_SHA512);
break;
case "MD5":
parameters.setAlgorithm(GoogleAuthProtos.MigrationPayload.Algorithm.ALGORITHM_MD5);
break;
default:
throw new GoogleAuthInfoException(info.getUri(), String.format("Unsupported Algorithm: %s", info.getOtpInfo().getAlgorithm(false)));
}
switch (info.getOtpInfo().getDigits()) {
case 6:
parameters.setDigits(GoogleAuthProtos.MigrationPayload.DigitCount.DIGIT_COUNT_SIX);
break;
case 8:
parameters.setDigits(GoogleAuthProtos.MigrationPayload.DigitCount.DIGIT_COUNT_EIGHT);
break;
default:
throw new GoogleAuthInfoException(info.getUri(), String.format("Unsupported number of digits: %s", info.getOtpInfo().getDigits()));
}
switch (info.getOtpInfo().getType().toLowerCase()) {
case HotpInfo.ID:
parameters.setType(GoogleAuthProtos.MigrationPayload.OtpType.OTP_TYPE_HOTP);
parameters.setCounter(((HotpInfo) info.getOtpInfo()).getCounter());
break;
case TotpInfo.ID:
parameters.setType(GoogleAuthProtos.MigrationPayload.OtpType.OTP_TYPE_TOTP);
break;
default:
throw new GoogleAuthInfoException(info.getUri(), String.format("Type unsupported by GoogleAuthProtos: %s", info.getOtpInfo().getType()));
}
builder.addOtpParameters(parameters.build());
}
Uri.Builder exportUriBuilder = new Uri.Builder()
.scheme(SCHEME_EXPORT)
.authority("offline");
String data = Base64.encode(builder.build().toByteArray());
exportUriBuilder.appendQueryParameter("data", data);
return exportUriBuilder.build();
}
}
}
@@ -1,24 +1,41 @@
package com.beemdevelopment.aegis.otp;
import android.net.Uri;
public class GoogleAuthInfoException extends Exception {
public GoogleAuthInfoException(Throwable cause) {
private final Uri _uri;
public GoogleAuthInfoException(Uri uri, Throwable cause) {
super(cause);
_uri = uri;
}
public GoogleAuthInfoException(String message) {
public GoogleAuthInfoException(Uri uri, String message) {
super(message);
_uri = uri;
}
public GoogleAuthInfoException(String message, Throwable cause) {
public GoogleAuthInfoException(Uri uri, String message, Throwable cause) {
super(message, cause);
_uri = uri;
}
/**
* Reports whether the scheme of the URI is phonefactor://.
*/
public boolean isPhoneFactor() {
return _uri != null && _uri.getScheme() != null && _uri.getScheme().equals("phonefactor");
}
@Override
public String getMessage() {
Throwable cause = getCause();
if (cause == null) {
if (cause == null
|| this == cause
|| (super.getMessage() != null && super.getMessage().equals(cause.getMessage()))) {
return super.getMessage();
}
return String.format("%s (%s)", super.getMessage(), cause.getMessage());
}
}
@@ -11,6 +11,7 @@ import java.security.NoSuchAlgorithmException;
public class HotpInfo extends OtpInfo {
public static final String ID = "hotp";
public static final int DEFAULT_COUNTER = 0;
private long _counter;
@@ -20,7 +21,7 @@ public class HotpInfo extends OtpInfo {
}
public HotpInfo(byte[] secret) throws OtpInfoException {
this(secret, 0);
this(secret, DEFAULT_COUNTER);
}
public HotpInfo(byte[] secret, String algorithm, int digits, long counter) throws OtpInfoException {
@@ -29,7 +30,9 @@ public class HotpInfo extends OtpInfo {
}
@Override
public String getOtp() {
public String getOtp() throws OtpInfoException {
checkSecret();
try {
OTP otp = HOTP.generateOTP(getSecret(), getAlgorithm(true), getDigits(), getCounter());
return otp.toString();
@@ -39,7 +42,7 @@ public class HotpInfo extends OtpInfo {
}
@Override
public String getType() {
public String getTypeId() {
return ID;
}
@@ -0,0 +1,95 @@
package com.beemdevelopment.aegis.otp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.beemdevelopment.aegis.crypto.otp.MOTP;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
public class MotpInfo extends TotpInfo {
public static final String ID = "motp";
public static final String SCHEME = "motp";
public static final String ALGORITHM = "MD5";
public static final int PERIOD = 10;
public static final int DIGITS = 6;
private String _pin;
public MotpInfo(@NonNull byte[] secret) throws OtpInfoException {
this(secret, null);
}
public MotpInfo(byte[] secret, String pin) throws OtpInfoException {
super(secret, ALGORITHM, DIGITS, PERIOD);
setPin(pin);
}
@Override
public String getOtp() {
if (_pin == null) {
throw new IllegalStateException("PIN must be set before generating an OTP");
}
try {
MOTP otp = MOTP.generateOTP(getSecret(), getAlgorithm(false), getDigits(), getPeriod(), getPin());
return otp.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
@Override
public String getOtp(long time) {
if (_pin == null) {
throw new IllegalStateException("PIN must be set before generating an OTP");
}
try {
MOTP otp = MOTP.generateOTP(getSecret(), getAlgorithm(false), getDigits(), getPeriod(), getPin(), time);
return otp.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
@Override
public String getTypeId() {
return ID;
}
@Override
public JSONObject toJson() {
JSONObject result = super.toJson();
try {
result.put("pin", getPin());
} catch (JSONException e) {
throw new RuntimeException(e);
}
return result;
}
@Nullable
public String getPin() {
return _pin;
}
public void setPin(@NonNull String pin) {
this._pin = pin;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof MotpInfo)) {
return false;
}
MotpInfo info = (MotpInfo) o;
return super.equals(o) && Objects.equals(getPin(), info.getPin());
}
}
@@ -8,14 +8,18 @@ import org.json.JSONObject;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Locale;
public abstract class OtpInfo implements Serializable {
public static final int DEFAULT_DIGITS = 6;
public static final String DEFAULT_ALGORITHM = "SHA1";
private byte[] _secret;
private String _algorithm;
private int _digits;
public OtpInfo(byte[] secret) throws OtpInfoException {
this(secret, "SHA1", 6);
this(secret, DEFAULT_ALGORITHM, DEFAULT_DIGITS);
}
public OtpInfo(byte[] secret, String algorithm, int digits) throws OtpInfoException {
@@ -24,15 +28,25 @@ public abstract class OtpInfo implements Serializable {
setDigits(digits);
}
public abstract String getOtp();
public abstract String getOtp() throws OtpInfoException;
public abstract String getType();
protected void checkSecret() throws OtpInfoException {
if (getSecret().length == 0) {
throw new OtpInfoException("Secret is empty");
}
}
public abstract String getTypeId();
public String getType() {
return getTypeId().toUpperCase(Locale.ROOT);
}
public JSONObject toJson() {
JSONObject obj = new JSONObject();
try {
obj.put("secret", new String(Base32.encode(getSecret())));
obj.put("secret", Base32.encode(getSecret()));
obj.put("algo", getAlgorithm(false));
obj.put("digits", getDigits());
} catch (JSONException e) {
@@ -62,14 +76,15 @@ public abstract class OtpInfo implements Serializable {
}
public static boolean isAlgorithmValid(String algorithm) {
return algorithm.equals("SHA1") || algorithm.equals("SHA256") || algorithm.equals("SHA512");
return algorithm.equals("SHA1") || algorithm.equals("SHA256") ||
algorithm.equals("SHA512") || algorithm.equals("MD5");
}
public void setAlgorithm(String algorithm) throws OtpInfoException {
if (algorithm.startsWith("Hmac")) {
algorithm = algorithm.substring(4);
}
algorithm = algorithm.toUpperCase();
algorithm = algorithm.toUpperCase(Locale.ROOT);
if (!isAlgorithmValid(algorithm)) {
throw new OtpInfoException(String.format("unsupported algorithm: %s", algorithm));
@@ -107,6 +122,12 @@ public abstract class OtpInfo implements Serializable {
case HotpInfo.ID:
info = new HotpInfo(secret, algo, digits, obj.getLong("counter"));
break;
case YandexInfo.ID:
info = new YandexInfo(secret, obj.getString("pin"));
break;
case MotpInfo.ID:
info = new MotpInfo(secret, obj.getString("pin"));
break;
default:
throw new OtpInfoException("unsupported otp type: " + type);
}
@@ -127,7 +148,7 @@ public abstract class OtpInfo implements Serializable {
}
OtpInfo info = (OtpInfo) o;
return getType().equals(info.getType())
return getTypeId().equals(info.getTypeId())
&& Arrays.equals(getSecret(), info.getSecret())
&& getAlgorithm(false).equals(info.getAlgorithm(false))
&& getDigits() == info.getDigits();
@@ -5,12 +5,14 @@ import com.beemdevelopment.aegis.crypto.otp.TOTP;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
public class SteamInfo extends TotpInfo {
public static final String ID = "steam";
public static final int DIGITS = 5;
public SteamInfo(byte[] secret) throws OtpInfoException {
super(secret, "SHA1", 5, 30);
super(secret, OtpInfo.DEFAULT_ALGORITHM, DIGITS, TotpInfo.DEFAULT_PERIOD);
}
public SteamInfo(byte[] secret, String algorithm, int digits, int period) throws OtpInfoException {
@@ -18,7 +20,9 @@ public class SteamInfo extends TotpInfo {
}
@Override
public String getOtp() {
public String getOtp() throws OtpInfoException {
checkSecret();
try {
OTP otp = TOTP.generateOTP(getSecret(), getAlgorithm(true), getDigits(), getPeriod());
return otp.toSteamString();
@@ -28,7 +32,13 @@ public class SteamInfo extends TotpInfo {
}
@Override
public String getType() {
public String getTypeId() {
return ID;
}
@Override
public String getType() {
String id = getTypeId();
return id.substring(0, 1).toUpperCase(Locale.ROOT) + id.substring(1);
}
}
@@ -11,12 +11,13 @@ import java.security.NoSuchAlgorithmException;
public class TotpInfo extends OtpInfo {
public static final String ID = "totp";
public static final int DEFAULT_PERIOD = 30;
private int _period;
public TotpInfo(byte[] secret) throws OtpInfoException {
super(secret);
setPeriod(30);
setPeriod(DEFAULT_PERIOD);
}
public TotpInfo(byte[] secret, String algorithm, int digits, int period) throws OtpInfoException {
@@ -25,7 +26,9 @@ public class TotpInfo extends OtpInfo {
}
@Override
public String getOtp() {
public String getOtp() throws OtpInfoException {
checkSecret();
try {
OTP otp = TOTP.generateOTP(getSecret(), getAlgorithm(true), getDigits(), getPeriod());
return otp.toString();
@@ -34,8 +37,17 @@ public class TotpInfo extends OtpInfo {
}
}
public String getOtp(long time) {
try {
OTP otp = TOTP.generateOTP(getSecret(), getAlgorithm(true), getDigits(), getPeriod(), time);
return otp.toString();
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
@Override
public String getType() {
public String getTypeId() {
return ID;
}

Some files were not shown because too many files have changed in this diff Show More