]> git.saurik.com Git - apple/securityd.git/blob - src/main.cpp
securityd-29035.tar.gz
[apple/securityd.git] / src / main.cpp
1 /*
2 * Copyright (c) 2000-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 // securityd - Apple security services daemon.
27 //
28 #include <securityd_client/ucsp.h>
29
30 #include "server.h"
31 #include "entropy.h"
32 #include "authority.h"
33 #include "session.h"
34 #include "pcscmonitor.h"
35 #include "self.h"
36
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>
42
43 #include <unistd.h>
44 #include <sys/types.h>
45 #include <signal.h>
46 #include <syslog.h>
47
48
49 // #define PERFORMANCE_MEASUREMENT 1
50
51 #ifdef PERFORMANCE_MEASUREMENT
52 #include <mach/mach_time.h>
53 #endif
54
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"
66
67 //
68 // Local functions of the main program driver
69 //
70 static void usage(const char *me) __attribute__((noreturn));
71 static void handleSignals(int sig);
72 static PCSCMonitor::ServiceLevel scOptions(const char *optionString);
73
74
75 static Port gMainServerPort;
76
77
78 //
79 // Main driver
80 //
81 int main(int argc, char *argv[])
82 {
83 #ifdef PERFORMANCE_MEASUREMENT
84 // needed for automated timing of securityd startup
85 uint64_t startTime = mach_absolute_time ();
86 #endif
87
88 Debug::trace (kSecTraceSecurityServerStart);
89
90 // clear the umask - we know what we're doing
91 secdebug("SS", "starting umask was 0%o", ::umask(0));
92 ::umask(0);
93
94 // program arguments (preset to defaults)
95 bool debugMode = false;
96 const char *bootstrapName = NULL;
97 bool doFork = false;
98 bool reExecute = false;
99 int workerTimeout = 0;
100 int maxThreads = 0;
101 const char *authorizationConfig = "/etc/authorization";
102 const char *tokenCacheDir = "/var/db/TokenCache";
103 const char *entropyFile = "/var/db/SystemEntropyCache";
104 const char *equivDbFile = EQUIVALENCEDBPATH;
105 const char *smartCardOptions = getenv("SMARTCARDS");
106
107 // parse command line arguments
108 extern char *optarg;
109 extern int optind;
110 int arg;
111 while ((arg = getopt(argc, argv, "a:c:de:E:fN:s:t:T:X")) != -1) {
112 switch (arg) {
113 case 'a':
114 authorizationConfig = optarg;
115 break;
116 case 'c':
117 tokenCacheDir = optarg;
118 break;
119 case 'd':
120 debugMode = true;
121 break;
122 case 'e':
123 equivDbFile = optarg;
124 break;
125 case 'E':
126 entropyFile = optarg;
127 break;
128 case 'f':
129 fprintf(stderr, "%s: the -f option is obsolete\n", argv[0]);
130 break;
131 case 'N':
132 bootstrapName = optarg;
133 break;
134 case 's':
135 smartCardOptions = optarg;
136 break;
137 case 't':
138 if ((maxThreads = atoi(optarg)) < 0)
139 maxThreads = 0;
140 break;
141 case 'T':
142 if ((workerTimeout = atoi(optarg)) < 0)
143 workerTimeout = 0;
144 break;
145 case 'X':
146 doFork = true;
147 reExecute = true;
148 break;
149 default:
150 usage(argv[0]);
151 }
152 }
153
154 // take no non-option arguments
155 if (optind < argc)
156 usage(argv[0]);
157
158 // figure out the bootstrap name
159 if (!bootstrapName) {
160 bootstrapName = getenv(SECURITYSERVER_BOOTSTRAP_ENV);
161 if (!bootstrapName)
162 bootstrapName = SECURITYSERVER_BOOTSTRAP_NAME;
163 }
164
165 // configure logging first
166 if (debugMode) {
167 Syslog::open(bootstrapName, LOG_AUTHPRIV, LOG_PERROR);
168 Syslog::notice("%s started in debug mode", argv[0]);
169 } else {
170 Syslog::open(bootstrapName, LOG_AUTHPRIV, LOG_CONS);
171 }
172
173 // if we're not running as root in production mode, fail
174 // in debug mode, issue a warning
175 if (uid_t uid = getuid()) {
176 #if defined(NDEBUG)
177 Syslog::alert("Tried to run securityd as user %d: aborted", uid);
178 fprintf(stderr, "You are not allowed to run securityd\n");
179 exit(1);
180 #else
181 fprintf(stderr, "securityd is unprivileged; some features may not work.\n");
182 secdebug("SS", "Running as user %d (you have been warned)", uid);
183 #endif //NDEBUG
184 }
185
186 // turn into a properly diabolical daemon unless debugMode is on
187 if (!debugMode && getppid() != 1) {
188 if (!Daemon::incarnate(doFork))
189 exit(1); // can't daemonize
190
191 if (reExecute && !Daemon::executeSelf(argv))
192 exit(1); // can't self-execute
193 }
194
195 // arm signal handlers; code below may generate signals we want to see
196 if (signal(SIGCHLD, handleSignals) == SIG_ERR)
197 secdebug("SS", "Cannot handle SIGCHLD: errno=%d", errno);
198 if (signal(SIGINT, handleSignals) == SIG_ERR)
199 secdebug("SS", "Cannot handle SIGINT: errno=%d", errno);
200 if (signal(SIGTERM, handleSignals) == SIG_ERR)
201 secdebug("SS", "Cannot handle SIGTERM: errno=%d", errno);
202 #if !defined(NDEBUG)
203 if (signal(SIGUSR1, handleSignals) == SIG_ERR)
204 secdebug("SS", "Cannot handle SIGHUP: errno=%d", errno);
205 #endif //NDEBUG
206
207 // create a code signing engine
208 CodeSigning::OSXSigner signer;
209
210 // create an Authorization engine
211 Authority authority(authorizationConfig);
212
213 // establish the ACL machinery
214 new AnyAclSubject::Maker();
215 new PasswordAclSubject::Maker();
216 new ProtectedPasswordAclSubject::Maker();
217 new PromptedAclSubject::Maker();
218 new ThresholdAclSubject::Maker();
219 new CommentAclSubject::Maker();
220 new ProcessAclSubject::Maker();
221 new CodeSignatureAclSubject::Maker(signer);
222 new KeychainPromptAclSubject::Maker();
223 new PreAuthorizationAcls::OriginMaker();
224 new PreAuthorizationAcls::SourceMaker();
225
226 // establish the code equivalents database
227 CodeSignatures codeSignatures(equivDbFile);
228
229 // create the main server object and register it
230 Server server(authority, codeSignatures, bootstrapName);
231
232 // Remember the primary service port to send signal events to
233 gMainServerPort = server.primaryServicePort();
234
235 // set server configuration from arguments, if specified
236 if (workerTimeout)
237 server.timeout(workerTimeout);
238 if (maxThreads)
239 server.maxThreads(maxThreads);
240
241 // add the RNG seed timer
242 # if defined(NDEBUG)
243 EntropyManager entropy(server, entropyFile);
244 # else
245 if (getuid() == 0) new EntropyManager(server, entropyFile);
246 # endif
247
248 // create a token-cache interface
249 #if !defined(NDEBUG)
250 if (const char *s = getenv("TOKENCACHE"))
251 tokenCacheDir = s;
252 #endif //NDEBUG
253
254 // create a smartcard monitor to manage external token devices
255 PCSCMonitor secureCards(server, tokenCacheDir, scOptions(smartCardOptions));
256
257 // create the RootSession object (if -d, give it graphics and tty attributes)
258 RootSession rootSession(server,
259 debugMode ? (sessionHasGraphicAccess | sessionHasTTY) : 0);
260
261 // install MDS and initialize the local CSSM
262 server.loadCssm();
263
264 // okay, we're ready to roll
265 Syslog::notice("Entering service");
266 secdebug("SS", "%s initialized", bootstrapName);
267 Debug::trace (kSecTraceSecurityServerInitialized);
268
269 #ifdef PERFORMANCE_MEASUREMENT
270 // needed for automated timing of securityd startup
271 uint64_t endTime = mach_absolute_time ();
272
273 // compute how long it took to initialize
274 uint64_t elapsedTime = endTime - startTime;
275 mach_timebase_info_data_t multiplier;
276 mach_timebase_info (&multiplier);
277
278 elapsedTime = elapsedTime * multiplier.numer / multiplier.denom;
279
280 FILE* f = fopen ("/var/log/startuptime.txt", "a");
281 if (f == NULL)
282 {
283 // probably not running as root.
284 f = fopen ("/tmp/startuptime.txt", "a");
285 }
286
287 fprintf (f, "%lld\n", elapsedTime);
288 fclose (f);
289 #endif
290
291 // go
292 server.run();
293
294 // fell out of runloop (should not happen)
295 Syslog::alert("Aborting");
296 return 1;
297 }
298
299
300 //
301 // Issue usage message and die
302 //
303 static void usage(const char *me)
304 {
305 fprintf(stderr, "Usage: %s [-dX]"
306 "\n\t[-a authConfigFile] Authorization configuration file"
307 "\n\t[-c tokencache] smartcard token cache directory"
308 "\n\t[-e equivDatabase] path to code equivalence database"
309 "\n\t[-N serviceName] MACH service name"
310 "\n\t[-s off|on|conservative|aggressive] smartcard operation level"
311 "\n\t[-t maxthreads] [-T threadTimeout] server thread control"
312 "\n", me);
313 exit(2);
314 }
315
316
317 //
318 // Translate strings (e.g. "conservative") into PCSCMonitor service levels
319 //
320 static PCSCMonitor::ServiceLevel scOptions(const char *optionString)
321 {
322 if (optionString)
323 if (!strcmp(optionString, "off"))
324 return PCSCMonitor::forcedOff;
325 else if (!strcmp(optionString, "on"))
326 return PCSCMonitor::forcedOn;
327 else if (!strcmp(optionString, "conservative"))
328 return PCSCMonitor::conservative;
329 else if (!strcmp(optionString, "aggressive"))
330 return PCSCMonitor::aggressive;
331 else if (!strcmp(optionString, "external"))
332 return PCSCMonitor::externalDaemon;
333 else
334 usage("securityd");
335 else
336 return PCSCMonitor::aggressive;
337 }
338
339
340 //
341 // Handle signals.
342 // We send ourselves a message (through the "self" service), so actual
343 // actions happen on the normal event loop path. Note that another thread
344 // may be picking up the message immediately.
345 //
346 static void handleSignals(int sig)
347 {
348 if (kern_return_t rc = self_client_handleSignal(gMainServerPort, mach_task_self(), sig))
349 Syslog::error("self-send failed (mach error %d)", rc);
350 }