1
0
mirror of https://github.com/bitwarden/mobile synced 2025-12-05 23:53:33 +00:00

Compare commits

...

286 Commits

Author SHA1 Message Date
Andreas Coroiu
da051b8fc1 Add example of delegated UI class 2024-02-19 16:44:15 +01:00
Andreas Coroiu
c801b2fc3a Fix incompatible GUID conversions 2024-02-19 15:35:17 +01:00
Federico Maccaroni
41161864db PM-5154 [Passkeys iOS] Fix Credential ID handling on bytes and string formats. Fix Discoverable to be lowercase on set so it doesn't break parsing on clients. Added UserDisplayName on Fido2 entities. Extracted the Guid Standard/Raw format helpers to a extensions class. 2024-02-16 19:30:33 -03:00
Andreas Coroiu
a1c9ebf01f fix wrong signature format 2024-02-16 10:57:44 +01:00
Federico Maccaroni
7381d5278a PM-5154 Fixed select passkey flow and started implementing create passkey on iOS 2024-02-15 21:16:54 -03:00
Federico Maccaroni
8b5a7b257d Merge branch 'PM-5731-create-c-web-authn-authenticator-to-support-maui-apps' into temp-passkeys-ios-fede 2024-02-15 21:09:09 -03:00
mpbw2
62e0626648 Merge branch 'feature/maui-migration-passkeys' into PM-5731-create-c-web-authn-authenticator-to-support-maui-apps 2024-02-15 14:42:53 -05:00
Federico Maccaroni
d339514d9a Merge branch 'main' into feature/maui-migration-passkeys
# Conflicts:
#	.github/workflows/build.yml
#	nuget.config
#	src/App/App.csproj
#	src/App/Platforms/Android/AndroidManifest.xml
#	src/App/Platforms/iOS/AppDelegate.cs
#	src/Core/Core.csproj
#	src/Core/Pages/Settings/AutofillSettingsPageViewModel.android.cs
#	src/Core/Utilities/ThemeManager.cs
#	src/iOS.Autofill/CredentialProviderViewController.cs
#	src/iOS.Autofill/iOS.Autofill.csproj
2024-02-14 14:19:51 -03:00
Federico Maccaroni
75ec96f282 PM-3349 Added exception on gitignore so the nupkg for the AndroidX Credentials is added 2024-02-14 13:58:35 -03:00
Andreas Coroiu
3c848a3dcc [PM-5731] feat: implement credential assertion in client 2024-02-12 13:45:41 +01:00
Federico Maccaroni
18beb4e5f4 Added iOS passkeys integration, warning this branch has lots of logs to ease "debugging" extensions. 2024-02-09 18:15:25 -03:00
Federico Maccaroni
e9d1792dd7 Merge branch 'feature/maui-migration-passkeys' into PM-5731-create-c-web-authn-authenticator-to-support-maui-apps 2024-02-08 12:33:33 -03:00
Federico Maccaroni
8f8a5795d3 Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys 2024-02-08 12:33:16 -03:00
Federico Maccaroni
4631a9e62c PM-3349 PM-3350 Fixed Unit tests because of referencing FFImageLoading when it's not possible 2024-02-08 12:31:52 -03:00
Federico Maccaroni
51ee6a84b5 Merged main into maui-migration 2024-02-08 12:17:34 -03:00
Andreas Coroiu
b8c5ef501a [PM-5731] feat: implement fido2 client createCredential 2024-02-08 14:41:08 +01:00
Andreas Coroiu
2075f8168c [PM-5731] chore: document uri helpers 2024-02-08 14:41:07 +01:00
Andreas Coroiu
0f5df0f6b0 [PM-5731] feat: add incomplete rpId verification 2024-02-08 14:41:07 +01:00
Andreas Coroiu
ad8faec200 [PM-5731] feat: add sameOriginWithAncestor and user id length checks 2024-02-08 14:41:07 +01:00
Andreas Coroiu
3223ceb9a8 [PM-5731] fix: failing test 2024-02-08 14:41:06 +01:00
Dinis Vieira
8d5006c0bd [PM-5906] Fix for incorrect Send MaxAccess white text color on label when using light theme on iOS (#2981)
* PM-5906 workaround for incorrect textcolor when programmatically changing text on Entry

* Update src/Core/Pages/Send/SendAddEditPage.xaml.cs

Co-authored-by: Federico Maccaroni <fedemkr@gmail.com>

---------

Co-authored-by: Federico Maccaroni <fedemkr@gmail.com>
2024-02-07 19:09:18 +00:00
Dinis Vieira
37208571fe [PM-5907] Fix for incorrect TOTP white text color on label when using light theme on iOS (#2982)
* PM-5907 workaround for incorrect textcolor when programmatically changing text on Entry

* Update src/Core/Pages/Vault/CipherAddEditPage.xaml.cs

Co-authored-by: Federico Maccaroni <fedemkr@gmail.com>

---------

Co-authored-by: Federico Maccaroni <fedemkr@gmail.com>
2024-02-07 19:08:51 +00:00
Federico Maccaroni
7469dad35a PM-5731 Fix build updating discoverable flag 2024-02-07 15:31:21 -03:00
Dinis Vieira
759627b3c7 PM-6077 Separated Android and iOS HybridWebViewHandler so that it can be used on iOS.Core (#2983) 2024-02-07 17:50:07 +00:00
Federico Maccaroni
eae84ded42 Merge branch 'feature/maui-migration-passkeys' into PM-5731-create-c-web-authn-authenticator-to-support-maui-apps 2024-02-07 14:00:00 -03:00
Federico Maccaroni
563210a74e Merge branch 'PM-5731-create-c-web-authn-authenticator-to-support-maui-apps' of https://github.com/bitwarden/mobile into PM-5731-create-c-web-authn-authenticator-to-support-maui-apps 2024-02-07 13:59:53 -03:00
Federico Maccaroni
08fac4752f PM-3349 PM-3350 Fix crash on iOS AppGroup container URL because of sln config on AndroidX Credentials. Changed the project reference of Credentials to be a local NuGet. 2024-02-07 13:59:31 -03:00
Andreas Coroiu
70db27b750 [PM-5731] feat: scaffold fido2 client 2024-02-06 14:20:52 +01:00
Andreas Coroiu
00cff182b4 [PM-5731] chore: add user presence todo comment 2024-02-06 08:38:38 +01:00
Federico Maccaroni
dc5e90436b Merge branch 'feature/maui-migration-passkeys' into PM-5731-create-c-web-authn-authenticator-to-support-maui-apps 2024-02-05 14:32:00 -03:00
Federico Maccaroni
9307e7e0d8 Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys 2024-02-05 14:31:44 -03:00
Federico Maccaroni
b1a0801f9b PM-3349 Removed commented code from build.yml regarding FDroid that is not needed anymore. 2024-02-05 13:14:37 -03:00
Federico Maccaroni
04cc53b934 Merge branch 'main' into feature/maui-migration 2024-02-05 11:50:41 -03:00
Federico Maccaroni
c138658a31 [PM-5896] Fix MAUI iOS Background crash due to lock files on suspension (#2969)
* PM-5896 Fix background crash on iOS due to lock files when app gets suspended. Changed loading and error placeholders of the CachedImage to not be used and use default icon of IconLabel instead changing visibility.

* PM-5896 Changed methods to be protected so that they don't get removed by the linker.

* PM-5896 Added stub class and references to it so to have stronger references to Icon_Success and Icon_Error so the linker doesn't remove them.
2024-02-05 11:46:08 -03:00
Dinis Vieira
f1854f2c04 PM-5903 Changed App.xaml.cs SetOption to only update the needed properties instead of replacing the existing Options object which would cause the AccountSwitcher button bug (#2973) 2024-02-03 15:59:22 +00:00
Federico Maccaroni
e4056d9ee6 Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys 2024-02-02 15:51:50 -03:00
Federico Maccaroni
eb95a54db2 PM-3350 Fix iossimulator-x64 argon2id load so we can test on simulators and also made easier to maintain loading the argon2id library on the iOS projects by setting a general Directory.Build.props that is shared. 2024-02-02 15:48:04 -03:00
Dinis Vieira
7ddea4c70b PM-5902 fix for account switcher not dismissing when tapping outside (#2974) 2024-02-01 21:44:13 +00:00
Federico Maccaroni
3804e86995 Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys 2024-02-01 12:35:50 -03:00
Andreas Coroiu
b787a6c840 [PM-5731] chore: clean up and refactor attestation tests 2024-02-01 13:57:38 +01:00
Andreas Coroiu
a6c4bc9273 [PM-5731] chore: clean up and refactor assertion tests 2024-02-01 09:23:30 +01:00
Federico Maccaroni
b23bed182f Merge branch 'main' into feature/maui-migration 2024-01-31 12:14:02 -03:00
Federico Maccaroni
f8e421871b Merge branch 'feature/maui-migration' of https://github.com/bitwarden/mobile into feature/maui-migration 2024-01-31 12:13:31 -03:00
Andreas Coroiu
4988dbea72 [PM-5731] feat: ensure unlocked vault 2024-01-30 14:40:48 +01:00
Andreas Coroiu
ca250c53ad [PM-5731] feat: add support for specifying user presence requirement 2024-01-30 14:19:41 +01:00
Andreas Coroiu
6bb724ff06 [PM-5731] feat: add support for silent discoverability 2024-01-30 13:10:09 +01:00
Andreas Coroiu
f3c64a89eb [PM-5731] chore: add Async to method names 2024-01-30 10:15:58 +01:00
Andreas Coroiu
aa71ebc634 [PM-5731] chore: use primary constructor 2024-01-30 10:14:08 +01:00
Andreas Coroiu
d0bb7f0a54 [PM-5731] feat: remove logging 2024-01-30 10:01:11 +01:00
mpbw2
d0103496b9 [PM-5910] Workaround for for sliding elements in Duo 2FA flow (#2967)
* workaround for sliding elements in duo 2fa flow

* restrict workaround to Android

* restrict workaround to Android

* Revert "restrict workaround to Android"

This reverts commit c2753d5dc4.

* Revert "restrict workaround to Android"

This reverts commit 69688cfb98.
2024-01-29 17:26:14 -05:00
Federico Maccaroni
cd8952221e Merge branch 'main' into feature/maui-migration 2024-01-29 17:17:07 -03:00
Federico Maccaroni
155c7539bd Removing error/loading placeholders of icons on the cells to see if that is causing the background crash on iOS; so we can test this in TestFlight 2024-01-29 17:16:01 -03:00
Federico Maccaroni
5f43681fb1 PM-3350 Go back to include argon2id and interpreter 2024-01-29 14:30:42 -03:00
Federico Maccaroni
d2965e6e10 PM-3350 Enabled iOS extensions and WatchOS app to be included based on the Directory.Build.props 2024-01-29 14:01:18 -03:00
Federico Maccaroni
ec1ade7761 Merge branch 'main' into feature/maui-migration
# Conflicts:
#	src/App/Platforms/Android/AndroidManifest.xml
2024-01-29 13:58:30 -03:00
Federico Maccaroni
f35bef0d7b PM-3350 Go back to use Interpreter and added some Directory.Build.props to easily change Codesign properties and also include/exclude iOS extensions / WatchOS from the build. 2024-01-29 13:56:31 -03:00
Andreas Coroiu
5d5d113369 [PM-5731] feat: implement signing 2024-01-29 14:43:14 +01:00
Andreas Coroiu
7ca9e61e93 [PM-5731] feat: return public key in DER format 2024-01-29 13:50:30 +01:00
Andreas Coroiu
da7326b0cc [PM-5731] feat: implement key generation 2024-01-29 11:27:24 +01:00
Federico Maccaroni
138d37cf5e PM-5928 Fix circle animation to be shown on verification codes list on each item 2024-01-26 12:27:57 -03:00
Andreas Coroiu
c87728027e [PM-5731] feat: partial attestation implementation 2024-01-26 14:57:44 +01:00
Federico Maccaroni
fc2fed079f PM-3350 Try to disable Interpreter to have better crash knowledge. This time testing if avoiding loading the argon2id lib we're able to not use the interpreter. 2024-01-26 10:34:28 -03:00
Federico Maccaroni
9c441a98f4 Merge branch 'main' into feature/maui-migration 2024-01-26 10:17:21 -03:00
Andreas Coroiu
e1908d8eef [PM-5731] chore: clean up unusued params 2024-01-26 10:45:23 +01:00
Andreas Coroiu
8be604feac [PM-5731] feat: add unknown error handling 2024-01-26 10:44:39 +01:00
Andreas Coroiu
c90ed74faa [PM-5731] feat: add user verification checks 2024-01-26 10:30:31 +01:00
Federico Maccaroni
1491872b62 PM-3350 Added check for state migration version before trying to migrate LiteDB values into Prefs when there's no need to and that may be inducing crashes on backgrounded iOS apps. 2024-01-25 17:56:28 -03:00
Federico Maccaroni
c74636ffa5 PM-3350 Commented event collection upload on the timer and when sending the app to background to see if that prevents the app from crashing on release mode. 2024-01-25 13:22:42 -03:00
Federico Maccaroni
05677f93c5 Fix merge from main 2024-01-25 13:20:13 -03:00
Federico Maccaroni
0aef241df6 Merge branch 'main' into feature/maui-migration
# Conflicts:
#	src/Core/Pages/Settings/AboutSettingsPageViewModel.cs
2024-01-25 13:16:42 -03:00
Andreas Coroiu
32c43afae2 [PM-5731] feat: implement credential creation 2024-01-25 16:29:26 +01:00
Andreas Coroiu
44b2443554 [PM-5731] feat: add new credential confirmaiton 2024-01-25 10:49:23 +01:00
Federico Maccaroni
e0b58461b5 Merge branch 'main' into feature/maui-migration 2024-01-24 11:22:28 -03:00
Federico Maccaroni
cd33c7f608 PM-3350 Added new style to prevent spell check and text prediction 2024-01-24 11:22:02 -03:00
Andreas Coroiu
f0dde7eb82 [PM-5731] feat: implement credential exclusion 2024-01-24 14:18:27 +01:00
Andreas Coroiu
19639b61c3 [PM-5731] feat: start implementing attestation 2024-01-24 11:04:37 +01:00
Federico Maccaroni
9d29af36e5 Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys 2024-01-23 18:00:53 -03:00
Federico Maccaroni
4472d7f9a8 PM-3349 PM-3350 Fix external link icon 2024-01-23 17:59:32 -03:00
Federico Maccaroni
999579915c Merge branch 'main' into feature/maui-migration 2024-01-23 17:34:55 -03:00
Federico Maccaroni
63904fd303 PM-3350 Fix Avatar toolbar icon on extensions to load properly and to take advantage of using directly SkiaSharp to do the native conversion to UIImage. Also improved the toolbar item so that size is set appropriately. 2024-01-23 17:34:27 -03:00
Andreas Coroiu
ce550fee74 [PM-5731] feat: scaffold make credential 2024-01-23 14:29:20 +01:00
Andreas Coroiu
f0841eb8b2 [PM-5731] chore: minor clean up 2024-01-23 10:37:04 +01:00
Andreas Coroiu
b23d58c0b1 [PM-5732] feat: finish authenticator assertion implementation
note: CryptoFunctionService still needs Sign implemenation
2024-01-23 10:28:00 +01:00
Federico Maccaroni
2cb6872e4e Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys 2024-01-22 16:57:59 -03:00
Federico Maccaroni
f539bf051d Merge branch 'main' into feature/maui-migration 2024-01-22 16:57:45 -03:00
Federico Maccaroni
14f845d623 Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys
# Conflicts:
#	src/App/Platforms/iOS/AppDelegate.cs
2024-01-22 16:57:07 -03:00
Federico Maccaroni
133a80acef PM-3350 Fixed CancellationTokenSource proper disposal 2024-01-22 12:30:29 -03:00
Andreas Coroiu
e8f6c37c06 [PM-5731] feat: implement assertion without signature 2024-01-22 16:08:15 +01:00
Federico Maccaroni
b43790de9a Merge branch 'main' into feature/maui-migration 2024-01-22 10:00:30 -03:00
Andreas Coroiu
d0e0f0ecdb [PM-5731] feat: add support for counter 2024-01-22 13:36:53 +01:00
Federico Maccaroni
0bdd63df06 Merge branch 'main' into feature/maui-migration 2024-01-19 15:14:50 -03:00
Federico Maccaroni
c6544b49e9 PM-3350 Removed TapGesture Window MAUI hack from iOS.Extension and iOS.ShareExtension 2024-01-19 15:14:22 -03:00
Federico Maccaroni
8e1a8b5f0e PM-3349 PM-3350 Updated XCode version on build.yml to 15.1 2024-01-19 15:02:53 -03:00
Federico Maccaroni
4717f5e230 PM-3349 PM-3350 Improved code safety with try...catch, better invoke on main thread and better null handling. 2024-01-19 15:01:31 -03:00
Andreas Coroiu
ad80defa40 [PM-5731] fix: tests a bit, needed some additional "arrange" steps 2024-01-19 16:42:24 +01:00
Andreas Coroiu
0dc281edc1 [PM-5731] feat: check for UV when reprompt is active 2024-01-19 15:47:06 +01:00
Andreas Coroiu
378551e2d5 [PM-5731] feat: add user does not consent test 2024-01-19 15:18:46 +01:00
Andreas Coroiu
dbe4110027 [PM-5731] feat: add tests for successful UV requests 2024-01-19 11:36:34 +01:00
Andreas Coroiu
a08466d220 [PM-5731] feat: find discoverable credentials 2024-01-19 11:23:56 +01:00
Andreas Coroiu
66a01e30d3 [PM-5731] feat: ask for credentials when found 2024-01-19 10:45:03 +01:00
Federico Maccaroni
01ee1ff845 PM-3350 Enabled back UseInterpreter on iOS Release given that it crashes on startup without it. 2024-01-18 18:54:34 -03:00
Federico Maccaroni
75b4655f38 PM-3350 Testing UseInterpreter false on CI build 2024-01-18 16:32:00 -03:00
mpbw2
9b2f596d15 Move Android camera/scan changes to xaml 2024-01-18 11:31:16 -05:00
Andreas Coroiu
cc89b6a5d5 [PM-5731] feat: add rp mismatch test 2024-01-18 10:15:21 +01:00
Andreas Coroiu
32c2f2aac4 [PM-5731] feat: add first test 2024-01-18 09:23:06 +01:00
Andreas Coroiu
f9b4e30b0b [PM-5731] feat: implement get assertion params object 2024-01-18 09:23:05 +01:00
mpbw2
55fb71744d Improve TOTP scan performance on Android 2024-01-17 13:03:11 -05:00
Federico Maccaroni
ee252be634 Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys 2024-01-17 13:22:47 -03:00
Federico Maccaroni
66f0471f2e Merge branch 'main' into feature/maui-migration 2024-01-17 13:22:26 -03:00
Federico Maccaroni
6b9eeba88d PM-3350 PM-3349 Added property to Directory.Build.props to enable Unit Testing globally so Test runners work 2024-01-17 13:22:00 -03:00
Federico Maccaroni
0a1fbfafb5 PM-3349 Fix navigation when coming from autofill with Accessibility Services enabled. The user was getting into Home page instead of where they were, with this workaround the app navigates as if the account has been switched, leaving the user as closely as possible to where they were, basically on the first screen for the current state of the user. 2024-01-17 09:34:31 -03:00
Federico Maccaroni
0a5d772886 PM-3350 Fix build.yml format 2024-01-16 11:32:27 -03:00
Federico Maccaroni
70c8a264d2 PM-3350 PM-3349 Enable running Core tests 2024-01-15 17:35:37 -03:00
Federico Maccaroni
b5fbb2cade Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys
# Conflicts:
#	bitwarden-mobile.sln
2024-01-15 17:24:33 -03:00
Federico Maccaroni
9027755b71 PM-3350 PM-3349 Updated Readme with MAUI and main branch 2024-01-15 17:20:46 -03:00
Federico Maccaroni
6d625f285b PM-3350 PM-3349 Updated Unit Test projects to NET 8.0 and fixed it to work with Core project reference. Also fixed a test that was breaking due to CIpherKey creation being wrong. Added "UT" as a constant to add when building/running Core.Test project so we have something on the context that tells us that is for a UT. With this I had to remove FFImageLoading on UT context because it doesn't support NET 8.0 2024-01-15 17:18:51 -03:00
Federico Maccaroni
822ad7564e Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys
# Conflicts:
#	src/iOS.Autofill/iOS.Autofill.csproj
2024-01-12 13:59:59 -03:00
Federico Maccaroni
1949a450fd PM-3350 Improved code safety adding a lot of try...catch and logging throughout the app. Also made the invoking on main thread safer on several places of the app. Additionally, on the GroupingsPageViewModel changed the code removing the old Xamarin hack and just using Replace directly instead of Clearing first to see if that fixes the crash we're having sometimes on the app. 2024-01-12 13:54:34 -03:00
Federico Maccaroni
27fa79e0bd Merge branch 'main' into feature/maui-migration 2024-01-12 09:16:10 -03:00
Federico Maccaroni
1e29eacc61 PM-3350 Removed "iOS" old folder project that has been moved into the MAUI Single app project. 2024-01-11 17:51:34 -03:00
Federico Maccaroni
b81d26d589 Bump main iOS version 2024-01-11 14:18:34 -03:00
Federico Maccaroni
cd107b6161 Merge branch 'main' into feature/maui-migration
# Conflicts:
#	src/App/Platforms/Android/AndroidManifest.xml
#	src/iOS.Core/Renderers/CollectionView/ExtendedGroupableItemsViewController.cs
2024-01-11 14:17:34 -03:00
Federico Maccaroni
7ac3646fb0 PM-3350 Added nuget.config so we add the nuget package source for MAUI Nightly builds 2024-01-11 10:31:36 -03:00
Federico Maccaroni
d1e4e8645a PM-3350 Updated MauiVersion to 8.0.4-nightly.* to have the TapGestureRecognizer fix applied. This is done on the Directory.Build.props so we don't have to change it on every csproj. Also removed the workaround of TapGestureHack and fix the Show environment picker to work on the extensions as well. 2024-01-10 19:53:53 -03:00
Federico Maccaroni
36a648e53e Merge branch 'feature/maui-migration' into feature/maui-migration-passkeys
# Conflicts:
#	src/Core/Core.csproj
2024-01-09 18:10:56 -03:00
Federico Maccaroni
6c04ac67b1 PM-3349 Fix Picker selection style by doing a custom PickerHandler for Android which uses SetSingleChoiceItems(...) to provide with the appropriate UI 2024-01-09 15:08:45 -03:00
Federico Maccaroni
dfb7a0621f PM-5154 Added Fido2AuthenticationService to provide us a wrapper for the actual implementation 2024-01-03 19:02:49 -03:00
mpbw2
1eb9e5f8ea add cred manager project to build config 2024-01-03 16:36:56 -05:00
mpbw2
b149e7549c initial commit of android credential provider service (wip) 2024-01-03 16:30:44 -05:00
Federico Maccaroni
e3877cc589 PM-5154 Continue Passkeys Autofill in iOS 2024-01-03 18:22:03 -03:00
Federico Maccaroni
275ae76761 PM-5154 Start implementing Passkeys Autofill in iOS 2024-01-03 18:21:02 -03:00
Federico Maccaroni
a1e4f0aaa2 PM-3350 Updated version to 2024.1.0 on iOS 2024-01-02 13:21:32 -03:00
Federico Maccaroni
adaef0d15b Merge branch 'main' into feature/maui-migration
# Conflicts:
#	src/App/Platforms/Android/AndroidManifest.xml
2024-01-02 13:20:15 -03:00
Dinis Vieira
fa4a2247e3 PM-3349 Changed the "track color" for the Android switch so that the color is different from the "thumb" 2023-12-23 23:09:11 +00:00
Dinis Vieira
5d2fc4530f PM-3349 Minor aligment improvemment for region selection in HomePage 2023-12-23 15:25:41 +00:00
Dinis Vieira
9b64af3423 PM-3349 Fix for icon and text spacing in some list items 2023-12-23 14:30:24 +00:00
Dinis Vieira
b6ff6e34f6 PM-3349 Added custom window so that we can always get the current Active Window. This is used to support the Android Autofil and multi-window scenarios. 2023-12-23 12:30:21 +00:00
Dinis Vieira
6d4c706026 Merge branch 'feature/maui-migration-android-autofill' into feature/maui-migration-android-autofill-redirect-page 2023-12-22 22:16:17 +00:00
Dinis Vieira
14fd026ea0 Merge branch 'feature/maui-migration' into feature/maui-migration-android-autofill 2023-12-22 22:15:58 +00:00
Dinis Vieira
a4392a8730 PM-3349 PM-3350 Changed search icon used in app to avoid issue with icon size on iOS 2023-12-22 22:15:01 +00:00
Dinis Vieira
1b885ea438 PM-3350 Fix for Delete Account buttons on iOS 2023-12-22 17:07:43 +00:00
mpbw2
fa022a1a4f Revert "initial commit of android credential provider service (wip)"
This reverts commit 6011b63958.
2023-12-20 18:23:08 -05:00
mpbw2
6011b63958 initial commit of android credential provider service (wip) 2023-12-20 18:04:21 -05:00
Dinis Vieira
7d79b98bf2 PM-3349 Minor ui fix (space between buttons in delete account page) 2023-12-20 19:04:26 +00:00
Dinis Vieira
d4e75e9de8 PM-3349 Added Window events unsubscription of events. Also changed code to avoid potentially having multiple autofillwindow 2023-12-18 22:56:21 +00:00
Dinis Vieira
c3370b58ec Added some comments and improvemments. 2023-12-18 00:24:38 +00:00
Dinis Vieira
3de13325c9 Merge branch 'feature/maui-migration-android-autofill' into feature/maui-migration-android-autofill-redirect-page 2023-12-17 22:26:46 +00:00
Dinis Vieira
c253c110c1 Merge branch 'feature/maui-migration' into feature/maui-migration-android-autofill 2023-12-17 22:26:33 +00:00
Dinis Vieira
bf35d1f2dc PM-3349 minor fix to add space in HomePage between the region picker labels. 2023-12-17 22:26:15 +00:00
Dinis Vieira
05b6aa90b6 Improved autofill workaround to better handle switching between windows. 2023-12-17 22:05:37 +00:00
Dinis Vieira
e39898bba6 Reusing App.xaml.cs Navigation for the Android RedirectPage
Some other cleanup and changes
2023-12-16 15:18:07 +00:00
Dinis Vieira
da0866cc85 Merge branch 'feature/maui-migration-android-autofill' into feature/maui-migration-android-autofill-redirect-page 2023-12-15 23:51:08 +00:00
Dinis Vieira
b3140381ab Merge branch 'feature/maui-migration' into feature/maui-migration-android-autofill
# Conflicts:
#	src/Core/App.xaml.cs
2023-12-15 23:50:48 +00:00
Dinis Vieira
c01a8f8d93 PM-3349 Ensure "_isResumed=true" is set on App.xaml.cs:Bootstrap 2023-12-15 23:48:11 +00:00
Federico Maccaroni
8484b4af30 PM-3349 Uncommented the Deploy step for Android job 2023-12-15 16:38:40 -03:00
Federico Maccaroni
6b9faed45f PM-3349 Commented the Deploy step for Android job given that we're using the hotfix-rc branch for testing iOS on TestFlight 2023-12-15 12:08:01 -03:00
Federico Maccaroni
770a1c5dfe Merge branch 'main' into feature/maui-migration 2023-12-15 11:53:57 -03:00
Dinis Vieira
3c87d4db1c minor improvemments on autofill-redirect 2023-12-15 13:48:34 +00:00
Dinis Vieira
8b3c6ab35f minor change (public to private fields) 2023-12-14 22:43:50 +00:00
Dinis Vieira
90912977c4 Merge branch 'feature/maui-migration-android-autofill' into feature/maui-migration-android-autofill-redirect-page 2023-12-14 22:02:39 +00:00
Dinis Vieira
740b368b8c Merge branch 'feature/maui-migration' into feature/maui-migration-android-autofill 2023-12-14 22:00:06 +00:00
Federico Maccaroni
3a40a4cda8 PM-3349 Upgraded Android targetSdkVersion to 34 2023-12-14 17:52:11 -03:00
Federico Maccaroni
9bcd2e51f7 Merge branch 'feature/maui-migration' of https://github.com/bitwarden/mobile into feature/maui-migration 2023-12-14 17:32:48 -03:00
Federico Maccaroni
741214a1cc PM-3349 PM-3350 Enabled argon2id and fixed one issue with the Uris when getting the icon image 2023-12-14 17:32:43 -03:00
Federico Maccaroni
aad87dfdce Update .github/workflows/build.yml setup-xcode commit hash
Co-authored-by: Vince Grassia <593223+vgrassia@users.noreply.github.com>
2023-12-14 17:28:10 -03:00
Federico Maccaroni
8fc1e9a3b9 PM-3350 Updated Plugin.Fingerprint so biometrics work 2023-12-14 16:32:04 -03:00
Federico Maccaroni
2a8e15146e PM-3350 Apply Cryptography TrimmerRootAssembly only to iOS 2023-12-14 14:28:20 -03:00
Federico Maccaroni
8559d5908e Merge branch 'feature/maui-migration' of https://github.com/bitwarden/mobile into feature/maui-migration 2023-12-14 13:16:41 -03:00
Federico Maccaroni
f60c4d94fe PM-3350 Fix crash on Release by adding Interpreter on iOS and also adding System.Security.Cryptography to be ignored by the linker 2023-12-14 13:16:32 -03:00
Dinis Vieira
05858bea48 Proof of concept for having multiple window in Android for autofill support and navigating with the help of an Extended splash page. 2023-12-13 23:42:58 +00:00
Dinis Vieira
5cbef47fd4 Merge branch 'feature/maui-migration' into feature/maui-migration-android-autofill 2023-12-13 22:05:52 +00:00
Dinis Vieira
4bf695d18c PM-3349 Fix for app crashing on Android when Dark mode is enabled
Removed unused button style for android
2023-12-13 19:20:43 +00:00
Dinis Vieira
c24e0dfa28 Merge branch 'feature/maui-migration' into feature/maui-migration-android-autofill 2023-12-13 17:30:27 +00:00
Federico Maccaroni
9ccd0834ff Merge branch 'main' into feature/maui-migration 2023-12-13 10:24:29 -03:00
Federico Maccaroni
a806f17d3b PM-3350 Changed linker to use default mode given that "Full" is presenting some problems as the linker is stripping things it shouldn't and we're trying to solve it. So for now we will use the mode "Link SDK assemblies only" so QA can test. 2023-12-12 21:10:51 -03:00
Federico Maccaroni
436a162df2 Merge branch 'main' into feature/maui-migration 2023-12-12 20:19:42 -03:00
Dinis Vieira
f2c298607e Merge branch 'feature/maui-migration' into feature/maui-migration-android-autofill 2023-12-11 22:19:49 +00:00
Federico Maccaroni
b5dbb9ae5e PM-3350 Bumped iOS version 2023-12-11 13:21:31 -03:00
Federico Maccaroni
7a5f7c0274 Merge branch 'master' into feature/maui-migration 2023-12-11 11:42:46 -03:00
Dinis Vieira
17acb57732 PM-3349 Added base structure for avoiding Android Autofill crash. This workaround works but it's not complete as it can't handle the entire workflow when showing CipherSelectionPAge (like checking if it should show LockPage) 2023-12-10 15:05:08 +00:00
Federico Maccaroni
5803635f44 PM-3349 PM-3350 Refactored cipher bindings to have a simpler approach reusing a new CipherItemViewModel to avoid unwanted issues in the app 2023-12-07 23:59:06 -03:00
Federico Maccaroni
19c393842f PM-3350 Cleared left ClipLogger from the iOS extensions debug logging. 2023-12-07 18:14:02 -03:00
Federico Maccaroni
15a306490d Merge branch 'feature/maui-migration' into feature/maui-migration-ios-ext-tap-workaround 2023-12-07 17:41:53 -03:00
Federico Maccaroni
a4a3d31c19 PM-3350 Fix iOS extensions navigation and Window/RootViewController handling for TapGestureRecognizer to work 2023-12-07 17:40:20 -03:00
Dinis Vieira
922dc683af PM-3349 Replaced CrossCurrentActivity plugin with MAUI internal CurrentActivity 2023-12-06 17:27:17 +00:00
Dinis Vieira
bae1b3e891 PM-3349 PM-3350 Minor change: removed unneeded HorizontalTextAlignment from Label. 2023-12-04 16:54:55 +00:00
Federico Maccaroni
a5888827c9 Merge branch 'feature/maui-migration' into feature/maui-migration-ios-ext-tap-workaround 2023-12-04 12:18:01 -03:00
Federico Maccaroni
0348940a12 Merge branch 'master' into feature/maui-migration 2023-12-04 12:17:48 -03:00
Federico Maccaroni
4c2998337d Merge branch 'feature/maui-migration' into feature/maui-migration-ios-ext-tap-workaround 2023-12-04 11:44:03 -03:00
Federico Maccaroni
7ea86380f4 PM-3349 PM-3350 build.yml uncommented jobs so we have a more complete workflow 2023-12-04 11:41:55 -03:00
Federico Maccaroni
406f4425c8 PM-3349 PM-3350 Added MAUI label on self-host settings and on about settings to differentiate from XF app 2023-12-04 11:35:35 -03:00
Federico Maccaroni
95ca911444 PM-3350 Improved MTouch linking and extra args on iOS related csprojs 2023-12-04 11:30:54 -03:00
Federico Maccaroni
fa62510e09 PM-3350 build.yml Added several fixes like not using MtouchUseLLVM on the iOS builds to fix they taking forever to build and some changes on the automation CI to do a debug build for the moment 2023-12-04 10:41:41 -03:00
Federico Maccaroni
65dc73495d PM-3350 build.yml added step to validate app for submitting into App Store and have better logs of it 2023-12-04 10:11:29 -03:00
Federico Maccaroni
02a2e41118 PM-3350 fix build.yml Bitwarden.ipa AppStore exported file 2023-12-04 10:10:18 -03:00
Federico Maccaroni
bd6f8295e7 PM-3350 iOS updated CFBundlerShortVersionString to latest one 2023.10.1 2023-12-04 10:01:56 -03:00
Federico Maccaroni
0a0cb7093b Merge branch 'master' into feature/maui-migration
# Conflicts:
#	.github/workflows/build.yml
2023-12-04 09:59:52 -03:00
Dinis Vieira
465e5eff76 PM-3349 PM-3350 Fix for text getting cut/truncated in both account switcher and ciphers/search lists
Issue is due to MAUI but can be avoided by using slightly different layout
2023-12-03 22:17:16 +00:00
Dinis Vieira
5b756aaf7a PM-3349 PM-3350 Added the ability for users to press "Continue" button as a fallback when using the Yubikey if the "SubmitCommand" doesn't trigger automatically. 2023-12-01 16:49:14 +00:00
Dinis Vieira
d168a7b750 PM-3349 PM-3350 Added workaround for More Options to work on Search and Groupings Page
Updated some code to MAUI Style also
2023-12-01 15:02:12 +00:00
Federico Maccaroni
7f4bbafe3c PM-3350 iOS applied workaround on the iOS Autofill and Share extension to maui embed the navigation page with its content page in the Window 2023-11-30 18:23:54 -03:00
Federico Maccaroni
a5804df6a3 PM-3350 iOS extensions TapGestureRecognizer try Window workaround 2023-11-29 18:42:39 -03:00
Federico Maccaroni
bfa2a51608 PM-3349 build.yml configured FDROID job for MAUI 2023-11-27 17:53:01 -03:00
Federico Maccaroni
32be08daae PM-3349 build.yml enabled android build workflow 2023-11-27 09:24:36 -03:00
Dinis Vieira
0a628cc8a8 PM-3349 PM-3350 Workaround to fix issues with text getting cropped/truncated when a Label has both Multiline and LinebreakMode set 2023-11-26 14:46:30 +00:00
Federico Maccaroni
80c424ed03 Update build.yml disabling iOS job to avoid long running process of publish until we can fix that 2023-11-25 10:17:48 -03:00
Federico Maccaroni
99fb5463cf PM-3350 iOS projs disable linking and set Newstandkit as weak framework 2023-11-24 17:47:12 -03:00
Federico Maccaroni
c5d941e1df PM-3350 added linkskip for iOS csprojs 2023-11-24 15:13:45 -03:00
Federico Maccaroni
3edfef6169 PM-3350 build.yml disable trimming on publish so it's faster 2023-11-24 13:59:09 -03:00
Federico Maccaroni
1c8742511a PM-3350 Added Document.Build.props to disable trimming on publish 2023-11-24 12:50:17 -03:00
Federico Maccaroni
8e424d6c05 PM-3350 build.yml changed image back to be macos-13 to see if the build is faster 2023-11-24 11:17:45 -03:00
Federico Maccaroni
390c303b90 PM-3350 build.yml try to fix ILLINK warnings and changed image to be macos-13-arm64 to see if the build is faster 2023-11-24 10:50:36 -03:00
Federico Maccaroni
443f7282b8 PM-3350 build.yml Upgraded iOS build to run on macos-13 image which has XCode 15, and set the XCode 15 version as currently the default one is 14.x 2023-11-23 18:05:58 -03:00
Federico Maccaroni
50109ee70b PM-3350 build.yml changed nuget restore for dotnet restore on iOS build to fix issue on restoring due to msbuild 2023-11-23 17:38:23 -03:00
Federico Maccaroni
9ffdfd51cc PM-3350 build.yml updated iOS build and ignore Android build to try the CI faster 2023-11-23 17:20:17 -03:00
Federico Maccaroni
04e409f3c6 PM-3349 build.yml add Android "prod" variant 2023-11-23 16:32:10 -03:00
Federico Maccaroni
6c143bad57 PM-3349 build.yml updated env helpers variables and set specific csproj to build on Android so not to build iOS extensions 2023-11-23 15:39:16 -03:00
Federico Maccaroni
286e18059a PM-3349 PM-3350 build.cake updated paths 2023-11-23 14:08:14 -03:00
Federico Maccaroni
553bf9ed0a PM-3349 build.yml commented verify format and just set qa as variant on MAUI Android for faster checks on CI 2023-11-23 13:08:18 -03:00
Federico Maccaroni
ddb27b52d3 PM-3349 build.yml update paths for MAUI Android 2023-11-23 12:49:29 -03:00
Federico Maccaroni
6c504aa710 PM-3349 Started to configure build.yml for MAUI Android 2023-11-23 12:18:31 -03:00
Dinis Vieira
62254aef8d PM-3349 PM-3350 Fixed issue where creating an account with weak/exposed password would get stuck after the Captcha (if a captcha is shown)
Changed App.xaml.cs NavigateImpl to be private
2023-11-21 22:39:44 +00:00
Dinis Vieira
06a0195a6d PM-3349 Added workaround for Android to avoid issues with setting MainPage when app is in background. They are now kept on a Queue to be executed after the app has resumed.
Updated some things on App.xaml.cs to the new MAUI style
2023-11-21 21:26:14 +00:00
Dinis Vieira
df2b0b21d5 PM-3350 Added workaround for iOS Avatar icon again. 2023-11-20 22:07:40 +00:00
Federico Maccaroni
e6b1bab860 PM-3350 Updated AppCenter package to latest version 5.0.3 and updated some things into MAUI style 2023-11-20 17:29:16 -03:00
Federico Maccaroni
ce41eb0578 PM-3350 Fixed account toolbar item and TitleView on SendAddOnlyPage, also removed comments on AvatarImageSource given the workaround is not needed anymore to draw the image successfully. 2023-11-20 16:09:23 -03:00
Federico Maccaroni
1a0b52d644 PM-3350 Fixed/Updated all MAUI-Migration TODOs 2023-11-20 13:10:03 -03:00
Federico Maccaroni
16ada4993c Merge branch 'feature/maui-migration' of https://github.com/bitwarden/mobile into feature/maui-migration
# Conflicts:
#	src/Core/Pages/Settings/OtherSettingsPageViewModel.cs
2023-11-20 10:49:42 -03:00
Federico Maccaroni
3795f3aa17 PM-3350 Added watchOS app to main project and fixed some csproj conditions for runtime identifiers on iOS. 2023-11-20 10:44:56 -03:00
Dinis Vieira
eceb506c77 Merge branch 'master' into feature/maui-migration
Fixed conflicts

# Conflicts:
#	src/App/Resources/AppResources.cs.Designer.cs
#	src/App/Resources/AppResources.da.Designer.cs
#	src/App/Resources/AppResources.de.Designer.cs
#	src/App/Resources/AppResources.es.Designer.cs
#	src/App/Resources/AppResources.fi.Designer.cs
#	src/App/Resources/AppResources.fr.Designer.cs
#	src/App/Resources/AppResources.hi.Designer.cs
#	src/App/Resources/AppResources.hr.Designer.cs
#	src/App/Resources/AppResources.hu.Designer.cs
#	src/App/Resources/AppResources.id.Designer.cs
#	src/App/Resources/AppResources.it.Designer.cs
#	src/App/Resources/AppResources.ja.Designer.cs
#	src/App/Resources/AppResources.nl.Designer.cs
#	src/App/Resources/AppResources.pl.Designer.cs
#	src/App/Resources/AppResources.pt-BR.Designer.cs
#	src/App/Resources/AppResources.pt-PT.Designer.cs
#	src/App/Resources/AppResources.ro.Designer.cs
#	src/App/Resources/AppResources.ru.Designer.cs
#	src/App/Resources/AppResources.sk.Designer.cs
#	src/App/Resources/AppResources.sv.Designer.cs
#	src/App/Resources/AppResources.th.Designer.cs
#	src/App/Resources/AppResources.tr.Designer.cs
#	src/App/Resources/AppResources.uk.Designer.cs
#	src/App/Resources/AppResources.vi.Designer.cs
#	src/App/Resources/AppResources.zh-Hans.Designer.cs
#	src/App/Resources/AppResources.zh-Hant.Designer.cs
#	src/Core/Controls/Settings/BaseSettingControlView.cs
#	src/Core/Pages/Accounts/EnvironmentPageViewModel.cs
#	src/Core/Pages/Accounts/HomePage.xaml.cs
#	src/Core/Pages/Accounts/HomePageViewModel.cs
#	src/Core/Pages/Accounts/SetPasswordPageViewModel.cs
#	src/Core/Pages/Settings/SecuritySettingsPageViewModel.cs
#	src/Core/Pages/TabsPage.cs
#	src/Core/Services/StateMigrationService.cs
#	src/Core/Utilities/BoolToColorConverter.cs
2023-11-19 15:06:02 +00:00
Dinis Vieira
2c7870d660 PM-3349 PM-3350 Removed AsyncCommand "wrapper" and added AsyncRelayCommand directly in all ViewModels that were using the other one. 2023-11-16 22:31:01 +00:00
Dinis Vieira
f02b3415a3 PM-3350 Removed workaround for iOS issue with Avatar icon as it's now fixed in latest .Net8 release. 2023-11-14 23:24:10 +00:00
Federico Maccaroni
beda4e9ff8 PM-3350 Updated PCL Crypto to latest alpha version to fix "Dll not found NCrypt" issue 2023-11-14 18:43:23 -03:00
Federico Maccaroni
df4d89cd52 PM-3350 Fixed iOS Extensions navigation to several pages and improved avoiding duplicate calls to OnNavigatedTo 2023-11-14 13:43:59 -03:00
Federico Maccaroni
5f12bb9747 PM-3350 Fixed iOS Share extension lazy views loading and an issue with the avatar loading. Also discovered issue with TapGestureRecognizer not working on MAUI Embedding 2023-11-13 21:30:56 -03:00
Federico Maccaroni
5712639492 Merge branch 'feature/maui-migration' of https://github.com/bitwarden/mobile into feature/maui-migration 2023-11-13 14:44:24 -03:00
Federico Maccaroni
e0a3c301fb PM-3349 PM-3350 Changed SendViewCell and its binding to be directly against the ViewModel 2023-11-13 14:44:19 -03:00
Dinis Vieira
27306fe353 PM-3349 PM-3350 Added the partial MAUI Community Toolkit implementation for TouchEffect. This is a temporary solution until they finalize this and add it to their nuget package.
This allows implementing the LongPressCommand in AccountSwitchingOverlay and also have the "Ripple effect" animation when touching an item in Android
2023-11-13 09:59:54 +00:00
Dinis Vieira
a31f15559f PM-3350 Fix for colored html text on iOS 2023-11-11 15:05:51 +00:00
Dinis Vieira
0e75f3f5c8 PM-3349 Fix for HTML Label on Android. Color hex doesn't need to be cropped anymore. 2023-11-10 23:30:54 +00:00
Federico Maccaroni
363da063fa PM-3349 PM-3350 Changed AccountViewCell and its binding to be directly against the ViewModel 2023-11-10 17:30:08 -03:00
Federico Maccaroni
974a571455 PM-3349 PM-3350 Changed binding set for CipherViewCell so it updates accordingly 2023-11-10 14:41:41 -03:00
Dinis Vieira
e0c721098c PM-3349 PM-3350 Migrated remaining AutomationProperties to SemanticProperties.
All 'IsInAccessibleTree="True"' were deleted.
'IsInAccessibleTree="False"' were kept and stayed in code.
2023-11-09 23:01:04 +00:00
Federico Maccaroni
a86f6e3034 PM-3350 Added configurations for Release mode (no FDroid yet) 2023-11-09 17:15:02 -03:00
Federico Maccaroni
fe17288b99 Merge branch 'feature/maui-migration' of https://github.com/bitwarden/mobile into feature/maui-migration 2023-11-09 16:16:26 -03:00
Federico Maccaroni
7324da9d47 PM-3350 Fixed iOS extensions (iOS.Extension and iOS.ShareExtension) to load and commented argon2id from debug configuration until we have the .a compiled again with the new platform/arch 2023-11-09 16:16:17 -03:00
Dinis Vieira
69aa6fc044 PM-3349 PM-3350 Started using OnNavigatedTo/From instead of On(Dis)Appearing for LoginPage and LoginSSOPage to avoid the "Modal loading" issues in iOS
Also had to add IsInitialized logic to these pages because OnNavigatedTo can be called twice in some scenario.
Some minor migrations of Device to DeviceInfo was also done
2023-11-09 15:09:37 +00:00
Dinis Vieira
e840dc2e30 Merge branch 'master' into feature/maui-migration
Fixed conflicts and added null check on ForwardEmailDomainName

# Conflicts:
#	src/Core/Pages/Vault/CipherAddEditPage.xaml
#	src/Core/Pages/Vault/CipherDetailsPage.xaml
#	src/iOS.Core/Renderers/CollectionView/ExtendedGroupableItemsViewController.cs
2023-11-05 23:59:30 +00:00
Dinis Vieira
eb25ee5d1b PM-3349 Fix for Android buttons having all letters in Caps 2023-11-04 18:39:08 +00:00
Dinis Vieira
840f24dbe5 PM-3349 Fix for TabGestureRecognizer not working inside the StackLayout area of IconLabelButton 2023-11-04 18:08:44 +00:00
Dinis Vieira
c6309173ba PM-3349 PM-3350 Migrated IconLabelButton Frames to Borders to fix issue with TapGestureRecognizer in Android
Also fixed some minor "styles" for normal Button and IconLabelButton (both Android and iOS)
2023-11-04 17:48:59 +00:00
Dinis Vieira
946c465f0c PM-3349 Added Handler that enables the ExtendedDatePicker to get IsFocused events in Android. This is a workaround for fixing the current bug where it's not possible to select the "current day" in the expiration date of a Send.
Fix for TimePicker not displaying default Time Value
Updated some "Device" code to the new MAUI "DeviceInfo"
2023-11-02 02:32:12 +00:00
Dinis Vieira
e90409d842 PM-3350 Added Scrollview on HomePage so that the "Create account" button can be accessed in smaller devices like iPhone SE. 2023-10-29 21:34:33 +00:00
Dinis Vieira
484b5a5160 PM-3349 PM-3350 Minor change to HomePage to set fixed Image height otherwise it takes more space than it did in the old Xamarin Forms app.
Added HIdeSoftInputOnTapped on several pages (the ones with Entry controls) to allow hiding the keyboard when tapping "outside" of it. (just like we did in Xamarin Forms app)
2023-10-28 19:02:54 +01:00
Dinis Vieira
2688209752 PM-3350 Removed duplicate reference to LaunchScreen.storyboard 2023-10-27 17:19:20 +01:00
Dinis Vieira
53e0e55915 PM-3350 Quick workaround to allow 2nd factor auth to not get stuck in iOS in modals.
Updated some older "Device" code to the newer MAUI code.
2023-10-27 15:36:47 +01:00
Dinis Vieira
ca57948d9f PM-3350 Removed MAUI Splash Screen. Fixed iOS Privacy Screen logo (hardcoded image to avoid it getting cropped) 2023-10-27 11:41:21 +01:00
Dinis Vieira
aaf082faba PM-3349 Fixed white tint color not appearing on images added as MAU IImage SVG
PM-3349 PM-3350 Fix for Avatar text not adjusting to white/black color correctly
2023-10-25 22:20:01 +01:00
Dinis Vieira
e7aeb08cae PM-3350 Checked some [MAUI-Migration] and changed as needed.
TimePickerHandlerMappings: Remove old code for forcing the Wheel. After testing without it wheel picker is still used so this code shouldn't be needed anymore.
AppDelegate.ContinueUserActivity: Uncommented and changed the iOS ContinueUserActivity. It needs to call Platform.ContinueUserActivity according with Xamarin Essentials migration docs.
2023-10-24 23:37:18 +01:00
Dinis Vieira
f177968958 Checked some [MAUI-Migration] and deleted when it's working as intended.
SearchBarHandlerMapping: IME options working as intended
SliderHandlerMappings: The MAUI "replacement" for Color.Default seems to be White so the old use case doesn't seem to be needed anymore.
2023-10-24 22:25:05 +01:00
Dinis Vieira
f1d59210f9 PM-3349 PRM-3350 Replaced XZing with Camera.MAUI for QRCodes 2023-10-23 15:17:14 +01:00
Dinis Vieira
62213c0aaf PM-3350 Added some missing images in iOS 2023-10-20 13:33:39 +01:00
Dinis Vieira
8be8abb8fe PM-3350 Migrated some Device to DeviceInfo and added temporary workaround with some comments to be able to see the Generated Password on iOS 2023-10-20 00:04:19 +01:00
Dinis Vieira
174acbc558 PM-3349
Added Argon libraries for Android
minor change to gitignore so that the Argon x86 lib is not ignored on the Android platform
2023-10-18 15:41:20 +01:00
Dinis Vieira
4bcc7c0d71 Enabled argon2Id for iOS 2023-10-18 12:20:41 +01:00
Dinis Vieira
14b2960f30 PM-3350 Removed ButtonHandlerMappings and some other code related with fonts as MAUI is taking care of Accessibility and no custom code should be needed
Migrated SelectableLabelRenderer to Handler
Cleaned LabelHandlerMappings and added logic to migrate the CustomLabelRenderer
2023-10-18 01:21:19 +01:00
Dinis Vieira
455c3a257c PM-3350 Migrated the CustomViewCellRenderer for iOS 2023-10-17 22:23:04 +01:00
Dinis Vieira
8c623a2067 PM-3349 ToolbarHandler created for setting text on Android go back buttons. 2023-10-16 20:45:58 +01:00
Dinis Vieira
3cdf1c2f0e PM-3349 Replaced the FabShadowEffect with the new MAUI Shadow to fix the buggy shadows on the Android Fab Button. 2023-10-16 00:47:52 +01:00
Dinis Vieira
ce9503fa0c PM-3349 PM-3350
Added (migrated) CustomNavigationHandler (which should partially fix the AvatarIcon in the NavBar in iOS)
Added (migrated) CustomContentPageHandler (which should mostly place the AvatarIcon in the navBar in the correct place for iOS)
Added Task.Delay (workaround) to allow the Avatar to load in iOS on the LoginPage
Added workaround for iOS bug with the toolbar size (more info in comment in AvatarImageSource.cs)
Went through the AccountViewCell MAUI-Migration comments. (and deleted/added more comments as needed)
Migrated some Device calls to DeviceInfo and MainThread
Added (migrated) CustomTabbedHandler (for managing the iOS TabBar)
2023-10-15 22:06:26 +01:00
Dinis Vieira
2e4da1b87d hardcoded AccountViewCell Avatar image to 40x40 to avoid current iOS/Android bugs where they fill much larger space. 2023-10-13 18:49:30 +01:00
Dinis Vieira
d63a219272 PM-3349 Implemented HybridWebViewHandler for iOS 2023-10-07 23:44:24 +01:00
Dinis Vieira
c92cd90a97 PM-3349 Implemented HybridWebViewHandler for Android which enables 2nd factor auth flows
Ensured CustomTabbedPageHandler had it's DisconnectHandler called
Some minor code upgrades of older obsolete Xamarin Forms code.
2023-10-07 17:25:29 +01:00
Dinis Vieira
1dcd3a3daa PM-3349 Changed UseMauiApp init so that Android Handlers still get added 2023-10-07 16:56:08 +01:00
Federico Maccaroni
efb8763d3c Merge branch 'feature/maui-migration' of https://github.com/bitwarden/mobile into feature/maui-migration 2023-10-04 12:45:08 -03:00
Federico Maccaroni
90649d1c8b PM-3350 MAUI Migration Fix iOS Autofill extension 2023-10-04 12:35:43 -03:00
Dinis Vieira
828055791f PM-3349 Removed Deploy from iOS.Autofill to allow running Android
Changed MainApplication SpecialFolder.Personal to SpecialFolder.LocalApplicationData
2023-10-02 21:15:33 +01:00
Dinis Vieira
87eebda55f Changes to solution to hopefully fix Config Mappings 2023-10-02 16:40:31 +01:00
Dinis Vieira
7542d1ae1c fix conflicts 2023-10-02 16:08:09 +01:00
Federico Maccaroni
990de4ea4e PM-3349 PM-3350 MAUI Migration Start iOS extensions 2023-10-02 12:05:57 -03:00
Dinis Vieira
0dbc23f734 PM-3349 PM-3350 Add null checks on CipherDetailsPageVM to avoid crash opening Secure Notes. 2023-10-01 23:15:55 +01:00
Dinis Vieira
9f6c8601d3 TabBarEffect removed and it's behavior is now taken care of by CustomTabbedPageHandler 2023-10-01 22:32:37 +01:00
Dinis Vieira
8b7f9b9fb3 PM-3349: Android
Added CustomTabbedPageHandler for Android to handle the tab "reselection" for PopToRoot.
Commented support for Windows in App.csproj
Disabled Interpreter on Android to avoid very slow app in Debug (during Login for example)
Added some null checks that were causing crashes (on GeneratorPageVM and PickerVM)
Minor TabsPage cleanup
2023-10-01 15:35:04 +01:00
Federico Maccaroni
d17789d5ee PM-3349 PM-3350 MAUI Migration fix nullable bindings and fallbacks 2023-09-29 12:27:12 -03:00
Federico Maccaroni
b8f0747dd4 PM-3349 PM-3350 MAUI Migration fix nullable exception bindings and AsyncCommand canExecute null exception 2023-09-29 12:12:01 -03:00
Federico Maccaroni
8ef9443b1e PM-3349 PM-3350 MAUI Migration Initial 2023-09-29 11:02:19 -03:00
92 changed files with 4796 additions and 172 deletions

1
.gitignore vendored
View File

@@ -148,6 +148,7 @@ publish/
# NuGet Packages
*.nupkg
!**/Xamarin.AndroidX.Credentials.1.0.0.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.

View File

@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<MauiVersion>8.0.4-nightly.*</MauiVersion>
<MauiVersion>8.0.7-nightly.*</MauiVersion>
<ReleaseCodesignProvision>Automatic:AppStore</ReleaseCodesignProvision>
<ReleaseCodesignKey>iPhone Distribution</ReleaseCodesignKey>
<IncludeBitwardeniOSExtensions>True</IncludeBitwardeniOSExtensions>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>Xamarin.AndroidX.Credentials</name>
</assembly>
<members>
</members>
</doc>

View File

@@ -2,5 +2,6 @@
<configuration>
<packageSources>
<add key="MAUI Nightly builds" value="https://pkgs.dev.azure.com/xamarin/public/_packaging/maui-nightly/nuget/v3/index.json" />
<add key="Local AndroidX Credentials" value="lib/android/Xamarin.AndroidX.Credentials" />
</packageSources>
</configuration>

View File

@@ -121,6 +121,7 @@
<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">
<PackageReference Include="Xamarin.AndroidX.AutoFill" Version="1.1.0.18" />
<PackageReference Include="Xamarin.AndroidX.Activity.Ktx" Version="1.7.2.1" />
<PackageReference Include="Xamarin.AndroidX.Credentials" Version="1.0.0" />
</ItemGroup>
<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android' AND !$(DefineConstants.Contains(FDROID))">
<PackageReference Include="Xamarin.GooglePlayServices.SafetyNet" Version="118.0.1.5" />

View File

@@ -0,0 +1,9 @@
namespace Bit.Droid.Autofill
{
public class CredentialProviderConstants
{
public const string CredentialProviderCipherId = "credentialProviderCipherId";
public const string CredentialDataIntentExtra = "CREDENTIAL_DATA";
public const string CredentialIdIntentExtra = "credId";
}
}

View File

@@ -0,0 +1,65 @@
using System.Threading.Tasks;
using Android.App;
using Android.Content.PM;
using Android.OS;
using AndroidX.Credentials.Provider;
using AndroidX.Credentials.WebAuthn;
using Bit.Core.Abstractions;
using Bit.Core.Utilities;
using Bit.App.Droid.Utilities;
namespace Bit.Droid.Autofill
{
[Activity(
NoHistory = true,
LaunchMode = LaunchMode.SingleTop)]
public class CredentialProviderSelectionActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
Intent?.Validate();
base.OnCreate(bundle);
var cipherId = Intent?.GetStringExtra(CredentialProviderConstants.CredentialProviderCipherId);
if (string.IsNullOrEmpty(cipherId))
{
SetResult(Result.Canceled);
Finish();
return;
}
GetCipherAndPerformPasskeyAuthAsync(cipherId).FireAndForget();
}
private async Task GetCipherAndPerformPasskeyAuthAsync(string cipherId)
{
// TODO this is a work in progress
// https://developer.android.com/training/sign-in/credential-provider#passkeys-implement
var getRequest = PendingIntentHandler.RetrieveProviderGetCredentialRequest(Intent);
// var publicKeyRequest = getRequest?.CredentialOptions as PublicKeyCredentialRequestOptions;
var requestInfo = Intent.GetBundleExtra(CredentialProviderConstants.CredentialDataIntentExtra);
var credIdEnc = requestInfo?.GetString(CredentialProviderConstants.CredentialIdIntentExtra);
var cipherService = ServiceContainer.Resolve<ICipherService>();
var cipher = await cipherService.GetAsync(cipherId);
var decCipher = await cipher.DecryptAsync();
var passkey = decCipher.Login.Fido2Credentials.Find(f => f.CredentialId == credIdEnc);
var credId = Convert.FromBase64String(credIdEnc);
// var privateKey = Convert.FromBase64String(passkey.PrivateKey);
// var uid = Convert.FromBase64String(passkey.uid);
var origin = getRequest?.CallingAppInfo.Origin;
var packageName = getRequest?.CallingAppInfo.PackageName;
// --- continue WIP here (save TOTP copy as last step) ---
// Copy TOTP if needed
var autofillHandler = ServiceContainer.Resolve<IAutofillHandler>();
autofillHandler.Autofill(decCipher);
}
}
}

View File

@@ -0,0 +1,147 @@
using Android;
using Android.App;
using Android.Content;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using AndroidX.Credentials.Provider;
using Bit.Core.Abstractions;
using Bit.Core.Utilities;
using AndroidX.Credentials.Exceptions;
using AndroidX.Credentials.WebAuthn;
using Bit.Core.Models.View;
using Resource = Microsoft.Maui.Resource;
namespace Bit.Droid.Autofill
{
[Service(Permission = Manifest.Permission.BindCredentialProviderService, Label = "Bitwarden", Exported = true)]
[IntentFilter(new string[] { "android.service.credentials.CredentialProviderService" })]
[MetaData("android.credentials.provider", Resource = "@xml/provider")]
[Register("com.x8bit.bitwarden.Autofill.CredentialProviderService")]
public class CredentialProviderService : AndroidX.Credentials.Provider.CredentialProviderService
{
private const string GetPasskeyIntentAction = "PACKAGE_NAME.GET_PASSKEY";
private const int UniqueRequestCode = 94556023;
private ICipherService _cipherService;
private IUserVerificationService _userVerificationService;
private IVaultTimeoutService _vaultTimeoutService;
private LazyResolve<ILogger> _logger = new LazyResolve<ILogger>("logger");
public override async void OnBeginCreateCredentialRequest(BeginCreateCredentialRequest request,
CancellationSignal cancellationSignal, IOutcomeReceiver callback) => throw new NotImplementedException();
public override async void OnBeginGetCredentialRequest(BeginGetCredentialRequest request,
CancellationSignal cancellationSignal, IOutcomeReceiver callback)
{
try
{
_vaultTimeoutService ??= ServiceContainer.Resolve<IVaultTimeoutService>();
await _vaultTimeoutService.CheckVaultTimeoutAsync();
var locked = await _vaultTimeoutService.IsLockedAsync();
if (!locked)
{
var response = await ProcessGetCredentialsRequestAsync(request);
callback.OnResult(response);
}
// TODO handle auth/unlock account flow
}
catch (GetCredentialException e)
{
_logger.Value.Exception(e);
callback.OnError(e.ErrorMessage ?? "Error getting credentials");
}
catch (Exception e)
{
_logger.Value.Exception(e);
throw;
}
}
private async Task<BeginGetCredentialResponse> ProcessGetCredentialsRequestAsync(
BeginGetCredentialRequest request)
{
IList<CredentialEntry> credentialEntries = null;
foreach (var option in request.BeginGetCredentialOptions)
{
var credentialOption = option as BeginGetPublicKeyCredentialOption;
if (credentialOption != null)
{
credentialEntries ??= new List<CredentialEntry>();
((List<CredentialEntry>)credentialEntries).AddRange(
await PopulatePasskeyDataAsync(request.CallingAppInfo, credentialOption));
}
}
if (credentialEntries == null)
{
return new BeginGetCredentialResponse();
}
return new BeginGetCredentialResponse.Builder()
.SetCredentialEntries(credentialEntries)
.Build();
}
private async Task<List<CredentialEntry>> PopulatePasskeyDataAsync(CallingAppInfo callingAppInfo,
BeginGetPublicKeyCredentialOption option)
{
var packageName = callingAppInfo.PackageName;
var origin = callingAppInfo.Origin;
var signingInfo = callingAppInfo.SigningInfo;
var request = new PublicKeyCredentialRequestOptions(option.RequestJson);
var passkeyEntries = new List<CredentialEntry>();
_cipherService ??= ServiceContainer.Resolve<ICipherService>();
var ciphers = await _cipherService.GetAllDecryptedForUrlAsync(origin);
if (ciphers == null)
{
return passkeyEntries;
}
var passkeyCiphers = ciphers.Where(cipher => cipher.HasFido2Credential).ToList();
if (!passkeyCiphers.Any())
{
return passkeyEntries;
}
foreach (var cipher in passkeyCiphers)
{
var passkeyEntry = GetPasskey(cipher, option);
passkeyEntries.Add(passkeyEntry);
}
return passkeyEntries;
}
private PublicKeyCredentialEntry GetPasskey(CipherView cipher, BeginGetPublicKeyCredentialOption option)
{
var credDataBundle = new Bundle();
credDataBundle.PutString(CredentialProviderConstants.CredentialIdIntentExtra,
cipher.Login.MainFido2Credential.CredentialId);
var intent = new Intent(ApplicationContext, typeof(CredentialProviderSelectionActivity))
.SetAction(GetPasskeyIntentAction).SetPackage(Constants.PACKAGE_NAME);
intent.PutExtra(CredentialProviderConstants.CredentialDataIntentExtra, credDataBundle);
intent.PutExtra(CredentialProviderConstants.CredentialProviderCipherId, cipher.Id);
var pendingIntent = PendingIntent.GetActivity(ApplicationContext, UniqueRequestCode, intent,
PendingIntentFlags.Mutable | PendingIntentFlags.UpdateCurrent);
return new PublicKeyCredentialEntry.Builder(
ApplicationContext,
cipher.Login.Username ?? "No username",
pendingIntent,
option)
.SetDisplayName(cipher.Name)
.SetIcon(Icon.CreateWithResource(ApplicationContext, Resource.Drawable.icon))
.Build();
}
public override void OnClearCredentialStateRequest(ProviderClearCredentialStateRequest request,
CancellationSignal cancellationSignal, IOutcomeReceiver callback) => throw new NotImplementedException();
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<credential-provider xmlns:android="http://schemas.android.com/apk/res/android">
<capabilities>
<capability name="androidx.credentials.TYPE_PUBLIC_KEY_CREDENTIAL" />
</capabilities>
</credential-provider>

View File

@@ -37,6 +37,23 @@ namespace Bit.Droid.Services
_eventService = eventService;
}
public bool CredentialProviderServiceEnabled()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.UpsideDownCake)
{
return false;
}
try
{
// TODO - find a way to programmatically check if the credential provider service is enabled
return false;
}
catch
{
return false;
}
}
public bool AutofillServiceEnabled()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
@@ -163,7 +180,14 @@ namespace Bit.Droid.Services
return Accessibility.AccessibilityHelpers.OverlayPermitted();
}
public void DisableCredentialProviderService()
{
try
{
// TODO - find a way to programmatically disable the provider service, or take the user to the settings page where they can do it
}
catch { }
}
public void DisableAutofillService()
{

View File

@@ -11,6 +11,7 @@ using Android.Text.Method;
using Android.Views;
using Android.Views.InputMethods;
using Android.Widget;
using AndroidX.Credentials;
using Bit.App.Abstractions;
using Bit.Core.Resources.Localization;
using Bit.App.Utilities;
@@ -490,6 +491,27 @@ namespace Bit.Droid.Services
}
}
public void OpenCredentialProviderSettings()
{
var activity = (MainActivity)Microsoft.Maui.ApplicationModel.Platform.CurrentActivity;
try
{
var pendingIntent = CredentialManager.Create(activity).CreateSettingsPendingIntent();
pendingIntent.Send();
}
catch (ActivityNotFoundException)
{
var alertBuilder = new AlertDialog.Builder(activity);
alertBuilder.SetMessage(AppResources.BitwardenCredentialProviderGoToSettings);
alertBuilder.SetCancelable(true);
alertBuilder.SetPositiveButton(AppResources.Ok, (sender, args) =>
{
(sender as AlertDialog)?.Cancel();
});
alertBuilder.Create().Show();
}
}
public void OpenAccessibilitySettings()
{
try
@@ -548,6 +570,8 @@ namespace Bit.Droid.Services
return true;
}
public bool SupportsCredentialProviderService() => Build.VERSION.SdkInt >= BuildVersionCodes.UpsideDownCake;
public bool SupportsAutofillServices() => Build.VERSION.SdkInt >= BuildVersionCodes.O;
public bool SupportsInlineAutofill() => Build.VERSION.SdkInt >= BuildVersionCodes.R;

View File

@@ -88,7 +88,7 @@ namespace Bit.iOS
Core.Constants.AutofillNeedsIdentityReplacementKey);
if (needsAutofillReplacement.GetValueOrDefault())
{
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
}
else if (message.Command == "showAppExtension")
@@ -102,7 +102,7 @@ namespace Bit.iOS
var success = value as bool?;
if (success.GetValueOrDefault() && _deviceActionService.SystemMajorVersion() >= 12)
{
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
}
}
@@ -114,22 +114,21 @@ namespace Bit.iOS
return;
}
if (await ASHelpers.IdentitiesCanIncremental())
if (await ASHelpers.IdentitiesSupportIncrementalAsync())
{
var cipherId = message.Data as string;
if (message.Command == "addedCipher" && !string.IsNullOrWhiteSpace(cipherId))
{
var identity = await ASHelpers.GetCipherIdentityAsync(cipherId);
var identity = await ASHelpers.GetCipherPasswordIdentityAsync(cipherId);
if (identity == null)
{
return;
}
await ASCredentialIdentityStore.SharedStore?.SaveCredentialIdentitiesAsync(
new ASPasswordCredentialIdentity[] { identity });
await ASCredentialIdentityStoreExtensions.SaveCredentialIdentitiesAsync(identity);
return;
}
}
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
else if (message.Command == "deletedCipher" || message.Command == "softDeletedCipher")
{
@@ -138,28 +137,27 @@ namespace Bit.iOS
return;
}
if (await ASHelpers.IdentitiesCanIncremental())
if (await ASHelpers.IdentitiesSupportIncrementalAsync())
{
var identity = ASHelpers.ToCredentialIdentity(
var identity = ASHelpers.ToPasswordCredentialIdentity(
message.Data as Bit.Core.Models.View.CipherView);
if (identity == null)
{
return;
}
await ASCredentialIdentityStore.SharedStore?.RemoveCredentialIdentitiesAsync(
new ASPasswordCredentialIdentity[] { identity });
await ASCredentialIdentityStoreExtensions.RemoveCredentialIdentitiesAsync(identity);
return;
}
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
else if (message.Command == "logout" && UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
{
await ASCredentialIdentityStore.SharedStore?.RemoveAllCredentialIdentitiesAsync();
await ASCredentialIdentityStore.SharedStore.RemoveAllCredentialIdentitiesAsync();
}
else if ((message.Command == "softDeletedCipher" || message.Command == "restoredCipher")
&& UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
{
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
else if (message.Command == AppHelpers.VAULT_TIMEOUT_ACTION_CHANGED_MESSAGE_COMMAND)
{
@@ -168,12 +166,12 @@ namespace Bit.iOS
{
if (UIDevice.CurrentDevice.CheckSystemVersion(12, 0))
{
await ASCredentialIdentityStore.SharedStore?.RemoveAllCredentialIdentitiesAsync();
await ASCredentialIdentityStore.SharedStore.RemoveAllCredentialIdentitiesAsync();
}
}
else
{
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
}
}

View File

@@ -4,6 +4,7 @@ namespace Bit.Core.Abstractions
{
public interface IAutofillHandler
{
bool CredentialProviderServiceEnabled();
bool AutofillServicesEnabled();
bool SupportsAutofillService();
void Autofill(CipherView cipher);
@@ -11,6 +12,7 @@ namespace Bit.Core.Abstractions
bool AutofillAccessibilityServiceRunning();
bool AutofillAccessibilityOverlayPermitted();
bool AutofillServiceEnabled();
void DisableCredentialProviderService();
void DisableAutofillService();
}
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Threading.Tasks;
using Bit.Core.Enums;
using Bit.Core.Models.Domain;
namespace Bit.Core.Abstractions
{

View File

@@ -28,6 +28,7 @@ namespace Bit.App.Abstractions
bool SupportsNfc();
bool SupportsCamera();
bool SupportsFido2();
bool SupportsCredentialProviderService();
bool SupportsAutofillServices();
bool SupportsInlineAutofill();
bool SupportsDrawOver();
@@ -36,6 +37,7 @@ namespace Bit.App.Abstractions
void RateApp();
void OpenAccessibilitySettings();
void OpenAccessibilityOverlayPermissionSettings();
void OpenCredentialProviderSettings();
void OpenAutofillSettings();
long GetActiveTime();
void CloseMainApp();

View File

@@ -0,0 +1,9 @@
using Bit.Core.Utilities.Fido2;
namespace Bit.Core.Abstractions
{
public interface IFido2AuthenticationService
{
Task<Fido2AuthenticatorGetAssertionResult> GetAssertionAsync(Fido2AuthenticatorGetAssertionParams assertionParams);
}
}

View File

@@ -0,0 +1,13 @@
using Bit.Core.Utilities.Fido2;
namespace Bit.Core.Abstractions
{
public interface IFido2AuthenticatorService
{
void Init(IFido2UserInterface userInterface);
Task<Fido2AuthenticatorMakeCredentialResult> MakeCredentialAsync(Fido2AuthenticatorMakeCredentialParams makeCredentialParams);
Task<Fido2AuthenticatorGetAssertionResult> GetAssertionAsync(Fido2AuthenticatorGetAssertionParams assertionParams);
// TODO: Should this return a List? Or maybe IEnumerable?
Task<Fido2AuthenticatorDiscoverableCredentialMetadata[]> SilentCredentialDiscoveryAsync(string rpId);
}
}

View File

@@ -0,0 +1,35 @@
using Bit.Core.Utilities.Fido2;
namespace Bit.Core.Abstractions
{
/// <summary>
/// This class represents an abstraction of the WebAuthn Client as described by W3C:
/// https://www.w3.org/TR/webauthn-3/#webauthn-client
///
/// The WebAuthn Client is an intermediary entity typically implemented in the user agent
/// (in whole, or in part). Conceptually, it underlies the Web Authentication API and embodies
/// the implementation of the Web Authentication API's operations.
///
/// It is responsible for both marshalling the inputs for the underlying authenticator operations,
/// and for returning the results of the latter operations to the Web Authentication API's callers.
/// </summary>
public interface IFido2ClientService
{
/// <summary>
/// Allows WebAuthn Relying Party scripts to request the creation of a new public key credential source.
/// For more information please see: https://www.w3.org/TR/webauthn-3/#sctn-createCredential
/// </summary>
/// <param name="createCredentialParams">The parameters for the credential creation operation</param>
/// <returns>The new credential</returns>
Task<Fido2ClientCreateCredentialResult> CreateCredentialAsync(Fido2ClientCreateCredentialParams createCredentialParams);
/// <summary>
/// Allows WebAuthn Relying Party scripts to discover and use an existing public key credential, with the users consent.
/// Relying Party script can optionally specify some criteria to indicate what credential sources are acceptable to it.
/// For more information please see: https://www.w3.org/TR/webauthn-3/#sctn-getAssertion
/// </summary>
/// <param name="assertCredentialParams">The parameters for the credential assertion operation</param>
/// <returns>The asserted credential</returns>
Task<Fido2ClientAssertCredentialResult> AssertCredentialAsync(Fido2ClientAssertCredentialParams assertCredentialParams);
}
}

View File

@@ -0,0 +1,100 @@
using Bit.Core.Utilities.Fido2;
namespace Bit.Core.Abstractions
{
/// <summary>
/// Parameters used to ask the user to pick a credential from a list of existing credentials.
/// </summary>
public struct Fido2PickCredentialParams
{
/// <summary>
/// The IDs of the credentials that the user can pick from.
/// </summary>
public string[] CipherIds { get; set; }
/// <summary>
/// Whether or not the user must be verified before completing the operation.
/// </summary>
public bool UserVerification { get; set; }
}
/// <summary>
/// The result of asking the user to pick a credential from a list of existing credentials.
/// </summary>
public struct Fido2PickCredentialResult
{
/// <summary>
/// The ID of the cipher that contains the credentials the user picked.
/// </summary>
public string CipherId { get; set; }
/// <summary>
/// Whether or not the user was verified before completing the operation.
/// </summary>
public bool UserVerified { get; set; }
}
public struct Fido2ConfirmNewCredentialParams
{
///<summary>
/// The name of the credential.
///</summary>
public string CredentialName { get; set; }
///<summary>
/// The name of the user.
///</summary>
public string UserName { get; set; }
/// <summary>
/// Whether or not the user must be verified before completing the operation.
/// </summary>
public bool UserVerification { get; set; }
public string RpId { get; set; }
}
public struct Fido2ConfirmNewCredentialResult
{
/// <summary>
/// The name of the user.
/// </summary>
public string CipherId { get; set; }
/// <summary>
/// Whether or not the user was verified.
/// </summary>
public bool UserVerified { get; set; }
}
public interface IFido2UserInterface
{
/// <summary>
/// Ask the user to pick a credential from a list of existing credentials.
/// </summary>
/// <param name="pickCredentialParams">The parameters to use when asking the user to pick a credential.</param>
/// <returns>The ID of the cipher that contains the credentials the user picked.</returns>
Task<Fido2PickCredentialResult> PickCredentialAsync(Fido2PickCredentialParams pickCredentialParams);
/// <summary>
/// Inform the user that the operation was cancelled because their vault contains excluded credentials.
/// </summary>
/// <param name="existingCipherIds">The IDs of the excluded credentials.</param>
/// <returns>When user has confirmed the message</returns>
Task InformExcludedCredential(string[] existingCipherIds);
/// <summary>
/// Ask the user to confirm the creation of a new credential.
/// </summary>
/// <param name="confirmNewCredentialParams">The parameters to use when asking the user to confirm the creation of a new credential.</param>
/// <returns>The ID of the cipher where the new credential should be saved.</returns>
Task<Fido2ConfirmNewCredentialResult> ConfirmNewCredentialAsync(Fido2ConfirmNewCredentialParams confirmNewCredentialParams);
/// <summary>
/// Make sure that the vault is unlocked.
/// This should open a window and ask the user to login or unlock the vault if necessary.
/// </summary>
/// <returns>When vault has been unlocked.</returns>
Task EnsureUnlockedVaultAsync();
}
}

View File

@@ -34,6 +34,7 @@
<PackageReference Include="CsvHelper" Version="30.0.1" />
<PackageReference Include="LiteDB" Version="5.0.17" />
<PackageReference Include="PCLCrypto" Version="2.1.40-alpha" />
<PackageReference Include="System.Formats.Cbor" Version="8.0.0" />
<PackageReference Include="zxcvbn-core" Version="7.0.92" />
<PackageReference Include="MessagePack.MSBuild.Tasks" Version="2.5.124">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -52,6 +53,7 @@
<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">
<PackageReference Include="Xamarin.AndroidX.AutoFill" Version="1.1.0.18" />
<PackageReference Include="Xamarin.AndroidX.Activity.Ktx" Version="1.7.2.1" />
<PackageReference Include="Xamarin.AndroidX.Credentials" Version="1.0.0" />
</ItemGroup>
<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android' AND !$(DefineConstants.Contains(FDROID))">
<PackageReference Include="Xamarin.GooglePlayServices.SafetyNet" Version="118.0.1.5" />
@@ -75,6 +77,7 @@
<Folder Include="Utilities\Automation\" />
<Folder Include="Utilities\Prompts\" />
<Folder Include="Resources\Localization\" />
<Folder Include="Utilities\Fido2\" />
<Folder Include="Controls\Picker\" />
<Folder Include="Controls\Avatar\" />
</ItemGroup>
@@ -105,6 +108,7 @@
</MauiXaml>
</ItemGroup>
<ItemGroup>
<None Remove="Utilities\Fido2\" />
<None Remove="Controls\Picker\" />
<None Remove="Controls\Avatar\" />
</ItemGroup>

View File

@@ -1,5 +1,4 @@
using System;
using Bit.Core.Models.Domain;
using Bit.Core.Models.Domain;
namespace Bit.Core.Models.Api
{
@@ -21,6 +20,7 @@ namespace Bit.Core.Models.Api
RpName = fido2Key.RpName?.EncryptedString;
UserHandle = fido2Key.UserHandle?.EncryptedString;
UserName = fido2Key.UserName?.EncryptedString;
UserDisplayName = fido2Key.UserDisplayName?.EncryptedString;
Counter = fido2Key.Counter?.EncryptedString;
CreationDate = fido2Key.CreationDate;
}
@@ -35,6 +35,7 @@ namespace Bit.Core.Models.Api
public string RpName { get; set; }
public string UserHandle { get; set; }
public string UserName { get; set; }
public string UserDisplayName { get; set; }
public string Counter { get; set; }
public DateTime CreationDate { get; set; }
}

View File

@@ -19,6 +19,7 @@ namespace Bit.Core.Models.Data
RpName = apiData.RpName;
UserHandle = apiData.UserHandle;
UserName = apiData.UserName;
UserDisplayName = apiData.UserDisplayName;
Counter = apiData.Counter;
CreationDate = apiData.CreationDate;
}
@@ -33,6 +34,7 @@ namespace Bit.Core.Models.Data
public string RpName { get; set; }
public string UserHandle { get; set; }
public string UserName { get; set; }
public string UserDisplayName { get; set; }
public string Counter { get; set; }
public DateTime CreationDate { get; set; }
}

View File

@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bit.Core.Models.Data;
using Bit.Core.Models.Data;
using Bit.Core.Models.View;
namespace Bit.Core.Models.Domain
@@ -21,6 +17,7 @@ namespace Bit.Core.Models.Domain
nameof(RpName),
nameof(UserHandle),
nameof(UserName),
nameof(UserDisplayName),
nameof(Counter)
};
@@ -48,6 +45,7 @@ namespace Bit.Core.Models.Domain
public EncString RpName { get; set; }
public EncString UserHandle { get; set; }
public EncString UserName { get; set; }
public EncString UserDisplayName { get; set; }
public EncString Counter { get; set; }
public DateTime CreationDate { get; set; }

View File

@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Bit.Core.Enums;
using Bit.Core.Enums;
using Bit.Core.Models.Domain;
namespace Bit.Core.Models.View

View File

@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using Bit.Core.Enums;
using Bit.Core.Models.Domain;
using Bit.Core.Utilities;
namespace Bit.Core.Models.View
{
@@ -26,13 +26,40 @@ namespace Bit.Core.Models.View
public string RpName { get; set; }
public string UserHandle { get; set; }
public string UserName { get; set; }
public string UserDisplayName { get; set; }
public string Counter { get; set; }
public DateTime CreationDate { get; set; }
[JsonIgnore]
public int CounterValue {
get => int.TryParse(Counter, out var counter) ? counter : 0;
set => Counter = value.ToString();
}
[JsonIgnore]
public byte[] UserHandleValue {
get => UserHandle == null ? null : CoreHelpers.Base64UrlDecode(UserHandle);
set => UserHandle = value == null ? null : CoreHelpers.Base64UrlEncode(value);
}
[JsonIgnore]
public byte[] KeyBytes {
get => KeyValue == null ? null : CoreHelpers.Base64UrlDecode(KeyValue);
set => KeyValue = value == null ? null : CoreHelpers.Base64UrlEncode(value);
}
[JsonIgnore]
public bool DiscoverableValue {
get => bool.TryParse(Discoverable, out var discoverable) && discoverable;
set => Discoverable = value.ToString().ToLower(); // must be lowercase so it can be parsed in the current version of clients
}
[JsonIgnore]
public override string SubTitle => UserName;
public override List<KeyValuePair<string, LinkedIdType>> LinkedFieldOptions => new List<KeyValuePair<string, LinkedIdType>>();
public bool IsDiscoverable => !string.IsNullOrWhiteSpace(Discoverable);
[JsonIgnore]
public bool CanLaunch => !string.IsNullOrEmpty(RpId);
[JsonIgnore]
public string LaunchUri => $"https://{RpId}";
public bool IsUniqueAgainst(Fido2CredentialView fido2View) => fido2View?.RpId != RpId || fido2View?.UserName != UserName;

View File

@@ -21,6 +21,10 @@
<ScrollView>
<StackLayout Spacing="20">
<StackLayout StyleClass="box">
<StackLayout StyleClass="box-row-header">
<Label Text="MAUI APP"
StyleClass="box-header, box-header-platform" />
</StackLayout>
<StackLayout StyleClass="box-row-header">
<Label Text="{u:I18n SelfHostedEnvironment, Header=True}"
StyleClass="box-header, box-header-platform" />

View File

@@ -68,7 +68,8 @@ namespace Bit.App.Pages
{
get
{
var appInfo = string.Format("{0}: {1} ({2})",
// TODO: REMOVE WHEN MERGED INTO MAIN BRANCH
var appInfo = string.Format("MAUI {0}: {1} ({2})",
AppResources.Version,
_platformUtilsService.GetApplicationVersion(),
_deviceActionService.GetBuildNumber());

View File

@@ -19,6 +19,15 @@
Text="{u:I18n Autofill}"
StyleClass="settings-header" />
<controls:SwitchItemView
Title="{u:I18n CredentialProviderService}"
Subtitle="{u:I18n CredentialProviderServiceExplanationLong}"
IsVisible="{Binding SupportsCredentialProviderService}"
IsToggled="{Binding UseCredentialProviderService}"
AutomationId="CredentialProviderServiceSwitch"
StyleClass="settings-item-view"
HorizontalOptions="FillAndExpand" />
<controls:SwitchItemView
Title="{u:I18n AutofillServices}"
Subtitle="{u:I18n AutofillServicesExplanationLong}"

View File

@@ -6,12 +6,27 @@ namespace Bit.App.Pages
{
public partial class AutofillSettingsPageViewModel
{
private bool _useCredentialProviderService;
private bool _useAutofillServices;
private bool _useInlineAutofill;
private bool _useAccessibility;
private bool _useDrawOver;
private bool _askToAddLogin;
public bool SupportsCredentialProviderService => DeviceInfo.Platform == DevicePlatform.Android && _deviceActionService.SupportsCredentialProviderService();
public bool UseCredentialProviderService
{
get => _useCredentialProviderService;
set
{
if (SetProperty(ref _useCredentialProviderService, value))
{
((ICommand)ToggleUseCredentialProviderServiceCommand).Execute(null);
}
}
}
public bool SupportsAndroidAutofillServices => DeviceInfo.Platform == DevicePlatform.Android && _deviceActionService.SupportsAutofillServices();
public bool UseAutofillServices
@@ -84,6 +99,7 @@ namespace Bit.App.Pages
}
}
public AsyncRelayCommand ToggleUseCredentialProviderServiceCommand { get; private set; }
public AsyncRelayCommand ToggleUseAutofillServicesCommand { get; private set; }
public AsyncRelayCommand ToggleUseInlineAutofillCommand { get; private set; }
public AsyncRelayCommand ToggleUseAccessibilityCommand { get; private set; }
@@ -93,6 +109,7 @@ namespace Bit.App.Pages
private void InitAndroidCommands()
{
ToggleUseCredentialProviderServiceCommand = CreateDefaultAsyncRelayCommand(() => MainThread.InvokeOnMainThreadAsync(() => ToggleUseCredentialProviderService()), () => _inited, allowsMultipleExecutions: false);
ToggleUseAutofillServicesCommand = CreateDefaultAsyncRelayCommand(() => MainThread.InvokeOnMainThreadAsync(() => ToggleUseAutofillServices()), () => _inited, allowsMultipleExecutions: false);
ToggleUseInlineAutofillCommand = CreateDefaultAsyncRelayCommand(() => MainThread.InvokeOnMainThreadAsync(() => ToggleUseInlineAutofillEnabledAsync()), () => _inited, allowsMultipleExecutions: false);
ToggleUseAccessibilityCommand = CreateDefaultAsyncRelayCommand(ToggleUseAccessibilityAsync, () => _inited, allowsMultipleExecutions: false);
@@ -115,6 +132,9 @@ namespace Bit.App.Pages
private async Task UpdateAndroidAutofillSettingsAsync()
{
// TODO - uncomment once _autofillHandler.CredentialProviderServiceEnabled() returns a real value
// _useCredentialProviderService =
// SupportsCredentialProviderService && _autofillHandler.CredentialProviderServiceEnabled();
_useAutofillServices =
_autofillHandler.SupportsAutofillService() && _autofillHandler.AutofillServiceEnabled();
_useAccessibility = _autofillHandler.AutofillAccessibilityServiceRunning();
@@ -123,6 +143,7 @@ namespace Bit.App.Pages
await MainThread.InvokeOnMainThreadAsync(() =>
{
TriggerPropertyChanged(nameof(UseCredentialProviderService));
TriggerPropertyChanged(nameof(UseAutofillServices));
TriggerPropertyChanged(nameof(UseAccessibility));
TriggerPropertyChanged(nameof(UseDrawOver));
@@ -130,6 +151,18 @@ namespace Bit.App.Pages
});
}
private void ToggleUseCredentialProviderService()
{
if (UseCredentialProviderService)
{
_deviceActionService.OpenCredentialProviderSettings();
}
else
{
_autofillHandler.DisableCredentialProviderService();
}
}
private void ToggleUseAutofillServices()
{
if (UseAutofillServices)

View File

@@ -166,6 +166,15 @@ namespace Bit.Core.Resources.Localization {
}
}
/// <summary>
/// Looks up a localized string similar to Credential Provider service
/// </summary>
public static string CredentialProviderService {
get {
return ResourceManager.GetString("CredentialProviderService", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bitwarden needs attention - See &quot;Auto-fill Accessibility Service&quot; from Bitwarden settings.
/// </summary>
@@ -7685,6 +7694,15 @@ namespace Bit.Core.Resources.Localization {
}
}
/// <summary>
/// Looks up a localized string similar to We were unable to automatically open the Android credential provider settings menu for you. You can navigate to the credential provider settings menu manually from Android Settings &gt; System &gt; Passwords &amp; accounts &gt; Passwords, passkeys and data services.
/// </summary>
public static string BitwardenCredentialProviderGoToSettings {
get {
return ResourceManager.GetString("BitwardenCredentialProviderGoToSettings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Word separator.
/// </summary>
@@ -7703,6 +7721,15 @@ namespace Bit.Core.Resources.Localization {
}
}
/// <summary>
/// Looks up a localized string similar to The Android Credential Provider is used for managing passkeys for use with websites and other apps on your device.
/// </summary>
public static string CredentialProviderServiceExplanationLong {
get {
return ResourceManager.GetString("CredentialProviderServiceExplanationLong", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} hours and one minute.
/// </summary>

View File

@@ -1191,6 +1191,9 @@ Scanning will happen automatically.</value>
<data name="WindowsHello" xml:space="preserve">
<value>Windows Hello</value>
</data>
<data name="BitwardenCredentialProviderGoToSettings" xml:space="preserve">
<value>We were unable to automatically open the Android credential provider settings menu for you. You can navigate to the credential provider settings menu manually from Android Settings &gt; System &gt; Passwords &amp; accounts &gt; Passwords, passkeys and data services.</value>
</data>
<data name="BitwardenAutofillGoToSettings" xml:space="preserve">
<value>We were unable to automatically open the Android autofill settings menu for you. You can navigate to the autofill settings menu manually from Android Settings &gt; System &gt; Languages and input &gt; Advanced &gt; Autofill service.</value>
</data>
@@ -1816,6 +1819,9 @@ Scanning will happen automatically.</value>
<data name="AccessibilityDrawOverPermissionAlert" xml:space="preserve">
<value>Bitwarden needs attention - Turn on "Draw-Over" in "Auto-fill Services" from Bitwarden Settings</value>
</data>
<data name="CredentialProviderService" xml:space="preserve">
<value>Credential Provider service</value>
</data>
<data name="AutofillServices" xml:space="preserve">
<value>Auto-fill services</value>
</data>
@@ -2799,6 +2805,9 @@ Do you want to switch to this account?</value>
<data name="XHours" xml:space="preserve">
<value>{0} hours</value>
</data>
<data name="CredentialProviderServiceExplanationLong" xml:space="preserve">
<value>The Android Credential Provider is used for managing passkeys for use with websites and other apps on your device.</value>
</data>
<data name="AutofillServicesExplanationLong" xml:space="preserve">
<value>The Android Autofill Framework is used to assist in filling login information into other apps on your device.</value>
</data>

View File

@@ -0,0 +1,18 @@
using Bit.Core.Abstractions;
using Bit.Core.Utilities.Fido2;
namespace Bit.Core.Services
{
public class Fido2AuthenticationService : IFido2AuthenticationService
{
public Task<Fido2AuthenticatorGetAssertionResult> GetAssertionAsync(Fido2AuthenticatorGetAssertionParams assertionParams)
{
// TODO: IMPLEMENT this
return Task.FromResult(new Fido2AuthenticatorGetAssertionResult
{
AuthenticatorData = new byte[32],
Signature = new byte[8]
});
}
}
}

View File

@@ -0,0 +1,574 @@
using Bit.Core.Abstractions;
using Bit.Core.Models.View;
using Bit.Core.Enums;
using Bit.Core.Utilities.Fido2;
using Bit.Core.Utilities;
using System.Formats.Cbor;
using System.Security.Cryptography;
namespace Bit.Core.Services
{
public class Fido2AuthenticatorService: IFido2AuthenticatorService
{
// AAGUID: d548826e-79b4-db40-a3d8-11116f7e8349
public static readonly byte[] AAGUID = new byte[] { 0xd5, 0x48, 0x82, 0x6e, 0x79, 0xb4, 0xdb, 0x40, 0xa3, 0xd8, 0x11, 0x11, 0x6f, 0x7e, 0x83, 0x49 };
private readonly ICipherService _cipherService;
private readonly ISyncService _syncService;
private readonly ICryptoFunctionService _cryptoFunctionService;
private IFido2UserInterface _userInterface;
public Fido2AuthenticatorService(ICipherService cipherService, ISyncService syncService, ICryptoFunctionService cryptoFunctionService)
{
_cipherService = cipherService;
_syncService = syncService;
_cryptoFunctionService = cryptoFunctionService;
}
public void Init(IFido2UserInterface userInterface)
{
_userInterface = userInterface;
}
public async Task<Fido2AuthenticatorMakeCredentialResult> MakeCredentialAsync(Fido2AuthenticatorMakeCredentialParams makeCredentialParams)
{
if (makeCredentialParams.CredTypesAndPubKeyAlgs.All((p) => p.Alg != (int) Fido2AlgorithmIdentifier.ES256))
{
// var requestedAlgorithms = string.Join(", ", makeCredentialParams.CredTypesAndPubKeyAlgs.Select((p) => p.Algorithm).ToArray());
// _logService.Warning(
// $"[Fido2Authenticator] No compatible algorithms found, RP requested: {requestedAlgorithms}"
// );
ClipLogger.Log("[Fido2Authenticator] No compatible algorithms found, RP requested: {requestedAlgorithms}");
throw new NotSupportedError();
}
await _userInterface.EnsureUnlockedVaultAsync();
await _syncService.FullSyncAsync(false);
var existingCipherIds = await FindExcludedCredentialsAsync(
makeCredentialParams.ExcludeCredentialDescriptorList
);
if (existingCipherIds.Length > 0) {
// _logService.Info(
// "[Fido2Authenticator] Aborting due to excluded credential found in vault."
// );
ClipLogger.Log("[Fido2Authenticator] Aborting due to excluded credential found in vault");
await _userInterface.InformExcludedCredential(existingCipherIds);
throw new NotAllowedError();
}
var response = await _userInterface.ConfirmNewCredentialAsync(new Fido2ConfirmNewCredentialParams {
CredentialName = makeCredentialParams.RpEntity.Name,
UserName = makeCredentialParams.UserEntity.Name,
UserVerification = makeCredentialParams.RequireUserVerification,
RpId = makeCredentialParams.RpEntity.Id
});
var cipherId = response.CipherId;
var userVerified = response.UserVerified;
string credentialId;
if (cipherId == null) {
// _logService.Info(
// "[Fido2Authenticator] Aborting because user confirmation was not recieved."
// );
ClipLogger.Log("[Fido2Authenticator] Aborting because user confirmation was not recieved");
throw new NotAllowedError();
}
try {
var keyPair = GenerateKeyPair();
var fido2Credential = CreateCredentialView(makeCredentialParams, keyPair.privateKey);
ClipLogger.Log($"[Fido2Authenticator] IsDiscoverable {fido2Credential.Discoverable} - {fido2Credential.DiscoverableValue}");
var encrypted = await _cipherService.GetAsync(cipherId);
var cipher = await encrypted.DecryptAsync();
if (!userVerified && (makeCredentialParams.RequireUserVerification || cipher.Reprompt != CipherRepromptType.None)) {
// _logService.Info(
// "[Fido2Authenticator] Aborting because user verification was unsuccessful."
// );
ClipLogger.Log("[Fido2Authenticator] Aborting because user verification was unsuccessful");
throw new NotAllowedError();
}
cipher.Login.Fido2Credentials = new List<Fido2CredentialView> { fido2Credential };
var reencrypted = await _cipherService.EncryptAsync(cipher);
await _cipherService.SaveWithServerAsync(reencrypted);
credentialId = fido2Credential.CredentialId;
ClipLogger.Log($"[Fido2Authenticator] IsDiscoverable {cipher.Login.MainFido2Credential.Discoverable} - {cipher.Login.MainFido2Credential.DiscoverableValue}");
var authData = await GenerateAuthDataAsync(
rpId: makeCredentialParams.RpEntity.Id,
counter: fido2Credential.CounterValue,
userPresence: true,
userVerification: userVerified,
credentialId: credentialId.GuidToRawFormat(),
publicKey: keyPair.publicKey
);
return new Fido2AuthenticatorMakeCredentialResult
{
CredentialId = credentialId.GuidToRawFormat(),
AttestationObject = EncodeAttestationObject(authData),
AuthData = authData,
PublicKey = keyPair.publicKey.ExportDer(),
PublicKeyAlgorithm = (int) Fido2AlgorithmIdentifier.ES256,
};
} catch (NotAllowedError) {
throw;
} catch (Exception e) {
// _logService.Error(
// $"[Fido2Authenticator] Unknown error occured during attestation: {e.Message}"
// );
ClipLogger.Log("[Fido2Authenticator] Unknown error occured during attestation: {e.Message}");
throw new UnknownError();
}
}
public async Task<Fido2AuthenticatorGetAssertionResult> GetAssertionAsync(Fido2AuthenticatorGetAssertionParams assertionParams)
{
List<CipherView> cipherOptions;
await _userInterface.EnsureUnlockedVaultAsync();
await _syncService.FullSyncAsync(false);
if (assertionParams.AllowCredentialDescriptorList?.Length > 0) {
ClipLogger.Log("[Fido2Authenticator] Finding credentials with credential descriptor list");
cipherOptions = await FindCredentialsByIdAsync(
assertionParams.AllowCredentialDescriptorList,
assertionParams.RpId
);
} else
{
ClipLogger.Log("[Fido2Authenticator] Finding credentials with RP");
cipherOptions = await FindCredentialsByRpAsync(assertionParams.RpId);
}
if (cipherOptions.Count == 0) {
// _logService.Info(
// "[Fido2Authenticator] Aborting because no matching credentials were found in the vault."
// );
ClipLogger.Log("[Fido2Authenticator] Aborting because no matching credentials were found in the vault");
throw new NotAllowedError();
}
string selectedCipherId;
bool userVerified;
bool userPresence;
// TODO: We might want reconsider allowing user presence to be optional
if (assertionParams.AllowCredentialDescriptorList?.Length == 1 && assertionParams.RequireUserPresence == false)
{
ClipLogger.Log("[Fido2Authenticator] AllowCredentialDescriptorList + RequireUserPresence false");
selectedCipherId = cipherOptions[0].Id;
userVerified = false;
userPresence = false;
}
else
{
ClipLogger.Log("[Fido2Authenticator] PickCredentialAsync");
var response = await _userInterface.PickCredentialAsync(new Fido2PickCredentialParams {
CipherIds = cipherOptions.Select((cipher) => cipher.Id).ToArray(),
UserVerification = assertionParams.RequireUserVerification
});
selectedCipherId = response.CipherId;
userVerified = response.UserVerified;
userPresence = true;
}
var selectedCipher = cipherOptions.FirstOrDefault((c) => c.Id == selectedCipherId);
if (selectedCipher == null) {
// _logService.Info(
// "[Fido2Authenticator] Aborting because the selected credential could not be found."
// );
ClipLogger.Log("[Fido2Authenticator] Aborting because the selected credential could not be found");
throw new NotAllowedError();
}
if (!userPresence && assertionParams.RequireUserPresence) {
// _logService.Info(
// "[Fido2Authenticator] Aborting because user presence was required but not detected."
// );
ClipLogger.Log("[Fido2Authenticator] Aborting because user presence was required but not detected");
throw new NotAllowedError();
}
// TODO: Remove this hardcoding
userVerified = true;
if (!userVerified && (assertionParams.RequireUserVerification || selectedCipher.Reprompt != CipherRepromptType.None)) {
// _logService.Info(
// "[Fido2Authenticator] Aborting because user verification was unsuccessful."
// );
ClipLogger.Log("[Fido2Authenticator] Aborting because user verification was unsuccessful");
throw new NotAllowedError();
}
try
{
var selectedFido2Credential = selectedCipher.Login.MainFido2Credential;
var selectedCredentialId = selectedFido2Credential.CredentialId;
ClipLogger.Log($"[Fido2Authenticator] Selected fido2 cred {selectedFido2Credential.CredentialId}");
if (selectedFido2Credential.CounterValue != 0) {
++selectedFido2Credential.CounterValue;
}
await _cipherService.UpdateLastUsedDateAsync(selectedCipher.Id);
var encrypted = await _cipherService.EncryptAsync(selectedCipher);
await _cipherService.SaveWithServerAsync(encrypted);
ClipLogger.Log($"[Fido2Authenticator] Selected fido2 cred RPID {selectedFido2Credential.RpId}");
ClipLogger.Log($"[Fido2Authenticator] param RpId {assertionParams.RpId}");
var authenticatorData = await GenerateAuthDataAsync(
rpId: selectedFido2Credential.RpId,
userPresence: true,
userVerification: true,
counter: selectedFido2Credential.CounterValue
);
ClipLogger.Log($"authenticatorData base64 from bytes: {Convert.ToBase64String(authenticatorData, Base64FormattingOptions.None)}");
ClipLogger.Log($"ClientDataHash base64 from bytes: {Convert.ToBase64String(assertionParams.Hash, Base64FormattingOptions.None)}");
ClipLogger.Log($"selectedFido2Credential.KeyBytes base64 from bytes: {Convert.ToBase64String(selectedFido2Credential.KeyBytes, Base64FormattingOptions.None)}");
var signature = GenerateSignature(
authData: authenticatorData,
clientDataHash: assertionParams.Hash,
privateKey: selectedFido2Credential.KeyBytes
);
ClipLogger.Log($"signature base64 from bytes: {Convert.ToBase64String(signature, Base64FormattingOptions.None)}");
return new Fido2AuthenticatorGetAssertionResult
{
SelectedCredential = new Fido2AuthenticatorGetAssertionSelectedCredential
{
Id = selectedCredentialId.GuidToRawFormat(),
UserHandle = selectedFido2Credential.UserHandleValue
},
AuthenticatorData = authenticatorData,
Signature = signature
};
} catch (Exception e) {
// _logService.Error(
// $"[Fido2Authenticator] Unknown error occured during assertion: {e.Message}"
// );
ClipLogger.Log($"[Fido2Authenticator] Unknown error occured during assertion: {e.Message}");
throw new UnknownError();
}
}
public async Task<Fido2AuthenticatorDiscoverableCredentialMetadata[]> SilentCredentialDiscoveryAsync(string rpId)
{
var credentials = (await FindCredentialsByRpAsync(rpId)).Select(cipher => new Fido2AuthenticatorDiscoverableCredentialMetadata {
Type = "public-key",
Id = cipher.Login.MainFido2Credential.CredentialId.GuidToRawFormat(),
RpId = cipher.Login.MainFido2Credential.RpId,
UserHandle = cipher.Login.MainFido2Credential.UserHandleValue,
UserName = cipher.Login.MainFido2Credential.UserName
}).ToArray();
return credentials;
}
/// <summary>
/// Finds existing crendetials and returns the `CipherId` for each one
/// </summary>
private async Task<string[]> FindExcludedCredentialsAsync(
PublicKeyCredentialDescriptor[] credentials
) {
if (credentials == null || credentials.Length == 0) {
return Array.Empty<string>();
}
var ids = new List<string>();
foreach (var credential in credentials)
{
try
{
ids.Add(credential.Id.GuidToStandardFormat());
} catch {}
}
if (ids.Count == 0) {
return Array.Empty<string>();
}
var ciphers = await _cipherService.GetAllDecryptedAsync();
return ciphers
.FindAll(
(cipher) =>
!cipher.IsDeleted &&
cipher.OrganizationId == null &&
cipher.Type == CipherType.Login &&
cipher.Login.HasFido2Credentials &&
ids.Contains(cipher.Login.MainFido2Credential.CredentialId)
)
.Select((cipher) => cipher.Id)
.ToArray();
}
private async Task<List<CipherView>> FindCredentialsByIdAsync(PublicKeyCredentialDescriptor[] credentials, string rpId)
{
var ids = new List<string>();
foreach (var credential in credentials)
{
try
{
ClipLogger.Log($"[Fido2Authenticator] FindCredentialsByIdAsync -> Converting Guid byte length: {credential.Id.Length}");
ids.Add(credential.Id.GuidToStandardFormat());
}
catch(Exception ex)
{
ClipLogger.Log($"[Fido2Authenticator] FindCredentialsByIdAsync -> Converting Guid ex {ex}");
}
}
ClipLogger.Log($"[Fido2Authenticator] FindCredentialsByIdAsync -> {credentials.Length} vs {ids.Count}");
if (ids.Count == 0)
{
return new List<CipherView>();
}
ClipLogger.Log($"[Fido2Authenticator] FindCredentialsByIdAsync -> {ids[0]}");
var ciphers = await _cipherService.GetAllDecryptedAsync();
ClipLogger.Log($"[Fido2Authenticator] FindCredentialsByIdAsync -> ciphers count: {ciphers?.Count}");
return ciphers.FindAll((cipher) =>
!cipher.IsDeleted &&
cipher.Type == CipherType.Login &&
cipher.Login.HasFido2Credentials &&
cipher.Login.MainFido2Credential.RpId == rpId &&
ids.Contains(cipher.Login.MainFido2Credential.CredentialId)
);
}
private async Task<List<CipherView>> FindCredentialsByRpAsync(string rpId)
{
var ciphers = await _cipherService.GetAllDecryptedAsync();
return ciphers.FindAll((cipher) =>
!cipher.IsDeleted &&
cipher.Type == CipherType.Login &&
cipher.Login.HasFido2Credentials &&
cipher.Login.MainFido2Credential.RpId == rpId &&
cipher.Login.MainFido2Credential.DiscoverableValue
);
}
// TODO: Move this to a separate service
private (PublicKey publicKey, byte[] privateKey) GenerateKeyPair()
{
var dsa = ECDsa.Create();
dsa.GenerateKey(ECCurve.NamedCurves.nistP256);
var privateKey = dsa.ExportPkcs8PrivateKey();
return (new PublicKey(dsa), privateKey);
}
private Fido2CredentialView CreateCredentialView(Fido2AuthenticatorMakeCredentialParams makeCredentialsParams, byte[] privateKey)
{
return new Fido2CredentialView {
CredentialId = Guid.NewGuid().ToString(),
KeyType = Constants.DefaultFido2CredentialType,
KeyAlgorithm = Constants.DefaultFido2CredentialAlgorithm,
KeyCurve = Constants.DefaultFido2CredentialCurve,
KeyValue = CoreHelpers.Base64UrlEncode(privateKey),
RpId = makeCredentialsParams.RpEntity.Id,
UserHandle = CoreHelpers.Base64UrlEncode(makeCredentialsParams.UserEntity.Id),
UserName = makeCredentialsParams.UserEntity.Name,
CounterValue = 0,
RpName = makeCredentialsParams.RpEntity.Name,
UserDisplayName = makeCredentialsParams.UserEntity.DisplayName,
DiscoverableValue = makeCredentialsParams.RequireResidentKey,
CreationDate = DateTime.Now
};
}
private async Task<byte[]> GenerateAuthDataAsync(
string rpId,
bool userVerification,
bool userPresence,
int counter,
byte[] credentialId = null,
PublicKey publicKey = null
) {
var isAttestation = credentialId != null && publicKey != null;
List<byte> authData = new List<byte>();
var rpIdHash = await _cryptoFunctionService.HashAsync(rpId, CryptoHashAlgorithm.Sha256);
authData.AddRange(rpIdHash);
ClipLogger.Log($"[Fido2Authenticator] GenerateAuthDataAsync -> rpIdHash: {rpIdHash}");
ClipLogger.Log($"[Fido2Authenticator] GenerateAuthDataAsync -> ad: {isAttestation} - uv: {userVerification} - up: {userPresence}");
var flags = AuthDataFlags(
extensionData: false,
attestationData: isAttestation,
userVerification: userVerification,
userPresence: userPresence
);
authData.Add(flags);
ClipLogger.Log($"[Fido2Authenticator] GenerateAuthDataAsync -> flags: {flags}");
ClipLogger.Log($"[Fido2Authenticator] GenerateAuthDataAsync -> counter: {counter}");
authData.AddRange(new List<byte> {
(byte)(counter >> 24),
(byte)(counter >> 16),
(byte)(counter >> 8),
(byte)counter
});
if (isAttestation)
{
var attestedCredentialData = new List<byte>();
attestedCredentialData.AddRange(AAGUID);
// credentialIdLength (2 bytes) and credential Id
var credentialIdLength = new byte[] {
(byte)((credentialId.Length - (credentialId.Length & 0xff)) / 256),
(byte)(credentialId.Length & 0xff)
};
attestedCredentialData.AddRange(credentialIdLength);
attestedCredentialData.AddRange(credentialId);
attestedCredentialData.AddRange(publicKey.ExportCose());
ClipLogger.Log($"[Fido2Authenticator] GenerateAuthDataAsync -> adding attestedCD: {attestedCredentialData}");
authData.AddRange(attestedCredentialData);
}
return authData.ToArray();
}
private byte AuthDataFlags(bool extensionData, bool attestationData, bool userVerification, bool userPresence, bool backupEligibility = true, bool backupState = true) {
byte flags = 0;
if (extensionData) {
flags |= 0b1000000;
}
if (attestationData) {
flags |= 0b01000000;
}
if (backupEligibility)
{
flags |= 0b00001000;
}
if (backupState)
{
flags |= 0b00010000;
}
if (userVerification) {
flags |= 0b00000100;
}
if (userPresence) {
flags |= 0b00000001;
}
return flags;
}
private byte[] EncodeAttestationObject(byte[] authData) {
var attestationObject = new CborWriter(CborConformanceMode.Ctap2Canonical);
attestationObject.WriteStartMap(3);
attestationObject.WriteTextString("fmt");
attestationObject.WriteTextString("none");
attestationObject.WriteTextString("attStmt");
attestationObject.WriteStartMap(0);
attestationObject.WriteEndMap();
attestationObject.WriteTextString("authData");
attestationObject.WriteByteString(authData);
attestationObject.WriteEndMap();
return attestationObject.Encode();
}
// TODO: Move this to a separate service
private byte[] GenerateSignature(byte[] authData, byte[] clientDataHash, byte[] privateKey)
{
var sigBase = authData.Concat(clientDataHash).ToArray();
var dsa = ECDsa.Create();
dsa.ImportPkcs8PrivateKey(privateKey, out var bytesRead);
if (bytesRead == 0)
{
throw new Exception("Failed to import private key");
}
return dsa.SignData(sigBase, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence);
}
private class PublicKey
{
private readonly ECDsa _dsa;
public PublicKey(ECDsa dsa) {
_dsa = dsa;
}
public byte[] X => _dsa.ExportParameters(false).Q.X;
public byte[] Y => _dsa.ExportParameters(false).Q.Y;
public byte[] ExportDer()
{
return _dsa.ExportSubjectPublicKeyInfo();
}
public byte[] ExportCose()
{
var result = new CborWriter(CborConformanceMode.Ctap2Canonical);
result.WriteStartMap(5);
// kty = EC2
result.WriteInt32(1);
result.WriteInt32(2);
// alg = ES256
result.WriteInt32(3);
result.WriteInt32(-7);
// crv = P-256
result.WriteInt32(-1);
result.WriteInt32(1);
// x
result.WriteInt32(-2);
result.WriteByteString(X);
// y
result.WriteInt32(-3);
result.WriteByteString(Y);
result.WriteEndMap();
return result.Encode();
}
}
}
}

View File

@@ -0,0 +1,248 @@
using System.Text;
using System.Text.Json;
using Bit.Core.Abstractions;
using Bit.Core.Enums;
using Bit.Core.Utilities;
using Bit.Core.Utilities.Fido2;
namespace Bit.Core.Services
{
public class Fido2ClientService : IFido2ClientService
{
private readonly IStateService _stateService;
private readonly IEnvironmentService _environmentService;
private readonly ICryptoFunctionService _cryptoFunctionService;
private readonly IFido2AuthenticatorService _fido2AuthenticatorService;
public Fido2ClientService(
IStateService stateService,
IEnvironmentService environmentService,
ICryptoFunctionService cryptoFunctionService,
IFido2AuthenticatorService fido2AuthenticatorService)
{
_stateService = stateService;
_environmentService = environmentService;
_cryptoFunctionService = cryptoFunctionService;
_fido2AuthenticatorService = fido2AuthenticatorService;
}
public async Task<Fido2ClientCreateCredentialResult> CreateCredentialAsync(Fido2ClientCreateCredentialParams createCredentialParams)
{
var blockedUris = await _stateService.GetAutofillBlacklistedUrisAsync();
var domain = CoreHelpers.GetHostname(createCredentialParams.Origin);
if (blockedUris.Contains(domain))
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.UriBlockedError,
"Origin is blocked by the user");
}
if (!await _stateService.IsAuthenticatedAsync())
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.InvalidStateError,
"No user is logged in");
}
if (createCredentialParams.Origin == _environmentService.GetWebVaultUrl())
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.NotAllowedError,
"Saving Bitwarden credentials in a Bitwarden vault is not allowed");
}
if (!createCredentialParams.SameOriginWithAncestors)
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.NotAllowedError,
"Credential creation is now allowed from embedded contexts with different origins");
}
if (createCredentialParams.User.Id.Length < 1 || createCredentialParams.User.Id.Length > 64)
{
// TODO: Should we use ArgumentException here instead?
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.TypeError,
"The length of user.id is not between 1 and 64 bytes (inclusive)");
}
if (!createCredentialParams.Origin.StartsWith("https://"))
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.SecurityError,
"Origin is not a valid https origin");
}
if (!Fido2DomainUtils.IsValidRpId(createCredentialParams.Rp.Id, createCredentialParams.Origin))
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.SecurityError,
"RP ID cannot be used with this origin");
}
PublicKeyCredentialParameters[] credTypesAndPubKeyAlgs;
if (createCredentialParams.PubKeyCredParams?.Length > 0)
{
// Filter out all unsupported algorithms
credTypesAndPubKeyAlgs = createCredentialParams.PubKeyCredParams
.Where(kp => kp.Alg == -7 && kp.Type == "public-key")
.ToArray();
}
else
{
// Assign default algorithms
credTypesAndPubKeyAlgs = [
new PublicKeyCredentialParameters { Alg = -7, Type = "public-key" },
new PublicKeyCredentialParameters { Alg = -257, Type = "public-key" }
];
}
if (credTypesAndPubKeyAlgs.Length == 0)
{
throw new Fido2ClientException(Fido2ClientException.ErrorCode.NotSupportedError, "No supported algorithms found");
}
var clientDataJSON = JsonSerializer.Serialize(new {
type = "webauthn.create",
challenge = CoreHelpers.Base64UrlEncode(createCredentialParams.Challenge),
origin = createCredentialParams.Origin,
crossOrigin = !createCredentialParams.SameOriginWithAncestors,
// tokenBinding: {} // Not supported
});
var clientDataJSONBytes = Encoding.UTF8.GetBytes(clientDataJSON);
var clientDataHash = await _cryptoFunctionService.HashAsync(clientDataJSONBytes, CryptoHashAlgorithm.Sha256);
var makeCredentialParams = MapToMakeCredentialParams(createCredentialParams, credTypesAndPubKeyAlgs, clientDataHash);
try {
var makeCredentialResult = await _fido2AuthenticatorService.MakeCredentialAsync(makeCredentialParams);
return new Fido2ClientCreateCredentialResult {
CredentialId = makeCredentialResult.CredentialId,
AttestationObject = makeCredentialResult.AttestationObject,
AuthData = makeCredentialResult.AuthData,
ClientDataJSON = clientDataJSONBytes,
PublicKey = makeCredentialResult.PublicKey,
PublicKeyAlgorithm = makeCredentialResult.PublicKeyAlgorithm,
Transports = createCredentialParams.Rp.Id == "google.com" ? ["internal", "usb"] : ["internal"] // workaround for a bug on Google's side
};
} catch (InvalidStateError) {
throw new Fido2ClientException(Fido2ClientException.ErrorCode.InvalidStateError, "Unknown invalid state encountered");
} catch (Exception) {
throw new Fido2ClientException(Fido2ClientException.ErrorCode.UnknownError, $"An unknown error occurred");
}
}
public async Task<Fido2ClientAssertCredentialResult> AssertCredentialAsync(Fido2ClientAssertCredentialParams assertCredentialParams)
{
var blockedUris = await _stateService.GetAutofillBlacklistedUrisAsync();
var domain = CoreHelpers.GetHostname(assertCredentialParams.Origin);
if (blockedUris.Contains(domain))
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.UriBlockedError,
"Origin is blocked by the user");
}
if (!await _stateService.IsAuthenticatedAsync())
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.InvalidStateError,
"No user is logged in");
}
if (assertCredentialParams.Origin == _environmentService.GetWebVaultUrl())
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.NotAllowedError,
"Saving Bitwarden credentials in a Bitwarden vault is not allowed");
}
if (!assertCredentialParams.Origin.StartsWith("https://"))
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.SecurityError,
"Origin is not a valid https origin");
}
if (!Fido2DomainUtils.IsValidRpId(assertCredentialParams.RpId, assertCredentialParams.Origin))
{
throw new Fido2ClientException(
Fido2ClientException.ErrorCode.SecurityError,
"RP ID cannot be used with this origin");
}
var clientDataJSON = JsonSerializer.Serialize(new {
type = "webauthn.get",
challenge = CoreHelpers.Base64UrlEncode(assertCredentialParams.Challenge),
origin = assertCredentialParams.Origin,
crossOrigin = !assertCredentialParams.SameOriginWithAncestors,
});
var clientDataJSONBytes = Encoding.UTF8.GetBytes(clientDataJSON);
var clientDataHash = await _cryptoFunctionService.HashAsync(clientDataJSONBytes, CryptoHashAlgorithm.Sha256);
var getAssertionParams = MapToGetAssertionParams(assertCredentialParams, clientDataHash);
try {
var getAssertionResult = await _fido2AuthenticatorService.GetAssertionAsync(getAssertionParams);
return new Fido2ClientAssertCredentialResult {
AuthenticatorData = getAssertionResult.AuthenticatorData,
ClientDataJSON = clientDataJSONBytes,
Id = CoreHelpers.Base64UrlEncode(getAssertionResult.SelectedCredential.Id),
RawId = getAssertionResult.SelectedCredential.Id,
Signature = getAssertionResult.Signature,
UserHandle = getAssertionResult.SelectedCredential.UserHandle
};
} catch (InvalidStateError) {
throw new Fido2ClientException(Fido2ClientException.ErrorCode.InvalidStateError, "Unknown invalid state encountered");
} catch (Exception) {
throw new Fido2ClientException(Fido2ClientException.ErrorCode.UnknownError, $"An unknown error occurred");
}
throw new NotImplementedException();
}
private Fido2AuthenticatorMakeCredentialParams MapToMakeCredentialParams(
Fido2ClientCreateCredentialParams createCredentialParams,
PublicKeyCredentialParameters[] credTypesAndPubKeyAlgs,
byte[] clientDataHash)
{
var requireResidentKey = createCredentialParams.AuthenticatorSelection?.ResidentKey == "required" ||
createCredentialParams.AuthenticatorSelection?.ResidentKey == "preferred" ||
(createCredentialParams.AuthenticatorSelection?.ResidentKey == null &&
createCredentialParams.AuthenticatorSelection?.RequireResidentKey == true);
var requireUserVerification = createCredentialParams.AuthenticatorSelection?.UserVerification == "required" ||
createCredentialParams.AuthenticatorSelection?.UserVerification == "preferred" ||
createCredentialParams.AuthenticatorSelection?.UserVerification == null;
return new Fido2AuthenticatorMakeCredentialParams {
RequireResidentKey = requireResidentKey,
RequireUserVerification = requireUserVerification,
ExcludeCredentialDescriptorList = createCredentialParams.ExcludeCredentials,
CredTypesAndPubKeyAlgs = credTypesAndPubKeyAlgs,
Hash = clientDataHash,
RpEntity = createCredentialParams.Rp,
UserEntity = createCredentialParams.User,
Extensions = createCredentialParams.Extensions
};
}
private Fido2AuthenticatorGetAssertionParams MapToGetAssertionParams(
Fido2ClientAssertCredentialParams assertCredentialParams,
byte[] cliendDataHash)
{
var requireUserVerification = assertCredentialParams.UserVerification == "required" ||
assertCredentialParams.UserVerification == "preferred" ||
assertCredentialParams.UserVerification == null;
return new Fido2AuthenticatorGetAssertionParams {
RpId = assertCredentialParams.RpId,
Challenge = assertCredentialParams.Challenge,
AllowCredentialDescriptorList = assertCredentialParams.AllowCredentials,
RequireUserPresence = true,
RequireUserVerification = requireUserVerification,
Hash = cliendDataHash
};
}
}
}

