2 * Copyright (c) 2003-2004 Apple Computer, Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
23 * AuthorizationDBPlist.cpp
28 #include "AuthorizationDBPlist.h"
29 #include <security_utilities/logging.h>
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
35 namespace Authorization
{
37 AuthorizationDBPlist::AuthorizationDBPlist(const char *configFile
) :
38 mFileName(configFile
), mLastChecked(DBL_MIN
)
40 memset(&mRulesFileMtimespec
, 0, sizeof(mRulesFileMtimespec
));
43 void AuthorizationDBPlist::sync(CFAbsoluteTime now
)
46 StLock
<Mutex
> _(mLock
);
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",
59 StLock
<Mutex
> _(mReadWriteLock
);
60 if (stat(mFileName
.c_str(), &st
)) {
61 Syslog::error("Stating rules file \"%s\": %s", mFileName
.c_str(),
67 if (memcmp(&st
.st_mtimespec
, &mRulesFileMtimespec
, sizeof(mRulesFileMtimespec
))) {
68 StLock
<Mutex
> _(mLock
);
75 void AuthorizationDBPlist::save()
80 StLock
<Mutex
> _(mReadWriteLock
);
82 secdebug("authdb", "policy db changed, saving to disk.");
84 string tempFile
= mFileName
+ ",";
87 fd
= open(tempFile
.c_str(), O_WRONLY
|O_CREAT
|O_EXCL
, 0644);
89 if (errno
== EEXIST
) {
90 unlink(tempFile
.c_str());
102 Syslog::error("Saving rules file \"%s\": %s", tempFile
.c_str(),
107 CFDataRef configXML
= CFPropertyListCreateXMLData(NULL
, mConfig
);
111 CFIndex configSize
= CFDataGetLength(configXML
);
112 ssize_t bytesWritten
= write(fd
, CFDataGetBytePtr(configXML
), configSize
);
113 CFRelease(configXML
);
115 if (bytesWritten
!= configSize
) {
116 if (bytesWritten
== -1)
117 Syslog::error("Problem writing rules file \"%s\": (errno=%s)",
118 tempFile
.c_str(), strerror(errno
));
120 Syslog::error("Problem writing rules file \"%s\": "
121 "only wrote %lu out of %ld bytes",
122 tempFile
.c_str(), bytesWritten
, configSize
);
125 unlink(tempFile
.c_str());
130 if (rename(tempFile
.c_str(), mFileName
.c_str()))
131 unlink(tempFile
.c_str());
133 mLastChecked
= CFAbsoluteTimeGetCurrent(); // we have the copy that's on disk now, so don't go loading it right away
137 void AuthorizationDBPlist::load()
139 StLock
<Mutex
> _(mReadWriteLock
);
141 secdebug("authdb", "(re)loading policy db from disk.");
142 int fd
= open(mFileName
.c_str(), O_RDONLY
, 0);
144 Syslog::error("Problem opening rules file \"%s\": %s",
145 mFileName
.c_str(), strerror(errno
));
150 if (fstat(fd
, &st
)) {
153 UnixError::throwMe(error
);
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 ssize_t bytesRead
= read(fd
, buffer
, fileSize
);
162 if (bytesRead
!= fileSize
) {
163 if (bytesRead
== -1) {
164 Syslog::error("Problem reading rules file \"%s\": %s",
165 mFileName
.c_str(), strerror(errno
));
169 Syslog::error("Problem reading rules file \"%s\": "
170 "only read %ul out of %ul bytes",
171 bytesRead
, fileSize
, mFileName
.c_str());
176 CFStringRef errorString
;
177 CFDictionaryRef configPlist
= reinterpret_cast<CFDictionaryRef
>(CFPropertyListCreateFromXMLData(NULL
, xmlData
, kCFPropertyListMutableContainersAndLeaves
, &errorString
));
181 const char *error
= CFStringGetCStringPtr(errorString
,
182 kCFStringEncodingUTF8
);
184 if (CFStringGetCString(errorString
, buffer
, 512,
185 kCFStringEncodingUTF8
))
189 Syslog::error("Parsing rules file \"%s\": %s",
190 mFileName
.c_str(), error
);
192 CFRelease(errorString
);
198 if (CFGetTypeID(configPlist
) != CFDictionaryGetTypeID()) {
200 Syslog::error("Rules file \"%s\": is not a dictionary",
204 CFRelease(configPlist
);
208 parseConfig(configPlist
);
211 CFRelease(configPlist
);
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();
219 void AuthorizationDBPlist::parseConfig(CFDictionaryRef config
)
221 CFStringRef rightsKey
= CFSTR("rights");
222 CFStringRef rulesKey
= CFSTR("rules");
223 CFMutableDictionaryRef newRights
= NULL
;
224 CFMutableDictionaryRef newRules
= NULL
;
228 Syslog::alert("Failed to parse config, no config");
229 MacOSError::throwMe(errAuthorizationInternal
);
232 if (CFDictionaryContainsKey(config
, rulesKey
))
233 newRules
= reinterpret_cast<CFMutableDictionaryRef
>(const_cast<void*>(CFDictionaryGetValue(config
, rulesKey
)));
235 if (CFDictionaryContainsKey(config
, rightsKey
))
236 newRights
= reinterpret_cast<CFMutableDictionaryRef
>(const_cast<void*>(CFDictionaryGetValue(config
, rightsKey
)));
238 if (newRules
&& newRights
239 && (CFDictionaryGetTypeID() == CFGetTypeID(newRules
))
240 && (CFDictionaryGetTypeID() == CFGetTypeID(newRights
)))
242 mConfigRights
= static_cast<CFMutableDictionaryRef
>(newRights
);
243 mConfigRules
= static_cast<CFMutableDictionaryRef
>(newRules
);
246 CFDictionaryApplyFunction(newRights
, parseRule
, this);
248 Syslog::alert("Failed to parse config and apply dictionary function");
249 MacOSError::throwMe(errAuthorizationInternal
); // XXX/cs invalid rule file
255 Syslog::alert("Failed to parse config, invalid rule file");
256 MacOSError::throwMe(errAuthorizationInternal
); // XXX/cs invalid rule file
260 void AuthorizationDBPlist::parseRule(const void *key
, const void *value
, void *context
)
262 static_cast<AuthorizationDBPlist
*>(context
)->addRight(static_cast<CFStringRef
>(key
), static_cast<CFDictionaryRef
>(value
));
265 void AuthorizationDBPlist::addRight(CFStringRef key
, CFDictionaryRef definition
)
267 string keyString
= cfString(key
);
268 mRules
[keyString
] = Rule(keyString
, definition
, mConfigRules
);
272 AuthorizationDBPlist::validateRule(string inRightName
, CFDictionaryRef inRightDefinition
) const
275 0 == CFDictionaryGetCount(mConfigRules
)) {
276 Syslog::error("No rule definitions!");
277 MacOSError::throwMe(errAuthorizationInternal
);
280 Rule
newRule(inRightName
, inRightDefinition
, mConfigRules
);
281 if (newRule
->name() == inRightName
)
284 secdebug("authrule", "invalid definition for rule %s.\n",
285 inRightName
.c_str());
291 AuthorizationDBPlist::getRuleDefinition(string
&key
)
293 if (!mConfigRights
||
294 0 == CFDictionaryGetCount(mConfigRights
)) {
295 Syslog::error("No rule definitions!");
296 MacOSError::throwMe(errAuthorizationInternal
);
298 CFStringRef cfKey
= makeCFString(key
);
299 StLock
<Mutex
> _(mLock
);
300 if (CFDictionaryContainsKey(mConfigRights
, cfKey
)) {
301 CFDictionaryRef definition
= reinterpret_cast<CFMutableDictionaryRef
>(const_cast<void*>(CFDictionaryGetValue(mConfigRights
, cfKey
)));
303 return CFDictionaryCreateCopy(NULL
, definition
);
311 AuthorizationDBPlist::existRule(string
&ruleName
) const
313 AuthItemRef
candidateRule(ruleName
.c_str());
314 string ruleForCandidate
= getRule(candidateRule
)->name();
315 // same name or covered by wildcard right -> modification.
316 if ( (ruleName
== ruleForCandidate
) ||
317 (*(ruleForCandidate
.rbegin()) == '.') )
324 AuthorizationDBPlist::getRule(const AuthItemRef
&inRight
) const
326 string
key(inRight
->name());
328 StLock
<Mutex
> _(mLock
);
330 secdebug("authdb", "looking up rule %s.", inRight
->name());
335 map
<string
,Rule
>::const_iterator rule
= mRules
.find(key
);
337 if (rule
!= mRules
.end())
338 return (*rule
).second
;
343 // any reduction of a combination of two chars is futile
344 if (key
.size() > 2) {
345 // find last dot with exception of possible dot at end
346 string::size_type index
= key
.rfind('.', key
.size() - 2);
347 // cut right after found dot, or make it match default rule
348 key
= key
.substr(0, index
== string::npos
? 0 : index
+ 1);
355 AuthorizationDBPlist::setRule(const char *inRightName
, CFDictionaryRef inRuleDefinition
)
357 // if mConfig is now a reasonable guard
358 if (!inRuleDefinition
|| !mConfigRights
)
360 Syslog::alert("Failed to set rule, no definition or rights");
361 MacOSError::throwMe(errAuthorizationDenied
); // ???/gh errAuthorizationInternal instead?
364 CFRef
<CFStringRef
> keyRef(CFStringCreateWithCString(NULL
, inRightName
,
365 kCFStringEncodingASCII
));
370 StLock
<Mutex
> _(mLock
);
371 secdebug("authdb", "setting up rule %s.", inRightName
);
372 CFDictionarySetValue(mConfigRights
, keyRef
, inRuleDefinition
);
374 parseConfig(mConfig
);
379 AuthorizationDBPlist::removeRule(const char *inRightName
)
381 // if mConfig is now a reasonable guard
384 Syslog::alert("Failed to remove rule, no rights");
385 MacOSError::throwMe(errAuthorizationDenied
); // ???/gh errAuthorizationInternal instead?
388 CFRef
<CFStringRef
> keyRef(CFStringCreateWithCString(NULL
, inRightName
,
389 kCFStringEncodingASCII
));
394 StLock
<Mutex
> _(mLock
);
395 secdebug("authdb", "removing rule %s.", inRightName
);
396 CFDictionaryRemoveValue(mConfigRights
, keyRef
);
398 parseConfig(mConfig
);
403 } // end namespace Authorization