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 size_t bytesWritten
= write(fd
, CFDataGetBytePtr(configXML
), configSize
);
113 CFRelease(configXML
);
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
));
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 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
));
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
;
227 MacOSError::throwMe(errAuthorizationInternal
);
229 if (CFDictionaryContainsKey(config
, rulesKey
))
230 newRules
= reinterpret_cast<CFMutableDictionaryRef
>(const_cast<void*>(CFDictionaryGetValue(config
, rulesKey
)));
232 if (CFDictionaryContainsKey(config
, rightsKey
))
233 newRights
= reinterpret_cast<CFMutableDictionaryRef
>(const_cast<void*>(CFDictionaryGetValue(config
, rightsKey
)));
235 if (newRules
&& newRights
236 && (CFDictionaryGetTypeID() == CFGetTypeID(newRules
))
237 && (CFDictionaryGetTypeID() == CFGetTypeID(newRights
)))
239 mConfigRights
= static_cast<CFMutableDictionaryRef
>(newRights
);
240 mConfigRules
= static_cast<CFMutableDictionaryRef
>(newRules
);
243 CFDictionaryApplyFunction(newRights
, parseRule
, this);
245 MacOSError::throwMe(errAuthorizationInternal
); // XXX/cs invalid rule file
250 MacOSError::throwMe(errAuthorizationInternal
); // XXX/cs invalid rule file
253 void AuthorizationDBPlist::parseRule(const void *key
, const void *value
, void *context
)
255 static_cast<AuthorizationDBPlist
*>(context
)->addRight(static_cast<CFStringRef
>(key
), static_cast<CFDictionaryRef
>(value
));
258 void AuthorizationDBPlist::addRight(CFStringRef key
, CFDictionaryRef definition
)
260 string keyString
= cfString(key
);
261 mRules
[keyString
] = Rule(keyString
, definition
, mConfigRules
);
265 AuthorizationDBPlist::validateRule(string inRightName
, CFDictionaryRef inRightDefinition
) const
268 Rule
newRule(inRightName
, inRightDefinition
, mConfigRules
);
269 if (newRule
->name() == inRightName
)
272 secdebug("authrule", "invalid definition for rule %s.\n",
273 inRightName
.c_str());
279 AuthorizationDBPlist::getRuleDefinition(string
&key
)
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
)));
286 return CFDictionaryCreateCopy(NULL
, definition
);
294 AuthorizationDBPlist::existRule(string
&ruleName
) const
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()) == '.') )
307 AuthorizationDBPlist::getRule(const AuthItemRef
&inRight
) const
309 string
key(inRight
->name());
311 StLock
<Mutex
> _(mLock
);
313 secdebug("authdb", "looking up rule %s.", inRight
->name());
318 map
<string
,Rule
>::const_iterator rule
= mRules
.find(key
);
320 if (rule
!= mRules
.end())
321 return (*rule
).second
;
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);
338 AuthorizationDBPlist::setRule(const char *inRightName
, CFDictionaryRef inRuleDefinition
)
340 // if mConfig is now a reasonable guard
341 if (!inRuleDefinition
|| !mConfigRights
)
342 MacOSError::throwMe(errAuthorizationDenied
); // errInvalidRule
344 CFRef
<CFStringRef
> keyRef(CFStringCreateWithCString(NULL
, inRightName
,
345 kCFStringEncodingASCII
));
350 StLock
<Mutex
> _(mLock
);
351 secdebug("authdb", "setting up rule %s.", inRightName
);
352 CFDictionarySetValue(mConfigRights
, keyRef
, inRuleDefinition
);
354 parseConfig(mConfig
);
359 AuthorizationDBPlist::removeRule(const char *inRightName
)
361 // if mConfig is now a reasonable guard
363 MacOSError::throwMe(errAuthorizationDenied
);
365 CFRef
<CFStringRef
> keyRef(CFStringCreateWithCString(NULL
, inRightName
,
366 kCFStringEncodingASCII
));
371 StLock
<Mutex
> _(mLock
);
372 secdebug("authdb", "removing rule %s.", inRightName
);
373 CFDictionaryRemoveValue(mConfigRights
, keyRef
);
375 parseConfig(mConfig
);
380 } // end namespace Authorization