]> git.saurik.com Git - apple/libsecurity_codesigning.git/blob - lib/StaticCode.cpp
libsecurity_codesigning-55037.15.tar.gz
[apple/libsecurity_codesigning.git] / lib / StaticCode.cpp
1 /*
2 * Copyright (c) 2006-2012 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 "sigblob.h"
33 #include "resources.h"
34 #include "renum.h"
35 #include "detachedrep.h"
36 #include "csdatabase.h"
37 #include "csutilities.h"
38 #include "SecCode.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
52
53 namespace Security {
54 namespace CodeSigning {
55
56 using namespace UnixPlusPlus;
57
58
59 //
60 // Construct a SecStaticCode object given a disk representation object
61 //
62 SecStaticCode::SecStaticCode(DiskRep *rep)
63 : mRep(rep),
64 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL),
65 mDesignatedReq(NULL), mGotResourceBase(false), mEvalDetails(NULL)
66 {
67 CODESIGN_STATIC_CREATE(this, rep);
68 checkForSystemSignature();
69 }
70
71
72 //
73 // Clean up a SecStaticCode object
74 //
75 SecStaticCode::~SecStaticCode() throw()
76 try {
77 ::free(const_cast<Requirement *>(mDesignatedReq));
78 if (mResourcesValidContext)
79 delete mResourcesValidContext;
80 } catch (...) {
81 return;
82 }
83
84
85 //
86 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
87 // and falls back on comparing canonical paths if (both are) not.
88 //
89 bool SecStaticCode::equal(SecCFObject &secOther)
90 {
91 SecStaticCode *other = static_cast<SecStaticCode *>(&secOther);
92 CFDataRef mine = this->cdHash();
93 CFDataRef his = other->cdHash();
94 if (mine || his)
95 return mine && his && CFEqual(mine, his);
96 else
97 return CFEqual(this->canonicalPath(), other->canonicalPath());
98 }
99
100 CFHashCode SecStaticCode::hash()
101 {
102 if (CFDataRef h = this->cdHash())
103 return CFHash(h);
104 else
105 return CFHash(this->canonicalPath());
106 }
107
108
109 //
110 // Attach a detached signature.
111 //
112 void SecStaticCode::detachedSignature(CFDataRef sigData)
113 {
114 if (sigData) {
115 mRep = new DetachedRep(sigData, mRep->base(), "explicit detached");
116 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep);
117 } else {
118 mRep = mRep->base();
119 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL);
120 }
121 }
122
123
124 //
125 // Consult the system detached signature database to see if it contains
126 // a detached signature for this StaticCode. If it does, fetch and attach it.
127 // We do this only if the code has no signature already attached.
128 //
129 void SecStaticCode::checkForSystemSignature()
130 {
131 if (!this->isSigned())
132 try {
133 if (RefPointer<DiskRep> dsig = signatureDatabase().findCode(mRep)) {
134 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig);
135 mRep = dsig;
136 }
137 } catch (...) {
138 }
139 }
140
141
142 //
143 // Return a descriptive string identifying the source of the code signature
144 //
145 string SecStaticCode::signatureSource()
146 {
147 if (!isSigned())
148 return "unsigned";
149 if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get()))
150 return rep->source();
151 return "embedded";
152 }
153
154
155 //
156 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
157 // (if possible).
158 //
159 SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref)
160 {
161 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
162 if (SecStaticCode *scode = dynamic_cast<SecStaticCode *>(object))
163 return scode;
164 else if (SecCode *code = dynamic_cast<SecCode *>(object))
165 return code->staticCode();
166 else // neither (a SecSomethingElse)
167 MacOSError::throwMe(errSecCSInvalidObjectRef);
168 }
169
170 SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref)
171 {
172 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
173 if (dynamic_cast<SecStaticCode *>(object))
174 return NULL;
175 else if (SecCode *code = dynamic_cast<SecCode *>(object))
176 return code;
177 else // neither (a SecSomethingElse)
178 MacOSError::throwMe(errSecCSInvalidObjectRef);
179 }
180
181
182 //
183 // Void all cached validity data.
184 //
185 // We also throw out cached components, because the new signature data may have
186 // a different idea of what components should be present. We could reconcile the
187 // cached data instead, if performance seems to be impacted.
188 //
189 void SecStaticCode::resetValidity()
190 {
191 CODESIGN_EVAL_STATIC_RESET(this);
192 mValidated = false;
193 mExecutableValidated = false;
194 mResourcesValidated = false;
195 if (mResourcesValidContext) {
196 delete mResourcesValidContext;
197 mResourcesValidContext = NULL;
198 }
199 mDir = NULL;
200 mSignature = NULL;
201 for (unsigned n = 0; n < cdSlotCount; n++)
202 mCache[n] = NULL;
203 mInfoDict = NULL;
204 mEntitlements = NULL;
205 mResourceDict = NULL;
206 mDesignatedReq = NULL;
207 mGotResourceBase = false;
208 mTrust = NULL;
209 mCertChain = NULL;
210 mEvalDetails = NULL;
211 mRep->flush();
212
213 // we may just have updated the system database, so check again
214 checkForSystemSignature();
215 }
216
217
218 //
219 // Retrieve a sealed component by special slot index.
220 // If the CodeDirectory has already been validated, validate against that.
221 // Otherwise, retrieve the component without validation (but cache it). Validation
222 // will go through the cache and validate all cached components.
223 //
224 CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
225 {
226 assert(slot <= cdSlotMax);
227
228 CFRef<CFDataRef> &cache = mCache[slot];
229 if (!cache) {
230 if (CFRef<CFDataRef> data = mRep->component(slot)) {
231 if (validated()) // if the directory has been validated...
232 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good
233 CFDataGetLength(data), -slot))
234 MacOSError::throwMe(fail); // ... then bail
235 cache = data; // it's okay, cache it
236 } else { // absent, mark so
237 if (validated()) // if directory has been validated...
238 if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing
239 MacOSError::throwMe(fail); // was supposed to be there
240 cache = CFDataRef(kCFNull); // white lie
241 }
242 }
243 return (cache == CFDataRef(kCFNull)) ? NULL : cache.get();
244 }
245
246
247 //
248 // Get the CodeDirectory.
249 // Throws (if check==true) or returns NULL (check==false) if there is none.
250 // Always throws if the CodeDirectory exists but is invalid.
251 // NEVER validates against the signature.
252 //
253 const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */)
254 {
255 if (!mDir) {
256 if (mDir.take(mRep->codeDirectory())) {
257 const CodeDirectory *dir = reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
258 dir->checkIntegrity();
259 }
260 }
261 if (mDir)
262 return reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
263 if (check)
264 MacOSError::throwMe(errSecCSUnsigned);
265 return NULL;
266 }
267
268
269 //
270 // Get the hash of the CodeDirectory.
271 // Returns NULL if there is none.
272 //
273 CFDataRef SecStaticCode::cdHash()
274 {
275 if (!mCDHash) {
276 if (const CodeDirectory *cd = codeDirectory(false)) {
277 SHA1 hash;
278 hash(cd, cd->length());
279 SHA1::Digest digest;
280 hash.finish(digest);
281 mCDHash.take(makeCFData(digest, sizeof(digest)));
282 CODESIGN_STATIC_CDHASH(this, digest, sizeof(digest));
283 }
284 }
285 return mCDHash;
286 }
287
288
289 //
290 // Return the CMS signature blob; NULL if none found.
291 //
292 CFDataRef SecStaticCode::signature()
293 {
294 if (!mSignature)
295 mSignature.take(mRep->signature());
296 if (mSignature)
297 return mSignature;
298 MacOSError::throwMe(errSecCSUnsigned);
299 }
300
301
302 //
303 // Verify the signature on the CodeDirectory.
304 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
305 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
306 //
307 void SecStaticCode::validateDirectory()
308 {
309 // echo previous outcome, if any
310 if (!validated())
311 try {
312 // perform validation (or die trying)
313 CODESIGN_EVAL_STATIC_DIRECTORY(this);
314 mValidationExpired = verifySignature();
315 component(cdInfoSlot, errSecCSInfoPlistFailed); // force load of Info Dictionary (if any)
316 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
317 if (mCache[slot]) // if we already loaded that resource...
318 validateComponent(slot); // ... then check it now
319 mValidated = true; // we've done the deed...
320 mValidationResult = noErr; // ... and it was good
321 } catch (const CommonError &err) {
322 mValidated = true;
323 mValidationResult = err.osStatus();
324 throw;
325 } catch (...) {
326 secdebug("staticCode", "%p validation threw non-common exception", this);
327 mValidated = true;
328 mValidationResult = errSecCSInternalError;
329 throw;
330 }
331 assert(validated());
332 if (mValidationResult == noErr) {
333 if (mValidationExpired)
334 if ((apiFlags() & kSecCSConsiderExpiration)
335 || (codeDirectory()->flags & kSecCodeSignatureForceExpiration))
336 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED);
337 } else
338 MacOSError::throwMe(mValidationResult);
339 }
340
341
342 //
343 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
344 // Those latter components are checked by validateResources().
345 //
346 void SecStaticCode::validateNonResourceComponents()
347 {
348 this->validateDirectory();
349 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
350 switch (slot) {
351 case cdResourceDirSlot: // validated by validateResources
352 break;
353 default:
354 this->component(slot); // loads and validates
355 break;
356 }
357 }
358
359
360 //
361 // Get the (signed) signing date from the code signature.
362 // Sadly, we need to validate the signature to get the date (as a side benefit).
363 // This means that you can't get the signing time for invalidly signed code.
364 //
365 // We could run the decoder "almost to" verification to avoid this, but there seems
366 // little practical point to such a duplication of effort.
367 //
368 CFAbsoluteTime SecStaticCode::signingTime()
369 {
370 validateDirectory();
371 return mSigningTime;
372 }
373
374 CFAbsoluteTime SecStaticCode::signingTimestamp()
375 {
376 validateDirectory();
377 return mSigningTimestamp;
378 }
379
380
381 //
382 // Verify the CMS signature on the CodeDirectory.
383 // This performs the cryptographic tango. It returns if the signature is valid,
384 // or throws if it is not. As a side effect, a successful return sets up the
385 // cached certificate chain for future use.
386 // Returns true if the signature is expired (the X.509 sense), false if it's not.
387 //
388 bool SecStaticCode::verifySignature()
389 {
390 // ad-hoc signed code is considered validly signed by definition
391 if (flag(kSecCodeSignatureAdhoc)) {
392 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
393 return false;
394 }
395
396 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str());
397
398 // decode CMS and extract SecTrust for verification
399 CFRef<CMSDecoderRef> cms;
400 MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder
401 CFDataRef sig = this->signature();
402 MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig)));
403 this->codeDirectory(); // load CodeDirectory (sets mDir)
404 MacOSError::check(CMSDecoderSetDetachedContent(cms, mDir));
405 MacOSError::check(CMSDecoderFinalizeMessage(cms));
406 MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray()));
407 CFRef<CFTypeRef> policy = verificationPolicy(apiFlags());
408 CMSSignerStatus status;
409 MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, policy,
410 false, &status, &mTrust.aref(), NULL));
411 if (status != kCMSSignerValid)
412 MacOSError::throwMe(errSecCSSignatureFailed);
413
414 // internal signing time (as specified by the signer; optional)
415 mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
416 switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) {
417 case noErr:
418 case errSecSigningTimeMissing:
419 break;
420 default:
421 MacOSError::throwMe(rc);
422 }
423
424 // certified signing time (as specified by a TSA; optional)
425 mSigningTimestamp = 0;
426 switch (OSStatus rc = CMSDecoderCopySignerTimestamp(cms, 0, &mSigningTimestamp)) {
427 case noErr:
428 case errSecTimestampMissing:
429 break;
430 default:
431 MacOSError::throwMe(rc);
432 }
433
434 // set up the environment for SecTrust
435 MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors
436 MacOSError::check(SecTrustSetKeychains(mTrust, cfEmptyArray())); // no keychains
437 CSSM_APPLE_TP_ACTION_DATA actionData = {
438 CSSM_APPLE_TP_ACTION_VERSION, // version of data structure
439 CSSM_TP_ACTION_IMPLICIT_ANCHORS // action flags
440 };
441
442 for (;;) { // at most twice
443 MacOSError::check(SecTrustSetParameters(mTrust,
444 CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData))));
445
446 // evaluate trust and extract results
447 SecTrustResultType trustResult;
448 MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
449 MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails));
450 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? CFArrayGetCount(mCertChain) : 0);
451 switch (trustResult) {
452 case kSecTrustResultProceed:
453 case kSecTrustResultUnspecified:
454 break; // success
455 case kSecTrustResultDeny:
456 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject
457 case kSecTrustResultInvalid:
458 assert(false); // should never happen
459 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
460 default:
461 {
462 OSStatus result;
463 MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result));
464 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
465 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
466 if (mSigningTimestamp == 0) // no timestamp available
467 if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET))
468 && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) {
469 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
470 actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs)
471 continue; // retry validation while tolerating expiration
472 }
473 MacOSError::throwMe(result);
474 }
475 }
476 return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED;
477 }
478 }
479
480
481 //
482 // Return the TP policy used for signature verification.
483 // This may be a simple SecPolicyRef or a CFArray of policies.
484 // The caller owns the return value.
485 //
486 static SecPolicyRef makeCRLPolicy()
487 {
488 CFRef<SecPolicyRef> policy;
489 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref()));
490 CSSM_APPLE_TP_CRL_OPTIONS options;
491 memset(&options, 0, sizeof(options));
492 options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION;
493 options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT;
494 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
495 MacOSError::check(SecPolicySetValue(policy, &optData));
496 return policy.yield();
497 }
498
499 static SecPolicyRef makeOCSPPolicy()
500 {
501 CFRef<SecPolicyRef> policy;
502 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref()));
503 CSSM_APPLE_TP_OCSP_OPTIONS options;
504 memset(&options, 0, sizeof(options));
505 options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION;
506 options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT;
507 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
508 MacOSError::check(SecPolicySetValue(policy, &optData));
509 return policy.yield();
510 }
511
512 CFTypeRef SecStaticCode::verificationPolicy(SecCSFlags flags)
513 {
514 CFRef<SecPolicyRef> core;
515 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3,
516 &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref()));
517 if (flags & kSecCSEnforceRevocationChecks) {
518 CFRef<SecPolicyRef> crl = makeCRLPolicy();
519 CFRef<SecPolicyRef> ocsp = makeOCSPPolicy();
520 return makeCFArray(3, core.get(), crl.get(), ocsp.get());
521 } else {
522 return core.yield();
523 }
524 }
525
526
527 //
528 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
529 // The resource must already have been placed in the cache.
530 // This does NOT perform basic validation.
531 //
532 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
533 {
534 assert(slot <= cdSlotMax);
535 CFDataRef data = mCache[slot];
536 assert(data); // must be cached
537 if (data == CFDataRef(kCFNull)) {
538 if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there...
539 MacOSError::throwMe(fail); // ... and is missing
540 } else {
541 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot))
542 MacOSError::throwMe(fail);
543 }
544 }
545
546
547 //
548 // Perform static validation of the main executable.
549 // This reads the main executable from disk and validates it against the
550 // CodeDirectory code slot array.
551 // Note that this is NOT an in-memory validation, and is thus potentially
552 // subject to timing attacks.
553 //
554 void SecStaticCode::validateExecutable()
555 {
556 if (!validatedExecutable()) {
557 try {
558 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this,
559 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots);
560 const CodeDirectory *cd = this->codeDirectory();
561 if (!cd)
562 MacOSError::throwMe(errSecCSUnsigned);
563 AutoFileDesc fd(mainExecutablePath(), O_RDONLY);
564 fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass)
565 if (Universal *fat = mRep->mainExecutableImage())
566 fd.seek(fat->archOffset());
567 size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0;
568 size_t remaining = cd->codeLimit;
569 for (size_t slot = 0; slot < cd->nCodeSlots; ++slot) {
570 size_t size = min(remaining, pageSize);
571 if (!cd->validateSlot(fd, size, slot)) {
572 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, slot);
573 MacOSError::throwMe(errSecCSSignatureFailed);
574 }
575 remaining -= size;
576 }
577 mExecutableValidated = true;
578 mExecutableValidResult = noErr;
579 } catch (const CommonError &err) {
580 mExecutableValidated = true;
581 mExecutableValidResult = err.osStatus();
582 throw;
583 } catch (...) {
584 secdebug("staticCode", "%p executable validation threw non-common exception", this);
585 mExecutableValidated = true;
586 mExecutableValidResult = errSecCSInternalError;
587 throw;
588 }
589 }
590 assert(validatedExecutable());
591 if (mExecutableValidResult != noErr)
592 MacOSError::throwMe(mExecutableValidResult);
593 }
594
595
596 //
597 // Perform static validation of sealed resources.
598 //
599 // This performs a whole-code static resource scan and effectively
600 // computes a concordance between what's on disk and what's in the ResourceDirectory.
601 // Any unsanctioned difference causes an error.
602 //
603 void SecStaticCode::validateResources()
604 {
605 if (!validatedResources()) {
606 try {
607 // sanity first
608 CFDictionaryRef sealedResources = resourceDictionary();
609 if (this->resourceBase()) // disk has resources
610 if (sealedResources)
611 /* go to work below */;
612 else
613 MacOSError::throwMe(errSecCSResourcesNotFound);
614 else // disk has no resources
615 if (sealedResources)
616 MacOSError::throwMe(errSecCSResourcesNotFound);
617 else
618 return; // no resources, not sealed - fine (no work)
619
620 // found resources, and they are sealed
621 CFDictionaryRef rules = cfget<CFDictionaryRef>(sealedResources, "rules");
622 CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files");
623 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this,
624 (char*)this->mainExecutablePath().c_str(), int(CFDictionaryGetCount(files)));
625
626 // make a shallow copy of the ResourceDirectory so we can "check off" what we find
627 CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files);
628
629 // scan through the resources on disk, checking each against the resourceDirectory
630 mResourcesValidContext = new CollectingContext(*this); // collect all failures in here
631 ResourceBuilder resources(cfString(this->resourceBase()), rules, codeDirectory()->hashType);
632 mRep->adjustResources(resources);
633 string path;
634 ResourceBuilder::Rule *rule;
635
636 while (resources.next(path, rule)) {
637 validateResource(path, *mResourcesValidContext);
638 CFDictionaryRemoveValue(resourceMap, CFTempString(path));
639 }
640
641 if (CFDictionaryGetCount(resourceMap) > 0) {
642 secdebug("staticCode", "%p sealed resource(s) not found in code", this);
643 CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext);
644 }
645
646 // now check for any errors found in the reporting context
647 mResourcesValidated = true;
648 if (mResourcesValidContext->osStatus() != noErr)
649 mResourcesValidContext->throwMe();
650
651 } catch (const CommonError &err) {
652 mResourcesValidated = true;
653 mResourcesValidResult = err.osStatus();
654 throw;
655 } catch (...) {
656 secdebug("staticCode", "%p executable validation threw non-common exception", this);
657 mResourcesValidated = true;
658 mResourcesValidResult = errSecCSInternalError;
659 throw;
660 }
661 }
662 assert(validatedResources());
663 if (mResourcesValidResult)
664 MacOSError::throwMe(mResourcesValidResult);
665 if (mResourcesValidContext->osStatus() != noErr)
666 mResourcesValidContext->throwMe();
667 }
668
669
670 void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context)
671 {
672 CollectingContext *ctx = static_cast<CollectingContext *>(context);
673 ResourceSeal seal(value);
674 if (!seal.optional()) {
675 if (key && CFGetTypeID(key) == CFStringGetTypeID()) {
676 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing,
677 CFTempURL(CFStringRef(key), false, ctx->code.resourceBase()));
678 } else {
679 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key);
680 }
681 }
682 }
683
684
685 //
686 // Load, validate, cache, and return CFDictionary forms of sealed resources.
687 //
688 CFDictionaryRef SecStaticCode::infoDictionary()
689 {
690 if (!mInfoDict) {
691 mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed));
692 secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get());
693 }
694 return mInfoDict;
695 }
696
697 CFDictionaryRef SecStaticCode::entitlements()
698 {
699 if (!mEntitlements) {
700 validateDirectory();
701 if (CFDataRef entitlementData = component(cdEntitlementSlot)) {
702 validateComponent(cdEntitlementSlot);
703 const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData));
704 if (blob->validateBlob()) {
705 mEntitlements.take(blob->entitlements());
706 secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get());
707 }
708 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
709 }
710 }
711 return mEntitlements;
712 }
713
714 CFDictionaryRef SecStaticCode::resourceDictionary()
715 {
716 if (mResourceDict) // cached
717 return mResourceDict;
718 if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, errSecCSSignatureFailed))
719 if (cfscan(dict, "{rules=%Dn,files=%Dn}")) {
720 secdebug("staticCode", "%p loaded ResourceDict %p",
721 this, mResourceDict.get());
722 return mResourceDict = dict;
723 }
724 // bad format
725 return NULL;
726 }
727
728
729 //
730 // Load and cache the resource directory base.
731 // Note that the base is optional for each DiskRep.
732 //
733 CFURLRef SecStaticCode::resourceBase()
734 {
735 if (!mGotResourceBase) {
736 string base = mRep->resourcesRootPath();
737 if (!base.empty())
738 mResourceBase.take(makeCFURL(base, true));
739 mGotResourceBase = true;
740 }
741 return mResourceBase;
742 }
743
744
745 //
746 // Load a component, validate it, convert it to a CFDictionary, and return that.
747 // This will force load and validation, which means that it will perform basic
748 // validation if it hasn't been done yet.
749 //
750 CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
751 {
752 validateDirectory();
753 if (CFDataRef infoData = component(slot, fail)) {
754 validateComponent(slot, fail);
755 if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData))
756 return dict;
757 else
758 MacOSError::throwMe(errSecCSBadDictionaryFormat);
759 }
760 return NULL;
761 }
762
763
764 //
765 // Load, validate, and return a sealed resource.
766 // The resource data (loaded in to memory as a blob) is returned and becomes
767 // the responsibility of the caller; it is NOT cached by SecStaticCode.
768 //
769 // A resource that is not sealed will not be returned, and an error will be thrown.
770 // A missing resource will cause an error unless it's marked optional in the Directory.
771 // Under no circumstances will a corrupt resource be returned.
772 // NULL will only be returned for a resource that is neither sealed nor present
773 // (or that is sealed, absent, and marked optional).
774 // If the ResourceDictionary itself is not sealed, this function will always fail.
775 //
776 // There is currently no interface for partial retrieval of the resource data.
777 // (Since the ResourceDirectory does not currently support segmentation, all the
778 // data would have to be read anyway, but it could be read into a reusable buffer.)
779 //
780 CFDataRef SecStaticCode::resource(string path, ValidationContext &ctx)
781 {
782 if (CFDictionaryRef rdict = resourceDictionary()) {
783 if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) {
784 ResourceSeal seal = file;
785 if (!resourceBase()) // no resources in DiskRep
786 MacOSError::throwMe(errSecCSResourcesNotFound);
787 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
788 if (CFRef<CFDataRef> data = cfLoadFile(fullpath)) {
789 MakeHash<CodeDirectory> hasher(this->codeDirectory());
790 hasher->update(CFDataGetBytePtr(data), CFDataGetLength(data));
791 if (hasher->verify(seal.hash()))
792 return data.yield(); // good
793 else
794 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
795 } else {
796 if (!seal.optional())
797 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
798 else
799 return NULL; // validly missing
800 }
801 } else
802 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
803 return NULL;
804 } else
805 MacOSError::throwMe(errSecCSResourcesNotSealed);
806 }
807
808 CFDataRef SecStaticCode::resource(string path)
809 {
810 ValidationContext ctx;
811 return resource(path, ctx);
812 }
813
814
815 void SecStaticCode::validateResource(string path, ValidationContext &ctx)
816 {
817 if (CFDictionaryRef rdict = resourceDictionary()) {
818 if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) {
819 ResourceSeal seal = file;
820 if (!resourceBase()) // no resources in DiskRep
821 MacOSError::throwMe(errSecCSResourcesNotFound);
822 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
823 AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional filee
824 if (fd) {
825 MakeHash<CodeDirectory> hasher(this->codeDirectory());
826 hashFileData(fd, hasher.get());
827 if (hasher->verify(seal.hash()))
828 return; // verify good
829 else
830 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
831 } else {
832 if (!seal.optional())
833 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
834 else
835 return; // validly missing
836 }
837 } else
838 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
839 } else
840 MacOSError::throwMe(errSecCSResourcesNotSealed);
841 }
842
843
844 //
845 // Test a CodeDirectory flag.
846 // Returns false if there is no CodeDirectory.
847 // May throw if the CodeDirectory is present but somehow invalid.
848 //
849 bool SecStaticCode::flag(uint32_t tested)
850 {
851 if (const CodeDirectory *cd = this->codeDirectory(false))
852 return cd->flags & tested;
853 else
854 return false;
855 }
856
857
858 //
859 // Retrieve the full SuperBlob containing all internal requirements.
860 //
861 const Requirements *SecStaticCode::internalRequirements()
862 {
863 if (CFDataRef req = component(cdRequirementsSlot))
864 return (const Requirements *)CFDataGetBytePtr(req);
865 else
866 return NULL;
867 }
868
869
870 //
871 // Retrieve a particular internal requirement by type.
872 //
873 const Requirement *SecStaticCode::internalRequirement(SecRequirementType type)
874 {
875 if (const Requirements *reqs = internalRequirements())
876 return reqs->find<Requirement>(type);
877 else
878 return NULL;
879 }
880
881
882 //
883 // Return the Designated Requirement (DR). This can be either explicit in the
884 // Internal Requirements component, or implicitly generated on demand here.
885 // Note that an explicit DR may have been implicitly generated at signing time;
886 // we don't distinguish this case.
887 //
888 const Requirement *SecStaticCode::designatedRequirement()
889 {
890 if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) {
891 return req; // explicit in signing data
892 } else {
893 if (!mDesignatedReq)
894 mDesignatedReq = defaultDesignatedRequirement();
895 return mDesignatedReq;
896 }
897 }
898
899
900 //
901 // Generate the default Designated Requirement (DR) for this StaticCode.
902 // Ignore any explicit DR it may contain.
903 //
904 const Requirement *SecStaticCode::defaultDesignatedRequirement()
905 {
906 if (flag(kSecCodeSignatureAdhoc)) {
907 // adhoc signature: return a plain cdhash requirement
908 Requirement::Maker maker;
909 SHA1 hash;
910 hash(codeDirectory(), codeDirectory()->length());
911 SHA1::Digest digest;
912 hash.finish(digest);
913 maker.cdhash(digest);
914 return maker.make();
915 } else {
916 // full signature: Gin up full context and let DRMaker do its thing
917 validateDirectory(); // need the cert chain
918 Requirement::Context context(this->certificates(),
919 this->infoDictionary(),
920 this->entitlements(),
921 this->identifier(),
922 this->codeDirectory()
923 );
924 return DRMaker(context).make();
925 }
926 }
927
928
929 //
930 // Validate a SecStaticCode against the internal requirement of a particular type.
931 //
932 void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target,
933 OSStatus nullError /* = noErr */)
934 {
935 DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError);
936 if (const Requirement *req = internalRequirement(type))
937 target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed);
938 else if (nullError)
939 MacOSError::throwMe(nullError);
940 else
941 /* accept it */;
942 }
943
944
945 //
946 // Validate this StaticCode against an external Requirement
947 //
948 bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure)
949 {
950 assert(req);
951 validateDirectory();
952 return req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure);
953 }
954
955 void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure)
956 {
957 if (!this->satisfiesRequirement(req, failure))
958 MacOSError::throwMe(failure);
959 }
960
961
962 //
963 // Retrieve one certificate from the cert chain.
964 // Positive and negative indices can be used:
965 // [ leaf, intermed-1, ..., intermed-n, anchor ]
966 // 0 1 ... -2 -1
967 // Returns NULL if unavailable for any reason.
968 //
969 SecCertificateRef SecStaticCode::cert(int ix)
970 {
971 validateDirectory(); // need cert chain
972 if (mCertChain) {
973 CFIndex length = CFArrayGetCount(mCertChain);
974 if (ix < 0)
975 ix += length;
976 if (ix >= 0 && ix < length)
977 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix));
978 }
979 return NULL;
980 }
981
982 CFArrayRef SecStaticCode::certificates()
983 {
984 validateDirectory(); // need cert chain
985 return mCertChain;
986 }
987
988
989 //
990 // Gather (mostly) API-official information about this StaticCode.
991 //
992 // This method lives in the twilight between the API and internal layers,
993 // since it generates API objects (Sec*Refs) for return.
994 //
995 CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags)
996 {
997 //
998 // Start with the pieces that we return even for unsigned code.
999 // This makes Sec[Static]CodeRefs useful as API-level replacements
1000 // of our internal OSXCode objects.
1001 //
1002 CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1,
1003 kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get()
1004 );
1005
1006 //
1007 // If we're not signed, this is all you get
1008 //
1009 if (!this->isSigned())
1010 return dict.yield();
1011
1012 //
1013 // Add the generic attributes that we always include
1014 //
1015 CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier()));
1016 CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format()));
1017 CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource()));
1018 CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash());
1019 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(this->codeDirectory(false)->hashType));
1020
1021 //
1022 // Deliver any Info.plist only if it looks intact
1023 //
1024 try {
1025 if (CFDictionaryRef info = this->infoDictionary())
1026 CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
1027 } catch (...) { } // don't deliver Info.plist if questionable
1028
1029 //
1030 // kSecCSSigningInformation adds information about signing certificates and chains
1031 //
1032 if (flags & kSecCSSigningInformation) {
1033 if (CFArrayRef certs = this->certificates())
1034 CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs);
1035 if (CFDataRef sig = this->signature())
1036 CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig);
1037 if (mTrust)
1038 CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust);
1039 if (CFAbsoluteTime time = this->signingTime())
1040 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
1041 CFDictionaryAddValue(dict, kSecCodeInfoTime, date);
1042 if (CFAbsoluteTime time = this->signingTimestamp())
1043 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
1044 CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date);
1045 }
1046
1047 //
1048 // kSecCSRequirementInformation adds information on requirements
1049 //
1050 if (flags & kSecCSRequirementInformation) {
1051 if (const Requirements *reqs = this->internalRequirements()) {
1052 CFDictionaryAddValue(dict, kSecCodeInfoRequirements,
1053 CFTempString(Dumper::dump(reqs)));
1054 CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs));
1055 }
1056
1057 const Requirement *dreq = this->designatedRequirement();
1058 CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle();
1059 CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef);
1060 if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit
1061 CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1062 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
1063 } else { // implicit
1064 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef);
1065 }
1066
1067 if (CFDataRef ent = this->component(cdEntitlementSlot)) {
1068 CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
1069 if (CFDictionaryRef entdict = this->entitlements())
1070 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
1071 }
1072 }
1073
1074 //
1075 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1076 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1077 // to reliably transmit through the API wall so that code outside the Security.framework
1078 // can use it without having to play nasty tricks to get it.
1079 //
1080 if (flags & kSecCSInternalInformation) {
1081 if (mDir)
1082 CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir);
1083 CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase()));
1084 if (CFDictionaryRef resources = resourceDictionary())
1085 CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, resources);
1086 }
1087
1088
1089 //
1090 // kSecCSContentInformation adds more information about the physical layout
1091 // of the signed code. This is (only) useful for packaging or patching-oriented
1092 // applications.
1093 //
1094 if (flags & kSecCSContentInformation)
1095 if (CFRef<CFArrayRef> files = mRep->modifiedFiles())
1096 CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files);
1097
1098 return dict.yield();
1099 }
1100
1101
1102 //
1103 // Resource validation contexts.
1104 // The default context simply throws a CSError, rudely terminating the operation.
1105 //
1106 SecStaticCode::ValidationContext::~ValidationContext()
1107 { /* virtual */ }
1108
1109 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
1110 {
1111 CSError::throwMe(rc, type, value);
1112 }
1113
1114 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
1115 {
1116 if (mStatus == noErr)
1117 mStatus = rc; // record first failure for eventual error return
1118 if (type) {
1119 if (!mCollection)
1120 mCollection.take(makeCFMutableDictionary());
1121 CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type));
1122 if (!element) {
1123 element = makeCFMutableArray(0);
1124 if (!element)
1125 CFError::throwMe();
1126 CFDictionaryAddValue(mCollection, type, element);
1127 CFRelease(element);
1128 }
1129 CFArrayAppendValue(element, value);
1130 }
1131 }
1132
1133 void SecStaticCode::CollectingContext::throwMe()
1134 {
1135 assert(mStatus != noErr);
1136 throw CSError(mStatus, mCollection.retain());
1137 }
1138
1139
1140 //
1141 // SecStaticCode::AllArchitectures produces SecStaticCode objects separately
1142 // for each architecture represented by a base object.
1143 //
1144 // Performance note: This is a simple, straight-forward implementation that
1145 // does not heroically try to share resources between the code objects produced.
1146 // In practice, this means we'll re-open files and re-read resource files.
1147 // In exchange, we enter all the code paths in the normal way, and do not have
1148 // special sharing paths to worry about.
1149 // If a performance tool brings you here because you have *proof* of a performance
1150 // problem, consider digging up MachO and Universal (for sharing file descriptors),
1151 // and SecStaticCode (for sharing resource iterators). That ought to cover most of
1152 // the big chunks. If you're just offended by the simplicity of this implementation,
1153 // go play somewhere else.
1154 //
1155 SecStaticCode::AllArchitectures::AllArchitectures(SecStaticCode *code)
1156 : mBase(code)
1157 {
1158 if (Universal *fat = code->diskRep()->mainExecutableImage()) {
1159 fat->architectures(mArchitectures);
1160 mCurrent = mArchitectures.begin();
1161 mState = fatBinary;
1162 } else {
1163 mState = firstNonFat;
1164 }
1165 }
1166
1167 SecStaticCode *SecStaticCode::AllArchitectures::operator () ()
1168 {
1169 switch (mState) {
1170 case firstNonFat:
1171 mState = atEnd;
1172 return mBase;
1173 case fatBinary:
1174 {
1175 if (mCurrent == mArchitectures.end())
1176 return NULL;
1177 Architecture arch = *mCurrent++;
1178 if (arch == mBase->diskRep()->mainExecutableImage()->bestNativeArch()) {
1179 return mBase;
1180 } else {
1181 DiskRep::Context ctx;
1182 ctx.arch = arch;
1183 return new SecStaticCode(DiskRep::bestGuess(mBase->mainExecutablePath(), &ctx));
1184 }
1185 }
1186 default:
1187 return NULL;
1188 }
1189 }
1190
1191
1192 } // end namespace CodeSigning
1193 } // end namespace Security