macOS Code Signing

Reading time: 16 minutes

tip

AWSハッキングを学び、実践する:HackTricks Training AWS Red Team Expert (ARTE)
GCPハッキングを学び、実践する:HackTricks Training GCP Red Team Expert (GRTE) Azureハッキングを学び、実践する:HackTricks Training Azure Red Team Expert (AzRTE)

HackTricksをサポートする

基本情報

Mach O Entitlements And Ipsw Indexing

Mach-o バイナリには LC_CODE_SIGNATURE というロードコマンドが含まれており、バイナリ内部の署名の offsetsize を示します。実際、GUI ツール MachOView を使うと、バイナリの末尾にこの情報を持つ Code Signature というセクションを見つけることができます:

Code Signature のマジックヘッダは 0xFADE0CC0 です。続いて、それらを含む superBlob の長さや blob の数といった情報があります。
この情報は source code here:

c
/*
* Structure of an embedded-signature SuperBlob
*/

typedef struct __BlobIndex {
uint32_t type;                                  /* type of entry */
uint32_t offset;                                /* offset of entry */
} CS_BlobIndex
__attribute__ ((aligned(1)));

typedef struct __SC_SuperBlob {
uint32_t magic;                                 /* magic number */
uint32_t length;                                /* total length of SuperBlob */
uint32_t count;                                 /* number of index entries following */
CS_BlobIndex index[];                   /* (count) entries */
/* followed by Blobs in no particular order as indicated by offsets in index */
} CS_SuperBlob
__attribute__ ((aligned(1)));

#define KERNEL_HAVE_CS_GENERICBLOB 1
typedef struct __SC_GenericBlob {
uint32_t magic;                                 /* magic number */
uint32_t length;                                /* total length of blob */
char data[];
} CS_GenericBlob
__attribute__ ((aligned(1)));

一般的に含まれる blob は Code Directory、Requirements、Entitlements、および Cryptographic Message Syntax (CMS) です。
さらに、blob にエンコードされたデータが ビッグエンディアン である点に注意してください。

また、署名はバイナリから切り離されて /var/db/DetachedSignatures に保存されることがあり(iOSで使用される)、

Code Directory Blob

宣言は Code Directory Blob in the code で確認できます:

c
typedef struct __CodeDirectory {
uint32_t magic;                                 /* magic number (CSMAGIC_CODEDIRECTORY) */
uint32_t length;                                /* total length of CodeDirectory blob */
uint32_t version;                               /* compatibility version */
uint32_t flags;                                 /* setup and mode flags */
uint32_t hashOffset;                    /* offset of hash slot element at index zero */
uint32_t identOffset;                   /* offset of identifier string */
uint32_t nSpecialSlots;                 /* number of special hash slots */
uint32_t nCodeSlots;                    /* number of ordinary (code) hash slots */
uint32_t codeLimit;                             /* limit to main image signature range */
uint8_t hashSize;                               /* size of each hash in bytes */
uint8_t hashType;                               /* type of hash (cdHashType* constants) */
uint8_t platform;                               /* platform identifier; zero if not platform binary */
uint8_t pageSize;                               /* log2(page size in bytes); 0 => infinite */
uint32_t spare2;                                /* unused (must be zero) */

char end_earliest[0];

/* Version 0x20100 */
uint32_t scatterOffset;                 /* offset of optional scatter vector */
char end_withScatter[0];

/* Version 0x20200 */
uint32_t teamOffset;                    /* offset of optional team identifier */
char end_withTeam[0];

/* Version 0x20300 */
uint32_t spare3;                                /* unused (must be zero) */
uint64_t codeLimit64;                   /* limit to main image signature range, 64 bits */
char end_withCodeLimit64[0];

/* Version 0x20400 */
uint64_t execSegBase;                   /* offset of executable segment */
uint64_t execSegLimit;                  /* limit of executable segment */
uint64_t execSegFlags;                  /* executable segment flags */
char end_withExecSeg[0];

/* Version 0x20500 */
uint32_t runtime;
uint32_t preEncryptOffset;
char end_withPreEncryptOffset[0];

/* Version 0x20600 */
uint8_t linkageHashType;
uint8_t linkageApplicationType;
uint16_t linkageApplicationSubType;
uint32_t linkageOffset;
uint32_t linkageSize;
char end_withLinkage[0];

/* followed by dynamic content as located by offset fields above */
} CS_CodeDirectory
__attribute__ ((aligned(1)));

