/*
- * Copyright (c) 2006-2007 Apple Inc. All Rights Reserved.
+ * Copyright (c) 2006-2012 Apple Inc. All Rights Reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
#include "StaticCode.h"
#include "Code.h"
#include "reqmaker.h"
+#include "drmaker.h"
#include "reqdumper.h"
#include "sigblob.h"
#include "resources.h"
#include "renum.h"
+#include "detachedrep.h"
+#include "csdatabase.h"
#include "csutilities.h"
+#include "SecCode.h"
#include <CoreFoundation/CFURLAccess.h>
#include <Security/SecPolicyPriv.h>
#include <Security/SecTrustPriv.h>
#include <Security/SecCmsContentInfo.h>
#include <Security/SecCmsSignerInfo.h>
#include <Security/SecCmsSignedData.h>
+#include <Security/cssmapplePriv.h>
#include <security_utilities/unix++.h>
-#include <security_codesigning/cfmunge.h>
+#include <security_utilities/cfmunge.h>
#include <Security/CMSDecoder.h>
using namespace UnixPlusPlus;
-//
-// We use a DetachedRep to interpose (filter) the genuine DiskRep representing
-// the code on disk, *if* a detached signature was set on this object. In this
-// situation, mRep will point to a (2 element) chain of DiskReps.
-//
-// This is a neat way of dealing with the (unusual) detached-signature case
-// without disturbing things unduly. Consider DetachedDiskRep to be closely
-// married to SecStaticCode; it's unlikely to work right if you use it elsewhere.
-//
-class DetachedRep : public DiskRep {
-public:
- DetachedRep(CFDataRef sig, DiskRep *orig);
-
- const RefPointer<DiskRep> original; // underlying representation
-
- DiskRep *base() { return original; }
- CFDataRef component(CodeDirectory::SpecialSlot slot);
- std::string mainExecutablePath() { return original->mainExecutablePath(); }
- CFURLRef canonicalPath() { return original->canonicalPath(); }
- std::string recommendedIdentifier() { return original->recommendedIdentifier(); }
- std::string resourcesRootPath() { return original->resourcesRootPath(); }
- CFDictionaryRef defaultResourceRules() { return original->defaultResourceRules(); }
- Universal *mainExecutableImage() { return original->mainExecutableImage(); }
- size_t signingBase() { return original->signingBase(); }
- size_t signingLimit() { return original->signingLimit(); }
- std::string format() { return original->format(); }
- FileDesc &fd() { return original->fd(); }
- void flush() { return original->flush(); }
-
-private:
- CFCopyRef<CFDataRef> mSignature;
- const EmbeddedSignatureBlob *mArch; // current architecture; points into mSignature
- const EmbeddedSignatureBlob *mGlobal; // shared elements; points into mSignature
-};
-
-
//
// Construct a SecStaticCode object given a disk representation object
//
SecStaticCode::SecStaticCode(DiskRep *rep)
: mRep(rep),
- mValidated(false), mExecutableValidated(false),
+ mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL),
mDesignatedReq(NULL), mGotResourceBase(false), mEvalDetails(NULL)
{
+ CODESIGN_STATIC_CREATE(this, rep);
+ checkForSystemSignature();
}
// Clean up a SecStaticCode object
//
SecStaticCode::~SecStaticCode() throw()
-{
+try {
::free(const_cast<Requirement *>(mDesignatedReq));
+ if (mResourcesValidContext)
+ delete mResourcesValidContext;
+} catch (...) {
+ return;
+}
+
+
+//
+// CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
+// and falls back on comparing canonical paths if (both are) not.
+//
+bool SecStaticCode::equal(SecCFObject &secOther)
+{
+ SecStaticCode *other = static_cast<SecStaticCode *>(&secOther);
+ CFDataRef mine = this->cdHash();
+ CFDataRef his = other->cdHash();
+ if (mine || his)
+ return mine && his && CFEqual(mine, his);
+ else
+ return CFEqual(this->canonicalPath(), other->canonicalPath());
+}
+
+CFHashCode SecStaticCode::hash()
+{
+ if (CFDataRef h = this->cdHash())
+ return CFHash(h);
+ else
+ return CFHash(this->canonicalPath());
}
//
void SecStaticCode::detachedSignature(CFDataRef sigData)
{
- if (sigData)
- mRep = new DetachedRep(sigData, mRep->base());
- else
+ if (sigData) {
+ mRep = new DetachedRep(sigData, mRep->base(), "explicit detached");
+ CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep);
+ } else {
mRep = mRep->base();
+ CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL);
+ }
+}
+
+
+//
+// Consult the system detached signature database to see if it contains
+// a detached signature for this StaticCode. If it does, fetch and attach it.
+// We do this only if the code has no signature already attached.
+//
+void SecStaticCode::checkForSystemSignature()
+{
+ if (!this->isSigned())
+ try {
+ if (RefPointer<DiskRep> dsig = signatureDatabase().findCode(mRep)) {
+ CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig);
+ mRep = dsig;
+ }
+ } catch (...) {
+ }
+}
+
+
+//
+// Return a descriptive string identifying the source of the code signature
+//
+string SecStaticCode::signatureSource()
+{
+ if (!isSigned())
+ return "unsigned";
+ if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get()))
+ return rep->source();
+ return "embedded";
}
//
void SecStaticCode::resetValidity()
{
- secdebug("staticCode", "%p resetting validity status", this);
+ CODESIGN_EVAL_STATIC_RESET(this);
mValidated = false;
mExecutableValidated = false;
+ mResourcesValidated = false;
+ if (mResourcesValidContext) {
+ delete mResourcesValidContext;
+ mResourcesValidContext = NULL;
+ }
mDir = NULL;
mSignature = NULL;
for (unsigned n = 0; n < cdSlotCount; n++)
mEntitlements = NULL;
mResourceDict = NULL;
mDesignatedReq = NULL;
+ mGotResourceBase = false;
mTrust = NULL;
mCertChain = NULL;
mEvalDetails = NULL;
mRep->flush();
+
+ // we may just have updated the system database, so check again
+ checkForSystemSignature();
}
// Otherwise, retrieve the component without validation (but cache it). Validation
// will go through the cache and validate all cached components.
//
-CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot)
+CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
{
assert(slot <= cdSlotMax);
if (validated()) // if the directory has been validated...
if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good
CFDataGetLength(data), -slot))
- MacOSError::throwMe(errSecCSSignatureFailed); // ... then bail
+ MacOSError::throwMe(fail); // ... then bail
cache = data; // it's okay, cache it
} else { // absent, mark so
if (validated()) // if directory has been validated...
if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing
- MacOSError::throwMe(errSecCSSignatureFailed); // was supposed to be there
+ MacOSError::throwMe(fail); // was supposed to be there
cache = CFDataRef(kCFNull); // white lie
}
}
if (!mDir) {
if (mDir.take(mRep->codeDirectory())) {
const CodeDirectory *dir = reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
- dir->checkVersion();
+ dir->checkIntegrity();
}
}
if (mDir)
}
+//
+// Get the hash of the CodeDirectory.
+// Returns NULL if there is none.
+//
+CFDataRef SecStaticCode::cdHash()
+{
+ if (!mCDHash) {
+ if (const CodeDirectory *cd = codeDirectory(false)) {
+ SHA1 hash;
+ hash(cd, cd->length());
+ SHA1::Digest digest;
+ hash.finish(digest);
+ mCDHash.take(makeCFData(digest, sizeof(digest)));
+ CODESIGN_STATIC_CDHASH(this, digest, sizeof(digest));
+ }
+ }
+ return mCDHash;
+}
+
+
//
// Return the CMS signature blob; NULL if none found.
//
if (!validated())
try {
// perform validation (or die trying)
- secdebug("staticCode", "%p validating directory", this);
+ CODESIGN_EVAL_STATIC_DIRECTORY(this);
mValidationExpired = verifySignature();
- component(cdInfoSlot); // force load of Info Dictionary (if any)
- for (CodeDirectory::SpecialSlot slot = codeDirectory()->nSpecialSlots;
- slot >= 1; --slot)
+ component(cdInfoSlot, errSecCSInfoPlistFailed); // force load of Info Dictionary (if any)
+ for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
if (mCache[slot]) // if we already loaded that resource...
validateComponent(slot); // ... then check it now
mValidated = true; // we've done the deed...
}
+//
+// Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
+// Those latter components are checked by validateResources().
+//
+void SecStaticCode::validateNonResourceComponents()
+{
+ this->validateDirectory();
+ for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
+ switch (slot) {
+ case cdResourceDirSlot: // validated by validateResources
+ break;
+ default:
+ this->component(slot); // loads and validates
+ break;
+ }
+}
+
+
//
// Get the (signed) signing date from the code signature.
// Sadly, we need to validate the signature to get the date (as a side benefit).
return mSigningTime;
}
+CFAbsoluteTime SecStaticCode::signingTimestamp()
+{
+ validateDirectory();
+ return mSigningTimestamp;
+}
+
//
// Verify the CMS signature on the CodeDirectory.
// This performs the cryptographic tango. It returns if the signature is valid,
// or throws if it is not. As a side effect, a successful return sets up the
// cached certificate chain for future use.
+// Returns true if the signature is expired (the X.509 sense), false if it's not.
//
bool SecStaticCode::verifySignature()
{
// ad-hoc signed code is considered validly signed by definition
if (flag(kSecCodeSignatureAdhoc)) {
- secdebug("staticCode", "%p considered verified since it is ad-hoc", this);
+ CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
return false;
}
+
+ DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str());
// decode CMS and extract SecTrust for verification
- secdebug("staticCode", "%p verifying signature", this);
CFRef<CMSDecoderRef> cms;
MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder
CFDataRef sig = this->signature();
MacOSError::check(CMSDecoderSetDetachedContent(cms, mDir));
MacOSError::check(CMSDecoderFinalizeMessage(cms));
MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray()));
+ CFRef<CFTypeRef> policy = verificationPolicy(apiFlags());
CMSSignerStatus status;
- MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, verificationPolicy(),
+ MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, policy,
false, &status, &mTrust.aref(), NULL));
if (status != kCMSSignerValid)
MacOSError::throwMe(errSecCSSignatureFailed);
- // get signing date (we've got the decoder handle right here)
- mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
- SecCmsMessageRef cmsg;
- MacOSError::check(CMSDecoderGetCmsMessage(cms, &cmsg));
- SecCmsSignedDataRef signedData = NULL;
- int numContentInfos = SecCmsMessageContentLevelCount(cmsg);
- for(int dex = 0; !signedData && dex < numContentInfos; dex++) {
- SecCmsContentInfoRef ci = SecCmsMessageContentLevel(cmsg, dex);
- SECOidTag tag = SecCmsContentInfoGetContentTypeTag(ci);
- switch(tag) {
- case SEC_OID_PKCS7_SIGNED_DATA:
- if (SecCmsSignedDataRef signedData = SecCmsSignedDataRef(SecCmsContentInfoGetContent(ci)))
- if (SecCmsSignerInfoRef signerInfo = SecCmsSignedDataGetSignerInfo(signedData, 0))
- SecCmsSignerInfoGetSigningTime(signerInfo, &mSigningTime);
- break;
- default:
- break;
- }
- }
+ // internal signing time (as specified by the signer; optional)
+ mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
+ switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) {
+ case noErr:
+ case errSecSigningTimeMissing:
+ break;
+ default:
+ MacOSError::throwMe(rc);
+ }
+ // certified signing time (as specified by a TSA; optional)
+ mSigningTimestamp = 0;
+ switch (OSStatus rc = CMSDecoderCopySignerTimestamp(cms, 0, &mSigningTimestamp)) {
+ case noErr:
+ case errSecTimestampMissing:
+ break;
+ default:
+ MacOSError::throwMe(rc);
+ }
+
// set up the environment for SecTrust
MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors
+ MacOSError::check(SecTrustSetKeychains(mTrust, cfEmptyArray())); // no keychains
CSSM_APPLE_TP_ACTION_DATA actionData = {
CSSM_APPLE_TP_ACTION_VERSION, // version of data structure
CSSM_TP_ACTION_IMPLICIT_ANCHORS // action flags
};
- for (;;) {
+ for (;;) { // at most twice
MacOSError::check(SecTrustSetParameters(mTrust,
CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData))));
SecTrustResultType trustResult;
MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails));
- secdebug("staticCode", "%p verification result=%d chain=%ld",
- this, trustResult, mCertChain ? CFArrayGetCount(mCertChain) : -1);
+ CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? CFArrayGetCount(mCertChain) : 0);
switch (trustResult) {
case kSecTrustResultProceed:
- case kSecTrustResultConfirm:
case kSecTrustResultUnspecified:
break; // success
case kSecTrustResultDeny:
case kSecTrustResultInvalid:
assert(false); // should never happen
MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
- case kSecTrustResultRecoverableTrustFailure:
- case kSecTrustResultFatalTrustFailure:
- case kSecTrustResultOtherError:
+ default:
{
OSStatus result;
MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result));
- if (result == CSSMERR_TP_CERT_EXPIRED && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) {
- secdebug("staticCode", "expired certificate(s); retrying validation");
- actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED;
- continue; // retry validation
- }
+ // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
+ // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
+ if (mSigningTimestamp == 0) // no timestamp available
+ if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET))
+ && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) {
+ CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
+ actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs)
+ continue; // retry validation while tolerating expiration
+ }
MacOSError::throwMe(result);
}
}
//
// Return the TP policy used for signature verification.
-// This policy object is cached and reused.
+// This may be a simple SecPolicyRef or a CFArray of policies.
+// The caller owns the return value.
//
-SecPolicyRef SecStaticCode::verificationPolicy()
+static SecPolicyRef makeCRLPolicy()
{
- if (!mPolicy)
- MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3,
- &CSSMOID_APPLE_TP_CODE_SIGNING, &mPolicy.aref()));
- return mPolicy;
+ CFRef<SecPolicyRef> policy;
+ MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref()));
+ CSSM_APPLE_TP_CRL_OPTIONS options;
+ memset(&options, 0, sizeof(options));
+ options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION;
+ options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT;
+ CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
+ MacOSError::check(SecPolicySetValue(policy, &optData));
+ return policy.yield();
+}
+
+static SecPolicyRef makeOCSPPolicy()
+{
+ CFRef<SecPolicyRef> policy;
+ MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref()));
+ CSSM_APPLE_TP_OCSP_OPTIONS options;
+ memset(&options, 0, sizeof(options));
+ options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION;
+ options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT;
+ CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
+ MacOSError::check(SecPolicySetValue(policy, &optData));
+ return policy.yield();
+}
+
+CFTypeRef SecStaticCode::verificationPolicy(SecCSFlags flags)
+{
+ CFRef<SecPolicyRef> core;
+ MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3,
+ &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref()));
+ if (flags & kSecCSEnforceRevocationChecks) {
+ CFRef<SecPolicyRef> crl = makeCRLPolicy();
+ CFRef<SecPolicyRef> ocsp = makeOCSPPolicy();
+ return makeCFArray(3, core.get(), crl.get(), ocsp.get());
+ } else {
+ return core.yield();
+ }
}
// The resource must already have been placed in the cache.
// This does NOT perform basic validation.
//
-void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot)
+void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
{
+ assert(slot <= cdSlotMax);
CFDataRef data = mCache[slot];
assert(data); // must be cached
if (data == CFDataRef(kCFNull)) {
if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there...
- MacOSError::throwMe(errSecCSSignatureFailed); // ... and is missing
+ MacOSError::throwMe(fail); // ... and is missing
} else {
if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot))
- MacOSError::throwMe(errSecCSSignatureFailed);
+ MacOSError::throwMe(fail);
}
}
//
void SecStaticCode::validateExecutable()
{
- secdebug("staticCode", "%p performing static main exec validate of %s",
- this, mainExecutablePath().c_str());
- const CodeDirectory *cd = this->codeDirectory();
- if (!cd)
- MacOSError::throwMe(errSecCSUnsigned);
- AutoFileDesc fd(mainExecutablePath(), O_RDONLY);
- fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass)
- if (Universal *fat = mRep->mainExecutableImage())
- fd.seek(fat->archOffset());
- size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0;
- size_t remaining = cd->codeLimit;
- for (size_t slot = 0; slot < cd->nCodeSlots; ++slot) {
- size_t size = min(remaining, pageSize);
- if (!cd->validateSlot(fd, size, slot)) {
- secdebug("staticCode", "%p failed static validation of code page %zd", this, slot);
- mExecutableValidated = true; // we tried
- mExecutableValid = false; // it failed
- MacOSError::throwMe(errSecCSSignatureFailed);
+ if (!validatedExecutable()) {
+ try {
+ DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this,
+ (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots);
+ const CodeDirectory *cd = this->codeDirectory();
+ if (!cd)
+ MacOSError::throwMe(errSecCSUnsigned);
+ AutoFileDesc fd(mainExecutablePath(), O_RDONLY);
+ fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass)
+ if (Universal *fat = mRep->mainExecutableImage())
+ fd.seek(fat->archOffset());
+ size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0;
+ size_t remaining = cd->codeLimit;
+ for (size_t slot = 0; slot < cd->nCodeSlots; ++slot) {
+ size_t size = min(remaining, pageSize);
+ if (!cd->validateSlot(fd, size, slot)) {
+ CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, slot);
+ MacOSError::throwMe(errSecCSSignatureFailed);
+ }
+ remaining -= size;
+ }
+ mExecutableValidated = true;
+ mExecutableValidResult = noErr;
+ } catch (const CommonError &err) {
+ mExecutableValidated = true;
+ mExecutableValidResult = err.osStatus();
+ throw;
+ } catch (...) {
+ secdebug("staticCode", "%p executable validation threw non-common exception", this);
+ mExecutableValidated = true;
+ mExecutableValidResult = errSecCSInternalError;
+ throw;
}
- remaining -= size;
}
- secdebug("staticCode", "%p validated full executable (%d pages)",
- this, int(cd->nCodeSlots));
- mExecutableValidated = true; // we tried
- mExecutableValid = true; // it worked
+ assert(validatedExecutable());
+ if (mExecutableValidResult != noErr)
+ MacOSError::throwMe(mExecutableValidResult);
}
//
void SecStaticCode::validateResources()
{
- // sanity first
- CFDictionaryRef sealedResources = resourceDictionary();
- if (this->resourceBase()) // disk has resources
- if (sealedResources)
- /* go to work below */;
- else
- MacOSError::throwMe(errSecCSResourcesNotFound);
- else // disk has no resources
- if (sealedResources)
- MacOSError::throwMe(errSecCSResourcesNotFound);
- else
- return; // no resources, not sealed - fine (no work)
-
- // found resources, and they are sealed
- CFDictionaryRef rules = cfget<CFDictionaryRef>(sealedResources, "rules");
- CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files");
- secdebug("staticCode", "%p verifying %d sealed resources",
- this, int(CFDictionaryGetCount(files)));
-
- // make a shallow copy of the ResourceDirectory so we can "check off" what we find
- CFRef<CFMutableDictionaryRef> resourceMap = CFDictionaryCreateMutableCopy(NULL,
- CFDictionaryGetCount(files), files);
- if (!resourceMap)
- CFError::throwMe();
-
- // scan through the resources on disk, checking each against the resourceDirectory
- CollectingContext ctx(*this); // collect all failures in here
- ResourceBuilder resources(cfString(this->resourceBase()), rules);
- mRep->adjustResources(resources);
- string path;
- ResourceBuilder::Rule *rule;
-
- while (resources.next(path, rule)) {
- if (CFDataRef value = resource(path, ctx))
- CFRelease(value);
- CFDictionaryRemoveValue(resourceMap, CFTempString(path));
- secdebug("staticCode", "%p validated %s", this, path.c_str());
- }
-
- if (CFDictionaryGetCount(resourceMap) > 0) {
- secdebug("staticCode", "%p sealed resource(s) not found in code", this);
- CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, &ctx);
- }
-
- // now check for any errors found in the reporting context
- if (ctx)
- ctx.throwMe();
+ if (!validatedResources()) {
+ try {
+ // sanity first
+ CFDictionaryRef sealedResources = resourceDictionary();
+ if (this->resourceBase()) // disk has resources
+ if (sealedResources)
+ /* go to work below */;
+ else
+ MacOSError::throwMe(errSecCSResourcesNotFound);
+ else // disk has no resources
+ if (sealedResources)
+ MacOSError::throwMe(errSecCSResourcesNotFound);
+ else
+ return; // no resources, not sealed - fine (no work)
+
+ // found resources, and they are sealed
+ CFDictionaryRef rules = cfget<CFDictionaryRef>(sealedResources, "rules");
+ CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files");
+ DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this,
+ (char*)this->mainExecutablePath().c_str(), int(CFDictionaryGetCount(files)));
+
+ // make a shallow copy of the ResourceDirectory so we can "check off" what we find
+ CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files);
+
+ // scan through the resources on disk, checking each against the resourceDirectory
+ mResourcesValidContext = new CollectingContext(*this); // collect all failures in here
+ ResourceBuilder resources(cfString(this->resourceBase()), rules, codeDirectory()->hashType);
+ mRep->adjustResources(resources);
+ string path;
+ ResourceBuilder::Rule *rule;
+
+ while (resources.next(path, rule)) {
+ validateResource(path, *mResourcesValidContext);
+ CFDictionaryRemoveValue(resourceMap, CFTempString(path));
+ }
+
+ if (CFDictionaryGetCount(resourceMap) > 0) {
+ secdebug("staticCode", "%p sealed resource(s) not found in code", this);
+ CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext);
+ }
+
+ // now check for any errors found in the reporting context
+ mResourcesValidated = true;
+ if (mResourcesValidContext->osStatus() != noErr)
+ mResourcesValidContext->throwMe();
- secdebug("staticCode", "%p sealed resources okay", this);
+ } catch (const CommonError &err) {
+ mResourcesValidated = true;
+ mResourcesValidResult = err.osStatus();
+ throw;
+ } catch (...) {
+ secdebug("staticCode", "%p executable validation threw non-common exception", this);
+ mResourcesValidated = true;
+ mResourcesValidResult = errSecCSInternalError;
+ throw;
+ }
+ }
+ assert(validatedResources());
+ if (mResourcesValidResult)
+ MacOSError::throwMe(mResourcesValidResult);
+ if (mResourcesValidContext->osStatus() != noErr)
+ mResourcesValidContext->throwMe();
}
{
CollectingContext *ctx = static_cast<CollectingContext *>(context);
ResourceSeal seal(value);
- if (!seal.optional())
+ if (!seal.optional()) {
if (key && CFGetTypeID(key) == CFStringGetTypeID()) {
ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing,
CFTempURL(CFStringRef(key), false, ctx->code.resourceBase()));
- } else
+ } else {
ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key);
+ }
+ }
}
CFDictionaryRef SecStaticCode::infoDictionary()
{
if (!mInfoDict) {
- mInfoDict.take(getDictionary(cdInfoSlot));
+ mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed));
secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get());
}
return mInfoDict;
{
if (mResourceDict) // cached
return mResourceDict;
- if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot))
+ if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, errSecCSSignatureFailed))
if (cfscan(dict, "{rules=%Dn,files=%Dn}")) {
secdebug("staticCode", "%p loaded ResourceDict %p",
this, mResourceDict.get());
// This will force load and validation, which means that it will perform basic
// validation if it hasn't been done yet.
//
-CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot)
+CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
{
validateDirectory();
- if (CFDataRef infoData = component(slot)) {
- validateComponent(slot);
+ if (CFDataRef infoData = component(slot, fail)) {
+ validateComponent(slot, fail);
if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData))
return dict;
else
MacOSError::throwMe(errSecCSResourcesNotFound);
CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
if (CFRef<CFDataRef> data = cfLoadFile(fullpath)) {
- SHA1 hasher;
- hasher(CFDataGetBytePtr(data), CFDataGetLength(data));
- if (hasher.verify(seal.hash()))
+ MakeHash<CodeDirectory> hasher(this->codeDirectory());
+ hasher->update(CFDataGetBytePtr(data), CFDataGetLength(data));
+ if (hasher->verify(seal.hash()))
return data.yield(); // good
else
ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
}
+void SecStaticCode::validateResource(string path, ValidationContext &ctx)
+{
+ if (CFDictionaryRef rdict = resourceDictionary()) {
+ if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) {
+ ResourceSeal seal = file;
+ if (!resourceBase()) // no resources in DiskRep
+ MacOSError::throwMe(errSecCSResourcesNotFound);
+ CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
+ AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional filee
+ if (fd) {
+ MakeHash<CodeDirectory> hasher(this->codeDirectory());
+ hashFileData(fd, hasher.get());
+ if (hasher->verify(seal.hash()))
+ return; // verify good
+ else
+ ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
+ } else {
+ if (!seal.optional())
+ ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
+ else
+ return; // validly missing
+ }
+ } else
+ ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
+ } else
+ MacOSError::throwMe(errSecCSResourcesNotSealed);
+}
+
+
//
// Test a CodeDirectory flag.
// Returns false if there is no CodeDirectory.
//
-// Return the Designated Requirement. This can be either explicit in the
-// Internal Requirements resource, or implicitly generated.
+// Return the Designated Requirement (DR). This can be either explicit in the
+// Internal Requirements component, or implicitly generated on demand here.
+// Note that an explicit DR may have been implicitly generated at signing time;
+// we don't distinguish this case.
//
const Requirement *SecStaticCode::designatedRequirement()
{
//
-// Generate the default (implicit) Designated Requirement for this StaticCode.
-// This is a heuristic of sorts, and may change over time (for the better, we hope).
-//
-// The current logic is this:
-// * If the code is ad-hoc signed, use the CodeDirectory hash directory.
-// * Otherwise, use the form anchor (anchor) and identifier (CodeDirectory identifier).
-// ** If the root CA is Apple's, we use the "anchor apple" construct. Otherwise,
-// we default to the leaf (directly signing) certificate.
+// Generate the default Designated Requirement (DR) for this StaticCode.
+// Ignore any explicit DR it may contain.
//
const Requirement *SecStaticCode::defaultDesignatedRequirement()
{
- validateDirectory(); // need the cert chain
- Requirement::Maker maker;
-
- // if this is an ad-hoc (unsigned) object, return a cdhash requirement
if (flag(kSecCodeSignatureAdhoc)) {
+ // adhoc signature: return a plain cdhash requirement
+ Requirement::Maker maker;
SHA1 hash;
hash(codeDirectory(), codeDirectory()->length());
SHA1::Digest digest;
hash.finish(digest);
maker.cdhash(digest);
+ return maker.make();
} else {
- // always require the identifier
- maker.put(opAnd);
- maker.ident(codeDirectory()->identifier());
-
- SHA1::Digest anchorHash;
- hashOfCertificate(cert(Requirement::anchorCert), anchorHash);
- if (!memcmp(anchorHash, Requirement::appleAnchorHash(), SHA1::digestLength)
-#if defined(TEST_APPLE_ANCHOR)
- || !memcmp(anchorHash, Requirement::testAppleAnchorHash(), SHA1::digestLength)
-#endif
- )
- defaultDesignatedAppleAnchor(maker);
- else
- defaultDesignatedNonAppleAnchor(maker);
+ // full signature: Gin up full context and let DRMaker do its thing
+ validateDirectory(); // need the cert chain
+ Requirement::Context context(this->certificates(),
+ this->infoDictionary(),
+ this->entitlements(),
+ this->identifier(),
+ this->codeDirectory()
+ );
+ return DRMaker(context).make();
}
-
- return maker();
-}
-
-static const uint8_t adcSdkMarker[] = { APPLE_EXTENSION_OID, 2, 1 };
-static const CSSM_DATA adcSdkMarkerOID = { sizeof(adcSdkMarker), (uint8_t *)adcSdkMarker };
-
-void SecStaticCode::defaultDesignatedAppleAnchor(Requirement::Maker &maker)
-{
- if (isAppleSDKSignature()) {
- // get the Common Name DN element for the leaf
- CFRef<CFStringRef> leafCN;
- MacOSError::check(SecCertificateCopySubjectComponent(cert(Requirement::leafCert),
- &CSSMOID_CommonName, &leafCN.aref()));
-
- // apple anchor generic and ...
- maker.put(opAnd);
- maker.anchorGeneric(); // apple generic anchor and...
- // ... leaf[subject.CN] = <leaf's subject> and ...
- maker.put(opAnd);
- maker.put(opCertField); // certificate
- maker.put(0); // leaf
- maker.put("subject.CN"); // [subject.CN]
- maker.put(matchEqual); // =
- maker.putData(leafCN); // <leaf CN>
- // ... cert 1[field.<marker>] exists
- maker.put(opCertGeneric); // certificate
- maker.put(1); // 1
- maker.putData(adcSdkMarkerOID.Data, adcSdkMarkerOID.Length); // [field.<marker>]
- maker.put(matchExists); // exists
- return;
- }
-
- // otherwise, claim this program for Apple
- maker.anchor();
-}
-
-bool SecStaticCode::isAppleSDKSignature()
-{
- if (CFArrayRef certChain = certificates()) // got cert chain
- if (CFArrayGetCount(certChain) == 3) // leaf, one intermediate, anchor
- if (SecCertificateRef intermediate = cert(1)) // get intermediate
- if (certificateHasField(intermediate, CssmOid::overlay(adcSdkMarkerOID)))
- return true;
- return false;
-}
-
-
-void SecStaticCode::defaultDesignatedNonAppleAnchor(Requirement::Maker &maker)
-{
- // get the Organization DN element for the leaf
- CFRef<CFStringRef> leafOrganization;
- MacOSError::check(SecCertificateCopySubjectComponent(cert(Requirement::leafCert),
- &CSSMOID_OrganizationName, &leafOrganization.aref()));
-
- // now step up the cert chain looking for the first cert with a different one
- int slot = Requirement::leafCert; // start at leaf
- if (leafOrganization) {
- while (SecCertificateRef ca = cert(slot+1)) { // NULL if you over-run the anchor slot
- CFRef<CFStringRef> caOrganization;
- MacOSError::check(SecCertificateCopySubjectComponent(ca, &CSSMOID_OrganizationName, &caOrganization.aref()));
- if (CFStringCompare(leafOrganization, caOrganization, 0) != kCFCompareEqualTo)
- break;
- slot++;
- }
- if (slot == CFArrayGetCount(mCertChain) - 1) // went all the way to the anchor...
- slot = Requirement::anchorCert; // ... so say that
- }
-
- // nail the last cert with the leaf's Organization value
- SHA1::Digest authorityHash;
- hashOfCertificate(cert(slot), authorityHash);
- maker.anchor(slot, authorityHash);
}
void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target,
OSStatus nullError /* = noErr */)
{
- secdebug("staticCode", "%p validating %s requirements for %p",
- this, Requirement::typeNames[type], target);
+ DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError);
if (const Requirement *req = internalRequirement(type))
- target->validateRequirements(req, nullError ? nullError : errSecCSReqFailed);
- else if (nullError) {
- secdebug("staticCode", "%p NULL validate for %s prohibited",
- this, Requirement::typeNames[type]);
+ target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed);
+ else if (nullError)
MacOSError::throwMe(nullError);
- } else
- secdebug("staticCode", "%p NULL validate (no requirements for %s)",
- this, Requirement::typeNames[type]);
+ else
+ /* accept it */;
}
//
// Validate this StaticCode against an external Requirement
//
-void SecStaticCode::validateRequirements(const Requirement *req, OSStatus failure)
+bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure)
{
assert(req);
validateDirectory();
- req->validate(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()), failure);
+ return req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure);
+}
+
+void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure)
+{
+ if (!this->satisfiesRequirement(req, failure))
+ MacOSError::throwMe(failure);
}
// [ leaf, intermed-1, ..., intermed-n, anchor ]
// 0 1 ... -2 -1
// Returns NULL if unavailable for any reason.
-//
+//
SecCertificateRef SecStaticCode::cert(int ix)
{
validateDirectory(); // need cert chain
//
-// Gather API-official information about this StaticCode.
+// Gather (mostly) API-official information about this StaticCode.
//
// This method lives in the twilight between the API and internal layers,
// since it generates API objects (Sec*Refs) for return.
if (!this->isSigned())
return dict.yield();
-
//
- // Now add the generic attributes that we always include
+ // Add the generic attributes that we always include
//
CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier()));
CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format()));
- if (CFDictionaryRef info = infoDictionary())
- CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
+ CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource()));
+ CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash());
+ CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(this->codeDirectory(false)->hashType));
+
+ //
+ // Deliver any Info.plist only if it looks intact
+ //
+ try {
+ if (CFDictionaryRef info = this->infoDictionary())
+ CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
+ } catch (...) { } // don't deliver Info.plist if questionable
//
// kSecCSSigningInformation adds information about signing certificates and chains
//
if (flags & kSecCSSigningInformation) {
- if (CFArrayRef certs = certificates())
+ if (CFArrayRef certs = this->certificates())
CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs);
- if (CFDataRef sig = signature())
+ if (CFDataRef sig = this->signature())
CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig);
if (mTrust)
CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust);
- if (CFAbsoluteTime time = signingTime())
+ if (CFAbsoluteTime time = this->signingTime())
if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
CFDictionaryAddValue(dict, kSecCodeInfoTime, date);
+ if (CFAbsoluteTime time = this->signingTimestamp())
+ if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
+ CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date);
}
//
// kSecCSRequirementInformation adds information on requirements
//
if (flags & kSecCSRequirementInformation) {
- if (const Requirements *reqs = internalRequirements()) {
+ if (const Requirements *reqs = this->internalRequirements()) {
CFDictionaryAddValue(dict, kSecCodeInfoRequirements,
CFTempString(Dumper::dump(reqs)));
CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs));
}
- const Requirement *dreq = designatedRequirement();
- const Requirement *ddreq = defaultDesignatedRequirement();
- CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(ddreq))->handle();
- if (dreq == ddreq) {
- CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, ddreqRef);
- CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
- } else {
- CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement,
- CFRef<SecRequirementRef>((new SecRequirement(dreq))->handle()));
+
+ const Requirement *dreq = this->designatedRequirement();
+ CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle();
+ CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef);
+ if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit
+ CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
+ } else { // implicit
+ CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef);
}
- if (CFDataRef ent = component(cdEntitlementSlot))
- CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
+ if (CFDataRef ent = this->component(cdEntitlementSlot)) {
+ CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
+ if (CFDictionaryRef entdict = this->entitlements())
+ CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
+ }
}
//
//
if (flags & kSecCSInternalInformation) {
if (mDir)
- CFDictionaryAddValue(dict, CFSTR("CodeDirectory"), mDir);
- CFDictionaryAddValue(dict, CFSTR("CodeOffset"), CFTempNumber(mRep->signingBase()));
+ CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir);
+ CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase()));
if (CFDictionaryRef resources = resourceDictionary())
- CFDictionaryAddValue(dict, CFSTR("ResourceDirectory"), resources);
+ CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, resources);
}
mStatus = rc; // record first failure for eventual error return
if (type) {
if (!mCollection)
- mCollection.take(makeCFMutableDictionary(0));
+ mCollection.take(makeCFMutableDictionary());
CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type));
if (!element) {
element = makeCFMutableArray(0);
void SecStaticCode::CollectingContext::throwMe()
{
assert(mStatus != noErr);
- throw CSError(mStatus, mCollection.yield());
+ throw CSError(mStatus, mCollection.retain());
}
//
-// DetachedRep construction
+// SecStaticCode::AllArchitectures produces SecStaticCode objects separately
+// for each architecture represented by a base object.
//
-DetachedRep::DetachedRep(CFDataRef sig, DiskRep *orig)
- : original(orig), mSignature(sig)
+// Performance note: This is a simple, straight-forward implementation that
+// does not heroically try to share resources between the code objects produced.
+// In practice, this means we'll re-open files and re-read resource files.
+// In exchange, we enter all the code paths in the normal way, and do not have
+// special sharing paths to worry about.
+// If a performance tool brings you here because you have *proof* of a performance
+// problem, consider digging up MachO and Universal (for sharing file descriptors),
+// and SecStaticCode (for sharing resource iterators). That ought to cover most of
+// the big chunks. If you're just offended by the simplicity of this implementation,
+// go play somewhere else.
+//
+SecStaticCode::AllArchitectures::AllArchitectures(SecStaticCode *code)
+ : mBase(code)
{
- const BlobCore *sigBlob = reinterpret_cast<const BlobCore *>(CFDataGetBytePtr(sig));
- if (sigBlob->is<EmbeddedSignatureBlob>()) { // architecture-less
- mArch = EmbeddedSignatureBlob::specific(sigBlob);
- mGlobal = NULL;
- return;
- } else if (sigBlob->is<DetachedSignatureBlob>()) { // architecture collection
- const DetachedSignatureBlob *dsblob = DetachedSignatureBlob::specific(sigBlob);
- if (Universal *fat = orig->mainExecutableImage()) {
- if (const BlobCore *blob = dsblob->find(fat->bestNativeArch().cpuType())) {
- mArch = EmbeddedSignatureBlob::specific(blob);
- mGlobal = EmbeddedSignatureBlob::specific(dsblob->find(0));
- return;
- } else
- secdebug("staticcode", "detached signature missing architecture %s",
- fat->bestNativeArch().name());
- } else
- secdebug("staticcode", "detached signature requires Mach-O binary");
- } else
- secdebug("staticcode", "detached signature bad magic 0x%x", sigBlob->magic());
- MacOSError::throwMe(errSecCSSignatureInvalid);
+ if (Universal *fat = code->diskRep()->mainExecutableImage()) {
+ fat->architectures(mArchitectures);
+ mCurrent = mArchitectures.begin();
+ mState = fatBinary;
+ } else {
+ mState = firstNonFat;
+ }
}
-CFDataRef DetachedRep::component(CodeDirectory::SpecialSlot slot)
+SecStaticCode *SecStaticCode::AllArchitectures::operator () ()
{
- if (CFDataRef result = mArch->component(slot))
- return result;
- if (mGlobal)
- if (CFDataRef result = mGlobal->component(slot))
- return result;
- return original->component(slot);
+ switch (mState) {
+ case firstNonFat:
+ mState = atEnd;
+ return mBase;
+ case fatBinary:
+ {
+ if (mCurrent == mArchitectures.end())
+ return NULL;
+ Architecture arch = *mCurrent++;
+ if (arch == mBase->diskRep()->mainExecutableImage()->bestNativeArch()) {
+ return mBase;
+ } else {
+ DiskRep::Context ctx;
+ ctx.arch = arch;
+ return new SecStaticCode(DiskRep::bestGuess(mBase->mainExecutablePath(), &ctx));
+ }
+ }
+ default:
+ return NULL;
+ }
}