]> git.saurik.com Git - apple/security.git/blob - keychain/TrustedPeersHelper/RecoveryKey/RecoverKeySet.swift
Security-59306.101.1.tar.gz
[apple/security.git] / keychain / TrustedPeersHelper / RecoveryKey / RecoverKeySet.swift
1 /*
2 * Copyright (c) 2019 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 import Foundation
25 import SecurityFoundation
26
27 let OT_RECOVERY_SIGNING_HKDF_SIZE = 56
28 let OT_RECOVERY_ENCRYPTION_HKDF_SIZE = 56
29
30 enum RecoveryKeyType: Int {
31 case kOTRecoveryKeySigning = 1
32 case kOTRecoveryKeyEncryption = 2
33 }
34
35 class RecoveryKeySet: NSObject {
36 public var encryptionKey: _SFECKeyPair
37 public var signingKey: _SFECKeyPair
38
39 public var secret: Data
40 public var recoverySalt: String
41
42 public init (secret: Data, recoverySalt: String) throws {
43 self.secret = secret
44 self.recoverySalt = recoverySalt
45
46 let encryptionKeyData = try RecoveryKeySet.generateRecoveryKey(keyType: RecoveryKeyType.kOTRecoveryKeyEncryption, masterSecret: secret, recoverySalt: recoverySalt)
47 self.encryptionKey = _SFECKeyPair.init(secKey: try RecoveryKeySet.createSecKey(keyData: encryptionKeyData))
48
49 let signingKeyData = try RecoveryKeySet.generateRecoveryKey(keyType: RecoveryKeyType.kOTRecoveryKeySigning, masterSecret: secret, recoverySalt: recoverySalt)
50 self.signingKey = _SFECKeyPair.init(secKey: try RecoveryKeySet.createSecKey(keyData: signingKeyData))
51
52 let RecoverySigningPubKeyHash = try RecoveryKeySet.hashRecoveryedSigningPublicKey(keyData: self.signingKey.publicKey().spki())
53 _ = try RecoveryKeySet.storeRecoveryedSigningKeyPair(keyData: self.signingKey.keyData, label: RecoverySigningPubKeyHash)
54 _ = try RecoveryKeySet.storeRecoveryedEncryptionKeyPair(keyData: self.encryptionKey.keyData, label: RecoverySigningPubKeyHash)
55 }
56
57 class func generateMasterKeyString() -> (String?) {
58 return SecRKCreateRecoveryKeyString(nil) as String
59 }
60
61 class func generateRecoveryKey(keyType: RecoveryKeyType, masterSecret: Data, recoverySalt: String) throws -> (Data) {
62 var keyLength: Int
63 var info: Data
64 var derivedKey: Data
65 var finalKey = Data()
66
67 switch keyType {
68 case RecoveryKeyType.kOTRecoveryKeyEncryption:
69 keyLength = OT_RECOVERY_ENCRYPTION_HKDF_SIZE
70
71 let infoString = Array("Recovery Encryption Private Key".utf8)
72 info = Data(bytes: infoString, count: infoString.count)
73
74 case RecoveryKeyType.kOTRecoveryKeySigning:
75 keyLength = OT_RECOVERY_SIGNING_HKDF_SIZE
76
77 let infoString = Array("Recovery Signing Private Key".utf8)
78 info = Data(bytes: infoString, count: infoString.count)
79
80 }
81
82 guard let cp = ccec_cp_384() else {
83 throw RecoveryKeySetError.keyGeneration
84 }
85 var status: Int32 = 0
86
87 let fullKey = TPHObjectiveC.ccec384Context()
88 defer { TPHObjectiveC.contextFree(fullKey) }
89
90 derivedKey = Data(count: keyLength)
91
92 var masterSecretMutable = masterSecret
93
94 let bottleSaltData = Data(bytes: Array(recoverySalt.utf8), count: recoverySalt.utf8.count)
95
96 try derivedKey.withUnsafeMutableBytes { (derivedKeyBytes: UnsafeMutableRawBufferPointer) throws ->Void in
97 try masterSecretMutable.withUnsafeMutableBytes { (masterSecretBytes: UnsafeMutableRawBufferPointer) throws ->Void in
98 try bottleSaltData.withUnsafeBytes { (bottleSaltBytes: UnsafeRawBufferPointer) throws -> Void in
99 try info.withUnsafeBytes { (infoBytes: UnsafeRawBufferPointer) throws -> Void in
100 status = cchkdf(ccsha384_di(),
101 masterSecretBytes.count, masterSecretBytes.baseAddress!,
102 bottleSaltBytes.count, bottleSaltBytes.baseAddress!,
103 infoBytes.count, infoBytes.baseAddress!,
104 derivedKeyBytes.count, derivedKeyBytes.baseAddress!)
105 if status != 0 {
106 throw RecoveryKeySetError.corecryptoKeyGeneration(corecryptoError: status)
107 }
108
109 if keyType == RecoveryKeyType.kOTRecoveryKeyEncryption || keyType == RecoveryKeyType.kOTRecoveryKeySigning {
110 status = ccec_generate_key_deterministic(cp,
111 derivedKeyBytes.count, derivedKeyBytes.bindMemory(to: UInt8.self).baseAddress!,
112 ccDRBGGetRngState(),
113 UInt32(CCEC_GENKEY_DETERMINISTIC_FIPS),
114 fullKey)
115
116 guard status == 0 else {
117 throw RecoveryKeySetError.corecryptoKeyGeneration(corecryptoError: status)
118 }
119
120 let space = ccec_x963_export_size(1, ccec_ctx_pub(fullKey))
121 var key = Data(count: space)
122 key.withUnsafeMutableBytes { (bytes: UnsafeMutableRawBufferPointer) -> Void in
123 ccec_x963_export(1, bytes.baseAddress!, fullKey)
124 }
125 finalKey = Data(key)
126 }
127 }
128 }
129 }
130 }
131 return finalKey
132 }
133
134 class func createSecKey(keyData: Data) throws -> (SecKey) {
135 let keyAttributes = [kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrKeyType: kSecAttrKeyTypeEC]
136
137 guard let key = SecKeyCreateWithData(keyData as CFData, keyAttributes as CFDictionary, nil) else {
138 throw RecoveryKeySetError.keyGeneration
139 }
140
141 return key
142 }
143
144 class func setKeyMaterialInKeychain(query: [CFString: Any]) throws -> (Bool) {
145 var result = false
146
147 var results: CFTypeRef?
148 var status = SecItemAdd(query as CFDictionary, &results)
149
150 if status == errSecSuccess {
151 result = true
152 } else if status == errSecDuplicateItem {
153 var updateQuery: [CFString: Any] = query
154 updateQuery[kSecClass] = nil
155
156 status = SecItemUpdate(query as CFDictionary, updateQuery as CFDictionary)
157
158 if status != errSecSuccess {
159 throw RecoveryKeySetError.failedToSaveToKeychain(errorCode: status)
160 } else {
161 result = true
162 }
163 } else {
164 throw RecoveryKeySetError.failedToSaveToKeychain(errorCode: status)
165 }
166
167 return result
168 }
169
170 class func hashRecoveryedSigningPublicKey(keyData: Data) throws -> (String) {
171 let di = ccsha384_di()
172 var result = Data(count: TPHObjectiveC.ccsha384_diSize())
173
174 var keyDataMutable = keyData
175 result.withUnsafeMutableBytes {(resultBytes: UnsafeMutableRawBufferPointer) -> Void in
176 keyDataMutable.withUnsafeMutableBytes {(keyDataBytes: UnsafeMutableRawBufferPointer) -> Void in
177 ccdigest(di, keyDataBytes.count, keyDataBytes.baseAddress!, resultBytes.baseAddress!)
178 }
179 }
180 let hash = result.base64EncodedString(options: [])
181
182 return hash
183 }
184
185 class func storeRecoveryedEncryptionKeyPair(keyData: Data, label: String) throws -> (Bool) {
186
187 let query: [CFString: Any] = [
188 kSecClass: kSecClassKey,
189 kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked,
190 kSecUseDataProtectionKeychain: true,
191 kSecAttrAccessGroup: "com.apple.security.octagon",
192 kSecAttrSynchronizable: false,
193 kSecAttrLabel: label,
194 kSecAttrApplicationLabel: String(format: "Recoveryed Encryption Key-%@", NSUUID().uuidString),
195 kSecValueData: keyData,
196 ]
197 return try RecoveryKeySet.setKeyMaterialInKeychain(query: query)
198 }
199
200 class func storeRecoveryedSigningKeyPair(keyData: Data, label: String) throws -> (Bool) {
201 let query: [CFString: Any] = [
202 kSecClass: kSecClassKey,
203 kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked,
204 kSecUseDataProtectionKeychain: true,
205 kSecAttrAccessGroup: "com.apple.security.octagon",
206 kSecAttrSynchronizable: false,
207 kSecAttrApplicationLabel: String(format: "Recoveryed Signing Key-%@", NSUUID().uuidString),
208 kSecAttrLabel: label,
209 kSecValueData: keyData,
210 ]
211 return try RecoveryKeySet.setKeyMaterialInKeychain(query: query)
212 }
213
214 class func retrieveRecoveryKeysFromKeychain(label: String) throws -> [ [CFString: Any]]? {
215 var keySet: [[CFString: Any]]?
216
217 let query: [CFString: Any] = [
218 kSecClass: kSecClassKey,
219 kSecAttrAccessGroup: "com.apple.security.octagon",
220 kSecAttrLabel: label,
221 kSecReturnAttributes: true,
222 kSecReturnData: true,
223 kSecAttrSynchronizable: false,
224 kSecMatchLimit: kSecMatchLimitAll,
225 ]
226
227 var result: CFTypeRef?
228 let status = SecItemCopyMatching(query as CFDictionary, &result)
229
230 if status != errSecSuccess || result == nil {
231 throw RecoveryKeySetError.itemDoesNotExist
232 }
233
234 if result != nil {
235 if let dictionaryArray = result as? [[CFString: Any]] {
236 keySet = dictionaryArray
237 } else {
238 if let dictionary = result as? [CFString: Any] {
239 keySet = [dictionary]
240 } else {
241 keySet = nil
242 }
243 }
244 }
245 return keySet
246 }
247
248 class func findRecoveryKeysForLabel(label: String) throws -> (_SFECKeyPair?, _SFECKeyPair?) {
249 var signingKey: _SFECKeyPair?
250 var encryptionKey: _SFECKeyPair?
251
252 let keySet = try retrieveRecoveryKeysFromKeychain(label: label)
253 if keySet == nil {
254 throw RecoveryKeySetError.itemDoesNotExist
255 }
256 for item in keySet! {
257 let keyTypeData = item[kSecAttrApplicationLabel as CFString] as! Data
258 let keyType = String(data: keyTypeData, encoding: .utf8)!
259
260 if keyType.range(of: "Encryption") != nil {
261 let keyData = item[kSecValueData as CFString] as! Data
262 let encryptionSecKey = try RecoveryKeySet.createSecKey(keyData: keyData)
263 encryptionKey = _SFECKeyPair.init(secKey: encryptionSecKey)
264 } else if keyType.range(of: "Signing") != nil {
265 let keyData = item[kSecValueData as CFString] as! Data
266 let signingSecKey = try RecoveryKeySet.createSecKey(keyData: keyData)
267 signingKey = _SFECKeyPair.init(secKey: signingSecKey)
268 } else {
269 throw RecoveryKeySetError.unsupportedKeyType(keyType: keyType)
270 }
271 }
272
273 return (signingKey, encryptionKey)
274 }
275 }
276
277 enum RecoveryKeySetError: Error {
278 case keyGeneration
279 case itemDoesNotExist
280 case failedToSaveToKeychain(errorCode: OSStatus)
281 case unsupportedKeyType(keyType: String)
282 case corecryptoKeyGeneration(corecryptoError: Int32)
283 }
284
285 extension RecoveryKeySetError: LocalizedError {
286 public var errorDescription: String? {
287 switch self {
288 case .keyGeneration:
289 return "Key generation failed"
290 case .itemDoesNotExist:
291 return "Item does not exist"
292 case .failedToSaveToKeychain(errorCode: let osError):
293 return "Failed to save item to keychain: \(osError)"
294 case .unsupportedKeyType(keyType: let keyType):
295 return "Unsupported Key Type \(keyType)"
296 case .corecryptoKeyGeneration(corecryptoError: let corecryptoError):
297 return "Key generation crypto failed \(corecryptoError)"
298 }
299 }
300 }
301
302 extension RecoveryKeySetError: CustomNSError {
303
304 public static var errorDomain: String {
305 return "com.apple.security.trustedpeers.RecoveryKeySetError"
306 }
307
308 public var errorCode: Int {
309 switch self {
310 case .keyGeneration:
311 return 1
312 case .itemDoesNotExist:
313 return 2
314 case .failedToSaveToKeychain:
315 return 3
316 case .unsupportedKeyType:
317 return 4
318 case .corecryptoKeyGeneration:
319 return 5
320 }
321 }
322
323 public var errorUserInfo: [String: Any] {
324 var userInfo: [String: Any] = [:]
325 if let desc = self.errorDescription {
326 userInfo[NSLocalizedDescriptionKey] = desc
327 }
328 switch self {
329 case .failedToSaveToKeychain(errorCode: let osError):
330 userInfo[NSUnderlyingErrorKey] = NSError(domain: NSOSStatusErrorDomain, code: Int(osError), userInfo: nil)
331 case .corecryptoKeyGeneration(corecryptoError: let corecryptoError):
332 userInfo[NSUnderlyingErrorKey] = NSError(domain: "corecrypto", code: Int(corecryptoError), userInfo: nil)
333 default:
334 break
335 }
336 return userInfo
337 }
338 }