]> git.saurik.com Git - apple/security.git/blob - authd/engine.c
Security-55471.tar.gz
[apple/security.git] / authd / engine.c
1 /* Copyright (c) 2012 Apple Inc. All rights reserved. */
2
3 #include "engine.h"
4 #include "rule.h"
5 #include "authitems.h"
6 #include "authtoken.h"
7 #include "agent.h"
8 #include "process.h"
9 #include "debugging.h"
10 #include "server.h"
11 #include "credential.h"
12 #include "session.h"
13 #include "mechanism.h"
14 #include "authutilities.h"
15 #include "ccaudit.h"
16 #include "connection.h"
17
18 #include <pwd.h>
19 #include <Security/checkpw.h>
20 int checkpw_internal( const struct passwd *pw, const char* password );
21
22 #include <Security/AuthorizationTags.h>
23 #include <Security/AuthorizationTagsPriv.h>
24 #include <Security/AuthorizationPlugin.h>
25 #include <sandbox.h>
26
27 static void _set_process_hints(auth_items_t, process_t);
28 static void _set_process_immutable_hints(auth_items_t, process_t);
29 static void _set_auth_token_hints(auth_items_t, auth_token_t);
30 static OSStatus _evaluate_user_credential_for_rule(engine_t, credential_t, rule_t, bool, bool, enum Reason *);
31 static void _engine_set_credential(engine_t, credential_t, bool);
32 static OSStatus _evaluate_rule(engine_t, rule_t);
33
34 enum {
35 kEngineHintsFlagTemporary = (1 << 30)
36 };
37
38 #pragma mark -
39 #pragma mark engine creation
40
41 struct _engine_s {
42 __AUTH_BASE_STRUCT_HEADER__;
43
44 connection_t conn;
45 process_t proc;
46 auth_token_t auth;
47
48 AuthorizationFlags flags;
49 auth_items_t hints;
50 auth_items_t context;
51 auth_items_t sticky_context;
52 auth_items_t immutable_hints;
53
54 auth_rights_t grantedRights;
55
56 enum Reason reason;
57 int32_t tries;
58
59 CFAbsoluteTime now;
60
61 credential_t sessionCredential;
62 CFMutableSetRef credentials;
63 CFMutableSetRef effectiveCredentials;
64
65 CFMutableDictionaryRef mechanism_agents;
66
67 // set only in engine_authorize
68 const char * currentRightName; // weak ref
69 rule_t currentRule; // weak ref
70
71 rule_t authenticateRule;
72
73 bool dismissed;
74 };
75
76 static void
77 _engine_finalizer(CFTypeRef value)
78 {
79 engine_t engine = (engine_t)value;
80
81 CFReleaseSafe(engine->mechanism_agents);
82 CFReleaseSafe(engine->conn);
83 CFReleaseSafe(engine->auth);
84 CFReleaseSafe(engine->hints);
85 CFReleaseSafe(engine->context);
86 CFReleaseSafe(engine->immutable_hints);
87 CFReleaseSafe(engine->sticky_context);
88 CFReleaseSafe(engine->grantedRights);
89 CFReleaseSafe(engine->sessionCredential);
90 CFReleaseSafe(engine->credentials);
91 CFReleaseSafe(engine->effectiveCredentials);
92 CFReleaseSafe(engine->authenticateRule);
93 }
94
95 AUTH_TYPE_INSTANCE(engine,
96 .init = NULL,
97 .copy = NULL,
98 .finalize = _engine_finalizer,
99 .equal = NULL,
100 .hash = NULL,
101 .copyFormattingDesc = NULL,
102 .copyDebugDesc = NULL
103 );
104
105 static CFTypeID engine_get_type_id() {
106 static CFTypeID type_id = _kCFRuntimeNotATypeID;
107 static dispatch_once_t onceToken;
108
109 dispatch_once(&onceToken, ^{
110 type_id = _CFRuntimeRegisterClass(&_auth_type_engine);
111 });
112
113 return type_id;
114 }
115
116 engine_t
117 engine_create(connection_t conn, auth_token_t auth)
118 {
119 engine_t engine = NULL;
120 require(conn != NULL, done);
121 require(auth != NULL, done);
122
123 engine = (engine_t)_CFRuntimeCreateInstance(kCFAllocatorDefault, engine_get_type_id(), AUTH_CLASS_SIZE(engine), NULL);
124 require(engine != NULL, done);
125
126 engine->conn = (connection_t)CFRetain(conn);
127 engine->proc = connection_get_process(conn);
128 engine->auth = (auth_token_t)CFRetain(auth);
129
130 engine->hints = auth_items_create();
131 engine->context = auth_items_create();
132 engine->immutable_hints = auth_items_create();
133 engine->sticky_context = auth_items_create();
134 _set_process_hints(engine->hints, engine->proc);
135 _set_process_immutable_hints(engine->immutable_hints, engine->proc);
136 _set_auth_token_hints(engine->hints, auth);
137
138 engine->grantedRights = auth_rights_create();
139
140 engine->reason = noReason;
141
142 engine->now = CFAbsoluteTimeGetCurrent();
143
144 session_update(auth_token_get_session(engine->auth));
145 engine->sessionCredential = credential_create(session_get_uid(auth_token_get_session(engine->auth)));
146 engine->credentials = CFSetCreateMutable(kCFAllocatorDefault, 0, &kCFTypeSetCallBacks);
147 engine->effectiveCredentials = CFSetCreateMutable(kCFAllocatorDefault, 0, &kCFTypeSetCallBacks);
148
149 session_credentials_iterate(auth_token_get_session(engine->auth), ^bool(credential_t cred) {
150 CFSetAddValue(engine->effectiveCredentials, cred);
151 return true;
152 });
153
154 auth_token_credentials_iterate(engine->auth, ^bool(credential_t cred) {
155 // we added all session credentials already now just add all previously acquired credentials
156 if (!credential_get_shared(cred)) {
157 CFSetAddValue(engine->credentials, cred);
158 }
159 return true;
160 });
161
162 engine->mechanism_agents = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
163
164 done:
165 return engine;
166 }
167
168 #pragma mark -
169 #pragma mark agent hints
170
171 void
172 _set_process_hints(auth_items_t hints, process_t proc)
173 {
174 // process information
175 RequestorType type = bundle;
176 auth_items_set_data(hints, AGENT_HINT_CLIENT_TYPE, &type, sizeof(type));
177 auth_items_set_int(hints, AGENT_HINT_CLIENT_PID, process_get_pid(proc));
178 auth_items_set_uint(hints, AGENT_HINT_CLIENT_UID, process_get_uid(proc));
179 }
180
181 void
182 _set_process_immutable_hints(auth_items_t immutable_hints, process_t proc)
183 {
184 // process information - immutable
185 auth_items_set_bool(immutable_hints, AGENT_HINT_PROCESS_SIGNED, process_apple_signed(proc));
186 }
187
188 void
189 _set_auth_token_hints(auth_items_t hints, auth_token_t auth)
190 {
191 auth_items_set_string(hints, AGENT_HINT_CLIENT_PATH, auth_token_get_code_url(auth));
192 auth_items_set_int(hints, AGENT_HINT_CREATOR_PID, auth_token_get_pid(auth));
193 const audit_info_s * info = auth_token_get_audit_info(auth);
194 auth_items_set_data(hints, AGENT_HINT_CREATOR_AUDIT_TOKEN, &info->opaqueToken, sizeof(info->opaqueToken));
195 }
196
197 static void
198 _set_right_hints(auth_items_t hints, const char * right)
199 {
200 auth_items_set_string(hints, AGENT_HINT_AUTHORIZE_RIGHT, right);
201 }
202
203 static void
204 _set_rule_hints(auth_items_t hints, rule_t rule)
205 {
206 auth_items_set_string(hints, AGENT_HINT_AUTHORIZE_RULE, rule_get_name(rule));
207 const char * group = rule_get_group(rule);
208 if (rule_get_class(rule) == RC_USER && group != NULL) {
209 auth_items_set_string(hints, AGENT_HINT_REQUIRE_USER_IN_GROUP, group);
210 } else {
211 auth_items_remove(hints, AGENT_HINT_REQUIRE_USER_IN_GROUP);
212 }
213 }
214
215 static void
216 _set_localization_hints(authdb_connection_t dbconn, auth_items_t hints, rule_t rule)
217 {
218 char * key = calloc(1u, 128);
219
220 authdb_step(dbconn, "SELECT lang,value FROM prompts WHERE r_id = ?", ^(sqlite3_stmt *stmt) {
221 sqlite3_bind_int64(stmt, 1, rule_get_id(rule));
222 }, ^bool(auth_items_t data) {
223 snprintf(key, 128, "%s%s", kAuthorizationRuleParameterDescription, auth_items_get_string(data, "lang"));
224 auth_items_set_string(hints, key, auth_items_get_string(data, "value"));
225 auth_items_set_flags(hints, key, kEngineHintsFlagTemporary);
226 return true;
227 });
228
229 authdb_step(dbconn, "SELECT lang,value FROM buttons WHERE r_id = ?", ^(sqlite3_stmt *stmt) {
230 sqlite3_bind_int64(stmt, 1, rule_get_id(rule));
231 }, ^bool(auth_items_t data) {
232 snprintf(key, 128, "%s%s", kAuthorizationRuleParameterButton, auth_items_get_string(data, "lang"));
233 auth_items_set_string(hints, key, auth_items_get_string(data, "value"));
234 auth_items_set_flags(hints, key, kEngineHintsFlagTemporary);
235 return true;
236 });
237
238 free_safe(key);
239 }
240
241 static void
242 _set_session_hints(engine_t engine, rule_t rule)
243 {
244 LOGV("engine[%i]: ** prepare agent hints for rule %s", connection_get_pid(engine->conn), rule_get_name(rule));
245 if (_evaluate_user_credential_for_rule(engine, engine->sessionCredential, rule, true, true, NULL) == errAuthorizationSuccess) {
246 const char * tmp = credential_get_name(engine->sessionCredential);
247 if (tmp != NULL) {
248 auth_items_set_string(engine->hints, AGENT_HINT_SUGGESTED_USER, tmp);
249 }
250 tmp = credential_get_realname(engine->sessionCredential);
251 if (tmp != NULL) {
252 auth_items_set_string(engine->hints, AGENT_HINT_SUGGESTED_USER_LONG, tmp);
253 }
254 } else {
255 auth_items_remove(engine->hints, AGENT_HINT_SUGGESTED_USER);
256 auth_items_remove(engine->hints, AGENT_HINT_SUGGESTED_USER_LONG);
257 }
258 }
259
260 #pragma mark -
261 #pragma mark right processing
262
263 static OSStatus
264 _evaluate_credential_for_rule(engine_t engine, credential_t cred, rule_t rule, bool ignoreShared, bool sessionOwner, enum Reason * reason)
265 {
266 if (auth_token_least_privileged(engine->auth)) {
267 if (credential_is_right(cred) && credential_get_valid(cred) && _compare_string(engine->currentRightName, credential_get_name(cred))) {
268 if (!ignoreShared) {
269 if (!rule_get_shared(rule) && credential_get_shared(cred)) {
270 LOGV("engine[%i]: - shared right %s (does NOT satisfy rule)", connection_get_pid(engine->conn), credential_get_name(cred));
271 if (reason) { *reason = unknownReason; }
272 return errAuthorizationDenied;
273 }
274 }
275
276 return errAuthorizationSuccess;
277 } else {
278 if (reason) { *reason = unknownReason; }
279 return errAuthorizationDenied;
280 }
281 } else {
282 return _evaluate_user_credential_for_rule(engine,cred,rule,ignoreShared,sessionOwner, reason);
283 }
284 }
285
286 static OSStatus
287 _evaluate_user_credential_for_rule(engine_t engine, credential_t cred, rule_t rule, bool ignoreShared, bool sessionOwner, enum Reason * reason)
288 {
289 const char * cred_label = sessionOwner ? "session owner" : "credential";
290 LOGV("engine[%i]: - validating %s%s %s (%i) for %s", connection_get_pid(engine->conn),
291 credential_get_shared(cred) ? "shared " : "",
292 cred_label,
293 credential_get_name(cred),
294 credential_get_uid(cred),
295 rule_get_name(rule));
296
297 if (rule_get_class(rule) != RC_USER) {
298 LOGV("engine[%i]: - invalid rule class %i (denied)", connection_get_pid(engine->conn), rule_get_class(rule));
299 return errAuthorizationDenied;
300 }
301
302 if (credential_get_valid(cred) != true) {
303 LOGV("engine[%i]: - %s %i invalid (does NOT satisfy rule)", connection_get_pid(engine->conn), cred_label, credential_get_uid(cred));
304 if (reason) { *reason = invalidPassphrase; }
305 return errAuthorizationDenied;
306 }
307
308 if (engine->now - credential_get_creation_time(cred) > rule_get_timeout(rule)) {
309 LOGV("engine[%i]: - %s %i expired '%f > %lli' (does NOT satisfy rule)", connection_get_pid(engine->conn), cred_label, credential_get_uid(cred),
310 (engine->now - credential_get_creation_time(cred)), rule_get_timeout(rule));
311 if (reason) { *reason = unknownReason; }
312 return errAuthorizationDenied;
313 }
314
315
316 if (!ignoreShared) {
317 if (!rule_get_shared(rule) && credential_get_shared(cred)) {
318 LOGV("engine[%i]: - shared %s %i (does NOT satisfy rule)", connection_get_pid(engine->conn), cred_label, credential_get_uid(cred));
319 if (reason) { *reason = unknownReason; }
320 return errAuthorizationDenied;
321 }
322 }
323
324 if (credential_get_uid(cred) == 0) {
325 LOGV("engine[%i]: - %s %i has uid 0 (does satisfy rule)", connection_get_pid(engine->conn), cred_label, credential_get_uid(cred));
326 return errAuthorizationSuccess;
327 }
328
329 if (rule_get_session_owner(rule)) {
330 if (credential_get_uid(cred) == session_get_uid(auth_token_get_session(engine->auth))) {
331 LOGV("engine[%i]: - %s %i is session owner (does satisfy rule)", connection_get_pid(engine->conn), cred_label, credential_get_uid(cred));
332 return errAuthorizationSuccess;
333 }
334 }
335
336 if (rule_get_group(rule) != NULL) {
337 do
338 {
339 // This allows testing a group modifier without prompting the user
340 // When (authenticate-user = false) we are just testing the creator uid.
341 // If a group modifier is enabled (RuleFlagEntitledAndGroup | RuleFlagVPNEntitledAndGroup)
342 // we want to skip the creator uid group check.
343 // group modifiers are checked early during the evaluation in _check_entitlement_for_rule
344 if (!rule_get_authenticate_user(rule)) {
345 if (rule_check_flags(rule, RuleFlagEntitledAndGroup | RuleFlagVPNEntitledAndGroup)) {
346 break;
347 }
348 }
349
350 if (credential_check_membership(cred, rule_get_group(rule))) {
351 LOGV("engine[%i]: - %s %i is member of group %s (does satisfy rule)", connection_get_pid(engine->conn), cred_label, credential_get_uid(cred), rule_get_group(rule));
352 return errAuthorizationSuccess;
353 } else {
354 if (reason) { *reason = userNotInGroup; }
355 }
356 } while (0);
357 } else if (rule_get_session_owner(rule)) { // rule asks only if user is the session owner
358 if (reason) { *reason = unacceptableUser; }
359 }
360
361 LOGV("engine[%i]: - %s %i (does NOT satisfy rule)", connection_get_pid(engine->conn), cred_label, credential_get_uid(cred));
362 return errAuthorizationDenied;
363 }
364
365 static agent_t
366 _get_agent(engine_t engine, mechanism_t mech, bool create, bool firstMech)
367 {
368 agent_t agent = (agent_t)CFDictionaryGetValue(engine->mechanism_agents, mech);
369 if (create && !agent) {
370 agent = agent_create(engine, mech, engine->auth, engine->proc, firstMech);
371 if (agent) {
372 CFDictionaryAddValue(engine->mechanism_agents, mech, agent);
373 CFReleaseSafe(agent);
374 }
375 }
376 return agent;
377 }
378
379 static uint64_t
380 _evaluate_builtin_mechanism(engine_t engine, mechanism_t mech)
381 {
382 uint64_t result = kAuthorizationResultDeny;
383
384 switch (mechanism_get_type(mech)) {
385 case kMechanismTypeEntitled:
386 if (auth_token_has_entitlement_for_right(engine->auth, engine->currentRightName)) {
387 result = kAuthorizationResultAllow;
388 }
389 break;
390 default:
391 break;
392 }
393
394 return result;
395 }
396
397
398 static OSStatus
399 _evaluate_mechanisms(engine_t engine, CFArrayRef mechanisms)
400 {
401 uint64_t result = kAuthorizationResultAllow;
402 ccaudit_t ccaudit = ccaudit_create(engine->proc, engine->auth, AUE_ssauthmech);
403 auth_items_t context = auth_items_create();
404 auth_items_t hints = auth_items_create();
405
406 auth_items_copy(context, engine->context);
407 auth_items_copy(hints, engine->hints);
408 auth_items_copy(context, engine->sticky_context);
409
410 CFIndex count = CFArrayGetCount(mechanisms);
411 for (CFIndex i = 0; i < count; i++) {
412 mechanism_t mech = (mechanism_t)CFArrayGetValueAtIndex(mechanisms, i);
413
414 if (mechanism_get_type(mech)) {
415 LOGV("engine[%i]: running builtin mechanism %s (%li of %li)", connection_get_pid(engine->conn), mechanism_get_string(mech), i+1, count);
416 result = _evaluate_builtin_mechanism(engine, mech);
417 } else {
418 agent_t agent = _get_agent(engine, mech, true, i == 0);
419 require_action(agent != NULL, done, result = kAuthorizationResultUndefined; LOGE("engine[%i]: error creating mechanism agent", connection_get_pid(engine->conn)));
420 LOGV("engine[%i]: running mechanism %s (%li of %li)", connection_get_pid(engine->conn), mechanism_get_string(agent_get_mechanism(agent)), i+1, count);
421 result = agent_run(agent, hints, context, engine->immutable_hints);
422
423 auth_items_copy(context, agent_get_context(agent));
424 auth_items_copy(hints, agent_get_hints(agent));
425
426 bool interrupted = false;
427 for (CFIndex i2 = 0; i2 != i; i2++) {
428 agent_t agent2 = _get_agent(engine, (mechanism_t)CFArrayGetValueAtIndex(mechanisms, i2), false, i == 0);
429 if (agent_get_state(agent2) == interrupting) {
430 agent_deactivate(agent);
431 interrupted = true;
432 i = i2 - 1;
433 char * buf = NULL;
434 asprintf(&buf, "evaluation interrupted by %s; restarting evaluation there", mechanism_get_string(agent_get_mechanism(agent2)));
435 ccaudit_log_mechanism(ccaudit, engine->currentRightName, mechanism_get_string(agent_get_mechanism(agent2)), kAuthorizationResultAllow, buf);
436 free_safe(buf);
437 auth_items_copy(context, agent_get_context(agent2));
438 auth_items_copy(hints, agent_get_hints(agent2));
439 break;
440 }
441 }
442
443 if (interrupted) {
444 LOGV("engine[%i]: mechanisms interrupted", connection_get_pid(engine->conn));
445 enum Reason reason = worldChanged;
446 auth_items_set_data(hints, AGENT_HINT_RETRY_REASON, &reason, sizeof(reason));
447 result = kAuthorizationResultAllow;
448 _cf_dictionary_iterate(engine->mechanism_agents, ^bool(CFTypeRef key __attribute__((__unused__)), CFTypeRef value) {
449 agent_t tempagent = (agent_t)value;
450 agent_clear_interrupt(tempagent);
451 return true;
452 });
453 }
454 }
455
456 if (result == kAuthorizationResultAllow) {
457 ccaudit_log_mechanism(ccaudit, engine->currentRightName, mechanism_get_string(mech), kAuthorizationResultAllow, NULL);
458 } else {
459 ccaudit_log_mechanism(ccaudit, engine->currentRightName, mechanism_get_string(mech), (uint32_t)result, NULL);
460 break;
461 }
462 }
463
464 done:
465 if ((result == kAuthorizationResultUserCanceled) || (result == kAuthorizationResultAllow)) {
466 // only make non-sticky context values available externally
467 auth_items_set_flags(context, kAuthorizationEnvironmentPassword, kAuthorizationContextFlagVolatile);
468 auth_items_copy_with_flags(engine->context, context, kAuthorizationContextFlagExtractable | kAuthorizationContextFlagVolatile);
469 } else if (result == kAuthorizationResultDeny) {
470 auth_items_clear(engine->sticky_context);
471 // save off sticky values in context
472 auth_items_copy_with_flags(engine->sticky_context, context, kAuthorizationContextFlagSticky);
473 }
474
475 CFReleaseSafe(ccaudit);
476 CFReleaseSafe(context);
477 CFReleaseSafe(hints);
478
479 switch(result)
480 {
481 case kAuthorizationResultDeny:
482 return errAuthorizationDenied;
483 case kAuthorizationResultUserCanceled:
484 return errAuthorizationCanceled;
485 case kAuthorizationResultAllow:
486 return errAuthorizationSuccess;
487 case kAuthorizationResultUndefined:
488 return errAuthorizationInternal;
489 default:
490 {
491 LOGV("engine[%i]: unexpected error result", connection_get_pid(engine->conn));
492 return errAuthorizationInternal;
493 }
494 }
495 }
496
497 static OSStatus
498 _evaluate_authentication(engine_t engine, rule_t rule)
499 {
500 OSStatus status = errAuthorizationDenied;
501 ccaudit_t ccaudit = ccaudit_create(engine->proc, engine->auth, AUE_ssauthint);
502 LOGV("engine[%i]: evaluate authentication", connection_get_pid(engine->conn));
503 _set_rule_hints(engine->hints, rule);
504 _set_session_hints(engine, rule);
505
506 CFArrayRef mechanisms = rule_get_mechanisms(rule);
507 if (!(CFArrayGetCount(mechanisms) > 0)) {
508 mechanisms = rule_get_mechanisms(engine->authenticateRule);
509 }
510 require_action(CFArrayGetCount(mechanisms) > 0, done, LOGV("engine[%i]: error no mechanisms found", connection_get_pid(engine->conn)));
511
512 int64_t ruleTries = rule_get_tries(rule);
513 for (engine->tries = 0; engine->tries < ruleTries; engine->tries++) {
514
515 auth_items_set_data(engine->hints, AGENT_HINT_RETRY_REASON, &engine->reason, sizeof(engine->reason));
516 auth_items_set_int(engine->hints, AGENT_HINT_TRIES, engine->tries);
517
518 status = _evaluate_mechanisms(engine, mechanisms);
519
520 LOGV("engine[%i]: evaluate mechanisms result %i", connection_get_pid(engine->conn), status);
521
522 // successfully ran mechanisms to obtain credential
523 if (status == errAuthorizationSuccess) {
524 // deny is the default
525 status = errAuthorizationDenied;
526
527 credential_t newCred = NULL;
528 if (auth_items_exist(engine->context, "uid")) {
529 newCred = credential_create(auth_items_get_uint(engine->context, "uid"));
530 } else {
531 LOGV("engine[%i]: mechanism failed to return a valid uid", connection_get_pid(engine->conn));
532 }
533
534 if (newCred) {
535 if (credential_get_valid(newCred)) {
536 LOG("UID %u authenticated as user %s (UID %u) for right '%s'", auth_token_get_uid(engine->auth), credential_get_name(newCred), credential_get_uid(newCred), engine->currentRightName);
537 ccaudit_log_success(ccaudit, newCred, engine->currentRightName);
538 } else {
539 LOG("UID %u failed to authenticate as user '%s' for right '%s'", auth_token_get_uid(engine->auth), auth_items_get_string(engine->context, "username"), engine->currentRightName);
540 ccaudit_log_failure(ccaudit, auth_items_get_string(engine->context, "username"), engine->currentRightName);
541 }
542
543 status = _evaluate_user_credential_for_rule(engine, newCred, rule, true, false, &engine->reason);
544
545 if (status == errAuthorizationSuccess) {
546 _engine_set_credential(engine, newCred, rule_get_shared(rule));
547 CFReleaseSafe(newCred);
548
549 if (auth_token_least_privileged(engine->auth)) {
550 credential_t rightCred = credential_create_with_right(engine->currentRightName);
551 _engine_set_credential(engine, rightCred, rule_get_shared(rule));
552 CFReleaseSafe(rightCred);
553 }
554
555 session_t session = auth_token_get_session(engine->auth);
556 if (credential_get_uid(newCred) == session_get_uid(session)) {
557 LOGV("engine[%i]: authenticated as the session owner", connection_get_pid(engine->conn));
558 session_set_attributes(auth_token_get_session(engine->auth), AU_SESSION_FLAG_HAS_AUTHENTICATED);
559 }
560
561 break;
562 }
563
564 CFReleaseSafe(newCred);
565 }
566
567 } else if (status == errAuthorizationCanceled || status == errAuthorizationInternal) {
568 break;
569 } else if (status == errAuthorizationDenied) {
570 engine->reason = invalidPassphrase;
571 }
572 }
573
574 if (engine->tries == ruleTries) {
575 engine->reason = tooManyTries;
576 auth_items_set_data(engine->hints, AGENT_HINT_RETRY_REASON, &engine->reason, sizeof(engine->reason));
577 auth_items_set_int(engine->hints, AGENT_HINT_TRIES, engine->tries);
578 _evaluate_mechanisms(engine, mechanisms);
579 ccaudit_log(ccaudit, engine->currentRightName, NULL, 1113);
580 }
581
582 done:
583 CFReleaseSafe(ccaudit);
584
585 return status;
586 }
587
588 static bool
589 _check_entitlement_for_rule(engine_t engine, rule_t rule)
590 {
591 bool entitled = false;
592 CFTypeRef value = NULL;
593
594 if (rule_check_flags(rule, RuleFlagEntitledAndGroup)) {
595 if (auth_token_has_entitlement_for_right(engine->auth, engine->currentRightName)) {
596 if (credential_check_membership(auth_token_get_credential(engine->auth), rule_get_group(rule))) {
597 LOGV("engine[%i]: creator of authorization has entitlement for right %s and is member of group '%s'", connection_get_pid(engine->conn), engine->currentRightName, rule_get_group(rule));
598 entitled = true;
599 goto done;
600 }
601 }
602 }
603
604 if (rule_check_flags(rule, RuleFlagVPNEntitledAndGroup)) {
605 // com.apple.networking.vpn.configuration is an array we only check for it's existence
606 value = auth_token_copy_entitlement_value(engine->auth, "com.apple.networking.vpn.configuration");
607 if (value) {
608 if (credential_check_membership(auth_token_get_credential(engine->auth), rule_get_group(rule))) {
609 LOGV("engine[%i]: creator of authorization has VPN entitlement and is member of group '%s'", connection_get_pid(engine->conn), rule_get_group(rule));
610 entitled = true;
611 goto done;
612 }
613 }
614 }
615
616 done:
617 CFReleaseSafe(value);
618 return entitled;
619 }
620
621 static OSStatus
622 _evaluate_class_user(engine_t engine, rule_t rule)
623 {
624 __block OSStatus status = errAuthorizationDenied;
625
626 if (_check_entitlement_for_rule(engine,rule)) {
627 return errAuthorizationSuccess;
628 }
629
630 if (rule_get_allow_root(rule) && auth_token_get_uid(engine->auth) == 0) {
631 LOGV("engine[%i]: creator of authorization has uid == 0 granting right %s", connection_get_pid(engine->conn), engine->currentRightName);
632 return errAuthorizationSuccess;
633 }
634
635 if (!rule_get_authenticate_user(rule)) {
636 status = _evaluate_user_credential_for_rule(engine, engine->sessionCredential, rule, true, true, NULL);
637
638 if (status == errAuthorizationSuccess) {
639 return errAuthorizationSuccess;
640 }
641
642 return errAuthorizationDenied;
643 }
644
645 // First -- check all the credentials we have either acquired or currently have
646 _cf_set_iterate(engine->credentials, ^bool(CFTypeRef value) {
647 credential_t cred = (credential_t)value;
648 // Passed-in user credentials are allowed for least-privileged mode
649 if (auth_token_least_privileged(engine->auth) && !credential_is_right(cred) && credential_get_valid(cred)) {
650 status = _evaluate_user_credential_for_rule(engine, cred, rule, false, false, NULL);
651 if (errAuthorizationSuccess == status) {
652 credential_t rightCred = credential_create_with_right(engine->currentRightName);
653 _engine_set_credential(engine,rightCred,rule_get_shared(rule));
654 CFReleaseSafe(rightCred);
655 return false; // exit loop
656 }
657 }
658
659 status = _evaluate_credential_for_rule(engine, cred, rule, false, false, NULL);
660 if (status == errAuthorizationSuccess) {
661 return false; // exit loop
662 }
663 return true;
664 });
665
666 if (status == errAuthorizationSuccess) {
667 return status;
668 }
669
670 // Second -- go through the credentials associated to the authorization token session/auth token
671 _cf_set_iterate(engine->effectiveCredentials, ^bool(CFTypeRef value) {
672 credential_t cred = (credential_t)value;
673 status = _evaluate_credential_for_rule(engine, cred, rule, false, false, NULL);
674 if (status == errAuthorizationSuccess) {
675 // Add the credential we used to the output set.
676 _engine_set_credential(engine, cred, false);
677 return false; // exit loop
678 }
679 return true;
680 });
681
682 if (status == errAuthorizationSuccess) {
683 return status;
684 }
685
686 // Finally - we didn't find a credential. Obtain a new credential if our flags let us do so.
687 if (!(engine->flags & kAuthorizationFlagExtendRights)) {
688 LOGV("engine[%i]: authorization denied (kAuthorizationFlagExtendRights not set)", connection_get_pid(engine->conn));
689 return errAuthorizationDenied;
690 }
691
692 // authorization that timeout immediately cannot be preauthorized
693 if (engine->flags & kAuthorizationFlagPreAuthorize && rule_get_timeout(rule) == 0) {
694 return errAuthorizationSuccess;
695 }
696
697 if (!(engine->flags & kAuthorizationFlagInteractionAllowed)) {
698 LOGV("engine[%i]: Interaction not allowed (kAuthorizationFlagInteractionAllowed not set)", connection_get_pid(engine->conn));
699 return errAuthorizationInteractionNotAllowed;
700 }
701
702 if (!(session_get_attributes(auth_token_get_session(engine->auth)) & AU_SESSION_FLAG_HAS_GRAPHIC_ACCESS)) {
703 LOGV("engine[%i]: Interaction not allowed (session has no ui access)", connection_get_pid(engine->conn));
704 return errAuthorizationInteractionNotAllowed;
705 }
706
707 if (server_in_dark_wake()) {
708 LOGV("engine[%i]: authorization denied (in DarkWake)", connection_get_pid(engine->conn));
709 return errAuthorizationDenied;
710 }
711
712 return _evaluate_authentication(engine,rule);
713 }
714
715 static OSStatus
716 _evaluate_class_rule(engine_t engine, rule_t rule)
717 {
718 __block OSStatus status = errAuthorizationDenied;
719 int64_t kofn = rule_get_kofn(rule);
720
721 uint32_t total = (uint32_t)rule_get_delegates_count(rule);
722 __block uint32_t success_count = 0;
723 __block uint32_t count = 0;
724 LOGV("engine[%i]: ** rule %s has %zi delegates kofn = %lli", connection_get_pid(engine->conn), rule_get_name(rule), total, kofn);
725 rule_delegates_iterator(rule, ^bool(rule_t delegate) {
726 count++;
727
728 if (kofn != 0 && success_count == kofn) {
729 status = errAuthorizationSuccess;
730 return false;
731 }
732
733 LOGV("engine[%i]: * evaluate rule %s (%i)", connection_get_pid(engine->conn), rule_get_name(delegate), count);
734 status = _evaluate_rule(engine, delegate);
735
736 // if status is cancel/internal error abort
737 if ((status == errAuthorizationCanceled) || (status == errAuthorizationInternal))
738 return false;
739
740 if (status != errAuthorizationSuccess) {
741 if (kofn != 0) {
742 // if remaining is less then required abort
743 if ((total - count) < (kofn - success_count)) {
744 LOGD("engine[%i]: rule evaluation remaining: %i, required: %lli", connection_get_pid(engine->conn), (total - count), (kofn - success_count));
745 return false;
746 }
747 return true;
748 }
749 return false;
750 } else {
751 success_count++;
752 return true;
753 }
754 });
755
756 return status;
757 }
758
759 static OSStatus
760 _evaluate_class_mechanism(engine_t engine, rule_t rule)
761 {
762 OSStatus status = errAuthorizationDenied;
763 CFArrayRef mechanisms = NULL;
764
765 require_action(rule_get_mechanisms_count(rule) > 0, done, status = errAuthorizationSuccess; LOGV("engine[%i]: no mechanisms specified", connection_get_pid(engine->conn)));
766
767 mechanisms = rule_get_mechanisms(rule);
768
769 if (server_in_dark_wake()) {
770 CFIndex count = CFArrayGetCount(mechanisms);
771 for (CFIndex i = 0; i < count; i++) {
772 if (!mechanism_is_privileged((mechanism_t)CFArrayGetValueAtIndex(mechanisms, i))) {
773 LOGV("engine[%i]: authorization denied (in DarkWake)", connection_get_pid(engine->conn));
774 goto done;
775 }
776 }
777 }
778
779 int64_t ruleTries = rule_get_tries(rule);
780 engine->tries = 0;
781 do {
782 auth_items_set_data(engine->hints, AGENT_HINT_RETRY_REASON, &engine->reason, sizeof(engine->reason));
783 auth_items_set_int(engine->hints, AGENT_HINT_TRIES, engine->tries);
784
785 status = _evaluate_mechanisms(engine, mechanisms);
786 LOGV("engine[%i]: evaluate mechanisms result %i", connection_get_pid(engine->conn), status);
787
788 if ((status == errAuthorizationSuccess) || (status == errAuthorizationCanceled)) {
789
790 if (status == errAuthorizationSuccess) {
791 credential_t newCred = NULL;
792 if (auth_items_exist(engine->context, "uid")) {
793 newCred = credential_create(auth_items_get_uint(engine->context, "uid"));
794 } else {
795 LOGV("engine[%i]: mechanism did not return a uid", connection_get_pid(engine->conn));
796 }
797
798 if (newCred) {
799 _engine_set_credential(engine, newCred, rule_get_shared(rule));
800
801 if (auth_token_least_privileged(engine->auth)) {
802 credential_t rightCred = credential_create_with_right(engine->currentRightName);
803 _engine_set_credential(engine, rightCred, rule_get_shared(rule));
804 CFReleaseSafe(rightCred);
805 }
806
807 if (strcmp(engine->currentRightName, "system.login.console") == 0 && !auth_items_exist(engine->context, AGENT_CONTEXT_AUTO_LOGIN)) {
808 session_set_attributes(auth_token_get_session(engine->auth), AU_SESSION_FLAG_HAS_AUTHENTICATED);
809 }
810
811 CFReleaseSafe(newCred);
812 }
813 }
814 } // mechanism errAuthorizationSuccess
815
816 engine->tries++;
817
818 } while ( (status == errAuthorizationDenied) // only if we have an expected faulure we continue
819 && ((ruleTries == 0) || ((ruleTries > 0) && engine->tries < ruleTries))); // ruleTries == 0 means we try forever
820 // ruleTires > 0 means we try upto ruleTries times
821 done:
822 return status;
823 }
824
825 static OSStatus
826 _evaluate_rule(engine_t engine, rule_t rule)
827 {
828 if (rule_check_flags(rule, RuleFlagEntitled)) {
829 if (auth_token_has_entitlement_for_right(engine->auth, engine->currentRightName)) {
830 LOGV("engine[%i]: rule allow, creator of authorization has entitlement for right %s", connection_get_pid(engine->conn), engine->currentRightName);
831 return errAuthorizationSuccess;
832 }
833 }
834
835 if (rule_check_flags(rule, RuleFlagRequireAppleSigned)) {
836 if (!auth_token_apple_signed(engine->auth)) {
837 LOGV("engine[%i]: rule deny, creator of authorization is not signed by apple", connection_get_pid(engine->conn));
838 return errAuthorizationDenied;
839 }
840 }
841
842 switch (rule_get_class(rule)) {
843 case RC_ALLOW:
844 LOGV("engine[%i]: rule set to allow", connection_get_pid(engine->conn));
845 return errAuthorizationSuccess;
846 case RC_DENY:
847 LOGV("engine[%i]: rule set to deny", connection_get_pid(engine->conn));
848 return errAuthorizationDenied;
849 case RC_USER:
850 return _evaluate_class_user(engine,rule);
851 case RC_RULE:
852 return _evaluate_class_rule(engine, rule);
853 case RC_MECHANISM:
854 return _evaluate_class_mechanism(engine, rule);
855 default:
856 LOGV("engine[%i]: invalid class for rule or rule not found", connection_get_pid(engine->conn));
857 return errAuthorizationInternal;
858 }
859 }
860
861 static rule_t
862 _find_rule(engine_t engine, authdb_connection_t dbconn, const char * string)
863 {
864 rule_t r = NULL;
865 size_t sLen = strlen(string);
866
867 char * buf = calloc(1u, sLen + 1);
868 strlcpy(buf, string, sLen + 1);
869 char * ptr = buf + sLen;
870 __block int64_t count = 0;
871
872 for (;;) {
873
874 // lookup rule
875 authdb_step(dbconn, "SELECT COUNT(name) AS cnt FROM rules WHERE name = ? AND type = 1",
876 ^(sqlite3_stmt *stmt) {
877 sqlite3_bind_text(stmt, 1, buf, -1, NULL);
878 }, ^bool(auth_items_t data) {
879 count = auth_items_get_int64(data, "cnt");
880 return false;
881 });
882
883 if (count > 0) {
884 r = rule_create_with_string(buf, dbconn);
885 goto done;
886 }
887
888 // if buf ends with a . and we didn't find a rule remove .
889 if (*ptr == '.') {
890 *ptr = '\0';
891 }
892 // find any remaining . and truncate the string
893 ptr = strrchr(buf, '.');
894 if (ptr) {
895 *(ptr+1) = '\0';
896 } else {
897 break;
898 }
899 }
900
901 done:
902 free_safe(buf);
903
904 // set default if we didn't find a rule
905 if (r == NULL) {
906 r = rule_create_with_string("", dbconn);
907 if (rule_get_id(r) == 0) {
908 CFReleaseNull(r);
909 LOGE("engine[%i]: default rule lookup error (missing), using builtin defaults", connection_get_pid(engine->conn));
910 r = rule_create_default();
911 }
912 }
913 return r;
914 }
915
916 static void _parse_enviroment(engine_t engine, auth_items_t enviroment)
917 {
918 require(enviroment != NULL, done);
919
920 #if DEBUG
921 LOGV("engine[%i]: Dumping Enviroment", connection_get_pid(engine->conn));
922 _show_cf(enviroment);
923 #endif
924
925 // Check if a credential was passed into the environment and we were asked to extend the rights
926 if (engine->flags & kAuthorizationFlagExtendRights) {
927 const char * user = auth_items_get_string(enviroment, kAuthorizationEnvironmentUsername);
928 const char * pass = auth_items_get_string(enviroment, kAuthorizationEnvironmentPassword);
929 bool shared = auth_items_exist(enviroment, kAuthorizationEnvironmentShared);
930 require(user != NULL, done);
931
932 struct passwd *pw = getpwnam(user);
933 require_action(pw != NULL, done, LOGE("engine[%i]: user not found %s", connection_get_pid(engine->conn), user));
934
935 int checkpw_status = checkpw_internal(pw, pass ? pass : "");
936 require_action(checkpw_status == CHECKPW_SUCCESS, done, LOGE("engine[%i]: checkpw() returned %d; failed to authenticate user %s (uid %u).", connection_get_pid(engine->conn), checkpw_status, pw->pw_name, pw->pw_uid));
937
938 credential_t cred = credential_create(pw->pw_uid);
939 if (credential_get_valid(cred)) {
940 LOG("engine[%i]: checkpw() succeeded, creating credential for user %s", connection_get_pid(engine->conn), user);
941 _engine_set_credential(engine, cred, shared);
942
943 auth_items_set_string(engine->context, kAuthorizationEnvironmentUsername, user);
944 auth_items_set_string(engine->context, kAuthorizationEnvironmentPassword, pass ? pass : "");
945 }
946 CFReleaseSafe(cred);
947 }
948
949 done:
950 endpwent();
951 return;
952 }
953
954 static bool _verify_sandbox(engine_t engine, const char * right)
955 {
956 pid_t pid = process_get_pid(engine->proc);
957 if (sandbox_check(pid, "authorization-right-obtain", SANDBOX_FILTER_RIGHT_NAME, right)) {
958 LOGE("Sandbox denied authorizing right '%s' by client '%s' [%d]", right, process_get_code_url(engine->proc), pid);
959 return false;
960 }
961
962 pid = auth_token_get_pid(engine->auth);
963 if (auth_token_get_sandboxed(engine->auth) && sandbox_check(pid, "authorization-right-obtain", SANDBOX_FILTER_RIGHT_NAME, right)) {
964 LOGE("Sandbox denied authorizing right '%s' for authorization created by '%s' [%d]", right, auth_token_get_code_url(engine->auth), pid);
965 return false;
966 }
967
968 return true;
969 }
970
971 #pragma mark -
972 #pragma mark engine methods
973
974 OSStatus engine_authorize(engine_t engine, auth_rights_t rights, auth_items_t enviroment, AuthorizationFlags flags)
975 {
976 __block OSStatus status = errAuthorizationSuccess;
977 __block bool savePassword = false;
978 ccaudit_t ccaudit = NULL;
979
980 require(rights != NULL, done);
981
982 ccaudit = ccaudit_create(engine->proc, engine->auth, AUE_ssauthorize);
983 if (auth_rights_get_count(rights) > 0) {
984 ccaudit_log(ccaudit, "begin evaluation", NULL, 0);
985 }
986
987 engine->flags = flags;
988
989 if (enviroment) {
990 _parse_enviroment(engine, enviroment);
991 auth_items_copy(engine->hints, enviroment);
992 }
993
994 auth_items_copy(engine->context, auth_token_get_context(engine->auth));
995
996 engine->dismissed = false;
997 auth_rights_clear(engine->grantedRights);
998
999 auth_rights_iterate(rights, ^bool(const char *key) {
1000 if (!key)
1001 return true;
1002
1003
1004 if (!_verify_sandbox(engine, key)) {
1005 status = errAuthorizationDenied;
1006 return false;
1007 }
1008
1009 authdb_connection_t dbconn = authdb_connection_acquire(server_get_database()); // get db handle
1010
1011 LOGV("engine[%i]: evaluate right %s", connection_get_pid(engine->conn), key);
1012 rule_t rule = _find_rule(engine, dbconn, key);
1013 const char * rule_name = rule_get_name(rule);
1014 if (rule_name && (strcasecmp(rule_name, "") == 0)) {
1015 rule_name = "default (not defined)";
1016 }
1017 LOGV("engine[%i]: using rule %s", connection_get_pid(engine->conn), rule_name);
1018
1019 // only need the hints & mechanisms if we are going to show ui
1020 if (engine->flags & kAuthorizationFlagInteractionAllowed) {
1021 _set_right_hints(engine->hints, key);
1022 _set_localization_hints(dbconn, engine->hints, rule);
1023 if (!engine->authenticateRule) {
1024 engine->authenticateRule = rule_create_with_string("authenticate", dbconn);
1025 }
1026 }
1027
1028 authdb_connection_release(&dbconn); // release db handle
1029
1030 engine->currentRightName = key;
1031 engine->currentRule = rule;
1032
1033 ccaudit_log(ccaudit, key, rule_name, 0);
1034
1035 status = _evaluate_rule(engine, engine->currentRule);
1036 switch (status) {
1037 case errAuthorizationSuccess:
1038 auth_rights_add(engine->grantedRights, key);
1039 auth_rights_set_flags(engine->grantedRights, key, auth_rights_get_flags(rights,key));
1040
1041 if ((engine->flags & kAuthorizationFlagPreAuthorize) &&
1042 (rule_get_class(engine->currentRule) == RC_USER) &&
1043 (rule_get_timeout(engine->currentRule) == 0)) {
1044 auth_rights_set_flags(engine->grantedRights, engine->currentRightName, kAuthorizationFlagPreAuthorize);
1045 }
1046
1047 LOG("Succeeded authorizing right '%s' by client '%s' [%d] for authorization created by '%s' [%d] (%X,%d)",
1048 key, process_get_code_url(engine->proc), process_get_pid(engine->proc),
1049 auth_token_get_code_url(engine->auth), auth_token_get_pid(engine->auth), engine->flags, auth_token_least_privileged(engine->auth));
1050 if (rule_get_extract_password(engine->currentRule)) {
1051 savePassword = true;
1052 }
1053 break;
1054 case errAuthorizationDenied:
1055 case errAuthorizationInteractionNotAllowed:
1056 case errAuthorizationCanceled:
1057 if (engine->flags & kAuthorizationFlagInteractionAllowed) {
1058 LOG("Failed to authorize right '%s' by client '%s' [%d] for authorization created by '%s' [%d] (%X,%d) (%i)",
1059 key, process_get_code_url(engine->proc), process_get_pid(engine->proc),
1060 auth_token_get_code_url(engine->auth), auth_token_get_pid(engine->auth), engine->flags, auth_token_least_privileged(engine->auth), status);
1061 } else {
1062 LOGV("Failed to authorize right '%s' by client '%s' [%d] for authorization created by '%s' [%d] (%X,%d) (%i)",
1063 key, process_get_code_url(engine->proc), process_get_pid(engine->proc),
1064 auth_token_get_code_url(engine->auth), auth_token_get_pid(engine->auth), engine->flags, auth_token_least_privileged(engine->auth), status);
1065 }
1066 break;
1067 default:
1068 LOGE("engine[%i]: evaluate returned %i returning errAuthorizationInternal", connection_get_pid(engine->conn), status);
1069 status = errAuthorizationInternal;
1070 break;
1071 }
1072
1073 ccaudit_log_authorization(ccaudit, engine->currentRightName, status);
1074
1075 CFReleaseSafe(rule);
1076 engine->currentRightName = NULL;
1077 engine->currentRule = NULL;
1078
1079 auth_items_remove_with_flags(engine->hints, kEngineHintsFlagTemporary);
1080
1081 if (!(engine->flags & kAuthorizationFlagPartialRights) && (status != errAuthorizationSuccess)) {
1082 return false;
1083 }
1084
1085 return true;
1086 });
1087
1088 if ((engine->flags & kAuthorizationFlagPartialRights) && (auth_rights_get_count(engine->grantedRights) > 0)) {
1089 status = errAuthorizationSuccess;
1090 }
1091
1092 if (engine->dismissed) {
1093 status = errAuthorizationDenied;
1094 }
1095
1096 LOGV("engine[%i]: authorize result: %i", connection_get_pid(engine->conn), status);
1097
1098 if ((engine->flags & kAuthorizationFlagExtendRights) && !(engine->flags & kAuthorizationFlagDestroyRights)) {
1099 _cf_set_iterate(engine->credentials, ^bool(CFTypeRef value) {
1100 credential_t cred = (credential_t)value;
1101 // skip all uid credentials when running in least privileged
1102 if (auth_token_least_privileged(engine->auth) && !credential_is_right(cred))
1103 return true;
1104
1105 session_t session = auth_token_get_session(engine->auth);
1106 auth_token_set_credential(engine->auth, cred);
1107 if (credential_get_shared(cred)) {
1108 session_set_credential(session, cred);
1109 }
1110 if (credential_is_right(cred)) {
1111 LOGV("engine[%i]: adding least privileged %scredential %s to authorization", connection_get_pid(engine->conn), credential_get_shared(cred) ? "shared " : "", credential_get_name(cred));
1112 } else {
1113 LOGV("engine[%i]: adding %scredential %s (%i) to authorization", connection_get_pid(engine->conn), credential_get_shared(cred) ? "shared " : "", credential_get_name(cred), credential_get_uid(cred));
1114 }
1115 return true;
1116 });
1117 }
1118
1119 if ((status == errAuthorizationSuccess) || (status == errAuthorizationCanceled)) {
1120 if (savePassword && (status == errAuthorizationSuccess)) {
1121 auth_items_set_flags(engine->context, kAuthorizationEnvironmentPassword, kAuthorizationContextFlagExtractable);
1122 }
1123
1124 auth_items_copy_with_flags(auth_token_get_context(engine->auth), engine->context, kAuthorizationContextFlagExtractable);
1125 }
1126
1127 if (auth_rights_get_count(rights) > 0) {
1128 ccaudit_log(ccaudit, "end evaluation", NULL, status);
1129 }
1130
1131 #if DEBUG
1132 LOGV("engine[%i]: ********** Dumping auth->credentials **********", connection_get_pid(engine->conn));
1133 auth_token_credentials_iterate(engine->auth, ^bool(credential_t cred) {
1134 _show_cf(cred);
1135 return true;
1136 });
1137 LOGV("engine[%i]: ********** Dumping session->credentials **********", connection_get_pid(engine->conn));
1138 session_credentials_iterate(auth_token_get_session(engine->auth), ^bool(credential_t cred) {
1139 _show_cf(cred);
1140 return true;
1141 });
1142 LOGV("engine[%i]: ********** Dumping engine->context **********", connection_get_pid(engine->conn));
1143 _show_cf(engine->context);
1144 LOGV("engine[%i]: ********** Dumping auth->context **********", connection_get_pid(engine->conn));
1145 _show_cf(auth_token_get_context(engine->auth));
1146 LOGV("engine[%i]: ********** Dumping granted rights **********", connection_get_pid(engine->conn));
1147 _show_cf(engine->grantedRights);
1148 #endif
1149
1150 done:
1151 auth_items_clear(engine->context);
1152 auth_items_clear(engine->sticky_context);
1153 CFReleaseSafe(ccaudit);
1154 CFDictionaryRemoveAllValues(engine->mechanism_agents);
1155
1156 return status;
1157 }
1158
1159 static bool
1160 _wildcard_right_exists(engine_t engine, const char * right)
1161 {
1162 // checks if a wild card right exists
1163 // ex: com.apple. system.
1164 bool exists = false;
1165 rule_t rule = NULL;
1166 authdb_connection_t dbconn = authdb_connection_acquire(server_get_database()); // get db handle
1167 require(dbconn != NULL, done);
1168
1169 rule = _find_rule(engine, dbconn, right);
1170 require(rule != NULL, done);
1171
1172 const char * ruleName = rule_get_name(rule);
1173 require(ruleName != NULL, done);
1174 size_t len = strlen(ruleName);
1175 require(len != 0, done);
1176
1177 if (ruleName[len-1] == '.') {
1178 exists = true;
1179 goto done;
1180 }
1181
1182 done:
1183 authdb_connection_release(&dbconn);
1184 CFReleaseSafe(rule);
1185
1186 return exists;
1187 }
1188
1189 // Validate db right modification
1190
1191 // meta rights are constructed as follows:
1192 // we don't allow setting of wildcard rights, so you can only be more specific
1193 // note that you should never restrict things with a wildcard right without disallowing
1194 // changes to the entire domain. ie.
1195 // system.privilege. -> never
1196 // config.add.system.privilege. -> never
1197 // config.modify.system.privilege. -> never
1198 // config.delete.system.privilege. -> never
1199 // For now we don't allow any configuration of configuration rules
1200 // config.config. -> never
1201
1202 OSStatus engine_verify_modification(engine_t engine, rule_t rule, bool remove, bool force_modify)
1203 {
1204 OSStatus status = errAuthorizationDenied;
1205 auth_rights_t checkRight = NULL;
1206 char buf[BUFSIZ];
1207 memset(buf, 0, sizeof(buf));
1208
1209 const char * right = rule_get_name(rule);
1210 require(right != NULL, done);
1211 size_t len = strlen(right);
1212 require(len != 0, done);
1213
1214 require_action(right[len-1] != '.', done, LOGE("engine[%i]: not allowed to set wild card rules", connection_get_pid(engine->conn)));
1215
1216 if (strncasecmp(right, kConfigRight, strlen(kConfigRight)) == 0) {
1217 // special handling of meta right change:
1218 // config.add. config.modify. config.remove. config.{}.
1219 // check for config.<right> (which always starts with config.config.)
1220 strlcat(buf, kConfigRight, sizeof(buf));
1221 } else {
1222 bool existing = (rule_get_id(rule) != 0) ? true : _wildcard_right_exists(engine, right);
1223 if (!remove) {
1224 if (existing || force_modify) {
1225 strlcat(buf, kAuthorizationConfigRightModify,sizeof(buf));
1226 } else {
1227 strlcat(buf, kAuthorizationConfigRightAdd, sizeof(buf));
1228 }
1229 } else {
1230 if (existing) {
1231 strlcat(buf, kAuthorizationConfigRightRemove, sizeof(buf));
1232 } else {
1233 status = errAuthorizationSuccess;
1234 goto done;
1235 }
1236 }
1237 }
1238
1239 strlcat(buf, right, sizeof(buf));
1240
1241 checkRight = auth_rights_create();
1242 auth_rights_add(checkRight, buf);
1243 status = engine_authorize(engine, checkRight, NULL, kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights);
1244
1245 done:
1246 LOGV("engine[%i]: authorizing %s for db modification: %i", connection_get_pid(engine->conn), right, status);
1247 CFReleaseSafe(checkRight);
1248 return status;
1249 }
1250
1251 void
1252 _engine_set_credential(engine_t engine, credential_t cred, bool shared)
1253 {
1254 LOGV("engine[%i]: adding %scredential %s (%i) to engine shared: %i", connection_get_pid(engine->conn), credential_get_shared(cred) ? "shared " : "", credential_get_name(cred), credential_get_uid(cred), shared);
1255 CFSetSetValue(engine->credentials, cred);
1256 if (shared) {
1257 credential_t sharedCred = credential_create_with_credential(cred, true);
1258 CFSetSetValue(engine->credentials, sharedCred);
1259 CFReleaseSafe(sharedCred);
1260 }
1261 }
1262
1263 auth_rights_t
1264 engine_get_granted_rights(engine_t engine)
1265 {
1266 return engine->grantedRights;
1267 }
1268
1269 CFAbsoluteTime engine_get_time(engine_t engine)
1270 {
1271 return engine->now;
1272 }
1273
1274 void engine_destroy_agents(engine_t engine)
1275 {
1276 engine->dismissed = true;
1277
1278 _cf_dictionary_iterate(engine->mechanism_agents, ^bool(CFTypeRef key __attribute__((__unused__)), CFTypeRef value) {
1279 LOGD("engine[%i]: Destroying %s", connection_get_pid(engine->conn), mechanism_get_string((mechanism_t)key));
1280 agent_t agent = (agent_t)value;
1281 agent_destroy(agent);
1282
1283 return true;
1284 });
1285 }
1286
1287 void engine_interrupt_agent(engine_t engine)
1288 {
1289 _cf_dictionary_iterate(engine->mechanism_agents, ^bool(CFTypeRef key __attribute__((__unused__)), CFTypeRef value) {
1290 agent_t agent = (agent_t)value;
1291 agent_notify_interrupt(agent);
1292 return true;
1293 });
1294 }