]> git.saurik.com Git - ldid.git/blob - ldid.cpp
Standardize _syscall as exactly one function call.
[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 <errno.h>
32 #include <fcntl.h>
33 #include <stdbool.h>
34 #include <stdint.h>
35 #include <unistd.h>
36
37 #include <sys/mman.h>
38 #include <sys/stat.h>
39
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>
45
46 #include <plist/plist.h>
47
48 #include "ldid.hpp"
49
50 #define _assert___(line) \
51 #line
52 #define _assert__(line) \
53 _assert___(line)
54
55 #define _assert_(expr, format, ...) \
56 do if (!(expr)) { \
57 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
58 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
59 } while (false)
60
61 #define _assert(expr) \
62 _assert_(expr, "%s", #expr)
63
64 #define _syscall(expr) ({ \
65 __typeof__(expr) _value; \
66 do if ((long) (_value = (expr)) != -1) \
67 break; \
68 else switch (errno) { \
69 case EINTR: \
70 continue; \
71 default: \
72 _assert_(false, "errno=%u", errno); \
73 } while (true); \
74 _value; \
75 })
76
77 #define _trace() \
78 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
79
80 #define _not(type) \
81 ((type) ~ (type) 0)
82
83 #define _packed \
84 __attribute__((packed))
85
86 template <typename Type_>
87 struct Iterator_ {
88 typedef typename Type_::const_iterator Result;
89 };
90
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)
97
98 struct fat_header {
99 uint32_t magic;
100 uint32_t nfat_arch;
101 } _packed;
102
103 #define FAT_MAGIC 0xcafebabe
104 #define FAT_CIGAM 0xbebafeca
105
106 struct fat_arch {
107 uint32_t cputype;
108 uint32_t cpusubtype;
109 uint32_t offset;
110 uint32_t size;
111 uint32_t align;
112 } _packed;
113
114 struct mach_header {
115 uint32_t magic;
116 uint32_t cputype;
117 uint32_t cpusubtype;
118 uint32_t filetype;
119 uint32_t ncmds;
120 uint32_t sizeofcmds;
121 uint32_t flags;
122 } _packed;
123
124 #define MH_MAGIC 0xfeedface
125 #define MH_CIGAM 0xcefaedfe
126
127 #define MH_MAGIC_64 0xfeedfacf
128 #define MH_CIGAM_64 0xcffaedfe
129
130 #define MH_DYLDLINK 0x4
131
132 #define MH_OBJECT 0x1
133 #define MH_EXECUTE 0x2
134 #define MH_DYLIB 0x6
135 #define MH_BUNDLE 0x8
136 #define MH_DYLIB_STUB 0x9
137
138 struct load_command {
139 uint32_t cmd;
140 uint32_t cmdsize;
141 } _packed;
142
143 #define LC_REQ_DYLD uint32_t(0x80000000)
144
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)
159
160 struct dylib {
161 uint32_t name;
162 uint32_t timestamp;
163 uint32_t current_version;
164 uint32_t compatibility_version;
165 } _packed;
166
167 struct dylib_command {
168 uint32_t cmd;
169 uint32_t cmdsize;
170 struct dylib dylib;
171 } _packed;
172
173 struct uuid_command {
174 uint32_t cmd;
175 uint32_t cmdsize;
176 uint8_t uuid[16];
177 } _packed;
178
179 struct symtab_command {
180 uint32_t cmd;
181 uint32_t cmdsize;
182 uint32_t symoff;
183 uint32_t nsyms;
184 uint32_t stroff;
185 uint32_t strsize;
186 } _packed;
187
188 struct dyld_info_command {
189 uint32_t cmd;
190 uint32_t cmdsize;
191 uint32_t rebase_off;
192 uint32_t rebase_size;
193 uint32_t bind_off;
194 uint32_t bind_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;
199 uint32_t export_off;
200 uint32_t export_size;
201 } _packed;
202
203 struct dysymtab_command {
204 uint32_t cmd;
205 uint32_t cmdsize;
206 uint32_t ilocalsym;
207 uint32_t nlocalsym;
208 uint32_t iextdefsym;
209 uint32_t nextdefsym;
210 uint32_t iundefsym;
211 uint32_t nundefsym;
212 uint32_t tocoff;
213 uint32_t ntoc;
214 uint32_t modtaboff;
215 uint32_t nmodtab;
216 uint32_t extrefsymoff;
217 uint32_t nextrefsyms;
218 uint32_t indirectsymoff;
219 uint32_t nindirectsyms;
220 uint32_t extreloff;
221 uint32_t nextrel;
222 uint32_t locreloff;
223 uint32_t nlocrel;
224 } _packed;
225
226 struct dylib_table_of_contents {
227 uint32_t symbol_index;
228 uint32_t module_index;
229 } _packed;
230
231 struct dylib_module {
232 uint32_t module_name;
233 uint32_t iextdefsym;
234 uint32_t nextdefsym;
235 uint32_t irefsym;
236 uint32_t nrefsym;
237 uint32_t ilocalsym;
238 uint32_t nlocalsym;
239 uint32_t iextrel;
240 uint32_t nextrel;
241 uint32_t iinit_iterm;
242 uint32_t ninit_nterm;
243 uint32_t objc_module_info_addr;
244 uint32_t objc_module_info_size;
245 } _packed;
246
247 struct dylib_reference {
248 uint32_t isym:24;
249 uint32_t flags:8;
250 } _packed;
251
252 struct relocation_info {
253 int32_t r_address;
254 uint32_t r_symbolnum:24;
255 uint32_t r_pcrel:1;
256 uint32_t r_length:2;
257 uint32_t r_extern:1;
258 uint32_t r_type:4;
259 } _packed;
260
261 struct nlist {
262 union {
263 char *n_name;
264 int32_t n_strx;
265 } n_un;
266
267 uint8_t n_type;
268 uint8_t n_sect;
269 uint8_t n_desc;
270 uint32_t n_value;
271 } _packed;
272
273 struct segment_command {
274 uint32_t cmd;
275 uint32_t cmdsize;
276 char segname[16];
277 uint32_t vmaddr;
278 uint32_t vmsize;
279 uint32_t fileoff;
280 uint32_t filesize;
281 uint32_t maxprot;
282 uint32_t initprot;
283 uint32_t nsects;
284 uint32_t flags;
285 } _packed;
286
287 struct segment_command_64 {
288 uint32_t cmd;
289 uint32_t cmdsize;
290 char segname[16];
291 uint64_t vmaddr;
292 uint64_t vmsize;
293 uint64_t fileoff;
294 uint64_t filesize;
295 uint32_t maxprot;
296 uint32_t initprot;
297 uint32_t nsects;
298 uint32_t flags;
299 } _packed;
300
301 struct section {
302 char sectname[16];
303 char segname[16];
304 uint32_t addr;
305 uint32_t size;
306 uint32_t offset;
307 uint32_t align;
308 uint32_t reloff;
309 uint32_t nreloc;
310 uint32_t flags;
311 uint32_t reserved1;
312 uint32_t reserved2;
313 } _packed;
314
315 struct section_64 {
316 char sectname[16];
317 char segname[16];
318 uint64_t addr;
319 uint64_t size;
320 uint32_t offset;
321 uint32_t align;
322 uint32_t reloff;
323 uint32_t nreloc;
324 uint32_t flags;
325 uint32_t reserved1;
326 uint32_t reserved2;
327 } _packed;
328
329 struct linkedit_data_command {
330 uint32_t cmd;
331 uint32_t cmdsize;
332 uint32_t dataoff;
333 uint32_t datasize;
334 } _packed;
335
336 struct encryption_info_command {
337 uint32_t cmd;
338 uint32_t cmdsize;
339 uint32_t cryptoff;
340 uint32_t cryptsize;
341 uint32_t cryptid;
342 } _packed;
343
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
359
360 inline void get(std::streambuf &stream, void *data, size_t size) {
361 _assert(stream.sgetn(static_cast<char *>(data), size) == size);
362 }
363
364 inline void put(std::streambuf &stream, const void *data, size_t size) {
365 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
366 }
367
368 inline void pad(std::streambuf &stream, size_t size) {
369 char padding[size];
370 memset(padding, 0, size);
371 put(stream, padding, size);
372 }
373
374 template <typename Type_>
375 Type_ Align(Type_ value, size_t align) {
376 value += align - 1;
377 value /= align;
378 value *= align;
379 return value;
380 }
381
382 static const uint8_t PageShift_(0x0c);
383 static const uint32_t PageSize_(1 << PageShift_);
384
385 static inline uint16_t Swap_(uint16_t value) {
386 return
387 ((value >> 8) & 0x00ff) |
388 ((value << 8) & 0xff00);
389 }
390
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);
396 return value;
397 }
398
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;
403 return value;
404 }
405
406 static inline int16_t Swap_(int16_t value) {
407 return Swap_(static_cast<uint16_t>(value));
408 }
409
410 static inline int32_t Swap_(int32_t value) {
411 return Swap_(static_cast<uint32_t>(value));
412 }
413
414 static inline int64_t Swap_(int64_t value) {
415 return Swap_(static_cast<uint64_t>(value));
416 }
417
418 static bool little_(true);
419
420 static inline uint16_t Swap(uint16_t value) {
421 return little_ ? Swap_(value) : value;
422 }
423
424 static inline uint32_t Swap(uint32_t value) {
425 return little_ ? Swap_(value) : value;
426 }
427
428 static inline uint64_t Swap(uint64_t value) {
429 return little_ ? Swap_(value) : value;
430 }
431
432 static inline int16_t Swap(int16_t value) {
433 return Swap(static_cast<uint16_t>(value));
434 }
435
436 static inline int32_t Swap(int32_t value) {
437 return Swap(static_cast<uint32_t>(value));
438 }
439
440 static inline int64_t Swap(int64_t value) {
441 return Swap(static_cast<uint64_t>(value));
442 }
443
444 template <typename Target_>
445 class Pointer;
446
447 class Swapped {
448 protected:
449 bool swapped_;
450
451 Swapped() :
452 swapped_(false)
453 {
454 }
455
456 public:
457 Swapped(bool swapped) :
458 swapped_(swapped)
459 {
460 }
461
462 template <typename Type_>
463 Type_ Swap(Type_ value) const {
464 return swapped_ ? Swap_(value) : value;
465 }
466 };
467
468 class Data :
469 public Swapped
470 {
471 private:
472 void *base_;
473 size_t size_;
474
475 public:
476 Data(void *base, size_t size) :
477 base_(base),
478 size_(size)
479 {
480 }
481
482 void *GetBase() const {
483 return base_;
484 }
485
486 size_t GetSize() const {
487 return size_;
488 }
489 };
490
491 class MachHeader :
492 public Data
493 {
494 private:
495 bool bits64_;
496
497 struct mach_header *mach_header_;
498 struct load_command *load_command_;
499
500 public:
501 MachHeader(void *base, size_t size) :
502 Data(base, size)
503 {
504 mach_header_ = (mach_header *) base;
505
506 switch (Swap(mach_header_->magic)) {
507 case MH_CIGAM:
508 swapped_ = !swapped_;
509 case MH_MAGIC:
510 bits64_ = false;
511 break;
512
513 case MH_CIGAM_64:
514 swapped_ = !swapped_;
515 case MH_MAGIC_64:
516 bits64_ = true;
517 break;
518
519 default:
520 _assert(false);
521 }
522
523 void *post = mach_header_ + 1;
524 if (bits64_)
525 post = (uint32_t *) post + 1;
526 load_command_ = (struct load_command *) post;
527
528 _assert(
529 Swap(mach_header_->filetype) == MH_EXECUTE ||
530 Swap(mach_header_->filetype) == MH_DYLIB ||
531 Swap(mach_header_->filetype) == MH_BUNDLE
532 );
533 }
534
535 bool Bits64() const {
536 return bits64_;
537 }
538
539 struct mach_header *operator ->() const {
540 return mach_header_;
541 }
542
543 operator struct mach_header *() const {
544 return mach_header_;
545 }
546
547 uint32_t GetCPUType() const {
548 return Swap(mach_header_->cputype);
549 }
550
551 uint32_t GetCPUSubtype() const {
552 return Swap(mach_header_->cpusubtype) & 0xff;
553 }
554
555 struct load_command *GetLoadCommand() const {
556 return load_command_;
557 }
558
559 std::vector<struct load_command *> GetLoadCommands() const {
560 std::vector<struct load_command *> load_commands;
561
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));
566 }
567
568 return load_commands;
569 }
570
571 std::vector<segment_command *> GetSegments(const char *segment_name) const {
572 std::vector<struct segment_command *> segment_commands;
573
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);
579 }
580 }
581
582 return segment_commands;
583 }
584
585 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) const {
586 std::vector<struct segment_command_64 *> segment_commands;
587
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);
593 }
594 }
595
596 return segment_commands;
597 }
598
599 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
600 std::vector<section *> sections;
601
602 _foreach (segment, GetSegments(segment_name)) {
603 section *section = (struct section *) (segment + 1);
604
605 uint32_t sect;
606 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
607 if (strncmp(section->sectname, section_name, 16) == 0)
608 sections.push_back(section);
609 ++section;
610 }
611 }
612
613 return sections;
614 }
615
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);
619 uint32_t cmd;
620
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)
625 goto next_command;
626
627 section *sections = (struct section *) (segment_command + 1);
628
629 uint32_t sect;
630 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
631 section *section = &sections[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_));
636 }
637 }
638 }
639
640 next_command:
641 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
642 }
643
644 return Pointer<Target_>(this);
645 }
646
647 template <typename Target_>
648 Pointer<Target_> GetOffset(uint32_t offset) {
649 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
650 }
651 };
652
653 class FatMachHeader :
654 public MachHeader
655 {
656 private:
657 fat_arch *fat_arch_;
658
659 public:
660 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
661 MachHeader(base, size),
662 fat_arch_(fat_arch)
663 {
664 }
665
666 fat_arch *GetFatArch() const {
667 return fat_arch_;
668 }
669 };
670
671 class FatHeader :
672 public Data
673 {
674 private:
675 fat_header *fat_header_;
676 std::vector<FatMachHeader> mach_headers_;
677
678 public:
679 FatHeader(void *base, size_t size) :
680 Data(base, size)
681 {
682 fat_header_ = reinterpret_cast<struct fat_header *>(base);
683
684 if (Swap(fat_header_->magic) == FAT_CIGAM) {
685 swapped_ = !swapped_;
686 goto fat;
687 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
688 fat_header_ = NULL;
689 mach_headers_.push_back(FatMachHeader(base, size, NULL));
690 } else fat: {
691 size_t fat_narch = Swap(fat_header_->nfat_arch);
692 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
693 size_t arch;
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));
698 ++fat_arch;
699 }
700 }
701 }
702
703 std::vector<FatMachHeader> &GetMachHeaders() {
704 return mach_headers_;
705 }
706
707 bool IsFat() const {
708 return fat_header_ != NULL;
709 }
710
711 struct fat_header *operator ->() const {
712 return fat_header_;
713 }
714
715 operator struct fat_header *() const {
716 return fat_header_;
717 }
718 };
719
720 template <typename Target_>
721 class Pointer {
722 private:
723 const MachHeader *framework_;
724 const Target_ *pointer_;
725
726 public:
727 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
728 framework_(framework),
729 pointer_(pointer)
730 {
731 }
732
733 operator const Target_ *() const {
734 return pointer_;
735 }
736
737 const Target_ *operator ->() const {
738 return pointer_;
739 }
740
741 Pointer<Target_> &operator ++() {
742 ++pointer_;
743 return *this;
744 }
745
746 template <typename Value_>
747 Value_ Swap(Value_ value) {
748 return framework_->Swap(value);
749 }
750 };
751
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)
760
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)
767
768 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
769
770 #define CS_HASHTYPE_SHA1 1
771
772 struct BlobIndex {
773 uint32_t type;
774 uint32_t offset;
775 } _packed;
776
777 struct Blob {
778 uint32_t magic;
779 uint32_t length;
780 } _packed;
781
782 struct SuperBlob {
783 struct Blob blob;
784 uint32_t count;
785 struct BlobIndex index[];
786 } _packed;
787
788 struct CodeDirectory {
789 uint32_t version;
790 uint32_t flags;
791 uint32_t hashOffset;
792 uint32_t identOffset;
793 uint32_t nSpecialSlots;
794 uint32_t nCodeSlots;
795 uint32_t codeLimit;
796 uint8_t hashSize;
797 uint8_t hashType;
798 uint8_t spare1;
799 uint8_t pageSize;
800 uint32_t spare2;
801 } _packed;
802
803 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
804
805 static void sha1(uint8_t *hash, const void *data, size_t size) {
806 SHA1(static_cast<const uint8_t *>(data), size, hash);
807 }
808
809 struct CodesignAllocation {
810 FatMachHeader mach_header_;
811 uint32_t offset_;
812 uint32_t size_;
813 uint32_t limit_;
814 uint32_t alloc_;
815 uint32_t align_;
816
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),
819 offset_(offset),
820 size_(size),
821 limit_(limit),
822 alloc_(alloc),
823 align_(align)
824 {
825 }
826 };
827
828 class File {
829 private:
830 int file_;
831
832 public:
833 File() :
834 file_(-1)
835 {
836 }
837
838 ~File() {
839 if (file_ != -1)
840 _syscall(close(file_));
841 }
842
843 void open(const char *path, int flags) {
844 _assert(file_ == -1);
845 file_ = _syscall(::open(path, flags));
846 }
847
848 int file() const {
849 return file_;
850 }
851 };
852
853 class Map {
854 private:
855 File file_;
856 void *data_;
857 size_t size_;
858
859 void clear() {
860 if (data_ == NULL)
861 return;
862 _syscall(munmap(data_, size_));
863 data_ = NULL;
864 size_ = 0;
865 }
866
867 public:
868 Map() :
869 data_(NULL),
870 size_(0)
871 {
872 }
873
874 Map(const char *path, int oflag, int pflag, int mflag) :
875 Map()
876 {
877 open(path, oflag, pflag, mflag);
878 }
879
880 Map(const char *path, bool edit) :
881 Map()
882 {
883 open(path, edit);
884 }
885
886 ~Map() {
887 clear();
888 }
889
890 bool empty() const {
891 return data_ == NULL;
892 }
893
894 void open(const char *path, int oflag, int pflag, int mflag) {
895 clear();
896
897 file_.open(path, oflag);
898 int file(file_.file());
899
900 struct stat stat;
901 _syscall(fstat(file, &stat));
902 size_ = stat.st_size;
903
904 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
905 }
906
907 void open(const char *path, bool edit) {
908 if (edit)
909 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
910 else
911 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
912 }
913
914 void *data() const {
915 return data_;
916 }
917
918 size_t size() const {
919 return size_;
920 }
921
922 operator std::string() const {
923 return std::string(static_cast<char *>(data_), size_);
924 }
925 };
926
927 namespace ldid {
928
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);
931
932 size_t offset(0);
933 if (source.IsFat())
934 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
935
936 std::vector<CodesignAllocation> allocations;
937 _foreach (mach_header, source.GetMachHeaders()) {
938 struct linkedit_data_command *signature(NULL);
939 struct symtab_command *symtab(NULL);
940
941 _foreach (load_command, mach_header.GetLoadCommands()) {
942 uint32_t cmd(mach_header.Swap(load_command->cmd));
943 if (false);
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);
948 }
949
950 size_t size;
951 if (signature == NULL)
952 size = mach_header.GetSize();
953 else {
954 size = mach_header.Swap(signature->dataoff);
955 _assert(size <= mach_header.GetSize());
956 }
957
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);
962 size = end;
963 }
964
965 size_t alloc(allocate(size));
966
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);
970
971 uint32_t limit(size);
972 if (alloc != 0)
973 limit = Align(limit, 0x10);
974
975 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
976 offset += size + alloc;
977 offset = Align(offset, 0x10);
978 }
979
980 size_t position(0);
981
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);
988
989 _foreach (allocation, allocations) {
990 auto &mach_header(allocation.mach_header_);
991
992 fat_arch fat_arch;
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);
1000 }
1001 }
1002
1003 _foreach (allocation, allocations) {
1004 auto &mach_header(allocation.mach_header_);
1005
1006 pad(output, allocation.offset_ - position);
1007 position = allocation.offset_;
1008
1009 std::vector<std::string> commands;
1010
1011 _foreach (load_command, mach_header.GetLoadCommands()) {
1012 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
1013
1014 switch (mach_header.Swap(load_command->cmd)) {
1015 case LC_CODE_SIGNATURE:
1016 continue;
1017 break;
1018
1019 case LC_SEGMENT: {
1020 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1021 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1022 break;
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_);
1026 } break;
1027
1028 case LC_SEGMENT_64: {
1029 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1030 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1031 break;
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_);
1035 } break;
1036 }
1037
1038 commands.push_back(copy);
1039 }
1040
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)));
1048 }
1049
1050 size_t begin(position);
1051
1052 uint32_t after(0);
1053 _foreach(command, commands)
1054 after += command.size();
1055
1056 std::stringbuf altern;
1057
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);
1064
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);
1070 }
1071
1072 _foreach(command, commands) {
1073 put(output, command.data(), command.size());
1074 put(altern, command.data(), command.size());
1075 position += command.size();
1076 }
1077
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;
1083 }
1084
1085 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
1086
1087 std::string overlap(altern.str());
1088 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
1089
1090 put(output, top + (position - begin), allocation.size_ - (position - begin));
1091 position = begin + allocation.size_;
1092
1093 pad(output, allocation.limit_ - allocation.size_);
1094 position += allocation.limit_ - allocation.size_;
1095
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_;
1100 }
1101 }
1102
1103 }
1104
1105 typedef std::map<uint32_t, std::string> Blobs;
1106
1107 static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1108 auto value(buffer.str());
1109 std::swap(blobs[slot], value);
1110 }
1111
1112 static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1113 auto value(buffer.str());
1114 Blob blob;
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);
1119 }
1120
1121 static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1122 size_t total(0);
1123 _foreach (blob, blobs)
1124 total += blob.second.size();
1125
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));
1131
1132 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1133
1134 _foreach (blob, blobs) {
1135 BlobIndex index;
1136 index.type = Swap(blob.first);
1137 index.offset = Swap(uint32_t(offset));
1138 put(output, &index, sizeof(index));
1139 offset += blob.second.size();
1140 }
1141
1142 _foreach (blob, blobs)
1143 put(output, blob.second.data(), blob.second.size());
1144
1145 return offset;
1146 }
1147
1148 class Buffer {
1149 private:
1150 BIO *bio_;
1151
1152 public:
1153 Buffer(BIO *bio) :
1154 bio_(bio)
1155 {
1156 _assert(bio_ != NULL);
1157 }
1158
1159 Buffer() :
1160 bio_(BIO_new(BIO_s_mem()))
1161 {
1162 }
1163
1164 Buffer(const char *data, size_t size) :
1165 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1166 {
1167 }
1168
1169 Buffer(const std::string &data) :
1170 Buffer(data.data(), data.size())
1171 {
1172 }
1173
1174 Buffer(PKCS7 *pkcs) :
1175 Buffer()
1176 {
1177 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1178 }
1179
1180 ~Buffer() {
1181 BIO_free_all(bio_);
1182 }
1183
1184 operator BIO *() const {
1185 return bio_;
1186 }
1187
1188 explicit operator std::string() const {
1189 char *data;
1190 auto size(BIO_get_mem_data(bio_, &data));
1191 return std::string(data, size);
1192 }
1193 };
1194
1195 class Stuff {
1196 private:
1197 PKCS12 *value_;
1198 EVP_PKEY *key_;
1199 X509 *cert_;
1200 STACK_OF(X509) *ca_;
1201
1202 public:
1203 Stuff(BIO *bio) :
1204 value_(d2i_PKCS12_bio(bio, NULL)),
1205 ca_(NULL)
1206 {
1207 _assert(value_ != NULL);
1208 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1209 _assert(key_ != NULL);
1210 _assert(cert_ != NULL);
1211 }
1212
1213 Stuff(const std::string &data) :
1214 Stuff(Buffer(data))
1215 {
1216 }
1217
1218 ~Stuff() {
1219 sk_X509_pop_free(ca_, X509_free);
1220 X509_free(cert_);
1221 EVP_PKEY_free(key_);
1222 PKCS12_free(value_);
1223 }
1224
1225 operator PKCS12 *() const {
1226 return value_;
1227 }
1228
1229 operator EVP_PKEY *() const {
1230 return key_;
1231 }
1232
1233 operator X509 *() const {
1234 return cert_;
1235 }
1236
1237 operator STACK_OF(X509) *() const {
1238 return ca_;
1239 }
1240 };
1241
1242 class Signature {
1243 private:
1244 PKCS7 *value_;
1245
1246 public:
1247 Signature(const Stuff &stuff, const Buffer &data) :
1248 value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
1249 {
1250 _assert(value_ != NULL);
1251 }
1252
1253 ~Signature() {
1254 PKCS7_free(value_);
1255 }
1256
1257 operator PKCS7 *() const {
1258 return value_;
1259 }
1260 };
1261
1262 namespace ldid {
1263
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));
1267
1268 uint32_t special(0);
1269
1270 special = std::max(special, CSSLOT_REQUIREMENTS);
1271 alloc += sizeof(struct BlobIndex);
1272 alloc += 0xc;
1273
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();
1279 }
1280
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;
1286
1287 if (!key.empty()) {
1288 alloc += sizeof(struct BlobIndex);
1289 alloc += sizeof(struct Blob);
1290 // XXX: this is just a "sufficiently large number"
1291 alloc += 0x3000;
1292 }
1293
1294 _foreach (slot, slots)
1295 special = std::max(special, slot.first);
1296
1297 uint32_t normal((size + PageSize_ - 1) / PageSize_);
1298 alloc = Align(alloc + (special + normal) * SHA_DIGEST_LENGTH, 16);
1299 return alloc;
1300 }), fun([&](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1301 Blobs blobs;
1302
1303 if (true) {
1304 std::stringbuf data;
1305
1306 Blobs requirements;
1307 put(data, CSMAGIC_REQUIREMENTS, requirements);
1308
1309 insert(blobs, CSSLOT_REQUIREMENTS, data);
1310 }
1311
1312 if (!entitlements.empty()) {
1313 std::stringbuf data;
1314 put(data, entitlements.data(), entitlements.size());
1315 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
1316 }
1317
1318 if (true) {
1319 std::stringbuf data;
1320
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_);
1327
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));
1342
1343 put(data, name.c_str(), name.size() + 1);
1344
1345 uint8_t storage[special + normal][SHA_DIGEST_LENGTH];
1346 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = storage + special;
1347
1348 memset(storage, 0, sizeof(*storage) * special);
1349
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));
1353 }
1354
1355 _foreach (slot, slots) {
1356 _assert(sizeof(*hashes) == slot.second.size());
1357 memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
1358 }
1359
1360 if (normal != 1)
1361 for (size_t i = 0; i != normal - 1; ++i)
1362 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
1363 if (normal != 0)
1364 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
1365
1366 put(data, storage, sizeof(storage));
1367
1368 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
1369 }
1370
1371 if (!key.empty()) {
1372 std::stringbuf data;
1373 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1374
1375 Stuff stuff(key);
1376 Buffer bio(sign);
1377
1378 Signature signature(stuff, sign);
1379 Buffer result(signature);
1380 std::string value(result);
1381 put(data, value.data(), value.size());
1382
1383 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1384 }
1385
1386 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
1387 }));
1388 }
1389
1390 static void Unsign(void *idata, size_t isize, std::streambuf &output) {
1391 Allocate(idata, isize, output, fun([](size_t size) -> size_t {
1392 return 0;
1393 }), fun([](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1394 return 0;
1395 }));
1396 }
1397
1398 }
1399
1400 int main(int argc, char *argv[]) {
1401 OpenSSL_add_all_algorithms();
1402
1403 union {
1404 uint16_t word;
1405 uint8_t byte[2];
1406 } endian = {1};
1407
1408 little_ = endian.byte[0];
1409
1410 bool flag_r(false);
1411 bool flag_e(false);
1412
1413 bool flag_T(false);
1414
1415 bool flag_S(false);
1416 bool flag_s(false);
1417
1418 bool flag_D(false);
1419
1420 bool flag_A(false);
1421 bool flag_a(false);
1422
1423 uint32_t flag_CPUType(_not(uint32_t));
1424 uint32_t flag_CPUSubtype(_not(uint32_t));
1425
1426 const char *flag_I(NULL);
1427
1428 bool timeh(false);
1429 uint32_t timev(0);
1430
1431 Map entitlements;
1432 Map key;
1433 ldid::Slots slots;
1434
1435 std::vector<std::string> files;
1436
1437 if (argc == 1) {
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]);
1442 exit(0);
1443 }
1444
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]) {
1449 case 'r':
1450 _assert(!flag_s);
1451 _assert(!flag_S);
1452 flag_r = true;
1453 break;
1454
1455 case 'e': flag_e = true; break;
1456
1457 case 'E': {
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);
1462 char *arge;
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());
1468 } break;
1469
1470 case 'D': flag_D = true; break;
1471
1472 case 'a': flag_a = true; break;
1473
1474 case 'A':
1475 _assert(!flag_A);
1476 flag_A = true;
1477 if (argv[argi][2] != '\0') {
1478 const char *cpu = argv[argi] + 2;
1479 const char *colon = strchr(cpu, ':');
1480 _assert(colon != NULL);
1481 char *arge;
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]));
1486 }
1487 break;
1488
1489 case 's':
1490 _assert(!flag_r);
1491 _assert(!flag_S);
1492 flag_s = true;
1493 break;
1494
1495 case 'S':
1496 _assert(!flag_r);
1497 _assert(!flag_s);
1498 flag_S = true;
1499 if (argv[argi][2] != '\0') {
1500 const char *xml = argv[argi] + 2;
1501 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
1502 }
1503 break;
1504
1505 case 'K':
1506 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
1507 break;
1508
1509 case 'T': {
1510 flag_T = true;
1511 if (argv[argi][2] == '-')
1512 timeh = true;
1513 else {
1514 char *arge;
1515 timev = strtoul(argv[argi] + 2, &arge, 0);
1516 _assert(arge == argv[argi] + strlen(argv[argi]));
1517 }
1518 } break;
1519
1520 case 'I': {
1521 flag_I = argv[argi] + 2;
1522 } break;
1523
1524 default:
1525 goto usage;
1526 break;
1527 }
1528
1529 _assert(flag_S || key.empty());
1530 _assert(flag_S || flag_I == NULL);
1531
1532 if (files.empty()) usage: {
1533 exit(0);
1534 }
1535
1536 size_t filei(0), filee(0);
1537 _foreach (file, files) try {
1538 const char *path(file.c_str());
1539
1540 if (flag_S || flag_r) {
1541 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
1542
1543 std::string dir;
1544 const char *base = strrchr(path, '/');
1545
1546 if (base != NULL)
1547 dir.assign(path, base++ - path + 1);
1548 else
1549 base = path;
1550
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);
1554
1555 if (flag_r)
1556 ldid::Unsign(input.data(), input.size(), output);
1557 else {
1558 const char *name(flag_I ?: base);
1559 ldid::Sign(input.data(), input.size(), output, name, entitlements, key, slots);
1560 }
1561
1562 struct stat info;
1563 _syscall(stat(path, &info));
1564 #ifndef __WIN32__
1565 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1566 #endif
1567 _syscall(chmod(temp.c_str(), info.st_mode));
1568 _syscall(unlink(path));
1569 _syscall(rename(temp.c_str(), path));
1570 }
1571
1572 Map mapping(path, flag_T || flag_s);
1573 FatHeader fat_header(mapping.data(), mapping.size());
1574
1575 _foreach (mach_header, fat_header.GetMachHeaders()) {
1576 struct linkedit_data_command *signature(NULL);
1577 struct encryption_info_command *encryption(NULL);
1578
1579 if (flag_A) {
1580 if (mach_header.GetCPUType() != flag_CPUType)
1581 continue;
1582 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
1583 continue;
1584 }
1585
1586 if (flag_a)
1587 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
1588
1589 _foreach (load_command, mach_header.GetLoadCommands()) {
1590 uint32_t cmd(mach_header.Swap(load_command->cmd));
1591
1592 if (false);
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));
1599
1600 if (flag_T) {
1601 uint32_t timed;
1602
1603 if (!timeh)
1604 timed = timev;
1605 else {
1606 dylib_command->dylib.timestamp = 0;
1607 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
1608 }
1609
1610 dylib_command->dylib.timestamp = mach_header.Swap(timed);
1611 }
1612 }
1613 }
1614
1615 if (flag_D) {
1616 _assert(encryption != NULL);
1617 encryption->cryptid = mach_header.Swap(0);
1618 }
1619
1620 if (flag_e) {
1621 _assert(signature != NULL);
1622
1623 uint32_t data = mach_header.Swap(signature->dataoff);
1624
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);
1628
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);
1634 }
1635 }
1636
1637 if (flag_s) {
1638 _assert(signature != NULL);
1639
1640 uint32_t data = mach_header.Swap(signature->dataoff);
1641
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);
1645
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);
1650
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);
1653
1654 if (pages != 1)
1655 for (size_t i = 0; i != pages - 1; ++i)
1656 sha1(hashes[i], top + PageSize_ * i, PageSize_);
1657 if (pages != 0)
1658 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
1659 }
1660 }
1661 }
1662
1663 ++filei;
1664 } catch (const char *) {
1665 ++filee;
1666 ++filei;
1667 }
1668
1669 return filee;
1670 }