]> git.saurik.com Git - ldid.git/blob - ldid.cpp
922515826a25fe974e4ae8a200a50b7d7a73f07e
[ldid.git] / ldid.cpp
1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
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.
11
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.
16
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/>.
19 **/
20 /* }}} */
21
22 #include <cstdio>
23 #include <cstdlib>
24 #include <cstring>
25 #include <fstream>
26 #include <map>
27 #include <sstream>
28 #include <string>
29 #include <vector>
30
31 #include <dlfcn.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <stdbool.h>
35 #include <stdint.h>
36
37 #include <sys/mman.h>
38 #include <sys/stat.h>
39
40 #include <openssl/sha.h>
41
42 #include <plist/plist.h>
43
44 #define _assert___(line) \
45 #line
46 #define _assert__(line) \
47 _assert___(line)
48 #define _assert_(e) \
49 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" e ")"
50
51 #define _assert(expr) \
52 do if (!(expr)) { \
53 fprintf(stderr, "%s(%u): _assert(%s); errno=%u\n", __FILE__, __LINE__, #expr, errno); \
54 _assert_(#expr); \
55 } while (false)
56
57 #define _syscall(expr) ({ \
58 __typeof__(expr) _value; \
59 do if ((long) (_value = (expr)) != -1) \
60 break; \
61 else switch (errno) { \
62 case EINTR: \
63 continue; \
64 default: \
65 _assert(false); \
66 } while (true); \
67 _value; \
68 })
69
70 #define _trace() \
71 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
72
73 #define _not(type) \
74 ((type) ~ (type) 0)
75
76 #define _packed \
77 __attribute__((packed))
78
79 template <typename Type_>
80 struct Iterator_ {
81 typedef typename Type_::const_iterator Result;
82 };
83
84 #define _foreach(item, list) \
85 for (bool _stop(true); _stop; ) \
86 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
87 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
88 for (bool _suck(true); _suck; _suck = false) \
89 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
90
91 struct fat_header {
92 uint32_t magic;
93 uint32_t nfat_arch;
94 } _packed;
95
96 #define FAT_MAGIC 0xcafebabe
97 #define FAT_CIGAM 0xbebafeca
98
99 struct fat_arch {
100 uint32_t cputype;
101 uint32_t cpusubtype;
102 uint32_t offset;
103 uint32_t size;
104 uint32_t align;
105 } _packed;
106
107 struct mach_header {
108 uint32_t magic;
109 uint32_t cputype;
110 uint32_t cpusubtype;
111 uint32_t filetype;
112 uint32_t ncmds;
113 uint32_t sizeofcmds;
114 uint32_t flags;
115 } _packed;
116
117 #define MH_MAGIC 0xfeedface
118 #define MH_CIGAM 0xcefaedfe
119
120 #define MH_MAGIC_64 0xfeedfacf
121 #define MH_CIGAM_64 0xcffaedfe
122
123 #define MH_DYLDLINK 0x4
124
125 #define MH_OBJECT 0x1
126 #define MH_EXECUTE 0x2
127 #define MH_DYLIB 0x6
128 #define MH_BUNDLE 0x8
129 #define MH_DYLIB_STUB 0x9
130
131 struct load_command {
132 uint32_t cmd;
133 uint32_t cmdsize;
134 } _packed;
135
136 #define LC_REQ_DYLD uint32_t(0x80000000)
137
138 #define LC_SEGMENT uint32_t(0x01)
139 #define LC_SYMTAB uint32_t(0x02)
140 #define LC_DYSYMTAB uint32_t(0x0b)
141 #define LC_LOAD_DYLIB uint32_t(0x0c)
142 #define LC_ID_DYLIB uint32_t(0x0d)
143 #define LC_SEGMENT_64 uint32_t(0x19)
144 #define LC_UUID uint32_t(0x1b)
145 #define LC_CODE_SIGNATURE uint32_t(0x1d)
146 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
147 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
148 #define LC_ENCRYPTION_INFO uint32_t(0x21)
149 #define LC_DYLD_INFO uint32_t(0x22)
150 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
151 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
152
153 struct dylib {
154 uint32_t name;
155 uint32_t timestamp;
156 uint32_t current_version;
157 uint32_t compatibility_version;
158 } _packed;
159
160 struct dylib_command {
161 uint32_t cmd;
162 uint32_t cmdsize;
163 struct dylib dylib;
164 } _packed;
165
166 struct uuid_command {
167 uint32_t cmd;
168 uint32_t cmdsize;
169 uint8_t uuid[16];
170 } _packed;
171
172 struct symtab_command {
173 uint32_t cmd;
174 uint32_t cmdsize;
175 uint32_t symoff;
176 uint32_t nsyms;
177 uint32_t stroff;
178 uint32_t strsize;
179 } _packed;
180
181 struct dyld_info_command {
182 uint32_t cmd;
183 uint32_t cmdsize;
184 uint32_t rebase_off;
185 uint32_t rebase_size;
186 uint32_t bind_off;
187 uint32_t bind_size;
188 uint32_t weak_bind_off;
189 uint32_t weak_bind_size;
190 uint32_t lazy_bind_off;
191 uint32_t lazy_bind_size;
192 uint32_t export_off;
193 uint32_t export_size;
194 } _packed;
195
196 struct dysymtab_command {
197 uint32_t cmd;
198 uint32_t cmdsize;
199 uint32_t ilocalsym;
200 uint32_t nlocalsym;
201 uint32_t iextdefsym;
202 uint32_t nextdefsym;
203 uint32_t iundefsym;
204 uint32_t nundefsym;
205 uint32_t tocoff;
206 uint32_t ntoc;
207 uint32_t modtaboff;
208 uint32_t nmodtab;
209 uint32_t extrefsymoff;
210 uint32_t nextrefsyms;
211 uint32_t indirectsymoff;
212 uint32_t nindirectsyms;
213 uint32_t extreloff;
214 uint32_t nextrel;
215 uint32_t locreloff;
216 uint32_t nlocrel;
217 } _packed;
218
219 struct dylib_table_of_contents {
220 uint32_t symbol_index;
221 uint32_t module_index;
222 } _packed;
223
224 struct dylib_module {
225 uint32_t module_name;
226 uint32_t iextdefsym;
227 uint32_t nextdefsym;
228 uint32_t irefsym;
229 uint32_t nrefsym;
230 uint32_t ilocalsym;
231 uint32_t nlocalsym;
232 uint32_t iextrel;
233 uint32_t nextrel;
234 uint32_t iinit_iterm;
235 uint32_t ninit_nterm;
236 uint32_t objc_module_info_addr;
237 uint32_t objc_module_info_size;
238 } _packed;
239
240 struct dylib_reference {
241 uint32_t isym:24;
242 uint32_t flags:8;
243 } _packed;
244
245 struct relocation_info {
246 int32_t r_address;
247 uint32_t r_symbolnum:24;
248 uint32_t r_pcrel:1;
249 uint32_t r_length:2;
250 uint32_t r_extern:1;
251 uint32_t r_type:4;
252 } _packed;
253
254 struct nlist {
255 union {
256 char *n_name;
257 int32_t n_strx;
258 } n_un;
259
260 uint8_t n_type;
261 uint8_t n_sect;
262 uint8_t n_desc;
263 uint32_t n_value;
264 } _packed;
265
266 struct segment_command {
267 uint32_t cmd;
268 uint32_t cmdsize;
269 char segname[16];
270 uint32_t vmaddr;
271 uint32_t vmsize;
272 uint32_t fileoff;
273 uint32_t filesize;
274 uint32_t maxprot;
275 uint32_t initprot;
276 uint32_t nsects;
277 uint32_t flags;
278 } _packed;
279
280 struct segment_command_64 {
281 uint32_t cmd;
282 uint32_t cmdsize;
283 char segname[16];
284 uint64_t vmaddr;
285 uint64_t vmsize;
286 uint64_t fileoff;
287 uint64_t filesize;
288 uint32_t maxprot;
289 uint32_t initprot;
290 uint32_t nsects;
291 uint32_t flags;
292 } _packed;
293
294 struct section {
295 char sectname[16];
296 char segname[16];
297 uint32_t addr;
298 uint32_t size;
299 uint32_t offset;
300 uint32_t align;
301 uint32_t reloff;
302 uint32_t nreloc;
303 uint32_t flags;
304 uint32_t reserved1;
305 uint32_t reserved2;
306 } _packed;
307
308 struct section_64 {
309 char sectname[16];
310 char segname[16];
311 uint64_t addr;
312 uint64_t size;
313 uint32_t offset;
314 uint32_t align;
315 uint32_t reloff;
316 uint32_t nreloc;
317 uint32_t flags;
318 uint32_t reserved1;
319 uint32_t reserved2;
320 } _packed;
321
322 struct linkedit_data_command {
323 uint32_t cmd;
324 uint32_t cmdsize;
325 uint32_t dataoff;
326 uint32_t datasize;
327 } _packed;
328
329 struct encryption_info_command {
330 uint32_t cmd;
331 uint32_t cmdsize;
332 uint32_t cryptoff;
333 uint32_t cryptsize;
334 uint32_t cryptid;
335 } _packed;
336
337 #define BIND_OPCODE_MASK 0xf0
338 #define BIND_IMMEDIATE_MASK 0x0f
339 #define BIND_OPCODE_DONE 0x00
340 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
341 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
342 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
343 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
344 #define BIND_OPCODE_SET_TYPE_IMM 0x50
345 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
346 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
347 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
348 #define BIND_OPCODE_DO_BIND 0x90
349 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
350 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
351 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
352
353 inline void get(std::streambuf &stream, void *data, size_t size) {
354 _assert(stream.sgetn(static_cast<char *>(data), size) == size);
355 }
356
357 inline void put(std::streambuf &stream, const void *data, size_t size) {
358 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
359 }
360
361 inline void pad(std::streambuf &stream, size_t size) {
362 char padding[size];
363 memset(padding, 0, size);
364 put(stream, padding, size);
365 }
366
367 template <typename Type_>
368 Type_ Align(Type_ value, size_t align) {
369 value += align - 1;
370 value /= align;
371 value *= align;
372 return value;
373 }
374
375 uint16_t Swap_(uint16_t value) {
376 return
377 ((value >> 8) & 0x00ff) |
378 ((value << 8) & 0xff00);
379 }
380
381 uint32_t Swap_(uint32_t value) {
382 value = ((value >> 8) & 0x00ff00ff) |
383 ((value << 8) & 0xff00ff00);
384 value = ((value >> 16) & 0x0000ffff) |
385 ((value << 16) & 0xffff0000);
386 return value;
387 }
388
389 uint64_t Swap_(uint64_t value) {
390 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
391 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
392 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
393 return value;
394 }
395
396 int16_t Swap_(int16_t value) {
397 return Swap_(static_cast<uint16_t>(value));
398 }
399
400 int32_t Swap_(int32_t value) {
401 return Swap_(static_cast<uint32_t>(value));
402 }
403
404 int64_t Swap_(int64_t value) {
405 return Swap_(static_cast<uint64_t>(value));
406 }
407
408 bool little_(true);
409
410 uint16_t Swap(uint16_t value) {
411 return little_ ? Swap_(value) : value;
412 }
413
414 uint32_t Swap(uint32_t value) {
415 return little_ ? Swap_(value) : value;
416 }
417
418 uint64_t Swap(uint64_t value) {
419 return little_ ? Swap_(value) : value;
420 }
421
422 int16_t Swap(int16_t value) {
423 return Swap(static_cast<uint16_t>(value));
424 }
425
426 int32_t Swap(int32_t value) {
427 return Swap(static_cast<uint32_t>(value));
428 }
429
430 int64_t Swap(int64_t value) {
431 return Swap(static_cast<uint64_t>(value));
432 }
433
434 template <typename Target_>
435 class Pointer;
436
437 class Swapped {
438 protected:
439 bool swapped_;
440
441 Swapped() :
442 swapped_(false)
443 {
444 }
445
446 public:
447 Swapped(bool swapped) :
448 swapped_(swapped)
449 {
450 }
451
452 template <typename Type_>
453 Type_ Swap(Type_ value) const {
454 return swapped_ ? Swap_(value) : value;
455 }
456 };
457
458 class Data :
459 public Swapped
460 {
461 private:
462 void *base_;
463 size_t size_;
464
465 public:
466 Data(void *base, size_t size) :
467 base_(base),
468 size_(size)
469 {
470 }
471
472 void *GetBase() const {
473 return base_;
474 }
475
476 size_t GetSize() const {
477 return size_;
478 }
479 };
480
481 class MachHeader :
482 public Data
483 {
484 private:
485 bool bits64_;
486
487 struct mach_header *mach_header_;
488 struct load_command *load_command_;
489
490 public:
491 MachHeader(void *base, size_t size) :
492 Data(base, size)
493 {
494 mach_header_ = (mach_header *) base;
495
496 switch (Swap(mach_header_->magic)) {
497 case MH_CIGAM:
498 swapped_ = !swapped_;
499 case MH_MAGIC:
500 bits64_ = false;
501 break;
502
503 case MH_CIGAM_64:
504 swapped_ = !swapped_;
505 case MH_MAGIC_64:
506 bits64_ = true;
507 break;
508
509 default:
510 _assert(false);
511 }
512
513 void *post = mach_header_ + 1;
514 if (bits64_)
515 post = (uint32_t *) post + 1;
516 load_command_ = (struct load_command *) post;
517
518 _assert(
519 Swap(mach_header_->filetype) == MH_EXECUTE ||
520 Swap(mach_header_->filetype) == MH_DYLIB ||
521 Swap(mach_header_->filetype) == MH_BUNDLE
522 );
523 }
524
525 bool Bits64() const {
526 return bits64_;
527 }
528
529 struct mach_header *operator ->() const {
530 return mach_header_;
531 }
532
533 operator struct mach_header *() const {
534 return mach_header_;
535 }
536
537 uint32_t GetCPUType() const {
538 return Swap(mach_header_->cputype);
539 }
540
541 uint32_t GetCPUSubtype() const {
542 return Swap(mach_header_->cpusubtype) & 0xff;
543 }
544
545 struct load_command *GetLoadCommand() const {
546 return load_command_;
547 }
548
549 std::vector<struct load_command *> GetLoadCommands() const {
550 std::vector<struct load_command *> load_commands;
551
552 struct load_command *load_command = load_command_;
553 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
554 load_commands.push_back(load_command);
555 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
556 }
557
558 return load_commands;
559 }
560
561 std::vector<segment_command *> GetSegments(const char *segment_name) const {
562 std::vector<struct segment_command *> segment_commands;
563
564 _foreach (load_command, GetLoadCommands()) {
565 if (Swap(load_command->cmd) == LC_SEGMENT) {
566 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
567 if (strncmp(segment_command->segname, segment_name, 16) == 0)
568 segment_commands.push_back(segment_command);
569 }
570 }
571
572 return segment_commands;
573 }
574
575 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) const {
576 std::vector<struct segment_command_64 *> segment_commands;
577
578 _foreach (load_command, GetLoadCommands()) {
579 if (Swap(load_command->cmd) == LC_SEGMENT_64) {
580 segment_command_64 *segment_command = reinterpret_cast<struct segment_command_64 *>(load_command);
581 if (strncmp(segment_command->segname, segment_name, 16) == 0)
582 segment_commands.push_back(segment_command);
583 }
584 }
585
586 return segment_commands;
587 }
588
589 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
590 std::vector<section *> sections;
591
592 _foreach (segment, GetSegments(segment_name)) {
593 section *section = (struct section *) (segment + 1);
594
595 uint32_t sect;
596 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
597 if (strncmp(section->sectname, section_name, 16) == 0)
598 sections.push_back(section);
599 ++section;
600 }
601 }
602
603 return sections;
604 }
605
606 template <typename Target_>
607 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
608 load_command *load_command = (struct load_command *) (mach_header_ + 1);
609 uint32_t cmd;
610
611 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
612 if (Swap(load_command->cmd) == LC_SEGMENT) {
613 segment_command *segment_command = (struct segment_command *) load_command;
614 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
615 goto next_command;
616
617 section *sections = (struct section *) (segment_command + 1);
618
619 uint32_t sect;
620 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
621 section *section = &sections[sect];
622 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
623 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
624 //printf("0x%.8x %s\n", address, segment_command->segname);
625 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
626 }
627 }
628 }
629
630 next_command:
631 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
632 }
633
634 return Pointer<Target_>(this);
635 }
636
637 template <typename Target_>
638 Pointer<Target_> GetOffset(uint32_t offset) {
639 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
640 }
641 };
642
643 class FatMachHeader :
644 public MachHeader
645 {
646 private:
647 fat_arch *fat_arch_;
648
649 public:
650 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
651 MachHeader(base, size),
652 fat_arch_(fat_arch)
653 {
654 }
655
656 fat_arch *GetFatArch() const {
657 return fat_arch_;
658 }
659 };
660
661 class FatHeader :
662 public Data
663 {
664 private:
665 fat_header *fat_header_;
666 std::vector<FatMachHeader> mach_headers_;
667
668 public:
669 FatHeader(void *base, size_t size) :
670 Data(base, size)
671 {
672 fat_header_ = reinterpret_cast<struct fat_header *>(base);
673
674 if (Swap(fat_header_->magic) == FAT_CIGAM) {
675 swapped_ = !swapped_;
676 goto fat;
677 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
678 fat_header_ = NULL;
679 mach_headers_.push_back(FatMachHeader(base, size, NULL));
680 } else fat: {
681 size_t fat_narch = Swap(fat_header_->nfat_arch);
682 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
683 size_t arch;
684 for (arch = 0; arch != fat_narch; ++arch) {
685 uint32_t arch_offset = Swap(fat_arch->offset);
686 uint32_t arch_size = Swap(fat_arch->size);
687 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
688 ++fat_arch;
689 }
690 }
691 }
692
693 std::vector<FatMachHeader> &GetMachHeaders() {
694 return mach_headers_;
695 }
696
697 bool IsFat() const {
698 return fat_header_ != NULL;
699 }
700
701 struct fat_header *operator ->() const {
702 return fat_header_;
703 }
704
705 operator struct fat_header *() const {
706 return fat_header_;
707 }
708 };
709
710 template <typename Target_>
711 class Pointer {
712 private:
713 const MachHeader *framework_;
714 const Target_ *pointer_;
715
716 public:
717 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
718 framework_(framework),
719 pointer_(pointer)
720 {
721 }
722
723 operator const Target_ *() const {
724 return pointer_;
725 }
726
727 const Target_ *operator ->() const {
728 return pointer_;
729 }
730
731 Pointer<Target_> &operator ++() {
732 ++pointer_;
733 return *this;
734 }
735
736 template <typename Value_>
737 Value_ Swap(Value_ value) {
738 return framework_->Swap(value);
739 }
740 };
741
742 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
743 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
744 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
745 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
746 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
747 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
748 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
749 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
750
751 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
752 #define CSSLOT_INFOSLOT uint32_t(0x00001)
753 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
754 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
755 #define CSSLOT_APPLICATION uint32_t(0x00004)
756 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
757
758 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
759
760 #define CS_HASHTYPE_SHA1 1
761
762 struct BlobIndex {
763 uint32_t type;
764 uint32_t offset;
765 } _packed;
766
767 struct Blob {
768 uint32_t magic;
769 uint32_t length;
770 } _packed;
771
772 struct SuperBlob {
773 struct Blob blob;
774 uint32_t count;
775 struct BlobIndex index[];
776 } _packed;
777
778 struct CodeDirectory {
779 uint32_t version;
780 uint32_t flags;
781 uint32_t hashOffset;
782 uint32_t identOffset;
783 uint32_t nSpecialSlots;
784 uint32_t nCodeSlots;
785 uint32_t codeLimit;
786 uint8_t hashSize;
787 uint8_t hashType;
788 uint8_t spare1;
789 uint8_t pageSize;
790 uint32_t spare2;
791 } _packed;
792
793 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
794
795 void sha1(uint8_t *hash, const void *data, size_t size) {
796 SHA1(static_cast<const uint8_t *>(data), size, hash);
797 }
798
799 struct CodesignAllocation {
800 FatMachHeader mach_header_;
801 uint32_t offset_;
802 uint32_t size_;
803 uint32_t limit_;
804 uint32_t alloc_;
805 uint32_t special_;
806 uint32_t align_;
807
808 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t special, size_t align) :
809 mach_header_(mach_header),
810 offset_(offset),
811 size_(size),
812 limit_(limit),
813 alloc_(alloc),
814 special_(special),
815 align_(align)
816 {
817 }
818 };
819
820 class File {
821 private:
822 int file_;
823
824 public:
825 File() :
826 file_(-1)
827 {
828 }
829
830 ~File() {
831 if (file_ != -1)
832 _syscall(close(file_));
833 }
834
835 void open(const char *path, int flags) {
836 _assert(file_ == -1);
837 _syscall(file_ = ::open(path, flags));
838 }
839
840 int file() const {
841 return file_;
842 }
843 };
844
845 class Map {
846 private:
847 File file_;
848 void *data_;
849 size_t size_;
850
851 void clear() {
852 if (data_ == NULL)
853 return;
854 _syscall(munmap(data_, size_));
855 data_ = NULL;
856 size_ = 0;
857 }
858
859 public:
860 Map() :
861 data_(NULL),
862 size_(0)
863 {
864 }
865
866 Map(const char *path, int oflag, int pflag, int mflag) :
867 Map()
868 {
869 open(path, oflag, pflag, mflag);
870 }
871
872 Map(const char *path, bool edit) :
873 Map()
874 {
875 open(path, edit);
876 }
877
878 ~Map() {
879 clear();
880 }
881
882 void open(const char *path, int oflag, int pflag, int mflag) {
883 clear();
884
885 file_.open(path, oflag);
886 int file(file_.file());
887
888 struct stat stat;
889 _syscall(fstat(file, &stat));
890 size_ = stat.st_size;
891
892 _syscall(data_ = mmap(NULL, size_, pflag, mflag, file, 0));
893 }
894
895 void open(const char *path, bool edit) {
896 if (edit)
897 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
898 else
899 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
900 }
901
902 void *data() const {
903 return data_;
904 }
905
906 size_t size() const {
907 return size_;
908 }
909
910 operator std::string() const {
911 return std::string(static_cast<char *>(data_), size_);
912 }
913 };
914
915 void resign(void *idata, size_t isize, std::streambuf &output, const char *name, const std::string &entitlements) {
916 FatHeader source(idata, isize);
917
918 uint8_t pageshift(0x0c);
919 uint32_t pagesize(1 << pageshift);
920
921 size_t offset(0);
922 if (source.IsFat())
923 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
924
925 std::vector<CodesignAllocation> allocations;
926 _foreach (mach_header, source.GetMachHeaders()) {
927 struct linkedit_data_command *signature(NULL);
928 struct symtab_command *symtab(NULL);
929
930 _foreach (load_command, mach_header.GetLoadCommands()) {
931 uint32_t cmd(mach_header.Swap(load_command->cmd));
932 if (false);
933 else if (cmd == LC_CODE_SIGNATURE)
934 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
935 else if (cmd == LC_SYMTAB)
936 symtab = reinterpret_cast<struct symtab_command *>(load_command);
937 }
938
939 size_t size;
940 if (signature == NULL)
941 size = mach_header.GetSize();
942 else {
943 size = mach_header.Swap(signature->dataoff);
944 _assert(size <= mach_header.GetSize());
945 }
946
947 if (symtab != NULL) {
948 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
949 _assert(end <= size);
950 _assert(end >= size - 0x10);
951 size = end;
952 }
953
954 size_t alloc(0);
955 uint32_t special(0);
956
957 if (name != NULL) {
958 alloc += sizeof(struct SuperBlob);
959
960 special = std::max(special, CSSLOT_REQUIREMENTS);
961 alloc += sizeof(struct BlobIndex);
962 alloc += 0xc;
963
964 if (entitlements.size() != 0) {
965 special = std::max(special, CSSLOT_ENTITLEMENTS);
966 alloc += sizeof(struct BlobIndex);
967 alloc += sizeof(struct Blob);
968 alloc += entitlements.size();
969 }
970
971 special = std::max(special, CSSLOT_CODEDIRECTORY);
972 alloc += sizeof(struct BlobIndex);
973 alloc += sizeof(struct Blob);
974 alloc += sizeof(struct CodeDirectory);
975 alloc += strlen(name) + 1;
976
977 uint32_t normal((size + pagesize - 1) / pagesize);
978 alloc = Align(alloc + (special + normal) * SHA_DIGEST_LENGTH, 16);
979 }
980
981 auto *fat_arch(mach_header.GetFatArch());
982 uint32_t align(fat_arch == NULL ? 0 : source.Swap(fat_arch->align));
983 offset = Align(offset, 1 << align);
984
985 uint32_t limit(size);
986 if (alloc != 0)
987 limit = Align(limit, 0x10);
988
989 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, special, align));
990 offset += size + alloc;
991 offset = Align(offset, 16);
992 }
993
994 size_t position(0);
995
996 if (source.IsFat()) {
997 fat_header fat_header;
998 fat_header.magic = Swap(FAT_MAGIC);
999 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1000 put(output, &fat_header, sizeof(fat_header));
1001 position += sizeof(fat_header);
1002
1003 _foreach (allocation, allocations) {
1004 auto &mach_header(allocation.mach_header_);
1005
1006 fat_arch fat_arch;
1007 fat_arch.cputype = Swap(mach_header->cputype);
1008 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1009 fat_arch.offset = Swap(allocation.offset_);
1010 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1011 fat_arch.align = Swap(allocation.align_);
1012 put(output, &fat_arch, sizeof(fat_arch));
1013 position += sizeof(fat_arch);
1014 }
1015 }
1016
1017 _foreach (allocation, allocations) {
1018 auto &mach_header(allocation.mach_header_);
1019
1020 pad(output, allocation.offset_ - position);
1021 position = allocation.offset_;
1022
1023 std::vector<std::string> commands;
1024
1025 _foreach (load_command, mach_header.GetLoadCommands()) {
1026 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
1027
1028 switch (uint32_t cmd = mach_header.Swap(load_command->cmd)) {
1029 case LC_CODE_SIGNATURE:
1030 continue;
1031 break;
1032
1033 case LC_SEGMENT: {
1034 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1035 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1036 break;
1037 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1038 segment_command->filesize = size;
1039 segment_command->vmsize = Align(size, 0x1000);
1040 } break;
1041
1042 case LC_SEGMENT_64: {
1043 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1044 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1045 break;
1046 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1047 segment_command->filesize = size;
1048 segment_command->vmsize = Align(size, 0x1000);
1049 } break;
1050 }
1051
1052 commands.push_back(copy);
1053 }
1054
1055 if (name != NULL) {
1056 linkedit_data_command signature;
1057 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1058 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1059 signature.dataoff = mach_header.Swap(allocation.limit_);
1060 signature.datasize = mach_header.Swap(allocation.alloc_);
1061 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1062 }
1063
1064 size_t begin(position);
1065
1066 uint32_t after(0);
1067 _foreach(command, commands)
1068 after += command.size();
1069
1070 std::stringbuf altern;
1071
1072 struct mach_header header(*mach_header);
1073 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1074 header.sizeofcmds = mach_header.Swap(after);
1075 put(output, &header, sizeof(header));
1076 put(altern, &header, sizeof(header));
1077 position += sizeof(header);
1078
1079 if (mach_header.Bits64()) {
1080 auto pad(mach_header.Swap(uint32_t(0)));
1081 put(output, &pad, sizeof(pad));
1082 put(altern, &pad, sizeof(pad));
1083 position += sizeof(pad);
1084 }
1085
1086 _foreach(command, commands) {
1087 put(output, command.data(), command.size());
1088 put(altern, command.data(), command.size());
1089 position += command.size();
1090 }
1091
1092 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1093 if (before > after) {
1094 pad(output, before - after);
1095 pad(altern, before - after);
1096 position += before - after;
1097 }
1098
1099 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
1100
1101 std::string overlap(altern.str());
1102 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
1103
1104 put(output, top + (position - begin), allocation.size_ - (position - begin));
1105 position = begin + allocation.size_;
1106
1107 pad(output, allocation.limit_ - allocation.size_);
1108 position += allocation.limit_ - allocation.size_;
1109
1110 if (name != NULL) {
1111 std::map<uint32_t, std::string> blobs;
1112
1113 if (true) {
1114 std::stringbuf data;
1115
1116 Blob blob;
1117 blob.magic = Swap(CSMAGIC_REQUIREMENTS);
1118 blob.length = Swap(uint32_t(sizeof(Blob) + sizeof(uint32_t)));
1119 put(data, &blob, sizeof(blob));
1120
1121 uint32_t requirements(0);
1122 requirements = Swap(0);
1123 put(data, &requirements, sizeof(requirements));
1124
1125 blobs.insert(std::make_pair(CSSLOT_REQUIREMENTS, data.str()));
1126 }
1127
1128 if (entitlements.size() != 0) {
1129 std::stringbuf data;
1130
1131 Blob blob;
1132 blob.magic = Swap(CSMAGIC_EMBEDDED_ENTITLEMENTS);
1133 blob.length = Swap(uint32_t(sizeof(blob) + entitlements.size()));
1134 put(data, &blob, sizeof(blob));
1135
1136 put(data, entitlements.data(), entitlements.size());
1137
1138 blobs.insert(std::make_pair(CSSLOT_ENTITLEMENTS, data.str()));
1139 }
1140
1141 if (true) {
1142 std::stringbuf data;
1143
1144 uint32_t normal((allocation.limit_ + pagesize - 1) / pagesize);
1145
1146 Blob blob;
1147 blob.magic = Swap(CSMAGIC_CODEDIRECTORY);
1148 blob.length = Swap(uint32_t(sizeof(blob) + sizeof(CodeDirectory) + strlen(name) + 1 + SHA_DIGEST_LENGTH * (allocation.special_ + normal)));
1149 put(data, &blob, sizeof(blob));
1150
1151 CodeDirectory directory;
1152 directory.version = Swap(uint32_t(0x00020001));
1153 directory.flags = Swap(uint32_t(0));
1154 directory.hashOffset = Swap(uint32_t(sizeof(blob) + sizeof(CodeDirectory) + strlen(name) + 1 + SHA_DIGEST_LENGTH * allocation.special_));
1155 directory.identOffset = Swap(uint32_t(sizeof(blob) + sizeof(CodeDirectory)));
1156 directory.nSpecialSlots = Swap(allocation.special_);
1157 directory.codeLimit = Swap(allocation.limit_);
1158 directory.nCodeSlots = Swap(normal);
1159 directory.hashSize = SHA_DIGEST_LENGTH;
1160 directory.hashType = CS_HASHTYPE_SHA1;
1161 directory.spare1 = 0x00;
1162 directory.pageSize = pageshift;
1163 directory.spare2 = Swap(uint32_t(0));
1164 put(data, &directory, sizeof(directory));
1165
1166 put(data, name, strlen(name) + 1);
1167
1168 uint8_t storage[allocation.special_ + normal][SHA_DIGEST_LENGTH];
1169 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = storage + allocation.special_;
1170
1171 memset(storage, 0, sizeof(*storage) * allocation.special_);
1172
1173 _foreach (blob, blobs) {
1174 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1175 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
1176 }
1177
1178 if (normal != 1)
1179 for (size_t i = 0; i != normal - 1; ++i)
1180 sha1(hashes[i], (pagesize * i < overlap.size() ? overlap.data() : top) + pagesize * i, pagesize);
1181 if (normal != 0)
1182 sha1(hashes[normal - 1], top + pagesize * (normal - 1), ((allocation.limit_ - 1) % pagesize) + 1);
1183
1184 put(data, storage, sizeof(storage));
1185
1186 blobs.insert(std::make_pair(CSSLOT_CODEDIRECTORY, data.str()));
1187 }
1188
1189 size_t total(0);
1190 _foreach (blob, blobs)
1191 total += blob.second.size();
1192
1193 struct SuperBlob super;
1194 super.blob.magic = Swap(CSMAGIC_EMBEDDED_SIGNATURE);
1195 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1196 super.count = Swap(uint32_t(blobs.size()));
1197 put(output, &super, sizeof(super));
1198
1199 uint32_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1200 position += offset + total;
1201
1202 _foreach (blob, blobs) {
1203 BlobIndex index;
1204 index.type = Swap(blob.first);
1205 index.offset = Swap(offset);
1206 put(output, &index, sizeof(index));
1207 offset += blob.second.size();
1208 }
1209
1210 _foreach (blob, blobs)
1211 put(output, blob.second.data(), blob.second.size());
1212
1213 if (allocation.alloc_ > position)
1214 pad(output, allocation.alloc_ - position);
1215 }
1216 }
1217 }
1218
1219 int main(int argc, const char *argv[]) {
1220 union {
1221 uint16_t word;
1222 uint8_t byte[2];
1223 } endian = {1};
1224
1225 little_ = endian.byte[0];
1226
1227 bool flag_r(false);
1228 bool flag_e(false);
1229
1230 bool flag_T(false);
1231
1232 bool flag_S(false);
1233 bool flag_s(false);
1234
1235 bool flag_D(false);
1236
1237 bool flag_A(false);
1238 bool flag_a(false);
1239
1240 uint32_t flag_CPUType(_not(uint32_t));
1241 uint32_t flag_CPUSubtype(_not(uint32_t));
1242
1243 const char *flag_I(NULL);
1244
1245 bool timeh(false);
1246 uint32_t timev(0);
1247
1248 Map entitlements;
1249
1250 std::vector<std::string> files;
1251
1252 if (argc == 1) {
1253 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
1254 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
1255 fprintf(stderr, " %s -S cat\n", argv[0]);
1256 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
1257 exit(0);
1258 }
1259
1260 for (int argi(1); argi != argc; ++argi)
1261 if (argv[argi][0] != '-')
1262 files.push_back(argv[argi]);
1263 else switch (argv[argi][1]) {
1264 case 'r': flag_r = true; break;
1265 case 'e': flag_e = true; break;
1266
1267 case 'D': flag_D = true; break;
1268
1269 case 'a': flag_a = true; break;
1270
1271 case 'A':
1272 flag_A = true;
1273 if (argv[argi][2] != '\0') {
1274 const char *cpu = argv[argi] + 2;
1275 const char *colon = strchr(cpu, ':');
1276 _assert(colon != NULL);
1277 char *arge;
1278 flag_CPUType = strtoul(cpu, &arge, 0);
1279 _assert(arge == colon);
1280 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
1281 _assert(arge == argv[argi] + strlen(argv[argi]));
1282 }
1283 break;
1284
1285 case 's':
1286 _assert(!flag_S);
1287 flag_s = true;
1288 break;
1289
1290 case 'S':
1291 _assert(!flag_s);
1292 flag_S = true;
1293 if (argv[argi][2] != '\0') {
1294 const char *xml = argv[argi] + 2;
1295 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
1296 }
1297 break;
1298
1299 case 'T': {
1300 flag_T = true;
1301 if (argv[argi][2] == '-')
1302 timeh = true;
1303 else {
1304 char *arge;
1305 timev = strtoul(argv[argi] + 2, &arge, 0);
1306 _assert(arge == argv[argi] + strlen(argv[argi]));
1307 }
1308 } break;
1309
1310 case 'I': {
1311 flag_I = argv[argi] + 2;
1312 } break;
1313
1314 default:
1315 goto usage;
1316 break;
1317 }
1318
1319 _assert(!flag_S || !flag_r);
1320
1321 if (files.empty()) usage: {
1322 exit(0);
1323 }
1324
1325 size_t filei(0), filee(0);
1326 _foreach (file, files) try {
1327 const char *path(file.c_str());
1328 const char *base = strrchr(path, '/');
1329
1330 std::string dir;
1331 if (base != NULL)
1332 dir.assign(path, base++ - path + 1);
1333 else
1334 base = path;
1335
1336 const char *name(flag_I ?: base);
1337 char *temp(NULL);
1338
1339 if (flag_S || flag_r) {
1340 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
1341
1342 std::filebuf output;
1343 asprintf(&temp, "%s.%s.cs", dir.c_str(), base);
1344 _assert(output.open(temp, std::ios::out | std::ios::trunc | std::ios::binary) == &output);
1345
1346 resign(input.data(), input.size(), output, flag_S ? name : NULL, entitlements);
1347 }
1348
1349 Map mapping(temp ?: path, flag_T || flag_s);
1350 FatHeader fat_header(mapping.data(), mapping.size());
1351
1352 _foreach (mach_header, fat_header.GetMachHeaders()) {
1353 struct linkedit_data_command *signature(NULL);
1354 struct encryption_info_command *encryption(NULL);
1355
1356 if (flag_A) {
1357 if (mach_header.GetCPUType() != flag_CPUType)
1358 continue;
1359 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
1360 continue;
1361 }
1362
1363 if (flag_a)
1364 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
1365
1366 _foreach (load_command, mach_header.GetLoadCommands()) {
1367 uint32_t cmd(mach_header.Swap(load_command->cmd));
1368
1369 if (false);
1370 else if (cmd == LC_CODE_SIGNATURE)
1371 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
1372 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
1373 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
1374 else if (cmd == LC_ID_DYLIB) {
1375 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
1376
1377 if (flag_T) {
1378 uint32_t timed;
1379
1380 if (!timeh)
1381 timed = timev;
1382 else {
1383 dylib_command->dylib.timestamp = 0;
1384 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
1385 }
1386
1387 dylib_command->dylib.timestamp = mach_header.Swap(timed);
1388 }
1389 }
1390 }
1391
1392 if (flag_D) {
1393 _assert(encryption != NULL);
1394 encryption->cryptid = mach_header.Swap(0);
1395 }
1396
1397 if (flag_e) {
1398 _assert(signature != NULL);
1399
1400 uint32_t data = mach_header.Swap(signature->dataoff);
1401
1402 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1403 uint8_t *blob = top + data;
1404 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1405
1406 for (size_t index(0); index != Swap(super->count); ++index)
1407 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1408 uint32_t begin = Swap(super->index[index].offset);
1409 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
1410 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(struct Blob), stdout);
1411 }
1412 }
1413
1414 if (flag_s) {
1415 _assert(signature != NULL);
1416
1417 uint32_t data = mach_header.Swap(signature->dataoff);
1418
1419 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1420 uint8_t *blob = top + data;
1421 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
1422
1423 for (size_t index(0); index != Swap(super->count); ++index)
1424 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
1425 uint32_t begin = Swap(super->index[index].offset);
1426 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
1427
1428 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
1429 uint32_t pages = Swap(directory->nCodeSlots);
1430
1431 if (pages != 1)
1432 for (size_t i = 0; i != pages - 1; ++i)
1433 sha1(hashes[i], top + 0x1000 * i, 0x1000);
1434 if (pages != 0)
1435 sha1(hashes[pages - 1], top + 0x1000 * (pages - 1), ((data - 1) % 0x1000) + 1);
1436 }
1437 }
1438 }
1439
1440 if (temp != NULL) {
1441 struct stat info;
1442 _syscall(stat(path, &info));
1443 _syscall(chown(temp, info.st_uid, info.st_gid));
1444 _syscall(chmod(temp, info.st_mode));
1445 _syscall(unlink(path));
1446 _syscall(rename(temp, path));
1447 free(temp);
1448 }
1449
1450 ++filei;
1451 } catch (const char *) {
1452 ++filee;
1453 ++filei;
1454 }
1455
1456 return filee;
1457 }