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 put(std::streambuf
&stream
, uint8_t value
) {
519 _assert(stream
.sputc(value
) != EOF
);
522 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
523 _assert(read(stream
, data
, size
) == size
);
526 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
527 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
530 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
532 for (size_t total(0); total
!= size
;) {
533 auto writ(std::min(size
- total
, size_t(4096 * 4)));
534 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
536 progress(double(total
) / size
);
540 static inline void put(std::streambuf
&stream
, const std::string
&data
) {
541 return put(stream
, data
.data(), data
.size());
544 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
547 if (auto writ
= read(stream
, data
, size
))
553 static inline void pad(std::streambuf
&stream
, size_t size
) {
555 memset(padding
, 0, size
);
556 put(stream
, padding
, size
);
559 template <typename Type_
>
560 Type_
Align(Type_ value
, size_t align
) {
567 static const uint8_t PageShift_(0x0c);
568 static const uint32_t PageSize_(1 << PageShift_
);
570 static inline unsigned bytes(uint64_t value
) {
571 return (64 - __builtin_clzll(value
) + 7) / 8;
574 static void put(std::streambuf
&stream
, uint64_t value
, size_t length
) {
576 do put(stream
, uint8_t(value
>> (length
-= 8)));
580 static void der(std::streambuf
&stream
, uint64_t value
) {
584 unsigned length(bytes(value
));
585 put(stream
, 0x80 | length
);
586 put(stream
, value
, length
);
590 static std::string
der(uint8_t tag
, const char *value
, size_t length
) {
594 put(data
, value
, length
);
598 static std::string
der(uint8_t tag
, const char *value
) {
599 return der(tag
, value
, strlen(value
)); }
600 static std::string
der(uint8_t tag
, const std::string
&value
) {
601 return der(tag
, value
.data(), value
.size()); }
603 template <typename Type_
>
604 static void der_(std::stringbuf
&data
, const Type_
&values
) {
606 for (const auto &value
: values
)
607 size
+= value
.size();
609 for (const auto &value
: values
)
613 static std::string
der(const std::vector
<std::string
> &values
) {
620 static std::string
der(const std::multiset
<std::string
> &values
) {
627 static std::string
der(const std::pair
<std::string
, std::string
> &value
) {
628 const auto key(der(0x0c, value
.first
));
631 der(data
, key
.size() + value
.second
.size());
633 put(data
, value
.second
);
638 static std::string
der(plist_t data
) {
639 switch (const auto type
= plist_get_node_type(data
)) {
640 case PLIST_BOOLEAN
: {
642 plist_get_bool_val(data
, &value
);
647 put(data
, value
!= 0 ? 1 : 0);
653 plist_get_uint_val(data
, &value
);
654 const auto length(bytes(value
));
659 put(data
, value
, length
);
674 plist_get_data_val(data
, &value
, &length
);
675 _scope({ free(value
); });
676 return der(0x04, value
, length
);
681 plist_get_string_val(data
, &value
);
682 _scope({ free(value
); });
683 return der(0x0c, value
);
687 std::vector
<std::string
> values
;
688 for (auto e(plist_array_get_size(data
)), i(decltype(e
)(0)); i
!= e
; ++i
)
689 values
.push_back(der(plist_array_get_item(data
, i
)));
694 std::multiset
<std::string
> values
;
696 plist_dict_iter
iterator(NULL
);
697 plist_dict_new_iter(data
, &iterator
);
698 _scope({ free(iterator
); });
703 plist_dict_next_item(data
, iterator
, &key
, &value
);
706 _scope({ free(key
); });
707 values
.insert(der(std::make_pair(key
, der(value
))));
714 _assert_(false, "unsupported plist type %d", type
);
720 static inline uint16_t Swap_(uint16_t value
) {
722 ((value
>> 8) & 0x00ff) |
723 ((value
<< 8) & 0xff00);
726 static inline uint32_t Swap_(uint32_t value
) {
727 value
= ((value
>> 8) & 0x00ff00ff) |
728 ((value
<< 8) & 0xff00ff00);
729 value
= ((value
>> 16) & 0x0000ffff) |
730 ((value
<< 16) & 0xffff0000);
734 static inline uint64_t Swap_(uint64_t value
) {
735 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
736 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
737 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
741 static inline int16_t Swap_(int16_t value
) {
742 return Swap_(static_cast<uint16_t>(value
));
745 static inline int32_t Swap_(int32_t value
) {
746 return Swap_(static_cast<uint32_t>(value
));
749 static inline int64_t Swap_(int64_t value
) {
750 return Swap_(static_cast<uint64_t>(value
));
753 static bool little_(true);
755 static inline uint16_t Swap(uint16_t value
) {
756 return little_
? Swap_(value
) : value
;
759 static inline uint32_t Swap(uint32_t value
) {
760 return little_
? Swap_(value
) : value
;
763 static inline uint64_t Swap(uint64_t value
) {
764 return little_
? Swap_(value
) : value
;
767 static inline int16_t Swap(int16_t value
) {
768 return Swap(static_cast<uint16_t>(value
));
771 static inline int32_t Swap(int32_t value
) {
772 return Swap(static_cast<uint32_t>(value
));
775 static inline int64_t Swap(int64_t value
) {
776 return Swap(static_cast<uint64_t>(value
));
789 Swapped(bool swapped
) :
794 template <typename Type_
>
795 Type_
Swap(Type_ value
) const {
796 return swapped_
? Swap_(value
) : value
;
808 Data(void *base
, size_t size
) :
814 void *GetBase() const {
818 size_t GetSize() const {
829 struct mach_header
*mach_header_
;
830 struct load_command
*load_command_
;
833 MachHeader(void *base
, size_t size
) :
836 mach_header_
= (mach_header
*) base
;
838 switch (Swap(mach_header_
->magic
)) {
840 swapped_
= !swapped_
;
846 swapped_
= !swapped_
;
855 void *post
= mach_header_
+ 1;
857 post
= (uint32_t *) post
+ 1;
858 load_command_
= (struct load_command
*) post
;
861 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
862 Swap(mach_header_
->filetype
) == MH_DYLIB
||
863 Swap(mach_header_
->filetype
) == MH_DYLINKER
||
864 Swap(mach_header_
->filetype
) == MH_BUNDLE
868 bool Bits64() const {
872 struct mach_header
*operator ->() const {
876 operator struct mach_header
*() const {
880 uint32_t GetCPUType() const {
881 return Swap(mach_header_
->cputype
);
884 uint32_t GetCPUSubtype() const {
885 return Swap(mach_header_
->cpusubtype
) & 0xff;
888 struct load_command
*GetLoadCommand() const {
889 return load_command_
;
892 std::vector
<struct load_command
*> GetLoadCommands() const {
893 std::vector
<struct load_command
*> load_commands
;
895 struct load_command
*load_command
= load_command_
;
896 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
897 load_commands
.push_back(load_command
);
898 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
901 return load_commands
;
904 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
905 _foreach (load_command
, GetLoadCommands())
906 switch (Swap(load_command
->cmd
)) {
908 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
909 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
910 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
911 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
912 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
915 case LC_SEGMENT_64
: {
916 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
917 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
918 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
919 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
920 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
925 template <typename Target_
>
926 Target_
*GetOffset(uint32_t offset
) const {
927 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
931 class FatMachHeader
:
938 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
939 MachHeader(base
, size
),
944 fat_arch
*GetFatArch() const {
953 fat_header
*fat_header_
;
954 std::vector
<FatMachHeader
> mach_headers_
;
957 FatHeader(void *base
, size_t size
) :
960 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
962 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
963 swapped_
= !swapped_
;
965 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
967 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
969 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
970 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
972 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
973 uint32_t arch_offset
= Swap(fat_arch
->offset
);
974 uint32_t arch_size
= Swap(fat_arch
->size
);
975 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
981 std::vector
<FatMachHeader
> &GetMachHeaders() {
982 return mach_headers_
;
986 return fat_header_
!= NULL
;
989 struct fat_header
*operator ->() const {
993 operator struct fat_header
*() const {
998 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
999 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
1000 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
1001 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
1002 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
1003 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
1004 #define CSMAGIC_EMBEDDED_DERFORMAT uint32_t(0xfade7172) // name?
1005 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
1006 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
1008 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
1009 #define CSSLOT_INFOSLOT uint32_t(0x00001)
1010 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
1011 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
1012 #define CSSLOT_APPLICATION uint32_t(0x00004)
1013 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
1014 #define CSSLOT_REPSPECIFIC uint32_t(0x00006) // name?
1015 #define CSSLOT_DERFORMAT uint32_t(0x00007) // name?
1016 #define CSSLOT_ALTERNATE uint32_t(0x01000)
1018 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
1020 #define CS_HASHTYPE_SHA160_160 1
1021 #define CS_HASHTYPE_SHA256_256 2
1022 #define CS_HASHTYPE_SHA256_160 3
1023 #define CS_HASHTYPE_SHA386_386 4
1026 #define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
1027 #define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
1028 #define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
1029 #define CS_EXECSEG_JIT 0x040 /* JIT enabled */
1030 #define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
1031 #define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
1032 #define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
1034 enum SecCodeExecSegFlags
{
1035 kSecCodeExecSegMainBinary
= 0x001,
1036 kSecCodeExecSegAllowUnsigned
= 0x010,
1037 kSecCodeExecSegDebugger
= 0x020,
1038 kSecCodeExecSegJit
= 0x040,
1039 kSecCodeExecSegSkipLibraryVal
= 0x080,
1040 kSecCodeExecSegCanLoadCdHash
= 0x100,
1041 kSecCodeExecSegCanExecCdHash
= 0x100,
1058 struct BlobIndex index
[];
1061 struct CodeDirectory
{
1064 uint32_t hashOffset
;
1065 uint32_t identOffset
;
1066 uint32_t nSpecialSlots
;
1067 uint32_t nCodeSlots
;
1074 uint32_t scatterOffset
;
1075 uint32_t teamIDOffset
;
1077 uint64_t codeLimit64
;
1078 uint64_t execSegBase
;
1079 uint64_t execSegLimit
;
1080 uint64_t execSegFlags
;
1081 #if 0 // version = 0x20500
1083 uint32_t preEncryptOffset
;
1085 #if 0 // version = 0x20600
1086 uint8_t linkageHashType
;
1087 uint8_t linkageTruncated
;
1089 uint32_t linkageOffset
;
1090 uint32_t linkageSize
;
1094 enum CodeSignatureFlags
{
1095 kSecCodeSignatureHost
= 0x0001,
1096 kSecCodeSignatureAdhoc
= 0x0002,
1097 kSecCodeSignatureForceHard
= 0x0100,
1098 kSecCodeSignatureForceKill
= 0x0200,
1099 kSecCodeSignatureForceExpiration
= 0x0400,
1100 kSecCodeSignatureRestrict
= 0x0800,
1101 kSecCodeSignatureEnforcement
= 0x1000,
1102 kSecCodeSignatureLibraryValidation
= 0x2000,
1103 kSecCodeSignatureRuntime
= 0x10000,
1106 enum Kind
: uint32_t {
1107 exprForm
= 1, // prefix expr form
1110 enum ExprOp
: uint32_t {
1111 opFalse
, // unconditionally false
1112 opTrue
, // unconditionally true
1113 opIdent
, // match canonical code [string]
1114 opAppleAnchor
, // signed by Apple as Apple's product
1115 opAnchorHash
, // match anchor [cert hash]
1116 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
1117 opAnd
, // binary prefix expr AND expr [expr; expr]
1118 opOr
, // binary prefix expr OR expr [expr; expr]
1119 opCDHash
, // match hash of CodeDirectory directly [cd hash]
1120 opNot
, // logical inverse [expr]
1121 opInfoKeyField
, // Info.plist key field [string; match suffix]
1122 opCertField
, // Certificate field [cert index; field name; match suffix]
1123 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
1124 opTrustedCerts
, // require trust settings to approve the cert chain
1125 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
1126 opAppleGenericAnchor
, // signed by Apple in any capacity
1127 opEntitlementField
, // entitlement dictionary field [string; match suffix]
1128 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
1129 opNamedAnchor
, // named anchor type
1130 opNamedCode
, // named subroutine
1131 opPlatform
, // platform constraint [integer]
1132 exprOpCount
// (total opcode count in use)
1135 enum MatchOperation
{
1136 matchExists
, // anything but explicit "false" - no value stored
1137 matchEqual
, // equal (CFEqual)
1138 matchContains
, // partial match (substring)
1139 matchBeginsWith
, // partial match (initial substring)
1140 matchEndsWith
, // partial match (terminal substring)
1141 matchLessThan
, // less than (string with numeric comparison)
1142 matchGreaterThan
, // greater than (string with numeric comparison)
1143 matchLessEqual
, // less or equal (string with numeric comparison)
1144 matchGreaterEqual
, // greater or equal (string with numeric comparison)
1147 #define OID_ISO_MEMBER 42
1148 #define OID_US OID_ISO_MEMBER, 134, 72
1149 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
1150 #define APPLE_ADS_OID APPLE_OID, 0x64
1151 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
1153 #ifndef LDID_NOFLAGT
1154 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
1161 Algorithm(size_t size
, uint8_t type
) :
1167 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
1169 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
1170 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
1171 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
1173 virtual const char *name() = 0;
1176 struct AlgorithmSHA1
:
1180 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
)
1184 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1188 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1189 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
1192 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1193 return operator()(hash
.sha1_
, data
, size
);
1196 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1197 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1198 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1201 virtual const char *name() {
1206 struct AlgorithmSHA256
:
1210 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
)
1214 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1215 return hash
.sha256_
;
1218 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1219 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1222 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1223 return operator()(hash
.sha256_
, data
, size
);
1226 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1227 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1228 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1231 virtual const char *name() {
1236 static bool do_sha1(true);
1237 static bool do_sha256(true);
1239 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1240 static AlgorithmSHA1 sha1
;
1241 static AlgorithmSHA256 sha256
;
1243 static std::vector
<Algorithm
*> algorithms
;
1244 if (algorithms
.empty()) {
1246 algorithms
.push_back(&sha1
);
1248 algorithms
.push_back(&sha256
);
1255 std::string entitlements_
;
1256 std::string derformat_
;
1259 struct CodesignAllocation
{
1260 FatMachHeader mach_header_
;
1269 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
) :
1270 mach_header_(mach_header
),
1282 #ifndef LDID_NOTOOLS
1295 _syscall(close(file_
));
1298 void open(const char *path
, int flags
) {
1299 _assert(file_
== -1);
1300 file_
= _syscall(::open(path
, flags
));
1317 _syscall(munmap(data_
, size_
));
1329 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1332 open(path
, oflag
, pflag
, mflag
);
1335 Map(const std::string
&path
, bool edit
) :
1345 bool empty() const {
1346 return data_
== NULL
;
1349 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1352 file_
.open(path
.c_str(), oflag
);
1353 int file(file_
.file());
1356 _syscall(fstat(file
, &stat
));
1357 size_
= stat
.st_size
;
1359 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1362 void open(const std::string
&path
, bool edit
) {
1364 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1366 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1369 void *data() const {
1373 size_t size() const {
1377 operator std::string() const {
1378 return std::string(static_cast<char *>(data_
), size_
);
1385 #ifndef LDID_NOPLIST
1386 static plist_t
plist(const std::string
&data
);
1389 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1390 _foreach (load_command
, mach_header
.GetLoadCommands())
1391 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1392 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1393 auto offset(mach_header
.Swap(signature
->dataoff
));
1394 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1395 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1397 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1398 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1399 auto begin(Swap(super
->index
[index
].offset
));
1400 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1401 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1402 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1407 std::string
Analyze(const void *data
, size_t size
) {
1408 std::string entitlements
;
1410 FatHeader
fat_header(const_cast<void *>(data
), size
);
1411 _foreach (mach_header
, fat_header
.GetMachHeaders())
1412 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1413 if (entitlements
.empty())
1414 entitlements
.assign(data
, size
);
1416 _assert(entitlements
.compare(0, entitlements
.size(), data
, size
) == 0);
1419 return entitlements
;
1422 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
) {
1423 FatHeader
source(const_cast<void *>(idata
), isize
);
1427 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1429 std::vector
<CodesignAllocation
> allocations
;
1430 _foreach (mach_header
, source
.GetMachHeaders()) {
1431 struct linkedit_data_command
*signature(NULL
);
1432 struct symtab_command
*symtab(NULL
);
1434 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1435 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1437 else if (cmd
== LC_CODE_SIGNATURE
)
1438 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1439 else if (cmd
== LC_SYMTAB
)
1440 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1444 if (signature
== NULL
)
1445 size
= mach_header
.GetSize();
1447 size
= mach_header
.Swap(signature
->dataoff
);
1448 _assert(size
<= mach_header
.GetSize());
1451 if (symtab
!= NULL
) {
1452 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1453 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1454 _assert(end
<= size
);
1455 _assert(end
>= size
- 0x10);
1461 size_t alloc(allocate(mach_header
, baton
, size
));
1463 auto *fat_arch(mach_header
.GetFatArch());
1466 if (fat_arch
!= NULL
)
1467 align
= source
.Swap(fat_arch
->align
);
1468 else switch (mach_header
.GetCPUType()) {
1469 case CPU_TYPE_POWERPC
:
1470 case CPU_TYPE_POWERPC64
:
1472 case CPU_TYPE_X86_64
:
1476 case CPU_TYPE_ARM64
:
1484 const char *arch(NULL
);
1485 switch (mach_header
.GetCPUType()) {
1486 case CPU_TYPE_POWERPC
:
1489 case CPU_TYPE_POWERPC64
:
1495 case CPU_TYPE_X86_64
:
1501 case CPU_TYPE_ARM64
:
1506 offset
= Align(offset
, 1 << align
);
1508 uint32_t limit(size
);
1510 limit
= Align(limit
, 0x10);
1512 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1513 offset
+= size
+ alloc
;
1514 offset
= Align(offset
, 0x10);
1519 if (source
.IsFat()) {
1520 fat_header fat_header
;
1521 fat_header
.magic
= Swap(FAT_MAGIC
);
1522 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1523 put(output
, &fat_header
, sizeof(fat_header
));
1524 position
+= sizeof(fat_header
);
1526 // XXX: support fat_arch_64 (not in my toolchain)
1527 // probably use C++14 generic lambda (not in my toolchain)
1530 _foreach (allocation
, allocations
) {
1531 const auto offset(allocation
.offset_
);
1532 const auto size(allocation
.limit_
+ allocation
.alloc_
);
1533 if (uint32_t(offset
) != offset
|| uint32_t(size
) != size
)
1537 }(), "FAT slice >=4GiB not currently supported");
1539 _foreach (allocation
, allocations
) {
1540 auto &mach_header(allocation
.mach_header_
);
1543 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1544 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1545 fat_arch
.offset
= Swap(uint32_t(allocation
.offset_
));
1546 fat_arch
.size
= Swap(uint32_t(allocation
.limit_
+ allocation
.alloc_
));
1547 fat_arch
.align
= Swap(allocation
.align_
);
1548 put(output
, &fat_arch
, sizeof(fat_arch
));
1549 position
+= sizeof(fat_arch
);
1553 _foreach (allocation
, allocations
) {
1554 progress(allocation
.arch_
);
1555 auto &mach_header(allocation
.mach_header_
);
1557 pad(output
, allocation
.offset_
- position
);
1558 position
= allocation
.offset_
;
1563 std::vector
<std::string
> commands
;
1565 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1566 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1568 switch (mach_header
.Swap(load_command
->cmd
)) {
1569 case LC_CODE_SIGNATURE
:
1573 // XXX: this is getting ridiculous: provide a better abstraction
1576 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1578 if ((segment_command
->initprot
& 04) != 0) {
1579 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1580 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1587 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1588 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1589 segment_command
->filesize
= size
;
1590 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1594 case LC_SEGMENT_64
: {
1595 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1597 if ((segment_command
->initprot
& 04) != 0) {
1598 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1599 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1606 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1607 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1608 segment_command
->filesize
= size
;
1609 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1614 commands
.push_back(copy
);
1617 if (allocation
.alloc_
!= 0) {
1618 linkedit_data_command signature
;
1619 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1620 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1621 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1622 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1623 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1626 size_t begin(position
);
1629 _foreach(command
, commands
)
1630 after
+= command
.size();
1632 std::stringbuf altern
;
1634 struct mach_header
header(*mach_header
);
1635 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1636 header
.sizeofcmds
= mach_header
.Swap(after
);
1637 put(output
, &header
, sizeof(header
));
1638 put(altern
, &header
, sizeof(header
));
1639 position
+= sizeof(header
);
1641 if (mach_header
.Bits64()) {
1642 auto pad(mach_header
.Swap(uint32_t(0)));
1643 put(output
, &pad
, sizeof(pad
));
1644 put(altern
, &pad
, sizeof(pad
));
1645 position
+= sizeof(pad
);
1648 _foreach(command
, commands
) {
1649 put(output
, command
.data(), command
.size());
1650 put(altern
, command
.data(), command
.size());
1651 position
+= command
.size();
1654 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1655 if (before
> after
) {
1656 pad(output
, before
- after
);
1657 pad(altern
, before
- after
);
1658 position
+= before
- after
;
1661 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1663 std::string
overlap(altern
.str());
1664 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1666 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1667 position
= begin
+ allocation
.size_
;
1669 pad(output
, allocation
.limit_
- allocation
.size_
);
1670 position
+= allocation
.limit_
- allocation
.size_
;
1672 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, left
, right
, overlap
, top
, progress
));
1673 if (allocation
.alloc_
> saved
)
1674 pad(output
, allocation
.alloc_
- saved
);
1676 _assert(allocation
.alloc_
== saved
);
1677 position
+= allocation
.alloc_
;
1683 typedef std::map
<uint32_t, std::string
> Blobs
;
1685 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1686 auto value(buffer
.str());
1687 std::swap(blobs
[slot
], value
);
1690 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1691 auto value(buffer
.str());
1693 blob
.magic
= Swap(magic
);
1694 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1695 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1696 auto &save(blobs
[slot
]);
1697 std::swap(save
, value
);
1701 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1703 _foreach (blob
, blobs
)
1704 total
+= blob
.second
.size();
1706 struct SuperBlob super
;
1707 super
.blob
.magic
= Swap(magic
);
1708 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1709 super
.count
= Swap(uint32_t(blobs
.size()));
1710 put(output
, &super
, sizeof(super
));
1712 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1714 _foreach (blob
, blobs
) {
1716 index
.type
= Swap(blob
.first
);
1717 index
.offset
= Swap(uint32_t(offset
));
1718 put(output
, &index
, sizeof(index
));
1719 offset
+= blob
.second
.size();
1722 _foreach (blob
, blobs
)
1723 put(output
, blob
.second
.data(), blob
.second
.size());
1728 #ifndef LDID_NOSMIME
1737 _assert(bio_
!= NULL
);
1741 bio_(BIO_new(BIO_s_mem()))
1745 Buffer(const char *data
, size_t size
) :
1746 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1750 Buffer(const std::string
&data
) :
1751 Buffer(data
.data(), data
.size())
1755 Buffer(PKCS7
*pkcs
) :
1758 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1765 operator BIO
*() const {
1769 explicit operator std::string() const {
1771 auto size(BIO_get_mem_data(bio_
, &data
));
1772 return std::string(data
, size
);
1781 STACK_OF(X509
) *ca_
;
1785 value_(d2i_PKCS12_bio(bio
, NULL
)),
1788 _assert(value_
!= NULL
);
1789 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1791 _assert(key_
!= NULL
);
1792 _assert(cert_
!= NULL
);
1795 ca_
= sk_X509_new_null();
1796 _assert(ca_
!= NULL
);
1799 Stuff(const std::string
&data
) :
1805 sk_X509_pop_free(ca_
, X509_free
);
1807 EVP_PKEY_free(key_
);
1808 PKCS12_free(value_
);
1811 operator PKCS12
*() const {
1815 operator EVP_PKEY
*() const {
1819 operator X509
*() const {
1823 operator STACK_OF(X509
) *() const {
1833 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
) {
1834 value_
= PKCS7_new();
1835 _assert(value_
!= NULL
);
1837 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1838 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1840 STACK_OF(X509
) *certs(stuff
);
1841 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1842 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1844 // XXX: this is the same as PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP)
1845 _assert(X509_check_private_key(stuff
, stuff
));
1846 auto info(PKCS7_add_signature(value_
, stuff
, stuff
, EVP_sha1()));
1847 _assert(info
!= NULL
);
1848 _assert(PKCS7_add_certificate(value_
, stuff
));
1849 _assert(PKCS7_add_signed_attribute(info
, NID_pkcs9_contentType
, V_ASN1_OBJECT
, OBJ_nid2obj(NID_pkcs7_data
)));
1851 PKCS7_set_detached(value_
, 1);
1853 ASN1_OCTET_STRING
*string(ASN1_OCTET_STRING_new());
1854 _assert(string
!= NULL
);
1856 _assert(ASN1_STRING_set(string
, xml
.data(), xml
.size()));
1858 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1859 _assert(PKCS7_add_signed_attribute(info
, nid
, V_ASN1_OCTET_STRING
, string
));
1861 ASN1_OCTET_STRING_free(string
);
1865 // XXX: this is the same as PKCS7_final(value_, data, PKCS7_BINARY)
1866 BIO
*bio(PKCS7_dataInit(value_
, NULL
));
1867 _assert(bio
!= NULL
);
1868 _scope({ BIO_free_all(bio
); });
1869 SMIME_crlf_copy(data
, bio
, PKCS7_BINARY
);
1871 _assert(PKCS7_dataFinal(value_
, bio
));
1878 operator PKCS7
*() const {
1885 public std::streambuf
1888 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1892 virtual int_type
overflow(int_type next
) {
1898 public std::streambuf
1903 LDID_SHA1_CTX sha1_
;
1904 LDID_SHA256_CTX sha256_
;
1907 HashBuffer(ldid::Hash
&hash
) :
1910 LDID_SHA1_Init(&sha1_
);
1911 LDID_SHA256_Init(&sha256_
);
1915 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
1916 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
1919 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1920 LDID_SHA1_Update(&sha1_
, data
, size
);
1921 LDID_SHA256_Update(&sha256_
, data
, size
);
1925 virtual int_type
overflow(int_type next
) {
1926 if (next
== traits_type::eof())
1938 std::streambuf
&buffer_
;
1941 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
1947 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1948 _assert(HashBuffer::xsputn(data
, size
) == size
);
1949 return buffer_
.sputn(data
, size
);
1953 #ifndef LDID_NOTOOLS
1954 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1955 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1963 Split(const std::string
&path
) {
1964 size_t slash(path
.rfind('/'));
1965 if (slash
== std::string::npos
)
1968 dir
= path
.substr(0, slash
+ 1);
1969 base
= path
.substr(slash
+ 1);
1974 static void mkdir_p(const std::string
&path
) {
1978 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
1981 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1984 auto slash(path
.rfind('/', path
.size() - 1));
1985 if (slash
== std::string::npos
)
1987 mkdir_p(path
.substr(0, slash
));
1990 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1991 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1993 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1997 static void Commit(const std::string
&path
, const std::string
&temp
) {
1999 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
2001 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
2003 _syscall(chmod(temp
.c_str(), info
.st_mode
));
2006 _syscall(rename(temp
.c_str(), path
.c_str()));
2012 #ifndef LDID_NOSMIME
2013 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
2014 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
2015 _assert(index
>= 0);
2016 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
2017 _assert(next
== -1);
2018 auto entry(X509_NAME_get_entry(name
, index
));
2019 _assert(entry
!= NULL
);
2020 auto asn(X509_NAME_ENTRY_get_data(entry
));
2021 _assert(asn
!= NULL
);
2022 value
.assign(reinterpret_cast<const char *>(ASN1_STRING_get0_data(asn
)), ASN1_STRING_length(asn
));
2026 static void req(std::streambuf
&buffer
, uint32_t value
) {
2027 value
= Swap(value
);
2028 put(buffer
, &value
, sizeof(value
));
2031 static void req(std::streambuf
&buffer
, const std::string
&value
) {
2032 req(buffer
, value
.size());
2033 put(buffer
, value
.data(), value
.size());
2034 static uint8_t zeros
[] = {0,0,0,0};
2035 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
2038 template <size_t Size_
>
2039 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
2041 put(buffer
, data
, Size_
);
2042 static uint8_t zeros
[] = {0,0,0,0};
2043 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
2046 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
) {
2053 #ifndef LDID_NOSMIME
2056 auto name(X509_get_subject_name(stuff
));
2057 _assert(name
!= NULL
);
2058 get(team
, name
, NID_organizationalUnitName
);
2059 get(common
, name
, NID_commonName
);
2064 std::stringbuf backing
;
2066 if (!requirements
.empty()) {
2067 put(backing
, requirements
.data(), requirements
.size());
2071 std::stringbuf requirement
;
2072 req(requirement
, exprForm
);
2073 req(requirement
, opAnd
);
2074 req(requirement
, opIdent
);
2075 req(requirement
, identifier
);
2076 req(requirement
, opAnd
);
2077 req(requirement
, opAppleGenericAnchor
);
2078 req(requirement
, opAnd
);
2079 req(requirement
, opCertField
);
2080 req(requirement
, 0);
2081 req(requirement
, "subject.CN");
2082 req(requirement
, matchEqual
);
2083 req(requirement
, common
);
2084 req(requirement
, opCertGeneric
);
2085 req(requirement
, 1);
2086 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
2087 req(requirement
, matchExists
);
2088 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
2090 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
2094 // XXX: this is just a "sufficiently large number"
2095 size_t certificate(0x3000);
2097 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2098 size_t alloc(sizeof(struct SuperBlob
));
2100 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
2102 uint32_t special(0);
2104 _foreach (slot
, slots
)
2105 special
= std::max(special
, slot
.first
);
2107 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2108 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
2109 special
= std::max(special
, CSSLOT_INFOSLOT
);
2112 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
2113 alloc
+= sizeof(struct BlobIndex
);
2114 alloc
+= backing
.str().size();
2117 baton
.entitlements_
= entitlements
;
2120 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
2121 baton
.entitlements_
.assign(data
, size
);
2124 if (!baton
.entitlements_
.empty() || !entitlements
.empty()) {
2125 auto combined(plist(baton
.entitlements_
));
2126 _scope({ plist_free(combined
); });
2127 _assert(plist_get_node_type(combined
) == PLIST_DICT
);
2129 auto merging(plist(entitlements
));
2130 _scope({ plist_free(merging
); });
2131 _assert(plist_get_node_type(merging
) == PLIST_DICT
);
2133 plist_dict_iter
iterator(NULL
);
2134 plist_dict_new_iter(merging
, &iterator
);
2135 _scope({ free(iterator
); });
2139 plist_t
value(NULL
);
2140 plist_dict_next_item(merging
, iterator
, &key
, &value
);
2143 _scope({ free(key
); });
2144 plist_dict_set_item(combined
, key
, plist_copy(value
));
2147 baton
.derformat_
= der(combined
);
2151 plist_to_xml(combined
, &xml
, &size
);
2152 _scope({ free(xml
); });
2154 baton
.entitlements_
.assign(xml
, size
);
2158 if (!baton
.entitlements_
.empty()) {
2159 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2160 alloc
+= sizeof(struct BlobIndex
);
2161 alloc
+= sizeof(struct Blob
);
2162 alloc
+= baton
.entitlements_
.size();
2165 if (!baton
.derformat_
.empty()) {
2166 special
= std::max(special
, CSSLOT_DERFORMAT
);
2167 alloc
+= sizeof(struct BlobIndex
);
2168 alloc
+= sizeof(struct Blob
);
2169 alloc
+= baton
.derformat_
.size();
2172 size_t directory(0);
2174 directory
+= sizeof(struct BlobIndex
);
2175 directory
+= sizeof(struct Blob
);
2176 directory
+= sizeof(struct CodeDirectory
);
2177 directory
+= identifier
.size() + 1;
2180 directory
+= team
.size() + 1;
2182 for (Algorithm
*algorithm
: GetAlgorithms())
2183 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2185 #ifndef LDID_NOSMIME
2187 alloc
+= sizeof(struct BlobIndex
);
2188 alloc
+= sizeof(struct Blob
);
2189 alloc
+= certificate
;
2194 }), 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 {
2198 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2202 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2203 execs
|= kSecCodeExecSegMainBinary
;
2205 if (!baton
.entitlements_
.empty()) {
2206 std::stringbuf data
;
2207 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2208 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2210 #ifndef LDID_NOPLIST
2211 auto entitlements(plist(baton
.entitlements_
));
2212 _scope({ plist_free(entitlements
); });
2213 _assert(plist_get_node_type(entitlements
) == PLIST_DICT
);
2215 const auto entitled([&](const char *key
) {
2216 auto item(plist_dict_get_item(entitlements
, key
));
2217 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2220 plist_get_bool_val(item
, &value
);
2224 if (entitled("get-task-allow"))
2225 execs
|= kSecCodeExecSegAllowUnsigned
;
2226 if (entitled("run-unsigned-code"))
2227 execs
|= kSecCodeExecSegAllowUnsigned
;
2228 if (entitled("com.apple.private.cs.debugger"))
2229 execs
|= kSecCodeExecSegDebugger
;
2230 if (entitled("dynamic-codesigning"))
2231 execs
|= kSecCodeExecSegJit
;
2232 if (entitled("com.apple.private.skip-library-validation"))
2233 execs
|= kSecCodeExecSegSkipLibraryVal
;
2234 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2235 execs
|= kSecCodeExecSegCanLoadCdHash
;
2236 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2237 execs
|= kSecCodeExecSegCanExecCdHash
;
2241 if (!baton
.derformat_
.empty()) {
2242 std::stringbuf data
;
2243 put(data
, baton
.derformat_
.data(), baton
.derformat_
.size());
2244 insert(blobs
, CSSLOT_DERFORMAT
, CSMAGIC_EMBEDDED_DERFORMAT
, data
);
2249 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2250 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2251 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2252 for (Algorithm
*algorithm
: GetAlgorithms())
2253 (*algorithm
)(slot
, data
, size
);
2258 for (Algorithm
*pointer
: GetAlgorithms()) {
2259 Algorithm
&algorithm(*pointer
);
2261 std::stringbuf data
;
2263 uint32_t special(0);
2264 _foreach (blob
, blobs
)
2265 special
= std::max(special
, blob
.first
);
2266 _foreach (slot
, posts
)
2267 special
= std::max(special
, slot
.first
);
2268 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2270 CodeDirectory directory
;
2271 directory
.version
= Swap(uint32_t(0x00020400));
2272 directory
.flags
= Swap(uint32_t(flags
));
2273 directory
.nSpecialSlots
= Swap(special
);
2274 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2275 directory
.nCodeSlots
= Swap(normal
);
2276 directory
.hashSize
= algorithm
.size_
;
2277 directory
.hashType
= algorithm
.type_
;
2278 directory
.platform
= platform
? 0x01 : 0x00;
2279 directory
.pageSize
= PageShift_
;
2280 directory
.spare2
= Swap(uint32_t(0));
2281 directory
.scatterOffset
= Swap(uint32_t(0));
2282 directory
.spare3
= Swap(uint32_t(0));
2283 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2284 directory
.execSegBase
= Swap(uint64_t(left
));
2285 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2286 directory
.execSegFlags
= Swap(execs
);
2288 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2290 directory
.identOffset
= Swap(uint32_t(offset
));
2291 offset
+= identifier
.size() + 1;
2294 directory
.teamIDOffset
= Swap(uint32_t(0));
2296 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2297 offset
+= team
.size() + 1;
2300 offset
+= special
* algorithm
.size_
;
2301 directory
.hashOffset
= Swap(uint32_t(offset
));
2302 offset
+= normal
* algorithm
.size_
;
2304 put(data
, &directory
, sizeof(directory
));
2306 put(data
, identifier
.c_str(), identifier
.size() + 1);
2308 put(data
, team
.c_str(), team
.size() + 1);
2310 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2311 auto *hashes(&storage
[special
* algorithm
.size_
]);
2313 memset(storage
.data(), 0, special
* algorithm
.size_
);
2315 _foreach (blob
, blobs
) {
2316 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2317 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2320 _foreach (slot
, posts
)
2321 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2325 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2326 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2327 progress(double(i
) / normal
);
2330 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2333 put(data
, storage
.data(), storage
.size());
2335 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2336 algorithm(hash
, save
.data(), save
.size());
2341 #ifndef LDID_NOSMIME
2344 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
));
2345 _scope({ CFRelease(plist
); });
2347 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
));
2348 _scope({ CFRelease(cdhashes
); });
2350 CFDictionarySetValue(plist
, CFSTR("cdhashes"), cdhashes
);
2352 auto plist(plist_new_dict());
2353 _scope({ plist_free(plist
); });
2355 auto cdhashes(plist_new_array());
2356 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2360 for (Algorithm
*pointer
: GetAlgorithms()) {
2361 Algorithm
&algorithm(*pointer
);
2364 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2367 std::vector
<char> hash
;
2368 algorithm(hash
, blob
.data(), blob
.size());
2372 auto value(CFDataCreate(kCFAllocatorDefault
, reinterpret_cast<const UInt8
*>(hash
.data()), hash
.size()));
2373 _scope({ CFRelease(value
); });
2374 CFArrayAppendValue(cdhashes
, value
);
2376 plist_array_append_item(cdhashes
, plist_new_data(hash
.data(), hash
.size()));
2381 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
));
2382 _scope({ CFRelease(created
); });
2383 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created
)));
2384 auto size(CFDataGetLength(created
));
2388 plist_to_xml(plist
, &xml
, &size
);
2389 _scope({ free(xml
); });
2392 std::stringbuf data
;
2393 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2398 Signature
signature(stuff
, sign
, std::string(xml
, size
));
2399 Buffer
result(signature
);
2400 std::string
value(result
);
2401 put(data
, value
.data(), value
.size());
2403 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2404 _assert(save
.size() <= certificate
);
2408 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2414 #ifndef LDID_NOTOOLS
2415 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2416 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2418 }), 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 {
2423 std::string
DiskFolder::Path(const std::string
&path
) const {
2424 return path_
+ path
;
2427 DiskFolder::DiskFolder(const std::string
&path
) :
2430 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2433 DiskFolder::~DiskFolder() {
2434 if (!std::uncaught_exception())
2435 for (const auto &commit
: commit_
)
2436 Commit(commit
.first
, commit
.second
);
2440 std::string
readlink(const std::string
&path
) {
2441 for (size_t size(1024); ; size
*= 2) {
2445 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2446 if (size_t(writ
) >= size
)
2455 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 {
2456 std::string
path(Path(root
) + base
);
2458 DIR *dir(opendir(path
.c_str()));
2459 _assert(dir
!= NULL
);
2460 _scope({ _syscall(closedir(dir
)); });
2462 while (auto child
= readdir(dir
)) {
2463 std::string
name(child
->d_name
);
2464 if (name
== "." || name
== "..")
2466 if (Starts(name
, ".ldid."))
2473 _syscall(stat((path
+ name
).c_str(), &info
));
2475 else if (S_ISDIR(info
.st_mode
))
2477 else if (S_ISREG(info
.st_mode
))
2480 _assert_(false, "st_mode=%x", info
.st_mode
);
2482 switch (child
->d_type
) {
2490 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2493 _assert_(false, "d_type=%u", child
->d_type
);
2498 Find(root
, base
+ name
+ "/", code
, link
);
2504 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2510 auto from(Path(path
));
2511 commit_
[from
] = Temporary(save
, from
);
2516 bool DiskFolder::Look(const std::string
&path
) const {
2517 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2520 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2522 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2523 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2525 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2526 data
.pubseekpos(0, std::ios::in
);
2527 code(data
, length
, NULL
);
2530 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 {
2531 Find(path
, "", code
, link
);
2535 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2539 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2542 std::string
SubFolder::Path(const std::string
&path
) const {
2543 return path_
+ path
;
2546 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2547 return parent_
.Save(Path(path
), edit
, flag
, code
);
2550 bool SubFolder::Look(const std::string
&path
) const {
2551 return parent_
.Look(Path(path
));
2554 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2555 return parent_
.Open(Path(path
), code
);
2558 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 {
2559 return parent_
.Find(Path(path
), code
, link
);
2562 std::string
UnionFolder::Map(const std::string
&path
) const {
2563 auto remap(remaps_
.find(path
));
2564 if (remap
== remaps_
.end())
2566 return remap
->second
;
2569 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 {
2570 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2571 code(file
.substr(path
.size()));
2574 UnionFolder::UnionFolder(Folder
&parent
) :
2579 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2580 return parent_
.Save(Map(path
), edit
, flag
, code
);
2583 bool UnionFolder::Look(const std::string
&path
) const {
2584 auto file(resets_
.find(path
));
2585 if (file
!= resets_
.end())
2587 return parent_
.Look(Map(path
));
2590 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2591 auto file(resets_
.find(path
));
2592 if (file
== resets_
.end())
2593 return parent_
.Open(Map(path
), code
);
2594 auto &entry(file
->second
);
2596 auto &data(*entry
.data_
);
2597 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2598 data
.pubseekpos(0, std::ios::in
);
2599 code(data
, length
, entry
.flag_
);
2602 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 {
2603 for (auto &reset
: resets_
)
2604 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2605 auto &entry(reset
.second
);
2606 auto &data(*entry
.data_
);
2607 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2608 data
.pubseekpos(0, std::ios::in
);
2609 code(data
, length
, entry
.flag_
);
2612 for (auto &remap
: remaps_
)
2613 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2614 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2615 code(data
, length
, flag
);
2619 parent_
.Find(path
, fun([&](const std::string
&name
) {
2620 if (deletes_
.find(path
+ name
) == deletes_
.end())
2622 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2623 if (deletes_
.find(path
+ name
) == deletes_
.end())
2628 #ifndef LDID_NOTOOLS
2629 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2633 char data
[4096 * 4];
2634 size_t writ(source
.sgetn(data
, sizeof(data
)));
2637 _assert(target
.sputn(data
, writ
) == writ
);
2639 progress(double(total
) / length
);
2643 #ifndef LDID_NOPLIST
2644 static plist_t
plist(const std::string
&data
) {
2646 return plist_new_dict();
2647 plist_t
plist(NULL
);
2648 if (Starts(data
, "bplist00"))
2649 plist_from_bin(data
.data(), data
.size(), &plist
);
2651 plist_from_xml(data
.data(), data
.size(), &plist
);
2652 _assert(plist
!= NULL
);
2656 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2657 std::stringbuf data
;
2658 copy(buffer
, data
, length
, dummy_
);
2659 auto node(plist(data
.str()));
2660 _scope({ plist_free(node
); });
2661 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2665 static std::string
plist_s(plist_t node
) {
2666 _assert(node
!= NULL
);
2667 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2669 plist_get_string_val(node
, &data
);
2670 _scope({ free(data
); });
2686 std::vector
<std::string
> matches_
;
2689 Expression(const std::string
&code
) {
2690 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2691 matches_
.resize(regex_
.re_nsub
+ 1);
2698 bool operator ()(const std::string
&data
) {
2699 regmatch_t matches
[matches_
.size()];
2700 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2701 if (value
== REG_NOMATCH
)
2703 _assert_(value
== 0, "regexec()");
2704 for (size_t i(0); i
!= matches_
.size(); ++i
)
2705 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2709 const std::string
&operator [](size_t index
) const {
2710 return matches_
[index
];
2719 mutable std::unique_ptr
<Expression
> regex_
;
2721 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2728 Rule(const Rule
&rhs
) :
2729 weight_(rhs
.weight_
),
2735 void Compile() const {
2736 regex_
.reset(new Expression(code_
));
2739 bool operator ()(const std::string
&data
) const {
2740 _assert(regex_
.get() != NULL
);
2741 return (*regex_
)(data
);
2744 bool operator <(const Rule
&rhs
) const {
2745 if (weight_
> rhs
.weight_
)
2747 if (weight_
< rhs
.weight_
)
2749 return mode_
> rhs
.mode_
;
2754 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2755 return lhs
->code_
< rhs
->code_
;
2759 #ifndef LDID_NOPLIST
2760 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
) {
2761 // XXX: this is a miserable fail
2762 std::stringbuf temp
;
2763 put(temp
, prefix
, size
);
2764 copy(buffer
, temp
, length
- size
, progress
);
2765 // XXX: this is a stupid hack
2766 pad(temp
, 0x10 - (length
& 0xf));
2767 auto data(temp
.str());
2769 HashProxy
proxy(hash
, save
);
2770 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2774 std::map
<std::string
, Hash
> files
;
2775 std::map
<std::string
, std::string
> links
;
2777 void Merge(const std::string
&root
, const State
&state
) {
2778 for (const auto &entry
: state
.files
)
2779 files
[root
+ entry
.first
] = entry
.second
;
2780 for (const auto &entry
: state
.links
)
2781 links
[root
+ entry
.first
] = entry
.second
;
2785 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
) {
2786 std::string executable
;
2787 std::string identifier
;
2791 std::string
info("Info.plist");
2793 SubFolder
folder(parent
, [&]() {
2794 if (parent
.Look(info
))
2798 else if (parent
.Look("Contents/" + info
))
2800 else if (parent
.Look("Resources/" + info
)) {
2801 info
= "Resources/" + info
;
2803 } else _assert_(false, "cannot find Info.plist");
2806 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2807 plist_d(buffer
, length
, fun([&](plist_t node
) {
2808 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2809 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2813 if (mac
&& info
== "Info.plist")
2814 executable
= "MacOS/" + executable
;
2816 progress(root
+ "*");
2818 std::string entitlements
;
2819 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2820 // XXX: this is a miserable fail
2821 std::stringbuf temp
;
2822 copy(buffer
, temp
, length
, progress
);
2823 // XXX: this is a stupid hack
2824 pad(temp
, 0x10 - (length
& 0xf));
2825 auto data(temp
.str());
2826 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2829 static const std::string
directory("_CodeSignature/");
2830 static const std::string
signature(directory
+ "CodeResources");
2832 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2834 auto &rules1(versions
[""]);
2835 auto &rules2(versions
["2"]);
2837 const std::string
resources(mac
? "Resources/" : "");
2840 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2841 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2842 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2843 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2844 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2848 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2849 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2850 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2851 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2852 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2853 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2854 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2855 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2856 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2857 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2858 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2859 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2860 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2861 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2866 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2867 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2868 std::map
<std::string
, Bundle
> bundles
;
2870 folder
.Find("", fun([&](const std::string
&name
) {
2873 auto bundle(root
+ Split(name
).dir
);
2875 _assert(!bundle
.empty());
2876 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2878 SubFolder
subfolder(folder
, bundle
);
2880 bundles
[nested
[1]] = Sign(bundle
, subfolder
, key
, local
, "", Starts(name
, "PlugIns/") ? alter
:
2881 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
2883 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2886 std::set
<std::string
> excludes
;
2888 auto exclude([&](const std::string
&name
) {
2889 // BundleDiskRep::adjustResources -> builder.addExclusion
2890 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
2893 for (const auto &bundle
: bundles
)
2894 if (Starts(name
, bundle
.first
+ "/")) {
2895 excludes
.insert(name
);
2902 folder
.Find("", fun([&](const std::string
&name
) {
2906 if (local
.files
.find(name
) != local
.files
.end())
2908 auto &hash(local
.files
[name
]);
2910 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2911 progress(root
+ name
);
2922 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
2924 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
2925 switch (Swap(header
.magic
)) {
2927 // Java class file format
2928 if (Swap(header
.count
) >= 40)
2931 case MH_MAGIC
: case MH_MAGIC_64
:
2932 case MH_CIGAM
: case MH_CIGAM_64
:
2933 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
2935 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
2940 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
2941 HashProxy
proxy(hash
, save
);
2942 put(proxy
, header
.bytes
, size
);
2943 copy(data
, proxy
, length
- size
, progress
);
2946 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2950 local
.links
[name
] = read();
2953 auto plist(plist_new_dict());
2954 _scope({ plist_free(plist
); });
2956 for (const auto &version
: versions
) {
2957 auto files(plist_new_dict());
2958 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
2960 for (const auto &rule
: version
.second
)
2963 bool old(&version
.second
== &rules1
);
2965 for (const auto &hash
: local
.files
)
2966 for (const auto &rule
: version
.second
)
2967 if (rule(hash
.first
)) {
2968 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
2969 else if (old
&& rule
.mode_
== NoMode
)
2970 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2971 else if (rule
.mode_
!= OmitMode
) {
2972 auto entry(plist_new_dict());
2973 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
2975 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
2976 if (rule
.mode_
== OptionalMode
)
2977 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2978 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
2985 for (const auto &link
: local
.links
)
2986 for (const auto &rule
: version
.second
)
2987 if (rule(link
.first
)) {
2988 if (rule
.mode_
!= OmitMode
) {
2989 auto entry(plist_new_dict());
2990 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
2991 if (rule
.mode_
== OptionalMode
)
2992 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
2993 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
3000 for (const auto &bundle
: bundles
) {
3001 auto entry(plist_new_dict());
3002 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
3003 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
3004 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
3008 for (const auto &version
: versions
) {
3009 auto rules(plist_new_dict());
3010 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
3012 std::multiset
<const Rule
*, RuleCode
> ordered
;
3013 for (const auto &rule
: version
.second
)
3014 ordered
.insert(&rule
);
3016 for (const auto &rule
: ordered
)
3017 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
3018 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
3020 auto entry(plist_new_dict());
3021 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
3023 switch (rule
->mode_
) {
3027 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
3030 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3033 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
3036 plist_dict_set_item(entry
, "top", plist_new_bool(true));
3040 if (rule
->weight_
>= 10000)
3041 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
3042 else if (rule
->weight_
!= 1)
3043 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
3047 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
3048 HashProxy
proxy(local
.files
[signature
], save
);
3051 plist_to_xml(plist
, &xml
, &size
);
3052 _scope({ free(xml
); });
3053 put(proxy
, xml
, size
);
3057 bundle
.path
= folder
.Path(executable
);
3059 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
3060 progress(root
+ executable
);
3061 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
3063 slots
[1] = local
.files
.at(info
);
3064 slots
[3] = local
.files
.at(signature
);
3065 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
3069 remote
.Merge(root
, local
);
3073 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
) {
3075 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
3082 std::string
Hex(const uint8_t *data
, size_t size
) {
3084 hex
.reserve(size
* 2);
3085 for (size_t i(0); i
!= size
; ++i
) {
3086 hex
+= "0123456789abcdef"[data
[i
] >> 4];
3087 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
3092 static void usage(const char *argv0
) {
3093 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv0
);
3094 fprintf(stderr
, " %s -e MobileSafari\n", argv0
);
3095 fprintf(stderr
, " %s -S cat\n", argv0
);
3096 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv0
);
3099 #ifndef LDID_NOTOOLS
3100 int main(int argc
, char *argv
[]) {
3101 #ifndef LDID_NOSMIME
3102 OpenSSL_add_all_algorithms();
3110 little_
= endian
.byte
[0];
3119 #ifndef LDID_NOFLAGT
3137 bool platform(false);
3139 uint32_t flag_CPUType(_not(uint32_t));
3140 uint32_t flag_CPUSubtype(_not(uint32_t));
3142 const char *flag_I(NULL
);
3144 #ifndef LDID_NOFLAGT
3154 std::vector
<std::string
> files
;
3161 for (int argi(1); argi
!= argc
; ++argi
)
3162 if (argv
[argi
][0] != '-')
3163 files
.push_back(argv
[argi
]);
3164 else switch (argv
[argi
][1]) {
3171 case 'e': flag_e
= true; break;
3174 const char *string
= argv
[argi
] + 2;
3175 const char *colon
= strchr(string
, ':');
3176 _assert(colon
!= NULL
);
3177 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3179 unsigned number(strtoul(string
, &arge
, 0));
3180 _assert(arge
== colon
);
3181 auto &slot(slots
[number
]);
3182 for (Algorithm
*algorithm
: GetAlgorithms())
3183 (*algorithm
)(slot
, file
.data(), file
.size());
3186 case 'q': flag_q
= true; break;
3189 const char *hash
= argv
[argi
] + 2;
3197 fprintf(stderr
, "WARNING: -H is only present for compatibility with a fork of ldid\n");
3198 fprintf(stderr
, " you should NOT be manually specifying the hash algorithm\n");
3202 else if (strcmp(hash
, "sha1") == 0)
3204 else if (strcmp(hash
, "sha256") == 0)
3206 else _assert(false);
3209 case 'h': flag_h
= true; break;
3212 const char *xml
= argv
[argi
] + 2;
3213 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3216 case 'D': flag_D
= true; break;
3217 case 'd': flag_d
= true; break;
3219 case 'a': flag_a
= true; break;
3224 if (argv
[argi
][2] != '\0') {
3225 const char *cpu
= argv
[argi
] + 2;
3226 const char *colon
= strchr(cpu
, ':');
3227 _assert(colon
!= NULL
);
3229 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3230 _assert(arge
== colon
);
3231 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3232 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3237 const char *name
= argv
[argi
] + 2;
3239 else if (strcmp(name
, "host") == 0)
3240 flags
|= kSecCodeSignatureHost
;
3241 else if (strcmp(name
, "adhoc") == 0)
3242 flags
|= kSecCodeSignatureAdhoc
;
3243 else if (strcmp(name
, "hard") == 0)
3244 flags
|= kSecCodeSignatureForceHard
;
3245 else if (strcmp(name
, "kill") == 0)
3246 flags
|= kSecCodeSignatureForceKill
;
3247 else if (strcmp(name
, "expires") == 0)
3248 flags
|= kSecCodeSignatureForceExpiration
;
3249 else if (strcmp(name
, "restrict") == 0)
3250 flags
|= kSecCodeSignatureRestrict
;
3251 else if (strcmp(name
, "enforcement") == 0)
3252 flags
|= kSecCodeSignatureEnforcement
;
3253 else if (strcmp(name
, "library-validation") == 0)
3254 flags
|= kSecCodeSignatureLibraryValidation
;
3255 else if (strcmp(name
, "runtime") == 0)
3256 flags
|= kSecCodeSignatureRuntime
;
3257 else _assert(false);
3274 if (argv
[argi
][2] != '\0') {
3275 const char *xml
= argv
[argi
] + 2;
3276 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3285 if (argv
[argi
][2] != '\0')
3286 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3289 #ifndef LDID_NOFLAGT
3292 if (argv
[argi
][2] == '-')
3296 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
3297 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3307 flag_I
= argv
[argi
] + 2;
3316 _assert(flag_S
|| key
.empty());
3317 _assert(flag_S
|| flag_I
== NULL
);
3319 if (flag_d
&& !flag_h
) {
3321 fprintf(stderr
, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3327 size_t filei(0), filee(0);
3328 _foreach (file
, files
) try {
3329 std::string
path(file
);
3332 _syscall(stat(path
.c_str(), &info
));
3334 if (S_ISDIR(info
.st_mode
)) {
3336 #ifndef LDID_NOPLIST
3337 ldid::DiskFolder
folder(path
+ "/");
3338 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3342 } else if (flag_S
|| flag_r
) {
3343 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3345 std::filebuf output
;
3347 auto temp(Temporary(output
, split
));
3350 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3352 std::string
identifier(flag_I
?: split
.base
.c_str());
3353 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3360 #ifndef LDID_NOFLAGT
3367 Map
mapping(path
, modify
);
3368 FatHeader
fat_header(mapping
.data(), mapping
.size());
3370 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3371 struct linkedit_data_command
*signature(NULL
);
3372 struct encryption_info_command
*encryption(NULL
);
3375 if (mach_header
.GetCPUType() != flag_CPUType
)
3377 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3382 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3384 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3385 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3388 else if (cmd
== LC_CODE_SIGNATURE
)
3389 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3390 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3391 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3392 else if (cmd
== LC_LOAD_DYLIB
) {
3393 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3394 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3396 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3399 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3400 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3404 #ifndef LDID_NOFLAGT
3405 else if (cmd
== LC_ID_DYLIB
) {
3406 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3414 dylib_command
->dylib
.timestamp
= 0;
3415 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
3418 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
3424 if (flag_d
&& encryption
!= NULL
) {
3425 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3429 _assert(encryption
!= NULL
);
3430 encryption
->cryptid
= mach_header
.Swap(0);
3434 _assert(signature
!= NULL
);
3436 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3438 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3439 uint8_t *blob
= top
+ data
;
3440 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3442 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3443 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3444 uint32_t begin
= Swap(super
->index
[index
].offset
);
3445 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3446 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3451 _assert(signature
!= NULL
);
3453 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3455 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3456 uint8_t *blob
= top
+ data
;
3457 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3459 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3460 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3461 uint32_t begin
= Swap(super
->index
[index
].offset
);
3462 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3463 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3468 _assert(signature
!= NULL
);
3470 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3472 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3473 uint8_t *blob
= top
+ data
;
3474 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3476 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3477 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
3478 uint32_t begin
= Swap(super
->index
[index
].offset
);
3479 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3481 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
3482 uint32_t pages
= Swap(directory
->nCodeSlots
);
3485 for (size_t i
= 0; i
!= pages
- 1; ++i
)
3486 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
3488 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
3493 _assert(signature
!= NULL
);
3495 auto algorithms(GetAlgorithms());
3497 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3499 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3500 uint8_t *blob
= top
+ data
;
3501 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3504 CodeDirectory
*directory_
;
3506 Algorithm
&algorithm_
;
3510 std::map
<uint8_t, Candidate
> candidates
;
3512 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3513 auto type(Swap(super
->index
[index
].type
));
3514 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3515 uint32_t begin
= Swap(super
->index
[index
].offset
);
3516 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3517 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3518 auto type(directory
->hashType
);
3519 _assert(type
> 0 && type
<= algorithms
.size());
3520 auto &algorithm(*algorithms
[type
- 1]);
3521 uint8_t hash
[algorithm
.size_
];
3522 algorithm(hash
, blob
+ begin
, end
- begin
);
3523 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20)}});
3527 _assert(!candidates
.empty());
3528 auto best(candidates
.end());
3531 const auto directory(best
->second
.directory_
);
3532 const auto flags(Swap(directory
->flags
));
3535 if (flags
& kSecCodeSignatureHost
)
3537 if (flags
& kSecCodeSignatureAdhoc
)
3539 if (flags
& kSecCodeSignatureForceHard
)
3541 if (flags
& kSecCodeSignatureForceKill
)
3543 if (flags
& kSecCodeSignatureForceExpiration
)
3544 names
+= ",expires";
3545 if (flags
& kSecCodeSignatureRestrict
)
3546 names
+= ",restrict";
3547 if (flags
& kSecCodeSignatureEnforcement
)
3548 names
+= ",enforcement";
3549 if (flags
& kSecCodeSignatureLibraryValidation
)
3550 names
+= ",library-validation";
3551 if (flags
& kSecCodeSignatureRuntime
)
3552 names
+= ",runtime";
3554 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3555 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3556 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3558 std::string choices
;
3559 for (const auto &candidate
: candidates
) {
3560 auto choice(candidate
.second
.algorithm_
.name());
3563 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3565 printf("Hash choices=%s\n", choices
.c_str() + 1);
3567 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3572 } catch (const char *) {