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