View File

@@ -0,0 +1,61 @@
using System.Runtime.CompilerServices;
using System.Text;
using Bit.Core.Abstractions;
#if IOS
using UIKit;
#endif
namespace Bit.Core.Services
{
public class ClipLogger : ILogger
{
private static readonly StringBuilder _currentBreadcrumbs = new StringBuilder();
static ILogger _instance;
public static ILogger Instance
{
get
{
if (_instance is null)
{
_instance = new ClipLogger();
}
return _instance;
}
}
protected ClipLogger()
{
}
public static void Log(string breadcrumb)
{
_currentBreadcrumbs.AppendLine($"{DateTime.Now.ToShortTimeString()}: {breadcrumb}");
#if IOS
UIPasteboard.General.String = _currentBreadcrumbs.ToString();
#endif
}
public void Error(string message, IDictionary<string, string> extraData = null, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
{
var classAndMethod = $"{Path.GetFileNameWithoutExtension(sourceFilePath)}.{memberName}";
var filePathAndLineNumber = $"{Path.GetFileName(sourceFilePath)}:{sourceLineNumber}";
var properties = new Dictionary<string, string>
{
["File"] = filePathAndLineNumber,
["Method"] = memberName
};
Log(message ?? $"Error found in: {classAndMethod}, {filePathAndLineNumber}");
}
public void Exception(Exception ex) => Log(ex?.ToString());
public Task InitAsync() => Task.CompletedTask;
public Task<bool> IsEnabled() => Task.FromResult(true);
public Task SetEnabled(bool value) => Task.CompletedTask;
}
}

View File

@@ -1,5 +1,5 @@
using System;
using Bit.Core.Abstractions;
using Bit.Core.Abstractions;
using Bit.Core.Services;
using Bit.Core.Utilities;
namespace Bit.Core.Services
@@ -22,10 +22,23 @@ namespace Bit.Core.Services
#if !FDROID
// just in case the caller throws the exception in a moment where the logger can't be resolved
// we need to track the error as well
Microsoft.AppCenter.Crashes.Crashes.TrackError(ex);
//Microsoft.AppCenter.Crashes.Crashes.TrackError(ex);
ClipLogger.Log(ex?.ToString());
#endif
}
}
public static void LogBreadcrumb(string breadcrumb)
{
if (ServiceContainer.Resolve<ILogger>("logger", true) is ILogger logger)
{
logger.Error(breadcrumb);
}
else
{
ClipLogger.Log(breadcrumb);
}
}
}
}

