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