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.5 2006/08/14 23:15:47 cheshire
49 Tidy up Change History comment
51 Revision 1.4 2005/06/04 04:47:47 cheshire
52 <rdar://problem/4138070> ddnswriteconfig (Bonjour PreferencePane) vulnerability
53 Remove self-installing capability of ddnswriteconfig
55 Revision 1.3 2005/02/16 00:17:35 cheshire
56 Don't create empty arrays -- CFArrayGetValueAtIndex(array,0) returns an essentially random (non-null)
57 result for empty arrays, which can lead to code crashing if it's not sufficiently defensive.
59 Revision 1.2 2005/02/10 22:35:20 cheshire
60 <rdar://problem/3727944> Update name
62 Revision 1.1 2005/02/05 01:59:19 cheshire
63 Add Preference Pane to facilitate testing of DDNS & wide-area features
68 #import "PrivilegedOperations.h"
69 #import "ConfigurationRights.h"
80 #import <mach-o/dyld.h>
81 #import <AssertMacros.h>
82 #import <Security/Security.h>
83 #import <CoreServices/CoreServices.h>
84 #import <CoreFoundation/CoreFoundation.h>
85 #import <SystemConfiguration/SystemConfiguration.h>
86 #import <Foundation/Foundation.h>
89 static AuthorizationRef gAuthRef = 0;
92 WriteArrayToDynDNS(CFStringRef arrayKey, CFArrayRef domainArray)
94 SCPreferencesRef store;
96 CFDictionaryRef origDict;
97 CFMutableDictionaryRef dict = NULL;
99 CFStringRef scKey = CFSTR("/System/Network/DynamicDNS");
102 // Add domain to the array member ("arrayKey") of the DynamicDNS dictionary
103 // Will replace duplicate, at head of list
104 // At this point, we only support a single-item list
105 store = SCPreferencesCreate(NULL, CFSTR("com.apple.preference.bonjour"), NULL);
106 require_action(store != NULL, SysConfigErr, err=paramErr;);
107 require_action(true == SCPreferencesLock( store, true), LockFailed, err=coreFoundationUnknownErr;);
109 origDict = SCPreferencesPathGetValue(store, scKey);
111 dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
115 dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
117 require_action( dict != NULL, NoDict, err=memFullErr;);
119 if (CFArrayGetCount(domainArray) > 0) {
120 CFDictionarySetValue(dict, arrayKey, domainArray);
122 CFDictionaryRemoveValue(dict, arrayKey);
125 result = SCPreferencesPathSetValue(store, scKey, dict);
126 require_action(result, SCError, err=kernelPrivilegeErr;);
128 result = SCPreferencesCommitChanges(store);
129 require_action(result, SCError, err=kernelPrivilegeErr;);
130 result = SCPreferencesApplyChanges(store);
131 require_action(result, SCError, err=kernelPrivilegeErr;);
136 SCPreferencesUnlock(store);
145 readTaggedBlock(int fd, u_int32_t *pTag, u_int32_t *pLen, char **ppBuff)
146 // Read tag, block len and block data from stream and return. Dealloc *ppBuff via free().
152 num = read(fd, &tag, sizeof tag);
153 require_action(num == sizeof tag, GetTagFailed, result = -1;);
154 num = read(fd, &len, sizeof len);
155 require_action(num == sizeof len, GetLenFailed, result = -1;);
157 *ppBuff = (char*) malloc( len);
158 require_action(*ppBuff != NULL, AllocFailed, result = -1;);
160 num = read(fd, *ppBuff, len);
184 result = readTaggedBlock( fd, &tag, &len, &p);
185 require( result == 0, ReadParamsFailed);
188 (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDestroyRights);
192 result = AuthorizationCreateFromExternalForm((AuthorizationExternalForm*) p, &gAuthRef);
201 HandleWriteDomain(int fd, int domainType)
203 CFArrayRef domainArray;
204 CFDataRef domainData;
209 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
210 AuthorizationRights authSet = { 1, &scAuth };
212 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
215 result = readTaggedBlock(fd, &tag, &len, &p);
216 require(result == 0, ReadParamsFailed);
218 domainData = CFDataCreate(NULL, (UInt8 *)p, len);
219 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
222 result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
224 result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
233 HandleWriteHostname(int fd)
235 CFArrayRef domainArray;
236 CFDataRef domainData;
241 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
242 AuthorizationRights authSet = { 1, &scAuth };
244 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags) 0, NULL)))
247 result = readTaggedBlock(fd, &tag, &len, &p);
248 require(result == 0, ReadParamsFailed);
250 domainData = CFDataCreate(NULL, (const UInt8 *)p, len);
251 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
252 result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
260 MyMakeUidAccess(uid_t uid)
262 // make the "uid/gid" ACL subject
263 // this is a CSSM_LIST_ELEMENT chain
264 CSSM_ACL_PROCESS_SUBJECT_SELECTOR selector = {
265 CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION, // selector version
266 CSSM_ACL_MATCH_UID, // set mask: match uids (only)
268 0 // gid (not matched here)
270 CSSM_LIST_ELEMENT subject2 = { NULL, 0 };
271 subject2.Element.Word.Data = (UInt8 *)&selector;
272 subject2.Element.Word.Length = sizeof(selector);
273 CSSM_LIST_ELEMENT subject1 = { &subject2, CSSM_ACL_SUBJECT_TYPE_PROCESS, CSSM_LIST_ELEMENT_WORDID };
276 // rights granted (replace with individual list if desired)
277 CSSM_ACL_AUTHORIZATION_TAG rights[] = {
278 CSSM_ACL_AUTHORIZATION_ANY // everything
280 // owner component (right to change ACL)
281 CSSM_ACL_OWNER_PROTOTYPE owner = {
283 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
287 // ACL entries (any number, just one here)
288 CSSM_ACL_ENTRY_INFO acls[] = {
293 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
295 // rights for this entry
296 { sizeof(rights) / sizeof(rights[0]), rights },
302 SecAccessRef access = NULL;
303 (void) SecAccessCreateFromOwnerAndACL(&owner, sizeof(acls) / sizeof(acls[0]), acls, &access);
309 MyAddDynamicDNSPassword(SecKeychainRef keychain, SecAccessRef access, UInt32 serviceNameLength, const char *serviceName,
310 UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData)
312 char * description = DYNDNS_KEYCHAIN_DESCRIPTION;
313 UInt32 descriptionLength = strlen(DYNDNS_KEYCHAIN_DESCRIPTION);
314 UInt32 type = 'ddns';
315 UInt32 creator = 'ddns';
316 UInt32 typeLength = sizeof(type);
317 UInt32 creatorLength = sizeof(creator);
320 // set up attribute vector (each attribute consists of {tag, length, pointer})
321 SecKeychainAttribute attrs[] = { { kSecLabelItemAttr, serviceNameLength, (char *)serviceName },
322 { kSecAccountItemAttr, accountNameLength, (char *)accountName },
323 { kSecServiceItemAttr, serviceNameLength, (char *)serviceName },
324 { kSecDescriptionItemAttr, descriptionLength, (char *)description },
325 { kSecTypeItemAttr, typeLength, (UInt32 *)&type },
326 { kSecCreatorItemAttr, creatorLength, (UInt32 *)&creator } };
327 SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs };
329 err = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &attributes, passwordLength, passwordData, keychain, access, NULL);
335 SetKeychainEntry(int fd)
336 // Create a new entry in system keychain, or replace existing
338 CFDataRef secretData;
339 CFDictionaryRef secretDictionary;
340 CFStringRef keyNameString;
341 CFStringRef domainString;
342 CFStringRef secretString;
343 SecKeychainItemRef item = NULL;
351 AuthorizationItem kcAuth = { EDIT_SYS_KEYCHAIN_RIGHT, 0, NULL, 0 };
352 AuthorizationRights authSet = { 1, &kcAuth };
354 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
357 result = readTaggedBlock(fd, &tag, &len, &p);
358 require_noerr(result, ReadParamsFailed);
360 secretData = CFDataCreate(NULL, (UInt8 *)p, len);
361 secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
363 keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
364 assert(keyNameString != NULL);
366 domainString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_DOMAIN_KEY);
367 assert(domainString != NULL);
369 secretString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_SECRET_KEY);
370 assert(secretString != NULL);
372 CFStringGetCString(keyNameString, keyname, 1005, kCFStringEncodingUTF8);
373 CFStringGetCString(domainString, domain, 1005, kCFStringEncodingUTF8);
374 CFStringGetCString(secretString, secret, 1005, kCFStringEncodingUTF8);
376 result = SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
377 if (result == noErr) {
378 result = SecKeychainFindGenericPassword(NULL, strlen(domain), domain, 0, NULL, 0, NULL, &item);
379 if (result == noErr) {
380 result = SecKeychainItemDelete(item);
381 if (result != noErr) fprintf(stderr, "SecKeychainItemDelete returned %d\n", result);
384 result = MyAddDynamicDNSPassword(NULL, MyMakeUidAccess(0), strlen(domain), domain, strlen(keyname)+1, keyname, strlen(secret)+1, secret);
385 if (result != noErr) fprintf(stderr, "MyAddDynamicDNSPassword returned %d\n", result);
386 if (item) CFRelease(item);
394 int main( int argc, char **argv)
395 /* argv[0] is the exec path; argv[1] is a fd for input data; argv[2]... are operation codes.
396 The tool supports the following operations:
397 V -- exit with status PRIV_OP_TOOL_VERS
398 A -- read AuthInfo from input pipe
399 Wd -- write registration domain to dynamic store
400 Wb -- write browse domain to dynamic store
401 Wh -- write hostname to dynamic store
402 Wk -- write keychain entry for given account name
405 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
406 int commFD = -1, iArg, result = 0;
408 if ( 0 != seteuid( 0))
411 if ( argc == 3 && 0 == strcmp( argv[2], "V"))
412 return PRIV_OP_TOOL_VERS;
416 commFD = strtol( argv[1], NULL, 0);
417 lseek( commFD, 0, SEEK_SET);
419 for ( iArg = 2; iArg < argc && result == 0; iArg++)
421 if ( 0 == strcmp( "A", argv[ iArg])) // get auth info
423 result = SetAuthInfo( commFD);
425 else if ( 0 == strcmp( "Wd", argv[ iArg])) // Write registration domain
427 result = HandleWriteDomain( commFD, 1);
429 else if ( 0 == strcmp( "Wb", argv[ iArg])) // Write browse domain
431 result = HandleWriteDomain( commFD, 0);
433 else if ( 0 == strcmp( "Wh", argv[ iArg])) // Write hostname
435 result = HandleWriteHostname( commFD);
437 else if ( 0 == strcmp( "Wk", argv[ iArg])) // Write keychain entry
439 result = SetKeychainEntry( commFD);