]> git.saurik.com Git - ldid.git/blob - ldid.cpp
4ad9b2f06827744da417996aacc2878db85c3560
[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
1458 _assert(key_ != NULL);
1459 _assert(cert_ != NULL);
1460
1461 if (ca_ == NULL)
1462 ca_ = sk_X509_new_null();
1463 _assert(ca_ != NULL);
1464 }
1465
1466 Stuff(const std::string &data) :
1467 Stuff(Buffer(data))
1468 {
1469 }
1470
1471 ~Stuff() {
1472 sk_X509_pop_free(ca_, X509_free);
1473 X509_free(cert_);
1474 EVP_PKEY_free(key_);
1475 PKCS12_free(value_);
1476 }
1477
1478 operator PKCS12 *() const {
1479 return value_;
1480 }
1481
1482 operator EVP_PKEY *() const {
1483 return key_;
1484 }
1485
1486 operator X509 *() const {
1487 return cert_;
1488 }
1489
1490 operator STACK_OF(X509) *() const {
1491 return ca_;
1492 }
1493 };
1494
1495 class Signature {
1496 private:
1497 PKCS7 *value_;
1498
1499 public:
1500 Signature(const Stuff &stuff, const Buffer &data, const std::string &xml) {
1501 value_ = PKCS7_new();
1502 _assert(value_ != NULL);
1503
1504 _assert(PKCS7_set_type(value_, NID_pkcs7_signed));
1505 _assert(PKCS7_content_new(value_, NID_pkcs7_data));
1506
1507 STACK_OF(X509) *certs(stuff);
1508 for (unsigned i(0), e(sk_X509_num(certs)); i != e; i++)
1509 _assert(PKCS7_add_certificate(value_, sk_X509_value(certs, e - i - 1)));
1510
1511 auto info(PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP));
1512 _assert(info != NULL);
1513
1514 PKCS7_set_detached(value_, 1);
1515
1516 ASN1_OCTET_STRING *string(ASN1_OCTET_STRING_new());
1517 _assert(string != NULL);
1518 try {
1519 _assert(ASN1_STRING_set(string, xml.data(), xml.size()));
1520
1521 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1522 _assert(PKCS7_add_signed_attribute(info, nid, V_ASN1_OCTET_STRING, string));
1523 } catch (...) {
1524 ASN1_OCTET_STRING_free(string);
1525 throw;
1526 }
1527
1528 _assert(PKCS7_final(value_, data, PKCS7_BINARY));
1529 }
1530
1531 ~Signature() {
1532 PKCS7_free(value_);
1533 }
1534
1535 operator PKCS7 *() const {
1536 return value_;
1537 }
1538 };
1539 #endif
1540
1541 class NullBuffer :
1542 public std::streambuf
1543 {
1544 public:
1545 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1546 return size;
1547 }
1548
1549 virtual int_type overflow(int_type next) {
1550 return next;
1551 }
1552 };
1553
1554 class Digest {
1555 public:
1556 uint8_t sha1_[LDID_SHA1_DIGEST_LENGTH];
1557 };
1558
1559 class HashBuffer :
1560 public std::streambuf
1561 {
1562 private:
1563 ldid::Hash &hash_;
1564
1565 LDID_SHA1_CTX sha1_;
1566 LDID_SHA256_CTX sha256_;
1567
1568 public:
1569 HashBuffer(ldid::Hash &hash) :
1570 hash_(hash)
1571 {
1572 LDID_SHA1_Init(&sha1_);
1573 LDID_SHA256_Init(&sha256_);
1574 }
1575
1576 ~HashBuffer() {
1577 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.sha1_), &sha1_);
1578 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_.sha256_), &sha256_);
1579 }
1580
1581 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1582 LDID_SHA1_Update(&sha1_, data, size);
1583 LDID_SHA256_Update(&sha256_, data, size);
1584 return size;
1585 }
1586
1587 virtual int_type overflow(int_type next) {
1588 if (next == traits_type::eof())
1589 return sync();
1590 char value(next);
1591 xsputn(&value, 1);
1592 return next;
1593 }
1594 };
1595
1596 class HashProxy :
1597 public HashBuffer
1598 {
1599 private:
1600 std::streambuf &buffer_;
1601
1602 public:
1603 HashProxy(ldid::Hash &hash, std::streambuf &buffer) :
1604 HashBuffer(hash),
1605 buffer_(buffer)
1606 {
1607 }
1608
1609 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1610 _assert(HashBuffer::xsputn(data, size) == size);
1611 return buffer_.sputn(data, size);
1612 }
1613 };
1614
1615 #ifndef LDID_NOTOOLS
1616 static bool Starts(const std::string &lhs, const std::string &rhs) {
1617 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1618 }
1619
1620 class Split {
1621 public:
1622 std::string dir;
1623 std::string base;
1624
1625 Split(const std::string &path) {
1626 size_t slash(path.rfind('/'));
1627 if (slash == std::string::npos)
1628 base = path;
1629 else {
1630 dir = path.substr(0, slash + 1);
1631 base = path.substr(slash + 1);
1632 }
1633 }
1634 };
1635
1636 static void mkdir_p(const std::string &path) {
1637 if (path.empty())
1638 return;
1639 #ifdef __WIN32__
1640 if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
1641 return;
1642 #else
1643 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1644 return;
1645 #endif
1646 auto slash(path.rfind('/', path.size() - 1));
1647 if (slash == std::string::npos)
1648 return;
1649 mkdir_p(path.substr(0, slash));
1650 }
1651
1652 static std::string Temporary(std::filebuf &file, const Split &split) {
1653 std::string temp(split.dir + ".ldid." + split.base);
1654 mkdir_p(split.dir);
1655 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1656 return temp;
1657 }
1658
1659 static void Commit(const std::string &path, const std::string &temp) {
1660 struct stat info;
1661 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
1662 #ifndef __WIN32__
1663 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1664 #endif
1665 _syscall(chmod(temp.c_str(), info.st_mode));
1666 }
1667
1668 _syscall(rename(temp.c_str(), path.c_str()));
1669 }
1670 #endif
1671
1672 namespace ldid {
1673
1674 static void get(std::string &value, X509_NAME *name, int nid) {
1675 auto index(X509_NAME_get_index_by_NID(name, nid, -1));
1676 _assert(index >= 0);
1677 auto next(X509_NAME_get_index_by_NID(name, nid, index));
1678 _assert(next == -1);
1679 auto entry(X509_NAME_get_entry(name, index));
1680 _assert(entry != NULL);
1681 auto asn(X509_NAME_ENTRY_get_data(entry));
1682 _assert(asn != NULL);
1683 value.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn)), ASN1_STRING_length(asn));
1684 }
1685
1686 static void req(std::streambuf &buffer, uint32_t value) {
1687 value = Swap(value);
1688 put(buffer, &value, sizeof(value));
1689 }
1690
1691 static void req(std::streambuf &buffer, const std::string &value) {
1692 req(buffer, value.size());
1693 put(buffer, value.data(), value.size());
1694 static uint8_t zeros[] = {0,0,0,0};
1695 put(buffer, zeros, 3 - (value.size() + 3) % 4);
1696 }
1697
1698 template <size_t Size_>
1699 static void req(std::streambuf &buffer, uint8_t (&&data)[Size_]) {
1700 req(buffer, Size_);
1701 put(buffer, data, Size_);
1702 static uint8_t zeros[] = {0,0,0,0};
1703 put(buffer, zeros, 3 - (Size_ + 3) % 4);
1704 }
1705
1706 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) {
1707 Hash hash;
1708
1709
1710 std::string team;
1711 std::string common;
1712
1713 #ifndef LDID_NOSMIME
1714 if (!key.empty()) {
1715 Stuff stuff(key);
1716 auto name(X509_get_subject_name(stuff));
1717 _assert(name != NULL);
1718 get(team, name, NID_organizationalUnitName);
1719 get(common, name, NID_commonName);
1720 }
1721 #endif
1722
1723
1724 std::stringbuf backing;
1725
1726 if (!requirements.empty()) {
1727 put(backing, requirements.data(), requirements.size());
1728 } else {
1729 Blobs blobs;
1730
1731 std::stringbuf requirement;
1732 req(requirement, exprForm);
1733 req(requirement, opAnd);
1734 req(requirement, opIdent);
1735 req(requirement, identifier);
1736 req(requirement, opAnd);
1737 req(requirement, opAppleGenericAnchor);
1738 req(requirement, opAnd);
1739 req(requirement, opCertField);
1740 req(requirement, 0);
1741 req(requirement, "subject.CN");
1742 req(requirement, matchEqual);
1743 req(requirement, common);
1744 req(requirement, opCertGeneric);
1745 req(requirement, 1);
1746 req(requirement, (uint8_t []) {APPLE_EXTENSION_OID, 2, 1});
1747 req(requirement, matchExists);
1748 insert(blobs, 3, CSMAGIC_REQUIREMENT, requirement);
1749
1750 put(backing, CSMAGIC_REQUIREMENTS, blobs);
1751 }
1752
1753
1754 // XXX: this is just a "sufficiently large number"
1755 size_t certificate(0x3000);
1756
1757 Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, size_t size) -> size_t {
1758 size_t alloc(sizeof(struct SuperBlob));
1759
1760 uint32_t normal((size + PageSize_ - 1) / PageSize_);
1761
1762 uint32_t special(0);
1763
1764 _foreach (slot, slots)
1765 special = std::max(special, slot.first);
1766
1767 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1768 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
1769 special = std::max(special, CSSLOT_INFOSLOT);
1770 }));
1771
1772 special = std::max(special, CSSLOT_REQUIREMENTS);
1773 alloc += sizeof(struct BlobIndex);
1774 alloc += backing.str().size();
1775
1776 if (!entitlements.empty()) {
1777 special = std::max(special, CSSLOT_ENTITLEMENTS);
1778 alloc += sizeof(struct BlobIndex);
1779 alloc += sizeof(struct Blob);
1780 alloc += entitlements.size();
1781 }
1782
1783 size_t directory(0);
1784
1785 directory += sizeof(struct BlobIndex);
1786 directory += sizeof(struct Blob);
1787 directory += sizeof(struct CodeDirectory);
1788 directory += identifier.size() + 1;
1789
1790 if (!team.empty())
1791 directory += team.size() + 1;
1792
1793 for (Algorithm *algorithm : GetAlgorithms())
1794 alloc = Align(alloc + directory + (special + normal) * algorithm->size_, 16);
1795
1796 #ifndef LDID_NOSMIME
1797 if (!key.empty()) {
1798 alloc += sizeof(struct BlobIndex);
1799 alloc += sizeof(struct Blob);
1800 alloc += certificate;
1801 }
1802 #endif
1803
1804 return alloc;
1805 }), 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 {
1806 Blobs blobs;
1807
1808 if (true) {
1809 insert(blobs, CSSLOT_REQUIREMENTS, backing);
1810 }
1811
1812 if (!entitlements.empty()) {
1813 std::stringbuf data;
1814 put(data, entitlements.data(), entitlements.size());
1815 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
1816 }
1817
1818 Slots posts(slots);
1819
1820 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1821 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0) {
1822 auto &slot(posts[CSSLOT_INFOSLOT]);
1823 for (Algorithm *algorithm : GetAlgorithms())
1824 (*algorithm)(slot, data, size);
1825 }
1826 }));
1827
1828 unsigned total(0);
1829 for (Algorithm *pointer : GetAlgorithms()) {
1830 Algorithm &algorithm(*pointer);
1831
1832 std::stringbuf data;
1833
1834 uint32_t special(0);
1835 _foreach (blob, blobs)
1836 special = std::max(special, blob.first);
1837 _foreach (slot, posts)
1838 special = std::max(special, slot.first);
1839 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
1840
1841 CodeDirectory directory;
1842 directory.version = Swap(uint32_t(0x00020200));
1843 directory.flags = Swap(uint32_t(0));
1844 directory.nSpecialSlots = Swap(special);
1845 directory.codeLimit = Swap(uint32_t(limit));
1846 directory.nCodeSlots = Swap(normal);
1847 directory.hashSize = algorithm.size_;
1848 directory.hashType = algorithm.type_;
1849 directory.spare1 = 0x00;
1850 directory.pageSize = PageShift_;
1851 directory.spare2 = Swap(uint32_t(0));
1852 directory.scatterOffset = Swap(uint32_t(0));
1853 //directory.spare3 = Swap(uint32_t(0));
1854 //directory.codeLimit64 = Swap(uint64_t(0));
1855
1856 uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory));
1857
1858 directory.identOffset = Swap(uint32_t(offset));
1859 offset += identifier.size() + 1;
1860
1861 if (team.empty())
1862 directory.teamIDOffset = Swap(uint32_t(0));
1863 else {
1864 directory.teamIDOffset = Swap(uint32_t(offset));
1865 offset += team.size() + 1;
1866 }
1867
1868 offset += special * algorithm.size_;
1869 directory.hashOffset = Swap(uint32_t(offset));
1870 offset += normal * algorithm.size_;
1871
1872 put(data, &directory, sizeof(directory));
1873
1874 put(data, identifier.c_str(), identifier.size() + 1);
1875 if (!team.empty())
1876 put(data, team.c_str(), team.size() + 1);
1877
1878 std::vector<uint8_t> storage((special + normal) * algorithm.size_);
1879 auto *hashes(&storage[special * algorithm.size_]);
1880
1881 memset(storage.data(), 0, special * algorithm.size_);
1882
1883 _foreach (blob, blobs) {
1884 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1885 algorithm(hashes - blob.first * algorithm.size_, local, Swap(local->length));
1886 }
1887
1888 _foreach (slot, posts)
1889 memcpy(hashes - slot.first * algorithm.size_, algorithm[slot.second], algorithm.size_);
1890
1891 percent(0);
1892 if (normal != 1)
1893 for (size_t i = 0; i != normal - 1; ++i) {
1894 algorithm(hashes + i * algorithm.size_, (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
1895 percent(double(i) / normal);
1896 }
1897 if (normal != 0)
1898 algorithm(hashes + (normal - 1) * algorithm.size_, top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
1899 percent(1);
1900
1901 put(data, storage.data(), storage.size());
1902
1903 const auto &save(insert(blobs, total == 0 ? CSSLOT_CODEDIRECTORY : CSSLOT_ALTERNATE + total - 1, CSMAGIC_CODEDIRECTORY, data));
1904 algorithm(hash, save.data(), save.size());
1905
1906 ++total;
1907 }
1908
1909 #ifndef LDID_NOSMIME
1910 if (!key.empty()) {
1911 auto plist(plist_new_dict());
1912 _scope({ plist_free(plist); });
1913
1914 auto cdhashes(plist_new_array());
1915 plist_dict_set_item(plist, "cdhashes", cdhashes);
1916
1917 unsigned total(0);
1918 for (Algorithm *pointer : GetAlgorithms()) {
1919 Algorithm &algorithm(*pointer);
1920 (void) algorithm;
1921
1922 const auto &blob(blobs[total == 0 ? CSSLOT_CODEDIRECTORY : CSSLOT_ALTERNATE + total - 1]);
1923 ++total;
1924
1925 std::vector<char> hash;
1926 algorithm(hash, blob.data(), blob.size());
1927 hash.resize(20);
1928
1929 plist_array_append_item(cdhashes, plist_new_data(hash.data(), hash.size()));
1930 }
1931
1932 char *xml(NULL);
1933 uint32_t size;
1934 plist_to_xml(plist, &xml, &size);
1935 _scope({ free(xml); });
1936
1937 std::stringbuf data;
1938 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1939
1940 Stuff stuff(key);
1941 Buffer bio(sign);
1942
1943 Signature signature(stuff, sign, std::string(xml, size));
1944 Buffer result(signature);
1945 std::string value(result);
1946 put(data, value.data(), value.size());
1947
1948 const auto &save(insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data));
1949 _assert(save.size() <= certificate);
1950 }
1951 #endif
1952
1953 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
1954 }), percent);
1955
1956 return hash;
1957 }
1958
1959 #ifndef LDID_NOTOOLS
1960 static void Unsign(void *idata, size_t isize, std::streambuf &output, const Functor<void (double)> &percent) {
1961 Allocate(idata, isize, output, fun([](const MachHeader &mach_header, size_t size) -> size_t {
1962 return 0;
1963 }), 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 {
1964 return 0;
1965 }), percent);
1966 }
1967
1968 std::string DiskFolder::Path(const std::string &path) const {
1969 return path_ + "/" + path;
1970 }
1971
1972 DiskFolder::DiskFolder(const std::string &path) :
1973 path_(path)
1974 {
1975 }
1976
1977 DiskFolder::~DiskFolder() {
1978 if (!std::uncaught_exception())
1979 for (const auto &commit : commit_)
1980 Commit(commit.first, commit.second);
1981 }
1982
1983 #ifndef __WIN32__
1984 std::string readlink(const std::string &path) {
1985 for (size_t size(1024); ; size *= 2) {
1986 std::string data;
1987 data.resize(size);
1988
1989 int writ(_syscall(::readlink(path.c_str(), &data[0], data.size())));
1990 if (size_t(writ) >= size)
1991 continue;
1992
1993 data.resize(writ);
1994 return data;
1995 }
1996 }
1997 #endif
1998
1999 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 {
2000 std::string path(Path(root) + base);
2001
2002 DIR *dir(opendir(path.c_str()));
2003 _assert(dir != NULL);
2004 _scope({ _syscall(closedir(dir)); });
2005
2006 while (auto child = readdir(dir)) {
2007 std::string name(child->d_name);
2008 if (name == "." || name == "..")
2009 continue;
2010 if (Starts(name, ".ldid."))
2011 continue;
2012
2013 bool directory;
2014
2015 #ifdef __WIN32__
2016 struct stat info;
2017 _syscall(stat((path + name).c_str(), &info));
2018 if (false);
2019 else if (S_ISDIR(info.st_mode))
2020 directory = true;
2021 else if (S_ISREG(info.st_mode))
2022 directory = false;
2023 else
2024 _assert_(false, "st_mode=%x", info.st_mode);
2025 #else
2026 switch (child->d_type) {
2027 case DT_DIR:
2028 directory = true;
2029 break;
2030 case DT_REG:
2031 directory = false;
2032 break;
2033 case DT_LNK:
2034 link(base + name, fun([&]() { return readlink(path + name); }));
2035 continue;
2036 default:
2037 _assert_(false, "d_type=%u", child->d_type);
2038 }
2039 #endif
2040
2041 if (directory)
2042 Find(root, base + name + "/", code, link);
2043 else
2044 code(base + name);
2045 }
2046 }
2047
2048 void DiskFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2049 if (!edit) {
2050 // XXX: use nullbuf
2051 std::stringbuf save;
2052 code(save);
2053 } else {
2054 std::filebuf save;
2055 auto from(Path(path));
2056 commit_[from] = Temporary(save, from);
2057 code(save);
2058 }
2059 }
2060
2061 bool DiskFolder::Look(const std::string &path) const {
2062 return _syscall(access(Path(path).c_str(), R_OK), ENOENT) == 0;
2063 }
2064
2065 void DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2066 std::filebuf data;
2067 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
2068 _assert_(result == &data, "DiskFolder::Open(%s)", path.c_str());
2069
2070 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2071 data.pubseekpos(0, std::ios::in);
2072 code(data, length, NULL);
2073 }
2074
2075 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 {
2076 Find(path, "", code, link);
2077 }
2078 #endif
2079
2080 SubFolder::SubFolder(Folder &parent, const std::string &path) :
2081 parent_(parent),
2082 path_(path)
2083 {
2084 }
2085
2086 void SubFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2087 return parent_.Save(path_ + path, edit, flag, code);
2088 }
2089
2090 bool SubFolder::Look(const std::string &path) const {
2091 return parent_.Look(path_ + path);
2092 }
2093
2094 void SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2095 return parent_.Open(path_ + path, code);
2096 }
2097
2098 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 {
2099 return parent_.Find(path_ + path, code, link);
2100 }
2101
2102 std::string UnionFolder::Map(const std::string &path) const {
2103 auto remap(remaps_.find(path));
2104 if (remap == remaps_.end())
2105 return path;
2106 return remap->second;
2107 }
2108
2109 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 {
2110 if (file.size() >= path.size() && file.substr(0, path.size()) == path)
2111 code(file.substr(path.size()));
2112 }
2113
2114 UnionFolder::UnionFolder(Folder &parent) :
2115 parent_(parent)
2116 {
2117 }
2118
2119 void UnionFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2120 return parent_.Save(Map(path), edit, flag, code);
2121 }
2122
2123 bool UnionFolder::Look(const std::string &path) const {
2124 auto file(resets_.find(path));
2125 if (file != resets_.end())
2126 return true;
2127 return parent_.Look(Map(path));
2128 }
2129
2130 void UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
2131 auto file(resets_.find(path));
2132 if (file == resets_.end())
2133 return parent_.Open(Map(path), code);
2134 auto &entry(file->second);
2135
2136 auto &data(*entry.data_);
2137 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2138 data.pubseekpos(0, std::ios::in);
2139 code(data, length, entry.flag_);
2140 }
2141
2142 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 {
2143 for (auto &reset : resets_)
2144 Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2145 auto &entry(reset.second);
2146 auto &data(*entry.data_);
2147 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2148 data.pubseekpos(0, std::ios::in);
2149 code(data, length, entry.flag_);
2150 }));
2151
2152 for (auto &remap : remaps_)
2153 Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2154 parent_.Open(remap.second, fun([&](std::streambuf &data, size_t length, const void *flag) {
2155 code(data, length, flag);
2156 }));
2157 }));
2158
2159 parent_.Find(path, fun([&](const std::string &name) {
2160 if (deletes_.find(path + name) == deletes_.end())
2161 code(name);
2162 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2163 if (deletes_.find(path + name) == deletes_.end())
2164 link(name, read);
2165 }));
2166 }
2167
2168 #ifndef LDID_NOTOOLS
2169 static void copy(std::streambuf &source, std::streambuf &target, size_t length, const ldid::Functor<void (double)> &percent) {
2170 percent(0);
2171 size_t total(0);
2172 for (;;) {
2173 char data[4096 * 4];
2174 size_t writ(source.sgetn(data, sizeof(data)));
2175 if (writ == 0)
2176 break;
2177 _assert(target.sputn(data, writ) == writ);
2178 total += writ;
2179 percent(double(total) / length);
2180 }
2181 }
2182
2183 #ifndef LDID_NOPLIST
2184 static plist_t plist(const std::string &data) {
2185 plist_t plist(NULL);
2186 if (Starts(data, "bplist00"))
2187 plist_from_bin(data.data(), data.size(), &plist);
2188 else
2189 plist_from_xml(data.data(), data.size(), &plist);
2190 _assert(plist != NULL);
2191 return plist;
2192 }
2193
2194 static void plist_d(std::streambuf &buffer, size_t length, const Functor<void (plist_t)> &code) {
2195 std::stringbuf data;
2196 copy(buffer, data, length, ldid::fun(dummy));
2197 auto node(plist(data.str()));
2198 _scope({ plist_free(node); });
2199 _assert(plist_get_node_type(node) == PLIST_DICT);
2200 code(node);
2201 }
2202
2203 static std::string plist_s(plist_t node) {
2204 _assert(node != NULL);
2205 _assert(plist_get_node_type(node) == PLIST_STRING);
2206 char *data;
2207 plist_get_string_val(node, &data);
2208 _scope({ free(data); });
2209 return data;
2210 }
2211 #endif
2212
2213 enum Mode {
2214 NoMode,
2215 OptionalMode,
2216 OmitMode,
2217 NestedMode,
2218 TopMode,
2219 };
2220
2221 class Expression {
2222 private:
2223 regex_t regex_;
2224 std::vector<std::string> matches_;
2225
2226 public:
2227 Expression(const std::string &code) {
2228 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED) == 0, "regcomp()");
2229 matches_.resize(regex_.re_nsub + 1);
2230 }
2231
2232 ~Expression() {
2233 regfree(&regex_);
2234 }
2235
2236 bool operator ()(const std::string &data) {
2237 regmatch_t matches[matches_.size()];
2238 auto value(regexec(&regex_, data.c_str(), matches_.size(), matches, 0));
2239 if (value == REG_NOMATCH)
2240 return false;
2241 _assert_(value == 0, "regexec()");
2242 for (size_t i(0); i != matches_.size(); ++i)
2243 matches_[i].assign(data.data() + matches[i].rm_so, matches[i].rm_eo - matches[i].rm_so);
2244 return true;
2245 }
2246
2247 const std::string &operator [](size_t index) const {
2248 return matches_[index];
2249 }
2250 };
2251
2252 struct Rule {
2253 unsigned weight_;
2254 Mode mode_;
2255 std::string code_;
2256
2257 mutable std::auto_ptr<Expression> regex_;
2258
2259 Rule(unsigned weight, Mode mode, const std::string &code) :
2260 weight_(weight),
2261 mode_(mode),
2262 code_(code)
2263 {
2264 }
2265
2266 Rule(const Rule &rhs) :
2267 weight_(rhs.weight_),
2268 mode_(rhs.mode_),
2269 code_(rhs.code_)
2270 {
2271 }
2272
2273 void Compile() const {
2274 regex_.reset(new Expression(code_));
2275 }
2276
2277 bool operator ()(const std::string &data) const {
2278 _assert(regex_.get() != NULL);
2279 return (*regex_)(data);
2280 }
2281
2282 bool operator <(const Rule &rhs) const {
2283 if (weight_ > rhs.weight_)
2284 return true;
2285 if (weight_ < rhs.weight_)
2286 return false;
2287 return mode_ > rhs.mode_;
2288 }
2289 };
2290
2291 struct RuleCode {
2292 bool operator ()(const Rule *lhs, const Rule *rhs) const {
2293 return lhs->code_ < rhs->code_;
2294 }
2295 };
2296
2297 #ifndef LDID_NOPLIST
2298 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) {
2299 // XXX: this is a miserable fail
2300 std::stringbuf temp;
2301 put(temp, prefix, size);
2302 copy(buffer, temp, length - size, percent);
2303 // XXX: this is a stupid hack
2304 pad(temp, 0x10 - (length & 0xf));
2305 auto data(temp.str());
2306
2307 HashProxy proxy(hash, save);
2308 return Sign(data.data(), data.size(), proxy, identifier, entitlements, requirements, key, slots, percent);
2309 }
2310
2311 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) {
2312 std::string executable;
2313 std::string identifier;
2314
2315 bool mac(false);
2316
2317 std::string info("Info.plist");
2318 if (!folder.Look(info) && folder.Look("Resources/" + info)) {
2319 mac = true;
2320 info = "Resources/" + info;
2321 }
2322
2323 folder.Open(info, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2324 plist_d(buffer, length, fun([&](plist_t node) {
2325 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
2326 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
2327 }));
2328 }));
2329
2330 if (!mac && folder.Look("MacOS/" + executable)) {
2331 executable = "MacOS/" + executable;
2332 mac = true;
2333 }
2334
2335 std::string entitlements;
2336 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2337 // XXX: this is a miserable fail
2338 std::stringbuf temp;
2339 copy(buffer, temp, length, percent);
2340 // XXX: this is a stupid hack
2341 pad(temp, 0x10 - (length & 0xf));
2342 auto data(temp.str());
2343 entitlements = alter(root, Analyze(data.data(), data.size()));
2344 }));
2345
2346 static const std::string directory("_CodeSignature/");
2347 static const std::string signature(directory + "CodeResources");
2348
2349 std::map<std::string, std::multiset<Rule>> versions;
2350
2351 auto &rules1(versions[""]);
2352 auto &rules2(versions["2"]);
2353
2354 const std::string resources(mac ? "Resources/" : "");
2355
2356 if (true) {
2357 rules1.insert(Rule{1, NoMode, "^" + resources});
2358 rules1.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2359 rules1.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
2360 rules1.insert(Rule{1010, NoMode, "^Base\\.lproj/"});
2361 rules1.insert(Rule{1, NoMode, "^version.plist$"});
2362 }
2363
2364 if (true) {
2365 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
2366 rules2.insert(Rule{20, NoMode, "^" + resources});
2367 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
2368 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
2369 rules2.insert(Rule{1, NoMode, "^.*"});
2370 rules2.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2371 rules2.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
2372 rules2.insert(Rule{1010, NoMode, "^Base\\.lproj/"});
2373 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
2374 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
2375 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
2376 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
2377 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
2378 }
2379
2380 std::map<std::string, Hash> local;
2381
2382 std::string failure(mac ? "Contents/|Versions/[^/]*/Resources/" : "");
2383 Expression nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure + ")Info\\.plist$");
2384 std::map<std::string, Bundle> bundles;
2385
2386 folder.Find("", fun([&](const std::string &name) {
2387 if (!nested(name))
2388 return;
2389 auto bundle(root + Split(name).dir);
2390 bundle.resize(bundle.size() - resources.size());
2391 SubFolder subfolder(folder, bundle);
2392
2393 bundles[nested[1]] = Sign(bundle, subfolder, key, local, "", Starts(name, "PlugIns/") ? alter :
2394 static_cast<const Functor<std::string (const std::string &, const std::string &)> &>(fun([&](const std::string &, const std::string &entitlements) -> std::string { return entitlements; }))
2395 , progress, percent);
2396 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2397 }));
2398
2399 std::set<std::string> excludes;
2400
2401 auto exclude([&](const std::string &name) {
2402 // BundleDiskRep::adjustResources -> builder.addExclusion
2403 if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
2404 return true;
2405
2406 for (const auto &bundle : bundles)
2407 if (Starts(name, bundle.first + "/")) {
2408 excludes.insert(name);
2409 return true;
2410 }
2411
2412 return false;
2413 });
2414
2415 std::map<std::string, std::string> links;
2416
2417 folder.Find("", fun([&](const std::string &name) {
2418 if (exclude(name))
2419 return;
2420
2421 if (local.find(name) != local.end())
2422 return;
2423 auto &hash(local[name]);
2424
2425 folder.Open(name, fun([&](std::streambuf &data, size_t length, const void *flag) {
2426 progress(root + name);
2427
2428 union {
2429 struct {
2430 uint32_t magic;
2431 uint32_t count;
2432 };
2433
2434 uint8_t bytes[8];
2435 } header;
2436
2437 auto size(most(data, &header.bytes, sizeof(header.bytes)));
2438
2439 if (name != "_WatchKitStub/WK" && size == sizeof(header.bytes))
2440 switch (Swap(header.magic)) {
2441 case FAT_MAGIC:
2442 // Java class file format
2443 if (Swap(header.count) >= 40)
2444 break;
2445 case FAT_CIGAM:
2446 case MH_MAGIC: case MH_MAGIC_64:
2447 case MH_CIGAM: case MH_CIGAM_64:
2448 folder.Save(name, true, flag, fun([&](std::streambuf &save) {
2449 Slots slots;
2450 Sign(header.bytes, size, data, hash, save, identifier, "", "", key, slots, length, percent);
2451 }));
2452 return;
2453 }
2454
2455 folder.Save(name, false, flag, fun([&](std::streambuf &save) {
2456 HashProxy proxy(hash, save);
2457 put(proxy, header.bytes, size);
2458 copy(data, proxy, length - size, percent);
2459 }));
2460 }));
2461 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2462 if (exclude(name))
2463 return;
2464
2465 links[name] = read();
2466 }));
2467
2468 auto plist(plist_new_dict());
2469 _scope({ plist_free(plist); });
2470
2471 for (const auto &version : versions) {
2472 auto files(plist_new_dict());
2473 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
2474
2475 for (const auto &rule : version.second)
2476 rule.Compile();
2477
2478 bool old(&version.second == &rules1);
2479
2480 for (const auto &hash : local)
2481 for (const auto &rule : version.second)
2482 if (rule(hash.first)) {
2483 if (!old && mac && excludes.find(hash.first) != excludes.end());
2484 else if (old && rule.mode_ == NoMode)
2485 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
2486 else if (rule.mode_ != OmitMode) {
2487 auto entry(plist_new_dict());
2488 plist_dict_set_item(entry, "hash", plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
2489 if (!old)
2490 plist_dict_set_item(entry, "hash2", plist_new_data(reinterpret_cast<const char *>(hash.second.sha256_), sizeof(hash.second.sha256_)));
2491 if (rule.mode_ == OptionalMode)
2492 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2493 plist_dict_set_item(files, hash.first.c_str(), entry);
2494 }
2495
2496 break;
2497 }
2498
2499 for (const auto &link : links)
2500 for (const auto &rule : version.second)
2501 if (rule(link.first)) {
2502 if (rule.mode_ != OmitMode) {
2503 auto entry(plist_new_dict());
2504 plist_dict_set_item(entry, "symlink", plist_new_string(link.second.c_str()));
2505 if (rule.mode_ == OptionalMode)
2506 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2507 plist_dict_set_item(files, link.first.c_str(), entry);
2508 }
2509
2510 break;
2511 }
2512
2513 if (!old && mac)
2514 for (const auto &bundle : bundles) {
2515 auto entry(plist_new_dict());
2516 plist_dict_set_item(entry, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle.second.hash.sha256_), sizeof(bundle.second.hash.sha256_)));
2517 plist_dict_set_item(entry, "requirement", plist_new_string("anchor apple generic"));
2518 plist_dict_set_item(files, bundle.first.c_str(), entry);
2519 }
2520 }
2521
2522 for (const auto &version : versions) {
2523 auto rules(plist_new_dict());
2524 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
2525
2526 std::multiset<const Rule *, RuleCode> ordered;
2527 for (const auto &rule : version.second)
2528 ordered.insert(&rule);
2529
2530 for (const auto &rule : ordered)
2531 if (rule->weight_ == 1 && rule->mode_ == NoMode)
2532 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
2533 else {
2534 auto entry(plist_new_dict());
2535 plist_dict_set_item(rules, rule->code_.c_str(), entry);
2536
2537 switch (rule->mode_) {
2538 case NoMode:
2539 break;
2540 case OmitMode:
2541 plist_dict_set_item(entry, "omit", plist_new_bool(true));
2542 break;
2543 case OptionalMode:
2544 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2545 break;
2546 case NestedMode:
2547 plist_dict_set_item(entry, "nested", plist_new_bool(true));
2548 break;
2549 case TopMode:
2550 plist_dict_set_item(entry, "top", plist_new_bool(true));
2551 break;
2552 }
2553
2554 if (rule->weight_ >= 10000)
2555 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
2556 else if (rule->weight_ != 1)
2557 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
2558 }
2559 }
2560
2561 folder.Save(signature, true, NULL, fun([&](std::streambuf &save) {
2562 HashProxy proxy(local[signature], save);
2563 char *xml(NULL);
2564 uint32_t size;
2565 plist_to_xml(plist, &xml, &size);
2566 _scope({ free(xml); });
2567 put(proxy, xml, size);
2568 }));
2569
2570 Bundle bundle;
2571 bundle.path = executable;
2572
2573 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2574 progress(root + executable);
2575 folder.Save(executable, true, flag, fun([&](std::streambuf &save) {
2576 Slots slots;
2577 slots[1] = local.at(info);
2578 slots[3] = local.at(signature);
2579 bundle.hash = Sign(NULL, 0, buffer, local[executable], save, identifier, entitlements, requirements, key, slots, length, percent);
2580 }));
2581 }));
2582
2583 for (const auto &entry : local)
2584 remote[root + entry.first] = entry.second;
2585
2586 return bundle;
2587 }
2588
2589 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) {
2590 std::map<std::string, Hash> local;
2591 return Sign(root, folder, key, local, requirements, alter, progress, percent);
2592 }
2593 #endif
2594
2595 #endif
2596 }
2597
2598 #ifndef LDID_NOTOOLS
2599 int main(int argc, char *argv[]) {
2600 #ifndef LDID_NOSMIME
2601 OpenSSL_add_all_algorithms();
2602 #endif
2603
2604 union {
2605 uint16_t word;
2606 uint8_t byte[2];
2607 } endian = {1};
2608
2609 little_ = endian.byte[0];
2610
2611 bool flag_r(false);
2612 bool flag_e(false);
2613 bool flag_q(false);
2614
2615 #ifndef LDID_NOFLAGT
2616 bool flag_T(false);
2617 #endif
2618
2619 bool flag_S(false);
2620 bool flag_s(false);
2621
2622 bool flag_D(false);
2623
2624 bool flag_A(false);
2625 bool flag_a(false);
2626
2627 bool flag_u(false);
2628
2629 uint32_t flag_CPUType(_not(uint32_t));
2630 uint32_t flag_CPUSubtype(_not(uint32_t));
2631
2632 const char *flag_I(NULL);
2633
2634 #ifndef LDID_NOFLAGT
2635 bool timeh(false);
2636 uint32_t timev(0);
2637 #endif
2638
2639 Map entitlements;
2640 Map requirements;
2641 Map key;
2642 ldid::Slots slots;
2643
2644 std::vector<std::string> files;
2645
2646 if (argc == 1) {
2647 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
2648 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
2649 fprintf(stderr, " %s -S cat\n", argv[0]);
2650 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
2651 exit(0);
2652 }
2653
2654 for (int argi(1); argi != argc; ++argi)
2655 if (argv[argi][0] != '-')
2656 files.push_back(argv[argi]);
2657 else switch (argv[argi][1]) {
2658 case 'r':
2659 _assert(!flag_s);
2660 _assert(!flag_S);
2661 flag_r = true;
2662 break;
2663
2664 case 'e': flag_e = true; break;
2665
2666 case 'E': {
2667 const char *string = argv[argi] + 2;
2668 const char *colon = strchr(string, ':');
2669 _assert(colon != NULL);
2670 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
2671 char *arge;
2672 unsigned number(strtoul(string, &arge, 0));
2673 _assert(arge == colon);
2674 auto &slot(slots[number]);
2675 for (Algorithm *algorithm : GetAlgorithms())
2676 (*algorithm)(slot, file.data(), file.size());
2677 } break;
2678
2679 case 'q': flag_q = true; break;
2680
2681 case 'Q': {
2682 const char *xml = argv[argi] + 2;
2683 requirements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2684 } break;
2685
2686 case 'D': flag_D = true; break;
2687
2688 case 'a': flag_a = true; break;
2689
2690 case 'A':
2691 _assert(!flag_A);
2692 flag_A = true;
2693 if (argv[argi][2] != '\0') {
2694 const char *cpu = argv[argi] + 2;
2695 const char *colon = strchr(cpu, ':');
2696 _assert(colon != NULL);
2697 char *arge;
2698 flag_CPUType = strtoul(cpu, &arge, 0);
2699 _assert(arge == colon);
2700 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2701 _assert(arge == argv[argi] + strlen(argv[argi]));
2702 }
2703 break;
2704
2705 case 's':
2706 _assert(!flag_r);
2707 _assert(!flag_S);
2708 flag_s = true;
2709 break;
2710
2711 case 'S':
2712 _assert(!flag_r);
2713 _assert(!flag_s);
2714 flag_S = true;
2715 if (argv[argi][2] != '\0') {
2716 const char *xml = argv[argi] + 2;
2717 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2718 }
2719 break;
2720
2721 case 'K':
2722 if (argv[argi][2] != '\0')
2723 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
2724 break;
2725
2726 #ifndef LDID_NOFLAGT
2727 case 'T': {
2728 flag_T = true;
2729 if (argv[argi][2] == '-')
2730 timeh = true;
2731 else {
2732 char *arge;
2733 timev = strtoul(argv[argi] + 2, &arge, 0);
2734 _assert(arge == argv[argi] + strlen(argv[argi]));
2735 }
2736 } break;
2737 #endif
2738
2739 case 'u': {
2740 flag_u = true;
2741 } break;
2742
2743 case 'I': {
2744 flag_I = argv[argi] + 2;
2745 } break;
2746
2747 default:
2748 goto usage;
2749 break;
2750 }
2751
2752 _assert(flag_S || key.empty());
2753 _assert(flag_S || flag_I == NULL);
2754
2755 if (files.empty()) usage: {
2756 exit(0);
2757 }
2758
2759 size_t filei(0), filee(0);
2760 _foreach (file, files) try {
2761 std::string path(file);
2762
2763 struct stat info;
2764 _syscall(stat(path.c_str(), &info));
2765
2766 if (S_ISDIR(info.st_mode)) {
2767 #ifndef LDID_NOPLIST
2768 _assert(!flag_r);
2769 ldid::DiskFolder folder(path);
2770 path += "/" + Sign("", folder, key, requirements, ldid::fun([&](const std::string &, const std::string &) -> std::string { return entitlements; })
2771 , ldid::fun([&](const std::string &) {}), ldid::fun(dummy)
2772 ).path;
2773 #else
2774 _assert(false);
2775 #endif
2776 } else if (flag_S || flag_r) {
2777 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
2778
2779 std::filebuf output;
2780 Split split(path);
2781 auto temp(Temporary(output, split));
2782
2783 if (flag_r)
2784 ldid::Unsign(input.data(), input.size(), output, ldid::fun(dummy));
2785 else {
2786 std::string identifier(flag_I ?: split.base.c_str());
2787 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, requirements, key, slots, ldid::fun(dummy));
2788 }
2789
2790 Commit(path, temp);
2791 }
2792
2793 bool modify(false);
2794 #ifndef LDID_NOFLAGT
2795 if (flag_T)
2796 modify = true;
2797 #endif
2798 if (flag_s)
2799 modify = true;
2800
2801 Map mapping(path, modify);
2802 FatHeader fat_header(mapping.data(), mapping.size());
2803
2804 _foreach (mach_header, fat_header.GetMachHeaders()) {
2805 struct linkedit_data_command *signature(NULL);
2806 struct encryption_info_command *encryption(NULL);
2807
2808 if (flag_A) {
2809 if (mach_header.GetCPUType() != flag_CPUType)
2810 continue;
2811 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2812 continue;
2813 }
2814
2815 if (flag_a)
2816 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2817
2818 _foreach (load_command, mach_header.GetLoadCommands()) {
2819 uint32_t cmd(mach_header.Swap(load_command->cmd));
2820
2821 if (false);
2822 else if (cmd == LC_CODE_SIGNATURE)
2823 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
2824 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
2825 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
2826 else if (cmd == LC_LOAD_DYLIB) {
2827 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2828 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
2829
2830 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2831 if (flag_u) {
2832 Version version;
2833 version.value = mach_header.Swap(dylib_command->dylib.current_version);
2834 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
2835 }
2836 }
2837 }
2838 #ifndef LDID_NOFLAGT
2839 else if (cmd == LC_ID_DYLIB) {
2840 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2841
2842 if (flag_T) {
2843 uint32_t timed;
2844
2845 if (!timeh)
2846 timed = timev;
2847 else {
2848 dylib_command->dylib.timestamp = 0;
2849 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2850 }
2851
2852 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2853 }
2854 }
2855 #endif
2856 }
2857
2858 if (flag_D) {
2859 _assert(encryption != NULL);
2860 encryption->cryptid = mach_header.Swap(0);
2861 }
2862
2863 if (flag_e) {
2864 _assert(signature != NULL);
2865
2866 uint32_t data = mach_header.Swap(signature->dataoff);
2867
2868 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2869 uint8_t *blob = top + data;
2870 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2871
2872 for (size_t index(0); index != Swap(super->count); ++index)
2873 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2874 uint32_t begin = Swap(super->index[index].offset);
2875 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
2876 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
2877 }
2878 }
2879
2880 if (flag_q) {
2881 _assert(signature != NULL);
2882
2883 uint32_t data = mach_header.Swap(signature->dataoff);
2884
2885 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2886 uint8_t *blob = top + data;
2887 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2888
2889 for (size_t index(0); index != Swap(super->count); ++index)
2890 if (Swap(super->index[index].type) == CSSLOT_REQUIREMENTS) {
2891 uint32_t begin = Swap(super->index[index].offset);
2892 struct Blob *requirement = reinterpret_cast<struct Blob *>(blob + begin);
2893 fwrite(requirement, 1, Swap(requirement->length), stdout);
2894 }
2895 }
2896
2897 if (flag_s) {
2898 _assert(signature != NULL);
2899
2900 uint32_t data = mach_header.Swap(signature->dataoff);
2901
2902 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2903 uint8_t *blob = top + data;
2904 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2905
2906 for (size_t index(0); index != Swap(super->count); ++index)
2907 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2908 uint32_t begin = Swap(super->index[index].offset);
2909 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob));
2910
2911 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
2912 uint32_t pages = Swap(directory->nCodeSlots);
2913
2914 if (pages != 1)
2915 for (size_t i = 0; i != pages - 1; ++i)
2916 LDID_SHA1(top + PageSize_ * i, PageSize_, hashes[i]);
2917 if (pages != 0)
2918 LDID_SHA1(top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1, hashes[pages - 1]);
2919 }
2920 }
2921 }
2922
2923 ++filei;
2924 } catch (const char *) {
2925 ++filee;
2926 ++filei;
2927 }
2928
2929 return filee;
2930 }
2931 #endif