この struct には異なるバージョンがあり、古いものは含まれる情報が少ない場合があることに注意してください。

コードページの署名

バイナリ全体をハッシュするのは、メモリに部分的にしかロードされない場合には非効率であり、ほとんど無意味です。したがって、コード署名は実際にはハッシュのハッシュであり、各バイナリページが個別にハッシュされます。\

実際、前述の Code Directory コードでは、そのフィールドのひとつに ページサイズが指定されている のがわかります。さらに、バイナリのサイズがページサイズの倍数でない場合、フィールド CodeLimit が署名の終端を指定します。

bash
# Get all hashes of /bin/ps
codesign -d -vvvvvv /bin/ps
[...]
CandidateCDHash sha256=c46e56e9490d93fe35a76199bdb367b3463c91dc
CandidateCDHashFull sha256=c46e56e9490d93fe35a76199bdb367b3463c91dcdb3c46403ab8ba1c2d13fd86
Hash choices=sha256
CMSDigest=c46e56e9490d93fe35a76199bdb367b3463c91dcdb3c46403ab8ba1c2d13fd86
CMSDigestType=2
Executable Segment base=0
Executable Segment limit=32768
Executable Segment flags=0x1
Page size=4096
-7=a542b4dcbc134fbd950c230ed9ddb99a343262a2df8e0c847caee2b6d3b41cc8
-6=0000000000000000000000000000000000000000000000000000000000000000
-5=2bb2de519f43b8e116c7eeea8adc6811a276fb134c55c9c2e9dcbd3047f80c7d
-4=0000000000000000000000000000000000000000000000000000000000000000
-3=0000000000000000000000000000000000000000000000000000000000000000
-2=4ca453dc8908dc7f6e637d6159c8761124ae56d080a4a550ad050c27ead273b3
-1=0000000000000000000000000000000000000000000000000000000000000000
0=a5e6478f89812c0c09f123524cad560a9bf758d16014b586089ddc93f004e39c
1=ad7facb2586fc6e966c004d7d1d16b024f5805ff7cb47c7a85dabd8b48892ca7
2=93d476eeace15a5ad14c0fb56169fd080a04b99582b4c7a01e1afcbc58688f
[...]

# Calculate the hasehs of each page manually
BINARY=/bin/ps
SIZE=`stat -f "%Z" $BINARY`
PAGESIZE=4096 # From the previous output
PAGES=`expr $SIZE / $PAGESIZE`
for i in `seq 0 $PAGES`; do
dd if=$BINARY of=/tmp/`basename $BINARY`.page.$i bs=$PAGESIZE skip=$i count=1
done
openssl sha256 /tmp/*.page.*

Entitlements Blob

アプリケーションには、すべての entitlements が定義された entitlement blob が含まれている場合があることに注意してください。さらに、一部の iOS バイナリでは、entitlements が特殊スロット -7(-5 entitlements special slot の代わり)に格納されていることがあります。

Special Slots

MacOS のアプリケーションは実行に必要なすべてをバイナリ内に持っているわけではなく、external resources(通常はアプリケーションの bundle 内)も使用します。したがって、バイナリ内には外部リソースが改変されていないかを確認するためのハッシュを格納するいくつかのスロットがあります。

実際、Code Directory structs には特殊スロットの数を示すパラメータ nSpecialSlots があり、それを見ることができます。特殊スロット 0 は存在せず、最も一般的なもの(-1 から -6)は次の通りです:

  • info.plist のハッシュ(または __TEXT.__info__plist 内のもの)。
  • Requirements のハッシュ
  • Resource Directory のハッシュ(bundle 内の _CodeSignature/CodeResources ファイルのハッシュ)。
  • アプリケーション固有(未使用)
  • entitlements のハッシュ
  • DMG code signatures のみ
  • DER Entitlements

Code Signing Flags

各プロセスにはカーネルによって設定されるビットマスクである status が関連付けられており、その一部は code signature によって上書きすることができます。code signing に含めることができるこれらのフラグは defined in the code:

c
/* code signing attributes of a process */
#define CS_VALID                    0x00000001  /* dynamically valid */
#define CS_ADHOC                    0x00000002  /* ad hoc signed */
#define CS_GET_TASK_ALLOW           0x00000004  /* has get-task-allow entitlement */
#define CS_INSTALLER                0x00000008  /* has installer entitlement */

