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