]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/PreferencePane/ddnswriteconfig.m
mDNSResponder-107.6.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.5 2006/08/14 23:15:47 cheshire
49 Tidy up Change History comment
50
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
54
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.
58
59 Revision 1.2 2005/02/10 22:35:20 cheshire
60 <rdar://problem/3727944> Update name
61
62 Revision 1.1 2005/02/05 01:59:19 cheshire
63 Add Preference Pane to facilitate testing of DDNS & wide-area features
64
65 */
66
67
68 #import "PrivilegedOperations.h"
69 #import "ConfigurationRights.h"
70
71 #import <stdio.h>
72 #import <stdint.h>
73 #import <stdlib.h>
74 #import <unistd.h>
75 #import <fcntl.h>
76 #import <errno.h>
77 #import <sys/types.h>
78 #import <sys/stat.h>
79 #import <sys/mman.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>
87
88
89 static AuthorizationRef gAuthRef = 0;
90
91 OSStatus
92 WriteArrayToDynDNS(CFStringRef arrayKey, CFArrayRef domainArray)
93 {
94 SCPreferencesRef store;
95 OSStatus err = noErr;
96 CFDictionaryRef origDict;
97 CFMutableDictionaryRef dict = NULL;
98 Boolean result;
99 CFStringRef scKey = CFSTR("/System/Network/DynamicDNS");
100
101
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;);
108
109 origDict = SCPreferencesPathGetValue(store, scKey);
110 if (origDict) {
111 dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
112 }
113
114 if (!dict) {
115 dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
116 }
117 require_action( dict != NULL, NoDict, err=memFullErr;);
118
119 if (CFArrayGetCount(domainArray) > 0) {
120 CFDictionarySetValue(dict, arrayKey, domainArray);
121 } else {
122 CFDictionaryRemoveValue(dict, arrayKey);
123 }
124
125 result = SCPreferencesPathSetValue(store, scKey, dict);
126 require_action(result, SCError, err=kernelPrivilegeErr;);
127
128 result = SCPreferencesCommitChanges(store);
129 require_action(result, SCError, err=kernelPrivilegeErr;);
130 result = SCPreferencesApplyChanges(store);
131 require_action(result, SCError, err=kernelPrivilegeErr;);
132
133 SCError:
134 CFRelease(dict);
135 NoDict:
136 SCPreferencesUnlock(store);
137 LockFailed:
138 CFRelease(store);
139 SysConfigErr:
140 return err;
141 }
142
143
144 static int
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().
147 {
148 ssize_t num;
149 u_int32_t tag, len;
150 int result = 0;
151
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;);
156
157 *ppBuff = (char*) malloc( len);
158 require_action(*ppBuff != NULL, AllocFailed, result = -1;);
159
160 num = read(fd, *ppBuff, len);
161 if (num == len) {
162 *pTag = tag;
163 *pLen = len;
164 } else {
165 free(*ppBuff);
166 result = -1;
167 }
168
169 AllocFailed:
170 GetLenFailed:
171 GetTagFailed:
172 return result;
173 }
174
175
176
177 int
178 SetAuthInfo( int fd)
179 {
180 int result = 0;
181 u_int32_t tag, len;
182 char *p;
183
184 result = readTaggedBlock( fd, &tag, &len, &p);
185 require( result == 0, ReadParamsFailed);
186
187 if (gAuthRef != 0) {
188 (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDestroyRights);
189 gAuthRef = 0;
190 }
191
192 result = AuthorizationCreateFromExternalForm((AuthorizationExternalForm*) p, &gAuthRef);
193
194 free( p);
195 ReadParamsFailed:
196 return result;
197 }
198
199
200 int
201 HandleWriteDomain(int fd, int domainType)
202 {
203 CFArrayRef domainArray;
204 CFDataRef domainData;
205 int result = 0;
206 u_int32_t tag, len;
207 char *p;
208
209 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
210 AuthorizationRights authSet = { 1, &scAuth };
211
212 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
213 return result;
214
215 result = readTaggedBlock(fd, &tag, &len, &p);
216 require(result == 0, ReadParamsFailed);
217
218 domainData = CFDataCreate(NULL, (UInt8 *)p, len);
219 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
220
221 if (domainType) {
222 result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
223 } else {
224 result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
225 }
226
227 ReadParamsFailed:
228 return result;
229 }
230
231
232 int
233 HandleWriteHostname(int fd)
234 {
235 CFArrayRef domainArray;
236 CFDataRef domainData;
237 int result = 0;
238 u_int32_t tag, len;
239 char *p;
240
241 AuthorizationItem scAuth = { UPDATE_SC_RIGHT, 0, NULL, 0 };
242 AuthorizationRights authSet = { 1, &scAuth };
243
244 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags) 0, NULL)))
245 return result;
246
247 result = readTaggedBlock(fd, &tag, &len, &p);
248 require(result == 0, ReadParamsFailed);
249
250 domainData = CFDataCreate(NULL, (const UInt8 *)p, len);
251 domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
252 result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
253
254 ReadParamsFailed:
255 return result;
256 }
257
258
259 SecAccessRef
260 MyMakeUidAccess(uid_t uid)
261 {
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)
267 uid, // uid to match
268 0 // gid (not matched here)
269 };
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 };
274
275
276 // rights granted (replace with individual list if desired)
277 CSSM_ACL_AUTHORIZATION_TAG rights[] = {
278 CSSM_ACL_AUTHORIZATION_ANY // everything
279 };
280 // owner component (right to change ACL)
281 CSSM_ACL_OWNER_PROTOTYPE owner = {
282 // TypedSubject
283 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
284 // Delegate
285 false
286 };
287 // ACL entries (any number, just one here)
288 CSSM_ACL_ENTRY_INFO acls[] = {
289 {
290 // prototype
291 {
292 // TypedSubject
293 { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 },
294 false, // Delegate
295 // rights for this entry
296 { sizeof(rights) / sizeof(rights[0]), rights },
297 // rest is defaulted
298 }
299 }
300 };
301
302 SecAccessRef access = NULL;
303 (void) SecAccessCreateFromOwnerAndACL(&owner, sizeof(acls) / sizeof(acls[0]), acls, &access);
304 return access;
305 }
306
307
308 OSStatus
309 MyAddDynamicDNSPassword(SecKeychainRef keychain, SecAccessRef access, UInt32 serviceNameLength, const char *serviceName,
310 UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData)
311 {
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);
318 OSStatus err;
319
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 };
328
329 err = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, &attributes, passwordLength, passwordData, keychain, access, NULL);
330 return err;
331 }
332
333
334 int
335 SetKeychainEntry(int fd)
336 // Create a new entry in system keychain, or replace existing
337 {
338 CFDataRef secretData;
339 CFDictionaryRef secretDictionary;
340 CFStringRef keyNameString;
341 CFStringRef domainString;
342 CFStringRef secretString;
343 SecKeychainItemRef item = NULL;
344 int result = 0;
345 u_int32_t tag, len;
346 char *p;
347 char keyname[1005];
348 char domain[1005];
349 char secret[1005];
350
351 AuthorizationItem kcAuth = { EDIT_SYS_KEYCHAIN_RIGHT, 0, NULL, 0 };
352 AuthorizationRights authSet = { 1, &kcAuth };
353
354 if (noErr != (result = AuthorizationCopyRights(gAuthRef, &authSet, NULL, (AuthorizationFlags)0, NULL)))
355 return result;
356
357 result = readTaggedBlock(fd, &tag, &len, &p);
358 require_noerr(result, ReadParamsFailed);
359
360 secretData = CFDataCreate(NULL, (UInt8 *)p, len);
361 secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
362
363 keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
364 assert(keyNameString != NULL);
365
366 domainString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_DOMAIN_KEY);
367 assert(domainString != NULL);
368
369 secretString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_SECRET_KEY);
370 assert(secretString != NULL);
371
372 CFStringGetCString(keyNameString, keyname, 1005, kCFStringEncodingUTF8);
373 CFStringGetCString(domainString, domain, 1005, kCFStringEncodingUTF8);
374 CFStringGetCString(secretString, secret, 1005, kCFStringEncodingUTF8);
375
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);
382 }
383
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);
387 }
388
389 ReadParamsFailed:
390 return result;
391 }
392
393
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
403 */
404 {
405 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
406 int commFD = -1, iArg, result = 0;
407
408 if ( 0 != seteuid( 0))
409 return -1;
410
411 if ( argc == 3 && 0 == strcmp( argv[2], "V"))
412 return PRIV_OP_TOOL_VERS;
413
414 if ( argc >= 1)
415 {
416 commFD = strtol( argv[1], NULL, 0);
417 lseek( commFD, 0, SEEK_SET);
418 }
419 for ( iArg = 2; iArg < argc && result == 0; iArg++)
420 {
421 if ( 0 == strcmp( "A", argv[ iArg])) // get auth info
422 {
423 result = SetAuthInfo( commFD);
424 }
425 else if ( 0 == strcmp( "Wd", argv[ iArg])) // Write registration domain
426 {
427 result = HandleWriteDomain( commFD, 1);
428 }
429 else if ( 0 == strcmp( "Wb", argv[ iArg])) // Write browse domain
430 {
431 result = HandleWriteDomain( commFD, 0);
432 }
433 else if ( 0 == strcmp( "Wh", argv[ iArg])) // Write hostname
434 {
435 result = HandleWriteHostname( commFD);
436 }
437 else if ( 0 == strcmp( "Wk", argv[ iArg])) // Write keychain entry
438 {
439 result = SetKeychainEntry( commFD);
440 }
441 }
442 [pool release];
443 return result;
444 }