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