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.10 2007/11/30 23:43:04 cheshire
49 Fixed compile warning: declaration of 'access' shadows a global declaration
51 Revision 1.9 2007/09/18 19:09:02 cheshire
52 <rdar://problem/5489549> mDNSResponderHelper (and other binaries) missing SCCS version strings
54 Revision 1.8 2007/07/20 23:41:03 mkrochma
55 <rdar://problem/5348663> null deref in ddnswriteconfig
57 Revision 1.7 2007/03/07 00:49:00 cheshire
58 <rdar://problem/4618207> Security: ddnswriteconfig does not verify that authorization blob is of correct size
60 Revision 1.6 2007/02/09 00:39:06 cheshire
63 Revision 1.5 2006/08/14 23:15:47 cheshire
64 Tidy up Change History comment
66 Revision 1.4 2005/06/04 04:47:47 cheshire
67 <rdar://problem/4138070> ddnswriteconfig (Bonjour PreferencePane) vulnerability
68 Remove self-installing capability of ddnswriteconfig
70 Revision 1.3 2005/02/16 00:17:35 cheshire
71 Don't create empty arrays -- CFArrayGetValueAtIndex(array,0) returns an essentially random (non-null)
72 result for empty arrays, which can lead to code crashing if it's not sufficiently defensive.
74 Revision 1.2 2005/02/10 22:35:20 cheshire
75 <rdar://problem/3727944> Update name
77 Revision 1.1 2005/02/05 01:59:19 cheshire
78 Add Preference Pane to facilitate testing of DDNS & wide-area features
83 #import "PrivilegedOperations.h"
84 #import "ConfigurationRights.h"
95 #import <mach-o/dyld.h>
96 #import <AssertMacros.h>
97 #import <Security/Security.h>
98 #import <CoreServices/CoreServices.h>
99 #import <CoreFoundation/CoreFoundation.h>
100 #import <SystemConfiguration/SystemConfiguration.h>
101 #import <Foundation/Foundation.h>
104 static AuthorizationRef gAuthRef = 0;
107 WriteArrayToDynDNS(CFStringRef arrayKey, CFArrayRef domainArray)
109 SCPreferencesRef store;
110 OSStatus err = noErr;
111 CFDictionaryRef origDict;
112 CFMutableDictionaryRef dict = NULL;
114 CFStringRef scKey = CFSTR("/System/Network/DynamicDNS");
117 // Add domain to the array member ("arrayKey") of the DynamicDNS dictionary
118 // Will replace duplicate, at head of list
119 // At this point, we only support a single-item list
120 store = SCPreferencesCreate(NULL, CFSTR("com.apple.preference.bonjour"), NULL);
121 require_action(store != NULL, SysConfigErr, err=paramErr;);
122 require_action(true == SCPreferencesLock( store, true), LockFailed, err=coreFoundationUnknownErr;);
124 origDict = SCPreferencesPathGetValue(store, scKey);
126 dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
130 dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
132 require_action( dict != NULL, NoDict, err=memFullErr;);
134 if (CFArrayGetCount(domainArray) > 0) {
135 CFDictionarySetValue(dict, arrayKey, domainArray);
137 CFDictionaryRemoveValue(dict, arrayKey);
140 result = SCPreferencesPathSetValue(store, scKey, dict);
141 require_action(result, SCError, err=kernelPrivilegeErr;);
143 result = SCPreferencesCommitChanges(store);
144 require_action(result, SCError, err=kernelPrivilegeErr;);
145 result = SCPreferencesApplyChanges(store);
146 require_action(result, SCError, err=kernelPrivilegeErr;);
151 SCPreferencesUnlock(store);
160 readTaggedBlock(int fd, u_int32_t *pTag, u_int32_t *pLen, char **ppBuff)
161 // Read tag, block len and block data from stream and return. Dealloc *ppBuff via free().
167 num = read(fd, &tag, sizeof tag);
168 require_action(num == sizeof tag, GetTagFailed, result = -1;);
169 num = read(fd, &len, sizeof len);
170 require_action(num == sizeof len, GetLenFailed, result = -1;);
172 *ppBuff = (char*) malloc( len);
173 require_action(*ppBuff != NULL, AllocFailed, result = -1;);
175 num = read(fd, *ppBuff, len);
199 result = readTaggedBlock( fd, &tag, &len, &p);
200 require( result == 0, ReadParamsFailed);
201 require( len == sizeof(AuthorizationExternalForm), ReadParamsFailed);
202 require( len == kAuthorizationExternalFormLength, ReadParamsFailed);
205 (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDestroyRights);
209 result = AuthorizationCreateFromExternalForm((AuthorizationExternalForm*) p, &gAuthRef);
218 HandleWriteDomain(int fd, int domainType)
220 CFArrayRef domainArray;
221 CFDataRef domainData;
226 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
227 AuthorizationRights authSet = { 1, &scAuth };
229 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
232 result = readTaggedBlock(fd, &tag, &len, &p);
233 require(result == 0, ReadParamsFailed);
235 domainData = CFDataCreate(NULL, (UInt8 *)p, len);
236 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
239 result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
241 result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
250 HandleWriteHostname(int fd)
252 CFArrayRef domainArray;
253 CFDataRef domainData;
258 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
259 AuthorizationRights authSet = { 1, &scAuth };
261 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags) 0, NULL)))
264 result = readTaggedBlock(fd, &tag, &len, &p);
265 require(result == 0, ReadParamsFailed);
267 domainData = CFDataCreate(NULL, (const UInt8 *)p, len);
268 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
269 result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
277 MyMakeUidAccess(uid_t uid)
279 // make the "uid/gid" ACL subject
280 // this is a CSSM_LIST_ELEMENT chain
281 CSSM_ACL_PROCESS_SUBJECT_SELECTOR selector = {
282 CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION, // selector version
283 CSSM_ACL_MATCH_UID, // set mask: match uids (only)
285 0 // gid (not matched here)
287 CSSM_LIST_ELEMENT subject2 = { NULL, 0, 0, {{0,0,0}} };
288 subject2.Element.Word.Data = (UInt8 *)&selector;
289 subject2.Element.Word.Length = sizeof(selector);
290 CSSM_LIST_ELEMENT subject1 = { &subject2, CSSM_ACL_SUBJECT_TYPE_PROCESS, CSSM_LIST_ELEMENT_WORDID, {{0,0,0}} };
293 // rights granted (replace with individual list if desired)
294 CSSM_ACL_AUTHORIZATION_TAG rights[] = {
295 CSSM_ACL_AUTHORIZATION_ANY // everything
297 // owner component (right to change ACL)
298 CSSM_ACL_OWNER_PROTOTYPE owner = {
300 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
304 // ACL entries (any number, just one here)
305 CSSM_ACL_ENTRY_INFO acls =
307 // CSSM_ACL_ENTRY_PROTOTYPE
309 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 }, // TypedSubject
311 { sizeof(rights) / sizeof(rights[0]), rights }, // Authorization rights for this entry
312 { { 0, 0 }, { 0, 0 } }, // CSSM_ACL_VALIDITY_PERIOD
313 "" // CSSM_STRING EntryTag
319 SecAccessRef a = NULL;
320 (void) SecAccessCreateFromOwnerAndACL(&owner, 1, &acls, &a);
326 MyAddDynamicDNSPassword(SecKeychainRef keychain, SecAccessRef a, UInt32 serviceNameLength, const char *serviceName,
327 UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData)
329 char * description = DYNDNS_KEYCHAIN_DESCRIPTION;
330 UInt32 descriptionLength = strlen(DYNDNS_KEYCHAIN_DESCRIPTION);
331 UInt32 type = 'ddns';
332 UInt32 creator = 'ddns';
333 UInt32 typeLength = sizeof(type);
334 UInt32 creatorLength = sizeof(creator);
337 // set up attribute vector (each attribute consists of {tag, length, pointer})
338 SecKeychainAttribute attrs[] = { { kSecLabelItemAttr, serviceNameLength, (char *)serviceName },
339 { kSecAccountItemAttr, accountNameLength, (char *)accountName },
340 { kSecServiceItemAttr, serviceNameLength, (char *)serviceName },
341 { kSecDescriptionItemAttr, descriptionLength, (char *)description },
342 { kSecTypeItemAttr, typeLength, (UInt32 *)&type },
343 { kSecCreatorItemAttr, creatorLength, (UInt32 *)&creator } };
344 SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs };
346 err = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &attributes, passwordLength, passwordData, keychain, a, NULL);
352 SetKeychainEntry(int fd)
353 // Create a new entry in system keychain, or replace existing
355 CFDataRef secretData;
356 CFDictionaryRef secretDictionary;
357 CFStringRef keyNameString;
358 CFStringRef domainString;
359 CFStringRef secretString;
360 SecKeychainItemRef item = NULL;
368 AuthorizationItem kcAuth = { EDIT_SYS_KEYCHAIN_RIGHT, 0, NULL, 0 };
369 AuthorizationRights authSet = { 1, &kcAuth };
371 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
374 result = readTaggedBlock(fd, &tag, &len, &p);
375 require_noerr(result, ReadParamsFailed);
377 secretData = CFDataCreate(NULL, (UInt8 *)p, len);
378 secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
380 keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
381 assert(keyNameString != NULL);
383 domainString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_DOMAIN_KEY);
384 assert(domainString != NULL);
386 secretString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_SECRET_KEY);
387 assert(secretString != NULL);
389 CFStringGetCString(keyNameString, keyname, 1005, kCFStringEncodingUTF8);
390 CFStringGetCString(domainString, domain, 1005, kCFStringEncodingUTF8);
391 CFStringGetCString(secretString, secret, 1005, kCFStringEncodingUTF8);
393 result = SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
394 if (result == noErr) {
395 result = SecKeychainFindGenericPassword(NULL, strlen(domain), domain, 0, NULL, 0, NULL, &item);
396 if (result == noErr) {
397 result = SecKeychainItemDelete(item);
398 if (result != noErr) fprintf(stderr, "SecKeychainItemDelete returned %d\n", result);
401 result = MyAddDynamicDNSPassword(NULL, MyMakeUidAccess(0), strlen(domain), domain, strlen(keyname)+1, keyname, strlen(secret)+1, secret);
402 if (result != noErr) fprintf(stderr, "MyAddDynamicDNSPassword returned %d\n", result);
403 if (item) CFRelease(item);
411 int main( int argc, char **argv)
412 /* argv[0] is the exec path; argv[1] is a fd for input data; argv[2]... are operation codes.
413 The tool supports the following operations:
414 V -- exit with status PRIV_OP_TOOL_VERS
415 A -- read AuthInfo from input pipe
416 Wd -- write registration domain to dynamic store
417 Wb -- write browse domain to dynamic store
418 Wh -- write hostname to dynamic store
419 Wk -- write keychain entry for given account name
422 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
423 int commFD = -1, iArg, result = 0;
425 if ( 0 != seteuid( 0))
428 if ( argc == 3 && 0 == strcmp( argv[2], "V"))
429 return PRIV_OP_TOOL_VERS;
433 commFD = strtol( argv[1], NULL, 0);
434 lseek( commFD, 0, SEEK_SET);
436 for ( iArg = 2; iArg < argc && result == 0; iArg++)
438 if ( 0 == strcmp( "A", argv[ iArg])) // get auth info
440 result = SetAuthInfo( commFD);
442 else if ( 0 == strcmp( "Wd", argv[ iArg])) // Write registration domain
444 result = HandleWriteDomain( commFD, 1);
446 else if ( 0 == strcmp( "Wb", argv[ iArg])) // Write browse domain
448 result = HandleWriteDomain( commFD, 0);
450 else if ( 0 == strcmp( "Wh", argv[ iArg])) // Write hostname
452 result = HandleWriteHostname( commFD);
454 else if ( 0 == strcmp( "Wk", argv[ iArg])) // Write keychain entry
456 result = SetKeychainEntry( commFD);
463 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
464 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
465 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
466 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
467 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
469 // NOT static -- otherwise the compiler may optimize it out
470 // The "@(#) " pattern is a special prefix the "what" command looks for
471 const char VersionString_SCCS[] = "@(#) ddnswriteconfig " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
473 // If the process crashes, then this string will be magically included in the automatically-generated crash log
474 const char *__crashreporter_info__ = VersionString_SCCS + 5;
475 asm(".desc ___crashreporter_info__, 0x10");