]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/PreferencePane/ddnswriteconfig.m
mDNSResponder-161.1.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
47 $Log: ddnswriteconfig.m,v $
48 Revision 1.9 2007/09/18 19:09:02 cheshire
49 <rdar://problem/5489549> mDNSResponderHelper (and other binaries) missing SCCS version strings
50
51 Revision 1.8 2007/07/20 23:41:03 mkrochma
52 <rdar://problem/5348663> null deref in ddnswriteconfig
53
54 Revision 1.7 2007/03/07 00:49:00 cheshire
55 <rdar://problem/4618207> Security: ddnswriteconfig does not verify that authorization blob is of correct size
56
57 Revision 1.6 2007/02/09 00:39:06 cheshire
58 Fix compile warnings
59
60 Revision 1.5 2006/08/14 23:15:47 cheshire
61 Tidy up Change History comment
62
63 Revision 1.4 2005/06/04 04:47:47 cheshire
64 <rdar://problem/4138070> ddnswriteconfig (Bonjour PreferencePane) vulnerability
65 Remove self-installing capability of ddnswriteconfig
66
67 Revision 1.3 2005/02/16 00:17:35 cheshire
68 Don't create empty arrays -- CFArrayGetValueAtIndex(array,0) returns an essentially random (non-null)
69 result for empty arrays, which can lead to code crashing if it's not sufficiently defensive.
70
71 Revision 1.2 2005/02/10 22:35:20 cheshire
72 <rdar://problem/3727944> Update name
73
74 Revision 1.1 2005/02/05 01:59:19 cheshire
75 Add Preference Pane to facilitate testing of DDNS & wide-area features
76
77 */
78
79
80 #import "PrivilegedOperations.h"
81 #import "ConfigurationRights.h"
82
83 #import <stdio.h>
84 #import <stdint.h>
85 #import <stdlib.h>
86 #import <unistd.h>
87 #import <fcntl.h>
88 #import <errno.h>
89 #import <sys/types.h>
90 #import <sys/stat.h>
91 #import <sys/mman.h>
92 #import <mach-o/dyld.h>
93 #import <AssertMacros.h>
94 #import <Security/Security.h>
95 #import <CoreServices/CoreServices.h>
96 #import <CoreFoundation/CoreFoundation.h>
97 #import <SystemConfiguration/SystemConfiguration.h>
98 #import <Foundation/Foundation.h>
99
100
101 static AuthorizationRef gAuthRef = 0;
102
103 static OSStatus
104 WriteArrayToDynDNS(CFStringRef arrayKey, CFArrayRef domainArray)
105 {
106 SCPreferencesRef store;
107 OSStatus err = noErr;
108 CFDictionaryRef origDict;
109 CFMutableDictionaryRef dict = NULL;
110 Boolean result;
111 CFStringRef scKey = CFSTR("/System/Network/DynamicDNS");
112
113
114 // Add domain to the array member ("arrayKey") of the DynamicDNS dictionary
115 // Will replace duplicate, at head of list
116 // At this point, we only support a single-item list
117 store = SCPreferencesCreate(NULL, CFSTR("com.apple.preference.bonjour"), NULL);
118 require_action(store != NULL, SysConfigErr, err=paramErr;);
119 require_action(true == SCPreferencesLock( store, true), LockFailed, err=coreFoundationUnknownErr;);
120
121 origDict = SCPreferencesPathGetValue(store, scKey);
122 if (origDict) {
123 dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
124 }
125
126 if (!dict) {
127 dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
128 }
129 require_action( dict != NULL, NoDict, err=memFullErr;);
130
131 if (CFArrayGetCount(domainArray) > 0) {
132 CFDictionarySetValue(dict, arrayKey, domainArray);
133 } else {
134 CFDictionaryRemoveValue(dict, arrayKey);
135 }
136
137 result = SCPreferencesPathSetValue(store, scKey, dict);
138 require_action(result, SCError, err=kernelPrivilegeErr;);
139
140 result = SCPreferencesCommitChanges(store);
141 require_action(result, SCError, err=kernelPrivilegeErr;);
142 result = SCPreferencesApplyChanges(store);
143 require_action(result, SCError, err=kernelPrivilegeErr;);
144
145 SCError:
146 CFRelease(dict);
147 NoDict:
148 SCPreferencesUnlock(store);
149 LockFailed:
150 CFRelease(store);
151 SysConfigErr:
152 return err;
153 }
154
155
156 static int
157 readTaggedBlock(int fd, u_int32_t *pTag, u_int32_t *pLen, char **ppBuff)
158 // Read tag, block len and block data from stream and return. Dealloc *ppBuff via free().
159 {
160 ssize_t num, len;
161 u_int32_t tag;
162 int result = 0;
163
164 num = read(fd, &tag, sizeof tag);
165 require_action(num == sizeof tag, GetTagFailed, result = -1;);
166 num = read(fd, &len, sizeof len);
167 require_action(num == sizeof len, GetLenFailed, result = -1;);
168
169 *ppBuff = (char*) malloc( len);
170 require_action(*ppBuff != NULL, AllocFailed, result = -1;);
171
172 num = read(fd, *ppBuff, len);
173 if (num == len) {
174 *pTag = tag;
175 *pLen = len;
176 } else {
177 free(*ppBuff);
178 result = -1;
179 }
180
181 AllocFailed:
182 GetLenFailed:
183 GetTagFailed:
184 return result;
185 }
186
187
188
189 static int
190 SetAuthInfo( int fd)
191 {
192 int result = 0;
193 u_int32_t tag, len;
194 char *p;
195
196 result = readTaggedBlock( fd, &tag, &len, &p);
197 require( result == 0, ReadParamsFailed);
198 require( len == sizeof(AuthorizationExternalForm), ReadParamsFailed);
199 require( len == kAuthorizationExternalFormLength, ReadParamsFailed);
200
201 if (gAuthRef != 0) {
202 (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDestroyRights);
203 gAuthRef = 0;
204 }
205
206 result = AuthorizationCreateFromExternalForm((AuthorizationExternalForm*) p, &gAuthRef);
207
208 free( p);
209 ReadParamsFailed:
210 return result;
211 }
212
213
214 static int
215 HandleWriteDomain(int fd, int domainType)
216 {
217 CFArrayRef domainArray;
218 CFDataRef domainData;
219 int result = 0;
220 u_int32_t tag, len;
221 char *p;
222
223 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
224 AuthorizationRights authSet = { 1, &scAuth };
225
226 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
227 return result;
228
229 result = readTaggedBlock(fd, &tag, &len, &p);
230 require(result == 0, ReadParamsFailed);
231
232 domainData = CFDataCreate(NULL, (UInt8 *)p, len);
233 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
234
235 if (domainType) {
236 result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
237 } else {
238 result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
239 }
240
241 ReadParamsFailed:
242 return result;
243 }
244
245
246 static int
247 HandleWriteHostname(int fd)
248 {
249 CFArrayRef domainArray;
250 CFDataRef domainData;
251 int result = 0;
252 u_int32_t tag, len;
253 char *p;
254
255 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
256 AuthorizationRights authSet = { 1, &scAuth };
257
258 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags) 0, NULL)))
259 return result;
260
261 result = readTaggedBlock(fd, &tag, &len, &p);
262 require(result == 0, ReadParamsFailed);
263
264 domainData = CFDataCreate(NULL, (const UInt8 *)p, len);
265 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
266 result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
267
268 ReadParamsFailed:
269 return result;
270 }
271
272
273 static SecAccessRef
274 MyMakeUidAccess(uid_t uid)
275 {
276 // make the "uid/gid" ACL subject
277 // this is a CSSM_LIST_ELEMENT chain
278 CSSM_ACL_PROCESS_SUBJECT_SELECTOR selector = {
279 CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION, // selector version
280 CSSM_ACL_MATCH_UID, // set mask: match uids (only)
281 uid, // uid to match
282 0 // gid (not matched here)
283 };
284 CSSM_LIST_ELEMENT subject2 = { NULL, 0, 0, {{0,0,0}} };
285 subject2.Element.Word.Data = (UInt8 *)&selector;
286 subject2.Element.Word.Length = sizeof(selector);
287 CSSM_LIST_ELEMENT subject1 = { &subject2, CSSM_ACL_SUBJECT_TYPE_PROCESS, CSSM_LIST_ELEMENT_WORDID, {{0,0,0}} };
288
289
290 // rights granted (replace with individual list if desired)
291 CSSM_ACL_AUTHORIZATION_TAG rights[] = {
292 CSSM_ACL_AUTHORIZATION_ANY // everything
293 };
294 // owner component (right to change ACL)
295 CSSM_ACL_OWNER_PROTOTYPE owner = {
296 // TypedSubject
297 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
298 // Delegate
299 false
300 };
301 // ACL entries (any number, just one here)
302 CSSM_ACL_ENTRY_INFO acls =
303 {
304 // CSSM_ACL_ENTRY_PROTOTYPE
305 {
306 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 }, // TypedSubject
307 false, // Delegate
308 { sizeof(rights) / sizeof(rights[0]), rights }, // Authorization rights for this entry
309 { { 0, 0 }, { 0, 0 } }, // CSSM_ACL_VALIDITY_PERIOD
310 "" // CSSM_STRING EntryTag
311 },
312 // CSSM_ACL_HANDLE
313 0
314 };
315
316 SecAccessRef access = NULL;
317 (void) SecAccessCreateFromOwnerAndACL(&owner, 1, &acls, &access);
318 return access;
319 }
320
321
322 static OSStatus
323 MyAddDynamicDNSPassword(SecKeychainRef keychain, SecAccessRef access, UInt32 serviceNameLength, const char *serviceName,
324 UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData)
325 {
326 char * description = DYNDNS_KEYCHAIN_DESCRIPTION;
327 UInt32 descriptionLength = strlen(DYNDNS_KEYCHAIN_DESCRIPTION);
328 UInt32 type = 'ddns';
329 UInt32 creator = 'ddns';
330 UInt32 typeLength = sizeof(type);
331 UInt32 creatorLength = sizeof(creator);
332 OSStatus err;
333
334 // set up attribute vector (each attribute consists of {tag, length, pointer})
335 SecKeychainAttribute attrs[] = { { kSecLabelItemAttr, serviceNameLength, (char *)serviceName },
336 { kSecAccountItemAttr, accountNameLength, (char *)accountName },
337 { kSecServiceItemAttr, serviceNameLength, (char *)serviceName },
338 { kSecDescriptionItemAttr, descriptionLength, (char *)description },
339 { kSecTypeItemAttr, typeLength, (UInt32 *)&type },
340 { kSecCreatorItemAttr, creatorLength, (UInt32 *)&creator } };
341 SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs };
342
343 err = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &attributes, passwordLength, passwordData, keychain, access, NULL);
344 return err;
345 }
346
347
348 static int
349 SetKeychainEntry(int fd)
350 // Create a new entry in system keychain, or replace existing
351 {
352 CFDataRef secretData;
353 CFDictionaryRef secretDictionary;
354 CFStringRef keyNameString;
355 CFStringRef domainString;
356 CFStringRef secretString;
357 SecKeychainItemRef item = NULL;
358 int result = 0;
359 u_int32_t tag, len;
360 char *p;
361 char keyname[1005];
362 char domain[1005];
363 char secret[1005];
364
365 AuthorizationItem kcAuth = { EDIT_SYS_KEYCHAIN_RIGHT, 0, NULL, 0 };
366 AuthorizationRights authSet = { 1, &kcAuth };
367
368 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
369 return result;
370
371 result = readTaggedBlock(fd, &tag, &len, &p);
372 require_noerr(result, ReadParamsFailed);
373
374 secretData = CFDataCreate(NULL, (UInt8 *)p, len);
375 secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
376
377 keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
378 assert(keyNameString != NULL);
379
380 domainString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_DOMAIN_KEY);
381 assert(domainString != NULL);
382
383 secretString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_SECRET_KEY);
384 assert(secretString != NULL);
385
386 CFStringGetCString(keyNameString, keyname, 1005, kCFStringEncodingUTF8);
387 CFStringGetCString(domainString, domain, 1005, kCFStringEncodingUTF8);
388 CFStringGetCString(secretString, secret, 1005, kCFStringEncodingUTF8);
389
390 result = SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
391 if (result == noErr) {
392 result = SecKeychainFindGenericPassword(NULL, strlen(domain), domain, 0, NULL, 0, NULL, &item);
393 if (result == noErr) {
394 result = SecKeychainItemDelete(item);
395 if (result != noErr) fprintf(stderr, "SecKeychainItemDelete returned %d\n", result);
396 }
397
398 result = MyAddDynamicDNSPassword(NULL, MyMakeUidAccess(0), strlen(domain), domain, strlen(keyname)+1, keyname, strlen(secret)+1, secret);
399 if (result != noErr) fprintf(stderr, "MyAddDynamicDNSPassword returned %d\n", result);
400 if (item) CFRelease(item);
401 }
402
403 ReadParamsFailed:
404 return result;
405 }
406
407
408 int main( int argc, char **argv)
409 /* argv[0] is the exec path; argv[1] is a fd for input data; argv[2]... are operation codes.
410 The tool supports the following operations:
411 V -- exit with status PRIV_OP_TOOL_VERS
412 A -- read AuthInfo from input pipe
413 Wd -- write registration domain to dynamic store
414 Wb -- write browse domain to dynamic store
415 Wh -- write hostname to dynamic store
416 Wk -- write keychain entry for given account name
417 */
418 {
419 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
420 int commFD = -1, iArg, result = 0;
421
422 if ( 0 != seteuid( 0))
423 return -1;
424
425 if ( argc == 3 && 0 == strcmp( argv[2], "V"))
426 return PRIV_OP_TOOL_VERS;
427
428 if ( argc > 1)
429 {
430 commFD = strtol( argv[1], NULL, 0);
431 lseek( commFD, 0, SEEK_SET);
432 }
433 for ( iArg = 2; iArg < argc && result == 0; iArg++)
434 {
435 if ( 0 == strcmp( "A", argv[ iArg])) // get auth info
436 {
437 result = SetAuthInfo( commFD);
438 }
439 else if ( 0 == strcmp( "Wd", argv[ iArg])) // Write registration domain
440 {
441 result = HandleWriteDomain( commFD, 1);
442 }
443 else if ( 0 == strcmp( "Wb", argv[ iArg])) // Write browse domain
444 {
445 result = HandleWriteDomain( commFD, 0);
446 }
447 else if ( 0 == strcmp( "Wh", argv[ iArg])) // Write hostname
448 {
449 result = HandleWriteHostname( commFD);
450 }
451 else if ( 0 == strcmp( "Wk", argv[ iArg])) // Write keychain entry
452 {
453 result = SetKeychainEntry( commFD);
454 }
455 }
456 [pool release];
457 return result;
458 }
459
460 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
461 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
462 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
463 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
464 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
465
466 // NOT static -- otherwise the compiler may optimize it out
467 // The "@(#) " pattern is a special prefix the "what" command looks for
468 const char VersionString_SCCS[] = "@(#) ddnswriteconfig " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
469
470 // If the process crashes, then this string will be magically included in the automatically-generated crash log
471 const char *__crashreporter_info__ = VersionString_SCCS + 5;
472 asm(".desc ___crashreporter_info__, 0x10");