]> git.saurik.com Git - apple/security.git/blob - Security/libsecurity_codesigning/lib/StaticCode.cpp
f221e5bec4cda9fea916729866456ef5aaabaae2
[apple/security.git] / Security / libsecurity_codesigning / lib / StaticCode.cpp
1 /*
2 * Copyright (c) 2006-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 // StaticCode - SecStaticCode API objects
26 //
27 #include "StaticCode.h"
28 #include "Code.h"
29 #include "reqmaker.h"
30 #include "drmaker.h"
31 #include "reqdumper.h"
32 #include "reqparser.h"
33 #include "sigblob.h"
34 #include "resources.h"
35 #include "detachedrep.h"
36 #include "csdatabase.h"
37 #include "dirscanner.h"
38 #include <CoreFoundation/CFURLAccess.h>
39 #include <Security/SecPolicyPriv.h>
40 #include <Security/SecTrustPriv.h>
41 #include <Security/SecCertificatePriv.h>
42 #include <Security/CMSPrivate.h>
43 #include <Security/SecCmsContentInfo.h>
44 #include <Security/SecCmsSignerInfo.h>
45 #include <Security/SecCmsSignedData.h>
46 #include <Security/cssmapplePriv.h>
47 #include <security_utilities/unix++.h>
48 #include <security_utilities/cfmunge.h>
49 #include <Security/CMSDecoder.h>
50 #include <security_utilities/logging.h>
51 #include <dirent.h>
52 #include <sstream>
53 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
54
55
56 namespace Security {
57 namespace CodeSigning {
58
59 using namespace UnixPlusPlus;
60
61 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
62 static const char WWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
63 static const char MACWWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
64 static const char developerID[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
65 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
66 static const char distributionCertificate[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
67 static const char iPhoneDistributionCert[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
68
69 //
70 // Map a component slot number to a suitable error code for a failure
71 //
72 static inline OSStatus errorForSlot(CodeDirectory::SpecialSlot slot)
73 {
74 switch (slot) {
75 case cdInfoSlot:
76 return errSecCSInfoPlistFailed;
77 case cdResourceDirSlot:
78 return errSecCSResourceDirectoryFailed;
79 default:
80 return errSecCSSignatureFailed;
81 }
82 }
83
84
85 //
86 // Construct a SecStaticCode object given a disk representation object
87 //
88 SecStaticCode::SecStaticCode(DiskRep *rep)
89 : mRep(rep),
90 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL),
91 mProgressQueue("com.apple.security.validation-progress", false, DISPATCH_QUEUE_PRIORITY_DEFAULT),
92 mDesignatedReq(NULL), mGotResourceBase(false), mMonitor(NULL), mLimitedAsync(NULL), mEvalDetails(NULL)
93 {
94 CODESIGN_STATIC_CREATE(this, rep);
95 CFRef<CFDataRef> codeDirectory = rep->codeDirectory();
96 if (codeDirectory && CFDataGetLength(codeDirectory) <= 0)
97 MacOSError::throwMe(errSecCSSignatureInvalid);
98 checkForSystemSignature();
99 }
100
101
102 //
103 // Clean up a SecStaticCode object
104 //
105 SecStaticCode::~SecStaticCode() throw()
106 try {
107 ::free(const_cast<Requirement *>(mDesignatedReq));
108 delete mResourcesValidContext;
109 delete mLimitedAsync;
110 } catch (...) {
111 return;
112 }
113
114 //
115 // Initialize a nested SecStaticCode object from its parent
116 //
117 void SecStaticCode::initializeFromParent(const SecStaticCode& parent) {
118 setMonitor(parent.monitor());
119 if (parent.mLimitedAsync)
120 mLimitedAsync = new LimitedAsync(*parent.mLimitedAsync);
121 }
122
123 //
124 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
125 // and falls back on comparing canonical paths if (both are) not.
126 //
127 bool SecStaticCode::equal(SecCFObject &secOther)
128 {
129 SecStaticCode *other = static_cast<SecStaticCode *>(&secOther);
130 CFDataRef mine = this->cdHash();
131 CFDataRef his = other->cdHash();
132 if (mine || his)
133 return mine && his && CFEqual(mine, his);
134 else
135 return CFEqual(CFRef<CFURLRef>(this->copyCanonicalPath()), CFRef<CFURLRef>(other->copyCanonicalPath()));
136 }
137
138 CFHashCode SecStaticCode::hash()
139 {
140 if (CFDataRef h = this->cdHash())
141 return CFHash(h);
142 else
143 return CFHash(CFRef<CFURLRef>(this->copyCanonicalPath()));
144 }
145
146
147 //
148 // Invoke a stage monitor if registered
149 //
150 CFTypeRef SecStaticCode::reportEvent(CFStringRef stage, CFDictionaryRef info)
151 {
152 if (mMonitor)
153 return mMonitor(this->handle(false), stage, info);
154 else
155 return NULL;
156 }
157
158 void SecStaticCode::prepareProgress(unsigned int workload)
159 {
160 dispatch_sync(mProgressQueue, ^{
161 mCancelPending = false; // not cancelled
162 });
163 if (mValidationFlags & kSecCSReportProgress) {
164 mCurrentWork = 0; // nothing done yet
165 mTotalWork = workload; // totally fake - we don't know how many files we'll get to chew
166 }
167 }
168
169 void SecStaticCode::reportProgress(unsigned amount /* = 1 */)
170 {
171 if (mMonitor && (mValidationFlags & kSecCSReportProgress)) {
172 // update progress and report
173 __block bool cancel = false;
174 dispatch_sync(mProgressQueue, ^{
175 if (mCancelPending)
176 cancel = true;
177 mCurrentWork += amount;
178 mMonitor(this->handle(false), CFSTR("progress"), CFTemp<CFDictionaryRef>("{current=%d,total=%d}", mCurrentWork, mTotalWork));
179 });
180 // if cancellation is pending, abort now
181 if (cancel)
182 MacOSError::throwMe(errSecCSCancelled);
183 }
184 }
185
186
187 //
188 // Set validation conditions for fine-tuning legacy tolerance
189 //
190 static void addError(CFTypeRef cfError, void* context)
191 {
192 if (CFGetTypeID(cfError) == CFNumberGetTypeID()) {
193 int64_t error;
194 CFNumberGetValue(CFNumberRef(cfError), kCFNumberSInt64Type, (void*)&error);
195 MacOSErrorSet* errors = (MacOSErrorSet*)context;
196 errors->insert(OSStatus(error));
197 }
198 }
199
200 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions)
201 {
202 if (conditions) {
203 CFDictionary source(conditions, errSecCSDbCorrupt);
204 mAllowOmissions = source.get<CFArrayRef>("omissions");
205 if (CFArrayRef errors = source.get<CFArrayRef>("errors"))
206 CFArrayApplyFunction(errors, CFRangeMake(0, CFArrayGetCount(errors)), addError, &this->mTolerateErrors);
207 }
208 }
209
210
211 //
212 // Request cancellation of a validation in progress.
213 // We do this by posting an abort flag that is checked periodically.
214 //
215 void SecStaticCode::cancelValidation()
216 {
217 if (!(mValidationFlags & kSecCSReportProgress)) // not using progress reporting; cancel won't make it through
218 MacOSError::throwMe(errSecCSInvalidFlags);
219 dispatch_sync(mProgressQueue, ^{
220 mCancelPending = true;
221 });
222 }
223
224
225 //
226 // Attach a detached signature.
227 //
228 void SecStaticCode::detachedSignature(CFDataRef sigData)
229 {
230 if (sigData) {
231 mDetachedSig = sigData;
232 mRep = new DetachedRep(sigData, mRep->base(), "explicit detached");
233 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep);
234 } else {
235 mDetachedSig = NULL;
236 mRep = mRep->base();
237 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL);
238 }
239 }
240
241
242 //
243 // Consult the system detached signature database to see if it contains
244 // a detached signature for this StaticCode. If it does, fetch and attach it.
245 // We do this only if the code has no signature already attached.
246 //
247 void SecStaticCode::checkForSystemSignature()
248 {
249 if (!this->isSigned()) {
250 SignatureDatabase db;
251 if (db.isOpen())
252 try {
253 if (RefPointer<DiskRep> dsig = db.findCode(mRep)) {
254 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig);
255 mRep = dsig;
256 }
257 } catch (...) {
258 }
259 }
260 }
261
262
263 //
264 // Return a descriptive string identifying the source of the code signature
265 //
266 string SecStaticCode::signatureSource()
267 {
268 if (!isSigned())
269 return "unsigned";
270 if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get()))
271 return rep->source();
272 return "embedded";
273 }
274
275
276 //
277 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
278 // (if possible).
279 //
280 SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref)
281 {
282 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
283 if (SecStaticCode *scode = dynamic_cast<SecStaticCode *>(object))
284 return scode;
285 else if (SecCode *code = dynamic_cast<SecCode *>(object))
286 return code->staticCode();
287 else // neither (a SecSomethingElse)
288 MacOSError::throwMe(errSecCSInvalidObjectRef);
289 }
290
291 SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref)
292 {
293 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
294 if (dynamic_cast<SecStaticCode *>(object))
295 return NULL;
296 else if (SecCode *code = dynamic_cast<SecCode *>(object))
297 return code;
298 else // neither (a SecSomethingElse)
299 MacOSError::throwMe(errSecCSInvalidObjectRef);
300 }
301
302
303 //
304 // Void all cached validity data.
305 //
306 // We also throw out cached components, because the new signature data may have
307 // a different idea of what components should be present. We could reconcile the
308 // cached data instead, if performance seems to be impacted.
309 //
310 void SecStaticCode::resetValidity()
311 {
312 CODESIGN_EVAL_STATIC_RESET(this);
313 mValidated = false;
314 mExecutableValidated = mResourcesValidated = false;
315 if (mResourcesValidContext) {
316 delete mResourcesValidContext;
317 mResourcesValidContext = NULL;
318 }
319 mDir = NULL;
320 mSignature = NULL;
321 for (unsigned n = 0; n < cdSlotCount; n++)
322 mCache[n] = NULL;
323 mInfoDict = NULL;
324 mEntitlements = NULL;
325 mResourceDict = NULL;
326 mDesignatedReq = NULL;
327 mCDHash = NULL;
328 mGotResourceBase = false;
329 mTrust = NULL;
330 mCertChain = NULL;
331 mEvalDetails = NULL;
332 mRep->flush();
333
334 // we may just have updated the system database, so check again
335 checkForSystemSignature();
336 }
337
338
339 //
340 // Retrieve a sealed component by special slot index.
341 // If the CodeDirectory has already been validated, validate against that.
342 // Otherwise, retrieve the component without validation (but cache it). Validation
343 // will go through the cache and validate all cached components.
344 //
345 CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
346 {
347 assert(slot <= cdSlotMax);
348
349 CFRef<CFDataRef> &cache = mCache[slot];
350 if (!cache) {
351 if (CFRef<CFDataRef> data = mRep->component(slot)) {
352 if (validated()) // if the directory has been validated...
353 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good
354 CFDataGetLength(data), -slot))
355 MacOSError::throwMe(errorForSlot(slot)); // ... then bail
356 cache = data; // it's okay, cache it
357 } else { // absent, mark so
358 if (validated()) // if directory has been validated...
359 if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing
360 MacOSError::throwMe(errorForSlot(slot)); // was supposed to be there
361 cache = CFDataRef(kCFNull); // white lie
362 }
363 }
364 return (cache == CFDataRef(kCFNull)) ? NULL : cache.get();
365 }
366
367
368 //
369 // Get the CodeDirectory.
370 // Throws (if check==true) or returns NULL (check==false) if there is none.
371 // Always throws if the CodeDirectory exists but is invalid.
372 // NEVER validates against the signature.
373 //
374 const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */)
375 {
376 if (!mDir) {
377 if (mDir.take(mRep->codeDirectory())) {
378 const CodeDirectory *dir = reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
379 dir->checkIntegrity();
380 }
381 }
382 if (mDir)
383 return reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
384 if (check)
385 MacOSError::throwMe(errSecCSUnsigned);
386 return NULL;
387 }
388
389
390 //
391 // Get the hash of the CodeDirectory.
392 // Returns NULL if there is none.
393 //
394 CFDataRef SecStaticCode::cdHash()
395 {
396 if (!mCDHash) {
397 if (const CodeDirectory *cd = codeDirectory(false)) {
398 SHA1 hash;
399 hash(cd, cd->length());
400 SHA1::Digest digest;
401 hash.finish(digest);
402 mCDHash.take(makeCFData(digest, sizeof(digest)));
403 CODESIGN_STATIC_CDHASH(this, digest, sizeof(digest));
404 }
405 }
406 return mCDHash;
407 }
408
409
410 //
411 // Return the CMS signature blob; NULL if none found.
412 //
413 CFDataRef SecStaticCode::signature()
414 {
415 if (!mSignature)
416 mSignature.take(mRep->signature());
417 if (mSignature)
418 return mSignature;
419 MacOSError::throwMe(errSecCSUnsigned);
420 }
421
422
423 //
424 // Verify the signature on the CodeDirectory.
425 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
426 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
427 //
428 void SecStaticCode::validateDirectory()
429 {
430 // echo previous outcome, if any
431 // track revocation separately, as it may not have been checked
432 // during the initial validation
433 if (!validated() || ((mValidationFlags & kSecCSEnforceRevocationChecks) && !revocationChecked()))
434 try {
435 // perform validation (or die trying)
436 CODESIGN_EVAL_STATIC_DIRECTORY(this);
437 mValidationExpired = verifySignature();
438 if (mValidationFlags & kSecCSEnforceRevocationChecks)
439 mRevocationChecked = true;
440
441 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
442 if (mCache[slot]) // if we already loaded that resource...
443 validateComponent(slot, errorForSlot(slot)); // ... then check it now
444 mValidated = true; // we've done the deed...
445 mValidationResult = errSecSuccess; // ... and it was good
446 } catch (const CommonError &err) {
447 mValidated = true;
448 mValidationResult = err.osStatus();
449 throw;
450 } catch (...) {
451 secdebug("staticCode", "%p validation threw non-common exception", this);
452 mValidated = true;
453 mValidationResult = errSecCSInternalError;
454 throw;
455 }
456 assert(validated());
457 if (mValidationResult == errSecSuccess) {
458 if (mValidationExpired)
459 if ((mValidationFlags & kSecCSConsiderExpiration)
460 || (codeDirectory()->flags & kSecCodeSignatureForceExpiration))
461 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED);
462 } else
463 MacOSError::throwMe(mValidationResult);
464 }
465
466
467 //
468 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
469 // Those latter components are checked by validateResources().
470 //
471 void SecStaticCode::validateNonResourceComponents()
472 {
473 this->validateDirectory();
474 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
475 switch (slot) {
476 case cdResourceDirSlot: // validated by validateResources
477 break;
478 default:
479 this->component(slot); // loads and validates
480 break;
481 }
482 }
483
484
485 //
486 // Get the (signed) signing date from the code signature.
487 // Sadly, we need to validate the signature to get the date (as a side benefit).
488 // This means that you can't get the signing time for invalidly signed code.
489 //
490 // We could run the decoder "almost to" verification to avoid this, but there seems
491 // little practical point to such a duplication of effort.
492 //
493 CFAbsoluteTime SecStaticCode::signingTime()
494 {
495 validateDirectory();
496 return mSigningTime;
497 }
498
499 CFAbsoluteTime SecStaticCode::signingTimestamp()
500 {
501 validateDirectory();
502 return mSigningTimestamp;
503 }
504
505
506 //
507 // Verify the CMS signature on the CodeDirectory.
508 // This performs the cryptographic tango. It returns if the signature is valid,
509 // or throws if it is not. As a side effect, a successful return sets up the
510 // cached certificate chain for future use.
511 // Returns true if the signature is expired (the X.509 sense), false if it's not.
512 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
513 //
514 bool SecStaticCode::verifySignature()
515 {
516 // ad-hoc signed code is considered validly signed by definition
517 if (flag(kSecCodeSignatureAdhoc)) {
518 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
519 return false;
520 }
521
522 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str());
523
524 // decode CMS and extract SecTrust for verification
525 CFRef<CMSDecoderRef> cms;
526 MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder
527 CFDataRef sig = this->signature();
528 MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig)));
529 this->codeDirectory(); // load CodeDirectory (sets mDir)
530 MacOSError::check(CMSDecoderSetDetachedContent(cms, mDir));
531 MacOSError::check(CMSDecoderFinalizeMessage(cms));
532 MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray()));
533 CFRef<CFArrayRef> vf_policies = verificationPolicies();
534 CFRef<CFArrayRef> ts_policies = SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies);
535 CMSSignerStatus status;
536 MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, vf_policies,
537 false, &status, &mTrust.aref(), NULL));
538
539 if (status != kCMSSignerValid)
540 MacOSError::throwMe(errSecCSSignatureFailed);
541
542 // internal signing time (as specified by the signer; optional)
543 mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
544 switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) {
545 case errSecSuccess:
546 case errSecSigningTimeMissing:
547 break;
548 default:
549 MacOSError::throwMe(rc);
550 }
551
552 // certified signing time (as specified by a TSA; optional)
553 mSigningTimestamp = 0;
554 switch (OSStatus rc = CMSDecoderCopySignerTimestampWithPolicy(cms, ts_policies, 0, &mSigningTimestamp)) {
555 case errSecSuccess:
556 case errSecTimestampMissing:
557 break;
558 default:
559 MacOSError::throwMe(rc);
560 }
561
562 // set up the environment for SecTrust
563 if (mValidationFlags & kSecCSNoNetworkAccess) {
564 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust,false)); // no network?
565 }
566 MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors
567 MacOSError::check(SecTrustSetKeychains(mTrust, cfEmptyArray())); // no keychains
568 CSSM_APPLE_TP_ACTION_DATA actionData = {
569 CSSM_APPLE_TP_ACTION_VERSION, // version of data structure
570 CSSM_TP_ACTION_IMPLICIT_ANCHORS // action flags
571 };
572
573 for (;;) { // at most twice
574 MacOSError::check(SecTrustSetParameters(mTrust,
575 CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData))));
576
577 // evaluate trust and extract results
578 SecTrustResultType trustResult;
579 MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
580 MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails));
581
582 // if this is an Apple developer cert....
583 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain)) {
584 CFRef<CFStringRef> teamIDFromCert;
585 if (CFArrayGetCount(mCertChain) > 0) {
586 /* Note that SecCertificateCopySubjectComponent sets the out paramater to NULL if there is no field present */
587 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, Requirement::leafCert),
588 &CSSMOID_OrganizationalUnitName,
589 &teamIDFromCert.aref()));
590
591 if (teamIDFromCert) {
592 CFRef<CFStringRef> teamIDFromCD = CFStringCreateWithCString(NULL, teamID(), kCFStringEncodingUTF8);
593 if (!teamIDFromCD) {
594 MacOSError::throwMe(errSecCSInternalError);
595 }
596
597 if (CFStringCompare(teamIDFromCert, teamIDFromCD, 0) != kCFCompareEqualTo) {
598 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory", cfString(teamIDFromCert).c_str(), teamID());
599 MacOSError::throwMe(errSecCSSignatureInvalid);
600 }
601 }
602 }
603 }
604
605 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? (int)CFArrayGetCount(mCertChain) : 0);
606 switch (trustResult) {
607 case kSecTrustResultProceed:
608 case kSecTrustResultUnspecified:
609 break; // success
610 case kSecTrustResultDeny:
611 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject
612 case kSecTrustResultInvalid:
613 assert(false); // should never happen
614 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
615 default:
616 {
617 OSStatus result;
618 MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result));
619 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
620 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
621 if (mSigningTimestamp == 0) // no timestamp available
622 if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET))
623 && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) {
624 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
625 actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs)
626 continue; // retry validation while tolerating expiration
627 }
628 MacOSError::throwMe(result);
629 }
630 }
631
632 if (mSigningTimestamp) {
633 CFIndex rootix = CFArrayGetCount(mCertChain);
634 if (SecCertificateRef mainRoot = SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, rootix-1)))
635 if (isAppleCA(mainRoot)) {
636 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
637 CFRef<CFArrayRef> tsCerts;
638 MacOSError::check(CMSDecoderCopySignerTimestampCertificates(cms, 0, &tsCerts.aref()));
639 CFIndex tsn = CFArrayGetCount(tsCerts);
640 bool good = tsn > 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts, tsn-1)));
641 if (!good)
642 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
643 }
644 }
645
646 return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED;
647 }
648 }
649
650
651 //
652 // Return the TP policy used for signature verification.
653 // This may be a simple SecPolicyRef or a CFArray of policies.
654 // The caller owns the return value.
655 //
656 static SecPolicyRef makeCRLPolicy()
657 {
658 CFRef<SecPolicyRef> policy;
659 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref()));
660 CSSM_APPLE_TP_CRL_OPTIONS options;
661 memset(&options, 0, sizeof(options));
662 options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION;
663 options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT;
664 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
665 MacOSError::check(SecPolicySetValue(policy, &optData));
666 return policy.yield();
667 }
668
669 static SecPolicyRef makeOCSPPolicy()
670 {
671 CFRef<SecPolicyRef> policy;
672 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref()));
673 CSSM_APPLE_TP_OCSP_OPTIONS options;
674 memset(&options, 0, sizeof(options));
675 options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION;
676 options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT;
677 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
678 MacOSError::check(SecPolicySetValue(policy, &optData));
679 return policy.yield();
680 }
681
682 CFArrayRef SecStaticCode::verificationPolicies()
683 {
684 CFRef<SecPolicyRef> core;
685 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3,
686 &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref()));
687 if (mValidationFlags & kSecCSNoNetworkAccess) {
688 // Skips all revocation since they require network connectivity
689 // therefore annihilates kSecCSEnforceRevocationChecks if present
690 CFRef<SecPolicyRef> no_revoc = SecPolicyCreateRevocation(kSecRevocationNetworkAccessDisabled);
691 return makeCFArray(2, core.get(), no_revoc.get());
692 }
693 else if (mValidationFlags & kSecCSEnforceRevocationChecks) {
694 // Add CRL and OCSPPolicies
695 CFRef<SecPolicyRef> crl = makeCRLPolicy();
696 CFRef<SecPolicyRef> ocsp = makeOCSPPolicy();
697 return makeCFArray(3, core.get(), crl.get(), ocsp.get());
698 } else {
699 return makeCFArray(1, core.get());
700 }
701 }
702
703
704 //
705 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
706 // The resource must already have been placed in the cache.
707 // This does NOT perform basic validation.
708 //
709 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
710 {
711 assert(slot <= cdSlotMax);
712 CFDataRef data = mCache[slot];
713 assert(data); // must be cached
714 if (data == CFDataRef(kCFNull)) {
715 if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there...
716 MacOSError::throwMe(fail); // ... and is missing
717 } else {
718 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot))
719 MacOSError::throwMe(fail);
720 }
721 }
722
723
724 //
725 // Perform static validation of the main executable.
726 // This reads the main executable from disk and validates it against the
727 // CodeDirectory code slot array.
728 // Note that this is NOT an in-memory validation, and is thus potentially
729 // subject to timing attacks.
730 //
731 void SecStaticCode::validateExecutable()
732 {
733 if (!validatedExecutable()) {
734 try {
735 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this,
736 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots);
737 const CodeDirectory *cd = this->codeDirectory();
738 if (!cd)
739 MacOSError::throwMe(errSecCSUnsigned);
740 AutoFileDesc fd(mainExecutablePath(), O_RDONLY);
741 fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass)
742 if (Universal *fat = mRep->mainExecutableImage())
743 fd.seek(fat->archOffset());
744 size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0;
745 size_t remaining = cd->codeLimit;
746 for (uint32_t slot = 0; slot < cd->nCodeSlots; ++slot) {
747 size_t size = min(remaining, pageSize);
748 if (!cd->validateSlot(fd, size, slot)) {
749 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot);
750 MacOSError::throwMe(errSecCSSignatureFailed);
751 }
752 remaining -= size;
753 }
754 mExecutableValidated = true;
755 mExecutableValidResult = errSecSuccess;
756 } catch (const CommonError &err) {
757 mExecutableValidated = true;
758 mExecutableValidResult = err.osStatus();
759 throw;
760 } catch (...) {
761 secdebug("staticCode", "%p executable validation threw non-common exception", this);
762 mExecutableValidated = true;
763 mExecutableValidResult = errSecCSInternalError;
764 throw;
765 }
766 }
767 assert(validatedExecutable());
768 if (mExecutableValidResult != errSecSuccess)
769 MacOSError::throwMe(mExecutableValidResult);
770 }
771
772
773 //
774 // Perform static validation of sealed resources and nested code.
775 //
776 // This performs a whole-code static resource scan and effectively
777 // computes a concordance between what's on disk and what's in the ResourceDirectory.
778 // Any unsanctioned difference causes an error.
779 //
780 unsigned SecStaticCode::estimateResourceWorkload()
781 {
782 // workload estimate = number of sealed files
783 CFDictionaryRef sealedResources = resourceDictionary();
784 CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files2");
785 if (files == NULL)
786 files = cfget<CFDictionaryRef>(sealedResources, "files");
787 return files ? unsigned(CFDictionaryGetCount(files)) : 0;
788 }
789
790 void SecStaticCode::validateResources(SecCSFlags flags)
791 {
792 // do we have a superset of this requested validation cached?
793 bool doit = true;
794 if (mResourcesValidated) { // have cached outcome
795 if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan
796 doit = false;
797 }
798
799 if (doit) {
800 if (mLimitedAsync == NULL) {
801 mLimitedAsync = new LimitedAsync(diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey);
802 }
803
804 try {
805 // sanity first
806 CFDictionaryRef sealedResources = resourceDictionary();
807 if (this->resourceBase()) // disk has resources
808 if (sealedResources)
809 /* go to work below */;
810 else
811 MacOSError::throwMe(errSecCSResourcesNotFound);
812 else // disk has no resources
813 if (sealedResources)
814 MacOSError::throwMe(errSecCSResourcesNotFound);
815 else
816 return; // no resources, not sealed - fine (no work)
817
818 // found resources, and they are sealed
819 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this,
820 (char*)this->mainExecutablePath().c_str(), 0);
821
822 // scan through the resources on disk, checking each against the resourceDirectory
823 if (mValidationFlags & kSecCSFullReport)
824 mResourcesValidContext = new CollectingContext(*this); // collect all failures in here
825 else
826 mResourcesValidContext = new ValidationContext(*this); // simple bug-out on first error
827
828 // use V2 resource seal if available, otherwise fall back to V1
829 CFDictionaryRef rules;
830 CFDictionaryRef files;
831 uint32_t version;
832 if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature
833 rules = cfget<CFDictionaryRef>(sealedResources, "rules2");
834 files = cfget<CFDictionaryRef>(sealedResources, "files2");
835 version = 2;
836 } else { // only V1 available
837 rules = cfget<CFDictionaryRef>(sealedResources, "rules");
838 files = cfget<CFDictionaryRef>(sealedResources, "files");
839 version = 1;
840 }
841 if (!rules || !files)
842 MacOSError::throwMe(errSecCSResourcesInvalid);
843
844 // check for weak resource rules
845 bool strict = flags & kSecCSStrictValidate;
846 if (strict) {
847 if (hasWeakResourceRules(rules, version, mAllowOmissions))
848 if (mTolerateErrors.find(errSecCSWeakResourceRules) == mTolerateErrors.end())
849 MacOSError::throwMe(errSecCSWeakResourceRules);
850 if (version == 1)
851 if (mTolerateErrors.find(errSecCSWeakResourceEnvelope) == mTolerateErrors.end())
852 MacOSError::throwMe(errSecCSWeakResourceEnvelope);
853 }
854
855 Dispatch::Group group;
856 Dispatch::Group &groupRef = group; // (into block)
857
858 // scan through the resources on disk, checking each against the resourceDirectory
859 __block CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files);
860 string base = cfString(this->resourceBase());
861 ResourceBuilder resources(base, base, rules, codeDirectory()->hashType, strict, mTolerateErrors);
862 diskRep()->adjustResources(resources);
863
864 resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const string relpath, ResourceBuilder::Rule *rule) {
865 CFDictionaryRemoveValue(resourceMap, CFTempString(relpath));
866 bool isSymlink = (ent->fts_info == FTS_SL);
867
868 void (^validate)() = ^{
869 validateResource(files, relpath, isSymlink, *mResourcesValidContext, flags, version);
870 reportProgress();
871 };
872
873 mLimitedAsync->perform(groupRef, validate);
874 });
875 group.wait(); // wait until all async resources have been validated as well
876
877 unsigned leftovers = unsigned(CFDictionaryGetCount(resourceMap));
878 if (leftovers > 0) {
879 secdebug("staticCode", "%d sealed resource(s) not found in code", int(leftovers));
880 CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext);
881 }
882
883 // now check for any errors found in the reporting context
884 mResourcesValidated = true;
885 mResourcesDeep = flags & kSecCSCheckNestedCode;
886 if (mResourcesValidContext->osStatus() != errSecSuccess)
887 mResourcesValidContext->throwMe();
888 } catch (const CommonError &err) {
889 mResourcesValidated = true;
890 mResourcesDeep = flags & kSecCSCheckNestedCode;
891 mResourcesValidResult = err.osStatus();
892 throw;
893 } catch (...) {
894 secdebug("staticCode", "%p executable validation threw non-common exception", this);
895 mResourcesValidated = true;
896 mResourcesDeep = flags & kSecCSCheckNestedCode;
897 mResourcesValidResult = errSecCSInternalError;
898 throw;
899 }
900 }
901 assert(validatedResources());
902 if (mResourcesValidResult)
903 MacOSError::throwMe(mResourcesValidResult);
904 if (mResourcesValidContext->osStatus() != errSecSuccess)
905 mResourcesValidContext->throwMe();
906 }
907
908
909 void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context)
910 {
911 ValidationContext *ctx = static_cast<ValidationContext *>(context);
912 ResourceSeal seal(value);
913 if (!seal.optional()) {
914 if (key && CFGetTypeID(key) == CFStringGetTypeID()) {
915 CFTempURL tempURL(CFStringRef(key), false, ctx->code.resourceBase());
916 if (!tempURL.get()) {
917 ctx->reportProblem(errSecCSBadDictionaryFormat, kSecCFErrorResourceSeal, key);
918 } else {
919 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, tempURL);
920 }
921 } else {
922 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key);
923 }
924 }
925 }
926
927
928 static bool isOmitRule(CFTypeRef value)
929 {
930 if (CFGetTypeID(value) == CFBooleanGetTypeID())
931 return value == kCFBooleanFalse;
932 CFDictionary rule(value, errSecCSResourceRulesInvalid);
933 return rule.get<CFBooleanRef>("omit") == kCFBooleanTrue;
934 }
935
936 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions)
937 {
938 // compute allowed omissions
939 CFRef<CFArrayRef> defaultOmissions = this->diskRep()->allowedResourceOmissions();
940 if (!defaultOmissions)
941 MacOSError::throwMe(errSecCSInternalError);
942 CFRef<CFMutableArrayRef> allowed = CFArrayCreateMutableCopy(NULL, 0, defaultOmissions);
943 if (allowedOmissions)
944 CFArrayAppendArray(allowed, allowedOmissions, CFRangeMake(0, CFArrayGetCount(allowedOmissions)));
945 CFRange range = CFRangeMake(0, CFArrayGetCount(allowed));
946
947 // check all resource rules for weakness
948 string catchAllRule = (version == 1) ? "^Resources/" : "^.*";
949 __block bool coversAll = false;
950 __block bool forbiddenOmission = false;
951 CFArrayRef allowedRef = allowed.get(); // (into block)
952 CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid);
953 rules.apply(^(CFStringRef key, CFTypeRef value) {
954 string pattern = cfString(key, errSecCSResourceRulesInvalid);
955 if (pattern == catchAllRule && value == kCFBooleanTrue) {
956 coversAll = true;
957 return;
958 }
959 if (isOmitRule(value))
960 forbiddenOmission |= !CFArrayContainsValue(allowedRef, range, key);
961 });
962
963 return !coversAll || forbiddenOmission;
964 }
965
966
967 //
968 // Load, validate, cache, and return CFDictionary forms of sealed resources.
969 //
970 CFDictionaryRef SecStaticCode::infoDictionary()
971 {
972 if (!mInfoDict) {
973 mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed));
974 secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get());
975 }
976 return mInfoDict;
977 }
978
979 CFDictionaryRef SecStaticCode::entitlements()
980 {
981 if (!mEntitlements) {
982 validateDirectory();
983 if (CFDataRef entitlementData = component(cdEntitlementSlot)) {
984 validateComponent(cdEntitlementSlot);
985 const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData));
986 if (blob->validateBlob()) {
987 mEntitlements.take(blob->entitlements());
988 secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get());
989 }
990 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
991 }
992 }
993 return mEntitlements;
994 }
995
996 CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */)
997 {
998 if (mResourceDict) // cached
999 return mResourceDict;
1000 if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, check))
1001 if (cfscan(dict, "{rules=%Dn,files=%Dn}")) {
1002 secdebug("staticCode", "%p loaded ResourceDict %p",
1003 this, mResourceDict.get());
1004 return mResourceDict = dict;
1005 }
1006 // bad format
1007 return NULL;
1008 }
1009
1010
1011 //
1012 // Load and cache the resource directory base.
1013 // Note that the base is optional for each DiskRep.
1014 //
1015 CFURLRef SecStaticCode::resourceBase()
1016 {
1017 if (!mGotResourceBase) {
1018 string base = mRep->resourcesRootPath();
1019 if (!base.empty())
1020 mResourceBase.take(makeCFURL(base, true));
1021 mGotResourceBase = true;
1022 }
1023 return mResourceBase;
1024 }
1025
1026
1027 //
1028 // Load a component, validate it, convert it to a CFDictionary, and return that.
1029 // This will force load and validation, which means that it will perform basic
1030 // validation if it hasn't been done yet.
1031 //
1032 CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */)
1033 {
1034 if (check)
1035 validateDirectory();
1036 if (CFDataRef infoData = component(slot)) {
1037 validateComponent(slot);
1038 if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData))
1039 return dict;
1040 else
1041 MacOSError::throwMe(errSecCSBadDictionaryFormat);
1042 }
1043 return NULL;
1044 }
1045
1046
1047 //
1048 // Load, validate, and return a sealed resource.
1049 // The resource data (loaded in to memory as a blob) is returned and becomes
1050 // the responsibility of the caller; it is NOT cached by SecStaticCode.
1051 //
1052 // A resource that is not sealed will not be returned, and an error will be thrown.
1053 // A missing resource will cause an error unless it's marked optional in the Directory.
1054 // Under no circumstances will a corrupt resource be returned.
1055 // NULL will only be returned for a resource that is neither sealed nor present
1056 // (or that is sealed, absent, and marked optional).
1057 // If the ResourceDictionary itself is not sealed, this function will always fail.
1058 //
1059 // There is currently no interface for partial retrieval of the resource data.
1060 // (Since the ResourceDirectory does not currently support segmentation, all the
1061 // data would have to be read anyway, but it could be read into a reusable buffer.)
1062 //
1063 CFDataRef SecStaticCode::resource(string path, ValidationContext &ctx)
1064 {
1065 if (CFDictionaryRef rdict = resourceDictionary()) {
1066 if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) {
1067 ResourceSeal seal = file;
1068 if (!resourceBase()) // no resources in DiskRep
1069 MacOSError::throwMe(errSecCSResourcesNotFound);
1070 if (seal.nested())
1071 MacOSError::throwMe(errSecCSResourcesNotSealed); // (it's nested code)
1072 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1073 if (CFRef<CFDataRef> data = cfLoadFile(fullpath)) {
1074 MakeHash<CodeDirectory> hasher(this->codeDirectory());
1075 hasher->update(CFDataGetBytePtr(data), CFDataGetLength(data));
1076 if (hasher->verify(seal.hash()))
1077 return data.yield(); // good
1078 else
1079 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1080 } else {
1081 if (!seal.optional())
1082 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1083 else
1084 return NULL; // validly missing
1085 }
1086 } else
1087 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1088 return NULL;
1089 } else
1090 MacOSError::throwMe(errSecCSResourcesNotSealed);
1091 }
1092
1093 CFDataRef SecStaticCode::resource(string path)
1094 {
1095 ValidationContext ctx(*this);
1096 return resource(path, ctx);
1097 }
1098
1099 void SecStaticCode::validateResource(CFDictionaryRef files, string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version)
1100 {
1101 if (!resourceBase()) // no resources in DiskRep
1102 MacOSError::throwMe(errSecCSResourcesNotFound);
1103 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1104 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1105 ResourceSeal seal = file;
1106 if (seal.nested()) {
1107 if (isSymlink)
1108 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1109 string suffix = ".framework";
1110 bool isFramework = (path.length() > suffix.length())
1111 && (path.compare(path.length()-suffix.length(), suffix.length(), suffix) == 0);
1112 validateNestedCode(fullpath, seal, flags, isFramework);
1113 } else if (seal.link()) {
1114 char target[PATH_MAX];
1115 ssize_t len = ::readlink(cfString(fullpath).c_str(), target, sizeof(target)-1);
1116 if (len < 0)
1117 UnixError::check(-1);
1118 target[len] = '\0';
1119 if (cfString(seal.link()) != target)
1120 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath);
1121 } else if (seal.hash()) { // genuine file
1122 AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file
1123 if (fd) {
1124 MakeHash<CodeDirectory> hasher(this->codeDirectory());
1125 hashFileData(fd, hasher.get());
1126 if (hasher->verify(seal.hash()))
1127 return; // verify good
1128 else
1129 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1130 } else {
1131 if (!seal.optional())
1132 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1133 else
1134 return; // validly missing
1135 }
1136 } else
1137 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1138 return;
1139 }
1140 if (version == 1) { // version 1 ignores symlinks altogether
1141 char target[PATH_MAX];
1142 if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0)
1143 return;
1144 }
1145 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1146 }
1147
1148 void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework)
1149 {
1150 CFRef<SecRequirementRef> req;
1151 if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref()))
1152 MacOSError::throwMe(errSecCSResourcesInvalid);
1153
1154 // recursively verify this nested code
1155 try {
1156 if (!(flags & kSecCSCheckNestedCode))
1157 flags |= kSecCSBasicValidateOnly;
1158 SecPointer<SecStaticCode> code = new SecStaticCode(DiskRep::bestGuess(cfString(path)));
1159 code->initializeFromParent(*this);
1160 code->staticValidate(flags, SecRequirement::required(req));
1161
1162 if (isFramework && (flags & kSecCSStrictValidate))
1163 try {
1164 validateOtherVersions(path, flags, req, code);
1165 } catch (const CSError &err) {
1166 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1167 } catch (const MacOSError &err) {
1168 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1169 }
1170
1171 } catch (CSError &err) {
1172 if (err.error == errSecCSReqFailed) {
1173 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1174 return;
1175 }
1176 err.augment(kSecCFErrorPath, path);
1177 throw;
1178 } catch (const MacOSError &err) {
1179 if (err.error == errSecCSReqFailed) {
1180 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1181 return;
1182 }
1183 CSError::throwMe(err.error, kSecCFErrorPath, path);
1184 }
1185 }
1186
1187 void SecStaticCode::validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code)
1188 {
1189 // Find out what current points to and do not revalidate
1190 std::string mainPath = cfStringRelease(code->diskRep()->copyCanonicalPath());
1191
1192 char main_path[PATH_MAX];
1193 bool foundTarget = false;
1194
1195 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1196 not a security hole */
1197 if (realpath(mainPath.c_str(), main_path) != NULL)
1198 foundTarget = true;
1199
1200 std::ostringstream versionsPath;
1201 versionsPath << cfString(path) << "/Versions/";
1202
1203 DirScanner scanner(versionsPath.str());
1204
1205 if (scanner.initialized()) {
1206 struct dirent *entry = NULL;
1207 while ((entry = scanner.getNext()) != NULL) {
1208 std::ostringstream fullPath;
1209
1210 if (entry->d_type != DT_DIR ||
1211 strcmp(entry->d_name, ".") == 0 ||
1212 strcmp(entry->d_name, "..") == 0 ||
1213 strcmp(entry->d_name, "Current") == 0)
1214 continue;
1215
1216 fullPath << versionsPath.str() << entry->d_name;
1217
1218 char real_full_path[PATH_MAX];
1219 if (realpath(fullPath.str().c_str(), real_full_path) == NULL)
1220 UnixError::check(-1);
1221
1222 // Do case insensitive comparions because realpath() was called for both paths
1223 if (foundTarget && strcmp(main_path, real_full_path) == 0)
1224 continue;
1225
1226 SecPointer<SecStaticCode> frameworkVersion = new SecStaticCode(DiskRep::bestGuess(real_full_path));
1227 frameworkVersion->initializeFromParent(*this);
1228 frameworkVersion->staticValidate(flags, SecRequirement::required(req));
1229 }
1230 }
1231 }
1232
1233
1234 //
1235 // Test a CodeDirectory flag.
1236 // Returns false if there is no CodeDirectory.
1237 // May throw if the CodeDirectory is present but somehow invalid.
1238 //
1239 bool SecStaticCode::flag(uint32_t tested)
1240 {
1241 if (const CodeDirectory *cd = this->codeDirectory(false))
1242 return cd->flags & tested;
1243 else
1244 return false;
1245 }
1246
1247
1248 //
1249 // Retrieve the full SuperBlob containing all internal requirements.
1250 //
1251 const Requirements *SecStaticCode::internalRequirements()
1252 {
1253 if (CFDataRef reqData = component(cdRequirementsSlot)) {
1254 const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData);
1255 if (!req->validateBlob())
1256 MacOSError::throwMe(errSecCSReqInvalid);
1257 return req;
1258 } else
1259 return NULL;
1260 }
1261
1262
1263 //
1264 // Retrieve a particular internal requirement by type.
1265 //
1266 const Requirement *SecStaticCode::internalRequirement(SecRequirementType type)
1267 {
1268 if (const Requirements *reqs = internalRequirements())
1269 return reqs->find<Requirement>(type);
1270 else
1271 return NULL;
1272 }
1273
1274
1275 //
1276 // Return the Designated Requirement (DR). This can be either explicit in the
1277 // Internal Requirements component, or implicitly generated on demand here.
1278 // Note that an explicit DR may have been implicitly generated at signing time;
1279 // we don't distinguish this case.
1280 //
1281 const Requirement *SecStaticCode::designatedRequirement()
1282 {
1283 if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) {
1284 return req; // explicit in signing data
1285 } else {
1286 if (!mDesignatedReq)
1287 mDesignatedReq = defaultDesignatedRequirement();
1288 return mDesignatedReq;
1289 }
1290 }
1291
1292
1293 //
1294 // Generate the default Designated Requirement (DR) for this StaticCode.
1295 // Ignore any explicit DR it may contain.
1296 //
1297 const Requirement *SecStaticCode::defaultDesignatedRequirement()
1298 {
1299 if (flag(kSecCodeSignatureAdhoc)) {
1300 // adhoc signature: return a cdhash requirement for all architectures
1301 __block Requirement::Maker maker;
1302 Requirement::Maker::Chain chain(maker, opOr);
1303
1304 // insert cdhash requirement for all architectures
1305 chain.add();
1306 maker.cdhash(this->cdHash());
1307 handleOtherArchitectures(^(SecStaticCode *subcode) {
1308 if (CFDataRef cdhash = subcode->cdHash()) {
1309 chain.add();
1310 maker.cdhash(cdhash);
1311 }
1312 });
1313 return maker.make();
1314 } else {
1315 // full signature: Gin up full context and let DRMaker do its thing
1316 validateDirectory(); // need the cert chain
1317 Requirement::Context context(this->certificates(),
1318 this->infoDictionary(),
1319 this->entitlements(),
1320 this->identifier(),
1321 this->codeDirectory()
1322 );
1323 return DRMaker(context).make();
1324 }
1325 }
1326
1327
1328 //
1329 // Validate a SecStaticCode against the internal requirement of a particular type.
1330 //
1331 void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target,
1332 OSStatus nullError /* = errSecSuccess */)
1333 {
1334 DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError);
1335 if (const Requirement *req = internalRequirement(type))
1336 target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed);
1337 else if (nullError)
1338 MacOSError::throwMe(nullError);
1339 else
1340 /* accept it */;
1341 }
1342
1343
1344 //
1345 // Validate this StaticCode against an external Requirement
1346 //
1347 bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure)
1348 {
1349 assert(req);
1350 validateDirectory();
1351 return req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure);
1352 }
1353
1354 void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure)
1355 {
1356 if (!this->satisfiesRequirement(req, failure))
1357 MacOSError::throwMe(failure);
1358 }
1359
1360
1361 //
1362 // Retrieve one certificate from the cert chain.
1363 // Positive and negative indices can be used:
1364 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1365 // 0 1 ... -2 -1
1366 // Returns NULL if unavailable for any reason.
1367 //
1368 SecCertificateRef SecStaticCode::cert(int ix)
1369 {
1370 validateDirectory(); // need cert chain
1371 if (mCertChain) {
1372 CFIndex length = CFArrayGetCount(mCertChain);
1373 if (ix < 0)
1374 ix += length;
1375 if (ix >= 0 && ix < length)
1376 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix));
1377 }
1378 return NULL;
1379 }
1380
1381 CFArrayRef SecStaticCode::certificates()
1382 {
1383 validateDirectory(); // need cert chain
1384 return mCertChain;
1385 }
1386
1387
1388 //
1389 // Gather (mostly) API-official information about this StaticCode.
1390 //
1391 // This method lives in the twilight between the API and internal layers,
1392 // since it generates API objects (Sec*Refs) for return.
1393 //
1394 CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags)
1395 {
1396 //
1397 // Start with the pieces that we return even for unsigned code.
1398 // This makes Sec[Static]CodeRefs useful as API-level replacements
1399 // of our internal OSXCode objects.
1400 //
1401 CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1,
1402 kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get()
1403 );
1404
1405 //
1406 // If we're not signed, this is all you get
1407 //
1408 if (!this->isSigned())
1409 return dict.yield();
1410
1411 //
1412 // Add the generic attributes that we always include
1413 //
1414 CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier()));
1415 CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get()));
1416 CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format()));
1417 CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource()));
1418 CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash());
1419 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(this->codeDirectory(false)->hashType));
1420
1421 //
1422 // Deliver any Info.plist only if it looks intact
1423 //
1424 try {
1425 if (CFDictionaryRef info = this->infoDictionary())
1426 CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
1427 } catch (...) { } // don't deliver Info.plist if questionable
1428
1429 //
1430 // kSecCSSigningInformation adds information about signing certificates and chains
1431 //
1432 if (flags & kSecCSSigningInformation)
1433 try {
1434 if (CFArrayRef certs = this->certificates())
1435 CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs);
1436 if (CFDataRef sig = this->signature())
1437 CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig);
1438 if (mTrust)
1439 CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust);
1440 if (CFAbsoluteTime time = this->signingTime())
1441 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
1442 CFDictionaryAddValue(dict, kSecCodeInfoTime, date);
1443 if (CFAbsoluteTime time = this->signingTimestamp())
1444 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
1445 CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date);
1446 if (const char *teamID = this->teamID())
1447 CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID));
1448 } catch (...) { }
1449
1450 //
1451 // kSecCSRequirementInformation adds information on requirements
1452 //
1453 if (flags & kSecCSRequirementInformation)
1454 try {
1455 if (const Requirements *reqs = this->internalRequirements()) {
1456 CFDictionaryAddValue(dict, kSecCodeInfoRequirements,
1457 CFTempString(Dumper::dump(reqs)));
1458 CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs));
1459 }
1460
1461 const Requirement *dreq = this->designatedRequirement();
1462 CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle();
1463 CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef);
1464 if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit
1465 CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1466 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
1467 } else { // implicit
1468 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef);
1469 }
1470 } catch (...) { }
1471
1472 try {
1473 if (CFDataRef ent = this->component(cdEntitlementSlot)) {
1474 CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
1475 if (CFDictionaryRef entdict = this->entitlements())
1476 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
1477 }
1478 } catch (...) { }
1479
1480 //
1481 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1482 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1483 // to reliably transmit through the API wall so that code outside the Security.framework
1484 // can use it without having to play nasty tricks to get it.
1485 //
1486 if (flags & kSecCSInternalInformation)
1487 try {
1488 if (mDir)
1489 CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir);
1490 CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase()));
1491 if (CFRef<CFDictionaryRef> rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation
1492 CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict);
1493 } catch (...) { }
1494
1495
1496 //
1497 // kSecCSContentInformation adds more information about the physical layout
1498 // of the signed code. This is (only) useful for packaging or patching-oriented
1499 // applications.
1500 //
1501 if (flags & kSecCSContentInformation)
1502 if (CFRef<CFArrayRef> files = mRep->modifiedFiles())
1503 CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files);
1504
1505 return dict.yield();
1506 }
1507
1508
1509 //
1510 // Resource validation contexts.
1511 // The default context simply throws a CSError, rudely terminating the operation.
1512 //
1513 SecStaticCode::ValidationContext::~ValidationContext()
1514 { /* virtual */ }
1515
1516 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
1517 {
1518 CSError::throwMe(rc, type, value);
1519 }
1520
1521 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
1522 {
1523 StLock<Mutex> _(mLock);
1524 if (mStatus == errSecSuccess)
1525 mStatus = rc; // record first failure for eventual error return
1526 if (type) {
1527 if (!mCollection)
1528 mCollection.take(makeCFMutableDictionary());
1529 CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type));
1530 if (!element) {
1531 element = makeCFMutableArray(0);
1532 if (!element)
1533 CFError::throwMe();
1534 CFDictionaryAddValue(mCollection, type, element);
1535 CFRelease(element);
1536 }
1537 CFArrayAppendValue(element, value);
1538 }
1539 }
1540
1541 void SecStaticCode::CollectingContext::throwMe()
1542 {
1543 assert(mStatus != errSecSuccess);
1544 throw CSError(mStatus, mCollection.retain());
1545 }
1546
1547
1548 //
1549 // Master validation driver.
1550 // This is the static validation (only) driver for the API.
1551 //
1552 // SecStaticCode exposes an a la carte menu of topical validators applying
1553 // to a given object. The static validation API pulls them together reliably,
1554 // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries)
1555 // and nested code. This function will crawl a suitable cross-section of this
1556 // validation matrix based on which options it is given, creating temporary
1557 // SecStaticCode objects on the fly to complete the task.
1558 // (The point, of course, is to do as little duplicate work as possible.)
1559 //
1560 void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req)
1561 {
1562 setValidationFlags(flags);
1563
1564 // initialize progress/cancellation state
1565 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
1566
1567 // core components: once per architecture (if any)
1568 this->staticValidateCore(flags, req);
1569 if (flags & kSecCSCheckAllArchitectures)
1570 handleOtherArchitectures(^(SecStaticCode* subcode) {
1571 if (flags & kSecCSCheckGatekeeperArchitectures) {
1572 Universal *fat = subcode->diskRep()->mainExecutableImage();
1573 assert(fat && fat->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
1574 Architecture arch = fat->bestNativeArch(); // actually, the ONLY one
1575 if ((arch.cpuType() & ~CPU_ARCH_MASK) == CPU_TYPE_POWERPC)
1576 return; // irrelevant to Gatekeeper
1577 }
1578 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) architecture
1579 subcode->staticValidateCore(flags, req);
1580 });
1581 reportProgress();
1582
1583 // allow monitor intervention in source validation phase
1584 reportEvent(CFSTR("prepared"), NULL);
1585
1586 // resources: once for all architectures
1587 if (!(flags & kSecCSDoNotValidateResources))
1588 this->validateResources(flags);
1589
1590 // perform strict validation if desired
1591 if (flags & kSecCSStrictValidate)
1592 mRep->strictValidate(mTolerateErrors);
1593 reportProgress();
1594
1595 // allow monitor intervention
1596 if (CFRef<CFTypeRef> veto = reportEvent(CFSTR("validated"), NULL)) {
1597 if (CFGetTypeID(veto) == CFNumberGetTypeID())
1598 MacOSError::throwMe(cfNumber<OSStatus>(veto.as<CFNumberRef>()));
1599 else
1600 MacOSError::throwMe(errSecCSBadCallbackValue);
1601 }
1602 }
1603
1604 void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req)
1605 {
1606 try {
1607 this->validateNonResourceComponents(); // also validates the CodeDirectory
1608 if (!(flags & kSecCSDoNotValidateExecutable))
1609 this->validateExecutable();
1610 if (req)
1611 this->validateRequirement(req->requirement(), errSecCSReqFailed);
1612 } catch (CSError &err) {
1613 if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O
1614 if (MachO *mach = fat->architecture()) {
1615 err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName()));
1616 delete mach;
1617 }
1618 throw;
1619 } catch (const MacOSError &err) {
1620 // add architecture information if we can get it
1621 if (Universal *fat = this->diskRep()->mainExecutableImage())
1622 if (MachO *mach = fat->architecture()) {
1623 CFTempString arch(mach->architecture().displayName());
1624 delete mach;
1625 CSError::throwMe(err.error, kSecCFErrorArchitecture, arch);
1626 }
1627 throw;
1628 }
1629 }
1630
1631
1632 //
1633 // A helper that generates SecStaticCode objects for all but the primary architecture
1634 // of a fat binary and calls a block on them.
1635 // If there's only one architecture (or this is an architecture-agnostic code),
1636 // nothing happens quickly.
1637 //
1638 void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other))
1639 {
1640 if (Universal *fat = this->diskRep()->mainExecutableImage()) {
1641 Universal::Architectures architectures;
1642 fat->architectures(architectures);
1643 if (architectures.size() > 1) {
1644 DiskRep::Context ctx;
1645 size_t activeOffset = fat->archOffset();
1646 for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) {
1647 ctx.offset = fat->archOffset(*arch);
1648 if (ctx.offset > SIZE_MAX)
1649 MacOSError::throwMe(errSecCSInternalError);
1650 ctx.size = fat->lengthOfSlice((size_t)ctx.offset);
1651 if (ctx.offset != activeOffset) { // inactive architecture; check it
1652 SecPointer<SecStaticCode> subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx));
1653 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
1654 if (this->teamID() == NULL || subcode->teamID() == NULL) {
1655 if (this->teamID() != subcode->teamID())
1656 MacOSError::throwMe(errSecCSSignatureInvalid);
1657 } else if (strcmp(this->teamID(), subcode->teamID()) != 0)
1658 MacOSError::throwMe(errSecCSSignatureInvalid);
1659 handle(subcode);
1660 }
1661 }
1662 }
1663 }
1664 }
1665
1666 //
1667 // A method that takes a certificate chain (certs) and evaluates
1668 // if it is a Mac or IPhone developer cert, an app store distribution cert,
1669 // or a developer ID
1670 //
1671 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs)
1672 {
1673 static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + MACWWDRRequirement + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")";
1674 SecPointer<SecRequirement> req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true);
1675 Requirement::Context ctx(certs, NULL, NULL, "", NULL);
1676
1677 return req->requirement()->validates(ctx);
1678 }
1679
1680 } // end namespace CodeSigning
1681 } // end namespace Security