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