X-Git-Url: https://git.saurik.com/apple/securityd.git/blobdiff_plain/eeadf2e6470f45ea0275a6019635573f2a7b5a2c..4cd1cad0dea00daa03e1b54fdf2797a02373ad5b:/src/server.cpp diff --git a/src/server.cpp b/src/server.cpp index af82dd7..0177679 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -1,10 +1,8 @@ /* - * Copyright (c) 2000-2004 Apple Computer, Inc. All Rights Reserved. + * Copyright (c) 2000-2004,2009 Apple Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * - * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. - * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in @@ -25,14 +23,23 @@ // -// server - the actual SecurityServer server object +// server - securityd main server object // -#include // knowledge of mig message sizes +#include // MIG ucsp service +#include "self.h" // MIG self service +#include +#include #include "server.h" #include "session.h" #include "acls.h" #include "notifications.h" +#include "child.h" #include +#include +#include "pcscmonitor.h" + +#include "agentquery.h" + using namespace MachPlusPlus; @@ -48,6 +55,7 @@ Authority::~Authority() { } + // // Construct the server object // @@ -56,10 +64,15 @@ Server::Server(Authority &authority, CodeSignatures &signatures, const char *boo mBootstrapName(bootstrapName), mCSPModule(gGuidAppleCSP, mCssm), mCSP(mCSPModule), mAuthority(authority), - mCodeSignatures(signatures) + mCodeSignatures(signatures), + mVerbosity(0), + mWaitForClients(true), mShuttingDown(false) { + // make me eternal (in the object mesh) + ref(); + // engage the subsidiary port handler for sleep notifications - add(sleepWatcher); + add(sleepWatcher); } @@ -78,13 +91,14 @@ Server::~Server() // by calling Server::connection() [no argument] until it is released by // calling Connection::endWork(). // -Connection &Server::connection(mach_port_t port) +Connection &Server::connection(mach_port_t port, audit_token_t &auditToken) { Server &server = active(); StLock _(server); Connection *conn = server.mConnections.get(port, CSSM_ERRCODE_INVALID_CONTEXT_HANDLE); + conn->process().checkSession(auditToken); active().mCurrentConnection() = conn; - conn->beginWork(); + conn->beginWork(auditToken); return *conn; } @@ -97,11 +111,11 @@ Connection &Server::connection(bool tolerant) return *conn; } -void Server::requestComplete() +void Server::requestComplete(CSSM_RETURN &rcode) { // note: there may not be an active connection if connection setup failed if (RefPointer &conn = active().mCurrentConnection()) { - conn->endWork(); + conn->endWork(rcode); conn = NULL; } IFDUMPING("state", NodeCore::dumpAll()); @@ -124,44 +138,36 @@ Session &Server::session() RefPointer Server::key(KeyHandle key) { - return HandleObject::findRef(key, CSSMERR_CSP_INVALID_KEY_REFERENCE); + return U32HandleObject::findRef(key, CSSMERR_CSP_INVALID_KEY_REFERENCE); } RefPointer Server::database(DbHandle db) { - RefPointer database = - HandleObject::findRef(db, CSSMERR_DL_INVALID_DB_HANDLE); - if (database->process() != process()) - CssmError::throwMe(CSSMERR_DL_INVALID_DB_HANDLE); - return database; + return find(db, CSSMERR_DL_INVALID_DB_HANDLE); } RefPointer Server::keychain(DbHandle db) { - RefPointer keychain = - HandleObject::findRef(db, CSSMERR_DL_INVALID_DB_HANDLE); - if (keychain->process() != process()) - CssmError::throwMe(CSSMERR_DL_INVALID_DB_HANDLE); - return keychain; + return find(db, CSSMERR_DL_INVALID_DB_HANDLE); } -RefPointer Server::optionalDatabase(DbHandle db) +RefPointer Server::optionalDatabase(DbHandle db, bool persistent) { - if (db == noDb) - return &process().localStore(); - else + if (persistent && db != noDb) return database(db); + else + return &process().localStore(); } // // Locate an ACL bearer (database or key) by handle +// The handle might be used across IPC, so we clamp it accordingly // -SecurityServerAcl &Server::aclBearer(AclKind kind, CSSM_HANDLE handle) +AclSource &Server::aclBearer(AclKind kind, U32HandleObject::Handle handle) { - SecurityServerAcl &bearer = - HandleObject::find(handle, CSSMERR_CSSM_INVALID_ADDIN_HANDLE); - if (kind != bearer.kind()) + AclSource &bearer = U32HandleObject::find(handle, CSSMERR_CSSM_INVALID_ADDIN_HANDLE); + if (kind != bearer.acl().aclKind()) CssmError::throwMe(CSSMERR_CSSM_INVALID_HANDLE_USAGE); return bearer; } @@ -174,43 +180,37 @@ void Server::run() { MachServer::run(0x10000, MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) | - MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_SENDER)); + MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT)); +} + + +// +// Handle thread overflow. MachServer will call this if it has hit its thread +// limit and yet still needs another thread. +// +void Server::threadLimitReached(UInt32 limit) +{ + Syslog::notice("securityd has reached its thread limit (%ld) - service deadlock is possible", + limit); } // // The primary server run-loop function. -// Invokes the MIG-generated main dispatch function (ucsp_server). +// Invokes the MIG-generated main dispatch function (ucsp_server), as well +// as the self-send dispatch (self_server). // For debug builds, look up request names in a MIG-generated table // for better debug-log messages. // boolean_t ucsp_server(mach_msg_header_t *, mach_msg_header_t *); +boolean_t self_server(mach_msg_header_t *, mach_msg_header_t *); -#if defined(NDEBUG) boolean_t Server::handle(mach_msg_header_t *in, mach_msg_header_t *out) { - return ucsp_server(in, out); + return ucsp_server(in, out) || self_server(in, out); } -#else //NDEBUG - -static const struct IPCName { const char *name; int ipc; } ipcNames[] = - { subsystem_to_name_map_ucsp }; // macro generated by MIG, from ucsp.h - -boolean_t Server::handle(mach_msg_header_t *in, mach_msg_header_t *out) -{ - const int first = ipcNames[0].ipc; - const char *name = (in->msgh_id >= first && in->msgh_id < first + ucsp_MSG_COUNT) ? - ipcNames[in->msgh_id - first].name : "OUT OF BOUNDS"; - secdebug("SSreq", "begin %s (%d)", name, in->msgh_id); - boolean_t result = ucsp_server(in, out); - secdebug("SSreq", "end %s (%d)", name, in->msgh_id); - return result; -} - -#endif //NDEBUG - // // Set up a new Connection. This establishes the environment (process et al) as needed @@ -219,23 +219,29 @@ boolean_t Server::handle(mach_msg_header_t *in, mach_msg_header_t *out) // Everything at and below that level is constructed. This is straight-forward except // in the case of session re-initialization (see below). // -void Server::setupConnection(ConnectLevel type, Port servicePort, Port replyPort, Port taskPort, - const security_token_t &securityToken, const ClientSetupInfo *info, const char *identity) +void Server::setupConnection(ConnectLevel type, Port replyPort, Port taskPort, + const audit_token_t &auditToken, const ClientSetupInfo *info) { + AuditToken audit(auditToken); + // first, make or find the process based on task port StLock _(*this); RefPointer &proc = mProcesses[taskPort]; - if (type == connectNewSession && proc) { - // The client has talked to us before and now wants to create a new session. - proc->changeSession(servicePort); + if (proc && proc->session().sessionId() != audit.sessionId()) + proc->changeSession(audit.sessionId()); + if (proc && type == connectNewProcess) { + // the client has amnesia - reset it + assert(info); + proc->reset(taskPort, info, audit); + proc->changeSession(audit.sessionId()); } if (!proc) { if (type == connectNewThread) // client error (or attack) CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); - assert(info && identity); - proc = new Process(servicePort, taskPort, info, identity, - securityToken.val[0], securityToken.val[1]); + assert(info); + proc = new Process(taskPort, info, audit); notifyIfDead(taskPort); + mPids[proc->pid()] = proc; } // now, establish a connection and register it in the server @@ -269,29 +275,41 @@ void Server::endConnection(Port replyPort) // void Server::notifyDeadName(Port port) { - StLock _(*this); + // We need the lock to get a proper iterator on mConnections or mProcesses, + // but must release it before we call abort or kill, as these might take + // unbounded time, including calls out to token daemons etc. + + StLock serverLock(*this); secdebug("SSports", "port %d is dead", port.port()); // is it a connection? PortMap::iterator conIt = mConnections.find(port); if (conIt != mConnections.end()) { - conIt->second->abort(); + SECURITYD_PORTS_DEAD_CONNECTION(port); + RefPointer con = conIt->second; mConnections.erase(conIt); + serverLock.unlock(); + con->abort(); return; } // is it a process? PortMap::iterator procIt = mProcesses.find(port); if (procIt != mProcesses.end()) { - procIt->second->kill(); + SECURITYD_PORTS_DEAD_PROCESS(port); + RefPointer proc = procIt->second; + mPids.erase(proc->pid()); mProcesses.erase(procIt); + serverLock.unlock(); + // The kill may take some time; make sure there is a spare thread around + // to prevent deadlocks + StLock _(*this); + proc->kill(); return; } - // is it a notification client? - if (Listener::remove(port)) - return; - + // well, what IS IT?! + SECURITYD_PORTS_DEAD_ORPHAN(port); secdebug("server", "spurious dead port notification for port %d", port.port()); } @@ -302,8 +320,78 @@ void Server::notifyDeadName(Port port) // void Server::notifyNoSenders(Port port, mach_port_mscount_t) { - secdebug("SSports", "port %d no senders", port.port()); - Session::destroy(port); + SECURITYD_PORTS_DEAD_SESSION(port); +} + + +// +// Handling signals. +// These are sent as Mach messages from ourselves to escape the limitations of +// the signal handler environment. +// +kern_return_t self_server_handleSignal(mach_port_t sport, + mach_port_t taskPort, int sig) +{ + try { + SECURITYD_SIGNAL_HANDLED(sig); + if (taskPort != mach_task_self()) { + Syslog::error("handleSignal: received from someone other than myself"); + return KERN_SUCCESS; + } + switch (sig) { + case SIGCHLD: + ServerChild::checkChildren(); + break; + case SIGINT: + SECURITYD_SHUTDOWN_NOW(); + Syslog::notice("securityd terminated due to SIGINT"); + _exit(0); + case SIGTERM: + Server::active().beginShutdown(); + break; + case SIGPIPE: + fprintf(stderr, "securityd ignoring SIGPIPE received"); + break; + +#if defined(DEBUGDUMP) + case SIGUSR1: + NodeCore::dumpAll(); + break; +#endif //DEBUGDUMP + + case SIGUSR2: + { + extern PCSCMonitor *gPCSC; + gPCSC->startSoftTokens(); + break; + } + + default: + assert(false); + } + } catch(...) { + secdebug("SS", "exception handling a signal (ignored)"); + } + mach_port_deallocate(mach_task_self(), taskPort); + return KERN_SUCCESS; +} + + +kern_return_t self_server_handleSession(mach_port_t sport, + mach_port_t taskPort, uint32_t event, uint64_t ident) +{ + try { + if (taskPort != mach_task_self()) { + Syslog::error("handleSession: received from someone other than myself"); + return KERN_SUCCESS; + } + if (event == AUE_SESSION_CLOSE) + Session::destroy(ident); + } catch(...) { + secdebug("SS", "exception handling a signal (ignored)"); + } + mach_port_deallocate(mach_task_self(), taskPort); + return KERN_SUCCESS; } @@ -312,65 +400,164 @@ void Server::notifyNoSenders(Port port, mach_port_mscount_t) // void Server::SleepWatcher::systemWillSleep() { - secdebug("SS", "sleep notification received"); + SECURITYD_POWER_SLEEP(); Session::processSystemSleep(); + for (set::const_iterator it = mPowerClients.begin(); it != mPowerClients.end(); it++) + (*it)->systemWillSleep(); +} + +void Server::SleepWatcher::systemIsWaking() +{ + SECURITYD_POWER_WAKE(); + for (set::const_iterator it = mPowerClients.begin(); it != mPowerClients.end(); it++) + (*it)->systemIsWaking(); +} + +void Server::SleepWatcher::systemWillPowerOn() +{ + SECURITYD_POWER_ON(); + Server::active().longTermActivity(); + for (set::const_iterator it = mPowerClients.begin(); it != mPowerClients.end(); it++) + (*it)->systemWillPowerOn(); +} + +void Server::SleepWatcher::add(PowerWatcher *client) +{ + assert(mPowerClients.find(client) == mPowerClients.end()); + mPowerClients.insert(client); +} + +void Server::SleepWatcher::remove(PowerWatcher *client) +{ + assert(mPowerClients.find(client) != mPowerClients.end()); + mPowerClients.erase(client); } // -// Return the primary Cryptographic Service Provider. -// This will be lazily loaded when it is first requested. +// Expose the process/pid map to the outside // -CssmClient::CSP &Server::getCsp() +Process *Server::findPid(pid_t pid) const { - if (!mCssm->isActive()) - loadCssm(); - return mCSP; + PidMap::const_iterator it = mPids.find(pid); + return (it == mPids.end()) ? NULL : it->second; } // -// Initialize the CSSM/MDS subsystem. -// This is thread-safe and can be done lazily. +// Set delayed shutdown mode +// +void Server::waitForClients(bool waiting) +{ + mWaitForClients = waiting; +} + + +// +// Begin shutdown processing. +// We relinquish our primary state authority. From now on, we'll be +// kept alive (only) by our current clients. +// +static FILE *reportFile; + +void Server::beginShutdown() +{ + StLock _(*this); + if (!mWaitForClients) { + SECURITYD_SHUTDOWN_NOW(); + _exit(0); + } else { + if (!mShuttingDown) { + mShuttingDown = true; + Session::invalidateAuthHosts(); + SECURITYD_SHUTDOWN_BEGIN(); + if (verbosity() >= 2) { + reportFile = fopen("/var/log/securityd-shutdown.log", "w"); + shutdownSnitch(); + } + } + } +} + + // -static void initMds(); +// During shutdown, we report residual clients to dtrace, and allow a state dump +// for debugging. +// We don't bother locking for the shuttingDown() check; it's a latching boolean +// and we'll be good enough without a lock. +// +void Server::eventDone() +{ + if (this->shuttingDown()) { + StLock lazy(*this, false); // lazy lock acquisition + if (SECURITYD_SHUTDOWN_COUNT_ENABLED()) { + lazy.lock(); + SECURITYD_SHUTDOWN_COUNT(mProcesses.size(), VProc::Transaction::debugCount()); + } + if (verbosity() >= 2) { + lazy.lock(); + shutdownSnitch(); + } + IFDUMPING("shutdown", NodeCore::dumpAll()); + } +} + + +void Server::shutdownSnitch() +{ + time_t now; + time(&now); + fprintf(reportFile, "%.24s %d residual clients:\n", ctime(&now), int(mPids.size())); + for (PidMap::const_iterator it = mPids.begin(); it != mPids.end(); ++it) + if (SecCodeRef clientCode = it->second->processCode()) { + CFRef path; + OSStatus rc = SecCodeCopyPath(clientCode, kSecCSDefaultFlags, &path.aref()); + if (path) + fprintf(reportFile, " %s (%d)\n", cfString(path).c_str(), it->first); + else + fprintf(reportFile, "pid=%d (error %d)\n", it->first, int32_t(rc)); + } + fprintf(reportFile, "\n"); + fflush(reportFile); +} -void Server::loadCssm() + +// +// Initialize the CSSM/MDS subsystem. +// This was once done lazily on demand. These days, we are setting up the +// system MDS here, and CSSM is pretty much always needed, so this is called +// early during program startup. Do note that the server may not (yet) be running. +// +void Server::loadCssm(bool mdsIsInstalled) { if (!mCssm->isActive()) { StLock _(*this); + VProc::Transaction xact; if (!mCssm->isActive()) { - try { - initMds(); - } catch (const CssmError &error) { - switch (error.osStatus()) { - case CSSMERR_DL_MDS_ERROR: - case CSSMERR_DL_OS_ACCESS_DENIED: - secdebug("SS", "MDS initialization failed; continuing"); - Syslog::warning("MDS initialization failed; continuing"); - break; - default: - throw; - } - } + if (!mdsIsInstalled) { // non-system securityd instance should not reinitialize MDS + secdebug("SS", "Installing MDS"); + IFDEBUG(if (geteuid() == 0)) + MDSClient::mds().install(); + } secdebug("SS", "CSSM initializing"); mCssm->init(); mCSP->attach(); - IFDEBUG(char guids[Guid::stringRepLength+1]); - secdebug("SS", "CSSM ready with CSP %s", mCSP->guid().toString(guids)); + secdebug("SS", "CSSM ready with CSP %s", mCSP->guid().toString().c_str()); } } } -#include -static void initMds() +// +// LongtermActivity/lock combo +// +LongtermStLock::LongtermStLock(Mutex &lck) + : StLock(lck, false) // don't take the lock yet { - secdebug("SS", "MDS initializing"); - CssmAllocatorMemoryFunctions memory(Allocator::standard()); - MDS_FUNCS functions; - MDS_HANDLE handle; - CssmError::check(MDS_Initialize(NULL, &memory, &functions, &handle)); - CssmError::check(MDS_Install(handle)); - CssmError::check(MDS_Terminate(handle)); + if (lck.tryLock()) { // uncontested + this->mActive = true; + } else { // contested - need backup thread + Server::active().longTermActivity(); + this->lock(); + } }