#define CS_FORCED_LV                0x00000010  /* Library Validation required by Hardened System Policy */
#define CS_INVALID_ALLOWED          0x00000020  /* (macOS Only) Page invalidation allowed by task port policy */

#define CS_HARD                     0x00000100  /* don't load invalid pages */
#define CS_KILL                     0x00000200  /* kill process if it becomes invalid */
#define CS_CHECK_EXPIRATION         0x00000400  /* force expiration checking */
#define CS_RESTRICT                 0x00000800  /* tell dyld to treat restricted */

#define CS_ENFORCEMENT              0x00001000  /* require enforcement */
#define CS_REQUIRE_LV               0x00002000  /* require library validation */
#define CS_ENTITLEMENTS_VALIDATED   0x00004000  /* code signature permits restricted entitlements */
#define CS_NVRAM_UNRESTRICTED       0x00008000  /* has com.apple.rootless.restricted-nvram-variables.heritable entitlement */

#define CS_RUNTIME                  0x00010000  /* Apply hardened runtime policies */
#define CS_LINKER_SIGNED            0x00020000  /* Automatically signed by the linker */

#define CS_ALLOWED_MACHO            (CS_ADHOC | CS_HARD | CS_KILL | CS_CHECK_EXPIRATION | \
CS_RESTRICT | CS_ENFORCEMENT | CS_REQUIRE_LV | CS_RUNTIME | CS_LINKER_SIGNED)

#define CS_EXEC_SET_HARD            0x00100000  /* set CS_HARD on any exec'ed process */
#define CS_EXEC_SET_KILL            0x00200000  /* set CS_KILL on any exec'ed process */
#define CS_EXEC_SET_ENFORCEMENT     0x00400000  /* set CS_ENFORCEMENT on any exec'ed process */
#define CS_EXEC_INHERIT_SIP         0x00800000  /* set CS_INSTALLER on any exec'ed process */

#define CS_KILLED                   0x01000000  /* was killed by kernel for invalidity */
#define CS_NO_UNTRUSTED_HELPERS     0x02000000  /* kernel did not load a non-platform-binary dyld or Rosetta runtime */
#define CS_DYLD_PLATFORM            CS_NO_UNTRUSTED_HELPERS /* old name */
#define CS_PLATFORM_BINARY          0x04000000  /* this is a platform binary */
#define CS_PLATFORM_PATH            0x08000000  /* platform binary by the fact of path (osx only) */

#define CS_DEBUGGED                 0x10000000  /* process is currently or has previously been debugged and allowed to run with invalid pages */
#define CS_SIGNED                   0x20000000  /* process has a signature (may have gone invalid) */
#define CS_DEV_CODE                 0x40000000  /* code is dev signed, cannot be loaded into prod signed code (will go away with rdar://problem/28322552) */
#define CS_DATAVAULT_CONTROLLER     0x80000000  /* has Data Vault controller entitlement */

#define CS_ENTITLEMENT_FLAGS        (CS_GET_TASK_ALLOW | CS_INSTALLER | CS_DATAVAULT_CONTROLLER | CS_NVRAM_UNRESTRICTED)

