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>
30 #include <System/sys/fsctl.h>
32 // mLock is held when the database is changed
33 // mReadWriteLock is held when the file on disk is changed
34 // during load(), save() and parseConfig() mLock is assumed
36 namespace Authorization
{
38 AuthorizationDBPlist::AuthorizationDBPlist(const char *configFile
) :
39 mFileName(configFile
), mLastChecked(DBL_MIN
)
41 memset(&mRulesFileMtimespec
, 0, sizeof(mRulesFileMtimespec
));
44 void AuthorizationDBPlist::sync(CFAbsoluteTime now
)
47 StLock
<Mutex
> _(mLock
);
50 // Don't do anything if we checked the timestamp less than 5 seconds ago
51 if (mLastChecked
> now
- 5.0) {
52 secdebug("authdb", "no sync: last reload %.0f + 5 > %.0f",
60 StLock
<Mutex
> _(mReadWriteLock
);
61 if (stat(mFileName
.c_str(), &st
)) {
62 Syslog::error("Stating rules file \"%s\": %s", mFileName
.c_str(),
68 if (memcmp(&st
.st_mtimespec
, &mRulesFileMtimespec
, sizeof(mRulesFileMtimespec
))) {
69 StLock
<Mutex
> _(mLock
);
76 void AuthorizationDBPlist::save()
81 StLock
<Mutex
> _(mReadWriteLock
);
83 secdebug("authdb", "policy db changed, saving to disk.");
85 string tempFile
= mFileName
+ ",";
88 fd
= open(tempFile
.c_str(), O_WRONLY
|O_CREAT
|O_EXCL
, 0644);
90 if (errno
== EEXIST
) {
91 unlink(tempFile
.c_str());
103 Syslog::error("Saving rules file \"%s\": %s", tempFile
.c_str(),
108 CFDataRef configXML
= CFPropertyListCreateXMLData(NULL
, mConfig
);
112 CFIndex configSize
= CFDataGetLength(configXML
);
113 ssize_t bytesWritten
= write(fd
, CFDataGetBytePtr(configXML
), configSize
);
114 CFRelease(configXML
);
116 if (bytesWritten
!= configSize
) {
117 if (bytesWritten
== -1)
118 Syslog::error("Problem writing rules file \"%s\": (errno=%s)",
119 tempFile
.c_str(), strerror(errno
));
121 Syslog::error("Problem writing rules file \"%s\": "
122 "only wrote %lu out of %ld bytes",
123 tempFile
.c_str(), bytesWritten
, configSize
);
126 unlink(tempFile
.c_str());
130 if (-1 == fcntl(fd
, F_FULLFSYNC
, NULL
))
134 int fd2
= open (mFileName
.c_str(), O_RDONLY
);
135 if (rename(tempFile
.c_str(), mFileName
.c_str()))
138 unlink(tempFile
.c_str());
142 /* force a sync to flush the journal */
143 int flags
= FSCTL_SYNC_WAIT
|FSCTL_SYNC_FULLSYNC
;
144 ffsctl(fd2
, FSCTL_SYNC_VOLUME
, &flags
, sizeof(flags
));
146 mLastChecked
= CFAbsoluteTimeGetCurrent(); // we have the copy that's on disk now, so don't go loading it right away
151 void AuthorizationDBPlist::load()
153 StLock
<Mutex
> _(mReadWriteLock
);
154 CFDictionaryRef configPlist
;
156 secdebug("authdb", "(re)loading policy db from disk.");
157 int fd
= open(mFileName
.c_str(), O_RDONLY
, 0);
159 Syslog::error("Problem opening rules file \"%s\": %s",
160 mFileName
.c_str(), strerror(errno
));
165 if (fstat(fd
, &st
)) {
168 UnixError::throwMe(error
);
171 mRulesFileMtimespec
= st
.st_mtimespec
;
172 off_t fileSize
= st
.st_size
;
173 CFMutableDataRef xmlData
= CFDataCreateMutable(NULL
, fileSize
);
174 CFDataSetLength(xmlData
, fileSize
);
175 void *buffer
= CFDataGetMutableBytePtr(xmlData
);
176 ssize_t bytesRead
= read(fd
, buffer
, fileSize
);
177 if (bytesRead
!= fileSize
) {
178 if (bytesRead
== -1) {
179 Syslog::error("Problem reading rules file \"%s\": %s",
180 mFileName
.c_str(), strerror(errno
));
183 Syslog::error("Problem reading rules file \"%s\": "
184 "only read %ul out of %ul bytes",
185 bytesRead
, fileSize
, mFileName
.c_str());
189 CFStringRef errorString
;
190 configPlist
= reinterpret_cast<CFDictionaryRef
>(CFPropertyListCreateFromXMLData(NULL
, xmlData
, kCFPropertyListMutableContainersAndLeaves
, &errorString
));
194 const char *error
= CFStringGetCStringPtr(errorString
,
195 kCFStringEncodingUTF8
);
197 if (CFStringGetCString(errorString
, buffer
, 512,
198 kCFStringEncodingUTF8
))
202 Syslog::error("Parsing rules file \"%s\": %s",
203 mFileName
.c_str(), error
);
205 CFRelease(errorString
);
210 if (CFGetTypeID(configPlist
) != CFDictionaryGetTypeID()) {
212 Syslog::error("Rules file \"%s\": is not a dictionary",
218 parseConfig(configPlist
);
224 CFRelease(configPlist
);
228 // If all went well, we have the copy that's on disk now, so don't go loading it right away
229 mLastChecked
= CFAbsoluteTimeGetCurrent();
232 void AuthorizationDBPlist::parseConfig(CFDictionaryRef config
)
234 CFStringRef rightsKey
= CFSTR("rights");
235 CFStringRef rulesKey
= CFSTR("rules");
236 CFMutableDictionaryRef newRights
= NULL
;
237 CFMutableDictionaryRef newRules
= NULL
;
241 Syslog::alert("Failed to parse config, no config");
242 MacOSError::throwMe(errAuthorizationInternal
);
245 if (CFDictionaryContainsKey(config
, rulesKey
))
246 newRules
= reinterpret_cast<CFMutableDictionaryRef
>(const_cast<void*>(CFDictionaryGetValue(config
, rulesKey
)));
248 if (CFDictionaryContainsKey(config
, rightsKey
))
249 newRights
= reinterpret_cast<CFMutableDictionaryRef
>(const_cast<void*>(CFDictionaryGetValue(config
, rightsKey
)));
251 if (newRules
&& newRights
252 && (CFDictionaryGetTypeID() == CFGetTypeID(newRules
))
253 && (CFDictionaryGetTypeID() == CFGetTypeID(newRights
)))
255 mConfigRights
= static_cast<CFMutableDictionaryRef
>(newRights
);
256 mConfigRules
= static_cast<CFMutableDictionaryRef
>(newRules
);
259 CFDictionaryApplyFunction(newRights
, parseRule
, this);
261 Syslog::alert("Failed to parse config and apply dictionary function");
262 MacOSError::throwMe(errAuthorizationInternal
); // XXX/cs invalid rule file
268 Syslog::alert("Failed to parse config, invalid rule file");
269 MacOSError::throwMe(errAuthorizationInternal
); // XXX/cs invalid rule file
273 void AuthorizationDBPlist::parseRule(const void *key
, const void *value
, void *context
)
275 static_cast<AuthorizationDBPlist
*>(context
)->addRight(static_cast<CFStringRef
>(key
), static_cast<CFDictionaryRef
>(value
));
278 void AuthorizationDBPlist::addRight(CFStringRef key
, CFDictionaryRef definition
)
280 string keyString
= cfString(key
);
281 mRules
[keyString
] = Rule(keyString
, definition
, mConfigRules
);
285 AuthorizationDBPlist::validateRule(string inRightName
, CFDictionaryRef inRightDefinition
) const
288 0 == CFDictionaryGetCount(mConfigRules
)) {
289 Syslog::error("No rule definitions!");
290 MacOSError::throwMe(errAuthorizationInternal
);
293 Rule
newRule(inRightName
, inRightDefinition
, mConfigRules
);
294 if (newRule
->name() == inRightName
)
297 secdebug("authrule", "invalid definition for rule %s.\n",
298 inRightName
.c_str());
304 AuthorizationDBPlist::getRuleDefinition(string
&key
)
306 if (!mConfigRights
||
307 0 == CFDictionaryGetCount(mConfigRights
)) {
308 Syslog::error("No rule definitions!");
309 MacOSError::throwMe(errAuthorizationInternal
);
311 CFStringRef cfKey
= makeCFString(key
);
312 StLock
<Mutex
> _(mLock
);
313 if (CFDictionaryContainsKey(mConfigRights
, cfKey
)) {
314 CFDictionaryRef definition
= reinterpret_cast<CFMutableDictionaryRef
>(const_cast<void*>(CFDictionaryGetValue(mConfigRights
, cfKey
)));
316 return CFDictionaryCreateCopy(NULL
, definition
);
324 AuthorizationDBPlist::existRule(string
&ruleName
) const
326 AuthItemRef
candidateRule(ruleName
.c_str());
327 string ruleForCandidate
= getRule(candidateRule
)->name();
328 // same name or covered by wildcard right -> modification.
329 if ( (ruleName
== ruleForCandidate
) ||
330 (*(ruleForCandidate
.rbegin()) == '.') )
337 AuthorizationDBPlist::getRule(const AuthItemRef
&inRight
) const
339 string
key(inRight
->name());
341 StLock
<Mutex
> _(mLock
);
343 secdebug("authdb", "looking up rule %s.", inRight
->name());
348 map
<string
,Rule
>::const_iterator rule
= mRules
.find(key
);
350 if (rule
!= mRules
.end())
351 return (*rule
).second
;
356 // any reduction of a combination of two chars is futile
357 if (key
.size() > 2) {
358 // find last dot with exception of possible dot at end
359 string::size_type index
= key
.rfind('.', key
.size() - 2);
360 // cut right after found dot, or make it match default rule
361 key
= key
.substr(0, index
== string::npos
? 0 : index
+ 1);
368 AuthorizationDBPlist::setRule(const char *inRightName
, CFDictionaryRef inRuleDefinition
)
370 // if mConfig is now a reasonable guard
371 if (!inRuleDefinition
|| !mConfigRights
)
373 Syslog::alert("Failed to set rule, no definition or rights");
374 MacOSError::throwMe(errAuthorizationDenied
); // ???/gh errAuthorizationInternal instead?
377 CFRef
<CFStringRef
> keyRef(CFStringCreateWithCString(NULL
, inRightName
,
378 kCFStringEncodingASCII
));
383 StLock
<Mutex
> _(mLock
);
384 secdebug("authdb", "setting up rule %s.", inRightName
);
385 CFDictionarySetValue(mConfigRights
, keyRef
, inRuleDefinition
);
387 parseConfig(mConfig
);
392 AuthorizationDBPlist::removeRule(const char *inRightName
)
394 // if mConfig is now a reasonable guard
397 Syslog::alert("Failed to remove rule, no rights");
398 MacOSError::throwMe(errAuthorizationDenied
); // ???/gh errAuthorizationInternal instead?
401 CFRef
<CFStringRef
> keyRef(CFStringCreateWithCString(NULL
, inRightName
,
402 kCFStringEncodingASCII
));
407 StLock
<Mutex
> _(mLock
);
408 secdebug("authdb", "removing rule %s.", inRightName
);
409 CFDictionaryRemoveValue(mConfigRights
, keyRef
);
411 parseConfig(mConfig
);
416 } // end namespace Authorization