]> git.saurik.com Git - ldid.git/blob - ldid.cpp
3411e599393651406dfe1a801ae5de4bcfd9f9ca
[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<char *>(ASN1_STRING_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 // XXX: use nullbuf
2507 std::stringbuf save;
2508 code(save);
2509 } else {
2510 std::filebuf save;
2511 auto from(Path(path));
2512 commit_[from] = Temporary(save, from);
2513 code(save);
2514 }
2515 }
2516
2517 bool DiskFolder::Look(const std::string &path) const {
2518 return _syscall(access(Path(path).c_str(), R_OK), ENOENT) == 0;
2519 }
2520
2521 void DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2522 std::filebuf data;
2523 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
2524 _assert_(result == &data, "DiskFolder::Open(%s)", Path(path).c_str());
2525
2526 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2527 data.pubseekpos(0, std::ios::in);
2528 code(data, length, NULL);
2529 }
2530
2531 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 {
2532 Find(path, "", code, link);
2533 }
2534 #endif
2535
2536 SubFolder::SubFolder(Folder &parent, const std::string &path) :
2537 parent_(parent),
2538 path_(path)
2539 {
2540 _assert_(path_.size() == 0 || path_[path_.size() - 1] == '/', "missing / on %s", path_.c_str());
2541 }
2542
2543 std::string SubFolder::Path(const std::string &path) const {
2544 return path_ + path;
2545 }
2546
2547 void SubFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2548 return parent_.Save(Path(path), edit, flag, code);
2549 }
2550
2551 bool SubFolder::Look(const std::string &path) const {
2552 return parent_.Look(Path(path));
2553 }
2554
2555 void SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2556 return parent_.Open(Path(path), code);
2557 }
2558
2559 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 {
2560 return parent_.Find(Path(path), code, link);
2561 }
2562
2563 std::string UnionFolder::Map(const std::string &path) const {
2564 auto remap(remaps_.find(path));
2565 if (remap == remaps_.end())
2566 return path;
2567 return remap->second;
2568 }
2569
2570 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 {
2571 if (file.size() >= path.size() && file.substr(0, path.size()) == path)
2572 code(file.substr(path.size()));
2573 }
2574
2575 UnionFolder::UnionFolder(Folder &parent) :
2576 parent_(parent)
2577 {
2578 }
2579
2580 void UnionFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2581 return parent_.Save(Map(path), edit, flag, code);
2582 }
2583
2584 bool UnionFolder::Look(const std::string &path) const {
2585 auto file(resets_.find(path));
2586 if (file != resets_.end())
2587 return true;
2588 return parent_.Look(Map(path));
2589 }
2590
2591 void UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2592 auto file(resets_.find(path));
2593 if (file == resets_.end())
2594 return parent_.Open(Map(path), code);
2595 auto &entry(file->second);
2596
2597 auto &data(*entry.data_);
2598 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2599 data.pubseekpos(0, std::ios::in);
2600 code(data, length, entry.flag_);
2601 }
2602
2603 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 {
2604 for (auto &reset : resets_)
2605 Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2606 auto &entry(reset.second);
2607 auto &data(*entry.data_);
2608 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2609 data.pubseekpos(0, std::ios::in);
2610 code(data, length, entry.flag_);
2611 }));
2612
2613 for (auto &remap : remaps_)
2614 Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2615 parent_.Open(remap.second, fun([&](std::streambuf &data, size_t length, const void *flag) {
2616 code(data, length, flag);
2617 }));
2618 }));
2619
2620 parent_.Find(path, fun([&](const std::string &name) {
2621 if (deletes_.find(path + name) == deletes_.end())
2622 code(name);
2623 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2624 if (deletes_.find(path + name) == deletes_.end())
2625 link(name, read);
2626 }));
2627 }
2628
2629 #ifndef LDID_NOTOOLS
2630 static void copy(std::streambuf &source, std::streambuf &target, size_t length, const Progress &progress) {
2631 progress(0);
2632 size_t total(0);
2633 for (;;) {
2634 char data[4096 * 4];
2635 size_t writ(source.sgetn(data, sizeof(data)));
2636 if (writ == 0)
2637 break;
2638 _assert(target.sputn(data, writ) == writ);
2639 total += writ;
2640 progress(double(total) / length);
2641 }
2642 }
2643
2644 #ifndef LDID_NOPLIST
2645 static plist_t plist(const std::string &data) {
2646 if (data.empty())
2647 return plist_new_dict();
2648 plist_t plist(NULL);
2649 if (Starts(data, "bplist00"))
2650 plist_from_bin(data.data(), data.size(), &plist);
2651 else
2652 plist_from_xml(data.data(), data.size(), &plist);
2653 _assert(plist != NULL);
2654 return plist;
2655 }
2656
2657 static void plist_d(std::streambuf &buffer, size_t length, const Functor<void (plist_t)> &code) {
2658 std::stringbuf data;
2659 copy(buffer, data, length, dummy_);
2660 auto node(plist(data.str()));
2661 _scope({ plist_free(node); });
2662 _assert(plist_get_node_type(node) == PLIST_DICT);
2663 code(node);
2664 }
2665
2666 static std::string plist_s(plist_t node) {
2667 _assert(node != NULL);
2668 _assert(plist_get_node_type(node) == PLIST_STRING);
2669 char *data;
2670 plist_get_string_val(node, &data);
2671 _scope({ free(data); });
2672 return data;
2673 }
2674 #endif
2675
2676 enum Mode {
2677 NoMode,
2678 OptionalMode,
2679 OmitMode,
2680 NestedMode,
2681 TopMode,
2682 };
2683
2684 class Expression {
2685 private:
2686 regex_t regex_;
2687 std::vector<std::string> matches_;
2688
2689 public:
2690 Expression(const std::string &code) {
2691 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED) == 0, "regcomp()");
2692 matches_.resize(regex_.re_nsub + 1);
2693 }
2694
2695 ~Expression() {
2696 regfree(&regex_);
2697 }
2698
2699 bool operator ()(const std::string &data) {
2700 regmatch_t matches[matches_.size()];
2701 auto value(regexec(&regex_, data.c_str(), matches_.size(), matches, 0));
2702 if (value == REG_NOMATCH)
2703 return false;
2704 _assert_(value == 0, "regexec()");
2705 for (size_t i(0); i != matches_.size(); ++i)
2706 matches_[i].assign(data.data() + matches[i].rm_so, matches[i].rm_eo - matches[i].rm_so);
2707 return true;
2708 }
2709
2710 const std::string &operator [](size_t index) const {
2711 return matches_[index];
2712 }
2713 };
2714
2715 struct Rule {
2716 unsigned weight_;
2717 Mode mode_;
2718 std::string code_;
2719
2720 mutable std::auto_ptr<Expression> regex_;
2721
2722 Rule(unsigned weight, Mode mode, const std::string &code) :
2723 weight_(weight),
2724 mode_(mode),
2725 code_(code)
2726 {
2727 }
2728
2729 Rule(const Rule &rhs) :
2730 weight_(rhs.weight_),
2731 mode_(rhs.mode_),
2732 code_(rhs.code_)
2733 {
2734 }
2735
2736 void Compile() const {
2737 regex_.reset(new Expression(code_));
2738 }
2739
2740 bool operator ()(const std::string &data) const {
2741 _assert(regex_.get() != NULL);
2742 return (*regex_)(data);
2743 }
2744
2745 bool operator <(const Rule &rhs) const {
2746 if (weight_ > rhs.weight_)
2747 return true;
2748 if (weight_ < rhs.weight_)
2749 return false;
2750 return mode_ > rhs.mode_;
2751 }
2752 };
2753
2754 struct RuleCode {
2755 bool operator ()(const Rule *lhs, const Rule *rhs) const {
2756 return lhs->code_ < rhs->code_;
2757 }
2758 };
2759
2760 #ifndef LDID_NOPLIST
2761 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) {
2762 // XXX: this is a miserable fail
2763 std::stringbuf temp;
2764 put(temp, prefix, size);
2765 copy(buffer, temp, length - size, progress);
2766 // XXX: this is a stupid hack
2767 pad(temp, 0x10 - (length & 0xf));
2768 auto data(temp.str());
2769
2770 HashProxy proxy(hash, save);
2771 return Sign(data.data(), data.size(), proxy, identifier, entitlements, merge, requirements, key, slots, flags, platform, progress);
2772 }
2773
2774 struct State {
2775 std::map<std::string, Hash> files;
2776 std::map<std::string, std::string> links;
2777
2778 void Merge(const std::string &root, const State &state) {
2779 for (const auto &entry : state.files)
2780 files[root + entry.first] = entry.second;
2781 for (const auto &entry : state.links)
2782 links[root + entry.first] = entry.second;
2783 }
2784 };
2785
2786 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) {
2787 std::string executable;
2788 std::string identifier;
2789
2790 bool mac(false);
2791
2792 std::string info("Info.plist");
2793
2794 SubFolder folder(parent, [&]() {
2795 if (parent.Look(info))
2796 return "";
2797 mac = true;
2798 if (false);
2799 else if (parent.Look("Contents/" + info))
2800 return "Contents/";
2801 else if (parent.Look("Resources/" + info)) {
2802 info = "Resources/" + info;
2803 return "";
2804 } else _assert_(false, "cannot find Info.plist");
2805 }());
2806
2807 folder.Open(info, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2808 plist_d(buffer, length, fun([&](plist_t node) {
2809 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
2810 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
2811 }));
2812 }));
2813
2814 if (mac && info == "Info.plist")
2815 executable = "MacOS/" + executable;
2816
2817 progress(root + "*");
2818
2819 std::string entitlements;
2820 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2821 // XXX: this is a miserable fail
2822 std::stringbuf temp;
2823 copy(buffer, temp, length, progress);
2824 // XXX: this is a stupid hack
2825 pad(temp, 0x10 - (length & 0xf));
2826 auto data(temp.str());
2827 entitlements = alter(root, Analyze(data.data(), data.size()));
2828 }));
2829
2830 static const std::string directory("_CodeSignature/");
2831 static const std::string signature(directory + "CodeResources");
2832
2833 std::map<std::string, std::multiset<Rule>> versions;
2834
2835 auto &rules1(versions[""]);
2836 auto &rules2(versions["2"]);
2837
2838 const std::string resources(mac ? "Resources/" : "");
2839
2840 if (true) {
2841 rules1.insert(Rule{1, NoMode, "^" + (resources == "" ? ".*" : resources)});
2842 rules1.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2843 rules1.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
2844 rules1.insert(Rule{1010, NoMode, "^" + resources + "Base\\.lproj/"});
2845 rules1.insert(Rule{1, NoMode, "^version.plist$"});
2846 }
2847
2848 if (true) {
2849 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
2850 if (mac) rules2.insert(Rule{20, NoMode, "^" + resources});
2851 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
2852 if (mac) rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2853 rules2.insert(Rule{1, NoMode, "^.*"});
2854 rules2.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2855 rules2.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
2856 if (!mac) rules2.insert(Rule{1010, NoMode, "^Base\\.lproj/"});
2857 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
2858 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
2859 if (mac) rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
2860 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
2861 if (mac) rules2.insert(Rule{1010, NoMode, "^" + resources + "Base\\.lproj/"});
2862 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
2863 }
2864
2865 State local;
2866
2867 std::string failure(mac ? "Contents/|Versions/[^/]*/Resources/" : "");
2868 Expression nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure + ")Info\\.plist$");
2869 std::map<std::string, Bundle> bundles;
2870
2871 folder.Find("", fun([&](const std::string &name) {
2872 if (!nested(name))
2873 return;
2874 auto bundle(root + Split(name).dir);
2875 if (mac) {
2876 _assert(!bundle.empty());
2877 bundle = Split(bundle.substr(0, bundle.size() - 1)).dir;
2878 }
2879 SubFolder subfolder(folder, bundle);
2880
2881 bundles[nested[1]] = Sign(bundle, subfolder, key, local, "", Starts(name, "PlugIns/") ? alter :
2882 static_cast<const Functor<std::string (const std::string &, const std::string &)> &>(fun([&](const std::string &, const std::string &) -> std::string { return entitlements; }))
2883 , progress);
2884 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2885 }));
2886
2887 std::set<std::string> excludes;
2888
2889 auto exclude([&](const std::string &name) {
2890 // BundleDiskRep::adjustResources -> builder.addExclusion
2891 if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
2892 return true;
2893
2894 for (const auto &bundle : bundles)
2895 if (Starts(name, bundle.first + "/")) {
2896 excludes.insert(name);
2897 return true;
2898 }
2899
2900 return false;
2901 });
2902
2903 folder.Find("", fun([&](const std::string &name) {
2904 if (exclude(name))
2905 return;
2906
2907 if (local.files.find(name) != local.files.end())
2908 return;
2909 auto &hash(local.files[name]);
2910
2911 folder.Open(name, fun([&](std::streambuf &data, size_t length, const void *flag) {
2912 progress(root + name);
2913
2914 union {
2915 struct {
2916 uint32_t magic;
2917 uint32_t count;
2918 };
2919
2920 uint8_t bytes[8];
2921 } header;
2922
2923 auto size(most(data, &header.bytes, sizeof(header.bytes)));
2924
2925 if (name != "_WatchKitStub/WK" && size == sizeof(header.bytes))
2926 switch (Swap(header.magic)) {
2927 case FAT_MAGIC:
2928 // Java class file format
2929 if (Swap(header.count) >= 40)
2930 break;
2931 case FAT_CIGAM:
2932 case MH_MAGIC: case MH_MAGIC_64:
2933 case MH_CIGAM: case MH_CIGAM_64:
2934 folder.Save(name, true, flag, fun([&](std::streambuf &save) {
2935 Slots slots;
2936 Sign(header.bytes, size, data, hash, save, identifier, "", false, "", key, slots, length, 0, false, Progression(progress, root + name));
2937 }));
2938 return;
2939 }
2940
2941 folder.Save(name, false, flag, fun([&](std::streambuf &save) {
2942 HashProxy proxy(hash, save);
2943 put(proxy, header.bytes, size);
2944 copy(data, proxy, length - size, progress);
2945 }));
2946 }));
2947 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2948 if (exclude(name))
2949 return;
2950
2951 local.links[name] = read();
2952 }));
2953
2954 auto plist(plist_new_dict());
2955 _scope({ plist_free(plist); });
2956
2957 for (const auto &version : versions) {
2958 auto files(plist_new_dict());
2959 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
2960
2961 for (const auto &rule : version.second)
2962 rule.Compile();
2963
2964 bool old(&version.second == &rules1);
2965
2966 for (const auto &hash : local.files)
2967 for (const auto &rule : version.second)
2968 if (rule(hash.first)) {
2969 if (!old && mac && excludes.find(hash.first) != excludes.end());
2970 else if (old && rule.mode_ == NoMode)
2971 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
2972 else if (rule.mode_ != OmitMode) {
2973 auto entry(plist_new_dict());
2974 plist_dict_set_item(entry, "hash", plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
2975 if (!old)
2976 plist_dict_set_item(entry, "hash2", plist_new_data(reinterpret_cast<const char *>(hash.second.sha256_), sizeof(hash.second.sha256_)));
2977 if (rule.mode_ == OptionalMode)
2978 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2979 plist_dict_set_item(files, hash.first.c_str(), entry);
2980 }
2981
2982 break;
2983 }
2984
2985 if (!old)
2986 for (const auto &link : local.links)
2987 for (const auto &rule : version.second)
2988 if (rule(link.first)) {
2989 if (rule.mode_ != OmitMode) {
2990 auto entry(plist_new_dict());
2991 plist_dict_set_item(entry, "symlink", plist_new_string(link.second.c_str()));
2992 if (rule.mode_ == OptionalMode)
2993 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2994 plist_dict_set_item(files, link.first.c_str(), entry);
2995 }
2996
2997 break;
2998 }
2999
3000 if (!old && mac)
3001 for (const auto &bundle : bundles) {
3002 auto entry(plist_new_dict());
3003 plist_dict_set_item(entry, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle.second.hash.sha256_), sizeof(bundle.second.hash.sha256_)));
3004 plist_dict_set_item(entry, "requirement", plist_new_string("anchor apple generic"));
3005 plist_dict_set_item(files, bundle.first.c_str(), entry);
3006 }
3007 }
3008
3009 for (const auto &version : versions) {
3010 auto rules(plist_new_dict());
3011 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
3012
3013 std::multiset<const Rule *, RuleCode> ordered;
3014 for (const auto &rule : version.second)
3015 ordered.insert(&rule);
3016
3017 for (const auto &rule : ordered)
3018 if (rule->weight_ == 1 && rule->mode_ == NoMode)
3019 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
3020 else {
3021 auto entry(plist_new_dict());
3022 plist_dict_set_item(rules, rule->code_.c_str(), entry);
3023
3024 switch (rule->mode_) {
3025 case NoMode:
3026 break;
3027 case OmitMode:
3028 plist_dict_set_item(entry, "omit", plist_new_bool(true));
3029 break;
3030 case OptionalMode:
3031 plist_dict_set_item(entry, "optional", plist_new_bool(true));
3032 break;
3033 case NestedMode:
3034 plist_dict_set_item(entry, "nested", plist_new_bool(true));
3035 break;
3036 case TopMode:
3037 plist_dict_set_item(entry, "top", plist_new_bool(true));
3038 break;
3039 }
3040
3041 if (rule->weight_ >= 10000)
3042 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
3043 else if (rule->weight_ != 1)
3044 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
3045 }
3046 }
3047
3048 folder.Save(signature, true, NULL, fun([&](std::streambuf &save) {
3049 HashProxy proxy(local.files[signature], save);
3050 char *xml(NULL);
3051 uint32_t size;
3052 plist_to_xml(plist, &xml, &size);
3053 _scope({ free(xml); });
3054 put(proxy, xml, size);
3055 }));
3056
3057 Bundle bundle;
3058 bundle.path = folder.Path(executable);
3059
3060 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
3061 progress(root + executable);
3062 folder.Save(executable, true, flag, fun([&](std::streambuf &save) {
3063 Slots slots;
3064 slots[1] = local.files.at(info);
3065 slots[3] = local.files.at(signature);
3066 bundle.hash = Sign(NULL, 0, buffer, local.files[executable], save, identifier, entitlements, false, requirements, key, slots, length, 0, false, Progression(progress, root + executable));
3067 }));
3068 }));
3069
3070 remote.Merge(root, local);
3071 return bundle;
3072 }
3073
3074 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) {
3075 State local;
3076 return Sign(root, folder, key, local, requirements, alter, progress);
3077 }
3078 #endif
3079
3080 #endif
3081 }
3082
3083 std::string Hex(const uint8_t *data, size_t size) {
3084 std::string hex;
3085 hex.reserve(size * 2);
3086 for (size_t i(0); i != size; ++i) {
3087 hex += "0123456789abcdef"[data[i] >> 4];
3088 hex += "0123456789abcdef"[data[i] & 0xf];
3089 }
3090 return hex;
3091 }
3092
3093 static void usage(const char *argv0) {
3094 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv0);
3095 fprintf(stderr, " %s -e MobileSafari\n", argv0);
3096 fprintf(stderr, " %s -S cat\n", argv0);
3097 fprintf(stderr, " %s -Stfp.xml gdb\n", argv0);
3098 }
3099
3100 #ifndef LDID_NOTOOLS
3101 int main(int argc, char *argv[]) {
3102 #ifndef LDID_NOSMIME
3103 OpenSSL_add_all_algorithms();
3104 #endif
3105
3106 union {
3107 uint16_t word;
3108 uint8_t byte[2];
3109 } endian = {1};
3110
3111 little_ = endian.byte[0];
3112
3113 bool flag_r(false);
3114 bool flag_e(false);
3115 bool flag_q(false);
3116
3117 bool flag_H(false);
3118 bool flag_h(false);
3119
3120 #ifndef LDID_NOFLAGT
3121 bool flag_T(false);
3122 #endif
3123
3124 bool flag_S(false);
3125 bool flag_s(false);
3126
3127 bool flag_D(false);
3128 bool flag_d(false);
3129
3130 bool flag_A(false);
3131 bool flag_a(false);
3132
3133 bool flag_u(false);
3134
3135 bool flag_M(false);
3136
3137 uint32_t flags(0);
3138 bool platform(false);
3139
3140 uint32_t flag_CPUType(_not(uint32_t));
3141 uint32_t flag_CPUSubtype(_not(uint32_t));
3142
3143 const char *flag_I(NULL);
3144
3145 #ifndef LDID_NOFLAGT
3146 bool timeh(false);
3147 uint32_t timev(0);
3148 #endif
3149
3150 Map entitlements;
3151 Map requirements;
3152 Map key;
3153 ldid::Slots slots;
3154
3155 std::vector<std::string> files;
3156
3157 if (argc == 1) {
3158 usage(argv[0]);
3159 return 0;
3160 }
3161
3162 for (int argi(1); argi != argc; ++argi)
3163 if (argv[argi][0] != '-')
3164 files.push_back(argv[argi]);
3165 else switch (argv[argi][1]) {
3166 case 'r':
3167 _assert(!flag_s);
3168 _assert(!flag_S);
3169 flag_r = true;
3170 break;
3171
3172 case 'e': flag_e = true; break;
3173
3174 case 'E': {
3175 const char *string = argv[argi] + 2;
3176 const char *colon = strchr(string, ':');
3177 _assert(colon != NULL);
3178 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
3179 char *arge;
3180 unsigned number(strtoul(string, &arge, 0));
3181 _assert(arge == colon);
3182 auto &slot(slots[number]);
3183 for (Algorithm *algorithm : GetAlgorithms())
3184 (*algorithm)(slot, file.data(), file.size());
3185 } break;
3186
3187 case 'q': flag_q = true; break;
3188
3189 case 'H': {
3190 const char *hash = argv[argi] + 2;
3191
3192 if (!flag_H) {
3193 flag_H = true;
3194
3195 do_sha1 = false;
3196 do_sha256 = false;
3197
3198 fprintf(stderr, "WARNING: -H is only present for compatibility with a fork of ldid\n");
3199 fprintf(stderr, " you should NOT be manually specifying the hash algorithm\n");
3200 }
3201
3202 if (false);
3203 else if (strcmp(hash, "sha1") == 0)
3204 do_sha1 = true;
3205 else if (strcmp(hash, "sha256") == 0)
3206 do_sha256 = true;
3207 else _assert(false);
3208 } break;
3209
3210 case 'h': flag_h = true; break;
3211
3212 case 'Q': {
3213 const char *xml = argv[argi] + 2;
3214 requirements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
3215 } break;
3216
3217 case 'D': flag_D = true; break;
3218 case 'd': flag_d = true; break;
3219
3220 case 'a': flag_a = true; break;
3221
3222 case 'A':
3223 _assert(!flag_A);
3224 flag_A = true;
3225 if (argv[argi][2] != '\0') {
3226 const char *cpu = argv[argi] + 2;
3227 const char *colon = strchr(cpu, ':');
3228 _assert(colon != NULL);
3229 char *arge;
3230 flag_CPUType = strtoul(cpu, &arge, 0);
3231 _assert(arge == colon);
3232 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
3233 _assert(arge == argv[argi] + strlen(argv[argi]));
3234 }
3235 break;
3236
3237 case 'C': {
3238 const char *name = argv[argi] + 2;
3239 if (false);
3240 else if (strcmp(name, "host") == 0)
3241 flags |= kSecCodeSignatureHost;
3242 else if (strcmp(name, "adhoc") == 0)
3243 flags |= kSecCodeSignatureAdhoc;
3244 else if (strcmp(name, "hard") == 0)
3245 flags |= kSecCodeSignatureForceHard;
3246 else if (strcmp(name, "kill") == 0)
3247 flags |= kSecCodeSignatureForceKill;
3248 else if (strcmp(name, "expires") == 0)
3249 flags |= kSecCodeSignatureForceExpiration;
3250 else if (strcmp(name, "restrict") == 0)
3251 flags |= kSecCodeSignatureRestrict;
3252 else if (strcmp(name, "enforcement") == 0)
3253 flags |= kSecCodeSignatureEnforcement;
3254 else if (strcmp(name, "library-validation") == 0)
3255 flags |= kSecCodeSignatureLibraryValidation;
3256 else if (strcmp(name, "runtime") == 0)
3257 flags |= kSecCodeSignatureRuntime;
3258 else _assert(false);
3259 } break;
3260
3261 case 'P':
3262 platform = true;
3263 break;
3264
3265 case 's':
3266 _assert(!flag_r);
3267 _assert(!flag_S);
3268 flag_s = true;
3269 break;
3270
3271 case 'S':
3272 _assert(!flag_r);
3273 _assert(!flag_s);
3274 flag_S = true;
3275 if (argv[argi][2] != '\0') {
3276 const char *xml = argv[argi] + 2;
3277 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
3278 }
3279 break;
3280
3281 case 'M':
3282 flag_M = true;
3283 break;
3284
3285 case 'K':
3286 if (argv[argi][2] != '\0')
3287 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
3288 break;
3289
3290 #ifndef LDID_NOFLAGT
3291 case 'T': {
3292 flag_T = true;
3293 if (argv[argi][2] == '-')
3294 timeh = true;
3295 else {
3296 char *arge;
3297 timev = strtoul(argv[argi] + 2, &arge, 0);
3298 _assert(arge == argv[argi] + strlen(argv[argi]));
3299 }
3300 } break;
3301 #endif
3302
3303 case 'u': {
3304 flag_u = true;
3305 } break;
3306
3307 case 'I': {
3308 flag_I = argv[argi] + 2;
3309 } break;
3310
3311 default:
3312 usage(argv[0]);
3313 return 1;
3314 break;
3315 }
3316
3317 _assert(flag_S || key.empty());
3318 _assert(flag_S || flag_I == NULL);
3319
3320 if (flag_d && !flag_h) {
3321 flag_h = true;
3322 fprintf(stderr, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3323 }
3324
3325 if (files.empty())
3326 return 0;
3327
3328 size_t filei(0), filee(0);
3329 _foreach (file, files) try {
3330 std::string path(file);
3331
3332 struct stat info;
3333 _syscall(stat(path.c_str(), &info));
3334
3335 if (S_ISDIR(info.st_mode)) {
3336 _assert(flag_S);
3337 #ifndef LDID_NOPLIST
3338 ldid::DiskFolder folder(path + "/");
3339 path += "/" + Sign("", folder, key, requirements, ldid::fun([&](const std::string &, const std::string &) -> std::string { return entitlements; }), dummy_).path;
3340 #else
3341 _assert(false);
3342 #endif
3343 } else if (flag_S || flag_r) {
3344 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
3345
3346 std::filebuf output;
3347 Split split(path);
3348 auto temp(Temporary(output, split));
3349
3350 if (flag_r)
3351 ldid::Unsign(input.data(), input.size(), output, dummy_);
3352 else {
3353 std::string identifier(flag_I ?: split.base.c_str());
3354 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, flag_M, requirements, key, slots, flags, platform, dummy_);
3355 }
3356
3357 Commit(path, temp);
3358 }
3359
3360 bool modify(false);
3361 #ifndef LDID_NOFLAGT
3362 if (flag_T)
3363 modify = true;
3364 #endif
3365 if (flag_s)
3366 modify = true;
3367
3368 Map mapping(path, modify);
3369 FatHeader fat_header(mapping.data(), mapping.size());
3370
3371 _foreach (mach_header, fat_header.GetMachHeaders()) {
3372 struct linkedit_data_command *signature(NULL);
3373 struct encryption_info_command *encryption(NULL);
3374
3375 if (flag_A) {
3376 if (mach_header.GetCPUType() != flag_CPUType)
3377 continue;
3378 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
3379 continue;
3380 }
3381
3382 if (flag_a)
3383 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
3384
3385 _foreach (load_command, mach_header.GetLoadCommands()) {
3386 uint32_t cmd(mach_header.Swap(load_command->cmd));
3387
3388 if (false);
3389 else if (cmd == LC_CODE_SIGNATURE)
3390 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
3391 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
3392 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
3393 else if (cmd == LC_LOAD_DYLIB) {
3394 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
3395 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
3396
3397 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3398 if (flag_u) {
3399 Version version;
3400 version.value = mach_header.Swap(dylib_command->dylib.current_version);
3401 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
3402 }
3403 }
3404 }
3405 #ifndef LDID_NOFLAGT
3406 else if (cmd == LC_ID_DYLIB) {
3407 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
3408
3409 if (flag_T) {
3410 uint32_t timed;
3411
3412 if (!timeh)
3413 timed = timev;
3414 else {
3415 dylib_command->dylib.timestamp = 0;
3416 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
3417 }
3418
3419 dylib_command->dylib.timestamp = mach_header.Swap(timed);
3420 }
3421 }
3422 #endif
3423 }
3424
3425 if (flag_d && encryption != NULL) {
3426 printf("cryptid=%d\n", mach_header.Swap(encryption->cryptid));
3427 }
3428
3429 if (flag_D) {
3430 _assert(encryption != NULL);
3431 encryption->cryptid = mach_header.Swap(0);
3432 }
3433
3434 if (flag_e) {
3435 _assert(signature != NULL);
3436
3437 uint32_t data = mach_header.Swap(signature->dataoff);
3438
3439 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3440 uint8_t *blob = top + data;
3441 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3442
3443 for (size_t index(0); index != Swap(super->count); ++index)
3444 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
3445 uint32_t begin = Swap(super->index[index].offset);
3446 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
3447 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
3448 }
3449 }
3450
3451 if (flag_q) {
3452 _assert(signature != NULL);
3453
3454 uint32_t data = mach_header.Swap(signature->dataoff);
3455
3456 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3457 uint8_t *blob = top + data;
3458 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3459
3460 for (size_t index(0); index != Swap(super->count); ++index)
3461 if (Swap(super->index[index].type) == CSSLOT_REQUIREMENTS) {
3462 uint32_t begin = Swap(super->index[index].offset);
3463 struct Blob *requirement = reinterpret_cast<struct Blob *>(blob + begin);
3464 fwrite(requirement, 1, Swap(requirement->length), stdout);
3465 }
3466 }
3467
3468 if (flag_s) {
3469 _assert(signature != NULL);
3470
3471 uint32_t data = mach_header.Swap(signature->dataoff);
3472
3473 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3474 uint8_t *blob = top + data;
3475 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3476
3477 for (size_t index(0); index != Swap(super->count); ++index)
3478 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
3479 uint32_t begin = Swap(super->index[index].offset);
3480 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob));
3481
3482 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
3483 uint32_t pages = Swap(directory->nCodeSlots);
3484
3485 if (pages != 1)
3486 for (size_t i = 0; i != pages - 1; ++i)
3487 LDID_SHA1(top + PageSize_ * i, PageSize_, hashes[i]);
3488 if (pages != 0)
3489 LDID_SHA1(top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1, hashes[pages - 1]);
3490 }
3491 }
3492
3493 if (flag_h) {
3494 _assert(signature != NULL);
3495
3496 auto algorithms(GetAlgorithms());
3497
3498 uint32_t data = mach_header.Swap(signature->dataoff);
3499
3500 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3501 uint8_t *blob = top + data;
3502 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3503
3504 struct Candidate {
3505 CodeDirectory *directory_;
3506 size_t size_;
3507 Algorithm &algorithm_;
3508 std::string hash_;
3509 };
3510
3511 std::map<uint8_t, Candidate> candidates;
3512
3513 for (size_t index(0); index != Swap(super->count); ++index) {
3514 auto type(Swap(super->index[index].type));
3515 if ((type == CSSLOT_CODEDIRECTORY || type >= CSSLOT_ALTERNATE) && type != CSSLOT_SIGNATURESLOT) {
3516 uint32_t begin = Swap(super->index[index].offset);
3517 uint32_t end = index + 1 == Swap(super->count) ? Swap(super->blob.length) : Swap(super->index[index + 1].offset);
3518 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob));
3519 auto type(directory->hashType);
3520 _assert(type > 0 && type <= algorithms.size());
3521 auto &algorithm(*algorithms[type - 1]);
3522 uint8_t hash[algorithm.size_];
3523 algorithm(hash, blob + begin, end - begin);
3524 candidates.insert({type, {directory, end - begin, algorithm, Hex(hash, 20)}});
3525 }
3526 }
3527
3528 _assert(!candidates.empty());
3529 auto best(candidates.end());
3530 --best;
3531
3532 const auto directory(best->second.directory_);
3533 const auto flags(Swap(directory->flags));
3534
3535 std::string names;
3536 if (flags & kSecCodeSignatureHost)
3537 names += ",host";
3538 if (flags & kSecCodeSignatureAdhoc)
3539 names += ",adhoc";
3540 if (flags & kSecCodeSignatureForceHard)
3541 names += ",hard";
3542 if (flags & kSecCodeSignatureForceKill)
3543 names += ",kill";
3544 if (flags & kSecCodeSignatureForceExpiration)
3545 names += ",expires";
3546 if (flags & kSecCodeSignatureRestrict)
3547 names += ",restrict";
3548 if (flags & kSecCodeSignatureEnforcement)
3549 names += ",enforcement";
3550 if (flags & kSecCodeSignatureLibraryValidation)
3551 names += ",library-validation";
3552 if (flags & kSecCodeSignatureRuntime)
3553 names += ",runtime";
3554
3555 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3556 Swap(directory->version), best->second.size_, flags, names.empty() ? "none" : names.c_str() + 1, Swap(directory->nCodeSlots), Swap(directory->nSpecialSlots));
3557 printf("Hash type=%s size=%d\n", best->second.algorithm_.name(), directory->hashSize);
3558
3559 std::string choices;
3560 for (const auto &candidate : candidates) {
3561 auto choice(candidate.second.algorithm_.name());
3562 choices += ',';
3563 choices += choice;
3564 printf("CandidateCDHash %s=%s\n", choice, candidate.second.hash_.c_str());
3565 }
3566 printf("Hash choices=%s\n", choices.c_str() + 1);
3567
3568 printf("CDHash=%s\n", best->second.hash_.c_str());
3569 }
3570 }
3571
3572 ++filei;
3573 } catch (const char *) {
3574 ++filee;
3575 ++filei;
3576 }
3577
3578 return filee;
3579 }
3580 #endif