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