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