2 File: ddnswriteconfig.m
4 Abstract: Setuid root tool invoked by Preference Pane to perform
5 privileged accesses to system configuration preferences and the system keychain.
6 Invoked by PrivilegedOperations.c.
8 Copyright: (c) Copyright 2005 Apple Computer, Inc. All rights reserved.
10 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
11 ("Apple") in consideration of your agreement to the following terms, and your
12 use, installation, modification or redistribution of this Apple software
13 constitutes acceptance of these terms. If you do not agree with these terms,
14 please do not use, install, modify or redistribute this Apple software.
16 In consideration of your agreement to abide by the following terms, and subject
17 to these terms, Apple grants you a personal, non-exclusive license, under Apple's
18 copyrights in this original Apple software (the "Apple Software"), to use,
19 reproduce, modify and redistribute the Apple Software, with or without
20 modifications, in source and/or binary forms; provided that if you redistribute
21 the Apple Software in its entirety and without modifications, you must retain
22 this notice and the following text and disclaimers in all such redistributions of
23 the Apple Software. Neither the name, trademarks, service marks or logos of
24 Apple Computer, Inc. may be used to endorse or promote products derived from the
25 Apple Software without specific prior written permission from Apple. Except as
26 expressly stated in this notice, no other rights or licenses, express or implied,
27 are granted by Apple herein, including but not limited to any patent rights that
28 may be infringed by your derivative works or by other works in which the Apple
29 Software may be incorporated.
31 The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
32 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
33 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
34 PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
35 COMBINATION WITH YOUR PRODUCTS.
37 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
38 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
39 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
41 OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
42 (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
43 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 Change History (most recent first):
47 $Log: ddnswriteconfig.m,v $
48 Revision 1.9 2007/09/18 19:09:02 cheshire
49 <rdar://problem/5489549> mDNSResponderHelper (and other binaries) missing SCCS version strings
51 Revision 1.8 2007/07/20 23:41:03 mkrochma
52 <rdar://problem/5348663> null deref in ddnswriteconfig
54 Revision 1.7 2007/03/07 00:49:00 cheshire
55 <rdar://problem/4618207> Security: ddnswriteconfig does not verify that authorization blob is of correct size
57 Revision 1.6 2007/02/09 00:39:06 cheshire
60 Revision 1.5 2006/08/14 23:15:47 cheshire
61 Tidy up Change History comment
63 Revision 1.4 2005/06/04 04:47:47 cheshire
64 <rdar://problem/4138070> ddnswriteconfig (Bonjour PreferencePane) vulnerability
65 Remove self-installing capability of ddnswriteconfig
67 Revision 1.3 2005/02/16 00:17:35 cheshire
68 Don't create empty arrays -- CFArrayGetValueAtIndex(array,0) returns an essentially random (non-null)
69 result for empty arrays, which can lead to code crashing if it's not sufficiently defensive.
71 Revision 1.2 2005/02/10 22:35:20 cheshire
72 <rdar://problem/3727944> Update name
74 Revision 1.1 2005/02/05 01:59:19 cheshire
75 Add Preference Pane to facilitate testing of DDNS & wide-area features
80 #import "PrivilegedOperations.h"
81 #import "ConfigurationRights.h"
92 #import <mach-o/dyld.h>
93 #import <AssertMacros.h>
94 #import <Security/Security.h>
95 #import <CoreServices/CoreServices.h>
96 #import <CoreFoundation/CoreFoundation.h>
97 #import <SystemConfiguration/SystemConfiguration.h>
98 #import <Foundation/Foundation.h>
101 static AuthorizationRef gAuthRef = 0;
104 WriteArrayToDynDNS(CFStringRef arrayKey, CFArrayRef domainArray)
106 SCPreferencesRef store;
107 OSStatus err = noErr;
108 CFDictionaryRef origDict;
109 CFMutableDictionaryRef dict = NULL;
111 CFStringRef scKey = CFSTR("/System/Network/DynamicDNS");
114 // Add domain to the array member ("arrayKey") of the DynamicDNS dictionary
115 // Will replace duplicate, at head of list
116 // At this point, we only support a single-item list
117 store = SCPreferencesCreate(NULL, CFSTR("com.apple.preference.bonjour"), NULL);
118 require_action(store != NULL, SysConfigErr, err=paramErr;);
119 require_action(true == SCPreferencesLock( store, true), LockFailed, err=coreFoundationUnknownErr;);
121 origDict = SCPreferencesPathGetValue(store, scKey);
123 dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
127 dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
129 require_action( dict != NULL, NoDict, err=memFullErr;);
131 if (CFArrayGetCount(domainArray) > 0) {
132 CFDictionarySetValue(dict, arrayKey, domainArray);
134 CFDictionaryRemoveValue(dict, arrayKey);
137 result = SCPreferencesPathSetValue(store, scKey, dict);
138 require_action(result, SCError, err=kernelPrivilegeErr;);
140 result = SCPreferencesCommitChanges(store);
141 require_action(result, SCError, err=kernelPrivilegeErr;);
142 result = SCPreferencesApplyChanges(store);
143 require_action(result, SCError, err=kernelPrivilegeErr;);
148 SCPreferencesUnlock(store);
157 readTaggedBlock(int fd, u_int32_t *pTag, u_int32_t *pLen, char **ppBuff)
158 // Read tag, block len and block data from stream and return. Dealloc *ppBuff via free().
164 num = read(fd, &tag, sizeof tag);
165 require_action(num == sizeof tag, GetTagFailed, result = -1;);
166 num = read(fd, &len, sizeof len);
167 require_action(num == sizeof len, GetLenFailed, result = -1;);
169 *ppBuff = (char*) malloc( len);
170 require_action(*ppBuff != NULL, AllocFailed, result = -1;);
172 num = read(fd, *ppBuff, len);
196 result = readTaggedBlock( fd, &tag, &len, &p);
197 require( result == 0, ReadParamsFailed);
198 require( len == sizeof(AuthorizationExternalForm), ReadParamsFailed);
199 require( len == kAuthorizationExternalFormLength, ReadParamsFailed);
202 (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDestroyRights);
206 result = AuthorizationCreateFromExternalForm((AuthorizationExternalForm*) p, &gAuthRef);
215 HandleWriteDomain(int fd, int domainType)
217 CFArrayRef domainArray;
218 CFDataRef domainData;
223 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
224 AuthorizationRights authSet = { 1, &scAuth };
226 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
229 result = readTaggedBlock(fd, &tag, &len, &p);
230 require(result == 0, ReadParamsFailed);
232 domainData = CFDataCreate(NULL, (UInt8 *)p, len);
233 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
236 result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
238 result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
247 HandleWriteHostname(int fd)
249 CFArrayRef domainArray;
250 CFDataRef domainData;
255 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
256 AuthorizationRights authSet = { 1, &scAuth };
258 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags) 0, NULL)))
261 result = readTaggedBlock(fd, &tag, &len, &p);
262 require(result == 0, ReadParamsFailed);
264 domainData = CFDataCreate(NULL, (const UInt8 *)p, len);
265 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
266 result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
274 MyMakeUidAccess(uid_t uid)
276 // make the "uid/gid" ACL subject
277 // this is a CSSM_LIST_ELEMENT chain
278 CSSM_ACL_PROCESS_SUBJECT_SELECTOR selector = {
279 CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION, // selector version
280 CSSM_ACL_MATCH_UID, // set mask: match uids (only)
282 0 // gid (not matched here)
284 CSSM_LIST_ELEMENT subject2 = { NULL, 0, 0, {{0,0,0}} };
285 subject2.Element.Word.Data = (UInt8 *)&selector;
286 subject2.Element.Word.Length = sizeof(selector);
287 CSSM_LIST_ELEMENT subject1 = { &subject2, CSSM_ACL_SUBJECT_TYPE_PROCESS, CSSM_LIST_ELEMENT_WORDID, {{0,0,0}} };
290 // rights granted (replace with individual list if desired)
291 CSSM_ACL_AUTHORIZATION_TAG rights[] = {
292 CSSM_ACL_AUTHORIZATION_ANY // everything
294 // owner component (right to change ACL)
295 CSSM_ACL_OWNER_PROTOTYPE owner = {
297 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
301 // ACL entries (any number, just one here)
302 CSSM_ACL_ENTRY_INFO acls =
304 // CSSM_ACL_ENTRY_PROTOTYPE
306 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 }, // TypedSubject
308 { sizeof(rights) / sizeof(rights[0]), rights }, // Authorization rights for this entry
309 { { 0, 0 }, { 0, 0 } }, // CSSM_ACL_VALIDITY_PERIOD
310 "" // CSSM_STRING EntryTag
316 SecAccessRef access = NULL;
317 (void) SecAccessCreateFromOwnerAndACL(&owner, 1, &acls, &access);
323 MyAddDynamicDNSPassword(SecKeychainRef keychain, SecAccessRef access, UInt32 serviceNameLength, const char *serviceName,
324 UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData)
326 char * description = DYNDNS_KEYCHAIN_DESCRIPTION;
327 UInt32 descriptionLength = strlen(DYNDNS_KEYCHAIN_DESCRIPTION);
328 UInt32 type = 'ddns';
329 UInt32 creator = 'ddns';
330 UInt32 typeLength = sizeof(type);
331 UInt32 creatorLength = sizeof(creator);
334 // set up attribute vector (each attribute consists of {tag, length, pointer})
335 SecKeychainAttribute attrs[] = { { kSecLabelItemAttr, serviceNameLength, (char *)serviceName },
336 { kSecAccountItemAttr, accountNameLength, (char *)accountName },
337 { kSecServiceItemAttr, serviceNameLength, (char *)serviceName },
338 { kSecDescriptionItemAttr, descriptionLength, (char *)description },
339 { kSecTypeItemAttr, typeLength, (UInt32 *)&type },
340 { kSecCreatorItemAttr, creatorLength, (UInt32 *)&creator } };
341 SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs };
343 err = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &attributes, passwordLength, passwordData, keychain, access, NULL);
349 SetKeychainEntry(int fd)
350 // Create a new entry in system keychain, or replace existing
352 CFDataRef secretData;
353 CFDictionaryRef secretDictionary;
354 CFStringRef keyNameString;
355 CFStringRef domainString;
356 CFStringRef secretString;
357 SecKeychainItemRef item = NULL;
365 AuthorizationItem kcAuth = { EDIT_SYS_KEYCHAIN_RIGHT, 0, NULL, 0 };
366 AuthorizationRights authSet = { 1, &kcAuth };
368 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
371 result = readTaggedBlock(fd, &tag, &len, &p);
372 require_noerr(result, ReadParamsFailed);
374 secretData = CFDataCreate(NULL, (UInt8 *)p, len);
375 secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
377 keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
378 assert(keyNameString != NULL);
380 domainString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_DOMAIN_KEY);
381 assert(domainString != NULL);
383 secretString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_SECRET_KEY);
384 assert(secretString != NULL);
386 CFStringGetCString(keyNameString, keyname, 1005, kCFStringEncodingUTF8);
387 CFStringGetCString(domainString, domain, 1005, kCFStringEncodingUTF8);
388 CFStringGetCString(secretString, secret, 1005, kCFStringEncodingUTF8);
390 result = SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
391 if (result == noErr) {
392 result = SecKeychainFindGenericPassword(NULL, strlen(domain), domain, 0, NULL, 0, NULL, &item);
393 if (result == noErr) {
394 result = SecKeychainItemDelete(item);
395 if (result != noErr) fprintf(stderr, "SecKeychainItemDelete returned %d\n", result);
398 result = MyAddDynamicDNSPassword(NULL, MyMakeUidAccess(0), strlen(domain), domain, strlen(keyname)+1, keyname, strlen(secret)+1, secret);
399 if (result != noErr) fprintf(stderr, "MyAddDynamicDNSPassword returned %d\n", result);
400 if (item) CFRelease(item);
408 int main( int argc, char **argv)
409 /* argv[0] is the exec path; argv[1] is a fd for input data; argv[2]... are operation codes.
410 The tool supports the following operations:
411 V -- exit with status PRIV_OP_TOOL_VERS
412 A -- read AuthInfo from input pipe
413 Wd -- write registration domain to dynamic store
414 Wb -- write browse domain to dynamic store
415 Wh -- write hostname to dynamic store
416 Wk -- write keychain entry for given account name
419 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
420 int commFD = -1, iArg, result = 0;
422 if ( 0 != seteuid( 0))
425 if ( argc == 3 && 0 == strcmp( argv[2], "V"))
426 return PRIV_OP_TOOL_VERS;
430 commFD = strtol( argv[1], NULL, 0);
431 lseek( commFD, 0, SEEK_SET);
433 for ( iArg = 2; iArg < argc && result == 0; iArg++)
435 if ( 0 == strcmp( "A", argv[ iArg])) // get auth info
437 result = SetAuthInfo( commFD);
439 else if ( 0 == strcmp( "Wd", argv[ iArg])) // Write registration domain
441 result = HandleWriteDomain( commFD, 1);
443 else if ( 0 == strcmp( "Wb", argv[ iArg])) // Write browse domain
445 result = HandleWriteDomain( commFD, 0);
447 else if ( 0 == strcmp( "Wh", argv[ iArg])) // Write hostname
449 result = HandleWriteHostname( commFD);
451 else if ( 0 == strcmp( "Wk", argv[ iArg])) // Write keychain entry
453 result = SetKeychainEntry( commFD);
460 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
461 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
462 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
463 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
464 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
466 // NOT static -- otherwise the compiler may optimize it out
467 // The "@(#) " pattern is a special prefix the "what" command looks for
468 const char VersionString_SCCS[] = "@(#) ddnswriteconfig " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
470 // If the process crashes, then this string will be magically included in the automatically-generated crash log
471 const char *__crashreporter_info__ = VersionString_SCCS + 5;
472 asm(".desc ___crashreporter_info__, 0x10");