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):
46 $Log: ddnswriteconfig.m,v $
47 Revision 1.3 2005/02/16 00:17:35 cheshire
48 Don't create empty arrays -- CFArrayGetValueAtIndex(array,0) returns an essentially random (non-null)
49 result for empty arrays, which can lead to code crashing if it's not sufficiently defensive.
51 Revision 1.2 2005/02/10 22:35:20 cheshire
52 <rdar://problem/3727944> Update name
54 Revision 1.1 2005/02/05 01:59:19 cheshire
55 Add Preference Pane to facilitate testing of DDNS & wide-area features
60 #import "PrivilegedOperations.h"
61 #import "ConfigurationRights.h"
72 #import <mach-o/dyld.h>
73 #import <AssertMacros.h>
74 #import <Security/Security.h>
75 #import <CoreServices/CoreServices.h>
76 #import <CoreFoundation/CoreFoundation.h>
77 #import <SystemConfiguration/SystemConfiguration.h>
78 #import <Foundation/Foundation.h>
81 static AuthorizationRef gAuthRef = 0;
84 CopySUIDTool(const char *srcPath, const char *dstPath)
85 // Copy a tool from srcPath to dstPath and set its 'x' and SUID bits. Return 0 on success.
87 int srcFD, dstFD, err = 0;
91 srcFD = open( srcPath, O_RDONLY, (mode_t) 0);
92 require_action( srcFD > 0, OpenSrcFailed, err=errno;);
94 len = lseek( srcFD, 0, SEEK_END);
95 require_action( len > 0, GetSrcLenFailed, err=errno;);
96 pSrc = mmap( NULL, len, PROT_READ, MAP_FILE, srcFD, 0);
97 require_action( pSrc != (void*)-1, MMapFailed, err=errno;);
99 dstFD = open( dstPath, O_RDWR | O_CREAT | O_TRUNC, (mode_t) 0);
100 require_action( dstFD > 0, OpenDstFailed, err=errno;);
102 written = write( dstFD, pSrc, len);
103 require_action( written == len, WriteFailed, err=errno;);
105 err = fchmod( dstFD, S_IRUSR | S_IXUSR | S_ISUID | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
120 InstallRootTool( const char *srcPath)
123 return -1; // failure; not running as root
125 (void) mkdir(kToolHome kToolDir, S_IRUSR | S_IXUSR | S_IWUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
127 return CopySUIDTool( srcPath, kToolPath);
132 WriteArrayToDynDNS(CFStringRef arrayKey, CFArrayRef domainArray)
134 SCPreferencesRef store;
135 OSStatus err = noErr;
136 CFDictionaryRef origDict;
137 CFMutableDictionaryRef dict = NULL;
139 CFStringRef scKey = CFSTR("/System/Network/DynamicDNS");
142 // Add domain to the array member ("arrayKey") of the DynamicDNS dictionary
143 // Will replace duplicate, at head of list
144 // At this point, we only support a single-item list
145 store = SCPreferencesCreate(NULL, CFSTR("com.apple.preference.bonjour"), NULL);
146 require_action(store != NULL, SysConfigErr, err=paramErr;);
147 require_action(true == SCPreferencesLock( store, true), LockFailed, err=coreFoundationUnknownErr;);
149 origDict = SCPreferencesPathGetValue(store, scKey);
151 dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
155 dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
157 require_action( dict != NULL, NoDict, err=memFullErr;);
159 if (CFArrayGetCount(domainArray) > 0) {
160 CFDictionarySetValue(dict, arrayKey, domainArray);
162 CFDictionaryRemoveValue(dict, arrayKey);
165 result = SCPreferencesPathSetValue(store, scKey, dict);
166 require_action(result, SCError, err=kernelPrivilegeErr;);
168 result = SCPreferencesCommitChanges(store);
169 require_action(result, SCError, err=kernelPrivilegeErr;);
170 result = SCPreferencesApplyChanges(store);
171 require_action(result, SCError, err=kernelPrivilegeErr;);
176 SCPreferencesUnlock(store);
185 readTaggedBlock(int fd, u_int32_t *pTag, u_int32_t *pLen, char **ppBuff)
186 // Read tag, block len and block data from stream and return. Dealloc *ppBuff via free().
192 num = read(fd, &tag, sizeof tag);
193 require_action(num == sizeof tag, GetTagFailed, result = -1;);
194 num = read(fd, &len, sizeof len);
195 require_action(num == sizeof len, GetLenFailed, result = -1;);
197 *ppBuff = (char*) malloc( len);
198 require_action(*ppBuff != NULL, AllocFailed, result = -1;);
200 num = read(fd, *ppBuff, len);
224 result = readTaggedBlock( fd, &tag, &len, &p);
225 require( result == 0, ReadParamsFailed);
228 (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDestroyRights);
232 result = AuthorizationCreateFromExternalForm((AuthorizationExternalForm*) p, &gAuthRef);
241 HandleWriteDomain(int fd, int domainType)
243 CFArrayRef domainArray;
244 CFDataRef domainData;
249 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
250 AuthorizationRights authSet = { 1, &scAuth };
252 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
255 result = readTaggedBlock(fd, &tag, &len, &p);
256 require(result == 0, ReadParamsFailed);
258 domainData = CFDataCreate(NULL, (UInt8 *)p, len);
259 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
262 result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
264 result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
273 HandleWriteHostname(int fd)
275 CFArrayRef domainArray;
276 CFDataRef domainData;
281 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
282 AuthorizationRights authSet = { 1, &scAuth };
284 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags) 0, NULL)))
287 result = readTaggedBlock(fd, &tag, &len, &p);
288 require(result == 0, ReadParamsFailed);
290 domainData = CFDataCreate(NULL, (const UInt8 *)p, len);
291 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
292 result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
300 MyMakeUidAccess(uid_t uid)
302 // make the "uid/gid" ACL subject
303 // this is a CSSM_LIST_ELEMENT chain
304 CSSM_ACL_PROCESS_SUBJECT_SELECTOR selector = {
305 CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION, // selector version
306 CSSM_ACL_MATCH_UID, // set mask: match uids (only)
308 0 // gid (not matched here)
310 CSSM_LIST_ELEMENT subject2 = { NULL, 0 };
311 subject2.Element.Word.Data = (UInt8 *)&selector;
312 subject2.Element.Word.Length = sizeof(selector);
313 CSSM_LIST_ELEMENT subject1 = { &subject2, CSSM_ACL_SUBJECT_TYPE_PROCESS, CSSM_LIST_ELEMENT_WORDID };
316 // rights granted (replace with individual list if desired)
317 CSSM_ACL_AUTHORIZATION_TAG rights[] = {
318 CSSM_ACL_AUTHORIZATION_ANY // everything
320 // owner component (right to change ACL)
321 CSSM_ACL_OWNER_PROTOTYPE owner = {
323 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
327 // ACL entries (any number, just one here)
328 CSSM_ACL_ENTRY_INFO acls[] = {
333 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
335 // rights for this entry
336 { sizeof(rights) / sizeof(rights[0]), rights },
342 SecAccessRef access = NULL;
343 (void) SecAccessCreateFromOwnerAndACL(&owner, sizeof(acls) / sizeof(acls[0]), acls, &access);
349 MyAddDynamicDNSPassword(SecKeychainRef keychain, SecAccessRef access, UInt32 serviceNameLength, const char *serviceName,
350 UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData)
352 char * description = DYNDNS_KEYCHAIN_DESCRIPTION;
353 UInt32 descriptionLength = strlen(DYNDNS_KEYCHAIN_DESCRIPTION);
354 UInt32 type = 'ddns';
355 UInt32 creator = 'ddns';
356 UInt32 typeLength = sizeof(type);
357 UInt32 creatorLength = sizeof(creator);
360 // set up attribute vector (each attribute consists of {tag, length, pointer})
361 SecKeychainAttribute attrs[] = { { kSecLabelItemAttr, serviceNameLength, (char *)serviceName },
362 { kSecAccountItemAttr, accountNameLength, (char *)accountName },
363 { kSecServiceItemAttr, serviceNameLength, (char *)serviceName },
364 { kSecDescriptionItemAttr, descriptionLength, (char *)description },
365 { kSecTypeItemAttr, typeLength, (UInt32 *)&type },
366 { kSecCreatorItemAttr, creatorLength, (UInt32 *)&creator } };
367 SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs };
369 err = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &attributes, passwordLength, passwordData, keychain, access, NULL);
375 SetKeychainEntry(int fd)
376 // Create a new entry in system keychain, or replace existing
378 CFDataRef secretData;
379 CFDictionaryRef secretDictionary;
380 CFStringRef keyNameString;
381 CFStringRef domainString;
382 CFStringRef secretString;
383 SecKeychainItemRef item = NULL;
391 AuthorizationItem kcAuth = { EDIT_SYS_KEYCHAIN_RIGHT, 0, NULL, 0 };
392 AuthorizationRights authSet = { 1, &kcAuth };
394 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
397 result = readTaggedBlock(fd, &tag, &len, &p);
398 require_noerr(result, ReadParamsFailed);
400 secretData = CFDataCreate(NULL, (UInt8 *)p, len);
401 secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
403 keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
404 assert(keyNameString != NULL);
406 domainString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_DOMAIN_KEY);
407 assert(domainString != NULL);
409 secretString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_SECRET_KEY);
410 assert(secretString != NULL);
412 CFStringGetCString(keyNameString, keyname, 1005, kCFStringEncodingUTF8);
413 CFStringGetCString(domainString, domain, 1005, kCFStringEncodingUTF8);
414 CFStringGetCString(secretString, secret, 1005, kCFStringEncodingUTF8);
416 result = SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
417 if (result == noErr) {
418 result = SecKeychainFindGenericPassword(NULL, strlen(domain), domain, 0, NULL, 0, NULL, &item);
419 if (result == noErr) {
420 result = SecKeychainItemDelete(item);
421 if (result != noErr) fprintf(stderr, "SecKeychainItemDelete returned %d\n", result);
424 result = MyAddDynamicDNSPassword(NULL, MyMakeUidAccess(0), strlen(domain), domain, strlen(keyname)+1, keyname, strlen(secret)+1, secret);
425 if (result != noErr) fprintf(stderr, "MyAddDynamicDNSPassword returned %d\n", result);
426 if (item) CFRelease(item);
434 int main( int argc, char **argv)
435 /* argv[0] is the exec path; argv[1] is a fd for input data; argv[2]... are operation codes.
436 The tool supports the following operations:
437 V -- exit with status PRIV_OP_TOOL_VERS
438 I -- install self as suid-root tool into system (must be run as root)
439 A -- read AuthInfo from input pipe
440 Wd -- write registration domain to dynamic store
441 Wb -- write browse domain to dynamic store
442 Wh -- write hostname to dynamic store
443 Wk -- write keychain entry for given account name
446 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
447 int commFD = -1, iArg, savedUID, result = 0;
449 if ( argc == 3 && 0 == strcmp( argv[2], "I")) {
450 return InstallRootTool( argv[0]);
453 savedUID = geteuid();
455 if ( 0 != seteuid( 0))
461 if ( argc == 3 && 0 == strcmp( argv[2], "V"))
462 return PRIV_OP_TOOL_VERS;
466 commFD = strtol( argv[1], NULL, 0);
467 lseek( commFD, 0, SEEK_SET);
469 for ( iArg = 2; iArg < argc && result == 0; iArg++)
471 if ( 0 == strcmp( "A", argv[ iArg])) // get auth info
473 result = SetAuthInfo( commFD);
475 else if ( 0 == strcmp( "Wd", argv[ iArg])) // Write registration domain
477 result = HandleWriteDomain( commFD, 1);
479 else if ( 0 == strcmp( "Wb", argv[ iArg])) // Write browse domain
481 result = HandleWriteDomain( commFD, 0);
483 else if ( 0 == strcmp( "Wh", argv[ iArg])) // Write hostname
485 result = HandleWriteHostname( commFD);
487 else if ( 0 == strcmp( "Wk", argv[ iArg])) // Write keychain entry
489 result = SetKeychainEntry( commFD);