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 #define _assert_(expr, format, ...) \
57 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
58 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
61 #define _assert(expr) \
62 _assert_(expr, "%s", #expr)
64 #define _syscall(expr) ({ \
65 __typeof__(expr) _value; \
66 do if ((long) (_value = (expr)) != -1) \
68 else switch (errno) { \
72 _assert_(false, "errno=%u", errno); \
78 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
84 __attribute__((packed))
86 template <typename Type_
>
88 typedef typename
Type_::const_iterator Result
;
91 #define _foreach(item, list) \
92 for (bool _stop(true); _stop; ) \
93 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
94 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
95 for (bool _suck(true); _suck; _suck = false) \
96 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
103 #define FAT_MAGIC 0xcafebabe
104 #define FAT_CIGAM 0xbebafeca
124 #define MH_MAGIC 0xfeedface
125 #define MH_CIGAM 0xcefaedfe
127 #define MH_MAGIC_64 0xfeedfacf
128 #define MH_CIGAM_64 0xcffaedfe
130 #define MH_DYLDLINK 0x4
132 #define MH_OBJECT 0x1
133 #define MH_EXECUTE 0x2
135 #define MH_BUNDLE 0x8
136 #define MH_DYLIB_STUB 0x9
138 struct load_command
{
143 #define LC_REQ_DYLD uint32_t(0x80000000)
145 #define LC_SEGMENT uint32_t(0x01)
146 #define LC_SYMTAB uint32_t(0x02)
147 #define LC_DYSYMTAB uint32_t(0x0b)
148 #define LC_LOAD_DYLIB uint32_t(0x0c)
149 #define LC_ID_DYLIB uint32_t(0x0d)
150 #define LC_SEGMENT_64 uint32_t(0x19)
151 #define LC_UUID uint32_t(0x1b)
152 #define LC_CODE_SIGNATURE uint32_t(0x1d)
153 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
154 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
155 #define LC_ENCRYPTION_INFO uint32_t(0x21)
156 #define LC_DYLD_INFO uint32_t(0x22)
157 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
158 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
163 uint32_t current_version
;
164 uint32_t compatibility_version
;
167 struct dylib_command
{
173 struct uuid_command
{
179 struct symtab_command
{
188 struct dyld_info_command
{
192 uint32_t rebase_size
;
195 uint32_t weak_bind_off
;
196 uint32_t weak_bind_size
;
197 uint32_t lazy_bind_off
;
198 uint32_t lazy_bind_size
;
200 uint32_t export_size
;
203 struct dysymtab_command
{
216 uint32_t extrefsymoff
;
217 uint32_t nextrefsyms
;
218 uint32_t indirectsymoff
;
219 uint32_t nindirectsyms
;
226 struct dylib_table_of_contents
{
227 uint32_t symbol_index
;
228 uint32_t module_index
;
231 struct dylib_module
{
232 uint32_t module_name
;
241 uint32_t iinit_iterm
;
242 uint32_t ninit_nterm
;
243 uint32_t objc_module_info_addr
;
244 uint32_t objc_module_info_size
;
247 struct dylib_reference
{
252 struct relocation_info
{
254 uint32_t r_symbolnum
:24;
273 struct segment_command
{
287 struct segment_command_64
{
329 struct linkedit_data_command
{
336 struct encryption_info_command
{
344 #define BIND_OPCODE_MASK 0xf0
345 #define BIND_IMMEDIATE_MASK 0x0f
346 #define BIND_OPCODE_DONE 0x00
347 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
348 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
349 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
350 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
351 #define BIND_OPCODE_SET_TYPE_IMM 0x50
352 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
353 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
354 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
355 #define BIND_OPCODE_DO_BIND 0x90
356 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
357 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
358 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
360 inline void get(std::streambuf
&stream
, void *data
, size_t size
) {
361 _assert(stream
.sgetn(static_cast<char *>(data
), size
) == size
);
364 inline void put(std::streambuf
&stream
, const void *data
, size_t size
) {
365 _assert(stream
.sputn(static_cast<const char *>(data
), size
) == size
);
368 inline void pad(std::streambuf
&stream
, size_t size
) {
370 memset(padding
, 0, size
);
371 put(stream
, padding
, size
);
374 template <typename Type_
>
375 Type_
Align(Type_ value
, size_t align
) {
382 static const uint8_t PageShift_(0x0c);
383 static const uint32_t PageSize_(1 << PageShift_
);
385 static inline uint16_t Swap_(uint16_t value
) {
387 ((value
>> 8) & 0x00ff) |
388 ((value
<< 8) & 0xff00);
391 static inline uint32_t Swap_(uint32_t value
) {
392 value
= ((value
>> 8) & 0x00ff00ff) |
393 ((value
<< 8) & 0xff00ff00);
394 value
= ((value
>> 16) & 0x0000ffff) |
395 ((value
<< 16) & 0xffff0000);
399 static inline uint64_t Swap_(uint64_t value
) {
400 value
= (value
& 0x00000000ffffffff) << 32 | (value
& 0xffffffff00000000) >> 32;
401 value
= (value
& 0x0000ffff0000ffff) << 16 | (value
& 0xffff0000ffff0000) >> 16;
402 value
= (value
& 0x00ff00ff00ff00ff) << 8 | (value
& 0xff00ff00ff00ff00) >> 8;
406 static inline int16_t Swap_(int16_t value
) {
407 return Swap_(static_cast<uint16_t>(value
));
410 static inline int32_t Swap_(int32_t value
) {
411 return Swap_(static_cast<uint32_t>(value
));
414 static inline int64_t Swap_(int64_t value
) {
415 return Swap_(static_cast<uint64_t>(value
));
418 static bool little_(true);
420 static inline uint16_t Swap(uint16_t value
) {
421 return little_
? Swap_(value
) : value
;
424 static inline uint32_t Swap(uint32_t value
) {
425 return little_
? Swap_(value
) : value
;
428 static inline uint64_t Swap(uint64_t value
) {
429 return little_
? Swap_(value
) : value
;
432 static inline int16_t Swap(int16_t value
) {
433 return Swap(static_cast<uint16_t>(value
));
436 static inline int32_t Swap(int32_t value
) {
437 return Swap(static_cast<uint32_t>(value
));
440 static inline int64_t Swap(int64_t value
) {
441 return Swap(static_cast<uint64_t>(value
));
444 template <typename Target_
>
457 Swapped(bool swapped
) :
462 template <typename Type_
>
463 Type_
Swap(Type_ value
) const {
464 return swapped_
? Swap_(value
) : value
;
476 Data(void *base
, size_t size
) :
482 void *GetBase() const {
486 size_t GetSize() const {
497 struct mach_header
*mach_header_
;
498 struct load_command
*load_command_
;
501 MachHeader(void *base
, size_t size
) :
504 mach_header_
= (mach_header
*) base
;
506 switch (Swap(mach_header_
->magic
)) {
508 swapped_
= !swapped_
;
514 swapped_
= !swapped_
;
523 void *post
= mach_header_
+ 1;
525 post
= (uint32_t *) post
+ 1;
526 load_command_
= (struct load_command
*) post
;
529 Swap(mach_header_
->filetype
) == MH_EXECUTE
||
530 Swap(mach_header_
->filetype
) == MH_DYLIB
||
531 Swap(mach_header_
->filetype
) == MH_BUNDLE
535 bool Bits64() const {
539 struct mach_header
*operator ->() const {
543 operator struct mach_header
*() const {
547 uint32_t GetCPUType() const {
548 return Swap(mach_header_
->cputype
);
551 uint32_t GetCPUSubtype() const {
552 return Swap(mach_header_
->cpusubtype
) & 0xff;
555 struct load_command
*GetLoadCommand() const {
556 return load_command_
;
559 std::vector
<struct load_command
*> GetLoadCommands() const {
560 std::vector
<struct load_command
*> load_commands
;
562 struct load_command
*load_command
= load_command_
;
563 for (uint32_t cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
564 load_commands
.push_back(load_command
);
565 load_command
= (struct load_command
*) ((uint8_t *) load_command
+ Swap(load_command
->cmdsize
));
568 return load_commands
;
571 std::vector
<segment_command
*> GetSegments(const char *segment_name
) const {
572 std::vector
<struct segment_command
*> segment_commands
;
574 _foreach (load_command
, GetLoadCommands()) {
575 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
576 segment_command
*segment_command
= reinterpret_cast<struct segment_command
*>(load_command
);
577 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
578 segment_commands
.push_back(segment_command
);
582 return segment_commands
;
585 std::vector
<segment_command_64
*> GetSegments64(const char *segment_name
) const {
586 std::vector
<struct segment_command_64
*> segment_commands
;
588 _foreach (load_command
, GetLoadCommands()) {
589 if (Swap(load_command
->cmd
) == LC_SEGMENT_64
) {
590 segment_command_64
*segment_command
= reinterpret_cast<struct segment_command_64
*>(load_command
);
591 if (strncmp(segment_command
->segname
, segment_name
, 16) == 0)
592 segment_commands
.push_back(segment_command
);
596 return segment_commands
;
599 std::vector
<section
*> GetSections(const char *segment_name
, const char *section_name
) const {
600 std::vector
<section
*> sections
;
602 _foreach (segment
, GetSegments(segment_name
)) {
603 section
*section
= (struct section
*) (segment
+ 1);
606 for (sect
= 0; sect
!= Swap(segment
->nsects
); ++sect
) {
607 if (strncmp(section
->sectname
, section_name
, 16) == 0)
608 sections
.push_back(section
);
616 template <typename Target_
>
617 Pointer
<Target_
> GetPointer(uint32_t address
, const char *segment_name
= NULL
) const {
618 load_command
*load_command
= (struct load_command
*) (mach_header_
+ 1);
621 for (cmd
= 0; cmd
!= Swap(mach_header_
->ncmds
); ++cmd
) {
622 if (Swap(load_command
->cmd
) == LC_SEGMENT
) {
623 segment_command
*segment_command
= (struct segment_command
*) load_command
;
624 if (segment_name
!= NULL
&& strncmp(segment_command
->segname
, segment_name
, 16) != 0)
627 section
*sections
= (struct section
*) (segment_command
+ 1);
630 for (sect
= 0; sect
!= Swap(segment_command
->nsects
); ++sect
) {
631 section
*section
= §ions
[sect
];
632 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
633 if (address
>= Swap(section
->addr
) && address
< Swap(section
->addr
) + Swap(section
->size
)) {
634 //printf("0x%.8x %s\n", address, segment_command->segname);
635 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(address
- Swap(section
->addr
) + Swap(section
->offset
) + (char *) mach_header_
));
641 load_command
= (struct load_command
*) ((char *) load_command
+ Swap(load_command
->cmdsize
));
644 return Pointer
<Target_
>(this);
647 template <typename Target_
>
648 Pointer
<Target_
> GetOffset(uint32_t offset
) {
649 return Pointer
<Target_
>(this, reinterpret_cast<Target_
*>(offset
+ (uint8_t *) mach_header_
));
653 class FatMachHeader
:
660 FatMachHeader(void *base
, size_t size
, fat_arch
*fat_arch
) :
661 MachHeader(base
, size
),
666 fat_arch
*GetFatArch() const {
675 fat_header
*fat_header_
;
676 std::vector
<FatMachHeader
> mach_headers_
;
679 FatHeader(void *base
, size_t size
) :
682 fat_header_
= reinterpret_cast<struct fat_header
*>(base
);
684 if (Swap(fat_header_
->magic
) == FAT_CIGAM
) {
685 swapped_
= !swapped_
;
687 } else if (Swap(fat_header_
->magic
) != FAT_MAGIC
) {
689 mach_headers_
.push_back(FatMachHeader(base
, size
, NULL
));
691 size_t fat_narch
= Swap(fat_header_
->nfat_arch
);
692 fat_arch
*fat_arch
= reinterpret_cast<struct fat_arch
*>(fat_header_
+ 1);
694 for (arch
= 0; arch
!= fat_narch
; ++arch
) {
695 uint32_t arch_offset
= Swap(fat_arch
->offset
);
696 uint32_t arch_size
= Swap(fat_arch
->size
);
697 mach_headers_
.push_back(FatMachHeader((uint8_t *) base
+ arch_offset
, arch_size
, fat_arch
));
703 std::vector
<FatMachHeader
> &GetMachHeaders() {
704 return mach_headers_
;
708 return fat_header_
!= NULL
;
711 struct fat_header
*operator ->() const {
715 operator struct fat_header
*() const {
720 template <typename Target_
>
723 const MachHeader
*framework_
;
724 const Target_
*pointer_
;
727 Pointer(const MachHeader
*framework
= NULL
, const Target_
*pointer
= NULL
) :
728 framework_(framework
),
733 operator const Target_
*() const {
737 const Target_
*operator ->() const {
741 Pointer
<Target_
> &operator ++() {
746 template <typename Value_
>
747 Value_
Swap(Value_ value
) {
748 return framework_
->Swap(value
);
752 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
753 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
754 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
755 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
756 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
757 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
758 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
759 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
761 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
762 #define CSSLOT_INFOSLOT uint32_t(0x00001)
763 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
764 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
765 #define CSSLOT_APPLICATION uint32_t(0x00004)
766 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
768 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
770 #define CS_HASHTYPE_SHA1 1
785 struct BlobIndex index
[];
788 struct CodeDirectory
{
792 uint32_t identOffset
;
793 uint32_t nSpecialSlots
;
803 extern "C" uint32_t hash(uint8_t *k
, uint32_t length
, uint32_t initval
);
805 static void sha1(uint8_t *hash
, const void *data
, size_t size
) {
806 SHA1(static_cast<const uint8_t *>(data
), size
, hash
);
809 struct CodesignAllocation
{
810 FatMachHeader mach_header_
;
817 CodesignAllocation(FatMachHeader mach_header
, size_t offset
, size_t size
, size_t limit
, size_t alloc
, size_t align
) :
818 mach_header_(mach_header
),
840 _syscall(close(file_
));
843 void open(const char *path
, int flags
) {
844 _assert(file_
== -1);
845 file_
= _syscall(::open(path
, flags
));
862 _syscall(munmap(data_
, size_
));
874 Map(const char *path
, int oflag
, int pflag
, int mflag
) :
877 open(path
, oflag
, pflag
, mflag
);
880 Map(const char *path
, bool edit
) :
891 return data_
== NULL
;
894 void open(const char *path
, int oflag
, int pflag
, int mflag
) {
897 file_
.open(path
, oflag
);
898 int file(file_
.file());
901 _syscall(fstat(file
, &stat
));
902 size_
= stat
.st_size
;
904 data_
= _syscall(mmap(NULL
, size_
, pflag
, mflag
, file
, 0));
907 void open(const char *path
, bool edit
) {
909 open(path
, O_RDWR
, PROT_READ
| PROT_WRITE
, MAP_SHARED
);
911 open(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
918 size_t size() const {
922 operator std::string() const {
923 return std::string(static_cast<char *>(data_
), size_
);
929 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
) {
930 FatHeader
source(idata
, isize
);
934 offset
+= sizeof(fat_header
) + sizeof(fat_arch
) * source
.Swap(source
->nfat_arch
);
936 std::vector
<CodesignAllocation
> allocations
;
937 _foreach (mach_header
, source
.GetMachHeaders()) {
938 struct linkedit_data_command
*signature(NULL
);
939 struct symtab_command
*symtab(NULL
);
941 _foreach (load_command
, mach_header
.GetLoadCommands()) {
942 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
944 else if (cmd
== LC_CODE_SIGNATURE
)
945 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
946 else if (cmd
== LC_SYMTAB
)
947 symtab
= reinterpret_cast<struct symtab_command
*>(load_command
);
951 if (signature
== NULL
)
952 size
= mach_header
.GetSize();
954 size
= mach_header
.Swap(signature
->dataoff
);
955 _assert(size
<= mach_header
.GetSize());
958 if (symtab
!= NULL
) {
959 auto end(mach_header
.Swap(symtab
->stroff
) + mach_header
.Swap(symtab
->strsize
));
960 _assert(end
<= size
);
961 _assert(end
>= size
- 0x10);
965 size_t alloc(allocate(size
));
967 auto *fat_arch(mach_header
.GetFatArch());
968 uint32_t align(fat_arch
== NULL
? 0 : source
.Swap(fat_arch
->align
));
969 offset
= Align(offset
, 1 << align
);
971 uint32_t limit(size
);
973 limit
= Align(limit
, 0x10);
975 allocations
.push_back(CodesignAllocation(mach_header
, offset
, size
, limit
, alloc
, align
));
976 offset
+= size
+ alloc
;
977 offset
= Align(offset
, 0x10);
982 if (source
.IsFat()) {
983 fat_header fat_header
;
984 fat_header
.magic
= Swap(FAT_MAGIC
);
985 fat_header
.nfat_arch
= Swap(uint32_t(allocations
.size()));
986 put(output
, &fat_header
, sizeof(fat_header
));
987 position
+= sizeof(fat_header
);
989 _foreach (allocation
, allocations
) {
990 auto &mach_header(allocation
.mach_header_
);
993 fat_arch
.cputype
= Swap(mach_header
->cputype
);
994 fat_arch
.cpusubtype
= Swap(mach_header
->cpusubtype
);
995 fat_arch
.offset
= Swap(allocation
.offset_
);
996 fat_arch
.size
= Swap(allocation
.limit_
+ allocation
.alloc_
);
997 fat_arch
.align
= Swap(allocation
.align_
);
998 put(output
, &fat_arch
, sizeof(fat_arch
));
999 position
+= sizeof(fat_arch
);
1003 _foreach (allocation
, allocations
) {
1004 auto &mach_header(allocation
.mach_header_
);
1006 pad(output
, allocation
.offset_
- position
);
1007 position
= allocation
.offset_
;
1009 std::vector
<std::string
> commands
;
1011 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1012 std::string
copy(reinterpret_cast<const char *>(load_command
), load_command
->cmdsize
);
1014 switch (mach_header
.Swap(load_command
->cmd
)) {
1015 case LC_CODE_SIGNATURE
:
1020 auto segment_command(reinterpret_cast<struct segment_command
*>(©
[0]));
1021 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1023 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1024 segment_command
->filesize
= size
;
1025 segment_command
->vmsize
= Align(size
, PageSize_
);
1028 case LC_SEGMENT_64
: {
1029 auto segment_command(reinterpret_cast<struct segment_command_64
*>(©
[0]));
1030 if (strncmp(segment_command
->segname
, "__LINKEDIT", 16) != 0)
1032 size_t size(mach_header
.Swap(allocation
.limit_
+ allocation
.alloc_
- mach_header
.Swap(segment_command
->fileoff
)));
1033 segment_command
->filesize
= size
;
1034 segment_command
->vmsize
= Align(size
, PageSize_
);
1038 commands
.push_back(copy
);
1041 if (allocation
.alloc_
!= 0) {
1042 linkedit_data_command signature
;
1043 signature
.cmd
= mach_header
.Swap(LC_CODE_SIGNATURE
);
1044 signature
.cmdsize
= mach_header
.Swap(uint32_t(sizeof(signature
)));
1045 signature
.dataoff
= mach_header
.Swap(allocation
.limit_
);
1046 signature
.datasize
= mach_header
.Swap(allocation
.alloc_
);
1047 commands
.push_back(std::string(reinterpret_cast<const char *>(&signature
), sizeof(signature
)));
1050 size_t begin(position
);
1053 _foreach(command
, commands
)
1054 after
+= command
.size();
1056 std::stringbuf altern
;
1058 struct mach_header
header(*mach_header
);
1059 header
.ncmds
= mach_header
.Swap(uint32_t(commands
.size()));
1060 header
.sizeofcmds
= mach_header
.Swap(after
);
1061 put(output
, &header
, sizeof(header
));
1062 put(altern
, &header
, sizeof(header
));
1063 position
+= sizeof(header
);
1065 if (mach_header
.Bits64()) {
1066 auto pad(mach_header
.Swap(uint32_t(0)));
1067 put(output
, &pad
, sizeof(pad
));
1068 put(altern
, &pad
, sizeof(pad
));
1069 position
+= sizeof(pad
);
1072 _foreach(command
, commands
) {
1073 put(output
, command
.data(), command
.size());
1074 put(altern
, command
.data(), command
.size());
1075 position
+= command
.size();
1078 uint32_t before(mach_header
.Swap(mach_header
->sizeofcmds
));
1079 if (before
> after
) {
1080 pad(output
, before
- after
);
1081 pad(altern
, before
- after
);
1082 position
+= before
- after
;
1085 auto top(reinterpret_cast<char *>(mach_header
.GetBase()));
1087 std::string
overlap(altern
.str());
1088 overlap
.append(top
+ overlap
.size(), Align(overlap
.size(), 0x1000) - overlap
.size());
1090 put(output
, top
+ (position
- begin
), allocation
.size_
- (position
- begin
));
1091 position
= begin
+ allocation
.size_
;
1093 pad(output
, allocation
.limit_
- allocation
.size_
);
1094 position
+= allocation
.limit_
- allocation
.size_
;
1096 size_t saved(save(output
, allocation
.limit_
, overlap
, top
));
1097 if (allocation
.alloc_
> saved
)
1098 pad(output
, allocation
.alloc_
- saved
);
1099 position
+= allocation
.alloc_
;
1105 typedef std::map
<uint32_t, std::string
> Blobs
;
1107 static void insert(Blobs
&blobs
, uint32_t slot
, const std::stringbuf
&buffer
) {
1108 auto value(buffer
.str());
1109 std::swap(blobs
[slot
], value
);
1112 static void insert(Blobs
&blobs
, uint32_t slot
, uint32_t magic
, const std::stringbuf
&buffer
) {
1113 auto value(buffer
.str());
1115 blob
.magic
= Swap(magic
);
1116 blob
.length
= Swap(uint32_t(sizeof(blob
) + value
.size()));
1117 value
.insert(0, reinterpret_cast<char *>(&blob
), sizeof(blob
));
1118 std::swap(blobs
[slot
], value
);
1121 static size_t put(std::streambuf
&output
, uint32_t magic
, const Blobs
&blobs
) {
1123 _foreach (blob
, blobs
)
1124 total
+= blob
.second
.size();
1126 struct SuperBlob super
;
1127 super
.blob
.magic
= Swap(magic
);
1128 super
.blob
.length
= Swap(uint32_t(sizeof(SuperBlob
) + blobs
.size() * sizeof(BlobIndex
) + total
));
1129 super
.count
= Swap(uint32_t(blobs
.size()));
1130 put(output
, &super
, sizeof(super
));
1132 size_t offset(sizeof(SuperBlob
) + sizeof(BlobIndex
) * blobs
.size());
1134 _foreach (blob
, blobs
) {
1136 index
.type
= Swap(blob
.first
);
1137 index
.offset
= Swap(uint32_t(offset
));
1138 put(output
, &index
, sizeof(index
));
1139 offset
+= blob
.second
.size();
1142 _foreach (blob
, blobs
)
1143 put(output
, blob
.second
.data(), blob
.second
.size());
1156 _assert(bio_
!= NULL
);
1160 bio_(BIO_new(BIO_s_mem()))
1164 Buffer(const char *data
, size_t size
) :
1165 Buffer(BIO_new_mem_buf(const_cast<char *>(data
), size
))
1169 Buffer(const std::string
&data
) :
1170 Buffer(data
.data(), data
.size())
1174 Buffer(PKCS7
*pkcs
) :
1177 _assert(i2d_PKCS7_bio(bio_
, pkcs
) != 0);
1184 operator BIO
*() const {
1188 explicit operator std::string() const {
1190 auto size(BIO_get_mem_data(bio_
, &data
));
1191 return std::string(data
, size
);
1200 STACK_OF(X509
) *ca_
;
1204 value_(d2i_PKCS12_bio(bio
, NULL
)),
1207 _assert(value_
!= NULL
);
1208 _assert(PKCS12_parse(value_
, "", &key_
, &cert_
, &ca_
) != 0);
1209 _assert(key_
!= NULL
);
1210 _assert(cert_
!= NULL
);
1213 Stuff(const std::string
&data
) :
1219 sk_X509_pop_free(ca_
, X509_free
);
1221 EVP_PKEY_free(key_
);
1222 PKCS12_free(value_
);
1225 operator PKCS12
*() const {
1229 operator EVP_PKEY
*() const {
1233 operator X509
*() const {
1237 operator STACK_OF(X509
) *() const {
1247 Signature(const Stuff
&stuff
, const Buffer
&data
) :
1248 value_(PKCS7_sign(stuff
, stuff
, stuff
, data
, PKCS7_BINARY
| PKCS7_DETACHED
))
1250 _assert(value_
!= NULL
);
1257 operator PKCS7
*() const {
1264 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
) {
1265 Allocate(idata
, isize
, output
, fun([&](size_t size
) -> size_t {
1266 size_t alloc(sizeof(struct SuperBlob
));
1268 uint32_t special(0);
1270 special
= std::max(special
, CSSLOT_REQUIREMENTS
);
1271 alloc
+= sizeof(struct BlobIndex
);
1274 if (!entitlements
.empty()) {
1275 special
= std::max(special
, CSSLOT_ENTITLEMENTS
);
1276 alloc
+= sizeof(struct BlobIndex
);
1277 alloc
+= sizeof(struct Blob
);
1278 alloc
+= entitlements
.size();
1281 special
= std::max(special
, CSSLOT_CODEDIRECTORY
);
1282 alloc
+= sizeof(struct BlobIndex
);
1283 alloc
+= sizeof(struct Blob
);
1284 alloc
+= sizeof(struct CodeDirectory
);
1285 alloc
+= name
.size() + 1;
1288 alloc
+= sizeof(struct BlobIndex
);
1289 alloc
+= sizeof(struct Blob
);
1290 // XXX: this is just a "sufficiently large number"
1294 _foreach (slot
, slots
)
1295 special
= std::max(special
, slot
.first
);
1297 uint32_t normal((size
+ PageSize_
- 1) / PageSize_
);
1298 alloc
= Align(alloc
+ (special
+ normal
) * SHA_DIGEST_LENGTH
, 16);
1300 }), fun([&](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1304 std::stringbuf data
;
1307 put(data
, CSMAGIC_REQUIREMENTS
, requirements
);
1309 insert(blobs
, CSSLOT_REQUIREMENTS
, data
);
1312 if (!entitlements
.empty()) {
1313 std::stringbuf data
;
1314 put(data
, entitlements
.data(), entitlements
.size());
1315 insert(blobs
, CSSLOT_ENTITLEMENTS
, CSMAGIC_EMBEDDED_ENTITLEMENTS
, data
);
1319 std::stringbuf data
;
1321 uint32_t special(0);
1322 _foreach (blob
, blobs
)
1323 special
= std::max(special
, blob
.first
);
1324 _foreach (slot
, slots
)
1325 special
= std::max(special
, slot
.first
);
1326 uint32_t normal((limit
+ PageSize_
- 1) / PageSize_
);
1328 CodeDirectory directory
;
1329 directory
.version
= Swap(uint32_t(0x00020001));
1330 directory
.flags
= Swap(uint32_t(0));
1331 directory
.hashOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
) + name
.size() + 1 + SHA_DIGEST_LENGTH
* special
));
1332 directory
.identOffset
= Swap(uint32_t(sizeof(Blob
) + sizeof(CodeDirectory
)));
1333 directory
.nSpecialSlots
= Swap(special
);
1334 directory
.codeLimit
= Swap(uint32_t(limit
));
1335 directory
.nCodeSlots
= Swap(normal
);
1336 directory
.hashSize
= SHA_DIGEST_LENGTH
;
1337 directory
.hashType
= CS_HASHTYPE_SHA1
;
1338 directory
.spare1
= 0x00;
1339 directory
.pageSize
= PageShift_
;
1340 directory
.spare2
= Swap(uint32_t(0));
1341 put(data
, &directory
, sizeof(directory
));
1343 put(data
, name
.c_str(), name
.size() + 1);
1345 uint8_t storage
[special
+ normal
][SHA_DIGEST_LENGTH
];
1346 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = storage
+ special
;
1348 memset(storage
, 0, sizeof(*storage
) * special
);
1350 _foreach (blob
, blobs
) {
1351 auto local(reinterpret_cast<const Blob
*>(&blob
.second
[0]));
1352 sha1((uint8_t *) (hashes
- blob
.first
), local
, Swap(local
->length
));
1355 _foreach (slot
, slots
) {
1356 _assert(sizeof(*hashes
) == slot
.second
.size());
1357 memcpy(hashes
- slot
.first
, slot
.second
.data(), slot
.second
.size());
1361 for (size_t i
= 0; i
!= normal
- 1; ++i
)
1362 sha1(hashes
[i
], (PageSize_
* i
< overlap
.size() ? overlap
.data() : top
) + PageSize_
* i
, PageSize_
);
1364 sha1(hashes
[normal
- 1], top
+ PageSize_
* (normal
- 1), ((limit
- 1) % PageSize_
) + 1);
1366 put(data
, storage
, sizeof(storage
));
1368 insert(blobs
, CSSLOT_CODEDIRECTORY
, CSMAGIC_CODEDIRECTORY
, data
);
1372 std::stringbuf data
;
1373 const std::string
&sign(blobs
[CSSLOT_CODEDIRECTORY
]);
1378 Signature
signature(stuff
, sign
);
1379 Buffer
result(signature
);
1380 std::string
value(result
);
1381 put(data
, value
.data(), value
.size());
1383 insert(blobs
, CSSLOT_SIGNATURESLOT
, CSMAGIC_BLOBWRAPPER
, data
);
1386 return put(output
, CSMAGIC_EMBEDDED_SIGNATURE
, blobs
);
1390 static void Unsign(void *idata
, size_t isize
, std::streambuf
&output
) {
1391 Allocate(idata
, isize
, output
, fun([](size_t size
) -> size_t {
1393 }), fun([](std::streambuf
&output
, size_t limit
, const std::string
&overlap
, const char *top
) -> size_t {
1400 int main(int argc
, char *argv
[]) {
1401 OpenSSL_add_all_algorithms();
1408 little_
= endian
.byte
[0];
1423 uint32_t flag_CPUType(_not(uint32_t));
1424 uint32_t flag_CPUSubtype(_not(uint32_t));
1426 const char *flag_I(NULL
);
1435 std::vector
<std::string
> files
;
1438 fprintf(stderr
, "usage: %s -S[entitlements.xml] <binary>\n", argv
[0]);
1439 fprintf(stderr
, " %s -e MobileSafari\n", argv
[0]);
1440 fprintf(stderr
, " %s -S cat\n", argv
[0]);
1441 fprintf(stderr
, " %s -Stfp.xml gdb\n", argv
[0]);
1445 for (int argi(1); argi
!= argc
; ++argi
)
1446 if (argv
[argi
][0] != '-')
1447 files
.push_back(argv
[argi
]);
1448 else switch (argv
[argi
][1]) {
1455 case 'e': flag_e
= true; break;
1458 const char *slot
= argv
[argi
] + 2;
1459 const char *colon
= strchr(slot
, ':');
1460 _assert(colon
!= NULL
);
1461 Map
file(colon
+ 1, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1463 unsigned number(strtoul(slot
, &arge
, 0));
1464 _assert(arge
== colon
);
1465 std::string
&hash(slots
[number
]);
1466 hash
.resize(SHA_DIGEST_LENGTH
);
1467 sha1(reinterpret_cast<uint8_t *>(&hash
[0]), file
.data(), file
.size());
1470 case 'D': flag_D
= true; break;
1472 case 'a': flag_a
= true; break;
1477 if (argv
[argi
][2] != '\0') {
1478 const char *cpu
= argv
[argi
] + 2;
1479 const char *colon
= strchr(cpu
, ':');
1480 _assert(colon
!= NULL
);
1482 flag_CPUType
= strtoul(cpu
, &arge
, 0);
1483 _assert(arge
== colon
);
1484 flag_CPUSubtype
= strtoul(colon
+ 1, &arge
, 0);
1485 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
1499 if (argv
[argi
][2] != '\0') {
1500 const char *xml
= argv
[argi
] + 2;
1501 entitlements
.open(xml
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1506 key
.open(argv
[argi
] + 2, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1511 if (argv
[argi
][2] == '-')
1515 timev
= strtoul(argv
[argi
] + 2, &arge
, 0);
1516 _assert(arge
== argv
[argi
] + strlen(argv
[argi
]));
1521 flag_I
= argv
[argi
] + 2;
1529 _assert(flag_S
|| key
.empty());
1530 _assert(flag_S
|| flag_I
== NULL
);
1532 if (files
.empty()) usage
: {
1536 size_t filei(0), filee(0);
1537 _foreach (file
, files
) try {
1538 const char *path(file
.c_str());
1540 if (flag_S
|| flag_r
) {
1541 Map
input(path
, O_RDONLY
, PROT_READ
, MAP_PRIVATE
);
1544 const char *base
= strrchr(path
, '/');
1547 dir
.assign(path
, base
++ - path
+ 1);
1551 std::string
temp(dir
+ "." + base
+ ".cs");
1552 std::filebuf output
;
1553 _assert(output
.open(temp
.c_str(), std::ios::out
| std::ios::trunc
| std::ios::binary
) == &output
);
1556 ldid::Unsign(input
.data(), input
.size(), output
);
1558 const char *name(flag_I
?: base
);
1559 ldid::Sign(input
.data(), input
.size(), output
, name
, entitlements
, key
, slots
);
1563 _syscall(stat(path
, &info
));
1565 _syscall(chown(temp
.c_str(), info
.st_uid
, info
.st_gid
));
1567 _syscall(chmod(temp
.c_str(), info
.st_mode
));
1568 _syscall(unlink(path
));
1569 _syscall(rename(temp
.c_str(), path
));
1572 Map
mapping(path
, flag_T
|| flag_s
);
1573 FatHeader
fat_header(mapping
.data(), mapping
.size());
1575 _foreach (mach_header
, fat_header
.GetMachHeaders()) {
1576 struct linkedit_data_command
*signature(NULL
);
1577 struct encryption_info_command
*encryption(NULL
);
1580 if (mach_header
.GetCPUType() != flag_CPUType
)
1582 if (mach_header
.GetCPUSubtype() != flag_CPUSubtype
)
1587 printf("cpu=0x%x:0x%x\n", mach_header
.GetCPUType(), mach_header
.GetCPUSubtype());
1589 _foreach (load_command
, mach_header
.GetLoadCommands()) {
1590 uint32_t cmd(mach_header
.Swap(load_command
->cmd
));
1593 else if (cmd
== LC_CODE_SIGNATURE
)
1594 signature
= reinterpret_cast<struct linkedit_data_command
*>(load_command
);
1595 else if (cmd
== LC_ENCRYPTION_INFO
|| cmd
== LC_ENCRYPTION_INFO_64
)
1596 encryption
= reinterpret_cast<struct encryption_info_command
*>(load_command
);
1597 else if (cmd
== LC_ID_DYLIB
) {
1598 volatile struct dylib_command
*dylib_command(reinterpret_cast<struct dylib_command
*>(load_command
));
1606 dylib_command
->dylib
.timestamp
= 0;
1607 timed
= hash(reinterpret_cast<uint8_t *>(mach_header
.GetBase()), mach_header
.GetSize(), timev
);
1610 dylib_command
->dylib
.timestamp
= mach_header
.Swap(timed
);
1616 _assert(encryption
!= NULL
);
1617 encryption
->cryptid
= mach_header
.Swap(0);
1621 _assert(signature
!= NULL
);
1623 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
1625 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
1626 uint8_t *blob
= top
+ data
;
1627 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
1629 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1630 if (Swap(super
->index
[index
].type
) == CSSLOT_ENTITLEMENTS
) {
1631 uint32_t begin
= Swap(super
->index
[index
].offset
);
1632 struct Blob
*entitlements
= reinterpret_cast<struct Blob
*>(blob
+ begin
);
1633 fwrite(entitlements
+ 1, 1, Swap(entitlements
->length
) - sizeof(*entitlements
), stdout
);
1638 _assert(signature
!= NULL
);
1640 uint32_t data
= mach_header
.Swap(signature
->dataoff
);
1642 uint8_t *top
= reinterpret_cast<uint8_t *>(mach_header
.GetBase());
1643 uint8_t *blob
= top
+ data
;
1644 struct SuperBlob
*super
= reinterpret_cast<struct SuperBlob
*>(blob
);
1646 for (size_t index(0); index
!= Swap(super
->count
); ++index
)
1647 if (Swap(super
->index
[index
].type
) == CSSLOT_CODEDIRECTORY
) {
1648 uint32_t begin
= Swap(super
->index
[index
].offset
);
1649 struct CodeDirectory
*directory
= reinterpret_cast<struct CodeDirectory
*>(blob
+ begin
);
1651 uint8_t (*hashes
)[SHA_DIGEST_LENGTH
] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH
]>(blob
+ begin
+ Swap(directory
->hashOffset
));
1652 uint32_t pages
= Swap(directory
->nCodeSlots
);
1655 for (size_t i
= 0; i
!= pages
- 1; ++i
)
1656 sha1(hashes
[i
], top
+ PageSize_
* i
, PageSize_
);
1658 sha1(hashes
[pages
- 1], top
+ PageSize_
* (pages
- 1), ((data
- 1) % PageSize_
) + 1);
1664 } catch (const char *) {