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