2 * Copyright (c) 2019 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
25 import SecurityFoundation
27 let OT_RECOVERY_SIGNING_HKDF_SIZE = 56
28 let OT_RECOVERY_ENCRYPTION_HKDF_SIZE = 56
30 enum RecoveryKeyType: Int {
31 case kOTRecoveryKeySigning = 1
32 case kOTRecoveryKeyEncryption = 2
35 class RecoveryKeySet: NSObject {
36 public var encryptionKey: _SFECKeyPair
37 public var signingKey: _SFECKeyPair
39 public var secret: Data
40 public var recoverySalt: String
42 public init (secret: Data, recoverySalt: String) throws {
44 self.recoverySalt = recoverySalt
46 let encryptionKeyData = try RecoveryKeySet.generateRecoveryKey(keyType: RecoveryKeyType.kOTRecoveryKeyEncryption, masterSecret: secret, recoverySalt: recoverySalt)
47 self.encryptionKey = _SFECKeyPair.init(secKey: try RecoveryKeySet.createSecKey(keyData: encryptionKeyData))
49 let signingKeyData = try RecoveryKeySet.generateRecoveryKey(keyType: RecoveryKeyType.kOTRecoveryKeySigning, masterSecret: secret, recoverySalt: recoverySalt)
50 self.signingKey = _SFECKeyPair.init(secKey: try RecoveryKeySet.createSecKey(keyData: signingKeyData))
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)
57 class func generateMasterKeyString() -> (String?) {
58 return SecRKCreateRecoveryKeyString(nil) as String
61 class func generateRecoveryKey(keyType: RecoveryKeyType, masterSecret: Data, recoverySalt: String) throws -> (Data) {
68 case RecoveryKeyType.kOTRecoveryKeyEncryption:
69 keyLength = OT_RECOVERY_ENCRYPTION_HKDF_SIZE
71 let infoString = Array("Recovery Encryption Private Key".utf8)
72 info = Data(bytes: infoString, count: infoString.count)
74 case RecoveryKeyType.kOTRecoveryKeySigning:
75 keyLength = OT_RECOVERY_SIGNING_HKDF_SIZE
77 let infoString = Array("Recovery Signing Private Key".utf8)
78 info = Data(bytes: infoString, count: infoString.count)
82 guard let cp = ccec_cp_384() else {
83 throw RecoveryKeySetError.keyGeneration
87 let fullKey = TPHObjectiveC.ccec384Context()
88 defer { TPHObjectiveC.contextFree(fullKey) }
90 derivedKey = Data(count: keyLength)
92 var masterSecretMutable = masterSecret
94 let bottleSaltData = Data(bytes: Array(recoverySalt.utf8), count: recoverySalt.utf8.count)
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!)
106 throw RecoveryKeySetError.corecryptoKeyGeneration(corecryptoError: status)
109 if keyType == RecoveryKeyType.kOTRecoveryKeyEncryption || keyType == RecoveryKeyType.kOTRecoveryKeySigning {
110 status = ccec_generate_key_deterministic(cp,
111 derivedKeyBytes.count, derivedKeyBytes.bindMemory(to: UInt8.self).baseAddress!,
113 UInt32(CCEC_GENKEY_DETERMINISTIC_FIPS),
116 guard status == 0 else {
117 throw RecoveryKeySetError.corecryptoKeyGeneration(corecryptoError: status)
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)
134 class func createSecKey(keyData: Data) throws -> (SecKey) {
135 let keyAttributes = [kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrKeyType: kSecAttrKeyTypeEC]
137 guard let key = SecKeyCreateWithData(keyData as CFData, keyAttributes as CFDictionary, nil) else {
138 throw RecoveryKeySetError.keyGeneration
144 class func setKeyMaterialInKeychain(query: [CFString: Any]) throws -> (Bool) {
147 var results: CFTypeRef?
148 var status = SecItemAdd(query as CFDictionary, &results)
150 if status == errSecSuccess {
152 } else if status == errSecDuplicateItem {
153 var updateQuery: [CFString: Any] = query
154 updateQuery[kSecClass] = nil
156 status = SecItemUpdate(query as CFDictionary, updateQuery as CFDictionary)
158 if status != errSecSuccess {
159 throw RecoveryKeySetError.failedToSaveToKeychain(errorCode: status)
164 throw RecoveryKeySetError.failedToSaveToKeychain(errorCode: status)
170 class func hashRecoveryedSigningPublicKey(keyData: Data) throws -> (String) {
171 let di = ccsha384_di()
172 var result = Data(count: TPHObjectiveC.ccsha384_diSize())
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!)
180 let hash = result.base64EncodedString(options: [])
185 class func storeRecoveryedEncryptionKeyPair(keyData: Data, label: String) throws -> (Bool) {
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,
197 return try RecoveryKeySet.setKeyMaterialInKeychain(query: query)
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,
211 return try RecoveryKeySet.setKeyMaterialInKeychain(query: query)
214 class func retrieveRecoveryKeysFromKeychain(label: String) throws -> [ [CFString: Any]]? {
215 var keySet: [[CFString: Any]]?
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,
227 var result: CFTypeRef?
228 let status = SecItemCopyMatching(query as CFDictionary, &result)
230 if status != errSecSuccess || result == nil {
231 throw RecoveryKeySetError.itemDoesNotExist
235 if let dictionaryArray = result as? [[CFString: Any]] {
236 keySet = dictionaryArray
238 if let dictionary = result as? [CFString: Any] {
239 keySet = [dictionary]
248 class func findRecoveryKeysForLabel(label: String) throws -> (_SFECKeyPair?, _SFECKeyPair?) {
249 var signingKey: _SFECKeyPair?
250 var encryptionKey: _SFECKeyPair?
252 let keySet = try retrieveRecoveryKeysFromKeychain(label: label)
254 throw RecoveryKeySetError.itemDoesNotExist
256 for item in keySet! {
257 let keyTypeData = item[kSecAttrApplicationLabel as CFString] as! Data
258 let keyType = String(data: keyTypeData, encoding: .utf8)!
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)
269 throw RecoveryKeySetError.unsupportedKeyType(keyType: keyType)
273 return (signingKey, encryptionKey)
277 enum RecoveryKeySetError: Error {
279 case itemDoesNotExist
280 case failedToSaveToKeychain(errorCode: OSStatus)
281 case unsupportedKeyType(keyType: String)
282 case corecryptoKeyGeneration(corecryptoError: Int32)
285 extension RecoveryKeySetError: LocalizedError {
286 public var errorDescription: String? {
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)"
302 extension RecoveryKeySetError: CustomNSError {
304 public static var errorDomain: String {
305 return "com.apple.security.trustedpeers.RecoveryKeySetError"
308 public var errorCode: Int {
312 case .itemDoesNotExist:
314 case .failedToSaveToKeychain:
316 case .unsupportedKeyType:
318 case .corecryptoKeyGeneration:
323 public var errorUserInfo: [String: Any] {
324 var userInfo: [String: Any] = [:]
325 if let desc = self.errorDescription {
326 userInfo[NSLocalizedDescriptionKey] = desc
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)