View File

@@ -4,6 +4,7 @@ using System.Text;
using System.Threading.Tasks;
using Bit.Core.Abstractions;
using Bit.Core.Enums;
using Bit.Core.Models.Domain;
using PCLCrypto;
using static PCLCrypto.WinRTCrypto;

View File

@@ -38,12 +38,38 @@ namespace Bit.Core.Utilities
#endif
}
/// <summary>
/// Returns the host (and not port) of the given uri.
/// Does not support plain hostnames without a protocol.
///
/// Input => Output examples:
/// <para>https://bitwarden.com => bitwarden.com</para>
/// <para>https://login.bitwarden.com:1337 => login.bitwarden.com</para>
/// <para>https://sub.login.bitwarden.com:1337 => sub.login.bitwarden.com</para>
/// <para>https://localhost:8080 => localhost</para>
/// <para>localhost => null</para>
/// <para>bitwarden => null</para>
/// <para>127.0.0.1 => 127.0.0.1</para>
/// </summary>
public static string GetHostname(string uriString)
{
var uri = GetUri(uriString);
return string.IsNullOrEmpty(uri?.Host) ? null : uri.Host;
}
/// <summary>
/// Returns the host and port of the given uri.
/// Does not support plain hostnames without
///
/// Input => Output examples:
/// <para>https://bitwarden.com => bitwarden.com</para>
/// <para>https://login.bitwarden.com:1337 => login.bitwarden.com:1337</para>
/// <para>https://sub.login.bitwarden.com:1337 => sub.login.bitwarden.com:1337</para>
/// <para>https://localhost:8080 => localhost:8080</para>
/// <para>localhost => null</para>
/// <para>bitwarden => null</para>
/// <para>127.0.0.1 => 127.0.0.1</para>
/// </summary>
public static string GetHost(string uriString)
{
var uri = GetUri(uriString);
@@ -61,6 +87,19 @@ namespace Bit.Core.Utilities
return null;
}
/// <summary>
/// Returns the second and top level domain of the given uri.
/// Does not support plain hostnames without
///
/// Input => Output examples:
/// <para>https://bitwarden.com => bitwarden.com</para>
/// <para>https://login.bitwarden.com:1337 => bitwarden.com</para>
/// <para>https://sub.login.bitwarden.com:1337 => bitwarden.com</para>
/// <para>https://localhost:8080 => localhost</para>
/// <para>localhost => null</para>
/// <para>bitwarden => null</para>
/// <para>127.0.0.1 => 127.0.0.1</para>
/// </summary>
public static string GetDomain(string uriString)
{
var uri = GetUri(uriString);

View File

@@ -0,0 +1,18 @@
namespace Bit.Core.Utilities.Fido2
{
#nullable enable
/// <summary>
/// The Relying Party's requirements of the authenticator used in the creation of the credential.
/// </summary>
public class AuthenticatorSelectionCriteria
{
public bool? RequireResidentKey { get; set; }
public string? ResidentKey { get; set; }
public string UserVerification { get; set; } = "preferred";
/// <summary>
/// This member is intended for use by Relying Parties that wish to select the appropriate authenticators to participate in the create() operation.
/// </summary>
// public AuthenticatorAttachment? AuthenticatorAttachment { get; set; } // not used
}
}

View File

@@ -0,0 +1,6 @@
namespace Bit.Core.Utilities.Fido2 {
public enum Fido2AlgorithmIdentifier : int {
ES256 = -7,
RS256 = -257,
}
}

View File

@@ -0,0 +1,16 @@
/// <summary>
/// Represents the metadata of a discoverable credential for a FIDO2 authenticator.
/// See: https://www.w3.org/TR/webauthn-3/#sctn-op-silent-discovery
/// </summary>
public class Fido2AuthenticatorDiscoverableCredentialMetadata
{
public string Type { get; set; }
public byte[] Id { get; set; }
public string RpId { get; set; }
public byte[] UserHandle { get; set; }
public string UserName { get; set; }
}

View File

@@ -0,0 +1,37 @@
namespace Bit.Core.Utilities.Fido2
{
public class Fido2AuthenticatorException : Exception
{
public Fido2AuthenticatorException(string message) : base(message)
{
}
}
public class NotAllowedError : Fido2AuthenticatorException
{
public NotAllowedError() : base("NotAllowedError")
{
}
}
public class NotSupportedError : Fido2AuthenticatorException
{
public NotSupportedError() : base("NotSupportedError")
{
}
}
public class InvalidStateError : Fido2AuthenticatorException
{
public InvalidStateError() : base("InvalidStateError")
{
}
}
public class UnknownError : Fido2AuthenticatorException
{
public UnknownError() : base("UnknownError")
{
}
}
}

View File

@@ -0,0 +1,31 @@
namespace Bit.Core.Utilities.Fido2
{
public class Fido2AuthenticatorGetAssertionParams
{
/** The callers RP ID, as determined by the user agent and the client. */
public string RpId { get; set; }
/** The hash of the serialized client data, provided by the client. */
public byte[] Hash { get; set; }
public PublicKeyCredentialDescriptor[] AllowCredentialDescriptorList { get; set; }
/// <summary>
/// Instructs the authenticator to require a user-verifying gesture in order to complete the request. Examples of such gestures are fingerprint scan or a PIN.
/// </summary>
public bool RequireUserVerification { get; set; }
/// <summary>
/// Instructs the authenticator to require user consent to complete the operation.
/// </summary>
public bool RequireUserPresence { get; set; }
/// <summary>
/// The challenge to be signed by the authenticator.
/// </summary>
public byte[] Challenge { get; set; }
public object Extensions { get; set; }
}
}

View File

@@ -0,0 +1,24 @@
namespace Bit.Core.Utilities.Fido2
{
public class Fido2AuthenticatorGetAssertionResult
{
public byte[] AuthenticatorData { get; set; }
public byte[] Signature { get; set; }
public Fido2AuthenticatorGetAssertionSelectedCredential SelectedCredential { get; set; }
public override string ToString()
{
return $"AD: {AuthenticatorData.Length}; Sig: {Signature.Length}; SC: {SelectedCredential?.Id?.Length}; {SelectedCredential?.UserHandle?.Length}";
}
}
public class Fido2AuthenticatorGetAssertionSelectedCredential {
public byte[] Id { get; set; }
#nullable enable
public byte[]? UserHandle { get; set; }
}
}

View File

@@ -0,0 +1,53 @@
namespace Bit.Core.Utilities.Fido2
{
public class Fido2AuthenticatorMakeCredentialParams
{
/// <summary>
/// The Relying Party's PublicKeyCredentialRpEntity.
/// </summary>
public PublicKeyCredentialRpEntity RpEntity { get; set; }
/// <summary>
/// The Relying Party's PublicKeyCredentialRpEntity.
/// </summary>
public PublicKeyCredentialUserEntity UserEntity { get; set; }
/// <summary>
/// The hash of the serialized client data, provided by the client.
/// </summary>
public byte[] Hash { get; set; }
/// <summary>
/// A sequence of pairs of PublicKeyCredentialType and public key algorithms (COSEAlgorithmIdentifier) requested by the Relying Party. This sequence is ordered from most preferred to least preferred. The authenticator makes a best-effort to create the most preferred credential that it can.
/// </summary>
public PublicKeyCredentialParameters[] CredTypesAndPubKeyAlgs { get; set; }
/// <summary>
///An OPTIONAL list of PublicKeyCredentialDescriptor objects provided by the Relying Party with the intention that, if any of these are known to the authenticator, it SHOULD NOT create a new credential. excludeCredentialDescriptorList contains a list of known credentials.
/// </summary>
public PublicKeyCredentialDescriptor[] ExcludeCredentialDescriptorList { get; set; }
/// <summary>
/// The effective resident key requirement for credential creation, a Boolean value determined by the client. Resident is synonymous with discoverable. */
/// </summary>
public bool RequireResidentKey { get; set; }
/// <summary>
/// The effective user verification requirement for assertion, a Boolean value provided by the client.
/// </summary>
public bool RequireUserVerification { get; set; }
/// <summary>
/// CTAP2 authenticators support setting this to false, but we only support the WebAuthn authenticator model which does not have that option.
/// </summary>
// public bool RequireUserPresence { get; set; } // Always required
/// <summary>
/// The authenticator's attestation preference, a string provided by the client. This is a hint that the client gives to the authenticator about what kind of attestation statement it would like. The authenticator makes a best-effort to satisfy the preference.
/// Note: Attestation statements are not supported at this time.
/// </summary>
// public string AttestationPreference { get; set; }
public object Extensions { get; set; }
}
}

View File

@@ -0,0 +1,16 @@
namespace Bit.Core.Utilities.Fido2
{
public class Fido2AuthenticatorMakeCredentialResult
{
public byte[] CredentialId { get; set; }
public byte[] AttestationObject { get; set; }
public byte[] AuthData { get; set; }
public byte[] PublicKey { get; set; }
public int PublicKeyAlgorithm { get; set; }
}
}

View File

@@ -0,0 +1,57 @@
namespace Bit.Core.Utilities.Fido2
{
#nullable enable
/// <summary>
/// Parameters for asserting a credential.
///
/// This class is an extended version of the WebAuthn struct:
/// https://www.w3.org/TR/webauthn-2/#dictdef-publickeycredentialrequestoptions
/// </summary>
public class Fido2ClientAssertCredentialParams
{
/// <summary>
/// A value which is true if and only if the callers environment settings object is same-origin with its ancestors.
/// It is false if caller is cross-origin.
/// </summary>
public bool SameOriginWithAncestors { get; set; }
/// <summary>
/// The challenge that the selected authenticator signs, along with other data, when producing an authentication
/// assertion.
/// </summary>
public required byte[] Challenge { get; set; }
/// <summary>
/// The relying party identifier claimed by the caller. If omitted, its value will be the CredentialsContainer
/// object's relevant settings object's origin's effective domain.
/// </summary>
public string RpId { get; set; }
/// <summary>
/// The Relying Party's origin (e.g., "https://example.com").
/// </summary>
public string Origin { get; set; }
/// <summary>
/// A list of PublicKeyCredentialDescriptor objects representing public key credentials acceptable to the caller,
/// in descending order of the callers preference (the first item in the list is the most preferred credential,
/// and so on down the list).
/// </summary>
public PublicKeyCredentialDescriptor[] AllowCredentials { get; set; } = [];
/// <summary>
/// The Relying Party's requirements regarding user verification for the get() operation.
/// </summary>
public string UserVerification { get; set; } = "preferred";
/// <summary>
/// This time, in milliseconds, that the caller is willing to wait for the call to complete.
/// This is treated as a hint, and MAY be overridden by the client.
/// </summary>
/// <remarks>
/// This is not currently supported.
/// </remarks>
public int? Timeout { get; set; }
}
}

View File

@@ -0,0 +1,42 @@
namespace Bit.Core.Utilities.Fido2
{
/// <summary>
/// The result of asserting a credential.
///
/// See: https://www.w3.org/TR/webauthn-2/#publickeycredential
/// </summary>
public class Fido2ClientAssertCredentialResult
{
/// <summary>
/// Base64url encoding of the credential identifer.
/// </summary>
public required string Id { get; set; }
/// <summary>
/// The credential identifier.
/// </summary>
public required byte[] RawId { get; set; }
/// <summary>
/// The JSON-compatible serialization of client datapassed to the authenticator by the client in
/// order to generate this assertion.
/// </summary>
public required byte[] ClientDataJSON { get; set; }
/// <summary>
/// The authenticator data returned by the authenticator.
/// </summary>
public required byte[] AuthenticatorData { get; set; }
/// <summary>
/// The raw signature returned from the authenticator.
/// </summary>
public required byte[] Signature { get; set; }
/// <summary>
/// The user handle returned from the authenticator, or null if the authenticator did not
/// return a user handle.
/// </summary>
public byte[]? UserHandle { get; set; }
}
}

View File

@@ -0,0 +1,35 @@
namespace Bit.Core.Utilities.Fido2
{
/// <summary>
/// This class represents an authenticator's response to a client's request for generation of a
/// new authentication assertion given the WebAuthn Relying Party's challenge.
/// This response contains a cryptographic signature proving possession of the credential private key,
/// and optionally evidence of user consent to a specific transaction.
///
/// See: https://www.w3.org/TR/webauthn-2/#iface-authenticatorassertionresponse
/// </summary>
public class Fido2ClientAuthenticatorAssertionResponse
{
/// <summary>
/// The JSON-compatible serialization of client data passed to the authenticator by the client
/// in order to generate this assertion. The exact JSON serialization MUST be preserved, as the
/// hash of the serialized client data has been computed over it.
/// </summary>
public required byte[] ClientDataJSON { get; set; }
/// <summary>
/// The authenticator data returned by the authenticator.
/// </summary>
public required byte[] AuthenticatorData { get; set; }
/// <summary>
/// Raw signature returned from the authenticator.
/// </summary>
public required byte[] Signature { get; set; }
/// <summary>
/// The user handle returned from the authenticator, or null if the authenticator did not return a user handle.
/// </summary>
public byte[] UserHandle { get; set; } = null;
}
}

View File

@@ -0,0 +1,75 @@
namespace Bit.Core.Utilities.Fido2
{
#nullable enable
/// <summary>
/// Parameters for creating a new credential.
/// </summary>
public class Fido2ClientCreateCredentialParams
{
/// <summary>
/// The Relaying Parties origin, see: https://html.spec.whatwg.org/multipage/browsers.html#concept-origin
/// </summary>
public required string Origin { get; set; }
/// <summary>
/// A value which is true if and only if the callers environment settings object is same-origin with its ancestors.
/// It is false if caller is cross-origin.
/// </summary>
public bool SameOriginWithAncestors { get; set; }
/// <summary>
/// The Relying Party's preference for attestation conveyance
/// </summary>
public string? Attestation { get; set; } = "none";
/// <summary>
/// The Relying Party's requirements of the authenticator used in the creation of the credential.
/// </summary>
public AuthenticatorSelectionCriteria? AuthenticatorSelection { get; set; }
/// <summary>
/// Challenge intended to be used for generating the newly created credential's attestation object.
/// </summary>
public required byte[] Challenge { get; set; } // base64url encoded
/// <summary>
/// This member is intended for use by Relying Parties that wish to limit the creation of multiple credentials for
/// the same account on a single authenticator. The client is requested to return an error if the new credential would
/// be created on an authenticator that also contains one of the credentials enumerated in this parameter.
/// </summary>
public PublicKeyCredentialDescriptor[]? ExcludeCredentials { get; set; }
/// <summary>
/// This member contains additional parameters requesting additional processing by the client and authenticator.
/// Not currently supported.
/// </summary>
public object? Extensions { get; set; }
/// <summary>
/// This member contains information about the desired properties of the credential to be created.
/// The sequence is ordered from most preferred to least preferred.
/// The client makes a best-effort to create the most preferred credential that it can.
/// </summary>
public required PublicKeyCredentialParameters[] PubKeyCredParams { get; set; }
/// <summary>
/// Data about the Relying Party responsible for the request.
/// </summary>
public required PublicKeyCredentialRpEntity Rp { get; set; }
/// <summary>
/// Data about the user account for which the Relying Party is requesting attestation.
/// </summary>
public required PublicKeyCredentialUserEntity User { get; set; }
/// <summary>
/// This member specifies a time, in milliseconds, that the caller is willing to wait for the call to complete.
/// This is treated as a hint, and MAY be overridden by the client.
/// </summary>
/// <remarks>
/// This is not currently supported.
/// </remarks>
public int? Timeout { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
namespace Bit.Core.Utilities.Fido2
{
/// <summary>
/// The result of creating a new credential.
///
/// This class is an extended version of the WebAuthn struct:
/// https://www.w3.org/TR/webauthn-3/#credentialcreationdata-attestationobjectresult
/// </summary>
public class Fido2ClientCreateCredentialResult
{
public byte[] CredentialId { get; set; }
public byte[] ClientDataJSON { get; set; }
public byte[] AttestationObject { get; set; }
public byte[] AuthData { get; set; }
public byte[] PublicKey { get; set; }
public int PublicKeyAlgorithm { get; set; }
public string[] Transports { get; set; }
}
}

View File

@@ -0,0 +1,25 @@
namespace Bit.Core.Utilities.Fido2
{
public class Fido2ClientException : Exception
{
public enum ErrorCode
{
NotAllowedError,
TypeError,
SecurityError,
UriBlockedError,
NotSupportedError,
InvalidStateError,
UnknownError
}
public readonly ErrorCode Code;
public readonly string Reason;
public Fido2ClientException(ErrorCode code, string reason) : base($"{code} ({reason})")
{
Code = code;
Reason = reason;
}
}
}

View File

@@ -0,0 +1,65 @@
using Bit.Core.Abstractions;
namespace Bit.Core.Utilities.Fido2
{
/// <summary>
/// This implementation is used when all interactions are delegated to the operating system.
/// Most often these decisions have already been made by the time the Authenticator is called.
///
/// This is only supported for assertion operations. Attestation requires the user to interact
/// with the app directly.
/// </summary>
public class Fido2DelegatedUserInterface : IFido2UserInterface
{
private string _cipherId = null;
private bool _userVerified = false;
private Func<Task> _ensureUnlockedVaultAsyncCallback;
/// <summary>
/// Indicates that the user has already picked a credential from a list of existing credentials.
/// Picking a credential also assumes user presence.
/// </summary>
public Fido2DelegatedUserInterface UserPickedCredential(string cipherId)
{
_cipherId = cipherId;
return this;
}
/// <summary>
/// Indicates that the user was verified by the OS, e.g. by a fingerprint or face scan.
/// </summary>
public Fido2DelegatedUserInterface UserIsVerified()
{
_userVerified = true;
return this;
}
public Fido2DelegatedUserInterface WithEnsureUnlockedVaultAsyncCallback(Func<Task> callback)
{
_ensureUnlockedVaultAsyncCallback = callback;
return this;
}
public Task<Fido2PickCredentialResult> PickCredentialAsync(Fido2PickCredentialParams parameters)
{
return Task.FromResult(new Fido2PickCredentialResult
{
CipherId = _cipherId,
UserVerified = _userVerified
});
}
public Task EnsureUnlockedVaultAsync()
{
if (_ensureUnlockedVaultAsyncCallback != null)
{
return _ensureUnlockedVaultAsyncCallback();
}
throw new Exception("No callback provided to ensure the vault is unlocked");
}
public Task InformExcludedCredential(string[] existingCipherIds) => throw new NotImplementedException();
public Task<Fido2ConfirmNewCredentialResult> ConfirmNewCredentialAsync(Fido2ConfirmNewCredentialParams parameters) => throw new NotImplementedException();
}
}

View File

@@ -0,0 +1,37 @@
using System.Text.RegularExpressions;
namespace Bit.Core.Utilities.Fido2
{
public class Fido2DomainUtils
{
// TODO: This is a basic implementation of the domain validation logic, and is probably not correct.
// It doesn't support IP-adresses, and it doesn't follow the algorithm in the spec:
// https://html.spec.whatwg.org/multipage/browsers.html#is-a-registrable-domain-suffix-of-or-is-equal-to
public static bool IsValidRpId(string rpId, string origin)
{
if (rpId == null || origin == null)
{
return false;
}
// TODO: DomainName doesn't like it when we give it a URL with a protocol or port
// So we remove the protocol and port here, while still supporting ipv6 shortform
// https is enforced in the client, so we don't need to worry about that here
var originWithoutProtocolOrPort = Regex.Replace(origin, @"(https?://)?([^:/]+)(:\d+)?(/.*)?", "$2$4");
if (rpId == originWithoutProtocolOrPort)
{
return true;
}
if (!DomainName.TryParse(rpId, out var parsedRpId) || !DomainName.TryParse(originWithoutProtocolOrPort, out var parsedOrgin))
{
return false;
}
return parsedOrgin.Tld == parsedRpId.Tld &&
parsedOrgin.Domain == parsedRpId.Domain &&
(parsedOrgin.SubDomain == parsedRpId.SubDomain || parsedOrgin.SubDomain.EndsWith(parsedRpId.SubDomain));
}
}
}

View File

@@ -0,0 +1,9 @@
namespace Bit.Core.Utilities.Fido2
{
public class PublicKeyCredentialAlgorithmDescriptor {
public byte[] Id {get; set;}
public string[] Transports;
public string Type;
public int Algorithm;
}
}

View File

@@ -0,0 +1,9 @@
namespace Bit.Core.Utilities.Fido2
{
public class PublicKeyCredentialDescriptor {
public byte[] Id { get; set; }
public string[] Transports { get; set; }
public string Type { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
namespace Bit.Core.Utilities.Fido2
{
/// <summary>
/// A description of a key type and algorithm.
///</example>
public class PublicKeyCredentialParameters
{
public string Type { get; set; }
/// <summary>
/// Cose algorithm identifier, e.g. -7 for ES256.
/// </summary>
public int Alg { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
namespace Bit.Core.Utilities.Fido2
{
public class PublicKeyCredentialRpEntity
{
public string Id { get; set; }
public string Name { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
namespace Bit.Core.Utilities.Fido2
{
public class PublicKeyCredentialUserEntity {
public byte[] Id { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public string Icon { get; set; }
}
}

View File

@@ -0,0 +1,70 @@
using System.Globalization;
using System.Text.RegularExpressions;
namespace Bit.Core.Utilities
{
/// <summary>
/// Extension methods for converting between standard and raw GUID formats.
///
/// Note: Not optimized for performance. Don't use in performance-critical code.
/// </summary>
public static class GuidExtensions
{
public static byte[] GuidToRawFormat(this string guidString)
{
if (guidString == null)
{
throw new ArgumentException("GUID parameter is null", nameof(guidString));
}
if (!IsValidGuid(guidString)) {
throw new FormatException("GUID parameter is invalid");
}
var arr = new byte[16];
arr[0] = byte.Parse(guidString.Substring(0, 2), NumberStyles.HexNumber); // Parse ##......-....-....-....-............
arr[1] = byte.Parse(guidString.Substring(2, 2), NumberStyles.HexNumber); // Parse ..##....-....-....-....-............
arr[2] = byte.Parse(guidString.Substring(4, 2), NumberStyles.HexNumber); // Parse ....##..-....-....-....-............
arr[3] = byte.Parse(guidString.Substring(6, 2), NumberStyles.HexNumber); // Parse ......##-....-....-....-............
arr[4] = byte.Parse(guidString.Substring(9, 2), NumberStyles.HexNumber); // Parse ........-##..-....-....-............
arr[5] = byte.Parse(guidString.Substring(11, 2), NumberStyles.HexNumber); // Parse ........-..##-....-....-............
arr[6] = byte.Parse(guidString.Substring(14, 2), NumberStyles.HexNumber); // Parse ........-....-##..-....-............
arr[7] = byte.Parse(guidString.Substring(16, 2), NumberStyles.HexNumber); // Parse ........-....-..##-....-............
arr[8] = byte.Parse(guidString.Substring(19, 2), NumberStyles.HexNumber); // Parse ........-....-....-##..-............
arr[9] = byte.Parse(guidString.Substring(21, 2), NumberStyles.HexNumber); // Parse ........-....-....-..##-............
arr[10] = byte.Parse(guidString.Substring(24, 2), NumberStyles.HexNumber); // Parse ........-....-....-....-##..........
arr[11] = byte.Parse(guidString.Substring(26, 2), NumberStyles.HexNumber); // Parse ........-....-....-....-..##........
arr[12] = byte.Parse(guidString.Substring(28, 2), NumberStyles.HexNumber); // Parse ........-....-....-....-....##......
arr[13] = byte.Parse(guidString.Substring(30, 2), NumberStyles.HexNumber); // Parse ........-....-....-....-......##....
arr[14] = byte.Parse(guidString.Substring(32, 2), NumberStyles.HexNumber); // Parse ........-....-....-....-........##..
arr[15] = byte.Parse(guidString.Substring(34, 2), NumberStyles.HexNumber); // Parse ........-....-....-....-..........##
return arr;
}
public static string GuidToStandardFormat(this byte[] guidBytes)
{
if (guidBytes == null)
{
throw new ArgumentException("GUID parameter is null", nameof(guidBytes));
}
if (guidBytes.Length != 16)
{
throw new ArgumentException("Invalid raw GUID format", nameof(guidBytes));
}
return Convert.ToHexString(guidBytes).ToLower().Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-" );
}
public static bool IsValidGuid(string guid)
{
return Regex.IsMatch(guid, @"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$", RegexOptions.ECMAScript);
}
}
}

View File

@@ -1,9 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using Bit.Core.Abstractions;
using Bit.Core.Services;
@@ -118,6 +115,7 @@ namespace Bit.Core.Utilities
Register<IUsernameGenerationService>(usernameGenerationService);
Register<IDeviceTrustCryptoService>(deviceTrustCryptoService);
Register<IPasswordResetEnrollmentService>(passwordResetEnrollmentService);
Register<IFido2AuthenticationService>(new Fido2AuthenticationService());
}
public static void Register<T>(string serviceName, T obj)

View File

@@ -0,0 +1,48 @@
Additions allow you to add arbitrary C# to the generated classes
before they are compiled. This can be helpful for providing convenience
methods or adding pure C# classes.
== Adding Methods to Generated Classes ==
Let's say the library being bound has a Rectangle class with a constructor
that takes an x and y position, and a width and length size. It will look like
this:
public partial class Rectangle
{
public Rectangle (int x, int y, int width, int height)
{
// JNI bindings
}
}
Imagine we want to add a constructor to this class that takes a Point and
Size structure instead of 4 ints. We can add a new file called Rectangle.cs
with a partial class containing our new method:
public partial class Rectangle
{
public Rectangle (Point location, Size size) :
this (location.X, location.Y, size.Width, size.Height)
{
}
}
At compile time, the additions class will be added to the generated class
and the final assembly will a Rectangle class with both constructors.
== Adding C# Classes ==
Another thing that can be done is adding fully C# managed classes to the
generated library. In the above example, let's assume that there isn't a
Point class available in Java or our library. The one we create doesn't need
to interact with Java, so we'll create it like a normal class in C#.
By adding a Point.cs file with this class, it will end up in the binding library:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}

View File

@@ -0,0 +1,15 @@
<enum-field-mappings>
<!--
This example converts the constants Fragment_id, Fragment_name,
and Fragment_tag from android.support.v4.app.FragmentActivity.FragmentTag
to an enum called Android.Support.V4.App.FragmentTagType with values
Id, Name, and Tag.
<mapping jni-class="android/support/v4/app/FragmentActivity$FragmentTag" clr-enum-type="Android.Support.V4.App.FragmentTagType">
<field jni-name="Fragment_name" clr-name="Name" value="0" />
<field jni-name="Fragment_id" clr-name="Id" value="1" />
<field jni-name="Fragment_tag" clr-name="Tag" value="2" />
</mapping>
-->
</enum-field-mappings>

View File

@@ -0,0 +1,14 @@
<enum-method-mappings>
<!--
This example changes the Java method:
android.support.v4.app.Fragment.SavedState.writeToParcel (int flags)
to be:
android.support.v4.app.Fragment.SavedState.writeToParcel (Android.OS.ParcelableWriteFlags flags)
when bound in C#.
<mapping jni-class="android/support/v4/app/Fragment.SavedState">
<method jni-name="writeToParcel" parameter="flags" clr-enum-type="Android.OS.ParcelableWriteFlags" />
</mapping>
-->
</enum-method-mappings>

View File

@@ -0,0 +1,12 @@
<metadata>
<attr path="/api/package[@name='androidx.credentials']" name="managedName">AndroidX.Credentials</attr>
<attr path="/api/package[@name='androidx.credentials.provider']" name="managedName">AndroidX.Credentials.Provider</attr>
<attr path="/api/package[@name='androidx.credentials.exceptions']" name="managedName">AndroidX.Credentials.Exceptions</attr>
<attr path="/api/package[@name='androidx.credentials.webauthn']" name="managedName">AndroidX.Credentials.WebAuthn</attr>
<!-- fix companions -->
<attr path="/api/package/class[substring(@name,string-length(@name)-9)='.Companion']" name="managedName">CompanionStatic</attr>
<remove-node path="/api/package/class[substring(@name,string-length(@name)-9)='.Companion' and count(method)=0 and count(field)=0]" />
<attr path="/api/package/class[substring(@name,string-length(@name)-7)='.Default']" name="managedName">DefaultStatic</attr>
<remove-node path="/api/package/class[substring(@name,string-length(@name)-7)='.Default' and count(method)=0 and count(field)=0]" />
</metadata>

View File

@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-android</TargetFramework>
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
<!--<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">11.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>-->
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>XamarinBinding.AndroidX.Credentials</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Xamarin.Kotlin.StdLib" Version="1.9.10.1" />
</ItemGroup>
</Project>

Binary file not shown.

View File

@@ -0,0 +1,380 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AuthenticationServices;
using Bit.App.Abstractions;
using Bit.Core.Abstractions;
using Bit.Core.Models.View;
using Bit.Core.Services;
using Bit.Core.Utilities;
using Bit.Core.Utilities.Fido2;
using Bit.iOS.Core.Utilities;
using Foundation;
using Microsoft.Maui.ApplicationModel;
using ObjCRuntime;
using UIKit;
namespace Bit.iOS.Autofill
{
public partial class CredentialProviderViewController : ASCredentialProviderViewController, IAccountsManagerHost, IFido2UserInterface
{
private readonly LazyResolve<ICipherService> _cipherService = new LazyResolve<ICipherService>();
private readonly Fido2DelegatedUserInterface _userInterface = new Fido2DelegatedUserInterface();
private IFido2AuthenticatorService _fido2AuthService;
private IFido2AuthenticatorService Fido2AuthService
{
get
{
if (_fido2AuthService is null)
{
_fido2AuthService = ServiceContainer.Resolve<IFido2AuthenticatorService>();
_fido2AuthService.Init(_userInterface);
}
return _fido2AuthService;
}
}
public override async void PrepareInterfaceForPasskeyRegistration(IASCredentialRequest registrationRequest)
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
return;
}
ClipLogger.Log($"PIFPR(IASC)");
try
{
switch (registrationRequest?.Type)
{
case ASCredentialRequestType.PasskeyAssertion:
ClipLogger.Log($"PIFPR(IASC) -> Passkey");
var passkeyRegistrationRequest = Runtime.GetNSObject<ASPasskeyCredentialRequest>(registrationRequest.GetHandle());
await PrepareInterfaceForPasskeyRegistrationAsync(passkeyRegistrationRequest);
break;
default:
ClipLogger.Log($"PIFPR(IASC) -> Type not PA");
CancelRequest(ASExtensionErrorCode.Failed);
break;
}
}
catch (Exception ex)
{
OnProvidingCredentialException(ex);
}
}
private async Task PrepareInterfaceForPasskeyRegistrationAsync(ASPasskeyCredentialRequest passkeyRegistrationRequest)
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(17, 0) || passkeyRegistrationRequest?.CredentialIdentity is null)
{
ClipLogger.Log($"PIFPR Not iOS 17 or null passkey request/identity");
return;
}
InitAppIfNeeded();
if (!await IsAuthed())
{
ClipLogger.Log($"PIFPR Not Authed");
await _accountsManager.NavigateOnAccountChangeAsync(false);
return;
}
_context.PasskeyCredentialRequest = passkeyRegistrationRequest;
_context.IsCreatingPasskey = true;
var credIdentity = Runtime.GetNSObject<ASPasskeyCredentialIdentity>(passkeyRegistrationRequest.CredentialIdentity.GetHandle());
ClipLogger.Log($"PIFPR MakeCredentialAsync");
ClipLogger.Log($"PIFPR MakeCredentialAsync RpID: {credIdentity.RelyingPartyIdentifier}");
ClipLogger.Log($"PIFPR MakeCredentialAsync UserName: {credIdentity.UserName}");
ClipLogger.Log($"PIFPR MakeCredentialAsync UVP: {passkeyRegistrationRequest.UserVerificationPreference}");
ClipLogger.Log($"PIFPR MakeCredentialAsync SA: {passkeyRegistrationRequest.SupportedAlgorithms?.Select(a => (int)a)}");
ClipLogger.Log($"PIFPR MakeCredentialAsync UH: {credIdentity.UserHandle.GetBase64EncodedString(NSDataBase64EncodingOptions.None)}");
var result = await Fido2AuthService.MakeCredentialAsync(new Bit.Core.Utilities.Fido2.Fido2AuthenticatorMakeCredentialParams
{
Hash = passkeyRegistrationRequest.ClientDataHash.ToArray(),
CredTypesAndPubKeyAlgs = GetCredTypesAndPubKeyAlgs(passkeyRegistrationRequest.SupportedAlgorithms),
RequireUserVerification = passkeyRegistrationRequest.UserVerificationPreference == "required",
RequireResidentKey = true,
RpEntity = new PublicKeyCredentialRpEntity
{
Id = credIdentity.RelyingPartyIdentifier,
Name = credIdentity.RelyingPartyIdentifier
},
UserEntity = new PublicKeyCredentialUserEntity
{
Id = credIdentity.UserHandle.ToArray(),
Name = credIdentity.UserName,
DisplayName = credIdentity.UserName
}
});
await ASHelpers.ReplaceAllIdentitiesAsync();
ClipLogger.Log($"PIFPR Completing");
ClipLogger.Log($"PIFPR Completing - RpId: {credIdentity.RelyingPartyIdentifier}");
ClipLogger.Log($"PIFPR Completing - CDH: {passkeyRegistrationRequest.ClientDataHash.GetBase64EncodedString(NSDataBase64EncodingOptions.None)}");
ClipLogger.Log($"PIFPR Completing - CID: {Convert.ToBase64String(result.CredentialId, Base64FormattingOptions.None)}");
ClipLogger.Log($"PIFPR Completing - AO: {Convert.ToBase64String(result.AttestationObject, Base64FormattingOptions.None)}");
var expired = await ExtensionContext.CompleteRegistrationRequestAsync(new ASPasskeyRegistrationCredential(
credIdentity.RelyingPartyIdentifier,
passkeyRegistrationRequest.ClientDataHash,
NSData.FromArray(result.CredentialId),
NSData.FromArray(result.AttestationObject)));
ClipLogger.Log($"CompleteRegistrationRequestAsync: {expired}");
}
private PublicKeyCredentialParameters[] GetCredTypesAndPubKeyAlgs(NSNumber[] supportedAlgorithms)
{
if (supportedAlgorithms?.Any() != true)
{
return new PublicKeyCredentialParameters[]
{
new PublicKeyCredentialParameters
{
Type = Bit.Core.Constants.DefaultFido2CredentialType,
Alg = (int)Fido2AlgorithmIdentifier.ES256
},
new PublicKeyCredentialParameters
{
Type = Bit.Core.Constants.DefaultFido2CredentialType,
Alg = (int)Fido2AlgorithmIdentifier.RS256
}
};
}
return supportedAlgorithms
.Where(alg => (int)alg == (int)Fido2AlgorithmIdentifier.ES256)
.Select(alg => new PublicKeyCredentialParameters
{
Type = Bit.Core.Constants.DefaultFido2CredentialType,
Alg = (int)alg
}).ToArray();
}
public class UserInteractionRequiredException : Exception {}
private async Task ProvideCredentialWithoutUserInteractionAsync(ASPasskeyCredentialRequest passkeyCredentialRequest)
{
InitAppIfNeeded();
await _stateService.Value.SetPasswordRepromptAutofillAsync(false);
await _stateService.Value.SetPasswordVerifiedAutofillAsync(false);
_context.PasskeyCredentialRequest = passkeyCredentialRequest;
try {
await ProvideCredentialAsync(false);
} catch (UserInteractionRequiredException) {
CancelRequest(ASExtensionErrorCode.UserInteractionRequired);
}
}
public async Task CompleteAssertionRequestAsync(string rpId, NSData userHandleData, NSData credentialIdData, string cipherId)
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
OnProvidingCredentialException(new InvalidOperationException("Trying to complete assertion request before iOS 17"));
return;
}
if (_context.PasskeyCredentialRequest is null)
{
OnProvidingCredentialException(new InvalidOperationException("Trying to complete assertion request without a PasskeyCredentialRequest"));
return;
}
try
{
ClipLogger.Log($"ClientDataHash: {_context.PasskeyCredentialRequest.ClientDataHash}");
ClipLogger.Log($"ClientDataHash BA: {_context.PasskeyCredentialRequest.ClientDataHash.ToByteArray()}");
ClipLogger.Log($"ClientDataHash base64: {_context.PasskeyCredentialRequest.ClientDataHash.GetBase64EncodedString(NSDataBase64EncodingOptions.None)}");
ClipLogger.Log($"ClientDataHash base64 from bytes: {Convert.ToBase64String(_context.PasskeyCredentialRequest.ClientDataHash.ToByteArray(), Base64FormattingOptions.None)}");
var fido2AssertionResult = await Fido2AuthService.GetAssertionAsync(new Bit.Core.Utilities.Fido2.Fido2AuthenticatorGetAssertionParams
{
RpId = rpId,
Hash = _context.PasskeyCredentialRequest.ClientDataHash.ToArray(),
RequireUserVerification = _context.PasskeyCredentialRequest.UserVerificationPreference == "required",
RequireUserPresence = false,
AllowCredentialDescriptorList = new Bit.Core.Utilities.Fido2.PublicKeyCredentialDescriptor[]
{
new Bit.Core.Utilities.Fido2.PublicKeyCredentialDescriptor
{
Id = credentialIdData.ToArray()
}
}
});
_userInterface.UserPickedCredential(cipherId);
// if (os.PerformedFaceID) {
_userInterface.UserIsVerified();
//}
ClipLogger.Log("fido2AssertionResult:" + fido2AssertionResult);
var selectedUserHandleData = fido2AssertionResult.SelectedCredential != null
? NSData.FromArray(fido2AssertionResult.SelectedCredential.UserHandle)
: (NSData)userHandleData;
ClipLogger.Log("selectedUserHandleData:" + selectedUserHandleData);
var selectedCredentialIdData = fido2AssertionResult.SelectedCredential != null
? NSData.FromArray(fido2AssertionResult.SelectedCredential.Id)
: credentialIdData;
ClipLogger.Log("selectedCredentialIdData:" + selectedCredentialIdData);
await CompleteAssertionRequest(new ASPasskeyAssertionCredential(
selectedUserHandleData,
rpId,
NSData.FromArray(fido2AssertionResult.Signature),
_context.PasskeyCredentialRequest.ClientDataHash,
NSData.FromArray(fido2AssertionResult.AuthenticatorData),
selectedCredentialIdData
));
}
catch (InvalidOperationException)
{
ClipLogger.Log("CompleteAssertionRequestAsync -> InvalidOperationException NoOp");
return;
}
}
public async Task CompleteAssertionRequest(ASPasskeyAssertionCredential assertionCredential)
{
try
{
ClipLogger.Log("CompleteAssertionRequest(ASPasskeyAssertionCredential assertionCredential");
if (assertionCredential is null)
{
ClipLogger.Log("CompleteAssertionRequest(ASPasskeyAssertionCredential assertionCredential -> assertionCredential is null");
ServiceContainer.Reset();
CancelRequest(ASExtensionErrorCode.UserCanceled);
return;
}
//NSRunLoop.Main.BeginInvokeOnMainThread(() =>
//{
ServiceContainer.Reset();
#pragma warning disable CA1416 // Validate platform compatibility
ClipLogger.Log("CompleteAssertionRequest(ASPasskeyAssertionCredential assertionCredential -> completing");
var expired = await ExtensionContext.CompleteAssertionRequestAsync(assertionCredential);
//ExtensionContext.CompleteAssertionRequest(assertionCredential, expired =>
//{
// ClipLogger.Log($"ASExtensionContext?.CompleteAssertionRequest: {expired}");
//});
ClipLogger.Log($"CompleteAssertionRequest(ASPasskeyAssertionCredential assertionCredential -> Completed {expired}");
#pragma warning restore CA1416 // Validate platform compatibility
//});
}
catch (Exception ex)
{
ClipLogger.Log($"CompleteAssertionRequest(ASPasskeyAssertionCredential assertionCredential -> failed {ex}");
}
}
private bool CanProvideCredentialOnPasskeyRequest(CipherView cipherView)
{
return _context.PasskeyCredentialRequest != null && !cipherView.Login.HasFido2Credentials;
}
// IFido2UserInterface
public Task<Fido2PickCredentialResult> PickCredentialAsync(Fido2PickCredentialParams pickCredentialParams)
{
return Task.FromResult(new Fido2PickCredentialResult());
}
public Task InformExcludedCredential(string[] existingCipherIds)
{
return Task.CompletedTask;
}
public async Task<Fido2ConfirmNewCredentialResult> ConfirmNewCredentialAsync(Fido2ConfirmNewCredentialParams confirmNewCredentialParams)
{
// TODO: Show interface so the user can choose whether to create a new passkey or select one to add the passkey to.
var newCipher = new CipherView
{
Name = confirmNewCredentialParams.RpId,
Type = Bit.Core.Enums.CipherType.Login,
Login = new LoginView
{
Uris = new List<LoginUriView>
{
new LoginUriView
{
Uri = confirmNewCredentialParams.RpId
}
}
},
Card = new CardView(),
Identity = new IdentityView(),
SecureNote = new SecureNoteView
{
Type = Bit.Core.Enums.SecureNoteType.Generic
},
Reprompt = Bit.Core.Enums.CipherRepromptType.None
};
var encryptedCipher = await _cipherService.Value.EncryptAsync(newCipher);
await _cipherService.Value.SaveWithServerAsync(encryptedCipher);
return new Fido2ConfirmNewCredentialResult
{
CipherId = encryptedCipher.Id,
UserVerified = true
};
}
public async Task EnsureUnlockedVaultAsync()
{
if (_context.IsCreatingPasskey)
{
ClipLogger.Log($"EnsureUnlockedVaultAsync creating passkey");
if (!await IsLocked())
{
ClipLogger.Log($"EnsureUnlockedVaultAsync not locked");
return;
}
_context._unlockVaultTcs?.SetCanceled();
_context._unlockVaultTcs = new TaskCompletionSource<bool>();
MainThread.BeginInvokeOnMainThread(() =>
{
try
{
ClipLogger.Log($"EnsureUnlockedVaultAsync performing lock segue");
PerformSegue("lockPasswordSegue", this);
}
catch (Exception ex)
{
ClipLogger.Log($"EnsureUnlockedVaultAsync {ex}");
}
});
ClipLogger.Log($"EnsureUnlockedVaultAsync awaiting for unlock");
await _context._unlockVaultTcs.Task;
return;
}
ClipLogger.Log($"EnsureUnlockedVaultAsync Passkey selection");
if (!await IsAuthed() || await IsLocked())
{
CancelRequest(ASExtensionErrorCode.UserInteractionRequired);
throw new InvalidOperationException("Not authed or locked");
}
}
}
}

View File

@@ -20,7 +20,10 @@ using Foundation;
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Platform;
using ObjCRuntime;
using UIKit;
using static CoreFoundation.DispatchSource;
using static Microsoft.Maui.ApplicationModel.Permissions;
namespace Bit.iOS.Autofill
{
@@ -45,8 +48,12 @@ namespace Bit.iOS.Autofill
{
try
{
ClipLogger.Log("ViewDidLoad");
InitAppIfNeeded();
ClipLogger.Log("Inited");
base.ViewDidLoad();
Logo.Image = new UIImage(ThemeHelpers.LightTheme ? "logo.png" : "logo_white.png");
@@ -56,11 +63,12 @@ namespace Bit.iOS.Autofill
ExtContext = ExtensionContext
};
ClipLogger.Log("ViewDidLoad completed");
}
catch (Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
throw;
ClipLogger.Log($"ViewDidLoad ex: {ex}");
OnProvidingCredentialException(ex);
}
}
@@ -68,6 +76,7 @@ namespace Bit.iOS.Autofill
{
try
{
ClipLogger.Log("PrepareCredentialList(ASCredentialServiceIdentifier[] serviceIdentifiers");
InitAppIfNeeded();
_context.ServiceIdentifiers = serviceIdentifiers;
if (serviceIdentifiers.Length > 0)
@@ -101,59 +110,201 @@ namespace Bit.iOS.Autofill
}
catch (Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
throw;
OnProvidingCredentialException(ex);
}
}
public override async void ProvideCredentialWithoutUserInteraction(ASPasswordCredentialIdentity credentialIdentity)
[Export("prepareCredentialListForServiceIdentifiers:requestParameters:")]
public override async void PrepareCredentialList(ASCredentialServiceIdentifier[] serviceIdentifiers, ASPasskeyCredentialRequestParameters requestParameters)
{
try
{
ClipLogger.Log("PrepareCredentialList(ASCredentialServiceIdentifier[] serviceIdentifiers, ASPasskeyCredentialRequestParameters requestParameters");
InitAppIfNeeded();
await _stateService.Value.SetPasswordRepromptAutofillAsync(false);
await _stateService.Value.SetPasswordVerifiedAutofillAsync(false);
if (!await IsAuthed() || await IsLocked())
_context.ServiceIdentifiers = serviceIdentifiers;
if (serviceIdentifiers.Length > 0)
{
var err = new NSError(new NSString("ASExtensionErrorDomain"),
Convert.ToInt32(ASExtensionErrorCode.UserInteractionRequired), null);
ExtensionContext.CancelRequest(err);
return;
var uri = serviceIdentifiers[0].Identifier;
if (serviceIdentifiers[0].Type == ASCredentialServiceIdentifierType.Domain)
{
uri = string.Concat("https://", uri);
}
_context.UrlString = uri;
}
_context.CredentialIdentity = credentialIdentity;
await ProvideCredentialAsync(false);
}
catch (Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
throw;
}
}
public override async void PrepareInterfaceToProvideCredential(ASPasswordCredentialIdentity credentialIdentity)
{
try
{
InitAppIfNeeded();
if (!await IsAuthed())
{
await _accountsManager.NavigateOnAccountChangeAsync(false);
return;
}
_context.CredentialIdentity = credentialIdentity;
await CheckLockAsync(async () => await ProvideCredentialAsync());
else if (await IsLocked())
{
PerformSegue("lockPasswordSegue", this);
}
else
{
if (_context.ServiceIdentifiers == null || _context.ServiceIdentifiers.Length == 0)
{
PerformSegue("loginSearchSegue", this);
}
else
{
PerformSegue("loginListSegue", this);
}
}
}
catch (Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
throw;
OnProvidingCredentialException(ex);
}
}
[Export("provideCredentialWithoutUserInteractionForRequest:")]
public override async void ProvideCredentialWithoutUserInteraction(IASCredentialRequest credentialRequest)
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
return;
}
try
{
ClipLogger.Log("ProvideCredentialWithoutUserInteraction(IASCredentialRequest credentialRequest");
//ClipLogger.Log($"PCWUI(IASC) -> R: {credentialRequest?.GetType().FullName}");
//ClipLogger.Log($"PCWUI(IASC) -> I: {credentialRequest?.CredentialIdentity?.GetType().FullName}");
//ClipLogger.Log($"PCWUI(IASC) -> R k: {asPasskeyCredentialRequest?.GetType().FullName}");
//ClipLogger.Log($"PCWUI(IASC) -> I k: {asPasskeyCredentialRequest?.CredentialIdentity?.GetType().FullName}");
//var crType = asPasskeyCredentialRequest.GetType();
//foreach (var item in crType.GetProperties())
//{
// ClipLogger.Log($"PCWUI(IASC) -> R -> {item.Name} -- {item.PropertyType}");
//}
//var ciType = asPasskeyCredentialRequest.CredentialIdentity.GetType();
//foreach (var item in ciType.GetProperties())
//{
// ClipLogger.Log($"PCWUI(IASC) -> I -> {item.Name} -- {item.PropertyType}");
//}
switch (credentialRequest?.Type)
{
case ASCredentialRequestType.Password:
var passwordCredentialIdentity = Runtime.GetNSObject<ASPasswordCredentialIdentity>(credentialRequest.CredentialIdentity.GetHandle());
ClipLogger.Log($"PCWUI(IASC) -> Type P {passwordCredentialIdentity}");
await ProvideCredentialWithoutUserInteractionAsync(passwordCredentialIdentity);
break;
case ASCredentialRequestType.PasskeyAssertion:
var asPasskeyCredentialRequest = Runtime.GetNSObject<ASPasskeyCredentialRequest>(credentialRequest.GetHandle());
await ProvideCredentialWithoutUserInteractionAsync(asPasskeyCredentialRequest);
break;
default:
ClipLogger.Log($"PCWUI(IASC) -> Type not P nor PA");
CancelRequest(ASExtensionErrorCode.Failed);
break;
}
//switch (credentialRequest)
//{
// case ASPasswordCredentialRequest passwordRequest:
// await ProvideCredentialWithoutUserInteractionAsync(passwordRequest.CredentialIdentity as ASPasswordCredentialIdentity);
// break;
// case ASPasskeyCredentialRequest passkeyRequest:
// await ProvideCredentialWithoutUserInteractionAsync(passkeyRequest);
// break;
// default:
// CancelRequest(ASExtensionErrorCode.Failed);
// break;
//}
}
catch (Exception ex)
{
OnProvidingCredentialException(ex);
}
}
//public override async void ProvideCredentialWithoutUserInteraction(ASPasswordCredentialIdentity credentialIdentity)
//{
// try
// {
// ClipLogger.Log("ProvideCredentialWithoutUserInteraction(ASPasswordCredentialIdentity credentialIdentity");
// await ProvideCredentialWithoutUserInteractionAsync(credentialIdentity);
// }
// catch (Exception ex)
// {
// OnProvidingCredentialException(ex);
// }
//}
[Export("prepareInterfaceToProvideCredentialForRequest:")]
public override async void PrepareInterfaceToProvideCredential(IASCredentialRequest credentialRequest)
{
if (!UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
return;
}
try
{
ClipLogger.Log("PrepareInterfaceToProvideCredential(IASCredentialRequest credentialRequest");
switch (credentialRequest?.Type)
{
case ASCredentialRequestType.Password:
var passwordCredentialIdentity = Runtime.GetNSObject<ASPasswordCredentialIdentity>(credentialRequest.CredentialIdentity.GetHandle());
ClipLogger.Log($"PITPC(IASCR) -> Type P {credentialRequest.CredentialIdentity}");
await PrepareInterfaceToProvideCredentialAsync(c => c.PasswordCredentialIdentity = passwordCredentialIdentity);
break;
case ASCredentialRequestType.PasskeyAssertion:
var asPasskeyCredentialRequest = Runtime.GetNSObject<ASPasskeyCredentialRequest>(credentialRequest.GetHandle());
await PrepareInterfaceToProvideCredentialAsync(c => c.PasskeyCredentialRequest = asPasskeyCredentialRequest);
break;
default:
ClipLogger.Log($"PITPC(IASCR) -> Type not P nor PA");
CancelRequest(ASExtensionErrorCode.Failed);
break;
}
//switch (credentialRequest)
//{
// case ASPasswordCredentialRequest passwordRequest:
// //PrepareInterfaceToProvideCredential(passwordRequest.CredentialIdentity as ASPasswordCredentialIdentity);
// await PrepareInterfaceToProvideCredentialAsync(c => c.PasswordCredentialIdentity = passwordRequest.CredentialIdentity as ASPasswordCredentialIdentity);
// break;
// case ASPasskeyCredentialRequest passkeyRequest:
// await PrepareInterfaceToProvideCredentialAsync(c => c.PasskeyCredentialRequest = passkeyRequest);
// break;
// default:
// CancelRequest(ASExtensionErrorCode.Failed);
// break;
//}
}
catch (Exception ex)
{
OnProvidingCredentialException(ex);
}
}
//public override async void PrepareInterfaceToProvideCredential(ASPasswordCredentialIdentity credentialIdentity)
//{
// try
// {
// ClipLogger.Log("PrepareInterfaceToProvideCredential(ASPasswordCredentialIdentity credentialIdentity");
// await PrepareInterfaceToProvideCredentialAsync(c => c.PasswordCredentialIdentity = credentialIdentity);
// }
// catch (Exception ex)
// {
// OnProvidingCredentialException(ex);
// }
//}
public override async void PrepareInterfaceForExtensionConfiguration()
{
try
{
ClipLogger.Log("PrepareInterfaceForExtensionConfiguration");
InitAppIfNeeded();
_context.Configuring = true;
if (!await IsAuthed())
@@ -165,14 +316,44 @@ namespace Bit.iOS.Autofill
}
catch (Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
throw;
OnProvidingCredentialException(ex);
}
}
private async Task ProvideCredentialWithoutUserInteractionAsync(ASPasswordCredentialIdentity credentialIdentity)
{
ClipLogger.Log("ProvideCredentialWithoutUserInteractionAsync(ASPasswordCredentialIdentity credentialIdentity");
InitAppIfNeeded();
await _stateService.Value.SetPasswordRepromptAutofillAsync(false);
await _stateService.Value.SetPasswordVerifiedAutofillAsync(false);
if (!await IsAuthed() || await IsLocked())
{
var err = new NSError(new NSString("ASExtensionErrorDomain"),
Convert.ToInt32(ASExtensionErrorCode.UserInteractionRequired), null);
ExtensionContext.CancelRequest(err);
return;
}
_context.PasswordCredentialIdentity = credentialIdentity;
await ProvideCredentialAsync(false);
}
private async Task PrepareInterfaceToProvideCredentialAsync(Action<Context> updateContext)
{
ClipLogger.Log("PrepareInterfaceToProvideCredentialAsync(Action<Context> updateContext");
InitAppIfNeeded();
if (!await IsAuthed())
{
await _accountsManager.NavigateOnAccountChangeAsync(false);
return;
}
updateContext(_context);
await CheckLockAsync(async () => await ProvideCredentialAsync());
}
public void CompleteRequest(string id = null, string username = null,
string password = null, string totp = null)
{
ClipLogger.Log("CompleteRequest");
if ((_context?.Configuring ?? true) && string.IsNullOrWhiteSpace(password))
{
ServiceContainer.Reset();
@@ -207,10 +388,25 @@ namespace Bit.iOS.Autofill
});
}
private void OnProvidingCredentialException(Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
CancelRequest(ASExtensionErrorCode.Failed);
}
private void CancelRequest(ASExtensionErrorCode code)
{
ClipLogger.Log("CancelRequest" + code);
//var err = new NSError(new NSString("ASExtensionErrorDomain"), Convert.ToInt32(code), null);
var err = new NSError(ASExtensionErrorCodeExtensions.GetDomain(code), (int)code);
ExtensionContext?.CancelRequest(err);
}
public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
try
{
ClipLogger.Log("Preparing for Segue");
if (segue.DestinationViewController is UINavigationController navController)
{
if (navController.TopViewController is LoginListViewController listLoginController)
@@ -245,18 +441,19 @@ namespace Bit.iOS.Autofill
}
catch (Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
throw;
OnProvidingCredentialException(ex);
}
}
public async void DismissLockAndContinue()
public void DismissLockAndContinue()
{
ClipLogger.Log("DismissLockAndContinue");
DismissViewController(false, async () => await OnLockDismissedAsync());
}
private void NavigateToPage(ContentPage page)
{
ClipLogger.Log("NavigateToPage" + page.GetType().FullName);
var navigationPage = new NavigationPage(page);
var uiController = navigationPage.ToUIViewController(MauiContextSingleton.Instance.MauiContext);
uiController.ModalPresentationStyle = UIModalPresentationStyle.FullScreen;
@@ -268,90 +465,136 @@ namespace Bit.iOS.Autofill
{
try
{
if (_context.CredentialIdentity != null)
ClipLogger.Log("OnLockDismissedAsync");
if (_context.IsCreatingPasskey)
{
ClipLogger.Log("OnLockDismissedAsync -> IsCreatingPasskey");
_context._unlockVaultTcs.SetResult(true);
return;
}
if (_context.PasswordCredentialIdentity != null || _context.IsPasskey)
{
ClipLogger.Log("OnLockDismissedAsync -> ProvideCredentialAsync");
await MainThread.InvokeOnMainThreadAsync(() => ProvideCredentialAsync());
return;
}
if (_context.Configuring)
{
ClipLogger.Log("OnLockDismissedAsync -> Configuring");
await MainThread.InvokeOnMainThreadAsync(() => PerformSegue("setupSegue", this));
return;
}
if (_context.ServiceIdentifiers == null || _context.ServiceIdentifiers.Length == 0)
{
ClipLogger.Log("OnLockDismissedAsync -> loginSearchSegue");
await MainThread.InvokeOnMainThreadAsync(() => PerformSegue("loginSearchSegue", this));
}
else
{
ClipLogger.Log("OnLockDismissedAsync -> loginListSegue");
await MainThread.InvokeOnMainThreadAsync(() => PerformSegue("loginListSegue", this));
}
}
catch (Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
throw;
OnProvidingCredentialException(ex);
}
}
private async Task ProvideCredentialAsync(bool userInteraction = true)
{
_userInterface.WithEnsureUnlockedVaultAsyncCallback(async () => {
if (!userInteraction && (!await IsAuthed() || await IsLocked())) {
throw new UserInteractionRequiredException();
}
await EnsureUnlockedVaultAsync();
});
try
{
var cipherService = ServiceContainer.Resolve<ICipherService>("cipherService", true);
Bit.Core.Models.Domain.Cipher cipher = null;
var cancel = cipherService == null || _context.CredentialIdentity?.RecordIdentifier == null;
if (!cancel)
ClipLogger.Log("ProvideCredentialAsync");
if (_context.IsPasskey && UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
cipher = await cipherService.GetAsync(_context.CredentialIdentity.RecordIdentifier);
cancel = cipher == null || cipher.Type != Bit.Core.Enums.CipherType.Login || cipher.Login == null;
if (_context.PasskeyCredentialIdentity is null)
{
ClipLogger.Log("ProvideCredentialAsync -> IsPasskey failed");
CancelRequest(ASExtensionErrorCode.Failed);
}
ClipLogger.Log("ProvideCredentialAsync -> IsPasskey");
ClipLogger.Log($"ProvideCredentialAsync -> IsPasskey - RP: {_context.PasskeyCredentialIdentity.RelyingPartyIdentifier}");
ClipLogger.Log($"ProvideCredentialAsync -> IsPasskey - UH: {_context.PasskeyCredentialIdentity.UserHandle}");
ClipLogger.Log($"ProvideCredentialAsync -> IsPasskey - CID: {_context.PasskeyCredentialIdentity.CredentialId}");
ClipLogger.Log($"ProvideCredentialAsync -> IsPasskey - RI: {_context.RecordIdentifier}");
await CompleteAssertionRequestAsync(_context.PasskeyCredentialIdentity.RelyingPartyIdentifier,
_context.PasskeyCredentialIdentity.UserHandle,
_context.PasskeyCredentialIdentity.CredentialId,
_context.RecordIdentifier);
return;
}
if (cancel)
if (!ServiceContainer.TryResolve<ICipherService>(out var cipherService)
||
_context.RecordIdentifier == null)
{
var err = new NSError(new NSString("ASExtensionErrorDomain"),
Convert.ToInt32(ASExtensionErrorCode.CredentialIdentityNotFound), null);
ExtensionContext?.CancelRequest(err);
ClipLogger.Log("ProvideCredentialAsync -> CredentialIdentityNotFound");
CancelRequest(ASExtensionErrorCode.CredentialIdentityNotFound);
return;
}
ClipLogger.Log("ProvideCredentialAsync -> IsPassword");
var cipher = await cipherService.GetAsync(_context.RecordIdentifier);
if (cipher?.Login is null || cipher.Type != CipherType.Login)
{
CancelRequest(ASExtensionErrorCode.CredentialIdentityNotFound);
return;
}
var decCipher = await cipher.DecryptAsync();
if (decCipher.Reprompt != Bit.Core.Enums.CipherRepromptType.None)
if (!CanProvideCredentialOnPasskeyRequest(decCipher))
{
CancelRequest(ASExtensionErrorCode.CredentialIdentityNotFound);
return;
}
if (decCipher.Reprompt != CipherRepromptType.None)
{
// Prompt for password using either the lock screen or dialog unless
// already verified the password.
if (!userInteraction)
{
await _stateService.Value.SetPasswordRepromptAutofillAsync(true);
var err = new NSError(new NSString("ASExtensionErrorDomain"),
Convert.ToInt32(ASExtensionErrorCode.UserInteractionRequired), null);
ExtensionContext?.CancelRequest(err);
CancelRequest(ASExtensionErrorCode.UserInteractionRequired);
return;
}
else if (!await _stateService.Value.GetPasswordVerifiedAutofillAsync())
if (!await _stateService.Value.GetPasswordVerifiedAutofillAsync())
{
// Add a timeout to resolve keyboard not always showing up.
await Task.Delay(250);
var passwordRepromptService = ServiceContainer.Resolve<IPasswordRepromptService>("passwordRepromptService");
var passwordRepromptService = ServiceContainer.Resolve<IPasswordRepromptService>();
if (!await passwordRepromptService.PromptAndCheckPasswordIfNeededAsync())
{
var err = new NSError(new NSString("ASExtensionErrorDomain"),
Convert.ToInt32(ASExtensionErrorCode.UserCanceled), null);
ExtensionContext?.CancelRequest(err);
CancelRequest(ASExtensionErrorCode.UserCanceled);
return;
}
}
}
string totpCode = null;
var disableTotpCopy = await _stateService.Value.GetDisableAutoTotpCopyAsync();
if (!disableTotpCopy.GetValueOrDefault(false))
if (await _stateService.Value.GetDisableAutoTotpCopyAsync() != true)
{
var canAccessPremiumAsync = await _stateService.Value.CanAccessPremiumAsync();
if (!string.IsNullOrWhiteSpace(decCipher.Login.Totp) &&
(canAccessPremiumAsync || cipher.OrganizationUseTotp))
if (!string.IsNullOrWhiteSpace(decCipher.Login.Totp)
&&
(cipher.OrganizationUseTotp || await _stateService.Value.CanAccessPremiumAsync()))
{
var totpService = ServiceContainer.Resolve<ITotpService>("totpService");
totpCode = await totpService.GetCodeAsync(decCipher.Login.Totp);
totpCode = await ServiceContainer.Resolve<ITotpService>().GetCodeAsync(decCipher.Login.Totp);
}
}
@@ -359,13 +602,13 @@ namespace Bit.iOS.Autofill
}
catch (Exception ex)
{
LoggerHelper.LogEvenIfCantBeResolved(ex);
throw;
OnProvidingCredentialException(ex);
}
}
private async Task CheckLockAsync(Action notLockedAction)
{
ClipLogger.Log("CheckLockAsync");
if (await IsLocked() || await _stateService.Value.GetPasswordRepromptAutofillAsync())
{
DispatchQueue.MainQueue.DispatchAsync(() => PerformSegue("lockPasswordSegue", this));
@@ -389,6 +632,7 @@ namespace Bit.iOS.Autofill
private void LogoutIfAuthed()
{
ClipLogger.Log("LogoutIfAuthed");
NSRunLoop.Main.BeginInvokeOnMainThread(async () =>
{
try
@@ -411,12 +655,14 @@ namespace Bit.iOS.Autofill
private void InitApp()
{
ClipLogger.Log("InitApp");
iOSCoreHelpers.InitApp(this, Bit.Core.Constants.iOSAutoFillClearCiphersCacheKey,
_nfcSession, out _nfcDelegate, out _accountsManager);
}
private void InitAppIfNeeded()
{
ClipLogger.Log("InitAppIfNeeded");
if (ServiceContainer.RegisteredServices == null || ServiceContainer.RegisteredServices.Count == 0)
{
InitApp();
@@ -614,6 +860,7 @@ namespace Bit.iOS.Autofill
public void Navigate(NavigationTarget navTarget, INavigationParams navParams = null)
{
ClipLogger.Log("Navigate" + navTarget);
switch (navTarget)
{
case NavigationTarget.HomeLogin:

View File

@@ -93,8 +93,15 @@
<string>com.apple.authentication-services-credential-provider-ui</string>
<key>NSExtensionAttributes</key>
<dict>
<key>ASCredentialProviderExtensionShowsConfigurationUI</key>
<true/>
<key>ASCredentialProviderExtensionCapabilities</key>
<dict>
<key>ProvidesPasskeys</key>
<true/>
<key>ProvidesPasswords</key>
<true/>
<key>ShowsConfigurationUI</key>
<true/>
</dict>
</dict>
</dict>
</dict>

View File

@@ -62,7 +62,7 @@ namespace Bit.iOS.Autofill
Core.Constants.AutofillNeedsIdentityReplacementKey);
if (needsAutofillReplacement.GetValueOrDefault())
{
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
_accountSwitchingOverlayHelper = new AccountSwitchingOverlayHelper();

View File

@@ -1,6 +1,9 @@
using AuthenticationServices;
using System.Threading.Tasks;
using AuthenticationServices;
using Bit.iOS.Core.Models;
using Foundation;
using ObjCRuntime;
using UIKit;
namespace Bit.iOS.Autofill.Models
{
@@ -8,7 +11,42 @@ namespace Bit.iOS.Autofill.Models
{
public NSExtensionContext ExtContext { get; set; }
public ASCredentialServiceIdentifier[] ServiceIdentifiers { get; set; }
public ASPasswordCredentialIdentity CredentialIdentity { get; set; }
public ASPasswordCredentialIdentity PasswordCredentialIdentity { get; set; }
public ASPasskeyCredentialRequest PasskeyCredentialRequest { get; set; }
public bool Configuring { get; set; }
public bool IsCreatingPasskey { get; set; }
public TaskCompletionSource<bool> _unlockVaultTcs { get; set; }
public ASPasskeyCredentialIdentity PasskeyCredentialIdentity
{
get
{
if (PasskeyCredentialRequest != null && UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
return Runtime.GetNSObject<ASPasskeyCredentialIdentity>(PasskeyCredentialRequest.CredentialIdentity.GetHandle());
}
return null;
}
}
public string? RecordIdentifier
{
get
{
if (PasswordCredentialIdentity?.RecordIdentifier is string id)
{
return id;
}
if (UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
return PasskeyCredentialIdentity?.RecordIdentifier;
}
return null;
}
}
public bool IsPasskey => PasskeyCredentialRequest != null;
}
}

View File

@@ -31,7 +31,7 @@ namespace Bit.iOS.Autofill
BackButton.Title = AppResources.Back;
base.ViewDidLoad();
var task = ASHelpers.ReplaceAllIdentities();
var task = ASHelpers.ReplaceAllIdentitiesAsync();
}
partial void BackButton_Activated(UIBarButtonItem sender)

View File

@@ -81,6 +81,7 @@
<Compile Include="Models\Context.cs" />
<BundleResource Include="Resources\MaterialIcons_Regular.ttf" />
<BundleResource Include="Resources\bwi-font.ttf" />
<Compile Include="CredentialProviderViewController.Passkeys.cs" />
</ItemGroup>
<ItemGroup>
<BundleResource Include="Resources\check.png" />

View File

@@ -188,18 +188,17 @@ namespace Bit.iOS.Core.Controllers
await _cipherService.SaveWithServerAsync(cipherDomain);
await loadingAlert.DismissViewControllerAsync(true);
await _storageService.SaveAsync(Bit.Core.Constants.ClearCiphersCacheKey, true);
if (await ASHelpers.IdentitiesCanIncremental())
if (await ASHelpers.IdentitiesSupportIncrementalAsync())
{
var identity = await ASHelpers.GetCipherIdentityAsync(cipherDomain.Id);
var identity = await ASHelpers.GetCipherPasswordIdentityAsync(cipherDomain.Id);
if (identity != null)
{
await ASCredentialIdentityStore.SharedStore.SaveCredentialIdentitiesAsync(
new ASPasswordCredentialIdentity[] { identity });
await ASCredentialIdentityStoreExtensions.SaveCredentialIdentitiesAsync(identity);
}
}
else
{
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
Success(cipherDomain.Id);
}
@@ -229,7 +228,7 @@ namespace Bit.iOS.Core.Controllers
var appOptions = new AppOptions { IosExtension = true };
var app = new App.App(appOptions);
var generatorPage = new GeneratorPage(false, selectAction: async (username) =>
var generatorPage = new GeneratorPage(false, selectAction: (username) =>
{
UsernameCell.TextField.Text = username;
DismissViewController(false, null);

View File

@@ -11,9 +11,11 @@ namespace Bit.iOS.Core.Services
{
public bool SupportsAutofillService() => false;
public bool AutofillServiceEnabled() => false;
public void DisableCredentialProviderService() => throw new NotImplementedException();
public void Autofill(CipherView cipher) => throw new NotImplementedException();
public bool AutofillAccessibilityOverlayPermitted() => false;
public bool AutofillAccessibilityServiceRunning() => false;
public bool CredentialProviderServiceEnabled() => throw new NotImplementedException();
public bool AutofillServicesEnabled() => false;
public void CloseAutofill() => throw new NotImplementedException();
public void DisableAutofillService() => throw new NotImplementedException();

View File

@@ -301,6 +301,8 @@ namespace Bit.iOS.Core.Services
throw new NotImplementedException();
}
public void OpenCredentialProviderSettings() => throw new NotImplementedException();
public void OpenAutofillSettings()
{
throw new NotImplementedException();
@@ -339,6 +341,8 @@ namespace Bit.iOS.Core.Services
return false;
}
public bool SupportsCredentialProviderService() => throw new NotImplementedException();
public bool SupportsAutofillServices() => UIDevice.CurrentDevice.CheckSystemVersion(12, 0);
public bool SupportsInlineAutofill() => false;
public bool SupportsDrawOver() => false;
@@ -375,7 +379,7 @@ namespace Bit.iOS.Core.Services
public async Task OnAccountSwitchCompleteAsync()
{
await ASHelpers.ReplaceAllIdentities();
await ASHelpers.ReplaceAllIdentitiesAsync();
}
public Task SetScreenCaptureAllowedAsync()

View File

@@ -0,0 +1,39 @@
using AuthenticationServices;
using Foundation;
using UIKit;
namespace Bit.iOS.Core.Utilities
{
public static class ASCredentialIdentityStoreExtensions
{
/// <summary>
/// Saves password credential identities to the shared store of <see cref="ASCredentialIdentityStore"/>
/// Note: This is added to provide the proper method depending on the OS version.
/// </summary>
/// <param name="identities">Password identities to save</param>
public static Task<Tuple<bool, NSError>> SaveCredentialIdentitiesAsync(params ASPasswordCredentialIdentity[] identities)
{
if (UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
return ASCredentialIdentityStore.SharedStore.SaveCredentialIdentityEntriesAsync(identities);
}
return ASCredentialIdentityStore.SharedStore.SaveCredentialIdentitiesAsync(identities);
}
/// <summary>
/// Removes password credential identities of the shared store of <see cref="ASCredentialIdentityStore"/>
/// Note: This is added to provide the proper method depending on the OS version.
/// </summary>
/// <param name="identities">Password identities to remove</param>
public static Task<Tuple<bool, NSError>> RemoveCredentialIdentitiesAsync(params ASPasswordCredentialIdentity[] identities)
{
if (UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
return ASCredentialIdentityStore.SharedStore.RemoveCredentialIdentityEntriesAsync(identities);
}
return ASCredentialIdentityStore.SharedStore.RemoveCredentialIdentitiesAsync(identities);
}
}
}

View File

@@ -1,93 +1,125 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AuthenticationServices;
using AuthenticationServices;
using Bit.Core.Abstractions;
using Bit.Core.Enums;
using Bit.Core.Models.View;
using Bit.Core.Utilities;
using Foundation;
using UIKit;
namespace Bit.iOS.Core.Utilities
{
public static class ASHelpers
{
public static async Task ReplaceAllIdentities()
public static async Task ReplaceAllIdentitiesAsync()
{
if (await AutofillEnabled())
if (!await IsAutofillEnabledAsync())
{
var storageService = ServiceContainer.Resolve<IStorageService>("storageService");
var stateService = ServiceContainer.Resolve<IStateService>("stateService");
var timeoutAction = await stateService.GetVaultTimeoutActionAsync();
if (timeoutAction == VaultTimeoutAction.Logout)
{
await ASCredentialIdentityStore.SharedStore?.RemoveAllCredentialIdentitiesAsync();
return;
}
var vaultTimeoutService = ServiceContainer.Resolve<IVaultTimeoutService>("vaultTimeoutService");
if (await vaultTimeoutService.IsLockedAsync())
{
await ASCredentialIdentityStore.SharedStore?.RemoveAllCredentialIdentitiesAsync();
await storageService.SaveAsync(Constants.AutofillNeedsIdentityReplacementKey, true);
return;
}
var cipherService = ServiceContainer.Resolve<ICipherService>("cipherService");
var identities = new List<ASPasswordCredentialIdentity>();
var ciphers = await cipherService.GetAllDecryptedAsync();
foreach (var cipher in ciphers.Where(x => !x.IsDeleted))
{
var identity = ToCredentialIdentity(cipher);
if (identity != null)
{
identities.Add(identity);
}
}
if (identities.Any())
{
await ASCredentialIdentityStore.SharedStore?.ReplaceCredentialIdentitiesAsync(identities.ToArray());
await storageService.SaveAsync(Constants.AutofillNeedsIdentityReplacementKey, false);
return;
}
await ASCredentialIdentityStore.SharedStore?.RemoveAllCredentialIdentitiesAsync();
return;
}
var storageService = ServiceContainer.Resolve<IStorageService>("storageService");
var stateService = ServiceContainer.Resolve<IStateService>();
var timeoutAction = await stateService.GetVaultTimeoutActionAsync();
if (timeoutAction == VaultTimeoutAction.Logout)
{
await ASCredentialIdentityStore.SharedStore.RemoveAllCredentialIdentitiesAsync();
return;
}
var vaultTimeoutService = ServiceContainer.Resolve<IVaultTimeoutService>();
if (await vaultTimeoutService.IsLockedAsync())
{
await ASCredentialIdentityStore.SharedStore.RemoveAllCredentialIdentitiesAsync();
await storageService.SaveAsync(Constants.AutofillNeedsIdentityReplacementKey, true);
return;
}
var cipherService = ServiceContainer.Resolve<ICipherService>();
if (UIDevice.CurrentDevice.CheckSystemVersion(17, 0))
{
await ReplaceAllIdentitiesIOS17Async(cipherService, storageService);
}
else
{
await ReplaceAllIdentitiesIOS12Async(cipherService, storageService);
}
}
public static async Task<bool> IdentitiesCanIncremental()
private static async Task ReplaceAllIdentitiesIOS12Async(ICipherService cipherService, IStorageService storageService)
{
var stateService = ServiceContainer.Resolve<IStateService>("stateService");
var ciphers = await cipherService.GetAllDecryptedAsync();
var identities = ciphers.Where(c => !c.IsDeleted)
.Select(ToPasswordCredentialIdentity)
.Where(i => i != null)
.Cast<ASPasswordCredentialIdentity>()
.ToList();
if (!identities.Any())
{
await ASCredentialIdentityStore.SharedStore.RemoveAllCredentialIdentitiesAsync();
return;
}
#pragma warning disable CA1422 // Validate platform compatibility
await ASCredentialIdentityStore.SharedStore.ReplaceCredentialIdentitiesAsync(identities.ToArray());
#pragma warning restore CA1422 // Validate platform compatibility
await storageService.SaveAsync(Constants.AutofillNeedsIdentityReplacementKey, false);
}
private static async Task ReplaceAllIdentitiesIOS17Async(ICipherService cipherService, IStorageService storageService)
{
var ciphers = await cipherService.GetAllDecryptedAsync();
var identities = ciphers.Where(c => !c.IsDeleted)
.Select(ToCredentialIdentity)
.Where(i => i != null)
.Cast<IASCredentialIdentity>()
.ToList();
if (!identities.Any())
{
await ASCredentialIdentityStore.SharedStore.RemoveAllCredentialIdentitiesAsync();
return;
}
await ASCredentialIdentityStore.SharedStore.ReplaceCredentialIdentityEntriesAsync(identities.ToArray());
await storageService.SaveAsync(Constants.AutofillNeedsIdentityReplacementKey, false);
}
public static async Task<bool> IdentitiesSupportIncrementalAsync()
{
var stateService = ServiceContainer.Resolve<IStateService>();
var timeoutAction = await stateService.GetVaultTimeoutActionAsync();
if (timeoutAction == VaultTimeoutAction.Logout)
{
return false;
}
var state = await ASCredentialIdentityStore.SharedStore?.GetCredentialIdentityStoreStateAsync();
var state = await ASCredentialIdentityStore.SharedStore.GetCredentialIdentityStoreStateAsync();
return state != null && state.Enabled && state.SupportsIncrementalUpdates;
}
public static async Task<bool> AutofillEnabled()
public static async Task<bool> IsAutofillEnabledAsync()
{
var state = await ASCredentialIdentityStore.SharedStore?.GetCredentialIdentityStoreStateAsync();
var state = await ASCredentialIdentityStore.SharedStore.GetCredentialIdentityStoreStateAsync();
return state != null && state.Enabled;
}
public static async Task<ASPasswordCredentialIdentity> GetCipherIdentityAsync(string cipherId)
public static async Task<ASPasswordCredentialIdentity?> GetCipherPasswordIdentityAsync(string cipherId)
{
var cipherService = ServiceContainer.Resolve<ICipherService>("cipherService");
var cipherService = ServiceContainer.Resolve<ICipherService>();
var cipher = await cipherService.GetAsync(cipherId);
if (cipher == null)
{
return null;
}
var cipherView = await cipher.DecryptAsync();
return ToCredentialIdentity(cipherView);
return ToPasswordCredentialIdentity(cipherView);
}
public static ASPasswordCredentialIdentity ToCredentialIdentity(CipherView cipher)
public static ASPasswordCredentialIdentity? ToPasswordCredentialIdentity(CipherView cipher)
{
if (!cipher?.Login?.Uris?.Any() ?? true)
if (cipher?.Login?.Uris?.Any() != true)
{
return null;
}
var uri = cipher.Login.Uris.FirstOrDefault(u => u.Match != Bit.Core.Enums.UriMatchType.Never)?.Uri;
var uri = cipher.Login.Uris.FirstOrDefault(u => u.Match != UriMatchType.Never)?.Uri;
if (string.IsNullOrWhiteSpace(uri))
{
return null;
@@ -100,5 +132,24 @@ namespace Bit.iOS.Core.Utilities
var serviceId = new ASCredentialServiceIdentifier(uri, ASCredentialServiceIdentifierType.Url);
return new ASPasswordCredentialIdentity(serviceId, username, cipher.Id);
}
public static IASCredentialIdentity? ToCredentialIdentity(CipherView cipher)
{
if (!cipher.HasFido2Credential)
{
return ToPasswordCredentialIdentity(cipher);
}
if (!cipher.Login.MainFido2Credential.DiscoverableValue)
{
return null;
}
return new ASPasskeyCredentialIdentity(cipher.Login.MainFido2Credential.RpId,
cipher.Login.MainFido2Credential.UserName,
NSData.FromArray(cipher.Login.MainFido2Credential.CredentialId.GuidToRawFormat()),
cipher.Login.MainFido2Credential.UserHandle,
cipher.Id);
}
}
}

View File

@@ -0,0 +1,15 @@
using System.Runtime.InteropServices;
using Foundation;
namespace Bit.iOS.Core.Utilities
{
public static class NSDataExtensions
{
public static byte[] ToByteArray(this NSData data)
{
var bytes = new byte[data.Length];
Marshal.Copy(data.Bytes, bytes, 0, Convert.ToInt32(data.Length));
return bytes;
}
}
}

View File

@@ -123,7 +123,7 @@ namespace Bit.iOS.Core.Utilities
else
{
#if DEBUG
logger = DebugLogger.Instance;
logger = ClipLogger.Instance;
#else
logger = Logger.Instance;
#endif
@@ -138,6 +138,7 @@ namespace Bit.iOS.Core.Utilities
logger!.Exception(nreAppGroupContainer);
throw nreAppGroupContainer;
}
var liteDbStorage = new LiteDbStorageService(
Path.Combine(appGroupContainer.Path, "Library", "bitwarden.db"));
var localizeService = new LocalizeService();
@@ -189,6 +190,11 @@ namespace Bit.iOS.Core.Utilities
public static void RegisterFinallyBeforeBootstrap()
{
ServiceContainer.Register<IFido2AuthenticatorService>(new Fido2AuthenticatorService(
ServiceContainer.Resolve<ICipherService>(),
ServiceContainer.Resolve<ISyncService>(),
ServiceContainer.Resolve<ICryptoFunctionService>()));
ServiceContainer.Register<IWatchDeviceService>(new WatchDeviceService(ServiceContainer.Resolve<ICipherService>(),
ServiceContainer.Resolve<IEnvironmentService>(),
ServiceContainer.Resolve<IStateService>(),

View File

@@ -13,6 +13,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.0" />
<PackageReference Include="NSubstitute" Version="5.0.0" />
<PackageReference Include="System.Formats.Cbor" Version="8.0.0" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>

View File

@@ -0,0 +1,373 @@
using System;
using System.Threading.Tasks;
using Bit.Core.Abstractions;
using Bit.Core.Services;
using Bit.Core.Models.Domain;
using Bit.Core.Models.View;
using Bit.Core.Enums;
using Bit.Core.Utilities.Fido2;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Xunit;
using Bit.Core.Utilities;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
namespace Bit.Core.Test.Services
{
public class Fido2AuthenticatorGetAssertionTests : IDisposable
{
private readonly string _rpId = "bitwarden.com";
private readonly SutProvider<Fido2AuthenticatorService> _sutProvider = new SutProvider<Fido2AuthenticatorService>().Create();
private readonly IFido2UserInterface _userInterface = Substitute.For<IFido2UserInterface>();
private List<Guid> _credentialIds;
private List<CipherView> _ciphers;
private Fido2AuthenticatorGetAssertionParams _params;
private CipherView _selectedCipher;
/// <summary>
/// Sets up a working environment for the tests.
/// </summary>
public Fido2AuthenticatorGetAssertionTests()
{
_credentialIds = [ Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() ];
_ciphers = [
CreateCipherView(_credentialIds[0].ToString(), _rpId, false),
CreateCipherView(_credentialIds[1].ToString(), _rpId, true),
];
_selectedCipher = _ciphers[0];
_params = CreateParams(
rpId: _rpId,
allowCredentialDescriptorList: [
new PublicKeyCredentialDescriptor {
Id = _credentialIds[0].ToByteArray(),
Type = "public-key"
},
new PublicKeyCredentialDescriptor {
Id = _credentialIds[1].ToByteArray(),
Type = "public-key"
},
],
requireUserVerification: false
);
_sutProvider.GetDependency<ICipherService>().GetAllDecryptedAsync().Returns(_ciphers);
_userInterface.PickCredentialAsync(Arg.Any<Fido2PickCredentialParams>()).Returns(new Fido2PickCredentialResult {
CipherId = _ciphers[0].Id,
UserVerified = false
});
_sutProvider.Sut.Init(_userInterface);
}
public void Dispose()
{
}
#region missing non-discoverable credential
[Fact]
// Spec: If credentialOptions is now empty, return an error code equivalent to "NotAllowedError" and terminate the operation.
public async Task GetAssertionAsync_ThrowsNotAllowed_NoCredentialsExists()
{
// Arrange
_ciphers.Clear();
// Act & Assert
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.GetAssertionAsync(_params));
}
[Fact]
public async Task GetAssertionAsync_ThrowsNotAllowed_CredentialExistsButRpIdDoesNotMatch()
{
// Arrange
_params.RpId = "mismatch-rpid";
// Act & Assert
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.GetAssertionAsync(_params));
}
#endregion
#region vault contains credential
[Fact]
public async Task GetAssertionAsync_AsksForAllCredentials_ParamsContainsAllowedCredentialsList()
{
// Arrange
_params.AllowCredentialDescriptorList = [
new PublicKeyCredentialDescriptor {
Id = _credentialIds[0].ToByteArray(),
Type = "public-key"
},
new PublicKeyCredentialDescriptor {
Id = _credentialIds[1].ToByteArray(),
Type = "public-key"
},
];
// Act
await _sutProvider.Sut.GetAssertionAsync(_params);
// Assert
await _userInterface.Received().PickCredentialAsync(Arg.Is<Fido2PickCredentialParams>(
(pickCredentialParams) => pickCredentialParams.CipherIds.SequenceEqual(_ciphers.Select((cipher) => cipher.Id))
));
}
[Fact]
public async Task GetAssertionAsync_AsksForDiscoverableCredentials_ParamsDoesNotContainAllowedCredentialsList()
{
// Arrange
_params.AllowCredentialDescriptorList = null;
var discoverableCiphers = _ciphers.Where((cipher) => cipher.Login.MainFido2Credential.DiscoverableValue).ToList();
_userInterface.PickCredentialAsync(Arg.Any<Fido2PickCredentialParams>()).Returns(new Fido2PickCredentialResult {
CipherId = discoverableCiphers[0].Id,
UserVerified = false
});
// Act
await _sutProvider.Sut.GetAssertionAsync(_params);
// Assert
await _userInterface.Received().PickCredentialAsync(Arg.Is<Fido2PickCredentialParams>(
(pickCredentialParams) => pickCredentialParams.CipherIds.SequenceEqual(discoverableCiphers.Select((cipher) => cipher.Id))
));
}
[Fact]
// Spec: Prompt the user to select a public key credential source `selectedCredential` from `credentialOptions`.
// If requireUserVerification is true, the authorization gesture MUST include user verification.
public async Task GetAssertionAsync_RequestsUserVerification_ParamsRequireUserVerification() {
// Arrange
_params.RequireUserVerification = true;
_userInterface.PickCredentialAsync(Arg.Any<Fido2PickCredentialParams>()).Returns(new Fido2PickCredentialResult {
CipherId = _ciphers[0].Id,
UserVerified = true
});
// Act
await _sutProvider.Sut.GetAssertionAsync(_params);
// Assert
await _userInterface.Received().PickCredentialAsync(Arg.Is<Fido2PickCredentialParams>(
(pickCredentialParams) => pickCredentialParams.UserVerification == true
));
}
[Fact]
// Spec: Prompt the user to select a public key credential source `selectedCredential` from `credentialOptions`.
// If `requireUserPresence` is true, the authorization gesture MUST include a test of user presence.
// Comment: User presence is implied by the UI returning a credential.
public async Task GetAssertionAsync_DoesNotRequestUserVerification_ParamsDoNotRequireUserVerification() {
// Arrange
_params.RequireUserVerification = false;
// Act
await _sutProvider.Sut.GetAssertionAsync(_params);
// Assert
await _userInterface.Received().PickCredentialAsync(Arg.Is<Fido2PickCredentialParams>(
(pickCredentialParams) => pickCredentialParams.UserVerification == false
));
}
[Fact]
// Spec: If the user does not consent, return an error code equivalent to "NotAllowedError" and terminate the operation.
public async Task GetAssertionAsync_ThrowsNotAllowed_UserDoesNotConsent() {
// Arrange
_userInterface.PickCredentialAsync(Arg.Any<Fido2PickCredentialParams>()).Returns(new Fido2PickCredentialResult {
CipherId = null,
UserVerified = false
});
// Act & Assert
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.GetAssertionAsync(_params));
}
[Fact]
// Spec: If the user does not consent, return an error code equivalent to "NotAllowedError" and terminate the operation.
public async Task GetAssertionAsync_ThrowsNotAllowed_NoUserVerificationWhenRequired() {
// Arrange
_params.RequireUserVerification = true;
_userInterface.PickCredentialAsync(Arg.Any<Fido2PickCredentialParams>()).Returns(new Fido2PickCredentialResult {
CipherId = _selectedCipher.Id,
UserVerified = false
});
// Act and assert
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.GetAssertionAsync(_params));
}
[Fact]
// Spec: If the user does not consent, return an error code equivalent to "NotAllowedError" and terminate the operation.
public async Task GetAssertionAsync_ThrowsNotAllowed_NoUserVerificationForCipherWithReprompt() {
// Arrange
_selectedCipher.Reprompt = CipherRepromptType.Password;
_params.RequireUserVerification = false;
_userInterface.PickCredentialAsync(Arg.Any<Fido2PickCredentialParams>()).Returns(new Fido2PickCredentialResult {
CipherId = _selectedCipher.Id,
UserVerified = false
});
// Act & Assert
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.GetAssertionAsync(_params));
}
#endregion
#region assertion of credential
[Theory]
[InlineCustomAutoData(new[] { typeof(SutProviderCustomization) })]
// Spec: Increment the credential associated signature counter
public async Task GetAssertionAsync_IncrementsCounter_CounterIsLargerThanZero(Cipher encryptedCipher) {
// Arrange
_selectedCipher.Login.MainFido2Credential.CounterValue = 9000;
_sutProvider.GetDependency<ICipherService>().EncryptAsync(_selectedCipher).Returns(encryptedCipher);
// Act
await _sutProvider.Sut.GetAssertionAsync(_params);
// Assert
await _sutProvider.GetDependency<ICipherService>().Received().SaveWithServerAsync(encryptedCipher);
await _sutProvider.GetDependency<ICipherService>().Received().EncryptAsync(Arg.Is<CipherView>(
(cipher) => cipher.Login.MainFido2Credential.CounterValue == 9001
));
}
[Theory]
[InlineCustomAutoData(new[] { typeof(SutProviderCustomization) })]
// Spec: Increment the credential associated signature counter
public async Task GetAssertionAsync_DoesNotIncrementsCounter_CounterIsZero(Cipher encryptedCipher) {
// Arrange
_selectedCipher.Login.MainFido2Credential.CounterValue = 0;
_sutProvider.GetDependency<ICipherService>().EncryptAsync(_selectedCipher).Returns(encryptedCipher);
// Act
await _sutProvider.Sut.GetAssertionAsync(_params);
// Assert
await _sutProvider.GetDependency<ICipherService>().Received().SaveWithServerAsync(encryptedCipher);
await _sutProvider.GetDependency<ICipherService>().Received().EncryptAsync(Arg.Is<CipherView>(
(cipher) => cipher.Login.MainFido2Credential.CounterValue == 0
));
}
[Fact]
public async Task GetAssertionAsync_ReturnsAssertion() {
// Arrange
var keyPair = GenerateKeyPair();
var rpIdHashMock = RandomBytes(32);
_params.Hash = RandomBytes(32);
_params.RequireUserVerification = true;
_selectedCipher.Login.MainFido2Credential.CounterValue = 9000;
_selectedCipher.Login.MainFido2Credential.KeyValue = CoreHelpers.Base64UrlEncode(keyPair.ExportPkcs8PrivateKey());
_sutProvider.GetDependency<ICryptoFunctionService>().HashAsync(_params.RpId, CryptoHashAlgorithm.Sha256).Returns(rpIdHashMock);
_userInterface.PickCredentialAsync(Arg.Any<Fido2PickCredentialParams>()).Returns(new Fido2PickCredentialResult {
CipherId = _selectedCipher.Id,
UserVerified = true
});
// Act
var result = await _sutProvider.Sut.GetAssertionAsync(_params);
// Assert
var authData = result.AuthenticatorData;
var rpIdHash = authData.Take(32);
var flags = authData.Skip(32).Take(1);
var counter = authData.Skip(33).Take(4);
Assert.Equal(Guid.Parse(_selectedCipher.Login.MainFido2Credential.CredentialId).ToByteArray(), result.SelectedCredential.Id);
Assert.Equal(CoreHelpers.Base64UrlDecode(_selectedCipher.Login.MainFido2Credential.UserHandle), result.SelectedCredential.UserHandle);
Assert.Equal(rpIdHashMock, rpIdHash);
Assert.Equal(new byte[] { 0b00011101 }, flags); // UP = true, UV = true, BS = true, BE = true
Assert.Equal(new byte[] { 0, 0, 0x23, 0x29 }, counter); // 9001 in binary big-endian format
Assert.True(keyPair.VerifyData(authData.Concat(_params.Hash).ToArray(), result.Signature, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence), "Signature verification failed");
}
[Fact]
public async Task GetAssertionAsync_DoesNotAskForConfirmation_ParamsContainsOneAllowedCredentialAndUserPresenceIsFalse()
{
// Arrange
var rpIdHashMock = RandomBytes(32);
_params.RequireUserPresence = false;
_params.AllowCredentialDescriptorList = [
new PublicKeyCredentialDescriptor {
Id = _credentialIds[0].ToByteArray(),
Type = "public-key"
},
];
_sutProvider.GetDependency<ICryptoFunctionService>().HashAsync(_params.RpId, CryptoHashAlgorithm.Sha256).Returns(rpIdHashMock);
// Act
var result = await _sutProvider.Sut.GetAssertionAsync(_params);
// Assert
await _userInterface.DidNotReceive().PickCredentialAsync(Arg.Any<Fido2PickCredentialParams>());
var authData = result.AuthenticatorData;
var flags = authData.Skip(32).Take(1);
Assert.Equal(new byte[] { 0b00011000 }, flags); // UP = false, UV = false, BE = true, BS = true
}
[Fact]
public async Task GetAssertionAsync_ThrowsUnknownError_SaveFails() {
// Arrange
_sutProvider.GetDependency<ICipherService>().SaveWithServerAsync(Arg.Any<Cipher>()).Throws(new Exception());
// Act & Assert
await Assert.ThrowsAsync<UnknownError>(() => _sutProvider.Sut.GetAssertionAsync(_params));
}
#endregion
private byte[] RandomBytes(int length)
{
var bytes = new byte[length];
new Random().NextBytes(bytes);
return bytes;
}
private ECDsa GenerateKeyPair()
{
var dsa = ECDsa.Create();
dsa.GenerateKey(ECCurve.NamedCurves.nistP256);
return dsa;
}
#nullable enable
private CipherView CreateCipherView(string? credentialId, string? rpId, bool? discoverable)
{
return new CipherView {
Type = CipherType.Login,
Id = Guid.NewGuid().ToString(),
Reprompt = CipherRepromptType.None,
Login = new LoginView {
Fido2Credentials = new List<Fido2CredentialView> {
new Fido2CredentialView {
CredentialId = credentialId ?? Guid.NewGuid().ToString(),
RpId = rpId ?? "bitwarden.com",
Discoverable = discoverable.HasValue ? discoverable.ToString() : "true",
UserHandleValue = RandomBytes(32),
KeyValue = "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgO4wC7AlY4eJP7uedRUJGYsAIJAd6gN1Vp7uJh6xXAp6hRANCAARGvr56F_t27DEG1Tzl-qJRhrTUtC7jOEbasAEEZcE3TiMqoWCan0sxKDPylhRYk-1qyrBC_feN1UtGWH57sROa"
}
}
}
};
}
private Fido2AuthenticatorGetAssertionParams CreateParams(string? rpId = null, byte[]? hash = null, PublicKeyCredentialDescriptor[]? allowCredentialDescriptorList = null, bool? requireUserPresence = null, bool? requireUserVerification = null)
{
return new Fido2AuthenticatorGetAssertionParams {
RpId = rpId ?? "bitwarden.com",
Hash = hash ?? RandomBytes(32),
AllowCredentialDescriptorList = allowCredentialDescriptorList ?? null,
RequireUserPresence = requireUserPresence ?? true,
RequireUserVerification = requireUserPresence ?? false
};
}
}
}

View File

@@ -0,0 +1,396 @@
using System;
using System.Threading.Tasks;
using Bit.Core.Abstractions;
using Bit.Core.Services;
using Bit.Core.Models.Domain;
using Bit.Core.Models.View;
using Bit.Core.Enums;
using Bit.Core.Utilities.Fido2;
using Bit.Test.Common.AutoFixture;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Xunit;
using Bit.Core.Utilities;
using System.Collections.Generic;
using System.Linq;
using System.Formats.Cbor;
namespace Bit.Core.Test.Services
{
public class Fido2AuthenticatorMakeCredentialTests : IDisposable
{
private readonly string _rpId = "bitwarden.com";
private readonly SutProvider<Fido2AuthenticatorService> _sutProvider = new SutProvider<Fido2AuthenticatorService>().Create();
private Cipher _encryptedSelectedCipher;
private CipherView _selectedCipherView;
private Fido2AuthenticatorMakeCredentialParams _params;
private List<Guid> _credentialIds;
private List<CipherView> _ciphers;
public Fido2AuthenticatorMakeCredentialTests() {
_credentialIds = [ Guid.NewGuid(), Guid.NewGuid() ];
_ciphers = [
CreateCipherView(true, _credentialIds[0].ToString(), "bitwarden.com", false),
CreateCipherView(true, _credentialIds[1].ToString(), "bitwarden.com", true)
];
_selectedCipherView = _ciphers[0];
_encryptedSelectedCipher = CreateCipher();
_encryptedSelectedCipher.Id = _selectedCipherView.Id;
_params = new Fido2AuthenticatorMakeCredentialParams {
UserEntity = new PublicKeyCredentialUserEntity {
Id = RandomBytes(32),
Name = "test"
},
RpEntity = new PublicKeyCredentialRpEntity {
Id = _rpId,
Name = "Bitwarden"
},
CredTypesAndPubKeyAlgs = [
new PublicKeyCredentialParameters {
Type = "public-key",
Alg = -7 // ES256
}
],
RequireResidentKey = false,
RequireUserVerification = false,
ExcludeCredentialDescriptorList = null
};
_sutProvider.GetDependency<ICipherService>().GetAllDecryptedAsync().Returns(_ciphers);
_sutProvider.GetDependency<ICipherService>().EncryptAsync(Arg.Any<CipherView>()).Returns(_encryptedSelectedCipher);
_sutProvider.GetDependency<ICipherService>().GetAsync(Arg.Is(_encryptedSelectedCipher.Id)).Returns(_encryptedSelectedCipher);
_sutProvider.GetDependency<IFido2UserInterface>().ConfirmNewCredentialAsync(Arg.Any<Fido2ConfirmNewCredentialParams>()).Returns(new Fido2ConfirmNewCredentialResult {
CipherId = _selectedCipherView.Id,
UserVerified = false
});
var cryptoServiceMock = Substitute.For<ICryptoService>();
ServiceContainer.Register(typeof(CryptoService), cryptoServiceMock);
}
public void Dispose()
{
ServiceContainer.Reset();
}
#region invalid input parameters
[Fact]
// Spec: Check if at least one of the specified combinations of PublicKeyCredentialType and cryptographic parameters in credTypesAndPubKeyAlgs is supported. If not, return an error code equivalent to "NotSupportedError" and terminate the operation.
public async Task MakeCredentialAsync_ThrowsNotSupported_NoSupportedAlgorithm()
{
// Arrange
_params.CredTypesAndPubKeyAlgs = [
new PublicKeyCredentialParameters {
Type = "public-key",
Alg = -257 // RS256 which we do not support
}
];
// Act & Assert
await Assert.ThrowsAsync<NotSupportedError>(() => _sutProvider.Sut.MakeCredentialAsync(_params));
}
#endregion
#region vault contains excluded credential
[Fact]
// Spec: collect an authorization gesture confirming user consent for creating a new credential.
// Deviation: Consent is not asked and the user is simply informed of the situation.
public async Task MakeCredentialAsync_InformsUser_ExcludedCredentialFound()
{
// Arrange
_params.ExcludeCredentialDescriptorList = [
new PublicKeyCredentialDescriptor {
Type = "public-key",
Id = _credentialIds[0].ToByteArray()
}
];
// Act
try
{
await _sutProvider.Sut.MakeCredentialAsync(_params);
}
catch {}
// Assert
await _sutProvider.GetDependency<IFido2UserInterface>().Received().InformExcludedCredential(Arg.Is<string[]>(
(c) => c.SequenceEqual(new string[] { _ciphers[0].Id })
));
}
[Fact]
// Spec: return an error code equivalent to "NotAllowedError" and terminate the operation.
public async Task MakeCredentialAsync_ThrowsNotAllowed_ExcludedCredentialFound()
{
_params.ExcludeCredentialDescriptorList = [
new PublicKeyCredentialDescriptor {
Type = "public-key",
Id = _credentialIds[0].ToByteArray()
}
];
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.MakeCredentialAsync(_params));
}
[Fact]
// Deviation: Organization ciphers are not checked against excluded credentials, even if the user has access to them.
public async Task MakeCredentialAsync_DoesNotInformAboutExcludedCredential_ExcludedCredentialBelongsToOrganization()
{
_ciphers[0].OrganizationId = "someOrganizationId";
_params.ExcludeCredentialDescriptorList = [
new PublicKeyCredentialDescriptor {
Type = "public-key",
Id = _credentialIds[0].ToByteArray()
}
];
await _sutProvider.Sut.MakeCredentialAsync(_params);
await _sutProvider.GetDependency<IFido2UserInterface>().DidNotReceive().InformExcludedCredential(Arg.Any<string[]>());
}
#endregion
#region credential creation
[Fact]
public async Task MakeCredentialAsync_RequestsUserVerification_ParamsRequireUserVerification()
{
// Arrange
_params.RequireUserVerification = true;
_sutProvider.GetDependency<IFido2UserInterface>().ConfirmNewCredentialAsync(Arg.Any<Fido2ConfirmNewCredentialParams>()).Returns(new Fido2ConfirmNewCredentialResult {
CipherId = _selectedCipherView.Id,
UserVerified = true
});
// Act
await _sutProvider.Sut.MakeCredentialAsync(_params);
// Assert
await _sutProvider.GetDependency<IFido2UserInterface>().Received().ConfirmNewCredentialAsync(Arg.Is<Fido2ConfirmNewCredentialParams>(
(p) => p.UserVerification == true
));
}
[Fact]
public async Task MakeCredentialAsync_DoesNotRequestUserVerification_ParamsDoNotRequireUserVerification()
{
// Arrange
_params.RequireUserVerification = false;
// Act
await _sutProvider.Sut.MakeCredentialAsync(_params);
// Assert
await _sutProvider.GetDependency<IFido2UserInterface>().Received().ConfirmNewCredentialAsync(Arg.Is<Fido2ConfirmNewCredentialParams>(
(p) => p.UserVerification == false
));
}
[Fact]
public async Task MakeCredentialAsync_SavesNewCredential_RequestConfirmedByUser()
{
// Arrange
_params.RequireResidentKey = true;
// Act
await _sutProvider.Sut.MakeCredentialAsync(_params);
// Assert
await _sutProvider.GetDependency<ICipherService>().Received().EncryptAsync(Arg.Is<CipherView>(
(c) =>
c.Login.MainFido2Credential.KeyType == "public-key" &&
c.Login.MainFido2Credential.KeyAlgorithm == "ECDSA" &&
c.Login.MainFido2Credential.KeyCurve == "P-256" &&
c.Login.MainFido2Credential.RpId == _params.RpEntity.Id &&
c.Login.MainFido2Credential.RpName == _params.RpEntity.Name &&
c.Login.MainFido2Credential.UserHandle == CoreHelpers.Base64UrlEncode(_params.UserEntity.Id) &&
c.Login.MainFido2Credential.UserName == _params.UserEntity.Name &&
c.Login.MainFido2Credential.CounterValue == 0 &&
// c.Login.MainFido2Credential.UserDisplayName == _params.UserEntity.DisplayName &&
c.Login.MainFido2Credential.DiscoverableValue == true
));
await _sutProvider.GetDependency<ICipherService>().Received().SaveWithServerAsync(_encryptedSelectedCipher);
}
[Fact]
// Spec: If the user does not consent or if user verification fails, return an error code equivalent to "NotAllowedError" and terminate the operation.
public async Task MakeCredentialAsync_ThrowsNotAllowed_RequestNotConfirmedByUser()
{
// Arrange
_sutProvider.GetDependency<IFido2UserInterface>().ConfirmNewCredentialAsync(Arg.Any<Fido2ConfirmNewCredentialParams>()).Returns(new Fido2ConfirmNewCredentialResult {
CipherId = null,
UserVerified = false
});
// Act & Assert
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.MakeCredentialAsync(_params));
}
[Fact]
public async Task MakeCredentialAsync_ThrowsNotAllowed_NoUserVerificationWhenRequiredByParams()
{
// Arrange
_params.RequireUserVerification = true;
_sutProvider.GetDependency<IFido2UserInterface>().ConfirmNewCredentialAsync(Arg.Any<Fido2ConfirmNewCredentialParams>()).Returns(new Fido2ConfirmNewCredentialResult {
CipherId = _encryptedSelectedCipher.Id,
UserVerified = false
});
// Act & Assert
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.MakeCredentialAsync(_params));
}
[Fact]
public async Task MakeCredentialAsync_ThrowsNotAllowed_NoUserVerificationForCipherWithReprompt()
{
// Arrange
_params.RequireUserVerification = false;
_encryptedSelectedCipher.Reprompt = CipherRepromptType.Password;
_sutProvider.GetDependency<IFido2UserInterface>().ConfirmNewCredentialAsync(Arg.Any<Fido2ConfirmNewCredentialParams>()).Returns(new Fido2ConfirmNewCredentialResult {
CipherId = _encryptedSelectedCipher.Id,
UserVerified = false
});
// Act & Assert
await Assert.ThrowsAsync<NotAllowedError>(() => _sutProvider.Sut.MakeCredentialAsync(_params));
}
[Fact]
public async Task MakeCredentialAsync_ThrowsUnknownError_SavingCipherFails()
{
// Arrange
_sutProvider.GetDependency<ICipherService>().SaveWithServerAsync(Arg.Any<Cipher>()).Throws(new Exception("Error"));
// Act & Assert
await Assert.ThrowsAsync<UnknownError>(() => _sutProvider.Sut.MakeCredentialAsync(_params));
}
[Fact]
public async Task MakeCredentialAsync_ReturnsAttestation()
{
// Arrange
var rpIdHashMock = RandomBytes(32);
_sutProvider.GetDependency<ICryptoFunctionService>().HashAsync(_params.RpEntity.Id, CryptoHashAlgorithm.Sha256).Returns(rpIdHashMock);
CipherView generatedCipherView = null;
_sutProvider.GetDependency<ICipherService>().EncryptAsync(Arg.Any<CipherView>()).Returns((call) => {
generatedCipherView = call.Arg<CipherView>();
return _encryptedSelectedCipher;
});
// Act
var result = await _sutProvider.Sut.MakeCredentialAsync(_params);
// Assert
var credentialIdBytes = Guid.Parse(generatedCipherView.Login.MainFido2Credential.CredentialId).ToByteArray();
var attestationObject = DecodeAttestationObject(result.AttestationObject);
Assert.Equal("none", attestationObject.Fmt);
var authData = attestationObject.AuthData;
var rpIdHash = authData.Take(32).ToArray();
var flags = authData.Skip(32).Take(1).ToArray();
var counter = authData.Skip(33).Take(4).ToArray();
var aaguid = authData.Skip(37).Take(16).ToArray();
var credentialIdLength = authData.Skip(53).Take(2).ToArray();
var credentialId = authData.Skip(55).Take(16).ToArray();
// Unsure how to test public key
// const publicKey = authData.Skip(71).ToArray(); // Key data is 77 bytes long
Assert.Equal(71 + 77, authData.Length);
Assert.Equal(rpIdHashMock, rpIdHash);
Assert.Equal([0b01000001], flags); // UP = true, AD = true
Assert.Equal([0, 0, 0, 0], counter);
Assert.Equal(Fido2AuthenticatorService.AAGUID, aaguid);
Assert.Equal([0, 16], credentialIdLength); // 16 bytes because we're using GUIDs
Assert.Equal(credentialIdBytes, credentialId);
}
#endregion
private byte[] RandomBytes(int length)
{
var bytes = new byte[length];
new Random().NextBytes(bytes);
return bytes;
}
#nullable enable
private CipherView CreateCipherView(bool? withFido2Credential, string? credentialId = null, string? rpId = null, bool? discoverable = null)
{
return new CipherView {
Type = CipherType.Login,
Id = Guid.NewGuid().ToString(),
Reprompt = CipherRepromptType.None,
Login = new LoginView {
Fido2Credentials = withFido2Credential.HasValue && withFido2Credential.Value ? new List<Fido2CredentialView> {
new Fido2CredentialView {
CredentialId = credentialId ?? Guid.NewGuid().ToString(),
RpId = rpId ?? "bitwarden.com",
Discoverable = discoverable.HasValue ? discoverable.ToString() : "true",
UserHandleValue = RandomBytes(32)
}
} : null
}
};
}
private Cipher CreateCipher()
{
return new Cipher {
Id = Guid.NewGuid().ToString(),
Type = CipherType.Login,
Key = null,
Attachments = [],
Login = new Login {},
};
}
private struct AttestationObject
{
public string? Fmt { get; set; }
public object? AttStmt { get; set; }
public byte[]? AuthData { get; set; }
}
private AttestationObject DecodeAttestationObject(byte[] attestationObject)
{
string? fmt = null;
object? attStmt = null;
byte[]? authData = null;
var reader = new CborReader(attestationObject, CborConformanceMode.Ctap2Canonical);
reader.ReadStartMap();
while (reader.BytesRemaining != 0)
{
var key = reader.ReadTextString();
switch (key)
{
case "fmt":
fmt = reader.ReadTextString();
break;
case "attStmt":
reader.ReadStartMap();
reader.ReadEndMap();
break;
case "authData":
authData = reader.ReadByteString();
break;
default:
throw new Exception("Unknown key");
}
}
return new AttestationObject {
Fmt = fmt,
AttStmt = attStmt,
AuthData = authData
};
}
}
}

View File

@@ -0,0 +1,123 @@
using System;
using System.Threading.Tasks;
using Bit.Core.Abstractions;
using Bit.Core.Services;
using Bit.Core.Models.View;
using Bit.Core.Enums;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using NSubstitute;
using Xunit;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
namespace Bit.Core.Test.Services
{
public class Fido2AuthenticatorSilentCredentialDiscoveryTests
{
[Theory]
[InlineCustomAutoData(new[] { typeof(SutProviderCustomization) })]
public async Task SilentCredentialDiscoveryAsync_ReturnsEmptyArray_NoCredentialsExist(SutProvider<Fido2AuthenticatorService> sutProvider)
{
sutProvider.GetDependency<ICipherService>().GetAllDecryptedAsync().Returns([]);
var result = await sutProvider.Sut.SilentCredentialDiscoveryAsync("bitwarden.com");
Assert.Empty(result);
}
[Theory]
[InlineCustomAutoData(new[] { typeof(SutProviderCustomization) })]
public async Task SilentCredentialDiscoveryAsync_ReturnsEmptyArray_OnlyNonDiscoverableCredentialsExist(SutProvider<Fido2AuthenticatorService> sutProvider)
{
sutProvider.GetDependency<ICipherService>().GetAllDecryptedAsync().Returns([
CreateCipherView("bitwarden.com", false),
CreateCipherView("bitwarden.com", false),
CreateCipherView("bitwarden.com", false)
]);
var result = await sutProvider.Sut.SilentCredentialDiscoveryAsync("bitwarden.com");
Assert.Empty(result);
}
[Theory]
[InlineCustomAutoData(new[] { typeof(SutProviderCustomization) })]
public async Task SilentCredentialDiscoveryAsync_ReturnsEmptyArray_NoCredentialsWithMatchingRpIdExist(SutProvider<Fido2AuthenticatorService> sutProvider)
{
sutProvider.GetDependency<ICipherService>().GetAllDecryptedAsync().Returns([
CreateCipherView("a.bitwarden.com", true),
CreateCipherView("example.com", true)
]);
var result = await sutProvider.Sut.SilentCredentialDiscoveryAsync("bitwarden.com");
Assert.Empty(result);
}
[Theory]
[InlineCustomAutoData(new[] { typeof(SutProviderCustomization) })]
public async Task SilentCredentialDiscoveryAsync_ReturnsCredentials_DiscoverableCredentialsWithMatchingRpIdExist(SutProvider<Fido2AuthenticatorService> sutProvider)
{
var matchingCredentials = new List<CipherView> {
CreateCipherView("bitwarden.com", true),
CreateCipherView("bitwarden.com", true)
};
var nonMatchingCredentials = new List<CipherView> {
CreateCipherView("example.com", true)
};
sutProvider.GetDependency<ICipherService>().GetAllDecryptedAsync().Returns(
matchingCredentials.Concat(nonMatchingCredentials).ToList()
);
var result = await sutProvider.Sut.SilentCredentialDiscoveryAsync("bitwarden.com");
Assert.True(
result.SequenceEqual(matchingCredentials.Select(c => new Fido2AuthenticatorDiscoverableCredentialMetadata {
Type = "public-key",
Id = Guid.Parse(c.Login.MainFido2Credential.CredentialId).ToByteArray(),
RpId = "bitwarden.com",
UserHandle = c.Login.MainFido2Credential.UserHandleValue,
UserName = c.Login.MainFido2Credential.UserName
}), new MetadataComparer())
);
}
private byte[] RandomBytes(int length)
{
var bytes = new byte[length];
new Random().NextBytes(bytes);
return bytes;
}
#nullable enable
private CipherView CreateCipherView(string rpId, bool discoverable)
{
return new CipherView {
Type = CipherType.Login,
Id = Guid.NewGuid().ToString(),
Reprompt = CipherRepromptType.None,
Login = new LoginView {
Fido2Credentials = new List<Fido2CredentialView> {
new Fido2CredentialView {
CredentialId = Guid.NewGuid().ToString(),
RpId = rpId ?? "null.com",
DiscoverableValue = discoverable,
UserHandleValue = RandomBytes(32),
KeyValue = "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgO4wC7AlY4eJP7uedRUJGYsAIJAd6gN1Vp7uJh6xXAp6hRANCAARGvr56F_t27DEG1Tzl-qJRhrTUtC7jOEbasAEEZcE3TiMqoWCan0sxKDPylhRYk-1qyrBC_feN1UtGWH57sROa"
}
}
}
};
}
private class MetadataComparer : IEqualityComparer<Fido2AuthenticatorDiscoverableCredentialMetadata>
{
public int GetHashCode([DisallowNull] Fido2AuthenticatorDiscoverableCredentialMetadata obj) => throw new NotImplementedException();
public bool Equals(Fido2AuthenticatorDiscoverableCredentialMetadata? a, Fido2AuthenticatorDiscoverableCredentialMetadata? b) =>
a != null && b != null && a.Type == b.Type && a.RpId == b.RpId && a.UserName == b.UserName && a.Id.SequenceEqual(b.Id) && a.UserHandle.SequenceEqual(b.UserHandle);
}
}
}

View File

@@ -0,0 +1,222 @@
using System;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Bit.Core.Abstractions;
using Bit.Core.Services;
using Bit.Core.Utilities;
using Bit.Core.Utilities.Fido2;
using Bit.Test.Common.AutoFixture;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Xunit;
namespace Bit.Core.Test.Services
{
public class Fido2ClientAssertCredentialTests : IDisposable
{
private readonly SutProvider<Fido2ClientService> _sutProvider = new SutProvider<Fido2ClientService>().Create();
private Fido2ClientAssertCredentialParams _params;
public Fido2ClientAssertCredentialTests()
{
_params = new Fido2ClientAssertCredentialParams {
Origin = "https://bitwarden.com",
Challenge = RandomBytes(32),
RpId = "bitwarden.com",
UserVerification = "required",
AllowCredentials = [
new PublicKeyCredentialDescriptor {
Id = RandomBytes(32),
Type = "public-key"
}
],
Timeout = 60000,
};
_sutProvider.GetDependency<IStateService>().GetAutofillBlacklistedUrisAsync().Returns([]);
_sutProvider.GetDependency<IStateService>().IsAuthenticatedAsync().Returns(true);
}
public void Dispose()
{
}
[Fact(Skip = "Not sure how to check this, or if it matters.")]
// Spec: If callerOrigin is an opaque origin, return a DOMException whose name is "NotAllowedError", and terminate this algorithm.
public Task AssertCredentialAsync_ThrowsNotAllowedError_OriginIsOpaque() => throw new NotImplementedException();
[Fact]
// Spec: Let effectiveDomain be the callerOrigins effective domain. If effective domain is not a valid domain,
// then return a DOMException whose name is "SecurityError" and terminate this algorithm.
public async Task AssertCredentialAsync_ThrowsSecurityError_OriginIsNotValidDomain()
{
// Arrange
_params.Origin = "invalid-domain-name";
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.AssertCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.SecurityError, exception.Code);
}
[Fact]
// Spec: If options.rp.id is not a registrable domain suffix of and is not equal to effectiveDomain,
// return a DOMException whose name is "SecurityError", and terminate this algorithm.
public async Task AssertCredentialAsync_ThrowsSecurityError_RpIdIsNotValidForOrigin()
{
// Arrange
_params.Origin = "https://passwordless.dev";
_params.RpId = "bitwarden.com";
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.AssertCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.SecurityError, exception.Code);
}
[Fact]
// Spec: The origin's scheme must be https.
public async Task AssertCredentialAsync_ThrowsSecurityError_OriginIsNotHttps()
{
// Arrange
_params.Origin = "http://bitwarden.com";
_params.RpId = "bitwarden.com";
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.AssertCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.SecurityError, exception.Code);
}
[Fact]
// Spec: If the origin's hostname is a blocked uri, then return UriBlockedError.
public async Task AssertCredentialAsync_ThrowsUriBlockedError_OriginIsBlocked()
{
// Arrange
_params.Origin = "https://sub.bitwarden.com";
_sutProvider.GetDependency<IStateService>().GetAutofillBlacklistedUrisAsync().Returns([
"sub.bitwarden.com"
]);
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.AssertCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.UriBlockedError, exception.Code);
}
[Fact]
public async Task AssertCredentialAsync_ThrowsInvalidStateError_AuthenticatorThrowsInvalidStateError()
{
// Arrange
_sutProvider.GetDependency<IFido2AuthenticatorService>()
.GetAssertionAsync(Arg.Any<Fido2AuthenticatorGetAssertionParams>())
.Throws(new InvalidStateError());
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.AssertCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.InvalidStateError, exception.Code);
}
[Fact]
// This keeps sensetive information form leaking
public async Task AssertCredentialAsync_ThrowsUnknownError_AuthenticatorThrowsUnknownError()
{
// Arrange
_sutProvider.GetDependency<IFido2AuthenticatorService>()
.GetAssertionAsync(Arg.Any<Fido2AuthenticatorGetAssertionParams>())
.Throws(new Exception("unknown error"));
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.AssertCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.UnknownError, exception.Code);
}
[Fact]
public async Task AssertCredentialAsync_ThrowsInvalidStateError_UserIsLoggedOut()
{
// Arrange
_sutProvider.GetDependency<IStateService>().IsAuthenticatedAsync().Returns(false);
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.AssertCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.InvalidStateError, exception.Code);
}
[Fact]
public async Task AssertCredentialAsync_ThrowsNotAllowedError_OriginIsBitwardenVault()
{
// Arrange
_params.Origin = "https://vault.bitwarden.com";
_sutProvider.GetDependency<IEnvironmentService>().GetWebVaultUrl().Returns("https://vault.bitwarden.com");
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.AssertCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.NotAllowedError, exception.Code);
}
[Fact]
public async Task AssertCredentialAsync_ReturnsAssertion()
{
// Arrange
_params.UserVerification = "required";
var authenticatorResult = new Fido2AuthenticatorGetAssertionResult {
AuthenticatorData = RandomBytes(32),
SelectedCredential = new Fido2AuthenticatorGetAssertionSelectedCredential {
Id = RandomBytes(16),
UserHandle = RandomBytes(32)
},
Signature = RandomBytes(32)
};
_sutProvider.GetDependency<IFido2AuthenticatorService>()
.GetAssertionAsync(Arg.Any<Fido2AuthenticatorGetAssertionParams>())
.Returns(authenticatorResult);
// Act
var result = await _sutProvider.Sut.AssertCredentialAsync(_params);
// Assert
await _sutProvider.GetDependency<IFido2AuthenticatorService>()
.Received()
.GetAssertionAsync(Arg.Is<Fido2AuthenticatorGetAssertionParams>(x =>
x.RpId == _params.RpId &&
x.RequireUserPresence == true &&
x.RequireUserVerification == true &&
x.AllowCredentialDescriptorList.Length == 1 &&
x.AllowCredentialDescriptorList[0].Id == _params.AllowCredentials[0].Id
));
Assert.Equal(authenticatorResult.SelectedCredential.Id, result.RawId);
Assert.Equal(CoreHelpers.Base64UrlEncode(authenticatorResult.SelectedCredential.Id), result.Id);
Assert.Equal(authenticatorResult.AuthenticatorData, result.AuthenticatorData);
Assert.Equal(authenticatorResult.Signature, result.Signature);
var clientDataJSON = JsonSerializer.Deserialize<JsonObject>(Encoding.UTF8.GetString(result.ClientDataJSON));
Assert.Equal("webauthn.get", clientDataJSON["type"].GetValue<string>());
Assert.Equal(CoreHelpers.Base64UrlEncode(_params.Challenge), clientDataJSON["challenge"].GetValue<string>());
Assert.Equal(_params.Origin, clientDataJSON["origin"].GetValue<string>());
Assert.Equal(!_params.SameOriginWithAncestors, clientDataJSON["crossOrigin"].GetValue<bool>());
}
private byte[] RandomBytes(int length)
{
var bytes = new byte[length];
new Random().NextBytes(bytes);
return bytes;
}
}
}

View File

@@ -0,0 +1,305 @@
using System;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Bit.Core.Abstractions;
using Bit.Core.Services;
using Bit.Core.Utilities;
using Bit.Core.Utilities.Fido2;
using Bit.Test.Common.AutoFixture;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using Xunit;
namespace Bit.Core.Test.Services
{
public class Fido2ClientCreateCredentialTests : IDisposable
{
private readonly SutProvider<Fido2ClientService> _sutProvider = new SutProvider<Fido2ClientService>().Create();
private Fido2ClientCreateCredentialParams _params;
public Fido2ClientCreateCredentialTests()
{
_params = new Fido2ClientCreateCredentialParams {
Origin = "https://bitwarden.com",
SameOriginWithAncestors = true,
Attestation = "none",
Challenge = RandomBytes(32),
PubKeyCredParams = [
new PublicKeyCredentialParameters {
Type = "public-key",
Alg = -7
}
],
Rp = new PublicKeyCredentialRpEntity {
Id = "bitwarden.com",
Name = "Bitwarden"
},
User = new PublicKeyCredentialUserEntity {
Id = RandomBytes(32),
Name = "user@bitwarden.com",
DisplayName = "User"
}
};
_sutProvider.GetDependency<IStateService>().GetAutofillBlacklistedUrisAsync().Returns([]);
_sutProvider.GetDependency<IStateService>().IsAuthenticatedAsync().Returns(true);
}
public void Dispose()
{
}
[Fact]
// Spec: If sameOriginWithAncestors is false, return a "NotAllowedError" DOMException.
public async Task CreateCredentialAsync_ThrowsNotAllowedError_SameOriginWithAncestorsIsFalse()
{
// Arrange
_params.SameOriginWithAncestors = false;
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.NotAllowedError, exception.Code);
}
[Fact]
// Spec: If the length of options.user.id is not between 1 and 64 bytes (inclusive) then return a TypeError.
public async Task CreateCredentialAsync_ThrowsTypeError_UserIdIsTooSmall()
{
// Arrange
_params.User.Id = RandomBytes(0);
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.TypeError, exception.Code);
}
[Fact]
// Spec: If the length of options.user.id is not between 1 and 64 bytes (inclusive) then return a TypeError.
public async Task CreateCredentialAsync_ThrowsTypeError_UserIdIsTooLarge()
{
// Arrange
_params.User.Id = RandomBytes(65);
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.TypeError, exception.Code);
}
[Fact(Skip = "Not sure how to check this, or if it matters.")]
// Spec: If callerOrigin is an opaque origin, return a DOMException whose name is "NotAllowedError", and terminate this algorithm.
public Task CreateCredentialAsync_ThrowsNotAllowedError_OriginIsOpaque() => throw new NotImplementedException();
[Fact]
// Spec: Let effectiveDomain be the callerOrigins effective domain. If effective domain is not a valid domain,
// then return a DOMException whose name is "SecurityError" and terminate this algorithm.
public async Task CreateCredentialAsync_ThrowsSecurityError_OriginIsNotValidDomain()
{
// Arrange
_params.Origin = "invalid-domain-name";
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.SecurityError, exception.Code);
}
[Fact]
// Spec: If options.rp.id is not a registrable domain suffix of and is not equal to effectiveDomain,
// return a DOMException whose name is "SecurityError", and terminate this algorithm.
public async Task CreateCredentialAsync_ThrowsSecurityError_RpIdIsNotValidForOrigin()
{
// Arrange
_params.Origin = "https://passwordless.dev";
_params.Rp.Id = "bitwarden.com";
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.SecurityError, exception.Code);
}
[Fact]
// Spec: The origin's scheme must be https.
public async Task CreateCredentialAsync_ThrowsSecurityError_OriginIsNotHttps()
{
// Arrange
_params.Origin = "http://bitwarden.com";
_params.Rp.Id = "bitwarden.com";
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.SecurityError, exception.Code);
}
[Fact]
// Spec: If the origin's hostname is a blocked uri, then return UriBlockedError.
public async Task CreateCredentialAsync_ThrowsUriBlockedError_OriginIsBlocked()
{
// Arrange
_params.Origin = "https://sub.bitwarden.com";
_sutProvider.GetDependency<IStateService>().GetAutofillBlacklistedUrisAsync().Returns([
"sub.bitwarden.com"
]);
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.UriBlockedError, exception.Code);
}
[Fact]
// Spec: If credTypesAndPubKeyAlgs is empty, return a DOMException whose name is "NotSupportedError", and terminate this algorithm.
public async Task CreateCredentialAsync_ThrowsNotSupportedError_CredTypesAndPubKeyAlgsIsEmpty()
{
// Arrange
_params.PubKeyCredParams = [
new PublicKeyCredentialParameters {
Type = "not-supported",
Alg = -7
},
new PublicKeyCredentialParameters {
Type = "public-key",
Alg = -9001
}
];
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.NotSupportedError, exception.Code);
}
[Fact(Skip = "Not implemented")]
// Spec: If the options.signal is present and its aborted flag is set to true, return a DOMException whose name is "AbortError" and terminate this algorithm.
public Task CreateCredentialAsync_ThrowsAbortError_AbortedByCaller() => throw new NotImplementedException();
[Fact]
public async Task CreateCredentialAsync_ReturnsNewCredential()
{
// Arrange
_params.AuthenticatorSelection = new AuthenticatorSelectionCriteria {
ResidentKey = "required",
UserVerification = "required"
};
var authenticatorResult = new Fido2AuthenticatorMakeCredentialResult {
CredentialId = RandomBytes(32),
AttestationObject = RandomBytes(32),
AuthData = RandomBytes(32),
PublicKey = RandomBytes(32),
PublicKeyAlgorithm = -7,
};
_sutProvider.GetDependency<IFido2AuthenticatorService>()
.MakeCredentialAsync(Arg.Any<Fido2AuthenticatorMakeCredentialParams>())
.Returns(authenticatorResult);
// Act
var result = await _sutProvider.Sut.CreateCredentialAsync(_params);
// Assert
await _sutProvider.GetDependency<IFido2AuthenticatorService>()
.Received()
.MakeCredentialAsync(Arg.Is<Fido2AuthenticatorMakeCredentialParams>(x =>
x.RequireResidentKey == true &&
x.RequireUserVerification == true &&
x.RpEntity.Id == _params.Rp.Id &&
x.UserEntity.DisplayName == _params.User.DisplayName
));
Assert.Equal(authenticatorResult.CredentialId, result.CredentialId);
Assert.Equal(authenticatorResult.AttestationObject, result.AttestationObject);
Assert.Equal(authenticatorResult.AuthData, result.AuthData);
Assert.Equal(authenticatorResult.PublicKey, result.PublicKey);
Assert.Equal(authenticatorResult.PublicKeyAlgorithm, result.PublicKeyAlgorithm);
Assert.Equal(["internal"], result.Transports);
var clientDataJSON = JsonSerializer.Deserialize<JsonObject>(Encoding.UTF8.GetString(result.ClientDataJSON));
Assert.Equal("webauthn.create", clientDataJSON["type"].GetValue<string>());
Assert.Equal(CoreHelpers.Base64UrlEncode(_params.Challenge), clientDataJSON["challenge"].GetValue<string>());
Assert.Equal(_params.Origin, clientDataJSON["origin"].GetValue<string>());
Assert.Equal(!_params.SameOriginWithAncestors, clientDataJSON["crossOrigin"].GetValue<bool>());
}
[Fact]
public async Task CreateCredentialAsync_ThrowsInvalidStateError_AuthenticatorThrowsInvalidStateError()
{
// Arrange
_params.AuthenticatorSelection = new AuthenticatorSelectionCriteria {
ResidentKey = "required",
UserVerification = "required"
};
_sutProvider.GetDependency<IFido2AuthenticatorService>()
.MakeCredentialAsync(Arg.Any<Fido2AuthenticatorMakeCredentialParams>())
.Throws(new InvalidStateError());
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.InvalidStateError, exception.Code);
}
[Fact]
// This keeps sensetive information form leaking
public async Task CreateCredentialAsync_ThrowsUnknownError_AuthenticatorThrowsUnknownError()
{
// Arrange
_sutProvider.GetDependency<IFido2AuthenticatorService>()
.MakeCredentialAsync(Arg.Any<Fido2AuthenticatorMakeCredentialParams>())
.Throws(new Exception("unknown error"));
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.UnknownError, exception.Code);
}
[Fact]
public async Task CreateCredentialAsync_ThrowsInvalidStateError_UserIsLoggedOut()
{
// Arrange
_sutProvider.GetDependency<IStateService>().IsAuthenticatedAsync().Returns(false);
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.InvalidStateError, exception.Code);
}
[Fact]
public async Task CreateCredentialAsync_ThrowsNotAllowedError_OriginIsBitwardenVault()
{
// Arrange
_params.Origin = "https://vault.bitwarden.com";
_sutProvider.GetDependency<IEnvironmentService>().GetWebVaultUrl().Returns("https://vault.bitwarden.com");
// Act
var exception = await Assert.ThrowsAsync<Fido2ClientException>(() => _sutProvider.Sut.CreateCredentialAsync(_params));
// Assert
Assert.Equal(Fido2ClientException.ErrorCode.NotAllowedError, exception.Code);
}
private byte[] RandomBytes(int length)
{
var bytes = new byte[length];
new Random().NextBytes(bytes);
return bytes;
}
}
}

