]> git.saurik.com Git - apple/securityd.git/blob - src/codesigdb.cpp
securityd-27887.tar.gz
[apple/securityd.git] / src / codesigdb.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
24
25 //
26 // codesigdb - code-hash equivalence database
27 //
28 #include "codesigdb.h"
29 #include "process.h"
30 #include "server.h"
31 #include "agentquery.h"
32 #include <security_utilities/memutils.h>
33 #include <security_utilities/logging.h>
34
35
36 //
37 // A self-constructing database key class.
38 // Key format is <t><uid|S><key data>
39 // where
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).
43 //
44 class DbKey : public CssmAutoData {
45 public:
46 DbKey(char type, const CssmData &key, bool perUser = false, uid_t user = 0);
47 };
48
49 DbKey::DbKey(char type, const CssmData &key, bool perUser, uid_t user)
50 : CssmAutoData(Allocator::standard())
51 {
52 using namespace LowLevelMemoryUtilities;
53 char header[20];
54 size_t headerLength;
55 if (perUser)
56 headerLength = 1 + sprintf(header, "%c%d", type, user);
57 else
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());
62 }
63
64
65 //
66 // A subclass of Identity made of whole cloth (from a raw CodeSignature ACL information)
67 //
68 class AclIdentity : public CodeSignatures::Identity {
69 public:
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 : "") { }
74
75 protected:
76 std::string getPath() const { return mPath; }
77 const CssmData getHash(CodeSigning::OSXSigner &) const { return mHash; }
78
79 private:
80 const CssmData mHash;
81 std::string mPath;
82 };
83
84
85 //
86 // Construct a CodeSignatures objects
87 //
88 CodeSignatures::CodeSignatures(const char *path)
89 {
90 try {
91 mDb.open(path, O_RDWR | O_CREAT, 0644);
92 } catch (const CommonError &err) {
93 try {
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());
97 } catch (...) {
98 Syslog::warning("cannot open %s; using no code equivalents", path);
99 secdebug("codesign", "unable to open %s; using no code equivalents", path);
100 }
101 }
102 if (mDb)
103 mDb.flush(); // in case we just created it
104 IFDUMPING("equiv", debugDump("open"));
105 }
106
107 CodeSignatures::~CodeSignatures()
108 {
109 }
110
111
112 //
113 // (Re)open the equivalence database.
114 // This is useful to switch to database in another volume.
115 //
116 void CodeSignatures::open(const char *path)
117 {
118 mDb.open(path, O_RDWR | O_CREAT, 0644);
119 mDb.flush();
120 IFDUMPING("equiv", debugDump("reopen"));
121 }
122
123
124 //
125 // Basic Identity objects
126 //
127 CodeSignatures::Identity::Identity() : mState(untried)
128 { }
129
130 CodeSignatures::Identity::~Identity()
131 { }
132
133 string CodeSignatures::Identity::canonicalName(const string &path)
134 {
135 string::size_type slash = path.rfind('/');
136 if (slash == string::npos) // bloody unlikely, but whatever...
137 return path;
138 return path.substr(slash+1);
139 }
140
141
142 //
143 // Find and store database objects (primitive layer)
144 //
145 bool CodeSignatures::find(Identity &id, uid_t user)
146 {
147 if (id.mState != Identity::untried)
148 return id.mState == Identity::valid;
149 try {
150 DbKey userKey('H', id.getHash(mSigner), true, user);
151 CssmData linkValue;
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;
156 return true;
157 }
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;
163 return true;
164 }
165 } catch (...) {
166 secdebug("codesign", "exception validating identity for %s - marking failed", id.path().c_str());
167 id.mState = Identity::invalid;
168 }
169 return id.mState == Identity::valid;
170 }
171
172 void CodeSignatures::makeLink(Identity &id, const string &ident, bool forUser, uid_t user)
173 {
174 DbKey key('H', id.getHash(mSigner), forUser, user);
175 if (!mDb.put(key, StringData(ident)))
176 UnixError::throwMe();
177 }
178
179 void CodeSignatures::makeApplication(const std::string &name, const std::string &path)
180 {
181 //@@@ create app record and fill (later)
182 }
183
184
185 //
186 // Administrative manipulation calls
187 //
188 void CodeSignatures::addLink(const CssmData &oldHash, const CssmData &newHash,
189 const char *inName, bool forSystem)
190 {
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);
201 if (oldCode) {
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);
206 }
207 } else {
208 makeLink(oldCode, name, !forSystem, user);
209 }
210 if (!newCode)
211 makeLink(newCode, name, !forSystem, user);
212 mDb.flush();
213 }
214
215 void CodeSignatures::removeLink(const CssmData &hash, const char *name, bool forSystem)
216 {
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);
223 mDb.erase(key);
224 mDb.flush();
225 }
226
227
228 //
229 // Verify signature matches
230 //
231 bool CodeSignatures::verify(Process &process,
232 const CodeSigning::Signature *trustedSignature, const CssmData *comment)
233 {
234 secdebug("codesign", "start verify");
235
236 // if we have no client code, we cannot possibly match this
237 if (!process.clientCode()) {
238 secdebug("codesign", "no code base: fail");
239 return false;
240 }
241
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;
245 try {
246 if (clientIdentity.getHash(mSigner) == CssmData(*trustedSignature)) {
247 secdebug("codesign", "direct match: pass");
248 return true;
249 }
250 } catch (...) {
251 secdebug("codesign", "exception getting client code hash: fail");
252 return false;
253 }
254
255 // ah well. Establish mediator objects for database signature links
256 AclIdentity aclIdentity(trustedSignature, comment ? comment->interpretedAs<const char>() : NULL);
257
258 uid_t user = process.uid();
259 {
260 StLock<Mutex> _(mDatabaseLock);
261 find(aclIdentity, user);
262 find(clientIdentity, user);
263 }
264
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");
269 return true;
270 } else {
271 secdebug("codesign", "client/acl links exist but are unequal: fail");
272 return false;
273 }
274 }
275
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");
281 return false;
282 }
283
284 // The names match - we have a possible update.
285
286 // Take the UI lock now to serialize "update rushes".
287 Server::active().longTermActivity();
288 StLock<Mutex> uiLocker(mUILock);
289
290 // re-read the database in case some other thread beat us to the update
291 {
292 StLock<Mutex> _(mDatabaseLock);
293 find(aclIdentity, user);
294 find(clientIdentity, user);
295 }
296 if (aclIdentity && clientIdentity) {
297 if (aclIdentity.trustedName() == clientIdentity.trustedName()) {
298 secdebug("codesign", "app references match: pass (on the rematch)");
299 return true;
300 } else {
301 secdebug("codesign", "client/acl links exist but are unequal: fail (on the rematch)");
302 return false;
303 }
304 }
305
306 // ask the user
307 QueryCodeCheck query;
308 query.inferHints(process);
309 if (!query(aclIdentity.path().c_str()))
310 {
311 secdebug("codesign", "user declined equivalence: fail");
312 return false;
313 }
314
315 // take the database lock back for real
316 StLock<Mutex> _(mDatabaseLock);
317
318 // user wants us to go ahead and establish trust (if possible)
319 if (aclIdentity) {
320 // acl is linked but new client: link the client to this application
321 makeLink(clientIdentity, aclIdentity.trustedName(), true, user);
322 mDb.flush();
323 secdebug("codesign", "client %s linked to application %s: pass",
324 clientIdentity.path().c_str(), aclIdentity.trustedName().c_str());
325 return true;
326 }
327
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);
331 mDb.flush();
332 secdebug("codesign", "acl %s linked to client %s: pass",
333 aclIdentity.path().c_str(), clientIdentity.trustedName().c_str());
334 return true;
335 }
336
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);
342 mDb.flush();
343 secdebug("codesign", "new linkages established: pass");
344 return true;
345 }
346
347
348 //
349 // Debug dumping support
350 //
351 #if defined(DEBUGDUMP)
352
353 void CodeSignatures::debugDump(const char *how) const
354 {
355 using namespace Debug;
356 using namespace LowLevelMemoryUtilities;
357 if (!how)
358 how = "dump";
359 CssmData key, value;
360 if (!mDb.first(key, value)) {
361 dump("CODE EQUIVALENTS DATABASE IS EMPTY (%s)\n", how);
362 } else {
363 dump("CODE EQUIVALENTS DATABASE DUMP (%s)\n", how);
364 do {
365 const char *header = key.interpretedAs<const char>();
366 size_t headerLength = strlen(header) + 1;
367 dump("%s:", header);
368 dumpData(key.at(headerLength), key.length() - headerLength);
369 dump(" => ");
370 dumpData(value);
371 dump("\n");
372 } while (mDb.next(key, value));
373 dump("END DUMP\n");
374 }
375 }
376
377 void CodeSignatures::Identity::debugDump(const char *how) const
378 {
379 using namespace Debug;
380 if (!how)
381 how = "dump";
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));
386 dump("\n");
387 }
388
389 #endif //DEBUGDUMP