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@
26 // codesigdb - code-hash equivalence database
28 #include "codesigdb.h"
31 #include "agentquery.h"
32 #include <security_utilities/memutils.h>
33 #include <security_utilities/logging.h>
37 // A self-constructing database key class.
38 // Key format is <t><uid|S><key data>
40 // <t> single ASCII character type code ('H' for hash links)
41 // <uid|S> decimal userid of owning user, or 'S' for system entries. Followed by null byte.
42 // <key data> variable length key value (binary).
44 class DbKey
: public CssmAutoData
{
46 DbKey(char type
, const CssmData
&key
, bool perUser
= false, uid_t user
= 0);
49 DbKey::DbKey(char type
, const CssmData
&key
, bool perUser
, uid_t user
)
50 : CssmAutoData(Allocator::standard())
52 using namespace LowLevelMemoryUtilities
;
56 headerLength
= 1 + sprintf(header
, "%c%d", type
, user
);
58 headerLength
= 1 + sprintf(header
, "%cS", type
);
59 malloc(headerLength
+ key
.length());
60 memcpy(this->data(), header
, headerLength
);
61 memcpy(get().at(headerLength
), key
.data(), key
.length());
66 // A subclass of Identity made of whole cloth (from a raw CodeSignature ACL information)
68 class AclIdentity
: public CodeSignatures::Identity
{
70 AclIdentity(const CodeSigning::Signature
*sig
, const char *comment
)
71 : mHash(*sig
), mPath(comment
? comment
: "") { }
72 AclIdentity(const CssmData
&hash
, const char *comment
)
73 : mHash(hash
), mPath(comment
? comment
: "") { }
76 std::string
getPath() const { return mPath
; }
77 const CssmData
getHash(CodeSigning::OSXSigner
&) const { return mHash
; }
86 // Construct a CodeSignatures objects
88 CodeSignatures::CodeSignatures(const char *path
)
91 mDb
.open(path
, O_RDWR
| O_CREAT
, 0644);
92 } catch (const CommonError
&err
) {
94 mDb
.open(path
, O_RDONLY
, 0644);
95 Syslog::warning("database %s opened READONLY (R/W failed errno=%d)", path
, err
.unixError());
96 secdebug("codesign", "database %s opened READONLY (R/W failed errno=%d)", path
, err
.unixError());
98 Syslog::warning("cannot open %s; using no code equivalents", path
);
99 secdebug("codesign", "unable to open %s; using no code equivalents", path
);
103 mDb
.flush(); // in case we just created it
104 IFDUMPING("equiv", debugDump("open"));
107 CodeSignatures::~CodeSignatures()
113 // (Re)open the equivalence database.
114 // This is useful to switch to database in another volume.
116 void CodeSignatures::open(const char *path
)
118 mDb
.open(path
, O_RDWR
| O_CREAT
, 0644);
120 IFDUMPING("equiv", debugDump("reopen"));
125 // Basic Identity objects
127 CodeSignatures::Identity::Identity() : mState(untried
)
130 CodeSignatures::Identity::~Identity()
133 string
CodeSignatures::Identity::canonicalName(const string
&path
)
135 string::size_type slash
= path
.rfind('/');
136 if (slash
== string::npos
) // bloody unlikely, but whatever...
138 return path
.substr(slash
+1);
143 // Find and store database objects (primitive layer)
145 bool CodeSignatures::find(Identity
&id
, uid_t user
)
147 if (id
.mState
!= Identity::untried
)
148 return id
.mState
== Identity::valid
;
150 DbKey
userKey('H', id
.getHash(mSigner
), true, user
);
152 if (mDb
.get(userKey
, linkValue
)) {
153 id
.mName
= string(linkValue
.interpretedAs
<const char>(), linkValue
.length());
154 IFDUMPING("equiv", id
.debugDump("found/user"));
155 id
.mState
= Identity::valid
;
158 DbKey
sysKey('H', id
.getHash(mSigner
));
159 if (mDb
.get(sysKey
, linkValue
)) {
160 id
.mName
= string(linkValue
.interpretedAs
<const char>(), linkValue
.length());
161 IFDUMPING("equiv", id
.debugDump("found/system"));
162 id
.mState
= Identity::valid
;
166 secdebug("codesign", "exception validating identity for %s - marking failed", id
.path().c_str());
167 id
.mState
= Identity::invalid
;
169 return id
.mState
== Identity::valid
;
172 void CodeSignatures::makeLink(Identity
&id
, const string
&ident
, bool forUser
, uid_t user
)
174 DbKey
key('H', id
.getHash(mSigner
), forUser
, user
);
175 if (!mDb
.put(key
, StringData(ident
)))
176 UnixError::throwMe();
179 void CodeSignatures::makeApplication(const std::string
&name
, const std::string
&path
)
181 //@@@ create app record and fill (later)
186 // Administrative manipulation calls
188 void CodeSignatures::addLink(const CssmData
&oldHash
, const CssmData
&newHash
,
189 const char *inName
, bool forSystem
)
191 string name
= Identity::canonicalName(inName
);
192 uid_t user
= Server::process().uid();
193 if (forSystem
&& user
) // only root user can establish forSystem links
194 UnixError::throwMe(EACCES
);
195 if (!forSystem
) // in fact, for now we don't allow per-user calls at all
196 UnixError::throwMe(EACCES
);
197 AclIdentity
oldCode(oldHash
, name
.c_str());
198 AclIdentity
newCode(newHash
, name
.c_str());
199 secdebug("codesign", "addlink for name %s", name
.c_str());
200 StLock
<Mutex
> _(mDatabaseLock
);
202 if (oldCode
.trustedName() != name
) {
203 secdebug("codesign", "addlink does not match existing name %s",
204 oldCode
.trustedName().c_str());
205 MacOSError::throwMe(CSSMERR_CSP_VERIFY_FAILED
);
208 makeLink(oldCode
, name
, !forSystem
, user
);
211 makeLink(newCode
, name
, !forSystem
, user
);
215 void CodeSignatures::removeLink(const CssmData
&hash
, const char *name
, bool forSystem
)
217 AclIdentity
code(hash
, name
);
218 uid_t user
= Server::process().uid();
219 if (forSystem
&& user
) // only root user can remove forSystem links
220 UnixError::throwMe(EACCES
);
221 DbKey
key('H', hash
, !forSystem
, user
);
222 StLock
<Mutex
> _(mDatabaseLock
);
229 // Verify signature matches
231 bool CodeSignatures::verify(Process
&process
,
232 const CodeSigning::Signature
*trustedSignature
, const CssmData
*comment
)
234 secdebug("codesign", "start verify");
236 // if we have no client code, we cannot possibly match this
237 if (!process
.clientCode()) {
238 secdebug("codesign", "no code base: fail");
242 // first of all, if the signature directly matches the client's code, we're obviously fine
243 // we don't even need the database for that...
244 Identity
&clientIdentity
= process
;
246 if (clientIdentity
.getHash(mSigner
) == CssmData(*trustedSignature
)) {
247 secdebug("codesign", "direct match: pass");
251 secdebug("codesign", "exception getting client code hash: fail");
255 // ah well. Establish mediator objects for database signature links
256 AclIdentity
aclIdentity(trustedSignature
, comment
? comment
->interpretedAs
<const char>() : NULL
);
258 uid_t user
= process
.uid();
260 StLock
<Mutex
> _(mDatabaseLock
);
261 find(aclIdentity
, user
);
262 find(clientIdentity
, user
);
265 // if both links exist, we can decide this right now
266 if (aclIdentity
&& clientIdentity
) {
267 if (aclIdentity
.trustedName() == clientIdentity
.trustedName()) {
268 secdebug("codesign", "app references match: pass");
271 secdebug("codesign", "client/acl links exist but are unequal: fail");
276 // check for name equality
277 secdebug("codesign", "matching client %s against acl %s",
278 clientIdentity
.name().c_str(), aclIdentity
.name().c_str());
279 if (aclIdentity
.name() != clientIdentity
.name()) {
280 secdebug("codesign", "name/path mismatch: fail");
284 // The names match - we have a possible update.
286 // Take the UI lock now to serialize "update rushes".
287 Server::active().longTermActivity();
288 StLock
<Mutex
> uiLocker(mUILock
);
290 // re-read the database in case some other thread beat us to the update
292 StLock
<Mutex
> _(mDatabaseLock
);
293 find(aclIdentity
, user
);
294 find(clientIdentity
, user
);
296 if (aclIdentity
&& clientIdentity
) {
297 if (aclIdentity
.trustedName() == clientIdentity
.trustedName()) {
298 secdebug("codesign", "app references match: pass (on the rematch)");
301 secdebug("codesign", "client/acl links exist but are unequal: fail (on the rematch)");
307 QueryCodeCheck query
;
308 query
.inferHints(process
);
309 if (!query(aclIdentity
.path().c_str()))
311 secdebug("codesign", "user declined equivalence: fail");
315 // take the database lock back for real
316 StLock
<Mutex
> _(mDatabaseLock
);
318 // user wants us to go ahead and establish trust (if possible)
320 // acl is linked but new client: link the client to this application
321 makeLink(clientIdentity
, aclIdentity
.trustedName(), true, user
);
323 secdebug("codesign", "client %s linked to application %s: pass",
324 clientIdentity
.path().c_str(), aclIdentity
.trustedName().c_str());
328 if (clientIdentity
) { // code link exists, acl link missing
329 // client is linked but ACL (hash) never seen: link the ACL to this app
330 makeLink(aclIdentity
, clientIdentity
.trustedName(), true, user
);
332 secdebug("codesign", "acl %s linked to client %s: pass",
333 aclIdentity
.path().c_str(), clientIdentity
.trustedName().c_str());
337 // the De Novo case: no links, must create everything
338 string ident
= clientIdentity
.name();
339 makeApplication(ident
, clientIdentity
.path());
340 makeLink(clientIdentity
, ident
, true, user
);
341 makeLink(aclIdentity
, ident
, true, user
);
343 secdebug("codesign", "new linkages established: pass");
349 // Debug dumping support
351 #if defined(DEBUGDUMP)
353 void CodeSignatures::debugDump(const char *how
) const
355 using namespace Debug
;
356 using namespace LowLevelMemoryUtilities
;
360 if (!mDb
.first(key
, value
)) {
361 dump("CODE EQUIVALENTS DATABASE IS EMPTY (%s)\n", how
);
363 dump("CODE EQUIVALENTS DATABASE DUMP (%s)\n", how
);
365 const char *header
= key
.interpretedAs
<const char>();
366 size_t headerLength
= strlen(header
) + 1;
368 dumpData(key
.at(headerLength
), key
.length() - headerLength
);
372 } while (mDb
.next(key
, value
));
377 void CodeSignatures::Identity::debugDump(const char *how
) const
379 using namespace Debug
;
382 dump("IDENTITY (%s) path=%s", how
, getPath().c_str());
383 dump(" name=%s hash=", mName
.empty() ? "(unset)" : mName
.c_str());
384 CodeSigning::OSXSigner signer
;
385 dumpData(getHash(signer
));