-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Keystore.kt
955 lines (878 loc) · 34.9 KB
/
Keystore.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
package me.henneke.wearauthn.fido.context
import android.content.Context
import android.os.Build
import android.security.keystore.*
import androidx.core.content.edit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import me.henneke.wearauthn.*
import me.henneke.wearauthn.Logging.Companion.e
import me.henneke.wearauthn.Logging.Companion.i
import me.henneke.wearauthn.Logging.Companion.w
import me.henneke.wearauthn.fido.ctap2.*
import me.henneke.wearauthn.fido.u2f.Response
import me.henneke.wearauthn.ui.defaultSharedPreferences
import java.lang.Integer.max
import java.nio.ByteBuffer
import java.security.*
import java.security.interfaces.ECPublicKey
import java.security.spec.ECGenParameterSpec
import java.security.spec.ECParameterSpec
import java.text.SimpleDateFormat
import java.time.Instant
import java.util.*
import javax.crypto.*
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.or
private const val TAG = "Keystore"
private const val PROVIDER_ANDROID_KEYSTORE = "AndroidKeyStore"
private const val MASTER_SIGNING_KEY_ALIAS = "%MASTER_SIGNING_KEY%"
private const val USER_INFO_ENCRYPTION_KEY_ALIAS = "%USER_INFO_ENCRYPTION_KEY%"
private const val USER_VERIFICATION_FUSE_KEY_ALIAS = "%USER_VERIFICATION_FUSE_KEY%"
private const val HMAC_SECRET_KEY_ALIAS_PREFIX = "%HMAC_SECRET%"
private const val HMAC_CONTEXT_HMAC_SECRET_USER_NOT_VERIFIED = "user_not_verified"
private const val AES_GCM_NO_PADDING = "AES/GCM/NoPadding"
private const val AES_CBC_NO_PADDING = "AES/CBC/NoPadding"
const val USER_VERIFICATION_TIMEOUT_S = 5 * 60 // 5 minutes
// Resident keys created with a validity not sufficiently long in the past lead to spurious errors.
// As a workaround, we shift all validity dates one day into the past.
const val RESIDENT_KEY_CREATION_TIME_SHIFT_S = 24 * 60 * 60L // 1 day
fun KeyStore.getSecretKey(keyAlias: String): SecretKey? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
getKey(keyAlias, null) as? SecretKey
} else {
(getEntry(keyAlias, null) as? KeyStore.SecretKeyEntry)?.secretKey
}
}
fun KeyStore.getPrivateKey(keyAlias: String): PrivateKey? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
getKey(keyAlias, null) as? PrivateKey
} else {
(getEntry(keyAlias, null) as? KeyStore.PrivateKeyEntry)?.privateKey
}
}
fun KeyStore.getPublicKey(keyAlias: String): PublicKey? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
getCertificate(keyAlias).publicKey
} else {
(getEntry(keyAlias, null) as? KeyStore.PrivateKeyEntry)?.certificate?.publicKey
}
}
private fun generateSymmetricKey(
algorithm: String,
builder: KeyGenParameterSpec.Builder
): SecretKey? {
return try {
val kpg = KeyGenerator.getInstance(
algorithm,
PROVIDER_ANDROID_KEYSTORE
)
val parameterSpec = builder.build()
kpg.run {
init(parameterSpec)
generateKey()
}
} catch (error: Exception) {
if (error is UserNotAuthenticatedException)
throw error
e(TAG, error) { "Failed to generate symmetric key:" }
null
}
}
private fun generateEllipticCurveKey(builder: KeyGenParameterSpec.Builder): KeyPair? {
return try {
val kpg =
KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_EC,
PROVIDER_ANDROID_KEYSTORE
)
val parameterSpec = builder.build()
kpg.run {
initialize(parameterSpec)
generateKeyPair()
}
} catch (error: Exception) {
if (error is UserNotAuthenticatedException)
throw error
e(TAG, error) { "Failed to generate EC key:" }
null
}
}
private val authenticatorKeyAgreementKeyPair: KeyPair by lazy {
val ecParameterSpec = ECGenParameterSpec("secp256r1")
val kpg = KeyPairGenerator.getInstance("EC")
kpg.initialize(ecParameterSpec)
kpg.genKeyPair()
}
@ExperimentalUnsignedTypes
val authenticatorKeyAgreementKey
get() = getCoseRepresentation(
authenticatorKeyAgreementKeyPair.public as ECPublicKey,
ECAlgorithm.KeyAgreement
)
val authenticatorKeyAgreementParams: ECParameterSpec
get() = (authenticatorKeyAgreementKeyPair.public as ECPublicKey).params
fun agreeOnSharedSecret(platformKey: PublicKey): ByteArray {
return KeyAgreement.getInstance("ECDH").run {
init(authenticatorKeyAgreementKeyPair.private)
doPhase(platformKey, true)
generateSecret()
}.sha256()
}
fun decryptSalt(
sharedSecret: ByteArray,
saltEnc: ByteArray,
saltAuth: ByteArray
): ByteArray? {
val saltAuthComputed = Mac.getInstance("HmacSHA256").run {
init(SecretKeySpec(sharedSecret, "HmacSHA256"))
doFinal(saltEnc)
}.take(16).toByteArray()
if (!MessageDigest.isEqual(saltAuth, saltAuthComputed))
return null
// hmac-secret uses an IV consisting of 0s since the plaintexts are (approximately) random
// NOTE: This causes a warning on insecure uses of cryptography in the Play Console.
val iv = IvParameterSpec(ByteArray(16))
return Cipher.getInstance(AES_CBC_NO_PADDING).run {
init(Cipher.DECRYPT_MODE, SecretKeySpec(sharedSecret, AES_CBC_NO_PADDING), iv)
doFinal(saltEnc)
}
}
fun encryptHmacOutput(sharedSecret: ByteArray, hmacSecret: ByteArray): ByteArray {
// hmac-secret uses an IV consisting of 0s since the plaintexts are (approximately) random
// NOTE: This causes a warning on insecure uses of cryptography in the Play Console.
val iv = IvParameterSpec(ByteArray(16))
return Cipher.getInstance(AES_CBC_NO_PADDING).run {
init(Cipher.ENCRYPT_MODE, SecretKeySpec(sharedSecret, AES_CBC_NO_PADDING), iv)
doFinal(hmacSecret)
}
}
fun generateWebAuthnCredential(
createResidentKey: Boolean = false,
createHmacSecret: Boolean = false,
attestationChallenge: ByteArray? = null
): String? {
val nonce = ByteArray(32)
SecureRandom.getInstanceStrong().nextBytes(nonce)
val keyAlias = nonce.base64()
val purpose = KeyProperties.PURPOSE_SIGN
val ecParameterSpec = KeyGenParameterSpec.Builder(keyAlias, purpose).apply {
setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
setDigests(KeyProperties.DIGEST_SHA256)
setKeySize(256)
setAttestationChallenge(attestationChallenge)
if (createResidentKey) {
setKeyValidityStart(
Date.from(
Instant.now().minusSeconds(
RESIDENT_KEY_CREATION_TIME_SHIFT_S
)
)
)
}
}
generateEllipticCurveKey(ecParameterSpec) ?: return null
if (createHmacSecret) {
val hmacParameterSpec =
KeyGenParameterSpec.Builder(
HMAC_SECRET_KEY_ALIAS_PREFIX + keyAlias,
KeyProperties.PURPOSE_SIGN
)
.apply {
setDigests(KeyProperties.DIGEST_SHA256)
setKeySize(256)
}
if (generateSymmetricKey(
KeyProperties.KEY_ALGORITHM_HMAC_SHA256,
hmacParameterSpec
) == null
) {
deleteKey(keyAlias)
return null
}
}
return keyAlias
}
private fun getOrCreateUserInfoEncryptionKeyIfNecessary(): SecretKey? {
if (isValidKeyAlias(USER_INFO_ENCRYPTION_KEY_ALIAS))
return androidKeystore.getSecretKey(USER_INFO_ENCRYPTION_KEY_ALIAS)
val purposes = KeyProperties.PURPOSE_DECRYPT or KeyProperties.PURPOSE_ENCRYPT
val parameterSpec =
KeyGenParameterSpec.Builder(USER_INFO_ENCRYPTION_KEY_ALIAS, purposes).apply {
setBlockModes(KeyProperties.BLOCK_MODE_GCM)
setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
setUserAuthenticationRequired(true)
// Long enough that users should not be asked to confirm their device credentials
// because of it in normal usage scenarios, but short enough not to trigger undocumented
// Keystore failures (at around a week).
setUserAuthenticationValidityDurationSeconds(3 * 24 * 60 * 60)
}
return generateSymmetricKey(
KeyProperties.KEY_ALGORITHM_AES,
parameterSpec
).also {
if (it == null)
e(TAG) { "Failed to initialize user info encryption key" }
}
}
private fun recreateInvalidatedUserInfoEncryptionKey(): SecretKey? {
i(TAG) { "User info encryption was no longer valid and has been recreated" }
deleteKey(USER_INFO_ENCRYPTION_KEY_ALIAS)
return getOrCreateUserInfoEncryptionKeyIfNecessary()
}
fun encryptWithUserInfoEncryptionKey(data: ByteArray): ByteArray? {
val secretKey = try {
getOrCreateUserInfoEncryptionKeyIfNecessary()
} catch (e: UnrecoverableEntryException) {
recreateInvalidatedUserInfoEncryptionKey()
} ?: return null
val cipher = try {
Cipher.getInstance(AES_GCM_NO_PADDING).apply {
init(Cipher.ENCRYPT_MODE, secretKey)
}
} catch (e: KeyPermanentlyInvalidatedException) {
val newSecretKey = recreateInvalidatedUserInfoEncryptionKey()
?: return null
Cipher.getInstance(AES_GCM_NO_PADDING).apply {
init(Cipher.ENCRYPT_MODE, newSecretKey)
}
}
val iv = cipher.iv
check(iv.size < 256)
val cipherText = cipher.doFinal(data)
// We assume that the length of the auth tag is 16, which is the default.
check(cipherText.size == data.size + 16)
return byteArrayOf(iv.size.toByte()) + iv + cipherText
}
fun decryptWithUserInfoEncryptionKey(data: ByteArray): ByteArray? {
if (data.isEmpty()) {
e(TAG) { "Failed to decrypt user info: Stored data is empty" }
return null
}
val ivSize = data[0]
if (data.size < 1 + ivSize) {
e(TAG) { "Failed to decrypt user info: Stored IV size is invalid." }
return null
}
val iv = data.sliceArray(1 until 1 + ivSize)
val cipherText = data.sliceArray(1 + ivSize until data.size)
return try {
val secretKey = androidKeystore.getSecretKey(USER_INFO_ENCRYPTION_KEY_ALIAS) ?: return null
Cipher.getInstance(AES_GCM_NO_PADDING).run {
init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(128, iv))
doFinal(cipherText)
}
} catch (error: Exception) {
if (error is UnrecoverableEntryException || error is KeyPermanentlyInvalidatedException) {
recreateInvalidatedUserInfoEncryptionKey()
} else if (error is UserNotAuthenticatedException) {
throw error
} else {
e(TAG, error) { "Failed to decrypt user info:" }
}
null
}
}
fun armUserVerificationFuse(context: Context) {
if (getUserVerificationState(context) != false)
return
context.defaultSharedPreferences.edit {
putBoolean(FUSE_CREATED_PREFERENCE_KEY, true)
}
val parameterSpec =
KeyGenParameterSpec.Builder(USER_VERIFICATION_FUSE_KEY_ALIAS, KeyProperties.PURPOSE_SIGN)
.apply {
setDigests(KeyProperties.DIGEST_SHA256)
setKeySize(256)
setUserAuthenticationRequired(true)
setUserAuthenticationValidityDurationSeconds(USER_VERIFICATION_TIMEOUT_S)
setUserAuthenticationValidWhileOnBody(true)
}
// No need to handle UserNotAuthenticatedException here since the user confirmed their device
// credential just before this function was called.
if (generateSymmetricKey(
KeyProperties.KEY_ALGORITHM_HMAC_SHA256,
parameterSpec
) != null
)
i(TAG) { "Armed user verification fuse" }
else
e(TAG) { "Failed to arm user verification fuse" }
}
fun getUserVerificationState(context: Context, obeyTimeout: Boolean = false): Boolean? {
val fuseCreated = context.defaultSharedPreferences.getBoolean(
FUSE_CREATED_PREFERENCE_KEY, true
)
return try {
val secretKey = androidKeystore.getSecretKey(USER_VERIFICATION_FUSE_KEY_ALIAS)
?: return if (fuseCreated) {
e(TAG) { "Fuse not present but 'fuse_created' preference is set to true" }
null
} else {
false
}
// Initialize a signature operation to collect a KeyPermanentlyInvalidatedException if the
// secure lock screen has been disabled since the creation of the fuse.
Mac.getInstance("HmacSHA256").init(secretKey)
if (fuseCreated) {
true
} else {
e(TAG) { "Fuse present but 'fuse_created' preference is set to false" }
null
}
} catch (error: Exception) {
if (error is UserNotAuthenticatedException) {
// We do not care about whether the user has recently authenticated, unless we are
// asked explicitly to check the timeout.
if (obeyTimeout) {
throw error
} else {
true
}
} else {
if (error !is UnrecoverableEntryException && error !is KeyPermanentlyInvalidatedException)
e(TAG, error) { "Unexpectedly failed to access fuse:" }
null
}
}.also { i(TAG) { "User verification state is: $it" } }
}
private val androidKeystore = KeyStore.getInstance(PROVIDER_ANDROID_KEYSTORE).apply { load(null) }
val isKeystoreEmpty
get() = androidKeystore.size() == 0
fun isValidKeyAlias(keyAlias: String): Boolean {
return androidKeystore.containsAlias(keyAlias)
}
fun deleteKey(keyAlias: String) {
androidKeystore.deleteEntry(keyAlias)
}
fun deleteAllKeys() {
for (keyAlias in androidKeystore.aliases()) {
deleteKey(keyAlias)
}
}
fun getCertificateChain(keyAlias: String): Array<out java.security.cert.Certificate>? {
return androidKeystore.getCertificateChain(keyAlias)
}
fun initMasterSigningKeyIfNecessary() {
synchronized(MASTER_SIGNING_KEY_ALIAS) {
if (!isValidKeyAlias(MASTER_SIGNING_KEY_ALIAS)) {
val parameterSpec =
KeyGenParameterSpec.Builder(MASTER_SIGNING_KEY_ALIAS, KeyProperties.PURPOSE_SIGN)
.apply {
setDigests(KeyProperties.DIGEST_SHA256)
setKeySize(256)
}
check(
generateSymmetricKey(
KeyProperties.KEY_ALGORITHM_HMAC_SHA256,
parameterSpec
) != null
) { "Failed to initialize master signing key" }
}
}
}
private fun signWithMasterSigningKey(vararg data: ByteArray): ByteArray {
val secretKey = androidKeystore.getSecretKey(MASTER_SIGNING_KEY_ALIAS)!!
return Mac.getInstance("HmacSHA256").run {
init(secretKey)
for (datum in data) {
update(datum)
}
doFinal()
}
}
fun pokeMasterSigningKey() {
GlobalScope.launch(Dispatchers.IO) {
signWithMasterSigningKey(byteArrayOf(0))
}
}
private fun verifyWithMasterSigningKey(signature: ByteArray, vararg data: ByteArray): Boolean {
return MessageDigest.isEqual(signWithMasterSigningKey(*data), signature)
}
data class Assertion(val authenticatorData: ByteArray, val signature: ByteArray) {
init {
require(authenticatorData.size >= 32 + 1 + 4)
}
}
abstract class Credential {
abstract val rpIdHash: ByteArray
protected abstract val keyAlias: String
private val keyInfo by lazy { getKeyInfo(keyAlias) }
val isResident: Boolean
get() = creationDate != null
val creationDate: Date?
get() {
val validityStart = keyInfo?.keyValidityStart ?: return null
return Date.from(
validityStart.toInstant().plusSeconds(RESIDENT_KEY_CREATION_TIME_SHIFT_S)
)
}
val isKeyMaterialInTEE: Boolean
get() = keyInfo?.isInsideSecureHardware == true
protected abstract fun toKeyHandle(): ByteArray
private var _keyHandle: ByteArray? = null
val keyHandle: ByteArray
get() = _keyHandle ?: toKeyHandle().also { _keyHandle = it }
val u2fPublicKeyRepresentation by lazy {
val publicKey = androidKeystore.getPublicKey(keyAlias) as? ECPublicKey
if (publicKey != null)
getUncompressedRepresentation(publicKey)
else
null
}
@ExperimentalUnsignedTypes
val ctap2PublicKeyRepresentation by lazy {
val publicKey = androidKeystore.getPublicKey(keyAlias) as? ECPublicKey
if (publicKey != null)
getCoseRepresentation(publicKey, ECAlgorithm.Signature)
else
null
}
@ExperimentalUnsignedTypes
fun toCborCredential(): CborTextStringMap {
return CborTextStringMap(
mapOf(
"type" to CborTextString("public-key"),
"id" to CborByteString(keyHandle)
)
)
}
fun sign(vararg data: ByteArray): ByteArray {
val privateKey = androidKeystore.getPrivateKey(keyAlias)!!
return Signature.getInstance("SHA256withECDSA").run {
initSign(privateKey)
for (datum in data) {
update(datum)
}
sign()
}
}
@ExperimentalUnsignedTypes
private fun assert(
clientDataHash: ByteArray,
extensionOutputs: CborValue?,
userPresent: Boolean,
userVerified: Boolean,
context: AuthenticatorContext
): Assertion {
val flags = (if (extensionOutputs != null) FLAGS_ED_INCLUDED else 0) or
(if (userPresent) FLAGS_USER_PRESENT else 0) or
(if (userVerified) FLAGS_USER_VERIFIED else 0)
// Either we just created the credential and the counter, or its existence has been checked
// in fromKeyHandle.
val counter = context.atomicallyIncrementAndGetCounter(keyAlias)!!
val authenticatorData =
rpIdHash + flags.bytes() + counter.bytes() + (extensionOutputs?.toCbor()
?: byteArrayOf())
val signature = sign(authenticatorData, clientDataHash)
return Assertion(authenticatorData, signature)
}
@ExperimentalUnsignedTypes
fun assertU2f(
clientDataHash: ByteArray,
userPresent: Boolean,
userVerified: Boolean,
context: AuthenticatorContext
): Response.AuthenticationResponse {
val assertion = assert(clientDataHash, null, userPresent, userVerified, context)
return Response.AuthenticationResponse(assertion.authenticatorData.sliceArray(32 until 37) + assertion.signature)
}
@ExperimentalUnsignedTypes
fun assertWebAuthn(
clientDataHash: ByteArray,
extensionOutputs: CborValue?,
userPresent: Boolean,
userVerified: Boolean,
numberOfCredentials: Int?,
userSelected: Boolean,
returnCredential: Boolean,
context: AuthenticatorContext
): CborLongMap {
val assertion = assert(clientDataHash, extensionOutputs, userPresent, userVerified, context)
val resultMap = mutableMapOf<Long, CborValue>(
GET_ASSERTION_RESPONSE_AUTH_DATA to CborByteString(assertion.authenticatorData),
GET_ASSERTION_RESPONSE_SIGNATURE to CborByteString(assertion.signature)
)
if (returnCredential)
resultMap[GET_ASSERTION_RESPONSE_CREDENTIAL] = toCborCredential()
val usesMultipleResidentKeys = numberOfCredentials != 1
check(usesMultipleResidentKeys implies isResident)
if (isResident) {
// Resident keys are always WebAuthn credentials.
check(this is WebAuthnCredential)
// For a resident key, we have to add a "user" field to the result, which contains
// personal information only if the authenticator does not use the display and there are
// multiple assertions that need to be returned. At this point, the personal information
// is not null only if the user has been verified.
val userMap = mutableMapOf<String, CborValue>(
// userId is ensured to be not null in deserialize.
"id" to CborByteString(userId!!)
)
if (!context.isHidTransport && usesMultipleResidentKeys) {
if (userDisplayName != null || userName != null || userIcon != null)
i(TAG) { "Revealing personal information to the client" }
userDisplayName?.let { userMap["displayName"] = CborTextString(it) }
userName?.let { userMap["name"] = CborTextString(it) }
userIcon?.let { userMap["icon"] = CborTextString(it) }
}
resultMap[GET_ASSERTION_RESPONSE_USER] = CborTextStringMap(userMap)
}
if (numberOfCredentials != null && numberOfCredentials != 1)
resultMap[GET_ASSERTION_RESPONSE_NUMBER_OF_CREDENTIALS] =
CborLong(numberOfCredentials.toLong())
if (userSelected)
resultMap[GET_ASSERTION_RESPONSE_USER_SELECTED] = CborBoolean(true)
return CborLongMap(resultMap)
}
@ExperimentalUnsignedTypes
open fun delete(context: AuthenticatorContext) {
context.deleteCounter(keyAlias)
deleteKey(keyAlias)
}
companion object {
@ExperimentalUnsignedTypes
fun fromKeyHandle(
keyHandle: ByteArray,
rpIdHash: ByteArray,
context: AuthenticatorContext
): Credential? {
require(rpIdHash.size == 32)
if (keyHandle.size < 64)
return null
val keyHandleData = keyHandle.sliceArray(0 until keyHandle.size - 32)
val keyHandleSignature = keyHandle.sliceArray(keyHandle.size - 32 until keyHandle.size)
if (!verifyWithMasterSigningKey(
keyHandleSignature,
rpIdHash,
keyHandleData
)
)
return null
val nonce = keyHandleData.sliceArray(0 until 32)
val keyAlias = nonce.base64()
if (!context.isValidWebAuthnCredentialKeyAlias(keyAlias)) {
w(TAG) { "Valid signature, but invalid counter or Keystore entry" }
return null
}
return if (keyHandleData.size == 32) {
// U2F: keyHandleData only consists of the nonce.
U2FCredential(keyAlias, rpIdHash)
} else {
// WebAuthn: keyHandleData consists of the nonce, a null byte, and the RP name.
// At this point, keyHandleData has size at least 33.
if (keyHandleData[32] != 0.toByte()) {
// This should never happen since we would have had to sign an invalid handle.
e(TAG) { "Encountered invalid signed key handle: missing zero byte" }
return null
}
val rawRpName = keyHandleData.sliceArray(33 until keyHandleData.size)
val rpName = if (rawRpName.isNotEmpty())
rawRpName.decodeToStringOrNull() ?: run {
w(TAG) { "Failed to decode RP name in key handle" }
return@fromKeyHandle null
}
else
null
WebAuthnCredential(
keyAlias,
rpIdHash,
rpName
)
}.also { it._keyHandle = keyHandle }
}
@ExperimentalUnsignedTypes
fun fromCborCredential(
credential: CborValue,
rpIdHash: ByteArray,
context: AuthenticatorContext
): Credential? {
val map = credential.unbox<Map<String, CborValue>>()
if (map["type"].unbox<String>() != "public-key")
return null
val credentialId = map["id"].unbox<ByteArray>()
return fromKeyHandle(
credentialId,
rpIdHash,
context
)
}
}
}
data class U2FCredential(override val keyAlias: String, override val rpIdHash: ByteArray) :
Credential() {
init {
require(keyAlias.base64() != null)
require(rpIdHash.size == 32)
}
override fun toKeyHandle(): ByteArray {
require(rpIdHash.size == 32)
val nonce = keyAlias.base64()!!
val keyHandleSignature =
signWithMasterSigningKey(rpIdHash, nonce)
return nonce + keyHandleSignature
}
}
@ExperimentalUnsignedTypes
class WebAuthnCredential(
override val keyAlias: String,
override val rpIdHash: ByteArray,
val rpName: String? = null,
val userId: ByteArray? = null,
userDisplayName: String? = null,
userName: String? = null,
userIcon: String? = null,
val encryptedUserMap: ByteArray? = null
) : Credential() {
init {
require(keyAlias.base64()?.size == 32)
require(rpIdHash.size == 32)
require(rpName == null || rpName.length <= 64)
}
var userDisplayName = userDisplayName
private set
var userName = userName
private set
var userIcon = userIcon
private set
override fun toKeyHandle(): ByteArray {
val nonce = keyAlias.base64()!!
val keyHandleData = nonce + byteArrayOf(0) + (rpName?.toByteArray() ?: byteArrayOf())
val keyHandleSignature =
signWithMasterSigningKey(
rpIdHash,
keyHandleData
)
return keyHandleData + keyHandleSignature
}
fun unlockUserInfoIfNecessary() {
if (!isResident || encryptedUserMap == null)
return
val rawUserMap =
decryptWithUserInfoEncryptionKey(
encryptedUserMap
)
if (rawUserMap != null) {
val userMap = fromCborToEnd(rawUserMap)
userDisplayName = userMap.getOptional("displayName")?.unbox()
userName = userMap.getOptional("name")?.unbox()
userIcon = userMap.getOptional("icon")?.unbox()
}
}
fun serialize(userVerified: Boolean): String {
check(isResident)
// These fields are always present for resident credentials we just created.
check(userId != null)
check(userName != null)
return CborTextStringMap(mutableMapOf<String, CborValue>(
"keyAlias" to CborTextString(keyAlias),
"userId" to CborByteString(userId)
).also { map ->
rpName?.let { map["rpName"] = CborTextString(it) }
// Personal information is stored only if user verification is enabled, which is allowed
// by the spec and works around the potential privacy leak of having someone else
// configure user verification to get access to this information.
if (userVerified) {
val userMap = mutableMapOf(
"name" to CborTextString(userName!!)
)
userDisplayName?.let { userMap["userDisplayName"] = CborTextString(it) }
userIcon?.let { userMap["icon"] = CborTextString(it) }
val encryptedUserMap =
encryptWithUserInfoEncryptionKey(
CborTextStringMap(userMap).toCbor()
)
encryptedUserMap?.let { map["encryptedUser"] = CborByteString(it) }
}
}).toCbor().base64()
}
override fun delete(context: AuthenticatorContext) {
if (isResident)
context.deleteResidentCredential(this)
super.delete(context)
}
fun getTwoLineInfo(simpleCount: Int): Pair<String, String?> {
val userDisplayNameInfo = userDisplayName.takeUnless { it.isNullOrBlank() }
val userNameInfo = userName.takeUnless { it.isNullOrBlank() }
val creationDateInfo =
creationDate?.let { "Created ${SimpleDateFormat.getDateInstance().format(it)}" }
return when {
userDisplayNameInfo != null && userNameInfo != null -> {
Pair(userDisplayNameInfo, userNameInfo)
}
userNameInfo != null -> {
Pair(userNameInfo, creationDateInfo)
}
userDisplayNameInfo != null -> {
Pair(userDisplayNameInfo, creationDateInfo)
}
else -> {
Pair("Account #${simpleCount}", creationDateInfo)
}
}
}
fun getFormattedInfo(): String? {
val userDisplayNameInfo = userDisplayName.takeUnless { it.isNullOrBlank() }
val userNameInfo = userName.takeUnless { it.isNullOrBlank() }
val creationDateInfo =
creationDate?.let { "Created ${SimpleDateFormat.getDateInstance().format(it)}" }
val infoOrBlank = if (userDisplayNameInfo != null) "$userDisplayNameInfo\n" else "" +
if (userNameInfo != null) "$userNameInfo\n" else "" +
if (creationDateInfo != null) "$creationDateInfo" else ""
return infoOrBlank.takeUnless { it.isBlank() }
}
@ExperimentalUnsignedTypes
val androidKeystoreAttestation: CborArray
get() {
val certificateChain = getCertificateChain(
keyAlias
) ?: return CborArray(arrayOf())
return CborArray(certificateChain.map {
CborByteString(it.encoded)
}.toTypedArray())
}
val hasHmacSecret: Boolean
get() = androidKeystore.containsAlias(HMAC_SECRET_KEY_ALIAS_PREFIX + keyAlias)
fun signWithHmacSecret(userVerified: Boolean, vararg data: ByteArray): ByteArray? {
val secretKeyAlias = HMAC_SECRET_KEY_ALIAS_PREFIX + keyAlias
val secretKey = androidKeystore.getSecretKey(secretKeyAlias) ?: return null
return Mac.getInstance("HmacSHA256").run {
init(secretKey)
// CTAP 2.1 requires two HMAC secrets: one if UV has been performed and one if it
// hasn't. We derive both secrets from the same HMAC credential by appending a fixed
// string if UV has not been performed. In this way, we preserve backward compatibility
// with the most (and only) common use case.
if (!userVerified)
update(HMAC_CONTEXT_HMAC_SECRET_USER_NOT_VERIFIED.toByteArray())
for (datum in data) {
update(datum)
}
doFinal()
}
}
companion object : Logging {
override val TAG = "WebAuthnCredential"
fun deserialize(str: String, rpIdHash: ByteArray): WebAuthnCredential? {
i { "Deserializing a WebAuthn credential" }
val bytes = str.base64() ?: run {
w { "Deserialization failed: Invalid Base64" }
return null
}
val cbor = fromCborToEnd(bytes) as? CborTextStringMap ?: run {
w { "Deserialization failed: Invalid CBOR" }
return null
}
val map = cbor.value
val keyAlias = (map["keyAlias"] as? CborTextString)?.value ?: run {
w { "Deserialization failed: Failed to read keyAlias" }
return null
}
val rpName = (map["rpName"] as? CborTextString)?.value
val userId = (map["userId"] as? CborByteString)?.value ?: run {
w { "Deserialization failed: Failed to read userId" }
return null
}
val encryptedUserMap = (map["encryptedUser"] as? CborByteString)?.value
if (encryptedUserMap == null)
d { "Resident credential did not contain encrypted user info" }
val credential = WebAuthnCredential(
keyAlias = keyAlias,
rpIdHash = rpIdHash,
rpName = rpName,
userId = userId,
encryptedUserMap = encryptedUserMap
)
if (!credential.isResident) {
w { "Deserialization failed: Not a resident credential" }
return null
}
return credential
}
}
}
private fun getUncompressedRepresentation(publicKey: ECPublicKey): ByteArray {
val xRaw = publicKey.w.affineX.toByteArray()
require(xRaw.size <= 32 || (xRaw.size == 33 && xRaw[0] == 0.toByte())) { "Can only handle 256 bit keys." }
val yRaw = publicKey.w.affineY.toByteArray()
require(yRaw.size <= 32 || (yRaw.size == 33 && yRaw[0] == 0.toByte())) { "Can only handle 256 bit keys." }
val uncompressed = ByteBuffer.allocate(65)
uncompressed.run {
position(65 - yRaw.size)
put(yRaw)
position(65 - 32 - xRaw.size)
put(xRaw)
position(0)
put(0x04)
}
return uncompressed.array()
}
enum class ECAlgorithm {
Signature,
KeyAgreement
}
@ExperimentalUnsignedTypes
private fun getCoseRepresentation(publicKey: ECPublicKey, algorithm: ECAlgorithm): CborLongMap {
val xRaw = publicKey.w.affineX.toByteArray()
require(xRaw.size <= 32 || (xRaw.size == 33 && xRaw[0] == 0.toByte())) { "Can only handle 256 bit keys." }
val xPadded =
ByteArray(max(32 - xRaw.size, 0)) + xRaw.slice(max(xRaw.size - 32, 0) until xRaw.size)
check(xPadded.size == 32)
val yRaw = publicKey.w.affineY.toByteArray()
require(yRaw.size <= 32 || (yRaw.size == 33 && yRaw[0] == 0.toByte())) { "Can only handle 256 bit keys." }
val yPadded =
ByteArray(max(32 - yRaw.size, 0)) + yRaw.slice(max(yRaw.size - 32, 0) until yRaw.size)
check(yPadded.size == 32)
val template = when (algorithm) {
ECAlgorithm.Signature -> COSE_KEY_ES256_TEMPLATE
ECAlgorithm.KeyAgreement -> COSE_KEY_ECDH_TEMPLATE
}
return CborLongMap(
template + mapOf(
COSE_KEY_EC256_X to CborByteString(xPadded),
COSE_KEY_EC256_Y to CborByteString(yPadded)
)
)
}
private fun getKeyInfo(keyAlias: String): KeyInfo? {
return try {
when (val key = androidKeystore.getKey(keyAlias, null)) {
is SecretKey -> {
val factory =
SecretKeyFactory.getInstance(
key.getAlgorithm(),
PROVIDER_ANDROID_KEYSTORE
)
try {
factory.getKeySpec(key, KeyInfo::class.java) as KeyInfo
} catch (e: Exception) {
null
}
}
is PrivateKey -> {
val factory = KeyFactory.getInstance(
key.getAlgorithm(),
PROVIDER_ANDROID_KEYSTORE
)
try {
factory.getKeySpec(key, KeyInfo::class.java) as KeyInfo
} catch (e: java.lang.Exception) {
null
}
}
else -> null
}
} catch (e: Exception) {
null
}
}
fun checkAllKeysInHardware(): Boolean {
for (alias in androidKeystore.aliases()) {
val keyInfo = getKeyInfo(alias) ?: return false
if (!keyInfo.isInsideSecureHardware || keyInfo.origin != KeyProperties.ORIGIN_GENERATED) {
return false
}
}
return true
}