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