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