]> git.cameronkatri.com Git - ldid.git/blob - ldid.cpp
Fix macOS actions (#9)
[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_MAJOR >= 3
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_sha1)
1257 algorithms.push_back(&sha1);
1258 if (do_sha256)
1259 algorithms.push_back(&sha256);
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 auto info(PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP));
1866 _assert(info != NULL);
1867
1868 PKCS7_set_detached(value_, 1);
1869
1870 ASN1_OCTET_STRING *string(ASN1_OCTET_STRING_new());
1871 _assert(string != NULL);
1872 try {
1873 _assert(ASN1_STRING_set(string, xml.data(), xml.size()));
1874
1875 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1876 _assert(PKCS7_add_signed_attribute(info, nid, V_ASN1_OCTET_STRING, string));
1877 } catch (...) {
1878 ASN1_OCTET_STRING_free(string);
1879 throw;
1880 }
1881
1882 _assert(PKCS7_final(value_, data, PKCS7_BINARY));
1883 }
1884
1885 ~Signature() {
1886 PKCS7_free(value_);
1887 }
1888
1889 operator PKCS7 *() const {
1890 return value_;
1891 }
1892 };
1893 #endif
1894
1895 class NullBuffer :
1896 public std::streambuf
1897 {
1898 public:
1899 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1900 return size;
1901 }
1902
1903 virtual int_type overflow(int_type next) {
1904 return next;
1905 }
1906 };
1907
1908 class HashBuffer :
1909 public std::streambuf
1910 {
1911 private:
1912 ldid::Hash &hash_;
1913
1914 LDID_SHA1_CTX sha1_;
1915 LDID_SHA256_CTX sha256_;
1916
1917 public:
1918 HashBuffer(ldid::Hash &hash) :
1919 hash_(hash)
1920 {
1921 LDID_SHA1_Init(&sha1_);
1922 LDID_SHA256_Init(&sha256_);
1923 }
1924
1925 ~HashBuffer() {
1926 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.sha1_), &sha1_);
1927 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_.sha256_), &sha256_);
1928 }
1929
1930 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1931 LDID_SHA1_Update(&sha1_, data, size);
1932 LDID_SHA256_Update(&sha256_, data, size);
1933 return size;
1934 }
1935
1936 virtual int_type overflow(int_type next) {
1937 if (next == traits_type::eof())
1938 return sync();
1939 char value(next);
1940 xsputn(&value, 1);
1941 return next;
1942 }
1943 };
1944
1945 class HashProxy :
1946 public HashBuffer
1947 {
1948 private:
1949 std::streambuf &buffer_;
1950
1951 public:
1952 HashProxy(ldid::Hash &hash, std::streambuf &buffer) :
1953 HashBuffer(hash),
1954 buffer_(buffer)
1955 {
1956 }
1957
1958 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1959 _assert(HashBuffer::xsputn(data, size) == size);
1960 return buffer_.sputn(data, size);
1961 }
1962 };
1963
1964 #ifndef LDID_NOTOOLS
1965 static bool Starts(const std::string &lhs, const std::string &rhs) {
1966 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1967 }
1968
1969 class Split {
1970 public:
1971 std::string dir;
1972 std::string base;
1973
1974 Split(const std::string &path) {
1975 size_t slash(path.rfind('/'));
1976 if (slash == std::string::npos)
1977 base = path;
1978 else {
1979 dir = path.substr(0, slash + 1);
1980 base = path.substr(slash + 1);
1981 }
1982 }
1983 };
1984
1985 static void mkdir_p(const std::string &path) {
1986 if (path.empty())
1987 return;
1988 #ifdef __WIN32__
1989 if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
1990 return;
1991 #else
1992 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1993 return;
1994 #endif
1995 auto slash(path.rfind('/', path.size() - 1));
1996 if (slash == std::string::npos)
1997 return;
1998 mkdir_p(path.substr(0, slash));
1999 }
2000
2001 static std::string Temporary(std::filebuf &file, const Split &split) {
2002 std::string temp(split.dir + ".ldid." + split.base);
2003 mkdir_p(split.dir);
2004 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
2005 return temp;
2006 }
2007
2008 static void Commit(const std::string &path, const std::string &temp) {
2009 struct stat info;
2010 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
2011 #ifndef __WIN32__
2012 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
2013 #endif
2014 _syscall(chmod(temp.c_str(), info.st_mode));
2015 }
2016
2017 _syscall(rename(temp.c_str(), path.c_str()));
2018 }
2019 #endif
2020
2021 namespace ldid {
2022
2023 #ifndef LDID_NOSMIME
2024 static void get(std::string &value, X509_NAME *name, int nid) {
2025 auto index(X509_NAME_get_index_by_NID(name, nid, -1));
2026 _assert(index >= 0);
2027 auto next(X509_NAME_get_index_by_NID(name, nid, index));
2028 _assert(next == -1);
2029 auto entry(X509_NAME_get_entry(name, index));
2030 _assert(entry != NULL);
2031 auto asn(X509_NAME_ENTRY_get_data(entry));
2032 _assert(asn != NULL);
2033 value.assign(reinterpret_cast<const char *>(ASN1_STRING_get0_data(asn)), ASN1_STRING_length(asn));
2034 }
2035 #endif
2036
2037 static void req(std::streambuf &buffer, uint32_t value) {
2038 value = Swap(value);
2039 put(buffer, &value, sizeof(value));
2040 }
2041
2042 static void req(std::streambuf &buffer, const std::string &value) {
2043 req(buffer, value.size());
2044 put(buffer, value.data(), value.size());
2045 static uint8_t zeros[] = {0,0,0,0};
2046 put(buffer, zeros, 3 - (value.size() + 3) % 4);
2047 }
2048
2049 template <size_t Size_>
2050 static void req(std::streambuf &buffer, uint8_t (&&data)[Size_]) {
2051 req(buffer, Size_);
2052 put(buffer, data, Size_);
2053 static uint8_t zeros[] = {0,0,0,0};
2054 put(buffer, zeros, 3 - (Size_ + 3) % 4);
2055 }
2056
2057 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) {
2058 Hash hash;
2059
2060
2061 std::string team;
2062 std::string common;
2063
2064 #ifndef LDID_NOSMIME
2065 if (!key.empty()) {
2066 Stuff stuff(key);
2067 auto name(X509_get_subject_name(stuff));
2068 _assert(name != NULL);
2069 get(team, name, NID_organizationalUnitName);
2070 get(common, name, NID_commonName);
2071 }
2072 #endif
2073
2074
2075 std::stringbuf backing;
2076
2077 if (!requirements.empty()) {
2078 put(backing, requirements.data(), requirements.size());
2079 } else {
2080 Blobs blobs;
2081
2082 std::stringbuf requirement;
2083 req(requirement, exprForm);
2084 req(requirement, opAnd);
2085 req(requirement, opIdent);
2086 req(requirement, identifier);
2087 req(requirement, opAnd);
2088 req(requirement, opAppleGenericAnchor);
2089 req(requirement, opAnd);
2090 req(requirement, opCertField);
2091 req(requirement, 0);
2092 req(requirement, "subject.CN");
2093 req(requirement, matchEqual);
2094 req(requirement, common);
2095 req(requirement, opCertGeneric);
2096 req(requirement, 1);
2097 req(requirement, (uint8_t []) {APPLE_EXTENSION_OID, 2, 1});
2098 req(requirement, matchExists);
2099 insert(blobs, 3, CSMAGIC_REQUIREMENT, requirement);
2100
2101 put(backing, CSMAGIC_REQUIREMENTS, blobs);
2102 }
2103
2104
2105 // XXX: this is just a "sufficiently large number"
2106 size_t certificate(0x3000);
2107
2108 Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, Baton &baton, size_t size) -> size_t {
2109 size_t alloc(sizeof(struct SuperBlob));
2110
2111 uint32_t normal((size + PageSize_ - 1) / PageSize_);
2112
2113 uint32_t special(0);
2114
2115 _foreach (slot, slots)
2116 special = std::max(special, slot.first);
2117
2118 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
2119 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
2120 special = std::max(special, CSSLOT_INFOSLOT);
2121 }));
2122
2123 special = std::max(special, CSSLOT_REQUIREMENTS);
2124 alloc += sizeof(struct BlobIndex);
2125 alloc += backing.str().size();
2126
2127 #ifdef LDID_NOPLIST
2128 baton.entitlements_ = entitlements;
2129 #else
2130 if (merge)
2131 Analyze(mach_header, fun([&](const char *data, size_t size) {
2132 baton.entitlements_.assign(data, size);
2133 }));
2134
2135 if (!baton.entitlements_.empty() || !entitlements.empty()) {
2136 auto combined(plist(baton.entitlements_));
2137 _scope({ plist_free(combined); });
2138 _assert(plist_get_node_type(combined) == PLIST_DICT);
2139
2140 auto merging(plist(entitlements));
2141 _scope({ plist_free(merging); });
2142 _assert(plist_get_node_type(merging) == PLIST_DICT);
2143
2144 plist_dict_iter iterator(NULL);
2145 plist_dict_new_iter(merging, &iterator);
2146 _scope({ free(iterator); });
2147
2148 for (;;) {
2149 char *key(NULL);
2150 plist_t value(NULL);
2151 plist_dict_next_item(merging, iterator, &key, &value);
2152 if (key == NULL)
2153 break;
2154 _scope({ free(key); });
2155 plist_dict_set_item(combined, key, plist_copy(value));
2156 }
2157
2158 baton.derformat_ = der(combined);
2159
2160 char *xml(NULL);
2161 uint32_t size;
2162 plist_to_xml(combined, &xml, &size);
2163 _scope({ free(xml); });
2164
2165 baton.entitlements_.assign(xml, size);
2166 }
2167 #endif
2168
2169 if (!baton.entitlements_.empty()) {
2170 special = std::max(special, CSSLOT_ENTITLEMENTS);
2171 alloc += sizeof(struct BlobIndex);
2172 alloc += sizeof(struct Blob);
2173 alloc += baton.entitlements_.size();
2174 }
2175
2176 if (!baton.derformat_.empty()) {
2177 special = std::max(special, CSSLOT_DERFORMAT);
2178 alloc += sizeof(struct BlobIndex);
2179 alloc += sizeof(struct Blob);
2180 alloc += baton.derformat_.size();
2181 }
2182
2183 size_t directory(0);
2184
2185 directory += sizeof(struct BlobIndex);
2186 directory += sizeof(struct Blob);
2187 directory += sizeof(struct CodeDirectory);
2188 directory += identifier.size() + 1;
2189
2190 if (!team.empty())
2191 directory += team.size() + 1;
2192
2193 for (Algorithm *algorithm : GetAlgorithms())
2194 alloc = Align(alloc + directory + (special + normal) * algorithm->size_, 16);
2195
2196 #ifndef LDID_NOSMIME
2197 if (!key.empty()) {
2198 alloc += sizeof(struct BlobIndex);
2199 alloc += sizeof(struct Blob);
2200 alloc += certificate;
2201 }
2202 #endif
2203
2204 return alloc;
2205 }), 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 {
2206 Blobs blobs;
2207
2208 if (true) {
2209 insert(blobs, CSSLOT_REQUIREMENTS, backing);
2210 }
2211
2212 uint64_t execs(0);
2213 if (mach_header.Swap(mach_header->filetype) == MH_EXECUTE)
2214 execs |= kSecCodeExecSegMainBinary;
2215
2216 if (!baton.entitlements_.empty()) {
2217 std::stringbuf data;
2218 put(data, baton.entitlements_.data(), baton.entitlements_.size());
2219 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
2220
2221 #ifndef LDID_NOPLIST
2222 auto entitlements(plist(baton.entitlements_));
2223 _scope({ plist_free(entitlements); });
2224 _assert(plist_get_node_type(entitlements) == PLIST_DICT);
2225
2226 const auto entitled([&](const char *key) {
2227 auto item(plist_dict_get_item(entitlements, key));
2228 if (plist_get_node_type(item) != PLIST_BOOLEAN)
2229 return false;
2230 uint8_t value(0);
2231 plist_get_bool_val(item, &value);
2232 return value != 0;
2233 });
2234
2235 if (entitled("get-task-allow"))
2236 execs |= kSecCodeExecSegAllowUnsigned;
2237 if (entitled("run-unsigned-code"))
2238 execs |= kSecCodeExecSegAllowUnsigned;
2239 if (entitled("com.apple.private.cs.debugger"))
2240 execs |= kSecCodeExecSegDebugger;
2241 if (entitled("dynamic-codesigning"))
2242 execs |= kSecCodeExecSegJit;
2243 if (entitled("com.apple.private.skip-library-validation"))
2244 execs |= kSecCodeExecSegSkipLibraryVal;
2245 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2246 execs |= kSecCodeExecSegCanLoadCdHash;
2247 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2248 execs |= kSecCodeExecSegCanExecCdHash;
2249 #endif
2250 }
2251
2252 if (!baton.derformat_.empty()) {
2253 std::stringbuf data;
2254 put(data, baton.derformat_.data(), baton.derformat_.size());
2255 insert(blobs, CSSLOT_DERFORMAT, CSMAGIC_EMBEDDED_DERFORMAT, data);
2256 }
2257
2258 Slots posts(slots);
2259
2260 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
2261 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0) {
2262 auto &slot(posts[CSSLOT_INFOSLOT]);
2263 for (Algorithm *algorithm : GetAlgorithms())
2264 (*algorithm)(slot, data, size);
2265 }
2266 }));
2267
2268 unsigned total(0);
2269 for (Algorithm *pointer : GetAlgorithms()) {
2270 Algorithm &algorithm(*pointer);
2271
2272 std::stringbuf data;
2273
2274 uint32_t special(0);
2275 _foreach (blob, blobs)
2276 special = std::max(special, blob.first);
2277 _foreach (slot, posts)
2278 special = std::max(special, slot.first);
2279 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
2280
2281 CodeDirectory directory;
2282 directory.version = Swap(uint32_t(0x00020400));
2283 directory.flags = Swap(uint32_t(flags));
2284 directory.nSpecialSlots = Swap(special);
2285 directory.codeLimit = Swap(uint32_t(limit > UINT32_MAX ? UINT32_MAX : limit));
2286 directory.nCodeSlots = Swap(normal);
2287 directory.hashSize = algorithm.size_;
2288 directory.hashType = algorithm.type_;
2289 directory.platform = platform ? 0x01 : 0x00;
2290 directory.pageSize = PageShift_;
2291 directory.spare2 = Swap(uint32_t(0));
2292 directory.scatterOffset = Swap(uint32_t(0));
2293 directory.spare3 = Swap(uint32_t(0));
2294 directory.codeLimit64 = Swap(uint64_t(limit > UINT32_MAX ? limit : 0));
2295 directory.execSegBase = Swap(uint64_t(left));
2296 directory.execSegLimit = Swap(uint64_t(right - left));
2297 directory.execSegFlags = Swap(execs);
2298
2299 uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory));
2300
2301 directory.identOffset = Swap(uint32_t(offset));
2302 offset += identifier.size() + 1;
2303
2304 if (team.empty())
2305 directory.teamIDOffset = Swap(uint32_t(0));
2306 else {
2307 directory.teamIDOffset = Swap(uint32_t(offset));
2308 offset += team.size() + 1;
2309 }
2310
2311 offset += special * algorithm.size_;
2312 directory.hashOffset = Swap(uint32_t(offset));
2313 offset += normal * algorithm.size_;
2314
2315 put(data, &directory, sizeof(directory));
2316
2317 put(data, identifier.c_str(), identifier.size() + 1);
2318 if (!team.empty())
2319 put(data, team.c_str(), team.size() + 1);
2320
2321 std::vector<uint8_t> storage((special + normal) * algorithm.size_);
2322 auto *hashes(&storage[special * algorithm.size_]);
2323
2324 memset(storage.data(), 0, special * algorithm.size_);
2325
2326 _foreach (blob, blobs) {
2327 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
2328 algorithm(hashes - blob.first * algorithm.size_, local, Swap(local->length));
2329 }
2330
2331 _foreach (slot, posts)
2332 memcpy(hashes - slot.first * algorithm.size_, algorithm[slot.second], algorithm.size_);
2333
2334 progress(0);
2335 if (normal != 1)
2336 for (size_t i = 0; i != normal - 1; ++i) {
2337 algorithm(hashes + i * algorithm.size_, (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
2338 progress(double(i) / normal);
2339 }
2340 if (normal != 0)
2341 algorithm(hashes + (normal - 1) * algorithm.size_, top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
2342 progress(1);
2343
2344 put(data, storage.data(), storage.size());
2345
2346 const auto &save(insert(blobs, total == 0 ? CSSLOT_CODEDIRECTORY : CSSLOT_ALTERNATE + total - 1, CSMAGIC_CODEDIRECTORY, data));
2347 algorithm(hash, save.data(), save.size());
2348
2349 ++total;
2350 }
2351
2352 #ifndef LDID_NOSMIME
2353 if (!key.empty()) {
2354 #ifdef LDID_NOPLIST
2355 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2356 _scope({ CFRelease(plist); });
2357
2358 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
2359 _scope({ CFRelease(cdhashes); });
2360
2361 CFDictionarySetValue(plist, CFSTR("cdhashes"), cdhashes);
2362 #else
2363 auto plist(plist_new_dict());
2364 _scope({ plist_free(plist); });
2365
2366 auto cdhashes(plist_new_array());
2367 plist_dict_set_item(plist, "cdhashes", cdhashes);
2368 #endif
2369
2370 unsigned total(0);
2371 for (Algorithm *pointer : GetAlgorithms()) {
2372 Algorithm &algorithm(*pointer);
2373 (void) algorithm;
2374
2375 const auto &blob(blobs[total == 0 ? CSSLOT_CODEDIRECTORY : CSSLOT_ALTERNATE + total - 1]);
2376 ++total;
2377
2378 std::vector<char> hash;
2379 algorithm(hash, blob.data(), blob.size());
2380 hash.resize(20);
2381
2382 #ifdef LDID_NOPLIST
2383 auto value(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(hash.data()), hash.size()));
2384 _scope({ CFRelease(value); });
2385 CFArrayAppendValue(cdhashes, value);
2386 #else
2387 plist_array_append_item(cdhashes, plist_new_data(hash.data(), hash.size()));
2388 #endif
2389 }
2390
2391 #ifdef LDID_NOPLIST
2392 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault, plist));
2393 _scope({ CFRelease(created); });
2394 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created)));
2395 auto size(CFDataGetLength(created));
2396 #else
2397 char *xml(NULL);
2398 uint32_t size;
2399 plist_to_xml(plist, &xml, &size);
2400 _scope({ free(xml); });
2401 #endif
2402
2403 std::stringbuf data;
2404 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
2405
2406 Stuff stuff(key);
2407 Buffer bio(sign);
2408
2409 Signature signature(stuff, sign, std::string(xml, size));
2410 Buffer result(signature);
2411 std::string value(result);
2412 put(data, value.data(), value.size());
2413
2414 const auto &save(insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data));
2415 _assert(save.size() <= certificate);
2416 }
2417 #endif
2418
2419 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
2420 }), progress);
2421
2422 return hash;
2423 }
2424
2425 #ifndef LDID_NOTOOLS
2426 static void Unsign(void *idata, size_t isize, std::streambuf &output, const Progress &progress) {
2427 Allocate(idata, isize, output, fun([](const MachHeader &mach_header, Baton &baton, size_t size) -> size_t {
2428 return 0;
2429 }), 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 {
2430 return 0;
2431 }), progress);
2432 }
2433
2434 std::string DiskFolder::Path(const std::string &path) const {
2435 return path_ + path;
2436 }
2437
2438 DiskFolder::DiskFolder(const std::string &path) :
2439 path_(path)
2440 {
2441 _assert_(path_.size() != 0 && path_[path_.size() - 1] == '/', "missing / on %s", path_.c_str());
2442 }
2443
2444 DiskFolder::~DiskFolder() {
2445 if (!std::uncaught_exception())
2446 for (const auto &commit : commit_)
2447 Commit(commit.first, commit.second);
2448 }
2449
2450 #ifndef __WIN32__
2451 std::string readlink(const std::string &path) {
2452 for (size_t size(1024); ; size *= 2) {
2453 std::string data;
2454 data.resize(size);
2455
2456 int writ(_syscall(::readlink(path.c_str(), &data[0], data.size())));
2457 if (size_t(writ) >= size)
2458 continue;
2459
2460 data.resize(writ);
2461 return data;
2462 }
2463 }
2464 #endif
2465
2466 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 {
2467 std::string path(Path(root) + base);
2468
2469 DIR *dir(opendir(path.c_str()));
2470 _assert(dir != NULL);
2471 _scope({ _syscall(closedir(dir)); });
2472
2473 while (auto child = readdir(dir)) {
2474 std::string name(child->d_name);
2475 if (name == "." || name == "..")
2476 continue;
2477 if (Starts(name, ".ldid."))
2478 continue;
2479
2480 bool directory;
2481
2482 #ifdef __WIN32__
2483 struct stat info;
2484 _syscall(stat((path + name).c_str(), &info));
2485 if (false);
2486 else if (S_ISDIR(info.st_mode))
2487 directory = true;
2488 else if (S_ISREG(info.st_mode))
2489 directory = false;
2490 else
2491 _assert_(false, "st_mode=%x", info.st_mode);
2492 #else
2493 switch (child->d_type) {
2494 case DT_DIR:
2495 directory = true;
2496 break;
2497 case DT_REG:
2498 directory = false;
2499 break;
2500 case DT_LNK:
2501 link(base + name, fun([&]() { return readlink(path + name); }));
2502 continue;
2503 default:
2504 _assert_(false, "d_type=%u", child->d_type);
2505 }
2506 #endif
2507
2508 if (directory)
2509 Find(root, base + name + "/", code, link);
2510 else
2511 code(base + name);
2512 }
2513 }
2514
2515 void DiskFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2516 if (!edit) {
2517 NullBuffer save;
2518 code(save);
2519 } else {
2520 std::filebuf save;
2521 auto from(Path(path));
2522 commit_[from] = Temporary(save, from);
2523 code(save);
2524 }
2525 }
2526
2527 bool DiskFolder::Look(const std::string &path) const {
2528 return _syscall(access(Path(path).c_str(), R_OK), ENOENT) == 0;
2529 }
2530
2531 void DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2532 std::filebuf data;
2533 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
2534 _assert_(result == &data, "DiskFolder::Open(%s)", Path(path).c_str());
2535
2536 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2537 data.pubseekpos(0, std::ios::in);
2538 code(data, length, NULL);
2539 }
2540
2541 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 {
2542 Find(path, "", code, link);
2543 }
2544 #endif
2545
2546 SubFolder::SubFolder(Folder &parent, const std::string &path) :
2547 parent_(parent),
2548 path_(path)
2549 {
2550 _assert_(path_.size() == 0 || path_[path_.size() - 1] == '/', "missing / on %s", path_.c_str());
2551 }
2552
2553 std::string SubFolder::Path(const std::string &path) const {
2554 return path_ + path;
2555 }
2556
2557 void SubFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2558 return parent_.Save(Path(path), edit, flag, code);
2559 }
2560
2561 bool SubFolder::Look(const std::string &path) const {
2562 return parent_.Look(Path(path));
2563 }
2564
2565 void SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2566 return parent_.Open(Path(path), code);
2567 }
2568
2569 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 {
2570 return parent_.Find(Path(path), code, link);
2571 }
2572
2573 std::string UnionFolder::Map(const std::string &path) const {
2574 auto remap(remaps_.find(path));
2575 if (remap == remaps_.end())
2576 return path;
2577 return remap->second;
2578 }
2579
2580 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 {
2581 if (file.size() >= path.size() && file.substr(0, path.size()) == path)
2582 code(file.substr(path.size()));
2583 }
2584
2585 UnionFolder::UnionFolder(Folder &parent) :
2586 parent_(parent)
2587 {
2588 }
2589
2590 void UnionFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2591 return parent_.Save(Map(path), edit, flag, code);
2592 }
2593
2594 bool UnionFolder::Look(const std::string &path) const {
2595 auto file(resets_.find(path));
2596 if (file != resets_.end())
2597 return true;
2598 return parent_.Look(Map(path));
2599 }
2600
2601 void UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2602 auto file(resets_.find(path));
2603 if (file == resets_.end())
2604 return parent_.Open(Map(path), code);
2605 auto &entry(file->second);
2606
2607 auto &data(*entry.data_);
2608 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2609 data.pubseekpos(0, std::ios::in);
2610 code(data, length, entry.flag_);
2611 }
2612
2613 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 {
2614 for (auto &reset : resets_)
2615 Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2616 auto &entry(reset.second);
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 for (auto &remap : remaps_)
2624 Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2625 parent_.Open(remap.second, fun([&](std::streambuf &data, size_t length, const void *flag) {
2626 code(data, length, flag);
2627 }));
2628 }));
2629
2630 parent_.Find(path, fun([&](const std::string &name) {
2631 if (deletes_.find(path + name) == deletes_.end())
2632 code(name);
2633 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2634 if (deletes_.find(path + name) == deletes_.end())
2635 link(name, read);
2636 }));
2637 }
2638
2639 #ifndef LDID_NOTOOLS
2640 static void copy(std::streambuf &source, std::streambuf &target, size_t length, const Progress &progress) {
2641 progress(0);
2642 size_t total(0);
2643 for (;;) {
2644 char data[4096 * 4];
2645 size_t writ(source.sgetn(data, sizeof(data)));
2646 if (writ == 0)
2647 break;
2648 _assert(target.sputn(data, writ) == writ);
2649 total += writ;
2650 progress(double(total) / length);
2651 }
2652 }
2653
2654 #ifndef LDID_NOPLIST
2655 static plist_t plist(const std::string &data) {
2656 if (data.empty())
2657 return plist_new_dict();
2658 plist_t plist(NULL);
2659 if (Starts(data, "bplist00"))
2660 plist_from_bin(data.data(), data.size(), &plist);
2661 else
2662 plist_from_xml(data.data(), data.size(), &plist);
2663 _assert(plist != NULL);
2664 return plist;
2665 }
2666
2667 static void plist_d(std::streambuf &buffer, size_t length, const Functor<void (plist_t)> &code) {
2668 std::stringbuf data;
2669 copy(buffer, data, length, dummy_);
2670 auto node(plist(data.str()));
2671 _scope({ plist_free(node); });
2672 _assert(plist_get_node_type(node) == PLIST_DICT);
2673 code(node);
2674 }
2675
2676 static std::string plist_s(plist_t node) {
2677 _assert(node != NULL);
2678 _assert(plist_get_node_type(node) == PLIST_STRING);
2679 char *data;
2680 plist_get_string_val(node, &data);
2681 _scope({ free(data); });
2682 return data;
2683 }
2684 #endif
2685
2686 enum Mode {
2687 NoMode,
2688 OptionalMode,
2689 OmitMode,
2690 NestedMode,
2691 TopMode,
2692 };
2693
2694 class Expression {
2695 private:
2696 regex_t regex_;
2697 std::vector<std::string> matches_;
2698
2699 public:
2700 Expression(const std::string &code) {
2701 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED) == 0, "regcomp()");
2702 matches_.resize(regex_.re_nsub + 1);
2703 }
2704
2705 ~Expression() {
2706 regfree(&regex_);
2707 }
2708
2709 bool operator ()(const std::string &data) {
2710 regmatch_t matches[matches_.size()];
2711 auto value(regexec(&regex_, data.c_str(), matches_.size(), matches, 0));
2712 if (value == REG_NOMATCH)
2713 return false;
2714 _assert_(value == 0, "regexec()");
2715 for (size_t i(0); i != matches_.size(); ++i)
2716 matches_[i].assign(data.data() + matches[i].rm_so, matches[i].rm_eo - matches[i].rm_so);
2717 return true;
2718 }
2719
2720 const std::string &operator [](size_t index) const {
2721 return matches_[index];
2722 }
2723 };
2724
2725 struct Rule {
2726 unsigned weight_;
2727 Mode mode_;
2728 std::string code_;
2729
2730 mutable std::unique_ptr<Expression> regex_;
2731
2732 Rule(unsigned weight, Mode mode, const std::string &code) :
2733 weight_(weight),
2734 mode_(mode),
2735 code_(code)
2736 {
2737 }
2738
2739 Rule(const Rule &rhs) :
2740 weight_(rhs.weight_),
2741 mode_(rhs.mode_),
2742 code_(rhs.code_)
2743 {
2744 }
2745
2746 void Compile() const {
2747 regex_.reset(new Expression(code_));
2748 }
2749
2750 bool operator ()(const std::string &data) const {
2751 _assert(regex_.get() != NULL);
2752 return (*regex_)(data);
2753 }
2754
2755 bool operator <(const Rule &rhs) const {
2756 if (weight_ > rhs.weight_)
2757 return true;
2758 if (weight_ < rhs.weight_)
2759 return false;
2760 return mode_ > rhs.mode_;
2761 }
2762 };
2763
2764 struct RuleCode {
2765 bool operator ()(const Rule *lhs, const Rule *rhs) const {
2766 return lhs->code_ < rhs->code_;
2767 }
2768 };
2769
2770 #ifndef LDID_NOPLIST
2771 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) {
2772 // XXX: this is a miserable fail
2773 std::stringbuf temp;
2774 put(temp, prefix, size);
2775 copy(buffer, temp, length - size, progress);
2776 // XXX: this is a stupid hack
2777 pad(temp, 0x10 - (length & 0xf));
2778 auto data(temp.str());
2779
2780 HashProxy proxy(hash, save);
2781 return Sign(data.data(), data.size(), proxy, identifier, entitlements, merge, requirements, key, slots, flags, platform, progress);
2782 }
2783
2784 struct State {
2785 std::map<std::string, Hash> files;
2786 std::map<std::string, std::string> links;
2787
2788 void Merge(const std::string &root, const State &state) {
2789 for (const auto &entry : state.files)
2790 files[root + entry.first] = entry.second;
2791 for (const auto &entry : state.links)
2792 links[root + entry.first] = entry.second;
2793 }
2794 };
2795
2796 Bundle Sign(const std::string &root, Folder &parent, const std::string &key, State &local, const std::string &requirements, const Functor<std::string (const std::string &, const std::string &)> &alter, const Progress &progress) {
2797 std::string executable;
2798 std::string identifier;
2799
2800 bool mac(false);
2801
2802 std::string info("Info.plist");
2803
2804 SubFolder folder(parent, [&]() {
2805 if (parent.Look(info))
2806 return "";
2807 mac = true;
2808 if (false);
2809 else if (parent.Look("Contents/" + info))
2810 return "Contents/";
2811 else if (parent.Look("Resources/" + info)) {
2812 info = "Resources/" + info;
2813 return "";
2814 } else _assert_(false, "cannot find Info.plist");
2815 }());
2816
2817 folder.Open(info, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2818 plist_d(buffer, length, fun([&](plist_t node) {
2819 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
2820 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
2821 }));
2822 }));
2823
2824 if (mac && info == "Info.plist")
2825 executable = "MacOS/" + executable;
2826
2827 progress(root + "*");
2828
2829 std::string entitlements;
2830 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2831 // XXX: this is a miserable fail
2832 std::stringbuf temp;
2833 copy(buffer, temp, length, progress);
2834 // XXX: this is a stupid hack
2835 pad(temp, 0x10 - (length & 0xf));
2836 auto data(temp.str());
2837 entitlements = alter(root, Analyze(data.data(), data.size()));
2838 }));
2839
2840 static const std::string directory("_CodeSignature/");
2841 static const std::string signature(directory + "CodeResources");
2842
2843 std::map<std::string, std::multiset<Rule>> versions;
2844
2845 auto &rules1(versions[""]);
2846 auto &rules2(versions["2"]);
2847
2848 const std::string resources(mac ? "Resources/" : "");
2849
2850 if (true) {
2851 rules1.insert(Rule{1, NoMode, "^" + (resources == "" ? ".*" : resources)});
2852 rules1.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2853 rules1.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
2854 rules1.insert(Rule{1010, NoMode, "^" + resources + "Base\\.lproj/"});
2855 rules1.insert(Rule{1, NoMode, "^version.plist$"});
2856 }
2857
2858 if (true) {
2859 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
2860 if (mac) rules2.insert(Rule{20, NoMode, "^" + resources});
2861 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
2862 if (mac) rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2863 rules2.insert(Rule{1, NoMode, "^.*"});
2864 rules2.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2865 rules2.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
2866 if (!mac) rules2.insert(Rule{1010, NoMode, "^Base\\.lproj/"});
2867 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
2868 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
2869 if (mac) rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
2870 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
2871 if (mac) rules2.insert(Rule{1010, NoMode, "^" + resources + "Base\\.lproj/"});
2872 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
2873 }
2874
2875 std::string failure(mac ? "Contents/|Versions/[^/]*/Resources/" : "");
2876 Expression nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure + ")Info\\.plist$");
2877 std::map<std::string, Bundle> bundles;
2878
2879 folder.Find("", fun([&](const std::string &name) {
2880 if (!nested(name))
2881 return;
2882 auto bundle(Split(name).dir);
2883 if (mac) {
2884 _assert(!bundle.empty());
2885 bundle = Split(bundle.substr(0, bundle.size() - 1)).dir;
2886 }
2887 SubFolder subfolder(folder, bundle);
2888
2889 State remote;
2890 bundles[nested[1]] = Sign(root + bundle, subfolder, key, remote, "", Starts(name, "PlugIns/") ? alter :
2891 static_cast<const Functor<std::string (const std::string &, const std::string &)> &>(fun([&](const std::string &, const std::string &) -> std::string { return entitlements; }))
2892 , progress);
2893 local.Merge(bundle, remote);
2894 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2895 }));
2896
2897 std::set<std::string> excludes;
2898
2899 auto exclude([&](const std::string &name) {
2900 // BundleDiskRep::adjustResources -> builder.addExclusion
2901 if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
2902 return true;
2903
2904 for (const auto &bundle : bundles)
2905 if (Starts(name, bundle.first + "/")) {
2906 excludes.insert(name);
2907 return true;
2908 }
2909
2910 return false;
2911 });
2912
2913 folder.Find("", fun([&](const std::string &name) {
2914 if (exclude(name))
2915 return;
2916
2917 if (local.files.find(name) != local.files.end())
2918 return;
2919 auto &hash(local.files[name]);
2920
2921 folder.Open(name, fun([&](std::streambuf &data, size_t length, const void *flag) {
2922 progress(root + name);
2923
2924 union {
2925 struct {
2926 uint32_t magic;
2927 uint32_t count;
2928 };
2929
2930 uint8_t bytes[8];
2931 } header;
2932
2933 auto size(most(data, &header.bytes, sizeof(header.bytes)));
2934
2935 if (name != "_WatchKitStub/WK" && size == sizeof(header.bytes))
2936 switch (Swap(header.magic)) {
2937 case FAT_MAGIC:
2938 // Java class file format
2939 if (Swap(header.count) >= 40)
2940 break;
2941 case FAT_CIGAM:
2942 case MH_MAGIC: case MH_MAGIC_64:
2943 case MH_CIGAM: case MH_CIGAM_64:
2944 folder.Save(name, true, flag, fun([&](std::streambuf &save) {
2945 Slots slots;
2946 Sign(header.bytes, size, data, hash, save, identifier, "", false, "", key, slots, length, 0, false, Progression(progress, root + name));
2947 }));
2948 return;
2949 }
2950
2951 folder.Save(name, false, flag, fun([&](std::streambuf &save) {
2952 HashProxy proxy(hash, save);
2953 put(proxy, header.bytes, size);
2954 copy(data, proxy, length - size, progress);
2955 }));
2956 }));
2957 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2958 if (exclude(name))
2959 return;
2960
2961 local.links[name] = read();
2962 }));
2963
2964 auto plist(plist_new_dict());
2965 _scope({ plist_free(plist); });
2966
2967 for (const auto &version : versions) {
2968 auto files(plist_new_dict());
2969 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
2970
2971 for (const auto &rule : version.second)
2972 rule.Compile();
2973
2974 bool old(&version.second == &rules1);
2975
2976 for (const auto &hash : local.files)
2977 for (const auto &rule : version.second)
2978 if (rule(hash.first)) {
2979 if (!old && mac && excludes.find(hash.first) != excludes.end());
2980 else if (old && rule.mode_ == NoMode)
2981 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
2982 else if (rule.mode_ != OmitMode) {
2983 auto entry(plist_new_dict());
2984 plist_dict_set_item(entry, "hash", plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
2985 if (!old)
2986 plist_dict_set_item(entry, "hash2", plist_new_data(reinterpret_cast<const char *>(hash.second.sha256_), sizeof(hash.second.sha256_)));
2987 if (rule.mode_ == OptionalMode)
2988 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2989 plist_dict_set_item(files, hash.first.c_str(), entry);
2990 }
2991
2992 break;
2993 }
2994
2995 if (!old)
2996 for (const auto &link : local.links)
2997 for (const auto &rule : version.second)
2998 if (rule(link.first)) {
2999 if (rule.mode_ != OmitMode) {
3000 auto entry(plist_new_dict());
3001 plist_dict_set_item(entry, "symlink", plist_new_string(link.second.c_str()));
3002 if (rule.mode_ == OptionalMode)
3003 plist_dict_set_item(entry, "optional", plist_new_bool(true));
3004 plist_dict_set_item(files, link.first.c_str(), entry);
3005 }
3006
3007 break;
3008 }
3009
3010 if (!old && mac)
3011 for (const auto &bundle : bundles) {
3012 auto entry(plist_new_dict());
3013 plist_dict_set_item(entry, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle.second.hash.sha256_), sizeof(bundle.second.hash.sha256_)));
3014 plist_dict_set_item(entry, "requirement", plist_new_string("anchor apple generic"));
3015 plist_dict_set_item(files, bundle.first.c_str(), entry);
3016 }
3017 }
3018
3019 for (const auto &version : versions) {
3020 auto rules(plist_new_dict());
3021 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
3022
3023 std::multiset<const Rule *, RuleCode> ordered;
3024 for (const auto &rule : version.second)
3025 ordered.insert(&rule);
3026
3027 for (const auto &rule : ordered)
3028 if (rule->weight_ == 1 && rule->mode_ == NoMode)
3029 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
3030 else {
3031 auto entry(plist_new_dict());
3032 plist_dict_set_item(rules, rule->code_.c_str(), entry);
3033
3034 switch (rule->mode_) {
3035 case NoMode:
3036 break;
3037 case OmitMode:
3038 plist_dict_set_item(entry, "omit", plist_new_bool(true));
3039 break;
3040 case OptionalMode:
3041 plist_dict_set_item(entry, "optional", plist_new_bool(true));
3042 break;
3043 case NestedMode:
3044 plist_dict_set_item(entry, "nested", plist_new_bool(true));
3045 break;
3046 case TopMode:
3047 plist_dict_set_item(entry, "top", plist_new_bool(true));
3048 break;
3049 }
3050
3051 if (rule->weight_ >= 10000)
3052 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
3053 else if (rule->weight_ != 1)
3054 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
3055 }
3056 }
3057
3058 folder.Save(signature, true, NULL, fun([&](std::streambuf &save) {
3059 HashProxy proxy(local.files[signature], save);
3060 char *xml(NULL);
3061 uint32_t size;
3062 plist_to_xml(plist, &xml, &size);
3063 _scope({ free(xml); });
3064 put(proxy, xml, size);
3065 }));
3066
3067 Bundle bundle;
3068 bundle.path = folder.Path(executable);
3069
3070 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
3071 progress(root + executable);
3072 folder.Save(executable, true, flag, fun([&](std::streambuf &save) {
3073 Slots slots;
3074 slots[1] = local.files.at(info);
3075 slots[3] = local.files.at(signature);
3076 bundle.hash = Sign(NULL, 0, buffer, local.files[executable], save, identifier, entitlements, false, requirements, key, slots, length, 0, false, Progression(progress, root + executable));
3077 }));
3078 }));
3079
3080 return bundle;
3081 }
3082
3083 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) {
3084 State local;
3085 return Sign(root, folder, key, local, requirements, alter, progress);
3086 }
3087 #endif
3088
3089 #endif
3090 }
3091
3092 std::string Hex(const uint8_t *data, size_t size) {
3093 std::string hex;
3094 hex.reserve(size * 2);
3095 for (size_t i(0); i != size; ++i) {
3096 hex += "0123456789abcdef"[data[i] >> 4];
3097 hex += "0123456789abcdef"[data[i] & 0xf];
3098 }
3099 return hex;
3100 }
3101
3102 static void usage(const char *argv0) {
3103 fprintf(stderr, "Link Identity Editor %s\n\n", LDID_VERSION);
3104 fprintf(stderr, "usage: %s [-Acputype:subtype] [-a] [-C[adhoc | enforcement | expires | hard |\n", argv0);
3105 fprintf(stderr, " host | kill | library-validation | restrict | runtime]] [-D] [-d]\n");
3106 fprintf(stderr, " [-Enum:file] [-e] [-h] [-Kkey.p12 [-Upassword]] [-M] [-P] [-q]\n");
3107 fprintf(stderr, " [-r | -Sfile | -s] [-Ttimestamp] [-u] file ...\n\n");
3108 fprintf(stderr, "Options:\n");
3109 fprintf(stderr, " -S[file.xml] Pseudo-sign using the entitlements in file.xml\n");
3110 fprintf(stderr, " -Kkey.p12 Sign using private key in key.p12\n");
3111 fprintf(stderr, " -Upassword Use password to unlock key.p12\n");
3112 fprintf(stderr, " -M Merge entitlements with any existing\n");
3113 fprintf(stderr, " -h Print CDHash of file\n\n");
3114 fprintf(stderr, "More information: 'man ldid'\n");
3115 }
3116
3117 #ifndef LDID_NOTOOLS
3118 int main(int argc, char *argv[]) {
3119 #ifndef LDID_NOSMIME
3120 OpenSSL_add_all_algorithms();
3121 # if OPENSSL_VERSION_MAJOR >= 3
3122 OSSL_PROVIDER *legacy = OSSL_PROVIDER_load(NULL, "legacy");
3123 OSSL_PROVIDER *deflt = OSSL_PROVIDER_load(NULL, "default");
3124 # endif
3125 #endif
3126
3127 union {
3128 uint16_t word;
3129 uint8_t byte[2];
3130 } endian = {1};
3131
3132 little_ = endian.byte[0];
3133
3134 bool flag_r(false);
3135 bool flag_e(false);
3136 bool flag_q(false);
3137
3138 bool flag_H(false);
3139 bool flag_h(false);
3140
3141 #ifndef LDID_NOFLAGT
3142 bool flag_T(false);
3143 #endif
3144
3145 bool flag_S(false);
3146 bool flag_s(false);
3147
3148 bool flag_D(false);
3149 bool flag_d(false);
3150
3151 bool flag_A(false);
3152 bool flag_a(false);
3153
3154 bool flag_u(false);
3155
3156 bool flag_M(false);
3157
3158 uint32_t flags(0);
3159 bool platform(false);
3160
3161 uint32_t flag_CPUType(_not(uint32_t));
3162 uint32_t flag_CPUSubtype(_not(uint32_t));
3163
3164 const char *flag_I(NULL);
3165
3166 #ifndef LDID_NOFLAGT
3167 bool timeh(false);
3168 uint32_t timev(0);
3169 #endif
3170
3171 Map entitlements;
3172 Map requirements;
3173 Map key;
3174 ldid::Slots slots;
3175
3176 std::vector<std::string> files;
3177
3178 if (argc == 1) {
3179 usage(argv[0]);
3180 return 0;
3181 }
3182
3183 for (int argi(1); argi != argc; ++argi)
3184 if (argv[argi][0] != '-')
3185 files.push_back(argv[argi]);
3186 else switch (argv[argi][1]) {
3187 case 'r':
3188 _assert(!flag_s);
3189 _assert(!flag_S);
3190 flag_r = true;
3191 break;
3192
3193 case 'e': flag_e = true; break;
3194
3195 case 'E': {
3196 const char *string = argv[argi] + 2;
3197 const char *colon = strchr(string, ':');
3198 _assert(colon != NULL);
3199 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
3200 char *arge;
3201 unsigned number(strtoul(string, &arge, 0));
3202 _assert(arge == colon);
3203 auto &slot(slots[number]);
3204 for (Algorithm *algorithm : GetAlgorithms())
3205 (*algorithm)(slot, file.data(), file.size());
3206 } break;
3207
3208 case 'q': flag_q = true; break;
3209
3210 case 'H': {
3211 const char *hash = argv[argi] + 2;
3212
3213 if (!flag_H) {
3214 flag_H = true;
3215
3216 do_sha1 = false;
3217 do_sha256 = false;
3218 }
3219
3220 if (false);
3221 else if (strcmp(hash, "sha1") == 0)
3222 do_sha1 = true;
3223 else if (strcmp(hash, "sha256") == 0)
3224 do_sha256 = true;
3225 else _assert(false);
3226 } break;
3227
3228 case 'h': flag_h = true; break;
3229
3230 case 'Q': {
3231 const char *xml = argv[argi] + 2;
3232 requirements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
3233 } break;
3234
3235 case 'D': flag_D = true; break;
3236 case 'd': flag_d = true; break;
3237
3238 case 'a': flag_a = true; break;
3239
3240 case 'A':
3241 _assert(!flag_A);
3242 flag_A = true;
3243 if (argv[argi][2] != '\0') {
3244 const char *cpu = argv[argi] + 2;
3245 const char *colon = strchr(cpu, ':');
3246 _assert(colon != NULL);
3247 char *arge;
3248 flag_CPUType = strtoul(cpu, &arge, 0);
3249 _assert(arge == colon);
3250 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
3251 _assert(arge == argv[argi] + strlen(argv[argi]));
3252 }
3253 break;
3254
3255 case 'C': {
3256 const char *name = argv[argi] + 2;
3257 if (false);
3258 else if (strcmp(name, "host") == 0)
3259 flags |= kSecCodeSignatureHost;
3260 else if (strcmp(name, "adhoc") == 0)
3261 flags |= kSecCodeSignatureAdhoc;
3262 else if (strcmp(name, "hard") == 0)
3263 flags |= kSecCodeSignatureForceHard;
3264 else if (strcmp(name, "kill") == 0)
3265 flags |= kSecCodeSignatureForceKill;
3266 else if (strcmp(name, "expires") == 0)
3267 flags |= kSecCodeSignatureForceExpiration;
3268 else if (strcmp(name, "restrict") == 0)
3269 flags |= kSecCodeSignatureRestrict;
3270 else if (strcmp(name, "enforcement") == 0)
3271 flags |= kSecCodeSignatureEnforcement;
3272 else if (strcmp(name, "library-validation") == 0)
3273 flags |= kSecCodeSignatureLibraryValidation;
3274 else if (strcmp(name, "runtime") == 0)
3275 flags |= kSecCodeSignatureRuntime;
3276 else _assert(false);
3277 } break;
3278
3279 case 'P':
3280 platform = true;
3281 break;
3282
3283 case 's':
3284 _assert(!flag_r);
3285 _assert(!flag_S);
3286 flag_s = true;
3287 break;
3288
3289 case 'S':
3290 _assert(!flag_r);
3291 _assert(!flag_s);
3292 flag_S = true;
3293 if (argv[argi][2] != '\0') {
3294 const char *xml = argv[argi] + 2;
3295 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
3296 }
3297 break;
3298
3299 case 'M':
3300 flag_M = true;
3301 break;
3302
3303 case 'U':
3304 password = argv[argi] + 2;
3305 break;
3306
3307 case 'K':
3308 if (argv[argi][2] != '\0')
3309 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
3310 break;
3311
3312 #ifndef LDID_NOFLAGT
3313 case 'T': {
3314 flag_T = true;
3315 if (argv[argi][2] == '-')
3316 timeh = true;
3317 else {
3318 char *arge;
3319 timev = strtoul(argv[argi] + 2, &arge, 0);
3320 _assert(arge == argv[argi] + strlen(argv[argi]));
3321 }
3322 } break;
3323 #endif
3324
3325 case 'u': {
3326 flag_u = true;
3327 } break;
3328
3329 case 'I': {
3330 flag_I = argv[argi] + 2;
3331 } break;
3332
3333 default:
3334 usage(argv[0]);
3335 return 1;
3336 break;
3337 }
3338
3339 _assert(flag_S || key.empty());
3340 _assert(flag_S || flag_I == NULL);
3341
3342 if (flag_d && !flag_h) {
3343 flag_h = true;
3344 fprintf(stderr, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3345 }
3346
3347 if (files.empty())
3348 return 0;
3349
3350 size_t filei(0), filee(0);
3351 _foreach (file, files) try {
3352 std::string path(file);
3353
3354 struct stat info;
3355 _syscall(stat(path.c_str(), &info));
3356
3357 if (S_ISDIR(info.st_mode)) {
3358 _assert(flag_S);
3359 #ifndef LDID_NOPLIST
3360 ldid::DiskFolder folder(path + "/");
3361 path += "/" + Sign("", folder, key, requirements, ldid::fun([&](const std::string &, const std::string &) -> std::string { return entitlements; }), dummy_).path;
3362 #else
3363 _assert(false);
3364 #endif
3365 } else if (flag_S || flag_r) {
3366 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
3367
3368 std::filebuf output;
3369 Split split(path);
3370 auto temp(Temporary(output, split));
3371
3372 if (flag_r)
3373 ldid::Unsign(input.data(), input.size(), output, dummy_);
3374 else {
3375 std::string identifier(flag_I ?: split.base.c_str());
3376 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, flag_M, requirements, key, slots, flags, platform, dummy_);
3377 }
3378
3379 Commit(path, temp);
3380 }
3381
3382 bool modify(false);
3383 #ifndef LDID_NOFLAGT
3384 if (flag_T)
3385 modify = true;
3386 #endif
3387 if (flag_s)
3388 modify = true;
3389
3390 Map mapping(path, modify);
3391 FatHeader fat_header(mapping.data(), mapping.size());
3392
3393 _foreach (mach_header, fat_header.GetMachHeaders()) {
3394 struct linkedit_data_command *signature(NULL);
3395 struct encryption_info_command *encryption(NULL);
3396
3397 if (flag_A) {
3398 if (mach_header.GetCPUType() != flag_CPUType)
3399 continue;
3400 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
3401 continue;
3402 }
3403
3404 if (flag_a)
3405 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
3406
3407 _foreach (load_command, mach_header.GetLoadCommands()) {
3408 uint32_t cmd(mach_header.Swap(load_command->cmd));
3409
3410 if (false);
3411 else if (cmd == LC_CODE_SIGNATURE)
3412 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
3413 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
3414 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
3415 else if (cmd == LC_LOAD_DYLIB) {
3416 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
3417 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
3418
3419 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3420 if (flag_u) {
3421 Version version;
3422 version.value = mach_header.Swap(dylib_command->dylib.current_version);
3423 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
3424 }
3425 }
3426 }
3427 #ifndef LDID_NOFLAGT
3428 else if (cmd == LC_ID_DYLIB) {
3429 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
3430
3431 if (flag_T) {
3432 uint32_t timed;
3433
3434 if (!timeh)
3435 timed = timev;
3436 else {
3437 dylib_command->dylib.timestamp = 0;
3438 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
3439 }
3440
3441 dylib_command->dylib.timestamp = mach_header.Swap(timed);
3442 }
3443 }
3444 #endif
3445 }
3446
3447 if (flag_d && encryption != NULL) {
3448 printf("cryptid=%d\n", mach_header.Swap(encryption->cryptid));
3449 }
3450
3451 if (flag_D) {
3452 _assert(encryption != NULL);
3453 encryption->cryptid = mach_header.Swap(0);
3454 }
3455
3456 if (flag_e) {
3457 _assert(signature != NULL);
3458
3459 uint32_t data = mach_header.Swap(signature->dataoff);
3460
3461 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3462 uint8_t *blob = top + data;
3463 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3464
3465 for (size_t index(0); index != Swap(super->count); ++index)
3466 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
3467 uint32_t begin = Swap(super->index[index].offset);
3468 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
3469 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
3470 }
3471 }
3472
3473 if (flag_q) {
3474 _assert(signature != NULL);
3475
3476 uint32_t data = mach_header.Swap(signature->dataoff);
3477
3478 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3479 uint8_t *blob = top + data;
3480 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3481
3482 for (size_t index(0); index != Swap(super->count); ++index)
3483 if (Swap(super->index[index].type) == CSSLOT_REQUIREMENTS) {
3484 uint32_t begin = Swap(super->index[index].offset);
3485 struct Blob *requirement = reinterpret_cast<struct Blob *>(blob + begin);
3486 fwrite(requirement, 1, Swap(requirement->length), stdout);
3487 }
3488 }
3489
3490 if (flag_s) {
3491 _assert(signature != NULL);
3492
3493 uint32_t data = mach_header.Swap(signature->dataoff);
3494
3495 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3496 uint8_t *blob = top + data;
3497 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3498
3499 for (size_t index(0); index != Swap(super->count); ++index)
3500 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
3501 uint32_t begin = Swap(super->index[index].offset);
3502 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob));
3503
3504 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
3505 uint32_t pages = Swap(directory->nCodeSlots);
3506
3507 if (pages != 1)
3508 for (size_t i = 0; i != pages - 1; ++i)
3509 LDID_SHA1(top + PageSize_ * i, PageSize_, hashes[i]);
3510 if (pages != 0)
3511 LDID_SHA1(top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1, hashes[pages - 1]);
3512 }
3513 }
3514
3515 if (flag_h) {
3516 _assert(signature != NULL);
3517
3518 auto algorithms(GetAlgorithms());
3519
3520 uint32_t data = mach_header.Swap(signature->dataoff);
3521
3522 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3523 uint8_t *blob = top + data;
3524 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3525
3526 struct Candidate {
3527 CodeDirectory *directory_;
3528 size_t size_;
3529 Algorithm &algorithm_;
3530 std::string hash_;
3531 };
3532
3533 std::map<uint8_t, Candidate> candidates;
3534
3535 for (size_t index(0); index != Swap(super->count); ++index) {
3536 auto type(Swap(super->index[index].type));
3537 if ((type == CSSLOT_CODEDIRECTORY || type >= CSSLOT_ALTERNATE) && type != CSSLOT_SIGNATURESLOT) {
3538 uint32_t begin = Swap(super->index[index].offset);
3539 uint32_t end = index + 1 == Swap(super->count) ? Swap(super->blob.length) : Swap(super->index[index + 1].offset);
3540 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob));
3541 auto type(directory->hashType);
3542 _assert(type > 0 && type <= algorithms.size());
3543 auto &algorithm(*algorithms[type - 1]);
3544 uint8_t hash[algorithm.size_];
3545 algorithm(hash, blob + begin, end - begin);
3546 candidates.insert({type, {directory, end - begin, algorithm, Hex(hash, 20)}});
3547 }
3548 }
3549
3550 _assert(!candidates.empty());
3551 auto best(candidates.end());
3552 --best;
3553
3554 const auto directory(best->second.directory_);
3555 const auto flags(Swap(directory->flags));
3556
3557 std::string names;
3558 if (flags & kSecCodeSignatureHost)
3559 names += ",host";
3560 if (flags & kSecCodeSignatureAdhoc)
3561 names += ",adhoc";
3562 if (flags & kSecCodeSignatureForceHard)
3563 names += ",hard";
3564 if (flags & kSecCodeSignatureForceKill)
3565 names += ",kill";
3566 if (flags & kSecCodeSignatureForceExpiration)
3567 names += ",expires";
3568 if (flags & kSecCodeSignatureRestrict)
3569 names += ",restrict";
3570 if (flags & kSecCodeSignatureEnforcement)
3571 names += ",enforcement";
3572 if (flags & kSecCodeSignatureLibraryValidation)
3573 names += ",library-validation";
3574 if (flags & kSecCodeSignatureRuntime)
3575 names += ",runtime";
3576
3577 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3578 Swap(directory->version), best->second.size_, flags, names.empty() ? "none" : names.c_str() + 1, Swap(directory->nCodeSlots), Swap(directory->nSpecialSlots));
3579 printf("Hash type=%s size=%d\n", best->second.algorithm_.name(), directory->hashSize);
3580
3581 std::string choices;
3582 for (const auto &candidate : candidates) {
3583 auto choice(candidate.second.algorithm_.name());
3584 choices += ',';
3585 choices += choice;
3586 printf("CandidateCDHash %s=%s\n", choice, candidate.second.hash_.c_str());
3587 }
3588 printf("Hash choices=%s\n", choices.c_str() + 1);
3589
3590 printf("CDHash=%s\n", best->second.hash_.c_str());
3591 }
3592 }
3593
3594 ++filei;
3595 } catch (const char *) {
3596 ++filee;
3597 ++filei;
3598 }
3599
3600 #ifndef LDID_NOSMIME
3601 # if OPENSSL_VERSION_MAJOR >= 3
3602 OSSL_PROVIDER_unload(legacy);
3603 OSSL_PROVIDER_unload(deflt);
3604 # endif
3605 #endif
3606
3607 return filee;
3608 }
3609 #endif