2 * Copyright (c) 2000-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 // securityd - Apple security services daemon.
28 #include <securityd_client/ucsp.h>
32 #include "authority.h"
34 #include "pcscmonitor.h"
37 #include <security_utilities/daemon.h>
38 #include <security_utilities/machserver.h>
39 #include <security_utilities/logging.h>
40 #include <security_utilities/ktracecodes.h>
41 #include <security_cdsa_client/osxsigner.h>
44 #include <sys/types.h>
49 // #define PERFORMANCE_MEASUREMENT 1
51 #ifdef PERFORMANCE_MEASUREMENT
52 #include <mach/mach_time.h>
55 // ACL subject types (their makers are instantiated here)
56 #include <security_cdsa_utilities/acl_any.h>
57 #include <security_cdsa_utilities/acl_password.h>
58 #include <security_cdsa_utilities/acl_prompted.h>
59 #include <security_cdsa_utilities/acl_protectedpw.h>
60 #include <security_cdsa_utilities/acl_threshold.h>
61 #include <security_cdsa_utilities/acl_codesigning.h>
62 #include <security_cdsa_utilities/acl_process.h>
63 #include <security_cdsa_utilities/acl_comment.h>
64 #include <security_cdsa_utilities/acl_preauth.h>
65 #include "acl_keychain.h"
69 // Local functions of the main program driver
71 static void usage(const char *me
) __attribute__((noreturn
));
72 static void handleSignals(int sig
);
73 static PCSCMonitor::ServiceLevel
scOptions(const char *optionString
);
76 static Port gMainServerPort
;
82 int main(int argc
, char *argv
[])
84 #ifdef PERFORMANCE_MEASUREMENT
85 // needed for automated timing of securityd startup
86 uint64_t startTime
= mach_absolute_time ();
89 Debug::trace (kSecTraceSecurityServerStart
);
91 // clear the umask - we know what we're doing
92 secdebug("SS", "starting umask was 0%o", ::umask(0));
95 // program arguments (preset to defaults)
96 bool debugMode
= false;
97 const char *bootstrapName
= NULL
;
99 bool reExecute
= false;
100 int workerTimeout
= 0;
102 const char *authorizationConfig
= "/etc/authorization";
103 const char *tokenCacheDir
= "/var/db/TokenCache";
104 const char *entropyFile
= "/var/db/SystemEntropyCache";
105 const char *equivDbFile
= EQUIVALENCEDBPATH
;
106 const char *smartCardOptions
= getenv("SMARTCARDS");
108 // parse command line arguments
112 while ((arg
= getopt(argc
, argv
, "a:c:de:E:fN:s:t:T:X")) != -1) {
115 authorizationConfig
= optarg
;
118 tokenCacheDir
= optarg
;
124 equivDbFile
= optarg
;
127 entropyFile
= optarg
;
130 fprintf(stderr
, "%s: the -f option is obsolete\n", argv
[0]);
133 bootstrapName
= optarg
;
136 smartCardOptions
= optarg
;
139 if ((maxThreads
= atoi(optarg
)) < 0)
143 if ((workerTimeout
= atoi(optarg
)) < 0)
155 // take no non-option arguments
159 // figure out the bootstrap name
160 if (!bootstrapName
) {
161 bootstrapName
= getenv(SECURITYSERVER_BOOTSTRAP_ENV
);
163 bootstrapName
= SECURITYSERVER_BOOTSTRAP_NAME
;
166 // configure logging first
168 Syslog::open(bootstrapName
, LOG_AUTHPRIV
, LOG_PERROR
);
169 Syslog::notice("%s started in debug mode", argv
[0]);
171 Syslog::open(bootstrapName
, LOG_AUTHPRIV
, LOG_CONS
);
174 // if we're not running as root in production mode, fail
175 // in debug mode, issue a warning
176 if (uid_t uid
= getuid()) {
178 Syslog::alert("Tried to run securityd as user %d: aborted", uid
);
179 fprintf(stderr
, "You are not allowed to run securityd\n");
182 fprintf(stderr
, "securityd is unprivileged; some features may not work.\n");
183 secdebug("SS", "Running as user %d (you have been warned)", uid
);
187 // turn into a properly diabolical daemon unless debugMode is on
188 if (!debugMode
&& getppid() != 1) {
189 if (!Daemon::incarnate(doFork
))
190 exit(1); // can't daemonize
192 if (reExecute
&& !Daemon::executeSelf(argv
))
193 exit(1); // can't self-execute
196 // arm signal handlers; code below may generate signals we want to see
197 if (signal(SIGCHLD
, handleSignals
) == SIG_ERR
)
198 secdebug("SS", "Cannot handle SIGCHLD: errno=%d", errno
);
199 if (signal(SIGINT
, handleSignals
) == SIG_ERR
)
200 secdebug("SS", "Cannot handle SIGINT: errno=%d", errno
);
201 if (signal(SIGTERM
, handleSignals
) == SIG_ERR
)
202 secdebug("SS", "Cannot handle SIGTERM: errno=%d", errno
);
204 if (signal(SIGUSR1
, handleSignals
) == SIG_ERR
)
205 secdebug("SS", "Cannot handle SIGHUP: errno=%d", errno
);
208 // create a code signing engine
209 CodeSigning::OSXSigner signer
;
211 // create an Authorization engine
212 Authority
authority(authorizationConfig
);
214 // establish the ACL machinery
215 new AnyAclSubject::Maker();
216 new PasswordAclSubject::Maker();
217 new ProtectedPasswordAclSubject::Maker();
218 new PromptedAclSubject::Maker();
219 new ThresholdAclSubject::Maker();
220 new CommentAclSubject::Maker();
221 new ProcessAclSubject::Maker();
222 new CodeSignatureAclSubject::Maker(signer
);
223 new KeychainPromptAclSubject::Maker();
224 new PreAuthorizationAcls::OriginMaker();
225 new PreAuthorizationAcls::SourceMaker();
227 // establish the code equivalents database
228 CodeSignatures
codeSignatures(equivDbFile
);
230 // create the main server object and register it
231 Server
server(authority
, codeSignatures
, bootstrapName
);
233 // Remember the primary service port to send signal events to
234 gMainServerPort
= server
.primaryServicePort();
236 // set server configuration from arguments, if specified
238 server
.timeout(workerTimeout
);
240 server
.maxThreads(maxThreads
);
242 // add the RNG seed timer
244 EntropyManager
entropy(server
, entropyFile
);
246 if (getuid() == 0) new EntropyManager(server
, entropyFile
);
249 // create a token-cache interface
251 if (const char *s
= getenv("TOKENCACHE"))
255 // create a smartcard monitor to manage external token devices
256 PCSCMonitor
secureCards(server
, tokenCacheDir
, scOptions(smartCardOptions
));
258 // create the RootSession object (if -d, give it graphics and tty attributes)
259 RootSession
rootSession(server
,
260 debugMode
? (sessionHasGraphicAccess
| sessionHasTTY
) : 0);
262 // install MDS and initialize the local CSSM
265 // okay, we're ready to roll
266 Syslog::notice("Entering service");
267 secdebug("SS", "%s initialized", bootstrapName
);
268 Debug::trace (kSecTraceSecurityServerInitialized
);
270 #ifdef PERFORMANCE_MEASUREMENT
271 // needed for automated timing of securityd startup
272 uint64_t endTime
= mach_absolute_time ();
274 // compute how long it took to initialize
275 uint64_t elapsedTime
= endTime
- startTime
;
276 mach_timebase_info_data_t multiplier
;
277 mach_timebase_info (&multiplier
);
279 elapsedTime
= elapsedTime
* multiplier
.numer
/ multiplier
.denom
;
281 FILE* f
= fopen ("/var/log/startuptime.txt", "a");
284 // probably not running as root.
285 f
= fopen ("/tmp/startuptime.txt", "a");
288 fprintf (f
, "%lld\n", elapsedTime
);
295 // fell out of runloop (should not happen)
296 Syslog::alert("Aborting");
302 // Issue usage message and die
304 static void usage(const char *me
)
306 fprintf(stderr
, "Usage: %s [-dX]"
307 "\n\t[-a authConfigFile] Authorization configuration file"
308 "\n\t[-c tokencache] smartcard token cache directory"
309 "\n\t[-e equivDatabase] path to code equivalence database"
310 "\n\t[-N serviceName] MACH service name"
311 "\n\t[-s off|on|conservative|aggressive] smartcard operation level"
312 "\n\t[-t maxthreads] [-T threadTimeout] server thread control"
319 // Translate strings (e.g. "conservative") into PCSCMonitor service levels
321 static PCSCMonitor::ServiceLevel
scOptions(const char *optionString
)
324 if (!strcmp(optionString
, "off"))
325 return PCSCMonitor::forcedOff
;
326 else if (!strcmp(optionString
, "on"))
327 return PCSCMonitor::forcedOn
;
328 else if (!strcmp(optionString
, "conservative"))
329 return PCSCMonitor::conservative
;
330 else if (!strcmp(optionString
, "aggressive"))
331 return PCSCMonitor::aggressive
;
332 else if (!strcmp(optionString
, "external"))
333 return PCSCMonitor::externalDaemon
;
337 return PCSCMonitor::aggressive
;
343 // We send ourselves a message (through the "self" service), so actual
344 // actions happen on the normal event loop path. Note that another thread
345 // may be picking up the message immediately.
347 static void handleSignals(int sig
)
349 if (kern_return_t rc
= self_client_handleSignal(gMainServerPort
, mach_task_self(), sig
))
350 Syslog::error("self-send failed (mach error %d)", rc
);