View File

@@ -0,0 +1,40 @@
using Bit.Core.Utilities.Fido2;
using Xunit;
namespace Bit.Core.Test.Utilities.Fido2
{
public class Fido2DomainUtilsTests
{
[Theory]
// From https://html.spec.whatwg.org/multipage/browsers.html#is-a-registrable-domain-suffix-of-or-is-equal-to
// [InlineData("0.0.0.0", "0.0.0.0", true)] // IP-addresses not allowed by WebAuthn spec
// [InlineData("0x10203", "0.1.2.3", true)]
// [InlineData("[0::1]", "::1", true)]
[InlineData("example.com", "example.com", true)]
[InlineData("example.com", "example.com.", false)]
[InlineData("example.com.", "example.com", false)]
[InlineData("example.com", "www.example.com", true)]
[InlineData("com", "example.com", false)]
[InlineData("example", "example", true)]
[InlineData("compute.amazonaws.com", "example.compute.amazonaws.com", false)]
[InlineData("example.compute.amazonaws.com", "www.example.compute.amazonaws.com", false)]
[InlineData("amazonaws.com", "www.example.compute.amazonaws.com", false)]
[InlineData("amazonaws.com", "test.amazonaws.com", true)]
// Custom tests
[InlineData("sub.login.bitwarden.com", "https://login.bitwarden.com:1337", false)]
[InlineData("passwordless.dev", "https://login.bitwarden.com:1337", false)]
[InlineData("login.passwordless.dev", "https://login.bitwarden.com:1337", false)]
[InlineData("bitwarden", "localhost", false)]
[InlineData("bitwarden", "bitwarden", true)]
[InlineData("127.0.0.1", "127.0.0.1", false)]
[InlineData("localhost", "https://localhost:8080", true)]
[InlineData("bitwarden.com", "https://bitwarden.com", true)]
[InlineData("bitwarden.com", "https://login.bitwarden.com:1337", true)]
[InlineData("login.bitwarden.com", "https://login.bitwarden.com:1337", true)]
[InlineData("login.bitwarden.com", "https://sub.login.bitwarden.com:1337", true)]
public void ValidateRpId(string rpId, string origin, bool isValid)
{
Assert.Equal(isValid, Fido2DomainUtils.IsValidRpId(rpId, origin));
}
}
}

