-
Notifications
You must be signed in to change notification settings - Fork 772
/
Keychain.swift
2933 lines (2730 loc) · 114 KB
/
Keychain.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
//
// Keychain.swift
// KeychainAccess
//
// Created by kishikawa katsumi on 2014/12/24.
// Copyright (c) 2014 kishikawa katsumi. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Security
#if os(iOS) || os(OSX)
import LocalAuthentication
#endif
public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error"
public enum ItemClass {
case genericPassword
case internetPassword
}
public enum ProtocolType {
case ftp
case ftpAccount
case http
case irc
case nntp
case pop3
case smtp
case socks
case imap
case ldap
case appleTalk
case afp
case telnet
case ssh
case ftps
case https
case httpProxy
case httpsProxy
case ftpProxy
case smb
case rtsp
case rtspProxy
case daap
case eppc
case ipp
case nntps
case ldaps
case telnetS
case imaps
case ircs
case pop3S
}
public enum AuthenticationType {
case ntlm
case msn
case dpa
case rpa
case httpBasic
case httpDigest
case htmlForm
case `default`
}
public enum Accessibility {
/**
Item data can only be accessed
while the device is unlocked. This is recommended for items that only
need be accesible while the application is in the foreground. Items
with this attribute will migrate to a new device when using encrypted
backups.
*/
case whenUnlocked
/**
Item data can only be
accessed once the device has been unlocked after a restart. This is
recommended for items that need to be accesible by background
applications. Items with this attribute will migrate to a new device
when using encrypted backups.
*/
case afterFirstUnlock
/**
Item data can always be accessed
regardless of the lock state of the device. This is not recommended
for anything except system use. Items with this attribute will migrate
to a new device when using encrypted backups.
*/
case always
/**
Item data can
only be accessed while the device is unlocked. This class is only
available if a passcode is set on the device. This is recommended for
items that only need to be accessible while the application is in the
foreground. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device, these items
will be missing. No items can be stored in this class on devices
without a passcode. Disabling the device passcode will cause all
items in this class to be deleted.
*/
@available(iOS 8.0, OSX 10.10, *)
case whenPasscodeSetThisDeviceOnly
/**
Item data can only
be accessed while the device is unlocked. This is recommended for items
that only need be accesible while the application is in the foreground.
Items with this attribute will never migrate to a new device, so after
a backup is restored to a new device, these items will be missing.
*/
case whenUnlockedThisDeviceOnly
/**
Item data can
only be accessed once the device has been unlocked after a restart.
This is recommended for items that need to be accessible by background
applications. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device these items will
be missing.
*/
case afterFirstUnlockThisDeviceOnly
/**
Item data can always
be accessed regardless of the lock state of the device. This option
is not recommended for anything except system use. Items with this
attribute will never migrate to a new device, so after a backup is
restored to a new device, these items will be missing.
*/
case alwaysThisDeviceOnly
}
public struct AuthenticationPolicy: OptionSet {
/**
User presence policy using Touch ID or Passcode. Touch ID does not
have to be available or enrolled. Item is still accessible by Touch ID
even if fingers are added or removed.
*/
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public static let userPresence = AuthenticationPolicy(rawValue: 1 << 0)
/**
Constraint: Touch ID (any finger). Touch ID must be available and
at least one finger must be enrolled. Item is still accessible by
Touch ID even if fingers are added or removed.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let touchIDAny = AuthenticationPolicy(rawValue: 1 << 1)
/**
Constraint: Touch ID from the set of currently enrolled fingers.
Touch ID must be available and at least one finger must be enrolled.
When fingers are added or removed, the item is invalidated.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let touchIDCurrentSet = AuthenticationPolicy(rawValue: 1 << 3)
/**
Constraint: Device passcode
*/
@available(iOS 9.0, OSX 10.11, *)
@available(watchOS, unavailable)
public static let devicePasscode = AuthenticationPolicy(rawValue: 1 << 4)
/**
Constraint logic operation: when using more than one constraint,
at least one of them must be satisfied.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let or = AuthenticationPolicy(rawValue: 1 << 14)
/**
Constraint logic operation: when using more than one constraint,
all must be satisfied.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let and = AuthenticationPolicy(rawValue: 1 << 15)
/**
Create access control for private key operations (i.e. sign operation)
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let privateKeyUsage = AuthenticationPolicy(rawValue: 1 << 30)
/**
Security: Application provided password for data encryption key generation.
This is not a constraint but additional item encryption mechanism.
*/
@available(iOS 9.0, *)
@available(OSX, unavailable)
@available(watchOS, unavailable)
public static let applicationPassword = AuthenticationPolicy(rawValue: 1 << 31)
#if swift(>=2.3)
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
#else
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
#endif
}
public struct Attributes {
public var `class`: String? {
return attributes[Class] as? String
}
public var data: Data? {
return attributes[ValueData] as? Data
}
public var ref: Data? {
return attributes[ValueRef] as? Data
}
public var persistentRef: Data? {
return attributes[ValuePersistentRef] as? Data
}
public var accessible: String? {
return attributes[AttributeAccessible] as? String
}
public var accessControl: SecAccessControl? {
if #available(OSX 10.10, *) {
if let accessControl = attributes[AttributeAccessControl] {
return (accessControl as! SecAccessControl)
}
return nil
} else {
return nil
}
}
public var accessGroup: String? {
return attributes[AttributeAccessGroup] as? String
}
public var synchronizable: Bool? {
return attributes[AttributeSynchronizable] as? Bool
}
public var creationDate: Date? {
return attributes[AttributeCreationDate] as? Date
}
public var modificationDate: Date? {
return attributes[AttributeModificationDate] as? Date
}
public var attributeDescription: String? {
return attributes[AttributeDescription] as? String
}
public var comment: String? {
return attributes[AttributeComment] as? String
}
public var creator: String? {
return attributes[AttributeCreator] as? String
}
public var type: String? {
return attributes[AttributeType] as? String
}
public var label: String? {
return attributes[AttributeLabel] as? String
}
public var isInvisible: Bool? {
return attributes[AttributeIsInvisible] as? Bool
}
public var isNegative: Bool? {
return attributes[AttributeIsNegative] as? Bool
}
public var account: String? {
return attributes[AttributeAccount] as? String
}
public var service: String? {
return attributes[AttributeService] as? String
}
public var generic: Data? {
return attributes[AttributeGeneric] as? Data
}
public var securityDomain: String? {
return attributes[AttributeSecurityDomain] as? String
}
public var server: String? {
return attributes[AttributeServer] as? String
}
public var `protocol`: String? {
return attributes[AttributeProtocol] as? String
}
public var authenticationType: String? {
return attributes[AttributeAuthenticationType] as? String
}
public var port: Int? {
return attributes[AttributePort] as? Int
}
public var path: String? {
return attributes[AttributePath] as? String
}
fileprivate let attributes: [String: Any]
init(attributes: [String: Any]) {
self.attributes = attributes
}
public subscript(key: String) -> Any? {
get {
return attributes[key]
}
}
}
public final class Keychain {
public var itemClass: ItemClass {
return options.itemClass
}
public var service: String {
return options.service
}
public var accessGroup: String? {
return options.accessGroup
}
public var server: URL {
return options.server
}
public var protocolType: ProtocolType {
return options.protocolType
}
public var authenticationType: AuthenticationType {
return options.authenticationType
}
public var accessibility: Accessibility {
return options.accessibility
}
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public var authenticationPolicy: AuthenticationPolicy? {
return options.authenticationPolicy
}
public var synchronizable: Bool {
return options.synchronizable
}
public var label: String? {
return options.label
}
public var comment: String? {
return options.comment
}
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public var authenticationPrompt: String? {
return options.authenticationPrompt
}
#if os(iOS) || os(OSX)
@available(iOS 9.0, OSX 10.11, *)
public var authenticationContext: LAContext? {
return options.authenticationContext as? LAContext
}
#endif
fileprivate let options: Options
// MARK:
public convenience init() {
var options = Options()
if let bundleIdentifier = Bundle.main.bundleIdentifier {
options.service = bundleIdentifier
}
self.init(options)
}
public convenience init(service: String) {
var options = Options()
options.service = service
self.init(options)
}
public convenience init(accessGroup: String) {
var options = Options()
if let bundleIdentifier = Bundle.main.bundleIdentifier {
options.service = bundleIdentifier
}
options.accessGroup = accessGroup
self.init(options)
}
public convenience init(service: String, accessGroup: String) {
var options = Options()
options.service = service
options.accessGroup = accessGroup
self.init(options)
}
public convenience init(server: String, protocolType: ProtocolType, authenticationType: AuthenticationType = .default) {
self.init(server: URL(string: server)!, protocolType: protocolType, authenticationType: authenticationType)
}
public convenience init(server: URL, protocolType: ProtocolType, authenticationType: AuthenticationType = .default) {
var options = Options()
options.itemClass = .internetPassword
options.server = server
options.protocolType = protocolType
options.authenticationType = authenticationType
self.init(options)
}
fileprivate init(_ opts: Options) {
options = opts
}
// MARK:
public func accessibility(_ accessibility: Accessibility) -> Keychain {
var options = self.options
options.accessibility = accessibility
return Keychain(options)
}
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public func accessibility(_ accessibility: Accessibility, authenticationPolicy: AuthenticationPolicy) -> Keychain {
var options = self.options
options.accessibility = accessibility
options.authenticationPolicy = authenticationPolicy
return Keychain(options)
}
public func synchronizable(_ synchronizable: Bool) -> Keychain {
var options = self.options
options.synchronizable = synchronizable
return Keychain(options)
}
public func label(_ label: String) -> Keychain {
var options = self.options
options.label = label
return Keychain(options)
}
public func comment(_ comment: String) -> Keychain {
var options = self.options
options.comment = comment
return Keychain(options)
}
public func attributes(_ attributes: [String: Any]) -> Keychain {
var options = self.options
attributes.forEach { options.attributes.updateValue($1, forKey: $0) }
return Keychain(options)
}
@available(iOS 8.0, OSX 10.10, *)
@available(watchOS, unavailable)
public func authenticationPrompt(_ authenticationPrompt: String) -> Keychain {
var options = self.options
options.authenticationPrompt = authenticationPrompt
return Keychain(options)
}
#if os(iOS) || os(OSX)
@available(iOS 9.0, OSX 10.11, *)
public func authenticationContext(_ authenticationContext: LAContext) -> Keychain {
var options = self.options
options.authenticationContext = authenticationContext
return Keychain(options)
}
#endif
// MARK:
public func get(_ key: String) throws -> String? {
return try getString(key)
}
public func getString(_ key: String) throws -> String? {
guard let data = try getData(key) else {
return nil
}
guard let string = String(data: data, encoding: .utf8) else {
print("failed to convert data to string")
throw Status.conversionError
}
return string
}
public func getData(_ key: String) throws -> Data? {
var query = options.query()
query[MatchLimit] = MatchLimitOne
query[ReturnData] = kCFBooleanTrue
query[AttributeAccount] = key
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
guard let data = result as? Data else {
throw Status.unexpectedError
}
return data
case errSecItemNotFound:
return nil
default:
throw securityError(status: status)
}
}
public func get<T>(_ key: String, handler: (Attributes?) -> T) throws -> T {
var query = options.query()
query[MatchLimit] = MatchLimitOne
query[ReturnData] = kCFBooleanTrue
query[ReturnAttributes] = kCFBooleanTrue
query[ReturnRef] = kCFBooleanTrue
query[ReturnPersistentRef] = kCFBooleanTrue
query[AttributeAccount] = key
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
guard let attributes = result as? [String: Any] else {
throw Status.unexpectedError
}
return handler(Attributes(attributes: attributes))
case errSecItemNotFound:
return handler(nil)
default:
throw securityError(status: status)
}
}
// MARK:
public func set(_ value: String, key: String) throws {
guard let data = value.data(using: .utf8, allowLossyConversion: false) else {
print("failed to convert string to data")
throw Status.conversionError
}
try set(data, key: key)
}
public func set(_ value: Data, key: String) throws {
var query = options.query()
query[AttributeAccount] = key
#if os(iOS)
if #available(iOS 9.0, *) {
query[UseAuthenticationUI] = UseAuthenticationUIFail
} else {
query[UseNoAuthenticationUI] = kCFBooleanTrue
}
#elseif os(OSX)
query[ReturnData] = kCFBooleanTrue
if #available(OSX 10.11, *) {
query[UseAuthenticationUI] = UseAuthenticationUIFail
}
#endif
var status = SecItemCopyMatching(query as CFDictionary, nil)
switch status {
case errSecSuccess, errSecInteractionNotAllowed:
var query = options.query()
query[AttributeAccount] = key
var (attributes, error) = options.attributes(key: nil, value: value)
if let error = error {
print(error.localizedDescription)
throw error
}
options.attributes.forEach { attributes.updateValue($1, forKey: $0) }
#if os(iOS)
if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) {
try remove(key)
try set(value, key: key)
} else {
status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
if status != errSecSuccess {
throw securityError(status: status)
}
}
#else
status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
if status != errSecSuccess {
throw securityError(status: status)
}
#endif
case errSecItemNotFound:
var (attributes, error) = options.attributes(key: key, value: value)
if let error = error {
print(error.localizedDescription)
throw error
}
options.attributes.forEach { attributes.updateValue($1, forKey: $0) }
status = SecItemAdd(attributes as CFDictionary, nil)
if status != errSecSuccess {
throw securityError(status: status)
}
default:
throw securityError(status: status)
}
}
public subscript(key: String) -> String? {
get {
#if swift(>=5.0)
return try? get(key)
#else
return (try? get(key)).flatMap { $0 }
#endif
}
set {
if let value = newValue {
do {
try set(value, key: key)
} catch {}
} else {
do {
try remove(key)
} catch {}
}
}
}
public subscript(string key: String) -> String? {
get {
return self[key]
}
set {
self[key] = newValue
}
}
public subscript(data key: String) -> Data? {
get {
#if swift(>=5.0)
return try? getData(key)
#else
return (try? getData(key)).flatMap { $0 }
#endif
}
set {
if let value = newValue {
do {
try set(value, key: key)
} catch {}
} else {
do {
try remove(key)
} catch {}
}
}
}
public subscript(attributes key: String) -> Attributes? {
get {
#if swift(>=5.0)
return try? get(key) { $0 }
#else
return (try? get(key) { $0 }).flatMap { $0 }
#endif
}
}
// MARK:
public func remove(_ key: String) throws {
var query = options.query()
query[AttributeAccount] = key
let status = SecItemDelete(query as CFDictionary)
if status != errSecSuccess && status != errSecItemNotFound {
throw securityError(status: status)
}
}
public func removeAll() throws {
var query = options.query()
#if !os(iOS) && !os(watchOS) && !os(tvOS)
query[MatchLimit] = MatchLimitAll
#endif
let status = SecItemDelete(query as CFDictionary)
if status != errSecSuccess && status != errSecItemNotFound {
throw securityError(status: status)
}
}
// MARK:
public func contains(_ key: String) throws -> Bool {
var query = options.query()
query[AttributeAccount] = key
let status = SecItemCopyMatching(query as CFDictionary, nil)
switch status {
case errSecSuccess:
return true
case errSecItemNotFound:
return false
default:
throw securityError(status: status)
}
}
// MARK:
public class func allKeys(_ itemClass: ItemClass) -> [(String, String)] {
var query = [String: Any]()
query[Class] = itemClass.rawValue
query[AttributeSynchronizable] = SynchronizableAny
query[MatchLimit] = MatchLimitAll
query[ReturnAttributes] = kCFBooleanTrue
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
if let items = result as? [[String: Any]] {
return prettify(itemClass: itemClass, items: items).map {
switch itemClass {
case .genericPassword:
return (($0["service"] ?? "") as! String, ($0["key"] ?? "") as! String)
case .internetPassword:
return (($0["server"] ?? "") as! String, ($0["key"] ?? "") as! String)
}
}
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}
public func allKeys() -> [String] {
let allItems = type(of: self).prettify(itemClass: itemClass, items: items())
let filter: ([String: Any]) -> String? = { $0["key"] as? String }
#if swift(>=4.1)
return allItems.compactMap(filter)
#else
return allItems.flatMap(filter)
#endif
}
public class func allItems(_ itemClass: ItemClass) -> [[String: Any]] {
var query = [String: Any]()
query[Class] = itemClass.rawValue
query[MatchLimit] = MatchLimitAll
query[ReturnAttributes] = kCFBooleanTrue
#if os(iOS) || os(watchOS) || os(tvOS)
query[ReturnData] = kCFBooleanTrue
#endif
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
if let items = result as? [[String: Any]] {
return prettify(itemClass: itemClass, items: items)
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}
public func allItems() -> [[String: Any]] {
return type(of: self).prettify(itemClass: itemClass, items: items())
}
#if os(iOS)
@available(iOS 8.0, *)
public func getSharedPassword(_ completion: @escaping (_ account: String?, _ password: String?, _ error: Error?) -> () = { account, password, error -> () in }) {
if let domain = server.host {
type(of: self).requestSharedWebCredential(domain: domain, account: nil) { (credentials, error) -> () in
if let credential = credentials.first {
let account = credential["account"]
let password = credential["password"]
completion(account, password, error)
} else {
completion(nil, nil, error)
}
}
} else {
let error = securityError(status: Status.param.rawValue)
completion(nil, nil, error)
}
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public func getSharedPassword(_ account: String, completion: @escaping (_ password: String?, _ error: Error?) -> () = { password, error -> () in }) {
if let domain = server.host {
type(of: self).requestSharedWebCredential(domain: domain, account: account) { (credentials, error) -> () in
if let credential = credentials.first {
if let password = credential["password"] {
completion(password, error)
} else {
completion(nil, error)
}
} else {
completion(nil, error)
}
}
} else {
let error = securityError(status: Status.param.rawValue)
completion(nil, error)
}
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public func setSharedPassword(_ password: String, account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) {
setSharedPassword(password as String?, account: account, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
fileprivate func setSharedPassword(_ password: String?, account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) {
if let domain = server.host {
SecAddSharedWebCredential(domain as CFString, account as CFString, password as CFString?) { error -> () in
if let error = error {
completion(error.error)
} else {
completion(nil)
}
}
} else {
let error = securityError(status: Status.param.rawValue)
completion(error)
}
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public func removeSharedPassword(_ account: String, completion: @escaping (_ error: Error?) -> () = { e -> () in }) {
setSharedPassword(nil, account: account, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public class func requestSharedWebCredential(_ completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: nil, account: nil, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public class func requestSharedWebCredential(domain: String, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: domain, account: nil, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
public class func requestSharedWebCredential(domain: String, account: String, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: Optional(domain), account: Optional(account)!, completion: completion)
}
#endif
#if os(iOS)
@available(iOS 8.0, *)
fileprivate class func requestSharedWebCredential(domain: String?, account: String?, completion: @escaping (_ credentials: [[String: String]], _ error: Error?) -> ()) {
SecRequestSharedWebCredential(domain as CFString?, account as CFString?) { (credentials, error) -> () in
var remoteError: NSError?
if let error = error {
remoteError = error.error
if remoteError?.code != Int(errSecItemNotFound) {
print("error:[\(remoteError!.code)] \(remoteError!.localizedDescription)")
}
}
if let credentials = credentials {
let credentials = (credentials as NSArray).map { credentials -> [String: String] in
var credential = [String: String]()
if let credentials = credentials as? [String: String] {
if let server = credentials[AttributeServer] {
credential["server"] = server
}
if let account = credentials[AttributeAccount] {
credential["account"] = account
}
if let password = credentials[SharedPassword] {
credential["password"] = password
}
}
return credential
}
completion(credentials, remoteError)
} else {
completion([], remoteError)
}
}
}
#endif
#if os(iOS)
/**
@abstract Returns a randomly generated password.
@return String password in the form xxx-xxx-xxx-xxx where x is taken from the sets "abcdefghkmnopqrstuvwxy", "ABCDEFGHJKLMNPQRSTUVWXYZ", "3456789" with at least one character from each set being present.
*/
@available(iOS 8.0, *)
public class func generatePassword() -> String {
return SecCreateSharedWebCredentialPassword()! as String
}
#endif
// MARK:
fileprivate func items() -> [[String: Any]] {
var query = options.query()
query[MatchLimit] = MatchLimitAll
query[ReturnAttributes] = kCFBooleanTrue
#if os(iOS) || os(watchOS) || os(tvOS)
query[ReturnData] = kCFBooleanTrue
#endif
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
if let items = result as? [[String: Any]] {
return items
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}