]> git.saurik.com Git - apple/security.git/blob - OSX/sec/SOSCircle/SecureObjectSync/SOSInternal.m
Security-58286.41.2.tar.gz
[apple/security.git] / OSX / sec / SOSCircle / SecureObjectSync / SOSInternal.m
1 /*
2 * Copyright (c) 2012-2014 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
25 #include <Security/SecureObjectSync/SOSInternal.h>
26 #include <Security/SecureObjectSync/SOSCircle.h>
27 #include <Security/SecureObjectSync/SOSCloudCircle.h>
28 #include <Security/SecureObjectSync/SOSKVSKeys.h>
29 #include "utilities/SecCFError.h"
30 #include "utilities/SecCFRelease.h"
31 #include "utilities/SecCFWrappers.h"
32 #include "utilities/iOSforOSX.h"
33
34 #include <CoreFoundation/CoreFoundation.h>
35
36 #include <Security/SecKey.h>
37 #include <Security/SecKeyPriv.h>
38 #include <Security/SecItem.h>
39 #include <securityd/SecDbItem.h> // For SecError
40 #include "utilities/iOSforOSX.h"
41
42 #include <Security/SecBase64.h>
43 #include <utilities/der_plist.h>
44 #include <utilities/der_plist_internal.h>
45 #include <corecrypto/ccder.h>
46 #include <utilities/der_date.h>
47
48 #include <corecrypto/ccrng.h>
49 #include <corecrypto/ccrng_pbkdf2_prng.h>
50
51 #include <CommonCrypto/CommonRandomSPI.h>
52
53 #include <AssertMacros.h>
54
55 const CFStringRef kSecIDSErrorDomain = CFSTR("com.apple.security.ids.error");
56 const CFStringRef kIDSOperationType = CFSTR("IDSMessageOperation");
57 const CFStringRef kIDSMessageToSendKey = CFSTR("MessageToSendKey");
58 const CFStringRef kIDSMessageUniqueID = CFSTR("MessageID");
59 const CFStringRef kIDSMessageRecipientPeerID = CFSTR("RecipientPeerID");
60 const CFStringRef kIDSMessageRecipientDeviceID = CFSTR("RecipientDeviceID");
61 const CFStringRef kIDSMessageUsesAckModel = CFSTR("UsesAckModel");
62 const CFStringRef kSOSErrorDomain = CFSTR("com.apple.security.sos.error");
63 const CFStringRef SOSTransportMessageTypeIDSV2 = CFSTR("IDS2.0");
64 const CFStringRef SOSTransportMessageTypeKVS = CFSTR("KVS");
65
66 bool SOSErrorCreate(CFIndex errorCode, CFErrorRef *error, CFDictionaryRef formatOptions, CFStringRef format, ...)
67 CF_FORMAT_FUNCTION(4, 5);
68
69
70 bool SOSErrorCreate(CFIndex errorCode, CFErrorRef *error, CFDictionaryRef formatOptions, CFStringRef format, ...) {
71 if (!errorCode) return true;
72 if (error && !*error) {
73 va_list va;
74 va_start(va, format);
75 SecCFCreateErrorWithFormatAndArguments(errorCode, kSOSErrorDomain, NULL, error, formatOptions, format, va);
76 va_end(va);
77 }
78 return false;
79 }
80
81 bool SOSCreateError(CFIndex errorCode, CFStringRef descriptionString, CFErrorRef previousError, CFErrorRef *newError) {
82 SOSCreateErrorWithFormat(errorCode, previousError, newError, NULL, CFSTR("%@"), descriptionString);
83 return false;
84 }
85
86 bool SOSCreateErrorWithFormat(CFIndex errorCode, CFErrorRef previousError, CFErrorRef *newError,
87 CFDictionaryRef formatOptions, CFStringRef format, ...) {
88 va_list va;
89 va_start(va, format);
90 bool res = SOSCreateErrorWithFormatAndArguments(errorCode, previousError, newError, formatOptions, format, va);
91 va_end(va);
92 return res;
93 }
94
95 bool SOSCreateErrorWithFormatAndArguments(CFIndex errorCode, CFErrorRef previousError, CFErrorRef *newError,
96 CFDictionaryRef formatOptions, CFStringRef format, va_list args) {
97 return SecCFCreateErrorWithFormatAndArguments(errorCode, kSOSErrorDomain, previousError, newError, formatOptions, format, args);
98 }
99
100
101 //
102 // Utility Functions
103 //
104
105 static OSStatus GenerateECPairImp(int keySize, CFBooleanRef permanent, SecKeyRef* public, SecKeyRef *full)
106 {
107 static const CFStringRef sTempNameToUse = CFSTR("GenerateECPair Temporary Key - Shouldn't be live");
108
109 CFNumberRef signing_bitsize = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &keySize);
110
111 CFDictionaryRef keygen_parameters = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
112 kSecAttrKeyType, kSecAttrKeyTypeEC,
113 kSecAttrKeySizeInBits, signing_bitsize,
114 kSecAttrIsPermanent, permanent,
115 kSecAttrLabel, sTempNameToUse,
116 NULL);
117 CFReleaseNull(signing_bitsize);
118 OSStatus result = SecKeyGeneratePair(keygen_parameters, public, full);
119 CFReleaseNull(keygen_parameters);
120
121 return result;
122 }
123
124 OSStatus GenerateECPair(int keySize, SecKeyRef* public, SecKeyRef *full)
125 {
126 return GenerateECPairImp(keySize, kCFBooleanFalse, public, full);
127 }
128
129 OSStatus GeneratePermanentECPair(int keySize, SecKeyRef* public, SecKeyRef *full)
130 {
131 return GenerateECPairImp(keySize, kCFBooleanTrue, public, full);
132 }
133
134 static CFStringRef SOSCircleCopyDescriptionFromData(CFDataRef data)
135 {
136 CFErrorRef error = NULL;
137 CFStringRef result = NULL;
138
139 SOSCircleRef circle = SOSCircleCreateFromData(kCFAllocatorDefault, data, &error);
140
141 if (circle)
142 result = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@"), circle);
143
144 CFReleaseSafe(circle);
145
146 return result;
147 }
148
149 CFStringRef SOSItemsChangedCopyDescription(CFDictionaryRef changes, bool is_sender)
150 {
151 CFMutableStringRef string = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFSTR("<Changes: {\n"));
152
153 CFDictionaryForEach(changes, ^(const void *key, const void *value) {
154 CFStringRef value_description = NULL;
155 if (isString(key) && isData(value)) {
156 CFDataRef value_data = (CFDataRef) value;
157 switch (SOSKVSKeyGetKeyType(key)) {
158 case kCircleKey:
159 value_description = SOSCircleCopyDescriptionFromData(value_data);
160 break;
161 case kMessageKey:
162 value_description = CFCopyDescription(value_data);
163 break;
164 default:
165 break;
166 }
167
168 }
169 CFStringAppendFormat(string, NULL, CFSTR(" '%@' %s %@\n"),
170 key,
171 is_sender ? "<=" : "=>",
172 value_description ? value_description : value);
173
174 CFReleaseNull(value_description);
175 });
176
177 CFStringAppendFormat(string, NULL, CFSTR("}"));
178
179 return string;
180 }
181
182
183 CFStringRef SOSCopyIDOfDataBuffer(CFDataRef data, CFErrorRef *error) {
184 const struct ccdigest_info * di = ccsha1_di();
185 uint8_t digest[di->output_size];
186 char encoded[2 * di->output_size]; // Big enough for base64 encoding.
187
188 ccdigest(di, CFDataGetLength(data), CFDataGetBytePtr(data), digest);
189
190 size_t length = SecBase64Encode(digest, sizeof(digest), encoded, sizeof(encoded));
191 assert(length && length < sizeof(encoded));
192 if (length > 26)
193 length = 26;
194 encoded[length] = 0;
195 return CFStringCreateWithCString(kCFAllocatorDefault, encoded, kCFStringEncodingASCII);
196 }
197
198 CFStringRef SOSCopyIDOfDataBufferWithLength(CFDataRef data, CFIndex len, CFErrorRef *error) {
199 CFStringRef retval = NULL;
200 CFStringRef tmp = SOSCopyIDOfDataBuffer(data, error);
201 if(tmp) retval = CFStringCreateWithSubstring(kCFAllocatorDefault, tmp, CFRangeMake(0, len));
202 CFReleaseNull(tmp);
203 return retval;
204 }
205
206 CFStringRef SOSCopyIDOfKey(SecKeyRef key, CFErrorRef *error) {
207 CFDataRef publicBytes = NULL;
208 CFStringRef result = NULL;
209 require_quiet(SecError(SecKeyCopyPublicBytes(key, &publicBytes), error, CFSTR("Failed to export public bytes %@"), key), fail);
210 result = SOSCopyIDOfDataBuffer(publicBytes, error);
211 fail:
212 CFReleaseNull(publicBytes);
213 return result;
214 }
215
216 CFStringRef SOSCopyIDOfKeyWithLength(SecKeyRef key, CFIndex len, CFErrorRef *error) {
217 CFStringRef retval = NULL;
218 CFStringRef tmp = SOSCopyIDOfKey(key, error);
219 if(tmp) retval = CFStringCreateWithSubstring(kCFAllocatorDefault, tmp, CFRangeMake(0, len));
220 CFReleaseNull(tmp);
221 return retval;
222 }
223
224
225 CFGiblisGetSingleton(ccec_const_cp_t, SOSGetBackupKeyCurveParameters, sBackupKeyCurveParameters, ^{
226 *sBackupKeyCurveParameters = ccec_cp_256();
227 });
228
229
230 //
231 // We're expecting full entropy here, so we just need to stretch
232 // via the PBKDF entropy rng. We'll choose a few iterations and no salt
233 // since we don't get sent any.
234 //
235 const int kBackupKeyIterations = 20;
236 const uint8_t sBackupKeySalt[] = { 0 };
237
238 bool SOSPerformWithDeviceBackupFullKey(ccec_const_cp_t cp, CFDataRef entropy, CFErrorRef *error, void (^operation)(ccec_full_ctx_t fullKey))
239 {
240 bool result = false;
241 ccec_full_ctx_decl_cp(cp, fullKey);
242
243 require_quiet(SOSGenerateDeviceBackupFullKey(fullKey, cp, entropy, error), exit);
244
245 operation(fullKey);
246
247 result = true;
248 exit:
249 ccec_full_ctx_clear_cp(cp, fullKey);
250
251 return result;
252 }
253
254
255 bool SOSGenerateDeviceBackupFullKey(ccec_full_ctx_t generatedKey, ccec_const_cp_t cp, CFDataRef entropy, CFErrorRef* error)
256 {
257 bool result = false;
258 int cc_result = 0;
259 struct ccrng_pbkdf2_prng_state pbkdf2_prng;
260 const int kBackupKeyMaxBytes = 1024; // This may be a function of the cp but will be updated when we use a formally deterministic key generation.
261
262 cc_result = ccrng_pbkdf2_prng_init(&pbkdf2_prng, kBackupKeyMaxBytes,
263 CFDataGetLength(entropy), CFDataGetBytePtr(entropy),
264 sizeof(sBackupKeySalt), sBackupKeySalt,
265 kBackupKeyIterations);
266 require_action_quiet(cc_result == 0, exit, SOSErrorCreate(kSOSErrorProcessingFailure, error, NULL, CFSTR("pbkdf rng init failed: %d"), cc_result));
267
268 cc_result = ccec_compact_generate_key(cp, (struct ccrng_state *) &pbkdf2_prng, generatedKey);
269 require_action_quiet(cc_result == 0, exit, SOSErrorCreate(kSOSErrorProcessingFailure, error, NULL, CFSTR("Generate key failed: %d"), cc_result));
270
271 result = true;
272 exit:
273 bzero(&pbkdf2_prng, sizeof(pbkdf2_prng));
274 return result;
275
276 }
277
278 CFDataRef SOSCopyDeviceBackupPublicKey(CFDataRef entropy, CFErrorRef *error)
279 {
280 CFDataRef result = NULL;
281 CFMutableDataRef publicKeyData = NULL;
282
283 ccec_full_ctx_decl_cp(SOSGetBackupKeyCurveParameters(), fullKey);
284
285 require_quiet(SOSGenerateDeviceBackupFullKey(fullKey, SOSGetBackupKeyCurveParameters(), entropy, error), exit);
286
287 size_t space = ccec_compact_export_size(false, ccec_ctx_pub(fullKey));
288 publicKeyData = CFDataCreateMutableWithScratch(kCFAllocatorDefault, space);
289 require_quiet(SecAllocationError(publicKeyData, error, CFSTR("Mutable data allocation")), exit);
290
291 ccec_compact_export(false, CFDataGetMutableBytePtr(publicKeyData), fullKey);
292
293 CFTransferRetained(result, publicKeyData);
294
295 exit:
296 CFReleaseNull(publicKeyData);
297 return result;
298 }
299
300
301 CFDataRef SOSDateCreate(void) {
302 CFDateRef now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent());
303 size_t bufsiz = der_sizeof_date(now, NULL);
304 uint8_t buf[bufsiz];
305 der_encode_date(now, NULL, buf, buf+bufsiz);
306 CFReleaseNull(now);
307 return CFDataCreate(NULL, buf, bufsiz);
308 }
309
310
311 CFDataRef CFDataCreateWithDER(CFAllocatorRef allocator, CFIndex size, uint8_t*(^operation)(size_t size, uint8_t *buffer)) {
312 __block CFMutableDataRef result = NULL;
313 if(!size) return NULL;
314 if((result = CFDataCreateMutableWithScratch(allocator, size)) == NULL) return NULL;
315 uint8_t *ptr = CFDataGetMutableBytePtr(result);
316 uint8_t *derptr = operation(size, ptr);
317 if(derptr == ptr) return result; // most probable case
318 if(!derptr || derptr < ptr) { // DER op failed - or derptr ended up prior to allocated buffer
319 CFReleaseNull(result);
320 } else if(derptr > ptr) { // This is a possible case where we don't end up using the entire allocated buffer
321 size_t diff = derptr - ptr; // The unused space ends up being the beginning of the allocation
322 CFDataDeleteBytes(result, CFRangeMake(0, diff));
323 }
324 return result;
325 }