Skip to content

Commit

Permalink
Improve entitlements parsing code
Browse files Browse the repository at this point in the history
  • Loading branch information
saagarjha committed Nov 1, 2020
1 parent 9e284da commit bf8ae39
Showing 1 changed file with 12 additions and 17 deletions.
29 changes: 12 additions & 17 deletions app/AppGroup.m
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@
//

#import <Foundation/Foundation.h>
#include <mach-o/loader.h>
#include <mach-o/getsect.h>
#include <dlfcn.h>
#import <mach-o/ldsyms.h>
#import <mach-o/loader.h>
#import <mach-o/getsect.h>
#import <dlfcn.h>

#define CSMAGIC_EMBEDDED_SIGNATURE 0xfade0cc0
#define CSMAGIC_EMBEDDED_ENTITLEMENTS 0xfade7171

struct cs_blob_index {
uint32_t type;
Expand All @@ -35,20 +39,11 @@

// Inspired by codesign.c in Darwin sources for Security.framework

// Find our mach-o header
Dl_info dl_info;
if (dladdr(AppEntitlements, &dl_info) == 0)
return nil;
if (dl_info.dli_fbase == NULL)
return nil;
char *base = dl_info.dli_fbase;
struct mach_header_64 *header = dl_info.dli_fbase;
if (header->magic != MH_MAGIC_64)
return nil;
const struct mach_header_64 *header = &_mh_execute_header;

// Simulator executables have fake entitlements in the code signature. The real entitlements can be found in an __entitlements section.
size_t entitlements_size;
char *entitlements_data = getsectiondata(header, "__TEXT", "__entitlements", &entitlements_size);
char *entitlements_data = (char *) getsectiondata(header, "__TEXT", "__entitlements", &entitlements_size);
if (entitlements_data != NULL) {
NSData *data = [NSData dataWithBytesNoCopy:entitlements_data
length:entitlements_size
Expand All @@ -60,7 +55,7 @@
}

// Find the LC_CODE_SIGNATURE
struct load_command *lc = (void *) (base + sizeof(*header));
struct load_command *lc = (void *) (header + 1);
struct linkedit_data_command *cs_lc = NULL;
for (uint32_t i = 0; i < header->ncmds; i++) {
if (lc->cmd == LC_CODE_SIGNATURE) {
Expand All @@ -80,14 +75,14 @@
NSData *csData = [fileHandle readDataOfLength:cs_lc->datasize];
[fileHandle closeFile];
const struct cs_superblob *cs = csData.bytes;
if (ntohl(cs->magic) != 0xfade0cc0)
if (ntohl(cs->magic) != CSMAGIC_EMBEDDED_SIGNATURE)
return nil;

// Find the entitlements in the code signature
NSData *entitlementsData = nil;
for (uint32_t i = 0; i < ntohl(cs->count); i++) {
struct cs_entitlements *ents = (void *) ((char *) cs + ntohl(cs->index[i].offset));
if (ntohl(ents->magic) == 0xfade7171) {
if (ntohl(ents->magic) == CSMAGIC_EMBEDDED_ENTITLEMENTS) {
entitlementsData = [NSData dataWithBytes:ents->entitlements
length:ntohl(ents->length) - offsetof(struct cs_entitlements, entitlements)];
}
Expand Down

0 comments on commit bf8ae39

Please sign in to comment.