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_
);
926 // I wish Apple cared about providing quality toolchains :/
928 template <typename Function_
>
931 template <typename Type_
, typename
... Args_
>
932 class Functor
<Type_ (Args_
...)> {
934 virtual Type_
operator ()(Args_
... args
) const = 0;
937 template <typename Function_
>
940 template <typename Value_
, typename Type_
, typename
... Args_
>
941 class FunctorImpl
<Type_ (Value_::*)(Args_
...) const> :
942 public Functor
<Type_ (Args_
...)>
945 const Value_
*value_
;
948 FunctorImpl(const Value_
&value
) :
953 virtual Type_
operator ()(Args_
... args
) const {
954 return (*value_
)(args
...);
958 template <typename Function_
>
959 FunctorImpl
<decltype(&Function_::operator())> fun(const Function_
&value
) {
965 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
) {
966 FatHeader
source(idata
, isize
);
970 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
972 std::vector
<CodesignAllocation
> allocations
;
973 _foreach (mach_header
, source
.GetMachHeaders()) {
974 struct linkedit_data_command
*signature(NULL
);
975 struct symtab_command
*symtab(NULL
);
977 _foreach (load_command
, mach_header
.GetLoadCommands()) {
978 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
980 else if (cmd
== LC_CODE_SIGNATURE
)
981 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
982 else if (cmd
== LC_SYMTAB
)
983 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
987 if (signature
== NULL
)
988 size
= mach_header
.GetSize();
990 size
= mach_header
.Swap(signature
->dataoff
);
991 _assert(size
<= mach_header
.GetSize());
994 if (symtab
!= NULL
) {
995 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
996 _assert(end
<= size
);
997 _assert(end
>= size
- 0x10);
1001 size_t alloc(allocate(size
));
1003 auto *fat_arch(mach_header
.GetFatArch());
1004 uint32_t align(fat_arch
== NULL
? 0 : source
.Swap(fat_arch
->align
));
1005 offset
= Align(offset
, 1 << align
);
1007 uint32_t limit(size
);
1009 limit
= Align(limit
, 0x10);
1011 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
1012 offset
+= size
+ alloc
;
1013 offset
= Align(offset
, 0x10);
1018 if (source
.IsFat()) {
1019 fat_header fat_header
;
1020 fat_header
.magic
= Swap(FAT_MAGIC
);
1021 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
1022 put(output
, &fat_header
, sizeof(fat_header
));
1023 position
+= sizeof(fat_header
);
1025 _foreach (allocation
, allocations
) {
1026 auto &mach_header(allocation
.mach_header_
);
1029 fat_arch
.cputype
= Swap(mach_header
->cputype
);
1030 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
1031 fat_arch
.offset
= Swap(allocation
.offset_
);
1032 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
1033 fat_arch
.align
= Swap(allocation
.align_
);
1034 put(output
, &fat_arch
, sizeof(fat_arch
));
1035 position
+= sizeof(fat_arch
);
1039 _foreach (allocation
, allocations
) {
1040 auto &mach_header(allocation
.mach_header_
);
1042 pad(output
, allocation
.offset_
- position
);
1043 position
= allocation
.offset_
;
1045 std::vector
<std::string
> commands
;
1047 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1048 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1050 switch (mach_header
.Swap(load_command
->cmd
)) {
1051 case LC_CODE_SIGNATURE
:
1056 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1057 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1059 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1060 segment_command
->filesize
= size
;
1061 segment_command
->vmsize
= Align(size
, PageSize_
);
1064 case LC_SEGMENT_64
: {
1065 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1066 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1068 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1069 segment_command
->filesize
= size
;
1070 segment_command
->vmsize
= Align(size
, PageSize_
);
1074 commands
.push_back(copy
);
1077 if (allocation
.alloc_
!= 0) {
1078 linkedit_data_command signature
;
1079 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1080 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1081 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1082 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1083 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1086 size_t begin(position
);
1089 _foreach(command
, commands
)
1090 after
+= command
.size();
1092 std::stringbuf altern
;
1094 struct mach_header
header(*mach_header
);
1095 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1096 header
.sizeofcmds
= mach_header
.Swap(after
);
1097 put(output
, &header
, sizeof(header
));
1098 put(altern
, &header
, sizeof(header
));
1099 position
+= sizeof(header
);
1101 if (mach_header
.Bits64()) {
1102 auto pad(mach_header
.Swap(uint32_t(0)));
1103 put(output
, &pad
, sizeof(pad
));
1104 put(altern
, &pad
, sizeof(pad
));
1105 position
+= sizeof(pad
);
1108 _foreach(command
, commands
) {
1109 put(output
, command
.data(), command
.size());
1110 put(altern
, command
.data(), command
.size());
1111 position
+= command
.size();
1114 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1115 if (before
> after
) {
1116 pad(output
, before
- after
);
1117 pad(altern
, before
- after
);
1118 position
+= before
- after
;
1121 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1123 std::string
overlap(altern
.str());
1124 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1126 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1127 position
= begin
+ allocation
.size_
;
1129 pad(output
, allocation
.limit_
- allocation
.size_
);
1130 position
+= allocation
.limit_
- allocation
.size_
;
1132 size_t saved(save(output
, allocation
.limit_
, overlap
, top
));
1133 if (allocation
.alloc_
> saved
)
1134 pad(output
, allocation
.alloc_
- saved
);
1135 position
+= allocation
.alloc_
;
1141 typedef std::map
<uint32_t, std::string
> Blobs
;
1143 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1144 auto value(buffer
.str());
1145 std::swap(blobs
[slot
], value
);
1148 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1149 auto value(buffer
.str());
1151 blob
.magic
= Swap(magic
);
1152 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1153 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1154 std::swap(blobs
[slot
], value
);
1157 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1159 _foreach (blob
, blobs
)
1160 total
+= blob
.second
.size();
1162 struct SuperBlob super
;
1163 super
.blob
.magic
= Swap(magic
);
1164 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1165 super
.count
= Swap(uint32_t(blobs
.size()));
1166 put(output
, &super
, sizeof(super
));
1168 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1170 _foreach (blob
, blobs
) {
1172 index
.type
= Swap(blob
.first
);
1173 index
.offset
= Swap(uint32_t(offset
));
1174 put(output
, &index
, sizeof(index
));
1175 offset
+= blob
.second
.size();
1178 _foreach (blob
, blobs
)
1179 put(output
, blob
.second
.data(), blob
.second
.size());
1192 _assert(bio_
!= NULL
);
1196 bio_(BIO_new(BIO_s_mem()))
1200 Buffer(const char *data
, size_t size
) :
1201 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1205 Buffer(const std::string
&data
) :
1206 Buffer(data
.data(), data
.size())
1210 Buffer(PKCS7
*pkcs
) :
1213 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1220 operator BIO
*() const {
1224 explicit operator std::string() const {
1226 auto size(BIO_get_mem_data(bio_
, &data
));
1227 return std::string(data
, size
);
1236 STACK_OF(X509
) *ca_
;
1240 value_(d2i_PKCS12_bio(bio
, NULL
)),
1243 _assert(value_
!= NULL
);
1244 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1245 _assert(key_
!= NULL
);
1246 _assert(cert_
!= NULL
);
1249 Stuff(const std::string
&data
) :
1255 sk_X509_pop_free(ca_
, X509_free
);
1257 EVP_PKEY_free(key_
);
1258 PKCS12_free(value_
);
1261 operator PKCS12
*() const {
1265 operator EVP_PKEY
*() const {
1269 operator X509
*() const {
1273 operator STACK_OF(X509
) *() const {
1283 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1284 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1286 _assert(value_
!= NULL
);
1293 operator PKCS7
*() const {
1300 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
) {
1301 Allocate(idata
, isize
, output
, fun([&](size_t size
) -> size_t {
1302 size_t alloc(sizeof(struct SuperBlob
));
1304 uint32_t special(0);
1306 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1307 alloc
+= sizeof(struct BlobIndex
);
1310 if (!entitlements
.empty()) {
1311 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1312 alloc
+= sizeof(struct BlobIndex
);
1313 alloc
+= sizeof(struct Blob
);
1314 alloc
+= entitlements
.size();
1317 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1318 alloc
+= sizeof(struct BlobIndex
);
1319 alloc
+= sizeof(struct Blob
);
1320 alloc
+= sizeof(struct CodeDirectory
);
1321 alloc
+= name
.size() + 1;
1324 alloc
+= sizeof(struct BlobIndex
);
1325 alloc
+= sizeof(struct Blob
);
1326 // XXX: this is just a "sufficiently large number"
1330 _foreach (slot
, slots
)
1331 special
= std::max(special
, slot
.first
);
1333 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1334 alloc
= Align(alloc
+ (special
+ normal
) * SHA_DIGEST_LENGTH
, 16);
1336 }), fun([&](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1340 std::stringbuf data
;
1343 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1345 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1348 if (!entitlements
.empty()) {
1349 std::stringbuf data
;
1350 put(data
, entitlements
.data(), entitlements
.size());
1351 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1355 std::stringbuf data
;
1357 uint32_t special(0);
1358 _foreach (blob
, blobs
)
1359 special
= std::max(special
, blob
.first
);
1360 _foreach (slot
, slots
)
1361 special
= std::max(special
, slot
.first
);
1362 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1364 CodeDirectory directory
;
1365 directory
.version
= Swap(uint32_t(0x00020001));
1366 directory
.flags
= Swap(uint32_t(0));
1367 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + name
.size() + 1 + SHA_DIGEST_LENGTH
* special
));
1368 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1369 directory
.nSpecialSlots
= Swap(special
);
1370 directory
.codeLimit
= Swap(uint32_t(limit
));
1371 directory
.nCodeSlots
= Swap(normal
);
1372 directory
.hashSize
= SHA_DIGEST_LENGTH
;
1373 directory
.hashType
= CS_HASHTYPE_SHA1
;
1374 directory
.spare1
= 0x00;
1375 directory
.pageSize
= PageShift_
;
1376 directory
.spare2
= Swap(uint32_t(0));
1377 put(data
, &directory
, sizeof(directory
));
1379 put(data
, name
.c_str(), name
.size() + 1);
1381 uint8_t storage
[special
+ normal
][SHA_DIGEST_LENGTH
];
1382 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = storage
+ special
;
1384 memset(storage
, 0, sizeof(*storage
) * special
);
1386 _foreach (blob
, blobs
) {
1387 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1388 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1391 _foreach (slot
, slots
) {
1392 _assert(sizeof(*hashes
) == slot
.second
.size());
1393 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1397 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1398 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1400 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1402 put(data
, storage
, sizeof(storage
));
1404 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1408 std::stringbuf data
;
1409 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1414 Signature
signature(stuff
, sign
);
1415 Buffer
result(signature
);
1416 std::string
value(result
);
1417 put(data
, value
.data(), value
.size());
1419 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1422 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1426 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1427 Allocate(idata
, isize
, output
, fun([](size_t size
) -> size_t {
1429 }), fun([](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1436 int main(int argc
, char *argv
[]) {
1437 OpenSSL_add_all_algorithms();
1444 little_
= endian
.byte
[0];
1459 uint32_t flag_CPUType(_not(uint32_t));
1460 uint32_t flag_CPUSubtype(_not(uint32_t));
1462 const char *flag_I(NULL
);
1471 std::vector
<std::string
> files
;
1474 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
1475 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
1476 fprintf(stderr
, " %s -S cat\n", argv
[0]);
1477 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
1481 for (int argi(1); argi
!= argc
; ++argi
)
1482 if (argv
[argi
][0] != '-')
1483 files
.push_back(argv
[argi
]);
1484 else switch (argv
[argi
][1]) {
1491 case 'e': flag_e
= true; break;
1494 const char *slot
= argv
[argi
] + 2;
1495 const char *colon
= strchr(slot
, ':');
1496 _assert(colon
!= NULL
);
1497 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1499 unsigned number(strtoul(slot
, &arge
, 0));
1500 _assert(arge
== colon
);
1501 std::string
&hash(slots
[number
]);
1502 hash
.resize(SHA_DIGEST_LENGTH
);
1503 sha1(reinterpret_cast<uint8_t *>(&hash
[0]), file
.data(), file
.size());
1506 case 'D': flag_D
= true; break;
1508 case 'a': flag_a
= true; break;
1513 if (argv
[argi
][2] != '\0') {
1514 const char *cpu
= argv
[argi
] + 2;
1515 const char *colon
= strchr(cpu
, ':');
1516 _assert(colon
!= NULL
);
1518 flag_CPUType
= strtoul(cpu
, &arge
, 0);
1519 _assert(arge
== colon
);
1520 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
1521 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
1535 if (argv
[argi
][2] != '\0') {
1536 const char *xml
= argv
[argi
] + 2;
1537 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1542 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1547 if (argv
[argi
][2] == '-')
1551 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
1552 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
1557 flag_I
= argv
[argi
] + 2;
1565 _assert(flag_S
|| key
.empty());
1566 _assert(flag_S
|| flag_I
== NULL
);
1568 if (files
.empty()) usage
: {
1572 size_t filei(0), filee(0);
1573 _foreach (file
, files
) try {
1574 const char *path(file
.c_str());
1576 if (flag_S
|| flag_r
) {
1577 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1580 const char *base
= strrchr(path
, '/');
1583 dir
.assign(path
, base
++ - path
+ 1);
1587 std::string
temp(dir
+ "." + base
+ ".cs");
1588 std::filebuf output
;
1589 _assert(output
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &output
);
1592 ldid::Unsign(input
.data(), input
.size(), output
);
1594 const char *name(flag_I
?: base
);
1595 ldid::Sign(input
.data(), input
.size(), output
, name
, entitlements
, key
, slots
);
1599 _syscall(stat(path
, &info
));
1601 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1603 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1604 _syscall(unlink(path
));
1605 _syscall(rename(temp
.c_str(), path
));
1608 Map
mapping(path
, flag_T
|| flag_s
);
1609 FatHeader
fat_header(mapping
.data(), mapping
.size());
1611 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
1612 struct linkedit_data_command
*signature(NULL
);
1613 struct encryption_info_command
*encryption(NULL
);
1616 if (mach_header
.GetCPUType() != flag_CPUType
)
1618 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
1623 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
1625 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1626 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1629 else if (cmd
== LC_CODE_SIGNATURE
)
1630 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1631 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
1632 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
1633 else if (cmd
== LC_ID_DYLIB
) {
1634 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
1642 dylib_command
->dylib
.timestamp
= 0;
1643 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
1646 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
1652 _assert(encryption
!= NULL
);
1653 encryption
->cryptid
= mach_header
.Swap(0);
1657 _assert(signature
!= NULL
);
1659 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
1661 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
1662 uint8_t *blob
= top
+ data
;
1663 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
1665 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1666 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1667 uint32_t begin
= Swap(super
->index
[index
].offset
);
1668 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
1669 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
1674 _assert(signature
!= NULL
);
1676 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
1678 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
1679 uint8_t *blob
= top
+ data
;
1680 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
1682 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1683 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
1684 uint32_t begin
= Swap(super
->index
[index
].offset
);
1685 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
1687 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
1688 uint32_t pages
= Swap(directory
->nCodeSlots
);
1691 for (size_t i
= 0; i
!= pages
- 1; ++i
)
1692 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
1694 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
1700 } catch (const char *) {