]> git.saurik.com Git - apple/securityd.git/blob - src/main.cpp
securityd-55126.2.tar.gz
[apple/securityd.git] / src / main.cpp
1 /*
2 * Copyright (c) 2000-2007 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 // 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 "notifications.h"
35 #include "pcscmonitor.h"
36 #include "auditevents.h"
37 #include "self.h"
38
39 #include <security_utilities/daemon.h>
40 #include <security_utilities/machserver.h>
41 #include <security_utilities/logging.h>
42
43 #include <Security/SecKeychainPriv.h>
44
45 #include <unistd.h>
46 #include <sys/types.h>
47 #include <signal.h>
48 #include <syslog.h>
49
50 // ACL subject types (their makers are instantiated here)
51 #include <security_cdsa_utilities/acl_any.h>
52 #include <security_cdsa_utilities/acl_password.h>
53 #include <security_cdsa_utilities/acl_prompted.h>
54 #include <security_cdsa_utilities/acl_protectedpw.h>
55 #include <security_cdsa_utilities/acl_threshold.h>
56 #include <security_cdsa_utilities/acl_codesigning.h>
57 #include <security_cdsa_utilities/acl_process.h>
58 #include <security_cdsa_utilities/acl_comment.h>
59 #include <security_cdsa_utilities/acl_preauth.h>
60 #include "acl_keychain.h"
61
62
63 //
64 // Local functions of the main program driver
65 //
66 static void usage(const char *me) __attribute__((noreturn));
67 static void handleSignals(int sig);
68 static PCSCMonitor::ServiceLevel scOptions(const char *optionString);
69
70
71 static Port gMainServerPort;
72 PCSCMonitor *gPCSC;
73
74
75 //
76 // Main driver
77 //
78 int main(int argc, char *argv[])
79 {
80 // clear the umask - we know what we're doing
81 secdebug("SS", "starting umask was 0%o", ::umask(0));
82 ::umask(0);
83
84 // tell the keychain (client) layer to turn off the server interface
85 SecKeychainSetServerMode();
86
87 // program arguments (preset to defaults)
88 bool debugMode = false;
89 const char *bootstrapName = NULL;
90 const char* messagingName = SECURITY_MESSAGES_NAME;
91 bool doFork = false;
92 bool reExecute = false;
93 int workerTimeout = 0;
94 int maxThreads = 0;
95 bool waitForClients = true;
96 bool mdsIsInstalled = false;
97 const char *authorizationConfig = "/etc/authorization";
98 const char *tokenCacheDir = "/var/db/TokenCache";
99 const char *entropyFile = "/var/db/SystemEntropyCache";
100 const char *equivDbFile = EQUIVALENCEDBPATH;
101 const char *smartCardOptions = getenv("SMARTCARDS");
102 uint32_t keychainAclDefault = CSSM_ACL_KEYCHAIN_PROMPT_INVALID | CSSM_ACL_KEYCHAIN_PROMPT_UNSIGNED;
103 unsigned int verbose = 0;
104
105 // check for the Installation-DVD environment and modify some default arguments if found
106 if (access("/etc/rc.cdrom", F_OK) == 0) { // /etc/rc.cdrom exists
107 SECURITYD_INSTALLMODE();
108 smartCardOptions = "off"; // needs writable directories that aren't
109 }
110
111 // parse command line arguments
112 extern char *optarg;
113 extern int optind;
114 int arg;
115 while ((arg = getopt(argc, argv, "a:c:de:E:imN:s:t:T:uvWX")) != -1) {
116 switch (arg) {
117 case 'a':
118 authorizationConfig = optarg;
119 break;
120 case 'c':
121 tokenCacheDir = optarg;
122 break;
123 case 'd':
124 debugMode = true;
125 break;
126 case 'e':
127 equivDbFile = optarg;
128 break;
129 case 'E':
130 entropyFile = optarg;
131 break;
132 case 'i':
133 keychainAclDefault &= ~CSSM_ACL_KEYCHAIN_PROMPT_INVALID;
134 break;
135 case 'm':
136 mdsIsInstalled = true;
137 break;
138 case 'N':
139 bootstrapName = optarg;
140 break;
141 case 's':
142 smartCardOptions = optarg;
143 break;
144 case 't':
145 if ((maxThreads = atoi(optarg)) < 0)
146 maxThreads = 0;
147 break;
148 case 'T':
149 if ((workerTimeout = atoi(optarg)) < 0)
150 workerTimeout = 0;
151 break;
152 case 'W':
153 waitForClients = false;
154 break;
155 case 'u':
156 keychainAclDefault &= ~CSSM_ACL_KEYCHAIN_PROMPT_UNSIGNED;
157 break;
158 case 'v':
159 verbose++;
160 break;
161 case 'X':
162 doFork = true;
163 reExecute = true;
164 break;
165 default:
166 usage(argv[0]);
167 }
168 }
169
170 // take no non-option arguments
171 if (optind < argc)
172 usage(argv[0]);
173
174 // figure out the bootstrap name
175 if (!bootstrapName) {
176 bootstrapName = getenv(SECURITYSERVER_BOOTSTRAP_ENV);
177 if (!bootstrapName)
178 {
179 bootstrapName = SECURITYSERVER_BOOTSTRAP_NAME;
180 }
181 else
182 {
183 messagingName = bootstrapName;
184 }
185 }
186 else
187 {
188 messagingName = bootstrapName;
189 }
190
191 // configure logging first
192 if (debugMode) {
193 Syslog::open(bootstrapName, LOG_AUTHPRIV, LOG_PERROR);
194 Syslog::notice("%s started in debug mode", argv[0]);
195 } else {
196 Syslog::open(bootstrapName, LOG_AUTHPRIV, LOG_CONS);
197 }
198
199 // if we're not running as root in production mode, fail
200 // in debug mode, issue a warning
201 if (uid_t uid = getuid()) {
202 #if defined(NDEBUG)
203 Syslog::alert("Tried to run securityd as user %d: aborted", uid);
204 fprintf(stderr, "You are not allowed to run securityd\n");
205 exit(1);
206 #else
207 fprintf(stderr, "securityd is unprivileged (uid=%d); some features may not work.\n", uid);
208 #endif //NDEBUG
209 }
210
211 // turn into a properly diabolical daemon unless debugMode is on
212 if (!debugMode && getppid() != 1) {
213 if (!Daemon::incarnate(doFork))
214 exit(1); // can't daemonize
215
216 if (reExecute && !Daemon::executeSelf(argv))
217 exit(1); // can't self-execute
218 }
219
220 // arm signal handlers; code below may generate signals we want to see
221 if (signal(SIGCHLD, handleSignals) == SIG_ERR
222 || signal(SIGINT, handleSignals) == SIG_ERR
223 || signal(SIGTERM, handleSignals) == SIG_ERR
224 || signal(SIGPIPE, handleSignals) == SIG_ERR
225 #if !defined(NDEBUG)
226 || signal(SIGUSR1, handleSignals) == SIG_ERR
227 #endif //NDEBUG
228 || signal(SIGUSR2, handleSignals) == SIG_ERR) {
229 perror("signal");
230 exit(1);
231 }
232
233 // create an Authorization engine
234 Authority authority(authorizationConfig);
235
236 // introduce all supported ACL subject types
237 new AnyAclSubject::Maker();
238 new PasswordAclSubject::Maker();
239 new ProtectedPasswordAclSubject::Maker();
240 new PromptedAclSubject::Maker();
241 new ThresholdAclSubject::Maker();
242 new CommentAclSubject::Maker();
243 new ProcessAclSubject::Maker();
244 new CodeSignatureAclSubject::Maker();
245 new KeychainPromptAclSubject::Maker(keychainAclDefault);
246 new PreAuthorizationAcls::OriginMaker();
247 new PreAuthorizationAcls::SourceMaker();
248
249 // establish the code equivalents database
250 CodeSignatures codeSignatures(equivDbFile);
251
252 // create the main server object and register it
253 Server server(authority, codeSignatures, bootstrapName);
254
255 // Remember the primary service port to send signal events to
256 gMainServerPort = server.primaryServicePort();
257
258 // set server configuration from arguments, if specified
259 if (workerTimeout)
260 server.timeout(workerTimeout);
261 if (maxThreads)
262 server.maxThreads(maxThreads);
263 server.floatingThread(true);
264 server.waitForClients(waitForClients);
265 server.verbosity(verbose);
266
267 // add the RNG seed timer
268 # if defined(NDEBUG)
269 EntropyManager entropy(server, entropyFile);
270 # else
271 if (getuid() == 0) new EntropyManager(server, entropyFile);
272 # endif
273
274 // create a smartcard monitor to manage external token devices
275 gPCSC = new PCSCMonitor(server, tokenCacheDir, scOptions(smartCardOptions));
276
277 // create the RootSession object (if -d, give it graphics and tty attributes)
278 RootSession rootSession(debugMode ? (sessionHasGraphicAccess | sessionHasTTY) : 0, server);
279
280 // create a monitor thread to watch for audit session events
281 AuditMonitor audits(gMainServerPort);
282 audits.run();
283
284 // install MDS (if needed) and initialize the local CSSM
285 server.loadCssm(mdsIsInstalled);
286
287 // create the shared memory notification hub
288 new SharedMemoryListener(messagingName, kSharedMemoryPoolSize);
289
290 // okay, we're ready to roll
291 SECURITYD_INITIALIZED((char*)bootstrapName);
292 Syslog::notice("Entering service");
293
294 // go
295 server.run();
296
297 // fell out of runloop (should not happen)
298 Syslog::alert("Aborting");
299 return 1;
300 }
301
302
303 //
304 // Issue usage message and die
305 //
306 static void usage(const char *me)
307 {
308 fprintf(stderr, "Usage: %s [-dwX]"
309 "\n\t[-a authConfigFile] Authorization configuration file"
310 "\n\t[-c tokencache] smartcard token cache directory"
311 "\n\t[-e equivDatabase] path to code equivalence database"
312 "\n\t[-N serviceName] MACH service name"
313 "\n\t[-s off|on|conservative|aggressive] smartcard operation level"
314 "\n\t[-t maxthreads] [-T threadTimeout] server thread control"
315 "\n", me);
316 exit(2);
317 }
318
319
320 //
321 // Translate strings (e.g. "conservative") into PCSCMonitor service levels
322 //
323 static PCSCMonitor::ServiceLevel scOptions(const char *optionString)
324 {
325 if (optionString)
326 if (!strcmp(optionString, "off"))
327 return PCSCMonitor::forcedOff;
328 else if (!strcmp(optionString, "on"))
329 return PCSCMonitor::forcedOn;
330 else if (!strcmp(optionString, "conservative"))
331 return PCSCMonitor::conservative;
332 else if (!strcmp(optionString, "aggressive"))
333 return PCSCMonitor::aggressive;
334 else if (!strcmp(optionString, "external"))
335 return PCSCMonitor::externalDaemon;
336 else
337 usage("securityd");
338 else
339 return PCSCMonitor::aggressive;
340 }
341
342
343 //
344 // Handle signals.
345 // We send ourselves a message (through the "self" service), so actual
346 // actions happen on the normal event loop path. Note that another thread
347 // may be picking up the message immediately.
348 //
349 static void handleSignals(int sig)
350 {
351 SECURITYD_SIGNAL_RECEIVED(sig);
352 if (kern_return_t rc = self_client_handleSignal(gMainServerPort, mach_task_self(), sig))
353 Syslog::error("self-send failed (mach error %d)", rc);
354 }