]> git.saurik.com Git - ldid.git/blob - ldid.cpp
UnionFolder (code for Impactor) should be in ldid.
[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 <iostream>
27 #include <memory>
28 #include <set>
29 #include <sstream>
30 #include <string>
31 #include <vector>
32
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <regex.h>
37 #include <stdbool.h>
38 #include <stdint.h>
39 #include <unistd.h>
40
41 #include <sys/mman.h>
42 #include <sys/stat.h>
43 #include <sys/types.h>
44
45 #include <openssl/err.h>
46 #include <openssl/pem.h>
47 #include <openssl/pkcs7.h>
48 #include <openssl/pkcs12.h>
49 #include <openssl/sha.h>
50
51 #include <plist/plist.h>
52
53 #include "ldid.hpp"
54
55 #define _assert___(line) \
56 #line
57 #define _assert__(line) \
58 _assert___(line)
59
60 #define _assert_(expr, format, ...) \
61 do if (!(expr)) { \
62 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
63 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
64 } while (false)
65
66 #define _assert(expr) \
67 _assert_(expr, "%s", #expr)
68
69 #define _syscall(expr, ...) [&] { for (;;) { \
70 auto _value(expr); \
71 if ((long) _value != -1) \
72 return _value; \
73 int error(errno); \
74 if (error == EINTR) \
75 continue; \
76 /* XXX: EINTR is included in this list to fix g++ */ \
77 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
78 if (error == success) \
79 return (decltype(expr)) -success; \
80 _assert_(false, "errno=%u", error); \
81 } }()
82
83 #define _trace() \
84 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
85
86 #define _not(type) \
87 ((type) ~ (type) 0)
88
89 #define _packed \
90 __attribute__((packed))
91
92 template <typename Type_>
93 struct Iterator_ {
94 typedef typename Type_::const_iterator Result;
95 };
96
97 #define _foreach(item, list) \
98 for (bool _stop(true); _stop; ) \
99 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
100 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
101 for (bool _suck(true); _suck; _suck = false) \
102 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
103
104 class _Scope {
105 };
106
107 template <typename Function_>
108 class Scope :
109 public _Scope
110 {
111 private:
112 Function_ function_;
113
114 public:
115 Scope(const Function_ &function) :
116 function_(function)
117 {
118 }
119
120 ~Scope() {
121 function_();
122 }
123 };
124
125 template <typename Function_>
126 Scope<Function_> _scope(const Function_ &function) {
127 return Scope<Function_>(function);
128 }
129
130 #define _scope__(counter, function) \
131 __attribute__((__unused__)) \
132 const _Scope &_scope ## counter(_scope([&]function))
133 #define _scope_(counter, function) \
134 _scope__(counter, function)
135 #define _scope(function) \
136 _scope_(__COUNTER__, function)
137
138 struct fat_header {
139 uint32_t magic;
140 uint32_t nfat_arch;
141 } _packed;
142
143 #define FAT_MAGIC 0xcafebabe
144 #define FAT_CIGAM 0xbebafeca
145
146 struct fat_arch {
147 uint32_t cputype;
148 uint32_t cpusubtype;
149 uint32_t offset;
150 uint32_t size;
151 uint32_t align;
152 } _packed;
153
154 struct mach_header {
155 uint32_t magic;
156 uint32_t cputype;
157 uint32_t cpusubtype;
158 uint32_t filetype;
159 uint32_t ncmds;
160 uint32_t sizeofcmds;
161 uint32_t flags;
162 } _packed;
163
164 #define MH_MAGIC 0xfeedface
165 #define MH_CIGAM 0xcefaedfe
166
167 #define MH_MAGIC_64 0xfeedfacf
168 #define MH_CIGAM_64 0xcffaedfe
169
170 #define MH_DYLDLINK 0x4
171
172 #define MH_OBJECT 0x1
173 #define MH_EXECUTE 0x2
174 #define MH_DYLIB 0x6
175 #define MH_BUNDLE 0x8
176 #define MH_DYLIB_STUB 0x9
177
178 struct load_command {
179 uint32_t cmd;
180 uint32_t cmdsize;
181 } _packed;
182
183 #define LC_REQ_DYLD uint32_t(0x80000000)
184
185 #define LC_SEGMENT uint32_t(0x01)
186 #define LC_SYMTAB uint32_t(0x02)
187 #define LC_DYSYMTAB uint32_t(0x0b)
188 #define LC_LOAD_DYLIB uint32_t(0x0c)
189 #define LC_ID_DYLIB uint32_t(0x0d)
190 #define LC_SEGMENT_64 uint32_t(0x19)
191 #define LC_UUID uint32_t(0x1b)
192 #define LC_CODE_SIGNATURE uint32_t(0x1d)
193 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
194 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
195 #define LC_ENCRYPTION_INFO uint32_t(0x21)
196 #define LC_DYLD_INFO uint32_t(0x22)
197 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
198 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
199
200 struct dylib {
201 uint32_t name;
202 uint32_t timestamp;
203 uint32_t current_version;
204 uint32_t compatibility_version;
205 } _packed;
206
207 struct dylib_command {
208 uint32_t cmd;
209 uint32_t cmdsize;
210 struct dylib dylib;
211 } _packed;
212
213 struct uuid_command {
214 uint32_t cmd;
215 uint32_t cmdsize;
216 uint8_t uuid[16];
217 } _packed;
218
219 struct symtab_command {
220 uint32_t cmd;
221 uint32_t cmdsize;
222 uint32_t symoff;
223 uint32_t nsyms;
224 uint32_t stroff;
225 uint32_t strsize;
226 } _packed;
227
228 struct dyld_info_command {
229 uint32_t cmd;
230 uint32_t cmdsize;
231 uint32_t rebase_off;
232 uint32_t rebase_size;
233 uint32_t bind_off;
234 uint32_t bind_size;
235 uint32_t weak_bind_off;
236 uint32_t weak_bind_size;
237 uint32_t lazy_bind_off;
238 uint32_t lazy_bind_size;
239 uint32_t export_off;
240 uint32_t export_size;
241 } _packed;
242
243 struct dysymtab_command {
244 uint32_t cmd;
245 uint32_t cmdsize;
246 uint32_t ilocalsym;
247 uint32_t nlocalsym;
248 uint32_t iextdefsym;
249 uint32_t nextdefsym;
250 uint32_t iundefsym;
251 uint32_t nundefsym;
252 uint32_t tocoff;
253 uint32_t ntoc;
254 uint32_t modtaboff;
255 uint32_t nmodtab;
256 uint32_t extrefsymoff;
257 uint32_t nextrefsyms;
258 uint32_t indirectsymoff;
259 uint32_t nindirectsyms;
260 uint32_t extreloff;
261 uint32_t nextrel;
262 uint32_t locreloff;
263 uint32_t nlocrel;
264 } _packed;
265
266 struct dylib_table_of_contents {
267 uint32_t symbol_index;
268 uint32_t module_index;
269 } _packed;
270
271 struct dylib_module {
272 uint32_t module_name;
273 uint32_t iextdefsym;
274 uint32_t nextdefsym;
275 uint32_t irefsym;
276 uint32_t nrefsym;
277 uint32_t ilocalsym;
278 uint32_t nlocalsym;
279 uint32_t iextrel;
280 uint32_t nextrel;
281 uint32_t iinit_iterm;
282 uint32_t ninit_nterm;
283 uint32_t objc_module_info_addr;
284 uint32_t objc_module_info_size;
285 } _packed;
286
287 struct dylib_reference {
288 uint32_t isym:24;
289 uint32_t flags:8;
290 } _packed;
291
292 struct relocation_info {
293 int32_t r_address;
294 uint32_t r_symbolnum:24;
295 uint32_t r_pcrel:1;
296 uint32_t r_length:2;
297 uint32_t r_extern:1;
298 uint32_t r_type:4;
299 } _packed;
300
301 struct nlist {
302 union {
303 char *n_name;
304 int32_t n_strx;
305 } n_un;
306
307 uint8_t n_type;
308 uint8_t n_sect;
309 uint8_t n_desc;
310 uint32_t n_value;
311 } _packed;
312
313 struct segment_command {
314 uint32_t cmd;
315 uint32_t cmdsize;
316 char segname[16];
317 uint32_t vmaddr;
318 uint32_t vmsize;
319 uint32_t fileoff;
320 uint32_t filesize;
321 uint32_t maxprot;
322 uint32_t initprot;
323 uint32_t nsects;
324 uint32_t flags;
325 } _packed;
326
327 struct segment_command_64 {
328 uint32_t cmd;
329 uint32_t cmdsize;
330 char segname[16];
331 uint64_t vmaddr;
332 uint64_t vmsize;
333 uint64_t fileoff;
334 uint64_t filesize;
335 uint32_t maxprot;
336 uint32_t initprot;
337 uint32_t nsects;
338 uint32_t flags;
339 } _packed;
340
341 struct section {
342 char sectname[16];
343 char segname[16];
344 uint32_t addr;
345 uint32_t size;
346 uint32_t offset;
347 uint32_t align;
348 uint32_t reloff;
349 uint32_t nreloc;
350 uint32_t flags;
351 uint32_t reserved1;
352 uint32_t reserved2;
353 } _packed;
354
355 struct section_64 {
356 char sectname[16];
357 char segname[16];
358 uint64_t addr;
359 uint64_t size;
360 uint32_t offset;
361 uint32_t align;
362 uint32_t reloff;
363 uint32_t nreloc;
364 uint32_t flags;
365 uint32_t reserved1;
366 uint32_t reserved2;
367 } _packed;
368
369 struct linkedit_data_command {
370 uint32_t cmd;
371 uint32_t cmdsize;
372 uint32_t dataoff;
373 uint32_t datasize;
374 } _packed;
375
376 struct encryption_info_command {
377 uint32_t cmd;
378 uint32_t cmdsize;
379 uint32_t cryptoff;
380 uint32_t cryptsize;
381 uint32_t cryptid;
382 } _packed;
383
384 #define BIND_OPCODE_MASK 0xf0
385 #define BIND_IMMEDIATE_MASK 0x0f
386 #define BIND_OPCODE_DONE 0x00
387 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
388 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
389 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
390 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
391 #define BIND_OPCODE_SET_TYPE_IMM 0x50
392 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
393 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
394 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
395 #define BIND_OPCODE_DO_BIND 0x90
396 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
397 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
398 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
399
400 inline void get(std::streambuf &stream, void *data, size_t size) {
401 _assert(stream.sgetn(static_cast<char *>(data), size) == size);
402 }
403
404 inline void put(std::streambuf &stream, const void *data, size_t size) {
405 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
406 }
407
408 inline void pad(std::streambuf &stream, size_t size) {
409 char padding[size];
410 memset(padding, 0, size);
411 put(stream, padding, size);
412 }
413
414 template <typename Type_>
415 Type_ Align(Type_ value, size_t align) {
416 value += align - 1;
417 value /= align;
418 value *= align;
419 return value;
420 }
421
422 static const uint8_t PageShift_(0x0c);
423 static const uint32_t PageSize_(1 << PageShift_);
424
425 static inline uint16_t Swap_(uint16_t value) {
426 return
427 ((value >> 8) & 0x00ff) |
428 ((value << 8) & 0xff00);
429 }
430
431 static inline uint32_t Swap_(uint32_t value) {
432 value = ((value >> 8) & 0x00ff00ff) |
433 ((value << 8) & 0xff00ff00);
434 value = ((value >> 16) & 0x0000ffff) |
435 ((value << 16) & 0xffff0000);
436 return value;
437 }
438
439 static inline uint64_t Swap_(uint64_t value) {
440 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
441 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
442 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
443 return value;
444 }
445
446 static inline int16_t Swap_(int16_t value) {
447 return Swap_(static_cast<uint16_t>(value));
448 }
449
450 static inline int32_t Swap_(int32_t value) {
451 return Swap_(static_cast<uint32_t>(value));
452 }
453
454 static inline int64_t Swap_(int64_t value) {
455 return Swap_(static_cast<uint64_t>(value));
456 }
457
458 static bool little_(true);
459
460 static inline uint16_t Swap(uint16_t value) {
461 return little_ ? Swap_(value) : value;
462 }
463
464 static inline uint32_t Swap(uint32_t value) {
465 return little_ ? Swap_(value) : value;
466 }
467
468 static inline uint64_t Swap(uint64_t value) {
469 return little_ ? Swap_(value) : value;
470 }
471
472 static inline int16_t Swap(int16_t value) {
473 return Swap(static_cast<uint16_t>(value));
474 }
475
476 static inline int32_t Swap(int32_t value) {
477 return Swap(static_cast<uint32_t>(value));
478 }
479
480 static inline int64_t Swap(int64_t value) {
481 return Swap(static_cast<uint64_t>(value));
482 }
483
484 template <typename Target_>
485 class Pointer;
486
487 class Swapped {
488 protected:
489 bool swapped_;
490
491 Swapped() :
492 swapped_(false)
493 {
494 }
495
496 public:
497 Swapped(bool swapped) :
498 swapped_(swapped)
499 {
500 }
501
502 template <typename Type_>
503 Type_ Swap(Type_ value) const {
504 return swapped_ ? Swap_(value) : value;
505 }
506 };
507
508 class Data :
509 public Swapped
510 {
511 private:
512 void *base_;
513 size_t size_;
514
515 public:
516 Data(void *base, size_t size) :
517 base_(base),
518 size_(size)
519 {
520 }
521
522 void *GetBase() const {
523 return base_;
524 }
525
526 size_t GetSize() const {
527 return size_;
528 }
529 };
530
531 class MachHeader :
532 public Data
533 {
534 private:
535 bool bits64_;
536
537 struct mach_header *mach_header_;
538 struct load_command *load_command_;
539
540 public:
541 MachHeader(void *base, size_t size) :
542 Data(base, size)
543 {
544 mach_header_ = (mach_header *) base;
545
546 switch (Swap(mach_header_->magic)) {
547 case MH_CIGAM:
548 swapped_ = !swapped_;
549 case MH_MAGIC:
550 bits64_ = false;
551 break;
552
553 case MH_CIGAM_64:
554 swapped_ = !swapped_;
555 case MH_MAGIC_64:
556 bits64_ = true;
557 break;
558
559 default:
560 _assert(false);
561 }
562
563 void *post = mach_header_ + 1;
564 if (bits64_)
565 post = (uint32_t *) post + 1;
566 load_command_ = (struct load_command *) post;
567
568 _assert(
569 Swap(mach_header_->filetype) == MH_EXECUTE ||
570 Swap(mach_header_->filetype) == MH_DYLIB ||
571 Swap(mach_header_->filetype) == MH_BUNDLE
572 );
573 }
574
575 bool Bits64() const {
576 return bits64_;
577 }
578
579 struct mach_header *operator ->() const {
580 return mach_header_;
581 }
582
583 operator struct mach_header *() const {
584 return mach_header_;
585 }
586
587 uint32_t GetCPUType() const {
588 return Swap(mach_header_->cputype);
589 }
590
591 uint32_t GetCPUSubtype() const {
592 return Swap(mach_header_->cpusubtype) & 0xff;
593 }
594
595 struct load_command *GetLoadCommand() const {
596 return load_command_;
597 }
598
599 std::vector<struct load_command *> GetLoadCommands() const {
600 std::vector<struct load_command *> load_commands;
601
602 struct load_command *load_command = load_command_;
603 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
604 load_commands.push_back(load_command);
605 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
606 }
607
608 return load_commands;
609 }
610
611 std::vector<segment_command *> GetSegments(const char *segment_name) const {
612 std::vector<struct segment_command *> segment_commands;
613
614 _foreach (load_command, GetLoadCommands()) {
615 if (Swap(load_command->cmd) == LC_SEGMENT) {
616 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
617 if (strncmp(segment_command->segname, segment_name, 16) == 0)
618 segment_commands.push_back(segment_command);
619 }
620 }
621
622 return segment_commands;
623 }
624
625 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) const {
626 std::vector<struct segment_command_64 *> segment_commands;
627
628 _foreach (load_command, GetLoadCommands()) {
629 if (Swap(load_command->cmd) == LC_SEGMENT_64) {
630 segment_command_64 *segment_command = reinterpret_cast<struct segment_command_64 *>(load_command);
631 if (strncmp(segment_command->segname, segment_name, 16) == 0)
632 segment_commands.push_back(segment_command);
633 }
634 }
635
636 return segment_commands;
637 }
638
639 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
640 std::vector<section *> sections;
641
642 _foreach (segment, GetSegments(segment_name)) {
643 section *section = (struct section *) (segment + 1);
644
645 uint32_t sect;
646 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
647 if (strncmp(section->sectname, section_name, 16) == 0)
648 sections.push_back(section);
649 ++section;
650 }
651 }
652
653 return sections;
654 }
655
656 template <typename Target_>
657 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
658 load_command *load_command = (struct load_command *) (mach_header_ + 1);
659 uint32_t cmd;
660
661 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
662 if (Swap(load_command->cmd) == LC_SEGMENT) {
663 segment_command *segment_command = (struct segment_command *) load_command;
664 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
665 goto next_command;
666
667 section *sections = (struct section *) (segment_command + 1);
668
669 uint32_t sect;
670 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
671 section *section = &sections[sect];
672 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
673 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
674 //printf("0x%.8x %s\n", address, segment_command->segname);
675 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
676 }
677 }
678 }
679
680 next_command:
681 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
682 }
683
684 return Pointer<Target_>(this);
685 }
686
687 template <typename Target_>
688 Pointer<Target_> GetOffset(uint32_t offset) {
689 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
690 }
691 };
692
693 class FatMachHeader :
694 public MachHeader
695 {
696 private:
697 fat_arch *fat_arch_;
698
699 public:
700 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
701 MachHeader(base, size),
702 fat_arch_(fat_arch)
703 {
704 }
705
706 fat_arch *GetFatArch() const {
707 return fat_arch_;
708 }
709 };
710
711 class FatHeader :
712 public Data
713 {
714 private:
715 fat_header *fat_header_;
716 std::vector<FatMachHeader> mach_headers_;
717
718 public:
719 FatHeader(void *base, size_t size) :
720 Data(base, size)
721 {
722 fat_header_ = reinterpret_cast<struct fat_header *>(base);
723
724 if (Swap(fat_header_->magic) == FAT_CIGAM) {
725 swapped_ = !swapped_;
726 goto fat;
727 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
728 fat_header_ = NULL;
729 mach_headers_.push_back(FatMachHeader(base, size, NULL));
730 } else fat: {
731 size_t fat_narch = Swap(fat_header_->nfat_arch);
732 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
733 size_t arch;
734 for (arch = 0; arch != fat_narch; ++arch) {
735 uint32_t arch_offset = Swap(fat_arch->offset);
736 uint32_t arch_size = Swap(fat_arch->size);
737 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
738 ++fat_arch;
739 }
740 }
741 }
742
743 std::vector<FatMachHeader> &GetMachHeaders() {
744 return mach_headers_;
745 }
746
747 bool IsFat() const {
748 return fat_header_ != NULL;
749 }
750
751 struct fat_header *operator ->() const {
752 return fat_header_;
753 }
754
755 operator struct fat_header *() const {
756 return fat_header_;
757 }
758 };
759
760 template <typename Target_>
761 class Pointer {
762 private:
763 const MachHeader *framework_;
764 const Target_ *pointer_;
765
766 public:
767 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
768 framework_(framework),
769 pointer_(pointer)
770 {
771 }
772
773 operator const Target_ *() const {
774 return pointer_;
775 }
776
777 const Target_ *operator ->() const {
778 return pointer_;
779 }
780
781 Pointer<Target_> &operator ++() {
782 ++pointer_;
783 return *this;
784 }
785
786 template <typename Value_>
787 Value_ Swap(Value_ value) {
788 return framework_->Swap(value);
789 }
790 };
791
792 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
793 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
794 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
795 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
796 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
797 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
798 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
799 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
800
801 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
802 #define CSSLOT_INFOSLOT uint32_t(0x00001)
803 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
804 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
805 #define CSSLOT_APPLICATION uint32_t(0x00004)
806 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
807
808 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
809
810 #define CS_HASHTYPE_SHA1 1
811
812 struct BlobIndex {
813 uint32_t type;
814 uint32_t offset;
815 } _packed;
816
817 struct Blob {
818 uint32_t magic;
819 uint32_t length;
820 } _packed;
821
822 struct SuperBlob {
823 struct Blob blob;
824 uint32_t count;
825 struct BlobIndex index[];
826 } _packed;
827
828 struct CodeDirectory {
829 uint32_t version;
830 uint32_t flags;
831 uint32_t hashOffset;
832 uint32_t identOffset;
833 uint32_t nSpecialSlots;
834 uint32_t nCodeSlots;
835 uint32_t codeLimit;
836 uint8_t hashSize;
837 uint8_t hashType;
838 uint8_t spare1;
839 uint8_t pageSize;
840 uint32_t spare2;
841 } _packed;
842
843 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
844
845 static void sha1(uint8_t *hash, const void *data, size_t size) {
846 SHA1(static_cast<const uint8_t *>(data), size, hash);
847 }
848
849 struct CodesignAllocation {
850 FatMachHeader mach_header_;
851 uint32_t offset_;
852 uint32_t size_;
853 uint32_t limit_;
854 uint32_t alloc_;
855 uint32_t align_;
856
857 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
858 mach_header_(mach_header),
859 offset_(offset),
860 size_(size),
861 limit_(limit),
862 alloc_(alloc),
863 align_(align)
864 {
865 }
866 };
867
868 class File {
869 private:
870 int file_;
871
872 public:
873 File() :
874 file_(-1)
875 {
876 }
877
878 ~File() {
879 if (file_ != -1)
880 _syscall(close(file_));
881 }
882
883 void open(const char *path, int flags) {
884 _assert(file_ == -1);
885 file_ = _syscall(::open(path, flags));
886 }
887
888 int file() const {
889 return file_;
890 }
891 };
892
893 class Map {
894 private:
895 File file_;
896 void *data_;
897 size_t size_;
898
899 void clear() {
900 if (data_ == NULL)
901 return;
902 _syscall(munmap(data_, size_));
903 data_ = NULL;
904 size_ = 0;
905 }
906
907 public:
908 Map() :
909 data_(NULL),
910 size_(0)
911 {
912 }
913
914 Map(const std::string &path, int oflag, int pflag, int mflag) :
915 Map()
916 {
917 open(path, oflag, pflag, mflag);
918 }
919
920 Map(const std::string &path, bool edit) :
921 Map()
922 {
923 open(path, edit);
924 }
925
926 ~Map() {
927 clear();
928 }
929
930 bool empty() const {
931 return data_ == NULL;
932 }
933
934 void open(const std::string &path, int oflag, int pflag, int mflag) {
935 clear();
936
937 file_.open(path.c_str(), oflag);
938 int file(file_.file());
939
940 struct stat stat;
941 _syscall(fstat(file, &stat));
942 size_ = stat.st_size;
943
944 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
945 }
946
947 void open(const std::string &path, bool edit) {
948 if (edit)
949 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
950 else
951 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
952 }
953
954 void *data() const {
955 return data_;
956 }
957
958 size_t size() const {
959 return size_;
960 }
961
962 operator std::string() const {
963 return std::string(static_cast<char *>(data_), size_);
964 }
965 };
966
967 namespace ldid {
968
969 static void Allocate(const 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) {
970 FatHeader source(const_cast<void *>(idata), isize);
971
972 size_t offset(0);
973 if (source.IsFat())
974 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
975
976 std::vector<CodesignAllocation> allocations;
977 _foreach (mach_header, source.GetMachHeaders()) {
978 struct linkedit_data_command *signature(NULL);
979 struct symtab_command *symtab(NULL);
980
981 _foreach (load_command, mach_header.GetLoadCommands()) {
982 uint32_t cmd(mach_header.Swap(load_command->cmd));
983 if (false);
984 else if (cmd == LC_CODE_SIGNATURE)
985 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
986 else if (cmd == LC_SYMTAB)
987 symtab = reinterpret_cast<struct symtab_command *>(load_command);
988 }
989
990 size_t size;
991 if (signature == NULL)
992 size = mach_header.GetSize();
993 else {
994 size = mach_header.Swap(signature->dataoff);
995 _assert(size <= mach_header.GetSize());
996 }
997
998 if (symtab != NULL) {
999 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
1000 _assert(end <= size);
1001 _assert(end >= size - 0x10);
1002 size = end;
1003 }
1004
1005 size_t alloc(allocate(size));
1006
1007 auto *fat_arch(mach_header.GetFatArch());
1008 uint32_t align(fat_arch == NULL ? 0 : source.Swap(fat_arch->align));
1009 offset = Align(offset, 1 << align);
1010
1011 uint32_t limit(size);
1012 if (alloc != 0)
1013 limit = Align(limit, 0x10);
1014
1015 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
1016 offset += size + alloc;
1017 offset = Align(offset, 0x10);
1018 }
1019
1020 size_t position(0);
1021
1022 if (source.IsFat()) {
1023 fat_header fat_header;
1024 fat_header.magic = Swap(FAT_MAGIC);
1025 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1026 put(output, &fat_header, sizeof(fat_header));
1027 position += sizeof(fat_header);
1028
1029 _foreach (allocation, allocations) {
1030 auto &mach_header(allocation.mach_header_);
1031
1032 fat_arch fat_arch;
1033 fat_arch.cputype = Swap(mach_header->cputype);
1034 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1035 fat_arch.offset = Swap(allocation.offset_);
1036 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1037 fat_arch.align = Swap(allocation.align_);
1038 put(output, &fat_arch, sizeof(fat_arch));
1039 position += sizeof(fat_arch);
1040 }
1041 }
1042
1043 _foreach (allocation, allocations) {
1044 auto &mach_header(allocation.mach_header_);
1045
1046 pad(output, allocation.offset_ - position);
1047 position = allocation.offset_;
1048
1049 std::vector<std::string> commands;
1050
1051 _foreach (load_command, mach_header.GetLoadCommands()) {
1052 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
1053
1054 switch (mach_header.Swap(load_command->cmd)) {
1055 case LC_CODE_SIGNATURE:
1056 continue;
1057 break;
1058
1059 case LC_SEGMENT: {
1060 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1061 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1062 break;
1063 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1064 segment_command->filesize = size;
1065 segment_command->vmsize = Align(size, PageSize_);
1066 } break;
1067
1068 case LC_SEGMENT_64: {
1069 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1070 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1071 break;
1072 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1073 segment_command->filesize = size;
1074 segment_command->vmsize = Align(size, PageSize_);
1075 } break;
1076 }
1077
1078 commands.push_back(copy);
1079 }
1080
1081 if (allocation.alloc_ != 0) {
1082 linkedit_data_command signature;
1083 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1084 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1085 signature.dataoff = mach_header.Swap(allocation.limit_);
1086 signature.datasize = mach_header.Swap(allocation.alloc_);
1087 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1088 }
1089
1090 size_t begin(position);
1091
1092 uint32_t after(0);
1093 _foreach(command, commands)
1094 after += command.size();
1095
1096 std::stringbuf altern;
1097
1098 struct mach_header header(*mach_header);
1099 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1100 header.sizeofcmds = mach_header.Swap(after);
1101 put(output, &header, sizeof(header));
1102 put(altern, &header, sizeof(header));
1103 position += sizeof(header);
1104
1105 if (mach_header.Bits64()) {
1106 auto pad(mach_header.Swap(uint32_t(0)));
1107 put(output, &pad, sizeof(pad));
1108 put(altern, &pad, sizeof(pad));
1109 position += sizeof(pad);
1110 }
1111
1112 _foreach(command, commands) {
1113 put(output, command.data(), command.size());
1114 put(altern, command.data(), command.size());
1115 position += command.size();
1116 }
1117
1118 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1119 if (before > after) {
1120 pad(output, before - after);
1121 pad(altern, before - after);
1122 position += before - after;
1123 }
1124
1125 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
1126
1127 std::string overlap(altern.str());
1128 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
1129
1130 put(output, top + (position - begin), allocation.size_ - (position - begin));
1131 position = begin + allocation.size_;
1132
1133 pad(output, allocation.limit_ - allocation.size_);
1134 position += allocation.limit_ - allocation.size_;
1135
1136 size_t saved(save(output, allocation.limit_, overlap, top));
1137 if (allocation.alloc_ > saved)
1138 pad(output, allocation.alloc_ - saved);
1139 position += allocation.alloc_;
1140 }
1141 }
1142
1143 }
1144
1145 typedef std::map<uint32_t, std::string> Blobs;
1146
1147 static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1148 auto value(buffer.str());
1149 std::swap(blobs[slot], value);
1150 }
1151
1152 static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1153 auto value(buffer.str());
1154 Blob blob;
1155 blob.magic = Swap(magic);
1156 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1157 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1158 std::swap(blobs[slot], value);
1159 }
1160
1161 static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1162 size_t total(0);
1163 _foreach (blob, blobs)
1164 total += blob.second.size();
1165
1166 struct SuperBlob super;
1167 super.blob.magic = Swap(magic);
1168 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1169 super.count = Swap(uint32_t(blobs.size()));
1170 put(output, &super, sizeof(super));
1171
1172 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1173
1174 _foreach (blob, blobs) {
1175 BlobIndex index;
1176 index.type = Swap(blob.first);
1177 index.offset = Swap(uint32_t(offset));
1178 put(output, &index, sizeof(index));
1179 offset += blob.second.size();
1180 }
1181
1182 _foreach (blob, blobs)
1183 put(output, blob.second.data(), blob.second.size());
1184
1185 return offset;
1186 }
1187
1188 class Buffer {
1189 private:
1190 BIO *bio_;
1191
1192 public:
1193 Buffer(BIO *bio) :
1194 bio_(bio)
1195 {
1196 _assert(bio_ != NULL);
1197 }
1198
1199 Buffer() :
1200 bio_(BIO_new(BIO_s_mem()))
1201 {
1202 }
1203
1204 Buffer(const char *data, size_t size) :
1205 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1206 {
1207 }
1208
1209 Buffer(const std::string &data) :
1210 Buffer(data.data(), data.size())
1211 {
1212 }
1213
1214 Buffer(PKCS7 *pkcs) :
1215 Buffer()
1216 {
1217 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1218 }
1219
1220 ~Buffer() {
1221 BIO_free_all(bio_);
1222 }
1223
1224 operator BIO *() const {
1225 return bio_;
1226 }
1227
1228 explicit operator std::string() const {
1229 char *data;
1230 auto size(BIO_get_mem_data(bio_, &data));
1231 return std::string(data, size);
1232 }
1233 };
1234
1235 class Stuff {
1236 private:
1237 PKCS12 *value_;
1238 EVP_PKEY *key_;
1239 X509 *cert_;
1240 STACK_OF(X509) *ca_;
1241
1242 public:
1243 Stuff(BIO *bio) :
1244 value_(d2i_PKCS12_bio(bio, NULL)),
1245 ca_(NULL)
1246 {
1247 _assert(value_ != NULL);
1248 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1249 _assert(key_ != NULL);
1250 _assert(cert_ != NULL);
1251 }
1252
1253 Stuff(const std::string &data) :
1254 Stuff(Buffer(data))
1255 {
1256 }
1257
1258 ~Stuff() {
1259 sk_X509_pop_free(ca_, X509_free);
1260 X509_free(cert_);
1261 EVP_PKEY_free(key_);
1262 PKCS12_free(value_);
1263 }
1264
1265 operator PKCS12 *() const {
1266 return value_;
1267 }
1268
1269 operator EVP_PKEY *() const {
1270 return key_;
1271 }
1272
1273 operator X509 *() const {
1274 return cert_;
1275 }
1276
1277 operator STACK_OF(X509) *() const {
1278 return ca_;
1279 }
1280 };
1281
1282 class Signature {
1283 private:
1284 PKCS7 *value_;
1285
1286 public:
1287 Signature(const Stuff &stuff, const Buffer &data) :
1288 value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
1289 {
1290 _assert(value_ != NULL);
1291 }
1292
1293 ~Signature() {
1294 PKCS7_free(value_);
1295 }
1296
1297 operator PKCS7 *() const {
1298 return value_;
1299 }
1300 };
1301
1302 class NullBuffer :
1303 public std::streambuf
1304 {
1305 public:
1306 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1307 return size;
1308 }
1309
1310 virtual int_type overflow(int_type next) {
1311 return next;
1312 }
1313 };
1314
1315 class HashBuffer :
1316 public std::streambuf
1317 {
1318 private:
1319 std::vector<char> &hash_;
1320 SHA_CTX context_;
1321
1322 public:
1323 HashBuffer(std::vector<char> &hash) :
1324 hash_(hash)
1325 {
1326 SHA1_Init(&context_);
1327 }
1328
1329 ~HashBuffer() {
1330 hash_.resize(SHA_DIGEST_LENGTH);
1331 SHA1_Final(reinterpret_cast<uint8_t *>(hash_.data()), &context_);
1332 }
1333
1334 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1335 SHA1_Update(&context_, data, size);
1336 return size;
1337 }
1338
1339 virtual int_type overflow(int_type next) {
1340 if (next == traits_type::eof())
1341 return sync();
1342 char value(next);
1343 xsputn(&value, 1);
1344 return next;
1345 }
1346 };
1347
1348 class HashProxy :
1349 public HashBuffer
1350 {
1351 private:
1352 std::streambuf &buffer_;
1353
1354 public:
1355 HashProxy(std::vector<char> &hash, std::streambuf &buffer) :
1356 HashBuffer(hash),
1357 buffer_(buffer)
1358 {
1359 }
1360
1361 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1362 _assert(HashBuffer::xsputn(data, size) == size);
1363 return buffer_.sputn(data, size);
1364 }
1365 };
1366
1367 static bool Starts(const std::string &lhs, const std::string &rhs) {
1368 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1369 }
1370
1371 class Split {
1372 public:
1373 std::string dir;
1374 std::string base;
1375
1376 Split(const std::string &path) {
1377 size_t slash(path.rfind('/'));
1378 if (slash == std::string::npos)
1379 base = path;
1380 else {
1381 dir = path.substr(0, slash + 1);
1382 base = path.substr(slash + 1);
1383 }
1384 }
1385 };
1386
1387 static void mkdir_p(const std::string &path) {
1388 if (path.empty())
1389 return;
1390 #ifdef __WIN32__
1391 if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
1392 return;
1393 #else
1394 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1395 return;
1396 #endif
1397 auto slash(path.rfind('/', path.size() - 1));
1398 if (slash == std::string::npos)
1399 return;
1400 mkdir_p(path.substr(0, slash));
1401 }
1402
1403 static std::string Temporary(std::filebuf &file, const Split &split) {
1404 std::string temp(split.dir + ".ldid." + split.base);
1405 mkdir_p(split.dir);
1406 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1407 return temp;
1408 }
1409
1410 static void Commit(const std::string &path, const std::string &temp) {
1411 struct stat info;
1412 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
1413 #ifndef __WIN32__
1414 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1415 #endif
1416 _syscall(chmod(temp.c_str(), info.st_mode));
1417 }
1418
1419 _syscall(rename(temp.c_str(), path.c_str()));
1420 }
1421
1422 namespace ldid {
1423
1424 void Sign(const void *idata, size_t isize, std::streambuf &output, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) {
1425 Allocate(idata, isize, output, fun([&](size_t size) -> size_t {
1426 size_t alloc(sizeof(struct SuperBlob));
1427
1428 uint32_t special(0);
1429
1430 special = std::max(special, CSSLOT_REQUIREMENTS);
1431 alloc += sizeof(struct BlobIndex);
1432 alloc += 0xc;
1433
1434 if (!entitlements.empty()) {
1435 special = std::max(special, CSSLOT_ENTITLEMENTS);
1436 alloc += sizeof(struct BlobIndex);
1437 alloc += sizeof(struct Blob);
1438 alloc += entitlements.size();
1439 }
1440
1441 special = std::max(special, CSSLOT_CODEDIRECTORY);
1442 alloc += sizeof(struct BlobIndex);
1443 alloc += sizeof(struct Blob);
1444 alloc += sizeof(struct CodeDirectory);
1445 alloc += identifier.size() + 1;
1446
1447 if (!key.empty()) {
1448 alloc += sizeof(struct BlobIndex);
1449 alloc += sizeof(struct Blob);
1450 // XXX: this is just a "sufficiently large number"
1451 alloc += 0x3000;
1452 }
1453
1454 _foreach (slot, slots)
1455 special = std::max(special, slot.first);
1456
1457 uint32_t normal((size + PageSize_ - 1) / PageSize_);
1458 alloc = Align(alloc + (special + normal) * SHA_DIGEST_LENGTH, 16);
1459 return alloc;
1460 }), fun([&](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1461 Blobs blobs;
1462
1463 if (true) {
1464 std::stringbuf data;
1465
1466 Blobs requirements;
1467 put(data, CSMAGIC_REQUIREMENTS, requirements);
1468
1469 insert(blobs, CSSLOT_REQUIREMENTS, data);
1470 }
1471
1472 if (!entitlements.empty()) {
1473 std::stringbuf data;
1474 put(data, entitlements.data(), entitlements.size());
1475 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
1476 }
1477
1478 if (true) {
1479 std::stringbuf data;
1480
1481 uint32_t special(0);
1482 _foreach (blob, blobs)
1483 special = std::max(special, blob.first);
1484 _foreach (slot, slots)
1485 special = std::max(special, slot.first);
1486 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
1487
1488 CodeDirectory directory;
1489 directory.version = Swap(uint32_t(0x00020001));
1490 directory.flags = Swap(uint32_t(0));
1491 directory.hashOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory) + identifier.size() + 1 + SHA_DIGEST_LENGTH * special));
1492 directory.identOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory)));
1493 directory.nSpecialSlots = Swap(special);
1494 directory.codeLimit = Swap(uint32_t(limit));
1495 directory.nCodeSlots = Swap(normal);
1496 directory.hashSize = SHA_DIGEST_LENGTH;
1497 directory.hashType = CS_HASHTYPE_SHA1;
1498 directory.spare1 = 0x00;
1499 directory.pageSize = PageShift_;
1500 directory.spare2 = Swap(uint32_t(0));
1501 put(data, &directory, sizeof(directory));
1502
1503 put(data, identifier.c_str(), identifier.size() + 1);
1504
1505 uint8_t storage[special + normal][SHA_DIGEST_LENGTH];
1506 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = storage + special;
1507
1508 memset(storage, 0, sizeof(*storage) * special);
1509
1510 _foreach (blob, blobs) {
1511 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1512 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
1513 }
1514
1515 _foreach (slot, slots) {
1516 _assert(sizeof(*hashes) == slot.second.size());
1517 memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
1518 }
1519
1520 if (normal != 1)
1521 for (size_t i = 0; i != normal - 1; ++i)
1522 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
1523 if (normal != 0)
1524 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
1525
1526 put(data, storage, sizeof(storage));
1527
1528 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
1529 }
1530
1531 if (!key.empty()) {
1532 std::stringbuf data;
1533 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1534
1535 Stuff stuff(key);
1536 Buffer bio(sign);
1537
1538 Signature signature(stuff, sign);
1539 Buffer result(signature);
1540 std::string value(result);
1541 put(data, value.data(), value.size());
1542
1543 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1544 }
1545
1546 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
1547 }));
1548 }
1549
1550 static void Unsign(void *idata, size_t isize, std::streambuf &output) {
1551 Allocate(idata, isize, output, fun([](size_t size) -> size_t {
1552 return 0;
1553 }), fun([](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1554 return 0;
1555 }));
1556 }
1557
1558 std::string DiskFolder::Path(const std::string &path) {
1559 return path_ + "/" + path;
1560 }
1561
1562 DiskFolder::DiskFolder(const std::string &path) :
1563 path_(path)
1564 {
1565 }
1566
1567 DiskFolder::~DiskFolder() {
1568 if (!std::uncaught_exception())
1569 for (const auto &commit : commit_)
1570 Commit(commit.first, commit.second);
1571 }
1572
1573 void DiskFolder::Find(const std::string &root, const std::string &base, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
1574 std::string path(Path(root) + base);
1575
1576 DIR *dir(opendir(path.c_str()));
1577 _assert(dir != NULL);
1578 _scope({ _syscall(closedir(dir)); });
1579
1580 while (auto child = readdir(dir)) {
1581 std::string name(child->d_name);
1582 if (name == "." || name == "..")
1583 continue;
1584 if (Starts(name, ".ldid."))
1585 continue;
1586
1587 bool directory;
1588
1589 #ifdef __WIN32__
1590 struct stat info;
1591 _syscall(stat(path.c_str(), &info));
1592 if (false);
1593 else if (S_ISDIR(info.st_mode))
1594 directory = true;
1595 else if (S_ISREG(info.st_mode))
1596 directory = false;
1597 else
1598 _assert_(false, "st_mode=%x", info.st_mode);
1599 #else
1600 switch (child->d_type) {
1601 case DT_DIR:
1602 directory = true;
1603 break;
1604 case DT_REG:
1605 directory = false;
1606 break;
1607 default:
1608 _assert_(false, "d_type=%u", child->d_type);
1609 }
1610 #endif
1611
1612 if (directory)
1613 Find(root, base + name + "/", code);
1614 else
1615 code(base + name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1616 std::string access(root + base + name);
1617 _assert_(Open(access, fun([&](std::streambuf &data) {
1618 NullBuffer save;
1619 code(data, save);
1620 })), "open(): %s", access.c_str());
1621 }));
1622 }
1623 }
1624
1625 void DiskFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1626 std::filebuf save;
1627 auto from(Path(path));
1628 commit_[from] = Temporary(save, from);
1629 code(save);
1630 }
1631
1632 bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1633 std::filebuf data;
1634 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
1635 if (result == NULL)
1636 return false;
1637 _assert(result == &data);
1638 code(data);
1639 return true;
1640 }
1641
1642 void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
1643 Find(path, "", code);
1644 }
1645
1646 SubFolder::SubFolder(Folder &parent, const std::string &path) :
1647 parent_(parent),
1648 path_(path)
1649 {
1650 }
1651
1652 void SubFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1653 return parent_.Save(path_ + path, code);
1654 }
1655
1656 bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1657 return parent_.Open(path_ + path, code);
1658 }
1659
1660 void SubFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1661 return parent_.Find(path_ + path, code);
1662 }
1663
1664 UnionFolder::UnionFolder(Folder &parent) :
1665 parent_(parent)
1666 {
1667 }
1668
1669 void UnionFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1670 return parent_.Save(path, code);
1671 }
1672
1673 bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1674 auto file(files_.find(path));
1675 if (file == files_.end())
1676 return parent_.Open(path, code);
1677
1678 auto &data(file->second);
1679 data.pubseekpos(0, std::ios::in);
1680 code(data);
1681 return true;
1682 }
1683
1684 void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1685 parent_.Find(path, fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &save) {
1686 if (files_.find(name) == files_.end())
1687 code(name, save);
1688 }));
1689
1690 for (auto &file : files_)
1691 code(file.first, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1692 parent_.Save(file.first, fun([&](std::streambuf &save) {
1693 file.second.pubseekpos(0, std::ios::in);
1694 code(file.second, save);
1695 }));
1696 }));
1697 }
1698
1699 static size_t copy(std::streambuf &source, std::streambuf &target) {
1700 size_t total(0);
1701 for (;;) {
1702 char data[4096];
1703 size_t writ(source.sgetn(data, sizeof(data)));
1704 if (writ == 0)
1705 break;
1706 _assert(target.sputn(data, writ) == writ);
1707 total += writ;
1708 }
1709 return total;
1710 }
1711
1712 static plist_t plist(const std::string &data) {
1713 plist_t plist(NULL);
1714 if (Starts(data, "bplist00"))
1715 plist_from_bin(data.data(), data.size(), &plist);
1716 else
1717 plist_from_xml(data.data(), data.size(), &plist);
1718 _assert(plist != NULL);
1719 return plist;
1720 }
1721
1722 static void plist_d(std::streambuf &buffer, const Functor<void (plist_t)> &code) {
1723 std::stringbuf data;
1724 copy(buffer, data);
1725 auto node(plist(data.str()));
1726 _scope({ plist_free(node); });
1727 _assert(plist_get_node_type(node) == PLIST_DICT);
1728 code(node);
1729 }
1730
1731 static std::string plist_s(plist_t node) {
1732 _assert(node != NULL);
1733 _assert(plist_get_node_type(node) == PLIST_STRING);
1734 char *data;
1735 plist_get_string_val(node, &data);
1736 _scope({ free(data); });
1737 return data;
1738 }
1739
1740 enum Mode {
1741 NoMode,
1742 OptionalMode,
1743 OmitMode,
1744 NestedMode,
1745 TopMode,
1746 };
1747
1748 class Expression {
1749 private:
1750 regex_t regex_;
1751
1752 public:
1753 Expression(const std::string &code) {
1754 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()");
1755 }
1756
1757 ~Expression() {
1758 regfree(&regex_);
1759 }
1760
1761 bool operator ()(const std::string &data) const {
1762 auto value(regexec(&regex_, data.c_str(), 0, NULL, 0));
1763 if (value == REG_NOMATCH)
1764 return false;
1765 _assert_(value == 0, "regexec()");
1766 return true;
1767 }
1768 };
1769
1770 struct Rule {
1771 unsigned weight_;
1772 Mode mode_;
1773 std::string code_;
1774
1775 mutable std::auto_ptr<Expression> regex_;
1776
1777 Rule(unsigned weight, Mode mode, const std::string &code) :
1778 weight_(weight),
1779 mode_(mode),
1780 code_(code)
1781 {
1782 }
1783
1784 Rule(const Rule &rhs) :
1785 weight_(rhs.weight_),
1786 mode_(rhs.mode_),
1787 code_(rhs.code_)
1788 {
1789 }
1790
1791 void Compile() const {
1792 regex_.reset(new Expression(code_));
1793 }
1794
1795 bool operator ()(const std::string &data) const {
1796 _assert(regex_.get() != NULL);
1797 return (*regex_)(data);
1798 }
1799
1800 bool operator <(const Rule &rhs) const {
1801 if (weight_ > rhs.weight_)
1802 return true;
1803 if (weight_ < rhs.weight_)
1804 return false;
1805 return mode_ > rhs.mode_;
1806 }
1807 };
1808
1809 struct RuleCode {
1810 bool operator ()(const Rule *lhs, const Rule *rhs) const {
1811 return lhs->code_ < rhs->code_;
1812 }
1813 };
1814
1815 std::string Bundle(const std::string &root, Folder &folder, const std::string &key, std::map<std::string, std::vector<char>> &remote) {
1816 std::string executable;
1817 std::string identifier;
1818
1819 static const std::string info("Info.plist");
1820
1821 _assert_(folder.Open(info, fun([&](std::streambuf &buffer) {
1822 plist_d(buffer, fun([&](plist_t node) {
1823 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
1824 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
1825 }));
1826 })), "open(): Info.plist");
1827
1828 std::map<std::string, std::multiset<Rule>> versions;
1829
1830 auto &rules1(versions[""]);
1831 auto &rules2(versions["2"]);
1832
1833 static const std::string signature("_CodeSignature/CodeResources");
1834
1835 folder.Open(signature, fun([&](std::streambuf &buffer) {
1836 plist_d(buffer, fun([&](plist_t node) {
1837 // XXX: maybe attempt to preserve existing rules
1838 }));
1839 }));
1840
1841 if (true) {
1842 rules1.insert(Rule{1, NoMode, "^"});
1843 rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1844 rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1845 rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1846 rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1847 rules1.insert(Rule{1, NoMode, "^version.plist$"});
1848 }
1849
1850 if (true) {
1851 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
1852 rules2.insert(Rule{20, NoMode, "^"});
1853 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
1854 rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1855 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1856 rules2.insert(Rule{1, NoMode, "^.*"});
1857 rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1858 rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1859 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
1860 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
1861 rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1862 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
1863 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
1864 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
1865 }
1866
1867 std::map<std::string, std::vector<char>> local;
1868
1869 static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1870
1871 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1872 if (!nested(name))
1873 return;
1874 auto bundle(root + Split(name).dir);
1875 SubFolder subfolder(folder, bundle);
1876 Bundle(bundle, subfolder, key, local);
1877 }));
1878
1879 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1880 if (name == executable || name == signature)
1881 return;
1882
1883 auto &hash(local[name]);
1884 if (!hash.empty())
1885 return;
1886
1887 code(fun([&](std::streambuf &data, std::streambuf &save) {
1888 HashProxy proxy(hash, save);
1889 copy(data, proxy);
1890 }));
1891
1892 _assert(hash.size() == SHA_DIGEST_LENGTH);
1893 }));
1894
1895 auto plist(plist_new_dict());
1896 _scope({ plist_free(plist); });
1897
1898 for (const auto &version : versions) {
1899 auto files(plist_new_dict());
1900 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
1901
1902 for (const auto &rule : version.second)
1903 rule.Compile();
1904
1905 for (const auto &hash : local)
1906 for (const auto &rule : version.second)
1907 if (rule(hash.first)) {
1908 if (rule.mode_ == NoMode)
1909 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(hash.second.data(), hash.second.size()));
1910 else if (rule.mode_ == OptionalMode) {
1911 auto entry(plist_new_dict());
1912 plist_dict_set_item(entry, "hash", plist_new_data(hash.second.data(), hash.second.size()));
1913 plist_dict_set_item(entry, "optional", plist_new_bool(true));
1914 plist_dict_set_item(files, hash.first.c_str(), entry);
1915 }
1916
1917 break;
1918 }
1919 }
1920
1921 for (const auto &version : versions) {
1922 auto rules(plist_new_dict());
1923 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
1924
1925 std::multiset<const Rule *, RuleCode> ordered;
1926 for (const auto &rule : version.second)
1927 ordered.insert(&rule);
1928
1929 for (const auto &rule : ordered)
1930 if (rule->weight_ == 1 && rule->mode_ == NoMode)
1931 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
1932 else {
1933 auto entry(plist_new_dict());
1934 plist_dict_set_item(rules, rule->code_.c_str(), entry);
1935
1936 switch (rule->mode_) {
1937 case NoMode:
1938 break;
1939 case OmitMode:
1940 plist_dict_set_item(entry, "omit", plist_new_bool(true));
1941 break;
1942 case OptionalMode:
1943 plist_dict_set_item(entry, "optional", plist_new_bool(true));
1944 break;
1945 case NestedMode:
1946 plist_dict_set_item(entry, "nested", plist_new_bool(true));
1947 break;
1948 case TopMode:
1949 plist_dict_set_item(entry, "top", plist_new_bool(true));
1950 break;
1951 }
1952
1953 if (rule->weight_ >= 10000)
1954 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
1955 else if (rule->weight_ != 1)
1956 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
1957 }
1958 }
1959
1960 folder.Save(signature, fun([&](std::streambuf &save) {
1961 HashProxy proxy(local[signature], save);
1962 char *xml(NULL);
1963 uint32_t size;
1964 plist_to_xml(plist, &xml, &size);
1965 _scope({ free(xml); });
1966 put(proxy, xml, size);
1967 }));
1968
1969 folder.Open(executable, fun([&](std::streambuf &buffer) {
1970 // XXX: this is a miserable fail
1971 std::stringbuf temp;
1972 copy(buffer, temp);
1973 auto data(temp.str());
1974
1975 folder.Save(executable, fun([&](std::streambuf &save) {
1976 Slots slots;
1977 slots[1] = local.at(info);
1978 slots[3] = local.at(signature);
1979
1980 HashProxy proxy(local[executable], save);
1981 Sign(data.data(), data.size(), proxy, identifier, "", key, slots);
1982 }));
1983 }));
1984
1985 for (const auto &hash : local)
1986 remote[root + hash.first] = hash.second;
1987
1988 return executable;
1989 }
1990
1991 }
1992
1993 int main(int argc, char *argv[]) {
1994 OpenSSL_add_all_algorithms();
1995
1996 union {
1997 uint16_t word;
1998 uint8_t byte[2];
1999 } endian = {1};
2000
2001 little_ = endian.byte[0];
2002
2003 bool flag_r(false);
2004 bool flag_e(false);
2005
2006 bool flag_T(false);
2007
2008 bool flag_S(false);
2009 bool flag_s(false);
2010
2011 bool flag_D(false);
2012
2013 bool flag_A(false);
2014 bool flag_a(false);
2015
2016 uint32_t flag_CPUType(_not(uint32_t));
2017 uint32_t flag_CPUSubtype(_not(uint32_t));
2018
2019 const char *flag_I(NULL);
2020
2021 bool timeh(false);
2022 uint32_t timev(0);
2023
2024 Map entitlements;
2025 Map key;
2026 ldid::Slots slots;
2027
2028 std::vector<std::string> files;
2029
2030 if (argc == 1) {
2031 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
2032 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
2033 fprintf(stderr, " %s -S cat\n", argv[0]);
2034 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
2035 exit(0);
2036 }
2037
2038 for (int argi(1); argi != argc; ++argi)
2039 if (argv[argi][0] != '-')
2040 files.push_back(argv[argi]);
2041 else switch (argv[argi][1]) {
2042 case 'r':
2043 _assert(!flag_s);
2044 _assert(!flag_S);
2045 flag_r = true;
2046 break;
2047
2048 case 'e': flag_e = true; break;
2049
2050 case 'E': {
2051 const char *slot = argv[argi] + 2;
2052 const char *colon = strchr(slot, ':');
2053 _assert(colon != NULL);
2054 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
2055 char *arge;
2056 unsigned number(strtoul(slot, &arge, 0));
2057 _assert(arge == colon);
2058 std::vector<char> &hash(slots[number]);
2059 hash.resize(SHA_DIGEST_LENGTH);
2060 sha1(reinterpret_cast<uint8_t *>(hash.data()), file.data(), file.size());
2061 } break;
2062
2063 case 'D': flag_D = true; break;
2064
2065 case 'a': flag_a = true; break;
2066
2067 case 'A':
2068 _assert(!flag_A);
2069 flag_A = true;
2070 if (argv[argi][2] != '\0') {
2071 const char *cpu = argv[argi] + 2;
2072 const char *colon = strchr(cpu, ':');
2073 _assert(colon != NULL);
2074 char *arge;
2075 flag_CPUType = strtoul(cpu, &arge, 0);
2076 _assert(arge == colon);
2077 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2078 _assert(arge == argv[argi] + strlen(argv[argi]));
2079 }
2080 break;
2081
2082 case 's':
2083 _assert(!flag_r);
2084 _assert(!flag_S);
2085 flag_s = true;
2086 break;
2087
2088 case 'S':
2089 _assert(!flag_r);
2090 _assert(!flag_s);
2091 flag_S = true;
2092 if (argv[argi][2] != '\0') {
2093 const char *xml = argv[argi] + 2;
2094 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2095 }
2096 break;
2097
2098 case 'K':
2099 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
2100 break;
2101
2102 case 'T': {
2103 flag_T = true;
2104 if (argv[argi][2] == '-')
2105 timeh = true;
2106 else {
2107 char *arge;
2108 timev = strtoul(argv[argi] + 2, &arge, 0);
2109 _assert(arge == argv[argi] + strlen(argv[argi]));
2110 }
2111 } break;
2112
2113 case 'I': {
2114 flag_I = argv[argi] + 2;
2115 } break;
2116
2117 default:
2118 goto usage;
2119 break;
2120 }
2121
2122 _assert(flag_S || key.empty());
2123 _assert(flag_S || flag_I == NULL);
2124
2125 if (files.empty()) usage: {
2126 exit(0);
2127 }
2128
2129 size_t filei(0), filee(0);
2130 _foreach (file, files) try {
2131 std::string path(file);
2132
2133 struct stat info;
2134 _syscall(stat(path.c_str(), &info));
2135
2136 if (S_ISDIR(info.st_mode)) {
2137 _assert(!flag_r);
2138 ldid::DiskFolder folder(path);
2139 std::map<std::string, std::vector<char>> hashes;
2140 path += "/" + Bundle("", folder, key, hashes);
2141 } else if (flag_S || flag_r) {
2142 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
2143
2144 std::filebuf output;
2145 Split split(path);
2146 auto temp(Temporary(output, split));
2147
2148 if (flag_r)
2149 ldid::Unsign(input.data(), input.size(), output);
2150 else {
2151 std::string identifier(flag_I ?: split.base.c_str());
2152 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
2153 }
2154
2155 Commit(path, temp);
2156 }
2157
2158 Map mapping(path, flag_T || flag_s);
2159 FatHeader fat_header(mapping.data(), mapping.size());
2160
2161 _foreach (mach_header, fat_header.GetMachHeaders()) {
2162 struct linkedit_data_command *signature(NULL);
2163 struct encryption_info_command *encryption(NULL);
2164
2165 if (flag_A) {
2166 if (mach_header.GetCPUType() != flag_CPUType)
2167 continue;
2168 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2169 continue;
2170 }
2171
2172 if (flag_a)
2173 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2174
2175 _foreach (load_command, mach_header.GetLoadCommands()) {
2176 uint32_t cmd(mach_header.Swap(load_command->cmd));
2177
2178 if (false);
2179 else if (cmd == LC_CODE_SIGNATURE)
2180 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
2181 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
2182 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
2183 else if (cmd == LC_ID_DYLIB) {
2184 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2185
2186 if (flag_T) {
2187 uint32_t timed;
2188
2189 if (!timeh)
2190 timed = timev;
2191 else {
2192 dylib_command->dylib.timestamp = 0;
2193 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2194 }
2195
2196 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2197 }
2198 }
2199 }
2200
2201 if (flag_D) {
2202 _assert(encryption != NULL);
2203 encryption->cryptid = mach_header.Swap(0);
2204 }
2205
2206 if (flag_e) {
2207 _assert(signature != NULL);
2208
2209 uint32_t data = mach_header.Swap(signature->dataoff);
2210
2211 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2212 uint8_t *blob = top + data;
2213 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2214
2215 for (size_t index(0); index != Swap(super->count); ++index)
2216 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2217 uint32_t begin = Swap(super->index[index].offset);
2218 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
2219 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
2220 }
2221 }
2222
2223 if (flag_s) {
2224 _assert(signature != NULL);
2225
2226 uint32_t data = mach_header.Swap(signature->dataoff);
2227
2228 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2229 uint8_t *blob = top + data;
2230 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2231
2232 for (size_t index(0); index != Swap(super->count); ++index)
2233 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2234 uint32_t begin = Swap(super->index[index].offset);
2235 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
2236
2237 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
2238 uint32_t pages = Swap(directory->nCodeSlots);
2239
2240 if (pages != 1)
2241 for (size_t i = 0; i != pages - 1; ++i)
2242 sha1(hashes[i], top + PageSize_ * i, PageSize_);
2243 if (pages != 0)
2244 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
2245 }
2246 }
2247 }
2248
2249 ++filei;
2250 } catch (const char *) {
2251 ++filee;
2252 ++filei;
2253 }
2254
2255 return filee;
2256 }