-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
KeyBackupService.swift
1072 lines (885 loc) · 41.4 KB
/
KeyBackupService.swift
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2020 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
import Argon2
@objc(OWSKeyBackupService)
public class KeyBackupService: NSObject {
public enum KBSError: Error {
case assertion
case invalidPin(triesRemaining: UInt32)
case backupMissing
}
public enum PinType: Int {
case numeric = 1
case alphanumeric = 2
public init(forPin pin: String) {
let normalizedPin = KeyBackupService.normalizePin(pin)
self = normalizedPin.digitsOnly() == normalizedPin ? .numeric : .alphanumeric
}
}
// PRAGMA MARK: - Depdendencies
static var networkManager: TSNetworkManager {
return TSNetworkManager.shared()
}
static var databaseStorage: SDSDatabaseStorage {
return .shared
}
static var tsAccountManager: TSAccountManager {
return .sharedInstance()
}
static var storageServiceManager: StorageServiceManagerProtocol {
return SSKEnvironment.shared.storageServiceManager
}
static var syncManager: SyncManagerProtocol {
return SSKEnvironment.shared.syncManager
}
// PRAGMA MARK: - Pin Management
static let maximumKeyAttempts: UInt32 = 10
/// Indicates whether or not we have a master key locally
@objc
public static var hasMasterKey: Bool {
return getOrLoadStateWithSneakyTransaction().masterKey != nil
}
/// Indicates whether or not we have a master key stored in KBS
@objc
public static var hasBackedUpMasterKey: Bool {
return getOrLoadStateWithSneakyTransaction().isMasterKeyBackedUp
}
public static func hasMasterKey(transaction: SDSAnyReadTransaction) -> Bool {
return getOrLoadState(transaction: transaction).masterKey != nil
}
public static var currentPinType: PinType? {
return getOrLoadStateWithSneakyTransaction().pinType
}
/// Indicates whether your pin is valid when compared to your stored keys.
/// This is a local verification and does not make any requests to the KBS.
@objc
public static func verifyPin(_ pin: String, resultHandler: @escaping (Bool) -> Void) {
DispatchQueue.global().async {
var isValid = false
defer {
DispatchQueue.main.async { resultHandler(isValid) }
}
guard let encodedVerificationString = getOrLoadStateWithSneakyTransaction().encodedVerificationString else {
owsFailDebug("Attempted to verify pin locally when we don't have a verification string")
return
}
guard let pinData = normalizePin(pin).data(using: .utf8) else {
owsFailDebug("failed to determine pin data")
return
}
do {
isValid = try Argon2.verify(encoded: encodedVerificationString, password: pinData, variant: .i)
} catch {
owsFailDebug("Failed to validate encodedVerificationString with error: \(error)")
}
}
}
@objc(restoreKeysWithPin:)
static func objc_RestoreKeys(with pin: String) -> AnyPromise {
return AnyPromise(restoreKeys(with: pin))
}
/// Loads the users key, if any, from the KBS into the database.
public static func restoreKeys(with pin: String, and auth: RemoteAttestationAuth? = nil) -> Promise<Void> {
return fetchBackupId(auth: auth).map(on: .global()) { backupId in
return try deriveEncryptionKeyAndAccessKey(pin: pin, backupId: backupId)
}.then { encryptionKey, accessKey in
restoreKeyRequest(accessKey: accessKey, with: auth).map { ($0, encryptionKey, accessKey) }
}.map(on: .global()) { response, encryptionKey, accessKey -> (Data, Data, Data) in
guard let status = response.status else {
owsFailDebug("KBS restore is missing status")
throw KBSError.assertion
}
// As long as the backup exists we should always receive a
// new token to use on our next request. Store it now.
if status != .missing {
guard let tokenData = response.token else {
owsFailDebug("KBS restore is missing token")
throw KBSError.assertion
}
try Token.updateNext(data: tokenData, tries: response.tries)
}
switch status {
case .tokenMismatch:
// the given token has already been spent. we'll use the new token
// on the next attempt.
owsFailDebug("attempted restore with spent token")
throw KBSError.assertion
case .pinMismatch:
throw KBSError.invalidPin(triesRemaining: response.tries)
case .missing:
throw KBSError.backupMissing
case .notYetValid:
owsFailDebug("the server thinks we provided a `validFrom` in the future")
throw KBSError.assertion
case .ok:
guard let encryptedMasterKey = response.data else {
owsFailDebug("Failed to extract encryptedMasterKey from successful KBS restore response")
throw KBSError.assertion
}
let masterKey = try decryptMasterKey(encryptedMasterKey, encryptionKey: encryptionKey)
return (masterKey, encryptedMasterKey, accessKey)
}
}.then { masterKey, encryptedMasterKey, accessKey in
// Backup our keys again, even though we just fetched them.
// This resets the number of remaining attempts.
backupKeyRequest(accessKey: accessKey, encryptedMasterKey: encryptedMasterKey, and: auth).map { ($0, masterKey) }
}.done(on: .global()) { response, masterKey in
guard let status = response.status else {
owsFailDebug("KBS backup is missing status")
throw KBSError.assertion
}
guard let tokenData = response.token else {
owsFailDebug("KBS restore is missing token")
throw KBSError.assertion
}
// We should always receive a new token to use on our next request.
try Token.updateNext(data: tokenData)
switch status {
case .alreadyExists:
// If we receive already exists, this means our backup has expired and
// been replaced. In normal circumstances this should never happen.
owsFailDebug("Received ALREADY_EXISTS response from KBS")
throw KBSError.assertion
case .notYetValid:
owsFailDebug("the server thinks we provided a `validFrom` in the future")
throw KBSError.assertion
case .ok:
let encodedVerificationString = try deriveEncodedVerificationString(pin: pin)
// We successfully stored the new keys in KBS, save them in the database
databaseStorage.write { transaction in
store(
masterKey: masterKey,
isMasterKeyBackedUp: true,
pinType: PinType(forPin: pin),
encodedVerificationString: encodedVerificationString,
transaction: transaction
)
}
}
}.recover(on: .global()) { error in
guard let kbsError = error as? KBSError else {
owsFailDebug("Unexpectedly surfacing a non KBS error \(error)")
throw error
}
throw kbsError
}
}
@objc(generateAndBackupKeysWithPin:rotateMasterKey:)
@available(swift, obsoleted: 1.0)
static func generateAndBackupKeys(with pin: String, rotateMasterKey: Bool) -> AnyPromise {
return AnyPromise(generateAndBackupKeys(with: pin, rotateMasterKey: rotateMasterKey))
}
/// Backs up the user's master key to KBS and stores it locally in the database.
/// If the user doesn't have a master key already a new one is generated.
public static func generateAndBackupKeys(with pin: String, rotateMasterKey: Bool) -> Promise<Void> {
return fetchBackupId(auth: nil).map(on: .global()) { backupId -> (Data, Data, Data) in
let masterKey: Data = {
if rotateMasterKey { return generateMasterKey() }
return getOrLoadStateWithSneakyTransaction().masterKey ?? generateMasterKey()
}()
let (encryptionKey, accessKey) = try deriveEncryptionKeyAndAccessKey(pin: pin, backupId: backupId)
let encryptedMasterKey = try encryptMasterKey(masterKey, encryptionKey: encryptionKey)
return (masterKey, encryptedMasterKey, accessKey)
}.then { masterKey, encryptedMasterKey, accessKey -> Promise<(KeyBackupProtoBackupResponse, Data)> in
backupKeyRequest(
accessKey: accessKey,
encryptedMasterKey: encryptedMasterKey
).map { ($0, masterKey) }
}.done(on: .global()) { response, masterKey in
guard let status = response.status else {
owsFailDebug("KBS backup is missing status")
throw KBSError.assertion
}
guard let tokenData = response.token else {
owsFailDebug("KBS restore is missing token")
throw KBSError.assertion
}
// We should always receive a new token to use on our next request. Store it now.
try Token.updateNext(data: tokenData)
switch status {
case .alreadyExists:
// the given token has already been spent. we'll use the new token
// on the next attempt.
owsFailDebug("attempted restore with spent token")
case .notYetValid:
owsFailDebug("the server thinks we provided a `validFrom` in the future")
throw KBSError.assertion
case .ok:
let encodedVerificationString = try deriveEncodedVerificationString(pin: pin)
// We successfully stored the new keys in KBS, save them in the database
databaseStorage.write { transaction in
store(
masterKey: masterKey,
isMasterKeyBackedUp: true,
pinType: PinType(forPin: pin),
encodedVerificationString: encodedVerificationString,
transaction: transaction
)
}
}
}.recover(on: .global()) { error in
Logger.error("recording backupKeyRequest errored: \(error)")
databaseStorage.write { transaction in
keyValueStore.setBool(true, key: hasBackupKeyRequestFailedIdentifier, transaction: transaction)
reloadState(transaction: transaction)
}
guard let kbsError = error as? KBSError else {
owsFailDebug("Unexpectedly surfacing a non KBS error: \(error)")
throw error
}
throw kbsError
}
}
@objc(deleteKeys)
static func objc_deleteKeys() -> AnyPromise {
return AnyPromise(deleteKeys())
}
/// Remove the keys locally from the device and from the KBS,
/// they will not be able to be restored.
public static func deleteKeys() -> Promise<Void> {
return deleteKeyRequest().ensure {
// Even if the request to delete our keys from KBS failed,
// purge them from the database.
databaseStorage.write { clearKeys(transaction: $0) }
}.asVoid()
}
// PRAGMA MARK: - Master Key Encryption
public enum DerivedKey: Hashable {
case registrationLock
case storageService
case storageServiceManifest(version: UInt64)
case storageServiceRecord(identifier: StorageService.StorageIdentifier)
var rawValue: String {
switch self {
case .registrationLock:
return "Registration Lock"
case .storageService:
return "Storage Service Encryption"
case .storageServiceManifest(let version):
return "Manifest_\(version)"
case .storageServiceRecord(let identifier):
return "Item_\(identifier.data.base64EncodedString())"
}
}
static var syncableKeys: [DerivedKey] {
return [
.storageService
]
}
private var dataToDeriveFrom: Data? {
switch self {
case .storageServiceManifest, .storageServiceRecord:
return DerivedKey.storageService.data
default:
// Most keys derive directly from the master key.
// Only a few exceptions derive from another derived key.
guard let masterKey = getOrLoadStateWithSneakyTransaction().masterKey else { return nil }
return masterKey
}
}
public var data: Data? {
// If we have this derived key stored in the database, use it.
// This should only happen if we're a linked device and received
// the derived key via a sync message, since we won't know about
// the master key.
if (!tsAccountManager.isPrimaryDevice || CurrentAppContext().isRunningTests),
let cachedData = getOrLoadStateWithSneakyTransaction().syncedDerivedKeys[self] {
return cachedData
}
guard let dataToDeriveFrom = dataToDeriveFrom else {
return nil
}
guard let data = rawValue.data(using: .utf8) else {
owsFailDebug("Failed to encode data")
return nil
}
return Cryptography.computeSHA256HMAC(data, withHMACKey: dataToDeriveFrom)
}
public var isAvailable: Bool { return data != nil }
}
public static func encrypt(keyType: DerivedKey, data: Data) throws -> Data {
guard let keyData = keyType.data, let key = OWSAES256Key(data: keyData) else {
owsFailDebug("missing derived key \(keyType)")
throw KBSError.assertion
}
guard let encryptedData = Cryptography.encryptAESGCMWithDataAndConcatenateResults(
plainTextData: data,
initializationVectorLength: kAESGCM256_DefaultIVLength,
key: key
) else {
owsFailDebug("Failed to encrypt data")
throw KBSError.assertion
}
return encryptedData
}
public static func decrypt(keyType: DerivedKey, encryptedData: Data) throws -> Data {
guard let keyData = keyType.data, let key = OWSAES256Key(data: keyData) else {
owsFailDebug("missing derived key \(keyType)")
throw KBSError.assertion
}
guard let data = Cryptography.decryptAESGCMConcatenatedData(
encryptedData: encryptedData,
initializationVectorLength: kAESGCM256_DefaultIVLength,
key: key
) else {
owsFailDebug("failed to decrypt data")
throw KBSError.assertion
}
return data
}
@objc
static func deriveRegistrationLockToken() -> String? {
return DerivedKey.registrationLock.data?.hexadecimalString
}
// PRAGMA MARK: - Master Key Management
private static func assertIsOnBackgroundQueue() {
guard !CurrentAppContext().isRunningTests else { return }
assertOnQueue(DispatchQueue.global())
}
static func deriveEncryptionKeyAndAccessKey(pin: String, backupId: Data) throws -> (encryptionKey: Data, accessKey: Data) {
assertIsOnBackgroundQueue()
guard let pinData = normalizePin(pin).data(using: .utf8) else { throw KBSError.assertion }
guard backupId.count == 32 else { throw KBSError.assertion }
let (rawHash, _) = try Argon2.hash(
iterations: 32,
memoryInKiB: 1024 * 16, // 16MiB
threads: 1,
password: pinData,
salt: backupId,
desiredLength: 64,
variant: .id,
version: .v13
)
return (encryptionKey: rawHash[0...31], accessKey: rawHash[32...63])
}
static func deriveEncodedVerificationString(pin: String, salt: Data = Cryptography.generateRandomBytes(16)) throws -> String {
assertIsOnBackgroundQueue()
guard let pinData = normalizePin(pin).data(using: .utf8) else { throw KBSError.assertion }
guard salt.count == 16 else { throw KBSError.assertion }
let (_, encodedString) = try Argon2.hash(
iterations: 64,
memoryInKiB: 512,
threads: 1,
password: pinData,
salt: salt,
desiredLength: 32,
variant: .i,
version: .v13
)
return encodedString
}
@objc
public static func normalizePin(_ pin: String) -> String {
// Trim leading and trailing whitespace
var normalizedPin = pin.ows_stripped()
// If this pin contains only numerals, ensure they are arabic numerals.
if pin.digitsOnly() == normalizedPin { normalizedPin = normalizedPin.ensureArabicNumerals }
// NFKD unicode normalization.
return normalizedPin.decomposedStringWithCompatibilityMapping
}
static func generateMasterKey() -> Data {
assertIsOnBackgroundQueue()
return Cryptography.generateRandomBytes(32)
}
static func encryptMasterKey(_ masterKey: Data, encryptionKey: Data) throws -> Data {
assertIsOnBackgroundQueue()
guard masterKey.count == 32 else { throw KBSError.assertion }
guard encryptionKey.count == 32 else { throw KBSError.assertion }
let (iv, cipherText) = try Cryptography.encryptSHA256HMACSIV(data: masterKey, key: encryptionKey)
guard iv.count == 16 else { throw KBSError.assertion }
guard cipherText.count == 32 else { throw KBSError.assertion }
return iv + cipherText
}
static func decryptMasterKey(_ ivAndCipher: Data, encryptionKey: Data) throws -> Data {
assertIsOnBackgroundQueue()
guard ivAndCipher.count == 48 else { throw KBSError.assertion }
let masterKey = try Cryptography.decryptSHA256HMACSIV(
iv: ivAndCipher[0...15],
cipherText: ivAndCipher[16...47],
key: encryptionKey
)
guard masterKey.count == 32 else { throw KBSError.assertion }
return masterKey
}
// PRAGMA MARK: - State
public static var keyValueStore: SDSKeyValueStore {
return SDSKeyValueStore(collection: "kOWSKeyBackupService_Keys")
}
private static let masterKeyIdentifer = "masterKey"
private static let pinTypeIdentifier = "pinType"
private static let encodedVerificationStringIdentifier = "encodedVerificationString"
private static let hasBackupKeyRequestFailedIdentifier = "hasBackupKeyRequestFailed"
private static let hasPendingRestorationIdentifier = "hasPendingRestoration"
private static let isMasterKeyBackedUpIdentifer = "isMasterKeyBackedUp"
private static let cacheQueue = DispatchQueue(label: "org.signal.KeyBackupService")
private static var cachedState: State?
private struct State {
let masterKey: Data?
let pinType: PinType?
let encodedVerificationString: String?
let hasBackupKeyRequestFailed: Bool
let hasPendingRestoration: Bool
let isMasterKeyBackedUp: Bool
let syncedDerivedKeys: [DerivedKey: Data]
init(transaction: SDSAnyReadTransaction) {
masterKey = keyValueStore.getData(masterKeyIdentifer, transaction: transaction)
if let rawPinType = keyValueStore.getInt(pinTypeIdentifier, transaction: transaction) {
pinType = PinType(rawValue: rawPinType)
} else {
pinType = nil
}
encodedVerificationString = keyValueStore.getString(
encodedVerificationStringIdentifier,
transaction: transaction
)
hasBackupKeyRequestFailed = keyValueStore.getBool(
hasBackupKeyRequestFailedIdentifier,
defaultValue: false,
transaction: transaction
)
hasPendingRestoration = keyValueStore.getBool(
hasPendingRestorationIdentifier,
defaultValue: false,
transaction: transaction
)
isMasterKeyBackedUp = keyValueStore.getBool(
isMasterKeyBackedUpIdentifer,
defaultValue: false,
transaction: transaction
)
var syncedDerivedKeys = [DerivedKey: Data]()
for type in DerivedKey.syncableKeys {
syncedDerivedKeys[type] = keyValueStore.getData(type.rawValue, transaction: transaction)
}
self.syncedDerivedKeys = syncedDerivedKeys
}
}
private static func getOrLoadState(transaction: SDSAnyReadTransaction) -> State {
if let cachedState = cacheQueue.sync(execute: { cachedState }) { return cachedState }
return loadState(transaction: transaction)
}
private static func getOrLoadStateWithSneakyTransaction() -> State {
if let cachedState = cacheQueue.sync(execute: { cachedState }) { return cachedState }
return databaseStorage.read { loadState(transaction: $0) }
}
@discardableResult
private static func loadState(transaction: SDSAnyReadTransaction) -> State {
let state = State(transaction: transaction)
cacheQueue.sync { cachedState = state }
return state
}
private static func reloadState(transaction: SDSAnyReadTransaction) {
_ = loadState(transaction: transaction)
}
@objc
public static func warmCaches() {
_ = getOrLoadStateWithSneakyTransaction()
}
/// Removes the KBS keys locally from the device, they can still be
/// restored from the server if you know the pin.
@objc
public static func clearKeys(transaction: SDSAnyWriteTransaction) {
Token.clearNext(transaction: transaction)
keyValueStore.removeValues(forKeys: [
masterKeyIdentifer,
isMasterKeyBackedUpIdentifer,
pinTypeIdentifier,
encodedVerificationStringIdentifier
], transaction: transaction)
for type in DerivedKey.syncableKeys {
keyValueStore.removeValue(forKey: type.rawValue, transaction: transaction)
}
reloadState(transaction: transaction)
}
static func store(
masterKey: Data,
isMasterKeyBackedUp: Bool,
pinType: PinType,
encodedVerificationString: String,
transaction: SDSAnyWriteTransaction
) {
let previousState = getOrLoadState(transaction: transaction)
guard masterKey != previousState.masterKey
|| isMasterKeyBackedUp != previousState.isMasterKeyBackedUp
|| pinType != previousState.pinType
|| encodedVerificationString != previousState.encodedVerificationString else { return }
keyValueStore.setData(
masterKey,
key: masterKeyIdentifer,
transaction: transaction
)
keyValueStore.setBool(
isMasterKeyBackedUp,
key: isMasterKeyBackedUpIdentifer,
transaction: transaction
)
keyValueStore.setInt(
pinType.rawValue,
key: pinTypeIdentifier,
transaction: transaction
)
keyValueStore.setString(
encodedVerificationString,
key: encodedVerificationStringIdentifier,
transaction: transaction
)
// Clear failed status
keyValueStore.setBool(
false,
key: hasBackupKeyRequestFailedIdentifier,
transaction: transaction
)
// Clear pending restore status
keyValueStore.setBool(
false,
key: hasPendingRestorationIdentifier,
transaction: transaction
)
reloadState(transaction: transaction)
// Only continue if we didn't previously have a master key or our master key has changed
guard masterKey != previousState.masterKey, tsAccountManager.isRegisteredAndReady else { return }
// Trigger a re-creation of the storage manifest, our keys have changed
storageServiceManager.resetLocalData(transaction: transaction)
// If the app is ready start that restoration.
guard AppReadiness.isAppReady else { return }
storageServiceManager.restoreOrCreateManifestIfNecessary()
// Sync our new keys with linked devices.
syncManager.sendKeysSyncMessage()
}
public static func storeSyncedKey(type: DerivedKey, data: Data?, transaction: SDSAnyWriteTransaction) {
guard !tsAccountManager.isPrimaryDevice || CurrentAppContext().isRunningTests else {
return owsFailDebug("primary device should never store synced keys")
}
guard DerivedKey.syncableKeys.contains(type) else {
return owsFailDebug("tried to store a non-syncable key")
}
keyValueStore.setData(data, key: type.rawValue, transaction: transaction)
reloadState(transaction: transaction)
// Trigger a re-fetch of the storage manifest, our keys have changed
if type == .storageService, data != nil {
storageServiceManager.restoreOrCreateManifestIfNecessary()
}
}
public static func hasBackupKeyRequestFailed(transaction: SDSAnyReadTransaction) -> Bool {
getOrLoadState(transaction: transaction).hasBackupKeyRequestFailed
}
public static func hasPendingRestoration(transaction: SDSAnyReadTransaction) -> Bool {
getOrLoadState(transaction: transaction).hasPendingRestoration
}
public static func recordPendingRestoration(transaction: SDSAnyWriteTransaction) {
keyValueStore.setBool(true, key: hasPendingRestorationIdentifier, transaction: transaction)
reloadState(transaction: transaction)
}
public static func clearPendingRestoration(transaction: SDSAnyWriteTransaction) {
keyValueStore.removeValue(forKey: hasPendingRestorationIdentifier, transaction: transaction)
reloadState(transaction: transaction)
}
public static func setMasterKeyBackedUp(_ value: Bool, transaction: SDSAnyWriteTransaction) {
keyValueStore.setBool(value, key: isMasterKeyBackedUpIdentifer, transaction: transaction)
reloadState(transaction: transaction)
}
public static func useDeviceLocalMasterKey(transaction: SDSAnyWriteTransaction) {
store(
masterKey: generateMasterKey(),
isMasterKeyBackedUp: false,
pinType: .alphanumeric,
encodedVerificationString: "",
transaction: transaction
)
OWS2FAManager.shared().markDisabled(transaction: transaction)
}
// PRAGMA MARK: - Requests
private static func enclaveRequest<RequestType: KBSRequestOption>(
with auth: RemoteAttestationAuth? = nil,
and requestOptionBuilder: @escaping (Token) throws -> RequestType
) -> Promise<RequestType.ResponseOptionType> {
return RemoteAttestation.performForKeyBackup(auth: auth).then { remoteAttestation in
fetchToken(for: remoteAttestation).map { ($0, remoteAttestation) }
}.map(on: DispatchQueue.global()) { tokenResponse, remoteAttestation -> (TSRequest, RemoteAttestation) in
let requestOption = try requestOptionBuilder(tokenResponse)
let requestBuilder = KeyBackupProtoRequest.builder()
requestOption.set(on: requestBuilder)
let kbRequestData = try requestBuilder.buildSerializedData()
guard let encryptionResult = Cryptography.encryptAESGCM(
plainTextData: kbRequestData,
initializationVectorLength: kAESGCM256_DefaultIVLength,
additionalAuthenticatedData: remoteAttestation.requestId,
key: remoteAttestation.keys.clientKey
) else {
owsFailDebug("Failed to encrypt request data")
throw KBSError.assertion
}
let request = OWSRequestFactory.kbsEnclaveRequest(
withRequestId: remoteAttestation.requestId,
data: encryptionResult.ciphertext,
cryptIv: encryptionResult.initializationVector,
cryptMac: encryptionResult.authTag,
enclaveName: remoteAttestation.enclaveName,
authUsername: remoteAttestation.auth.username,
authPassword: remoteAttestation.auth.password,
cookies: remoteAttestation.cookies,
requestType: RequestType.stringRepresentation
)
return (request, remoteAttestation)
}.then { request, remoteAttestation in
networkManager.makePromise(request: request).map { ($0.responseObject, remoteAttestation) }
}.map(on: DispatchQueue.global()) { responseObject, remoteAttestation in
guard let parser = ParamParser(responseObject: responseObject) else {
owsFailDebug("Failed to parse response object")
throw KBSError.assertion
}
let data = try parser.requiredBase64EncodedData(key: "data")
guard data.count > 0 else {
owsFailDebug("data is invalid")
throw KBSError.assertion
}
let iv = try parser.requiredBase64EncodedData(key: "iv")
guard iv.count == 12 else {
owsFailDebug("iv is invalid")
throw KBSError.assertion
}
let mac = try parser.requiredBase64EncodedData(key: "mac")
guard mac.count == 16 else {
owsFailDebug("mac is invalid")
throw KBSError.assertion
}
guard let encryptionResult = Cryptography.decryptAESGCM(
withInitializationVector: iv,
ciphertext: data,
additionalAuthenticatedData: nil,
authTag: mac,
key: remoteAttestation.keys.serverKey
) else {
owsFailDebug("failed to decrypt KBS response")
throw KBSError.assertion
}
let kbResponse = try KeyBackupProtoResponse.parseData(encryptionResult)
guard let typedResponse = RequestType.responseOption(from: kbResponse) else {
owsFailDebug("missing KBS response object")
throw KBSError.assertion
}
return typedResponse
}
}
private static func backupKeyRequest(accessKey: Data, encryptedMasterKey: Data, and auth: RemoteAttestationAuth? = nil) -> Promise<KeyBackupProtoBackupResponse> {
return enclaveRequest(with: auth) { token -> KeyBackupProtoBackupRequest in
guard let serviceId = Data.data(fromHex: TSConstants.keyBackupServiceId) else {
owsFailDebug("failed to encode service id")
throw KBSError.assertion
}
let backupRequestBuilder = KeyBackupProtoBackupRequest.builder()
backupRequestBuilder.setData(encryptedMasterKey)
backupRequestBuilder.setPin(accessKey)
backupRequestBuilder.setToken(token.data)
backupRequestBuilder.setBackupID(token.backupId)
backupRequestBuilder.setTries(maximumKeyAttempts)
backupRequestBuilder.setServiceID(serviceId)
// number of seconds since unix epoch after which this request should be valid
// Always set to the client's clock time, minus 24 hours to account for inaccurate clocks
backupRequestBuilder.setValidFrom(UInt64(Date().addingTimeInterval(-kDayInterval).timeIntervalSince1970))
do {
return try backupRequestBuilder.build()
} catch {
owsFailDebug("failed to build backup request")
throw KBSError.assertion
}
}
}
private static func restoreKeyRequest(accessKey: Data, with auth: RemoteAttestationAuth? = nil) -> Promise<KeyBackupProtoRestoreResponse> {
return enclaveRequest(with: auth) { token -> KeyBackupProtoRestoreRequest in
guard let serviceId = Data.data(fromHex: TSConstants.keyBackupServiceId) else {
owsFailDebug("failed to encode service id")
throw KBSError.assertion
}
let restoreRequestBuilder = KeyBackupProtoRestoreRequest.builder()
restoreRequestBuilder.setPin(accessKey)
restoreRequestBuilder.setToken(token.data)
restoreRequestBuilder.setBackupID(token.backupId)
restoreRequestBuilder.setServiceID(serviceId)
// number of seconds since unix epoch after which this request should be valid
// Always set to the client's clock time, minus 24 hours to account for inaccurate clocks
restoreRequestBuilder.setValidFrom(UInt64(Date().addingTimeInterval(-kDayInterval).timeIntervalSince1970))
do {
return try restoreRequestBuilder.build()
} catch {
owsFailDebug("failed to build restore request")
throw KBSError.assertion
}
}
}
private static func deleteKeyRequest() -> Promise<KeyBackupProtoDeleteResponse> {
return enclaveRequest { token -> KeyBackupProtoDeleteRequest in
guard let serviceId = Data.data(fromHex: TSConstants.keyBackupServiceId) else {
owsFailDebug("failed to encode service id")
throw KBSError.assertion
}
let deleteRequestBuilder = KeyBackupProtoDeleteRequest.builder()
deleteRequestBuilder.setBackupID(token.backupId)
deleteRequestBuilder.setServiceID(serviceId)
do {
return try deleteRequestBuilder.build()
} catch {
owsFailDebug("failed to build delete request")
throw KBSError.assertion
}
}
}
// PRAGMA MARK: - Token
public static var tokenStore: SDSKeyValueStore {
return SDSKeyValueStore(collection: "kOWSKeyBackupService_Token")
}
private struct Token {
private static var keyValueStore: SDSKeyValueStore {
return KeyBackupService.tokenStore
}
private static let backupIdKey = "backupIdKey"
private static let dataKey = "dataKey"
private static let triesKey = "triesKey"
let backupId: Data
let data: Data
let tries: UInt32
private init(backupId: Data, data: Data, tries: UInt32) throws {
guard backupId.count == 32 else {
owsFailDebug("invalid backupId")
throw KBSError.assertion
}
self.backupId = backupId
guard data.count == 32 else {
owsFailDebug("invalid token data")
throw KBSError.assertion
}
self.data = data
self.tries = tries
}
/// Update the token to use for the next enclave request.
/// If backupId or tries are nil, attempts to use the previously known value.
/// If we don't have a cached value (we've never stored a token before), an error is thrown.
@discardableResult
static func updateNext(backupId: Data? = nil, data: Data, tries: UInt32? = nil) throws -> Token {
guard let backupId = backupId ?? databaseStorage.read(block: { transaction in
keyValueStore.getData(backupIdKey, transaction: transaction)
}) else {
owsFailDebug("missing backupId")
throw KBSError.assertion
}
guard let tries = tries ?? databaseStorage.read(block: { transaction in
keyValueStore.getUInt32(triesKey, transaction: transaction)
}) else {
owsFailDebug("missing tries")
throw KBSError.assertion
}
let token = try Token(backupId: backupId, data: data, tries: tries)
token.recordAsCurrent()
return token
}
/// Update the token to use for the next enclave request.
@discardableResult
static func updateNext(responseObject: Any?) throws -> Token {
guard let paramParser = ParamParser(responseObject: responseObject) else {
owsFailDebug("Unexpectedly missing response object")
throw KBSError.assertion
}
let backupId = try paramParser.requiredBase64EncodedData(key: "backupId")
let data = try paramParser.requiredBase64EncodedData(key: "token")
let tries: UInt32 = try paramParser.required(key: "tries")
let token = try Token(backupId: backupId, data: data, tries: tries)
token.recordAsCurrent()
return token
}
static func clearNext() {
databaseStorage.write { clearNext(transaction: $0) }
}
static func clearNext(transaction: SDSAnyWriteTransaction) {
keyValueStore.setData(nil, key: backupIdKey, transaction: transaction)
keyValueStore.setData(nil, key: dataKey, transaction: transaction)
keyValueStore.setObject(nil, key: triesKey, transaction: transaction)
}
/// The token to use when making the next enclave request.
static var next: Token? {
return databaseStorage.read { transaction in
guard let backupId = keyValueStore.getData(backupIdKey, transaction: transaction),
let data = keyValueStore.getData(dataKey, transaction: transaction),
let tries = keyValueStore.getUInt32(triesKey, transaction: transaction) else {
return nil
}
do {
return try Token(backupId: backupId, data: data, tries: tries)
} catch {
// This should never happen, but if for some reason our stored token gets
// corrupted we'll return nil which will trigger us to fetch a fresh one
// from the enclave.
owsFailDebug("unexpectedly failed to initialize token with error: \(error)")
return nil
}
}
}
private func recordAsCurrent() {
databaseStorage.write { transaction in
Token.keyValueStore.setData(self.backupId, key: Token.backupIdKey, transaction: transaction)
Token.keyValueStore.setData(self.data, key: Token.dataKey, transaction: transaction)