2 * Copyright (c) 2000-2010,2013 Apple 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 // server - securityd main server object
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>
35 #include "notifications.h"
37 #include <mach/mach_error.h>
38 #include <security_utilities/ccaudit.h>
39 #include <security_utilities/casts.h>
40 #include "pcscmonitor.h"
42 #include "agentquery.h"
45 using namespace MachPlusPlus
;
48 // Construct the server object
50 Server::Server(CodeSignatures
&signatures
, const char *bootstrapName
)
51 : MachServer(bootstrapName
),
52 mBootstrapName(bootstrapName
),
53 mCSPModule(gGuidAppleCSP
, mCssm
), mCSP(mCSPModule
),
54 mCodeSignatures(signatures
),
56 mWaitForClients(true), mShuttingDown(false)
58 // make me eternal (in the object mesh)
61 // engage the subsidiary port handler for sleep notifications
67 // Clean up the server object
76 // Locate a connection by reply port and make it the current connection
77 // of this thread. The connection will be marked busy, and can be accessed
78 // by calling Server::connection() [no argument] until it is released by
79 // calling Connection::endWork().
81 Connection
&Server::connection(mach_port_t port
, audit_token_t
&auditToken
)
83 Server
&server
= active();
84 StLock
<Mutex
> _(server
);
85 Connection
*conn
= server
.mConnections
.get(port
, CSSM_ERRCODE_INVALID_CONTEXT_HANDLE
);
86 conn
->process().checkSession(auditToken
);
87 active().mCurrentConnection() = conn
;
88 conn
->beginWork(auditToken
);
92 Connection
&Server::connection(bool tolerant
)
94 Connection
*conn
= active().mCurrentConnection();
95 assert(conn
); // have to have one
101 void Server::requestComplete(CSSM_RETURN
&rcode
)
103 // note: there may not be an active connection if connection setup failed
104 if (RefPointer
<Connection
> &conn
= active().mCurrentConnection()) {
105 conn
->endWork(rcode
);
108 IFDUMPING("state", NodeCore::dumpAll());
113 // Shorthand for "current" process and session.
114 // This is the process and session for the current connection.
116 Process
&Server::process()
118 return connection().process();
121 Session
&Server::session()
123 return connection().process().session();
126 RefPointer
<Key
> Server::key(KeyHandle key
)
128 return U32HandleObject::findRef
<Key
>(key
, CSSMERR_CSP_INVALID_KEY_REFERENCE
);
131 RefPointer
<Database
> Server::database(DbHandle db
)
133 return find
<Database
>(db
, CSSMERR_DL_INVALID_DB_HANDLE
);
136 RefPointer
<KeychainDatabase
> Server::keychain(DbHandle db
)
138 return find
<KeychainDatabase
>(db
, CSSMERR_DL_INVALID_DB_HANDLE
);
141 RefPointer
<Database
> Server::optionalDatabase(DbHandle db
, bool persistent
)
143 if (persistent
&& db
!= noDb
)
146 return &process().localStore();
151 // Locate an ACL bearer (database or key) by handle
152 // The handle might be used across IPC, so we clamp it accordingly
154 AclSource
&Server::aclBearer(AclKind kind
, U32HandleObject::Handle handle
)
156 AclSource
&bearer
= U32HandleObject::find
<AclSource
>(handle
, CSSMERR_CSSM_INVALID_ADDIN_HANDLE
);
157 if (kind
!= bearer
.acl().aclKind())
158 CssmError::throwMe(CSSMERR_CSSM_INVALID_HANDLE_USAGE
);
164 // Run the server. This will not return until the server is forced to exit.
168 MachServer::run(0x10000,
169 MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0
) |
170 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT
));
175 // Handle thread overflow. MachServer will call this if it has hit its thread
176 // limit and yet still needs another thread.
178 void Server::threadLimitReached(UInt32 limit
)
180 Syslog::notice("securityd has reached its thread limit (%d) - service deadlock is possible",
186 // The primary server run-loop function.
187 // Invokes the MIG-generated main dispatch function (ucsp_server), as well
188 // as the self-send dispatch (self_server).
189 // For debug builds, look up request names in a MIG-generated table
190 // for better debug-log messages.
192 boolean_t
ucsp_server(mach_msg_header_t
*, mach_msg_header_t
*);
193 boolean_t
self_server(mach_msg_header_t
*, mach_msg_header_t
*);
196 boolean_t
Server::handle(mach_msg_header_t
*in
, mach_msg_header_t
*out
)
198 return ucsp_server(in
, out
) || self_server(in
, out
);
203 // Set up a new Connection. This establishes the environment (process et al) as needed
204 // and registers a properly initialized Connection object to run with.
205 // Type indicates how "deep" we need to initialize (new session, process, or connection).
206 // Everything at and below that level is constructed. This is straight-forward except
207 // in the case of session re-initialization (see below).
209 void Server::setupConnection(ConnectLevel type
, Port replyPort
, Port taskPort
,
210 const audit_token_t
&auditToken
, const ClientSetupInfo
*info
)
212 Security::CommonCriteria::AuditToken
audit(auditToken
);
214 // first, make or find the process based on task port
215 StLock
<Mutex
> _(*this);
216 RefPointer
<Process
> &proc
= mProcesses
[taskPort
];
217 if (proc
&& proc
->session().sessionId() != audit
.sessionId())
218 proc
->changeSession(audit
.sessionId());
219 if (proc
&& type
== connectNewProcess
) {
220 // the client has amnesia - reset it
222 proc
->reset(taskPort
, info
, audit
);
223 proc
->changeSession(audit
.sessionId());
226 if (type
== connectNewThread
) // client error (or attack)
227 CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR
);
229 proc
= new Process(taskPort
, info
, audit
);
230 notifyIfDead(taskPort
);
231 mPids
[proc
->pid()] = proc
;
234 // now, establish a connection and register it in the server
235 Connection
*connection
= new Connection(*proc
, replyPort
);
236 if (mConnections
.contains(replyPort
)) // malicious re-entry attempt?
237 CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR
); //@@@ error code? (client error)
238 mConnections
[replyPort
] = connection
;
239 notifyIfDead(replyPort
);
244 // Synchronously end a Connection.
245 // This is due to a request from the client, so no thread races are possible.
246 // In practice, this is optional since the DPN for the client thread reply port
247 // will destroy the connection anyway when the thread dies.
249 void Server::endConnection(Port replyPort
)
251 StLock
<Mutex
> _(*this);
252 PortMap
<Connection
>::iterator it
= mConnections
.find(replyPort
);
253 assert(it
!= mConnections
.end());
254 it
->second
->terminate();
255 mConnections
.erase(it
);
260 // Handling dead-port notifications.
261 // This receives DPNs for all kinds of ports we're interested in.
263 void Server::notifyDeadName(Port port
)
265 // We need the lock to get a proper iterator on mConnections or mProcesses,
266 // but must release it before we call abort or kill, as these might take
267 // unbounded time, including calls out to token daemons etc.
269 StLock
<Mutex
> serverLock(*this);
270 secnotice("SSports", "port %d is dead", port
.port());
272 // is it a connection?
273 PortMap
<Connection
>::iterator conIt
= mConnections
.find(port
);
274 if (conIt
!= mConnections
.end()) {
275 secnotice("SS", "%p dead connection %d", this, port
.port());
276 RefPointer
<Connection
> con
= conIt
->second
;
277 mConnections
.erase(conIt
);
284 PortMap
<Process
>::iterator procIt
= mProcesses
.find(port
);
285 if (procIt
!= mProcesses
.end()) {
286 secnotice("SS", "%p dead process %d", this, port
.port());
287 RefPointer
<Process
> proc
= procIt
->second
;
288 mPids
.erase(proc
->pid());
289 mProcesses
.erase(procIt
);
291 // The kill may take some time; make sure there is a spare thread around
292 // to prevent deadlocks
293 StLock
<MachServer
, &Server::busy
, &Server::idle
> _(*this);
298 // well, what IS IT?!
299 secnotice("server", "spurious dead port notification for port %d", port
.port());
304 // Handling no-senders notifications.
305 // This is currently only used for (subsidiary) service ports
307 void Server::notifyNoSenders(Port port
, mach_port_mscount_t
)
309 secnotice("SS", "%p dead session %d", this, port
.port());
315 // These are sent as Mach messages from ourselves to escape the limitations of
316 // the signal handler environment.
318 kern_return_t
self_server_handleSignal(mach_port_t sport
,
319 mach_port_t taskPort
, int sig
)
322 secnotice("SS", "signal handled %d", sig
);
323 if (taskPort
!= mach_task_self()) {
324 Syslog::error("handleSignal: received from someone other than myself");
329 ServerChild::checkChildren();
332 secnotice("SS", "shutdown due to SIGINT");
333 Syslog::notice("securityd terminated due to SIGINT");
336 Server::active().beginShutdown();
339 fprintf(stderr
, "securityd ignoring SIGPIPE received");
342 #if defined(DEBUGDUMP)
350 extern PCSCMonitor
*gPCSC
;
351 gPCSC
->startSoftTokens();
359 secnotice("SS", "exception handling a signal (ignored)");
361 mach_port_deallocate(mach_task_self(), taskPort
);
366 kern_return_t
self_server_handleSession(mach_port_t sport
,
367 mach_port_t taskPort
, uint32_t event
, uint64_t ident
)
370 if (taskPort
!= mach_task_self()) {
371 Syslog::error("handleSession: received from someone other than myself");
374 if (event
== AUE_SESSION_END
)
375 Session::destroy(int_cast
<uint64_t, Session::SessionId
>(ident
));
377 secnotice("SS", "exception handling a signal (ignored)");
379 mach_port_deallocate(mach_task_self(), taskPort
);
385 // Notifier for system sleep events
387 void Server::SleepWatcher::systemWillSleep()
389 secnotice("SS", "%p will sleep", this);
390 Session::processSystemSleep();
391 for (set
<PowerWatcher
*>::const_iterator it
= mPowerClients
.begin(); it
!= mPowerClients
.end(); it
++)
392 (*it
)->systemWillSleep();
395 void Server::SleepWatcher::systemIsWaking()
397 secnotice("SS", "%p is waking", this);
398 for (set
<PowerWatcher
*>::const_iterator it
= mPowerClients
.begin(); it
!= mPowerClients
.end(); it
++)
399 (*it
)->systemIsWaking();
402 void Server::SleepWatcher::systemWillPowerOn()
404 secnotice("SS", "%p will power on", this);
405 Server::active().longTermActivity();
406 for (set
<PowerWatcher
*>::const_iterator it
= mPowerClients
.begin(); it
!= mPowerClients
.end(); it
++)
407 (*it
)->systemWillPowerOn();
410 void Server::SleepWatcher::add(PowerWatcher
*client
)
412 assert(mPowerClients
.find(client
) == mPowerClients
.end());
413 mPowerClients
.insert(client
);
416 void Server::SleepWatcher::remove(PowerWatcher
*client
)
418 assert(mPowerClients
.find(client
) != mPowerClients
.end());
419 mPowerClients
.erase(client
);
424 // Expose the process/pid map to the outside
426 Process
*Server::findPid(pid_t pid
) const
428 PidMap::const_iterator it
= mPids
.find(pid
);
429 return (it
== mPids
.end()) ? NULL
: it
->second
;
434 // Set delayed shutdown mode
436 void Server::waitForClients(bool waiting
)
438 mWaitForClients
= waiting
;
443 // Begin shutdown processing.
444 // We relinquish our primary state authority. From now on, we'll be
445 // kept alive (only) by our current clients.
447 static FILE *reportFile
;
449 void Server::beginShutdown()
451 StLock
<Mutex
> _(*this);
452 if (!mWaitForClients
) {
453 secnotice("SS", "%p shutting down now", this);
456 if (!mShuttingDown
) {
457 mShuttingDown
= true;
458 Session::invalidateAuthHosts();
459 secnotice("SS", "%p beginning shutdown", this);
460 if (verbosity() >= 2) {
461 reportFile
= fopen("/var/log/securityd-shutdown.log", "w");
470 // During shutdown, we report residual clients to dtrace, and allow a state dump
472 // We don't bother locking for the shuttingDown() check; it's a latching boolean
473 // and we'll be good enough without a lock.
475 void Server::eventDone()
477 if (this->shuttingDown()) {
478 StLock
<Mutex
> lazy(*this, false); // lazy lock acquisition
479 if (verbosity() >= 2) {
481 secnotice("SS", "shutting down with %ld processes and %ld transactions", mProcesses
.size(), VProc::Transaction::debugCount());
484 IFDUMPING("shutdown", NodeCore::dumpAll());
489 void Server::shutdownSnitch()
493 fprintf(reportFile
, "%.24s %d residual clients:\n", ctime(&now
), int(mPids
.size()));
494 for (PidMap::const_iterator it
= mPids
.begin(); it
!= mPids
.end(); ++it
) {
495 string path
= it
->second
->getPath();
496 fprintf(reportFile
, " %s (%d)\n", path
.c_str(), it
->first
);
498 fprintf(reportFile
, "\n");
502 bool Server::inDarkWake()
504 return IOPMIsADarkWake(IOPMConnectionGetSystemCapabilities());
508 // Initialize the CSSM/MDS subsystem.
509 // This was once done lazily on demand. These days, we are setting up the
510 // system MDS here, and CSSM is pretty much always needed, so this is called
511 // early during program startup. Do note that the server may not (yet) be running.
513 void Server::loadCssm(bool mdsIsInstalled
)
515 if (!mCssm
->isActive()) {
516 StLock
<Mutex
> _(*this);
517 VProc::Transaction xact
;
518 if (!mCssm
->isActive()) {
519 if (!mdsIsInstalled
) { // non-system securityd instance should not reinitialize MDS
520 secnotice("SS", "Installing MDS");
521 IFDEBUG(if (geteuid() == 0))
522 MDSClient::mds().install();
524 secnotice("SS", "CSSM initializing");
527 secnotice("SS", "CSSM ready with CSP %s", mCSP
->guid().toString().c_str());
534 // LongtermActivity/lock combo
536 LongtermStLock::LongtermStLock(Mutex
&lck
)
537 : StLock
<Mutex
>(lck
, false) // don't take the lock yet
539 if (lck
.tryLock()) { // uncontested
540 this->mActive
= true;
541 } else { // contested - need backup thread
542 Server::active().longTermActivity();