Note that the function exec_mach_imgact can also add the CS_EXEC_* flags dynamically when starting the execution.

コード署名の要件

各アプリケーションは、実行可能になるために満たすべき要件requirements)を格納しています。もしアプリケーションに含まれる要件が満たされていない場合、実行は拒否されます(おそらく改変されているため)。

バイナリの要件は、のストリームである特殊な文法を使用しており、マジック値 0xfade0c00 を用いたblobとしてエンコードされ、そのハッシュは特別なコードスロットに格納されます

バイナリの要件は、次のように実行して確認できます:

bash
codesign -d -r- /bin/ls
Executable=/bin/ls
designated => identifier "com.apple.ls" and anchor apple

codesign -d -r- /Applications/Signal.app/
Executable=/Applications/Signal.app/Contents/MacOS/Signal
designated => identifier "org.whispersystems.signal-desktop" and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */ and certificate leaf[subject.OU] = U68MSDN6DR

tip

これらの署名は証明書情報、TeamID、IDs、entitlements、その他多くのデータをチェックできることに注意してください。

さらに、csreqツールを使ってコンパイル済みの要件を生成することも可能です:

bash
# Generate compiled requirements
csreq -b /tmp/output.csreq -r='identifier "org.whispersystems.signal-desktop" and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */ and certificate leaf[subject.OU] = U68MSDN6DR'

# Get the compiled bytes
od -A x -t x1 /tmp/output.csreq
0000000    fa  de  0c  00  00  00  00  b0  00  00  00  01  00  00  00  06
0000010    00  00  00  06  00  00  00  06  00  00  00  06  00  00  00  02
0000020    00  00  00  21  6f  72  67  2e  77  68  69  73  70  65  72  73
[...]

It's possible to access this information and create or modify requirements with some APIs from the Security.framework like:

有効性の確認

  • Sec[Static]CodeCheckValidity: SecCodeRef が Requirement に沿って有効かどうかをチェックします。
  • SecRequirementEvaluate: 証明書のコンテキストで Requirement を検証します。
  • SecTaskValidateForRequirement: 実行中の SecTask を CFString の Requirement に対して検証します。

コード要件の作成と管理

  • SecRequirementCreateWithData: 要件を表すバイナリデータから SecRequirementRef を作成します。
  • SecRequirementCreateWithString: 要件の文字列表現から SecRequirementRef を作成します。
  • SecRequirementCopy[Data/String]: SecRequirementRef のバイナリデータ表現を取得します。
  • SecRequirementCreateGroup: app-group membership の要件を作成します。

コード署名情報へのアクセス

  • SecStaticCodeCreateWithPath: コード署名を検査するためにファイルシステムパスから SecStaticCodeRef オブジェクトを初期化します。
  • SecCodeCopySigningInformation: SecCodeRef または SecStaticCodeRef から署名情報を取得します。

コード要件の変更

  • SecCodeSignerCreate: コード署名操作を行うための SecCodeSignerRef オブジェクトを作成します。
  • SecCodeSignerSetRequirement: 署名時に適用する新しい要件をコードサイナーに設定します。
  • SecCodeSignerAddSignature: 指定したサイナーで署名中のコードに署名を追加します。

要件によるコードの検証

  • SecStaticCodeCheckValidity: 指定された要件に対して静的コードオブジェクトを検証します。

追加の有用なAPI

  • SecCodeCopy[Internal/Designated]Requirement: Get SecRequirementRef from SecCodeRef
  • SecCodeCopyGuestWithAttributes: 特定の属性に基づくコードオブジェクトを表す SecCodeRef を作成します(サンドボックス用途で有用)。
  • SecCodeCopyPath: SecCodeRef に関連付けられたファイルシステムパスを取得します。
  • SecCodeCopySigningIdentifier: SecCodeRef から署名識別子(例: Team ID)を取得します。
  • SecCodeGetTypeID: SecCodeRef オブジェクトのタイプ識別子を返します。
  • SecRequirementGetTypeID: SecRequirementRef の CFTypeID を取得します。

