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>
48 #define _assert___(line) \
50 #define _assert__(line) \
53 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" e ")"
55 #define _assert(expr) \
57 fprintf(stderr, "%s(%u): _assert(%s); errno=%u\n", __FILE__, __LINE__, #expr, errno); \
61 #define _syscall(expr) ({ \
62 __typeof__(expr) _value; \
63 do if ((long) (_value = (expr)) != -1) \
65 else switch (errno) { \
75 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
81 __attribute__((packed))
83 template <typename Type_
>
85 typedef typename
Type_::const_iterator Result
;
88 #define _foreach(item, list) \
89 for (bool _stop(true); _stop; ) \
90 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
91 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
92 for (bool _suck(true); _suck; _suck = false) \
93 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
100 #define FAT_MAGIC 0xcafebabe
101 #define FAT_CIGAM 0xbebafeca
121 #define MH_MAGIC 0xfeedface
122 #define MH_CIGAM 0xcefaedfe
124 #define MH_MAGIC_64 0xfeedfacf
125 #define MH_CIGAM_64 0xcffaedfe
127 #define MH_DYLDLINK 0x4
129 #define MH_OBJECT 0x1
130 #define MH_EXECUTE 0x2
132 #define MH_BUNDLE 0x8
133 #define MH_DYLIB_STUB 0x9
135 struct load_command
{
140 #define LC_REQ_DYLD uint32_t(0x80000000)
142 #define LC_SEGMENT uint32_t(0x01)
143 #define LC_SYMTAB uint32_t(0x02)
144 #define LC_DYSYMTAB uint32_t(0x0b)
145 #define LC_LOAD_DYLIB uint32_t(0x0c)
146 #define LC_ID_DYLIB uint32_t(0x0d)
147 #define LC_SEGMENT_64 uint32_t(0x19)
148 #define LC_UUID uint32_t(0x1b)
149 #define LC_CODE_SIGNATURE uint32_t(0x1d)
150 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
151 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
152 #define LC_ENCRYPTION_INFO uint32_t(0x21)
153 #define LC_DYLD_INFO uint32_t(0x22)
154 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
155 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
160 uint32_t current_version
;
161 uint32_t compatibility_version
;
164 struct dylib_command
{
170 struct uuid_command
{
176 struct symtab_command
{
185 struct dyld_info_command
{
189 uint32_t rebase_size
;
192 uint32_t weak_bind_off
;
193 uint32_t weak_bind_size
;
194 uint32_t lazy_bind_off
;
195 uint32_t lazy_bind_size
;
197 uint32_t export_size
;
200 struct dysymtab_command
{
213 uint32_t extrefsymoff
;
214 uint32_t nextrefsyms
;
215 uint32_t indirectsymoff
;
216 uint32_t nindirectsyms
;
223 struct dylib_table_of_contents
{
224 uint32_t symbol_index
;
225 uint32_t module_index
;
228 struct dylib_module
{
229 uint32_t module_name
;
238 uint32_t iinit_iterm
;
239 uint32_t ninit_nterm
;
240 uint32_t objc_module_info_addr
;
241 uint32_t objc_module_info_size
;
244 struct dylib_reference
{
249 struct relocation_info
{
251 uint32_t r_symbolnum
:24;
270 struct segment_command
{
284 struct segment_command_64
{
326 struct linkedit_data_command
{
333 struct encryption_info_command
{
341 #define BIND_OPCODE_MASK 0xf0
342 #define BIND_IMMEDIATE_MASK 0x0f
343 #define BIND_OPCODE_DONE 0x00
344 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
345 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
346 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
347 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
348 #define BIND_OPCODE_SET_TYPE_IMM 0x50
349 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
350 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
351 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
352 #define BIND_OPCODE_DO_BIND 0x90
353 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
354 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
355 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
357 inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
358 _assert(stream
.sgetn(static_cast<char *>(data
), size
) == size
);
361 inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
362 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
365 inline void pad(std::streambuf
&stream
, size_t size
) {
367 memset(padding
, 0, size
);
368 put(stream
, padding
, size
);
371 template <typename Type_
>
372 Type_
Align(Type_ value
, size_t align
) {
379 static const uint8_t PageShift_(0x0c);
380 static const uint32_t PageSize_(1 << PageShift_
);
382 static inline uint16_t Swap_(uint16_t value
) {
384 ((value
>> 8) & 0x00ff) |
385 ((value
<< 8) & 0xff00);
388 static inline uint32_t Swap_(uint32_t value
) {
389 value
= ((value
>> 8) & 0x00ff00ff) |
390 ((value
<< 8) & 0xff00ff00);
391 value
= ((value
>> 16) & 0x0000ffff) |
392 ((value
<< 16) & 0xffff0000);
396 static inline uint64_t Swap_(uint64_t value
) {
397 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
398 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
399 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
403 static inline int16_t Swap_(int16_t value
) {
404 return Swap_(static_cast<uint16_t>(value
));
407 static inline int32_t Swap_(int32_t value
) {
408 return Swap_(static_cast<uint32_t>(value
));
411 static inline int64_t Swap_(int64_t value
) {
412 return Swap_(static_cast<uint64_t>(value
));
415 static bool little_(true);
417 static inline uint16_t Swap(uint16_t value
) {
418 return little_
? Swap_(value
) : value
;
421 static inline uint32_t Swap(uint32_t value
) {
422 return little_
? Swap_(value
) : value
;
425 static inline uint64_t Swap(uint64_t value
) {
426 return little_
? Swap_(value
) : value
;
429 static inline int16_t Swap(int16_t value
) {
430 return Swap(static_cast<uint16_t>(value
));
433 static inline int32_t Swap(int32_t value
) {
434 return Swap(static_cast<uint32_t>(value
));
437 static inline int64_t Swap(int64_t value
) {
438 return Swap(static_cast<uint64_t>(value
));
441 template <typename Target_
>
454 Swapped(bool swapped
) :
459 template <typename Type_
>
460 Type_
Swap(Type_ value
) const {
461 return swapped_
? Swap_(value
) : value
;
473 Data(void *base
, size_t size
) :
479 void *GetBase() const {
483 size_t GetSize() const {
494 struct mach_header
*mach_header_
;
495 struct load_command
*load_command_
;
498 MachHeader(void *base
, size_t size
) :
501 mach_header_
= (mach_header
*) base
;
503 switch (Swap(mach_header_
->magic
)) {
505 swapped_
= !swapped_
;
511 swapped_
= !swapped_
;
520 void *post
= mach_header_
+ 1;
522 post
= (uint32_t *) post
+ 1;
523 load_command_
= (struct load_command
*) post
;
526 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
527 Swap(mach_header_
->filetype
) == MH_DYLIB
||
528 Swap(mach_header_
->filetype
) == MH_BUNDLE
532 bool Bits64() const {
536 struct mach_header
*operator ->() const {
540 operator struct mach_header
*() const {
544 uint32_t GetCPUType() const {
545 return Swap(mach_header_
->cputype
);
548 uint32_t GetCPUSubtype() const {
549 return Swap(mach_header_
->cpusubtype
) & 0xff;
552 struct load_command
*GetLoadCommand() const {
553 return load_command_
;
556 std::vector
<struct load_command
*> GetLoadCommands() const {
557 std::vector
<struct load_command
*> load_commands
;
559 struct load_command
*load_command
= load_command_
;
560 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
561 load_commands
.push_back(load_command
);
562 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
565 return load_commands
;
568 std::vector
<segment_command
*> GetSegments(const char *segment_name
) const {
569 std::vector
<struct segment_command
*> segment_commands
;
571 _foreach (load_command
, GetLoadCommands()) {
572 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
573 segment_command
*segment_command
= reinterpret_cast<struct segment_command
*>(load_command
);
574 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
575 segment_commands
.push_back(segment_command
);
579 return segment_commands
;
582 std::vector
<segment_command_64
*> GetSegments64(const char *segment_name
) const {
583 std::vector
<struct segment_command_64
*> segment_commands
;
585 _foreach (load_command
, GetLoadCommands()) {
586 if (Swap(load_command
->cmd
) == LC_SEGMENT_64
) {
587 segment_command_64
*segment_command
= reinterpret_cast<struct segment_command_64
*>(load_command
);
588 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
589 segment_commands
.push_back(segment_command
);
593 return segment_commands
;
596 std::vector
<section
*> GetSections(const char *segment_name
, const char *section_name
) const {
597 std::vector
<section
*> sections
;
599 _foreach (segment
, GetSegments(segment_name
)) {
600 section
*section
= (struct section
*) (segment
+ 1);
603 for (sect
= 0; sect
!= Swap(segment
->nsects
); ++sect
) {
604 if (strncmp(section
->sectname
, section_name
, 16) == 0)
605 sections
.push_back(section
);
613 template <typename Target_
>
614 Pointer
<Target_
> GetPointer(uint32_t address
, const char *segment_name
= NULL
) const {
615 load_command
*load_command
= (struct load_command
*) (mach_header_
+ 1);
618 for (cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
619 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
620 segment_command
*segment_command
= (struct segment_command
*) load_command
;
621 if (segment_name
!= NULL
&& strncmp(segment_command
->segname
, segment_name
, 16) != 0)
624 section
*sections
= (struct section
*) (segment_command
+ 1);
627 for (sect
= 0; sect
!= Swap(segment_command
->nsects
); ++sect
) {
628 section
*section
= §ions
[sect
];
629 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
630 if (address
>= Swap(section
->addr
) && address
< Swap(section
->addr
) + Swap(section
->size
)) {
631 //printf("0x%.8x %s\n", address, segment_command->segname);
632 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(address
- Swap(section
->addr
) + Swap(section
->offset
) + (char *) mach_header_
));
638 load_command
= (struct load_command
*) ((char *) load_command
+ Swap(load_command
->cmdsize
));
641 return Pointer
<Target_
>(this);
644 template <typename Target_
>
645 Pointer
<Target_
> GetOffset(uint32_t offset
) {
646 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
));
650 class FatMachHeader
:
657 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
658 MachHeader(base
, size
),
663 fat_arch
*GetFatArch() const {
672 fat_header
*fat_header_
;
673 std::vector
<FatMachHeader
> mach_headers_
;
676 FatHeader(void *base
, size_t size
) :
679 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
681 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
682 swapped_
= !swapped_
;
684 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
686 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
688 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
689 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
691 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
692 uint32_t arch_offset
= Swap(fat_arch
->offset
);
693 uint32_t arch_size
= Swap(fat_arch
->size
);
694 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
700 std::vector
<FatMachHeader
> &GetMachHeaders() {
701 return mach_headers_
;
705 return fat_header_
!= NULL
;
708 struct fat_header
*operator ->() const {
712 operator struct fat_header
*() const {
717 template <typename Target_
>
720 const MachHeader
*framework_
;
721 const Target_
*pointer_
;
724 Pointer(const MachHeader
*framework
= NULL
, const Target_
*pointer
= NULL
) :
725 framework_(framework
),
730 operator const Target_
*() const {
734 const Target_
*operator ->() const {
738 Pointer
<Target_
> &operator ++() {
743 template <typename Value_
>
744 Value_
Swap(Value_ value
) {
745 return framework_
->Swap(value
);
749 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
750 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
751 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
752 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
753 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
754 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
755 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
756 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
758 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
759 #define CSSLOT_INFOSLOT uint32_t(0x00001)
760 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
761 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
762 #define CSSLOT_APPLICATION uint32_t(0x00004)
763 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
765 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
767 #define CS_HASHTYPE_SHA1 1
782 struct BlobIndex index
[];
785 struct CodeDirectory
{
789 uint32_t identOffset
;
790 uint32_t nSpecialSlots
;
800 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
802 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
803 SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
806 struct CodesignAllocation
{
807 FatMachHeader mach_header_
;
814 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
815 mach_header_(mach_header
),
837 _syscall(close(file_
));
840 void open(const char *path
, int flags
) {
841 _assert(file_
== -1);
842 _syscall(file_
= ::open(path
, flags
));
859 _syscall(munmap(data_
, size_
));
871 Map(const char *path
, int oflag
, int pflag
, int mflag
) :
874 open(path
, oflag
, pflag
, mflag
);
877 Map(const char *path
, bool edit
) :
888 return data_
== NULL
;
891 void open(const char *path
, int oflag
, int pflag
, int mflag
) {
894 file_
.open(path
, oflag
);
895 int file(file_
.file());
898 _syscall(fstat(file
, &stat
));
899 size_
= stat
.st_size
;
901 _syscall(data_
= mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
904 void open(const char *path
, bool edit
) {
906 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
908 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
915 size_t size() const {
919 operator std::string() const {
920 return std::string(static_cast<char *>(data_
), size_
);
924 // I wish Apple cared about providing quality toolchains :/
926 template <typename Function_
>
929 template <typename Type_
, typename
... Args_
>
930 class Functor
<Type_ (Args_
...)> {
932 virtual Type_
operator ()(Args_
... args
) const = 0;
935 template <typename Function_
>
938 template <typename Value_
, typename Type_
, typename
... Args_
>
939 class FunctorImpl
<Type_ (Value_::*)(Args_
...) const> :
940 public Functor
<Type_ (Args_
...)>
943 const Value_
*value_
;
946 FunctorImpl(const Value_
&value
) :
951 virtual Type_
operator ()(Args_
... args
) const {
952 return (*value_
)(args
...);
956 template <typename Function_
>
957 FunctorImpl
<decltype(&Function_::operator())> fun(const Function_
&value
) {
961 static void resign(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
) {
962 FatHeader
source(idata
, isize
);
966 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
968 std::vector
<CodesignAllocation
> allocations
;
969 _foreach (mach_header
, source
.GetMachHeaders()) {
970 struct linkedit_data_command
*signature(NULL
);
971 struct symtab_command
*symtab(NULL
);
973 _foreach (load_command
, mach_header
.GetLoadCommands()) {
974 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
976 else if (cmd
== LC_CODE_SIGNATURE
)
977 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
978 else if (cmd
== LC_SYMTAB
)
979 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
983 if (signature
== NULL
)
984 size
= mach_header
.GetSize();
986 size
= mach_header
.Swap(signature
->dataoff
);
987 _assert(size
<= mach_header
.GetSize());
990 if (symtab
!= NULL
) {
991 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
992 _assert(end
<= size
);
993 _assert(end
>= size
- 0x10);
997 size_t alloc(allocate(size
));
999 auto *fat_arch(mach_header
.GetFatArch());
1000 uint32_t align(fat_arch
== NULL
? 0 : source
.Swap(fat_arch
->align
));
1001 offset
= Align(offset
, 1 << align
);
1003 uint32_t limit(size
);
1005 limit
= Align(limit
, 0x10);
1007 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1008 offset
+= size
+ alloc
;
1009 offset
= Align(offset
, 0x10);
1014 if (source
.IsFat()) {
1015 fat_header fat_header
;
1016 fat_header
.magic
= Swap(FAT_MAGIC
);
1017 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1018 put(output
, &fat_header
, sizeof(fat_header
));
1019 position
+= sizeof(fat_header
);
1021 _foreach (allocation
, allocations
) {
1022 auto &mach_header(allocation
.mach_header_
);
1025 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1026 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1027 fat_arch
.offset
= Swap(allocation
.offset_
);
1028 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1029 fat_arch
.align
= Swap(allocation
.align_
);
1030 put(output
, &fat_arch
, sizeof(fat_arch
));
1031 position
+= sizeof(fat_arch
);
1035 _foreach (allocation
, allocations
) {
1036 auto &mach_header(allocation
.mach_header_
);
1038 pad(output
, allocation
.offset_
- position
);
1039 position
= allocation
.offset_
;
1041 std::vector
<std::string
> commands
;
1043 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1044 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1046 switch (mach_header
.Swap(load_command
->cmd
)) {
1047 case LC_CODE_SIGNATURE
:
1052 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1053 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1055 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1056 segment_command
->filesize
= size
;
1057 segment_command
->vmsize
= Align(size
, PageSize_
);
1060 case LC_SEGMENT_64
: {
1061 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1062 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1064 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1065 segment_command
->filesize
= size
;
1066 segment_command
->vmsize
= Align(size
, PageSize_
);
1070 commands
.push_back(copy
);
1073 if (allocation
.alloc_
!= 0) {
1074 linkedit_data_command signature
;
1075 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1076 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1077 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1078 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1079 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1082 size_t begin(position
);
1085 _foreach(command
, commands
)
1086 after
+= command
.size();
1088 std::stringbuf altern
;
1090 struct mach_header
header(*mach_header
);
1091 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1092 header
.sizeofcmds
= mach_header
.Swap(after
);
1093 put(output
, &header
, sizeof(header
));
1094 put(altern
, &header
, sizeof(header
));
1095 position
+= sizeof(header
);
1097 if (mach_header
.Bits64()) {
1098 auto pad(mach_header
.Swap(uint32_t(0)));
1099 put(output
, &pad
, sizeof(pad
));
1100 put(altern
, &pad
, sizeof(pad
));
1101 position
+= sizeof(pad
);
1104 _foreach(command
, commands
) {
1105 put(output
, command
.data(), command
.size());
1106 put(altern
, command
.data(), command
.size());
1107 position
+= command
.size();
1110 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1111 if (before
> after
) {
1112 pad(output
, before
- after
);
1113 pad(altern
, before
- after
);
1114 position
+= before
- after
;
1117 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1119 std::string
overlap(altern
.str());
1120 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1122 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1123 position
= begin
+ allocation
.size_
;
1125 pad(output
, allocation
.limit_
- allocation
.size_
);
1126 position
+= allocation
.limit_
- allocation
.size_
;
1128 size_t saved(save(output
, allocation
.limit_
, overlap
, top
));
1129 if (allocation
.alloc_
> saved
)
1130 pad(output
, allocation
.alloc_
- saved
);
1131 position
+= allocation
.alloc_
;
1135 typedef std::map
<uint32_t, std::string
> Blobs
;
1137 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1138 auto value(buffer
.str());
1139 std::swap(blobs
[slot
], value
);
1142 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1143 auto value(buffer
.str());
1145 blob
.magic
= Swap(magic
);
1146 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1147 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1148 std::swap(blobs
[slot
], value
);
1151 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1153 _foreach (blob
, blobs
)
1154 total
+= blob
.second
.size();
1156 struct SuperBlob super
;
1157 super
.blob
.magic
= Swap(magic
);
1158 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1159 super
.count
= Swap(uint32_t(blobs
.size()));
1160 put(output
, &super
, sizeof(super
));
1162 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1164 _foreach (blob
, blobs
) {
1166 index
.type
= Swap(blob
.first
);
1167 index
.offset
= Swap(uint32_t(offset
));
1168 put(output
, &index
, sizeof(index
));
1169 offset
+= blob
.second
.size();
1172 _foreach (blob
, blobs
)
1173 put(output
, blob
.second
.data(), blob
.second
.size());
1186 _assert(bio_
!= NULL
);
1190 bio_(BIO_new(BIO_s_mem()))
1194 Buffer(const char *data
, size_t size
) :
1195 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1199 Buffer(const std::string
&data
) :
1200 Buffer(data
.data(), data
.size())
1204 Buffer(PKCS7
*pkcs
) :
1207 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1214 operator BIO
*() const {
1218 explicit operator std::string() const {
1220 auto size(BIO_get_mem_data(bio_
, &data
));
1221 return std::string(data
, size
);
1230 STACK_OF(X509
) *ca_
;
1234 value_(d2i_PKCS12_bio(bio
, NULL
)),
1237 _assert(value_
!= NULL
);
1238 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1239 _assert(key_
!= NULL
);
1240 _assert(cert_
!= NULL
);
1243 Stuff(const std::string
&data
) :
1249 sk_X509_pop_free(ca_
, X509_free
);
1251 EVP_PKEY_free(key_
);
1252 PKCS12_free(value_
);
1255 operator PKCS12
*() const {
1259 operator EVP_PKEY
*() const {
1263 operator X509
*() const {
1267 operator STACK_OF(X509
) *() const {
1277 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1278 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1280 _assert(value_
!= NULL
);
1287 operator PKCS7
*() const {
1292 typedef std::map
<uint32_t, std::string
> Slots
;
1294 void resign(void *idata
, size_t isize
, std::streambuf
&output
, const std::string
&name
, const std::string
&entitlements
, const std::string
&key
, const Slots
&slots
) {
1295 resign(idata
, isize
, output
, fun([&](size_t size
) -> size_t {
1296 size_t alloc(sizeof(struct SuperBlob
));
1298 uint32_t special(0);
1300 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1301 alloc
+= sizeof(struct BlobIndex
);
1304 if (!entitlements
.empty()) {
1305 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1306 alloc
+= sizeof(struct BlobIndex
);
1307 alloc
+= sizeof(struct Blob
);
1308 alloc
+= entitlements
.size();
1311 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1312 alloc
+= sizeof(struct BlobIndex
);
1313 alloc
+= sizeof(struct Blob
);
1314 alloc
+= sizeof(struct CodeDirectory
);
1315 alloc
+= name
.size() + 1;
1318 alloc
+= sizeof(struct BlobIndex
);
1319 alloc
+= sizeof(struct Blob
);
1320 // XXX: this is just a "sufficiently large number"
1324 _foreach (slot
, slots
)
1325 special
= std::max(special
, slot
.first
);
1327 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1328 alloc
= Align(alloc
+ (special
+ normal
) * SHA_DIGEST_LENGTH
, 16);
1330 }), fun([&](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1334 std::stringbuf data
;
1337 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1339 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1342 if (!entitlements
.empty()) {
1343 std::stringbuf data
;
1344 put(data
, entitlements
.data(), entitlements
.size());
1345 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1349 std::stringbuf data
;
1351 uint32_t special(0);
1352 _foreach (blob
, blobs
)
1353 special
= std::max(special
, blob
.first
);
1354 _foreach (slot
, slots
)
1355 special
= std::max(special
, slot
.first
);
1356 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1358 CodeDirectory directory
;
1359 directory
.version
= Swap(uint32_t(0x00020001));
1360 directory
.flags
= Swap(uint32_t(0));
1361 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + name
.size() + 1 + SHA_DIGEST_LENGTH
* special
));
1362 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1363 directory
.nSpecialSlots
= Swap(special
);
1364 directory
.codeLimit
= Swap(uint32_t(limit
));
1365 directory
.nCodeSlots
= Swap(normal
);
1366 directory
.hashSize
= SHA_DIGEST_LENGTH
;
1367 directory
.hashType
= CS_HASHTYPE_SHA1
;
1368 directory
.spare1
= 0x00;
1369 directory
.pageSize
= PageShift_
;
1370 directory
.spare2
= Swap(uint32_t(0));
1371 put(data
, &directory
, sizeof(directory
));
1373 put(data
, name
.c_str(), name
.size() + 1);
1375 uint8_t storage
[special
+ normal
][SHA_DIGEST_LENGTH
];
1376 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = storage
+ special
;
1378 memset(storage
, 0, sizeof(*storage
) * special
);
1380 _foreach (blob
, blobs
) {
1381 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1382 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1385 _foreach (slot
, slots
) {
1386 _assert(sizeof(*hashes
) == slot
.second
.size());
1387 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1391 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1392 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1394 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1396 put(data
, storage
, sizeof(storage
));
1398 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1402 std::stringbuf data
;
1403 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1408 Signature
signature(stuff
, sign
);
1409 Buffer
result(signature
);
1410 std::string
value(result
);
1411 put(data
, value
.data(), value
.size());
1413 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1416 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1420 static void resign(void *idata
, size_t isize
, std::streambuf
&output
) {
1421 resign(idata
, isize
, output
, fun([](size_t size
) -> size_t {
1423 }), fun([](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1428 int main(int argc
, char *argv
[]) {
1429 OpenSSL_add_all_algorithms();
1436 little_
= endian
.byte
[0];
1451 uint32_t flag_CPUType(_not(uint32_t));
1452 uint32_t flag_CPUSubtype(_not(uint32_t));
1454 const char *flag_I(NULL
);
1463 std::vector
<std::string
> files
;
1466 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
1467 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
1468 fprintf(stderr
, " %s -S cat\n", argv
[0]);
1469 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
1473 for (int argi(1); argi
!= argc
; ++argi
)
1474 if (argv
[argi
][0] != '-')
1475 files
.push_back(argv
[argi
]);
1476 else switch (argv
[argi
][1]) {
1483 case 'e': flag_e
= true; break;
1486 const char *slot
= argv
[argi
] + 2;
1487 const char *colon
= strchr(slot
, ':');
1488 _assert(colon
!= NULL
);
1489 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1491 unsigned number(strtoul(slot
, &arge
, 0));
1492 _assert(arge
== colon
);
1493 std::string
&hash(slots
[number
]);
1494 hash
.resize(SHA_DIGEST_LENGTH
);
1495 sha1(reinterpret_cast<uint8_t *>(&hash
[0]), file
.data(), file
.size());
1498 case 'D': flag_D
= true; break;
1500 case 'a': flag_a
= true; break;
1505 if (argv
[argi
][2] != '\0') {
1506 const char *cpu
= argv
[argi
] + 2;
1507 const char *colon
= strchr(cpu
, ':');
1508 _assert(colon
!= NULL
);
1510 flag_CPUType
= strtoul(cpu
, &arge
, 0);
1511 _assert(arge
== colon
);
1512 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
1513 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
1527 if (argv
[argi
][2] != '\0') {
1528 const char *xml
= argv
[argi
] + 2;
1529 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1534 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1539 if (argv
[argi
][2] == '-')
1543 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
1544 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
1549 flag_I
= argv
[argi
] + 2;
1557 _assert(flag_S
|| key
.empty());
1558 _assert(flag_S
|| flag_I
== NULL
);
1560 if (files
.empty()) usage
: {
1564 size_t filei(0), filee(0);
1565 _foreach (file
, files
) try {
1566 const char *path(file
.c_str());
1568 if (flag_S
|| flag_r
) {
1569 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1572 const char *base
= strrchr(path
, '/');
1575 dir
.assign(path
, base
++ - path
+ 1);
1579 std::string
temp(dir
+ "." + base
+ ".cs");
1580 std::filebuf output
;
1581 _assert(output
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &output
);
1584 resign(input
.data(), input
.size(), output
);
1586 const char *name(flag_I
?: base
);
1587 resign(input
.data(), input
.size(), output
, name
, entitlements
, key
, slots
);
1591 _syscall(stat(path
, &info
));
1593 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1595 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1596 _syscall(unlink(path
));
1597 _syscall(rename(temp
.c_str(), path
));
1600 Map
mapping(path
, flag_T
|| flag_s
);
1601 FatHeader
fat_header(mapping
.data(), mapping
.size());
1603 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
1604 struct linkedit_data_command
*signature(NULL
);
1605 struct encryption_info_command
*encryption(NULL
);
1608 if (mach_header
.GetCPUType() != flag_CPUType
)
1610 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
1615 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
1617 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1618 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1621 else if (cmd
== LC_CODE_SIGNATURE
)
1622 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1623 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
1624 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
1625 else if (cmd
== LC_ID_DYLIB
) {
1626 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
1634 dylib_command
->dylib
.timestamp
= 0;
1635 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
1638 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
1644 _assert(encryption
!= NULL
);
1645 encryption
->cryptid
= mach_header
.Swap(0);
1649 _assert(signature
!= NULL
);
1651 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
1653 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
1654 uint8_t *blob
= top
+ data
;
1655 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
1657 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1658 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1659 uint32_t begin
= Swap(super
->index
[index
].offset
);
1660 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
1661 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
1666 _assert(signature
!= NULL
);
1668 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
1670 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
1671 uint8_t *blob
= top
+ data
;
1672 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
1674 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1675 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
1676 uint32_t begin
= Swap(super
->index
[index
].offset
);
1677 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
1679 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
1680 uint32_t pages
= Swap(directory
->nCodeSlots
);
1683 for (size_t i
= 0; i
!= pages
- 1; ++i
)
1684 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
1686 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
1692 } catch (const char *) {