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