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