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/>.
40 #include <openssl/err.h>
41 #include <openssl/pem.h>
42 #include <openssl/pkcs7.h>
43 #include <openssl/pkcs12.h>
44 #include <openssl/sha.h>
46 #include <plist/plist.h>
50 #define _assert___(line) \
52 #define _assert__(line) \
55 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" e ")"
57 #define _assert(expr) \
59 fprintf(stderr, "%s(%u): _assert(%s); errno=%u\n", __FILE__, __LINE__, #expr, errno); \
63 #define _syscall(expr) ({ \
64 __typeof__(expr) _value; \
65 do if ((long) (_value = (expr)) != -1) \
67 else switch (errno) { \
77 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
83 __attribute__((packed))
85 template <typename Type_
>
87 typedef typename
Type_::const_iterator Result
;
90 #define _foreach(item, list) \
91 for (bool _stop(true); _stop; ) \
92 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
93 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
94 for (bool _suck(true); _suck; _suck = false) \
95 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
102 #define FAT_MAGIC 0xcafebabe
103 #define FAT_CIGAM 0xbebafeca
123 #define MH_MAGIC 0xfeedface
124 #define MH_CIGAM 0xcefaedfe
126 #define MH_MAGIC_64 0xfeedfacf
127 #define MH_CIGAM_64 0xcffaedfe
129 #define MH_DYLDLINK 0x4
131 #define MH_OBJECT 0x1
132 #define MH_EXECUTE 0x2
134 #define MH_BUNDLE 0x8
135 #define MH_DYLIB_STUB 0x9
137 struct load_command
{
142 #define LC_REQ_DYLD uint32_t(0x80000000)
144 #define LC_SEGMENT uint32_t(0x01)
145 #define LC_SYMTAB uint32_t(0x02)
146 #define LC_DYSYMTAB uint32_t(0x0b)
147 #define LC_LOAD_DYLIB uint32_t(0x0c)
148 #define LC_ID_DYLIB uint32_t(0x0d)
149 #define LC_SEGMENT_64 uint32_t(0x19)
150 #define LC_UUID uint32_t(0x1b)
151 #define LC_CODE_SIGNATURE uint32_t(0x1d)
152 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
153 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
154 #define LC_ENCRYPTION_INFO uint32_t(0x21)
155 #define LC_DYLD_INFO uint32_t(0x22)
156 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
157 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
162 uint32_t current_version
;
163 uint32_t compatibility_version
;
166 struct dylib_command
{
172 struct uuid_command
{
178 struct symtab_command
{
187 struct dyld_info_command
{
191 uint32_t rebase_size
;
194 uint32_t weak_bind_off
;
195 uint32_t weak_bind_size
;
196 uint32_t lazy_bind_off
;
197 uint32_t lazy_bind_size
;
199 uint32_t export_size
;
202 struct dysymtab_command
{
215 uint32_t extrefsymoff
;
216 uint32_t nextrefsyms
;
217 uint32_t indirectsymoff
;
218 uint32_t nindirectsyms
;
225 struct dylib_table_of_contents
{
226 uint32_t symbol_index
;
227 uint32_t module_index
;
230 struct dylib_module
{
231 uint32_t module_name
;
240 uint32_t iinit_iterm
;
241 uint32_t ninit_nterm
;
242 uint32_t objc_module_info_addr
;
243 uint32_t objc_module_info_size
;
246 struct dylib_reference
{
251 struct relocation_info
{
253 uint32_t r_symbolnum
:24;
272 struct segment_command
{
286 struct segment_command_64
{
328 struct linkedit_data_command
{
335 struct encryption_info_command
{
343 #define BIND_OPCODE_MASK 0xf0
344 #define BIND_IMMEDIATE_MASK 0x0f
345 #define BIND_OPCODE_DONE 0x00
346 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
347 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
348 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
349 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
350 #define BIND_OPCODE_SET_TYPE_IMM 0x50
351 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
352 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
353 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
354 #define BIND_OPCODE_DO_BIND 0x90
355 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
356 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
357 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
359 inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
360 _assert(stream
.sgetn(static_cast<char *>(data
), size
) == size
);
363 inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
364 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
367 inline void pad(std::streambuf
&stream
, size_t size
) {
369 memset(padding
, 0, size
);
370 put(stream
, padding
, size
);
373 template <typename Type_
>
374 Type_
Align(Type_ value
, size_t align
) {
381 static const uint8_t PageShift_(0x0c);
382 static const uint32_t PageSize_(1 << PageShift_
);
384 static inline uint16_t Swap_(uint16_t value
) {
386 ((value
>> 8) & 0x00ff) |
387 ((value
<< 8) & 0xff00);
390 static inline uint32_t Swap_(uint32_t value
) {
391 value
= ((value
>> 8) & 0x00ff00ff) |
392 ((value
<< 8) & 0xff00ff00);
393 value
= ((value
>> 16) & 0x0000ffff) |
394 ((value
<< 16) & 0xffff0000);
398 static inline uint64_t Swap_(uint64_t value
) {
399 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
400 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
401 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
405 static inline int16_t Swap_(int16_t value
) {
406 return Swap_(static_cast<uint16_t>(value
));
409 static inline int32_t Swap_(int32_t value
) {
410 return Swap_(static_cast<uint32_t>(value
));
413 static inline int64_t Swap_(int64_t value
) {
414 return Swap_(static_cast<uint64_t>(value
));
417 static bool little_(true);
419 static inline uint16_t Swap(uint16_t value
) {
420 return little_
? Swap_(value
) : value
;
423 static inline uint32_t Swap(uint32_t value
) {
424 return little_
? Swap_(value
) : value
;
427 static inline uint64_t Swap(uint64_t value
) {
428 return little_
? Swap_(value
) : value
;
431 static inline int16_t Swap(int16_t value
) {
432 return Swap(static_cast<uint16_t>(value
));
435 static inline int32_t Swap(int32_t value
) {
436 return Swap(static_cast<uint32_t>(value
));
439 static inline int64_t Swap(int64_t value
) {
440 return Swap(static_cast<uint64_t>(value
));
443 template <typename Target_
>
456 Swapped(bool swapped
) :
461 template <typename Type_
>
462 Type_
Swap(Type_ value
) const {
463 return swapped_
? Swap_(value
) : value
;
475 Data(void *base
, size_t size
) :
481 void *GetBase() const {
485 size_t GetSize() const {
496 struct mach_header
*mach_header_
;
497 struct load_command
*load_command_
;
500 MachHeader(void *base
, size_t size
) :
503 mach_header_
= (mach_header
*) base
;
505 switch (Swap(mach_header_
->magic
)) {
507 swapped_
= !swapped_
;
513 swapped_
= !swapped_
;
522 void *post
= mach_header_
+ 1;
524 post
= (uint32_t *) post
+ 1;
525 load_command_
= (struct load_command
*) post
;
528 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
529 Swap(mach_header_
->filetype
) == MH_DYLIB
||
530 Swap(mach_header_
->filetype
) == MH_BUNDLE
534 bool Bits64() const {
538 struct mach_header
*operator ->() const {
542 operator struct mach_header
*() const {
546 uint32_t GetCPUType() const {
547 return Swap(mach_header_
->cputype
);
550 uint32_t GetCPUSubtype() const {
551 return Swap(mach_header_
->cpusubtype
) & 0xff;
554 struct load_command
*GetLoadCommand() const {
555 return load_command_
;
558 std::vector
<struct load_command
*> GetLoadCommands() const {
559 std::vector
<struct load_command
*> load_commands
;
561 struct load_command
*load_command
= load_command_
;
562 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
563 load_commands
.push_back(load_command
);
564 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
567 return load_commands
;
570 std::vector
<segment_command
*> GetSegments(const char *segment_name
) const {
571 std::vector
<struct segment_command
*> segment_commands
;
573 _foreach (load_command
, GetLoadCommands()) {
574 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
575 segment_command
*segment_command
= reinterpret_cast<struct segment_command
*>(load_command
);
576 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
577 segment_commands
.push_back(segment_command
);
581 return segment_commands
;
584 std::vector
<segment_command_64
*> GetSegments64(const char *segment_name
) const {
585 std::vector
<struct segment_command_64
*> segment_commands
;
587 _foreach (load_command
, GetLoadCommands()) {
588 if (Swap(load_command
->cmd
) == LC_SEGMENT_64
) {
589 segment_command_64
*segment_command
= reinterpret_cast<struct segment_command_64
*>(load_command
);
590 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
591 segment_commands
.push_back(segment_command
);
595 return segment_commands
;
598 std::vector
<section
*> GetSections(const char *segment_name
, const char *section_name
) const {
599 std::vector
<section
*> sections
;
601 _foreach (segment
, GetSegments(segment_name
)) {
602 section
*section
= (struct section
*) (segment
+ 1);
605 for (sect
= 0; sect
!= Swap(segment
->nsects
); ++sect
) {
606 if (strncmp(section
->sectname
, section_name
, 16) == 0)
607 sections
.push_back(section
);
615 template <typename Target_
>
616 Pointer
<Target_
> GetPointer(uint32_t address
, const char *segment_name
= NULL
) const {
617 load_command
*load_command
= (struct load_command
*) (mach_header_
+ 1);
620 for (cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
621 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
622 segment_command
*segment_command
= (struct segment_command
*) load_command
;
623 if (segment_name
!= NULL
&& strncmp(segment_command
->segname
, segment_name
, 16) != 0)
626 section
*sections
= (struct section
*) (segment_command
+ 1);
629 for (sect
= 0; sect
!= Swap(segment_command
->nsects
); ++sect
) {
630 section
*section
= §ions
[sect
];
631 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
632 if (address
>= Swap(section
->addr
) && address
< Swap(section
->addr
) + Swap(section
->size
)) {
633 //printf("0x%.8x %s\n", address, segment_command->segname);
634 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(address
- Swap(section
->addr
) + Swap(section
->offset
) + (char *) mach_header_
));
640 load_command
= (struct load_command
*) ((char *) load_command
+ Swap(load_command
->cmdsize
));
643 return Pointer
<Target_
>(this);
646 template <typename Target_
>
647 Pointer
<Target_
> GetOffset(uint32_t offset
) {
648 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
));
652 class FatMachHeader
:
659 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
660 MachHeader(base
, size
),
665 fat_arch
*GetFatArch() const {
674 fat_header
*fat_header_
;
675 std::vector
<FatMachHeader
> mach_headers_
;
678 FatHeader(void *base
, size_t size
) :
681 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
683 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
684 swapped_
= !swapped_
;
686 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
688 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
690 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
691 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
693 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
694 uint32_t arch_offset
= Swap(fat_arch
->offset
);
695 uint32_t arch_size
= Swap(fat_arch
->size
);
696 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
702 std::vector
<FatMachHeader
> &GetMachHeaders() {
703 return mach_headers_
;
707 return fat_header_
!= NULL
;
710 struct fat_header
*operator ->() const {
714 operator struct fat_header
*() const {
719 template <typename Target_
>
722 const MachHeader
*framework_
;
723 const Target_
*pointer_
;
726 Pointer(const MachHeader
*framework
= NULL
, const Target_
*pointer
= NULL
) :
727 framework_(framework
),
732 operator const Target_
*() const {
736 const Target_
*operator ->() const {
740 Pointer
<Target_
> &operator ++() {
745 template <typename Value_
>
746 Value_
Swap(Value_ value
) {
747 return framework_
->Swap(value
);
751 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
752 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
753 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
754 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
755 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
756 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
757 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
758 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
760 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
761 #define CSSLOT_INFOSLOT uint32_t(0x00001)
762 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
763 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
764 #define CSSLOT_APPLICATION uint32_t(0x00004)
765 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
767 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
769 #define CS_HASHTYPE_SHA1 1
784 struct BlobIndex index
[];
787 struct CodeDirectory
{
791 uint32_t identOffset
;
792 uint32_t nSpecialSlots
;
802 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
804 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
805 SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
808 struct CodesignAllocation
{
809 FatMachHeader mach_header_
;
816 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
817 mach_header_(mach_header
),
839 _syscall(close(file_
));
842 void open(const char *path
, int flags
) {
843 _assert(file_
== -1);
844 _syscall(file_
= ::open(path
, flags
));
861 _syscall(munmap(data_
, size_
));
873 Map(const char *path
, int oflag
, int pflag
, int mflag
) :
876 open(path
, oflag
, pflag
, mflag
);
879 Map(const char *path
, bool edit
) :
890 return data_
== NULL
;
893 void open(const char *path
, int oflag
, int pflag
, int mflag
) {
896 file_
.open(path
, oflag
);
897 int file(file_
.file());
900 _syscall(fstat(file
, &stat
));
901 size_
= stat
.st_size
;
903 _syscall(data_
= mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
906 void open(const char *path
, bool edit
) {
908 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
910 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
917 size_t size() const {
921 operator std::string() const {
922 return std::string(static_cast<char *>(data_
), size_
);
928 static void Allocate(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
) {
929 FatHeader
source(idata
, isize
);
933 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
935 std::vector
<CodesignAllocation
> allocations
;
936 _foreach (mach_header
, source
.GetMachHeaders()) {
937 struct linkedit_data_command
*signature(NULL
);
938 struct symtab_command
*symtab(NULL
);
940 _foreach (load_command
, mach_header
.GetLoadCommands()) {
941 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
943 else if (cmd
== LC_CODE_SIGNATURE
)
944 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
945 else if (cmd
== LC_SYMTAB
)
946 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
950 if (signature
== NULL
)
951 size
= mach_header
.GetSize();
953 size
= mach_header
.Swap(signature
->dataoff
);
954 _assert(size
<= mach_header
.GetSize());
957 if (symtab
!= NULL
) {
958 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
959 _assert(end
<= size
);
960 _assert(end
>= size
- 0x10);
964 size_t alloc(allocate(size
));
966 auto *fat_arch(mach_header
.GetFatArch());
967 uint32_t align(fat_arch
== NULL
? 0 : source
.Swap(fat_arch
->align
));
968 offset
= Align(offset
, 1 << align
);
970 uint32_t limit(size
);
972 limit
= Align(limit
, 0x10);
974 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
975 offset
+= size
+ alloc
;
976 offset
= Align(offset
, 0x10);
981 if (source
.IsFat()) {
982 fat_header fat_header
;
983 fat_header
.magic
= Swap(FAT_MAGIC
);
984 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
985 put(output
, &fat_header
, sizeof(fat_header
));
986 position
+= sizeof(fat_header
);
988 _foreach (allocation
, allocations
) {
989 auto &mach_header(allocation
.mach_header_
);
992 fat_arch
.cputype
= Swap(mach_header
->cputype
);
993 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
994 fat_arch
.offset
= Swap(allocation
.offset_
);
995 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
996 fat_arch
.align
= Swap(allocation
.align_
);
997 put(output
, &fat_arch
, sizeof(fat_arch
));
998 position
+= sizeof(fat_arch
);
1002 _foreach (allocation
, allocations
) {
1003 auto &mach_header(allocation
.mach_header_
);
1005 pad(output
, allocation
.offset_
- position
);
1006 position
= allocation
.offset_
;
1008 std::vector
<std::string
> commands
;
1010 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1011 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1013 switch (mach_header
.Swap(load_command
->cmd
)) {
1014 case LC_CODE_SIGNATURE
:
1019 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1020 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1022 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1023 segment_command
->filesize
= size
;
1024 segment_command
->vmsize
= Align(size
, PageSize_
);
1027 case LC_SEGMENT_64
: {
1028 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1029 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1031 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1032 segment_command
->filesize
= size
;
1033 segment_command
->vmsize
= Align(size
, PageSize_
);
1037 commands
.push_back(copy
);
1040 if (allocation
.alloc_
!= 0) {
1041 linkedit_data_command signature
;
1042 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1043 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1044 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1045 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1046 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1049 size_t begin(position
);
1052 _foreach(command
, commands
)
1053 after
+= command
.size();
1055 std::stringbuf altern
;
1057 struct mach_header
header(*mach_header
);
1058 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1059 header
.sizeofcmds
= mach_header
.Swap(after
);
1060 put(output
, &header
, sizeof(header
));
1061 put(altern
, &header
, sizeof(header
));
1062 position
+= sizeof(header
);
1064 if (mach_header
.Bits64()) {
1065 auto pad(mach_header
.Swap(uint32_t(0)));
1066 put(output
, &pad
, sizeof(pad
));
1067 put(altern
, &pad
, sizeof(pad
));
1068 position
+= sizeof(pad
);
1071 _foreach(command
, commands
) {
1072 put(output
, command
.data(), command
.size());
1073 put(altern
, command
.data(), command
.size());
1074 position
+= command
.size();
1077 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1078 if (before
> after
) {
1079 pad(output
, before
- after
);
1080 pad(altern
, before
- after
);
1081 position
+= before
- after
;
1084 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1086 std::string
overlap(altern
.str());
1087 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1089 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1090 position
= begin
+ allocation
.size_
;
1092 pad(output
, allocation
.limit_
- allocation
.size_
);
1093 position
+= allocation
.limit_
- allocation
.size_
;
1095 size_t saved(save(output
, allocation
.limit_
, overlap
, top
));
1096 if (allocation
.alloc_
> saved
)
1097 pad(output
, allocation
.alloc_
- saved
);
1098 position
+= allocation
.alloc_
;
1104 typedef std::map
<uint32_t, std::string
> Blobs
;
1106 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1107 auto value(buffer
.str());
1108 std::swap(blobs
[slot
], value
);
1111 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1112 auto value(buffer
.str());
1114 blob
.magic
= Swap(magic
);
1115 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1116 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1117 std::swap(blobs
[slot
], value
);
1120 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1122 _foreach (blob
, blobs
)
1123 total
+= blob
.second
.size();
1125 struct SuperBlob super
;
1126 super
.blob
.magic
= Swap(magic
);
1127 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1128 super
.count
= Swap(uint32_t(blobs
.size()));
1129 put(output
, &super
, sizeof(super
));
1131 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1133 _foreach (blob
, blobs
) {
1135 index
.type
= Swap(blob
.first
);
1136 index
.offset
= Swap(uint32_t(offset
));
1137 put(output
, &index
, sizeof(index
));
1138 offset
+= blob
.second
.size();
1141 _foreach (blob
, blobs
)
1142 put(output
, blob
.second
.data(), blob
.second
.size());
1155 _assert(bio_
!= NULL
);
1159 bio_(BIO_new(BIO_s_mem()))
1163 Buffer(const char *data
, size_t size
) :
1164 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1168 Buffer(const std::string
&data
) :
1169 Buffer(data
.data(), data
.size())
1173 Buffer(PKCS7
*pkcs
) :
1176 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1183 operator BIO
*() const {
1187 explicit operator std::string() const {
1189 auto size(BIO_get_mem_data(bio_
, &data
));
1190 return std::string(data
, size
);
1199 STACK_OF(X509
) *ca_
;
1203 value_(d2i_PKCS12_bio(bio
, NULL
)),
1206 _assert(value_
!= NULL
);
1207 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1208 _assert(key_
!= NULL
);
1209 _assert(cert_
!= NULL
);
1212 Stuff(const std::string
&data
) :
1218 sk_X509_pop_free(ca_
, X509_free
);
1220 EVP_PKEY_free(key_
);
1221 PKCS12_free(value_
);
1224 operator PKCS12
*() const {
1228 operator EVP_PKEY
*() const {
1232 operator X509
*() const {
1236 operator STACK_OF(X509
) *() const {
1246 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1247 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1249 _assert(value_
!= NULL
);
1256 operator PKCS7
*() const {
1263 void Sign(void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&name
, const std::string
&entitlements
, const std::string
&key
, const Slots
&slots
) {
1264 Allocate(idata
, isize
, output
, fun([&](size_t size
) -> size_t {
1265 size_t alloc(sizeof(struct SuperBlob
));
1267 uint32_t special(0);
1269 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1270 alloc
+= sizeof(struct BlobIndex
);
1273 if (!entitlements
.empty()) {
1274 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1275 alloc
+= sizeof(struct BlobIndex
);
1276 alloc
+= sizeof(struct Blob
);
1277 alloc
+= entitlements
.size();
1280 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1281 alloc
+= sizeof(struct BlobIndex
);
1282 alloc
+= sizeof(struct Blob
);
1283 alloc
+= sizeof(struct CodeDirectory
);
1284 alloc
+= name
.size() + 1;
1287 alloc
+= sizeof(struct BlobIndex
);
1288 alloc
+= sizeof(struct Blob
);
1289 // XXX: this is just a "sufficiently large number"
1293 _foreach (slot
, slots
)
1294 special
= std::max(special
, slot
.first
);
1296 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1297 alloc
= Align(alloc
+ (special
+ normal
) * SHA_DIGEST_LENGTH
, 16);
1299 }), fun([&](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1303 std::stringbuf data
;
1306 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1308 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1311 if (!entitlements
.empty()) {
1312 std::stringbuf data
;
1313 put(data
, entitlements
.data(), entitlements
.size());
1314 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1318 std::stringbuf data
;
1320 uint32_t special(0);
1321 _foreach (blob
, blobs
)
1322 special
= std::max(special
, blob
.first
);
1323 _foreach (slot
, slots
)
1324 special
= std::max(special
, slot
.first
);
1325 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1327 CodeDirectory directory
;
1328 directory
.version
= Swap(uint32_t(0x00020001));
1329 directory
.flags
= Swap(uint32_t(0));
1330 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + name
.size() + 1 + SHA_DIGEST_LENGTH
* special
));
1331 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1332 directory
.nSpecialSlots
= Swap(special
);
1333 directory
.codeLimit
= Swap(uint32_t(limit
));
1334 directory
.nCodeSlots
= Swap(normal
);
1335 directory
.hashSize
= SHA_DIGEST_LENGTH
;
1336 directory
.hashType
= CS_HASHTYPE_SHA1
;
1337 directory
.spare1
= 0x00;
1338 directory
.pageSize
= PageShift_
;
1339 directory
.spare2
= Swap(uint32_t(0));
1340 put(data
, &directory
, sizeof(directory
));
1342 put(data
, name
.c_str(), name
.size() + 1);
1344 uint8_t storage
[special
+ normal
][SHA_DIGEST_LENGTH
];
1345 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = storage
+ special
;
1347 memset(storage
, 0, sizeof(*storage
) * special
);
1349 _foreach (blob
, blobs
) {
1350 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1351 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1354 _foreach (slot
, slots
) {
1355 _assert(sizeof(*hashes
) == slot
.second
.size());
1356 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1360 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1361 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1363 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1365 put(data
, storage
, sizeof(storage
));
1367 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1371 std::stringbuf data
;
1372 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1377 Signature
signature(stuff
, sign
);
1378 Buffer
result(signature
);
1379 std::string
value(result
);
1380 put(data
, value
.data(), value
.size());
1382 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1385 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1389 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1390 Allocate(idata
, isize
, output
, fun([](size_t size
) -> size_t {
1392 }), fun([](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1399 int main(int argc
, char *argv
[]) {
1400 OpenSSL_add_all_algorithms();
1407 little_
= endian
.byte
[0];
1422 uint32_t flag_CPUType(_not(uint32_t));
1423 uint32_t flag_CPUSubtype(_not(uint32_t));
1425 const char *flag_I(NULL
);
1434 std::vector
<std::string
> files
;
1437 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
1438 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
1439 fprintf(stderr
, " %s -S cat\n", argv
[0]);
1440 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
1444 for (int argi(1); argi
!= argc
; ++argi
)
1445 if (argv
[argi
][0] != '-')
1446 files
.push_back(argv
[argi
]);
1447 else switch (argv
[argi
][1]) {
1454 case 'e': flag_e
= true; break;
1457 const char *slot
= argv
[argi
] + 2;
1458 const char *colon
= strchr(slot
, ':');
1459 _assert(colon
!= NULL
);
1460 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1462 unsigned number(strtoul(slot
, &arge
, 0));
1463 _assert(arge
== colon
);
1464 std::string
&hash(slots
[number
]);
1465 hash
.resize(SHA_DIGEST_LENGTH
);
1466 sha1(reinterpret_cast<uint8_t *>(&hash
[0]), file
.data(), file
.size());
1469 case 'D': flag_D
= true; break;
1471 case 'a': flag_a
= true; break;
1476 if (argv
[argi
][2] != '\0') {
1477 const char *cpu
= argv
[argi
] + 2;
1478 const char *colon
= strchr(cpu
, ':');
1479 _assert(colon
!= NULL
);
1481 flag_CPUType
= strtoul(cpu
, &arge
, 0);
1482 _assert(arge
== colon
);
1483 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
1484 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
1498 if (argv
[argi
][2] != '\0') {
1499 const char *xml
= argv
[argi
] + 2;
1500 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1505 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1510 if (argv
[argi
][2] == '-')
1514 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
1515 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
1520 flag_I
= argv
[argi
] + 2;
1528 _assert(flag_S
|| key
.empty());
1529 _assert(flag_S
|| flag_I
== NULL
);
1531 if (files
.empty()) usage
: {
1535 size_t filei(0), filee(0);
1536 _foreach (file
, files
) try {
1537 const char *path(file
.c_str());
1539 if (flag_S
|| flag_r
) {
1540 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1543 const char *base
= strrchr(path
, '/');
1546 dir
.assign(path
, base
++ - path
+ 1);
1550 std::string
temp(dir
+ "." + base
+ ".cs");
1551 std::filebuf output
;
1552 _assert(output
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &output
);
1555 ldid::Unsign(input
.data(), input
.size(), output
);
1557 const char *name(flag_I
?: base
);
1558 ldid::Sign(input
.data(), input
.size(), output
, name
, entitlements
, key
, slots
);
1562 _syscall(stat(path
, &info
));
1564 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1566 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1567 _syscall(unlink(path
));
1568 _syscall(rename(temp
.c_str(), path
));
1571 Map
mapping(path
, flag_T
|| flag_s
);
1572 FatHeader
fat_header(mapping
.data(), mapping
.size());
1574 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
1575 struct linkedit_data_command
*signature(NULL
);
1576 struct encryption_info_command
*encryption(NULL
);
1579 if (mach_header
.GetCPUType() != flag_CPUType
)
1581 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
1586 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
1588 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1589 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1592 else if (cmd
== LC_CODE_SIGNATURE
)
1593 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1594 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
1595 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
1596 else if (cmd
== LC_ID_DYLIB
) {
1597 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
1605 dylib_command
->dylib
.timestamp
= 0;
1606 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
1609 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
1615 _assert(encryption
!= NULL
);
1616 encryption
->cryptid
= mach_header
.Swap(0);
1620 _assert(signature
!= NULL
);
1622 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
1624 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
1625 uint8_t *blob
= top
+ data
;
1626 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
1628 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1629 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1630 uint32_t begin
= Swap(super
->index
[index
].offset
);
1631 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
1632 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
1637 _assert(signature
!= NULL
);
1639 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
1641 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
1642 uint8_t *blob
= top
+ data
;
1643 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
1645 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1646 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
1647 uint32_t begin
= Swap(super
->index
[index
].offset
);
1648 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
1650 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
1651 uint32_t pages
= Swap(directory
->nCodeSlots
);
1654 for (size_t i
= 0; i
!= pages
- 1; ++i
)
1655 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
1657 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
1663 } catch (const char *) {