#include "machorep.h"
#include "StaticCode.h"
#include "reqmaker.h"
namespace Security {
namespace CodeSigning {
using namespace UnixPlusPlus;
MachORep::MachORep(const char *path, const Context *ctx)
: SingleDiskRep(path), mSigningData(NULL)
{
if (ctx)
if (ctx->offset)
mExecutable = new Universal(fd(), ctx->offset);
else if (ctx->arch) {
auto_ptr<Universal> full(new Universal(fd()));
mExecutable = new Universal(fd(), full->archOffset(ctx->arch));
} else
mExecutable = new Universal(fd());
else
mExecutable = new Universal(fd());
assert(mExecutable);
CODESIGN_DISKREP_CREATE_MACHO(this, (char*)path, (void*)ctx);
}
MachORep::~MachORep()
{
delete mExecutable;
::free(mSigningData);
}
bool MachORep::candidate(FileDesc &fd)
{
switch (Universal::typeOf(fd)) {
case MH_EXECUTE:
case MH_DYLIB:
case MH_DYLINKER:
case MH_BUNDLE:
case MH_PRELOAD:
return true; case MH_OBJECT:
return false; default:
return false; }
}
static const uint8_t ppc_host_ireq[] = { 0xfa, 0xde, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x63, 0x6f, 0x6d, 0x2e,
0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6c, 0x61, 0x74, 0x65, 0x00,
};
const Requirements *MachORep::defaultRequirements(const Architecture *arch)
{
assert(arch); Requirements::Maker maker;
if (arch->cpuType() == CPU_TYPE_POWERPC)
maker.add(kSecHostRequirementType, ((const Requirement *)ppc_host_ireq)->clone());
if (Requirement *libreq = libraryRequirements(arch))
maker.add(kSecLibraryRequirementType, libreq);
return maker.make();
}
Requirement *MachORep::libraryRequirements(const Architecture *arch)
{
auto_ptr<MachO> macho(mainExecutableImage()->architecture(*arch));
Requirement::Maker maker;
Requirement::Maker::Chain chain(maker, opOr);
if (macho.get()) {
for (const load_command *command = macho->loadCommands(); command; command = macho->nextCommand(command)) {
if (macho->flip(command->cmd) == LC_LOAD_DYLIB) {
const dylib_command *dycmd = (const dylib_command *)command;
if (const char *name = macho->string(command, dycmd->dylib.name))
try {
secdebug("machorep", "examining DYLIB %s", name);
if (RefPointer<DiskRep> rep = DiskRep::bestFileGuess(name))
if (SecPointer<SecStaticCode> code = new SecStaticCode(rep))
if (const Requirement *req = code->designatedRequirement()) {
secdebug("machorep", "adding library requirement for %s", name);
chain.add();
chain.maker.copy(req);
}
} catch (...) {
secdebug("machorep", "exception getting library requirement (ignored)");
}
else
secdebug("machorep", "no string for DYLIB command (ignored)");
}
}
}
if (chain.empty())
return NULL;
else
return maker.make();
}
Universal *MachORep::mainExecutableImage()
{
if (!mExecutable)
mExecutable = new Universal(fd());
return mExecutable;
}
size_t MachORep::pageSize()
{
return segmentedPageSize;
}
size_t MachORep::signingBase()
{
return mainExecutableImage()->archOffset();
}
CFDataRef MachORep::identification()
{
std::auto_ptr<MachO> macho(mainExecutableImage()->architecture());
return identificationFor(macho.get());
}
CFDataRef MachORep::identificationFor(MachO *macho)
{
if (const load_command *cmd = macho->findCommand(LC_UUID)) {
const uuid_command *uuidc = reinterpret_cast<const uuid_command *>(cmd);
char result[4 + sizeof(uuidc->uuid)];
memcpy(result, "UUID", 4);
memcpy(result+4, uuidc->uuid, sizeof(uuidc->uuid));
return makeCFData(result, sizeof(result));
}
SHA1 hash;
hash(&macho->header(), sizeof(mach_header));
hash(macho->loadCommands(), macho->commandLength());
SHA1::Digest digest;
hash.finish(digest);
return makeCFData(digest, sizeof(digest));
}
CFDataRef MachORep::component(CodeDirectory::SpecialSlot slot)
{
switch (slot) {
case cdInfoSlot:
return infoPlist();
default:
return embeddedComponent(slot);
}
}
CFDataRef MachORep::embeddedComponent(CodeDirectory::SpecialSlot slot)
{
if (!mSigningData) { auto_ptr<MachO> macho(mainExecutableImage()->architecture());
if (macho.get())
if (const linkedit_data_command *cs = macho->findCodeSignature()) {
size_t offset = macho->flip(cs->dataoff);
size_t length = macho->flip(cs->datasize);
if (mSigningData = EmbeddedSignatureBlob::readBlob(macho->fd(), macho->offset() + offset, length)) {
secdebug("machorep", "%zd signing bytes in %d blob(s) from %s(%s)",
mSigningData->length(), mSigningData->count(),
mainExecutablePath().c_str(), macho->architecture().name());
} else {
secdebug("machorep", "failed to read signing bytes from %s(%s)",
mainExecutablePath().c_str(), macho->architecture().name());
MacOSError::throwMe(errSecCSSignatureInvalid);
}
}
}
if (mSigningData)
return mSigningData->component(slot);
return NULL;
}
CFDataRef MachORep::infoPlist()
{
CFRef<CFDataRef> info;
try {
auto_ptr<MachO> macho(mainExecutableImage()->architecture());
if (const section *sect = macho->findSection("__TEXT", "__info_plist")) {
if (macho->is64()) {
const section_64 *sect64 = reinterpret_cast<const section_64 *>(sect);
info.take(macho->dataAt(macho->flip(sect64->offset), macho->flip(sect64->size)));
} else {
info.take(macho->dataAt(macho->flip(sect->offset), macho->flip(sect->size)));
}
}
} catch (...) {
secdebug("machorep", "exception reading embedded Info.plist");
}
return info.yield();
}
string MachORep::recommendedIdentifier()
{
if (CFDataRef info = infoPlist()) {
if (CFDictionaryRef dict = makeCFDictionaryFrom(info)) {
CFStringRef code = CFStringRef(CFDictionaryGetValue(dict, kCFBundleIdentifierKey));
if (code && CFGetTypeID(code) != CFStringGetTypeID())
MacOSError::throwMe(errSecCSBadDictionaryFormat);
if (code)
return cfString(code);
} else
MacOSError::throwMe(errSecCSBadDictionaryFormat);
}
return SingleDiskRep::recommendedIdentifier();
}
string MachORep::format()
{
if (Universal *fat = mainExecutableImage()) {
Universal::Architectures archs;
fat->architectures(archs);
if (fat->isUniversal()) {
string s = "Mach-O universal (";
for (Universal::Architectures::const_iterator it = archs.begin();
it != archs.end(); ++it) {
if (it != archs.begin())
s += " ";
s += it->name();
}
return s + ")";
} else {
assert(archs.size() == 1);
return string("Mach-O thin (") + archs.begin()->name() + ")";
}
} else
return "Mach-O (unrecognized format)";
}
void MachORep::flush()
{
delete mExecutable;
mExecutable = NULL;
::free(mSigningData);
mSigningData = NULL;
SingleDiskRep::flush();
}
DiskRep::Writer *MachORep::writer()
{
return new Writer(this);
}
void MachORep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data)
{
assert(false);
MacOSError::throwMe(errSecCSInternalError);
}
} }