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/asn1t.h>
48 #include <openssl/pem.h>
49 #include <openssl/pkcs7.h>
50 #include <openssl/pkcs12.h>
54 #include <CommonCrypto/CommonDigest.h>
56 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
57 #define LDID_SHA1 CC_SHA1
58 #define LDID_SHA1_CTX CC_SHA1_CTX
59 #define LDID_SHA1_Init CC_SHA1_Init
60 #define LDID_SHA1_Update CC_SHA1_Update
61 #define LDID_SHA1_Final CC_SHA1_Final
63 #define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
64 #define LDID_SHA256 CC_SHA256
65 #define LDID_SHA256_CTX CC_SHA256_CTX
66 #define LDID_SHA256_Init CC_SHA256_Init
67 #define LDID_SHA256_Update CC_SHA256_Update
68 #define LDID_SHA256_Final CC_SHA256_Final
70 #include <openssl/sha.h>
72 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
73 #define LDID_SHA1 SHA1
74 #define LDID_SHA1_CTX SHA_CTX
75 #define LDID_SHA1_Init SHA1_Init
76 #define LDID_SHA1_Update SHA1_Update
77 #define LDID_SHA1_Final SHA1_Final
79 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
80 #define LDID_SHA256 SHA256
81 #define LDID_SHA256_CTX SHA256_CTX
82 #define LDID_SHA256_Init SHA256_Init
83 #define LDID_SHA256_Update SHA256_Update
84 #define LDID_SHA256_Final SHA256_Final
88 #include <plist/plist.h>
90 #include <CoreFoundation/CoreFoundation.h>
95 #define _assert___(line) \
97 #define _assert__(line) \
101 #define $(value) value
105 #define _assert_(expr, format, ...) \
107 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
108 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
111 // XXX: this is not acceptable
112 #define _assert_(expr, format, ...) \
114 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
119 #define _assert(expr) \
120 _assert_(expr, "%s", $(#expr))
122 #define _syscall(expr, ...) [&] { for (;;) { \
124 if ((long) _value != -1) \
127 if (error == EINTR) \
129 /* XXX: EINTR is included in this list to fix g++ */ \
130 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
131 if (error == success) \
132 return (decltype(expr)) -success; \
133 _assert_(false, "errno=%u", error); \
137 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
143 __attribute__((packed))
145 template <typename Type_
>
147 typedef typename
Type_::const_iterator Result
;
150 #define _foreach(item, list) \
151 for (bool _stop(true); _stop; ) \
152 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
153 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
154 for (bool _suck(true); _suck; _suck = false) \
155 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
160 template <typename Function_
>
168 Scope(const Function_
&function
) :
178 template <typename Function_
>
179 Scope
<Function_
> _scope(const Function_
&function
) {
180 return Scope
<Function_
>(function
);
183 #define _scope__(counter, function) \
184 __attribute__((__unused__)) \
185 const _Scope &_scope ## counter(_scope([&]function))
186 #define _scope_(counter, function) \
187 _scope__(counter, function)
188 #define _scope(function) \
189 _scope_(__COUNTER__, function)
191 #define CPU_ARCH_MASK uint32_t(0xff000000)
192 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
194 #define CPU_TYPE_ANY uint32_t(-1)
195 #define CPU_TYPE_VAX uint32_t( 1)
196 #define CPU_TYPE_MC680x0 uint32_t( 6)
197 #define CPU_TYPE_X86 uint32_t( 7)
198 #define CPU_TYPE_MC98000 uint32_t(10)
199 #define CPU_TYPE_HPPA uint32_t(11)
200 #define CPU_TYPE_ARM uint32_t(12)
201 #define CPU_TYPE_MC88000 uint32_t(13)
202 #define CPU_TYPE_SPARC uint32_t(14)
203 #define CPU_TYPE_I860 uint32_t(15)
204 #define CPU_TYPE_POWERPC uint32_t(18)
206 #define CPU_TYPE_I386 CPU_TYPE_X86
208 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
209 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
210 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
217 #define FAT_MAGIC 0xcafebabe
218 #define FAT_CIGAM 0xbebafeca
238 #define MH_MAGIC 0xfeedface
239 #define MH_CIGAM 0xcefaedfe
241 #define MH_MAGIC_64 0xfeedfacf
242 #define MH_CIGAM_64 0xcffaedfe
244 #define MH_DYLDLINK 0x4
246 #define MH_OBJECT 0x1
247 #define MH_EXECUTE 0x2
249 #define MH_DYLINKER 0x7
250 #define MH_BUNDLE 0x8
251 #define MH_DYLIB_STUB 0x9
253 struct load_command
{
258 #define LC_REQ_DYLD uint32_t(0x80000000)
260 #define LC_SEGMENT uint32_t(0x01)
261 #define LC_SYMTAB uint32_t(0x02)
262 #define LC_DYSYMTAB uint32_t(0x0b)
263 #define LC_LOAD_DYLIB uint32_t(0x0c)
264 #define LC_ID_DYLIB uint32_t(0x0d)
265 #define LC_SEGMENT_64 uint32_t(0x19)
266 #define LC_UUID uint32_t(0x1b)
267 #define LC_CODE_SIGNATURE uint32_t(0x1d)
268 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
269 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
270 #define LC_ENCRYPTION_INFO uint32_t(0x21)
271 #define LC_DYLD_INFO uint32_t(0x22)
272 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
273 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
288 uint32_t current_version
;
289 uint32_t compatibility_version
;
292 struct dylib_command
{
298 struct uuid_command
{
304 struct symtab_command
{
313 struct dyld_info_command
{
317 uint32_t rebase_size
;
320 uint32_t weak_bind_off
;
321 uint32_t weak_bind_size
;
322 uint32_t lazy_bind_off
;
323 uint32_t lazy_bind_size
;
325 uint32_t export_size
;
328 struct dysymtab_command
{
341 uint32_t extrefsymoff
;
342 uint32_t nextrefsyms
;
343 uint32_t indirectsymoff
;
344 uint32_t nindirectsyms
;
351 struct dylib_table_of_contents
{
352 uint32_t symbol_index
;
353 uint32_t module_index
;
356 struct dylib_module
{
357 uint32_t module_name
;
366 uint32_t iinit_iterm
;
367 uint32_t ninit_nterm
;
368 uint32_t objc_module_info_addr
;
369 uint32_t objc_module_info_size
;
372 struct dylib_reference
{
377 struct relocation_info
{
379 uint32_t r_symbolnum
:24;
398 struct segment_command
{
412 struct segment_command_64
{
455 struct linkedit_data_command
{
462 struct encryption_info_command
{
470 #define BIND_OPCODE_MASK 0xf0
471 #define BIND_IMMEDIATE_MASK 0x0f
472 #define BIND_OPCODE_DONE 0x00
473 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
474 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
475 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
476 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
477 #define BIND_OPCODE_SET_TYPE_IMM 0x50
478 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
479 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
480 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
481 #define BIND_OPCODE_DO_BIND 0x90
482 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
483 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
484 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
486 struct : ldid::Progress
{
487 virtual void operator()(const std::string
&value
) const {
490 virtual void operator()(double value
) const {
494 struct Progression
: ldid::Progress
{
495 const ldid::Progress
&progress_
;
498 Progression(const ldid::Progress
&progress
, const std::string
&name
) :
504 virtual void operator()(const std::string
&value
) const {
505 return progress_(name_
+ " (" + value
+ ")");
508 virtual void operator()(double value
) const {
509 return progress_(value
);
513 static std::streamsize
read(std::streambuf
&stream
, void *data
, size_t size
) {
514 auto writ(stream
.sgetn(static_cast<char *>(data
), size
));
519 static inline void put(std::streambuf
&stream
, uint8_t value
) {
520 _assert(stream
.sputc(value
) != EOF
);
523 static inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
524 _assert(read(stream
, data
, size
) == size
);
527 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
528 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
531 static inline void put(std::streambuf
&stream
, const void *data
, size_t size
, const ldid::Progress
&progress
) {
533 for (size_t total(0); total
!= size
;) {
534 auto writ(std::min(size
- total
, size_t(4096 * 4)));
535 _assert(stream
.sputn(static_cast<const char *>(data
) + total
, writ
) == writ
);
537 progress(double(total
) / size
);
541 static inline void put(std::streambuf
&stream
, const std::string
&data
) {
542 return put(stream
, data
.data(), data
.size());
545 static size_t most(std::streambuf
&stream
, void *data
, size_t size
) {
548 if (auto writ
= read(stream
, data
, size
))
554 static inline void pad(std::streambuf
&stream
, size_t size
) {
556 memset(padding
, 0, size
);
557 put(stream
, padding
, size
);
560 template <typename Type_
>
561 Type_
Align(Type_ value
, size_t align
) {
568 static const uint8_t PageShift_(0x0c);
569 static const uint32_t PageSize_(1 << PageShift_
);
571 static inline unsigned bytes(uint64_t value
) {
572 return (64 - __builtin_clzll(value
) + 7) / 8;
575 static void put(std::streambuf
&stream
, uint64_t value
, size_t length
) {
577 do put(stream
, uint8_t(value
>> (length
-= 8)));
581 static void der(std::streambuf
&stream
, uint64_t value
) {
585 unsigned length(bytes(value
));
586 put(stream
, 0x80 | length
);
587 put(stream
, value
, length
);
591 static std::string
der(uint8_t tag
, const char *value
, size_t length
) {
595 put(data
, value
, length
);
599 static std::string
der(uint8_t tag
, const char *value
) {
600 return der(tag
, value
, strlen(value
)); }
601 static std::string
der(uint8_t tag
, const std::string
&value
) {
602 return der(tag
, value
.data(), value
.size()); }
604 template <typename Type_
>
605 static void der_(std::stringbuf
&data
, const Type_
&values
) {
607 for (const auto &value
: values
)
608 size
+= value
.size();
610 for (const auto &value
: values
)
614 static std::string
der(const std::vector
<std::string
> &values
) {
621 static std::string
der(const std::multiset
<std::string
> &values
) {
628 static std::string
der(const std::pair
<std::string
, std::string
> &value
) {
629 const auto key(der(0x0c, value
.first
));
632 der(data
, key
.size() + value
.second
.size());
634 put(data
, value
.second
);
639 static std::string
der(plist_t data
) {
640 switch (const auto type
= plist_get_node_type(data
)) {
641 case PLIST_BOOLEAN
: {
643 plist_get_bool_val(data
, &value
);
648 put(data
, value
!= 0 ? 1 : 0);
654 plist_get_uint_val(data
, &value
);
655 const auto length(bytes(value
));
660 put(data
, value
, length
);
675 plist_get_data_val(data
, &value
, &length
);
676 _scope({ free(value
); });
677 return der(0x04, value
, length
);
682 plist_get_string_val(data
, &value
);
683 _scope({ free(value
); });
684 return der(0x0c, value
);
688 std::vector
<std::string
> values
;
689 for (auto e(plist_array_get_size(data
)), i(decltype(e
)(0)); i
!= e
; ++i
)
690 values
.push_back(der(plist_array_get_item(data
, i
)));
695 std::multiset
<std::string
> values
;
697 plist_dict_iter
iterator(NULL
);
698 plist_dict_new_iter(data
, &iterator
);
699 _scope({ free(iterator
); });
704 plist_dict_next_item(data
, iterator
, &key
, &value
);
707 _scope({ free(key
); });
708 values
.insert(der(std::make_pair(key
, der(value
))));
715 _assert_(false, "unsupported plist type %d", type
);
721 static inline uint16_t Swap_(uint16_t value
) {
723 ((value
>> 8) & 0x00ff) |
724 ((value
<< 8) & 0xff00);
727 static inline uint32_t Swap_(uint32_t value
) {
728 value
= ((value
>> 8) & 0x00ff00ff) |
729 ((value
<< 8) & 0xff00ff00);
730 value
= ((value
>> 16) & 0x0000ffff) |
731 ((value
<< 16) & 0xffff0000);
735 static inline uint64_t Swap_(uint64_t value
) {
736 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
737 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
738 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
742 static inline int16_t Swap_(int16_t value
) {
743 return Swap_(static_cast<uint16_t>(value
));
746 static inline int32_t Swap_(int32_t value
) {
747 return Swap_(static_cast<uint32_t>(value
));
750 static inline int64_t Swap_(int64_t value
) {
751 return Swap_(static_cast<uint64_t>(value
));
754 static bool little_(true);
756 static inline uint16_t Swap(uint16_t value
) {
757 return little_
? Swap_(value
) : value
;
760 static inline uint32_t Swap(uint32_t value
) {
761 return little_
? Swap_(value
) : value
;
764 static inline uint64_t Swap(uint64_t value
) {
765 return little_
? Swap_(value
) : value
;
768 static inline int16_t Swap(int16_t value
) {
769 return Swap(static_cast<uint16_t>(value
));
772 static inline int32_t Swap(int32_t value
) {
773 return Swap(static_cast<uint32_t>(value
));
776 static inline int64_t Swap(int64_t value
) {
777 return Swap(static_cast<uint64_t>(value
));
790 Swapped(bool swapped
) :
795 template <typename Type_
>
796 Type_
Swap(Type_ value
) const {
797 return swapped_
? Swap_(value
) : value
;
809 Data(void *base
, size_t size
) :
815 void *GetBase() const {
819 size_t GetSize() const {
830 struct mach_header
*mach_header_
;
831 struct load_command
*load_command_
;
834 MachHeader(void *base
, size_t size
) :
837 mach_header_
= (mach_header
*) base
;
839 switch (Swap(mach_header_
->magic
)) {
841 swapped_
= !swapped_
;
847 swapped_
= !swapped_
;
856 void *post
= mach_header_
+ 1;
858 post
= (uint32_t *) post
+ 1;
859 load_command_
= (struct load_command
*) post
;
862 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
863 Swap(mach_header_
->filetype
) == MH_DYLIB
||
864 Swap(mach_header_
->filetype
) == MH_DYLINKER
||
865 Swap(mach_header_
->filetype
) == MH_BUNDLE
869 bool Bits64() const {
873 struct mach_header
*operator ->() const {
877 operator struct mach_header
*() const {
881 uint32_t GetCPUType() const {
882 return Swap(mach_header_
->cputype
);
885 uint32_t GetCPUSubtype() const {
886 return Swap(mach_header_
->cpusubtype
) & 0xff;
889 struct load_command
*GetLoadCommand() const {
890 return load_command_
;
893 std::vector
<struct load_command
*> GetLoadCommands() const {
894 std::vector
<struct load_command
*> load_commands
;
896 struct load_command
*load_command
= load_command_
;
897 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
898 load_commands
.push_back(load_command
);
899 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
902 return load_commands
;
905 void ForSection(const ldid::Functor
<void (const char *, const char *, void *, size_t)> &code
) const {
906 _foreach (load_command
, GetLoadCommands())
907 switch (Swap(load_command
->cmd
)) {
909 auto segment(reinterpret_cast<struct segment_command
*>(load_command
));
910 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
911 auto section(reinterpret_cast<struct section
*>(segment
+ 1));
912 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
913 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
916 case LC_SEGMENT_64
: {
917 auto segment(reinterpret_cast<struct segment_command_64
*>(load_command
));
918 code(segment
->segname
, NULL
, GetOffset
<void>(segment
->fileoff
), segment
->filesize
);
919 auto section(reinterpret_cast<struct section_64
*>(segment
+ 1));
920 for (uint32_t i(0), e(Swap(segment
->nsects
)); i
!= e
; ++i
, ++section
)
921 code(segment
->segname
, section
->sectname
, GetOffset
<void>(segment
->fileoff
+ section
->offset
), section
->size
);
926 template <typename Target_
>
927 Target_
*GetOffset(uint32_t offset
) const {
928 return reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
);
932 class FatMachHeader
:
939 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
940 MachHeader(base
, size
),
945 fat_arch
*GetFatArch() const {
954 fat_header
*fat_header_
;
955 std::vector
<FatMachHeader
> mach_headers_
;
958 FatHeader(void *base
, size_t size
) :
961 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
963 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
964 swapped_
= !swapped_
;
966 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
968 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
970 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
971 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
973 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
974 uint32_t arch_offset
= Swap(fat_arch
->offset
);
975 uint32_t arch_size
= Swap(fat_arch
->size
);
976 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
982 std::vector
<FatMachHeader
> &GetMachHeaders() {
983 return mach_headers_
;
987 return fat_header_
!= NULL
;
990 struct fat_header
*operator ->() const {
994 operator struct fat_header
*() const {
999 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
1000 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
1001 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
1002 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
1003 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
1004 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
1005 #define CSMAGIC_EMBEDDED_DERFORMAT uint32_t(0xfade7172) // name?
1006 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
1007 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
1009 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
1010 #define CSSLOT_INFOSLOT uint32_t(0x00001)
1011 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
1012 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
1013 #define CSSLOT_APPLICATION uint32_t(0x00004)
1014 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
1015 #define CSSLOT_REPSPECIFIC uint32_t(0x00006) // name?
1016 #define CSSLOT_DERFORMAT uint32_t(0x00007) // name?
1017 #define CSSLOT_ALTERNATE uint32_t(0x01000)
1019 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
1021 #define CS_HASHTYPE_SHA160_160 1
1022 #define CS_HASHTYPE_SHA256_256 2
1023 #define CS_HASHTYPE_SHA256_160 3
1024 #define CS_HASHTYPE_SHA386_386 4
1027 #define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
1028 #define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
1029 #define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
1030 #define CS_EXECSEG_JIT 0x040 /* JIT enabled */
1031 #define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
1032 #define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
1033 #define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
1035 enum SecCodeExecSegFlags
{
1036 kSecCodeExecSegMainBinary
= 0x001,
1037 kSecCodeExecSegAllowUnsigned
= 0x010,
1038 kSecCodeExecSegDebugger
= 0x020,
1039 kSecCodeExecSegJit
= 0x040,
1040 kSecCodeExecSegSkipLibraryVal
= 0x080,
1041 kSecCodeExecSegCanLoadCdHash
= 0x100,
1042 kSecCodeExecSegCanExecCdHash
= 0x100,
1059 struct BlobIndex index
[];
1062 struct CodeDirectory
{
1065 uint32_t hashOffset
;
1066 uint32_t identOffset
;
1067 uint32_t nSpecialSlots
;
1068 uint32_t nCodeSlots
;
1075 uint32_t scatterOffset
;
1076 uint32_t teamIDOffset
;
1078 uint64_t codeLimit64
;
1079 uint64_t execSegBase
;
1080 uint64_t execSegLimit
;
1081 uint64_t execSegFlags
;
1082 #if 0 // version = 0x20500
1084 uint32_t preEncryptOffset
;
1086 #if 0 // version = 0x20600
1087 uint8_t linkageHashType
;
1088 uint8_t linkageTruncated
;
1090 uint32_t linkageOffset
;
1091 uint32_t linkageSize
;
1095 enum CodeSignatureFlags
{
1096 kSecCodeSignatureHost
= 0x0001,
1097 kSecCodeSignatureAdhoc
= 0x0002,
1098 kSecCodeSignatureForceHard
= 0x0100,
1099 kSecCodeSignatureForceKill
= 0x0200,
1100 kSecCodeSignatureForceExpiration
= 0x0400,
1101 kSecCodeSignatureRestrict
= 0x0800,
1102 kSecCodeSignatureEnforcement
= 0x1000,
1103 kSecCodeSignatureLibraryValidation
= 0x2000,
1104 kSecCodeSignatureRuntime
= 0x10000,
1107 enum Kind
: uint32_t {
1108 exprForm
= 1, // prefix expr form
1111 enum ExprOp
: uint32_t {
1112 opFalse
, // unconditionally false
1113 opTrue
, // unconditionally true
1114 opIdent
, // match canonical code [string]
1115 opAppleAnchor
, // signed by Apple as Apple's product
1116 opAnchorHash
, // match anchor [cert hash]
1117 opInfoKeyValue
, // *legacy* - use opInfoKeyField [key; value]
1118 opAnd
, // binary prefix expr AND expr [expr; expr]
1119 opOr
, // binary prefix expr OR expr [expr; expr]
1120 opCDHash
, // match hash of CodeDirectory directly [cd hash]
1121 opNot
, // logical inverse [expr]
1122 opInfoKeyField
, // Info.plist key field [string; match suffix]
1123 opCertField
, // Certificate field [cert index; field name; match suffix]
1124 opTrustedCert
, // require trust settings to approve one particular cert [cert index]
1125 opTrustedCerts
, // require trust settings to approve the cert chain
1126 opCertGeneric
, // Certificate component by OID [cert index; oid; match suffix]
1127 opAppleGenericAnchor
, // signed by Apple in any capacity
1128 opEntitlementField
, // entitlement dictionary field [string; match suffix]
1129 opCertPolicy
, // Certificate policy by OID [cert index; oid; match suffix]
1130 opNamedAnchor
, // named anchor type
1131 opNamedCode
, // named subroutine
1132 opPlatform
, // platform constraint [integer]
1133 exprOpCount
// (total opcode count in use)
1136 enum MatchOperation
{
1137 matchExists
, // anything but explicit "false" - no value stored
1138 matchEqual
, // equal (CFEqual)
1139 matchContains
, // partial match (substring)
1140 matchBeginsWith
, // partial match (initial substring)
1141 matchEndsWith
, // partial match (terminal substring)
1142 matchLessThan
, // less than (string with numeric comparison)
1143 matchGreaterThan
, // greater than (string with numeric comparison)
1144 matchLessEqual
, // less or equal (string with numeric comparison)
1145 matchGreaterEqual
, // greater or equal (string with numeric comparison)
1148 #define OID_ISO_MEMBER 42
1149 #define OID_US OID_ISO_MEMBER, 134, 72
1150 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
1151 #define APPLE_ADS_OID APPLE_OID, 0x64
1152 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
1154 #ifndef LDID_NOFLAGT
1155 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
1163 Algorithm(size_t size
, uint8_t type
, int nid
) :
1170 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const = 0;
1172 virtual void operator ()(uint8_t *hash
, const void *data
, size_t size
) const = 0;
1173 virtual void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const = 0;
1174 virtual void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const = 0;
1176 virtual const char *name() = 0;
1179 struct AlgorithmSHA1
:
1183 Algorithm(LDID_SHA1_DIGEST_LENGTH
, CS_HASHTYPE_SHA160_160
, NID_sha1
)
1187 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1191 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1192 LDID_SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
1195 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1196 return operator()(hash
.sha1_
, data
, size
);
1199 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1200 hash
.resize(LDID_SHA1_DIGEST_LENGTH
);
1201 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1204 virtual const char *name() {
1209 struct AlgorithmSHA256
:
1213 Algorithm(LDID_SHA256_DIGEST_LENGTH
, CS_HASHTYPE_SHA256_256
, NID_sha256
)
1217 virtual const uint8_t *operator [](const ldid::Hash
&hash
) const {
1218 return hash
.sha256_
;
1221 void operator ()(uint8_t *hash
, const void *data
, size_t size
) const {
1222 LDID_SHA256(static_cast<const uint8_t *>(data
), size
, hash
);
1225 void operator ()(ldid::Hash
&hash
, const void *data
, size_t size
) const {
1226 return operator()(hash
.sha256_
, data
, size
);
1229 void operator ()(std::vector
<char> &hash
, const void *data
, size_t size
) const {
1230 hash
.resize(LDID_SHA256_DIGEST_LENGTH
);
1231 return operator ()(reinterpret_cast<uint8_t *>(hash
.data()), data
, size
);
1234 virtual const char *name() {
1239 static bool do_sha1(true);
1240 static bool do_sha256(true);
1242 static const std::vector
<Algorithm
*> &GetAlgorithms() {
1243 static AlgorithmSHA1 sha1
;
1244 static AlgorithmSHA256 sha256
;
1246 static std::vector
<Algorithm
*> algorithms
;
1247 if (algorithms
.empty()) {
1249 algorithms
.push_back(&sha1
);
1251 algorithms
.push_back(&sha256
);
1258 std::string entitlements_
;
1259 std::string derformat_
;
1262 struct CodesignAllocation
{
1263 FatMachHeader mach_header_
;
1272 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
) :
1273 mach_header_(mach_header
),
1285 #ifndef LDID_NOTOOLS
1298 _syscall(close(file_
));
1301 void open(const char *path
, int flags
) {
1302 _assert(file_
== -1);
1303 file_
= _syscall(::open(path
, flags
));
1320 _syscall(munmap(data_
, size_
));
1332 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
1335 open(path
, oflag
, pflag
, mflag
);
1338 Map(const std::string
&path
, bool edit
) :
1348 bool empty() const {
1349 return data_
== NULL
;
1352 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
1355 file_
.open(path
.c_str(), oflag
);
1356 int file(file_
.file());
1359 _syscall(fstat(file
, &stat
));
1360 size_
= stat
.st_size
;
1362 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
1365 void open(const std::string
&path
, bool edit
) {
1367 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
1369 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1372 void *data() const {
1376 size_t size() const {
1380 operator std::string() const {
1381 return std::string(static_cast<char *>(data_
), size_
);
1388 #ifndef LDID_NOPLIST
1389 static plist_t
plist(const std::string
&data
);
1392 void Analyze(const MachHeader
&mach_header
, const Functor
<void (const char *data
, size_t size
)> &entitle
) {
1393 _foreach (load_command
, mach_header
.GetLoadCommands())
1394 if (mach_header
.Swap(load_command
->cmd
) == LC_CODE_SIGNATURE
) {
1395 auto signature(reinterpret_cast<struct linkedit_data_command
*>(load_command
));
1396 auto offset(mach_header
.Swap(signature
->dataoff
));
1397 auto pointer(reinterpret_cast<uint8_t *>(mach_header
.GetBase()) + offset
);
1398 auto super(reinterpret_cast<struct SuperBlob
*>(pointer
));
1400 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1401 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1402 auto begin(Swap(super
->index
[index
].offset
));
1403 auto blob(reinterpret_cast<struct Blob
*>(pointer
+ begin
));
1404 auto writ(Swap(blob
->length
) - sizeof(*blob
));
1405 entitle(reinterpret_cast<char *>(blob
+ 1), writ
);
1410 std::string
Analyze(const void *data
, size_t size
) {
1411 std::string entitlements
;
1413 FatHeader
fat_header(const_cast<void *>(data
), size
);
1414 _foreach (mach_header
, fat_header
.GetMachHeaders())
1415 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
1416 if (entitlements
.empty())
1417 entitlements
.assign(data
, size
);
1419 _assert(entitlements
.compare(0, entitlements
.size(), data
, size
) == 0);
1422 return entitlements
;
1425 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
) {
1426 FatHeader
source(const_cast<void *>(idata
), isize
);
1430 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
1432 std::vector
<CodesignAllocation
> allocations
;
1433 _foreach (mach_header
, source
.GetMachHeaders()) {
1434 struct linkedit_data_command
*signature(NULL
);
1435 struct symtab_command
*symtab(NULL
);
1437 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1438 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1440 else if (cmd
== LC_CODE_SIGNATURE
)
1441 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1442 else if (cmd
== LC_SYMTAB
)
1443 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
1447 if (signature
== NULL
)
1448 size
= mach_header
.GetSize();
1450 size
= mach_header
.Swap(signature
->dataoff
);
1451 _assert(size
<= mach_header
.GetSize());
1454 if (symtab
!= NULL
) {
1455 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
1456 if (symtab
->stroff
!= 0 || symtab
->strsize
!= 0) {
1457 _assert(end
<= size
);
1458 _assert(end
>= size
- 0x10);
1464 size_t alloc(allocate(mach_header
, baton
, size
));
1466 auto *fat_arch(mach_header
.GetFatArch());
1469 if (fat_arch
!= NULL
)
1470 align
= source
.Swap(fat_arch
->align
);
1471 else switch (mach_header
.GetCPUType()) {
1472 case CPU_TYPE_POWERPC
:
1473 case CPU_TYPE_POWERPC64
:
1475 case CPU_TYPE_X86_64
:
1479 case CPU_TYPE_ARM64
:
1487 const char *arch(NULL
);
1488 switch (mach_header
.GetCPUType()) {
1489 case CPU_TYPE_POWERPC
:
1492 case CPU_TYPE_POWERPC64
:
1498 case CPU_TYPE_X86_64
:
1504 case CPU_TYPE_ARM64
:
1509 offset
= Align(offset
, 1 << align
);
1511 uint32_t limit(size
);
1513 limit
= Align(limit
, 0x10);
1515 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
, arch
, baton
));
1516 offset
+= size
+ alloc
;
1517 offset
= Align(offset
, 0x10);
1522 if (source
.IsFat()) {
1523 fat_header fat_header
;
1524 fat_header
.magic
= Swap(FAT_MAGIC
);
1525 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1526 put(output
, &fat_header
, sizeof(fat_header
));
1527 position
+= sizeof(fat_header
);
1529 // XXX: support fat_arch_64 (not in my toolchain)
1530 // probably use C++14 generic lambda (not in my toolchain)
1533 _foreach (allocation
, allocations
) {
1534 const auto offset(allocation
.offset_
);
1535 const auto size(allocation
.limit_
+ allocation
.alloc_
);
1536 if (uint32_t(offset
) != offset
|| uint32_t(size
) != size
)
1540 }(), "FAT slice >=4GiB not currently supported");
1542 _foreach (allocation
, allocations
) {
1543 auto &mach_header(allocation
.mach_header_
);
1546 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1547 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1548 fat_arch
.offset
= Swap(uint32_t(allocation
.offset_
));
1549 fat_arch
.size
= Swap(uint32_t(allocation
.limit_
+ allocation
.alloc_
));
1550 fat_arch
.align
= Swap(allocation
.align_
);
1551 put(output
, &fat_arch
, sizeof(fat_arch
));
1552 position
+= sizeof(fat_arch
);
1556 _foreach (allocation
, allocations
) {
1557 progress(allocation
.arch_
);
1558 auto &mach_header(allocation
.mach_header_
);
1560 pad(output
, allocation
.offset_
- position
);
1561 position
= allocation
.offset_
;
1566 std::vector
<std::string
> commands
;
1568 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1569 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1571 switch (mach_header
.Swap(load_command
->cmd
)) {
1572 case LC_CODE_SIGNATURE
:
1576 // XXX: this is getting ridiculous: provide a better abstraction
1579 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1581 if ((segment_command
->initprot
& 04) != 0) {
1582 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1583 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1590 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1591 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1592 segment_command
->filesize
= size
;
1593 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1597 case LC_SEGMENT_64
: {
1598 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1600 if ((segment_command
->initprot
& 04) != 0) {
1601 auto begin(mach_header
.Swap(segment_command
->fileoff
));
1602 auto end(begin
+ mach_header
.Swap(segment_command
->filesize
));
1609 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) == 0) {
1610 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1611 segment_command
->filesize
= size
;
1612 segment_command
->vmsize
= Align(size
, 1 << allocation
.align_
);
1617 commands
.push_back(copy
);
1620 if (allocation
.alloc_
!= 0) {
1621 linkedit_data_command signature
;
1622 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1623 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1624 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1625 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1626 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1629 size_t begin(position
);
1632 _foreach(command
, commands
)
1633 after
+= command
.size();
1635 std::stringbuf altern
;
1637 struct mach_header
header(*mach_header
);
1638 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1639 header
.sizeofcmds
= mach_header
.Swap(after
);
1640 put(output
, &header
, sizeof(header
));
1641 put(altern
, &header
, sizeof(header
));
1642 position
+= sizeof(header
);
1644 if (mach_header
.Bits64()) {
1645 auto pad(mach_header
.Swap(uint32_t(0)));
1646 put(output
, &pad
, sizeof(pad
));
1647 put(altern
, &pad
, sizeof(pad
));
1648 position
+= sizeof(pad
);
1651 _foreach(command
, commands
) {
1652 put(output
, command
.data(), command
.size());
1653 put(altern
, command
.data(), command
.size());
1654 position
+= command
.size();
1657 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1658 if (before
> after
) {
1659 pad(output
, before
- after
);
1660 pad(altern
, before
- after
);
1661 position
+= before
- after
;
1664 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1666 std::string
overlap(altern
.str());
1667 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1669 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
), progress
);
1670 position
= begin
+ allocation
.size_
;
1672 pad(output
, allocation
.limit_
- allocation
.size_
);
1673 position
+= allocation
.limit_
- allocation
.size_
;
1675 size_t saved(save(mach_header
, allocation
.baton_
, output
, allocation
.limit_
, left
, right
, overlap
, top
, progress
));
1676 if (allocation
.alloc_
> saved
)
1677 pad(output
, allocation
.alloc_
- saved
);
1679 _assert(allocation
.alloc_
== saved
);
1680 position
+= allocation
.alloc_
;
1686 typedef std::map
<uint32_t, std::string
> Blobs
;
1688 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1689 auto value(buffer
.str());
1690 std::swap(blobs
[slot
], value
);
1693 static const std::string
&insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1694 auto value(buffer
.str());
1696 blob
.magic
= Swap(magic
);
1697 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1698 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1699 auto &save(blobs
[slot
]);
1700 std::swap(save
, value
);
1704 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1706 _foreach (blob
, blobs
)
1707 total
+= blob
.second
.size();
1709 struct SuperBlob super
;
1710 super
.blob
.magic
= Swap(magic
);
1711 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1712 super
.count
= Swap(uint32_t(blobs
.size()));
1713 put(output
, &super
, sizeof(super
));
1715 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1717 _foreach (blob
, blobs
) {
1719 index
.type
= Swap(blob
.first
);
1720 index
.offset
= Swap(uint32_t(offset
));
1721 put(output
, &index
, sizeof(index
));
1722 offset
+= blob
.second
.size();
1725 _foreach (blob
, blobs
)
1726 put(output
, blob
.second
.data(), blob
.second
.size());
1731 #ifndef LDID_NOSMIME
1740 _assert(bio_
!= NULL
);
1744 bio_(BIO_new(BIO_s_mem()))
1748 Buffer(const char *data
, size_t size
) :
1749 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1753 Buffer(const std::string
&data
) :
1754 Buffer(data
.data(), data
.size())
1758 Buffer(PKCS7
*pkcs
) :
1761 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1768 operator BIO
*() const {
1772 explicit operator std::string() const {
1774 auto size(BIO_get_mem_data(bio_
, &data
));
1775 return std::string(data
, size
);
1784 STACK_OF(X509
) *ca_
;
1788 value_(d2i_PKCS12_bio(bio
, NULL
)),
1791 _assert(value_
!= NULL
);
1792 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1794 _assert(key_
!= NULL
);
1795 _assert(cert_
!= NULL
);
1798 ca_
= sk_X509_new_null();
1799 _assert(ca_
!= NULL
);
1802 Stuff(const std::string
&data
) :
1808 sk_X509_pop_free(ca_
, X509_free
);
1810 EVP_PKEY_free(key_
);
1811 PKCS12_free(value_
);
1814 operator PKCS12
*() const {
1818 operator EVP_PKEY
*() const {
1822 operator X509
*() const {
1826 operator STACK_OF(X509
) *() const {
1833 ASN1_OCTET_STRING
*value_
;
1837 value_(ASN1_OCTET_STRING_new())
1839 _assert(value_
!= NULL
);
1842 Octet(const std::string
&value
) :
1845 _assert(ASN1_STRING_set(value_
, value
.data(), value
.size()));
1848 Octet(const uint8_t *data
, size_t size
) :
1851 _assert(ASN1_STRING_set(value_
, data
, size
));
1854 Octet(const Octet
&value
) = delete;
1858 ASN1_OCTET_STRING_free(value_
);
1865 operator ASN1_OCTET_STRING
*() const {
1871 ASN1_OBJECT
*algorithm
;
1872 ASN1_OCTET_STRING
*value
;
1875 DECLARE_ASN1_FUNCTIONS(APPLE_CDHASH
)
1877 ASN1_NDEF_SEQUENCE(APPLE_CDHASH
) = {
1878 ASN1_SIMPLE(APPLE_CDHASH
, algorithm
, ASN1_OBJECT
),
1879 ASN1_SIMPLE(APPLE_CDHASH
, value
, ASN1_OCTET_STRING
),
1880 } ASN1_NDEF_SEQUENCE_END(APPLE_CDHASH
)
1882 IMPLEMENT_ASN1_FUNCTIONS(APPLE_CDHASH
)
1885 ASN1_OBJECT
*object
;
1886 STACK_OF(APPLE_CDHASH
) *cdhashes
;
1889 DECLARE_ASN1_FUNCTIONS(APPLE_CDATTR
)
1891 ASN1_NDEF_SEQUENCE(APPLE_CDATTR
) = {
1892 ASN1_SIMPLE(APPLE_CDATTR
, object
, ASN1_OBJECT
),
1893 ASN1_SET_OF(APPLE_CDATTR
, cdhashes
, APPLE_CDHASH
),
1894 } ASN1_NDEF_SEQUENCE_END(APPLE_CDATTR
)
1896 IMPLEMENT_ASN1_FUNCTIONS(APPLE_CDATTR
)
1903 Signature(const Stuff
&stuff
, const Buffer
&data
, const std::string
&xml
, const ldid::Hash
&hash
) {
1904 value_
= PKCS7_new();
1905 _assert(value_
!= NULL
);
1907 _assert(PKCS7_set_type(value_
, NID_pkcs7_signed
));
1908 _assert(PKCS7_content_new(value_
, NID_pkcs7_data
));
1910 STACK_OF(X509
) *certs(stuff
);
1911 for (unsigned i(0), e(sk_X509_num(certs
)); i
!= e
; i
++)
1912 _assert(PKCS7_add_certificate(value_
, sk_X509_value(certs
, e
- i
- 1)));
1914 STACK_OF(X509_ATTRIBUTE
) *attributes(sk_X509_ATTRIBUTE_new_null());
1915 _assert(attributes
!= NULL
);
1916 _scope({ sk_X509_ATTRIBUTE_pop_free(attributes
, X509_ATTRIBUTE_free
); });
1919 // XXX: this is the same as PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP)
1920 _assert(X509_check_private_key(stuff
, stuff
));
1921 auto info(PKCS7_add_signature(value_
, stuff
, stuff
, EVP_sha1()));
1922 _assert(info
!= NULL
);
1923 _assert(PKCS7_add_certificate(value_
, stuff
));
1926 auto attribute(X509_ATTRIBUTE_create(NID_pkcs9_contentType
, V_ASN1_OBJECT
, OBJ_nid2obj(NID_pkcs7_data
)));
1927 _assert(attribute
!= NULL
);
1928 _assert(sk_X509_ATTRIBUTE_push(attributes
, attribute
) != 0);
1932 auto cdattr(APPLE_CDATTR_new());
1933 _assert(cdattr
!= NULL
);
1934 _scope({ APPLE_CDATTR_free(cdattr
); });
1936 static auto nid(OBJ_create("1.2.840.113635.100.9.2", "apple-2", "Apple 2"));
1937 cdattr
->object
= OBJ_nid2obj(nid
);
1939 for (Algorithm
*pointer
: GetAlgorithms()) {
1940 Algorithm
&algorithm(*pointer
);
1941 APPLE_CDHASH
*cdhash(APPLE_CDHASH_new());
1942 _assert(cdhash
!= NULL
);
1943 _assert(sk_push((_STACK
*) cdattr
->cdhashes
, cdhash
) != 0);
1944 cdhash
->algorithm
= OBJ_nid2obj(algorithm
.nid_
);
1945 Octet
string(algorithm
[hash
], algorithm
.size_
);
1946 cdhash
->value
= string
;
1950 // in e20b57270dece66ce2c68aeb5d14dd6d9f3c5d68 OpenSSL removed a "hack"
1951 // in the process, they introduced a useful bug in X509_ATTRIBUTE_set1_data
1952 // however, I don't want to rely on that or detect the bypass before it
1953 // so, instead, I create my own compatible attribute and re-serialize it :/
1955 ASN1_STRING
*seq(ASN1_STRING_new());
1956 _assert(seq
!= NULL
);
1957 _scope({ ASN1_STRING_free(seq
); });
1958 seq
->length
= ASN1_item_i2d((ASN1_VALUE
*) cdattr
, &seq
->data
, ASN1_ITEM_rptr(APPLE_CDATTR
));
1960 X509_ATTRIBUTE
*attribute(NULL
);
1961 const unsigned char *data(seq
->data
);
1962 _assert(d2i_X509_ATTRIBUTE(&attribute
, &data
, seq
->length
) != 0);
1963 _assert(attribute
!= NULL
);
1964 _assert(sk_X509_ATTRIBUTE_push(attributes
, attribute
) != 0);
1968 // XXX: move the "cdhashes" plist code to here and remove xml argument
1971 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "apple-1", "Apple 1"));
1972 auto attribute(X509_ATTRIBUTE_create(nid
, V_ASN1_OCTET_STRING
, string
));
1973 _assert(attribute
!= NULL
);
1975 _assert(sk_X509_ATTRIBUTE_push(attributes
, attribute
) != 0);
1978 _assert(PKCS7_set_signed_attributes(info
, attributes
) != 0);
1979 PKCS7_set_detached(value_
, 1);
1981 // XXX: this is the same as PKCS7_final(value_, data, PKCS7_BINARY)
1982 BIO
*bio(PKCS7_dataInit(value_
, NULL
));
1983 _assert(bio
!= NULL
);
1984 _scope({ BIO_free_all(bio
); });
1985 SMIME_crlf_copy(data
, bio
, PKCS7_BINARY
);
1987 _assert(PKCS7_dataFinal(value_
, bio
));
1994 operator PKCS7
*() const {
2001 public std::streambuf
2004 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
2008 virtual int_type
overflow(int_type next
) {
2014 public std::streambuf
2019 LDID_SHA1_CTX sha1_
;
2020 LDID_SHA256_CTX sha256_
;
2023 HashBuffer(ldid::Hash
&hash
) :
2026 LDID_SHA1_Init(&sha1_
);
2027 LDID_SHA256_Init(&sha256_
);
2031 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.sha1_
), &sha1_
);
2032 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_
.sha256_
), &sha256_
);
2035 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
2036 LDID_SHA1_Update(&sha1_
, data
, size
);
2037 LDID_SHA256_Update(&sha256_
, data
, size
);
2041 virtual int_type
overflow(int_type next
) {
2042 if (next
== traits_type::eof())
2054 std::streambuf
&buffer_
;
2057 HashProxy(ldid::Hash
&hash
, std::streambuf
&buffer
) :
2063 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
2064 _assert(HashBuffer::xsputn(data
, size
) == size
);
2065 return buffer_
.sputn(data
, size
);
2069 #ifndef LDID_NOTOOLS
2070 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
2071 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
2079 Split(const std::string
&path
) {
2080 size_t slash(path
.rfind('/'));
2081 if (slash
== std::string::npos
)
2084 dir
= path
.substr(0, slash
+ 1);
2085 base
= path
.substr(slash
+ 1);
2090 static void mkdir_p(const std::string
&path
) {
2094 if (_syscall(mkdir(path
.c_str()), EEXIST
) == -EEXIST
)
2097 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
2100 auto slash(path
.rfind('/', path
.size() - 1));
2101 if (slash
== std::string::npos
)
2103 mkdir_p(path
.substr(0, slash
));
2106 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
2107 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
2109 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
2113 static void Commit(const std::string
&path
, const std::string
&temp
) {
2115 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
2117 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
2119 _syscall(chmod(temp
.c_str(), info
.st_mode
));
2122 _syscall(rename(temp
.c_str(), path
.c_str()));
2128 #ifndef LDID_NOSMIME
2129 static void get(std::string
&value
, X509_NAME
*name
, int nid
) {
2130 auto index(X509_NAME_get_index_by_NID(name
, nid
, -1));
2131 _assert(index
>= 0);
2132 auto next(X509_NAME_get_index_by_NID(name
, nid
, index
));
2133 _assert(next
== -1);
2134 auto entry(X509_NAME_get_entry(name
, index
));
2135 _assert(entry
!= NULL
);
2136 auto asn(X509_NAME_ENTRY_get_data(entry
));
2137 _assert(asn
!= NULL
);
2138 value
.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn
)), ASN1_STRING_length(asn
));
2142 static void req(std::streambuf
&buffer
, uint32_t value
) {
2143 value
= Swap(value
);
2144 put(buffer
, &value
, sizeof(value
));
2147 static void req(std::streambuf
&buffer
, const std::string
&value
) {
2148 req(buffer
, value
.size());
2149 put(buffer
, value
.data(), value
.size());
2150 static uint8_t zeros
[] = {0,0,0,0};
2151 put(buffer
, zeros
, 3 - (value
.size() + 3) % 4);
2154 template <size_t Size_
>
2155 static void req(std::streambuf
&buffer
, uint8_t (&&data
)[Size_
]) {
2157 put(buffer
, data
, Size_
);
2158 static uint8_t zeros
[] = {0,0,0,0};
2159 put(buffer
, zeros
, 3 - (Size_
+ 3) % 4);
2162 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
) {
2169 #ifndef LDID_NOSMIME
2172 auto name(X509_get_subject_name(stuff
));
2173 _assert(name
!= NULL
);
2174 get(team
, name
, NID_organizationalUnitName
);
2175 get(common
, name
, NID_commonName
);
2180 std::stringbuf backing
;
2182 if (!requirements
.empty()) {
2183 put(backing
, requirements
.data(), requirements
.size());
2187 std::stringbuf requirement
;
2188 req(requirement
, exprForm
);
2189 req(requirement
, opAnd
);
2190 req(requirement
, opIdent
);
2191 req(requirement
, identifier
);
2192 req(requirement
, opAnd
);
2193 req(requirement
, opAppleGenericAnchor
);
2194 req(requirement
, opAnd
);
2195 req(requirement
, opCertField
);
2196 req(requirement
, 0);
2197 req(requirement
, "subject.CN");
2198 req(requirement
, matchEqual
);
2199 req(requirement
, common
);
2200 req(requirement
, opCertGeneric
);
2201 req(requirement
, 1);
2202 req(requirement
, (uint8_t []) {APPLE_EXTENSION_OID
, 2, 1});
2203 req(requirement
, matchExists
);
2204 insert(blobs
, 3, CSMAGIC_REQUIREMENT
, requirement
);
2206 put(backing
, CSMAGIC_REQUIREMENTS
, blobs
);
2210 // XXX: this is just a "sufficiently large number"
2211 size_t certificate(0x3000);
2213 Allocate(idata
, isize
, output
, fun([&](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2214 size_t alloc(sizeof(struct SuperBlob
));
2216 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
2218 uint32_t special(0);
2220 _foreach (slot
, slots
)
2221 special
= std::max(special
, slot
.first
);
2223 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2224 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0)
2225 special
= std::max(special
, CSSLOT_INFOSLOT
);
2228 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
2229 alloc
+= sizeof(struct BlobIndex
);
2230 alloc
+= backing
.str().size();
2233 baton
.entitlements_
= entitlements
;
2236 Analyze(mach_header
, fun([&](const char *data
, size_t size
) {
2237 baton
.entitlements_
.assign(data
, size
);
2240 if (!baton
.entitlements_
.empty() || !entitlements
.empty()) {
2241 auto combined(plist(baton
.entitlements_
));
2242 _scope({ plist_free(combined
); });
2243 _assert(plist_get_node_type(combined
) == PLIST_DICT
);
2245 auto merging(plist(entitlements
));
2246 _scope({ plist_free(merging
); });
2247 _assert(plist_get_node_type(merging
) == PLIST_DICT
);
2249 plist_dict_iter
iterator(NULL
);
2250 plist_dict_new_iter(merging
, &iterator
);
2251 _scope({ free(iterator
); });
2255 plist_t
value(NULL
);
2256 plist_dict_next_item(merging
, iterator
, &key
, &value
);
2259 _scope({ free(key
); });
2260 plist_dict_set_item(combined
, key
, plist_copy(value
));
2263 baton
.derformat_
= der(combined
);
2267 plist_to_xml(combined
, &xml
, &size
);
2268 _scope({ free(xml
); });
2270 baton
.entitlements_
.assign(xml
, size
);
2274 if (!baton
.entitlements_
.empty()) {
2275 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
2276 alloc
+= sizeof(struct BlobIndex
);
2277 alloc
+= sizeof(struct Blob
);
2278 alloc
+= baton
.entitlements_
.size();
2281 if (!baton
.derformat_
.empty()) {
2282 special
= std::max(special
, CSSLOT_DERFORMAT
);
2283 alloc
+= sizeof(struct BlobIndex
);
2284 alloc
+= sizeof(struct Blob
);
2285 alloc
+= baton
.derformat_
.size();
2288 size_t directory(0);
2290 directory
+= sizeof(struct BlobIndex
);
2291 directory
+= sizeof(struct Blob
);
2292 directory
+= sizeof(struct CodeDirectory
);
2293 directory
+= identifier
.size() + 1;
2296 directory
+= team
.size() + 1;
2298 for (Algorithm
*algorithm
: GetAlgorithms())
2299 alloc
= Align(alloc
+ directory
+ (special
+ normal
) * algorithm
->size_
, 16);
2301 #ifndef LDID_NOSMIME
2303 alloc
+= sizeof(struct BlobIndex
);
2304 alloc
+= sizeof(struct Blob
);
2305 alloc
+= certificate
;
2310 }), 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 {
2314 insert(blobs
, CSSLOT_REQUIREMENTS
, backing
);
2318 if (mach_header
.Swap(mach_header
->filetype
) == MH_EXECUTE
)
2319 execs
|= kSecCodeExecSegMainBinary
;
2321 if (!baton
.entitlements_
.empty()) {
2322 std::stringbuf data
;
2323 put(data
, baton
.entitlements_
.data(), baton
.entitlements_
.size());
2324 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
2326 #ifndef LDID_NOPLIST
2327 auto entitlements(plist(baton
.entitlements_
));
2328 _scope({ plist_free(entitlements
); });
2329 _assert(plist_get_node_type(entitlements
) == PLIST_DICT
);
2331 const auto entitled([&](const char *key
) {
2332 auto item(plist_dict_get_item(entitlements
, key
));
2333 if (plist_get_node_type(item
) != PLIST_BOOLEAN
)
2336 plist_get_bool_val(item
, &value
);
2340 if (entitled("get-task-allow"))
2341 execs
|= kSecCodeExecSegAllowUnsigned
;
2342 if (entitled("run-unsigned-code"))
2343 execs
|= kSecCodeExecSegAllowUnsigned
;
2344 if (entitled("com.apple.private.cs.debugger"))
2345 execs
|= kSecCodeExecSegDebugger
;
2346 if (entitled("dynamic-codesigning"))
2347 execs
|= kSecCodeExecSegJit
;
2348 if (entitled("com.apple.private.skip-library-validation"))
2349 execs
|= kSecCodeExecSegSkipLibraryVal
;
2350 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2351 execs
|= kSecCodeExecSegCanLoadCdHash
;
2352 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2353 execs
|= kSecCodeExecSegCanExecCdHash
;
2357 if (!baton
.derformat_
.empty()) {
2358 std::stringbuf data
;
2359 put(data
, baton
.derformat_
.data(), baton
.derformat_
.size());
2360 insert(blobs
, CSSLOT_DERFORMAT
, CSMAGIC_EMBEDDED_DERFORMAT
, data
);
2365 mach_header
.ForSection(fun([&](const char *segment
, const char *section
, void *data
, size_t size
) {
2366 if (strcmp(segment
, "__TEXT") == 0 && section
!= NULL
&& strcmp(section
, "__info_plist") == 0) {
2367 auto &slot(posts
[CSSLOT_INFOSLOT
]);
2368 for (Algorithm
*algorithm
: GetAlgorithms())
2369 (*algorithm
)(slot
, data
, size
);
2374 for (Algorithm
*pointer
: GetAlgorithms()) {
2375 Algorithm
&algorithm(*pointer
);
2377 std::stringbuf data
;
2379 uint32_t special(0);
2380 _foreach (blob
, blobs
)
2381 special
= std::max(special
, blob
.first
);
2382 _foreach (slot
, posts
)
2383 special
= std::max(special
, slot
.first
);
2384 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
2386 CodeDirectory directory
;
2387 directory
.version
= Swap(uint32_t(0x00020400));
2388 directory
.flags
= Swap(uint32_t(flags
));
2389 directory
.nSpecialSlots
= Swap(special
);
2390 directory
.codeLimit
= Swap(uint32_t(limit
> UINT32_MAX
? UINT32_MAX
: limit
));
2391 directory
.nCodeSlots
= Swap(normal
);
2392 directory
.hashSize
= algorithm
.size_
;
2393 directory
.hashType
= algorithm
.type_
;
2394 directory
.platform
= platform
? 0x01 : 0x00;
2395 directory
.pageSize
= PageShift_
;
2396 directory
.spare2
= Swap(uint32_t(0));
2397 directory
.scatterOffset
= Swap(uint32_t(0));
2398 directory
.spare3
= Swap(uint32_t(0));
2399 directory
.codeLimit64
= Swap(uint64_t(limit
> UINT32_MAX
? limit
: 0));
2400 directory
.execSegBase
= Swap(uint64_t(left
));
2401 directory
.execSegLimit
= Swap(uint64_t(right
- left
));
2402 directory
.execSegFlags
= Swap(execs
);
2404 uint32_t offset(sizeof(Blob
) + sizeof(CodeDirectory
));
2406 directory
.identOffset
= Swap(uint32_t(offset
));
2407 offset
+= identifier
.size() + 1;
2410 directory
.teamIDOffset
= Swap(uint32_t(0));
2412 directory
.teamIDOffset
= Swap(uint32_t(offset
));
2413 offset
+= team
.size() + 1;
2416 offset
+= special
* algorithm
.size_
;
2417 directory
.hashOffset
= Swap(uint32_t(offset
));
2418 offset
+= normal
* algorithm
.size_
;
2420 put(data
, &directory
, sizeof(directory
));
2422 put(data
, identifier
.c_str(), identifier
.size() + 1);
2424 put(data
, team
.c_str(), team
.size() + 1);
2426 std::vector
<uint8_t> storage((special
+ normal
) * algorithm
.size_
);
2427 auto *hashes(&storage
[special
* algorithm
.size_
]);
2429 memset(storage
.data(), 0, special
* algorithm
.size_
);
2431 _foreach (blob
, blobs
) {
2432 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
2433 algorithm(hashes
- blob
.first
* algorithm
.size_
, local
, Swap(local
->length
));
2436 _foreach (slot
, posts
)
2437 memcpy(hashes
- slot
.first
* algorithm
.size_
, algorithm
[slot
.second
], algorithm
.size_
);
2441 for (size_t i
= 0; i
!= normal
- 1; ++i
) {
2442 algorithm(hashes
+ i
* algorithm
.size_
, (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
2443 progress(double(i
) / normal
);
2446 algorithm(hashes
+ (normal
- 1) * algorithm
.size_
, top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
2449 put(data
, storage
.data(), storage
.size());
2451 const auto &save(insert(blobs
, total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1, CSMAGIC_CODEDIRECTORY
, data
));
2452 algorithm(hash
, save
.data(), save
.size());
2457 #ifndef LDID_NOSMIME
2460 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
));
2461 _scope({ CFRelease(plist
); });
2463 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
));
2464 _scope({ CFRelease(cdhashes
); });
2466 CFDictionarySetValue(plist
, CFSTR("cdhashes"), cdhashes
);
2468 auto plist(plist_new_dict());
2469 _scope({ plist_free(plist
); });
2471 auto cdhashes(plist_new_array());
2472 plist_dict_set_item(plist
, "cdhashes", cdhashes
);
2478 for (Algorithm
*pointer
: GetAlgorithms()) {
2479 Algorithm
&algorithm(*pointer
);
2482 const auto &blob(blobs
[total
== 0 ? CSSLOT_CODEDIRECTORY
: CSSLOT_ALTERNATE
+ total
- 1]);
2485 algorithm(hash
, blob
.data(), blob
.size());
2487 std::vector
<char> cdhash(algorithm
[hash
], algorithm
[hash
] + algorithm
.size_
);
2491 auto value(CFDataCreate(kCFAllocatorDefault
, reinterpret_cast<const UInt8
*>(cdhash
.data()), cdhash
.size()));
2492 _scope({ CFRelease(value
); });
2493 CFArrayAppendValue(cdhashes
, value
);
2495 plist_array_append_item(cdhashes
, plist_new_data(cdhash
.data(), cdhash
.size()));
2500 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault
, plist
));
2501 _scope({ CFRelease(created
); });
2502 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created
)));
2503 auto size(CFDataGetLength(created
));
2507 plist_to_xml(plist
, &xml
, &size
);
2508 _scope({ free(xml
); });
2511 std::stringbuf data
;
2512 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
2517 Signature
signature(stuff
, sign
, std::string(xml
, size
), hash
);
2518 Buffer
result(signature
);
2519 std::string
value(result
);
2520 put(data
, value
.data(), value
.size());
2522 const auto &save(insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
));
2523 _assert(save
.size() <= certificate
);
2527 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
2533 #ifndef LDID_NOTOOLS
2534 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
, const Progress
&progress
) {
2535 Allocate(idata
, isize
, output
, fun([](const MachHeader
&mach_header
, Baton
&baton
, size_t size
) -> size_t {
2537 }), 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 {
2542 std::string
DiskFolder::Path(const std::string
&path
) const {
2543 return path_
+ path
;
2546 DiskFolder::DiskFolder(const std::string
&path
) :
2549 _assert_(path_
.size() != 0 && path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2552 DiskFolder::~DiskFolder() {
2553 if (!std::uncaught_exception())
2554 for (const auto &commit
: commit_
)
2555 Commit(commit
.first
, commit
.second
);
2559 std::string
readlink(const std::string
&path
) {
2560 for (size_t size(1024); ; size
*= 2) {
2564 int writ(_syscall(::readlink(path
.c_str(), &data
[0], data
.size())));
2565 if (size_t(writ
) >= size
)
2574 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 {
2575 std::string
path(Path(root
) + base
);
2577 DIR *dir(opendir(path
.c_str()));
2578 _assert(dir
!= NULL
);
2579 _scope({ _syscall(closedir(dir
)); });
2581 while (auto child
= readdir(dir
)) {
2582 std::string
name(child
->d_name
);
2583 if (name
== "." || name
== "..")
2585 if (Starts(name
, ".ldid."))
2592 _syscall(stat((path
+ name
).c_str(), &info
));
2594 else if (S_ISDIR(info
.st_mode
))
2596 else if (S_ISREG(info
.st_mode
))
2599 _assert_(false, "st_mode=%x", info
.st_mode
);
2601 switch (child
->d_type
) {
2609 link(base
+ name
, fun([&]() { return readlink(path
+ name
); }));
2612 _assert_(false, "d_type=%u", child
->d_type
);
2617 Find(root
, base
+ name
+ "/", code
, link
);
2623 void DiskFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2629 auto from(Path(path
));
2630 commit_
[from
] = Temporary(save
, from
);
2635 bool DiskFolder::Look(const std::string
&path
) const {
2636 return _syscall(access(Path(path
).c_str(), R_OK
), ENOENT
) == 0;
2639 void DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2641 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
2642 _assert_(result
== &data
, "DiskFolder::Open(%s)", Path(path
).c_str());
2644 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2645 data
.pubseekpos(0, std::ios::in
);
2646 code(data
, length
, NULL
);
2649 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 {
2650 Find(path
, "", code
, link
);
2654 SubFolder::SubFolder(Folder
&parent
, const std::string
&path
) :
2658 _assert_(path_
.size() == 0 || path_
[path_
.size() - 1] == '/', "missing / on %s", path_
.c_str());
2661 std::string
SubFolder::Path(const std::string
&path
) const {
2662 return path_
+ path
;
2665 void SubFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2666 return parent_
.Save(Path(path
), edit
, flag
, code
);
2669 bool SubFolder::Look(const std::string
&path
) const {
2670 return parent_
.Look(Path(path
));
2673 void SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2674 return parent_
.Open(Path(path
), code
);
2677 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 {
2678 return parent_
.Find(Path(path
), code
, link
);
2681 std::string
UnionFolder::Map(const std::string
&path
) const {
2682 auto remap(remaps_
.find(path
));
2683 if (remap
== remaps_
.end())
2685 return remap
->second
;
2688 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 {
2689 if (file
.size() >= path
.size() && file
.substr(0, path
.size()) == path
)
2690 code(file
.substr(path
.size()));
2693 UnionFolder::UnionFolder(Folder
&parent
) :
2698 void UnionFolder::Save(const std::string
&path
, bool edit
, const void *flag
, const Functor
<void (std::streambuf
&)> &code
) {
2699 return parent_
.Save(Map(path
), edit
, flag
, code
);
2702 bool UnionFolder::Look(const std::string
&path
) const {
2703 auto file(resets_
.find(path
));
2704 if (file
!= resets_
.end())
2706 return parent_
.Look(Map(path
));
2709 void UnionFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) const {
2710 auto file(resets_
.find(path
));
2711 if (file
== resets_
.end())
2712 return parent_
.Open(Map(path
), code
);
2713 auto &entry(file
->second
);
2715 auto &data(*entry
.data_
);
2716 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2717 data
.pubseekpos(0, std::ios::in
);
2718 code(data
, length
, entry
.flag_
);
2721 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 {
2722 for (auto &reset
: resets_
)
2723 Map(path
, code
, reset
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2724 auto &entry(reset
.second
);
2725 auto &data(*entry
.data_
);
2726 auto length(data
.pubseekoff(0, std::ios::end
, std::ios::in
));
2727 data
.pubseekpos(0, std::ios::in
);
2728 code(data
, length
, entry
.flag_
);
2731 for (auto &remap
: remaps_
)
2732 Map(path
, code
, remap
.first
, fun([&](const Functor
<void (std::streambuf
&, size_t, const void *)> &code
) {
2733 parent_
.Open(remap
.second
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
2734 code(data
, length
, flag
);
2738 parent_
.Find(path
, fun([&](const std::string
&name
) {
2739 if (deletes_
.find(path
+ name
) == deletes_
.end())
2741 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
2742 if (deletes_
.find(path
+ name
) == deletes_
.end())
2747 #ifndef LDID_NOTOOLS
2748 static void copy(std::streambuf
&source
, std::streambuf
&target
, size_t length
, const Progress
&progress
) {
2752 char data
[4096 * 4];
2753 size_t writ(source
.sgetn(data
, sizeof(data
)));
2756 _assert(target
.sputn(data
, writ
) == writ
);
2758 progress(double(total
) / length
);
2762 #ifndef LDID_NOPLIST
2763 static plist_t
plist(const std::string
&data
) {
2765 return plist_new_dict();
2766 plist_t
plist(NULL
);
2767 if (Starts(data
, "bplist00"))
2768 plist_from_bin(data
.data(), data
.size(), &plist
);
2770 plist_from_xml(data
.data(), data
.size(), &plist
);
2771 _assert(plist
!= NULL
);
2775 static void plist_d(std::streambuf
&buffer
, size_t length
, const Functor
<void (plist_t
)> &code
) {
2776 std::stringbuf data
;
2777 copy(buffer
, data
, length
, dummy_
);
2778 auto node(plist(data
.str()));
2779 _scope({ plist_free(node
); });
2780 _assert(plist_get_node_type(node
) == PLIST_DICT
);
2784 static std::string
plist_s(plist_t node
) {
2785 _assert(node
!= NULL
);
2786 _assert(plist_get_node_type(node
) == PLIST_STRING
);
2788 plist_get_string_val(node
, &data
);
2789 _scope({ free(data
); });
2805 std::vector
<std::string
> matches_
;
2808 Expression(const std::string
&code
) {
2809 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
) == 0, "regcomp()");
2810 matches_
.resize(regex_
.re_nsub
+ 1);
2817 bool operator ()(const std::string
&data
) {
2818 regmatch_t matches
[matches_
.size()];
2819 auto value(regexec(®ex_
, data
.c_str(), matches_
.size(), matches
, 0));
2820 if (value
== REG_NOMATCH
)
2822 _assert_(value
== 0, "regexec()");
2823 for (size_t i(0); i
!= matches_
.size(); ++i
)
2824 matches_
[i
].assign(data
.data() + matches
[i
].rm_so
, matches
[i
].rm_eo
- matches
[i
].rm_so
);
2828 const std::string
&operator [](size_t index
) const {
2829 return matches_
[index
];
2838 mutable std::auto_ptr
<Expression
> regex_
;
2840 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
2847 Rule(const Rule
&rhs
) :
2848 weight_(rhs
.weight_
),
2854 void Compile() const {
2855 regex_
.reset(new Expression(code_
));
2858 bool operator ()(const std::string
&data
) const {
2859 _assert(regex_
.get() != NULL
);
2860 return (*regex_
)(data
);
2863 bool operator <(const Rule
&rhs
) const {
2864 if (weight_
> rhs
.weight_
)
2866 if (weight_
< rhs
.weight_
)
2868 return mode_
> rhs
.mode_
;
2873 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
2874 return lhs
->code_
< rhs
->code_
;
2878 #ifndef LDID_NOPLIST
2879 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
) {
2880 // XXX: this is a miserable fail
2881 std::stringbuf temp
;
2882 put(temp
, prefix
, size
);
2883 copy(buffer
, temp
, length
- size
, progress
);
2884 // XXX: this is a stupid hack
2885 pad(temp
, 0x10 - (length
& 0xf));
2886 auto data(temp
.str());
2888 HashProxy
proxy(hash
, save
);
2889 return Sign(data
.data(), data
.size(), proxy
, identifier
, entitlements
, merge
, requirements
, key
, slots
, flags
, platform
, progress
);
2893 std::map
<std::string
, Hash
> files
;
2894 std::map
<std::string
, std::string
> links
;
2896 void Merge(const std::string
&root
, const State
&state
) {
2897 for (const auto &entry
: state
.files
)
2898 files
[root
+ entry
.first
] = entry
.second
;
2899 for (const auto &entry
: state
.links
)
2900 links
[root
+ entry
.first
] = entry
.second
;
2904 Bundle
Sign(const std::string
&root
, Folder
&parent
, const std::string
&key
, State
&local
, const std::string
&requirements
, const Functor
<std::string (const std::string
&, const std::string
&)> &alter
, const Progress
&progress
) {
2905 std::string executable
;
2906 std::string identifier
;
2910 std::string
info("Info.plist");
2912 SubFolder
folder(parent
, [&]() {
2913 if (parent
.Look(info
))
2917 else if (parent
.Look("Contents/" + info
))
2919 else if (parent
.Look("Resources/" + info
)) {
2920 info
= "Resources/" + info
;
2922 } else _assert_(false, "cannot find Info.plist");
2925 folder
.Open(info
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2926 plist_d(buffer
, length
, fun([&](plist_t node
) {
2927 executable
= plist_s(plist_dict_get_item(node
, "CFBundleExecutable"));
2928 identifier
= plist_s(plist_dict_get_item(node
, "CFBundleIdentifier"));
2932 if (mac
&& info
== "Info.plist")
2933 executable
= "MacOS/" + executable
;
2935 progress(root
+ "*");
2937 std::string entitlements
;
2938 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
2939 // XXX: this is a miserable fail
2940 std::stringbuf temp
;
2941 copy(buffer
, temp
, length
, progress
);
2942 // XXX: this is a stupid hack
2943 pad(temp
, 0x10 - (length
& 0xf));
2944 auto data(temp
.str());
2945 entitlements
= alter(root
, Analyze(data
.data(), data
.size()));
2948 static const std::string
directory("_CodeSignature/");
2949 static const std::string
signature(directory
+ "CodeResources");
2951 std::map
<std::string
, std::multiset
<Rule
>> versions
;
2953 auto &rules1(versions
[""]);
2954 auto &rules2(versions
["2"]);
2956 const std::string
resources(mac
? "Resources/" : "");
2959 rules1
.insert(Rule
{1, NoMode
, "^" + (resources
== "" ? ".*" : resources
)});
2960 rules1
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2961 rules1
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2962 rules1
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2963 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
2967 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
2968 if (mac
) rules2
.insert(Rule
{20, NoMode
, "^" + resources
});
2969 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
2970 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2971 rules2
.insert(Rule
{1, NoMode
, "^.*"});
2972 rules2
.insert(Rule
{1000, OptionalMode
, "^" + resources
+ ".*\\.lproj/"});
2973 rules2
.insert(Rule
{1100, OmitMode
, "^" + resources
+ ".*\\.lproj/locversion.plist$"});
2974 if (!mac
) rules2
.insert(Rule
{1010, NoMode
, "^Base\\.lproj/"});
2975 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
2976 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
2977 if (mac
) rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
2978 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
2979 if (mac
) rules2
.insert(Rule
{1010, NoMode
, "^" + resources
+ "Base\\.lproj/"});
2980 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
2983 std::string
failure(mac
? "Contents/|Versions/[^/]*/Resources/" : "");
2984 Expression
nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure
+ ")Info\\.plist$");
2985 std::map
<std::string
, Bundle
> bundles
;
2987 folder
.Find("", fun([&](const std::string
&name
) {
2990 auto bundle(Split(name
).dir
);
2992 _assert(!bundle
.empty());
2993 bundle
= Split(bundle
.substr(0, bundle
.size() - 1)).dir
;
2995 SubFolder
subfolder(folder
, bundle
);
2998 bundles
[nested
[1]] = Sign(root
+ bundle
, subfolder
, key
, remote
, "", Starts(name
, "PlugIns/") ? alter
:
2999 static_cast<const Functor
<std::string (const std::string
&, const std::string
&)> &>(fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }))
3001 local
.Merge(bundle
, remote
);
3002 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
3005 std::set
<std::string
> excludes
;
3007 auto exclude([&](const std::string
&name
) {
3008 // BundleDiskRep::adjustResources -> builder.addExclusion
3009 if (name
== executable
|| Starts(name
, directory
) || Starts(name
, "_MASReceipt/") || name
== "CodeResources")
3012 for (const auto &bundle
: bundles
)
3013 if (Starts(name
, bundle
.first
+ "/")) {
3014 excludes
.insert(name
);
3021 folder
.Find("", fun([&](const std::string
&name
) {
3025 if (local
.files
.find(name
) != local
.files
.end())
3027 auto &hash(local
.files
[name
]);
3029 folder
.Open(name
, fun([&](std::streambuf
&data
, size_t length
, const void *flag
) {
3030 progress(root
+ name
);
3041 auto size(most(data
, &header
.bytes
, sizeof(header
.bytes
)));
3043 if (name
!= "_WatchKitStub/WK" && size
== sizeof(header
.bytes
))
3044 switch (Swap(header
.magic
)) {
3046 // Java class file format
3047 if (Swap(header
.count
) >= 40)
3050 case MH_MAGIC
: case MH_MAGIC_64
:
3051 case MH_CIGAM
: case MH_CIGAM_64
:
3052 folder
.Save(name
, true, flag
, fun([&](std::streambuf
&save
) {
3054 Sign(header
.bytes
, size
, data
, hash
, save
, identifier
, "", false, "", key
, slots
, length
, 0, false, Progression(progress
, root
+ name
));
3059 folder
.Save(name
, false, flag
, fun([&](std::streambuf
&save
) {
3060 HashProxy
proxy(hash
, save
);
3061 put(proxy
, header
.bytes
, size
);
3062 copy(data
, proxy
, length
- size
, progress
);
3065 }), fun([&](const std::string
&name
, const Functor
<std::string ()> &read
) {
3069 local
.links
[name
] = read();
3072 auto plist(plist_new_dict());
3073 _scope({ plist_free(plist
); });
3075 for (const auto &version
: versions
) {
3076 auto files(plist_new_dict());
3077 plist_dict_set_item(plist
, ("files" + version
.first
).c_str(), files
);
3079 for (const auto &rule
: version
.second
)
3082 bool old(&version
.second
== &rules1
);
3084 for (const auto &hash
: local
.files
)
3085 for (const auto &rule
: version
.second
)
3086 if (rule(hash
.first
)) {
3087 if (!old
&& mac
&& excludes
.find(hash
.first
) != excludes
.end());
3088 else if (old
&& rule
.mode_
== NoMode
)
3089 plist_dict_set_item(files
, hash
.first
.c_str(), plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3090 else if (rule
.mode_
!= OmitMode
) {
3091 auto entry(plist_new_dict());
3092 plist_dict_set_item(entry
, "hash", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha1_
), sizeof(hash
.second
.sha1_
)));
3094 plist_dict_set_item(entry
, "hash2", plist_new_data(reinterpret_cast<const char *>(hash
.second
.sha256_
), sizeof(hash
.second
.sha256_
)));
3095 if (rule
.mode_
== OptionalMode
)
3096 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3097 plist_dict_set_item(files
, hash
.first
.c_str(), entry
);
3104 for (const auto &link
: local
.links
)
3105 for (const auto &rule
: version
.second
)
3106 if (rule(link
.first
)) {
3107 if (rule
.mode_
!= OmitMode
) {
3108 auto entry(plist_new_dict());
3109 plist_dict_set_item(entry
, "symlink", plist_new_string(link
.second
.c_str()));
3110 if (rule
.mode_
== OptionalMode
)
3111 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3112 plist_dict_set_item(files
, link
.first
.c_str(), entry
);
3119 for (const auto &bundle
: bundles
) {
3120 auto entry(plist_new_dict());
3121 plist_dict_set_item(entry
, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle
.second
.hash
.sha256_
), sizeof(bundle
.second
.hash
.sha256_
)));
3122 plist_dict_set_item(entry
, "requirement", plist_new_string("anchor apple generic"));
3123 plist_dict_set_item(files
, bundle
.first
.c_str(), entry
);
3127 for (const auto &version
: versions
) {
3128 auto rules(plist_new_dict());
3129 plist_dict_set_item(plist
, ("rules" + version
.first
).c_str(), rules
);
3131 std::multiset
<const Rule
*, RuleCode
> ordered
;
3132 for (const auto &rule
: version
.second
)
3133 ordered
.insert(&rule
);
3135 for (const auto &rule
: ordered
)
3136 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
3137 plist_dict_set_item(rules
, rule
->code_
.c_str(), plist_new_bool(true));
3139 auto entry(plist_new_dict());
3140 plist_dict_set_item(rules
, rule
->code_
.c_str(), entry
);
3142 switch (rule
->mode_
) {
3146 plist_dict_set_item(entry
, "omit", plist_new_bool(true));
3149 plist_dict_set_item(entry
, "optional", plist_new_bool(true));
3152 plist_dict_set_item(entry
, "nested", plist_new_bool(true));
3155 plist_dict_set_item(entry
, "top", plist_new_bool(true));
3159 if (rule
->weight_
>= 10000)
3160 plist_dict_set_item(entry
, "weight", plist_new_uint(rule
->weight_
));
3161 else if (rule
->weight_
!= 1)
3162 plist_dict_set_item(entry
, "weight", plist_new_real(rule
->weight_
));
3166 folder
.Save(signature
, true, NULL
, fun([&](std::streambuf
&save
) {
3167 HashProxy
proxy(local
.files
[signature
], save
);
3170 plist_to_xml(plist
, &xml
, &size
);
3171 _scope({ free(xml
); });
3172 put(proxy
, xml
, size
);
3176 bundle
.path
= folder
.Path(executable
);
3178 folder
.Open(executable
, fun([&](std::streambuf
&buffer
, size_t length
, const void *flag
) {
3179 progress(root
+ executable
);
3180 folder
.Save(executable
, true, flag
, fun([&](std::streambuf
&save
) {
3182 slots
[1] = local
.files
.at(info
);
3183 slots
[3] = local
.files
.at(signature
);
3184 bundle
.hash
= Sign(NULL
, 0, buffer
, local
.files
[executable
], save
, identifier
, entitlements
, false, requirements
, key
, slots
, length
, 0, false, Progression(progress
, root
+ executable
));
3191 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
) {
3193 return Sign(root
, folder
, key
, local
, requirements
, alter
, progress
);
3200 std::string
Hex(const uint8_t *data
, size_t size
) {
3202 hex
.reserve(size
* 2);
3203 for (size_t i(0); i
!= size
; ++i
) {
3204 hex
+= "0123456789abcdef"[data
[i
] >> 4];
3205 hex
+= "0123456789abcdef"[data
[i
] & 0xf];
3210 static void usage(const char *argv0
) {
3211 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv0
);
3212 fprintf(stderr
, " %s -e MobileSafari\n", argv0
);
3213 fprintf(stderr
, " %s -S cat\n", argv0
);
3214 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv0
);
3217 #ifndef LDID_NOTOOLS
3218 int main(int argc
, char *argv
[]) {
3219 #ifndef LDID_NOSMIME
3220 OpenSSL_add_all_algorithms();
3228 little_
= endian
.byte
[0];
3238 #ifndef LDID_NOFLAGT
3256 bool platform(false);
3258 uint32_t flag_CPUType(_not(uint32_t));
3259 uint32_t flag_CPUSubtype(_not(uint32_t));
3261 const char *flag_I(NULL
);
3263 #ifndef LDID_NOFLAGT
3273 std::vector
<std::string
> files
;
3280 for (int argi(1); argi
!= argc
; ++argi
)
3281 if (argv
[argi
][0] != '-')
3282 files
.push_back(argv
[argi
]);
3283 else switch (argv
[argi
][1]) {
3290 case 'e': flag_e
= true; break;
3293 const char *string
= argv
[argi
] + 2;
3294 const char *colon
= strchr(string
, ':');
3295 _assert(colon
!= NULL
);
3296 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3298 unsigned number(strtoul(string
, &arge
, 0));
3299 _assert(arge
== colon
);
3300 auto &slot(slots
[number
]);
3301 for (Algorithm
*algorithm
: GetAlgorithms())
3302 (*algorithm
)(slot
, file
.data(), file
.size());
3305 case 'q': flag_q
= true; break;
3308 const char *hash
= argv
[argi
] + 2;
3316 fprintf(stderr
, "WARNING: -H is only present for compatibility with a fork of ldid\n");
3317 fprintf(stderr
, " you should NOT be manually specifying the hash algorithm\n");
3321 else if (strcmp(hash
, "sha1") == 0)
3323 else if (strcmp(hash
, "sha256") == 0)
3325 else _assert(false);
3328 case 'h': flag_h
= true; break;
3331 const char *xml
= argv
[argi
] + 2;
3332 requirements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3335 case 'D': flag_D
= true; break;
3336 case 'd': flag_d
= true; break;
3338 case 'a': flag_a
= true; break;
3343 if (argv
[argi
][2] != '\0') {
3344 const char *cpu
= argv
[argi
] + 2;
3345 const char *colon
= strchr(cpu
, ':');
3346 _assert(colon
!= NULL
);
3348 flag_CPUType
= strtoul(cpu
, &arge
, 0);
3349 _assert(arge
== colon
);
3350 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
3351 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3356 const char *name
= argv
[argi
] + 2;
3358 else if (strcmp(name
, "host") == 0)
3359 flags
|= kSecCodeSignatureHost
;
3360 else if (strcmp(name
, "adhoc") == 0)
3361 flags
|= kSecCodeSignatureAdhoc
;
3362 else if (strcmp(name
, "hard") == 0)
3363 flags
|= kSecCodeSignatureForceHard
;
3364 else if (strcmp(name
, "kill") == 0)
3365 flags
|= kSecCodeSignatureForceKill
;
3366 else if (strcmp(name
, "expires") == 0)
3367 flags
|= kSecCodeSignatureForceExpiration
;
3368 else if (strcmp(name
, "restrict") == 0)
3369 flags
|= kSecCodeSignatureRestrict
;
3370 else if (strcmp(name
, "enforcement") == 0)
3371 flags
|= kSecCodeSignatureEnforcement
;
3372 else if (strcmp(name
, "library-validation") == 0)
3373 flags
|= kSecCodeSignatureLibraryValidation
;
3374 else if (strcmp(name
, "runtime") == 0)
3375 flags
|= kSecCodeSignatureRuntime
;
3376 else _assert(false);
3393 if (argv
[argi
][2] != '\0') {
3394 const char *xml
= argv
[argi
] + 2;
3395 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3408 if (argv
[argi
][2] != '\0')
3409 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3412 #ifndef LDID_NOFLAGT
3415 if (argv
[argi
][2] == '-')
3419 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
3420 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
3430 flag_I
= argv
[argi
] + 2;
3439 _assert(flag_S
|| key
.empty());
3440 _assert(flag_S
|| flag_I
== NULL
);
3442 if (flag_d
&& !flag_h
) {
3444 fprintf(stderr
, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3450 size_t filei(0), filee(0);
3451 _foreach (file
, files
) try {
3452 std::string
path(file
);
3455 _syscall(stat(path
.c_str(), &info
));
3457 if (S_ISDIR(info
.st_mode
)) {
3459 #ifndef LDID_NOPLIST
3460 ldid::DiskFolder
folder(path
+ "/");
3461 path
+= "/" + Sign("", folder
, key
, requirements
, ldid::fun([&](const std::string
&, const std::string
&) -> std::string
{ return entitlements
; }), dummy_
).path
;
3465 } else if (flag_S
|| flag_r
) {
3466 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
3468 std::filebuf output
;
3470 auto temp(Temporary(output
, split
));
3473 ldid::Unsign(input
.data(), input
.size(), output
, dummy_
);
3475 std::string
identifier(flag_I
?: split
.base
.c_str());
3476 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, flag_M
, requirements
, key
, slots
, flags
, platform
, dummy_
);
3483 #ifndef LDID_NOFLAGT
3490 Map
mapping(path
, modify
);
3491 FatHeader
fat_header(mapping
.data(), mapping
.size());
3493 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
3494 struct linkedit_data_command
*signature(NULL
);
3495 struct encryption_info_command
*encryption(NULL
);
3498 if (mach_header
.GetCPUType() != flag_CPUType
)
3500 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
3505 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
3507 _foreach (load_command
, mach_header
.GetLoadCommands()) {
3508 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
3511 else if (cmd
== LC_CODE_SIGNATURE
)
3512 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
3513 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
3514 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
3515 else if (cmd
== LC_LOAD_DYLIB
) {
3516 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3517 const char *name(reinterpret_cast<const char *>(load_command
) + mach_header
.Swap(dylib_command
->dylib
.name
));
3519 if (strcmp(name
, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3522 version
.value
= mach_header
.Swap(dylib_command
->dylib
.current_version
);
3523 printf("uikit=%u.%u.%u\n", version
.major
, version
.minor
, version
.patch
);
3527 #ifndef LDID_NOFLAGT
3528 else if (cmd
== LC_ID_DYLIB
) {
3529 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
3537 dylib_command
->dylib
.timestamp
= 0;
3538 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
3541 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
3547 if (flag_d
&& encryption
!= NULL
) {
3548 printf("cryptid=%d\n", mach_header
.Swap(encryption
->cryptid
));
3552 _assert(encryption
!= NULL
);
3553 encryption
->cryptid
= mach_header
.Swap(0);
3557 _assert(signature
!= NULL
);
3559 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3561 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3562 uint8_t *blob
= top
+ data
;
3563 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3565 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3566 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
3567 uint32_t begin
= Swap(super
->index
[index
].offset
);
3568 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3569 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
3574 _assert(signature
!= NULL
);
3576 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3578 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3579 uint8_t *blob
= top
+ data
;
3580 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3582 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3583 if (Swap(super
->index
[index
].type
) == CSSLOT_REQUIREMENTS
) {
3584 uint32_t begin
= Swap(super
->index
[index
].offset
);
3585 struct Blob
*requirement
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3586 // XXX: this is obviously wrong. but like, -Q is also wrong?!
3587 // maybe I can fix all of this just by fixing both -q and -Q?
3588 fwrite(requirement
, 1, Swap(requirement
->length
), stdout
);
3593 _assert(signature
!= NULL
);
3595 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3597 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3598 uint8_t *blob
= top
+ data
;
3599 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3601 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3602 if (Swap(super
->index
[index
].type
) == CSSLOT_SIGNATURESLOT
) {
3603 uint32_t begin
= Swap(super
->index
[index
].offset
);
3604 struct Blob
*signature
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
3605 fwrite(signature
+ 1, 1, Swap(signature
->length
) - sizeof(*signature
), stdout
);
3610 _assert(signature
!= NULL
);
3612 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3614 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3615 uint8_t *blob
= top
+ data
;
3616 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3618 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
3619 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
3620 uint32_t begin
= Swap(super
->index
[index
].offset
);
3621 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3623 uint8_t (*hashes
)[LDID_SHA1_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
3624 uint32_t pages
= Swap(directory
->nCodeSlots
);
3627 for (size_t i
= 0; i
!= pages
- 1; ++i
)
3628 LDID_SHA1(top
+ PageSize_
* i
, PageSize_
, hashes
[i
]);
3630 LDID_SHA1(top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1, hashes
[pages
- 1]);
3635 _assert(signature
!= NULL
);
3637 auto algorithms(GetAlgorithms());
3639 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
3641 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
3642 uint8_t *blob
= top
+ data
;
3643 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
3646 CodeDirectory
*directory_
;
3648 Algorithm
&algorithm_
;
3652 std::map
<uint8_t, Candidate
> candidates
;
3654 for (size_t index(0); index
!= Swap(super
->count
); ++index
) {
3655 auto type(Swap(super
->index
[index
].type
));
3656 if ((type
== CSSLOT_CODEDIRECTORY
|| type
>= CSSLOT_ALTERNATE
) && type
!= CSSLOT_SIGNATURESLOT
) {
3657 uint32_t begin
= Swap(super
->index
[index
].offset
);
3658 uint32_t end
= index
+ 1 == Swap(super
->count
) ? Swap(super
->blob
.length
) : Swap(super
->index
[index
+ 1].offset
);
3659 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
+ sizeof(Blob
));
3660 auto type(directory
->hashType
);
3661 _assert(type
> 0 && type
<= algorithms
.size());
3662 auto &algorithm(*algorithms
[type
- 1]);
3663 uint8_t hash
[algorithm
.size_
];
3664 algorithm(hash
, blob
+ begin
, end
- begin
);
3665 candidates
.insert({type
, {directory
, end
- begin
, algorithm
, Hex(hash
, 20)}});
3669 _assert(!candidates
.empty());
3670 auto best(candidates
.end());
3673 const auto directory(best
->second
.directory_
);
3674 const auto flags(Swap(directory
->flags
));
3677 if (flags
& kSecCodeSignatureHost
)
3679 if (flags
& kSecCodeSignatureAdhoc
)
3681 if (flags
& kSecCodeSignatureForceHard
)
3683 if (flags
& kSecCodeSignatureForceKill
)
3685 if (flags
& kSecCodeSignatureForceExpiration
)
3686 names
+= ",expires";
3687 if (flags
& kSecCodeSignatureRestrict
)
3688 names
+= ",restrict";
3689 if (flags
& kSecCodeSignatureEnforcement
)
3690 names
+= ",enforcement";
3691 if (flags
& kSecCodeSignatureLibraryValidation
)
3692 names
+= ",library-validation";
3693 if (flags
& kSecCodeSignatureRuntime
)
3694 names
+= ",runtime";
3696 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3697 Swap(directory
->version
), best
->second
.size_
, flags
, names
.empty() ? "none" : names
.c_str() + 1, Swap(directory
->nCodeSlots
), Swap(directory
->nSpecialSlots
));
3698 printf("Hash type=%s size=%d\n", best
->second
.algorithm_
.name(), directory
->hashSize
);
3700 std::string choices
;
3701 for (const auto &candidate
: candidates
) {
3702 auto choice(candidate
.second
.algorithm_
.name());
3705 printf("CandidateCDHash %s=%s\n", choice
, candidate
.second
.hash_
.c_str());
3707 printf("Hash choices=%s\n", choices
.c_str() + 1);
3709 printf("CDHash=%s\n", best
->second
.hash_
.c_str());
3714 } catch (const char *) {