]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/StaticCode.cpp
Security-59754.60.13.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 #if TARGET_OS_OSX
31 #include "drmaker.h"
32 #include "notarization.h"
33 #endif
34 #include "reqdumper.h"
35 #include "reqparser.h"
36 #include "sigblob.h"
37 #include "resources.h"
38 #include "detachedrep.h"
39 #include "signerutils.h"
40 #if TARGET_OS_OSX
41 #include "csdatabase.h"
42 #endif
43 #include "dirscanner.h"
44 #include <CoreFoundation/CFURLAccess.h>
45 #include <Security/SecPolicyPriv.h>
46 #include <Security/SecTrustPriv.h>
47 #include <Security/SecCertificatePriv.h>
48 #if TARGET_OS_OSX
49 #include <Security/CMSPrivate.h>
50 #endif
51 #import <Security/SecCMS.h>
52 #include <Security/SecCmsContentInfo.h>
53 #include <Security/SecCmsSignerInfo.h>
54 #include <Security/SecCmsSignedData.h>
55 #if TARGET_OS_OSX
56 #include <Security/cssmapplePriv.h>
57 #endif
58 #include <security_utilities/unix++.h>
59 #include <security_utilities/cfmunge.h>
60 #include <security_utilities/casts.h>
61 #include <Security/CMSDecoder.h>
62 #include <security_utilities/logging.h>
63 #include <dirent.h>
64 #include <sys/xattr.h>
65 #include <sstream>
66 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
67 #include <dispatch/private.h>
68 #include <os/assumes.h>
69 #include <regex.h>
70 #import <utilities/entitlements.h>
71
72
73 namespace Security {
74 namespace CodeSigning {
75
76 using namespace UnixPlusPlus;
77
78 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
79 static const char WWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
80 static const char MACWWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
81 static const char developerID[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
82 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
83 static const char distributionCertificate[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
84 static const char iPhoneDistributionCert[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
85
86 //
87 // Map a component slot number to a suitable error code for a failure
88 //
89 static inline OSStatus errorForSlot(CodeDirectory::SpecialSlot slot)
90 {
91 switch (slot) {
92 case cdInfoSlot:
93 return errSecCSInfoPlistFailed;
94 case cdResourceDirSlot:
95 return errSecCSResourceDirectoryFailed;
96 default:
97 return errSecCSSignatureFailed;
98 }
99 }
100
101
102 //
103 // Construct a SecStaticCode object given a disk representation object
104 //
105 SecStaticCode::SecStaticCode(DiskRep *rep, uint32_t flags)
106 : mCheckfix30814861builder1(NULL),
107 mRep(rep),
108 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL),
109 mProgressQueue("com.apple.security.validation-progress", false, QOS_CLASS_UNSPECIFIED),
110 mOuterScope(NULL), mResourceScope(NULL),
111 mDesignatedReq(NULL), mGotResourceBase(false), mMonitor(NULL), mLimitedAsync(NULL),
112 mFlags(flags), mNotarizationChecked(false), mStaplingChecked(false), mNotarizationDate(NAN)
113 , mTrustedSigningCertChain(false)
114
115 {
116 CODESIGN_STATIC_CREATE(this, rep);
117 #if TARGET_OS_OSX
118 checkForSystemSignature();
119 #endif
120 }
121
122
123 //
124 // Clean up a SecStaticCode object
125 //
126 SecStaticCode::~SecStaticCode() _NOEXCEPT
127 try {
128 ::free(const_cast<Requirement *>(mDesignatedReq));
129 delete mResourcesValidContext;
130 delete mLimitedAsync;
131 delete mCheckfix30814861builder1;
132 } catch (...) {
133 return;
134 }
135
136 //
137 // Initialize a nested SecStaticCode object from its parent
138 //
139 void SecStaticCode::initializeFromParent(const SecStaticCode& parent) {
140 mOuterScope = &parent;
141 setMonitor(parent.monitor());
142 if (parent.mLimitedAsync)
143 mLimitedAsync = new LimitedAsync(*parent.mLimitedAsync);
144 }
145
146 //
147 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
148 // and falls back on comparing canonical paths if (both are) not.
149 //
150 bool SecStaticCode::equal(SecCFObject &secOther)
151 {
152 SecStaticCode *other = static_cast<SecStaticCode *>(&secOther);
153 CFDataRef mine = this->cdHash();
154 CFDataRef his = other->cdHash();
155 if (mine || his)
156 return mine && his && CFEqual(mine, his);
157 else
158 return CFEqual(CFRef<CFURLRef>(this->copyCanonicalPath()), CFRef<CFURLRef>(other->copyCanonicalPath()));
159 }
160
161 CFHashCode SecStaticCode::hash()
162 {
163 if (CFDataRef h = this->cdHash())
164 return CFHash(h);
165 else
166 return CFHash(CFRef<CFURLRef>(this->copyCanonicalPath()));
167 }
168
169
170 //
171 // Invoke a stage monitor if registered
172 //
173 CFTypeRef SecStaticCode::reportEvent(CFStringRef stage, CFDictionaryRef info)
174 {
175 if (mMonitor)
176 return mMonitor(this->handle(false), stage, info);
177 else
178 return NULL;
179 }
180
181 void SecStaticCode::prepareProgress(unsigned int workload)
182 {
183 dispatch_sync(mProgressQueue, ^{
184 mCancelPending = false; // not canceled
185 });
186 if (mValidationFlags & kSecCSReportProgress) {
187 mCurrentWork = 0; // nothing done yet
188 mTotalWork = workload; // totally fake - we don't know how many files we'll get to chew
189 }
190 }
191
192 void SecStaticCode::reportProgress(unsigned amount /* = 1 */)
193 {
194 if (mMonitor && (mValidationFlags & kSecCSReportProgress)) {
195 // update progress and report
196 __block bool cancel = false;
197 dispatch_sync(mProgressQueue, ^{
198 if (mCancelPending)
199 cancel = true;
200 mCurrentWork += amount;
201 mMonitor(this->handle(false), CFSTR("progress"), CFTemp<CFDictionaryRef>("{current=%d,total=%d}", mCurrentWork, mTotalWork));
202 });
203 // if cancellation is pending, abort now
204 if (cancel)
205 MacOSError::throwMe(errSecCSCancelled);
206 }
207 }
208
209
210 //
211 // Set validation conditions for fine-tuning legacy tolerance
212 //
213 static void addError(CFTypeRef cfError, void* context)
214 {
215 if (CFGetTypeID(cfError) == CFNumberGetTypeID()) {
216 int64_t error;
217 CFNumberGetValue(CFNumberRef(cfError), kCFNumberSInt64Type, (void*)&error);
218 MacOSErrorSet* errors = (MacOSErrorSet*)context;
219 errors->insert(OSStatus(error));
220 }
221 }
222
223 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions)
224 {
225 if (conditions) {
226 CFDictionary source(conditions, errSecCSDbCorrupt);
227 mAllowOmissions = source.get<CFArrayRef>("omissions");
228 if (CFArrayRef errors = source.get<CFArrayRef>("errors"))
229 CFArrayApplyFunction(errors, CFRangeMake(0, CFArrayGetCount(errors)), addError, &this->mTolerateErrors);
230 }
231 }
232
233
234 //
235 // Request cancellation of a validation in progress.
236 // We do this by posting an abort flag that is checked periodically.
237 //
238 void SecStaticCode::cancelValidation()
239 {
240 if (!(mValidationFlags & kSecCSReportProgress)) // not using progress reporting; cancel won't make it through
241 MacOSError::throwMe(errSecCSInvalidFlags);
242 dispatch_assert_queue(mProgressQueue);
243 mCancelPending = true;
244 }
245
246
247 //
248 // Attach a detached signature.
249 //
250 void SecStaticCode::detachedSignature(CFDataRef sigData)
251 {
252 if (sigData) {
253 mDetachedSig = sigData;
254 mRep = new DetachedRep(sigData, mRep->base(), "explicit detached");
255 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep);
256 } else {
257 mDetachedSig = NULL;
258 mRep = mRep->base();
259 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL);
260 }
261 }
262
263
264 //
265 // Consult the system detached signature database to see if it contains
266 // a detached signature for this StaticCode. If it does, fetch and attach it.
267 // We do this only if the code has no signature already attached.
268 //
269 void SecStaticCode::checkForSystemSignature()
270 {
271 #if TARGET_OS_OSX
272 if (!this->isSigned()) {
273 SignatureDatabase db;
274 if (db.isOpen())
275 try {
276 if (RefPointer<DiskRep> dsig = db.findCode(mRep)) {
277 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig);
278 mRep = dsig;
279 }
280 } catch (...) {
281 }
282 }
283 #else
284 MacOSError::throwMe(errSecUnimplemented);
285 #endif
286 }
287
288
289 //
290 // Return a descriptive string identifying the source of the code signature
291 //
292 string SecStaticCode::signatureSource()
293 {
294 if (!isSigned())
295 return "unsigned";
296 if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get()))
297 return rep->source();
298 return "embedded";
299 }
300
301
302 //
303 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
304 // (if possible).
305 //
306 SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref)
307 {
308 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
309 if (SecStaticCode *scode = dynamic_cast<SecStaticCode *>(object))
310 return scode;
311 else if (SecCode *code = dynamic_cast<SecCode *>(object))
312 return code->staticCode();
313 else // neither (a SecSomethingElse)
314 MacOSError::throwMe(errSecCSInvalidObjectRef);
315 }
316
317 SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref)
318 {
319 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
320 if (dynamic_cast<SecStaticCode *>(object))
321 return NULL;
322 else if (SecCode *code = dynamic_cast<SecCode *>(object))
323 return code;
324 else // neither (a SecSomethingElse)
325 MacOSError::throwMe(errSecCSInvalidObjectRef);
326 }
327
328
329 //
330 // Void all cached validity data.
331 //
332 // We also throw out cached components, because the new signature data may have
333 // a different idea of what components should be present. We could reconcile the
334 // cached data instead, if performance seems to be impacted.
335 //
336 void SecStaticCode::resetValidity()
337 {
338 CODESIGN_EVAL_STATIC_RESET(this);
339 mValidated = false;
340 mExecutableValidated = mResourcesValidated = false;
341 if (mResourcesValidContext) {
342 delete mResourcesValidContext;
343 mResourcesValidContext = NULL;
344 }
345 mDir = NULL;
346 mCodeDirectories.clear();
347 mSignature = NULL;
348 for (unsigned n = 0; n < cdSlotCount; n++)
349 mCache[n] = NULL;
350 mInfoDict = NULL;
351 mEntitlements = NULL;
352 mResourceDict = NULL;
353 mDesignatedReq = NULL;
354 mCDHash = NULL;
355 mGotResourceBase = false;
356 mTrust = NULL;
357 mCertChain = NULL;
358 mNotarizationChecked = false;
359 mStaplingChecked = false;
360 mNotarizationDate = NAN;
361 mRep->flush();
362
363 #if TARGET_OS_OSX
364 // we may just have updated the system database, so check again
365 checkForSystemSignature();
366 #endif
367 }
368
369
370 //
371 // Retrieve a sealed component by special slot index.
372 // If the CodeDirectory has already been validated, validate against that.
373 // Otherwise, retrieve the component without validation (but cache it). Validation
374 // will go through the cache and validate all cached components.
375 //
376 CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
377 {
378 assert(slot <= cdSlotMax);
379
380 CFRef<CFDataRef> &cache = mCache[slot];
381 if (!cache) {
382 if (CFRef<CFDataRef> data = mRep->component(slot)) {
383 if (validated()) { // if the directory has been validated...
384 if (!codeDirectory()->slotIsPresent(-slot))
385 return NULL;
386
387 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good
388 CFDataGetLength(data), -slot, false))
389 MacOSError::throwMe(errorForSlot(slot)); // ... then bail
390 }
391 cache = data; // it's okay, cache it
392 } else { // absent, mark so
393 if (validated()) // if directory has been validated...
394 if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing
395 MacOSError::throwMe(errorForSlot(slot)); // was supposed to be there
396 cache = CFDataRef(kCFNull); // white lie
397 }
398 }
399 return (cache == CFDataRef(kCFNull)) ? NULL : cache.get();
400 }
401
402
403 //
404 // Get the CodeDirectories.
405 // Throws (if check==true) or returns NULL (check==false) if there are none.
406 // Always throws if the CodeDirectories exist but are invalid.
407 // NEVER validates against the signature.
408 //
409 const SecStaticCode::CodeDirectoryMap *
410 SecStaticCode::codeDirectories(bool check /* = true */) const
411 {
412 if (mCodeDirectories.empty()) {
413 try {
414 loadCodeDirectories(mCodeDirectories);
415 } catch (...) {
416 if (check)
417 throw;
418 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectories.
419 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
420 if (!mCodeDirectories.empty()) {
421 assert(false);
422 Syslog::warning("code signing internal problem: mCodeDirectories set despite exception exit");
423 MacOSError::throwMe(errSecCSInternalError);
424 }
425 }
426 } else {
427 return &mCodeDirectories;
428 }
429 if (!mCodeDirectories.empty()) {
430 return &mCodeDirectories;
431 }
432 if (check) {
433 MacOSError::throwMe(errSecCSUnsigned);
434 }
435 return NULL;
436 }
437
438 //
439 // Get the CodeDirectory.
440 // Throws (if check==true) or returns NULL (check==false) if there is none.
441 // Always throws if the CodeDirectory exists but is invalid.
442 // NEVER validates against the signature.
443 //
444 const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */) const
445 {
446 if (!mDir) {
447 // pick our favorite CodeDirectory from the choices we've got
448 try {
449 CodeDirectoryMap const *candidates = codeDirectories(check);
450 if (candidates != NULL) {
451 CodeDirectory::HashAlgorithm type = CodeDirectory::bestHashOf(mHashAlgorithms);
452 mDir = candidates->at(type); // and the winner is...
453 }
454 } catch (...) {
455 if (check)
456 throw;
457 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectory.
458 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
459 if (mDir) {
460 assert(false);
461 Syslog::warning("code signing internal problem: mDir set despite exception exit");
462 MacOSError::throwMe(errSecCSInternalError);
463 }
464 }
465 }
466 if (mDir)
467 return reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
468 if (check)
469 MacOSError::throwMe(errSecCSUnsigned);
470 return NULL;
471 }
472
473
474 //
475 // Fetch an array of all available CodeDirectories.
476 // Returns false if unsigned (no classic CD slot), true otherwise.
477 //
478 bool SecStaticCode::loadCodeDirectories(CodeDirectoryMap& cdMap) const
479 {
480 __block CodeDirectoryMap candidates;
481 __block CodeDirectory::HashAlgorithms hashAlgorithms;
482 __block CFRef<CFDataRef> baseDir;
483 auto add = ^bool (CodeDirectory::SpecialSlot slot){
484 CFRef<CFDataRef> cdData = diskRep()->component(slot);
485 if (!cdData)
486 return false;
487 const CodeDirectory* cd = reinterpret_cast<const CodeDirectory*>(CFDataGetBytePtr(cdData));
488 if (!cd->validateBlob(CFDataGetLength(cdData)))
489 MacOSError::throwMe(errSecCSSignatureFailed); // no recovery - any suspect CD fails
490 cd->checkIntegrity();
491 auto result = candidates.insert(make_pair(cd->hashType, cdData.get()));
492 if (!result.second)
493 MacOSError::throwMe(errSecCSSignatureInvalid); // duplicate hashType, go to heck
494 hashAlgorithms.insert(cd->hashType);
495 if (slot == cdCodeDirectorySlot)
496 baseDir = cdData;
497 return true;
498 };
499 if (!add(cdCodeDirectorySlot))
500 return false; // no classic slot CodeDirectory -> unsigned
501 for (CodeDirectory::SpecialSlot slot = cdAlternateCodeDirectorySlots; slot < cdAlternateCodeDirectoryLimit; slot++)
502 if (!add(slot)) // no CodeDirectory at this slot -> end of alternates
503 break;
504 if (candidates.empty())
505 MacOSError::throwMe(errSecCSSignatureFailed); // no viable CodeDirectory in sight
506 // commit to cached values
507 cdMap.swap(candidates);
508 mHashAlgorithms.swap(hashAlgorithms);
509 mBaseDir = baseDir;
510 return true;
511 }
512
513
514 //
515 // Get the hash of the CodeDirectory.
516 // Returns NULL if there is none.
517 //
518 CFDataRef SecStaticCode::cdHash()
519 {
520 if (!mCDHash) {
521 if (const CodeDirectory *cd = codeDirectory(false)) {
522 mCDHash.take(cd->cdhash());
523 CODESIGN_STATIC_CDHASH(this, CFDataGetBytePtr(mCDHash), (unsigned int)CFDataGetLength(mCDHash));
524 }
525 }
526 return mCDHash;
527 }
528
529
530 //
531 // Get an array of the cdhashes for all digest types in this signature
532 // The array is sorted by cd->hashType.
533 //
534 CFArrayRef SecStaticCode::cdHashes()
535 {
536 if (!mCDHashes) {
537 CFRef<CFMutableArrayRef> cdList = makeCFMutableArray(0);
538 for (auto it = mCodeDirectories.begin(); it != mCodeDirectories.end(); ++it) {
539 const CodeDirectory *cd = (const CodeDirectory *)CFDataGetBytePtr(it->second);
540 if (CFRef<CFDataRef> hash = cd->cdhash())
541 CFArrayAppendValue(cdList, hash);
542 }
543 mCDHashes = cdList.get();
544 }
545 return mCDHashes;
546 }
547
548 //
549 // Get a dictionary of untruncated cdhashes for all digest types in this signature.
550 //
551 CFDictionaryRef SecStaticCode::cdHashesFull()
552 {
553 if (!mCDHashFullDict) {
554 CFRef<CFMutableDictionaryRef> cdDict = makeCFMutableDictionary();
555 for (auto const &it : mCodeDirectories) {
556 CodeDirectory::HashAlgorithm alg = it.first;
557 const CodeDirectory *cd = (const CodeDirectory *)CFDataGetBytePtr(it.second);
558 CFRef<CFDataRef> hash = cd->cdhash(false);
559 if (hash) {
560 CFDictionaryAddValue(cdDict, CFTempNumber(alg), hash);
561 }
562 }
563 mCDHashFullDict = cdDict.get();
564 }
565 return mCDHashFullDict;
566 }
567
568
569 //
570 // Return the CMS signature blob; NULL if none found.
571 //
572 CFDataRef SecStaticCode::signature()
573 {
574 if (!mSignature)
575 mSignature.take(mRep->signature());
576 if (mSignature)
577 return mSignature;
578 MacOSError::throwMe(errSecCSUnsigned);
579 }
580
581
582 //
583 // Verify the signature on the CodeDirectory.
584 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
585 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
586 //
587 void SecStaticCode::validateDirectory()
588 {
589 // echo previous outcome, if any
590 // track revocation separately, as it may not have been checked
591 // during the initial validation
592 if (!validated() || ((mValidationFlags & kSecCSEnforceRevocationChecks) && !revocationChecked()))
593 try {
594 // perform validation (or die trying)
595 CODESIGN_EVAL_STATIC_DIRECTORY(this);
596 mValidationExpired = verifySignature();
597 if (mValidationFlags & kSecCSEnforceRevocationChecks)
598 mRevocationChecked = true;
599
600 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
601 if (mCache[slot]) // if we already loaded that resource...
602 validateComponent(slot, errorForSlot(slot)); // ... then check it now
603 mValidated = true; // we've done the deed...
604 mValidationResult = errSecSuccess; // ... and it was good
605 } catch (const CommonError &err) {
606 mValidated = true;
607 mValidationResult = err.osStatus();
608 throw;
609 } catch (...) {
610 secinfo("staticCode", "%p validation threw non-common exception", this);
611 mValidated = true;
612 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
613 mValidationResult = errSecCSInternalError;
614 throw;
615 }
616 assert(validated());
617 // XXX: Embedded doesn't have CSSMERR_TP_CERT_EXPIRED so we can't throw it
618 // XXX: This should be implemented for embedded once we implement
619 // XXX: verifySignature and see how we're going to handle expired certs
620 #if TARGET_OS_OSX
621 if (mValidationResult == errSecSuccess) {
622 if (mValidationExpired)
623 if ((mValidationFlags & kSecCSConsiderExpiration)
624 || (codeDirectory()->flags & kSecCodeSignatureForceExpiration))
625 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED);
626 } else
627 MacOSError::throwMe(mValidationResult);
628 #endif
629 }
630
631
632 //
633 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
634 // Those latter components are checked by validateResources().
635 //
636 void SecStaticCode::validateNonResourceComponents()
637 {
638 this->validateDirectory();
639 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
640 switch (slot) {
641 case cdResourceDirSlot: // validated by validateResources
642 break;
643 default:
644 this->component(slot); // loads and validates
645 break;
646 }
647 }
648
649
650 //
651 // Check that any "top index" sealed into the signature conforms to what's actually here.
652 //
653 void SecStaticCode::validateTopDirectory()
654 {
655 assert(mDir); // must already have loaded CodeDirectories
656 if (CFDataRef topDirectory = component(cdTopDirectorySlot)) {
657 const auto topData = (const Endian<uint32_t> *)CFDataGetBytePtr(topDirectory);
658 const auto topDataEnd = topData + CFDataGetLength(topDirectory) / sizeof(*topData);
659 std::vector<uint32_t> signedVector(topData, topDataEnd);
660
661 std::vector<uint32_t> foundVector;
662 foundVector.push_back(cdCodeDirectorySlot); // mandatory
663 for (CodeDirectory::Slot slot = 1; slot <= cdSlotMax; ++slot)
664 if (component(slot))
665 foundVector.push_back(slot);
666 int alternateCount = int(mCodeDirectories.size() - 1); // one will go into cdCodeDirectorySlot
667 for (int n = 0; n < alternateCount; n++)
668 foundVector.push_back(cdAlternateCodeDirectorySlots + n);
669 foundVector.push_back(cdSignatureSlot); // mandatory (may be empty)
670
671 if (signedVector != foundVector)
672 MacOSError::throwMe(errSecCSSignatureFailed);
673 }
674 }
675
676
677 //
678 // Get the (signed) signing date from the code signature.
679 // Sadly, we need to validate the signature to get the date (as a side benefit).
680 // This means that you can't get the signing time for invalidly signed code.
681 //
682 // We could run the decoder "almost to" verification to avoid this, but there seems
683 // little practical point to such a duplication of effort.
684 //
685 CFAbsoluteTime SecStaticCode::signingTime()
686 {
687 validateDirectory();
688 return mSigningTime;
689 }
690
691 CFAbsoluteTime SecStaticCode::signingTimestamp()
692 {
693 validateDirectory();
694 return mSigningTimestamp;
695 }
696
697 #if TARGET_OS_OSX
698 #define kSecSHA256HashSize 32
699 // subject:/C=US/ST=California/L=San Jose/O=Adobe Systems Incorporated/OU=Information Systems/OU=Digital ID Class 3 - Microsoft Software Validation v2/CN=Adobe Systems Incorporated
700 // issuer :/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=Terms of use at https://www.verisign.com/rpa (c)10/CN=VeriSign Class 3 Code Signing 2010 CA
701 // Not Before: Dec 15 00:00:00 2010 GMT
702 // Not After : Dec 14 23:59:59 2012 GMT
703 static const unsigned char ASI_CS_12[] = {
704 0x77,0x82,0x9C,0x64,0x33,0x45,0x2E,0x4A,0xD3,0xA8,0xE4,0x6F,0x00,0x6C,0x27,0xEA,
705 0xFB,0xD3,0xF2,0x6D,0x50,0xF3,0x6F,0xE0,0xE9,0x6D,0x06,0x59,0x19,0xB5,0x46,0xFF
706 };
707
708 bool SecStaticCode::checkfix41082220(OSStatus cssmTrustResult)
709 {
710 // only applicable to revoked results
711 if (cssmTrustResult != CSSMERR_TP_CERT_REVOKED) {
712 return false;
713 }
714
715 // only this leaf certificate
716 if (CFArrayGetCount(mCertChain) == 0) {
717 return false;
718 }
719 CFRef<CFDataRef> leafHash(SecCertificateCopySHA256Digest((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, 0)));
720 if (memcmp(ASI_CS_12, CFDataGetBytePtr(leafHash), kSecSHA256HashSize) != 0) {
721 return false;
722 }
723
724 // detached dmg signature
725 if (!isDetached() || format() != std::string("disk image")) {
726 return false;
727 }
728
729 // sha-1 signed
730 if (hashAlgorithms().size() != 1 || hashAlgorithm() != kSecCodeSignatureHashSHA1) {
731 return false;
732 }
733
734 // not a privileged binary - no TeamID and no entitlements
735 if (component(cdEntitlementSlot) || teamID()) {
736 return false;
737 }
738
739 // no flags and old version
740 if (codeDirectory()->version != 0x20100 || codeDirectory()->flags != 0) {
741 return false;
742 }
743
744 Security::Syslog::warning("CodeSigning: Check-fix enabled for dmg '%s' with identifier '%s' signed with revoked certificates",
745 mainExecutablePath().c_str(), identifier().c_str());
746 return true;
747 }
748 #endif // TARGET_OS_OSX
749
750 //
751 // Verify the CMS signature.
752 // This performs the cryptographic tango. It returns if the signature is valid,
753 // or throws if it is not. As a side effect, a successful return sets up the
754 // cached certificate chain for future use.
755 // Returns true if the signature is expired (the X.509 sense), false if it's not.
756 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
757 //
758 bool SecStaticCode::verifySignature()
759 {
760 // ad-hoc signed code is considered validly signed by definition
761 if (flag(kSecCodeSignatureAdhoc)) {
762 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
763 return false;
764 }
765
766 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str());
767 #if TARGET_OS_OSX
768 if (!(mValidationFlags & kSecCSApplyEmbeddedPolicy)) {
769 // decode CMS and extract SecTrust for verification
770 CFRef<CMSDecoderRef> cms;
771 MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder
772 CFDataRef sig = this->signature();
773 MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig)));
774 this->codeDirectory(); // load CodeDirectory (sets mDir)
775 MacOSError::check(CMSDecoderSetDetachedContent(cms, mBaseDir));
776 MacOSError::check(CMSDecoderFinalizeMessage(cms));
777 MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray()));
778 CFRef<CFArrayRef> vf_policies(createVerificationPolicies());
779 CFRef<CFArrayRef> ts_policies(createTimeStampingAndRevocationPolicies());
780
781 CMSSignerStatus status;
782 MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, vf_policies,
783 false, &status, &mTrust.aref(), NULL));
784
785 if (status != kCMSSignerValid) {
786 const char *reason;
787 switch (status) {
788 case kCMSSignerUnsigned: reason="kCMSSignerUnsigned"; break;
789 case kCMSSignerNeedsDetachedContent: reason="kCMSSignerNeedsDetachedContent"; break;
790 case kCMSSignerInvalidSignature: reason="kCMSSignerInvalidSignature"; break;
791 case kCMSSignerInvalidCert: reason="kCMSSignerInvalidCert"; break;
792 case kCMSSignerInvalidIndex: reason="kCMSSignerInvalidIndex"; break;
793 default: reason="unknown"; break;
794 }
795 Security::Syslog::error("CMSDecoderCopySignerStatus failed with %s error (%d)",
796 reason, (int)status);
797 MacOSError::throwMe(errSecCSSignatureFailed);
798 }
799
800 // retrieve auxiliary v1 data bag and verify against current state
801 CFRef<CFDataRef> hashAgilityV1;
802 switch (OSStatus rc = CMSDecoderCopySignerAppleCodesigningHashAgility(cms, 0, &hashAgilityV1.aref())) {
803 case noErr:
804 if (hashAgilityV1) {
805 CFRef<CFDictionaryRef> hashDict = makeCFDictionaryFrom(hashAgilityV1);
806 CFArrayRef cdList = CFArrayRef(CFDictionaryGetValue(hashDict, CFSTR("cdhashes")));
807 CFArrayRef myCdList = this->cdHashes();
808
809 /* Note that this is not very "agile": There's no way to calculate the exact
810 * list for comparison if it contains hash algorithms we don't know yet... */
811 if (cdList == NULL || !CFEqual(cdList, myCdList))
812 MacOSError::throwMe(errSecCSSignatureFailed);
813 }
814 break;
815 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
816 break;
817 default:
818 MacOSError::throwMe(rc);
819 }
820
821 // retrieve auxiliary v2 data bag and verify against current state
822 CFRef<CFDictionaryRef> hashAgilityV2;
823 switch (OSStatus rc = CMSDecoderCopySignerAppleCodesigningHashAgilityV2(cms, 0, &hashAgilityV2.aref())) {
824 case noErr:
825 if (hashAgilityV2) {
826 /* Require number of code directoris and entries in the hash agility
827 * dict to be the same size (no stripping out code directories).
828 */
829 if (CFDictionaryGetCount(hashAgilityV2) != mCodeDirectories.size()) {
830 MacOSError::throwMe(errSecCSSignatureFailed);
831 }
832
833 /* Require every cdhash of every code directory whose hash
834 * algorithm we know to be in the agility dictionary.
835 *
836 * We check untruncated cdhashes here because we can.
837 */
838 bool foundOurs = false;
839 for (auto& entry : mCodeDirectories) {
840 SECOidTag tag = CodeDirectorySet::SECOidTagForAlgorithm(entry.first);
841
842 if (tag == SEC_OID_UNKNOWN) {
843 // Unknown hash algorithm, ignore.
844 continue;
845 }
846
847 CFRef<CFNumberRef> key = makeCFNumber(int(tag));
848 CFRef<CFDataRef> entryCdhash;
849 entryCdhash = (CFDataRef)CFDictionaryGetValue(hashAgilityV2, (void*)key.get());
850
851 CodeDirectory const *cd = (CodeDirectory const*)CFDataGetBytePtr(entry.second);
852 CFRef<CFDataRef> ourCdhash = cd->cdhash(false); // Untruncated cdhash!
853 if (!CFEqual(entryCdhash, ourCdhash)) {
854 MacOSError::throwMe(errSecCSSignatureFailed);
855 }
856
857 if (entry.first == this->hashAlgorithm()) {
858 foundOurs = true;
859 }
860 }
861
862 /* Require the cdhash of our chosen code directory to be in the dictionary.
863 * In theory, the dictionary could be full of unsupported cdhashes, but we
864 * really want ours, which is bound to be supported, to be covered.
865 */
866 if (!foundOurs) {
867 MacOSError::throwMe(errSecCSSignatureFailed);
868 }
869 }
870 break;
871 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
872 break;
873 default:
874 MacOSError::throwMe(rc);
875 }
876
877 // internal signing time (as specified by the signer; optional)
878 mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
879 switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) {
880 case errSecSuccess:
881 case errSecSigningTimeMissing:
882 break;
883 default:
884 Security::Syslog::error("Could not get signing time (error %d)", (int)rc);
885 MacOSError::throwMe(rc);
886 }
887
888 // certified signing time (as specified by a TSA; optional)
889 mSigningTimestamp = 0;
890 switch (OSStatus rc = CMSDecoderCopySignerTimestampWithPolicy(cms, ts_policies, 0, &mSigningTimestamp)) {
891 case errSecSuccess:
892 case errSecTimestampMissing:
893 break;
894 default:
895 Security::Syslog::error("Could not get timestamp (error %d)", (int)rc);
896 MacOSError::throwMe(rc);
897 }
898
899 // set up the environment for SecTrust
900 if (mValidationFlags & kSecCSNoNetworkAccess) {
901 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust,false)); // no network?
902 }
903 MacOSError::check(SecTrustSetKeychainsAllowed(mTrust, false));
904
905 CSSM_APPLE_TP_ACTION_DATA actionData = {
906 CSSM_APPLE_TP_ACTION_VERSION, // version of data structure
907 0 // action flags
908 };
909
910 if (!(mValidationFlags & kSecCSCheckTrustedAnchors)) {
911 /* no need to evaluate anchor trust when building cert chain */
912 MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors
913 actionData.ActionFlags |= CSSM_TP_ACTION_IMPLICIT_ANCHORS; // action flags
914 }
915
916 for (;;) { // at most twice
917 MacOSError::check(SecTrustSetParameters(mTrust,
918 CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData))));
919
920 // evaluate trust and extract results
921 SecTrustResultType trustResult;
922 MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
923 mCertChain.take(copyCertChain(mTrust));
924
925 // if this is an Apple developer cert....
926 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain)) {
927 CFRef<CFStringRef> teamIDFromCert;
928 if (CFArrayGetCount(mCertChain) > 0) {
929 SecCertificateRef leaf = (SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, Requirement::leafCert);
930 CFArrayRef organizationalUnits = SecCertificateCopyOrganizationalUnit(leaf);
931 if (organizationalUnits) {
932 teamIDFromCert.take((CFStringRef)CFRetain(CFArrayGetValueAtIndex(organizationalUnits, 0)));
933 CFRelease(organizationalUnits);
934 } else {
935 teamIDFromCert = NULL;
936 }
937
938 if (teamIDFromCert) {
939 CFRef<CFStringRef> teamIDFromCD = CFStringCreateWithCString(NULL, teamID(), kCFStringEncodingUTF8);
940 if (!teamIDFromCD) {
941 Security::Syslog::error("Could not get team identifier (%s)", teamID());
942 MacOSError::throwMe(errSecCSInvalidTeamIdentifier);
943 }
944
945 if (CFStringCompare(teamIDFromCert, teamIDFromCD, 0) != kCFCompareEqualTo) {
946 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory",
947 cfString(teamIDFromCert).c_str(), teamID());
948 MacOSError::throwMe(errSecCSBadTeamIdentifier);
949 }
950 }
951 }
952 }
953
954 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? (int)CFArrayGetCount(mCertChain) : 0);
955 switch (trustResult) {
956 case kSecTrustResultProceed:
957 case kSecTrustResultUnspecified:
958 break; // success
959 case kSecTrustResultDeny:
960 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject
961 case kSecTrustResultInvalid:
962 assert(false); // should never happen
963 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
964 default:
965 {
966 OSStatus result;
967 MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result));
968 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
969 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
970 if (mSigningTimestamp == 0) { // no timestamp available
971 if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET))
972 && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) {
973 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
974 actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs)
975 continue; // retry validation while tolerating expiration
976 }
977 }
978 if (checkfix41082220(result)) {
979 break; // success
980 }
981 Security::Syslog::error("SecStaticCode: verification failed (trust result %d, error %d)", trustResult, (int)result);
982 MacOSError::throwMe(result);
983 }
984 }
985
986 if (mSigningTimestamp) {
987 CFIndex rootix = CFArrayGetCount(mCertChain);
988 if (SecCertificateRef mainRoot = SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, rootix-1)))
989 if (isAppleCA(mainRoot)) {
990 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
991 CFRef<CFArrayRef> tsCerts;
992 OSStatus result = CMSDecoderCopySignerTimestampCertificates(cms, 0, &tsCerts.aref());
993 if (result) {
994 Security::Syslog::error("SecStaticCode: could not get timestamp certificates (error %d)", (int)result);
995 MacOSError::check(result);
996 }
997 CFIndex tsn = CFArrayGetCount(tsCerts);
998 bool good = tsn > 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts, tsn-1)));
999 if (!good) {
1000 result = CSSMERR_TP_NOT_TRUSTED;
1001 Security::Syslog::error("SecStaticCode: timestamp policy verification failed (error %d)", (int)result);
1002 MacOSError::throwMe(result);
1003 }
1004 }
1005 }
1006
1007 return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED;
1008 }
1009
1010 } else
1011 #endif
1012 {
1013 // Do some pre-verification initialization
1014 CFDataRef sig = this->signature();
1015 this->codeDirectory(); // load CodeDirectory (sets mDir)
1016 mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
1017
1018 CFRef<CFDictionaryRef> attrs;
1019 CFRef<CFArrayRef> vf_policies(createVerificationPolicies());
1020
1021 // Verify the CMS signature against mBaseDir (SHA1)
1022 MacOSError::check(SecCMSVerifyCopyDataAndAttributes(sig, mBaseDir, vf_policies, &mTrust.aref(), NULL, &attrs.aref()));
1023
1024 // Copy the signing time
1025 mSigningTime = SecTrustGetVerifyTime(mTrust);
1026
1027 // Validate the cert chain
1028 SecTrustResultType trustResult;
1029 MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
1030
1031 // retrieve auxiliary data bag and verify against current state
1032 CFRef<CFDataRef> hashBag;
1033 hashBag = CFDataRef(CFDictionaryGetValue(attrs, kSecCMSHashAgility));
1034 if (hashBag) {
1035 CFRef<CFDictionaryRef> hashDict = makeCFDictionaryFrom(hashBag);
1036 CFArrayRef cdList = CFArrayRef(CFDictionaryGetValue(hashDict, CFSTR("cdhashes")));
1037 CFArrayRef myCdList = this->cdHashes();
1038 if (cdList == NULL || !CFEqual(cdList, myCdList))
1039 MacOSError::throwMe(errSecCSSignatureFailed);
1040 }
1041
1042 /*
1043 * Populate mCertChain with the certs. If we failed validation, the
1044 * signer's cert will be checked installed provisioning profiles as an
1045 * alternative to verification against the policy for store-signed binaries
1046 */
1047 mCertChain.take(copyCertChain(mTrust));
1048
1049 // Did we implicitly trust the signer?
1050 mTrustedSigningCertChain = (trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed);
1051
1052 return false; // XXX: Not checking for expired certs
1053 }
1054 }
1055
1056 #if TARGET_OS_OSX
1057 //
1058 // Return the TP policy used for signature verification.
1059 // This may be a simple SecPolicyRef or a CFArray of policies.
1060 // The caller owns the return value.
1061 //
1062 static SecPolicyRef makeRevocationPolicy(CFOptionFlags flags)
1063 {
1064 CFRef<SecPolicyRef> policy(SecPolicyCreateRevocation(flags));
1065 return policy.yield();
1066 }
1067 #endif
1068
1069 CFArrayRef SecStaticCode::createVerificationPolicies()
1070 {
1071 if (mValidationFlags & kSecCSUseSoftwareSigningCert) {
1072 CFRef<SecPolicyRef> ssRef = SecPolicyCreateAppleSoftwareSigning();
1073 return makeCFArray(1, ssRef.get());
1074 }
1075 #if TARGET_OS_OSX
1076 if (mValidationFlags & kSecCSApplyEmbeddedPolicy) {
1077 CFRef<SecPolicyRef> iOSRef = SecPolicyCreateiPhoneApplicationSigning();
1078 return makeCFArray(1, iOSRef.get());
1079 }
1080
1081 CFRef<SecPolicyRef> core;
1082 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3,
1083 &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref()));
1084 if (mValidationFlags & kSecCSNoNetworkAccess) {
1085 // Skips all revocation since they require network connectivity
1086 // therefore annihilates kSecCSEnforceRevocationChecks if present
1087 CFRef<SecPolicyRef> no_revoc = makeRevocationPolicy(kSecRevocationNetworkAccessDisabled);
1088 return makeCFArray(2, core.get(), no_revoc.get());
1089 }
1090 else if (mValidationFlags & kSecCSEnforceRevocationChecks) {
1091 // Add CRL and OCSP policies
1092 CFRef<SecPolicyRef> revoc = makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod);
1093 return makeCFArray(2, core.get(), revoc.get());
1094 } else {
1095 return makeCFArray(1, core.get());
1096 }
1097 #elif TARGET_OS_TV
1098 CFRef<SecPolicyRef> tvOSRef = SecPolicyCreateAppleTVOSApplicationSigning();
1099 return makeCFArray(1, tvOSRef.get());
1100 #else
1101 CFRef<SecPolicyRef> iOSRef = SecPolicyCreateiPhoneApplicationSigning();
1102 return makeCFArray(1, iOSRef.get());
1103 #endif
1104
1105 }
1106
1107 CFArrayRef SecStaticCode::createTimeStampingAndRevocationPolicies()
1108 {
1109 CFRef<SecPolicyRef> tsPolicy = SecPolicyCreateAppleTimeStamping();
1110 #if TARGET_OS_OSX
1111 if (mValidationFlags & kSecCSNoNetworkAccess) {
1112 // Skips all revocation since they require network connectivity
1113 // therefore annihilates kSecCSEnforceRevocationChecks if present
1114 CFRef<SecPolicyRef> no_revoc = makeRevocationPolicy(kSecRevocationNetworkAccessDisabled);
1115 return makeCFArray(2, tsPolicy.get(), no_revoc.get());
1116 }
1117 else if (mValidationFlags & kSecCSEnforceRevocationChecks) {
1118 // Add CRL and OCSP policies
1119 CFRef<SecPolicyRef> revoc = makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod);
1120 return makeCFArray(2, tsPolicy.get(), revoc.get());
1121 }
1122 else {
1123 return makeCFArray(1, tsPolicy.get());
1124 }
1125 #else
1126 return makeCFArray(1, tsPolicy.get());
1127 #endif
1128
1129 }
1130
1131 CFArrayRef SecStaticCode::copyCertChain(SecTrustRef trust)
1132 {
1133 SecCertificateRef leafCert = SecTrustGetCertificateAtIndex(trust, 0);
1134 if (leafCert != NULL) {
1135 CFIndex count = SecTrustGetCertificateCount(trust);
1136
1137 CFMutableArrayRef certs = CFArrayCreateMutable(kCFAllocatorDefault, count,
1138 &kCFTypeArrayCallBacks);
1139
1140 CFArrayAppendValue(certs, leafCert);
1141 for (CFIndex i = 1; i < count; ++i) {
1142 CFArrayAppendValue(certs, SecTrustGetCertificateAtIndex(trust, i));
1143 }
1144
1145 return certs;
1146 }
1147 return NULL;
1148 }
1149
1150
1151 //
1152 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
1153 // The resource must already have been placed in the cache.
1154 // This does NOT perform basic validation.
1155 //
1156 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
1157 {
1158 assert(slot <= cdSlotMax);
1159 CFDataRef data = mCache[slot];
1160 assert(data); // must be cached
1161 if (data == CFDataRef(kCFNull)) {
1162 if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there...
1163 MacOSError::throwMe(fail); // ... and is missing
1164 } else {
1165 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot, false))
1166 MacOSError::throwMe(fail);
1167 }
1168 }
1169
1170
1171 //
1172 // Perform static validation of the main executable.
1173 // This reads the main executable from disk and validates it against the
1174 // CodeDirectory code slot array.
1175 // Note that this is NOT an in-memory validation, and is thus potentially
1176 // subject to timing attacks.
1177 //
1178 void SecStaticCode::validateExecutable()
1179 {
1180 if (!validatedExecutable()) {
1181 try {
1182 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this,
1183 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots);
1184 const CodeDirectory *cd = this->codeDirectory();
1185 if (!cd)
1186 MacOSError::throwMe(errSecCSUnsigned);
1187 AutoFileDesc fd(mainExecutablePath(), O_RDONLY);
1188 fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass)
1189 if (Universal *fat = mRep->mainExecutableImage())
1190 fd.seek(fat->archOffset());
1191 size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0;
1192 size_t remaining = cd->signingLimit();
1193 for (uint32_t slot = 0; slot < cd->nCodeSlots; ++slot) {
1194 size_t thisPage = remaining;
1195 if (pageSize)
1196 thisPage = min(thisPage, pageSize);
1197 __block bool good = true;
1198 CodeDirectory::multipleHashFileData(fd, thisPage, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type, Security::DynamicHash *hasher) {
1199 const CodeDirectory* cd = (const CodeDirectory*)CFDataGetBytePtr(mCodeDirectories[type]);
1200 if (!hasher->verify(cd->getSlot(slot,
1201 mValidationFlags & kSecCSValidatePEH)))
1202 good = false;
1203 });
1204 if (!good) {
1205 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot);
1206 MacOSError::throwMe(errSecCSSignatureFailed);
1207 }
1208 remaining -= thisPage;
1209 }
1210 assert(remaining == 0);
1211 mExecutableValidated = true;
1212 mExecutableValidResult = errSecSuccess;
1213 } catch (const CommonError &err) {
1214 mExecutableValidated = true;
1215 mExecutableValidResult = err.osStatus();
1216 throw;
1217 } catch (...) {
1218 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1219 mExecutableValidated = true;
1220 mExecutableValidResult = errSecCSInternalError;
1221 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1222 throw;
1223 }
1224 }
1225 assert(validatedExecutable());
1226 if (mExecutableValidResult != errSecSuccess)
1227 MacOSError::throwMe(mExecutableValidResult);
1228 }
1229
1230 //
1231 // Perform static validation of sealed resources and nested code.
1232 //
1233 // This performs a whole-code static resource scan and effectively
1234 // computes a concordance between what's on disk and what's in the ResourceDirectory.
1235 // Any unsanctioned difference causes an error.
1236 //
1237 unsigned SecStaticCode::estimateResourceWorkload()
1238 {
1239 // workload estimate = number of sealed files
1240 CFDictionaryRef sealedResources = resourceDictionary();
1241 CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files2");
1242 if (files == NULL)
1243 files = cfget<CFDictionaryRef>(sealedResources, "files");
1244 return files ? unsigned(CFDictionaryGetCount(files)) : 0;
1245 }
1246
1247 void SecStaticCode::validateResources(SecCSFlags flags)
1248 {
1249 // do we have a superset of this requested validation cached?
1250 bool doit = true;
1251 if (mResourcesValidated) { // have cached outcome
1252 if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan
1253 doit = false;
1254 }
1255
1256 if (doit) {
1257 string root = cfStringRelease(copyCanonicalPath());
1258 bool itemIsOnRootFS = isOnRootFilesystem(root.c_str());
1259 bool skipRootVolumeExceptions = (mValidationFlags & kSecCSSkipRootVolumeExceptions);
1260 bool useRootFSPolicy = itemIsOnRootFS && !skipRootVolumeExceptions;
1261
1262 bool itemMightUseXattrFiles = pathFileSystemUsesXattrFiles(root.c_str());
1263 bool skipXattrFiles = itemMightUseXattrFiles && (mValidationFlags & kSecCSSkipXattrFiles);
1264
1265 secinfo("staticCode", "performing resource validation for %s (%d, %d, %d, %d, %d)", root.c_str(),
1266 itemIsOnRootFS, skipRootVolumeExceptions, useRootFSPolicy, itemMightUseXattrFiles, skipXattrFiles);
1267
1268 if (mLimitedAsync == NULL) {
1269 bool runMultiThreaded = ((flags & kSecCSSingleThreaded) == kSecCSSingleThreaded) ? false :
1270 (diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey);
1271 mLimitedAsync = new LimitedAsync(runMultiThreaded);
1272 }
1273
1274 try {
1275 CFDictionaryRef rules;
1276 CFDictionaryRef files;
1277 uint32_t version;
1278 if (!loadResources(rules, files, version))
1279 return; // validly no resources; nothing to do (ok)
1280
1281 // found resources, and they are sealed
1282 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this,
1283 (char*)this->mainExecutablePath().c_str(), 0);
1284
1285 // scan through the resources on disk, checking each against the resourceDirectory
1286 mResourcesValidContext = new CollectingContext(*this); // collect all failures in here
1287
1288 // check for weak resource rules
1289 bool strict = flags & kSecCSStrictValidate;
1290 if (!useRootFSPolicy) {
1291 if (strict) {
1292 if (hasWeakResourceRules(rules, version, mAllowOmissions))
1293 if (mTolerateErrors.find(errSecCSWeakResourceRules) == mTolerateErrors.end())
1294 MacOSError::throwMe(errSecCSWeakResourceRules);
1295 if (version == 1)
1296 if (mTolerateErrors.find(errSecCSWeakResourceEnvelope) == mTolerateErrors.end())
1297 MacOSError::throwMe(errSecCSWeakResourceEnvelope);
1298 }
1299 }
1300
1301 Dispatch::Group group;
1302 Dispatch::Group &groupRef = group; // (into block)
1303
1304 // scan through the resources on disk, checking each against the resourceDirectory
1305 __block CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files);
1306 string base = cfString(this->resourceBase());
1307 ResourceBuilder resources(base, base, rules, strict, mTolerateErrors);
1308 this->mResourceScope = &resources;
1309 diskRep()->adjustResources(resources);
1310
1311 resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const string relpath, ResourceBuilder::Rule *rule) {
1312 CFDictionaryRemoveValue(resourceMap, CFTempString(relpath));
1313 bool isSymlink = (ent->fts_info == FTS_SL);
1314
1315 void (^validate)() = ^{
1316 bool needsValidation = true;
1317
1318 if (skipXattrFiles && pathIsValidXattrFile(cfString(resourceBase()) + "/" + relpath, "staticCode")) {
1319 secinfo("staticCode", "resource validation on xattr file skipped: %s", relpath.c_str());
1320 needsValidation = false;
1321 }
1322
1323 if (useRootFSPolicy) {
1324 CFRef<CFURLRef> itemURL = makeCFURL(relpath, false, resourceBase());
1325 string itemPath = cfString(itemURL);
1326 if (isOnRootFilesystem(itemPath.c_str())) {
1327 secinfo("staticCode", "resource validation on root volume skipped: %s", itemPath.c_str());
1328 needsValidation = false;
1329 }
1330 }
1331
1332 if (needsValidation) {
1333 secinfo("staticCode", "performing resource validation on item: %s", relpath.c_str());
1334 validateResource(files, relpath, isSymlink, *mResourcesValidContext, flags, version);
1335 }
1336 reportProgress();
1337 };
1338
1339 mLimitedAsync->perform(groupRef, validate);
1340 });
1341 group.wait(); // wait until all async resources have been validated as well
1342
1343 if (useRootFSPolicy) {
1344 // It's ok to allow leftovers on the root filesystem for now.
1345 } else {
1346 // Look through the leftovers and make sure they're all properly optional resources.
1347 unsigned leftovers = unsigned(CFDictionaryGetCount(resourceMap));
1348 if (leftovers > 0) {
1349 secinfo("staticCode", "%d sealed resource(s) not found in code", int(leftovers));
1350 CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext);
1351 }
1352 }
1353
1354 // now check for any errors found in the reporting context
1355 mResourcesValidated = true;
1356 mResourcesDeep = flags & kSecCSCheckNestedCode;
1357 if (mResourcesValidContext->osStatus() != errSecSuccess)
1358 mResourcesValidContext->throwMe();
1359 } catch (const CommonError &err) {
1360 mResourcesValidated = true;
1361 mResourcesDeep = flags & kSecCSCheckNestedCode;
1362 mResourcesValidResult = err.osStatus();
1363 throw;
1364 } catch (...) {
1365 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1366 mResourcesValidated = true;
1367 mResourcesDeep = flags & kSecCSCheckNestedCode;
1368 mResourcesValidResult = errSecCSInternalError;
1369 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1370 throw;
1371 }
1372 }
1373 assert(validatedResources());
1374 if (mResourcesValidResult)
1375 MacOSError::throwMe(mResourcesValidResult);
1376 if (mResourcesValidContext->osStatus() != errSecSuccess)
1377 mResourcesValidContext->throwMe();
1378 }
1379
1380
1381 bool SecStaticCode::loadResources(CFDictionaryRef& rules, CFDictionaryRef& files, uint32_t& version)
1382 {
1383 // sanity first
1384 CFDictionaryRef sealedResources = resourceDictionary();
1385 if (this->resourceBase()) { // disk has resources
1386 if (sealedResources)
1387 /* go to work below */;
1388 else
1389 MacOSError::throwMe(errSecCSResourcesNotFound);
1390 } else { // disk has no resources
1391 if (sealedResources)
1392 MacOSError::throwMe(errSecCSResourcesNotFound);
1393 else
1394 return false; // no resources, not sealed - fine (no work)
1395 }
1396
1397 // use V2 resource seal if available, otherwise fall back to V1
1398 if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature
1399 rules = cfget<CFDictionaryRef>(sealedResources, "rules2");
1400 files = cfget<CFDictionaryRef>(sealedResources, "files2");
1401 version = 2;
1402 } else { // only V1 available
1403 rules = cfget<CFDictionaryRef>(sealedResources, "rules");
1404 files = cfget<CFDictionaryRef>(sealedResources, "files");
1405 version = 1;
1406 }
1407 if (!rules || !files)
1408 MacOSError::throwMe(errSecCSResourcesInvalid);
1409 return true;
1410 }
1411
1412
1413 void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context)
1414 {
1415 ValidationContext *ctx = static_cast<ValidationContext *>(context);
1416 ResourceSeal seal(value);
1417 if (!seal.optional()) {
1418 if (key && CFGetTypeID(key) == CFStringGetTypeID()) {
1419 CFTempURL tempURL(CFStringRef(key), false, ctx->code.resourceBase());
1420 if (!tempURL.get()) {
1421 ctx->reportProblem(errSecCSBadDictionaryFormat, kSecCFErrorResourceSeal, key);
1422 } else {
1423 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, tempURL);
1424 }
1425 } else {
1426 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key);
1427 }
1428 }
1429 }
1430
1431
1432 static bool isOmitRule(CFTypeRef value)
1433 {
1434 if (CFGetTypeID(value) == CFBooleanGetTypeID())
1435 return value == kCFBooleanFalse;
1436 CFDictionary rule(value, errSecCSResourceRulesInvalid);
1437 return rule.get<CFBooleanRef>("omit") == kCFBooleanTrue;
1438 }
1439
1440 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions)
1441 {
1442 // compute allowed omissions
1443 CFRef<CFArrayRef> defaultOmissions = this->diskRep()->allowedResourceOmissions();
1444 if (!defaultOmissions) {
1445 Syslog::notice("code signing internal problem: diskRep returned no allowedResourceOmissions");
1446 MacOSError::throwMe(errSecCSInternalError);
1447 }
1448 CFRef<CFMutableArrayRef> allowed = CFArrayCreateMutableCopy(NULL, 0, defaultOmissions);
1449 if (allowedOmissions)
1450 CFArrayAppendArray(allowed, allowedOmissions, CFRangeMake(0, CFArrayGetCount(allowedOmissions)));
1451 CFRange range = CFRangeMake(0, CFArrayGetCount(allowed));
1452
1453 // check all resource rules for weakness
1454 string catchAllRule = (version == 1) ? "^Resources/" : "^.*";
1455 __block bool coversAll = false;
1456 __block bool forbiddenOmission = false;
1457 CFArrayRef allowedRef = allowed.get(); // (into block)
1458 CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid);
1459 rules.apply(^(CFStringRef key, CFTypeRef value) {
1460 string pattern = cfString(key, errSecCSResourceRulesInvalid);
1461 if (pattern == catchAllRule && value == kCFBooleanTrue) {
1462 coversAll = true;
1463 return;
1464 }
1465 if (isOmitRule(value))
1466 forbiddenOmission |= !CFArrayContainsValue(allowedRef, range, key);
1467 });
1468
1469 return !coversAll || forbiddenOmission;
1470 }
1471
1472
1473 //
1474 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1475 //
1476 CFDictionaryRef SecStaticCode::infoDictionary()
1477 {
1478 if (!mInfoDict) {
1479 mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed));
1480 secinfo("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get());
1481 }
1482 return mInfoDict;
1483 }
1484
1485 CFDictionaryRef SecStaticCode::entitlements()
1486 {
1487 if (!mEntitlements) {
1488 validateDirectory();
1489 if (CFDataRef entitlementData = component(cdEntitlementSlot)) {
1490 validateComponent(cdEntitlementSlot);
1491 const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData));
1492 if (blob->validateBlob()) {
1493 mEntitlements.take(blob->entitlements());
1494 secinfo("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get());
1495 }
1496 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1497 }
1498 }
1499 return mEntitlements;
1500 }
1501
1502 CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */)
1503 {
1504 if (mResourceDict) // cached
1505 return mResourceDict;
1506 if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, check))
1507 if (cfscan(dict, "{rules=%Dn,files=%Dn}")) {
1508 secinfo("staticCode", "%p loaded ResourceDict %p",
1509 this, mResourceDict.get());
1510 return mResourceDict = dict;
1511 }
1512 // bad format
1513 return NULL;
1514 }
1515
1516
1517 CFDataRef SecStaticCode::copyComponent(CodeDirectory::SpecialSlot slot, CFDataRef hash)
1518 {
1519 const CodeDirectory* cd = this->codeDirectory();
1520 if (CFCopyRef<CFDataRef> component = this->component(slot)) {
1521 if (hash) {
1522 const void *slotHash = cd->getSlot(slot, false);
1523 if (cd->hashSize != CFDataGetLength(hash) || 0 != memcmp(slotHash, CFDataGetBytePtr(hash), cd->hashSize)) {
1524 Syslog::notice("copyComponent hash mismatch slot %d length %d", slot, int(CFDataGetLength(hash)));
1525 return NULL; // mismatch
1526 }
1527 }
1528 return component.yield();
1529 }
1530 return NULL;
1531 }
1532
1533
1534
1535 //
1536 // Load and cache the resource directory base.
1537 // Note that the base is optional for each DiskRep.
1538 //
1539 CFURLRef SecStaticCode::resourceBase()
1540 {
1541 if (!mGotResourceBase) {
1542 string base = mRep->resourcesRootPath();
1543 if (!base.empty())
1544 mResourceBase.take(makeCFURL(base, true));
1545 mGotResourceBase = true;
1546 }
1547 return mResourceBase;
1548 }
1549
1550
1551 //
1552 // Load a component, validate it, convert it to a CFDictionary, and return that.
1553 // This will force load and validation, which means that it will perform basic
1554 // validation if it hasn't been done yet.
1555 //
1556 CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */)
1557 {
1558 if (check)
1559 validateDirectory();
1560 if (CFDataRef infoData = component(slot)) {
1561 validateComponent(slot);
1562 if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData))
1563 return dict;
1564 else
1565 MacOSError::throwMe(errSecCSBadDictionaryFormat);
1566 }
1567 return NULL;
1568 }
1569
1570 //
1571 //
1572 //
1573 CFDictionaryRef SecStaticCode::diskRepInformation()
1574 {
1575 return mRep->diskRepInformation();
1576 }
1577
1578 bool SecStaticCode::checkfix30814861(string path, bool addition) {
1579 // <rdar://problem/30814861> v2 resource rules don't match v1 resource rules
1580
1581 //// Condition 1: Is the app an iOS app that was built with an SDK lower than 9.0?
1582
1583 // We started signing correctly in 2014, 9.0 was first seeded mid-2016.
1584
1585 CFRef<CFDictionaryRef> inf = diskRepInformation();
1586 try {
1587 CFDictionary info(diskRepInformation(), errSecCSNotSupported);
1588 uint32_t platform =
1589 cfNumber(info.get<CFNumberRef>(kSecCodeInfoDiskRepVersionPlatform, errSecCSNotSupported), 0);
1590 uint32_t sdkVersion =
1591 cfNumber(info.get<CFNumberRef>(kSecCodeInfoDiskRepVersionSDK, errSecCSNotSupported), 0);
1592
1593 if (platform != PLATFORM_IOS || sdkVersion >= 0x00090000) {
1594 return false;
1595 }
1596 } catch (const MacOSError &error) {
1597 return false;
1598 }
1599
1600 //// Condition 2: Is it a .sinf/.supf/.supp file at the right location?
1601
1602 static regex_t pathre_sinf;
1603 static regex_t pathre_supp_supf;
1604 static dispatch_once_t once;
1605
1606 dispatch_once(&once, ^{
1607 os_assert_zero(regcomp(&pathre_sinf,
1608 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.sinf$",
1609 REG_EXTENDED | REG_NOSUB));
1610 os_assert_zero(regcomp(&pathre_supp_supf,
1611 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.(supf|supp)$",
1612 REG_EXTENDED | REG_NOSUB));
1613 });
1614
1615 // .sinf is added, .supf/.supp are modified.
1616 const regex_t &pathre = addition ? pathre_sinf : pathre_supp_supf;
1617
1618 const int result = regexec(&pathre, path.c_str(), 0, NULL, 0);
1619
1620 if (result == REG_NOMATCH) {
1621 return false;
1622 } else if (result != 0) {
1623 // Huh?
1624 secerror("unexpected regexec result %d for path '%s'", result, path.c_str());
1625 return false;
1626 }
1627
1628 //// Condition 3: Do the v1 rules actually exclude the file?
1629
1630 dispatch_once(&mCheckfix30814861builder1_once, ^{
1631 // Create the v1 resource builder lazily.
1632 CFDictionaryRef rules1 = cfget<CFDictionaryRef>(resourceDictionary(), "rules");
1633 const string base = cfString(resourceBase());
1634
1635 mCheckfix30814861builder1 = new ResourceBuilder(base, base, rules1, false, mTolerateErrors);
1636 });
1637
1638 ResourceBuilder::Rule const * const matchingRule = mCheckfix30814861builder1->findRule(path);
1639
1640 if (matchingRule == NULL || !(matchingRule->flags & ResourceBuilder::omitted)) {
1641 return false;
1642 }
1643
1644 //// All matched, this file is a check-fixed sinf/supf/supp.
1645
1646 return true;
1647
1648 }
1649
1650 void SecStaticCode::validateResource(CFDictionaryRef files, string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version)
1651 {
1652 if (!resourceBase()) // no resources in DiskRep
1653 MacOSError::throwMe(errSecCSResourcesNotFound);
1654 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1655 if (version > 1 && ((flags & (kSecCSStrictValidate|kSecCSRestrictSidebandData)) == (kSecCSStrictValidate|kSecCSRestrictSidebandData))) {
1656 AutoFileDesc fd(cfString(fullpath));
1657 if (fd.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME) || fd.hasExtendedAttribute(XATTR_FINDERINFO_NAME))
1658 ctx.reportProblem(errSecCSInvalidAssociatedFileData, kSecCFErrorResourceSideband, fullpath);
1659 }
1660 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1661 ResourceSeal seal(file);
1662 const ResourceSeal& rseal = seal;
1663 if (seal.nested()) {
1664 if (isSymlink)
1665 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1666 string suffix = ".framework";
1667 bool isFramework = (path.length() > suffix.length())
1668 && (path.compare(path.length()-suffix.length(), suffix.length(), suffix) == 0);
1669 validateNestedCode(fullpath, seal, flags, isFramework);
1670 } else if (seal.link()) {
1671 if (!isSymlink)
1672 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1673 validateSymlinkResource(cfString(fullpath), cfString(seal.link()), ctx, flags);
1674 } else if (seal.hash(hashAlgorithm())) { // genuine file
1675 if (isSymlink)
1676 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1677 AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file
1678 if (fd) {
1679 __block bool good = true;
1680 CodeDirectory::multipleHashFileData(fd, 0, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type, Security::DynamicHash *hasher) {
1681 if (!hasher->verify(rseal.hash(type)))
1682 good = false;
1683 });
1684 if (!good) {
1685 if (version == 2 && checkfix30814861(path, false)) {
1686 secinfo("validateResource", "%s check-fixed (altered).", path.c_str());
1687 } else {
1688 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1689 }
1690 }
1691 } else {
1692 if (!seal.optional())
1693 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1694 else
1695 return; // validly missing
1696 }
1697 } else
1698 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1699 return;
1700 }
1701 if (version == 1) { // version 1 ignores symlinks altogether
1702 char target[PATH_MAX];
1703 if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0)
1704 return;
1705 }
1706 if (version == 2 && checkfix30814861(path, true)) {
1707 secinfo("validateResource", "%s check-fixed (added).", path.c_str());
1708 } else {
1709 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1710 }
1711 }
1712
1713 void SecStaticCode::validatePlainMemoryResource(string path, CFDataRef fileData, SecCSFlags flags)
1714 {
1715 CFDictionaryRef rules;
1716 CFDictionaryRef files;
1717 uint32_t version;
1718 if (!loadResources(rules, files, version))
1719 MacOSError::throwMe(errSecCSResourcesNotFound); // no resources sealed; this can't be right
1720 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1721 ResourceSeal seal(file);
1722 const Byte *sealHash = seal.hash(hashAlgorithm());
1723 if (sealHash) {
1724 if (codeDirectory()->verifyMemoryContent(fileData, sealHash))
1725 return; // success
1726 }
1727 }
1728 MacOSError::throwMe(errSecCSBadResource);
1729 }
1730
1731 void SecStaticCode::validateSymlinkResource(std::string fullpath, std::string seal, ValidationContext &ctx, SecCSFlags flags)
1732 {
1733 static const char* const allowedDestinations[] = {
1734 "/System/",
1735 "/Library/",
1736 NULL
1737 };
1738 char target[PATH_MAX];
1739 ssize_t len = ::readlink(fullpath.c_str(), target, sizeof(target)-1);
1740 if (len < 0)
1741 UnixError::check(-1);
1742 target[len] = '\0';
1743 std::string fulltarget = target;
1744 if (target[0] != '/') {
1745 size_t lastSlash = fullpath.rfind('/');
1746 fulltarget = fullpath.substr(0, lastSlash) + '/' + target;
1747 }
1748 if (seal != target) {
1749 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, CFTempString(fullpath));
1750 return;
1751 }
1752 if ((mValidationFlags & (kSecCSStrictValidate|kSecCSRestrictSymlinks)) == (kSecCSStrictValidate|kSecCSRestrictSymlinks)) {
1753 char resolved[PATH_MAX];
1754 if (realpath(fulltarget.c_str(), resolved)) {
1755 assert(resolved[0] == '/');
1756 size_t rlen = strlen(resolved);
1757 if (target[0] == '/') {
1758 // absolute symlink; only allow absolute links to system locations
1759 for (const char* const* pathp = allowedDestinations; *pathp; pathp++) {
1760 size_t dlen = strlen(*pathp);
1761 if (rlen > dlen && strncmp(resolved, *pathp, dlen) == 0)
1762 return; // target inside /System, deemed okay
1763 }
1764 } else {
1765 // everything else must be inside the bundle(s)
1766 for (const SecStaticCode* code = this; code; code = code->mOuterScope) {
1767 string root = code->mResourceScope->root();
1768 if (strncmp(resolved, root.c_str(), root.size()) == 0) {
1769 if (code->mResourceScope->includes(resolved + root.length() + 1))
1770 return; // located in resource stack && included in envelope
1771 else
1772 break; // located but excluded from envelope (deny)
1773 }
1774 }
1775 }
1776 }
1777 // if we fell through, flag a symlink error
1778 if (mTolerateErrors.find(errSecCSInvalidSymlink) == mTolerateErrors.end())
1779 ctx.reportProblem(errSecCSInvalidSymlink, kSecCFErrorResourceAltered, CFTempString(fullpath));
1780 }
1781 }
1782
1783 void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework)
1784 {
1785 CFRef<SecRequirementRef> req;
1786 if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref()))
1787 MacOSError::throwMe(errSecCSResourcesInvalid);
1788
1789 // recursively verify this nested code
1790 try {
1791 if (!(flags & kSecCSCheckNestedCode))
1792 flags |= kSecCSBasicValidateOnly | kSecCSQuickCheck;
1793 SecPointer<SecStaticCode> code = new SecStaticCode(DiskRep::bestGuess(cfString(path)));
1794 code->initializeFromParent(*this);
1795 code->staticValidate(flags & (~kSecCSRestrictToAppLike), SecRequirement::required(req));
1796
1797 if (isFramework && (flags & kSecCSStrictValidate))
1798 try {
1799 validateOtherVersions(path, flags & (~kSecCSRestrictToAppLike), req, code);
1800 } catch (const CSError &err) {
1801 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1802 } catch (const MacOSError &err) {
1803 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1804 }
1805
1806 } catch (CSError &err) {
1807 if (err.error == errSecCSReqFailed) {
1808 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1809 return;
1810 }
1811 err.augment(kSecCFErrorPath, path);
1812 throw;
1813 } catch (const MacOSError &err) {
1814 if (err.error == errSecCSReqFailed) {
1815 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1816 return;
1817 }
1818 CSError::throwMe(err.error, kSecCFErrorPath, path);
1819 }
1820 }
1821
1822 void SecStaticCode::validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code)
1823 {
1824 // Find out what current points to and do not revalidate
1825 std::string mainPath = cfStringRelease(code->diskRep()->copyCanonicalPath());
1826
1827 char main_path[PATH_MAX];
1828 bool foundTarget = false;
1829
1830 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1831 not a security hole */
1832 if (realpath(mainPath.c_str(), main_path) != NULL)
1833 foundTarget = true;
1834
1835 std::ostringstream versionsPath;
1836 versionsPath << cfString(path) << "/Versions/";
1837
1838 DirScanner scanner(versionsPath.str());
1839
1840 if (scanner.initialized()) {
1841 struct dirent *entry = NULL;
1842 while ((entry = scanner.getNext()) != NULL) {
1843 std::ostringstream fullPath;
1844
1845 if (entry->d_type != DT_DIR || strcmp(entry->d_name, "Current") == 0)
1846 continue;
1847
1848 fullPath << versionsPath.str() << entry->d_name;
1849
1850 char real_full_path[PATH_MAX];
1851 if (realpath(fullPath.str().c_str(), real_full_path) == NULL)
1852 UnixError::check(-1);
1853
1854 // Do case insensitive comparions because realpath() was called for both paths
1855 if (foundTarget && strcmp(main_path, real_full_path) == 0)
1856 continue;
1857
1858 SecPointer<SecStaticCode> frameworkVersion = new SecStaticCode(DiskRep::bestGuess(real_full_path));
1859 frameworkVersion->initializeFromParent(*this);
1860 frameworkVersion->staticValidate(flags, SecRequirement::required(req));
1861 }
1862 }
1863 }
1864
1865
1866 //
1867 // Test a CodeDirectory flag.
1868 // Returns false if there is no CodeDirectory.
1869 // May throw if the CodeDirectory is present but somehow invalid.
1870 //
1871 bool SecStaticCode::flag(uint32_t tested)
1872 {
1873 if (const CodeDirectory *cd = this->codeDirectory(false))
1874 return cd->flags & tested;
1875 else
1876 return false;
1877 }
1878
1879
1880 //
1881 // Retrieve the full SuperBlob containing all internal requirements.
1882 //
1883 const Requirements *SecStaticCode::internalRequirements()
1884 {
1885 if (CFDataRef reqData = component(cdRequirementsSlot)) {
1886 const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData);
1887 if (!req->validateBlob())
1888 MacOSError::throwMe(errSecCSReqInvalid);
1889 return req;
1890 } else
1891 return NULL;
1892 }
1893
1894
1895 //
1896 // Retrieve a particular internal requirement by type.
1897 //
1898 const Requirement *SecStaticCode::internalRequirement(SecRequirementType type)
1899 {
1900 if (const Requirements *reqs = internalRequirements())
1901 return reqs->find<Requirement>(type);
1902 else
1903 return NULL;
1904 }
1905
1906
1907 //
1908 // Return the Designated Requirement (DR). This can be either explicit in the
1909 // Internal Requirements component, or implicitly generated on demand here.
1910 // Note that an explicit DR may have been implicitly generated at signing time;
1911 // we don't distinguish this case.
1912 //
1913 const Requirement *SecStaticCode::designatedRequirement()
1914 {
1915 if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) {
1916 return req; // explicit in signing data
1917 } else {
1918 if (!mDesignatedReq)
1919 mDesignatedReq = defaultDesignatedRequirement();
1920 return mDesignatedReq;
1921 }
1922 }
1923
1924
1925 //
1926 // Generate the default Designated Requirement (DR) for this StaticCode.
1927 // Ignore any explicit DR it may contain.
1928 //
1929 const Requirement *SecStaticCode::defaultDesignatedRequirement()
1930 {
1931 if (flag(kSecCodeSignatureAdhoc)) {
1932 // adhoc signature: return a cdhash requirement for all architectures
1933 __block Requirement::Maker maker;
1934 Requirement::Maker::Chain chain(maker, opOr);
1935
1936 // insert cdhash requirement for all architectures
1937 __block CFRef<CFMutableArrayRef> allHashes = CFArrayCreateMutableCopy(NULL, 0, this->cdHashes());
1938 handleOtherArchitectures(^(SecStaticCode *other) {
1939 CFArrayRef hashes = other->cdHashes();
1940 CFArrayAppendArray(allHashes, hashes, CFRangeMake(0, CFArrayGetCount(hashes)));
1941 });
1942 CFIndex count = CFArrayGetCount(allHashes);
1943 for (CFIndex n = 0; n < count; ++n) {
1944 chain.add();
1945 maker.cdhash(CFDataRef(CFArrayGetValueAtIndex(allHashes, n)));
1946 }
1947 return maker.make();
1948 } else {
1949 #if TARGET_OS_OSX
1950 // full signature: Gin up full context and let DRMaker do its thing
1951 validateDirectory(); // need the cert chain
1952 CFRef<CFDateRef> secureTimestamp;
1953 if (CFAbsoluteTime time = this->signingTimestamp()) {
1954 secureTimestamp.take(CFDateCreate(NULL, time));
1955 }
1956 Requirement::Context context(this->certificates(),
1957 this->infoDictionary(),
1958 this->entitlements(),
1959 this->identifier(),
1960 this->codeDirectory(),
1961 NULL,
1962 kSecCodeSignatureNoHash,
1963 false,
1964 secureTimestamp,
1965 this->teamID()
1966 );
1967 return DRMaker(context).make();
1968 #else
1969 MacOSError::throwMe(errSecCSUnimplemented);
1970 #endif
1971 }
1972 }
1973
1974
1975 //
1976 // Validate a SecStaticCode against the internal requirement of a particular type.
1977 //
1978 void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target,
1979 OSStatus nullError /* = errSecSuccess */)
1980 {
1981 DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError);
1982 if (const Requirement *req = internalRequirement(type))
1983 target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed);
1984 else if (nullError)
1985 MacOSError::throwMe(nullError);
1986 else
1987 /* accept it */;
1988 }
1989
1990 //
1991 // Validate this StaticCode against an external Requirement
1992 //
1993 bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure)
1994 {
1995 bool result = false;
1996 assert(req);
1997 validateDirectory();
1998 CFRef<CFDateRef> secureTimestamp;
1999 if (CFAbsoluteTime time = this->signingTimestamp()) {
2000 secureTimestamp.take(CFDateCreate(NULL, time));
2001 }
2002 result = req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(),
2003 codeDirectory()->identifier(), codeDirectory(),
2004 NULL, kSecCodeSignatureNoHash, mRep->appleInternalForcePlatform(),
2005 secureTimestamp, teamID()),
2006 failure);
2007 return result;
2008 }
2009
2010 void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure)
2011 {
2012 if (!this->satisfiesRequirement(req, failure))
2013 MacOSError::throwMe(failure);
2014 }
2015
2016 //
2017 // Retrieve one certificate from the cert chain.
2018 // Positive and negative indices can be used:
2019 // [ leaf, intermed-1, ..., intermed-n, anchor ]
2020 // 0 1 ... -2 -1
2021 // Returns NULL if unavailable for any reason.
2022 //
2023 SecCertificateRef SecStaticCode::cert(int ix)
2024 {
2025 validateDirectory(); // need cert chain
2026 if (mCertChain) {
2027 CFIndex length = CFArrayGetCount(mCertChain);
2028 if (ix < 0)
2029 ix += length;
2030 if (ix >= 0 && ix < length)
2031 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix));
2032 }
2033 return NULL;
2034 }
2035
2036 CFArrayRef SecStaticCode::certificates()
2037 {
2038 validateDirectory(); // need cert chain
2039 return mCertChain;
2040 }
2041
2042
2043 //
2044 // Gather (mostly) API-official information about this StaticCode.
2045 //
2046 // This method lives in the twilight between the API and internal layers,
2047 // since it generates API objects (Sec*Refs) for return.
2048 //
2049 CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags)
2050 {
2051 //
2052 // Start with the pieces that we return even for unsigned code.
2053 // This makes Sec[Static]CodeRefs useful as API-level replacements
2054 // of our internal OSXCode objects.
2055 //
2056 CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1,
2057 kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get()
2058 );
2059
2060 //
2061 // If we're not signed, this is all you get
2062 //
2063 if (!this->isSigned())
2064 return dict.yield();
2065
2066 //
2067 // Add the generic attributes that we always include
2068 //
2069 CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier()));
2070 CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get()));
2071 CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format()));
2072 CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource()));
2073 CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash());
2074 CFDictionaryAddValue(dict, kSecCodeInfoCdHashes, this->cdHashes());
2075 CFDictionaryAddValue(dict, kSecCodeInfoCdHashesFull, this->cdHashesFull());
2076 const CodeDirectory* cd = this->codeDirectory(false);
2077 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(cd->hashType));
2078 CFRef<CFArrayRef> digests = makeCFArrayFrom(^CFTypeRef(CodeDirectory::HashAlgorithm type) { return CFTempNumber(type); }, hashAlgorithms());
2079 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithms, digests);
2080 if (cd->platform)
2081 CFDictionaryAddValue(dict, kSecCodeInfoPlatformIdentifier, CFTempNumber(cd->platform));
2082 if (cd->runtimeVersion()) {
2083 CFDictionaryAddValue(dict, kSecCodeInfoRuntimeVersion, CFTempNumber(cd->runtimeVersion()));
2084 }
2085
2086 //
2087 // Deliver any Info.plist only if it looks intact
2088 //
2089 try {
2090 if (CFDictionaryRef info = this->infoDictionary())
2091 CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
2092 } catch (...) { } // don't deliver Info.plist if questionable
2093
2094 //
2095 // kSecCSSigningInformation adds information about signing certificates and chains
2096 //
2097 if (flags & kSecCSSigningInformation)
2098 try {
2099 if (CFDataRef sig = this->signature())
2100 CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig);
2101 if (const char *teamID = this->teamID())
2102 CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID));
2103 if (mTrust)
2104 CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust);
2105 if (CFArrayRef certs = this->certificates())
2106 CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs);
2107 if (CFAbsoluteTime time = this->signingTime())
2108 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
2109 CFDictionaryAddValue(dict, kSecCodeInfoTime, date);
2110 if (CFAbsoluteTime time = this->signingTimestamp())
2111 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
2112 CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date);
2113 } catch (...) { }
2114
2115 //
2116 // kSecCSRequirementInformation adds information on requirements
2117 //
2118 if (flags & kSecCSRequirementInformation)
2119
2120 //DR not currently supported on iOS
2121 #if TARGET_OS_OSX
2122 try {
2123 if (const Requirements *reqs = this->internalRequirements()) {
2124 CFDictionaryAddValue(dict, kSecCodeInfoRequirements,
2125 CFTempString(Dumper::dump(reqs)));
2126 CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs));
2127 }
2128
2129 const Requirement *dreq = this->designatedRequirement();
2130 CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle();
2131 CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef);
2132 if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit
2133 CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
2134 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
2135 } else { // implicit
2136 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef);
2137 }
2138 } catch (...) { }
2139 #endif
2140
2141 try {
2142 if (CFDataRef ent = this->component(cdEntitlementSlot)) {
2143 CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
2144 if (CFDictionaryRef entdict = this->entitlements()) {
2145 if (needsCatalystEntitlementFixup(entdict)) {
2146 // If this entitlement dictionary needs catalyst entitlements, make a copy and stick that into the
2147 // output dictionary instead.
2148 secinfo("staticCode", "%p fixed catalyst entitlements", this);
2149 CFRef<CFMutableDictionaryRef> tempEntitlements = makeCFMutableDictionary(entdict);
2150 updateCatalystEntitlements(tempEntitlements);
2151 CFRef<CFDictionaryRef> newEntitlements = CFDictionaryCreateCopy(NULL, tempEntitlements);
2152 if (newEntitlements) {
2153 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, newEntitlements.get());
2154 } else {
2155 secerror("%p unable to fixup entitlement dictionary", this);
2156 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
2157 }
2158 } else {
2159 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
2160 }
2161 }
2162 }
2163 } catch (...) { }
2164
2165 //
2166 // kSecCSInternalInformation adds internal information meant to be for Apple internal
2167 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
2168 // to reliably transmit through the API wall so that code outside the Security.framework
2169 // can use it without having to play nasty tricks to get it.
2170 //
2171 if (flags & kSecCSInternalInformation) {
2172 try {
2173 if (mDir)
2174 CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir);
2175 CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase()));
2176 if (!(flags & kSecCSSkipResourceDirectory)) {
2177 if (CFRef<CFDictionaryRef> rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation
2178 CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict);
2179 }
2180 if (CFRef<CFDictionaryRef> ddict = diskRepInformation())
2181 CFDictionaryAddValue(dict, kSecCodeInfoDiskRepInfo, ddict);
2182 } catch (...) { }
2183 if (mNotarizationChecked && !isnan(mNotarizationDate)) {
2184 CFRef<CFDateRef> date = CFDateCreate(NULL, mNotarizationDate);
2185 if (date) {
2186 CFDictionaryAddValue(dict, kSecCodeInfoNotarizationDate, date.get());
2187 } else {
2188 secerror("Error creating date from timestamp: %f", mNotarizationDate);
2189 }
2190 }
2191 if (this->codeDirectory()) {
2192 uint32_t version = this->codeDirectory()->version;
2193 CFDictionaryAddValue(dict, kSecCodeInfoSignatureVersion, CFTempNumber(version));
2194 }
2195 }
2196
2197 if (flags & kSecCSCalculateCMSDigest) {
2198 try {
2199 CFDictionaryAddValue(dict, kSecCodeInfoCMSDigestHashType, CFTempNumber(cmsDigestHashType()));
2200
2201 CFRef<CFDataRef> cmsDigest = createCmsDigest();
2202 if (cmsDigest) {
2203 CFDictionaryAddValue(dict, kSecCodeInfoCMSDigest, cmsDigest.get());
2204 }
2205 } catch (...) { }
2206 }
2207
2208 //
2209 // kSecCSContentInformation adds more information about the physical layout
2210 // of the signed code. This is (only) useful for packaging or patching-oriented
2211 // applications.
2212 //
2213 if (flags & kSecCSContentInformation && !(flags & kSecCSSkipResourceDirectory))
2214 if (CFRef<CFArrayRef> files = mRep->modifiedFiles())
2215 CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files);
2216
2217 return dict.yield();
2218 }
2219
2220
2221 //
2222 // Resource validation contexts.
2223 // The default context simply throws a CSError, rudely terminating the operation.
2224 //
2225 SecStaticCode::ValidationContext::~ValidationContext()
2226 { /* virtual */ }
2227
2228 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
2229 {
2230 CSError::throwMe(rc, type, value);
2231 }
2232
2233 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
2234 {
2235 StLock<Mutex> _(mLock);
2236 if (mStatus == errSecSuccess)
2237 mStatus = rc; // record first failure for eventual error return
2238 if (type) {
2239 if (!mCollection)
2240 mCollection.take(makeCFMutableDictionary());
2241 CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type));
2242 if (!element) {
2243 element = makeCFMutableArray(0);
2244 if (!element)
2245 CFError::throwMe();
2246 CFDictionaryAddValue(mCollection, type, element);
2247 CFRelease(element);
2248 }
2249 CFArrayAppendValue(element, value);
2250 }
2251 }
2252
2253 void SecStaticCode::CollectingContext::throwMe()
2254 {
2255 assert(mStatus != errSecSuccess);
2256 throw CSError(mStatus, mCollection.retain());
2257 }
2258
2259
2260 //
2261 // Master validation driver.
2262 // This is the static validation (only) driver for the API.
2263 //
2264 // SecStaticCode exposes an a la carte menu of topical validators applying
2265 // to a given object. The static validation API pulls them together reliably,
2266 // but it also adds three matrix dimensions: architecture (for "fat" Mach-O binaries),
2267 // nested code, and multiple digests. This function will crawl a suitable cross-section of this
2268 // validation matrix based on which options it is given, creating temporary
2269 // SecStaticCode objects on the fly to complete the task.
2270 // (The point, of course, is to do as little duplicate work as possible.)
2271 //
2272 void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req)
2273 {
2274 setValidationFlags(flags);
2275
2276 #if TARGET_OS_OSX
2277 if (!mStaplingChecked) {
2278 mRep->registerStapledTicket();
2279 mStaplingChecked = true;
2280 }
2281
2282 if (mFlags & kSecCSForceOnlineNotarizationCheck) {
2283 if (!mNotarizationChecked) {
2284 if (this->cdHash()) {
2285 bool is_revoked = checkNotarizationServiceForRevocation(this->cdHash(), (SecCSDigestAlgorithm)this->hashAlgorithm(), &mNotarizationDate);
2286 if (is_revoked) {
2287 MacOSError::throwMe(errSecCSRevokedNotarization);
2288 }
2289 }
2290 mNotarizationChecked = true;
2291 }
2292 }
2293 #endif // TARGET_OS_OSX
2294
2295 // initialize progress/cancellation state
2296 if (flags & kSecCSReportProgress)
2297 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
2298
2299
2300 // core components: once per architecture (if any)
2301 this->staticValidateCore(flags, req);
2302 if (flags & kSecCSCheckAllArchitectures)
2303 handleOtherArchitectures(^(SecStaticCode* subcode) {
2304 if (flags & kSecCSCheckGatekeeperArchitectures) {
2305 Universal *fat = subcode->diskRep()->mainExecutableImage();
2306 assert(fat && fat->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
2307 Architecture arch = fat->bestNativeArch(); // actually, the ONLY one
2308 if ((arch.cpuType() & ~CPU_ARCH_MASK) == CPU_TYPE_POWERPC)
2309 return; // irrelevant to Gatekeeper
2310 }
2311 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
2312 subcode->staticValidateCore(flags, req);
2313 });
2314 reportProgress();
2315
2316 // allow monitor intervention in source validation phase
2317 reportEvent(CFSTR("prepared"), NULL);
2318
2319 // resources: once for all architectures
2320 if (!(flags & kSecCSDoNotValidateResources)) {
2321 this->validateResources(flags);
2322 }
2323
2324 // perform strict validation if desired
2325 if (flags & kSecCSStrictValidate) {
2326 mRep->strictValidate(codeDirectory(), mTolerateErrors, mValidationFlags);
2327 reportProgress();
2328 } else if (flags & kSecCSStrictValidateStructure) {
2329 mRep->strictValidateStructure(codeDirectory(), mTolerateErrors, mValidationFlags);
2330 }
2331
2332 // allow monitor intervention
2333 if (CFRef<CFTypeRef> veto = reportEvent(CFSTR("validated"), NULL)) {
2334 if (CFGetTypeID(veto) == CFNumberGetTypeID())
2335 MacOSError::throwMe(cfNumber<OSStatus>(veto.as<CFNumberRef>()));
2336 else
2337 MacOSError::throwMe(errSecCSBadCallbackValue);
2338 }
2339 }
2340
2341 void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req)
2342 {
2343 try {
2344 this->validateNonResourceComponents(); // also validates the CodeDirectory
2345 this->validateTopDirectory();
2346 if (!(flags & kSecCSDoNotValidateExecutable))
2347 this->validateExecutable();
2348 if (req)
2349 this->validateRequirement(req->requirement(), errSecCSReqFailed);
2350 } catch (CSError &err) {
2351 if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O
2352 if (MachO *mach = fat->architecture()) {
2353 err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName()));
2354 delete mach;
2355 }
2356 throw;
2357 } catch (const MacOSError &err) {
2358 // add architecture information if we can get it
2359 if (Universal *fat = this->diskRep()->mainExecutableImage())
2360 if (MachO *mach = fat->architecture()) {
2361 CFTempString arch(mach->architecture().displayName());
2362 delete mach;
2363 CSError::throwMe(err.error, kSecCFErrorArchitecture, arch);
2364 }
2365 throw;
2366 }
2367 }
2368
2369
2370 //
2371 // A helper that generates SecStaticCode objects for all but the primary architecture
2372 // of a fat binary and calls a block on them.
2373 // If there's only one architecture (or this is an architecture-agnostic code),
2374 // nothing happens quickly.
2375 //
2376 void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other))
2377 {
2378 if (Universal *fat = this->diskRep()->mainExecutableImage()) {
2379 Universal::Architectures architectures;
2380 fat->architectures(architectures);
2381 if (architectures.size() > 1) {
2382 DiskRep::Context ctx;
2383 off_t activeOffset = fat->archOffset();
2384 for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) {
2385 try {
2386 ctx.offset = int_cast<size_t, off_t>(fat->archOffset(*arch));
2387 ctx.size = fat->lengthOfSlice(int_cast<off_t,size_t>(ctx.offset));
2388 if (ctx.offset != activeOffset) { // inactive architecture; check it
2389 SecPointer<SecStaticCode> subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx));
2390 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
2391 if (this->teamID() == NULL || subcode->teamID() == NULL) {
2392 if (this->teamID() != subcode->teamID())
2393 MacOSError::throwMe(errSecCSSignatureInvalid);
2394 } else if (strcmp(this->teamID(), subcode->teamID()) != 0)
2395 MacOSError::throwMe(errSecCSSignatureInvalid);
2396 handle(subcode);
2397 }
2398 } catch(std::out_of_range e) {
2399 // some of our int_casts fell over.
2400 MacOSError::throwMe(errSecCSBadObjectFormat);
2401 }
2402 }
2403 }
2404 }
2405 }
2406
2407 //
2408 // A method that takes a certificate chain (certs) and evaluates
2409 // if it is a Mac or IPhone developer cert, an app store distribution cert,
2410 // or a developer ID
2411 //
2412 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs)
2413 {
2414 static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + MACWWDRRequirement + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")";
2415 SecPointer<SecRequirement> req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true);
2416 Requirement::Context ctx(certs, NULL, NULL, "", NULL, NULL, kSecCodeSignatureNoHash, false, NULL, "");
2417
2418 return req->requirement()->validates(ctx);
2419 }
2420
2421 CFDataRef SecStaticCode::createCmsDigest()
2422 {
2423 /*
2424 * The CMS digest is a hash of the primary (first, most compatible) code directory,
2425 * but its hash algorithm is fixed and not related to the code directory's
2426 * hash algorithm.
2427 */
2428
2429 auto it = codeDirectories()->begin();
2430
2431 if (it == codeDirectories()->end()) {
2432 return NULL;
2433 }
2434
2435 CodeDirectory const * const cd = reinterpret_cast<CodeDirectory const*>(CFDataGetBytePtr(it->second));
2436
2437 RefPointer<DynamicHash> hash = cd->hashFor(mCMSDigestHashType);
2438 CFMutableDataRef data = CFDataCreateMutable(NULL, hash->digestLength());
2439 CFDataSetLength(data, hash->digestLength());
2440 hash->update(cd, cd->length());
2441 hash->finish(CFDataGetMutableBytePtr(data));
2442
2443 return data;
2444 }
2445
2446 } // end namespace CodeSigning
2447 } // end namespace Security