コード署名フラグと定数

  • kSecCSDefaultFlags: コード署名操作で多くの Security.framework 関数で使用されるデフォルトフラグ。
  • kSecCSSigningInformation: 署名情報を取得することを指定するために使用されるフラグ。

コード署名の強制

アプリのコードが実行される前に、カーネルコード署名 を検査します。さらに、メモリに新しいコードを書き込み実行する方法の一つは、mprotectMAP_JIT フラグで呼び出される場合に JIT を悪用することです。これを行うには、アプリケーションに特別な entitlement が必要である点に注意してください。

cs_blobs & cs_blob

cs_blob 構造体は、実行中のプロセスの entitlement に関する情報を含みます。csb_platform_binary はアプリケーションがプラットフォームバイナリかどうかも示します(これは OS がこれらのプロセスの task port への SEND 権利を保護するなどのセキュリティ機構を適用するために様々な場面でチェックします)。

c
struct cs_blob {
struct cs_blob  *csb_next;
vnode_t         csb_vnode;
void            *csb_ro_addr;
__xnu_struct_group(cs_cpu_info, csb_cpu_info, {
cpu_type_t      csb_cpu_type;
cpu_subtype_t   csb_cpu_subtype;
});
__xnu_struct_group(cs_signer_info, csb_signer_info, {
unsigned int    csb_flags;
unsigned int    csb_signer_type;
});
off_t           csb_base_offset;        /* Offset of Mach-O binary in fat binary */
off_t           csb_start_offset;       /* Blob coverage area start, from csb_base_offset */
off_t           csb_end_offset;         /* Blob coverage area end, from csb_base_offset */
vm_size_t       csb_mem_size;
vm_offset_t     csb_mem_offset;
void            *csb_mem_kaddr;
unsigned char   csb_cdhash[CS_CDHASH_LEN];
const struct cs_hash  *csb_hashtype;
#if CONFIG_SUPPLEMENTAL_SIGNATURES
unsigned char   csb_linkage[CS_CDHASH_LEN];
const struct cs_hash  *csb_linkage_hashtype;
#endif
int             csb_hash_pageshift;
int             csb_hash_firstlevel_pageshift;   /* First hash this many bytes, then hash the hashes together */
const CS_CodeDirectory *csb_cd;
const char      *csb_teamid;
#if CONFIG_SUPPLEMENTAL_SIGNATURES
char            *csb_supplement_teamid;
#endif
const CS_GenericBlob *csb_entitlements_blob;    /* raw blob, subrange of csb_mem_kaddr */
const CS_GenericBlob *csb_der_entitlements_blob;    /* raw blob, subrange of csb_mem_kaddr */

/*
* OSEntitlements pointer setup by AMFI. This is PAC signed in addition to the
* cs_blob being within RO-memory to prevent modifications on the temporary stack
* variable used to setup the blob.
*/
void *XNU_PTRAUTH_SIGNED_PTR("cs_blob.csb_entitlements") csb_entitlements;

unsigned int    csb_reconstituted;      /* signature has potentially been modified after validation */
__xnu_struct_group(cs_blob_platform_flags, csb_platform_flags, {
/* The following two will be replaced by the csb_signer_type. */
unsigned int    csb_platform_binary:1;
unsigned int    csb_platform_path:1;
});

/* Validation category used for TLE */
unsigned int    csb_validation_category;

#if CODE_SIGNING_MONITOR
void *XNU_PTRAUTH_SIGNED_PTR("cs_blob.csb_csm_obj") csb_csm_obj;
bool csb_csm_managed;
#endif
};

参考文献

tip

AWSハッキングを学び、実践する:HackTricks Training AWS Red Team Expert (ARTE)
GCPハッキングを学び、実践する:HackTricks Training GCP Red Team Expert (GRTE) Azureハッキングを学び、実践する:HackTricks Training Azure Red Team Expert (AzRTE)

HackTricksをサポートする