]> git.saurik.com Git - apple/security.git/blob - Security/libsecurity_codesigning/lib/StaticCode.cpp
f7503184cdc9ee735a7d22e50e14668dfa47e929
[apple/security.git] / Security / libsecurity_codesigning / lib / StaticCode.cpp
1 /*
2 * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 //
25 // StaticCode - SecStaticCode API objects
26 //
27 #include "StaticCode.h"
28 #include "Code.h"
29 #include "reqmaker.h"
30 #include "drmaker.h"
31 #include "reqdumper.h"
32 #include "reqparser.h"
33 #include "sigblob.h"
34 #include "resources.h"
35 #include "detachedrep.h"
36 #include "csdatabase.h"
37 #include "csutilities.h"
38 #include "dirscanner.h"
39 #include <CoreFoundation/CFURLAccess.h>
40 #include <Security/SecPolicyPriv.h>
41 #include <Security/SecTrustPriv.h>
42 #include <Security/SecCertificatePriv.h>
43 #include <Security/CMSPrivate.h>
44 #include <Security/SecCmsContentInfo.h>
45 #include <Security/SecCmsSignerInfo.h>
46 #include <Security/SecCmsSignedData.h>
47 #include <Security/cssmapplePriv.h>
48 #include <security_utilities/unix++.h>
49 #include <security_utilities/cfmunge.h>
50 #include <Security/CMSDecoder.h>
51 #include <security_utilities/logging.h>
52 #include <dirent.h>
53 #include <sstream>
54
55
56 namespace Security {
57 namespace CodeSigning {
58
59 using namespace UnixPlusPlus;
60
61 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
62 static const char WWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
63 static const char MACWWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
64 static const char developerID[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
65 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
66 static const char distributionCertificate[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
67 static const char iPhoneDistributionCert[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
68
69 //
70 // Map a component slot number to a suitable error code for a failure
71 //
72 static inline OSStatus errorForSlot(CodeDirectory::SpecialSlot slot)
73 {
74 switch (slot) {
75 case cdInfoSlot:
76 return errSecCSInfoPlistFailed;
77 case cdResourceDirSlot:
78 return errSecCSResourceDirectoryFailed;
79 default:
80 return errSecCSSignatureFailed;
81 }
82 }
83
84
85 //
86 // Construct a SecStaticCode object given a disk representation object
87 //
88 SecStaticCode::SecStaticCode(DiskRep *rep)
89 : mRep(rep),
90 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL),
91 mDesignatedReq(NULL), mGotResourceBase(false), mMonitor(NULL), mEvalDetails(NULL)
92 {
93 CODESIGN_STATIC_CREATE(this, rep);
94 CFRef<CFDataRef> codeDirectory = rep->codeDirectory();
95 if (codeDirectory && CFDataGetLength(codeDirectory) <= 0)
96 MacOSError::throwMe(errSecCSSignatureInvalid);
97 checkForSystemSignature();
98 }
99
100
101 //
102 // Clean up a SecStaticCode object
103 //
104 SecStaticCode::~SecStaticCode() throw()
105 try {
106 ::free(const_cast<Requirement *>(mDesignatedReq));
107 if (mResourcesValidContext)
108 delete mResourcesValidContext;
109 } catch (...) {
110 return;
111 }
112
113
114 //
115 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
116 // and falls back on comparing canonical paths if (both are) not.
117 //
118 bool SecStaticCode::equal(SecCFObject &secOther)
119 {
120 SecStaticCode *other = static_cast<SecStaticCode *>(&secOther);
121 CFDataRef mine = this->cdHash();
122 CFDataRef his = other->cdHash();
123 if (mine || his)
124 return mine && his && CFEqual(mine, his);
125 else
126 return CFEqual(CFRef<CFURLRef>(this->copyCanonicalPath()), CFRef<CFURLRef>(other->copyCanonicalPath()));
127 }
128
129 CFHashCode SecStaticCode::hash()
130 {
131 if (CFDataRef h = this->cdHash())
132 return CFHash(h);
133 else
134 return CFHash(CFRef<CFURLRef>(this->copyCanonicalPath()));
135 }
136
137
138 //
139 // Invoke a stage monitor if registered
140 //
141 CFTypeRef SecStaticCode::reportEvent(CFStringRef stage, CFDictionaryRef info)
142 {
143 if (mMonitor)
144 return mMonitor(this->handle(false), stage, info);
145 else
146 return NULL;
147 }
148
149 void SecStaticCode::prepareProgress(unsigned int workload)
150 {
151 {
152 StLock<Mutex> _(mCancelLock);
153 mCancelPending = false; // not cancelled
154 }
155 if (mValidationFlags & kSecCSReportProgress) {
156 mCurrentWork = 0; // nothing done yet
157 mTotalWork = workload; // totally fake - we don't know how many files we'll get to chew
158 }
159 }
160
161 void SecStaticCode::reportProgress(unsigned amount /* = 1 */)
162 {
163 if (mMonitor && (mValidationFlags & kSecCSReportProgress)) {
164 {
165 // if cancellation is pending, abort now
166 StLock<Mutex> _(mCancelLock);
167 if (mCancelPending)
168 MacOSError::throwMe(errSecCSCancelled);
169 }
170 // update progress and report
171 mCurrentWork += amount;
172 mMonitor(this->handle(false), CFSTR("progress"), CFTemp<CFDictionaryRef>("{current=%d,total=%d}", mCurrentWork, mTotalWork));
173 }
174 }
175
176
177 //
178 // Set validation conditions for fine-tuning legacy tolerance
179 //
180 static void addError(CFTypeRef cfError, void* context)
181 {
182 if (CFGetTypeID(cfError) == CFNumberGetTypeID()) {
183 int64_t error;
184 CFNumberGetValue(CFNumberRef(cfError), kCFNumberSInt64Type, (void*)&error);
185 MacOSErrorSet* errors = (MacOSErrorSet*)context;
186 errors->insert(OSStatus(error));
187 }
188 }
189
190 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions)
191 {
192 if (conditions) {
193 CFDictionary source(conditions, errSecCSDbCorrupt);
194 mAllowOmissions = source.get<CFArrayRef>("omissions");
195 if (CFArrayRef errors = source.get<CFArrayRef>("errors"))
196 CFArrayApplyFunction(errors, CFRangeMake(0, CFArrayGetCount(errors)), addError, &this->mTolerateErrors);
197 }
198 }
199
200
201 //
202 // Request cancellation of a validation in progress.
203 // We do this by posting an abort flag that is checked periodically.
204 //
205 void SecStaticCode::cancelValidation()
206 {
207 StLock<Mutex> _(mCancelLock);
208 if (!(mValidationFlags & kSecCSReportProgress)) // not using progress reporting; cancel won't make it through
209 MacOSError::throwMe(errSecCSInvalidFlags);
210 mCancelPending = true;
211 }
212
213
214 //
215 // Attach a detached signature.
216 //
217 void SecStaticCode::detachedSignature(CFDataRef sigData)
218 {
219 if (sigData) {
220 mDetachedSig = sigData;
221 mRep = new DetachedRep(sigData, mRep->base(), "explicit detached");
222 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep);
223 } else {
224 mDetachedSig = NULL;
225 mRep = mRep->base();
226 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL);
227 }
228 }
229
230
231 //
232 // Consult the system detached signature database to see if it contains
233 // a detached signature for this StaticCode. If it does, fetch and attach it.
234 // We do this only if the code has no signature already attached.
235 //
236 void SecStaticCode::checkForSystemSignature()
237 {
238 if (!this->isSigned()) {
239 SignatureDatabase db;
240 if (db.isOpen())
241 try {
242 if (RefPointer<DiskRep> dsig = db.findCode(mRep)) {
243 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig);
244 mRep = dsig;
245 }
246 } catch (...) {
247 }
248 }
249 }
250
251
252 //
253 // Return a descriptive string identifying the source of the code signature
254 //
255 string SecStaticCode::signatureSource()
256 {
257 if (!isSigned())
258 return "unsigned";
259 if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get()))
260 return rep->source();
261 return "embedded";
262 }
263
264
265 //
266 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
267 // (if possible).
268 //
269 SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref)
270 {
271 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
272 if (SecStaticCode *scode = dynamic_cast<SecStaticCode *>(object))
273 return scode;
274 else if (SecCode *code = dynamic_cast<SecCode *>(object))
275 return code->staticCode();
276 else // neither (a SecSomethingElse)
277 MacOSError::throwMe(errSecCSInvalidObjectRef);
278 }
279
280 SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref)
281 {
282 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
283 if (dynamic_cast<SecStaticCode *>(object))
284 return NULL;
285 else if (SecCode *code = dynamic_cast<SecCode *>(object))
286 return code;
287 else // neither (a SecSomethingElse)
288 MacOSError::throwMe(errSecCSInvalidObjectRef);
289 }
290
291
292 //
293 // Void all cached validity data.
294 //
295 // We also throw out cached components, because the new signature data may have
296 // a different idea of what components should be present. We could reconcile the
297 // cached data instead, if performance seems to be impacted.
298 //
299 void SecStaticCode::resetValidity()
300 {
301 CODESIGN_EVAL_STATIC_RESET(this);
302 mValidated = false;
303 mExecutableValidated = mResourcesValidated = false;
304 if (mResourcesValidContext) {
305 delete mResourcesValidContext;
306 mResourcesValidContext = NULL;
307 }
308 mDir = NULL;
309 mSignature = NULL;
310 for (unsigned n = 0; n < cdSlotCount; n++)
311 mCache[n] = NULL;
312 mInfoDict = NULL;
313 mEntitlements = NULL;
314 mResourceDict = NULL;
315 mDesignatedReq = NULL;
316 mCDHash = NULL;
317 mGotResourceBase = false;
318 mTrust = NULL;
319 mCertChain = NULL;
320 mEvalDetails = NULL;
321 mRep->flush();
322
323 // we may just have updated the system database, so check again
324 checkForSystemSignature();
325 }
326
327
328 //
329 // Retrieve a sealed component by special slot index.
330 // If the CodeDirectory has already been validated, validate against that.
331 // Otherwise, retrieve the component without validation (but cache it). Validation
332 // will go through the cache and validate all cached components.
333 //
334 CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
335 {
336 assert(slot <= cdSlotMax);
337
338 CFRef<CFDataRef> &cache = mCache[slot];
339 if (!cache) {
340 if (CFRef<CFDataRef> data = mRep->component(slot)) {
341 if (validated()) // if the directory has been validated...
342 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good
343 CFDataGetLength(data), -slot))
344 MacOSError::throwMe(errorForSlot(slot)); // ... then bail
345 cache = data; // it's okay, cache it
346 } else { // absent, mark so
347 if (validated()) // if directory has been validated...
348 if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing
349 MacOSError::throwMe(errorForSlot(slot)); // was supposed to be there
350 cache = CFDataRef(kCFNull); // white lie
351 }
352 }
353 return (cache == CFDataRef(kCFNull)) ? NULL : cache.get();
354 }
355
356
357 //
358 // Get the CodeDirectory.
359 // Throws (if check==true) or returns NULL (check==false) if there is none.
360 // Always throws if the CodeDirectory exists but is invalid.
361 // NEVER validates against the signature.
362 //
363 const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */)
364 {
365 if (!mDir) {
366 if (mDir.take(mRep->codeDirectory())) {
367 const CodeDirectory *dir = reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
368 dir->checkIntegrity();
369 }
370 }
371 if (mDir)
372 return reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
373 if (check)
374 MacOSError::throwMe(errSecCSUnsigned);
375 return NULL;
376 }
377
378
379 //
380 // Get the hash of the CodeDirectory.
381 // Returns NULL if there is none.
382 //
383 CFDataRef SecStaticCode::cdHash()
384 {
385 if (!mCDHash) {
386 if (const CodeDirectory *cd = codeDirectory(false)) {
387 SHA1 hash;
388 hash(cd, cd->length());
389 SHA1::Digest digest;
390 hash.finish(digest);
391 mCDHash.take(makeCFData(digest, sizeof(digest)));
392 CODESIGN_STATIC_CDHASH(this, digest, sizeof(digest));
393 }
394 }
395 return mCDHash;
396 }
397
398
399 //
400 // Return the CMS signature blob; NULL if none found.
401 //
402 CFDataRef SecStaticCode::signature()
403 {
404 if (!mSignature)
405 mSignature.take(mRep->signature());
406 if (mSignature)
407 return mSignature;
408 MacOSError::throwMe(errSecCSUnsigned);
409 }
410
411
412 //
413 // Verify the signature on the CodeDirectory.
414 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
415 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
416 //
417 void SecStaticCode::validateDirectory()
418 {
419 // echo previous outcome, if any
420 // track revocation separately, as it may not have been checked
421 // during the initial validation
422 if (!validated() || ((mValidationFlags & kSecCSEnforceRevocationChecks) && !revocationChecked()))
423 try {
424 // perform validation (or die trying)
425 CODESIGN_EVAL_STATIC_DIRECTORY(this);
426 mValidationExpired = verifySignature();
427 if (mValidationFlags & kSecCSEnforceRevocationChecks)
428 mRevocationChecked = true;
429
430 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
431 if (mCache[slot]) // if we already loaded that resource...
432 validateComponent(slot, errorForSlot(slot)); // ... then check it now
433 mValidated = true; // we've done the deed...
434 mValidationResult = errSecSuccess; // ... and it was good
435 } catch (const CommonError &err) {
436 mValidated = true;
437 mValidationResult = err.osStatus();
438 throw;
439 } catch (...) {
440 secdebug("staticCode", "%p validation threw non-common exception", this);
441 mValidated = true;
442 mValidationResult = errSecCSInternalError;
443 throw;
444 }
445 assert(validated());
446 if (mValidationResult == errSecSuccess) {
447 if (mValidationExpired)
448 if ((mValidationFlags & kSecCSConsiderExpiration)
449 || (codeDirectory()->flags & kSecCodeSignatureForceExpiration))
450 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED);
451 } else
452 MacOSError::throwMe(mValidationResult);
453 }
454
455
456 //
457 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
458 // Those latter components are checked by validateResources().
459 //
460 void SecStaticCode::validateNonResourceComponents()
461 {
462 this->validateDirectory();
463 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
464 switch (slot) {
465 case cdResourceDirSlot: // validated by validateResources
466 break;
467 default:
468 this->component(slot); // loads and validates
469 break;
470 }
471 }
472
473
474 //
475 // Get the (signed) signing date from the code signature.
476 // Sadly, we need to validate the signature to get the date (as a side benefit).
477 // This means that you can't get the signing time for invalidly signed code.
478 //
479 // We could run the decoder "almost to" verification to avoid this, but there seems
480 // little practical point to such a duplication of effort.
481 //
482 CFAbsoluteTime SecStaticCode::signingTime()
483 {
484 validateDirectory();
485 return mSigningTime;
486 }
487
488 CFAbsoluteTime SecStaticCode::signingTimestamp()
489 {
490 validateDirectory();
491 return mSigningTimestamp;
492 }
493
494
495 //
496 // Verify the CMS signature on the CodeDirectory.
497 // This performs the cryptographic tango. It returns if the signature is valid,
498 // or throws if it is not. As a side effect, a successful return sets up the
499 // cached certificate chain for future use.
500 // Returns true if the signature is expired (the X.509 sense), false if it's not.
501 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
502 //
503 bool SecStaticCode::verifySignature()
504 {
505 // ad-hoc signed code is considered validly signed by definition
506 if (flag(kSecCodeSignatureAdhoc)) {
507 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
508 return false;
509 }
510
511 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str());
512
513 // decode CMS and extract SecTrust for verification
514 CFRef<CMSDecoderRef> cms;
515 MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder
516 CFDataRef sig = this->signature();
517 MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig)));
518 this->codeDirectory(); // load CodeDirectory (sets mDir)
519 MacOSError::check(CMSDecoderSetDetachedContent(cms, mDir));
520 MacOSError::check(CMSDecoderFinalizeMessage(cms));
521 MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray()));
522 CFRef<CFArrayRef> vf_policies = verificationPolicies();
523 CFRef<CFArrayRef> ts_policies = SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies);
524 CMSSignerStatus status;
525 MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, vf_policies,
526 false, &status, &mTrust.aref(), NULL));
527
528 if (status != kCMSSignerValid)
529 MacOSError::throwMe(errSecCSSignatureFailed);
530
531 // internal signing time (as specified by the signer; optional)
532 mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
533 switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) {
534 case errSecSuccess:
535 case errSecSigningTimeMissing:
536 break;
537 default:
538 MacOSError::throwMe(rc);
539 }
540
541 // certified signing time (as specified by a TSA; optional)
542 mSigningTimestamp = 0;
543 switch (OSStatus rc = CMSDecoderCopySignerTimestampWithPolicy(cms, ts_policies, 0, &mSigningTimestamp)) {
544 case errSecSuccess:
545 case errSecTimestampMissing:
546 break;
547 default:
548 MacOSError::throwMe(rc);
549 }
550
551 // set up the environment for SecTrust
552 if (mValidationFlags & kSecCSNoNetworkAccess) {
553 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust,false)); // no network?
554 }
555 MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors
556 MacOSError::check(SecTrustSetKeychains(mTrust, cfEmptyArray())); // no keychains
557 CSSM_APPLE_TP_ACTION_DATA actionData = {
558 CSSM_APPLE_TP_ACTION_VERSION, // version of data structure
559 CSSM_TP_ACTION_IMPLICIT_ANCHORS // action flags
560 };
561
562 for (;;) { // at most twice
563 MacOSError::check(SecTrustSetParameters(mTrust,
564 CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData))));
565
566 // evaluate trust and extract results
567 SecTrustResultType trustResult;
568 MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
569 MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails));
570
571 // if this is an Apple developer cert....
572 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain)) {
573 CFRef<CFStringRef> teamIDFromCert;
574 if (CFArrayGetCount(mCertChain) > 0) {
575 /* Note that SecCertificateCopySubjectComponent sets the out paramater to NULL if there is no field present */
576 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, Requirement::leafCert),
577 &CSSMOID_OrganizationalUnitName,
578 &teamIDFromCert.aref()));
579
580 if (teamIDFromCert) {
581 CFRef<CFStringRef> teamIDFromCD = CFStringCreateWithCString(NULL, teamID(), kCFStringEncodingUTF8);
582 if (!teamIDFromCD) {
583 MacOSError::throwMe(errSecCSInternalError);
584 }
585
586 if (CFStringCompare(teamIDFromCert, teamIDFromCD, 0) != kCFCompareEqualTo) {
587 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory", cfString(teamIDFromCert).c_str(), teamID());
588 MacOSError::throwMe(errSecCSSignatureInvalid);
589 }
590 }
591 }
592 }
593
594 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? (int)CFArrayGetCount(mCertChain) : 0);
595 switch (trustResult) {
596 case kSecTrustResultProceed:
597 case kSecTrustResultUnspecified:
598 break; // success
599 case kSecTrustResultDeny:
600 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject
601 case kSecTrustResultInvalid:
602 assert(false); // should never happen
603 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
604 default:
605 {
606 OSStatus result;
607 MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result));
608 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
609 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
610 if (mSigningTimestamp == 0) // no timestamp available
611 if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET))
612 && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) {
613 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
614 actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs)
615 continue; // retry validation while tolerating expiration
616 }
617 MacOSError::throwMe(result);
618 }
619 }
620
621 if (mSigningTimestamp) {
622 CFIndex rootix = CFArrayGetCount(mCertChain);
623 if (SecCertificateRef mainRoot = SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, rootix-1)))
624 if (isAppleCA(mainRoot)) {
625 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
626 CFRef<CFArrayRef> tsCerts;
627 MacOSError::check(CMSDecoderCopySignerTimestampCertificates(cms, 0, &tsCerts.aref()));
628 CFIndex tsn = CFArrayGetCount(tsCerts);
629 bool good = tsn > 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts, tsn-1)));
630 if (!good)
631 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
632 }
633 }
634
635 return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED;
636 }
637 }
638
639
640 //
641 // Return the TP policy used for signature verification.
642 // This may be a simple SecPolicyRef or a CFArray of policies.
643 // The caller owns the return value.
644 //
645 static SecPolicyRef makeCRLPolicy()
646 {
647 CFRef<SecPolicyRef> policy;
648 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref()));
649 CSSM_APPLE_TP_CRL_OPTIONS options;
650 memset(&options, 0, sizeof(options));
651 options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION;
652 options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT;
653 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
654 MacOSError::check(SecPolicySetValue(policy, &optData));
655 return policy.yield();
656 }
657
658 static SecPolicyRef makeOCSPPolicy()
659 {
660 CFRef<SecPolicyRef> policy;
661 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref()));
662 CSSM_APPLE_TP_OCSP_OPTIONS options;
663 memset(&options, 0, sizeof(options));
664 options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION;
665 options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT;
666 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
667 MacOSError::check(SecPolicySetValue(policy, &optData));
668 return policy.yield();
669 }
670
671 CFArrayRef SecStaticCode::verificationPolicies()
672 {
673 CFRef<SecPolicyRef> core;
674 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3,
675 &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref()));
676 if (mValidationFlags & kSecCSNoNetworkAccess) {
677 // Skips all revocation since they require network connectivity
678 // therefore annihilates kSecCSEnforceRevocationChecks if present
679 CFRef<SecPolicyRef> no_revoc = SecPolicyCreateRevocation(kSecRevocationNetworkAccessDisabled);
680 return makeCFArray(2, core.get(), no_revoc.get());
681 }
682 else if (mValidationFlags & kSecCSEnforceRevocationChecks) {
683 // Add CRL and OCSPPolicies
684 CFRef<SecPolicyRef> crl = makeCRLPolicy();
685 CFRef<SecPolicyRef> ocsp = makeOCSPPolicy();
686 return makeCFArray(3, core.get(), crl.get(), ocsp.get());
687 } else {
688 return makeCFArray(1, core.get());
689 }
690 }
691
692
693 //
694 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
695 // The resource must already have been placed in the cache.
696 // This does NOT perform basic validation.
697 //
698 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
699 {
700 assert(slot <= cdSlotMax);
701 CFDataRef data = mCache[slot];
702 assert(data); // must be cached
703 if (data == CFDataRef(kCFNull)) {
704 if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there...
705 MacOSError::throwMe(fail); // ... and is missing
706 } else {
707 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot))
708 MacOSError::throwMe(fail);
709 }
710 }
711
712
713 //
714 // Perform static validation of the main executable.
715 // This reads the main executable from disk and validates it against the
716 // CodeDirectory code slot array.
717 // Note that this is NOT an in-memory validation, and is thus potentially
718 // subject to timing attacks.
719 //
720 void SecStaticCode::validateExecutable()
721 {
722 if (!validatedExecutable()) {
723 try {
724 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this,
725 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots);
726 const CodeDirectory *cd = this->codeDirectory();
727 if (!cd)
728 MacOSError::throwMe(errSecCSUnsigned);
729 AutoFileDesc fd(mainExecutablePath(), O_RDONLY);
730 fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass)
731 if (Universal *fat = mRep->mainExecutableImage())
732 fd.seek(fat->archOffset());
733 size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0;
734 size_t remaining = cd->codeLimit;
735 for (uint32_t slot = 0; slot < cd->nCodeSlots; ++slot) {
736 size_t size = min(remaining, pageSize);
737 if (!cd->validateSlot(fd, size, slot)) {
738 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot);
739 MacOSError::throwMe(errSecCSSignatureFailed);
740 }
741 remaining -= size;
742 }
743 mExecutableValidated = true;
744 mExecutableValidResult = errSecSuccess;
745 } catch (const CommonError &err) {
746 mExecutableValidated = true;
747 mExecutableValidResult = err.osStatus();
748 throw;
749 } catch (...) {
750 secdebug("staticCode", "%p executable validation threw non-common exception", this);
751 mExecutableValidated = true;
752 mExecutableValidResult = errSecCSInternalError;
753 throw;
754 }
755 }
756 assert(validatedExecutable());
757 if (mExecutableValidResult != errSecSuccess)
758 MacOSError::throwMe(mExecutableValidResult);
759 }
760
761
762 //
763 // Perform static validation of sealed resources and nested code.
764 //
765 // This performs a whole-code static resource scan and effectively
766 // computes a concordance between what's on disk and what's in the ResourceDirectory.
767 // Any unsanctioned difference causes an error.
768 //
769 unsigned SecStaticCode::estimateResourceWorkload()
770 {
771 // workload estimate = number of sealed files
772 CFDictionaryRef sealedResources = resourceDictionary();
773 CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files2");
774 if (files == NULL)
775 files = cfget<CFDictionaryRef>(sealedResources, "files");
776 return files ? unsigned(CFDictionaryGetCount(files)) : 0;
777 }
778
779 void SecStaticCode::validateResources(SecCSFlags flags)
780 {
781 // do we have a superset of this requested validation cached?
782 bool doit = true;
783 if (mResourcesValidated) { // have cached outcome
784 if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan
785 doit = false;
786 }
787 if (doit) {
788 try {
789 // sanity first
790 CFDictionaryRef sealedResources = resourceDictionary();
791 if (this->resourceBase()) // disk has resources
792 if (sealedResources)
793 /* go to work below */;
794 else
795 MacOSError::throwMe(errSecCSResourcesNotFound);
796 else // disk has no resources
797 if (sealedResources)
798 MacOSError::throwMe(errSecCSResourcesNotFound);
799 else
800 return; // no resources, not sealed - fine (no work)
801
802 // found resources, and they are sealed
803 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this,
804 (char*)this->mainExecutablePath().c_str(), 0);
805
806 // scan through the resources on disk, checking each against the resourceDirectory
807 if (mValidationFlags & kSecCSFullReport)
808 mResourcesValidContext = new CollectingContext(*this); // collect all failures in here
809 else
810 mResourcesValidContext = new ValidationContext(*this); // simple bug-out on first error
811
812 CFDictionaryRef rules;
813 CFDictionaryRef files;
814 uint32_t version;
815 if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature
816 rules = cfget<CFDictionaryRef>(sealedResources, "rules2");
817 files = cfget<CFDictionaryRef>(sealedResources, "files2");
818 version = 2;
819 } else { // only V1 available
820 rules = cfget<CFDictionaryRef>(sealedResources, "rules");
821 files = cfget<CFDictionaryRef>(sealedResources, "files");
822 version = 1;
823 }
824 if (!rules || !files)
825 MacOSError::throwMe(errSecCSResourcesInvalid);
826 // check for weak resource rules
827 bool strict = flags & kSecCSStrictValidate;
828 if (strict) {
829 if (hasWeakResourceRules(rules, version, mAllowOmissions))
830 if (mTolerateErrors.find(errSecCSWeakResourceRules) == mTolerateErrors.end())
831 MacOSError::throwMe(errSecCSWeakResourceRules);
832 if (version == 1)
833 if (mTolerateErrors.find(errSecCSWeakResourceEnvelope) == mTolerateErrors.end())
834 MacOSError::throwMe(errSecCSWeakResourceEnvelope);
835 }
836 __block CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files);
837 string base = cfString(this->resourceBase());
838 ResourceBuilder resources(base, base, rules, codeDirectory()->hashType, strict, mTolerateErrors);
839 diskRep()->adjustResources(resources);
840 resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const char *relpath, ResourceBuilder::Rule *rule) {
841 validateResource(files, relpath, ent->fts_info == FTS_SL, *mResourcesValidContext, flags, version);
842 reportProgress();
843 CFDictionaryRemoveValue(resourceMap, CFTempString(relpath));
844 });
845
846 unsigned leftovers = unsigned(CFDictionaryGetCount(resourceMap));
847 if (leftovers > 0) {
848 secdebug("staticCode", "%d sealed resource(s) not found in code", int(leftovers));
849 CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext);
850 }
851
852 // now check for any errors found in the reporting context
853 mResourcesValidated = true;
854 mResourcesDeep = flags & kSecCSCheckNestedCode;
855 if (mResourcesValidContext->osStatus() != errSecSuccess)
856 mResourcesValidContext->throwMe();
857 } catch (const CommonError &err) {
858 mResourcesValidated = true;
859 mResourcesDeep = flags & kSecCSCheckNestedCode;
860 mResourcesValidResult = err.osStatus();
861 throw;
862 } catch (...) {
863 secdebug("staticCode", "%p executable validation threw non-common exception", this);
864 mResourcesValidated = true;
865 mResourcesDeep = flags & kSecCSCheckNestedCode;
866 mResourcesValidResult = errSecCSInternalError;
867 throw;
868 }
869 }
870 assert(validatedResources());
871 if (mResourcesValidResult)
872 MacOSError::throwMe(mResourcesValidResult);
873 if (mResourcesValidContext->osStatus() != errSecSuccess)
874 mResourcesValidContext->throwMe();
875 }
876
877
878 void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context)
879 {
880 ValidationContext *ctx = static_cast<ValidationContext *>(context);
881 ResourceSeal seal(value);
882 if (!seal.optional()) {
883 if (key && CFGetTypeID(key) == CFStringGetTypeID()) {
884 CFTempURL tempURL(CFStringRef(key), false, ctx->code.resourceBase());
885 if (!tempURL.get()) {
886 ctx->reportProblem(errSecCSBadDictionaryFormat, kSecCFErrorResourceSeal, key);
887 } else {
888 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, tempURL);
889 }
890 } else {
891 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key);
892 }
893 }
894 }
895
896
897 static bool isOmitRule(CFTypeRef value)
898 {
899 if (CFGetTypeID(value) == CFBooleanGetTypeID())
900 return value == kCFBooleanFalse;
901 CFDictionary rule(value, errSecCSResourceRulesInvalid);
902 return rule.get<CFBooleanRef>("omit") == kCFBooleanTrue;
903 }
904
905 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions)
906 {
907 // compute allowed omissions
908 CFRef<CFArrayRef> defaultOmissions = this->diskRep()->allowedResourceOmissions();
909 if (!defaultOmissions)
910 MacOSError::throwMe(errSecCSInternalError);
911 CFRef<CFMutableArrayRef> allowed = CFArrayCreateMutableCopy(NULL, 0, defaultOmissions);
912 if (allowedOmissions)
913 CFArrayAppendArray(allowed, allowedOmissions, CFRangeMake(0, CFArrayGetCount(allowedOmissions)));
914 CFRange range = CFRangeMake(0, CFArrayGetCount(allowed));
915
916 // check all resource rules for weakness
917 string catchAllRule = (version == 1) ? "^Resources/" : "^.*";
918 __block bool coversAll = false;
919 __block bool forbiddenOmission = false;
920 CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid);
921 rules.apply(^(CFStringRef key, CFTypeRef value) {
922 string pattern = cfString(key, errSecCSResourceRulesInvalid);
923 if (pattern == catchAllRule && value == kCFBooleanTrue) {
924 coversAll = true;
925 return;
926 }
927 if (isOmitRule(value))
928 forbiddenOmission |= !CFArrayContainsValue(allowed, range, key);
929 });
930
931 return !coversAll || forbiddenOmission;
932 }
933
934
935 //
936 // Load, validate, cache, and return CFDictionary forms of sealed resources.
937 //
938 CFDictionaryRef SecStaticCode::infoDictionary()
939 {
940 if (!mInfoDict) {
941 mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed));
942 secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get());
943 }
944 return mInfoDict;
945 }
946
947 CFDictionaryRef SecStaticCode::entitlements()
948 {
949 if (!mEntitlements) {
950 validateDirectory();
951 if (CFDataRef entitlementData = component(cdEntitlementSlot)) {
952 validateComponent(cdEntitlementSlot);
953 const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData));
954 if (blob->validateBlob()) {
955 mEntitlements.take(blob->entitlements());
956 secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get());
957 }
958 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
959 }
960 }
961 return mEntitlements;
962 }
963
964 CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */)
965 {
966 if (mResourceDict) // cached
967 return mResourceDict;
968 if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, check))
969 if (cfscan(dict, "{rules=%Dn,files=%Dn}")) {
970 secdebug("staticCode", "%p loaded ResourceDict %p",
971 this, mResourceDict.get());
972 return mResourceDict = dict;
973 }
974 // bad format
975 return NULL;
976 }
977
978
979 //
980 // Load and cache the resource directory base.
981 // Note that the base is optional for each DiskRep.
982 //
983 CFURLRef SecStaticCode::resourceBase()
984 {
985 if (!mGotResourceBase) {
986 string base = mRep->resourcesRootPath();
987 if (!base.empty())
988 mResourceBase.take(makeCFURL(base, true));
989 mGotResourceBase = true;
990 }
991 return mResourceBase;
992 }
993
994
995 //
996 // Load a component, validate it, convert it to a CFDictionary, and return that.
997 // This will force load and validation, which means that it will perform basic
998 // validation if it hasn't been done yet.
999 //
1000 CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */)
1001 {
1002 if (check)
1003 validateDirectory();
1004 if (CFDataRef infoData = component(slot)) {
1005 validateComponent(slot);
1006 if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData))
1007 return dict;
1008 else
1009 MacOSError::throwMe(errSecCSBadDictionaryFormat);
1010 }
1011 return NULL;
1012 }
1013
1014
1015 //
1016 // Load, validate, and return a sealed resource.
1017 // The resource data (loaded in to memory as a blob) is returned and becomes
1018 // the responsibility of the caller; it is NOT cached by SecStaticCode.
1019 //
1020 // A resource that is not sealed will not be returned, and an error will be thrown.
1021 // A missing resource will cause an error unless it's marked optional in the Directory.
1022 // Under no circumstances will a corrupt resource be returned.
1023 // NULL will only be returned for a resource that is neither sealed nor present
1024 // (or that is sealed, absent, and marked optional).
1025 // If the ResourceDictionary itself is not sealed, this function will always fail.
1026 //
1027 // There is currently no interface for partial retrieval of the resource data.
1028 // (Since the ResourceDirectory does not currently support segmentation, all the
1029 // data would have to be read anyway, but it could be read into a reusable buffer.)
1030 //
1031 CFDataRef SecStaticCode::resource(string path, ValidationContext &ctx)
1032 {
1033 if (CFDictionaryRef rdict = resourceDictionary()) {
1034 if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) {
1035 ResourceSeal seal = file;
1036 if (!resourceBase()) // no resources in DiskRep
1037 MacOSError::throwMe(errSecCSResourcesNotFound);
1038 if (seal.nested())
1039 MacOSError::throwMe(errSecCSResourcesNotSealed); // (it's nested code)
1040 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1041 if (CFRef<CFDataRef> data = cfLoadFile(fullpath)) {
1042 MakeHash<CodeDirectory> hasher(this->codeDirectory());
1043 hasher->update(CFDataGetBytePtr(data), CFDataGetLength(data));
1044 if (hasher->verify(seal.hash()))
1045 return data.yield(); // good
1046 else
1047 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1048 } else {
1049 if (!seal.optional())
1050 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1051 else
1052 return NULL; // validly missing
1053 }
1054 } else
1055 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1056 return NULL;
1057 } else
1058 MacOSError::throwMe(errSecCSResourcesNotSealed);
1059 }
1060
1061 CFDataRef SecStaticCode::resource(string path)
1062 {
1063 ValidationContext ctx(*this);
1064 return resource(path, ctx);
1065 }
1066
1067 void SecStaticCode::validateResource(CFDictionaryRef files, string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version)
1068 {
1069 if (!resourceBase()) // no resources in DiskRep
1070 MacOSError::throwMe(errSecCSResourcesNotFound);
1071 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1072 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1073 ResourceSeal seal = file;
1074 if (seal.nested()) {
1075 if (isSymlink)
1076 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1077 string suffix = ".framework";
1078 bool isFramework = (path.length() > suffix.length())
1079 && (path.compare(path.length()-suffix.length(), suffix.length(), suffix) == 0);
1080 validateNestedCode(fullpath, seal, flags, isFramework);
1081 } else if (seal.link()) {
1082 char target[PATH_MAX];
1083 ssize_t len = ::readlink(cfString(fullpath).c_str(), target, sizeof(target)-1);
1084 if (len < 0)
1085 UnixError::check(-1);
1086 target[len] = '\0';
1087 if (cfString(seal.link()) != target)
1088 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath);
1089 } else if (seal.hash()) { // genuine file
1090 AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file
1091 if (fd) {
1092 MakeHash<CodeDirectory> hasher(this->codeDirectory());
1093 hashFileData(fd, hasher.get());
1094 if (hasher->verify(seal.hash()))
1095 return; // verify good
1096 else
1097 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1098 } else {
1099 if (!seal.optional())
1100 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1101 else
1102 return; // validly missing
1103 }
1104 } else
1105 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1106 return;
1107 }
1108 if (version == 1) { // version 1 ignores symlinks altogether
1109 char target[PATH_MAX];
1110 if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0)
1111 return;
1112 }
1113 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1114 }
1115
1116 void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework)
1117 {
1118 CFRef<SecRequirementRef> req;
1119 if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref()))
1120 MacOSError::throwMe(errSecCSResourcesInvalid);
1121
1122 // recursively verify this nested code
1123 try {
1124 if (!(flags & kSecCSCheckNestedCode))
1125 flags |= kSecCSBasicValidateOnly;
1126 SecPointer<SecStaticCode> code = new SecStaticCode(DiskRep::bestGuess(cfString(path)));
1127 code->setMonitor(this->monitor());
1128 code->staticValidate(flags, SecRequirement::required(req));
1129
1130 if (isFramework && (flags & kSecCSStrictValidate))
1131 try {
1132 validateOtherVersions(path, flags, req, code);
1133 } catch (const CSError &err) {
1134 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1135 } catch (const MacOSError &err) {
1136 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1137 }
1138
1139 } catch (CSError &err) {
1140 if (err.error == errSecCSReqFailed) {
1141 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1142 return;
1143 }
1144 err.augment(kSecCFErrorPath, path);
1145 throw;
1146 } catch (const MacOSError &err) {
1147 if (err.error == errSecCSReqFailed) {
1148 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1149 return;
1150 }
1151 CSError::throwMe(err.error, kSecCFErrorPath, path);
1152 }
1153 }
1154
1155 void SecStaticCode::validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code)
1156 {
1157 // Find out what current points to and do not revalidate
1158 std::string mainPath = cfStringRelease(code->diskRep()->copyCanonicalPath());
1159
1160 char main_path[PATH_MAX];
1161 bool foundTarget = false;
1162
1163 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1164 not a security hole */
1165 if (realpath(mainPath.c_str(), main_path) != NULL)
1166 foundTarget = true;
1167
1168 std::ostringstream versionsPath;
1169 versionsPath << cfString(path) << "/Versions/";
1170
1171 DirScanner scanner(versionsPath.str());
1172
1173 if (scanner.initialized()) {
1174 struct dirent *entry = NULL;
1175 while ((entry = scanner.getNext()) != NULL) {
1176 std::ostringstream fullPath;
1177
1178 if (entry->d_type != DT_DIR ||
1179 strcmp(entry->d_name, ".") == 0 ||
1180 strcmp(entry->d_name, "..") == 0 ||
1181 strcmp(entry->d_name, "Current") == 0)
1182 continue;
1183
1184 fullPath << versionsPath.str() << entry->d_name;
1185
1186 char real_full_path[PATH_MAX];
1187 if (realpath(fullPath.str().c_str(), real_full_path) == NULL)
1188 UnixError::check(-1);
1189
1190 // Do case insensitive comparions because realpath() was called for both paths
1191 if (foundTarget && strcmp(main_path, real_full_path) == 0)
1192 continue;
1193
1194 SecPointer<SecStaticCode> frameworkVersion = new SecStaticCode(DiskRep::bestGuess(real_full_path));
1195 frameworkVersion->setMonitor(this->monitor());
1196 frameworkVersion->staticValidate(flags, SecRequirement::required(req));
1197 }
1198 }
1199 }
1200
1201
1202 //
1203 // Test a CodeDirectory flag.
1204 // Returns false if there is no CodeDirectory.
1205 // May throw if the CodeDirectory is present but somehow invalid.
1206 //
1207 bool SecStaticCode::flag(uint32_t tested)
1208 {
1209 if (const CodeDirectory *cd = this->codeDirectory(false))
1210 return cd->flags & tested;
1211 else
1212 return false;
1213 }
1214
1215
1216 //
1217 // Retrieve the full SuperBlob containing all internal requirements.
1218 //
1219 const Requirements *SecStaticCode::internalRequirements()
1220 {
1221 if (CFDataRef reqData = component(cdRequirementsSlot)) {
1222 const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData);
1223 if (!req->validateBlob())
1224 MacOSError::throwMe(errSecCSReqInvalid);
1225 return req;
1226 } else
1227 return NULL;
1228 }
1229
1230
1231 //
1232 // Retrieve a particular internal requirement by type.
1233 //
1234 const Requirement *SecStaticCode::internalRequirement(SecRequirementType type)
1235 {
1236 if (const Requirements *reqs = internalRequirements())
1237 return reqs->find<Requirement>(type);
1238 else
1239 return NULL;
1240 }
1241
1242
1243 //
1244 // Return the Designated Requirement (DR). This can be either explicit in the
1245 // Internal Requirements component, or implicitly generated on demand here.
1246 // Note that an explicit DR may have been implicitly generated at signing time;
1247 // we don't distinguish this case.
1248 //
1249 const Requirement *SecStaticCode::designatedRequirement()
1250 {
1251 if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) {
1252 return req; // explicit in signing data
1253 } else {
1254 if (!mDesignatedReq)
1255 mDesignatedReq = defaultDesignatedRequirement();
1256 return mDesignatedReq;
1257 }
1258 }
1259
1260
1261 //
1262 // Generate the default Designated Requirement (DR) for this StaticCode.
1263 // Ignore any explicit DR it may contain.
1264 //
1265 const Requirement *SecStaticCode::defaultDesignatedRequirement()
1266 {
1267 if (flag(kSecCodeSignatureAdhoc)) {
1268 // adhoc signature: return a cdhash requirement for all architectures
1269 __block Requirement::Maker maker;
1270 Requirement::Maker::Chain chain(maker, opOr);
1271
1272 // insert cdhash requirement for all architectures
1273 chain.add();
1274 maker.cdhash(this->cdHash());
1275 handleOtherArchitectures(^(SecStaticCode *subcode) {
1276 if (CFDataRef cdhash = subcode->cdHash()) {
1277 chain.add();
1278 maker.cdhash(cdhash);
1279 }
1280 });
1281 return maker.make();
1282 } else {
1283 // full signature: Gin up full context and let DRMaker do its thing
1284 validateDirectory(); // need the cert chain
1285 Requirement::Context context(this->certificates(),
1286 this->infoDictionary(),
1287 this->entitlements(),
1288 this->identifier(),
1289 this->codeDirectory()
1290 );
1291 return DRMaker(context).make();
1292 }
1293 }
1294
1295
1296 //
1297 // Validate a SecStaticCode against the internal requirement of a particular type.
1298 //
1299 void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target,
1300 OSStatus nullError /* = errSecSuccess */)
1301 {
1302 DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError);
1303 if (const Requirement *req = internalRequirement(type))
1304 target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed);
1305 else if (nullError)
1306 MacOSError::throwMe(nullError);
1307 else
1308 /* accept it */;
1309 }
1310
1311
1312 //
1313 // Validate this StaticCode against an external Requirement
1314 //
1315 bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure)
1316 {
1317 assert(req);
1318 validateDirectory();
1319 return req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure);
1320 }
1321
1322 void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure)
1323 {
1324 if (!this->satisfiesRequirement(req, failure))
1325 MacOSError::throwMe(failure);
1326 }
1327
1328
1329 //
1330 // Retrieve one certificate from the cert chain.
1331 // Positive and negative indices can be used:
1332 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1333 // 0 1 ... -2 -1
1334 // Returns NULL if unavailable for any reason.
1335 //
1336 SecCertificateRef SecStaticCode::cert(int ix)
1337 {
1338 validateDirectory(); // need cert chain
1339 if (mCertChain) {
1340 CFIndex length = CFArrayGetCount(mCertChain);
1341 if (ix < 0)
1342 ix += length;
1343 if (ix >= 0 && ix < length)
1344 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix));
1345 }
1346 return NULL;
1347 }
1348
1349 CFArrayRef SecStaticCode::certificates()
1350 {
1351 validateDirectory(); // need cert chain
1352 return mCertChain;
1353 }
1354
1355
1356 //
1357 // Gather (mostly) API-official information about this StaticCode.
1358 //
1359 // This method lives in the twilight between the API and internal layers,
1360 // since it generates API objects (Sec*Refs) for return.
1361 //
1362 CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags)
1363 {
1364 //
1365 // Start with the pieces that we return even for unsigned code.
1366 // This makes Sec[Static]CodeRefs useful as API-level replacements
1367 // of our internal OSXCode objects.
1368 //
1369 CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1,
1370 kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get()
1371 );
1372
1373 //
1374 // If we're not signed, this is all you get
1375 //
1376 if (!this->isSigned())
1377 return dict.yield();
1378
1379 //
1380 // Add the generic attributes that we always include
1381 //
1382 CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier()));
1383 CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get()));
1384 CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format()));
1385 CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource()));
1386 CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash());
1387 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(this->codeDirectory(false)->hashType));
1388
1389 //
1390 // Deliver any Info.plist only if it looks intact
1391 //
1392 try {
1393 if (CFDictionaryRef info = this->infoDictionary())
1394 CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
1395 } catch (...) { } // don't deliver Info.plist if questionable
1396
1397 //
1398 // kSecCSSigningInformation adds information about signing certificates and chains
1399 //
1400 if (flags & kSecCSSigningInformation)
1401 try {
1402 if (CFArrayRef certs = this->certificates())
1403 CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs);
1404 if (CFDataRef sig = this->signature())
1405 CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig);
1406 if (mTrust)
1407 CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust);
1408 if (CFAbsoluteTime time = this->signingTime())
1409 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
1410 CFDictionaryAddValue(dict, kSecCodeInfoTime, date);
1411 if (CFAbsoluteTime time = this->signingTimestamp())
1412 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
1413 CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date);
1414 if (const char *teamID = this->teamID())
1415 CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID));
1416 } catch (...) { }
1417
1418 //
1419 // kSecCSRequirementInformation adds information on requirements
1420 //
1421 if (flags & kSecCSRequirementInformation)
1422 try {
1423 if (const Requirements *reqs = this->internalRequirements()) {
1424 CFDictionaryAddValue(dict, kSecCodeInfoRequirements,
1425 CFTempString(Dumper::dump(reqs)));
1426 CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs));
1427 }
1428
1429 const Requirement *dreq = this->designatedRequirement();
1430 CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle();
1431 CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef);
1432 if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit
1433 CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1434 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
1435 } else { // implicit
1436 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef);
1437 }
1438 } catch (...) { }
1439
1440 try {
1441 if (CFDataRef ent = this->component(cdEntitlementSlot)) {
1442 CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
1443 if (CFDictionaryRef entdict = this->entitlements())
1444 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
1445 }
1446 } catch (...) { }
1447
1448 //
1449 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1450 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1451 // to reliably transmit through the API wall so that code outside the Security.framework
1452 // can use it without having to play nasty tricks to get it.
1453 //
1454 if (flags & kSecCSInternalInformation)
1455 try {
1456 if (mDir)
1457 CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir);
1458 CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase()));
1459 if (CFRef<CFDictionaryRef> rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation
1460 CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict);
1461 } catch (...) { }
1462
1463
1464 //
1465 // kSecCSContentInformation adds more information about the physical layout
1466 // of the signed code. This is (only) useful for packaging or patching-oriented
1467 // applications.
1468 //
1469 if (flags & kSecCSContentInformation)
1470 if (CFRef<CFArrayRef> files = mRep->modifiedFiles())
1471 CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files);
1472
1473 return dict.yield();
1474 }
1475
1476
1477 //
1478 // Resource validation contexts.
1479 // The default context simply throws a CSError, rudely terminating the operation.
1480 //
1481 SecStaticCode::ValidationContext::~ValidationContext()
1482 { /* virtual */ }
1483
1484 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
1485 {
1486 CSError::throwMe(rc, type, value);
1487 }
1488
1489 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
1490 {
1491 if (mStatus == errSecSuccess)
1492 mStatus = rc; // record first failure for eventual error return
1493 if (type) {
1494 if (!mCollection)
1495 mCollection.take(makeCFMutableDictionary());
1496 CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type));
1497 if (!element) {
1498 element = makeCFMutableArray(0);
1499 if (!element)
1500 CFError::throwMe();
1501 CFDictionaryAddValue(mCollection, type, element);
1502 CFRelease(element);
1503 }
1504 CFArrayAppendValue(element, value);
1505 }
1506 }
1507
1508 void SecStaticCode::CollectingContext::throwMe()
1509 {
1510 assert(mStatus != errSecSuccess);
1511 throw CSError(mStatus, mCollection.retain());
1512 }
1513
1514
1515 //
1516 // Master validation driver.
1517 // This is the static validation (only) driver for the API.
1518 //
1519 // SecStaticCode exposes an a la carte menu of topical validators applying
1520 // to a given object. The static validation API pulls them together reliably,
1521 // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries)
1522 // and nested code. This function will crawl a suitable cross-section of this
1523 // validation matrix based on which options it is given, creating temporary
1524 // SecStaticCode objects on the fly to complete the task.
1525 // (The point, of course, is to do as little duplicate work as possible.)
1526 //
1527 void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req)
1528 {
1529 setValidationFlags(flags);
1530
1531 // initialize progress/cancellation state
1532 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
1533
1534 // core components: once per architecture (if any)
1535 this->staticValidateCore(flags, req);
1536 if (flags & kSecCSCheckAllArchitectures)
1537 handleOtherArchitectures(^(SecStaticCode* subcode) {
1538 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) architecture
1539 subcode->staticValidateCore(flags, req);
1540 });
1541 reportProgress();
1542
1543 // allow monitor intervention in source validation phase
1544 reportEvent(CFSTR("prepared"), NULL);
1545
1546 // resources: once for all architectures
1547 if (!(flags & kSecCSDoNotValidateResources))
1548 this->validateResources(flags);
1549
1550 // perform strict validation if desired
1551 if (flags & kSecCSStrictValidate)
1552 mRep->strictValidate(mTolerateErrors);
1553 reportProgress();
1554
1555 // allow monitor intervention
1556 if (CFRef<CFTypeRef> veto = reportEvent(CFSTR("validated"), NULL)) {
1557 if (CFGetTypeID(veto) == CFNumberGetTypeID())
1558 MacOSError::throwMe(cfNumber<OSStatus>(veto.as<CFNumberRef>()));
1559 else
1560 MacOSError::throwMe(errSecCSBadCallbackValue);
1561 }
1562 }
1563
1564 void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req)
1565 {
1566 try {
1567 this->validateNonResourceComponents(); // also validates the CodeDirectory
1568 if (!(flags & kSecCSDoNotValidateExecutable))
1569 this->validateExecutable();
1570 if (req)
1571 this->validateRequirement(req->requirement(), errSecCSReqFailed);
1572 } catch (CSError &err) {
1573 if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O
1574 if (MachO *mach = fat->architecture()) {
1575 err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName()));
1576 delete mach;
1577 }
1578 throw;
1579 } catch (const MacOSError &err) {
1580 // add architecture information if we can get it
1581 if (Universal *fat = this->diskRep()->mainExecutableImage())
1582 if (MachO *mach = fat->architecture()) {
1583 CFTempString arch(mach->architecture().displayName());
1584 delete mach;
1585 CSError::throwMe(err.error, kSecCFErrorArchitecture, arch);
1586 }
1587 throw;
1588 }
1589 }
1590
1591
1592 //
1593 // A helper that generates SecStaticCode objects for all but the primary architecture
1594 // of a fat binary and calls a block on them.
1595 // If there's only one architecture (or this is an architecture-agnostic code),
1596 // nothing happens quickly.
1597 //
1598 void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other))
1599 {
1600 if (Universal *fat = this->diskRep()->mainExecutableImage()) {
1601 Universal::Architectures architectures;
1602 fat->architectures(architectures);
1603 if (architectures.size() > 1) {
1604 DiskRep::Context ctx;
1605 size_t activeOffset = fat->archOffset();
1606 for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) {
1607 ctx.offset = fat->archOffset(*arch);
1608 if (ctx.offset > SIZE_MAX)
1609 MacOSError::throwMe(errSecCSInternalError);
1610 ctx.size = fat->lengthOfSlice((size_t)ctx.offset);
1611 if (ctx.offset != activeOffset) { // inactive architecture; check it
1612 SecPointer<SecStaticCode> subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx));
1613 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
1614 if (this->teamID() == NULL || subcode->teamID() == NULL) {
1615 if (this->teamID() != subcode->teamID())
1616 MacOSError::throwMe(errSecCSSignatureInvalid);
1617 } else if (strcmp(this->teamID(), subcode->teamID()) != 0)
1618 MacOSError::throwMe(errSecCSSignatureInvalid);
1619 handle(subcode);
1620 }
1621 }
1622 }
1623 }
1624 }
1625
1626 //
1627 // A method that takes a certificate chain (certs) and evaluates
1628 // if it is a Mac or IPhone developer cert, an app store distribution cert,
1629 // or a developer ID
1630 //
1631 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs)
1632 {
1633 static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + MACWWDRRequirement + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")";
1634 SecPointer<SecRequirement> req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true);
1635 Requirement::Context ctx(certs, NULL, NULL, "", NULL);
1636
1637 return req->requirement()->validates(ctx);
1638 }
1639
1640 } // end namespace CodeSigning
1641 } // end namespace Security