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/>.
42 #include <sys/types.h>
44 #include <openssl/err.h>
45 #include <openssl/pem.h>
46 #include <openssl/pkcs7.h>
47 #include <openssl/pkcs12.h>
48 #include <openssl/sha.h>
50 #include <plist/plist++.h>
54 #define _assert___(line) \
56 #define _assert__(line) \
59 #define _assert_(expr, format, ...) \
61 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
62 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
65 #define _assert(expr) \
66 _assert_(expr, "%s", #expr)
68 #define _syscall(expr, ...) [&] { for (;;) { \
70 if ((long) _value != -1) \
75 for (auto success : (long[]) {__VA_ARGS__}) \
76 if (error == success) \
77 return (decltype(expr)) -success; \
78 _assert_(false, "errno=%u", error); \
82 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
88 __attribute__((packed))
90 template <typename Type_
>
92 typedef typename
Type_::const_iterator Result
;
95 #define _foreach(item, list) \
96 for (bool _stop(true); _stop; ) \
97 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
98 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
99 for (bool _suck(true); _suck; _suck = false) \
100 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
105 template <typename Function_
>
113 Scope(const Function_
&function
) :
123 template <typename Function_
>
124 Scope
<Function_
> _scope(const Function_
&function
) {
125 return Scope
<Function_
>(function
);
128 #define _scope__(counter, function) \
129 __attribute__((__unused__)) \
130 const _Scope &_scope ## counter(_scope([&]function))
131 #define _scope_(counter, function) \
132 _scope__(counter, function)
133 #define _scope(function) \
134 _scope_(__COUNTER__, function)
141 #define FAT_MAGIC 0xcafebabe
142 #define FAT_CIGAM 0xbebafeca
162 #define MH_MAGIC 0xfeedface
163 #define MH_CIGAM 0xcefaedfe
165 #define MH_MAGIC_64 0xfeedfacf
166 #define MH_CIGAM_64 0xcffaedfe
168 #define MH_DYLDLINK 0x4
170 #define MH_OBJECT 0x1
171 #define MH_EXECUTE 0x2
173 #define MH_BUNDLE 0x8
174 #define MH_DYLIB_STUB 0x9
176 struct load_command
{
181 #define LC_REQ_DYLD uint32_t(0x80000000)
183 #define LC_SEGMENT uint32_t(0x01)
184 #define LC_SYMTAB uint32_t(0x02)
185 #define LC_DYSYMTAB uint32_t(0x0b)
186 #define LC_LOAD_DYLIB uint32_t(0x0c)
187 #define LC_ID_DYLIB uint32_t(0x0d)
188 #define LC_SEGMENT_64 uint32_t(0x19)
189 #define LC_UUID uint32_t(0x1b)
190 #define LC_CODE_SIGNATURE uint32_t(0x1d)
191 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
192 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
193 #define LC_ENCRYPTION_INFO uint32_t(0x21)
194 #define LC_DYLD_INFO uint32_t(0x22)
195 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
196 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
201 uint32_t current_version
;
202 uint32_t compatibility_version
;
205 struct dylib_command
{
211 struct uuid_command
{
217 struct symtab_command
{
226 struct dyld_info_command
{
230 uint32_t rebase_size
;
233 uint32_t weak_bind_off
;
234 uint32_t weak_bind_size
;
235 uint32_t lazy_bind_off
;
236 uint32_t lazy_bind_size
;
238 uint32_t export_size
;
241 struct dysymtab_command
{
254 uint32_t extrefsymoff
;
255 uint32_t nextrefsyms
;
256 uint32_t indirectsymoff
;
257 uint32_t nindirectsyms
;
264 struct dylib_table_of_contents
{
265 uint32_t symbol_index
;
266 uint32_t module_index
;
269 struct dylib_module
{
270 uint32_t module_name
;
279 uint32_t iinit_iterm
;
280 uint32_t ninit_nterm
;
281 uint32_t objc_module_info_addr
;
282 uint32_t objc_module_info_size
;
285 struct dylib_reference
{
290 struct relocation_info
{
292 uint32_t r_symbolnum
:24;
311 struct segment_command
{
325 struct segment_command_64
{
367 struct linkedit_data_command
{
374 struct encryption_info_command
{
382 #define BIND_OPCODE_MASK 0xf0
383 #define BIND_IMMEDIATE_MASK 0x0f
384 #define BIND_OPCODE_DONE 0x00
385 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
386 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
387 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
388 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
389 #define BIND_OPCODE_SET_TYPE_IMM 0x50
390 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
391 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
392 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
393 #define BIND_OPCODE_DO_BIND 0x90
394 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
395 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
396 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
398 inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
399 _assert(stream
.sgetn(static_cast<char *>(data
), size
) == size
);
402 inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
403 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
406 inline void pad(std::streambuf
&stream
, size_t size
) {
408 memset(padding
, 0, size
);
409 put(stream
, padding
, size
);
412 template <typename Type_
>
413 Type_
Align(Type_ value
, size_t align
) {
420 static const uint8_t PageShift_(0x0c);
421 static const uint32_t PageSize_(1 << PageShift_
);
423 static inline uint16_t Swap_(uint16_t value
) {
425 ((value
>> 8) & 0x00ff) |
426 ((value
<< 8) & 0xff00);
429 static inline uint32_t Swap_(uint32_t value
) {
430 value
= ((value
>> 8) & 0x00ff00ff) |
431 ((value
<< 8) & 0xff00ff00);
432 value
= ((value
>> 16) & 0x0000ffff) |
433 ((value
<< 16) & 0xffff0000);
437 static inline uint64_t Swap_(uint64_t value
) {
438 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
439 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
440 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
444 static inline int16_t Swap_(int16_t value
) {
445 return Swap_(static_cast<uint16_t>(value
));
448 static inline int32_t Swap_(int32_t value
) {
449 return Swap_(static_cast<uint32_t>(value
));
452 static inline int64_t Swap_(int64_t value
) {
453 return Swap_(static_cast<uint64_t>(value
));
456 static bool little_(true);
458 static inline uint16_t Swap(uint16_t value
) {
459 return little_
? Swap_(value
) : value
;
462 static inline uint32_t Swap(uint32_t value
) {
463 return little_
? Swap_(value
) : value
;
466 static inline uint64_t Swap(uint64_t value
) {
467 return little_
? Swap_(value
) : value
;
470 static inline int16_t Swap(int16_t value
) {
471 return Swap(static_cast<uint16_t>(value
));
474 static inline int32_t Swap(int32_t value
) {
475 return Swap(static_cast<uint32_t>(value
));
478 static inline int64_t Swap(int64_t value
) {
479 return Swap(static_cast<uint64_t>(value
));
482 template <typename Target_
>
495 Swapped(bool swapped
) :
500 template <typename Type_
>
501 Type_
Swap(Type_ value
) const {
502 return swapped_
? Swap_(value
) : value
;
514 Data(void *base
, size_t size
) :
520 void *GetBase() const {
524 size_t GetSize() const {
535 struct mach_header
*mach_header_
;
536 struct load_command
*load_command_
;
539 MachHeader(void *base
, size_t size
) :
542 mach_header_
= (mach_header
*) base
;
544 switch (Swap(mach_header_
->magic
)) {
546 swapped_
= !swapped_
;
552 swapped_
= !swapped_
;
561 void *post
= mach_header_
+ 1;
563 post
= (uint32_t *) post
+ 1;
564 load_command_
= (struct load_command
*) post
;
567 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
568 Swap(mach_header_
->filetype
) == MH_DYLIB
||
569 Swap(mach_header_
->filetype
) == MH_BUNDLE
573 bool Bits64() const {
577 struct mach_header
*operator ->() const {
581 operator struct mach_header
*() const {
585 uint32_t GetCPUType() const {
586 return Swap(mach_header_
->cputype
);
589 uint32_t GetCPUSubtype() const {
590 return Swap(mach_header_
->cpusubtype
) & 0xff;
593 struct load_command
*GetLoadCommand() const {
594 return load_command_
;
597 std::vector
<struct load_command
*> GetLoadCommands() const {
598 std::vector
<struct load_command
*> load_commands
;
600 struct load_command
*load_command
= load_command_
;
601 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
602 load_commands
.push_back(load_command
);
603 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
606 return load_commands
;
609 std::vector
<segment_command
*> GetSegments(const char *segment_name
) const {
610 std::vector
<struct segment_command
*> segment_commands
;
612 _foreach (load_command
, GetLoadCommands()) {
613 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
614 segment_command
*segment_command
= reinterpret_cast<struct segment_command
*>(load_command
);
615 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
616 segment_commands
.push_back(segment_command
);
620 return segment_commands
;
623 std::vector
<segment_command_64
*> GetSegments64(const char *segment_name
) const {
624 std::vector
<struct segment_command_64
*> segment_commands
;
626 _foreach (load_command
, GetLoadCommands()) {
627 if (Swap(load_command
->cmd
) == LC_SEGMENT_64
) {
628 segment_command_64
*segment_command
= reinterpret_cast<struct segment_command_64
*>(load_command
);
629 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
630 segment_commands
.push_back(segment_command
);
634 return segment_commands
;
637 std::vector
<section
*> GetSections(const char *segment_name
, const char *section_name
) const {
638 std::vector
<section
*> sections
;
640 _foreach (segment
, GetSegments(segment_name
)) {
641 section
*section
= (struct section
*) (segment
+ 1);
644 for (sect
= 0; sect
!= Swap(segment
->nsects
); ++sect
) {
645 if (strncmp(section
->sectname
, section_name
, 16) == 0)
646 sections
.push_back(section
);
654 template <typename Target_
>
655 Pointer
<Target_
> GetPointer(uint32_t address
, const char *segment_name
= NULL
) const {
656 load_command
*load_command
= (struct load_command
*) (mach_header_
+ 1);
659 for (cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
660 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
661 segment_command
*segment_command
= (struct segment_command
*) load_command
;
662 if (segment_name
!= NULL
&& strncmp(segment_command
->segname
, segment_name
, 16) != 0)
665 section
*sections
= (struct section
*) (segment_command
+ 1);
668 for (sect
= 0; sect
!= Swap(segment_command
->nsects
); ++sect
) {
669 section
*section
= §ions
[sect
];
670 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
671 if (address
>= Swap(section
->addr
) && address
< Swap(section
->addr
) + Swap(section
->size
)) {
672 //printf("0x%.8x %s\n", address, segment_command->segname);
673 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(address
- Swap(section
->addr
) + Swap(section
->offset
) + (char *) mach_header_
));
679 load_command
= (struct load_command
*) ((char *) load_command
+ Swap(load_command
->cmdsize
));
682 return Pointer
<Target_
>(this);
685 template <typename Target_
>
686 Pointer
<Target_
> GetOffset(uint32_t offset
) {
687 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
));
691 class FatMachHeader
:
698 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
699 MachHeader(base
, size
),
704 fat_arch
*GetFatArch() const {
713 fat_header
*fat_header_
;
714 std::vector
<FatMachHeader
> mach_headers_
;
717 FatHeader(void *base
, size_t size
) :
720 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
722 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
723 swapped_
= !swapped_
;
725 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
727 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
729 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
730 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
732 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
733 uint32_t arch_offset
= Swap(fat_arch
->offset
);
734 uint32_t arch_size
= Swap(fat_arch
->size
);
735 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
741 std::vector
<FatMachHeader
> &GetMachHeaders() {
742 return mach_headers_
;
746 return fat_header_
!= NULL
;
749 struct fat_header
*operator ->() const {
753 operator struct fat_header
*() const {
758 template <typename Target_
>
761 const MachHeader
*framework_
;
762 const Target_
*pointer_
;
765 Pointer(const MachHeader
*framework
= NULL
, const Target_
*pointer
= NULL
) :
766 framework_(framework
),
771 operator const Target_
*() const {
775 const Target_
*operator ->() const {
779 Pointer
<Target_
> &operator ++() {
784 template <typename Value_
>
785 Value_
Swap(Value_ value
) {
786 return framework_
->Swap(value
);
790 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
791 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
792 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
793 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
794 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
795 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
796 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
797 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
799 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
800 #define CSSLOT_INFOSLOT uint32_t(0x00001)
801 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
802 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
803 #define CSSLOT_APPLICATION uint32_t(0x00004)
804 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
806 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
808 #define CS_HASHTYPE_SHA1 1
823 struct BlobIndex index
[];
826 struct CodeDirectory
{
830 uint32_t identOffset
;
831 uint32_t nSpecialSlots
;
841 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
843 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
844 SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
847 struct CodesignAllocation
{
848 FatMachHeader mach_header_
;
855 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
856 mach_header_(mach_header
),
878 _syscall(close(file_
));
881 void open(const char *path
, int flags
) {
882 _assert(file_
== -1);
883 file_
= _syscall(::open(path
, flags
));
900 _syscall(munmap(data_
, size_
));
912 Map(const std::string
&path
, int oflag
, int pflag
, int mflag
) :
915 open(path
, oflag
, pflag
, mflag
);
918 Map(const std::string
&path
, bool edit
) :
929 return data_
== NULL
;
932 void open(const std::string
&path
, int oflag
, int pflag
, int mflag
) {
935 file_
.open(path
.c_str(), oflag
);
936 int file(file_
.file());
939 _syscall(fstat(file
, &stat
));
940 size_
= stat
.st_size
;
942 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
945 void open(const std::string
&path
, bool edit
) {
947 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
949 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
956 size_t size() const {
960 operator std::string() const {
961 return std::string(static_cast<char *>(data_
), size_
);
967 static void Allocate(const void *idata
, size_t isize
, std::streambuf
&output
, const Functor
<size_t (size_t)> &allocate
, const Functor
<size_t (std::streambuf
&output
, size_t, const std::string
&, const char *)> &save
) {
968 FatHeader
source(const_cast<void *>(idata
), isize
);
972 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
974 std::vector
<CodesignAllocation
> allocations
;
975 _foreach (mach_header
, source
.GetMachHeaders()) {
976 struct linkedit_data_command
*signature(NULL
);
977 struct symtab_command
*symtab(NULL
);
979 _foreach (load_command
, mach_header
.GetLoadCommands()) {
980 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
982 else if (cmd
== LC_CODE_SIGNATURE
)
983 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
984 else if (cmd
== LC_SYMTAB
)
985 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
989 if (signature
== NULL
)
990 size
= mach_header
.GetSize();
992 size
= mach_header
.Swap(signature
->dataoff
);
993 _assert(size
<= mach_header
.GetSize());
996 if (symtab
!= NULL
) {
997 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
998 _assert(end
<= size
);
999 _assert(end
>= size
- 0x10);
1003 size_t alloc(allocate(size
));
1005 auto *fat_arch(mach_header
.GetFatArch());
1006 uint32_t align(fat_arch
== NULL
? 0 : source
.Swap(fat_arch
->align
));
1007 offset
= Align(offset
, 1 << align
);
1009 uint32_t limit(size
);
1011 limit
= Align(limit
, 0x10);
1013 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1014 offset
+= size
+ alloc
;
1015 offset
= Align(offset
, 0x10);
1020 if (source
.IsFat()) {
1021 fat_header fat_header
;
1022 fat_header
.magic
= Swap(FAT_MAGIC
);
1023 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1024 put(output
, &fat_header
, sizeof(fat_header
));
1025 position
+= sizeof(fat_header
);
1027 _foreach (allocation
, allocations
) {
1028 auto &mach_header(allocation
.mach_header_
);
1031 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1032 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1033 fat_arch
.offset
= Swap(allocation
.offset_
);
1034 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1035 fat_arch
.align
= Swap(allocation
.align_
);
1036 put(output
, &fat_arch
, sizeof(fat_arch
));
1037 position
+= sizeof(fat_arch
);
1041 _foreach (allocation
, allocations
) {
1042 auto &mach_header(allocation
.mach_header_
);
1044 pad(output
, allocation
.offset_
- position
);
1045 position
= allocation
.offset_
;
1047 std::vector
<std::string
> commands
;
1049 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1050 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1052 switch (mach_header
.Swap(load_command
->cmd
)) {
1053 case LC_CODE_SIGNATURE
:
1058 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1059 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1061 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1062 segment_command
->filesize
= size
;
1063 segment_command
->vmsize
= Align(size
, PageSize_
);
1066 case LC_SEGMENT_64
: {
1067 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1068 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1070 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1071 segment_command
->filesize
= size
;
1072 segment_command
->vmsize
= Align(size
, PageSize_
);
1076 commands
.push_back(copy
);
1079 if (allocation
.alloc_
!= 0) {
1080 linkedit_data_command signature
;
1081 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1082 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1083 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1084 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1085 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1088 size_t begin(position
);
1091 _foreach(command
, commands
)
1092 after
+= command
.size();
1094 std::stringbuf altern
;
1096 struct mach_header
header(*mach_header
);
1097 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1098 header
.sizeofcmds
= mach_header
.Swap(after
);
1099 put(output
, &header
, sizeof(header
));
1100 put(altern
, &header
, sizeof(header
));
1101 position
+= sizeof(header
);
1103 if (mach_header
.Bits64()) {
1104 auto pad(mach_header
.Swap(uint32_t(0)));
1105 put(output
, &pad
, sizeof(pad
));
1106 put(altern
, &pad
, sizeof(pad
));
1107 position
+= sizeof(pad
);
1110 _foreach(command
, commands
) {
1111 put(output
, command
.data(), command
.size());
1112 put(altern
, command
.data(), command
.size());
1113 position
+= command
.size();
1116 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1117 if (before
> after
) {
1118 pad(output
, before
- after
);
1119 pad(altern
, before
- after
);
1120 position
+= before
- after
;
1123 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1125 std::string
overlap(altern
.str());
1126 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1128 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1129 position
= begin
+ allocation
.size_
;
1131 pad(output
, allocation
.limit_
- allocation
.size_
);
1132 position
+= allocation
.limit_
- allocation
.size_
;
1134 size_t saved(save(output
, allocation
.limit_
, overlap
, top
));
1135 if (allocation
.alloc_
> saved
)
1136 pad(output
, allocation
.alloc_
- saved
);
1137 position
+= allocation
.alloc_
;
1143 typedef std::map
<uint32_t, std::string
> Blobs
;
1145 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1146 auto value(buffer
.str());
1147 std::swap(blobs
[slot
], value
);
1150 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1151 auto value(buffer
.str());
1153 blob
.magic
= Swap(magic
);
1154 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1155 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1156 std::swap(blobs
[slot
], value
);
1159 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1161 _foreach (blob
, blobs
)
1162 total
+= blob
.second
.size();
1164 struct SuperBlob super
;
1165 super
.blob
.magic
= Swap(magic
);
1166 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1167 super
.count
= Swap(uint32_t(blobs
.size()));
1168 put(output
, &super
, sizeof(super
));
1170 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1172 _foreach (blob
, blobs
) {
1174 index
.type
= Swap(blob
.first
);
1175 index
.offset
= Swap(uint32_t(offset
));
1176 put(output
, &index
, sizeof(index
));
1177 offset
+= blob
.second
.size();
1180 _foreach (blob
, blobs
)
1181 put(output
, blob
.second
.data(), blob
.second
.size());
1194 _assert(bio_
!= NULL
);
1198 bio_(BIO_new(BIO_s_mem()))
1202 Buffer(const char *data
, size_t size
) :
1203 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1207 Buffer(const std::string
&data
) :
1208 Buffer(data
.data(), data
.size())
1212 Buffer(PKCS7
*pkcs
) :
1215 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1222 operator BIO
*() const {
1226 explicit operator std::string() const {
1228 auto size(BIO_get_mem_data(bio_
, &data
));
1229 return std::string(data
, size
);
1238 STACK_OF(X509
) *ca_
;
1242 value_(d2i_PKCS12_bio(bio
, NULL
)),
1245 _assert(value_
!= NULL
);
1246 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1247 _assert(key_
!= NULL
);
1248 _assert(cert_
!= NULL
);
1251 Stuff(const std::string
&data
) :
1257 sk_X509_pop_free(ca_
, X509_free
);
1259 EVP_PKEY_free(key_
);
1260 PKCS12_free(value_
);
1263 operator PKCS12
*() const {
1267 operator EVP_PKEY
*() const {
1271 operator X509
*() const {
1275 operator STACK_OF(X509
) *() const {
1285 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1286 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1288 _assert(value_
!= NULL
);
1295 operator PKCS7
*() const {
1301 public std::streambuf
1304 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1308 virtual int_type
overflow(int_type next
) {
1314 public std::streambuf
1317 std::vector
<char> &hash_
;
1321 HashBuffer(std::vector
<char> &hash
) :
1324 SHA1_Init(&context_
);
1328 hash_
.resize(SHA_DIGEST_LENGTH
);
1329 SHA1_Final(reinterpret_cast<uint8_t *>(hash_
.data()), &context_
);
1332 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1333 SHA1_Update(&context_
, data
, size
);
1337 virtual int_type
overflow(int_type next
) {
1338 if (next
== traits_type::eof())
1350 std::streambuf
&buffer_
;
1353 HashProxy(std::vector
<char> &hash
, std::streambuf
&buffer
) :
1359 virtual std::streamsize
xsputn(const char_type
*data
, std::streamsize size
) {
1360 _assert(HashBuffer::xsputn(data
, size
) == size
);
1361 return buffer_
.sputn(data
, size
);
1365 static bool Starts(const std::string
&lhs
, const std::string
&rhs
) {
1366 return lhs
.size() >= rhs
.size() && lhs
.compare(0, rhs
.size(), rhs
) == 0;
1374 Split(const std::string
&path
) {
1375 size_t slash(path
.rfind('/'));
1376 if (slash
== std::string::npos
)
1379 dir
= path
.substr(0, slash
+ 1);
1380 base
= path
.substr(slash
+ 1);
1385 static void mkdir_p(const std::string
&path
) {
1388 if (_syscall(mkdir(path
.c_str(), 0755), EEXIST
) == -EEXIST
)
1390 auto slash(path
.rfind('/', path
.size() - 1));
1391 if (slash
== std::string::npos
)
1393 mkdir_p(path
.substr(0, slash
));
1396 static std::string
Temporary(std::filebuf
&file
, const Split
&split
) {
1397 std::string
temp(split
.dir
+ ".ldid." + split
.base
);
1399 _assert_(file
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &file
, "open(): %s", temp
.c_str());
1403 static void Commit(const std::string
&path
, const std::string
&temp
) {
1405 if (_syscall(stat(path
.c_str(), &info
), ENOENT
) == 0) {
1407 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1409 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1412 _syscall(rename(temp
.c_str(), path
.c_str()));
1417 void Sign(const void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&identifier
, const std::string
&entitlements
, const std::string
&key
, const Slots
&slots
) {
1418 Allocate(idata
, isize
, output
, fun([&](size_t size
) -> size_t {
1419 size_t alloc(sizeof(struct SuperBlob
));
1421 uint32_t special(0);
1423 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1424 alloc
+= sizeof(struct BlobIndex
);
1427 if (!entitlements
.empty()) {
1428 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1429 alloc
+= sizeof(struct BlobIndex
);
1430 alloc
+= sizeof(struct Blob
);
1431 alloc
+= entitlements
.size();
1434 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1435 alloc
+= sizeof(struct BlobIndex
);
1436 alloc
+= sizeof(struct Blob
);
1437 alloc
+= sizeof(struct CodeDirectory
);
1438 alloc
+= identifier
.size() + 1;
1441 alloc
+= sizeof(struct BlobIndex
);
1442 alloc
+= sizeof(struct Blob
);
1443 // XXX: this is just a "sufficiently large number"
1447 _foreach (slot
, slots
)
1448 special
= std::max(special
, slot
.first
);
1450 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1451 alloc
= Align(alloc
+ (special
+ normal
) * SHA_DIGEST_LENGTH
, 16);
1453 }), fun([&](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1457 std::stringbuf data
;
1460 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1462 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1465 if (!entitlements
.empty()) {
1466 std::stringbuf data
;
1467 put(data
, entitlements
.data(), entitlements
.size());
1468 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1472 std::stringbuf data
;
1474 uint32_t special(0);
1475 _foreach (blob
, blobs
)
1476 special
= std::max(special
, blob
.first
);
1477 _foreach (slot
, slots
)
1478 special
= std::max(special
, slot
.first
);
1479 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1481 CodeDirectory directory
;
1482 directory
.version
= Swap(uint32_t(0x00020001));
1483 directory
.flags
= Swap(uint32_t(0));
1484 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + identifier
.size() + 1 + SHA_DIGEST_LENGTH
* special
));
1485 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1486 directory
.nSpecialSlots
= Swap(special
);
1487 directory
.codeLimit
= Swap(uint32_t(limit
));
1488 directory
.nCodeSlots
= Swap(normal
);
1489 directory
.hashSize
= SHA_DIGEST_LENGTH
;
1490 directory
.hashType
= CS_HASHTYPE_SHA1
;
1491 directory
.spare1
= 0x00;
1492 directory
.pageSize
= PageShift_
;
1493 directory
.spare2
= Swap(uint32_t(0));
1494 put(data
, &directory
, sizeof(directory
));
1496 put(data
, identifier
.c_str(), identifier
.size() + 1);
1498 uint8_t storage
[special
+ normal
][SHA_DIGEST_LENGTH
];
1499 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = storage
+ special
;
1501 memset(storage
, 0, sizeof(*storage
) * special
);
1503 _foreach (blob
, blobs
) {
1504 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1505 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1508 _foreach (slot
, slots
) {
1509 _assert(sizeof(*hashes
) == slot
.second
.size());
1510 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1514 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1515 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1517 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1519 put(data
, storage
, sizeof(storage
));
1521 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1525 std::stringbuf data
;
1526 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1531 Signature
signature(stuff
, sign
);
1532 Buffer
result(signature
);
1533 std::string
value(result
);
1534 put(data
, value
.data(), value
.size());
1536 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1539 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1543 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1544 Allocate(idata
, isize
, output
, fun([](size_t size
) -> size_t {
1546 }), fun([](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1551 std::string
DiskFolder::Path(const std::string
&path
) {
1552 return path_
+ "/" + path
;
1555 DiskFolder::DiskFolder(const std::string
&path
) :
1560 DiskFolder::~DiskFolder() {
1561 if (!std::uncaught_exception())
1562 for (const auto &commit
: commit_
)
1563 Commit(commit
.first
, commit
.second
);
1566 void DiskFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1568 auto from(Path(path
));
1569 commit_
[from
] = Temporary(save
, from
);
1573 bool DiskFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1575 auto result(data
.open(Path(path
).c_str(), std::ios::binary
| std::ios::in
));
1578 _assert(result
== &data
);
1583 void DiskFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)>&code
) {
1584 auto root(Path(path
));
1586 FTS
*fts(fts_open((char *[]) {const_cast<char *>(root
.c_str()), NULL
}, FTS_PHYSICAL
| FTS_NOCHDIR
, NULL
));
1587 _assert(fts
!= NULL
);
1588 _scope({ fts_close(fts
); });
1590 while (FTSENT
*entry
= fts_read(fts
)) {
1591 _assert(entry
->fts_pathlen
>= root
.size());
1592 _assert(strncmp(entry
->fts_path
, root
.c_str(), root
.size()) == 0);
1593 if (entry
->fts_pathlen
== root
.size())
1596 _assert(entry
->fts_path
[root
.size()] == '/');
1597 std::string
name(entry
->fts_path
+ root
.size() + 1);
1599 if (Starts(Split(name
).base
, ".ldid."))
1602 switch (auto info
= entry
->fts_info
) {
1608 code(name
, fun([&](const Functor
<void (std::streambuf
&, std::streambuf
&)> &code
) {
1609 std::string
access(path
+ name
);
1610 _assert_(Open(access
, fun([&](std::streambuf
&data
) {
1613 })), "open(): %s", access
.c_str());
1618 _assert_(false, "fts_info=%u", info
);
1623 SubFolder::SubFolder(Folder
*parent
, const std::string
&path
) :
1629 void SubFolder::Save(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1630 return parent_
->Save(path_
+ path
, code
);
1633 bool SubFolder::Open(const std::string
&path
, const Functor
<void (std::streambuf
&)> &code
) {
1634 return parent_
->Open(path_
+ path
, code
);
1637 void SubFolder::Find(const std::string
&path
, const Functor
<void (const std::string
&, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &)> &code
) {
1638 return parent_
->Find(path_
+ path
, code
);
1641 static size_t copy(std::streambuf
&source
, std::streambuf
&target
) {
1645 size_t writ(source
.sgetn(data
, sizeof(data
)));
1648 _assert(target
.sputn(data
, writ
) == writ
);
1654 static PList::Structure
*plist(const std::string
&data
) {
1655 if (!Starts(data
, "bplist00"))
1656 return PList::Structure::FromXml(data
);
1657 std::vector
<char> bytes(data
.data(), data
.data() + data
.size());
1658 return PList::Structure::FromBin(bytes
);
1661 static void plist_d(std::streambuf
&buffer
, const Functor
<void (PList::Dictionary
*)> &code
) {
1662 std::stringbuf data
;
1664 PList::Structure
*structure(plist(data
.str()));
1665 _scope({ delete structure
; });
1666 auto dictionary(dynamic_cast<PList::Dictionary
*>(structure
));
1667 _assert(dictionary
!= NULL
);
1671 static std::string
plist_s(PList::Node
*node
) {
1672 auto value(dynamic_cast<PList::String
*>(node
));
1673 _assert(value
!= NULL
);
1674 return value
->GetValue();
1690 Expression(const std::string
&code
) {
1691 _assert_(regcomp(®ex_
, code
.c_str(), REG_EXTENDED
| REG_NOSUB
) == 0, "regcomp()");
1698 bool operator ()(const std::string
&data
) const {
1699 auto value(regexec(®ex_
, data
.c_str(), 0, NULL
, 0));
1700 if (value
== REG_NOMATCH
)
1702 _assert_(value
== 0, "regexec()");
1712 mutable std::auto_ptr
<Expression
> regex_
;
1714 Rule(unsigned weight
, Mode mode
, const std::string
&code
) :
1721 Rule(const Rule
&rhs
) :
1722 weight_(rhs
.weight_
),
1728 void Compile() const {
1729 regex_
.reset(new Expression(code_
));
1732 bool operator ()(const std::string
&data
) const {
1733 _assert(regex_
.get() != NULL
);
1734 return (*regex_
)(data
);
1737 bool operator <(const Rule
&rhs
) const {
1738 if (weight_
> rhs
.weight_
)
1740 if (weight_
< rhs
.weight_
)
1742 return mode_
> rhs
.mode_
;
1747 bool operator ()(const Rule
*lhs
, const Rule
*rhs
) const {
1748 return lhs
->code_
< rhs
->code_
;
1752 std::string
Bundle(const std::string
&root
, Folder
&folder
, const std::string
&key
, std::map
<std::string
, std::vector
<char>> &remote
) {
1753 std::string executable
;
1754 std::string identifier
;
1756 static const std::string
info("Info.plist");
1758 _assert_(folder
.Open(info
, fun([&](std::streambuf
&buffer
) {
1759 plist_d(buffer
, fun([&](PList::Dictionary
*dictionary
) {
1760 executable
= plist_s(((*dictionary
)["CFBundleExecutable"]));
1761 identifier
= plist_s(((*dictionary
)["CFBundleIdentifier"]));
1763 })), "open(): Info.plist");
1765 std::map
<std::string
, std::multiset
<Rule
>> versions
;
1767 auto &rules1(versions
[""]);
1768 auto &rules2(versions
["2"]);
1770 static const std::string
signature("_CodeSignature/CodeResources");
1772 folder
.Open(signature
, fun([&](std::streambuf
&buffer
) {
1773 plist_d(buffer
, fun([&](PList::Dictionary
*dictionary
) {
1774 // XXX: maybe attempt to preserve existing rules
1779 rules1
.insert(Rule
{1, NoMode
, "^"});
1780 rules1
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1781 rules1
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1782 rules1
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1783 rules1
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1784 rules1
.insert(Rule
{1, NoMode
, "^version.plist$"});
1788 rules2
.insert(Rule
{11, NoMode
, ".*\\.dSYM($|/)"});
1789 rules2
.insert(Rule
{20, NoMode
, "^"});
1790 rules2
.insert(Rule
{2000, OmitMode
, "^(.*/)?\\.DS_Store$"});
1791 rules2
.insert(Rule
{10000, OmitMode
, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1792 rules2
.insert(Rule
{10, NestedMode
, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1793 rules2
.insert(Rule
{1, NoMode
, "^.*"});
1794 rules2
.insert(Rule
{1000, OptionalMode
, "^.*\\.lproj/"});
1795 rules2
.insert(Rule
{1100, OmitMode
, "^.*\\.lproj/locversion.plist$"});
1796 rules2
.insert(Rule
{20, OmitMode
, "^Info\\.plist$"});
1797 rules2
.insert(Rule
{20, OmitMode
, "^PkgInfo$"});
1798 rules2
.insert(Rule
{10000, OmitMode
, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1799 rules2
.insert(Rule
{10, NestedMode
, "^[^/]+$"});
1800 rules2
.insert(Rule
{20, NoMode
, "^embedded\\.provisionprofile$"});
1801 rules2
.insert(Rule
{20, NoMode
, "^version\\.plist$"});
1804 std::map
<std::string
, std::vector
<char>> local
;
1806 static Expression
nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1808 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1811 auto bundle(root
+ Split(name
).dir
);
1812 SubFolder
subfolder(&folder
, bundle
);
1813 Bundle(bundle
, subfolder
, key
, local
);
1816 folder
.Find("", fun([&](const std::string
&name
, const Functor
<void (const Functor
<void (std::streambuf
&, std::streambuf
&)> &)> &code
) {
1817 if (name
== executable
|| name
== signature
)
1820 auto &hash(local
[name
]);
1824 code(fun([&](std::streambuf
&data
, std::streambuf
&save
) {
1825 HashProxy
proxy(hash
, save
);
1829 _assert(hash
.size() == SHA_DIGEST_LENGTH
);
1832 PList::Dictionary plist
;
1834 for (const auto &version
: versions
) {
1835 PList::Dictionary files
;
1837 for (const auto &rule
: version
.second
)
1840 for (const auto &hash
: local
)
1841 for (const auto &rule
: version
.second
)
1842 if (rule(hash
.first
)) {
1843 if (rule
.mode_
== NoMode
)
1844 files
.Set(hash
.first
, PList::Data(hash
.second
));
1845 else if (rule
.mode_
== OptionalMode
) {
1846 PList::Dictionary entry
;
1847 entry
.Set("hash", PList::Data(hash
.second
));
1848 entry
.Set("optional", PList::Boolean(true));
1849 files
.Set(hash
.first
, entry
);
1855 plist
.Set("files" + version
.first
, files
);
1858 for (const auto &version
: versions
) {
1859 PList::Dictionary rules
;
1861 std::multiset
<const Rule
*, RuleCode
> ordered
;
1862 for (const auto &rule
: version
.second
)
1863 ordered
.insert(&rule
);
1865 for (const auto &rule
: ordered
)
1866 if (rule
->weight_
== 1 && rule
->mode_
== NoMode
)
1867 rules
.Set(rule
->code_
, PList::Boolean(true));
1869 PList::Dictionary entry
;
1871 switch (rule
->mode_
) {
1875 entry
.Set("omit", PList::Boolean(true));
1878 entry
.Set("optional", PList::Boolean(true));
1881 entry
.Set("nested", PList::Boolean(true));
1884 entry
.Set("top", PList::Boolean(true));
1888 if (rule
->weight_
>= 10000)
1889 entry
.Set("weight", PList::Integer(rule
->weight_
));
1890 else if (rule
->weight_
!= 1)
1891 entry
.Set("weight", PList::Real(rule
->weight_
));
1893 rules
.Set(rule
->code_
, entry
);
1896 plist
.Set("rules" + version
.first
, rules
);
1899 folder
.Save(signature
, fun([&](std::streambuf
&save
) {
1900 HashProxy
proxy(local
[signature
], save
);
1901 auto xml(plist
.ToXml());
1902 put(proxy
, xml
.data(), xml
.size());
1905 folder
.Open(executable
, fun([&](std::streambuf
&buffer
) {
1906 // XXX: this is a miserable fail
1907 std::stringbuf temp
;
1909 auto data(temp
.str());
1911 folder
.Save(executable
, fun([&](std::streambuf
&save
) {
1913 slots
[1] = local
.at(info
);
1914 slots
[3] = local
.at(signature
);
1916 HashProxy
proxy(local
[executable
], save
);
1917 Sign(data
.data(), data
.size(), proxy
, identifier
, "", key
, slots
);
1921 for (const auto &hash
: local
)
1922 remote
[root
+ hash
.first
] = hash
.second
;
1929 int main(int argc
, char *argv
[]) {
1930 OpenSSL_add_all_algorithms();
1937 little_
= endian
.byte
[0];
1952 uint32_t flag_CPUType(_not(uint32_t));
1953 uint32_t flag_CPUSubtype(_not(uint32_t));
1955 const char *flag_I(NULL
);
1964 std::vector
<std::string
> files
;
1967 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
1968 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
1969 fprintf(stderr
, " %s -S cat\n", argv
[0]);
1970 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
1974 for (int argi(1); argi
!= argc
; ++argi
)
1975 if (argv
[argi
][0] != '-')
1976 files
.push_back(argv
[argi
]);
1977 else switch (argv
[argi
][1]) {
1984 case 'e': flag_e
= true; break;
1987 const char *slot
= argv
[argi
] + 2;
1988 const char *colon
= strchr(slot
, ':');
1989 _assert(colon
!= NULL
);
1990 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1992 unsigned number(strtoul(slot
, &arge
, 0));
1993 _assert(arge
== colon
);
1994 std::vector
<char> &hash(slots
[number
]);
1995 hash
.resize(SHA_DIGEST_LENGTH
);
1996 sha1(reinterpret_cast<uint8_t *>(hash
.data()), file
.data(), file
.size());
1999 case 'D': flag_D
= true; break;
2001 case 'a': flag_a
= true; break;
2006 if (argv
[argi
][2] != '\0') {
2007 const char *cpu
= argv
[argi
] + 2;
2008 const char *colon
= strchr(cpu
, ':');
2009 _assert(colon
!= NULL
);
2011 flag_CPUType
= strtoul(cpu
, &arge
, 0);
2012 _assert(arge
== colon
);
2013 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
2014 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2028 if (argv
[argi
][2] != '\0') {
2029 const char *xml
= argv
[argi
] + 2;
2030 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2035 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2040 if (argv
[argi
][2] == '-')
2044 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
2045 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
2050 flag_I
= argv
[argi
] + 2;
2058 _assert(flag_S
|| key
.empty());
2059 _assert(flag_S
|| flag_I
== NULL
);
2061 if (files
.empty()) usage
: {
2065 size_t filei(0), filee(0);
2066 _foreach (file
, files
) try {
2067 std::string
path(file
);
2070 _syscall(stat(path
.c_str(), &info
));
2072 if (S_ISDIR(info
.st_mode
)) {
2074 ldid::DiskFolder
folder(path
);
2075 std::map
<std::string
, std::vector
<char>> hashes
;
2076 path
+= "/" + Bundle("", folder
, key
, hashes
);
2077 } else if (flag_S
|| flag_r
) {
2078 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
2080 std::filebuf output
;
2082 auto temp(Temporary(output
, split
));
2085 ldid::Unsign(input
.data(), input
.size(), output
);
2087 std::string
identifier(flag_I
?: split
.base
.c_str());
2088 ldid::Sign(input
.data(), input
.size(), output
, identifier
, entitlements
, key
, slots
);
2094 Map
mapping(path
, flag_T
|| flag_s
);
2095 FatHeader
fat_header(mapping
.data(), mapping
.size());
2097 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
2098 struct linkedit_data_command
*signature(NULL
);
2099 struct encryption_info_command
*encryption(NULL
);
2102 if (mach_header
.GetCPUType() != flag_CPUType
)
2104 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
2109 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
2111 _foreach (load_command
, mach_header
.GetLoadCommands()) {
2112 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
2115 else if (cmd
== LC_CODE_SIGNATURE
)
2116 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
2117 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
2118 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
2119 else if (cmd
== LC_ID_DYLIB
) {
2120 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
2128 dylib_command
->dylib
.timestamp
= 0;
2129 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
2132 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
2138 _assert(encryption
!= NULL
);
2139 encryption
->cryptid
= mach_header
.Swap(0);
2143 _assert(signature
!= NULL
);
2145 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2147 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2148 uint8_t *blob
= top
+ data
;
2149 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2151 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2152 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
2153 uint32_t begin
= Swap(super
->index
[index
].offset
);
2154 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
2155 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
2160 _assert(signature
!= NULL
);
2162 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
2164 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
2165 uint8_t *blob
= top
+ data
;
2166 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
2168 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
2169 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
2170 uint32_t begin
= Swap(super
->index
[index
].offset
);
2171 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
2173 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
2174 uint32_t pages
= Swap(directory
->nCodeSlots
);
2177 for (size_t i
= 0; i
!= pages
- 1; ++i
)
2178 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
2180 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
2186 } catch (const char *) {