]> git.saurik.com Git - ldid.git/blob - ldid.cpp
Wrap assertion strings, for configuration by host.
[ldid.git] / ldid.cpp
1 /* ldid - (Mach-O) Link-Loader Identity Editor
2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #include <cstdio>
23 #include <cstdlib>
24 #include <cstring>
25 #include <fstream>
26 #include <iostream>
27 #include <memory>
28 #include <set>
29 #include <sstream>
30 #include <string>
31 #include <vector>
32
33 #include <dirent.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <regex.h>
37 #include <stdbool.h>
38 #include <stdint.h>
39 #include <unistd.h>
40
41 #include <sys/mman.h>
42 #include <sys/stat.h>
43 #include <sys/types.h>
44
45 #ifndef LDID_NOSMIME
46 #include <openssl/err.h>
47 #include <openssl/pem.h>
48 #include <openssl/pkcs7.h>
49 #include <openssl/pkcs12.h>
50 #endif
51
52 #ifdef __APPLE__
53 #include <CommonCrypto/CommonDigest.h>
54
55 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
56 #define LDID_SHA1 CC_SHA1
57 #define LDID_SHA1_CTX CC_SHA1_CTX
58 #define LDID_SHA1_Init CC_SHA1_Init
59 #define LDID_SHA1_Update CC_SHA1_Update
60 #define LDID_SHA1_Final CC_SHA1_Final
61
62 #define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
63 #define LDID_SHA256 CC_SHA256
64 #define LDID_SHA256_CTX CC_SHA256_CTX
65 #define LDID_SHA256_Init CC_SHA256_Init
66 #define LDID_SHA256_Update CC_SHA256_Update
67 #define LDID_SHA256_Final CC_SHA256_Final
68 #else
69 #include <openssl/sha.h>
70
71 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
72 #define LDID_SHA1 SHA1
73 #define LDID_SHA1_CTX SHA_CTX
74 #define LDID_SHA1_Init SHA1_Init
75 #define LDID_SHA1_Update SHA1_Update
76 #define LDID_SHA1_Final SHA1_Final
77
78 #define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
79 #define LDID_SHA256 SHA256
80 #define LDID_SHA256_CTX SHA256_CTX
81 #define LDID_SHA256_Init SHA256_Init
82 #define LDID_SHA256_Update SHA256_Update
83 #define LDID_SHA256_Final SHA256_Final
84 #endif
85
86 #ifndef LDID_NOPLIST
87 #include <plist/plist.h>
88 #endif
89
90 #include "ldid.hpp"
91
92 #define _assert___(line) \
93 #line
94 #define _assert__(line) \
95 _assert___(line)
96
97 #ifndef $
98 #define $(value) value
99 #endif
100
101 #ifdef __EXCEPTIONS
102 #define _assert_(expr, format, ...) \
103 do if (!(expr)) { \
104 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
105 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
106 } while (false)
107 #else
108 // XXX: this is not acceptable
109 #define _assert_(expr, format, ...) \
110 do if (!(expr)) { \
111 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
112 exit(-1); \
113 } while (false)
114 #endif
115
116 #define _assert(expr) \
117 _assert_(expr, "%s", $(#expr))
118
119 #define _syscall(expr, ...) [&] { for (;;) { \
120 auto _value(expr); \
121 if ((long) _value != -1) \
122 return _value; \
123 int error(errno); \
124 if (error == EINTR) \
125 continue; \
126 /* XXX: EINTR is included in this list to fix g++ */ \
127 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
128 if (error == success) \
129 return (decltype(expr)) -success; \
130 _assert_(false, "errno=%u", error); \
131 } }()
132
133 #define _trace() \
134 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
135
136 #define _not(type) \
137 ((type) ~ (type) 0)
138
139 #define _packed \
140 __attribute__((packed))
141
142 template <typename Type_>
143 struct Iterator_ {
144 typedef typename Type_::const_iterator Result;
145 };
146
147 #define _foreach(item, list) \
148 for (bool _stop(true); _stop; ) \
149 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
150 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
151 for (bool _suck(true); _suck; _suck = false) \
152 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
153
154 class _Scope {
155 };
156
157 template <typename Function_>
158 class Scope :
159 public _Scope
160 {
161 private:
162 Function_ function_;
163
164 public:
165 Scope(const Function_ &function) :
166 function_(function)
167 {
168 }
169
170 ~Scope() {
171 function_();
172 }
173 };
174
175 template <typename Function_>
176 Scope<Function_> _scope(const Function_ &function) {
177 return Scope<Function_>(function);
178 }
179
180 #define _scope__(counter, function) \
181 __attribute__((__unused__)) \
182 const _Scope &_scope ## counter(_scope([&]function))
183 #define _scope_(counter, function) \
184 _scope__(counter, function)
185 #define _scope(function) \
186 _scope_(__COUNTER__, function)
187
188 #define CPU_ARCH_MASK uint32_t(0xff000000)
189 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
190
191 #define CPU_TYPE_ANY uint32_t(-1)
192 #define CPU_TYPE_VAX uint32_t( 1)
193 #define CPU_TYPE_MC680x0 uint32_t( 6)
194 #define CPU_TYPE_X86 uint32_t( 7)
195 #define CPU_TYPE_MC98000 uint32_t(10)
196 #define CPU_TYPE_HPPA uint32_t(11)
197 #define CPU_TYPE_ARM uint32_t(12)
198 #define CPU_TYPE_MC88000 uint32_t(13)
199 #define CPU_TYPE_SPARC uint32_t(14)
200 #define CPU_TYPE_I860 uint32_t(15)
201 #define CPU_TYPE_POWERPC uint32_t(18)
202
203 #define CPU_TYPE_I386 CPU_TYPE_X86
204
205 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
206 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
207 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
208
209 struct fat_header {
210 uint32_t magic;
211 uint32_t nfat_arch;
212 } _packed;
213
214 #define FAT_MAGIC 0xcafebabe
215 #define FAT_CIGAM 0xbebafeca
216
217 struct fat_arch {
218 uint32_t cputype;
219 uint32_t cpusubtype;
220 uint32_t offset;
221 uint32_t size;
222 uint32_t align;
223 } _packed;
224
225 struct mach_header {
226 uint32_t magic;
227 uint32_t cputype;
228 uint32_t cpusubtype;
229 uint32_t filetype;
230 uint32_t ncmds;
231 uint32_t sizeofcmds;
232 uint32_t flags;
233 } _packed;
234
235 #define MH_MAGIC 0xfeedface
236 #define MH_CIGAM 0xcefaedfe
237
238 #define MH_MAGIC_64 0xfeedfacf
239 #define MH_CIGAM_64 0xcffaedfe
240
241 #define MH_DYLDLINK 0x4
242
243 #define MH_OBJECT 0x1
244 #define MH_EXECUTE 0x2
245 #define MH_DYLIB 0x6
246 #define MH_BUNDLE 0x8
247 #define MH_DYLIB_STUB 0x9
248
249 struct load_command {
250 uint32_t cmd;
251 uint32_t cmdsize;
252 } _packed;
253
254 #define LC_REQ_DYLD uint32_t(0x80000000)
255
256 #define LC_SEGMENT uint32_t(0x01)
257 #define LC_SYMTAB uint32_t(0x02)
258 #define LC_DYSYMTAB uint32_t(0x0b)
259 #define LC_LOAD_DYLIB uint32_t(0x0c)
260 #define LC_ID_DYLIB uint32_t(0x0d)
261 #define LC_SEGMENT_64 uint32_t(0x19)
262 #define LC_UUID uint32_t(0x1b)
263 #define LC_CODE_SIGNATURE uint32_t(0x1d)
264 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
265 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
266 #define LC_ENCRYPTION_INFO uint32_t(0x21)
267 #define LC_DYLD_INFO uint32_t(0x22)
268 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
269 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
270
271 union Version {
272 struct {
273 uint8_t patch;
274 uint8_t minor;
275 uint16_t major;
276 } _packed;
277
278 uint32_t value;
279 };
280
281 struct dylib {
282 uint32_t name;
283 uint32_t timestamp;
284 uint32_t current_version;
285 uint32_t compatibility_version;
286 } _packed;
287
288 struct dylib_command {
289 uint32_t cmd;
290 uint32_t cmdsize;
291 struct dylib dylib;
292 } _packed;
293
294 struct uuid_command {
295 uint32_t cmd;
296 uint32_t cmdsize;
297 uint8_t uuid[16];
298 } _packed;
299
300 struct symtab_command {
301 uint32_t cmd;
302 uint32_t cmdsize;
303 uint32_t symoff;
304 uint32_t nsyms;
305 uint32_t stroff;
306 uint32_t strsize;
307 } _packed;
308
309 struct dyld_info_command {
310 uint32_t cmd;
311 uint32_t cmdsize;
312 uint32_t rebase_off;
313 uint32_t rebase_size;
314 uint32_t bind_off;
315 uint32_t bind_size;
316 uint32_t weak_bind_off;
317 uint32_t weak_bind_size;
318 uint32_t lazy_bind_off;
319 uint32_t lazy_bind_size;
320 uint32_t export_off;
321 uint32_t export_size;
322 } _packed;
323
324 struct dysymtab_command {
325 uint32_t cmd;
326 uint32_t cmdsize;
327 uint32_t ilocalsym;
328 uint32_t nlocalsym;
329 uint32_t iextdefsym;
330 uint32_t nextdefsym;
331 uint32_t iundefsym;
332 uint32_t nundefsym;
333 uint32_t tocoff;
334 uint32_t ntoc;
335 uint32_t modtaboff;
336 uint32_t nmodtab;
337 uint32_t extrefsymoff;
338 uint32_t nextrefsyms;
339 uint32_t indirectsymoff;
340 uint32_t nindirectsyms;
341 uint32_t extreloff;
342 uint32_t nextrel;
343 uint32_t locreloff;
344 uint32_t nlocrel;
345 } _packed;
346
347 struct dylib_table_of_contents {
348 uint32_t symbol_index;
349 uint32_t module_index;
350 } _packed;
351
352 struct dylib_module {
353 uint32_t module_name;
354 uint32_t iextdefsym;
355 uint32_t nextdefsym;
356 uint32_t irefsym;
357 uint32_t nrefsym;
358 uint32_t ilocalsym;
359 uint32_t nlocalsym;
360 uint32_t iextrel;
361 uint32_t nextrel;
362 uint32_t iinit_iterm;
363 uint32_t ninit_nterm;
364 uint32_t objc_module_info_addr;
365 uint32_t objc_module_info_size;
366 } _packed;
367
368 struct dylib_reference {
369 uint32_t isym:24;
370 uint32_t flags:8;
371 } _packed;
372
373 struct relocation_info {
374 int32_t r_address;
375 uint32_t r_symbolnum:24;
376 uint32_t r_pcrel:1;
377 uint32_t r_length:2;
378 uint32_t r_extern:1;
379 uint32_t r_type:4;
380 } _packed;
381
382 struct nlist {
383 union {
384 char *n_name;
385 int32_t n_strx;
386 } n_un;
387
388 uint8_t n_type;
389 uint8_t n_sect;
390 uint8_t n_desc;
391 uint32_t n_value;
392 } _packed;
393
394 struct segment_command {
395 uint32_t cmd;
396 uint32_t cmdsize;
397 char segname[16];
398 uint32_t vmaddr;
399 uint32_t vmsize;
400 uint32_t fileoff;
401 uint32_t filesize;
402 uint32_t maxprot;
403 uint32_t initprot;
404 uint32_t nsects;
405 uint32_t flags;
406 } _packed;
407
408 struct segment_command_64 {
409 uint32_t cmd;
410 uint32_t cmdsize;
411 char segname[16];
412 uint64_t vmaddr;
413 uint64_t vmsize;
414 uint64_t fileoff;
415 uint64_t filesize;
416 uint32_t maxprot;
417 uint32_t initprot;
418 uint32_t nsects;
419 uint32_t flags;
420 } _packed;
421
422 struct section {
423 char sectname[16];
424 char segname[16];
425 uint32_t addr;
426 uint32_t size;
427 uint32_t offset;
428 uint32_t align;
429 uint32_t reloff;
430 uint32_t nreloc;
431 uint32_t flags;
432 uint32_t reserved1;
433 uint32_t reserved2;
434 } _packed;
435
436 struct section_64 {
437 char sectname[16];
438 char segname[16];
439 uint64_t addr;
440 uint64_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 uint32_t reserved3;
449 } _packed;
450
451 struct linkedit_data_command {
452 uint32_t cmd;
453 uint32_t cmdsize;
454 uint32_t dataoff;
455 uint32_t datasize;
456 } _packed;
457
458 struct encryption_info_command {
459 uint32_t cmd;
460 uint32_t cmdsize;
461 uint32_t cryptoff;
462 uint32_t cryptsize;
463 uint32_t cryptid;
464 } _packed;
465
466 #define BIND_OPCODE_MASK 0xf0
467 #define BIND_IMMEDIATE_MASK 0x0f
468 #define BIND_OPCODE_DONE 0x00
469 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
470 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
471 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
472 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
473 #define BIND_OPCODE_SET_TYPE_IMM 0x50
474 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
475 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
476 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
477 #define BIND_OPCODE_DO_BIND 0x90
478 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
479 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
480 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
481
482 static auto dummy([](double) {});
483
484 static std::streamsize read(std::streambuf &stream, void *data, size_t size) {
485 auto writ(stream.sgetn(static_cast<char *>(data), size));
486 _assert(writ >= 0);
487 return writ;
488 }
489
490 static inline void get(std::streambuf &stream, void *data, size_t size) {
491 _assert(read(stream, data, size) == size);
492 }
493
494 static inline void put(std::streambuf &stream, const void *data, size_t size) {
495 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
496 }
497
498 static inline void put(std::streambuf &stream, const void *data, size_t size, const ldid::Functor<void (double)> &percent) {
499 percent(0);
500 for (size_t total(0); total != size;) {
501 auto writ(std::min(size - total, size_t(4096 * 4)));
502 _assert(stream.sputn(static_cast<const char *>(data) + total, writ) == writ);
503 total += writ;
504 percent(double(total) / size);
505 }
506 }
507
508 static size_t most(std::streambuf &stream, void *data, size_t size) {
509 size_t total(size);
510 while (size > 0)
511 if (auto writ = read(stream, data, size))
512 size -= writ;
513 else break;
514 return total - size;
515 }
516
517 static inline void pad(std::streambuf &stream, size_t size) {
518 char padding[size];
519 memset(padding, 0, size);
520 put(stream, padding, size);
521 }
522
523 template <typename Type_>
524 Type_ Align(Type_ value, size_t align) {
525 value += align - 1;
526 value /= align;
527 value *= align;
528 return value;
529 }
530
531 static const uint8_t PageShift_(0x0c);
532 static const uint32_t PageSize_(1 << PageShift_);
533
534 static inline uint16_t Swap_(uint16_t value) {
535 return
536 ((value >> 8) & 0x00ff) |
537 ((value << 8) & 0xff00);
538 }
539
540 static inline uint32_t Swap_(uint32_t value) {
541 value = ((value >> 8) & 0x00ff00ff) |
542 ((value << 8) & 0xff00ff00);
543 value = ((value >> 16) & 0x0000ffff) |
544 ((value << 16) & 0xffff0000);
545 return value;
546 }
547
548 static inline uint64_t Swap_(uint64_t value) {
549 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
550 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
551 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
552 return value;
553 }
554
555 static inline int16_t Swap_(int16_t value) {
556 return Swap_(static_cast<uint16_t>(value));
557 }
558
559 static inline int32_t Swap_(int32_t value) {
560 return Swap_(static_cast<uint32_t>(value));
561 }
562
563 static inline int64_t Swap_(int64_t value) {
564 return Swap_(static_cast<uint64_t>(value));
565 }
566
567 static bool little_(true);
568
569 static inline uint16_t Swap(uint16_t value) {
570 return little_ ? Swap_(value) : value;
571 }
572
573 static inline uint32_t Swap(uint32_t value) {
574 return little_ ? Swap_(value) : value;
575 }
576
577 static inline uint64_t Swap(uint64_t value) {
578 return little_ ? Swap_(value) : value;
579 }
580
581 static inline int16_t Swap(int16_t value) {
582 return Swap(static_cast<uint16_t>(value));
583 }
584
585 static inline int32_t Swap(int32_t value) {
586 return Swap(static_cast<uint32_t>(value));
587 }
588
589 static inline int64_t Swap(int64_t value) {
590 return Swap(static_cast<uint64_t>(value));
591 }
592
593 class Swapped {
594 protected:
595 bool swapped_;
596
597 Swapped() :
598 swapped_(false)
599 {
600 }
601
602 public:
603 Swapped(bool swapped) :
604 swapped_(swapped)
605 {
606 }
607
608 template <typename Type_>
609 Type_ Swap(Type_ value) const {
610 return swapped_ ? Swap_(value) : value;
611 }
612 };
613
614 class Data :
615 public Swapped
616 {
617 private:
618 void *base_;
619 size_t size_;
620
621 public:
622 Data(void *base, size_t size) :
623 base_(base),
624 size_(size)
625 {
626 }
627
628 void *GetBase() const {
629 return base_;
630 }
631
632 size_t GetSize() const {
633 return size_;
634 }
635 };
636
637 class MachHeader :
638 public Data
639 {
640 private:
641 bool bits64_;
642
643 struct mach_header *mach_header_;
644 struct load_command *load_command_;
645
646 public:
647 MachHeader(void *base, size_t size) :
648 Data(base, size)
649 {
650 mach_header_ = (mach_header *) base;
651
652 switch (Swap(mach_header_->magic)) {
653 case MH_CIGAM:
654 swapped_ = !swapped_;
655 case MH_MAGIC:
656 bits64_ = false;
657 break;
658
659 case MH_CIGAM_64:
660 swapped_ = !swapped_;
661 case MH_MAGIC_64:
662 bits64_ = true;
663 break;
664
665 default:
666 _assert(false);
667 }
668
669 void *post = mach_header_ + 1;
670 if (bits64_)
671 post = (uint32_t *) post + 1;
672 load_command_ = (struct load_command *) post;
673
674 _assert(
675 Swap(mach_header_->filetype) == MH_EXECUTE ||
676 Swap(mach_header_->filetype) == MH_DYLIB ||
677 Swap(mach_header_->filetype) == MH_BUNDLE
678 );
679 }
680
681 bool Bits64() const {
682 return bits64_;
683 }
684
685 struct mach_header *operator ->() const {
686 return mach_header_;
687 }
688
689 operator struct mach_header *() const {
690 return mach_header_;
691 }
692
693 uint32_t GetCPUType() const {
694 return Swap(mach_header_->cputype);
695 }
696
697 uint32_t GetCPUSubtype() const {
698 return Swap(mach_header_->cpusubtype) & 0xff;
699 }
700
701 struct load_command *GetLoadCommand() const {
702 return load_command_;
703 }
704
705 std::vector<struct load_command *> GetLoadCommands() const {
706 std::vector<struct load_command *> load_commands;
707
708 struct load_command *load_command = load_command_;
709 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
710 load_commands.push_back(load_command);
711 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
712 }
713
714 return load_commands;
715 }
716
717 void ForSection(const ldid::Functor<void (const char *, const char *, void *, size_t)> &code) const {
718 _foreach (load_command, GetLoadCommands())
719 switch (Swap(load_command->cmd)) {
720 case LC_SEGMENT: {
721 auto segment(reinterpret_cast<struct segment_command *>(load_command));
722 code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize);
723 auto section(reinterpret_cast<struct section *>(segment + 1));
724 for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section)
725 code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size);
726 } break;
727
728 case LC_SEGMENT_64: {
729 auto segment(reinterpret_cast<struct segment_command_64 *>(load_command));
730 code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize);
731 auto section(reinterpret_cast<struct section_64 *>(segment + 1));
732 for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section)
733 code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size);
734 } break;
735 }
736 }
737
738 template <typename Target_>
739 Target_ *GetOffset(uint32_t offset) const {
740 return reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_);
741 }
742 };
743
744 class FatMachHeader :
745 public MachHeader
746 {
747 private:
748 fat_arch *fat_arch_;
749
750 public:
751 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
752 MachHeader(base, size),
753 fat_arch_(fat_arch)
754 {
755 }
756
757 fat_arch *GetFatArch() const {
758 return fat_arch_;
759 }
760 };
761
762 class FatHeader :
763 public Data
764 {
765 private:
766 fat_header *fat_header_;
767 std::vector<FatMachHeader> mach_headers_;
768
769 public:
770 FatHeader(void *base, size_t size) :
771 Data(base, size)
772 {
773 fat_header_ = reinterpret_cast<struct fat_header *>(base);
774
775 if (Swap(fat_header_->magic) == FAT_CIGAM) {
776 swapped_ = !swapped_;
777 goto fat;
778 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
779 fat_header_ = NULL;
780 mach_headers_.push_back(FatMachHeader(base, size, NULL));
781 } else fat: {
782 size_t fat_narch = Swap(fat_header_->nfat_arch);
783 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
784 size_t arch;
785 for (arch = 0; arch != fat_narch; ++arch) {
786 uint32_t arch_offset = Swap(fat_arch->offset);
787 uint32_t arch_size = Swap(fat_arch->size);
788 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
789 ++fat_arch;
790 }
791 }
792 }
793
794 std::vector<FatMachHeader> &GetMachHeaders() {
795 return mach_headers_;
796 }
797
798 bool IsFat() const {
799 return fat_header_ != NULL;
800 }
801
802 struct fat_header *operator ->() const {
803 return fat_header_;
804 }
805
806 operator struct fat_header *() const {
807 return fat_header_;
808 }
809 };
810
811 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
812 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
813 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
814 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
815 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
816 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
817 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
818 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
819
820 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
821 #define CSSLOT_INFOSLOT uint32_t(0x00001)
822 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
823 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
824 #define CSSLOT_APPLICATION uint32_t(0x00004)
825 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
826 #define CSSLOT_ALTERNATE uint32_t(0x01000)
827
828 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
829
830 #define CS_HASHTYPE_SHA160_160 1
831 #define CS_HASHTYPE_SHA256_256 2
832 #define CS_HASHTYPE_SHA256_160 3
833 #define CS_HASHTYPE_SHA386_386 4
834
835 struct BlobIndex {
836 uint32_t type;
837 uint32_t offset;
838 } _packed;
839
840 struct Blob {
841 uint32_t magic;
842 uint32_t length;
843 } _packed;
844
845 struct SuperBlob {
846 struct Blob blob;
847 uint32_t count;
848 struct BlobIndex index[];
849 } _packed;
850
851 struct CodeDirectory {
852 uint32_t version;
853 uint32_t flags;
854 uint32_t hashOffset;
855 uint32_t identOffset;
856 uint32_t nSpecialSlots;
857 uint32_t nCodeSlots;
858 uint32_t codeLimit;
859 uint8_t hashSize;
860 uint8_t hashType;
861 uint8_t spare1;
862 uint8_t pageSize;
863 uint32_t spare2;
864 uint32_t scatterOffset;
865 uint32_t teamIDOffset;
866 //uint32_t spare3;
867 //uint64_t codeLimit64;
868 } _packed;
869
870 enum Kind : uint32_t {
871 exprForm = 1, // prefix expr form
872 };
873
874 enum ExprOp : uint32_t {
875 opFalse, // unconditionally false
876 opTrue, // unconditionally true
877 opIdent, // match canonical code [string]
878 opAppleAnchor, // signed by Apple as Apple's product
879 opAnchorHash, // match anchor [cert hash]
880 opInfoKeyValue, // *legacy* - use opInfoKeyField [key; value]
881 opAnd, // binary prefix expr AND expr [expr; expr]
882 opOr, // binary prefix expr OR expr [expr; expr]
883 opCDHash, // match hash of CodeDirectory directly [cd hash]
884 opNot, // logical inverse [expr]
885 opInfoKeyField, // Info.plist key field [string; match suffix]
886 opCertField, // Certificate field [cert index; field name; match suffix]
887 opTrustedCert, // require trust settings to approve one particular cert [cert index]
888 opTrustedCerts, // require trust settings to approve the cert chain
889 opCertGeneric, // Certificate component by OID [cert index; oid; match suffix]
890 opAppleGenericAnchor, // signed by Apple in any capacity
891 opEntitlementField, // entitlement dictionary field [string; match suffix]
892 opCertPolicy, // Certificate policy by OID [cert index; oid; match suffix]
893 opNamedAnchor, // named anchor type
894 opNamedCode, // named subroutine
895 opPlatform, // platform constraint [integer]
896 exprOpCount // (total opcode count in use)
897 };
898
899 enum MatchOperation {
900 matchExists, // anything but explicit "false" - no value stored
901 matchEqual, // equal (CFEqual)
902 matchContains, // partial match (substring)
903 matchBeginsWith, // partial match (initial substring)
904 matchEndsWith, // partial match (terminal substring)
905 matchLessThan, // less than (string with numeric comparison)
906 matchGreaterThan, // greater than (string with numeric comparison)
907 matchLessEqual, // less or equal (string with numeric comparison)
908 matchGreaterEqual, // greater or equal (string with numeric comparison)
909 };
910
911 #define OID_ISO_MEMBER 42
912 #define OID_US OID_ISO_MEMBER, 134, 72
913 #define APPLE_OID OID_US, 0x86, 0xf7, 0x63
914 #define APPLE_ADS_OID APPLE_OID, 0x64
915 #define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
916
917 #ifndef LDID_NOFLAGT
918 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
919 #endif
920
921 struct Algorithm {
922 size_t size_;
923 uint8_t type_;
924
925 Algorithm(size_t size, uint8_t type) :
926 size_(size),
927 type_(type)
928 {
929 }
930
931 virtual const uint8_t *operator [](const ldid::Hash &hash) const = 0;
932
933 virtual void operator ()(uint8_t *hash, const void *data, size_t size) const = 0;
934 virtual void operator ()(ldid::Hash &hash, const void *data, size_t size) const = 0;
935 virtual void operator ()(std::vector<char> &hash, const void *data, size_t size) const = 0;
936 };
937
938 struct AlgorithmSHA1 :
939 Algorithm
940 {
941 AlgorithmSHA1() :
942 Algorithm(LDID_SHA1_DIGEST_LENGTH, CS_HASHTYPE_SHA160_160)
943 {
944 }
945
946 virtual const uint8_t *operator [](const ldid::Hash &hash) const {
947 return hash.sha1_;
948 }
949
950 void operator ()(uint8_t *hash, const void *data, size_t size) const {
951 LDID_SHA1(static_cast<const uint8_t *>(data), size, hash);
952 }
953
954 void operator ()(ldid::Hash &hash, const void *data, size_t size) const {
955 return operator()(hash.sha1_, data, size);
956 }
957
958 void operator ()(std::vector<char> &hash, const void *data, size_t size) const {
959 hash.resize(LDID_SHA1_DIGEST_LENGTH);
960 return operator ()(reinterpret_cast<uint8_t *>(hash.data()), data, size);
961 }
962 };
963
964 struct AlgorithmSHA256 :
965 Algorithm
966 {
967 AlgorithmSHA256() :
968 Algorithm(LDID_SHA256_DIGEST_LENGTH, CS_HASHTYPE_SHA256_256)
969 {
970 }
971
972 virtual const uint8_t *operator [](const ldid::Hash &hash) const {
973 return hash.sha256_;
974 }
975
976 void operator ()(uint8_t *hash, const void *data, size_t size) const {
977 LDID_SHA256(static_cast<const uint8_t *>(data), size, hash);
978 }
979
980 void operator ()(ldid::Hash &hash, const void *data, size_t size) const {
981 return operator()(hash.sha256_, data, size);
982 }
983
984 void operator ()(std::vector<char> &hash, const void *data, size_t size) const {
985 hash.resize(LDID_SHA256_DIGEST_LENGTH);
986 return operator ()(reinterpret_cast<uint8_t *>(hash.data()), data, size);
987 }
988 };
989
990 static const std::vector<Algorithm *> &GetAlgorithms() {
991 static AlgorithmSHA1 sha1;
992 static AlgorithmSHA256 sha256;
993
994 static Algorithm *array[] = {
995 &sha1,
996 &sha256,
997 };
998
999 static std::vector<Algorithm *> algorithms(array, array + sizeof(array) / sizeof(array[0]));
1000 return algorithms;
1001 }
1002
1003 struct CodesignAllocation {
1004 FatMachHeader mach_header_;
1005 uint32_t offset_;
1006 uint32_t size_;
1007 uint32_t limit_;
1008 uint32_t alloc_;
1009 uint32_t align_;
1010
1011 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
1012 mach_header_(mach_header),
1013 offset_(offset),
1014 size_(size),
1015 limit_(limit),
1016 alloc_(alloc),
1017 align_(align)
1018 {
1019 }
1020 };
1021
1022 #ifndef LDID_NOTOOLS
1023 class File {
1024 private:
1025 int file_;
1026
1027 public:
1028 File() :
1029 file_(-1)
1030 {
1031 }
1032
1033 ~File() {
1034 if (file_ != -1)
1035 _syscall(close(file_));
1036 }
1037
1038 void open(const char *path, int flags) {
1039 _assert(file_ == -1);
1040 file_ = _syscall(::open(path, flags));
1041 }
1042
1043 int file() const {
1044 return file_;
1045 }
1046 };
1047
1048 class Map {
1049 private:
1050 File file_;
1051 void *data_;
1052 size_t size_;
1053
1054 void clear() {
1055 if (data_ == NULL)
1056 return;
1057 _syscall(munmap(data_, size_));
1058 data_ = NULL;
1059 size_ = 0;
1060 }
1061
1062 public:
1063 Map() :
1064 data_(NULL),
1065 size_(0)
1066 {
1067 }
1068
1069 Map(const std::string &path, int oflag, int pflag, int mflag) :
1070 Map()
1071 {
1072 open(path, oflag, pflag, mflag);
1073 }
1074
1075 Map(const std::string &path, bool edit) :
1076 Map()
1077 {
1078 open(path, edit);
1079 }
1080
1081 ~Map() {
1082 clear();
1083 }
1084
1085 bool empty() const {
1086 return data_ == NULL;
1087 }
1088
1089 void open(const std::string &path, int oflag, int pflag, int mflag) {
1090 clear();
1091
1092 file_.open(path.c_str(), oflag);
1093 int file(file_.file());
1094
1095 struct stat stat;
1096 _syscall(fstat(file, &stat));
1097 size_ = stat.st_size;
1098
1099 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
1100 }
1101
1102 void open(const std::string &path, bool edit) {
1103 if (edit)
1104 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
1105 else
1106 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
1107 }
1108
1109 void *data() const {
1110 return data_;
1111 }
1112
1113 size_t size() const {
1114 return size_;
1115 }
1116
1117 operator std::string() const {
1118 return std::string(static_cast<char *>(data_), size_);
1119 }
1120 };
1121 #endif
1122
1123 namespace ldid {
1124
1125 std::string Analyze(const void *data, size_t size) {
1126 std::string entitlements;
1127
1128 FatHeader fat_header(const_cast<void *>(data), size);
1129 _foreach (mach_header, fat_header.GetMachHeaders())
1130 _foreach (load_command, mach_header.GetLoadCommands())
1131 if (mach_header.Swap(load_command->cmd) == LC_CODE_SIGNATURE) {
1132 auto signature(reinterpret_cast<struct linkedit_data_command *>(load_command));
1133 auto offset(mach_header.Swap(signature->dataoff));
1134 auto pointer(reinterpret_cast<uint8_t *>(mach_header.GetBase()) + offset);
1135 auto super(reinterpret_cast<struct SuperBlob *>(pointer));
1136
1137 for (size_t index(0); index != Swap(super->count); ++index)
1138 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1139 auto begin(Swap(super->index[index].offset));
1140 auto blob(reinterpret_cast<struct Blob *>(pointer + begin));
1141 auto writ(Swap(blob->length) - sizeof(*blob));
1142
1143 if (entitlements.empty())
1144 entitlements.assign(reinterpret_cast<char *>(blob + 1), writ);
1145 else
1146 _assert(entitlements.compare(0, entitlements.size(), reinterpret_cast<char *>(blob + 1), writ) == 0);
1147 }
1148 }
1149
1150 return entitlements;
1151 }
1152
1153 static void Allocate(const void *idata, size_t isize, std::streambuf &output, const Functor<size_t (const MachHeader &, size_t)> &allocate, const Functor<size_t (const MachHeader &, std::streambuf &output, size_t, const std::string &, const char *, const Functor<void (double)> &)> &save, const Functor<void (double)> &percent) {
1154 FatHeader source(const_cast<void *>(idata), isize);
1155
1156 size_t offset(0);
1157 if (source.IsFat())
1158 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
1159
1160 std::vector<CodesignAllocation> allocations;
1161 _foreach (mach_header, source.GetMachHeaders()) {
1162 struct linkedit_data_command *signature(NULL);
1163 struct symtab_command *symtab(NULL);
1164
1165 _foreach (load_command, mach_header.GetLoadCommands()) {
1166 uint32_t cmd(mach_header.Swap(load_command->cmd));
1167 if (false);
1168 else if (cmd == LC_CODE_SIGNATURE)
1169 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
1170 else if (cmd == LC_SYMTAB)
1171 symtab = reinterpret_cast<struct symtab_command *>(load_command);
1172 }
1173
1174 size_t size;
1175 if (signature == NULL)
1176 size = mach_header.GetSize();
1177 else {
1178 size = mach_header.Swap(signature->dataoff);
1179 _assert(size <= mach_header.GetSize());
1180 }
1181
1182 if (symtab != NULL) {
1183 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
1184 _assert(end <= size);
1185 _assert(end >= size - 0x10);
1186 size = end;
1187 }
1188
1189 size_t alloc(allocate(mach_header, size));
1190
1191 auto *fat_arch(mach_header.GetFatArch());
1192 uint32_t align;
1193
1194 if (fat_arch != NULL)
1195 align = source.Swap(fat_arch->align);
1196 else switch (mach_header.GetCPUType()) {
1197 case CPU_TYPE_POWERPC:
1198 case CPU_TYPE_POWERPC64:
1199 case CPU_TYPE_X86:
1200 case CPU_TYPE_X86_64:
1201 align = 0xc;
1202 break;
1203 case CPU_TYPE_ARM:
1204 case CPU_TYPE_ARM64:
1205 align = 0xe;
1206 break;
1207 default:
1208 align = 0x0;
1209 break;
1210 }
1211
1212 offset = Align(offset, 1 << align);
1213
1214 uint32_t limit(size);
1215 if (alloc != 0)
1216 limit = Align(limit, 0x10);
1217
1218 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
1219 offset += size + alloc;
1220 offset = Align(offset, 0x10);
1221 }
1222
1223 size_t position(0);
1224
1225 if (source.IsFat()) {
1226 fat_header fat_header;
1227 fat_header.magic = Swap(FAT_MAGIC);
1228 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1229 put(output, &fat_header, sizeof(fat_header));
1230 position += sizeof(fat_header);
1231
1232 _foreach (allocation, allocations) {
1233 auto &mach_header(allocation.mach_header_);
1234
1235 fat_arch fat_arch;
1236 fat_arch.cputype = Swap(mach_header->cputype);
1237 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1238 fat_arch.offset = Swap(allocation.offset_);
1239 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1240 fat_arch.align = Swap(allocation.align_);
1241 put(output, &fat_arch, sizeof(fat_arch));
1242 position += sizeof(fat_arch);
1243 }
1244 }
1245
1246 _foreach (allocation, allocations) {
1247 auto &mach_header(allocation.mach_header_);
1248
1249 pad(output, allocation.offset_ - position);
1250 position = allocation.offset_;
1251
1252 std::vector<std::string> commands;
1253
1254 _foreach (load_command, mach_header.GetLoadCommands()) {
1255 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
1256
1257 switch (mach_header.Swap(load_command->cmd)) {
1258 case LC_CODE_SIGNATURE:
1259 continue;
1260 break;
1261
1262 case LC_SEGMENT: {
1263 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1264 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1265 break;
1266 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1267 segment_command->filesize = size;
1268 segment_command->vmsize = Align(size, 1 << allocation.align_);
1269 } break;
1270
1271 case LC_SEGMENT_64: {
1272 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1273 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1274 break;
1275 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1276 segment_command->filesize = size;
1277 segment_command->vmsize = Align(size, 1 << allocation.align_);
1278 } break;
1279 }
1280
1281 commands.push_back(copy);
1282 }
1283
1284 if (allocation.alloc_ != 0) {
1285 linkedit_data_command signature;
1286 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1287 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1288 signature.dataoff = mach_header.Swap(allocation.limit_);
1289 signature.datasize = mach_header.Swap(allocation.alloc_);
1290 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1291 }
1292
1293 size_t begin(position);
1294
1295 uint32_t after(0);
1296 _foreach(command, commands)
1297 after += command.size();
1298
1299 std::stringbuf altern;
1300
1301 struct mach_header header(*mach_header);
1302 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1303 header.sizeofcmds = mach_header.Swap(after);
1304 put(output, &header, sizeof(header));
1305 put(altern, &header, sizeof(header));
1306 position += sizeof(header);
1307
1308 if (mach_header.Bits64()) {
1309 auto pad(mach_header.Swap(uint32_t(0)));
1310 put(output, &pad, sizeof(pad));
1311 put(altern, &pad, sizeof(pad));
1312 position += sizeof(pad);
1313 }
1314
1315 _foreach(command, commands) {
1316 put(output, command.data(), command.size());
1317 put(altern, command.data(), command.size());
1318 position += command.size();
1319 }
1320
1321 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1322 if (before > after) {
1323 pad(output, before - after);
1324 pad(altern, before - after);
1325 position += before - after;
1326 }
1327
1328 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
1329
1330 std::string overlap(altern.str());
1331 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
1332
1333 put(output, top + (position - begin), allocation.size_ - (position - begin), percent);
1334 position = begin + allocation.size_;
1335
1336 pad(output, allocation.limit_ - allocation.size_);
1337 position += allocation.limit_ - allocation.size_;
1338
1339 size_t saved(save(mach_header, output, allocation.limit_, overlap, top, percent));
1340 if (allocation.alloc_ > saved)
1341 pad(output, allocation.alloc_ - saved);
1342 else
1343 _assert(allocation.alloc_ == saved);
1344 position += allocation.alloc_;
1345 }
1346 }
1347
1348 }
1349
1350 typedef std::map<uint32_t, std::string> Blobs;
1351
1352 static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1353 auto value(buffer.str());
1354 std::swap(blobs[slot], value);
1355 }
1356
1357 static const std::string &insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1358 auto value(buffer.str());
1359 Blob blob;
1360 blob.magic = Swap(magic);
1361 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1362 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1363 auto &save(blobs[slot]);
1364 std::swap(save, value);
1365 return save;
1366 }
1367
1368 static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1369 size_t total(0);
1370 _foreach (blob, blobs)
1371 total += blob.second.size();
1372
1373 struct SuperBlob super;
1374 super.blob.magic = Swap(magic);
1375 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1376 super.count = Swap(uint32_t(blobs.size()));
1377 put(output, &super, sizeof(super));
1378
1379 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1380
1381 _foreach (blob, blobs) {
1382 BlobIndex index;
1383 index.type = Swap(blob.first);
1384 index.offset = Swap(uint32_t(offset));
1385 put(output, &index, sizeof(index));
1386 offset += blob.second.size();
1387 }
1388
1389 _foreach (blob, blobs)
1390 put(output, blob.second.data(), blob.second.size());
1391
1392 return offset;
1393 }
1394
1395 #ifndef LDID_NOSMIME
1396 class Buffer {
1397 private:
1398 BIO *bio_;
1399
1400 public:
1401 Buffer(BIO *bio) :
1402 bio_(bio)
1403 {
1404 _assert(bio_ != NULL);
1405 }
1406
1407 Buffer() :
1408 bio_(BIO_new(BIO_s_mem()))
1409 {
1410 }
1411
1412 Buffer(const char *data, size_t size) :
1413 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1414 {
1415 }
1416
1417 Buffer(const std::string &data) :
1418 Buffer(data.data(), data.size())
1419 {
1420 }
1421
1422 Buffer(PKCS7 *pkcs) :
1423 Buffer()
1424 {
1425 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1426 }
1427
1428 ~Buffer() {
1429 BIO_free_all(bio_);
1430 }
1431
1432 operator BIO *() const {
1433 return bio_;
1434 }
1435
1436 explicit operator std::string() const {
1437 char *data;
1438 auto size(BIO_get_mem_data(bio_, &data));
1439 return std::string(data, size);
1440 }
1441 };
1442
1443 class Stuff {
1444 private:
1445 PKCS12 *value_;
1446 EVP_PKEY *key_;
1447 X509 *cert_;
1448 STACK_OF(X509) *ca_;
1449
1450 public:
1451 Stuff(BIO *bio) :
1452 value_(d2i_PKCS12_bio(bio, NULL)),
1453 ca_(NULL)
1454 {
1455 _assert(value_ != NULL);
1456 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1457 _assert(key_ != NULL);
1458 _assert(cert_ != NULL);
1459 }
1460
1461 Stuff(const std::string &data) :
1462 Stuff(Buffer(data))
1463 {
1464 }
1465
1466 ~Stuff() {
1467 sk_X509_pop_free(ca_, X509_free);
1468 X509_free(cert_);
1469 EVP_PKEY_free(key_);
1470 PKCS12_free(value_);
1471 }
1472
1473 operator PKCS12 *() const {
1474 return value_;
1475 }
1476
1477 operator EVP_PKEY *() const {
1478 return key_;
1479 }
1480
1481 operator X509 *() const {
1482 return cert_;
1483 }
1484
1485 operator STACK_OF(X509) *() const {
1486 return ca_;
1487 }
1488 };
1489
1490 class Signature {
1491 private:
1492 PKCS7 *value_;
1493
1494 public:
1495 Signature(const Stuff &stuff, const Buffer &data, const std::string &xml) {
1496 value_ = PKCS7_new();
1497 _assert(value_ != NULL);
1498
1499 _assert(PKCS7_set_type(value_, NID_pkcs7_signed));
1500 _assert(PKCS7_content_new(value_, NID_pkcs7_data));
1501
1502 STACK_OF(X509) *certs(stuff);
1503 for (unsigned i(0), e(sk_X509_num(certs)); i != e; i++)
1504 _assert(PKCS7_add_certificate(value_, sk_X509_value(certs, e - i - 1)));
1505
1506 auto info(PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP));
1507 _assert(info != NULL);
1508
1509 PKCS7_set_detached(value_, 1);
1510
1511 ASN1_OCTET_STRING *string(ASN1_OCTET_STRING_new());
1512 _assert(string != NULL);
1513 try {
1514 _assert(ASN1_STRING_set(string, xml.data(), xml.size()));
1515
1516 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1517 _assert(PKCS7_add_signed_attribute(info, nid, V_ASN1_OCTET_STRING, string));
1518 } catch (...) {
1519 ASN1_OCTET_STRING_free(string);
1520 throw;
1521 }
1522
1523 _assert(PKCS7_final(value_, data, PKCS7_BINARY));
1524 }
1525
1526 ~Signature() {
1527 PKCS7_free(value_);
1528 }
1529
1530 operator PKCS7 *() const {
1531 return value_;
1532 }
1533 };
1534 #endif
1535
1536 class NullBuffer :
1537 public std::streambuf
1538 {
1539 public:
1540 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1541 return size;
1542 }
1543
1544 virtual int_type overflow(int_type next) {
1545 return next;
1546 }
1547 };
1548
1549 class Digest {
1550 public:
1551 uint8_t sha1_[LDID_SHA1_DIGEST_LENGTH];
1552 };
1553
1554 class HashBuffer :
1555 public std::streambuf
1556 {
1557 private:
1558 ldid::Hash &hash_;
1559
1560 LDID_SHA1_CTX sha1_;
1561 LDID_SHA256_CTX sha256_;
1562
1563 public:
1564 HashBuffer(ldid::Hash &hash) :
1565 hash_(hash)
1566 {
1567 LDID_SHA1_Init(&sha1_);
1568 LDID_SHA256_Init(&sha256_);
1569 }
1570
1571 ~HashBuffer() {
1572 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.sha1_), &sha1_);
1573 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_.sha256_), &sha256_);
1574 }
1575
1576 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1577 LDID_SHA1_Update(&sha1_, data, size);
1578 LDID_SHA256_Update(&sha256_, data, size);
1579 return size;
1580 }
1581
1582 virtual int_type overflow(int_type next) {
1583 if (next == traits_type::eof())
1584 return sync();
1585 char value(next);
1586 xsputn(&value, 1);
1587 return next;
1588 }
1589 };
1590
1591 class HashProxy :
1592 public HashBuffer
1593 {
1594 private:
1595 std::streambuf &buffer_;
1596
1597 public:
1598 HashProxy(ldid::Hash &hash, std::streambuf &buffer) :
1599 HashBuffer(hash),
1600 buffer_(buffer)
1601 {
1602 }
1603
1604 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1605 _assert(HashBuffer::xsputn(data, size) == size);
1606 return buffer_.sputn(data, size);
1607 }
1608 };
1609
1610 #ifndef LDID_NOTOOLS
1611 static bool Starts(const std::string &lhs, const std::string &rhs) {
1612 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1613 }
1614
1615 class Split {
1616 public:
1617 std::string dir;
1618 std::string base;
1619
1620 Split(const std::string &path) {
1621 size_t slash(path.rfind('/'));
1622 if (slash == std::string::npos)
1623 base = path;
1624 else {
1625 dir = path.substr(0, slash + 1);
1626 base = path.substr(slash + 1);
1627 }
1628 }
1629 };
1630
1631 static void mkdir_p(const std::string &path) {
1632 if (path.empty())
1633 return;
1634 #ifdef __WIN32__
1635 if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
1636 return;
1637 #else
1638 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1639 return;
1640 #endif
1641 auto slash(path.rfind('/', path.size() - 1));
1642 if (slash == std::string::npos)
1643 return;
1644 mkdir_p(path.substr(0, slash));
1645 }
1646
1647 static std::string Temporary(std::filebuf &file, const Split &split) {
1648 std::string temp(split.dir + ".ldid." + split.base);
1649 mkdir_p(split.dir);
1650 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1651 return temp;
1652 }
1653
1654 static void Commit(const std::string &path, const std::string &temp) {
1655 struct stat info;
1656 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
1657 #ifndef __WIN32__
1658 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1659 #endif
1660 _syscall(chmod(temp.c_str(), info.st_mode));
1661 }
1662
1663 _syscall(rename(temp.c_str(), path.c_str()));
1664 }
1665 #endif
1666
1667 namespace ldid {
1668
1669 static void get(std::string &value, X509_NAME *name, int nid) {
1670 auto index(X509_NAME_get_index_by_NID(name, nid, -1));
1671 _assert(index >= 0);
1672 auto next(X509_NAME_get_index_by_NID(name, nid, index));
1673 _assert(next == -1);
1674 auto entry(X509_NAME_get_entry(name, index));
1675 _assert(entry != NULL);
1676 auto asn(X509_NAME_ENTRY_get_data(entry));
1677 _assert(asn != NULL);
1678 value.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn)), ASN1_STRING_length(asn));
1679 }
1680
1681 static void req(std::streambuf &buffer, uint32_t value) {
1682 value = Swap(value);
1683 put(buffer, &value, sizeof(value));
1684 }
1685
1686 static void req(std::streambuf &buffer, const std::string &value) {
1687 req(buffer, value.size());
1688 put(buffer, value.data(), value.size());
1689 static uint8_t zeros[] = {0,0,0,0};
1690 put(buffer, zeros, 3 - (value.size() + 3) % 4);
1691 }
1692
1693 template <size_t Size_>
1694 static void req(std::streambuf &buffer, uint8_t (&&data)[Size_]) {
1695 req(buffer, Size_);
1696 put(buffer, data, Size_);
1697 static uint8_t zeros[] = {0,0,0,0};
1698 put(buffer, zeros, 3 - (Size_ + 3) % 4);
1699 }
1700
1701 Hash Sign(const void *idata, size_t isize, std::streambuf &output, const std::string &identifier, const std::string &entitlements, const std::string &requirements, const std::string &key, const Slots &slots, const Functor<void (double)> &percent) {
1702 Hash hash;
1703
1704
1705 std::string team;
1706 std::string common;
1707
1708 #ifndef LDID_NOSMIME
1709 if (!key.empty()) {
1710 Stuff stuff(key);
1711 auto name(X509_get_subject_name(stuff));
1712 _assert(name != NULL);
1713 get(team, name, NID_organizationalUnitName);
1714 get(common, name, NID_commonName);
1715 }
1716 #endif
1717
1718
1719 std::stringbuf backing;
1720
1721 if (!requirements.empty()) {
1722 put(backing, requirements.data(), requirements.size());
1723 } else {
1724 Blobs blobs;
1725
1726 std::stringbuf requirement;
1727 req(requirement, exprForm);
1728 req(requirement, opAnd);
1729 req(requirement, opIdent);
1730 req(requirement, identifier);
1731 req(requirement, opAnd);
1732 req(requirement, opAppleGenericAnchor);
1733 req(requirement, opAnd);
1734 req(requirement, opCertField);
1735 req(requirement, 0);
1736 req(requirement, "subject.CN");
1737 req(requirement, matchEqual);
1738 req(requirement, common);
1739 req(requirement, opCertGeneric);
1740 req(requirement, 1);
1741 req(requirement, (uint8_t []) {APPLE_EXTENSION_OID, 2, 1});
1742 req(requirement, matchExists);
1743 insert(blobs, 3, CSMAGIC_REQUIREMENT, requirement);
1744
1745 put(backing, CSMAGIC_REQUIREMENTS, blobs);
1746 }
1747
1748
1749 // XXX: this is just a "sufficiently large number"
1750 size_t certificate(0x3000);
1751
1752 Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, size_t size) -> size_t {
1753 size_t alloc(sizeof(struct SuperBlob));
1754
1755 uint32_t normal((size + PageSize_ - 1) / PageSize_);
1756
1757 uint32_t special(0);
1758
1759 _foreach (slot, slots)
1760 special = std::max(special, slot.first);
1761
1762 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1763 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
1764 special = std::max(special, CSSLOT_INFOSLOT);
1765 }));
1766
1767 special = std::max(special, CSSLOT_REQUIREMENTS);
1768 alloc += sizeof(struct BlobIndex);
1769 alloc += backing.str().size();
1770
1771 if (!entitlements.empty()) {
1772 special = std::max(special, CSSLOT_ENTITLEMENTS);
1773 alloc += sizeof(struct BlobIndex);
1774 alloc += sizeof(struct Blob);
1775 alloc += entitlements.size();
1776 }
1777
1778 size_t directory(0);
1779
1780 directory += sizeof(struct BlobIndex);
1781 directory += sizeof(struct Blob);
1782 directory += sizeof(struct CodeDirectory);
1783 directory += identifier.size() + 1;
1784
1785 if (!team.empty())
1786 directory += team.size() + 1;
1787
1788 for (Algorithm *algorithm : GetAlgorithms())
1789 alloc = Align(alloc + directory + (special + normal) * algorithm->size_, 16);
1790
1791 #ifndef LDID_NOSMIME
1792 if (!key.empty()) {
1793 alloc += sizeof(struct BlobIndex);
1794 alloc += sizeof(struct Blob);
1795 alloc += certificate;
1796 }
1797 #endif
1798
1799 return alloc;
1800 }), fun([&](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top, const Functor<void (double)> &percent) -> size_t {
1801 Blobs blobs;
1802
1803 if (true) {
1804 insert(blobs, CSSLOT_REQUIREMENTS, backing);
1805 }
1806
1807 if (!entitlements.empty()) {
1808 std::stringbuf data;
1809 put(data, entitlements.data(), entitlements.size());
1810 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
1811 }
1812
1813 Slots posts(slots);
1814
1815 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1816 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0) {
1817 auto &slot(posts[CSSLOT_INFOSLOT]);
1818 for (Algorithm *algorithm : GetAlgorithms())
1819 (*algorithm)(slot, data, size);
1820 }
1821 }));
1822
1823 unsigned total(0);
1824 for (Algorithm *pointer : GetAlgorithms()) {
1825 Algorithm &algorithm(*pointer);
1826
1827 std::stringbuf data;
1828
1829 uint32_t special(0);
1830 _foreach (blob, blobs)
1831 special = std::max(special, blob.first);
1832 _foreach (slot, posts)
1833 special = std::max(special, slot.first);
1834 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
1835
1836 CodeDirectory directory;
1837 directory.version = Swap(uint32_t(0x00020200));
1838 directory.flags = Swap(uint32_t(0));
1839 directory.nSpecialSlots = Swap(special);
1840 directory.codeLimit = Swap(uint32_t(limit));
1841 directory.nCodeSlots = Swap(normal);
1842 directory.hashSize = algorithm.size_;
1843 directory.hashType = algorithm.type_;
1844 directory.spare1 = 0x00;
1845 directory.pageSize = PageShift_;
1846 directory.spare2 = Swap(uint32_t(0));
1847 directory.scatterOffset = Swap(uint32_t(0));
1848 //directory.spare3 = Swap(uint32_t(0));
1849 //directory.codeLimit64 = Swap(uint64_t(0));
1850
1851 uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory));
1852
1853 directory.identOffset = Swap(uint32_t(offset));
1854 offset += identifier.size() + 1;
1855
1856 if (team.empty())
1857 directory.teamIDOffset = Swap(uint32_t(0));
1858 else {
1859 directory.teamIDOffset = Swap(uint32_t(offset));
1860 offset += team.size() + 1;
1861 }
1862
1863 offset += special * algorithm.size_;
1864 directory.hashOffset = Swap(uint32_t(offset));
1865 offset += normal * algorithm.size_;
1866
1867 put(data, &directory, sizeof(directory));
1868
1869 put(data, identifier.c_str(), identifier.size() + 1);
1870 if (!team.empty())
1871 put(data, team.c_str(), team.size() + 1);
1872
1873 std::vector<uint8_t> storage((special + normal) * algorithm.size_);
1874 auto *hashes(&storage[special * algorithm.size_]);
1875
1876 memset(storage.data(), 0, special * algorithm.size_);
1877
1878 _foreach (blob, blobs) {
1879 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1880 algorithm(hashes - blob.first * algorithm.size_, local, Swap(local->length));
1881 }
1882
1883 _foreach (slot, posts)
1884 memcpy(hashes - slot.first * algorithm.size_, algorithm[slot.second], algorithm.size_);
1885
1886 percent(0);
1887 if (normal != 1)
1888 for (size_t i = 0; i != normal - 1; ++i) {
1889 algorithm(hashes + i * algorithm.size_, (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
1890 percent(double(i) / normal);
1891 }
1892 if (normal != 0)
1893 algorithm(hashes + (normal - 1) * algorithm.size_, top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
1894 percent(1);
1895
1896 put(data, storage.data(), storage.size());
1897
1898 const auto &save(insert(blobs, total == 0 ? CSSLOT_CODEDIRECTORY : CSSLOT_ALTERNATE + total - 1, CSMAGIC_CODEDIRECTORY, data));
1899 algorithm(hash, save.data(), save.size());
1900
1901 ++total;
1902 }
1903
1904 #ifndef LDID_NOSMIME
1905 if (!key.empty()) {
1906 auto plist(plist_new_dict());
1907 _scope({ plist_free(plist); });
1908
1909 auto cdhashes(plist_new_array());
1910 plist_dict_set_item(plist, "cdhashes", cdhashes);
1911
1912 unsigned total(0);
1913 for (Algorithm *pointer : GetAlgorithms()) {
1914 Algorithm &algorithm(*pointer);
1915 (void) algorithm;
1916
1917 const auto &blob(blobs[total == 0 ? CSSLOT_CODEDIRECTORY : CSSLOT_ALTERNATE + total - 1]);
1918 ++total;
1919
1920 std::vector<char> hash;
1921 algorithm(hash, blob.data(), blob.size());
1922 hash.resize(20);
1923
1924 plist_array_append_item(cdhashes, plist_new_data(hash.data(), hash.size()));
1925 }
1926
1927 char *xml(NULL);
1928 uint32_t size;
1929 plist_to_xml(plist, &xml, &size);
1930 _scope({ free(xml); });
1931
1932 std::stringbuf data;
1933 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1934
1935 Stuff stuff(key);
1936 Buffer bio(sign);
1937
1938 Signature signature(stuff, sign, std::string(xml, size));
1939 Buffer result(signature);
1940 std::string value(result);
1941 put(data, value.data(), value.size());
1942
1943 const auto &save(insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data));
1944 _assert(save.size() <= certificate);
1945 }
1946 #endif
1947
1948 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
1949 }), percent);
1950
1951 return hash;
1952 }
1953
1954 #ifndef LDID_NOTOOLS
1955 static void Unsign(void *idata, size_t isize, std::streambuf &output, const Functor<void (double)> &percent) {
1956 Allocate(idata, isize, output, fun([](const MachHeader &mach_header, size_t size) -> size_t {
1957 return 0;
1958 }), fun([](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top, const Functor<void (double)> &percent) -> size_t {
1959 return 0;
1960 }), percent);
1961 }
1962
1963 std::string DiskFolder::Path(const std::string &path) const {
1964 return path_ + "/" + path;
1965 }
1966
1967 DiskFolder::DiskFolder(const std::string &path) :
1968 path_(path)
1969 {
1970 }
1971
1972 DiskFolder::~DiskFolder() {
1973 if (!std::uncaught_exception())
1974 for (const auto &commit : commit_)
1975 Commit(commit.first, commit.second);
1976 }
1977
1978 #ifndef __WIN32__
1979 std::string readlink(const std::string &path) {
1980 for (size_t size(1024); ; size *= 2) {
1981 std::string data;
1982 data.resize(size);
1983
1984 int writ(_syscall(::readlink(path.c_str(), &data[0], data.size())));
1985 if (size_t(writ) >= size)
1986 continue;
1987
1988 data.resize(writ);
1989 return data;
1990 }
1991 }
1992 #endif
1993
1994 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 {
1995 std::string path(Path(root) + base);
1996
1997 DIR *dir(opendir(path.c_str()));
1998 _assert(dir != NULL);
1999 _scope({ _syscall(closedir(dir)); });
2000
2001 while (auto child = readdir(dir)) {
2002 std::string name(child->d_name);
2003 if (name == "." || name == "..")
2004 continue;
2005 if (Starts(name, ".ldid."))
2006 continue;
2007
2008 bool directory;
2009
2010 #ifdef __WIN32__
2011 struct stat info;
2012 _syscall(stat((path + name).c_str(), &info));
2013 if (false);
2014 else if (S_ISDIR(info.st_mode))
2015 directory = true;
2016 else if (S_ISREG(info.st_mode))
2017 directory = false;
2018 else
2019 _assert_(false, "st_mode=%x", info.st_mode);
2020 #else
2021 switch (child->d_type) {
2022 case DT_DIR:
2023 directory = true;
2024 break;
2025 case DT_REG:
2026 directory = false;
2027 break;
2028 case DT_LNK:
2029 link(base + name, fun([&]() { return readlink(path + name); }));
2030 continue;
2031 default:
2032 _assert_(false, "d_type=%u", child->d_type);
2033 }
2034 #endif
2035
2036 if (directory)
2037 Find(root, base + name + "/", code, link);
2038 else
2039 code(base + name);
2040 }
2041 }
2042
2043 void DiskFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2044 if (!edit) {
2045 // XXX: use nullbuf
2046 std::stringbuf save;
2047 code(save);
2048 } else {
2049 std::filebuf save;
2050 auto from(Path(path));
2051 commit_[from] = Temporary(save, from);
2052 code(save);
2053 }
2054 }
2055
2056 bool DiskFolder::Look(const std::string &path) const {
2057 return _syscall(access(Path(path).c_str(), R_OK), ENOENT) == 0;
2058 }
2059
2060 void DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2061 std::filebuf data;
2062 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
2063 _assert_(result == &data, "DiskFolder::Open(%s)", path.c_str());
2064
2065 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2066 data.pubseekpos(0, std::ios::in);
2067 code(data, length, NULL);
2068 }
2069
2070 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 {
2071 Find(path, "", code, link);
2072 }
2073 #endif
2074
2075 SubFolder::SubFolder(Folder &parent, const std::string &path) :
2076 parent_(parent),
2077 path_(path)
2078 {
2079 }
2080
2081 void SubFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2082 return parent_.Save(path_ + path, edit, flag, code);
2083 }
2084
2085 bool SubFolder::Look(const std::string &path) const {
2086 return parent_.Look(path_ + path);
2087 }
2088
2089 void SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2090 return parent_.Open(path_ + path, code);
2091 }
2092
2093 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 {
2094 return parent_.Find(path_ + path, code, link);
2095 }
2096
2097 std::string UnionFolder::Map(const std::string &path) const {
2098 auto remap(remaps_.find(path));
2099 if (remap == remaps_.end())
2100 return path;
2101 return remap->second;
2102 }
2103
2104 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 {
2105 if (file.size() >= path.size() && file.substr(0, path.size()) == path)
2106 code(file.substr(path.size()));
2107 }
2108
2109 UnionFolder::UnionFolder(Folder &parent) :
2110 parent_(parent)
2111 {
2112 }
2113
2114 void UnionFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2115 return parent_.Save(Map(path), edit, flag, code);
2116 }
2117
2118 bool UnionFolder::Look(const std::string &path) const {
2119 auto file(resets_.find(path));
2120 if (file != resets_.end())
2121 return true;
2122 return parent_.Look(Map(path));
2123 }
2124
2125 void UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2126 auto file(resets_.find(path));
2127 if (file == resets_.end())
2128 return parent_.Open(Map(path), code);
2129 auto &entry(file->second);
2130
2131 auto &data(*entry.data_);
2132 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2133 data.pubseekpos(0, std::ios::in);
2134 code(data, length, entry.flag_);
2135 }
2136
2137 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 {
2138 for (auto &reset : resets_)
2139 Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2140 auto &entry(reset.second);
2141 auto &data(*entry.data_);
2142 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2143 data.pubseekpos(0, std::ios::in);
2144 code(data, length, entry.flag_);
2145 }));
2146
2147 for (auto &remap : remaps_)
2148 Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2149 parent_.Open(remap.second, fun([&](std::streambuf &data, size_t length, const void *flag) {
2150 code(data, length, flag);
2151 }));
2152 }));
2153
2154 parent_.Find(path, fun([&](const std::string &name) {
2155 if (deletes_.find(path + name) == deletes_.end())
2156 code(name);
2157 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2158 if (deletes_.find(path + name) == deletes_.end())
2159 link(name, read);
2160 }));
2161 }
2162
2163 #ifndef LDID_NOTOOLS
2164 static void copy(std::streambuf &source, std::streambuf &target, size_t length, const ldid::Functor<void (double)> &percent) {
2165 percent(0);
2166 size_t total(0);
2167 for (;;) {
2168 char data[4096 * 4];
2169 size_t writ(source.sgetn(data, sizeof(data)));
2170 if (writ == 0)
2171 break;
2172 _assert(target.sputn(data, writ) == writ);
2173 total += writ;
2174 percent(double(total) / length);
2175 }
2176 }
2177
2178 #ifndef LDID_NOPLIST
2179 static plist_t plist(const std::string &data) {
2180 plist_t plist(NULL);
2181 if (Starts(data, "bplist00"))
2182 plist_from_bin(data.data(), data.size(), &plist);
2183 else
2184 plist_from_xml(data.data(), data.size(), &plist);
2185 _assert(plist != NULL);
2186 return plist;
2187 }
2188
2189 static void plist_d(std::streambuf &buffer, size_t length, const Functor<void (plist_t)> &code) {
2190 std::stringbuf data;
2191 copy(buffer, data, length, ldid::fun(dummy));
2192 auto node(plist(data.str()));
2193 _scope({ plist_free(node); });
2194 _assert(plist_get_node_type(node) == PLIST_DICT);
2195 code(node);
2196 }
2197
2198 static std::string plist_s(plist_t node) {
2199 _assert(node != NULL);
2200 _assert(plist_get_node_type(node) == PLIST_STRING);
2201 char *data;
2202 plist_get_string_val(node, &data);
2203 _scope({ free(data); });
2204 return data;
2205 }
2206 #endif
2207
2208 enum Mode {
2209 NoMode,
2210 OptionalMode,
2211 OmitMode,
2212 NestedMode,
2213 TopMode,
2214 };
2215
2216 class Expression {
2217 private:
2218 regex_t regex_;
2219 std::vector<std::string> matches_;
2220
2221 public:
2222 Expression(const std::string &code) {
2223 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED) == 0, "regcomp()");
2224 matches_.resize(regex_.re_nsub + 1);
2225 }
2226
2227 ~Expression() {
2228 regfree(&regex_);
2229 }
2230
2231 bool operator ()(const std::string &data) {
2232 regmatch_t matches[matches_.size()];
2233 auto value(regexec(&regex_, data.c_str(), matches_.size(), matches, 0));
2234 if (value == REG_NOMATCH)
2235 return false;
2236 _assert_(value == 0, "regexec()");
2237 for (size_t i(0); i != matches_.size(); ++i)
2238 matches_[i].assign(data.data() + matches[i].rm_so, matches[i].rm_eo - matches[i].rm_so);
2239 return true;
2240 }
2241
2242 const std::string &operator [](size_t index) const {
2243 return matches_[index];
2244 }
2245 };
2246
2247 struct Rule {
2248 unsigned weight_;
2249 Mode mode_;
2250 std::string code_;
2251
2252 mutable std::auto_ptr<Expression> regex_;
2253
2254 Rule(unsigned weight, Mode mode, const std::string &code) :
2255 weight_(weight),
2256 mode_(mode),
2257 code_(code)
2258 {
2259 }
2260
2261 Rule(const Rule &rhs) :
2262 weight_(rhs.weight_),
2263 mode_(rhs.mode_),
2264 code_(rhs.code_)
2265 {
2266 }
2267
2268 void Compile() const {
2269 regex_.reset(new Expression(code_));
2270 }
2271
2272 bool operator ()(const std::string &data) const {
2273 _assert(regex_.get() != NULL);
2274 return (*regex_)(data);
2275 }
2276
2277 bool operator <(const Rule &rhs) const {
2278 if (weight_ > rhs.weight_)
2279 return true;
2280 if (weight_ < rhs.weight_)
2281 return false;
2282 return mode_ > rhs.mode_;
2283 }
2284 };
2285
2286 struct RuleCode {
2287 bool operator ()(const Rule *lhs, const Rule *rhs) const {
2288 return lhs->code_ < rhs->code_;
2289 }
2290 };
2291
2292 #ifndef LDID_NOPLIST
2293 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, const std::string &requirements, const std::string &key, const Slots &slots, size_t length, const Functor<void (double)> &percent) {
2294 // XXX: this is a miserable fail
2295 std::stringbuf temp;
2296 put(temp, prefix, size);
2297 copy(buffer, temp, length - size, percent);
2298 // XXX: this is a stupid hack
2299 pad(temp, 0x10 - (length & 0xf));
2300 auto data(temp.str());
2301
2302 HashProxy proxy(hash, save);
2303 return Sign(data.data(), data.size(), proxy, identifier, entitlements, requirements, key, slots, percent);
2304 }
2305
2306 Bundle Sign(const std::string &root, Folder &folder, const std::string &key, std::map<std::string, Hash> &remote, const std::string &requirements, const Functor<std::string (const std::string &, const std::string &)> &alter, const Functor<void (const std::string &)> &progress, const Functor<void (double)> &percent) {
2307 std::string executable;
2308 std::string identifier;
2309
2310 bool mac(false);
2311
2312 std::string info("Info.plist");
2313 if (!folder.Look(info) && folder.Look("Resources/" + info)) {
2314 mac = true;
2315 info = "Resources/" + info;
2316 }
2317
2318 folder.Open(info, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2319 plist_d(buffer, length, fun([&](plist_t node) {
2320 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
2321 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
2322 }));
2323 }));
2324
2325 if (!mac && folder.Look("MacOS/" + executable)) {
2326 executable = "MacOS/" + executable;
2327 mac = true;
2328 }
2329
2330 std::string entitlements;
2331 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2332 // XXX: this is a miserable fail
2333 std::stringbuf temp;
2334 copy(buffer, temp, length, percent);
2335 // XXX: this is a stupid hack
2336 pad(temp, 0x10 - (length & 0xf));
2337 auto data(temp.str());
2338 entitlements = alter(root, Analyze(data.data(), data.size()));
2339 }));
2340
2341 static const std::string directory("_CodeSignature/");
2342 static const std::string signature(directory + "CodeResources");
2343
2344 std::map<std::string, std::multiset<Rule>> versions;
2345
2346 auto &rules1(versions[""]);
2347 auto &rules2(versions["2"]);
2348
2349 const std::string resources(mac ? "Resources/" : "");
2350
2351 if (true) {
2352 rules1.insert(Rule{1, NoMode, "^" + resources});
2353 rules1.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2354 rules1.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
2355 rules1.insert(Rule{1010, NoMode, "^Base\\.lproj/"});
2356 rules1.insert(Rule{1, NoMode, "^version.plist$"});
2357 }
2358
2359 if (true) {
2360 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
2361 rules2.insert(Rule{20, NoMode, "^" + resources});
2362 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
2363 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2364 rules2.insert(Rule{1, NoMode, "^.*"});
2365 rules2.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2366 rules2.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
2367 rules2.insert(Rule{1010, NoMode, "^Base\\.lproj/"});
2368 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
2369 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
2370 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
2371 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
2372 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
2373 }
2374
2375 std::map<std::string, Hash> local;
2376
2377 std::string failure(mac ? "Contents/|Versions/[^/]*/Resources/" : "");
2378 Expression nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure + ")Info\\.plist$");
2379 std::map<std::string, Bundle> bundles;
2380
2381 folder.Find("", fun([&](const std::string &name) {
2382 if (!nested(name))
2383 return;
2384 auto bundle(root + Split(name).dir);
2385 bundle.resize(bundle.size() - resources.size());
2386 SubFolder subfolder(folder, bundle);
2387
2388 bundles[nested[1]] = Sign(bundle, subfolder, key, local, "", Starts(name, "PlugIns/") ? alter :
2389 static_cast<const Functor<std::string (const std::string &, const std::string &)> &>(fun([&](const std::string &, const std::string &entitlements) -> std::string { return entitlements; }))
2390 , progress, percent);
2391 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2392 }));
2393
2394 std::set<std::string> excludes;
2395
2396 auto exclude([&](const std::string &name) {
2397 // BundleDiskRep::adjustResources -> builder.addExclusion
2398 if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
2399 return true;
2400
2401 for (const auto &bundle : bundles)
2402 if (Starts(name, bundle.first + "/")) {
2403 excludes.insert(name);
2404 return true;
2405 }
2406
2407 return false;
2408 });
2409
2410 std::map<std::string, std::string> links;
2411
2412 folder.Find("", fun([&](const std::string &name) {
2413 if (exclude(name))
2414 return;
2415
2416 if (local.find(name) != local.end())
2417 return;
2418 auto &hash(local[name]);
2419
2420 folder.Open(name, fun([&](std::streambuf &data, size_t length, const void *flag) {
2421 progress(root + name);
2422
2423 union {
2424 struct {
2425 uint32_t magic;
2426 uint32_t count;
2427 };
2428
2429 uint8_t bytes[8];
2430 } header;
2431
2432 auto size(most(data, &header.bytes, sizeof(header.bytes)));
2433
2434 if (name != "_WatchKitStub/WK" && size == sizeof(header.bytes))
2435 switch (Swap(header.magic)) {
2436 case FAT_MAGIC:
2437 // Java class file format
2438 if (Swap(header.count) >= 40)
2439 break;
2440 case FAT_CIGAM:
2441 case MH_MAGIC: case MH_MAGIC_64:
2442 case MH_CIGAM: case MH_CIGAM_64:
2443 folder.Save(name, true, flag, fun([&](std::streambuf &save) {
2444 Slots slots;
2445 Sign(header.bytes, size, data, hash, save, identifier, "", "", key, slots, length, percent);
2446 }));
2447 return;
2448 }
2449
2450 folder.Save(name, false, flag, fun([&](std::streambuf &save) {
2451 HashProxy proxy(hash, save);
2452 put(proxy, header.bytes, size);
2453 copy(data, proxy, length - size, percent);
2454 }));
2455 }));
2456 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2457 if (exclude(name))
2458 return;
2459
2460 links[name] = read();
2461 }));
2462
2463 auto plist(plist_new_dict());
2464 _scope({ plist_free(plist); });
2465
2466 for (const auto &version : versions) {
2467 auto files(plist_new_dict());
2468 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
2469
2470 for (const auto &rule : version.second)
2471 rule.Compile();
2472
2473 bool old(&version.second == &rules1);
2474
2475 for (const auto &hash : local)
2476 for (const auto &rule : version.second)
2477 if (rule(hash.first)) {
2478 if (!old && mac && excludes.find(hash.first) != excludes.end());
2479 else if (old && rule.mode_ == NoMode)
2480 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
2481 else if (rule.mode_ != OmitMode) {
2482 auto entry(plist_new_dict());
2483 plist_dict_set_item(entry, "hash", plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
2484 if (!old)
2485 plist_dict_set_item(entry, "hash2", plist_new_data(reinterpret_cast<const char *>(hash.second.sha256_), sizeof(hash.second.sha256_)));
2486 if (rule.mode_ == OptionalMode)
2487 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2488 plist_dict_set_item(files, hash.first.c_str(), entry);
2489 }
2490
2491 break;
2492 }
2493
2494 for (const auto &link : links)
2495 for (const auto &rule : version.second)
2496 if (rule(link.first)) {
2497 if (rule.mode_ != OmitMode) {
2498 auto entry(plist_new_dict());
2499 plist_dict_set_item(entry, "symlink", plist_new_string(link.second.c_str()));
2500 if (rule.mode_ == OptionalMode)
2501 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2502 plist_dict_set_item(files, link.first.c_str(), entry);
2503 }
2504
2505 break;
2506 }
2507
2508 if (!old && mac)
2509 for (const auto &bundle : bundles) {
2510 auto entry(plist_new_dict());
2511 plist_dict_set_item(entry, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle.second.hash.sha256_), sizeof(bundle.second.hash.sha256_)));
2512 plist_dict_set_item(entry, "requirement", plist_new_string("anchor apple generic"));
2513 plist_dict_set_item(files, bundle.first.c_str(), entry);
2514 }
2515 }
2516
2517 for (const auto &version : versions) {
2518 auto rules(plist_new_dict());
2519 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
2520
2521 std::multiset<const Rule *, RuleCode> ordered;
2522 for (const auto &rule : version.second)
2523 ordered.insert(&rule);
2524
2525 for (const auto &rule : ordered)
2526 if (rule->weight_ == 1 && rule->mode_ == NoMode)
2527 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
2528 else {
2529 auto entry(plist_new_dict());
2530 plist_dict_set_item(rules, rule->code_.c_str(), entry);
2531
2532 switch (rule->mode_) {
2533 case NoMode:
2534 break;
2535 case OmitMode:
2536 plist_dict_set_item(entry, "omit", plist_new_bool(true));
2537 break;
2538 case OptionalMode:
2539 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2540 break;
2541 case NestedMode:
2542 plist_dict_set_item(entry, "nested", plist_new_bool(true));
2543 break;
2544 case TopMode:
2545 plist_dict_set_item(entry, "top", plist_new_bool(true));
2546 break;
2547 }
2548
2549 if (rule->weight_ >= 10000)
2550 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
2551 else if (rule->weight_ != 1)
2552 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
2553 }
2554 }
2555
2556 folder.Save(signature, true, NULL, fun([&](std::streambuf &save) {
2557 HashProxy proxy(local[signature], save);
2558 char *xml(NULL);
2559 uint32_t size;
2560 plist_to_xml(plist, &xml, &size);
2561 _scope({ free(xml); });
2562 put(proxy, xml, size);
2563 }));
2564
2565 Bundle bundle;
2566 bundle.path = executable;
2567
2568 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2569 progress(root + executable);
2570 folder.Save(executable, true, flag, fun([&](std::streambuf &save) {
2571 Slots slots;
2572 slots[1] = local.at(info);
2573 slots[3] = local.at(signature);
2574 bundle.hash = Sign(NULL, 0, buffer, local[executable], save, identifier, entitlements, requirements, key, slots, length, percent);
2575 }));
2576 }));
2577
2578 for (const auto &entry : local)
2579 remote[root + entry.first] = entry.second;
2580
2581 return bundle;
2582 }
2583
2584 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 Functor<void (const std::string &)> &progress, const Functor<void (double)> &percent) {
2585 std::map<std::string, Hash> local;
2586 return Sign(root, folder, key, local, requirements, alter, progress, percent);
2587 }
2588 #endif
2589
2590 #endif
2591 }
2592
2593 #ifndef LDID_NOTOOLS
2594 int main(int argc, char *argv[]) {
2595 #ifndef LDID_NOSMIME
2596 OpenSSL_add_all_algorithms();
2597 #endif
2598
2599 union {
2600 uint16_t word;
2601 uint8_t byte[2];
2602 } endian = {1};
2603
2604 little_ = endian.byte[0];
2605
2606 bool flag_r(false);
2607 bool flag_e(false);
2608 bool flag_q(false);
2609
2610 #ifndef LDID_NOFLAGT
2611 bool flag_T(false);
2612 #endif
2613
2614 bool flag_S(false);
2615 bool flag_s(false);
2616
2617 bool flag_D(false);
2618
2619 bool flag_A(false);
2620 bool flag_a(false);
2621
2622 bool flag_u(false);
2623
2624 uint32_t flag_CPUType(_not(uint32_t));
2625 uint32_t flag_CPUSubtype(_not(uint32_t));
2626
2627 const char *flag_I(NULL);
2628
2629 #ifndef LDID_NOFLAGT
2630 bool timeh(false);
2631 uint32_t timev(0);
2632 #endif
2633
2634 Map entitlements;
2635 Map requirements;
2636 Map key;
2637 ldid::Slots slots;
2638
2639 std::vector<std::string> files;
2640
2641 if (argc == 1) {
2642 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
2643 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
2644 fprintf(stderr, " %s -S cat\n", argv[0]);
2645 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
2646 exit(0);
2647 }
2648
2649 for (int argi(1); argi != argc; ++argi)
2650 if (argv[argi][0] != '-')
2651 files.push_back(argv[argi]);
2652 else switch (argv[argi][1]) {
2653 case 'r':
2654 _assert(!flag_s);
2655 _assert(!flag_S);
2656 flag_r = true;
2657 break;
2658
2659 case 'e': flag_e = true; break;
2660
2661 case 'E': {
2662 const char *string = argv[argi] + 2;
2663 const char *colon = strchr(string, ':');
2664 _assert(colon != NULL);
2665 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
2666 char *arge;
2667 unsigned number(strtoul(string, &arge, 0));
2668 _assert(arge == colon);
2669 auto &slot(slots[number]);
2670 for (Algorithm *algorithm : GetAlgorithms())
2671 (*algorithm)(slot, file.data(), file.size());
2672 } break;
2673
2674 case 'q': flag_q = true; break;
2675
2676 case 'Q': {
2677 const char *xml = argv[argi] + 2;
2678 requirements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2679 } break;
2680
2681 case 'D': flag_D = true; break;
2682
2683 case 'a': flag_a = true; break;
2684
2685 case 'A':
2686 _assert(!flag_A);
2687 flag_A = true;
2688 if (argv[argi][2] != '\0') {
2689 const char *cpu = argv[argi] + 2;
2690 const char *colon = strchr(cpu, ':');
2691 _assert(colon != NULL);
2692 char *arge;
2693 flag_CPUType = strtoul(cpu, &arge, 0);
2694 _assert(arge == colon);
2695 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2696 _assert(arge == argv[argi] + strlen(argv[argi]));
2697 }
2698 break;
2699
2700 case 's':
2701 _assert(!flag_r);
2702 _assert(!flag_S);
2703 flag_s = true;
2704 break;
2705
2706 case 'S':
2707 _assert(!flag_r);
2708 _assert(!flag_s);
2709 flag_S = true;
2710 if (argv[argi][2] != '\0') {
2711 const char *xml = argv[argi] + 2;
2712 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2713 }
2714 break;
2715
2716 case 'K':
2717 if (argv[argi][2] != '\0')
2718 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
2719 break;
2720
2721 #ifndef LDID_NOFLAGT
2722 case 'T': {
2723 flag_T = true;
2724 if (argv[argi][2] == '-')
2725 timeh = true;
2726 else {
2727 char *arge;
2728 timev = strtoul(argv[argi] + 2, &arge, 0);
2729 _assert(arge == argv[argi] + strlen(argv[argi]));
2730 }
2731 } break;
2732 #endif
2733
2734 case 'u': {
2735 flag_u = true;
2736 } break;
2737
2738 case 'I': {
2739 flag_I = argv[argi] + 2;
2740 } break;
2741
2742 default:
2743 goto usage;
2744 break;
2745 }
2746
2747 _assert(flag_S || key.empty());
2748 _assert(flag_S || flag_I == NULL);
2749
2750 if (files.empty()) usage: {
2751 exit(0);
2752 }
2753
2754 size_t filei(0), filee(0);
2755 _foreach (file, files) try {
2756 std::string path(file);
2757
2758 struct stat info;
2759 _syscall(stat(path.c_str(), &info));
2760
2761 if (S_ISDIR(info.st_mode)) {
2762 #ifndef LDID_NOPLIST
2763 _assert(!flag_r);
2764 ldid::DiskFolder folder(path);
2765 path += "/" + Sign("", folder, key, requirements, ldid::fun([&](const std::string &, const std::string &) -> std::string { return entitlements; })
2766 , ldid::fun([&](const std::string &) {}), ldid::fun(dummy)
2767 ).path;
2768 #else
2769 _assert(false);
2770 #endif
2771 } else if (flag_S || flag_r) {
2772 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
2773
2774 std::filebuf output;
2775 Split split(path);
2776 auto temp(Temporary(output, split));
2777
2778 if (flag_r)
2779 ldid::Unsign(input.data(), input.size(), output, ldid::fun(dummy));
2780 else {
2781 std::string identifier(flag_I ?: split.base.c_str());
2782 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, requirements, key, slots, ldid::fun(dummy));
2783 }
2784
2785 Commit(path, temp);
2786 }
2787
2788 bool modify(false);
2789 #ifndef LDID_NOFLAGT
2790 if (flag_T)
2791 modify = true;
2792 #endif
2793 if (flag_s)
2794 modify = true;
2795
2796 Map mapping(path, modify);
2797 FatHeader fat_header(mapping.data(), mapping.size());
2798
2799 _foreach (mach_header, fat_header.GetMachHeaders()) {
2800 struct linkedit_data_command *signature(NULL);
2801 struct encryption_info_command *encryption(NULL);
2802
2803 if (flag_A) {
2804 if (mach_header.GetCPUType() != flag_CPUType)
2805 continue;
2806 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2807 continue;
2808 }
2809
2810 if (flag_a)
2811 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2812
2813 _foreach (load_command, mach_header.GetLoadCommands()) {
2814 uint32_t cmd(mach_header.Swap(load_command->cmd));
2815
2816 if (false);
2817 else if (cmd == LC_CODE_SIGNATURE)
2818 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
2819 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
2820 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
2821 else if (cmd == LC_LOAD_DYLIB) {
2822 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2823 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
2824
2825 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2826 if (flag_u) {
2827 Version version;
2828 version.value = mach_header.Swap(dylib_command->dylib.current_version);
2829 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
2830 }
2831 }
2832 }
2833 #ifndef LDID_NOFLAGT
2834 else if (cmd == LC_ID_DYLIB) {
2835 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2836
2837 if (flag_T) {
2838 uint32_t timed;
2839
2840 if (!timeh)
2841 timed = timev;
2842 else {
2843 dylib_command->dylib.timestamp = 0;
2844 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2845 }
2846
2847 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2848 }
2849 }
2850 #endif
2851 }
2852
2853 if (flag_D) {
2854 _assert(encryption != NULL);
2855 encryption->cryptid = mach_header.Swap(0);
2856 }
2857
2858 if (flag_e) {
2859 _assert(signature != NULL);
2860
2861 uint32_t data = mach_header.Swap(signature->dataoff);
2862
2863 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2864 uint8_t *blob = top + data;
2865 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2866
2867 for (size_t index(0); index != Swap(super->count); ++index)
2868 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2869 uint32_t begin = Swap(super->index[index].offset);
2870 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
2871 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
2872 }
2873 }
2874
2875 if (flag_q) {
2876 _assert(signature != NULL);
2877
2878 uint32_t data = mach_header.Swap(signature->dataoff);
2879
2880 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2881 uint8_t *blob = top + data;
2882 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2883
2884 for (size_t index(0); index != Swap(super->count); ++index)
2885 if (Swap(super->index[index].type) == CSSLOT_REQUIREMENTS) {
2886 uint32_t begin = Swap(super->index[index].offset);
2887 struct Blob *requirement = reinterpret_cast<struct Blob *>(blob + begin);
2888 fwrite(requirement, 1, Swap(requirement->length), stdout);
2889 }
2890 }
2891
2892 if (flag_s) {
2893 _assert(signature != NULL);
2894
2895 uint32_t data = mach_header.Swap(signature->dataoff);
2896
2897 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2898 uint8_t *blob = top + data;
2899 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2900
2901 for (size_t index(0); index != Swap(super->count); ++index)
2902 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2903 uint32_t begin = Swap(super->index[index].offset);
2904 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob));
2905
2906 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
2907 uint32_t pages = Swap(directory->nCodeSlots);
2908
2909 if (pages != 1)
2910 for (size_t i = 0; i != pages - 1; ++i)
2911 LDID_SHA1(top + PageSize_ * i, PageSize_, hashes[i]);
2912 if (pages != 0)
2913 LDID_SHA1(top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1, hashes[pages - 1]);
2914 }
2915 }
2916 }
2917
2918 ++filei;
2919 } catch (const char *) {
2920 ++filee;
2921 ++filei;
2922 }
2923
2924 return filee;
2925 }
2926 #endif