]> git.saurik.com Git - apple/securityd.git/blob - src/server.cpp
securityd-36975.tar.gz
[apple/securityd.git] / src / server.cpp
1 /*
2 * Copyright (c) 2000-2004,2009 Apple 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 // server - securityd main server object
27 //
28 #include <securityd_client/ucsp.h> // MIG ucsp service
29 #include "self.h" // MIG self service
30 #include <security_utilities/logging.h>
31 #include <security_cdsa_client/mdsclient.h>
32 #include "server.h"
33 #include "session.h"
34 #include "acls.h"
35 #include "notifications.h"
36 #include "child.h"
37 #include <mach/mach_error.h>
38 #include <security_utilities/ccaudit.h>
39 #include "pcscmonitor.h"
40
41 #include "agentquery.h"
42
43
44 using namespace MachPlusPlus;
45
46 //
47 // Construct an Authority
48 //
49 Authority::Authority(const char *configFile)
50 : Authorization::Engine(configFile)
51 {
52 }
53
54 Authority::~Authority()
55 {
56 }
57
58
59 //
60 // Construct the server object
61 //
62 Server::Server(Authority &authority, CodeSignatures &signatures, const char *bootstrapName)
63 : MachServer(bootstrapName),
64 mBootstrapName(bootstrapName),
65 mCSPModule(gGuidAppleCSP, mCssm), mCSP(mCSPModule),
66 mAuthority(authority),
67 mCodeSignatures(signatures),
68 mAudit(geteuid(), getpid()),
69 mVerbosity(0),
70 mWaitForClients(true), mShuttingDown(false)
71 {
72 // make me eternal (in the object mesh)
73 ref();
74
75 mAudit.registerSession();
76
77 // engage the subsidiary port handler for sleep notifications
78 add(sleepWatcher);
79 }
80
81
82 //
83 // Clean up the server object
84 //
85 Server::~Server()
86 {
87 //@@@ more later
88 }
89
90
91 //
92 // Locate a connection by reply port and make it the current connection
93 // of this thread. The connection will be marked busy, and can be accessed
94 // by calling Server::connection() [no argument] until it is released by
95 // calling Connection::endWork().
96 //
97 Connection &Server::connection(mach_port_t port, audit_token_t &auditToken)
98 {
99 Server &server = active();
100 StLock<Mutex> _(server);
101 Connection *conn = server.mConnections.get(port, CSSM_ERRCODE_INVALID_CONTEXT_HANDLE);
102 active().mCurrentConnection() = conn;
103 conn->beginWork(auditToken);
104 return *conn;
105 }
106
107 Connection &Server::connection(bool tolerant)
108 {
109 Connection *conn = active().mCurrentConnection();
110 assert(conn); // have to have one
111 if (!tolerant)
112 conn->checkWork();
113 return *conn;
114 }
115
116 void Server::requestComplete(CSSM_RETURN &rcode)
117 {
118 // note: there may not be an active connection if connection setup failed
119 if (RefPointer<Connection> &conn = active().mCurrentConnection()) {
120 conn->endWork(rcode);
121 conn = NULL;
122 }
123 IFDUMPING("state", NodeCore::dumpAll());
124 }
125
126
127 //
128 // Shorthand for "current" process and session.
129 // This is the process and session for the current connection.
130 //
131 Process &Server::process()
132 {
133 return connection().process();
134 }
135
136 Session &Server::session()
137 {
138 return connection().process().session();
139 }
140
141 RefPointer<Key> Server::key(KeyHandle key)
142 {
143 return U32HandleObject::findRef<Key>(key, CSSMERR_CSP_INVALID_KEY_REFERENCE);
144 }
145
146 RefPointer<Database> Server::database(DbHandle db)
147 {
148 return find<Database>(db, CSSMERR_DL_INVALID_DB_HANDLE);
149 }
150
151 RefPointer<KeychainDatabase> Server::keychain(DbHandle db)
152 {
153 return find<KeychainDatabase>(db, CSSMERR_DL_INVALID_DB_HANDLE);
154 }
155
156 RefPointer<Database> Server::optionalDatabase(DbHandle db, bool persistent)
157 {
158 if (persistent && db != noDb)
159 return database(db);
160 else
161 return &process().localStore();
162 }
163
164
165 //
166 // Locate an ACL bearer (database or key) by handle
167 // The handle might be used across IPC, so we clamp it accordingly
168 //
169 AclSource &Server::aclBearer(AclKind kind, U32HandleObject::Handle handle)
170 {
171 AclSource &bearer = U32HandleObject::find<AclSource>(handle, CSSMERR_CSSM_INVALID_ADDIN_HANDLE);
172 if (kind != bearer.acl().aclKind())
173 CssmError::throwMe(CSSMERR_CSSM_INVALID_HANDLE_USAGE);
174 return bearer;
175 }
176
177
178 //
179 // Run the server. This will not return until the server is forced to exit.
180 //
181 void Server::run()
182 {
183 MachServer::run(0x10000,
184 MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) |
185 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT));
186 }
187
188
189 //
190 // Handle thread overflow. MachServer will call this if it has hit its thread
191 // limit and yet still needs another thread.
192 //
193 void Server::threadLimitReached(UInt32 limit)
194 {
195 Syslog::notice("securityd has reached its thread limit (%ld) - service deadlock is possible",
196 limit);
197 }
198
199
200 //
201 // The primary server run-loop function.
202 // Invokes the MIG-generated main dispatch function (ucsp_server), as well
203 // as the self-send dispatch (self_server).
204 // For debug builds, look up request names in a MIG-generated table
205 // for better debug-log messages.
206 //
207 boolean_t ucsp_server(mach_msg_header_t *, mach_msg_header_t *);
208 boolean_t self_server(mach_msg_header_t *, mach_msg_header_t *);
209
210
211 boolean_t Server::handle(mach_msg_header_t *in, mach_msg_header_t *out)
212 {
213 return ucsp_server(in, out) || self_server(in, out);
214 }
215
216
217 //
218 // Set up a new Connection. This establishes the environment (process et al) as needed
219 // and registers a properly initialized Connection object to run with.
220 // Type indicates how "deep" we need to initialize (new session, process, or connection).
221 // Everything at and below that level is constructed. This is straight-forward except
222 // in the case of session re-initialization (see below).
223 //
224 void Server::setupConnection(ConnectLevel type, Port servicePort, Port replyPort, Port taskPort,
225 const audit_token_t &auditToken, const ClientSetupInfo *info, const char *identity)
226 {
227 // first, make or find the process based on task port
228 StLock<Mutex> _(*this);
229 RefPointer<Process> &proc = mProcesses[taskPort];
230 if (type == connectNewSession && proc) {
231 // The client has talked to us before and now wants to create a new session.
232 proc->changeSession(servicePort);
233 }
234 if (proc && type == connectNewProcess) {
235 // the client has amnesia - reset it
236 assert(info && identity);
237 proc->reset(servicePort, taskPort, info, identity, AuditToken(auditToken));
238 proc->changeSession(servicePort);
239 }
240 if (!proc) {
241 if (type == connectNewThread) // client error (or attack)
242 CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR);
243 assert(info && identity);
244 proc = new Process(servicePort, taskPort, info, identity, AuditToken(auditToken));
245 notifyIfDead(taskPort);
246 mPids[proc->pid()] = proc;
247 }
248
249 // now, establish a connection and register it in the server
250 Connection *connection = new Connection(*proc, replyPort);
251 if (mConnections.contains(replyPort)) // malicious re-entry attempt?
252 CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); //@@@ error code? (client error)
253 mConnections[replyPort] = connection;
254 notifyIfDead(replyPort);
255 }
256
257
258 //
259 // Synchronously end a Connection.
260 // This is due to a request from the client, so no thread races are possible.
261 // In practice, this is optional since the DPN for the client thread reply port
262 // will destroy the connection anyway when the thread dies.
263 //
264 void Server::endConnection(Port replyPort)
265 {
266 StLock<Mutex> _(*this);
267 PortMap<Connection>::iterator it = mConnections.find(replyPort);
268 assert(it != mConnections.end());
269 it->second->terminate();
270 mConnections.erase(it);
271 }
272
273
274 //
275 // Handling dead-port notifications.
276 // This receives DPNs for all kinds of ports we're interested in.
277 //
278 void Server::notifyDeadName(Port port)
279 {
280 StLock<Mutex> _(*this);
281 secdebug("SSports", "port %d is dead", port.port());
282
283 // is it a connection?
284 PortMap<Connection>::iterator conIt = mConnections.find(port);
285 if (conIt != mConnections.end()) {
286 SECURITYD_PORTS_DEAD_CONNECTION(port);
287 conIt->second->abort();
288 mConnections.erase(conIt);
289 return;
290 }
291
292 // is it a process?
293 PortMap<Process>::iterator procIt = mProcesses.find(port);
294 if (procIt != mProcesses.end()) {
295 SECURITYD_PORTS_DEAD_PROCESS(port);
296 Process *proc = procIt->second;
297 proc->kill();
298 mPids.erase(proc->pid());
299 mProcesses.erase(procIt);
300 return;
301 }
302
303 // well, what IS IT?!
304 SECURITYD_PORTS_DEAD_ORPHAN(port);
305 secdebug("server", "spurious dead port notification for port %d", port.port());
306 }
307
308
309 //
310 // Handling no-senders notifications.
311 // This is currently only used for (subsidiary) service ports
312 //
313 void Server::notifyNoSenders(Port port, mach_port_mscount_t)
314 {
315 SECURITYD_PORTS_DEAD_SESSION(port);
316 secdebug("SSports", "port %d no senders", port.port());
317 Session::destroy(port);
318 }
319
320
321 //
322 // Handling signals.
323 // These are sent as Mach messages from ourselves to escape the limitations of
324 // the signal handler environment.
325 //
326 kern_return_t self_server_handleSignal(mach_port_t sport,
327 mach_port_t taskPort, int sig)
328 {
329 try {
330 SECURITYD_SIGNAL_HANDLED(sig);
331 if (taskPort != mach_task_self()) {
332 Syslog::error("handleSignal: received from someone other than myself");
333 return KERN_SUCCESS;
334 }
335 switch (sig) {
336 case SIGCHLD:
337 ServerChild::checkChildren();
338 break;
339 case SIGINT:
340 SECURITYD_SHUTDOWN_NOW();
341 Syslog::notice("securityd terminated due to SIGINT");
342 _exit(0);
343 case SIGTERM:
344 Server::active().beginShutdown();
345 break;
346 case SIGPIPE:
347 fprintf(stderr, "securityd ignoring SIGPIPE received");
348 break;
349
350 #if defined(DEBUGDUMP)
351 case SIGUSR1:
352 NodeCore::dumpAll();
353 break;
354 #endif //DEBUGDUMP
355
356 case SIGUSR2:
357 {
358 extern PCSCMonitor *gPCSC;
359 gPCSC->startSoftTokens();
360 break;
361 }
362
363 default:
364 assert(false);
365 }
366 } catch(...) {
367 secdebug("SS", "exception handling a signal (ignored)");
368 }
369 mach_port_deallocate(mach_task_self(), taskPort);
370 return KERN_SUCCESS;
371 }
372
373
374 //
375 // Notifier for system sleep events
376 //
377 void Server::SleepWatcher::systemWillSleep()
378 {
379 SECURITYD_POWER_SLEEP();
380 Session::processSystemSleep();
381 for (set<PowerWatcher *>::const_iterator it = mPowerClients.begin(); it != mPowerClients.end(); it++)
382 (*it)->systemWillSleep();
383 }
384
385 void Server::SleepWatcher::systemIsWaking()
386 {
387 SECURITYD_POWER_WAKE();
388 for (set<PowerWatcher *>::const_iterator it = mPowerClients.begin(); it != mPowerClients.end(); it++)
389 (*it)->systemIsWaking();
390 }
391
392 void Server::SleepWatcher::systemWillPowerOn()
393 {
394 SECURITYD_POWER_ON();
395 Server::active().longTermActivity();
396 for (set<PowerWatcher *>::const_iterator it = mPowerClients.begin(); it != mPowerClients.end(); it++)
397 (*it)->systemWillPowerOn();
398 }
399
400 void Server::SleepWatcher::add(PowerWatcher *client)
401 {
402 assert(mPowerClients.find(client) == mPowerClients.end());
403 mPowerClients.insert(client);
404 }
405
406 void Server::SleepWatcher::remove(PowerWatcher *client)
407 {
408 assert(mPowerClients.find(client) != mPowerClients.end());
409 mPowerClients.erase(client);
410 }
411
412
413 //
414 // Expose the process/pid map to the outside
415 //
416 Process *Server::findPid(pid_t pid) const
417 {
418 PidMap::const_iterator it = mPids.find(pid);
419 return (it == mPids.end()) ? NULL : it->second;
420 }
421
422
423 //
424 // Set delayed shutdown mode
425 //
426 void Server::waitForClients(bool waiting)
427 {
428 mWaitForClients = waiting;
429 }
430
431
432 //
433 // Begin shutdown processing.
434 // We relinquish our primary state authority. From now on, we'll be
435 // kept alive (only) by our current clients.
436 //
437 static FILE *reportFile;
438
439 void Server::beginShutdown()
440 {
441 StLock<Mutex> _(*this);
442 if (!mWaitForClients) {
443 SECURITYD_SHUTDOWN_NOW();
444 _exit(0);
445 } else {
446 if (!mShuttingDown) {
447 mShuttingDown = true;
448 Session::invalidateAuthHosts();
449 SECURITYD_SHUTDOWN_BEGIN();
450 if (verbosity() >= 2) {
451 reportFile = fopen("/var/log/securityd-shutdown.log", "w");
452 shutdownSnitch();
453 }
454 }
455 }
456 }
457
458
459 //
460 // During shutdown, we report residual clients to dtrace, and allow a state dump
461 // for debugging.
462 // We don't bother locking for the shuttingDown() check; it's a latching boolean
463 // and we'll be good enough without a lock.
464 //
465 void Server::eventDone()
466 {
467 if (this->shuttingDown()) {
468 StLock<Mutex> lazy(*this, false); // lazy lock acquisition
469 if (SECURITYD_SHUTDOWN_COUNT_ENABLED()) {
470 lazy.lock();
471 SECURITYD_SHUTDOWN_COUNT(mProcesses.size(), VProc::Transaction::debugCount());
472 }
473 if (verbosity() >= 2) {
474 lazy.lock();
475 shutdownSnitch();
476 }
477 IFDUMPING("shutdown", NodeCore::dumpAll());
478 }
479 }
480
481
482 void Server::shutdownSnitch()
483 {
484 time_t now;
485 time(&now);
486 fprintf(reportFile, "%.24s %d residual clients:\n", ctime(&now), int(mPids.size()));
487 for (PidMap::const_iterator it = mPids.begin(); it != mPids.end(); ++it)
488 if (SecCodeRef clientCode = it->second->processCode()) {
489 CFRef<CFURLRef> path;
490 OSStatus rc = SecCodeCopyPath(clientCode, kSecCSDefaultFlags, &path.aref());
491 if (path)
492 fprintf(reportFile, " %s (%d)\n", cfString(path).c_str(), it->first);
493 else
494 fprintf(reportFile, "pid=%d (error %d)\n", it->first, int32_t(rc));
495 }
496 fprintf(reportFile, "\n");
497 fflush(reportFile);
498 }
499
500
501 //
502 // Initialize the CSSM/MDS subsystem.
503 // This was once done lazily on demand. These days, we are setting up the
504 // system MDS here, and CSSM is pretty much always needed, so this is called
505 // early during program startup. Do note that the server may not (yet) be running.
506 //
507 void Server::loadCssm(bool mdsIsInstalled)
508 {
509 if (!mCssm->isActive()) {
510 StLock<Mutex> _(*this);
511 VProc::Transaction xact;
512 if (!mCssm->isActive()) {
513 if (!mdsIsInstalled) { // non-system securityd instance should not reinitialize MDS
514 secdebug("SS", "Installing MDS");
515 IFDEBUG(if (geteuid() == 0))
516 MDSClient::mds().install();
517 }
518 secdebug("SS", "CSSM initializing");
519 mCssm->init();
520 mCSP->attach();
521 secdebug("SS", "CSSM ready with CSP %s", mCSP->guid().toString().c_str());
522 }
523 }
524 }
525
526
527 //
528 // LongtermActivity/lock combo
529 //
530 LongtermStLock::LongtermStLock(Mutex &lck)
531 : StLock<Mutex>(lck, false) // don't take the lock yet
532 {
533 if (lck.tryLock()) { // uncontested
534 this->mActive = true;
535 } else { // contested - need backup thread
536 Server::active().longTermActivity();
537 this->lock();
538 }
539 }