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