]> git.saurik.com Git - apple/securityd.git/blob - src/AuthorizationDBPlist.cpp
securityd-36489.tar.gz
[apple/securityd.git] / src / AuthorizationDBPlist.cpp
1 /*
2 * Copyright (c) 2003-2004 Apple Computer, Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 *
23 * AuthorizationDBPlist.cpp
24 * Security
25 *
26 */
27
28 #include "AuthorizationDBPlist.h"
29 #include <security_utilities/logging.h>
30
31 // mLock is held when the database is changed
32 // mReadWriteLock is held when the file on disk is changed
33 // during load(), save() and parseConfig() mLock is assumed
34
35 namespace Authorization {
36
37 AuthorizationDBPlist::AuthorizationDBPlist(const char *configFile) :
38 mFileName(configFile), mLastChecked(DBL_MIN)
39 {
40 memset(&mRulesFileMtimespec, 0, sizeof(mRulesFileMtimespec));
41 }
42
43 void AuthorizationDBPlist::sync(CFAbsoluteTime now)
44 {
45 if (mRules.empty()) {
46 StLock<Mutex> _(mLock);
47 load();
48 } else {
49 // Don't do anything if we checked the timestamp less than 5 seconds ago
50 if (mLastChecked > now - 5.0) {
51 secdebug("authdb", "no sync: last reload %.0f + 5 > %.0f",
52 mLastChecked, now);
53 return;
54 }
55
56 {
57 struct stat st;
58 {
59 StLock<Mutex> _(mReadWriteLock);
60 if (stat(mFileName.c_str(), &st)) {
61 Syslog::error("Stating rules file \"%s\": %s", mFileName.c_str(),
62 strerror(errno));
63 return;
64 }
65 }
66
67 if (memcmp(&st.st_mtimespec, &mRulesFileMtimespec, sizeof(mRulesFileMtimespec))) {
68 StLock<Mutex> _(mLock);
69 load();
70 }
71 }
72 }
73 }
74
75 void AuthorizationDBPlist::save()
76 {
77 if (!mConfig)
78 return;
79
80 StLock<Mutex> _(mReadWriteLock);
81
82 secdebug("authdb", "policy db changed, saving to disk.");
83 int fd = -1;
84 string tempFile = mFileName + ",";
85
86 for (;;) {
87 fd = open(tempFile.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0644);
88 if (fd == -1) {
89 if (errno == EEXIST) {
90 unlink(tempFile.c_str());
91 continue;
92 }
93 if (errno == EINTR)
94 continue;
95 else
96 break;
97 } else
98 break;
99 }
100
101 if (fd == -1) {
102 Syslog::error("Saving rules file \"%s\": %s", tempFile.c_str(),
103 strerror(errno));
104 return;
105 }
106
107 CFDataRef configXML = CFPropertyListCreateXMLData(NULL, mConfig);
108 if (!configXML)
109 return;
110
111 CFIndex configSize = CFDataGetLength(configXML);
112 size_t bytesWritten = write(fd, CFDataGetBytePtr(configXML), configSize);
113 CFRelease(configXML);
114
115 if (bytesWritten != configSize) {
116 if (bytesWritten == static_cast<size_t>(-1))
117 Syslog::error("Problem writing rules file \"%s\": (errno=%s)",
118 tempFile.c_str(), strerror(errno));
119 else
120 Syslog::error("Problem writing rules file \"%s\": "
121 "only wrote %lu out of %ld bytes",
122 tempFile.c_str(), bytesWritten, configSize);
123
124 close(fd);
125 unlink(tempFile.c_str());
126 }
127 else
128 {
129 close(fd);
130 if (rename(tempFile.c_str(), mFileName.c_str()))
131 unlink(tempFile.c_str());
132 else
133 mLastChecked = CFAbsoluteTimeGetCurrent(); // we have the copy that's on disk now, so don't go loading it right away
134 }
135 }
136
137 void AuthorizationDBPlist::load()
138 {
139 StLock<Mutex> _(mReadWriteLock);
140
141 secdebug("authdb", "(re)loading policy db from disk.");
142 int fd = open(mFileName.c_str(), O_RDONLY, 0);
143 if (fd == -1) {
144 Syslog::error("Problem opening rules file \"%s\": %s",
145 mFileName.c_str(), strerror(errno));
146 return;
147 }
148
149 struct stat st;
150 if (fstat(fd, &st)) {
151 int error = errno;
152 close(fd);
153 UnixError::throwMe(error);
154 }
155
156 mRulesFileMtimespec = st.st_mtimespec;
157 off_t fileSize = st.st_size;
158 CFMutableDataRef xmlData = CFDataCreateMutable(NULL, fileSize);
159 CFDataSetLength(xmlData, fileSize);
160 void *buffer = CFDataGetMutableBytePtr(xmlData);
161 size_t bytesRead = read(fd, buffer, fileSize);
162 if (bytesRead != fileSize) {
163 if (bytesRead == static_cast<size_t>(-1)) {
164 Syslog::error("Problem reading rules file \"%s\": %s",
165 mFileName.c_str(), strerror(errno));
166 CFRelease(xmlData);
167 return;
168 }
169 Syslog::error("Problem reading rules file \"%s\": "
170 "only read %ul out of %ul bytes",
171 bytesRead, fileSize, mFileName.c_str());
172 CFRelease(xmlData);
173 return;
174 }
175
176 CFStringRef errorString;
177 CFDictionaryRef configPlist = reinterpret_cast<CFDictionaryRef>(CFPropertyListCreateFromXMLData(NULL, xmlData, kCFPropertyListMutableContainersAndLeaves, &errorString));
178
179 if (!configPlist) {
180 char buffer[512];
181 const char *error = CFStringGetCStringPtr(errorString,
182 kCFStringEncodingUTF8);
183 if (error == NULL) {
184 if (CFStringGetCString(errorString, buffer, 512,
185 kCFStringEncodingUTF8))
186 error = buffer;
187 }
188
189 Syslog::error("Parsing rules file \"%s\": %s",
190 mFileName.c_str(), error);
191 if (errorString)
192 CFRelease(errorString);
193
194 CFRelease(xmlData);
195 return;
196 }
197
198 if (CFGetTypeID(configPlist) != CFDictionaryGetTypeID()) {
199
200 Syslog::error("Rules file \"%s\": is not a dictionary",
201 mFileName.c_str());
202
203 CFRelease(xmlData);
204 CFRelease(configPlist);
205 return;
206 }
207
208 parseConfig(configPlist);
209
210 CFRelease(xmlData);
211 CFRelease(configPlist);
212
213 close(fd);
214
215 // If all went well, we have the copy that's on disk now, so don't go loading it right away
216 mLastChecked = CFAbsoluteTimeGetCurrent();
217 }
218
219 void AuthorizationDBPlist::parseConfig(CFDictionaryRef config)
220 {
221 CFStringRef rightsKey = CFSTR("rights");
222 CFStringRef rulesKey = CFSTR("rules");
223 CFMutableDictionaryRef newRights = NULL;
224 CFMutableDictionaryRef newRules = NULL;
225
226 if (!config)
227 MacOSError::throwMe(errAuthorizationInternal);
228
229 if (CFDictionaryContainsKey(config, rulesKey))
230 newRules = reinterpret_cast<CFMutableDictionaryRef>(const_cast<void*>(CFDictionaryGetValue(config, rulesKey)));
231
232 if (CFDictionaryContainsKey(config, rightsKey))
233 newRights = reinterpret_cast<CFMutableDictionaryRef>(const_cast<void*>(CFDictionaryGetValue(config, rightsKey)));
234
235 if (newRules && newRights
236 && (CFDictionaryGetTypeID() == CFGetTypeID(newRules))
237 && (CFDictionaryGetTypeID() == CFGetTypeID(newRights)))
238 {
239 mConfigRights = static_cast<CFMutableDictionaryRef>(newRights);
240 mConfigRules = static_cast<CFMutableDictionaryRef>(newRules);
241 mRules.clear();
242 try {
243 CFDictionaryApplyFunction(newRights, parseRule, this);
244 } catch (...) {
245 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule file
246 }
247 mConfig = config;
248 }
249 else
250 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule file
251 }
252
253 void AuthorizationDBPlist::parseRule(const void *key, const void *value, void *context)
254 {
255 static_cast<AuthorizationDBPlist*>(context)->addRight(static_cast<CFStringRef>(key), static_cast<CFDictionaryRef>(value));
256 }
257
258 void AuthorizationDBPlist::addRight(CFStringRef key, CFDictionaryRef definition)
259 {
260 string keyString = cfString(key);
261 mRules[keyString] = Rule(keyString, definition, mConfigRules);
262 }
263
264 bool
265 AuthorizationDBPlist::validateRule(string inRightName, CFDictionaryRef inRightDefinition) const
266 {
267 try {
268 Rule newRule(inRightName, inRightDefinition, mConfigRules);
269 if (newRule->name() == inRightName)
270 return true;
271 } catch (...) {
272 secdebug("authrule", "invalid definition for rule %s.\n",
273 inRightName.c_str());
274 }
275 return false;
276 }
277
278 CFDictionaryRef
279 AuthorizationDBPlist::getRuleDefinition(string &key)
280 {
281 CFStringRef cfKey = makeCFString(key);
282 StLock<Mutex> _(mLock);
283 if (CFDictionaryContainsKey(mConfigRights, cfKey)) {
284 CFDictionaryRef definition = reinterpret_cast<CFMutableDictionaryRef>(const_cast<void*>(CFDictionaryGetValue(mConfigRights, cfKey)));
285 CFRelease(cfKey);
286 return CFDictionaryCreateCopy(NULL, definition);
287 } else {
288 CFRelease(cfKey);
289 return NULL;
290 }
291 }
292
293 bool
294 AuthorizationDBPlist::existRule(string &ruleName) const
295 {
296 AuthItemRef candidateRule(ruleName.c_str());
297 string ruleForCandidate = getRule(candidateRule)->name();
298 // same name or covered by wildcard right -> modification.
299 if ( (ruleName == ruleForCandidate) ||
300 (*(ruleForCandidate.rbegin()) == '.') )
301 return true;
302
303 return false;
304 }
305
306 Rule
307 AuthorizationDBPlist::getRule(const AuthItemRef &inRight) const
308 {
309 string key(inRight->name());
310 // Lock the rulemap
311 StLock<Mutex> _(mLock);
312
313 secdebug("authdb", "looking up rule %s.", inRight->name());
314 if (mRules.empty())
315 return Rule();
316
317 for (;;) {
318 map<string,Rule>::const_iterator rule = mRules.find(key);
319
320 if (rule != mRules.end())
321 return (*rule).second;
322
323 // no default rule
324 assert (key.size());
325
326 // any reduction of a combination of two chars is futile
327 if (key.size() > 2) {
328 // find last dot with exception of possible dot at end
329 string::size_type index = key.rfind('.', key.size() - 2);
330 // cut right after found dot, or make it match default rule
331 key = key.substr(0, index == string::npos ? 0 : index + 1);
332 } else
333 key.erase();
334 }
335 }
336
337 void
338 AuthorizationDBPlist::setRule(const char *inRightName, CFDictionaryRef inRuleDefinition)
339 {
340 // if mConfig is now a reasonable guard
341 if (!inRuleDefinition || !mConfigRights)
342 MacOSError::throwMe(errAuthorizationDenied); // errInvalidRule
343
344 CFRef<CFStringRef> keyRef(CFStringCreateWithCString(NULL, inRightName,
345 kCFStringEncodingASCII));
346 if (!keyRef)
347 return;
348
349 {
350 StLock<Mutex> _(mLock);
351 secdebug("authdb", "setting up rule %s.", inRightName);
352 CFDictionarySetValue(mConfigRights, keyRef, inRuleDefinition);
353 save();
354 parseConfig(mConfig);
355 }
356 }
357
358 void
359 AuthorizationDBPlist::removeRule(const char *inRightName)
360 {
361 // if mConfig is now a reasonable guard
362 if (!mConfigRights)
363 MacOSError::throwMe(errAuthorizationDenied);
364
365 CFRef<CFStringRef> keyRef(CFStringCreateWithCString(NULL, inRightName,
366 kCFStringEncodingASCII));
367 if (!keyRef)
368 return;
369
370 {
371 StLock<Mutex> _(mLock);
372 secdebug("authdb", "removing rule %s.", inRightName);
373 CFDictionaryRemoveValue(mConfigRights, keyRef);
374 save();
375 parseConfig(mConfig);
376 }
377 }
378
379
380 } // end namespace Authorization