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