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