]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/StaticCode.cpp
Security-59754.41.1.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 //
1232 // Perform static validation of sealed resources and nested code.
1233 //
1234 // This performs a whole-code static resource scan and effectively
1235 // computes a concordance between what's on disk and what's in the ResourceDirectory.
1236 // Any unsanctioned difference causes an error.
1237 //
1238 unsigned SecStaticCode::estimateResourceWorkload()
1239 {
1240 // workload estimate = number of sealed files
1241 CFDictionaryRef sealedResources = resourceDictionary();
1242 CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files2");
1243 if (files == NULL)
1244 files = cfget<CFDictionaryRef>(sealedResources, "files");
1245 return files ? unsigned(CFDictionaryGetCount(files)) : 0;
1246 }
1247
1248 void SecStaticCode::validateResources(SecCSFlags flags)
1249 {
1250 // do we have a superset of this requested validation cached?
1251 bool doit = true;
1252 if (mResourcesValidated) { // have cached outcome
1253 if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan
1254 doit = false;
1255 }
1256
1257 if (doit) {
1258 string root = cfStringRelease(copyCanonicalPath());
1259 bool itemIsOnRootFS = isOnRootFilesystem(root.c_str());
1260 bool requestForcedValidation = (mValidationFlags & kSecCSSkipRootVolumeExceptions);
1261 bool useRootFSPolicy = itemIsOnRootFS && !requestForcedValidation;
1262
1263 secinfo("staticCode", "performing resource validation for %s (%d, %d, %d)", root.c_str(),
1264 itemIsOnRootFS, requestForcedValidation, useRootFSPolicy);
1265
1266 if (mLimitedAsync == NULL) {
1267 bool runMultiThreaded = ((flags & kSecCSSingleThreaded) == kSecCSSingleThreaded) ? false :
1268 (diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey);
1269 mLimitedAsync = new LimitedAsync(runMultiThreaded);
1270 }
1271
1272 try {
1273 CFDictionaryRef rules;
1274 CFDictionaryRef files;
1275 uint32_t version;
1276 if (!loadResources(rules, files, version))
1277 return; // validly no resources; nothing to do (ok)
1278
1279 // found resources, and they are sealed
1280 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this,
1281 (char*)this->mainExecutablePath().c_str(), 0);
1282
1283 // scan through the resources on disk, checking each against the resourceDirectory
1284 mResourcesValidContext = new CollectingContext(*this); // collect all failures in here
1285
1286 // check for weak resource rules
1287 bool strict = flags & kSecCSStrictValidate;
1288 if (!useRootFSPolicy) {
1289 if (strict) {
1290 if (hasWeakResourceRules(rules, version, mAllowOmissions))
1291 if (mTolerateErrors.find(errSecCSWeakResourceRules) == mTolerateErrors.end())
1292 MacOSError::throwMe(errSecCSWeakResourceRules);
1293 if (version == 1)
1294 if (mTolerateErrors.find(errSecCSWeakResourceEnvelope) == mTolerateErrors.end())
1295 MacOSError::throwMe(errSecCSWeakResourceEnvelope);
1296 }
1297 }
1298
1299 Dispatch::Group group;
1300 Dispatch::Group &groupRef = group; // (into block)
1301
1302 // scan through the resources on disk, checking each against the resourceDirectory
1303 __block CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files);
1304 string base = cfString(this->resourceBase());
1305 ResourceBuilder resources(base, base, rules, strict, mTolerateErrors);
1306 this->mResourceScope = &resources;
1307 diskRep()->adjustResources(resources);
1308
1309 resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const string relpath, ResourceBuilder::Rule *rule) {
1310 CFDictionaryRemoveValue(resourceMap, CFTempString(relpath));
1311 bool isSymlink = (ent->fts_info == FTS_SL);
1312
1313 void (^validate)() = ^{
1314 bool needsValidation = true;
1315
1316 if (useRootFSPolicy) {
1317 CFRef<CFURLRef> itemURL = makeCFURL(relpath, false, resourceBase());
1318 string itemPath = cfString(itemURL);
1319 if (isOnRootFilesystem(itemPath.c_str())) {
1320 secinfo("staticCode", "resource validation on root volume skipped: %s", itemPath.c_str());
1321 needsValidation = false;
1322 }
1323 }
1324
1325 if (needsValidation) {
1326 secinfo("staticCode", "performing resource validation on item: %s", relpath.c_str());
1327 validateResource(files, relpath, isSymlink, *mResourcesValidContext, flags, version);
1328 }
1329 reportProgress();
1330 };
1331
1332 mLimitedAsync->perform(groupRef, validate);
1333 });
1334 group.wait(); // wait until all async resources have been validated as well
1335
1336 if (useRootFSPolicy) {
1337 // It's ok to allow leftovers on the root filesystem for now.
1338 } else {
1339 // Look through the leftovers and make sure they're all properly optional resources.
1340 unsigned leftovers = unsigned(CFDictionaryGetCount(resourceMap));
1341 if (leftovers > 0) {
1342 secinfo("staticCode", "%d sealed resource(s) not found in code", int(leftovers));
1343 CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext);
1344 }
1345 }
1346
1347 // now check for any errors found in the reporting context
1348 mResourcesValidated = true;
1349 mResourcesDeep = flags & kSecCSCheckNestedCode;
1350 if (mResourcesValidContext->osStatus() != errSecSuccess)
1351 mResourcesValidContext->throwMe();
1352 } catch (const CommonError &err) {
1353 mResourcesValidated = true;
1354 mResourcesDeep = flags & kSecCSCheckNestedCode;
1355 mResourcesValidResult = err.osStatus();
1356 throw;
1357 } catch (...) {
1358 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1359 mResourcesValidated = true;
1360 mResourcesDeep = flags & kSecCSCheckNestedCode;
1361 mResourcesValidResult = errSecCSInternalError;
1362 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1363 throw;
1364 }
1365 }
1366 assert(validatedResources());
1367 if (mResourcesValidResult)
1368 MacOSError::throwMe(mResourcesValidResult);
1369 if (mResourcesValidContext->osStatus() != errSecSuccess)
1370 mResourcesValidContext->throwMe();
1371 }
1372
1373
1374 bool SecStaticCode::loadResources(CFDictionaryRef& rules, CFDictionaryRef& files, uint32_t& version)
1375 {
1376 // sanity first
1377 CFDictionaryRef sealedResources = resourceDictionary();
1378 if (this->resourceBase()) { // disk has resources
1379 if (sealedResources)
1380 /* go to work below */;
1381 else
1382 MacOSError::throwMe(errSecCSResourcesNotFound);
1383 } else { // disk has no resources
1384 if (sealedResources)
1385 MacOSError::throwMe(errSecCSResourcesNotFound);
1386 else
1387 return false; // no resources, not sealed - fine (no work)
1388 }
1389
1390 // use V2 resource seal if available, otherwise fall back to V1
1391 if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature
1392 rules = cfget<CFDictionaryRef>(sealedResources, "rules2");
1393 files = cfget<CFDictionaryRef>(sealedResources, "files2");
1394 version = 2;
1395 } else { // only V1 available
1396 rules = cfget<CFDictionaryRef>(sealedResources, "rules");
1397 files = cfget<CFDictionaryRef>(sealedResources, "files");
1398 version = 1;
1399 }
1400 if (!rules || !files)
1401 MacOSError::throwMe(errSecCSResourcesInvalid);
1402 return true;
1403 }
1404
1405
1406 void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context)
1407 {
1408 ValidationContext *ctx = static_cast<ValidationContext *>(context);
1409 ResourceSeal seal(value);
1410 if (!seal.optional()) {
1411 if (key && CFGetTypeID(key) == CFStringGetTypeID()) {
1412 CFTempURL tempURL(CFStringRef(key), false, ctx->code.resourceBase());
1413 if (!tempURL.get()) {
1414 ctx->reportProblem(errSecCSBadDictionaryFormat, kSecCFErrorResourceSeal, key);
1415 } else {
1416 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, tempURL);
1417 }
1418 } else {
1419 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key);
1420 }
1421 }
1422 }
1423
1424
1425 static bool isOmitRule(CFTypeRef value)
1426 {
1427 if (CFGetTypeID(value) == CFBooleanGetTypeID())
1428 return value == kCFBooleanFalse;
1429 CFDictionary rule(value, errSecCSResourceRulesInvalid);
1430 return rule.get<CFBooleanRef>("omit") == kCFBooleanTrue;
1431 }
1432
1433 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions)
1434 {
1435 // compute allowed omissions
1436 CFRef<CFArrayRef> defaultOmissions = this->diskRep()->allowedResourceOmissions();
1437 if (!defaultOmissions) {
1438 Syslog::notice("code signing internal problem: diskRep returned no allowedResourceOmissions");
1439 MacOSError::throwMe(errSecCSInternalError);
1440 }
1441 CFRef<CFMutableArrayRef> allowed = CFArrayCreateMutableCopy(NULL, 0, defaultOmissions);
1442 if (allowedOmissions)
1443 CFArrayAppendArray(allowed, allowedOmissions, CFRangeMake(0, CFArrayGetCount(allowedOmissions)));
1444 CFRange range = CFRangeMake(0, CFArrayGetCount(allowed));
1445
1446 // check all resource rules for weakness
1447 string catchAllRule = (version == 1) ? "^Resources/" : "^.*";
1448 __block bool coversAll = false;
1449 __block bool forbiddenOmission = false;
1450 CFArrayRef allowedRef = allowed.get(); // (into block)
1451 CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid);
1452 rules.apply(^(CFStringRef key, CFTypeRef value) {
1453 string pattern = cfString(key, errSecCSResourceRulesInvalid);
1454 if (pattern == catchAllRule && value == kCFBooleanTrue) {
1455 coversAll = true;
1456 return;
1457 }
1458 if (isOmitRule(value))
1459 forbiddenOmission |= !CFArrayContainsValue(allowedRef, range, key);
1460 });
1461
1462 return !coversAll || forbiddenOmission;
1463 }
1464
1465
1466 //
1467 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1468 //
1469 CFDictionaryRef SecStaticCode::infoDictionary()
1470 {
1471 if (!mInfoDict) {
1472 mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed));
1473 secinfo("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get());
1474 }
1475 return mInfoDict;
1476 }
1477
1478 CFDictionaryRef SecStaticCode::entitlements()
1479 {
1480 if (!mEntitlements) {
1481 validateDirectory();
1482 if (CFDataRef entitlementData = component(cdEntitlementSlot)) {
1483 validateComponent(cdEntitlementSlot);
1484 const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData));
1485 if (blob->validateBlob()) {
1486 mEntitlements.take(blob->entitlements());
1487 secinfo("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get());
1488 }
1489 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1490 }
1491 }
1492 return mEntitlements;
1493 }
1494
1495 CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */)
1496 {
1497 if (mResourceDict) // cached
1498 return mResourceDict;
1499 if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, check))
1500 if (cfscan(dict, "{rules=%Dn,files=%Dn}")) {
1501 secinfo("staticCode", "%p loaded ResourceDict %p",
1502 this, mResourceDict.get());
1503 return mResourceDict = dict;
1504 }
1505 // bad format
1506 return NULL;
1507 }
1508
1509
1510 CFDataRef SecStaticCode::copyComponent(CodeDirectory::SpecialSlot slot, CFDataRef hash)
1511 {
1512 const CodeDirectory* cd = this->codeDirectory();
1513 if (CFCopyRef<CFDataRef> component = this->component(slot)) {
1514 if (hash) {
1515 const void *slotHash = cd->getSlot(slot, false);
1516 if (cd->hashSize != CFDataGetLength(hash) || 0 != memcmp(slotHash, CFDataGetBytePtr(hash), cd->hashSize)) {
1517 Syslog::notice("copyComponent hash mismatch slot %d length %d", slot, int(CFDataGetLength(hash)));
1518 return NULL; // mismatch
1519 }
1520 }
1521 return component.yield();
1522 }
1523 return NULL;
1524 }
1525
1526
1527
1528 //
1529 // Load and cache the resource directory base.
1530 // Note that the base is optional for each DiskRep.
1531 //
1532 CFURLRef SecStaticCode::resourceBase()
1533 {
1534 if (!mGotResourceBase) {
1535 string base = mRep->resourcesRootPath();
1536 if (!base.empty())
1537 mResourceBase.take(makeCFURL(base, true));
1538 mGotResourceBase = true;
1539 }
1540 return mResourceBase;
1541 }
1542
1543
1544 //
1545 // Load a component, validate it, convert it to a CFDictionary, and return that.
1546 // This will force load and validation, which means that it will perform basic
1547 // validation if it hasn't been done yet.
1548 //
1549 CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */)
1550 {
1551 if (check)
1552 validateDirectory();
1553 if (CFDataRef infoData = component(slot)) {
1554 validateComponent(slot);
1555 if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData))
1556 return dict;
1557 else
1558 MacOSError::throwMe(errSecCSBadDictionaryFormat);
1559 }
1560 return NULL;
1561 }
1562
1563 //
1564 //
1565 //
1566 CFDictionaryRef SecStaticCode::diskRepInformation()
1567 {
1568 return mRep->diskRepInformation();
1569 }
1570
1571 bool SecStaticCode::checkfix30814861(string path, bool addition) {
1572 // <rdar://problem/30814861> v2 resource rules don't match v1 resource rules
1573
1574 //// Condition 1: Is the app an iOS app that was built with an SDK lower than 9.0?
1575
1576 // We started signing correctly in 2014, 9.0 was first seeded mid-2016.
1577
1578 CFRef<CFDictionaryRef> inf = diskRepInformation();
1579 try {
1580 CFDictionary info(diskRepInformation(), errSecCSNotSupported);
1581 uint32_t platform =
1582 cfNumber(info.get<CFNumberRef>(kSecCodeInfoDiskRepVersionPlatform, errSecCSNotSupported), 0);
1583 uint32_t sdkVersion =
1584 cfNumber(info.get<CFNumberRef>(kSecCodeInfoDiskRepVersionSDK, errSecCSNotSupported), 0);
1585
1586 if (platform != PLATFORM_IOS || sdkVersion >= 0x00090000) {
1587 return false;
1588 }
1589 } catch (const MacOSError &error) {
1590 return false;
1591 }
1592
1593 //// Condition 2: Is it a .sinf/.supf/.supp file at the right location?
1594
1595 static regex_t pathre_sinf;
1596 static regex_t pathre_supp_supf;
1597 static dispatch_once_t once;
1598
1599 dispatch_once(&once, ^{
1600 os_assert_zero(regcomp(&pathre_sinf,
1601 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.sinf$",
1602 REG_EXTENDED | REG_NOSUB));
1603 os_assert_zero(regcomp(&pathre_supp_supf,
1604 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.(supf|supp)$",
1605 REG_EXTENDED | REG_NOSUB));
1606 });
1607
1608 // .sinf is added, .supf/.supp are modified.
1609 const regex_t &pathre = addition ? pathre_sinf : pathre_supp_supf;
1610
1611 const int result = regexec(&pathre, path.c_str(), 0, NULL, 0);
1612
1613 if (result == REG_NOMATCH) {
1614 return false;
1615 } else if (result != 0) {
1616 // Huh?
1617 secerror("unexpected regexec result %d for path '%s'", result, path.c_str());
1618 return false;
1619 }
1620
1621 //// Condition 3: Do the v1 rules actually exclude the file?
1622
1623 dispatch_once(&mCheckfix30814861builder1_once, ^{
1624 // Create the v1 resource builder lazily.
1625 CFDictionaryRef rules1 = cfget<CFDictionaryRef>(resourceDictionary(), "rules");
1626 const string base = cfString(resourceBase());
1627
1628 mCheckfix30814861builder1 = new ResourceBuilder(base, base, rules1, false, mTolerateErrors);
1629 });
1630
1631 ResourceBuilder::Rule const * const matchingRule = mCheckfix30814861builder1->findRule(path);
1632
1633 if (matchingRule == NULL || !(matchingRule->flags & ResourceBuilder::omitted)) {
1634 return false;
1635 }
1636
1637 //// All matched, this file is a check-fixed sinf/supf/supp.
1638
1639 return true;
1640
1641 }
1642
1643 void SecStaticCode::validateResource(CFDictionaryRef files, string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version)
1644 {
1645 if (!resourceBase()) // no resources in DiskRep
1646 MacOSError::throwMe(errSecCSResourcesNotFound);
1647 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1648 if (version > 1 && ((flags & (kSecCSStrictValidate|kSecCSRestrictSidebandData)) == (kSecCSStrictValidate|kSecCSRestrictSidebandData))) {
1649 AutoFileDesc fd(cfString(fullpath));
1650 if (fd.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME) || fd.hasExtendedAttribute(XATTR_FINDERINFO_NAME))
1651 ctx.reportProblem(errSecCSInvalidAssociatedFileData, kSecCFErrorResourceSideband, fullpath);
1652 }
1653 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1654 ResourceSeal seal(file);
1655 const ResourceSeal& rseal = seal;
1656 if (seal.nested()) {
1657 if (isSymlink)
1658 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1659 string suffix = ".framework";
1660 bool isFramework = (path.length() > suffix.length())
1661 && (path.compare(path.length()-suffix.length(), suffix.length(), suffix) == 0);
1662 validateNestedCode(fullpath, seal, flags, isFramework);
1663 } else if (seal.link()) {
1664 if (!isSymlink)
1665 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1666 validateSymlinkResource(cfString(fullpath), cfString(seal.link()), ctx, flags);
1667 } else if (seal.hash(hashAlgorithm())) { // genuine file
1668 if (isSymlink)
1669 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1670 AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file
1671 if (fd) {
1672 __block bool good = true;
1673 CodeDirectory::multipleHashFileData(fd, 0, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type, Security::DynamicHash *hasher) {
1674 if (!hasher->verify(rseal.hash(type)))
1675 good = false;
1676 });
1677 if (!good) {
1678 if (version == 2 && checkfix30814861(path, false)) {
1679 secinfo("validateResource", "%s check-fixed (altered).", path.c_str());
1680 } else {
1681 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1682 }
1683 }
1684 } else {
1685 if (!seal.optional())
1686 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1687 else
1688 return; // validly missing
1689 }
1690 } else
1691 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1692 return;
1693 }
1694 if (version == 1) { // version 1 ignores symlinks altogether
1695 char target[PATH_MAX];
1696 if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0)
1697 return;
1698 }
1699 if (version == 2 && checkfix30814861(path, true)) {
1700 secinfo("validateResource", "%s check-fixed (added).", path.c_str());
1701 } else {
1702 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1703 }
1704 }
1705
1706 void SecStaticCode::validatePlainMemoryResource(string path, CFDataRef fileData, SecCSFlags flags)
1707 {
1708 CFDictionaryRef rules;
1709 CFDictionaryRef files;
1710 uint32_t version;
1711 if (!loadResources(rules, files, version))
1712 MacOSError::throwMe(errSecCSResourcesNotFound); // no resources sealed; this can't be right
1713 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1714 ResourceSeal seal(file);
1715 const Byte *sealHash = seal.hash(hashAlgorithm());
1716 if (sealHash) {
1717 if (codeDirectory()->verifyMemoryContent(fileData, sealHash))
1718 return; // success
1719 }
1720 }
1721 MacOSError::throwMe(errSecCSBadResource);
1722 }
1723
1724 void SecStaticCode::validateSymlinkResource(std::string fullpath, std::string seal, ValidationContext &ctx, SecCSFlags flags)
1725 {
1726 static const char* const allowedDestinations[] = {
1727 "/System/",
1728 "/Library/",
1729 NULL
1730 };
1731 char target[PATH_MAX];
1732 ssize_t len = ::readlink(fullpath.c_str(), target, sizeof(target)-1);
1733 if (len < 0)
1734 UnixError::check(-1);
1735 target[len] = '\0';
1736 std::string fulltarget = target;
1737 if (target[0] != '/') {
1738 size_t lastSlash = fullpath.rfind('/');
1739 fulltarget = fullpath.substr(0, lastSlash) + '/' + target;
1740 }
1741 if (seal != target) {
1742 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, CFTempString(fullpath));
1743 return;
1744 }
1745 if ((mValidationFlags & (kSecCSStrictValidate|kSecCSRestrictSymlinks)) == (kSecCSStrictValidate|kSecCSRestrictSymlinks)) {
1746 char resolved[PATH_MAX];
1747 if (realpath(fulltarget.c_str(), resolved)) {
1748 assert(resolved[0] == '/');
1749 size_t rlen = strlen(resolved);
1750 if (target[0] == '/') {
1751 // absolute symlink; only allow absolute links to system locations
1752 for (const char* const* pathp = allowedDestinations; *pathp; pathp++) {
1753 size_t dlen = strlen(*pathp);
1754 if (rlen > dlen && strncmp(resolved, *pathp, dlen) == 0)
1755 return; // target inside /System, deemed okay
1756 }
1757 } else {
1758 // everything else must be inside the bundle(s)
1759 for (const SecStaticCode* code = this; code; code = code->mOuterScope) {
1760 string root = code->mResourceScope->root();
1761 if (strncmp(resolved, root.c_str(), root.size()) == 0) {
1762 if (code->mResourceScope->includes(resolved + root.length() + 1))
1763 return; // located in resource stack && included in envelope
1764 else
1765 break; // located but excluded from envelope (deny)
1766 }
1767 }
1768 }
1769 }
1770 // if we fell through, flag a symlink error
1771 if (mTolerateErrors.find(errSecCSInvalidSymlink) == mTolerateErrors.end())
1772 ctx.reportProblem(errSecCSInvalidSymlink, kSecCFErrorResourceAltered, CFTempString(fullpath));
1773 }
1774 }
1775
1776 void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework)
1777 {
1778 CFRef<SecRequirementRef> req;
1779 if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref()))
1780 MacOSError::throwMe(errSecCSResourcesInvalid);
1781
1782 // recursively verify this nested code
1783 try {
1784 if (!(flags & kSecCSCheckNestedCode))
1785 flags |= kSecCSBasicValidateOnly | kSecCSQuickCheck;
1786 SecPointer<SecStaticCode> code = new SecStaticCode(DiskRep::bestGuess(cfString(path)));
1787 code->initializeFromParent(*this);
1788 code->staticValidate(flags & (~kSecCSRestrictToAppLike), SecRequirement::required(req));
1789
1790 if (isFramework && (flags & kSecCSStrictValidate))
1791 try {
1792 validateOtherVersions(path, flags & (~kSecCSRestrictToAppLike), req, code);
1793 } catch (const CSError &err) {
1794 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1795 } catch (const MacOSError &err) {
1796 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1797 }
1798
1799 } catch (CSError &err) {
1800 if (err.error == errSecCSReqFailed) {
1801 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1802 return;
1803 }
1804 err.augment(kSecCFErrorPath, path);
1805 throw;
1806 } catch (const MacOSError &err) {
1807 if (err.error == errSecCSReqFailed) {
1808 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1809 return;
1810 }
1811 CSError::throwMe(err.error, kSecCFErrorPath, path);
1812 }
1813 }
1814
1815 void SecStaticCode::validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code)
1816 {
1817 // Find out what current points to and do not revalidate
1818 std::string mainPath = cfStringRelease(code->diskRep()->copyCanonicalPath());
1819
1820 char main_path[PATH_MAX];
1821 bool foundTarget = false;
1822
1823 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1824 not a security hole */
1825 if (realpath(mainPath.c_str(), main_path) != NULL)
1826 foundTarget = true;
1827
1828 std::ostringstream versionsPath;
1829 versionsPath << cfString(path) << "/Versions/";
1830
1831 DirScanner scanner(versionsPath.str());
1832
1833 if (scanner.initialized()) {
1834 struct dirent *entry = NULL;
1835 while ((entry = scanner.getNext()) != NULL) {
1836 std::ostringstream fullPath;
1837
1838 if (entry->d_type != DT_DIR || strcmp(entry->d_name, "Current") == 0)
1839 continue;
1840
1841 fullPath << versionsPath.str() << entry->d_name;
1842
1843 char real_full_path[PATH_MAX];
1844 if (realpath(fullPath.str().c_str(), real_full_path) == NULL)
1845 UnixError::check(-1);
1846
1847 // Do case insensitive comparions because realpath() was called for both paths
1848 if (foundTarget && strcmp(main_path, real_full_path) == 0)
1849 continue;
1850
1851 SecPointer<SecStaticCode> frameworkVersion = new SecStaticCode(DiskRep::bestGuess(real_full_path));
1852 frameworkVersion->initializeFromParent(*this);
1853 frameworkVersion->staticValidate(flags, SecRequirement::required(req));
1854 }
1855 }
1856 }
1857
1858
1859 //
1860 // Test a CodeDirectory flag.
1861 // Returns false if there is no CodeDirectory.
1862 // May throw if the CodeDirectory is present but somehow invalid.
1863 //
1864 bool SecStaticCode::flag(uint32_t tested)
1865 {
1866 if (const CodeDirectory *cd = this->codeDirectory(false))
1867 return cd->flags & tested;
1868 else
1869 return false;
1870 }
1871
1872
1873 //
1874 // Retrieve the full SuperBlob containing all internal requirements.
1875 //
1876 const Requirements *SecStaticCode::internalRequirements()
1877 {
1878 if (CFDataRef reqData = component(cdRequirementsSlot)) {
1879 const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData);
1880 if (!req->validateBlob())
1881 MacOSError::throwMe(errSecCSReqInvalid);
1882 return req;
1883 } else
1884 return NULL;
1885 }
1886
1887
1888 //
1889 // Retrieve a particular internal requirement by type.
1890 //
1891 const Requirement *SecStaticCode::internalRequirement(SecRequirementType type)
1892 {
1893 if (const Requirements *reqs = internalRequirements())
1894 return reqs->find<Requirement>(type);
1895 else
1896 return NULL;
1897 }
1898
1899
1900 //
1901 // Return the Designated Requirement (DR). This can be either explicit in the
1902 // Internal Requirements component, or implicitly generated on demand here.
1903 // Note that an explicit DR may have been implicitly generated at signing time;
1904 // we don't distinguish this case.
1905 //
1906 const Requirement *SecStaticCode::designatedRequirement()
1907 {
1908 if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) {
1909 return req; // explicit in signing data
1910 } else {
1911 if (!mDesignatedReq)
1912 mDesignatedReq = defaultDesignatedRequirement();
1913 return mDesignatedReq;
1914 }
1915 }
1916
1917
1918 //
1919 // Generate the default Designated Requirement (DR) for this StaticCode.
1920 // Ignore any explicit DR it may contain.
1921 //
1922 const Requirement *SecStaticCode::defaultDesignatedRequirement()
1923 {
1924 if (flag(kSecCodeSignatureAdhoc)) {
1925 // adhoc signature: return a cdhash requirement for all architectures
1926 __block Requirement::Maker maker;
1927 Requirement::Maker::Chain chain(maker, opOr);
1928
1929 // insert cdhash requirement for all architectures
1930 __block CFRef<CFMutableArrayRef> allHashes = CFArrayCreateMutableCopy(NULL, 0, this->cdHashes());
1931 handleOtherArchitectures(^(SecStaticCode *other) {
1932 CFArrayRef hashes = other->cdHashes();
1933 CFArrayAppendArray(allHashes, hashes, CFRangeMake(0, CFArrayGetCount(hashes)));
1934 });
1935 CFIndex count = CFArrayGetCount(allHashes);
1936 for (CFIndex n = 0; n < count; ++n) {
1937 chain.add();
1938 maker.cdhash(CFDataRef(CFArrayGetValueAtIndex(allHashes, n)));
1939 }
1940 return maker.make();
1941 } else {
1942 #if TARGET_OS_OSX
1943 // full signature: Gin up full context and let DRMaker do its thing
1944 validateDirectory(); // need the cert chain
1945 CFRef<CFDateRef> secureTimestamp;
1946 if (CFAbsoluteTime time = this->signingTimestamp()) {
1947 secureTimestamp.take(CFDateCreate(NULL, time));
1948 }
1949 Requirement::Context context(this->certificates(),
1950 this->infoDictionary(),
1951 this->entitlements(),
1952 this->identifier(),
1953 this->codeDirectory(),
1954 NULL,
1955 kSecCodeSignatureNoHash,
1956 false,
1957 secureTimestamp,
1958 this->teamID()
1959 );
1960 return DRMaker(context).make();
1961 #else
1962 MacOSError::throwMe(errSecCSUnimplemented);
1963 #endif
1964 }
1965 }
1966
1967
1968 //
1969 // Validate a SecStaticCode against the internal requirement of a particular type.
1970 //
1971 void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target,
1972 OSStatus nullError /* = errSecSuccess */)
1973 {
1974 DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError);
1975 if (const Requirement *req = internalRequirement(type))
1976 target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed);
1977 else if (nullError)
1978 MacOSError::throwMe(nullError);
1979 else
1980 /* accept it */;
1981 }
1982
1983 //
1984 // Validate this StaticCode against an external Requirement
1985 //
1986 bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure)
1987 {
1988 bool result = false;
1989 assert(req);
1990 validateDirectory();
1991 CFRef<CFDateRef> secureTimestamp;
1992 if (CFAbsoluteTime time = this->signingTimestamp()) {
1993 secureTimestamp.take(CFDateCreate(NULL, time));
1994 }
1995 result = req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(),
1996 codeDirectory()->identifier(), codeDirectory(),
1997 NULL, kSecCodeSignatureNoHash, mRep->appleInternalForcePlatform(),
1998 secureTimestamp, teamID()),
1999 failure);
2000 return result;
2001 }
2002
2003 void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure)
2004 {
2005 if (!this->satisfiesRequirement(req, failure))
2006 MacOSError::throwMe(failure);
2007 }
2008
2009 //
2010 // Retrieve one certificate from the cert chain.
2011 // Positive and negative indices can be used:
2012 // [ leaf, intermed-1, ..., intermed-n, anchor ]
2013 // 0 1 ... -2 -1
2014 // Returns NULL if unavailable for any reason.
2015 //
2016 SecCertificateRef SecStaticCode::cert(int ix)
2017 {
2018 validateDirectory(); // need cert chain
2019 if (mCertChain) {
2020 CFIndex length = CFArrayGetCount(mCertChain);
2021 if (ix < 0)
2022 ix += length;
2023 if (ix >= 0 && ix < length)
2024 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix));
2025 }
2026 return NULL;
2027 }
2028
2029 CFArrayRef SecStaticCode::certificates()
2030 {
2031 validateDirectory(); // need cert chain
2032 return mCertChain;
2033 }
2034
2035
2036 //
2037 // Gather (mostly) API-official information about this StaticCode.
2038 //
2039 // This method lives in the twilight between the API and internal layers,
2040 // since it generates API objects (Sec*Refs) for return.
2041 //
2042 CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags)
2043 {
2044 //
2045 // Start with the pieces that we return even for unsigned code.
2046 // This makes Sec[Static]CodeRefs useful as API-level replacements
2047 // of our internal OSXCode objects.
2048 //
2049 CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1,
2050 kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get()
2051 );
2052
2053 //
2054 // If we're not signed, this is all you get
2055 //
2056 if (!this->isSigned())
2057 return dict.yield();
2058
2059 //
2060 // Add the generic attributes that we always include
2061 //
2062 CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier()));
2063 CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get()));
2064 CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format()));
2065 CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource()));
2066 CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash());
2067 CFDictionaryAddValue(dict, kSecCodeInfoCdHashes, this->cdHashes());
2068 CFDictionaryAddValue(dict, kSecCodeInfoCdHashesFull, this->cdHashesFull());
2069 const CodeDirectory* cd = this->codeDirectory(false);
2070 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(cd->hashType));
2071 CFRef<CFArrayRef> digests = makeCFArrayFrom(^CFTypeRef(CodeDirectory::HashAlgorithm type) { return CFTempNumber(type); }, hashAlgorithms());
2072 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithms, digests);
2073 if (cd->platform)
2074 CFDictionaryAddValue(dict, kSecCodeInfoPlatformIdentifier, CFTempNumber(cd->platform));
2075 if (cd->runtimeVersion()) {
2076 CFDictionaryAddValue(dict, kSecCodeInfoRuntimeVersion, CFTempNumber(cd->runtimeVersion()));
2077 }
2078
2079 //
2080 // Deliver any Info.plist only if it looks intact
2081 //
2082 try {
2083 if (CFDictionaryRef info = this->infoDictionary())
2084 CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
2085 } catch (...) { } // don't deliver Info.plist if questionable
2086
2087 //
2088 // kSecCSSigningInformation adds information about signing certificates and chains
2089 //
2090 if (flags & kSecCSSigningInformation)
2091 try {
2092 if (CFDataRef sig = this->signature())
2093 CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig);
2094 if (const char *teamID = this->teamID())
2095 CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID));
2096 if (mTrust)
2097 CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust);
2098 if (CFArrayRef certs = this->certificates())
2099 CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs);
2100 if (CFAbsoluteTime time = this->signingTime())
2101 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
2102 CFDictionaryAddValue(dict, kSecCodeInfoTime, date);
2103 if (CFAbsoluteTime time = this->signingTimestamp())
2104 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
2105 CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date);
2106 } catch (...) { }
2107
2108 //
2109 // kSecCSRequirementInformation adds information on requirements
2110 //
2111 if (flags & kSecCSRequirementInformation)
2112
2113 //DR not currently supported on iOS
2114 #if TARGET_OS_OSX
2115 try {
2116 if (const Requirements *reqs = this->internalRequirements()) {
2117 CFDictionaryAddValue(dict, kSecCodeInfoRequirements,
2118 CFTempString(Dumper::dump(reqs)));
2119 CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs));
2120 }
2121
2122 const Requirement *dreq = this->designatedRequirement();
2123 CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle();
2124 CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef);
2125 if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit
2126 CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
2127 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
2128 } else { // implicit
2129 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef);
2130 }
2131 } catch (...) { }
2132 #endif
2133
2134 try {
2135 if (CFDataRef ent = this->component(cdEntitlementSlot)) {
2136 CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
2137 if (CFDictionaryRef entdict = this->entitlements()) {
2138 if (needsCatalystEntitlementFixup(entdict)) {
2139 // If this entitlement dictionary needs catalyst entitlements, make a copy and stick that into the
2140 // output dictionary instead.
2141 secinfo("staticCode", "%p fixed catalyst entitlements", this);
2142 CFRef<CFMutableDictionaryRef> tempEntitlements = makeCFMutableDictionary(entdict);
2143 updateCatalystEntitlements(tempEntitlements);
2144 CFRef<CFDictionaryRef> newEntitlements = CFDictionaryCreateCopy(NULL, tempEntitlements);
2145 if (newEntitlements) {
2146 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, newEntitlements.get());
2147 } else {
2148 secerror("%p unable to fixup entitlement dictionary", this);
2149 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
2150 }
2151 } else {
2152 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
2153 }
2154 }
2155 }
2156 } catch (...) { }
2157
2158 //
2159 // kSecCSInternalInformation adds internal information meant to be for Apple internal
2160 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
2161 // to reliably transmit through the API wall so that code outside the Security.framework
2162 // can use it without having to play nasty tricks to get it.
2163 //
2164 if (flags & kSecCSInternalInformation) {
2165 try {
2166 if (mDir)
2167 CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir);
2168 CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase()));
2169 if (!(flags & kSecCSSkipResourceDirectory)) {
2170 if (CFRef<CFDictionaryRef> rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation
2171 CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict);
2172 }
2173 if (CFRef<CFDictionaryRef> ddict = diskRepInformation())
2174 CFDictionaryAddValue(dict, kSecCodeInfoDiskRepInfo, ddict);
2175 } catch (...) { }
2176 if (mNotarizationChecked && !isnan(mNotarizationDate)) {
2177 CFRef<CFDateRef> date = CFDateCreate(NULL, mNotarizationDate);
2178 if (date) {
2179 CFDictionaryAddValue(dict, kSecCodeInfoNotarizationDate, date.get());
2180 } else {
2181 secerror("Error creating date from timestamp: %f", mNotarizationDate);
2182 }
2183 }
2184 if (this->codeDirectory()) {
2185 uint32_t version = this->codeDirectory()->version;
2186 CFDictionaryAddValue(dict, kSecCodeInfoSignatureVersion, CFTempNumber(version));
2187 }
2188 }
2189
2190 if (flags & kSecCSCalculateCMSDigest) {
2191 try {
2192 CFDictionaryAddValue(dict, kSecCodeInfoCMSDigestHashType, CFTempNumber(cmsDigestHashType()));
2193
2194 CFRef<CFDataRef> cmsDigest = createCmsDigest();
2195 if (cmsDigest) {
2196 CFDictionaryAddValue(dict, kSecCodeInfoCMSDigest, cmsDigest.get());
2197 }
2198 } catch (...) { }
2199 }
2200
2201 //
2202 // kSecCSContentInformation adds more information about the physical layout
2203 // of the signed code. This is (only) useful for packaging or patching-oriented
2204 // applications.
2205 //
2206 if (flags & kSecCSContentInformation && !(flags & kSecCSSkipResourceDirectory))
2207 if (CFRef<CFArrayRef> files = mRep->modifiedFiles())
2208 CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files);
2209
2210 return dict.yield();
2211 }
2212
2213
2214 //
2215 // Resource validation contexts.
2216 // The default context simply throws a CSError, rudely terminating the operation.
2217 //
2218 SecStaticCode::ValidationContext::~ValidationContext()
2219 { /* virtual */ }
2220
2221 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
2222 {
2223 CSError::throwMe(rc, type, value);
2224 }
2225
2226 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
2227 {
2228 StLock<Mutex> _(mLock);
2229 if (mStatus == errSecSuccess)
2230 mStatus = rc; // record first failure for eventual error return
2231 if (type) {
2232 if (!mCollection)
2233 mCollection.take(makeCFMutableDictionary());
2234 CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type));
2235 if (!element) {
2236 element = makeCFMutableArray(0);
2237 if (!element)
2238 CFError::throwMe();
2239 CFDictionaryAddValue(mCollection, type, element);
2240 CFRelease(element);
2241 }
2242 CFArrayAppendValue(element, value);
2243 }
2244 }
2245
2246 void SecStaticCode::CollectingContext::throwMe()
2247 {
2248 assert(mStatus != errSecSuccess);
2249 throw CSError(mStatus, mCollection.retain());
2250 }
2251
2252
2253 //
2254 // Master validation driver.
2255 // This is the static validation (only) driver for the API.
2256 //
2257 // SecStaticCode exposes an a la carte menu of topical validators applying
2258 // to a given object. The static validation API pulls them together reliably,
2259 // but it also adds three matrix dimensions: architecture (for "fat" Mach-O binaries),
2260 // nested code, and multiple digests. This function will crawl a suitable cross-section of this
2261 // validation matrix based on which options it is given, creating temporary
2262 // SecStaticCode objects on the fly to complete the task.
2263 // (The point, of course, is to do as little duplicate work as possible.)
2264 //
2265 void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req)
2266 {
2267 setValidationFlags(flags);
2268
2269 #if TARGET_OS_OSX
2270 if (!mStaplingChecked) {
2271 mRep->registerStapledTicket();
2272 mStaplingChecked = true;
2273 }
2274
2275 if (mFlags & kSecCSForceOnlineNotarizationCheck) {
2276 if (!mNotarizationChecked) {
2277 if (this->cdHash()) {
2278 bool is_revoked = checkNotarizationServiceForRevocation(this->cdHash(), (SecCSDigestAlgorithm)this->hashAlgorithm(), &mNotarizationDate);
2279 if (is_revoked) {
2280 MacOSError::throwMe(errSecCSRevokedNotarization);
2281 }
2282 }
2283 mNotarizationChecked = true;
2284 }
2285 }
2286 #endif // TARGET_OS_OSX
2287
2288 // initialize progress/cancellation state
2289 if (flags & kSecCSReportProgress)
2290 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
2291
2292
2293 // core components: once per architecture (if any)
2294 this->staticValidateCore(flags, req);
2295 if (flags & kSecCSCheckAllArchitectures)
2296 handleOtherArchitectures(^(SecStaticCode* subcode) {
2297 if (flags & kSecCSCheckGatekeeperArchitectures) {
2298 Universal *fat = subcode->diskRep()->mainExecutableImage();
2299 assert(fat && fat->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
2300 Architecture arch = fat->bestNativeArch(); // actually, the ONLY one
2301 if ((arch.cpuType() & ~CPU_ARCH_MASK) == CPU_TYPE_POWERPC)
2302 return; // irrelevant to Gatekeeper
2303 }
2304 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
2305 subcode->staticValidateCore(flags, req);
2306 });
2307 reportProgress();
2308
2309 // allow monitor intervention in source validation phase
2310 reportEvent(CFSTR("prepared"), NULL);
2311
2312 // resources: once for all architectures
2313 if (!(flags & kSecCSDoNotValidateResources)) {
2314 this->validateResources(flags);
2315 }
2316
2317 // perform strict validation if desired
2318 if (flags & kSecCSStrictValidate) {
2319 mRep->strictValidate(codeDirectory(), mTolerateErrors, mValidationFlags);
2320 reportProgress();
2321 } else if (flags & kSecCSStrictValidateStructure) {
2322 mRep->strictValidateStructure(codeDirectory(), mTolerateErrors, mValidationFlags);
2323 }
2324
2325 // allow monitor intervention
2326 if (CFRef<CFTypeRef> veto = reportEvent(CFSTR("validated"), NULL)) {
2327 if (CFGetTypeID(veto) == CFNumberGetTypeID())
2328 MacOSError::throwMe(cfNumber<OSStatus>(veto.as<CFNumberRef>()));
2329 else
2330 MacOSError::throwMe(errSecCSBadCallbackValue);
2331 }
2332 }
2333
2334 void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req)
2335 {
2336 try {
2337 this->validateNonResourceComponents(); // also validates the CodeDirectory
2338 this->validateTopDirectory();
2339 if (!(flags & kSecCSDoNotValidateExecutable))
2340 this->validateExecutable();
2341 if (req)
2342 this->validateRequirement(req->requirement(), errSecCSReqFailed);
2343 } catch (CSError &err) {
2344 if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O
2345 if (MachO *mach = fat->architecture()) {
2346 err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName()));
2347 delete mach;
2348 }
2349 throw;
2350 } catch (const MacOSError &err) {
2351 // add architecture information if we can get it
2352 if (Universal *fat = this->diskRep()->mainExecutableImage())
2353 if (MachO *mach = fat->architecture()) {
2354 CFTempString arch(mach->architecture().displayName());
2355 delete mach;
2356 CSError::throwMe(err.error, kSecCFErrorArchitecture, arch);
2357 }
2358 throw;
2359 }
2360 }
2361
2362
2363 //
2364 // A helper that generates SecStaticCode objects for all but the primary architecture
2365 // of a fat binary and calls a block on them.
2366 // If there's only one architecture (or this is an architecture-agnostic code),
2367 // nothing happens quickly.
2368 //
2369 void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other))
2370 {
2371 if (Universal *fat = this->diskRep()->mainExecutableImage()) {
2372 Universal::Architectures architectures;
2373 fat->architectures(architectures);
2374 if (architectures.size() > 1) {
2375 DiskRep::Context ctx;
2376 off_t activeOffset = fat->archOffset();
2377 for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) {
2378 try {
2379 ctx.offset = int_cast<size_t, off_t>(fat->archOffset(*arch));
2380 ctx.size = fat->lengthOfSlice(int_cast<off_t,size_t>(ctx.offset));
2381 if (ctx.offset != activeOffset) { // inactive architecture; check it
2382 SecPointer<SecStaticCode> subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx));
2383 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
2384 if (this->teamID() == NULL || subcode->teamID() == NULL) {
2385 if (this->teamID() != subcode->teamID())
2386 MacOSError::throwMe(errSecCSSignatureInvalid);
2387 } else if (strcmp(this->teamID(), subcode->teamID()) != 0)
2388 MacOSError::throwMe(errSecCSSignatureInvalid);
2389 handle(subcode);
2390 }
2391 } catch(std::out_of_range e) {
2392 // some of our int_casts fell over.
2393 MacOSError::throwMe(errSecCSBadObjectFormat);
2394 }
2395 }
2396 }
2397 }
2398 }
2399
2400 //
2401 // A method that takes a certificate chain (certs) and evaluates
2402 // if it is a Mac or IPhone developer cert, an app store distribution cert,
2403 // or a developer ID
2404 //
2405 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs)
2406 {
2407 static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + MACWWDRRequirement + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")";
2408 SecPointer<SecRequirement> req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true);
2409 Requirement::Context ctx(certs, NULL, NULL, "", NULL, NULL, kSecCodeSignatureNoHash, false, NULL, "");
2410
2411 return req->requirement()->validates(ctx);
2412 }
2413
2414 CFDataRef SecStaticCode::createCmsDigest()
2415 {
2416 /*
2417 * The CMS digest is a hash of the primary (first, most compatible) code directory,
2418 * but its hash algorithm is fixed and not related to the code directory's
2419 * hash algorithm.
2420 */
2421
2422 auto it = codeDirectories()->begin();
2423
2424 if (it == codeDirectories()->end()) {
2425 return NULL;
2426 }
2427
2428 CodeDirectory const * const cd = reinterpret_cast<CodeDirectory const*>(CFDataGetBytePtr(it->second));
2429
2430 RefPointer<DynamicHash> hash = cd->hashFor(mCMSDigestHashType);
2431 CFMutableDataRef data = CFDataCreateMutable(NULL, hash->digestLength());
2432 CFDataSetLength(data, hash->digestLength());
2433 hash->update(cd, cd->length());
2434 hash->finish(CFDataGetMutableBytePtr(data));
2435
2436 return data;
2437 }
2438
2439 } // end namespace CodeSigning
2440 } // end namespace Security