#include "signer.h"
#include "resources.h"
#include "signerutils.h"
#include "SecCodeSigner.h"
#include <Security/SecIdentity.h>
#include <Security/CMSEncoder.h>
#include <Security/CMSPrivate.h>
#include <Security/CSCommonPriv.h>
#include <CoreFoundation/CFBundlePriv.h>
#include "renum.h"
#include "machorep.h"
#include "csutilities.h"
#include <security_utilities/unix++.h>
#include <security_utilities/unixchild.h>
#include <security_utilities/cfmunge.h>
namespace Security {
namespace CodeSigning {
void SecCodeSigner::Signer::sign(SecCSFlags flags)
{
rep = code->diskRep()->base();
this->prepare(flags);
PreSigningContext context(*this);
if (Universal *fat = state.mNoMachO ? NULL : rep->mainExecutableImage()) {
signMachO(fat, context);
} else {
signArchitectureAgnostic(context);
}
}
void SecCodeSigner::Signer::remove(SecCSFlags flags)
{
if (state.mDetached)
MacOSError::throwMe(errSecCSNotSupported);
rep = code->diskRep();
if (Universal *fat = state.mNoMachO ? NULL : rep->mainExecutableImage()) {
MachOEditor editor(rep->writer(), *fat, kSecCodeSignatureNoHash, rep->mainExecutablePath());
editor.allocate(); editor.commit(); } else {
RefPointer<DiskRep::Writer> writer = rep->writer();
writer->remove();
writer->flush();
}
}
void SecCodeSigner::Signer::prepare(SecCSFlags flags)
{
CFRef<CFDictionaryRef> infoDict;
if (CFRef<CFDataRef> infoData = rep->component(cdInfoSlot))
infoDict.take(makeCFDictionaryFrom(infoData));
identifier = state.mIdentifier;
if (identifier.empty()) {
identifier = rep->recommendedIdentifier(state);
if (identifier.find('.') == string::npos)
identifier = state.mIdentifierPrefix + identifier;
if (identifier.find('.') == string::npos && state.isAdhoc())
identifier = identifier + "-" + uniqueName();
secdebug("signer", "using default identifier=%s", identifier.c_str());
} else
secdebug("signer", "using explicit identifier=%s", identifier.c_str());
if (state.mCdFlagsGiven) {
cdFlags = state.mCdFlags;
secdebug("signer", "using explicit cdFlags=0x%x", cdFlags);
} else {
cdFlags = 0;
if (infoDict)
if (CFTypeRef csflags = CFDictionaryGetValue(infoDict, CFSTR("CSFlags"))) {
if (CFGetTypeID(csflags) == CFNumberGetTypeID()) {
cdFlags = cfNumber<uint32_t>(CFNumberRef(csflags));
secdebug("signer", "using numeric cdFlags=0x%x from Info.plist", cdFlags);
} else if (CFGetTypeID(csflags) == CFStringGetTypeID()) {
cdFlags = cdTextFlags(cfString(CFStringRef(csflags)));
secdebug("signer", "using text cdFlags=0x%x from Info.plist", cdFlags);
} else
MacOSError::throwMe(errSecCSBadDictionaryFormat);
}
}
if (state.mSigner == SecIdentityRef(kCFNull)) cdFlags |= kSecCodeSignatureAdhoc;
string rpath = rep->resourcesRootPath();
if (!rpath.empty()) {
CFCopyRef<CFDictionaryRef> resourceRules = state.mResourceRules;
if (!resourceRules && infoDict)
if (CFTypeRef spec = CFDictionaryGetValue(infoDict, _kCFBundleResourceSpecificationKey)) {
if (CFGetTypeID(spec) == CFStringGetTypeID())
if (CFRef<CFDataRef> data = cfLoadFile(rpath + "/" + cfString(CFStringRef(spec))))
if (CFDictionaryRef dict = makeCFDictionaryFrom(data))
resourceRules.take(dict);
if (!resourceRules) MacOSError::throwMe(errSecCSResourceRulesInvalid);
}
if (!resourceRules)
resourceRules.take(rep->defaultResourceRules(state));
ResourceBuilder resources(rpath, cfget<CFDictionaryRef>(resourceRules, "rules"), digestAlgorithm());
rep->adjustResources(resources); CFRef<CFDictionaryRef> rdir = resources.build();
resourceDirectory.take(CFPropertyListCreateXMLData(NULL, rdir));
}
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
if (state.mSigningTime == CFDateRef(kCFNull)) {
signingTime = 0; } else if (!state.mSigningTime) {
signingTime = now; } else {
CFAbsoluteTime time = CFDateGetAbsoluteTime(state.mSigningTime);
if (time > now) MacOSError::throwMe(errSecCSBadDictionaryFormat);
signingTime = time;
}
pagesize = state.mPageSize ? cfNumber<size_t>(state.mPageSize) : rep->pageSize(state);
CFRef<SecIdentityRef> mTSAuth; }
void SecCodeSigner::Signer::signMachO(Universal *fat, const Requirement::Context &context)
{
auto_ptr<ArchEditor> editor(state.mDetached
? static_cast<ArchEditor *>(new BlobEditor(*fat, *this))
: new MachOEditor(rep->writer(), *fat, this->digestAlgorithm(), rep->mainExecutablePath()));
assert(editor->count() > 0);
if (!editor->attribute(writerNoGlobal)) populate(*editor);
for (MachOEditor::Iterator it = editor->begin(); it != editor->end(); ++it) {
MachOEditor::Arch &arch = *it->second;
arch.source.reset(fat->architecture(it->first));
arch.ireqs(state.mRequirements, rep->defaultRequirements(&arch.architecture, state), context);
if (editor->attribute(writerNoGlobal)) populate(arch);
populate(arch.cdbuilder, arch, arch.ireqs,
arch.source->offset(), arch.source->signingExtent());
if (state.mDetached) {
CFRef<CFDataRef> identification = MachORep::identificationFor(arch.source.get());
arch.add(cdIdentificationSlot, BlobWrapper::alloc(
CFDataGetBytePtr(identification), CFDataGetLength(identification)));
}
size_t cdSize = arch.cdbuilder.size();
arch.blobSize = arch.size(cdSize, state.mCMSSize, 0);
}
editor->allocate();
for (MachOEditor::Iterator it = editor->begin(); it != editor->end(); ++it) {
MachOEditor::Arch &arch = *it->second;
editor->reset(arch);
CodeDirectory *cd = arch.cdbuilder.build();
CFRef<CFDataRef> signature = signCodeDirectory(cd);
arch.add(cdCodeDirectorySlot, cd); arch.add(cdSignatureSlot, BlobWrapper::alloc(
CFDataGetBytePtr(signature), CFDataGetLength(signature)));
if (!state.mDryRun) {
EmbeddedSignatureBlob *blob = arch.make();
editor->write(arch, blob); }
}
if (!state.mDryRun)
editor->commit();
}
void SecCodeSigner::Signer::signArchitectureAgnostic(const Requirement::Context &context)
{
RefPointer<DiskRep::Writer> writer = state.mDetached ?
(new DetachedBlobWriter(*this)) : rep->writer();
CodeDirectory::Builder builder(state.mDigestAlgorithm);
InternalRequirements ireqs;
ireqs(state.mRequirements, rep->defaultRequirements(NULL, state), context);
populate(*writer);
populate(builder, *writer, ireqs, rep->signingBase(), rep->signingLimit());
if (state.mDetached) {
CFRef<CFDataRef> identification = rep->identification();
writer->component(cdIdentificationSlot, identification);
}
CodeDirectory *cd = builder.build();
CFRef<CFDataRef> signature = signCodeDirectory(cd);
if (!state.mDryRun) {
writer->codeDirectory(cd);
writer->signature(signature);
writer->flush();
}
::free(cd);
}
void SecCodeSigner::Signer::populate(DiskRep::Writer &writer)
{
if (resourceDirectory)
writer.component(cdResourceDirSlot, resourceDirectory);
}
void SecCodeSigner::Signer::populate(CodeDirectory::Builder &builder, DiskRep::Writer &writer,
InternalRequirements &ireqs, size_t offset , size_t length )
{
builder.executable(rep->mainExecutablePath(), pagesize, offset, length);
builder.flags(cdFlags);
builder.identifier(identifier);
if (CFRef<CFDataRef> data = rep->component(cdInfoSlot))
builder.specialSlot(cdInfoSlot, data);
if (ireqs) {
CFRef<CFDataRef> data = makeCFData(*ireqs);
writer.component(cdRequirementsSlot, data);
builder.specialSlot(cdRequirementsSlot, data);
}
if (resourceDirectory)
builder.specialSlot(cdResourceDirSlot, resourceDirectory);
#if NOT_YET
if (state.mApplicationData)
builder.specialSlot(cdApplicationSlot, state.mApplicationData);
#endif
if (state.mEntitlementData) {
writer.component(cdEntitlementSlot, state.mEntitlementData);
builder.specialSlot(cdEntitlementSlot, state.mEntitlementData);
}
writer.addDiscretionary(builder);
}
#include <security_smime/tsaSupport.h>
CFDataRef SecCodeSigner::Signer::signCodeDirectory(const CodeDirectory *cd)
{
assert(state.mSigner);
CFRef<CFMutableDictionaryRef> defaultTSContext = NULL;
if (state.mSigner == SecIdentityRef(kCFNull))
return CFDataCreate(NULL, NULL, 0);
CFRef<CMSEncoderRef> cms;
MacOSError::check(CMSEncoderCreate(&cms.aref()));
MacOSError::check(CMSEncoderSetCertificateChainMode(cms, kCMSCertificateChainWithRoot));
CMSEncoderAddSigners(cms, state.mSigner);
MacOSError::check(CMSEncoderSetHasDetachedContent(cms, true));
if (signingTime) {
MacOSError::check(CMSEncoderAddSignedAttributes(cms, kCMSAttrSigningTime));
MacOSError::check(CMSEncoderSetSigningTime(cms, signingTime));
}
MacOSError::check(CMSEncoderUpdateContent(cms, cd, cd->length()));
if (state.mWantTimeStamp)
{
CFRef<CFErrorRef> error = NULL;
defaultTSContext = SecCmsTSAGetDefaultContext(&error.aref());
if (error)
MacOSError::throwMe(errSecDataNotAvailable);
if (state.mNoTimeStampCerts || state.mTimestampService) {
if (state.mTimestampService)
CFDictionarySetValue(defaultTSContext, kTSAContextKeyURL, state.mTimestampService);
if (state.mNoTimeStampCerts)
CFDictionarySetValue(defaultTSContext, kTSAContextKeyNoCerts, kCFBooleanTrue);
}
CmsMessageSetTSAContext(cms, defaultTSContext);
}
CFDataRef signature;
MacOSError::check(CMSEncoderCopyEncodedContent(cms, &signature));
return signature;
}
uint32_t SecCodeSigner::Signer::cdTextFlags(std::string text)
{
uint32_t flags = 0;
for (string::size_type comma = text.find(','); ; text = text.substr(comma+1), comma = text.find(',')) {
string word = (comma == string::npos) ? text : text.substr(0, comma);
const SecCodeDirectoryFlagTable *item;
for (item = kSecCodeDirectoryFlagTable; item->name; item++)
if (item->signable && word == item->name) {
flags |= item->value;
break;
}
if (!item->name) MacOSError::throwMe(errSecCSInvalidFlags);
if (comma == string::npos) break;
}
return flags;
}
std::string SecCodeSigner::Signer::uniqueName() const
{
CFRef<CFDataRef> identification = rep->identification();
const UInt8 *ident = CFDataGetBytePtr(identification);
const unsigned int length = CFDataGetLength(identification);
string result;
for (unsigned int n = 0; n < length; n++) {
char hex[3];
snprintf(hex, sizeof(hex), "%02x", ident[n]);
result += hex;
}
return result;
}
} }