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