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