1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
43 #include <sys/types.h>
46 #include <openssl/err.h>
47 #include <openssl/pem.h>
48 #include <openssl/pkcs7.h>
49 #include <openssl/pkcs12.h>
53 #include <CommonCrypto/CommonDigest.h>
55 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
56 #define LDID_SHA1 CC_SHA1
57 #define LDID_SHA1_CTX CC_SHA1_CTX
58 #define LDID_SHA1_Init CC_SHA1_Init
59 #define LDID_SHA1_Update CC_SHA1_Update
60 #define LDID_SHA1_Final CC_SHA1_Final
62 #define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
63 #define LDID_SHA256 CC_SHA256
64 #define LDID_SHA256_CTX CC_SHA256_CTX
65 #define LDID_SHA256_Init CC_SHA256_Init
66 #define LDID_SHA256_Update CC_SHA256_Update
67 #define LDID_SHA256_Final CC_SHA256_Final
69 #include <openssl/sha.h>
71 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
72 #define LDID_SHA1 SHA1
73 #define LDID_SHA1_CTX SHA_CTX
74 #define LDID_SHA1_Init SHA1_Init
75 #define LDID_SHA1_Update SHA1_Update
76 #define LDID_SHA1_Final SHA1_Final
78 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
79 #define LDID_SHA256 SHA256
80 #define LDID_SHA256_CTX SHA256_CTX
81 #define LDID_SHA256_Init SHA256_Init
82 #define LDID_SHA256_Update SHA256_Update
83 #define LDID_SHA256_Final SHA256_Final
87 #include <plist/plist.h>
89 #include <CoreFoundation/CoreFoundation.h>
94 #define _assert___(line) \
96 #define _assert__(line) \
100 #define $(value) value
104 #define _assert_(expr, format, ...) \
106 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
107 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
110 // XXX: this is not acceptable
111 #define _assert_(expr, format, ...) \
113 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
118 #define _assert(expr) \
119 _assert_(expr, "%s", $(#expr))
121 #define _syscall(expr, ...) [&] { for (;;) { \
123 if ((long) _value != -1) \
126 if (error == EINTR) \
128 /* XXX: EINTR is included in this list to fix g++ */ \
129 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
130 if (error == success) \
131 return (decltype(expr)) -success; \
132 _assert_(false, "errno=%u", error); \
136 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
142 __attribute__((packed))
144 template <typename Type_
>
146 typedef typename
Type_::const_iterator Result
;
149 #define _foreach(item, list) \
150 for (bool _stop(true); _stop; ) \
151 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
152 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
153 for (bool _suck(true); _suck; _suck = false) \
154 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
159 template <typename Function_
>
167 Scope(const Function_
&function
) :
177 template <typename Function_
>
178 Scope
<Function_
> _scope(const Function_
&function
) {
179 return Scope
<Function_
>(function
);
182 #define _scope__(counter, function) \
183 __attribute__((__unused__)) \
184 const _Scope &_scope ## counter(_scope([&]function))
185 #define _scope_(counter, function) \
186 _scope__(counter, function)
187 #define _scope(function) \
188 _scope_(__COUNTER__, function)
190 #define CPU_ARCH_MASK uint32_t(0xff000000)
191 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
193 #define CPU_TYPE_ANY uint32_t(-1)
194 #define CPU_TYPE_VAX uint32_t( 1)
195 #define CPU_TYPE_MC680x0 uint32_t( 6)
196 #define CPU_TYPE_X86 uint32_t( 7)
197 #define CPU_TYPE_MC98000 uint32_t(10)
198 #define CPU_TYPE_HPPA uint32_t(11)
199 #define CPU_TYPE_ARM uint32_t(12)
200 #define CPU_TYPE_MC88000 uint32_t(13)
201 #define CPU_TYPE_SPARC uint32_t(14)
202 #define CPU_TYPE_I860 uint32_t(15)
203 #define CPU_TYPE_POWERPC uint32_t(18)
205 #define CPU_TYPE_I386 CPU_TYPE_X86
207 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
208 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
209 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
216 #define FAT_MAGIC 0xcafebabe
217 #define FAT_CIGAM 0xbebafeca
237 #define MH_MAGIC 0xfeedface
238 #define MH_CIGAM 0xcefaedfe
240 #define MH_MAGIC_64 0xfeedfacf
241 #define MH_CIGAM_64 0xcffaedfe
243 #define MH_DYLDLINK 0x4
245 #define MH_OBJECT 0x1
246 #define MH_EXECUTE 0x2
248 #define MH_DYLINKER 0x7
249 #define MH_BUNDLE 0x8
250 #define MH_DYLIB_STUB 0x9
252 struct load_command
{
257 #define LC_REQ_DYLD uint32_t(0x80000000)
259 #define LC_SEGMENT uint32_t(0x01)
260 #define LC_SYMTAB uint32_t(0x02)
261 #define LC_DYSYMTAB uint32_t(0x0b)
262 #define LC_LOAD_DYLIB uint32_t(0x0c)
263 #define LC_ID_DYLIB uint32_t(0x0d)
264 #define LC_SEGMENT_64 uint32_t(0x19)
265 #define LC_UUID uint32_t(0x1b)
266 #define LC_CODE_SIGNATURE uint32_t(0x1d)
267 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
268 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
269 #define LC_ENCRYPTION_INFO uint32_t(0x21)
270 #define LC_DYLD_INFO uint32_t(0x22)
271 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
272 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
287 uint32_t current_version
;
288 uint32_t compatibility_version
;
291 struct dylib_command
{
297 struct uuid_command
{
303 struct symtab_command
{
312 struct dyld_info_command
{
316 uint32_t rebase_size
;
319 uint32_t weak_bind_off
;
320 uint32_t weak_bind_size
;
321 uint32_t lazy_bind_off
;
322 uint32_t lazy_bind_size
;
324 uint32_t export_size
;
327 struct dysymtab_command
{
340 uint32_t extrefsymoff
;
341 uint32_t nextrefsyms
;
342 uint32_t indirectsymoff
;
343 uint32_t nindirectsyms
;
350 struct dylib_table_of_contents
{
351 uint32_t symbol_index
;
352 uint32_t module_index
;
355 struct dylib_module
{
356 uint32_t module_name
;
365 uint32_t iinit_iterm
;
366 uint32_t ninit_nterm
;
367 uint32_t objc_module_info_addr
;
368 uint32_t objc_module_info_size
;
371 struct dylib_reference
{
376 struct relocation_info
{
378 uint32_t r_symbolnum
:24;
397 struct segment_command
{
411 struct segment_command_64
{
454 struct linkedit_data_command
{
461 struct encryption_info_command
{
469 #define BIND_OPCODE_MASK 0xf0
470 #define BIND_IMMEDIATE_MASK 0x0f
471 #define BIND_OPCODE_DONE 0x00
472 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
473 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
474 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
475 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
476 #define BIND_OPCODE_SET_TYPE_IMM 0x50
477 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
478 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
479 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
480 #define BIND_OPCODE_DO_BIND 0x90
481 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
482 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
483 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
485 struct : ldid::Progress
{
486 virtual void operator()(const std::string
&value
) const {
489 virtual void operator()(double value
) const {
493 struct Progression
: ldid::Progress
{
494 const ldid::Progress
&progress_
;
497 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
503 virtual void operator()(const std::string
&value
) const {
504 return progress_(name_
+ " (" + value
+ ")");
507 virtual void operator()(double value
) const {
508 return progress_(value
);
512 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
513 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
518 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
519 _assert(read(stream
, data
, size
) == size
);
522 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
523 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
526 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
528 for (size_t total(0); total
!= size
;) {
529 auto writ(std::min(size
- total
, size_t(4096 * 4)));
530 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
532 progress(double(total
) / size
);
536 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
539 if (auto writ
= read(stream
, data
, size
))
545 static inline void pad(std::streambuf
&stream
, size_t size
) {
547 memset(padding
, 0, size
);
548 put(stream
, padding
, size
);
551 template <typename Type_
>
552 Type_
Align(Type_ value
, size_t align
) {
559 static const uint8_t PageShift_(0x0c);
560 static const uint32_t PageSize_(1 << PageShift_
);
562 static inline uint16_t Swap_(uint16_t value
) {
564 ((value
>> 8) & 0x00ff) |
565 ((value
<< 8) & 0xff00);
568 static inline uint32_t Swap_(uint32_t value
) {
569 value
= ((value
>> 8) & 0x00ff00ff) |
570 ((value
<< 8) & 0xff00ff00);
571 value
= ((value
>> 16) & 0x0000ffff) |
572 ((value
<< 16) & 0xffff0000);
576 static inline uint64_t Swap_(uint64_t value
) {
577 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
578 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
579 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
583 static inline int16_t Swap_(int16_t value
) {
584 return Swap_(static_cast<uint16_t>(value
));
587 static inline int32_t Swap_(int32_t value
) {
588 return Swap_(static_cast<uint32_t>(value
));
591 static inline int64_t Swap_(int64_t value
) {
592 return Swap_(static_cast<uint64_t>(value
));
595 static bool little_(true);
597 static inline uint16_t Swap(uint16_t value
) {
598 return little_
? Swap_(value
) : value
;
601 static inline uint32_t Swap(uint32_t value
) {
602 return little_
? Swap_(value
) : value
;
605 static inline uint64_t Swap(uint64_t value
) {
606 return little_
? Swap_(value
) : value
;
609 static inline int16_t Swap(int16_t value
) {
610 return Swap(static_cast<uint16_t>(value
));
613 static inline int32_t Swap(int32_t value
) {
614 return Swap(static_cast<uint32_t>(value
));
617 static inline int64_t Swap(int64_t value
) {
618 return Swap(static_cast<uint64_t>(value
));
631 Swapped(bool swapped
) :
636 template <typename Type_
>
637 Type_
Swap(Type_ value
) const {
638 return swapped_
? Swap_(value
) : value
;
650 Data(void *base
, size_t size
) :
656 void *GetBase() const {
660 size_t GetSize() const {
671 struct mach_header
*mach_header_
;
672 struct load_command
*load_command_
;
675 MachHeader(void *base
, size_t size
) :
678 mach_header_
= (mach_header
*) base
;
680 switch (Swap(mach_header_
->magic
)) {
682 swapped_
= !swapped_
;
688 swapped_
= !swapped_
;
697 void *post
= mach_header_
+ 1;
699 post
= (uint32_t *) post
+ 1;
700 load_command_
= (struct load_command
*) post
;
703 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
704 Swap(mach_header_
->filetype
) == MH_DYLIB
||
705 Swap(mach_header_
->filetype
) == MH_DYLINKER
||
706 Swap(mach_header_
->filetype
) == MH_BUNDLE
710 bool Bits64() const {
714 struct mach_header
*operator ->() const {
718 operator struct mach_header
*() const {
722 uint32_t GetCPUType() const {
723 return Swap(mach_header_
->cputype
);
726 uint32_t GetCPUSubtype() const {
727 return Swap(mach_header_
->cpusubtype
) & 0xff;
730 struct load_command
*GetLoadCommand() const {
731 return load_command_
;
734 std::vector
<struct load_command
*> GetLoadCommands() const {
735 std::vector
<struct load_command
*> load_commands
;
737 struct load_command
*load_command
= load_command_
;
738 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
739 load_commands
.push_back(load_command
);
740 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
743 return load_commands
;
746 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
747 _foreach (load_command
, GetLoadCommands())
748 switch (Swap(load_command
->cmd
)) {
750 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
751 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
752 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
753 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
754 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
757 case LC_SEGMENT_64
: {
758 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
759 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
760 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
761 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
762 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
767 template <typename Target_
>
768 Target_
*GetOffset(uint32_t offset
) const {
769 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
773 class FatMachHeader
:
780 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
781 MachHeader(base
, size
),
786 fat_arch
*GetFatArch() const {
795 fat_header
*fat_header_
;
796 std::vector
<FatMachHeader
> mach_headers_
;
799 FatHeader(void *base
, size_t size
) :
802 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
804 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
805 swapped_
= !swapped_
;
807 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
809 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
811 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
812 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
814 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
815 uint32_t arch_offset
= Swap(fat_arch
->offset
);
816 uint32_t arch_size
= Swap(fat_arch
->size
);
817 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
823 std::vector
<FatMachHeader
> &GetMachHeaders() {
824 return mach_headers_
;
828 return fat_header_
!= NULL
;
831 struct fat_header
*operator ->() const {
835 operator struct fat_header
*() const {
840 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
841 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
842 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
843 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
844 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
845 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
846 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
847 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
849 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
850 #define CSSLOT_INFOSLOT uint32_t(0x00001)
851 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
852 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
853 #define CSSLOT_APPLICATION uint32_t(0x00004)
854 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
855 #define CSSLOT_ALTERNATE uint32_t(0x01000)
857 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
859 #define CS_HASHTYPE_SHA160_160 1
860 #define CS_HASHTYPE_SHA256_256 2
861 #define CS_HASHTYPE_SHA256_160 3
862 #define CS_HASHTYPE_SHA386_386 4
865 #define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
866 #define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
867 #define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
868 #define CS_EXECSEG_JIT 0x040 /* JIT enabled */
869 #define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
870 #define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
871 #define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
873 enum SecCodeExecSegFlags
{
874 kSecCodeExecSegMainBinary
= 0x001,
875 kSecCodeExecSegAllowUnsigned
= 0x010,
876 kSecCodeExecSegDebugger
= 0x020,
877 kSecCodeExecSegJit
= 0x040,
878 kSecCodeExecSegSkipLibraryVal
= 0x080,
879 kSecCodeExecSegCanLoadCdHash
= 0x100,
880 kSecCodeExecSegCanExecCdHash
= 0x100,
897 struct BlobIndex index
[];
900 struct CodeDirectory
{
904 uint32_t identOffset
;
905 uint32_t nSpecialSlots
;
913 uint32_t scatterOffset
;
914 uint32_t teamIDOffset
;
916 uint64_t codeLimit64
;
917 uint64_t execSegBase
;
918 uint64_t execSegLimit
;
919 uint64_t execSegFlags
;
920 #if 0 // version = 0x20500
922 uint32_t preEncryptOffset
;
924 #if 0 // version = 0x20600
925 uint8_t linkageHashType
;
926 uint8_t linkageTruncated
;
928 uint32_t linkageOffset
;
929 uint32_t linkageSize
;
933 enum CodeSignatureFlags
{
934 kSecCodeSignatureHost
= 0x0001,
935 kSecCodeSignatureAdhoc
= 0x0002,
936 kSecCodeSignatureForceHard
= 0x0100,
937 kSecCodeSignatureForceKill
= 0x0200,
938 kSecCodeSignatureForceExpiration
= 0x0400,
939 kSecCodeSignatureRestrict
= 0x0800,
940 kSecCodeSignatureEnforcement
= 0x1000,
941 kSecCodeSignatureLibraryValidation
= 0x2000,
942 kSecCodeSignatureRuntime
= 0x10000,
945 enum Kind
: uint32_t {
946 exprForm
= 1, // prefix expr form
949 enum ExprOp
: uint32_t {
950 opFalse
, // unconditionally false
951 opTrue
, // unconditionally true
952 opIdent
, // match canonical code [string]
953 opAppleAnchor
, // signed by Apple as Apple's product
954 opAnchorHash
, // match anchor [cert hash]
955 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
956 opAnd
, // binary prefix expr AND expr [expr; expr]
957 opOr
, // binary prefix expr OR expr [expr; expr]
958 opCDHash
, // match hash of CodeDirectory directly [cd hash]
959 opNot
, // logical inverse [expr]
960 opInfoKeyField
, // Info.plist key field [string; match suffix]
961 opCertField
, // Certificate field [cert index; field name; match suffix]
962 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
963 opTrustedCerts
, // require trust settings to approve the cert chain
964 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
965 opAppleGenericAnchor
, // signed by Apple in any capacity
966 opEntitlementField
, // entitlement dictionary field [string; match suffix]
967 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
968 opNamedAnchor
, // named anchor type
969 opNamedCode
, // named subroutine
970 opPlatform
, // platform constraint [integer]
971 exprOpCount
// (total opcode count in use)
974 enum MatchOperation
{
975 matchExists
, // anything but explicit "false" - no value stored
976 matchEqual
, // equal (CFEqual)
977 matchContains
, // partial match (substring)
978 matchBeginsWith
, // partial match (initial substring)
979 matchEndsWith
, // partial match (terminal substring)
980 matchLessThan
, // less than (string with numeric comparison)
981 matchGreaterThan
, // greater than (string with numeric comparison)
982 matchLessEqual
, // less or equal (string with numeric comparison)
983 matchGreaterEqual
, // greater or equal (string with numeric comparison)
986 #define OID_ISO_MEMBER 42
987 #define OID_US OID_ISO_MEMBER, 134, 72
988 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
989 #define APPLE_ADS_OID APPLE_OID, 0x64
990 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
993 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
1000 Algorithm(size_t size
, uint8_t type
) :
1006 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
1008 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
1009 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
1010 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
1012 virtual const char *name() = 0;
1015 struct AlgorithmSHA1
:
1019 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
1023 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1027 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1028 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
1031 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1032 return operator()(hash
.sha1_
, data
, size
);
1035 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1036 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1037 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1040 virtual const char *name() {
1045 struct AlgorithmSHA256
:
1049 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1053 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1054 return hash
.sha256_
;
1057 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1058 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1061 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1062 return operator()(hash
.sha256_
, data
, size
);
1065 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1066 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1067 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1070 virtual const char *name() {
1075 static bool do_sha1(true);
1076 static bool do_sha256(true);
1078 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1079 static AlgorithmSHA1 sha1
;
1080 static AlgorithmSHA256 sha256
;
1082 static std::vector
<Algorithm
*> algorithms
;
1083 if (algorithms
.empty()) {
1085 algorithms
.push_back(&sha1
);
1087 algorithms
.push_back(&sha256
);
1094 std::string entitlements_
;
1097 struct CodesignAllocation
{
1098 FatMachHeader mach_header_
;
1107 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
, const char *arch
, const Baton
&baton
) :
1108 mach_header_(mach_header
),
1120 #ifndef LDID_NOTOOLS
1133 _syscall(close(file_
));
1136 void open(const char *path
, int flags
) {
1137 _assert(file_
== -1);
1138 file_
= _syscall(::open(path
, flags
));
1155 _syscall(munmap(data_
, size_
));
1167 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1170 open(path
, oflag
, pflag
, mflag
);
1173 Map(const std::string
&path
, bool edit
) :
1183 bool empty() const {
1184 return data_
== NULL
;
1187 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1190 file_
.open(path
.c_str(), oflag
);
1191 int file(file_
.file());
1194 _syscall(fstat(file
, &stat
));
1195 size_
= stat
.st_size
;
1197 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1200 void open(const std::string
&path
, bool edit
) {
1202 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1204 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1207 void *data() const {
1211 size_t size() const {
1215 operator std::string() const {
1216 return std::string(static_cast<char *>(data_
), size_
);
1223 #ifndef LDID_NOPLIST
1224 static plist_t
plist(const std::string
&data
);
1227 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1228 _foreach (load_command
, mach_header
.GetLoadCommands())
1229 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1230 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1231 auto offset(mach_header
.Swap(signature
->dataoff
));
1232 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1233 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1235 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1236 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1237 auto begin(Swap(super
->index
[index
].offset
));
1238 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1239 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1240 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1245 std::string
Analyze(const void *data
, size_t size
) {
1246 std::string entitlements
;
1248 FatHeader
fat_header(const_cast<void *>(data
), size
);
1249 _foreach (mach_header
, fat_header
.GetMachHeaders())
1250 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1251 if (entitlements
.empty())
1252 entitlements
.assign(data
, size
);
1254 _assert(entitlements
.compare(0, entitlements
.size(), data
, size
) == 0);
1257 return entitlements
;
1260 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (const MachHeader
&, Baton
&, size_t)> &allocate
, const Functor
<size_t (const MachHeader
&, const Baton
&, std::streambuf
&output
, size_t, size_t, size_t, const std::string
&, const char *, const Progress
&)> &save
, const Progress
&progress
) {
1261 FatHeader
source(const_cast<void *>(idata
), isize
);
1265 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1267 std::vector
<CodesignAllocation
> allocations
;
1268 _foreach (mach_header
, source
.GetMachHeaders()) {
1269 struct linkedit_data_command
*signature(NULL
);
1270 struct symtab_command
*symtab(NULL
);
1272 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1273 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1275 else if (cmd
== LC_CODE_SIGNATURE
)
1276 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1277 else if (cmd
== LC_SYMTAB
)
1278 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1282 if (signature
== NULL
)
1283 size
= mach_header
.GetSize();
1285 size
= mach_header
.Swap(signature
->dataoff
);
1286 _assert(size
<= mach_header
.GetSize());
1289 if (symtab
!= NULL
) {
1290 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1291 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1292 _assert(end
<= size
);
1293 _assert(end
>= size
- 0x10);
1299 size_t alloc(allocate(mach_header
, baton
, size
));
1301 auto *fat_arch(mach_header
.GetFatArch());
1304 if (fat_arch
!= NULL
)
1305 align
= source
.Swap(fat_arch
->align
);
1306 else switch (mach_header
.GetCPUType()) {
1307 case CPU_TYPE_POWERPC
:
1308 case CPU_TYPE_POWERPC64
:
1310 case CPU_TYPE_X86_64
:
1314 case CPU_TYPE_ARM64
:
1322 const char *arch(NULL
);
1323 switch (mach_header
.GetCPUType()) {
1324 case CPU_TYPE_POWERPC
:
1327 case CPU_TYPE_POWERPC64
:
1333 case CPU_TYPE_X86_64
:
1339 case CPU_TYPE_ARM64
:
1344 offset
= Align(offset
, 1 << align
);
1346 uint32_t limit(size
);
1348 limit
= Align(limit
, 0x10);
1350 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1351 offset
+= size
+ alloc
;
1352 offset
= Align(offset
, 0x10);
1357 if (source
.IsFat()) {
1358 fat_header fat_header
;
1359 fat_header
.magic
= Swap(FAT_MAGIC
);
1360 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1361 put(output
, &fat_header
, sizeof(fat_header
));
1362 position
+= sizeof(fat_header
);
1364 // XXX: support fat_arch_64 (not in my toolchain)
1365 // probably use C++14 generic lambda (not in my toolchain)
1368 _foreach (allocation
, allocations
) {
1369 const auto offset(allocation
.offset_
);
1370 const auto size(allocation
.limit_
+ allocation
.alloc_
);
1371 if (uint32_t(offset
) != offset
|| uint32_t(size
) != size
)
1375 }(), "FAT slice >=4GiB not currently supported");
1377 _foreach (allocation
, allocations
) {
1378 auto &mach_header(allocation
.mach_header_
);
1381 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1382 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1383 fat_arch
.offset
= Swap(uint32_t(allocation
.offset_
));
1384 fat_arch
.size
= Swap(uint32_t(allocation
.limit_
+ allocation
.alloc_
));
1385 fat_arch
.align
= Swap(allocation
.align_
);
1386 put(output
, &fat_arch
, sizeof(fat_arch
));
1387 position
+= sizeof(fat_arch
);
1391 _foreach (allocation
, allocations
) {
1392 progress(allocation
.arch_
);
1393 auto &mach_header(allocation
.mach_header_
);
1395 pad(output
, allocation
.offset_
- position
);
1396 position
= allocation
.offset_
;
1401 std::vector
<std::string
> commands
;
1403 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1404 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1406 switch (mach_header
.Swap(load_command
->cmd
)) {
1407 case LC_CODE_SIGNATURE
:
1411 // XXX: this is getting ridiculous: provide a better abstraction
1414 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1416 if ((segment_command
->initprot
& 04) != 0) {
1417 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1418 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1425 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1426 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1427 segment_command
->filesize
= size
;
1428 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1432 case LC_SEGMENT_64
: {
1433 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1435 if ((segment_command
->initprot
& 04) != 0) {
1436 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1437 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1444 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1445 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1446 segment_command
->filesize
= size
;
1447 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1452 commands
.push_back(copy
);
1455 if (allocation
.alloc_
!= 0) {
1456 linkedit_data_command signature
;
1457 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1458 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1459 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1460 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1461 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1464 size_t begin(position
);
1467 _foreach(command
, commands
)
1468 after
+= command
.size();
1470 std::stringbuf altern
;
1472 struct mach_header
header(*mach_header
);
1473 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1474 header
.sizeofcmds
= mach_header
.Swap(after
);
1475 put(output
, &header
, sizeof(header
));
1476 put(altern
, &header
, sizeof(header
));
1477 position
+= sizeof(header
);
1479 if (mach_header
.Bits64()) {
1480 auto pad(mach_header
.Swap(uint32_t(0)));
1481 put(output
, &pad
, sizeof(pad
));
1482 put(altern
, &pad
, sizeof(pad
));
1483 position
+= sizeof(pad
);
1486 _foreach(command
, commands
) {
1487 put(output
, command
.data(), command
.size());
1488 put(altern
, command
.data(), command
.size());
1489 position
+= command
.size();
1492 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1493 if (before
> after
) {
1494 pad(output
, before
- after
);
1495 pad(altern
, before
- after
);
1496 position
+= before
- after
;
1499 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1501 std::string
overlap(altern
.str());
1502 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1504 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1505 position
= begin
+ allocation
.size_
;
1507 pad(output
, allocation
.limit_
- allocation
.size_
);
1508 position
+= allocation
.limit_
- allocation
.size_
;
1510 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, left
, right
, overlap
, top
, progress
));
1511 if (allocation
.alloc_
> saved
)
1512 pad(output
, allocation
.alloc_
- saved
);
1514 _assert(allocation
.alloc_
== saved
);
1515 position
+= allocation
.alloc_
;
1521 typedef std::map
<uint32_t, std::string
> Blobs
;
1523 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1524 auto value(buffer
.str());
1525 std::swap(blobs
[slot
], value
);
1528 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1529 auto value(buffer
.str());
1531 blob
.magic
= Swap(magic
);
1532 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1533 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1534 auto &save(blobs
[slot
]);
1535 std::swap(save
, value
);
1539 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1541 _foreach (blob
, blobs
)
1542 total
+= blob
.second
.size();
1544 struct SuperBlob super
;
1545 super
.blob
.magic
= Swap(magic
);
1546 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1547 super
.count
= Swap(uint32_t(blobs
.size()));
1548 put(output
, &super
, sizeof(super
));
1550 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1552 _foreach (blob
, blobs
) {
1554 index
.type
= Swap(blob
.first
);
1555 index
.offset
= Swap(uint32_t(offset
));
1556 put(output
, &index
, sizeof(index
));
1557 offset
+= blob
.second
.size();
1560 _foreach (blob
, blobs
)
1561 put(output
, blob
.second
.data(), blob
.second
.size());
1566 #ifndef LDID_NOSMIME
1575 _assert(bio_
!= NULL
);
1579 bio_(BIO_new(BIO_s_mem()))
1583 Buffer(const char *data
, size_t size
) :
1584 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1588 Buffer(const std::string
&data
) :
1589 Buffer(data
.data(), data
.size())
1593 Buffer(PKCS7
*pkcs
) :
1596 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1603 operator BIO
*() const {
1607 explicit operator std::string() const {
1609 auto size(BIO_get_mem_data(bio_
, &data
));
1610 return std::string(data
, size
);
1619 STACK_OF(X509
) *ca_
;
1623 value_(d2i_PKCS12_bio(bio
, NULL
)),
1626 _assert(value_
!= NULL
);
1627 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1629 _assert(key_
!= NULL
);
1630 _assert(cert_
!= NULL
);
1633 ca_
= sk_X509_new_null();
1634 _assert(ca_
!= NULL
);
1637 Stuff(const std::string
&data
) :
1643 sk_X509_pop_free(ca_
, X509_free
);
1645 EVP_PKEY_free(key_
);
1646 PKCS12_free(value_
);
1649 operator PKCS12
*() const {
1653 operator EVP_PKEY
*() const {
1657 operator X509
*() const {
1661 operator STACK_OF(X509
) *() const {
1671 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
) {
1672 value_
= PKCS7_new();
1673 _assert(value_
!= NULL
);
1675 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1676 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1678 STACK_OF(X509
) *certs(stuff
);
1679 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1680 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1682 // XXX: this is the same as PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP)
1683 _assert(X509_check_private_key(stuff
, stuff
));
1684 auto info(PKCS7_add_signature(value_
, stuff
, stuff
, EVP_sha1()));
1685 _assert(info
!= NULL
);
1686 _assert(PKCS7_add_certificate(value_
, stuff
));
1687 _assert(PKCS7_add_signed_attribute(info
, NID_pkcs9_contentType
, V_ASN1_OBJECT
, OBJ_nid2obj(NID_pkcs7_data
)));
1689 PKCS7_set_detached(value_
, 1);
1691 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1692 _assert(string
!= NULL
);
1694 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1696 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1697 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1699 ASN1_OCTET_STRING_free(string
);
1703 // XXX: this is the same as PKCS7_final(value_, data, PKCS7_BINARY)
1704 BIO
*bio(PKCS7_dataInit(value_
, NULL
));
1705 _assert(bio
!= NULL
);
1706 _scope({ BIO_free_all(bio
); });
1707 SMIME_crlf_copy(data
, bio
, PKCS7_BINARY
);
1709 _assert(PKCS7_dataFinal(value_
, bio
));
1716 operator PKCS7
*() const {
1723 public std::streambuf
1726 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1730 virtual int_type
overflow(int_type next
) {
1736 public std::streambuf
1741 LDID_SHA1_CTX sha1_
;
1742 LDID_SHA256_CTX sha256_
;
1745 HashBuffer(ldid::Hash
&hash
) :
1748 LDID_SHA1_Init(&sha1_
);
1749 LDID_SHA256_Init(&sha256_
);
1753 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1754 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1757 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1758 LDID_SHA1_Update(&sha1_
, data
, size
);
1759 LDID_SHA256_Update(&sha256_
, data
, size
);
1763 virtual int_type
overflow(int_type next
) {
1764 if (next
== traits_type::eof())
1776 std::streambuf
&buffer_
;
1779 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1785 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1786 _assert(HashBuffer::xsputn(data
, size
) == size
);
1787 return buffer_
.sputn(data
, size
);
1791 #ifndef LDID_NOTOOLS
1792 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1793 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1801 Split(const std::string
&path
) {
1802 size_t slash(path
.rfind('/'));
1803 if (slash
== std::string::npos
)
1806 dir
= path
.substr(0, slash
+ 1);
1807 base
= path
.substr(slash
+ 1);
1812 static void mkdir_p(const std::string
&path
) {
1816 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1819 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1822 auto slash(path
.rfind('/', path
.size() - 1));
1823 if (slash
== std::string::npos
)
1825 mkdir_p(path
.substr(0, slash
));
1828 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1829 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1831 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1835 static void Commit(const std::string
&path
, const std::string
&temp
) {
1837 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1839 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1841 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1844 _syscall(rename(temp
.c_str(), path
.c_str()));
1850 #ifndef LDID_NOSMIME
1851 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
1852 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
1853 _assert(index
>= 0);
1854 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
1855 _assert(next
== -1);
1856 auto entry(X509_NAME_get_entry(name
, index
));
1857 _assert(entry
!= NULL
);
1858 auto asn(X509_NAME_ENTRY_get_data(entry
));
1859 _assert(asn
!= NULL
);
1860 value
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
1864 static void req(std::streambuf
&buffer
, uint32_t value
) {
1865 value
= Swap(value
);
1866 put(buffer
, &value
, sizeof(value
));
1869 static void req(std::streambuf
&buffer
, const std::string
&value
) {
1870 req(buffer
, value
.size());
1871 put(buffer
, value
.data(), value
.size());
1872 static uint8_t zeros
[] = {0,0,0,0};
1873 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
1876 template <size_t Size_
>
1877 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
1879 put(buffer
, data
, Size_
);
1880 static uint8_t zeros
[] = {0,0,0,0};
1881 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
1884 Hash
Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, bool merge
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, uint32_t flags
, bool platform
, const Progress
&progress
) {
1891 #ifndef LDID_NOSMIME
1894 auto name(X509_get_subject_name(stuff
));
1895 _assert(name
!= NULL
);
1896 get(team
, name
, NID_organizationalUnitName
);
1897 get(common
, name
, NID_commonName
);
1902 std::stringbuf backing
;
1904 if (!requirements
.empty()) {
1905 put(backing
, requirements
.data(), requirements
.size());
1909 std::stringbuf requirement
;
1910 req(requirement
, exprForm
);
1911 req(requirement
, opAnd
);
1912 req(requirement
, opIdent
);
1913 req(requirement
, identifier
);
1914 req(requirement
, opAnd
);
1915 req(requirement
, opAppleGenericAnchor
);
1916 req(requirement
, opAnd
);
1917 req(requirement
, opCertField
);
1918 req(requirement
, 0);
1919 req(requirement
, "subject.CN");
1920 req(requirement
, matchEqual
);
1921 req(requirement
, common
);
1922 req(requirement
, opCertGeneric
);
1923 req(requirement
, 1);
1924 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
1925 req(requirement
, matchExists
);
1926 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
1928 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
1932 // XXX: this is just a "sufficiently large number"
1933 size_t certificate(0x3000);
1935 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
1936 size_t alloc(sizeof(struct SuperBlob
));
1938 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1940 uint32_t special(0);
1942 _foreach (slot
, slots
)
1943 special
= std::max(special
, slot
.first
);
1945 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
1946 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
1947 special
= std::max(special
, CSSLOT_INFOSLOT
);
1950 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1951 alloc
+= sizeof(struct BlobIndex
);
1952 alloc
+= backing
.str().size();
1955 baton
.entitlements_
= entitlements
;
1957 #ifndef LDID_NOPLIST
1958 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1959 baton
.entitlements_
.assign(data
, size
);
1962 if (baton
.entitlements_
.empty())
1963 baton
.entitlements_
= entitlements
;
1964 else if (!entitlements
.empty()) {
1965 auto combined(plist(baton
.entitlements_
));
1966 _scope({ plist_free(combined
); });
1967 _assert(plist_get_node_type(combined
) == PLIST_DICT
);
1969 auto merging(plist(entitlements
));
1970 _scope({ plist_free(merging
); });
1971 _assert(plist_get_node_type(merging
) == PLIST_DICT
);
1973 plist_dict_iter
iterator(NULL
);
1974 plist_dict_new_iter(merging
, &iterator
);
1975 _scope({ free(iterator
); });
1979 plist_t
value(NULL
);
1980 plist_dict_next_item(merging
, iterator
, &key
, &value
);
1983 _scope({ free(key
); });
1984 plist_dict_set_item(combined
, key
, plist_copy(value
));
1989 plist_to_xml(combined
, &xml
, &size
);
1990 _scope({ free(xml
); });
1992 baton
.entitlements_
.assign(xml
, size
);
1999 if (!baton
.entitlements_
.empty()) {
2000 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2001 alloc
+= sizeof(struct BlobIndex
);
2002 alloc
+= sizeof(struct Blob
);
2003 alloc
+= baton
.entitlements_
.size();
2006 size_t directory(0);
2008 directory
+= sizeof(struct BlobIndex
);
2009 directory
+= sizeof(struct Blob
);
2010 directory
+= sizeof(struct CodeDirectory
);
2011 directory
+= identifier
.size() + 1;
2014 directory
+= team
.size() + 1;
2016 for (Algorithm
*algorithm
: GetAlgorithms())
2017 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2019 #ifndef LDID_NOSMIME
2021 alloc
+= sizeof(struct BlobIndex
);
2022 alloc
+= sizeof(struct Blob
);
2023 alloc
+= certificate
;
2028 }), fun([&](const MachHeader
&mach_header
, const Baton
&baton
, std::streambuf
&output
, size_t limit
, size_t left
, size_t right
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
2032 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2036 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2037 execs
|= kSecCodeExecSegMainBinary
;
2039 if (!baton
.entitlements_
.empty()) {
2040 std::stringbuf data
;
2041 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2042 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2044 #ifndef LDID_NOPLIST
2045 auto entitlements(plist(baton
.entitlements_
));
2046 _scope({ plist_free(entitlements
); });
2047 _assert(plist_get_node_type(entitlements
) == PLIST_DICT
);
2049 const auto entitled([&](const char *key
) {
2050 auto item(plist_dict_get_item(entitlements
, key
));
2051 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2054 plist_get_bool_val(item
, &value
);
2058 if (entitled("get-task-allow"))
2059 execs
|= kSecCodeExecSegAllowUnsigned
;
2060 if (entitled("run-unsigned-code"))
2061 execs
|= kSecCodeExecSegAllowUnsigned
;
2062 if (entitled("com.apple.private.cs.debugger"))
2063 execs
|= kSecCodeExecSegDebugger
;
2064 if (entitled("dynamic-codesigning"))
2065 execs
|= kSecCodeExecSegJit
;
2066 if (entitled("com.apple.private.skip-library-validation"))
2067 execs
|= kSecCodeExecSegSkipLibraryVal
;
2068 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2069 execs
|= kSecCodeExecSegCanLoadCdHash
;
2070 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2071 execs
|= kSecCodeExecSegCanExecCdHash
;
2077 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2078 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2079 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2080 for (Algorithm
*algorithm
: GetAlgorithms())
2081 (*algorithm
)(slot
, data
, size
);
2086 for (Algorithm
*pointer
: GetAlgorithms()) {
2087 Algorithm
&algorithm(*pointer
);
2089 std::stringbuf data
;
2091 uint32_t special(0);
2092 _foreach (blob
, blobs
)
2093 special
= std::max(special
, blob
.first
);
2094 _foreach (slot
, posts
)
2095 special
= std::max(special
, slot
.first
);
2096 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2098 CodeDirectory directory
;
2099 directory
.version
= Swap(uint32_t(0x00020400));
2100 directory
.flags
= Swap(uint32_t(flags
));
2101 directory
.nSpecialSlots
= Swap(special
);
2102 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2103 directory
.nCodeSlots
= Swap(normal
);
2104 directory
.hashSize
= algorithm
.size_
;
2105 directory
.hashType
= algorithm
.type_
;
2106 directory
.platform
= platform
? 0x01 : 0x00;
2107 directory
.pageSize
= PageShift_
;
2108 directory
.spare2
= Swap(uint32_t(0));
2109 directory
.scatterOffset
= Swap(uint32_t(0));
2110 directory
.spare3
= Swap(uint32_t(0));
2111 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2112 directory
.execSegBase
= Swap(uint64_t(left
));
2113 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2114 directory
.execSegFlags
= Swap(execs
);
2116 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2118 directory
.identOffset
= Swap(uint32_t(offset
));
2119 offset
+= identifier
.size() + 1;
2122 directory
.teamIDOffset
= Swap(uint32_t(0));
2124 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2125 offset
+= team
.size() + 1;
2128 offset
+= special
* algorithm
.size_
;
2129 directory
.hashOffset
= Swap(uint32_t(offset
));
2130 offset
+= normal
* algorithm
.size_
;
2132 put(data
, &directory
, sizeof(directory
));
2134 put(data
, identifier
.c_str(), identifier
.size() + 1);
2136 put(data
, team
.c_str(), team
.size() + 1);
2138 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2139 auto *hashes(&storage
[special
* algorithm
.size_
]);
2141 memset(storage
.data(), 0, special
* algorithm
.size_
);
2143 _foreach (blob
, blobs
) {
2144 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2145 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2148 _foreach (slot
, posts
)
2149 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2153 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2154 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2155 progress(double(i
) / normal
);
2158 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2161 put(data
, storage
.data(), storage
.size());
2163 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2164 algorithm(hash
, save
.data(), save
.size());
2169 #ifndef LDID_NOSMIME
2172 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
));
2173 _scope({ CFRelease(plist
); });
2175 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
));
2176 _scope({ CFRelease(cdhashes
); });
2178 CFDictionarySetValue(plist
, CFSTR("cdhashes"), cdhashes
);
2180 auto plist(plist_new_dict());
2181 _scope({ plist_free(plist
); });
2183 auto cdhashes(plist_new_array());
2184 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2188 for (Algorithm
*pointer
: GetAlgorithms()) {
2189 Algorithm
&algorithm(*pointer
);
2192 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2195 std::vector
<char> hash
;
2196 algorithm(hash
, blob
.data(), blob
.size());
2200 auto value(CFDataCreate(kCFAllocatorDefault
, reinterpret_cast<const UInt8
*>(hash
.data()), hash
.size()));
2201 _scope({ CFRelease(value
); });
2202 CFArrayAppendValue(cdhashes
, value
);
2204 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2209 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
));
2210 _scope({ CFRelease(created
); });
2211 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created
)));
2212 auto size(CFDataGetLength(created
));
2216 plist_to_xml(plist
, &xml
, &size
);
2217 _scope({ free(xml
); });
2220 std::stringbuf data
;
2221 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2226 Signature
signature(stuff
, sign
, std::string(xml
, size
));
2227 Buffer
result(signature
);
2228 std::string
value(result
);
2229 put(data
, value
.data(), value
.size());
2231 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2232 _assert(save
.size() <= certificate
);
2236 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2242 #ifndef LDID_NOTOOLS
2243 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2244 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2246 }), fun([](const MachHeader
&mach_header
, const Baton
&baton
, std::streambuf
&output
, size_t limit
, size_t left
, size_t right
, const std::string
&overlap
, const char *top
, const Progress
&progress
) -> size_t {
2251 std::string
DiskFolder::Path(const std::string
&path
) const {
2252 return path_
+ path
;
2255 DiskFolder::DiskFolder(const std::string
&path
) :
2258 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2261 DiskFolder::~DiskFolder() {
2262 if (!std::uncaught_exception())
2263 for (const auto &commit
: commit_
)
2264 Commit(commit
.first
, commit
.second
);
2268 std::string
readlink(const std::string
&path
) {
2269 for (size_t size(1024); ; size
*= 2) {
2273 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2274 if (size_t(writ
) >= size
)
2283 void DiskFolder::Find(const std::string
&root
, const std::string
&base
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2284 std::string
path(Path(root
) + base
);
2286 DIR *dir(opendir(path
.c_str()));
2287 _assert(dir
!= NULL
);
2288 _scope({ _syscall(closedir(dir
)); });
2290 while (auto child
= readdir(dir
)) {
2291 std::string
name(child
->d_name
);
2292 if (name
== "." || name
== "..")
2294 if (Starts(name
, ".ldid."))
2301 _syscall(stat((path
+ name
).c_str(), &info
));
2303 else if (S_ISDIR(info
.st_mode
))
2305 else if (S_ISREG(info
.st_mode
))
2308 _assert_(false, "st_mode=%x", info
.st_mode
);
2310 switch (child
->d_type
) {
2318 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2321 _assert_(false, "d_type=%u", child
->d_type
);
2326 Find(root
, base
+ name
+ "/", code
, link
);
2332 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2335 std::stringbuf save
;
2339 auto from(Path(path
));
2340 commit_
[from
] = Temporary(save
, from
);
2345 bool DiskFolder::Look(const std::string
&path
) const {
2346 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2349 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2351 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2352 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2354 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2355 data
.pubseekpos(0, std::ios::in
);
2356 code(data
, length
, NULL
);
2359 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2360 Find(path
, "", code
, link
);
2364 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2368 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2371 std::string
SubFolder::Path(const std::string
&path
) const {
2372 return path_
+ path
;
2375 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2376 return parent_
.Save(Path(path
), edit
, flag
, code
);
2379 bool SubFolder::Look(const std::string
&path
) const {
2380 return parent_
.Look(Path(path
));
2383 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2384 return parent_
.Open(Path(path
), code
);
2387 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2388 return parent_
.Find(Path(path
), code
, link
);
2391 std::string
UnionFolder::Map(const std::string
&path
) const {
2392 auto remap(remaps_
.find(path
));
2393 if (remap
== remaps_
.end())
2395 return remap
->second
;
2398 void UnionFolder::Map(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const std::string
&file
, const Functor
<void (const Functor
<void (std::streambuf
&, size_t, const void *)> &)> &save
) const {
2399 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2400 code(file
.substr(path
.size()));
2403 UnionFolder::UnionFolder(Folder
&parent
) :
2408 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2409 return parent_
.Save(Map(path
), edit
, flag
, code
);
2412 bool UnionFolder::Look(const std::string
&path
) const {
2413 auto file(resets_
.find(path
));
2414 if (file
!= resets_
.end())
2416 return parent_
.Look(Map(path
));
2419 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2420 auto file(resets_
.find(path
));
2421 if (file
== resets_
.end())
2422 return parent_
.Open(Map(path
), code
);
2423 auto &entry(file
->second
);
2425 auto &data(*entry
.data_
);
2426 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2427 data
.pubseekpos(0, std::ios::in
);
2428 code(data
, length
, entry
.flag_
);
2431 void UnionFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&)> &code
, const Functor
<void (const std::string
&, const Functor
<std::string ()> &)> &link
) const {
2432 for (auto &reset
: resets_
)
2433 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2434 auto &entry(reset
.second
);
2435 auto &data(*entry
.data_
);
2436 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2437 data
.pubseekpos(0, std::ios::in
);
2438 code(data
, length
, entry
.flag_
);
2441 for (auto &remap
: remaps_
)
2442 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2443 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2444 code(data
, length
, flag
);
2448 parent_
.Find(path
, fun([&](const std::string
&name
) {
2449 if (deletes_
.find(path
+ name
) == deletes_
.end())
2451 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2452 if (deletes_
.find(path
+ name
) == deletes_
.end())
2457 #ifndef LDID_NOTOOLS
2458 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2462 char data
[4096 * 4];
2463 size_t writ(source
.sgetn(data
, sizeof(data
)));
2466 _assert(target
.sputn(data
, writ
) == writ
);
2468 progress(double(total
) / length
);
2472 #ifndef LDID_NOPLIST
2473 static plist_t
plist(const std::string
&data
) {
2474 plist_t
plist(NULL
);
2475 if (Starts(data
, "bplist00"))
2476 plist_from_bin(data
.data(), data
.size(), &plist
);
2478 plist_from_xml(data
.data(), data
.size(), &plist
);
2479 _assert(plist
!= NULL
);
2483 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2484 std::stringbuf data
;
2485 copy(buffer
, data
, length
, dummy_
);
2486 auto node(plist(data
.str()));
2487 _scope({ plist_free(node
); });
2488 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2492 static std::string
plist_s(plist_t node
) {
2493 _assert(node
!= NULL
);
2494 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2496 plist_get_string_val(node
, &data
);
2497 _scope({ free(data
); });
2513 std::vector
<std::string
> matches_
;
2516 Expression(const std::string
&code
) {
2517 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2518 matches_
.resize(regex_
.re_nsub
+ 1);
2525 bool operator ()(const std::string
&data
) {
2526 regmatch_t matches
[matches_
.size()];
2527 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2528 if (value
== REG_NOMATCH
)
2530 _assert_(value
== 0, "regexec()");
2531 for (size_t i(0); i
!= matches_
.size(); ++i
)
2532 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2536 const std::string
&operator [](size_t index
) const {
2537 return matches_
[index
];
2546 mutable std::auto_ptr
<Expression
> regex_
;
2548 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2555 Rule(const Rule
&rhs
) :
2556 weight_(rhs
.weight_
),
2562 void Compile() const {
2563 regex_
.reset(new Expression(code_
));
2566 bool operator ()(const std::string
&data
) const {
2567 _assert(regex_
.get() != NULL
);
2568 return (*regex_
)(data
);
2571 bool operator <(const Rule
&rhs
) const {
2572 if (weight_
> rhs
.weight_
)
2574 if (weight_
< rhs
.weight_
)
2576 return mode_
> rhs
.mode_
;
2581 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2582 return lhs
->code_
< rhs
->code_
;
2586 #ifndef LDID_NOPLIST
2587 static Hash
Sign(const uint8_t *prefix
, size_t size
, std::streambuf
&buffer
, Hash
&hash
, std::streambuf
&save
, const std::string
&identifier
, const std::string
&entitlements
, bool merge
, const std::string
&requirements
, const std::string
&key
, const Slots
&slots
, size_t length
, uint32_t flags
, bool platform
, const Progress
&progress
) {
2588 // XXX: this is a miserable fail
2589 std::stringbuf temp
;
2590 put(temp
, prefix
, size
);
2591 copy(buffer
, temp
, length
- size
, progress
);
2592 // XXX: this is a stupid hack
2593 pad(temp
, 0x10 - (length
& 0xf));
2594 auto data(temp
.str());
2596 HashProxy
proxy(hash
, save
);
2597 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2601 std::map
<std::string
, Hash
> files
;
2602 std::map
<std::string
, std::string
> links
;
2604 void Merge(const std::string
&root
, const State
&state
) {
2605 for (const auto &entry
: state
.files
)
2606 files
[root
+ entry
.first
] = entry
.second
;
2607 for (const auto &entry
: state
.links
)
2608 links
[root
+ entry
.first
] = entry
.second
;
2612 Bundle
Sign(const std::string
&root
, Folder
&parent
, const std::string
&key
, State
&remote
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2613 std::string executable
;
2614 std::string identifier
;
2618 std::string
info("Info.plist");
2620 SubFolder
folder(parent
, [&]() {
2621 if (parent
.Look(info
))
2625 else if (parent
.Look("Contents/" + info
))
2627 else if (parent
.Look("Resources/" + info
)) {
2628 info
= "Resources/" + info
;
2630 } else _assert_(false, "cannot find Info.plist");
2633 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2634 plist_d(buffer
, length
, fun([&](plist_t node
) {
2635 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2636 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2640 if (mac
&& info
== "Info.plist")
2641 executable
= "MacOS/" + executable
;
2643 progress(root
+ "*");
2645 std::string entitlements
;
2646 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2647 // XXX: this is a miserable fail
2648 std::stringbuf temp
;
2649 copy(buffer
, temp
, length
, progress
);
2650 // XXX: this is a stupid hack
2651 pad(temp
, 0x10 - (length
& 0xf));
2652 auto data(temp
.str());
2653 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2656 static const std::string
directory("_CodeSignature/");
2657 static const std::string
signature(directory
+ "CodeResources");
2659 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2661 auto &rules1(versions
[""]);
2662 auto &rules2(versions
["2"]);
2664 const std::string
resources(mac
? "Resources/" : "");
2667 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2668 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2669 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2670 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2671 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2675 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2676 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2677 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2678 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2679 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2680 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2681 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2682 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2683 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2684 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2685 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2686 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2687 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2688 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2693 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2694 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2695 std::map
<std::string
, Bundle
> bundles
;
2697 folder
.Find("", fun([&](const std::string
&name
) {
2700 auto bundle(root
+ Split(name
).dir
);
2702 _assert(!bundle
.empty());
2703 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2705 SubFolder
subfolder(folder
, bundle
);
2707 bundles
[nested
[1]] = Sign(bundle
, subfolder
, key
, local
, "", Starts(name
, "PlugIns/") ? alter
:
2708 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2710 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2713 std::set
<std::string
> excludes
;
2715 auto exclude([&](const std::string
&name
) {
2716 // BundleDiskRep::adjustResources -> builder.addExclusion
2717 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2720 for (const auto &bundle
: bundles
)
2721 if (Starts(name
, bundle
.first
+ "/")) {
2722 excludes
.insert(name
);
2729 folder
.Find("", fun([&](const std::string
&name
) {
2733 if (local
.files
.find(name
) != local
.files
.end())
2735 auto &hash(local
.files
[name
]);
2737 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2738 progress(root
+ name
);
2749 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2751 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2752 switch (Swap(header
.magic
)) {
2754 // Java class file format
2755 if (Swap(header
.count
) >= 40)
2758 case MH_MAGIC
: case MH_MAGIC_64
:
2759 case MH_CIGAM
: case MH_CIGAM_64
:
2760 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2762 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2767 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2768 HashProxy
proxy(hash
, save
);
2769 put(proxy
, header
.bytes
, size
);
2770 copy(data
, proxy
, length
- size
, progress
);
2773 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2777 local
.links
[name
] = read();
2780 auto plist(plist_new_dict());
2781 _scope({ plist_free(plist
); });
2783 for (const auto &version
: versions
) {
2784 auto files(plist_new_dict());
2785 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2787 for (const auto &rule
: version
.second
)
2790 bool old(&version
.second
== &rules1
);
2792 for (const auto &hash
: local
.files
)
2793 for (const auto &rule
: version
.second
)
2794 if (rule(hash
.first
)) {
2795 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2796 else if (old
&& rule
.mode_
== NoMode
)
2797 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2798 else if (rule
.mode_
!= OmitMode
) {
2799 auto entry(plist_new_dict());
2800 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2802 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2803 if (rule
.mode_
== OptionalMode
)
2804 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2805 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2812 for (const auto &link
: local
.links
)
2813 for (const auto &rule
: version
.second
)
2814 if (rule(link
.first
)) {
2815 if (rule
.mode_
!= OmitMode
) {
2816 auto entry(plist_new_dict());
2817 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
2818 if (rule
.mode_
== OptionalMode
)
2819 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2820 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
2827 for (const auto &bundle
: bundles
) {
2828 auto entry(plist_new_dict());
2829 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
2830 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
2831 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
2835 for (const auto &version
: versions
) {
2836 auto rules(plist_new_dict());
2837 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
2839 std::multiset
<const Rule
*, RuleCode
> ordered
;
2840 for (const auto &rule
: version
.second
)
2841 ordered
.insert(&rule
);
2843 for (const auto &rule
: ordered
)
2844 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
2845 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
2847 auto entry(plist_new_dict());
2848 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
2850 switch (rule
->mode_
) {
2854 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
2857 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2860 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
2863 plist_dict_set_item(entry
, "top", plist_new_bool(true));
2867 if (rule
->weight_
>= 10000)
2868 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
2869 else if (rule
->weight_
!= 1)
2870 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
2874 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
2875 HashProxy
proxy(local
.files
[signature
], save
);
2878 plist_to_xml(plist
, &xml
, &size
);
2879 _scope({ free(xml
); });
2880 put(proxy
, xml
, size
);
2884 bundle
.path
= folder
.Path(executable
);
2886 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2887 progress(root
+ executable
);
2888 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
2890 slots
[1] = local
.files
.at(info
);
2891 slots
[3] = local
.files
.at(signature
);
2892 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
2896 remote
.Merge(root
, local
);
2900 Bundle
Sign(const std::string
&root
, Folder
&folder
, const std::string
&key
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2902 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
2909 std::string
Hex(const uint8_t *data
, size_t size
) {
2911 hex
.reserve(size
* 2);
2912 for (size_t i(0); i
!= size
; ++i
) {
2913 hex
+= "0123456789abcdef"[data
[i
] >> 4];
2914 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
2919 static void usage(const char *argv0
) {
2920 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv0
);
2921 fprintf(stderr
, " %s -e MobileSafari\n", argv0
);
2922 fprintf(stderr
, " %s -S cat\n", argv0
);
2923 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv0
);
2926 #ifndef LDID_NOTOOLS
2927 int main(int argc
, char *argv
[]) {
2928 #ifndef LDID_NOSMIME
2929 OpenSSL_add_all_algorithms();
2937 little_
= endian
.byte
[0];
2946 #ifndef LDID_NOFLAGT
2964 bool platform(false);
2966 uint32_t flag_CPUType(_not(uint32_t));
2967 uint32_t flag_CPUSubtype(_not(uint32_t));
2969 const char *flag_I(NULL
);
2971 #ifndef LDID_NOFLAGT
2981 std::vector
<std::string
> files
;
2988 for (int argi(1); argi
!= argc
; ++argi
)
2989 if (argv
[argi
][0] != '-')
2990 files
.push_back(argv
[argi
]);
2991 else switch (argv
[argi
][1]) {
2998 case 'e': flag_e
= true; break;
3001 const char *string
= argv
[argi
] + 2;
3002 const char *colon
= strchr(string
, ':');
3003 _assert(colon
!= NULL
);
3004 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3006 unsigned number(strtoul(string
, &arge
, 0));
3007 _assert(arge
== colon
);
3008 auto &slot(slots
[number
]);
3009 for (Algorithm
*algorithm
: GetAlgorithms())
3010 (*algorithm
)(slot
, file
.data(), file
.size());
3013 case 'q': flag_q
= true; break;
3016 const char *hash
= argv
[argi
] + 2;
3024 fprintf(stderr
, "WARNING: -H is only present for compatibility with a fork of ldid\n");
3025 fprintf(stderr
, " you should NOT be manually specifying the hash algorithm\n");
3029 else if (strcmp(hash
, "sha1") == 0)
3031 else if (strcmp(hash
, "sha256") == 0)
3033 else _assert(false);
3036 case 'h': flag_h
= true; break;
3039 const char *xml
= argv
[argi
] + 2;
3040 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3043 case 'D': flag_D
= true; break;
3044 case 'd': flag_d
= true; break;
3046 case 'a': flag_a
= true; break;
3051 if (argv
[argi
][2] != '\0') {
3052 const char *cpu
= argv
[argi
] + 2;
3053 const char *colon
= strchr(cpu
, ':');
3054 _assert(colon
!= NULL
);
3056 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3057 _assert(arge
== colon
);
3058 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3059 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3064 const char *name
= argv
[argi
] + 2;
3066 else if (strcmp(name
, "host") == 0)
3067 flags
|= kSecCodeSignatureHost
;
3068 else if (strcmp(name
, "adhoc") == 0)
3069 flags
|= kSecCodeSignatureAdhoc
;
3070 else if (strcmp(name
, "hard") == 0)
3071 flags
|= kSecCodeSignatureForceHard
;
3072 else if (strcmp(name
, "kill") == 0)
3073 flags
|= kSecCodeSignatureForceKill
;
3074 else if (strcmp(name
, "expires") == 0)
3075 flags
|= kSecCodeSignatureForceExpiration
;
3076 else if (strcmp(name
, "restrict") == 0)
3077 flags
|= kSecCodeSignatureRestrict
;
3078 else if (strcmp(name
, "enforcement") == 0)
3079 flags
|= kSecCodeSignatureEnforcement
;
3080 else if (strcmp(name
, "library-validation") == 0)
3081 flags
|= kSecCodeSignatureLibraryValidation
;
3082 else if (strcmp(name
, "runtime") == 0)
3083 flags
|= kSecCodeSignatureRuntime
;
3084 else _assert(false);
3101 if (argv
[argi
][2] != '\0') {
3102 const char *xml
= argv
[argi
] + 2;
3103 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3112 if (argv
[argi
][2] != '\0')
3113 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3116 #ifndef LDID_NOFLAGT
3119 if (argv
[argi
][2] == '-')
3123 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
3124 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3134 flag_I
= argv
[argi
] + 2;
3143 _assert(flag_S
|| key
.empty());
3144 _assert(flag_S
|| flag_I
== NULL
);
3146 if (flag_d
&& !flag_h
) {
3148 fprintf(stderr
, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3154 size_t filei(0), filee(0);
3155 _foreach (file
, files
) try {
3156 std::string
path(file
);
3159 _syscall(stat(path
.c_str(), &info
));
3161 if (S_ISDIR(info
.st_mode
)) {
3163 #ifndef LDID_NOPLIST
3164 ldid::DiskFolder
folder(path
+ "/");
3165 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3169 } else if (flag_S
|| flag_r
) {
3170 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3172 std::filebuf output
;
3174 auto temp(Temporary(output
, split
));
3177 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3179 std::string
identifier(flag_I
?: split
.base
.c_str());
3180 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3187 #ifndef LDID_NOFLAGT
3194 Map
mapping(path
, modify
);
3195 FatHeader
fat_header(mapping
.data(), mapping
.size());
3197 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3198 struct linkedit_data_command
*signature(NULL
);
3199 struct encryption_info_command
*encryption(NULL
);
3202 if (mach_header
.GetCPUType() != flag_CPUType
)
3204 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3209 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3211 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3212 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3215 else if (cmd
== LC_CODE_SIGNATURE
)
3216 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3217 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3218 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3219 else if (cmd
== LC_LOAD_DYLIB
) {
3220 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3221 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3223 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3226 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3227 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3231 #ifndef LDID_NOFLAGT
3232 else if (cmd
== LC_ID_DYLIB
) {
3233 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3241 dylib_command
->dylib
.timestamp
= 0;
3242 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
3245 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
3251 if (flag_d
&& encryption
!= NULL
) {
3252 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3256 _assert(encryption
!= NULL
);
3257 encryption
->cryptid
= mach_header
.Swap(0);
3261 _assert(signature
!= NULL
);
3263 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3265 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3266 uint8_t *blob
= top
+ data
;
3267 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3269 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3270 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3271 uint32_t begin
= Swap(super
->index
[index
].offset
);
3272 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3273 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3278 _assert(signature
!= NULL
);
3280 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3282 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3283 uint8_t *blob
= top
+ data
;
3284 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3286 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3287 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3288 uint32_t begin
= Swap(super
->index
[index
].offset
);
3289 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3290 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3295 _assert(signature
!= NULL
);
3297 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3299 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3300 uint8_t *blob
= top
+ data
;
3301 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3303 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3304 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
3305 uint32_t begin
= Swap(super
->index
[index
].offset
);
3306 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3308 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
3309 uint32_t pages
= Swap(directory
->nCodeSlots
);
3312 for (size_t i
= 0; i
!= pages
- 1; ++i
)
3313 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
3315 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
3320 _assert(signature
!= NULL
);
3322 auto algorithms(GetAlgorithms());
3324 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3326 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3327 uint8_t *blob
= top
+ data
;
3328 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3331 CodeDirectory
*directory_
;
3333 Algorithm
&algorithm_
;
3337 std::map
<uint8_t, Candidate
> candidates
;
3339 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3340 auto type(Swap(super
->index
[index
].type
));
3341 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3342 uint32_t begin
= Swap(super
->index
[index
].offset
);
3343 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3344 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3345 auto type(directory
->hashType
);
3346 _assert(type
> 0 && type
<= algorithms
.size());
3347 auto &algorithm(*algorithms
[type
- 1]);
3348 uint8_t hash
[algorithm
.size_
];
3349 algorithm(hash
, blob
+ begin
, end
- begin
);
3350 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20)}});
3354 _assert(!candidates
.empty());
3355 auto best(candidates
.end());
3358 const auto directory(best
->second
.directory_
);
3359 const auto flags(Swap(directory
->flags
));
3362 if (flags
& kSecCodeSignatureHost
)
3364 if (flags
& kSecCodeSignatureAdhoc
)
3366 if (flags
& kSecCodeSignatureForceHard
)
3368 if (flags
& kSecCodeSignatureForceKill
)
3370 if (flags
& kSecCodeSignatureForceExpiration
)
3371 names
+= ",expires";
3372 if (flags
& kSecCodeSignatureRestrict
)
3373 names
+= ",restrict";
3374 if (flags
& kSecCodeSignatureEnforcement
)
3375 names
+= ",enforcement";
3376 if (flags
& kSecCodeSignatureLibraryValidation
)
3377 names
+= ",library-validation";
3378 if (flags
& kSecCodeSignatureRuntime
)
3379 names
+= ",runtime";
3381 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3382 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3383 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3385 std::string choices
;
3386 for (const auto &candidate
: candidates
) {
3387 auto choice(candidate
.second
.algorithm_
.name());
3390 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3392 printf("Hash choices=%s\n", choices
.c_str() + 1);
3394 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3399 } catch (const char *) {