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.
47 #import "PrivilegedOperations.h"
48 #import "ConfigurationRights.h"
59 #import <mach-o/dyld.h>
61 #import <AssertMacros.h>
62 #import <Security/Security.h>
63 #import <CoreServices/CoreServices.h>
64 #import <CoreFoundation/CoreFoundation.h>
65 #import <SystemConfiguration/SystemConfiguration.h>
66 #import <Foundation/Foundation.h>
69 static AuthorizationRef gAuthRef = 0;
72 WriteArrayToDynDNS(CFStringRef arrayKey, CFArrayRef domainArray)
74 SCPreferencesRef store;
76 CFDictionaryRef origDict;
77 CFMutableDictionaryRef dict = NULL;
79 CFStringRef scKey = CFSTR("/System/Network/DynamicDNS");
82 // Add domain to the array member ("arrayKey") of the DynamicDNS dictionary
83 // Will replace duplicate, at head of list
84 // At this point, we only support a single-item list
85 store = SCPreferencesCreate(NULL, CFSTR("com.apple.preference.bonjour"), NULL);
86 require_action(store != NULL, SysConfigErr, err=paramErr;);
87 require_action(true == SCPreferencesLock( store, true), LockFailed, err=coreFoundationUnknownErr;);
89 origDict = SCPreferencesPathGetValue(store, scKey);
91 dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
95 dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
97 require_action( dict != NULL, NoDict, err=memFullErr;);
99 if (CFArrayGetCount(domainArray) > 0) {
100 CFDictionarySetValue(dict, arrayKey, domainArray);
102 CFDictionaryRemoveValue(dict, arrayKey);
105 result = SCPreferencesPathSetValue(store, scKey, dict);
106 require_action(result, SCError, err=kernelPrivilegeErr;);
108 result = SCPreferencesCommitChanges(store);
109 require_action(result, SCError, err=kernelPrivilegeErr;);
110 result = SCPreferencesApplyChanges(store);
111 require_action(result, SCError, err=kernelPrivilegeErr;);
116 SCPreferencesUnlock(store);
125 readTaggedBlock(int fd, u_int32_t *pTag, u_int32_t *pLen, char **ppBuff)
126 // Read tag, block len and block data from stream and return. Dealloc *ppBuff via free().
129 u_int32_t tag, len; // Don't use ssize_t because that's different on 32- vs. 64-bit
132 num = read(fd, &tag, sizeof tag);
133 require_action(num == sizeof tag, GetTagFailed, result = -1;);
134 num = read(fd, &len, sizeof len);
135 require_action(num == sizeof len, GetLenFailed, result = -1;);
137 *ppBuff = (char*) malloc( len);
138 require_action(*ppBuff != NULL, AllocFailed, result = -1;);
140 num = read(fd, *ppBuff, len);
141 if (num == (ssize_t)len) {
164 result = readTaggedBlock( fd, &tag, &len, &p);
165 require( result == 0, ReadParamsFailed);
166 require( len == sizeof(AuthorizationExternalForm), ReadParamsFailed);
167 require( len == kAuthorizationExternalFormLength, ReadParamsFailed);
170 (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDefaults);
174 result = AuthorizationCreateFromExternalForm((AuthorizationExternalForm*) p, &gAuthRef);
183 HandleWriteDomain(int fd, int domainType)
185 CFArrayRef domainArray;
186 CFDataRef domainData;
191 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
192 AuthorizationRights authSet = { 1, &scAuth };
194 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
197 result = readTaggedBlock(fd, &tag, &len, &p);
198 require(result == 0, ReadParamsFailed);
200 domainData = CFDataCreate(NULL, (UInt8 *)p, len);
201 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
204 result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
206 result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
215 HandleWriteHostname(int fd)
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, (const UInt8 *)p, len);
233 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
234 result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
242 MyMakeUidAccess(uid_t uid)
244 // make the "uid/gid" ACL subject
245 // this is a CSSM_LIST_ELEMENT chain
246 CSSM_ACL_PROCESS_SUBJECT_SELECTOR selector = {
247 CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION, // selector version
248 CSSM_ACL_MATCH_UID, // set mask: match uids (only)
250 0 // gid (not matched here)
252 CSSM_LIST_ELEMENT subject2 = { NULL, 0, 0, {{0,0,0}} };
253 subject2.Element.Word.Data = (UInt8 *)&selector;
254 subject2.Element.Word.Length = sizeof(selector);
255 CSSM_LIST_ELEMENT subject1 = { &subject2, CSSM_ACL_SUBJECT_TYPE_PROCESS, CSSM_LIST_ELEMENT_WORDID, {{0,0,0}} };
258 // rights granted (replace with individual list if desired)
259 CSSM_ACL_AUTHORIZATION_TAG rights[] = {
260 CSSM_ACL_AUTHORIZATION_ANY // everything
262 // owner component (right to change ACL)
263 CSSM_ACL_OWNER_PROTOTYPE owner = {
265 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
269 // ACL entries (any number, just one here)
270 CSSM_ACL_ENTRY_INFO acls =
272 // CSSM_ACL_ENTRY_PROTOTYPE
274 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 }, // TypedSubject
276 { sizeof(rights) / sizeof(rights[0]), rights }, // Authorization rights for this entry
277 { { 0, 0 }, { 0, 0 } }, // CSSM_ACL_VALIDITY_PERIOD
278 "" // CSSM_STRING EntryTag
284 SecAccessRef a = NULL;
285 (void) SecAccessCreateFromOwnerAndACL(&owner, 1, &acls, &a);
291 MyAddDynamicDNSPassword(SecKeychainRef keychain, SecAccessRef a, UInt32 serviceNameLength, const char *serviceName,
292 UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData)
294 char * description = DYNDNS_KEYCHAIN_DESCRIPTION;
295 UInt32 descriptionLength = strlen(DYNDNS_KEYCHAIN_DESCRIPTION);
296 UInt32 type = 'ddns';
297 UInt32 creator = 'ddns';
298 UInt32 typeLength = sizeof(type);
299 UInt32 creatorLength = sizeof(creator);
302 // set up attribute vector (each attribute consists of {tag, length, pointer})
303 SecKeychainAttribute attrs[] = { { kSecLabelItemAttr, serviceNameLength, (char *)serviceName },
304 { kSecAccountItemAttr, accountNameLength, (char *)accountName },
305 { kSecServiceItemAttr, serviceNameLength, (char *)serviceName },
306 { kSecDescriptionItemAttr, descriptionLength, (char *)description },
307 { kSecTypeItemAttr, typeLength, (UInt32 *)&type },
308 { kSecCreatorItemAttr, creatorLength, (UInt32 *)&creator } };
309 SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs };
311 err = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &attributes, passwordLength, passwordData, keychain, a, NULL);
317 SetKeychainEntry(int fd)
318 // Create a new entry in system keychain, or replace existing
320 CFDataRef secretData;
321 CFDictionaryRef secretDictionary;
322 CFStringRef keyNameString;
323 CFStringRef domainString;
324 CFStringRef secretString;
325 SecKeychainItemRef item = NULL;
329 char keyname[kDNSServiceMaxDomainName];
330 char domain[kDNSServiceMaxDomainName];
331 char secret[kDNSServiceMaxDomainName];
333 AuthorizationItem kcAuth = { EDIT_SYS_KEYCHAIN_RIGHT, 0, NULL, 0 };
334 AuthorizationRights authSet = { 1, &kcAuth };
336 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
339 result = readTaggedBlock(fd, &tag, &len, &p);
340 require_noerr(result, ReadParamsFailed);
342 secretData = CFDataCreate(NULL, (UInt8 *)p, len);
343 secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
345 keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
346 assert(keyNameString != NULL);
348 domainString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_DOMAIN_KEY);
349 assert(domainString != NULL);
351 secretString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_SECRET_KEY);
352 assert(secretString != NULL);
354 CFStringGetCString(keyNameString, keyname, kDNSServiceMaxDomainName, kCFStringEncodingUTF8);
355 CFStringGetCString(domainString, domain, kDNSServiceMaxDomainName, kCFStringEncodingUTF8);
356 CFStringGetCString(secretString, secret, kDNSServiceMaxDomainName, kCFStringEncodingUTF8);
358 result = SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
359 if (result == noErr) {
360 result = SecKeychainFindGenericPassword(NULL, strlen(domain), domain, 0, NULL, 0, NULL, &item);
361 if (result == noErr) {
362 result = SecKeychainItemDelete(item);
363 if (result != noErr) fprintf(stderr, "SecKeychainItemDelete returned %d\n", result);
366 result = MyAddDynamicDNSPassword(NULL, MyMakeUidAccess(0), strlen(domain), domain, strlen(keyname)+1, keyname, strlen(secret)+1, secret);
367 if (result != noErr) fprintf(stderr, "MyAddDynamicDNSPassword returned %d\n", result);
368 if (item) CFRelease(item);
376 int main( int argc, char **argv)
377 /* argv[0] is the exec path; argv[1] is a fd for input data; argv[2]... are operation codes.
378 The tool supports the following operations:
379 V -- exit with status PRIV_OP_TOOL_VERS
380 A -- read AuthInfo from input pipe
381 Wd -- write registration domain to dynamic store
382 Wb -- write browse domain to dynamic store
383 Wh -- write hostname to dynamic store
384 Wk -- write keychain entry for given account name
387 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
388 int commFD = -1, iArg, result = 0;
390 if ( 0 != seteuid( 0))
393 if ( argc == 3 && 0 == strcmp( argv[2], "V"))
394 return PRIV_OP_TOOL_VERS;
398 commFD = strtol( argv[1], NULL, 0);
399 lseek( commFD, 0, SEEK_SET);
401 for ( iArg = 2; iArg < argc && result == 0; iArg++)
403 if ( 0 == strcmp( "A", argv[ iArg])) // get auth info
405 result = SetAuthInfo( commFD);
407 else if ( 0 == strcmp( "Wd", argv[ iArg])) // Write registration domain
409 result = HandleWriteDomain( commFD, 1);
411 else if ( 0 == strcmp( "Wb", argv[ iArg])) // Write browse domain
413 result = HandleWriteDomain( commFD, 0);
415 else if ( 0 == strcmp( "Wh", argv[ iArg])) // Write hostname
417 result = HandleWriteHostname( commFD);
419 else if ( 0 == strcmp( "Wk", argv[ iArg])) // Write keychain entry
421 result = SetKeychainEntry( commFD);
428 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
429 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
430 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
431 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
432 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
434 // NOT static -- otherwise the compiler may optimize it out
435 // The "@(#) " pattern is a special prefix the "what" command looks for
436 const char VersionString_SCCS[] = "@(#) ddnswriteconfig " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
438 #if _BUILDING_XCODE_PROJECT_
439 // If the process crashes, then this string will be magically included in the automatically-generated crash log
440 const char *__crashreporter_info__ = VersionString_SCCS + 5;
441 asm(".desc ___crashreporter_info__, 0x10");