View File

@@ -0,0 +1,81 @@
using System;
using Bit.Core.Utilities;
using Xunit;
namespace Bit.Core.Test.Utilities.Fido2
{
public class GuidExtensionsTests
{
[Theory]
[InlineData("59788da2-4221-4725-8503-52fea66df0b2", new byte[] {0x59, 0x78, 0x8d, 0xa2, 0x42, 0x21, 0x47, 0x25, 0x85, 0x03, 0x52, 0xfe, 0xa6, 0x6d, 0xf0, 0xb2})]
[InlineData("e7895b55-2149-4cad-9e53-989192320a8a", new byte[] {0xe7, 0x89, 0x5b, 0x55, 0x21, 0x49, 0x4c, 0xad, 0x9e, 0x53, 0x98, 0x91, 0x92, 0x32, 0x0a, 0x8a})]
[InlineData("d12f1371-5c89-4d20-a72f-0522674bdec7", new byte[] {0xd1, 0x2f, 0x13, 0x71, 0x5c, 0x89, 0x4d, 0x20, 0xa7, 0x2f, 0x05, 0x22, 0x67, 0x4b, 0xde, 0xc7})]
[InlineData("040b76e4-aff1-4090-aaa2-7f781eb1f1ac", new byte[] {0x04, 0x0b, 0x76, 0xe4, 0xaf, 0xf1, 0x40, 0x90, 0xaa, 0xa2, 0x7f, 0x78, 0x1e, 0xb1, 0xf1, 0xac})]
[InlineData("bda63808-9bf6-427b-97b6-37f3b8d8f0ea", new byte[] {0xbd, 0xa6, 0x38, 0x08, 0x9b, 0xf6, 0x42, 0x7b, 0x97, 0xb6, 0x37, 0xf3, 0xb8, 0xd8, 0xf0, 0xea})]
[InlineData("5dfb0c92-0243-4c39-bf2b-29ffea097b96", new byte[] {0x5d, 0xfb, 0x0c, 0x92, 0x02, 0x43, 0x4c, 0x39, 0xbf, 0x2b, 0x29, 0xff, 0xea, 0x09, 0x7b, 0x96})]
[InlineData("5a65a8aa-6b88-4c72-bc11-a8a80ba9431e", new byte[] {0x5a, 0x65, 0xa8, 0xaa, 0x6b, 0x88, 0x4c, 0x72, 0xbc, 0x11, 0xa8, 0xa8, 0x0b, 0xa9, 0x43, 0x1e})]
[InlineData("76e7c061-892a-4740-a33c-2a52ea7ccb57", new byte[] {0x76, 0xe7, 0xc0, 0x61, 0x89, 0x2a, 0x47, 0x40, 0xa3, 0x3c, 0x2a, 0x52, 0xea, 0x7c, 0xcb, 0x57})]
[InlineData("322d5ade-6f81-4d7e-ab9c-8155d9a6a50f", new byte[] {0x32, 0x2d, 0x5a, 0xde, 0x6f, 0x81, 0x4d, 0x7e, 0xab, 0x9c, 0x81, 0x55, 0xd9, 0xa6, 0xa5, 0x0f})]
[InlineData("51927742-4e17-40af-991c-d958514ceedb", new byte[] {0x51, 0x92, 0x77, 0x42, 0x4e, 0x17, 0x40, 0xaf, 0x99, 0x1c, 0xd9, 0x58, 0x51, 0x4c, 0xee, 0xdb})]
public void GuidToRawFormat_ReturnsRawFormat_GivenCorrectlyFormattedGuid(string standardFormat, byte[] rawFormat)
{
var result = GuidExtensions.GuidToRawFormat(standardFormat);
Assert.Equal(rawFormat, result);
}
[Theory]
[InlineData("59788da-4221-4725-8503-52fea66df0b2")]
[InlineData("e7895b552-149-4cad-9e53-989192320a8a")]
[InlineData("x12f1371-5c89-4d20-a72f-0522674bdec7")]
[InlineData("040b76e4-aff1-4090-Aaa2-7f781eb1f1ac")]
[InlineData("bda63808-9bf6-427b-97b63-7f3b8d8f0ea")]
[InlineData("")]
public void GuidToRawFormat_ThrowsFormatException_IncorrectlyFormattedGuid(string standardFormat)
{
Assert.Throws<FormatException>(() => GuidExtensions.GuidToRawFormat(standardFormat));
}
[Fact]
public void GuidToRawFormat_ThrowsArgumentException_NullArgument()
{
Assert.Throws<ArgumentException>(() => GuidExtensions.GuidToRawFormat(null));
}
[Theory]
[InlineData(new byte[] {0x59, 0x78, 0x8d, 0xa2, 0x42, 0x21, 0x47, 0x25, 0x85, 0x03, 0x52, 0xfe, 0xa6, 0x6d, 0xf0, 0xb2}, "59788da2-4221-4725-8503-52fea66df0b2")]
[InlineData(new byte[] {0xe7, 0x89, 0x5b, 0x55, 0x21, 0x49, 0x4c, 0xad, 0x9e, 0x53, 0x98, 0x91, 0x92, 0x32, 0x0a, 0x8a}, "e7895b55-2149-4cad-9e53-989192320a8a")]
[InlineData(new byte[] {0xd1, 0x2f, 0x13, 0x71, 0x5c, 0x89, 0x4d, 0x20, 0xa7, 0x2f, 0x05, 0x22, 0x67, 0x4b, 0xde, 0xc7}, "d12f1371-5c89-4d20-a72f-0522674bdec7")]
[InlineData(new byte[] {0x04, 0x0b, 0x76, 0xe4, 0xaf, 0xf1, 0x40, 0x90, 0xaa, 0xa2, 0x7f, 0x78, 0x1e, 0xb1, 0xf1, 0xac}, "040b76e4-aff1-4090-aaa2-7f781eb1f1ac")]
[InlineData(new byte[] {0xbd, 0xa6, 0x38, 0x08, 0x9b, 0xf6, 0x42, 0x7b, 0x97, 0xb6, 0x37, 0xf3, 0xb8, 0xd8, 0xf0, 0xea}, "bda63808-9bf6-427b-97b6-37f3b8d8f0ea")]
[InlineData(new byte[] {0x5d, 0xfb, 0x0c, 0x92, 0x02, 0x43, 0x4c, 0x39, 0xbf, 0x2b, 0x29, 0xff, 0xea, 0x09, 0x7b, 0x96}, "5dfb0c92-0243-4c39-bf2b-29ffea097b96")]
[InlineData(new byte[] {0x5a, 0x65, 0xa8, 0xaa, 0x6b, 0x88, 0x4c, 0x72, 0xbc, 0x11, 0xa8, 0xa8, 0x0b, 0xa9, 0x43, 0x1e}, "5a65a8aa-6b88-4c72-bc11-a8a80ba9431e")]
[InlineData(new byte[] {0x76, 0xe7, 0xc0, 0x61, 0x89, 0x2a, 0x47, 0x40, 0xa3, 0x3c, 0x2a, 0x52, 0xea, 0x7c, 0xcb, 0x57}, "76e7c061-892a-4740-a33c-2a52ea7ccb57")]
[InlineData(new byte[] {0x32, 0x2d, 0x5a, 0xde, 0x6f, 0x81, 0x4d, 0x7e, 0xab, 0x9c, 0x81, 0x55, 0xd9, 0xa6, 0xa5, 0x0f}, "322d5ade-6f81-4d7e-ab9c-8155d9a6a50f")]
[InlineData(new byte[] {0x51, 0x92, 0x77, 0x42, 0x4e, 0x17, 0x40, 0xaf, 0x99, 0x1c, 0xd9, 0x58, 0x51, 0x4c, 0xee, 0xdb}, "51927742-4e17-40af-991c-d958514ceedb")]
public void GuidToStandardFormat(byte[] rawFormat, string standardFormat)
{
var result = GuidExtensions.GuidToStandardFormat(rawFormat);
Assert.Equal(standardFormat, result);
}
[Fact]
public void GuidToStandardFormat_ThrowsArgumentException_NullArgument()
{
Assert.Throws<ArgumentException>(() => GuidExtensions.GuidToStandardFormat(null));
}
[Fact]
public void GuidToStandardFormat_ThrowsArgumentException_TooLarge()
{
Assert.Throws<ArgumentException>(() => GuidExtensions.GuidToStandardFormat(new byte[17]));
}
[Fact]
public void GuidToStandardFormat_ThrowsArgumentException_TooShort()
{
Assert.Throws<ArgumentException>(() => GuidExtensions.GuidToStandardFormat(new byte[15]));
}
}
}