]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/PreferencePane/ddnswriteconfig.m
mDNSResponder-107.tar.gz
[apple/mdnsresponder.git] / mDNSMacOSX / PreferencePane / ddnswriteconfig.m
1 /*
2 File: ddnswriteconfig.m
3
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.
7
8 Copyright: (c) Copyright 2005 Apple Computer, Inc. All rights reserved.
9
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.
15
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.
30
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.
36
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.
44
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.
50
51 Revision 1.2 2005/02/10 22:35:20 cheshire
52 <rdar://problem/3727944> Update name
53
54 Revision 1.1 2005/02/05 01:59:19 cheshire
55 Add Preference Pane to facilitate testing of DDNS & wide-area features
56
57 */
58
59
60 #import "PrivilegedOperations.h"
61 #import "ConfigurationRights.h"
62
63 #import <stdio.h>
64 #import <stdint.h>
65 #import <stdlib.h>
66 #import <unistd.h>
67 #import <fcntl.h>
68 #import <errno.h>
69 #import <sys/types.h>
70 #import <sys/stat.h>
71 #import <sys/mman.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>
79
80
81 static AuthorizationRef gAuthRef = 0;
82
83 int
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.
86 {
87 int srcFD, dstFD, err = 0;
88 off_t len, written;
89 void *pSrc;
90
91 srcFD = open( srcPath, O_RDONLY, (mode_t) 0);
92 require_action( srcFD > 0, OpenSrcFailed, err=errno;);
93
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;);
98
99 dstFD = open( dstPath, O_RDWR | O_CREAT | O_TRUNC, (mode_t) 0);
100 require_action( dstFD > 0, OpenDstFailed, err=errno;);
101
102 written = write( dstFD, pSrc, len);
103 require_action( written == len, WriteFailed, err=errno;);
104
105 err = fchmod( dstFD, S_IRUSR | S_IXUSR | S_ISUID | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
106
107 WriteFailed:
108 close( dstFD);
109 OpenDstFailed:
110 munmap( pSrc, len);
111 MMapFailed:
112 GetSrcLenFailed:
113 close( srcFD);
114 OpenSrcFailed:
115 return err;
116 }
117
118
119 int
120 InstallRootTool( const char *srcPath)
121 {
122 if (geteuid() != 0)
123 return -1; // failure; not running as root
124
125 (void) mkdir(kToolHome kToolDir, S_IRUSR | S_IXUSR | S_IWUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
126
127 return CopySUIDTool( srcPath, kToolPath);
128 }
129
130
131 OSStatus
132 WriteArrayToDynDNS(CFStringRef arrayKey, CFArrayRef domainArray)
133 {
134 SCPreferencesRef store;
135 OSStatus err = noErr;
136 CFDictionaryRef origDict;
137 CFMutableDictionaryRef dict = NULL;
138 Boolean result;
139 CFStringRef scKey = CFSTR("/System/Network/DynamicDNS");
140
141
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;);
148
149 origDict = SCPreferencesPathGetValue(store, scKey);
150 if (origDict) {
151 dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
152 }
153
154 if (!dict) {
155 dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
156 }
157 require_action( dict != NULL, NoDict, err=memFullErr;);
158
159 if (CFArrayGetCount(domainArray) > 0) {
160 CFDictionarySetValue(dict, arrayKey, domainArray);
161 } else {
162 CFDictionaryRemoveValue(dict, arrayKey);
163 }
164
165 result = SCPreferencesPathSetValue(store, scKey, dict);
166 require_action(result, SCError, err=kernelPrivilegeErr;);
167
168 result = SCPreferencesCommitChanges(store);
169 require_action(result, SCError, err=kernelPrivilegeErr;);
170 result = SCPreferencesApplyChanges(store);
171 require_action(result, SCError, err=kernelPrivilegeErr;);
172
173 SCError:
174 CFRelease(dict);
175 NoDict:
176 SCPreferencesUnlock(store);
177 LockFailed:
178 CFRelease(store);
179 SysConfigErr:
180 return err;
181 }
182
183
184 static int
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().
187 {
188 ssize_t num;
189 u_int32_t tag, len;
190 int result = 0;
191
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;);
196
197 *ppBuff = (char*) malloc( len);
198 require_action(*ppBuff != NULL, AllocFailed, result = -1;);
199
200 num = read(fd, *ppBuff, len);
201 if (num == len) {
202 *pTag = tag;
203 *pLen = len;
204 } else {
205 free(*ppBuff);
206 result = -1;
207 }
208
209 AllocFailed:
210 GetLenFailed:
211 GetTagFailed:
212 return result;
213 }
214
215
216
217 int
218 SetAuthInfo( int fd)
219 {
220 int result = 0;
221 u_int32_t tag, len;
222 char *p;
223
224 result = readTaggedBlock( fd, &tag, &len, &p);
225 require( result == 0, ReadParamsFailed);
226
227 if (gAuthRef != 0) {
228 (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDestroyRights);
229 gAuthRef = 0;
230 }
231
232 result = AuthorizationCreateFromExternalForm((AuthorizationExternalForm*) p, &gAuthRef);
233
234 free( p);
235 ReadParamsFailed:
236 return result;
237 }
238
239
240 int
241 HandleWriteDomain(int fd, int domainType)
242 {
243 CFArrayRef domainArray;
244 CFDataRef domainData;
245 int result = 0;
246 u_int32_t tag, len;
247 char *p;
248
249 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
250 AuthorizationRights authSet = { 1, &scAuth };
251
252 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
253 return result;
254
255 result = readTaggedBlock(fd, &tag, &len, &p);
256 require(result == 0, ReadParamsFailed);
257
258 domainData = CFDataCreate(NULL, (UInt8 *)p, len);
259 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
260
261 if (domainType) {
262 result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
263 } else {
264 result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
265 }
266
267 ReadParamsFailed:
268 return result;
269 }
270
271
272 int
273 HandleWriteHostname(int fd)
274 {
275 CFArrayRef domainArray;
276 CFDataRef domainData;
277 int result = 0;
278 u_int32_t tag, len;
279 char *p;
280
281 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
282 AuthorizationRights authSet = { 1, &scAuth };
283
284 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags) 0, NULL)))
285 return result;
286
287 result = readTaggedBlock(fd, &tag, &len, &p);
288 require(result == 0, ReadParamsFailed);
289
290 domainData = CFDataCreate(NULL, (const UInt8 *)p, len);
291 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
292 result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
293
294 ReadParamsFailed:
295 return result;
296 }
297
298
299 SecAccessRef
300 MyMakeUidAccess(uid_t uid)
301 {
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)
307 uid, // uid to match
308 0 // gid (not matched here)
309 };
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 };
314
315
316 // rights granted (replace with individual list if desired)
317 CSSM_ACL_AUTHORIZATION_TAG rights[] = {
318 CSSM_ACL_AUTHORIZATION_ANY // everything
319 };
320 // owner component (right to change ACL)
321 CSSM_ACL_OWNER_PROTOTYPE owner = {
322 // TypedSubject
323 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
324 // Delegate
325 false
326 };
327 // ACL entries (any number, just one here)
328 CSSM_ACL_ENTRY_INFO acls[] = {
329 {
330 // prototype
331 {
332 // TypedSubject
333 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
334 false, // Delegate
335 // rights for this entry
336 { sizeof(rights) / sizeof(rights[0]), rights },
337 // rest is defaulted
338 }
339 }
340 };
341
342 SecAccessRef access = NULL;
343 (void) SecAccessCreateFromOwnerAndACL(&owner, sizeof(acls) / sizeof(acls[0]), acls, &access);
344 return access;
345 }
346
347
348 OSStatus
349 MyAddDynamicDNSPassword(SecKeychainRef keychain, SecAccessRef access, UInt32 serviceNameLength, const char *serviceName,
350 UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData)
351 {
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);
358 OSStatus err;
359
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 };
368
369 err = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &attributes, passwordLength, passwordData, keychain, access, NULL);
370 return err;
371 }
372
373
374 int
375 SetKeychainEntry(int fd)
376 // Create a new entry in system keychain, or replace existing
377 {
378 CFDataRef secretData;
379 CFDictionaryRef secretDictionary;
380 CFStringRef keyNameString;
381 CFStringRef domainString;
382 CFStringRef secretString;
383 SecKeychainItemRef item = NULL;
384 int result = 0;
385 u_int32_t tag, len;
386 char *p;
387 char keyname[1005];
388 char domain[1005];
389 char secret[1005];
390
391 AuthorizationItem kcAuth = { EDIT_SYS_KEYCHAIN_RIGHT, 0, NULL, 0 };
392 AuthorizationRights authSet = { 1, &kcAuth };
393
394 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
395 return result;
396
397 result = readTaggedBlock(fd, &tag, &len, &p);
398 require_noerr(result, ReadParamsFailed);
399
400 secretData = CFDataCreate(NULL, (UInt8 *)p, len);
401 secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
402
403 keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
404 assert(keyNameString != NULL);
405
406 domainString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_DOMAIN_KEY);
407 assert(domainString != NULL);
408
409 secretString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_SECRET_KEY);
410 assert(secretString != NULL);
411
412 CFStringGetCString(keyNameString, keyname, 1005, kCFStringEncodingUTF8);
413 CFStringGetCString(domainString, domain, 1005, kCFStringEncodingUTF8);
414 CFStringGetCString(secretString, secret, 1005, kCFStringEncodingUTF8);
415
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);
422 }
423
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);
427 }
428
429 ReadParamsFailed:
430 return result;
431 }
432
433
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
444 */
445 {
446 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
447 int commFD = -1, iArg, savedUID, result = 0;
448
449 if ( argc == 3 && 0 == strcmp( argv[2], "I")) {
450 return InstallRootTool( argv[0]);
451 }
452
453 savedUID = geteuid();
454 #if 1
455 if ( 0 != seteuid( 0))
456 return -1;
457 #else
458 sleep( 10);
459 #endif
460
461 if ( argc == 3 && 0 == strcmp( argv[2], "V"))
462 return PRIV_OP_TOOL_VERS;
463
464 if ( argc >= 1)
465 {
466 commFD = strtol( argv[1], NULL, 0);
467 lseek( commFD, 0, SEEK_SET);
468 }
469 for ( iArg = 2; iArg < argc && result == 0; iArg++)
470 {
471 if ( 0 == strcmp( "A", argv[ iArg])) // get auth info
472 {
473 result = SetAuthInfo( commFD);
474 }
475 else if ( 0 == strcmp( "Wd", argv[ iArg])) // Write registration domain
476 {
477 result = HandleWriteDomain( commFD, 1);
478 }
479 else if ( 0 == strcmp( "Wb", argv[ iArg])) // Write browse domain
480 {
481 result = HandleWriteDomain( commFD, 0);
482 }
483 else if ( 0 == strcmp( "Wh", argv[ iArg])) // Write hostname
484 {
485 result = HandleWriteHostname( commFD);
486 }
487 else if ( 0 == strcmp( "Wk", argv[ iArg])) // Write keychain entry
488 {
489 result = SetKeychainEntry( commFD);
490 }
491 }
492 [pool release];
493 return result;
494 }