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