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