]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKS.m
Security-58286.270.3.0.1.tar.gz
[apple/security.git] / keychain / ckks / CKKS.m
1 /*
2 * Copyright (c) 2016 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 #include <dispatch/dispatch.h>
25 #import <Foundation/Foundation.h>
26 #include <sys/sysctl.h>
27 #if OCTAGON
28 #import <CloudKit/CloudKit.h>
29 #endif
30
31 #include <utilities/debugging.h>
32 #include <securityd/SecItemServer.h>
33 #include <Security/SecItemPriv.h>
34
35 #import <Foundation/Foundation.h>
36 #import "keychain/ckks/CKKS.h"
37 #import "keychain/ckks/CKKSKeychainView.h"
38 #import "keychain/ckks/CKKSViewManager.h"
39 #import "keychain/ckks/CKKSKey.h"
40
41 #import "keychain/ot/OTManager.h"
42 const SecCKKSItemEncryptionVersion currentCKKSItemEncryptionVersion = CKKSItemEncryptionVersion2;
43
44 NSString* const SecCKKSActionAdd = @"add";
45 NSString* const SecCKKSActionDelete = @"delete";
46 NSString* const SecCKKSActionModify = @"modify";
47
48 CKKSItemState* const SecCKKSStateNew = (CKKSItemState*) @"new";
49 CKKSItemState* const SecCKKSStateUnauthenticated = (CKKSItemState*) @"unauthenticated";
50 CKKSItemState* const SecCKKSStateInFlight = (CKKSItemState*) @"inflight";
51 CKKSItemState* const SecCKKSStateReencrypt = (CKKSItemState*) @"reencrypt";
52 CKKSItemState* const SecCKKSStateError = (CKKSItemState*) @"error";
53 CKKSItemState* const SecCKKSStateZoneMismatch = (CKKSItemState*) @"zone_mismatch";
54 CKKSItemState* const SecCKKSStateDeleted = (CKKSItemState*) @"deleted";
55
56 CKKSProcessedState* const SecCKKSProcessedStateLocal = (CKKSProcessedState*) @"local";
57 CKKSProcessedState* const SecCKKSProcessedStateRemote = (CKKSProcessedState*) @"remote";
58
59 CKKSKeyClass* const SecCKKSKeyClassTLK = (CKKSKeyClass*) @"tlk";
60 CKKSKeyClass* const SecCKKSKeyClassA = (CKKSKeyClass*) @"classA";
61 CKKSKeyClass* const SecCKKSKeyClassC = (CKKSKeyClass*) @"classC";
62
63 NSString* SecCKKSContainerName = @"com.apple.security.keychain";
64 bool SecCKKSContainerUsePCS = false;
65
66 NSString* const SecCKKSSubscriptionID = @"keychain-changes";
67 NSString* const SecCKKSAPSNamedPort = @"com.apple.securityd.aps";
68
69 NSString* const SecCKRecordItemType = @"item";
70 NSString* const SecCKRecordHostOSVersionKey = @"uploadver";
71 NSString* const SecCKRecordEncryptionVersionKey = @"encver";
72 NSString* const SecCKRecordDataKey = @"data";
73 NSString* const SecCKRecordParentKeyRefKey = @"parentkeyref";
74 NSString* const SecCKRecordWrappedKeyKey = @"wrappedkey";
75 NSString* const SecCKRecordGenerationCountKey = @"gen";
76
77 NSString* const SecCKRecordPCSServiceIdentifier = @"pcsservice";
78 NSString* const SecCKRecordPCSPublicKey = @"pcspublickey";
79 NSString* const SecCKRecordPCSPublicIdentity = @"pcspublicidentity";
80 NSString* const SecCKRecordServerWasCurrent = @"server_wascurrent";
81
82 NSString* const SecCKRecordIntermediateKeyType = @"synckey";
83 NSString* const SecCKRecordKeyClassKey = @"class";
84
85 NSString* const SecCKRecordTLKShareType = @"tlkshare";
86 NSString* const SecCKRecordSenderPeerID = @"sender";
87 NSString* const SecCKRecordReceiverPeerID = @"receiver";
88 NSString* const SecCKRecordReceiverPublicEncryptionKey = @"receiverPublicEncryptionKey";
89 NSString* const SecCKRecordCurve = @"curve";
90 NSString* const SecCKRecordEpoch = @"epoch";
91 NSString* const SecCKRecordPoisoned = @"poisoned";
92 NSString* const SecCKRecordSignature = @"signature";
93 NSString* const SecCKRecordVersion = @"version";
94
95 NSString* const SecCKRecordCurrentKeyType = @"currentkey";
96
97 NSString* const SecCKRecordCurrentItemType = @"currentitem";
98 NSString* const SecCKRecordItemRefKey = @"item";
99
100 NSString* const SecCKRecordDeviceStateType = @"devicestate";
101 NSString* const SecCKRecordOctagonPeerID = @"octagonpeerid";
102 NSString* const SecCKRecordOctagonStatus = @"octagonstatus";
103 NSString* const SecCKRecordCirclePeerID = @"peerid";
104 NSString* const SecCKRecordCircleStatus = @"circle";
105 NSString* const SecCKRecordKeyState = @"keystate";
106 NSString* const SecCKRecordCurrentTLK = @"currentTLK";
107 NSString* const SecCKRecordCurrentClassA = @"currentClassA";
108 NSString* const SecCKRecordCurrentClassC = @"currentClassC";
109 NSString* const SecCKSRecordLastUnlockTime = @"lastunlock";
110 NSString* const SecCKSRecordOSVersionKey = @"osver";
111
112 NSString* const SecCKRecordManifestType = @"manifest";
113 NSString* const SecCKRecordManifestDigestValueKey = @"digest_value";
114 NSString* const SecCKRecordManifestGenerationCountKey = @"generation_count";
115 NSString* const SecCKRecordManifestLeafRecordIDsKey = @"leaf_records";
116 NSString* const SecCKRecordManifestPeerManifestRecordIDsKey = @"peer_manifests";
117 NSString* const SecCKRecordManifestCurrentItemsKey = @"current_items";
118 NSString* const SecCKRecordManifestSignaturesKey = @"signatures";
119 NSString* const SecCKRecordManifestSignerIDKey = @"signer_id";
120 NSString* const SecCKRecordManifestSchemaKey = @"schema";
121
122 NSString* const SecCKRecordManifestLeafType = @"manifest_leaf";
123 NSString* const SecCKRecordManifestLeafDERKey = @"der";
124 NSString* const SecCKRecordManifestLeafDigestKey = @"digest";
125
126 CKKSZoneKeyState* const SecCKKSZoneKeyStateReady = (CKKSZoneKeyState*) @"ready";
127 CKKSZoneKeyState* const SecCKKSZoneKeyStateReadyPendingUnlock = (CKKSZoneKeyState*) @"readypendingunlock";
128 CKKSZoneKeyState* const SecCKKSZoneKeyStateError = (CKKSZoneKeyState*) @"error";
129 CKKSZoneKeyState* const SecCKKSZoneKeyStateCancelled = (CKKSZoneKeyState*) @"cancelled";
130
131 CKKSZoneKeyState* const SecCKKSZoneKeyStateInitializing = (CKKSZoneKeyState*) @"initializing";
132 CKKSZoneKeyState* const SecCKKSZoneKeyStateInitialized = (CKKSZoneKeyState*) @"initialized";
133 CKKSZoneKeyState* const SecCKKSZoneKeyStateFetch = (CKKSZoneKeyState*) @"fetching";
134 CKKSZoneKeyState* const SecCKKSZoneKeyStateFetchComplete = (CKKSZoneKeyState*) @"fetchcomplete";
135 CKKSZoneKeyState* const SecCKKSZoneKeyStateNeedFullRefetch = (CKKSZoneKeyState*) @"needrefetch";
136 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForTLK = (CKKSZoneKeyState*) @"waitfortlk";
137 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForUnlock = (CKKSZoneKeyState*) @"waitforunlock";
138 CKKSZoneKeyState* const SecCKKSZoneKeyStateUnhealthy = (CKKSZoneKeyState*) @"unhealthy";
139 CKKSZoneKeyState* const SecCKKSZoneKeyStateBadCurrentPointers = (CKKSZoneKeyState*) @"badcurrentpointers";
140 CKKSZoneKeyState* const SecCKKSZoneKeyStateNewTLKsFailed = (CKKSZoneKeyState*) @"newtlksfailed";
141 CKKSZoneKeyState* const SecCKKSZoneKeyStateHealTLKShares = (CKKSZoneKeyState*) @"healtlkshares";
142 CKKSZoneKeyState* const SecCKKSZoneKeyStateHealTLKSharesFailed = (CKKSZoneKeyState*) @"healtlksharesfailed";
143 CKKSZoneKeyState* const SecCKKSZoneKeyStateWaitForFixupOperation = (CKKSZoneKeyState*) @"waitforfixupoperation";
144 CKKSZoneKeyState* const SecCKKSZoneKeyStateResettingZone = (CKKSZoneKeyState*) @"resetzone";
145 CKKSZoneKeyState* const SecCKKSZoneKeyStateResettingLocalData = (CKKSZoneKeyState*) @"resetlocal";
146 CKKSZoneKeyState* const SecCKKSZoneKeyStateLoggedOut = (CKKSZoneKeyState*) @"loggedout";
147 CKKSZoneKeyState* const SecCKKSZoneKeyStateZoneCreationFailed = (CKKSZoneKeyState*) @"zonecreationfailed";
148 CKKSZoneKeyState* const SecCKKSZoneKeyStateProcess = (CKKSZoneKeyState*) @"process";
149
150 NSDictionary<CKKSZoneKeyState*, NSNumber*>* CKKSZoneKeyStateMap(void) {
151 static NSDictionary<CKKSZoneKeyState*, NSNumber*>* map = nil;
152 static dispatch_once_t onceToken;
153 dispatch_once(&onceToken, ^{
154 map = @{
155 SecCKKSZoneKeyStateReady: @0U,
156 SecCKKSZoneKeyStateError: @1U,
157 SecCKKSZoneKeyStateCancelled: @2U,
158
159 SecCKKSZoneKeyStateInitializing: @3U,
160 SecCKKSZoneKeyStateInitialized: @4U,
161 SecCKKSZoneKeyStateFetchComplete: @5U,
162 SecCKKSZoneKeyStateWaitForTLK: @6U,
163 SecCKKSZoneKeyStateWaitForUnlock: @7U,
164 SecCKKSZoneKeyStateUnhealthy: @8U,
165 SecCKKSZoneKeyStateBadCurrentPointers: @9U,
166 SecCKKSZoneKeyStateNewTLKsFailed: @10U,
167 SecCKKSZoneKeyStateNeedFullRefetch: @11U,
168 SecCKKSZoneKeyStateHealTLKShares: @12U,
169 SecCKKSZoneKeyStateHealTLKSharesFailed:@13U,
170 SecCKKSZoneKeyStateWaitForFixupOperation:@14U,
171 SecCKKSZoneKeyStateReadyPendingUnlock: @15U,
172 SecCKKSZoneKeyStateFetch: @16U,
173 SecCKKSZoneKeyStateResettingZone: @17U,
174 SecCKKSZoneKeyStateResettingLocalData: @18U,
175 SecCKKSZoneKeyStateLoggedOut: @19U,
176 SecCKKSZoneKeyStateZoneCreationFailed: @20U,
177 };
178 });
179 return map;
180 }
181
182 NSDictionary<NSNumber*, CKKSZoneKeyState*>* CKKSZoneKeyStateInverseMap(void) {
183 static NSDictionary<NSNumber*, CKKSZoneKeyState*>* backwardMap = nil;
184 static dispatch_once_t onceToken;
185 dispatch_once(&onceToken, ^{
186 NSDictionary<CKKSZoneKeyState*, NSNumber*>* forwardMap = CKKSZoneKeyStateMap();
187 backwardMap = [NSDictionary dictionaryWithObjects:[forwardMap allKeys] forKeys:[forwardMap allValues]];
188 });
189 return backwardMap;
190 }
191
192 NSNumber* CKKSZoneKeyToNumber(CKKSZoneKeyState* state) {
193 if(!state) {
194 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
195 }
196 NSNumber* result = CKKSZoneKeyStateMap()[state];
197 if(result) {
198 return result;
199 }
200 return CKKSZoneKeyStateMap()[SecCKKSZoneKeyStateError];
201 }
202 CKKSZoneKeyState* CKKSZoneKeyRecover(NSNumber* stateNumber) {
203 if(!stateNumber) {
204 return SecCKKSZoneKeyStateError;
205 }
206 CKKSZoneKeyState* result = CKKSZoneKeyStateInverseMap()[stateNumber];
207 if(result) {
208 return result;
209 }
210 return SecCKKSZoneKeyStateError;
211 }
212
213 bool CKKSKeyStateTransient(CKKSZoneKeyState* state) {
214 // Easier to compare against a blacklist of end states
215 bool nontransient = [state isEqualToString:SecCKKSZoneKeyStateReady] ||
216 [state isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock] ||
217 [state isEqualToString:SecCKKSZoneKeyStateWaitForTLK] ||
218 [state isEqualToString:SecCKKSZoneKeyStateWaitForUnlock] ||
219 [state isEqualToString:SecCKKSZoneKeyStateError] ||
220 [state isEqualToString:SecCKKSZoneKeyStateCancelled];
221 return !nontransient;
222 }
223
224 const NSUInteger SecCKKSItemPaddingBlockSize = 20;
225
226 NSString* const SecCKKSAggdPropagationDelay = @"com.apple.security.ckks.propagationdelay";
227 NSString* const SecCKKSAggdPrimaryKeyConflict = @"com.apple.security.ckks.pkconflict";
228 NSString* const SecCKKSAggdViewKeyCount = @"com.apple.security.ckks.keycount";
229 NSString* const SecCKKSAggdItemReencryption = @"com.apple.security.ckks.reencrypt";
230
231 NSString* const SecCKKSUserDefaultsSuite = @"com.apple.security.ckks";
232
233 NSString* const CKKSErrorDomain = @"CKKSErrorDomain";
234 NSString* const CKKSServerExtensionErrorDomain = @"CKKSServerExtensionErrorDomain";
235
236 #if OCTAGON
237 static bool enableCKKS = true;
238 static bool testCKKS = false;
239
240 bool SecCKKSIsEnabled(void) {
241 if([CKDatabase class] == nil) {
242 // CloudKit is not linked. We cannot bring CKKS up; disable it with prejudice.
243 secerror("CKKS: CloudKit.framework appears to not be linked. Cannot enable CKKS (on pain of crash).");
244 return false;
245 }
246
247 return enableCKKS;
248 }
249
250 bool SecCKKSEnable() {
251 enableCKKS = true;
252 return enableCKKS;
253 }
254
255 bool SecCKKSDisable() {
256 enableCKKS = false;
257 return enableCKKS;
258 }
259
260 bool SecCKKSResetSyncing(void) {
261 [CKKSViewManager resetManager: true setTo: nil];
262 return SecCKKSIsEnabled();
263 }
264
265 bool SecCKKSTestsEnabled(void) {
266 return testCKKS;
267 }
268
269 bool SecCKKSTestsEnable(void) {
270 if([CKDatabase class] == nil) {
271 // CloudKit is not linked. We cannot bring CKKS up; disable it with prejudice.
272 secerror("CKKS: CloudKit.framework appears to not be linked. Cannot enable CKKS testing.");
273 testCKKS = false;
274 return false;
275 }
276
277 testCKKS = true;
278 return testCKKS;
279 }
280
281 bool SecCKKSTestsDisable(void) {
282 testCKKS = false;
283 return testCKKS;
284 }
285
286 // Feature flags to twiddle behavior
287 static bool CKKSSyncManifests = false;
288 bool SecCKKSSyncManifests(void) {
289 return CKKSSyncManifests;
290 }
291 bool SecCKKSEnableSyncManifests() {
292 CKKSSyncManifests = true;
293 return CKKSSyncManifests;
294 }
295 bool SecCKKSSetSyncManifests(bool value) {
296 CKKSSyncManifests = value;
297 return CKKSSyncManifests;
298 }
299
300 static bool CKKSEnforceManifests = false;
301 bool SecCKKSEnforceManifests(void) {
302 return CKKSEnforceManifests;
303 }
304 bool SecCKKSEnableEnforceManifests() {
305 CKKSEnforceManifests = true;
306 return CKKSEnforceManifests;
307 }
308 bool SecCKKSSetEnforceManifests(bool value) {
309 CKKSEnforceManifests = value;
310 return CKKSEnforceManifests;
311 }
312
313 // defaults write com.apple.security.ckks reduce-rate-limiting YES
314 static bool CKKSReduceRateLimiting = false;
315 bool SecCKKSReduceRateLimiting(void) {
316 static dispatch_once_t onceToken;
317 dispatch_once(&onceToken, ^{
318 // Use the default value as above, or apply the preferences value if it exists
319 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SecCKKSUserDefaultsSuite];
320 NSString* key = @"reduce-rate-limiting";
321 [defaults registerDefaults: @{key: CKKSReduceRateLimiting ? @YES : @NO}];
322
323 CKKSReduceRateLimiting = !![defaults boolForKey:@"reduce-rate-limiting"];
324 secnotice("ckks", "reduce-rate-limiting is %@", CKKSReduceRateLimiting ? @"on" : @"off");
325 });
326
327 return CKKSReduceRateLimiting;
328 }
329
330 bool SecCKKSSetReduceRateLimiting(bool value) {
331 (void) SecCKKSReduceRateLimiting(); // Call this once to read the defaults write
332 CKKSReduceRateLimiting = value;
333 secnotice("ckks", "reduce-rate-limiting is now %@", CKKSReduceRateLimiting ? @"on" : @"off");
334 return CKKSReduceRateLimiting;
335 }
336
337 // Here's a mechanism for CKKS feature flags with default values from NSUserDefaults:
338 /*static bool CKKSShareTLKs = true;
339 bool SecCKKSShareTLKs(void) {
340 return true;
341 static dispatch_once_t onceToken;
342 dispatch_once(&onceToken, ^{
343 // Use the default value as above, or apply the preferences value if it exists
344 NSUserDefaults* defaults = [[NSUserDefaults alloc] initWithSuiteName:SecCKKSUserDefaultsSuite];
345 [defaults registerDefaults: @{@"tlksharing": CKKSShareTLKs ? @YES : @NO}];
346
347 CKKSShareTLKs = !![defaults boolForKey:@"tlksharing"];
348 secnotice("ckksshare", "TLK sharing is %@", CKKSShareTLKs ? @"on" : @"off");
349 });
350
351 return CKKSShareTLKs;
352 }*/
353
354 // Feature flags to twiddle behavior for tests
355 static bool CKKSDisableAutomaticUUID = false;
356 bool SecCKKSTestDisableAutomaticUUID(void) {
357 #if DEBUG
358 return CKKSDisableAutomaticUUID;
359 #else
360 return false;
361 #endif
362 }
363 void SecCKKSTestSetDisableAutomaticUUID(bool set) {
364 CKKSDisableAutomaticUUID = set;
365 }
366
367 static bool CKKSDisableSOS = false;
368 bool SecCKKSTestDisableSOS(void) {
369 #if DEBUG
370 return CKKSDisableSOS;
371 #else
372 return false;
373 #endif
374 }
375 void SecCKKSTestSetDisableSOS(bool set) {
376 CKKSDisableSOS = set;
377 }
378
379
380 static bool CKKSDisableKeyNotifications = false;
381 bool SecCKKSTestDisableKeyNotifications(void) {
382 #if DEBUG
383 return CKKSDisableKeyNotifications;
384 #else
385 return false;
386 #endif
387 }
388 void SecCKKSTestSetDisableKeyNotifications(bool set) {
389 CKKSDisableKeyNotifications = set;
390 }
391
392 void SecCKKSTestResetFlags(void) {
393 SecCKKSTestSetDisableAutomaticUUID(false);
394 SecCKKSTestSetDisableSOS(false);
395 SecCKKSTestSetDisableKeyNotifications(false);
396 }
397
398 #else /* NO OCTAGON */
399
400 bool SecCKKSIsEnabled(void) {
401 secerror("CKKS was disabled at compile time.");
402 return false;
403 }
404
405 bool SecCKKSEnable() {
406 return false;
407 }
408
409 bool SecCKKSDisable() {
410 return false;
411 }
412
413 bool SecCKKSResetSyncing(void) {
414 return SecCKKSIsEnabled();
415 }
416
417 #endif /* OCTAGON */
418
419
420
421 void SecCKKSInitialize(SecDbRef db) {
422 #if OCTAGON
423 @autoreleasepool {
424 CKKSViewManager* manager = [CKKSViewManager manager];
425 [manager initializeZones];
426
427 SecDbAddNotifyPhaseBlock(db, ^(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
428 SecCKKSNotifyBlock(dbconn, phase, source, changes);
429 });
430
431 [manager.completedSecCKKSInitialize fulfill];
432 }
433 #endif
434 }
435
436 void SecCKKSNotifyBlock(SecDbConnectionRef dbconn, SecDbTransactionPhase phase, SecDbTransactionSource source, CFArrayRef changes) {
437 #if OCTAGON
438 if(phase == kSecDbTransactionDidRollback) {
439 return;
440 }
441
442 // Ignore our own changes, otherwise we'd infinite-loop.
443 if(source == kSecDbCKKSTransaction) {
444 secinfo("ckks", "Ignoring kSecDbCKKSTransaction notification");
445 return;
446 }
447
448 CFArrayForEach(changes, ^(CFTypeRef r) {
449 SecDbItemRef deleted = NULL;
450 SecDbItemRef added = NULL;
451
452 SecDbEventTranslateComponents(r, (CFTypeRef*) &deleted, (CFTypeRef*) &added);
453
454 if(!added && !deleted) {
455 secerror("CKKS: SecDbEvent gave us garbage: %@", r);
456 return;
457 }
458
459 [[CKKSViewManager manager] handleKeychainEventDbConnection: dbconn source:source added: added deleted: deleted];
460 });
461 #endif
462 }
463
464 void SecCKKS24hrNotification() {
465 #if OCTAGON
466 @autoreleasepool {
467 [[CKKSViewManager manager] xpc24HrNotification];
468 }
469 #endif
470 }
471
472 void CKKSRegisterSyncStatusCallback(CFStringRef cfuuid, SecBoolCFErrorCallback cfcallback) {
473 #if OCTAGON
474 // Keep plumbing, but transition to NS.
475 SecBoolNSErrorCallback nscallback = ^(bool result, NSError* err) {
476 cfcallback(result, (__bridge CFErrorRef) err);
477 };
478
479 [[CKKSViewManager manager] registerSyncStatusCallback: (__bridge NSString*) cfuuid callback:nscallback];
480 #endif
481 }
482
483 void SecCKKSPerformLocalResync() {
484 #if OCTAGON
485 secnotice("ckks", "Local keychain was reset; performing local resync");
486 [[CKKSViewManager manager] rpcResyncLocal:nil reply:^(NSError *result) {
487 if(result) {
488 secnotice("ckks", "Local keychain reset resync finished with an error: %@", result);
489 } else {
490 secnotice("ckks", "Local keychain reset resync finished successfully");
491 }
492 }];
493 #endif
494 }
495
496 NSString* SecCKKSHostOSVersion()
497 {
498 #ifdef PLATFORM
499 // Use complicated macro magic to get the string value passed in as preprocessor define PLATFORM.
500 #define PLATFORM_VALUE(f) #f
501 #define PLATFORM_OBJCSTR(f) @PLATFORM_VALUE(f)
502 NSString* platform = (PLATFORM_OBJCSTR(PLATFORM));
503 #undef PLATFORM_OBJCSTR
504 #undef PLATFORM_VALUE
505 #else
506 NSString* platform = "unknown";
507 #warning No PLATFORM defined; why?
508 #endif
509
510 NSString* osversion = nil;
511
512 // If we can get the build information from sysctl, use it.
513 char release[256];
514 size_t releasesize = sizeof(release);
515 bool haveSysctlInfo = true;
516 haveSysctlInfo &= (0 == sysctlbyname("kern.osrelease", release, &releasesize, NULL, 0));
517
518 char version[256];
519 size_t versionsize = sizeof(version);
520 haveSysctlInfo &= (0 == sysctlbyname("kern.osversion", version, &versionsize, NULL, 0));
521
522 if(haveSysctlInfo) {
523 // Null-terminate for extra safety
524 release[sizeof(release)-1] = '\0';
525 version[sizeof(version)-1] = '\0';
526 osversion = [NSString stringWithFormat:@"%s (%s)", release, version];
527 }
528
529 if(!osversion) {
530 // Otherwise, use the not-really-supported fallback.
531 osversion = [[NSProcessInfo processInfo] operatingSystemVersionString];
532
533 // subtly improve osversion (but it's okay if that does nothing)
534 osversion = [osversion stringByReplacingOccurrencesOfString:@"Version" withString:@""];
535 }
536
537 return [NSString stringWithFormat:@"%@ %@", platform, osversion];
538 }