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