]> git.saurik.com Git - ldid.git/blob - ldid.cpp
Provide a way to maintain file permissions in IPA.
[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 #define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
55 #define LDID_SHA1 CC_SHA1
56 #define LDID_SHA1_CTX CC_SHA1_CTX
57 #define LDID_SHA1_Init CC_SHA1_Init
58 #define LDID_SHA1_Update CC_SHA1_Update
59 #define LDID_SHA1_Final CC_SHA1_Final
60 #else
61 #include <openssl/sha.h>
62 #define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
63 #define LDID_SHA1 SHA1
64 #define LDID_SHA1_CTX SHA_CTX
65 #define LDID_SHA1_Init SHA1_Init
66 #define LDID_SHA1_Update SHA1_Update
67 #define LDID_SHA1_Final SHA1_Final
68 #endif
69
70 #ifndef LDID_NOPLIST
71 #include <plist/plist.h>
72 #endif
73
74 #include "ldid.hpp"
75
76 #define _assert___(line) \
77 #line
78 #define _assert__(line) \
79 _assert___(line)
80
81 #ifdef __EXCEPTIONS
82 #define _assert_(expr, format, ...) \
83 do if (!(expr)) { \
84 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
85 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
86 } while (false)
87 #else
88 // XXX: this is not acceptable
89 #define _assert_(expr, format, ...) \
90 do if (!(expr)) { \
91 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
92 exit(-1); \
93 } while (false)
94 #endif
95
96 #define _assert(expr) \
97 _assert_(expr, "%s", #expr)
98
99 #define _syscall(expr, ...) [&] { for (;;) { \
100 auto _value(expr); \
101 if ((long) _value != -1) \
102 return _value; \
103 int error(errno); \
104 if (error == EINTR) \
105 continue; \
106 /* XXX: EINTR is included in this list to fix g++ */ \
107 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
108 if (error == success) \
109 return (decltype(expr)) -success; \
110 _assert_(false, "errno=%u", error); \
111 } }()
112
113 #define _trace() \
114 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
115
116 #define _not(type) \
117 ((type) ~ (type) 0)
118
119 #define _packed \
120 __attribute__((packed))
121
122 template <typename Type_>
123 struct Iterator_ {
124 typedef typename Type_::const_iterator Result;
125 };
126
127 #define _foreach(item, list) \
128 for (bool _stop(true); _stop; ) \
129 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
130 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
131 for (bool _suck(true); _suck; _suck = false) \
132 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
133
134 class _Scope {
135 };
136
137 template <typename Function_>
138 class Scope :
139 public _Scope
140 {
141 private:
142 Function_ function_;
143
144 public:
145 Scope(const Function_ &function) :
146 function_(function)
147 {
148 }
149
150 ~Scope() {
151 function_();
152 }
153 };
154
155 template <typename Function_>
156 Scope<Function_> _scope(const Function_ &function) {
157 return Scope<Function_>(function);
158 }
159
160 #define _scope__(counter, function) \
161 __attribute__((__unused__)) \
162 const _Scope &_scope ## counter(_scope([&]function))
163 #define _scope_(counter, function) \
164 _scope__(counter, function)
165 #define _scope(function) \
166 _scope_(__COUNTER__, function)
167
168 #define CPU_ARCH_MASK uint32_t(0xff000000)
169 #define CPU_ARCH_ABI64 uint32_t(0x01000000)
170
171 #define CPU_TYPE_ANY uint32_t(-1)
172 #define CPU_TYPE_VAX uint32_t( 1)
173 #define CPU_TYPE_MC680x0 uint32_t( 6)
174 #define CPU_TYPE_X86 uint32_t( 7)
175 #define CPU_TYPE_MC98000 uint32_t(10)
176 #define CPU_TYPE_HPPA uint32_t(11)
177 #define CPU_TYPE_ARM uint32_t(12)
178 #define CPU_TYPE_MC88000 uint32_t(13)
179 #define CPU_TYPE_SPARC uint32_t(14)
180 #define CPU_TYPE_I860 uint32_t(15)
181 #define CPU_TYPE_POWERPC uint32_t(18)
182
183 #define CPU_TYPE_I386 CPU_TYPE_X86
184
185 #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
186 #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
187 #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
188
189 struct fat_header {
190 uint32_t magic;
191 uint32_t nfat_arch;
192 } _packed;
193
194 #define FAT_MAGIC 0xcafebabe
195 #define FAT_CIGAM 0xbebafeca
196
197 struct fat_arch {
198 uint32_t cputype;
199 uint32_t cpusubtype;
200 uint32_t offset;
201 uint32_t size;
202 uint32_t align;
203 } _packed;
204
205 struct mach_header {
206 uint32_t magic;
207 uint32_t cputype;
208 uint32_t cpusubtype;
209 uint32_t filetype;
210 uint32_t ncmds;
211 uint32_t sizeofcmds;
212 uint32_t flags;
213 } _packed;
214
215 #define MH_MAGIC 0xfeedface
216 #define MH_CIGAM 0xcefaedfe
217
218 #define MH_MAGIC_64 0xfeedfacf
219 #define MH_CIGAM_64 0xcffaedfe
220
221 #define MH_DYLDLINK 0x4
222
223 #define MH_OBJECT 0x1
224 #define MH_EXECUTE 0x2
225 #define MH_DYLIB 0x6
226 #define MH_BUNDLE 0x8
227 #define MH_DYLIB_STUB 0x9
228
229 struct load_command {
230 uint32_t cmd;
231 uint32_t cmdsize;
232 } _packed;
233
234 #define LC_REQ_DYLD uint32_t(0x80000000)
235
236 #define LC_SEGMENT uint32_t(0x01)
237 #define LC_SYMTAB uint32_t(0x02)
238 #define LC_DYSYMTAB uint32_t(0x0b)
239 #define LC_LOAD_DYLIB uint32_t(0x0c)
240 #define LC_ID_DYLIB uint32_t(0x0d)
241 #define LC_SEGMENT_64 uint32_t(0x19)
242 #define LC_UUID uint32_t(0x1b)
243 #define LC_CODE_SIGNATURE uint32_t(0x1d)
244 #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
245 #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
246 #define LC_ENCRYPTION_INFO uint32_t(0x21)
247 #define LC_DYLD_INFO uint32_t(0x22)
248 #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
249 #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
250
251 union Version {
252 struct {
253 uint8_t patch;
254 uint8_t minor;
255 uint16_t major;
256 } _packed;
257
258 uint32_t value;
259 };
260
261 struct dylib {
262 uint32_t name;
263 uint32_t timestamp;
264 uint32_t current_version;
265 uint32_t compatibility_version;
266 } _packed;
267
268 struct dylib_command {
269 uint32_t cmd;
270 uint32_t cmdsize;
271 struct dylib dylib;
272 } _packed;
273
274 struct uuid_command {
275 uint32_t cmd;
276 uint32_t cmdsize;
277 uint8_t uuid[16];
278 } _packed;
279
280 struct symtab_command {
281 uint32_t cmd;
282 uint32_t cmdsize;
283 uint32_t symoff;
284 uint32_t nsyms;
285 uint32_t stroff;
286 uint32_t strsize;
287 } _packed;
288
289 struct dyld_info_command {
290 uint32_t cmd;
291 uint32_t cmdsize;
292 uint32_t rebase_off;
293 uint32_t rebase_size;
294 uint32_t bind_off;
295 uint32_t bind_size;
296 uint32_t weak_bind_off;
297 uint32_t weak_bind_size;
298 uint32_t lazy_bind_off;
299 uint32_t lazy_bind_size;
300 uint32_t export_off;
301 uint32_t export_size;
302 } _packed;
303
304 struct dysymtab_command {
305 uint32_t cmd;
306 uint32_t cmdsize;
307 uint32_t ilocalsym;
308 uint32_t nlocalsym;
309 uint32_t iextdefsym;
310 uint32_t nextdefsym;
311 uint32_t iundefsym;
312 uint32_t nundefsym;
313 uint32_t tocoff;
314 uint32_t ntoc;
315 uint32_t modtaboff;
316 uint32_t nmodtab;
317 uint32_t extrefsymoff;
318 uint32_t nextrefsyms;
319 uint32_t indirectsymoff;
320 uint32_t nindirectsyms;
321 uint32_t extreloff;
322 uint32_t nextrel;
323 uint32_t locreloff;
324 uint32_t nlocrel;
325 } _packed;
326
327 struct dylib_table_of_contents {
328 uint32_t symbol_index;
329 uint32_t module_index;
330 } _packed;
331
332 struct dylib_module {
333 uint32_t module_name;
334 uint32_t iextdefsym;
335 uint32_t nextdefsym;
336 uint32_t irefsym;
337 uint32_t nrefsym;
338 uint32_t ilocalsym;
339 uint32_t nlocalsym;
340 uint32_t iextrel;
341 uint32_t nextrel;
342 uint32_t iinit_iterm;
343 uint32_t ninit_nterm;
344 uint32_t objc_module_info_addr;
345 uint32_t objc_module_info_size;
346 } _packed;
347
348 struct dylib_reference {
349 uint32_t isym:24;
350 uint32_t flags:8;
351 } _packed;
352
353 struct relocation_info {
354 int32_t r_address;
355 uint32_t r_symbolnum:24;
356 uint32_t r_pcrel:1;
357 uint32_t r_length:2;
358 uint32_t r_extern:1;
359 uint32_t r_type:4;
360 } _packed;
361
362 struct nlist {
363 union {
364 char *n_name;
365 int32_t n_strx;
366 } n_un;
367
368 uint8_t n_type;
369 uint8_t n_sect;
370 uint8_t n_desc;
371 uint32_t n_value;
372 } _packed;
373
374 struct segment_command {
375 uint32_t cmd;
376 uint32_t cmdsize;
377 char segname[16];
378 uint32_t vmaddr;
379 uint32_t vmsize;
380 uint32_t fileoff;
381 uint32_t filesize;
382 uint32_t maxprot;
383 uint32_t initprot;
384 uint32_t nsects;
385 uint32_t flags;
386 } _packed;
387
388 struct segment_command_64 {
389 uint32_t cmd;
390 uint32_t cmdsize;
391 char segname[16];
392 uint64_t vmaddr;
393 uint64_t vmsize;
394 uint64_t fileoff;
395 uint64_t filesize;
396 uint32_t maxprot;
397 uint32_t initprot;
398 uint32_t nsects;
399 uint32_t flags;
400 } _packed;
401
402 struct section {
403 char sectname[16];
404 char segname[16];
405 uint32_t addr;
406 uint32_t size;
407 uint32_t offset;
408 uint32_t align;
409 uint32_t reloff;
410 uint32_t nreloc;
411 uint32_t flags;
412 uint32_t reserved1;
413 uint32_t reserved2;
414 } _packed;
415
416 struct section_64 {
417 char sectname[16];
418 char segname[16];
419 uint64_t addr;
420 uint64_t size;
421 uint32_t offset;
422 uint32_t align;
423 uint32_t reloff;
424 uint32_t nreloc;
425 uint32_t flags;
426 uint32_t reserved1;
427 uint32_t reserved2;
428 uint32_t reserved3;
429 } _packed;
430
431 struct linkedit_data_command {
432 uint32_t cmd;
433 uint32_t cmdsize;
434 uint32_t dataoff;
435 uint32_t datasize;
436 } _packed;
437
438 struct encryption_info_command {
439 uint32_t cmd;
440 uint32_t cmdsize;
441 uint32_t cryptoff;
442 uint32_t cryptsize;
443 uint32_t cryptid;
444 } _packed;
445
446 #define BIND_OPCODE_MASK 0xf0
447 #define BIND_IMMEDIATE_MASK 0x0f
448 #define BIND_OPCODE_DONE 0x00
449 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
450 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
451 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
452 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
453 #define BIND_OPCODE_SET_TYPE_IMM 0x50
454 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
455 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
456 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
457 #define BIND_OPCODE_DO_BIND 0x90
458 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
459 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
460 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
461
462 inline void get(std::streambuf &stream, void *data, size_t size) {
463 _assert(stream.sgetn(static_cast<char *>(data), size) == size);
464 }
465
466 inline void put(std::streambuf &stream, const void *data, size_t size) {
467 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
468 }
469
470 inline void pad(std::streambuf &stream, size_t size) {
471 char padding[size];
472 memset(padding, 0, size);
473 put(stream, padding, size);
474 }
475
476 template <typename Type_>
477 Type_ Align(Type_ value, size_t align) {
478 value += align - 1;
479 value /= align;
480 value *= align;
481 return value;
482 }
483
484 static const uint8_t PageShift_(0x0c);
485 static const uint32_t PageSize_(1 << PageShift_);
486
487 static inline uint16_t Swap_(uint16_t value) {
488 return
489 ((value >> 8) & 0x00ff) |
490 ((value << 8) & 0xff00);
491 }
492
493 static inline uint32_t Swap_(uint32_t value) {
494 value = ((value >> 8) & 0x00ff00ff) |
495 ((value << 8) & 0xff00ff00);
496 value = ((value >> 16) & 0x0000ffff) |
497 ((value << 16) & 0xffff0000);
498 return value;
499 }
500
501 static inline uint64_t Swap_(uint64_t value) {
502 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
503 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
504 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
505 return value;
506 }
507
508 static inline int16_t Swap_(int16_t value) {
509 return Swap_(static_cast<uint16_t>(value));
510 }
511
512 static inline int32_t Swap_(int32_t value) {
513 return Swap_(static_cast<uint32_t>(value));
514 }
515
516 static inline int64_t Swap_(int64_t value) {
517 return Swap_(static_cast<uint64_t>(value));
518 }
519
520 static bool little_(true);
521
522 static inline uint16_t Swap(uint16_t value) {
523 return little_ ? Swap_(value) : value;
524 }
525
526 static inline uint32_t Swap(uint32_t value) {
527 return little_ ? Swap_(value) : value;
528 }
529
530 static inline uint64_t Swap(uint64_t value) {
531 return little_ ? Swap_(value) : value;
532 }
533
534 static inline int16_t Swap(int16_t value) {
535 return Swap(static_cast<uint16_t>(value));
536 }
537
538 static inline int32_t Swap(int32_t value) {
539 return Swap(static_cast<uint32_t>(value));
540 }
541
542 static inline int64_t Swap(int64_t value) {
543 return Swap(static_cast<uint64_t>(value));
544 }
545
546 class Swapped {
547 protected:
548 bool swapped_;
549
550 Swapped() :
551 swapped_(false)
552 {
553 }
554
555 public:
556 Swapped(bool swapped) :
557 swapped_(swapped)
558 {
559 }
560
561 template <typename Type_>
562 Type_ Swap(Type_ value) const {
563 return swapped_ ? Swap_(value) : value;
564 }
565 };
566
567 class Data :
568 public Swapped
569 {
570 private:
571 void *base_;
572 size_t size_;
573
574 public:
575 Data(void *base, size_t size) :
576 base_(base),
577 size_(size)
578 {
579 }
580
581 void *GetBase() const {
582 return base_;
583 }
584
585 size_t GetSize() const {
586 return size_;
587 }
588 };
589
590 class MachHeader :
591 public Data
592 {
593 private:
594 bool bits64_;
595
596 struct mach_header *mach_header_;
597 struct load_command *load_command_;
598
599 public:
600 MachHeader(void *base, size_t size) :
601 Data(base, size)
602 {
603 mach_header_ = (mach_header *) base;
604
605 switch (Swap(mach_header_->magic)) {
606 case MH_CIGAM:
607 swapped_ = !swapped_;
608 case MH_MAGIC:
609 bits64_ = false;
610 break;
611
612 case MH_CIGAM_64:
613 swapped_ = !swapped_;
614 case MH_MAGIC_64:
615 bits64_ = true;
616 break;
617
618 default:
619 _assert(false);
620 }
621
622 void *post = mach_header_ + 1;
623 if (bits64_)
624 post = (uint32_t *) post + 1;
625 load_command_ = (struct load_command *) post;
626
627 _assert(
628 Swap(mach_header_->filetype) == MH_EXECUTE ||
629 Swap(mach_header_->filetype) == MH_DYLIB ||
630 Swap(mach_header_->filetype) == MH_BUNDLE
631 );
632 }
633
634 bool Bits64() const {
635 return bits64_;
636 }
637
638 struct mach_header *operator ->() const {
639 return mach_header_;
640 }
641
642 operator struct mach_header *() const {
643 return mach_header_;
644 }
645
646 uint32_t GetCPUType() const {
647 return Swap(mach_header_->cputype);
648 }
649
650 uint32_t GetCPUSubtype() const {
651 return Swap(mach_header_->cpusubtype) & 0xff;
652 }
653
654 struct load_command *GetLoadCommand() const {
655 return load_command_;
656 }
657
658 std::vector<struct load_command *> GetLoadCommands() const {
659 std::vector<struct load_command *> load_commands;
660
661 struct load_command *load_command = load_command_;
662 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
663 load_commands.push_back(load_command);
664 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
665 }
666
667 return load_commands;
668 }
669
670 void ForSection(const ldid::Functor<void (const char *, const char *, void *, size_t)> &code) const {
671 _foreach (load_command, GetLoadCommands())
672 switch (Swap(load_command->cmd)) {
673 case LC_SEGMENT: {
674 auto segment(reinterpret_cast<struct segment_command *>(load_command));
675 code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize);
676 auto section(reinterpret_cast<struct section *>(segment + 1));
677 for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section)
678 code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size);
679 } break;
680
681 case LC_SEGMENT_64: {
682 auto segment(reinterpret_cast<struct segment_command_64 *>(load_command));
683 code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize);
684 auto section(reinterpret_cast<struct section_64 *>(segment + 1));
685 for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section)
686 code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size);
687 } break;
688 }
689 }
690
691 template <typename Target_>
692 Target_ *GetOffset(uint32_t offset) const {
693 return reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_);
694 }
695 };
696
697 class FatMachHeader :
698 public MachHeader
699 {
700 private:
701 fat_arch *fat_arch_;
702
703 public:
704 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
705 MachHeader(base, size),
706 fat_arch_(fat_arch)
707 {
708 }
709
710 fat_arch *GetFatArch() const {
711 return fat_arch_;
712 }
713 };
714
715 class FatHeader :
716 public Data
717 {
718 private:
719 fat_header *fat_header_;
720 std::vector<FatMachHeader> mach_headers_;
721
722 public:
723 FatHeader(void *base, size_t size) :
724 Data(base, size)
725 {
726 fat_header_ = reinterpret_cast<struct fat_header *>(base);
727
728 if (Swap(fat_header_->magic) == FAT_CIGAM) {
729 swapped_ = !swapped_;
730 goto fat;
731 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
732 fat_header_ = NULL;
733 mach_headers_.push_back(FatMachHeader(base, size, NULL));
734 } else fat: {
735 size_t fat_narch = Swap(fat_header_->nfat_arch);
736 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
737 size_t arch;
738 for (arch = 0; arch != fat_narch; ++arch) {
739 uint32_t arch_offset = Swap(fat_arch->offset);
740 uint32_t arch_size = Swap(fat_arch->size);
741 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
742 ++fat_arch;
743 }
744 }
745 }
746
747 std::vector<FatMachHeader> &GetMachHeaders() {
748 return mach_headers_;
749 }
750
751 bool IsFat() const {
752 return fat_header_ != NULL;
753 }
754
755 struct fat_header *operator ->() const {
756 return fat_header_;
757 }
758
759 operator struct fat_header *() const {
760 return fat_header_;
761 }
762 };
763
764 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
765 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
766 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
767 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
768 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
769 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
770 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
771 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
772
773 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
774 #define CSSLOT_INFOSLOT uint32_t(0x00001)
775 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
776 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
777 #define CSSLOT_APPLICATION uint32_t(0x00004)
778 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
779
780 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
781
782 #define CS_HASHTYPE_SHA1 1
783
784 struct BlobIndex {
785 uint32_t type;
786 uint32_t offset;
787 } _packed;
788
789 struct Blob {
790 uint32_t magic;
791 uint32_t length;
792 } _packed;
793
794 struct SuperBlob {
795 struct Blob blob;
796 uint32_t count;
797 struct BlobIndex index[];
798 } _packed;
799
800 struct CodeDirectory {
801 uint32_t version;
802 uint32_t flags;
803 uint32_t hashOffset;
804 uint32_t identOffset;
805 uint32_t nSpecialSlots;
806 uint32_t nCodeSlots;
807 uint32_t codeLimit;
808 uint8_t hashSize;
809 uint8_t hashType;
810 uint8_t spare1;
811 uint8_t pageSize;
812 uint32_t spare2;
813 uint32_t scatterOffset;
814 uint32_t teamIDOffset;
815 uint32_t spare3;
816 uint64_t codeLimit64;
817 } _packed;
818
819 #ifndef LDID_NOFLAGT
820 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
821 #endif
822
823 static void sha1(uint8_t *hash, const void *data, size_t size) {
824 LDID_SHA1(static_cast<const uint8_t *>(data), size, hash);
825 }
826
827 static void sha1(std::vector<char> &hash, const void *data, size_t size) {
828 hash.resize(LDID_SHA1_DIGEST_LENGTH);
829 sha1(reinterpret_cast<uint8_t *>(hash.data()), data, size);
830 }
831
832 struct CodesignAllocation {
833 FatMachHeader mach_header_;
834 uint32_t offset_;
835 uint32_t size_;
836 uint32_t limit_;
837 uint32_t alloc_;
838 uint32_t align_;
839
840 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
841 mach_header_(mach_header),
842 offset_(offset),
843 size_(size),
844 limit_(limit),
845 alloc_(alloc),
846 align_(align)
847 {
848 }
849 };
850
851 #ifndef LDID_NOTOOLS
852 class File {
853 private:
854 int file_;
855
856 public:
857 File() :
858 file_(-1)
859 {
860 }
861
862 ~File() {
863 if (file_ != -1)
864 _syscall(close(file_));
865 }
866
867 void open(const char *path, int flags) {
868 _assert(file_ == -1);
869 file_ = _syscall(::open(path, flags));
870 }
871
872 int file() const {
873 return file_;
874 }
875 };
876
877 class Map {
878 private:
879 File file_;
880 void *data_;
881 size_t size_;
882
883 void clear() {
884 if (data_ == NULL)
885 return;
886 _syscall(munmap(data_, size_));
887 data_ = NULL;
888 size_ = 0;
889 }
890
891 public:
892 Map() :
893 data_(NULL),
894 size_(0)
895 {
896 }
897
898 Map(const std::string &path, int oflag, int pflag, int mflag) :
899 Map()
900 {
901 open(path, oflag, pflag, mflag);
902 }
903
904 Map(const std::string &path, bool edit) :
905 Map()
906 {
907 open(path, edit);
908 }
909
910 ~Map() {
911 clear();
912 }
913
914 bool empty() const {
915 return data_ == NULL;
916 }
917
918 void open(const std::string &path, int oflag, int pflag, int mflag) {
919 clear();
920
921 file_.open(path.c_str(), oflag);
922 int file(file_.file());
923
924 struct stat stat;
925 _syscall(fstat(file, &stat));
926 size_ = stat.st_size;
927
928 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
929 }
930
931 void open(const std::string &path, bool edit) {
932 if (edit)
933 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
934 else
935 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
936 }
937
938 void *data() const {
939 return data_;
940 }
941
942 size_t size() const {
943 return size_;
944 }
945
946 operator std::string() const {
947 return std::string(static_cast<char *>(data_), size_);
948 }
949 };
950 #endif
951
952 namespace ldid {
953
954 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 *)> &save) {
955 FatHeader source(const_cast<void *>(idata), isize);
956
957 size_t offset(0);
958 if (source.IsFat())
959 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
960
961 std::vector<CodesignAllocation> allocations;
962 _foreach (mach_header, source.GetMachHeaders()) {
963 struct linkedit_data_command *signature(NULL);
964 struct symtab_command *symtab(NULL);
965
966 _foreach (load_command, mach_header.GetLoadCommands()) {
967 uint32_t cmd(mach_header.Swap(load_command->cmd));
968 if (false);
969 else if (cmd == LC_CODE_SIGNATURE)
970 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
971 else if (cmd == LC_SYMTAB)
972 symtab = reinterpret_cast<struct symtab_command *>(load_command);
973 }
974
975 size_t size;
976 if (signature == NULL)
977 size = mach_header.GetSize();
978 else {
979 size = mach_header.Swap(signature->dataoff);
980 _assert(size <= mach_header.GetSize());
981 }
982
983 if (symtab != NULL) {
984 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
985 _assert(end <= size);
986 _assert(end >= size - 0x10);
987 size = end;
988 }
989
990 size_t alloc(allocate(mach_header, size));
991
992 auto *fat_arch(mach_header.GetFatArch());
993 uint32_t align;
994
995 if (fat_arch != NULL)
996 align = source.Swap(fat_arch->align);
997 else switch (mach_header.GetCPUType()) {
998 case CPU_TYPE_POWERPC:
999 case CPU_TYPE_POWERPC64:
1000 case CPU_TYPE_X86:
1001 case CPU_TYPE_X86_64:
1002 align = 0xc;
1003 break;
1004 case CPU_TYPE_ARM:
1005 case CPU_TYPE_ARM64:
1006 align = 0xe;
1007 break;
1008 default:
1009 align = 0x0;
1010 break;
1011 }
1012
1013 offset = Align(offset, 1 << align);
1014
1015 uint32_t limit(size);
1016 if (alloc != 0)
1017 limit = Align(limit, 0x10);
1018
1019 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
1020 offset += size + alloc;
1021 offset = Align(offset, 0x10);
1022 }
1023
1024 size_t position(0);
1025
1026 if (source.IsFat()) {
1027 fat_header fat_header;
1028 fat_header.magic = Swap(FAT_MAGIC);
1029 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1030 put(output, &fat_header, sizeof(fat_header));
1031 position += sizeof(fat_header);
1032
1033 _foreach (allocation, allocations) {
1034 auto &mach_header(allocation.mach_header_);
1035
1036 fat_arch fat_arch;
1037 fat_arch.cputype = Swap(mach_header->cputype);
1038 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1039 fat_arch.offset = Swap(allocation.offset_);
1040 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1041 fat_arch.align = Swap(allocation.align_);
1042 put(output, &fat_arch, sizeof(fat_arch));
1043 position += sizeof(fat_arch);
1044 }
1045 }
1046
1047 _foreach (allocation, allocations) {
1048 auto &mach_header(allocation.mach_header_);
1049
1050 pad(output, allocation.offset_ - position);
1051 position = allocation.offset_;
1052
1053 std::vector<std::string> commands;
1054
1055 _foreach (load_command, mach_header.GetLoadCommands()) {
1056 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
1057
1058 switch (mach_header.Swap(load_command->cmd)) {
1059 case LC_CODE_SIGNATURE:
1060 continue;
1061 break;
1062
1063 case LC_SEGMENT: {
1064 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1065 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1066 break;
1067 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1068 segment_command->filesize = size;
1069 segment_command->vmsize = Align(size, 1 << allocation.align_);
1070 } break;
1071
1072 case LC_SEGMENT_64: {
1073 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1074 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1075 break;
1076 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1077 segment_command->filesize = size;
1078 segment_command->vmsize = Align(size, 1 << allocation.align_);
1079 } break;
1080 }
1081
1082 commands.push_back(copy);
1083 }
1084
1085 if (allocation.alloc_ != 0) {
1086 linkedit_data_command signature;
1087 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1088 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1089 signature.dataoff = mach_header.Swap(allocation.limit_);
1090 signature.datasize = mach_header.Swap(allocation.alloc_);
1091 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1092 }
1093
1094 size_t begin(position);
1095
1096 uint32_t after(0);
1097 _foreach(command, commands)
1098 after += command.size();
1099
1100 std::stringbuf altern;
1101
1102 struct mach_header header(*mach_header);
1103 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1104 header.sizeofcmds = mach_header.Swap(after);
1105 put(output, &header, sizeof(header));
1106 put(altern, &header, sizeof(header));
1107 position += sizeof(header);
1108
1109 if (mach_header.Bits64()) {
1110 auto pad(mach_header.Swap(uint32_t(0)));
1111 put(output, &pad, sizeof(pad));
1112 put(altern, &pad, sizeof(pad));
1113 position += sizeof(pad);
1114 }
1115
1116 _foreach(command, commands) {
1117 put(output, command.data(), command.size());
1118 put(altern, command.data(), command.size());
1119 position += command.size();
1120 }
1121
1122 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1123 if (before > after) {
1124 pad(output, before - after);
1125 pad(altern, before - after);
1126 position += before - after;
1127 }
1128
1129 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
1130
1131 std::string overlap(altern.str());
1132 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
1133
1134 put(output, top + (position - begin), allocation.size_ - (position - begin));
1135 position = begin + allocation.size_;
1136
1137 pad(output, allocation.limit_ - allocation.size_);
1138 position += allocation.limit_ - allocation.size_;
1139
1140 size_t saved(save(mach_header, output, allocation.limit_, overlap, top));
1141 if (allocation.alloc_ > saved)
1142 pad(output, allocation.alloc_ - saved);
1143 position += allocation.alloc_;
1144 }
1145 }
1146
1147 }
1148
1149 typedef std::map<uint32_t, std::string> Blobs;
1150
1151 static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1152 auto value(buffer.str());
1153 std::swap(blobs[slot], value);
1154 }
1155
1156 static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1157 auto value(buffer.str());
1158 Blob blob;
1159 blob.magic = Swap(magic);
1160 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1161 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1162 std::swap(blobs[slot], value);
1163 }
1164
1165 static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1166 size_t total(0);
1167 _foreach (blob, blobs)
1168 total += blob.second.size();
1169
1170 struct SuperBlob super;
1171 super.blob.magic = Swap(magic);
1172 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1173 super.count = Swap(uint32_t(blobs.size()));
1174 put(output, &super, sizeof(super));
1175
1176 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1177
1178 _foreach (blob, blobs) {
1179 BlobIndex index;
1180 index.type = Swap(blob.first);
1181 index.offset = Swap(uint32_t(offset));
1182 put(output, &index, sizeof(index));
1183 offset += blob.second.size();
1184 }
1185
1186 _foreach (blob, blobs)
1187 put(output, blob.second.data(), blob.second.size());
1188
1189 return offset;
1190 }
1191
1192 #ifndef LDID_NOSMIME
1193 class Buffer {
1194 private:
1195 BIO *bio_;
1196
1197 public:
1198 Buffer(BIO *bio) :
1199 bio_(bio)
1200 {
1201 _assert(bio_ != NULL);
1202 }
1203
1204 Buffer() :
1205 bio_(BIO_new(BIO_s_mem()))
1206 {
1207 }
1208
1209 Buffer(const char *data, size_t size) :
1210 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1211 {
1212 }
1213
1214 Buffer(const std::string &data) :
1215 Buffer(data.data(), data.size())
1216 {
1217 }
1218
1219 Buffer(PKCS7 *pkcs) :
1220 Buffer()
1221 {
1222 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1223 }
1224
1225 ~Buffer() {
1226 BIO_free_all(bio_);
1227 }
1228
1229 operator BIO *() const {
1230 return bio_;
1231 }
1232
1233 explicit operator std::string() const {
1234 char *data;
1235 auto size(BIO_get_mem_data(bio_, &data));
1236 return std::string(data, size);
1237 }
1238 };
1239
1240 class Stuff {
1241 private:
1242 PKCS12 *value_;
1243 EVP_PKEY *key_;
1244 X509 *cert_;
1245 STACK_OF(X509) *ca_;
1246
1247 public:
1248 Stuff(BIO *bio) :
1249 value_(d2i_PKCS12_bio(bio, NULL)),
1250 ca_(NULL)
1251 {
1252 _assert(value_ != NULL);
1253 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1254 _assert(key_ != NULL);
1255 _assert(cert_ != NULL);
1256 }
1257
1258 Stuff(const std::string &data) :
1259 Stuff(Buffer(data))
1260 {
1261 }
1262
1263 ~Stuff() {
1264 sk_X509_pop_free(ca_, X509_free);
1265 X509_free(cert_);
1266 EVP_PKEY_free(key_);
1267 PKCS12_free(value_);
1268 }
1269
1270 operator PKCS12 *() const {
1271 return value_;
1272 }
1273
1274 operator EVP_PKEY *() const {
1275 return key_;
1276 }
1277
1278 operator X509 *() const {
1279 return cert_;
1280 }
1281
1282 operator STACK_OF(X509) *() const {
1283 return ca_;
1284 }
1285 };
1286
1287 class Signature {
1288 private:
1289 PKCS7 *value_;
1290
1291 public:
1292 Signature(const Stuff &stuff, const Buffer &data) :
1293 value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
1294 {
1295 _assert(value_ != NULL);
1296 }
1297
1298 ~Signature() {
1299 PKCS7_free(value_);
1300 }
1301
1302 operator PKCS7 *() const {
1303 return value_;
1304 }
1305 };
1306 #endif
1307
1308 class NullBuffer :
1309 public std::streambuf
1310 {
1311 public:
1312 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1313 return size;
1314 }
1315
1316 virtual int_type overflow(int_type next) {
1317 return next;
1318 }
1319 };
1320
1321 class HashBuffer :
1322 public std::streambuf
1323 {
1324 private:
1325 std::vector<char> &hash_;
1326 LDID_SHA1_CTX context_;
1327
1328 public:
1329 HashBuffer(std::vector<char> &hash) :
1330 hash_(hash)
1331 {
1332 LDID_SHA1_Init(&context_);
1333 }
1334
1335 ~HashBuffer() {
1336 hash_.resize(LDID_SHA1_DIGEST_LENGTH);
1337 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.data()), &context_);
1338 }
1339
1340 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1341 LDID_SHA1_Update(&context_, data, size);
1342 return size;
1343 }
1344
1345 virtual int_type overflow(int_type next) {
1346 if (next == traits_type::eof())
1347 return sync();
1348 char value(next);
1349 xsputn(&value, 1);
1350 return next;
1351 }
1352 };
1353
1354 class HashProxy :
1355 public HashBuffer
1356 {
1357 private:
1358 std::streambuf &buffer_;
1359
1360 public:
1361 HashProxy(std::vector<char> &hash, std::streambuf &buffer) :
1362 HashBuffer(hash),
1363 buffer_(buffer)
1364 {
1365 }
1366
1367 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1368 _assert(HashBuffer::xsputn(data, size) == size);
1369 return buffer_.sputn(data, size);
1370 }
1371 };
1372
1373 #ifndef LDID_NOTOOLS
1374 static bool Starts(const std::string &lhs, const std::string &rhs) {
1375 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1376 }
1377
1378 class Split {
1379 public:
1380 std::string dir;
1381 std::string base;
1382
1383 Split(const std::string &path) {
1384 size_t slash(path.rfind('/'));
1385 if (slash == std::string::npos)
1386 base = path;
1387 else {
1388 dir = path.substr(0, slash + 1);
1389 base = path.substr(slash + 1);
1390 }
1391 }
1392 };
1393
1394 static void mkdir_p(const std::string &path) {
1395 if (path.empty())
1396 return;
1397 #ifdef __WIN32__
1398 if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
1399 return;
1400 #else
1401 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1402 return;
1403 #endif
1404 auto slash(path.rfind('/', path.size() - 1));
1405 if (slash == std::string::npos)
1406 return;
1407 mkdir_p(path.substr(0, slash));
1408 }
1409
1410 static std::string Temporary(std::filebuf &file, const Split &split) {
1411 std::string temp(split.dir + ".ldid." + split.base);
1412 mkdir_p(split.dir);
1413 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1414 return temp;
1415 }
1416
1417 static void Commit(const std::string &path, const std::string &temp) {
1418 struct stat info;
1419 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
1420 #ifndef __WIN32__
1421 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1422 #endif
1423 _syscall(chmod(temp.c_str(), info.st_mode));
1424 }
1425
1426 _syscall(rename(temp.c_str(), path.c_str()));
1427 }
1428 #endif
1429
1430 namespace ldid {
1431
1432 void Sign(const void *idata, size_t isize, std::streambuf &output, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) {
1433 std::string team;
1434
1435 #ifndef LDID_NOSMIME
1436 if (!key.empty()) {
1437 std::stringbuf data;
1438 Stuff stuff(key);
1439 auto name(X509_get_subject_name(stuff));
1440 _assert(name != NULL);
1441 auto index(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, -1));
1442 _assert(index >= 0);
1443 auto next(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, index));
1444 _assert(next == -1);
1445 auto entry(X509_NAME_get_entry(name, index));
1446 _assert(entry != NULL);
1447 auto asn(X509_NAME_ENTRY_get_data(entry));
1448 _assert(asn != NULL);
1449 team.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn)), ASN1_STRING_length(asn));
1450 }
1451 #endif
1452
1453 Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, size_t size) -> size_t {
1454 size_t alloc(sizeof(struct SuperBlob));
1455
1456 uint32_t special(0);
1457
1458 special = std::max(special, CSSLOT_REQUIREMENTS);
1459 alloc += sizeof(struct BlobIndex);
1460 alloc += 0xc;
1461
1462 if (!entitlements.empty()) {
1463 special = std::max(special, CSSLOT_ENTITLEMENTS);
1464 alloc += sizeof(struct BlobIndex);
1465 alloc += sizeof(struct Blob);
1466 alloc += entitlements.size();
1467 }
1468
1469 special = std::max(special, CSSLOT_CODEDIRECTORY);
1470 alloc += sizeof(struct BlobIndex);
1471 alloc += sizeof(struct Blob);
1472 alloc += sizeof(struct CodeDirectory);
1473 alloc += identifier.size() + 1;
1474
1475 if (!team.empty())
1476 alloc += team.size() + 1;
1477
1478 if (!key.empty()) {
1479 alloc += sizeof(struct BlobIndex);
1480 alloc += sizeof(struct Blob);
1481 // XXX: this is just a "sufficiently large number"
1482 alloc += 0x3000;
1483 }
1484
1485 _foreach (slot, slots)
1486 special = std::max(special, slot.first);
1487
1488 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1489 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
1490 special = std::max(special, CSSLOT_INFOSLOT);
1491 }));
1492
1493 uint32_t normal((size + PageSize_ - 1) / PageSize_);
1494 alloc = Align(alloc + (special + normal) * LDID_SHA1_DIGEST_LENGTH, 16);
1495 return alloc;
1496 }), fun([&](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1497 Blobs blobs;
1498
1499 if (true) {
1500 std::stringbuf data;
1501
1502 Blobs requirements;
1503 put(data, CSMAGIC_REQUIREMENTS, requirements);
1504
1505 insert(blobs, CSSLOT_REQUIREMENTS, data);
1506 }
1507
1508 if (!entitlements.empty()) {
1509 std::stringbuf data;
1510 put(data, entitlements.data(), entitlements.size());
1511 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
1512 }
1513
1514 if (true) {
1515 std::stringbuf data;
1516
1517 Slots posts(slots);
1518
1519 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1520 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
1521 sha1(posts[CSSLOT_INFOSLOT], data, size);
1522 }));
1523
1524 uint32_t special(0);
1525 _foreach (blob, blobs)
1526 special = std::max(special, blob.first);
1527 _foreach (slot, posts)
1528 special = std::max(special, slot.first);
1529 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
1530
1531 CodeDirectory directory;
1532 directory.version = Swap(uint32_t(0x00020200));
1533 directory.flags = Swap(uint32_t(0));
1534 directory.nSpecialSlots = Swap(special);
1535 directory.codeLimit = Swap(uint32_t(limit));
1536 directory.nCodeSlots = Swap(normal);
1537 directory.hashSize = LDID_SHA1_DIGEST_LENGTH;
1538 directory.hashType = CS_HASHTYPE_SHA1;
1539 directory.spare1 = 0x00;
1540 directory.pageSize = PageShift_;
1541 directory.spare2 = Swap(uint32_t(0));
1542 directory.scatterOffset = Swap(uint32_t(0));
1543 directory.spare3 = Swap(uint32_t(0));
1544 directory.codeLimit64 = Swap(uint64_t(0));
1545
1546 uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory));
1547
1548 directory.identOffset = Swap(uint32_t(offset));
1549 offset += identifier.size() + 1;
1550
1551 if (team.empty())
1552 directory.teamIDOffset = Swap(uint32_t(0));
1553 else {
1554 directory.teamIDOffset = Swap(uint32_t(offset));
1555 offset += team.size() + 1;
1556 }
1557
1558 offset += LDID_SHA1_DIGEST_LENGTH * special;
1559 directory.hashOffset = Swap(uint32_t(offset));
1560 offset += LDID_SHA1_DIGEST_LENGTH * normal;
1561
1562 put(data, &directory, sizeof(directory));
1563
1564 put(data, identifier.c_str(), identifier.size() + 1);
1565 put(data, team.c_str(), team.size() + 1);
1566
1567 uint8_t storage[special + normal][LDID_SHA1_DIGEST_LENGTH];
1568 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = storage + special;
1569
1570 memset(storage, 0, sizeof(*storage) * special);
1571
1572 _foreach (blob, blobs) {
1573 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1574 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
1575 }
1576
1577 _foreach (slot, posts) {
1578 _assert(sizeof(*hashes) == slot.second.size());
1579 memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
1580 }
1581
1582 if (normal != 1)
1583 for (size_t i = 0; i != normal - 1; ++i)
1584 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
1585 if (normal != 0)
1586 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
1587
1588 put(data, storage, sizeof(storage));
1589
1590 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
1591 }
1592
1593 #ifndef LDID_NOSMIME
1594 if (!key.empty()) {
1595 std::stringbuf data;
1596 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1597
1598 Stuff stuff(key);
1599 Buffer bio(sign);
1600
1601 Signature signature(stuff, sign);
1602 Buffer result(signature);
1603 std::string value(result);
1604 put(data, value.data(), value.size());
1605
1606 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1607 }
1608 #endif
1609
1610 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
1611 }));
1612 }
1613
1614 #ifndef LDID_NOTOOLS
1615 static void Unsign(void *idata, size_t isize, std::streambuf &output) {
1616 Allocate(idata, isize, output, fun([](const MachHeader &mach_header, size_t size) -> size_t {
1617 return 0;
1618 }), fun([](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1619 return 0;
1620 }));
1621 }
1622
1623 std::string DiskFolder::Path(const std::string &path) {
1624 return path_ + "/" + path;
1625 }
1626
1627 DiskFolder::DiskFolder(const std::string &path) :
1628 path_(path)
1629 {
1630 }
1631
1632 DiskFolder::~DiskFolder() {
1633 if (!std::uncaught_exception())
1634 for (const auto &commit : commit_)
1635 Commit(commit.first, commit.second);
1636 }
1637
1638 void DiskFolder::Find(const std::string &root, const std::string &base, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
1639 std::string path(Path(root) + base);
1640
1641 DIR *dir(opendir(path.c_str()));
1642 _assert(dir != NULL);
1643 _scope({ _syscall(closedir(dir)); });
1644
1645 while (auto child = readdir(dir)) {
1646 std::string name(child->d_name);
1647 if (name == "." || name == "..")
1648 continue;
1649 if (Starts(name, ".ldid."))
1650 continue;
1651
1652 bool directory;
1653
1654 #ifdef __WIN32__
1655 struct stat info;
1656 _syscall(stat(path.c_str(), &info));
1657 if (false);
1658 else if (S_ISDIR(info.st_mode))
1659 directory = true;
1660 else if (S_ISREG(info.st_mode))
1661 directory = false;
1662 else
1663 _assert_(false, "st_mode=%x", info.st_mode);
1664 #else
1665 switch (child->d_type) {
1666 case DT_DIR:
1667 directory = true;
1668 break;
1669 case DT_REG:
1670 directory = false;
1671 break;
1672 default:
1673 _assert_(false, "d_type=%u", child->d_type);
1674 }
1675 #endif
1676
1677 if (directory)
1678 Find(root, base + name + "/", code);
1679 else
1680 code(base + name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1681 std::string access(root + base + name);
1682 _assert_(Open(access, fun([&](std::streambuf &data, const void *flag) {
1683 NullBuffer save;
1684 code(data, save);
1685 })), "open(): %s", access.c_str());
1686 }));
1687 }
1688 }
1689
1690 void DiskFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) {
1691 std::filebuf save;
1692 auto from(Path(path));
1693 commit_[from] = Temporary(save, from);
1694 code(save);
1695 }
1696
1697 bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) {
1698 std::filebuf data;
1699 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
1700 if (result == NULL)
1701 return false;
1702 _assert(result == &data);
1703 code(data, NULL);
1704 return true;
1705 }
1706
1707 void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
1708 Find(path, "", code);
1709 }
1710 #endif
1711
1712 SubFolder::SubFolder(Folder &parent, const std::string &path) :
1713 parent_(parent),
1714 path_(path)
1715 {
1716 }
1717
1718 void SubFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) {
1719 return parent_.Save(path_ + path, flag, code);
1720 }
1721
1722 bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) {
1723 return parent_.Open(path_ + path, code);
1724 }
1725
1726 void SubFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1727 return parent_.Find(path_ + path, code);
1728 }
1729
1730 std::string UnionFolder::Map(const std::string &path) {
1731 auto remap(remaps_.find(path));
1732 if (remap == remaps_.end())
1733 return path;
1734 return remap->second;
1735 }
1736
1737 void UnionFolder::Map(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code, const std::string &file, const Functor<void (const Functor<void (std::streambuf &, const void *)> &)> &save) {
1738 if (file.size() >= path.size() && file.substr(0, path.size()) == path)
1739 code(file.substr(path.size()), fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1740 save(fun([&](std::streambuf &data, const void *flag) {
1741 parent_.Save(file, flag, fun([&](std::streambuf &save) {
1742 code(data, save);
1743 }));
1744 }));
1745 }));
1746 }
1747
1748 UnionFolder::UnionFolder(Folder &parent) :
1749 parent_(parent)
1750 {
1751 }
1752
1753 void UnionFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) {
1754 return parent_.Save(Map(path), flag, code);
1755 }
1756
1757 bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) {
1758 auto file(resets_.find(path));
1759 if (file == resets_.end())
1760 return parent_.Open(Map(path), code);
1761 auto &entry(file->second);
1762
1763 auto &data(entry.first);
1764 data.pubseekpos(0, std::ios::in);
1765 code(data, entry.second);
1766 return true;
1767 }
1768
1769 void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1770 parent_.Find(path, fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &save) {
1771 if (deletes_.find(path + name) == deletes_.end())
1772 code(name, save);
1773 }));
1774
1775 for (auto &reset : resets_)
1776 Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, const void *)> &code) {
1777 auto &entry(reset.second);
1778 entry.first.pubseekpos(0, std::ios::in);
1779 code(entry.first, entry.second);
1780 }));
1781
1782 for (auto &remap : remaps_)
1783 Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, const void *)> &code) {
1784 parent_.Open(remap.second, fun([&](std::streambuf &data, const void *flag) {
1785 code(data, flag);
1786 }));
1787 }));
1788 }
1789
1790 #ifndef LDID_NOTOOLS
1791 static size_t copy(std::streambuf &source, std::streambuf &target) {
1792 size_t total(0);
1793 for (;;) {
1794 char data[4096];
1795 size_t writ(source.sgetn(data, sizeof(data)));
1796 if (writ == 0)
1797 break;
1798 _assert(target.sputn(data, writ) == writ);
1799 total += writ;
1800 }
1801 return total;
1802 }
1803
1804 #ifndef LDID_NOPLIST
1805 static plist_t plist(const std::string &data) {
1806 plist_t plist(NULL);
1807 if (Starts(data, "bplist00"))
1808 plist_from_bin(data.data(), data.size(), &plist);
1809 else
1810 plist_from_xml(data.data(), data.size(), &plist);
1811 _assert(plist != NULL);
1812 return plist;
1813 }
1814
1815 static void plist_d(std::streambuf &buffer, const Functor<void (plist_t)> &code) {
1816 std::stringbuf data;
1817 copy(buffer, data);
1818 auto node(plist(data.str()));
1819 _scope({ plist_free(node); });
1820 _assert(plist_get_node_type(node) == PLIST_DICT);
1821 code(node);
1822 }
1823
1824 static std::string plist_s(plist_t node) {
1825 _assert(node != NULL);
1826 _assert(plist_get_node_type(node) == PLIST_STRING);
1827 char *data;
1828 plist_get_string_val(node, &data);
1829 _scope({ free(data); });
1830 return data;
1831 }
1832 #endif
1833
1834 enum Mode {
1835 NoMode,
1836 OptionalMode,
1837 OmitMode,
1838 NestedMode,
1839 TopMode,
1840 };
1841
1842 class Expression {
1843 private:
1844 regex_t regex_;
1845
1846 public:
1847 Expression(const std::string &code) {
1848 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()");
1849 }
1850
1851 ~Expression() {
1852 regfree(&regex_);
1853 }
1854
1855 bool operator ()(const std::string &data) const {
1856 auto value(regexec(&regex_, data.c_str(), 0, NULL, 0));
1857 if (value == REG_NOMATCH)
1858 return false;
1859 _assert_(value == 0, "regexec()");
1860 return true;
1861 }
1862 };
1863
1864 struct Rule {
1865 unsigned weight_;
1866 Mode mode_;
1867 std::string code_;
1868
1869 mutable std::auto_ptr<Expression> regex_;
1870
1871 Rule(unsigned weight, Mode mode, const std::string &code) :
1872 weight_(weight),
1873 mode_(mode),
1874 code_(code)
1875 {
1876 }
1877
1878 Rule(const Rule &rhs) :
1879 weight_(rhs.weight_),
1880 mode_(rhs.mode_),
1881 code_(rhs.code_)
1882 {
1883 }
1884
1885 void Compile() const {
1886 regex_.reset(new Expression(code_));
1887 }
1888
1889 bool operator ()(const std::string &data) const {
1890 _assert(regex_.get() != NULL);
1891 return (*regex_)(data);
1892 }
1893
1894 bool operator <(const Rule &rhs) const {
1895 if (weight_ > rhs.weight_)
1896 return true;
1897 if (weight_ < rhs.weight_)
1898 return false;
1899 return mode_ > rhs.mode_;
1900 }
1901 };
1902
1903 struct RuleCode {
1904 bool operator ()(const Rule *lhs, const Rule *rhs) const {
1905 return lhs->code_ < rhs->code_;
1906 }
1907 };
1908
1909 #ifndef LDID_NOPLIST
1910 void Sign(std::streambuf &buffer, std::vector<char> &hash, std::streambuf &save, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) {
1911 // XXX: this is a miserable fail
1912 std::stringbuf temp;
1913 copy(buffer, temp);
1914 auto data(temp.str());
1915
1916 HashProxy proxy(hash, save);
1917 Sign(data.data(), data.size(), proxy, identifier, entitlements, key, slots);
1918 }
1919
1920 std::string Bundle(const std::string &root, Folder &folder, const std::string &key, std::map<std::string, std::vector<char>> &remote, const std::string &entitlements) {
1921 std::string executable;
1922 std::string identifier;
1923
1924 static const std::string info("Info.plist");
1925
1926 _assert_(folder.Open(info, fun([&](std::streambuf &buffer, const void *flag) {
1927 plist_d(buffer, fun([&](plist_t node) {
1928 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
1929 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
1930 }));
1931 })), "open(): Info.plist");
1932
1933 static const std::string directory("_CodeSignature/");
1934 static const std::string signature(directory + "CodeResources");
1935
1936 std::map<std::string, std::multiset<Rule>> versions;
1937
1938 auto &rules1(versions[""]);
1939 auto &rules2(versions["2"]);
1940
1941 folder.Open(signature, fun([&](std::streambuf &buffer, const void *) {
1942 plist_d(buffer, fun([&](plist_t node) {
1943 // XXX: maybe attempt to preserve existing rules
1944 }));
1945 }));
1946
1947 if (true) {
1948 rules1.insert(Rule{1, NoMode, "^"});
1949 rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1950 rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1951 rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1952 rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1953 rules1.insert(Rule{1, NoMode, "^version.plist$"});
1954 }
1955
1956 if (true) {
1957 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
1958 rules2.insert(Rule{20, NoMode, "^"});
1959 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
1960 rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1961 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1962 rules2.insert(Rule{1, NoMode, "^.*"});
1963 rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1964 rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1965 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
1966 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
1967 rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1968 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
1969 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
1970 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
1971 }
1972
1973 std::map<std::string, std::vector<char>> local;
1974
1975 static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1976 static Expression dylib("^[^/]*\\.dylib$");
1977
1978 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1979 if (!nested(name))
1980 return;
1981 auto bundle(root + Split(name).dir);
1982 SubFolder subfolder(folder, bundle);
1983 Bundle(bundle, subfolder, key, local, "");
1984 }));
1985
1986 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1987 // BundleDiskRep::adjustResources -> builder.addExclusion
1988 if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
1989 return;
1990
1991 auto &hash(local[name]);
1992 if (!hash.empty())
1993 return;
1994
1995 code(fun([&](std::streambuf &data, std::streambuf &save) {
1996 if (dylib(name)) {
1997 Slots slots;
1998 Sign(data, hash, save, identifier, "", key, slots);
1999 } else {
2000 HashProxy proxy(hash, save);
2001 copy(data, proxy);
2002 }
2003 }));
2004
2005 _assert(hash.size() == LDID_SHA1_DIGEST_LENGTH);
2006 }));
2007
2008 auto plist(plist_new_dict());
2009 _scope({ plist_free(plist); });
2010
2011 for (const auto &version : versions) {
2012 auto files(plist_new_dict());
2013 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
2014
2015 for (const auto &rule : version.second)
2016 rule.Compile();
2017
2018 for (const auto &hash : local)
2019 for (const auto &rule : version.second)
2020 if (rule(hash.first)) {
2021 if (rule.mode_ == NoMode)
2022 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(hash.second.data(), hash.second.size()));
2023 else if (rule.mode_ == OptionalMode) {
2024 auto entry(plist_new_dict());
2025 plist_dict_set_item(entry, "hash", plist_new_data(hash.second.data(), hash.second.size()));
2026 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2027 plist_dict_set_item(files, hash.first.c_str(), entry);
2028 }
2029
2030 break;
2031 }
2032 }
2033
2034 for (const auto &version : versions) {
2035 auto rules(plist_new_dict());
2036 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
2037
2038 std::multiset<const Rule *, RuleCode> ordered;
2039 for (const auto &rule : version.second)
2040 ordered.insert(&rule);
2041
2042 for (const auto &rule : ordered)
2043 if (rule->weight_ == 1 && rule->mode_ == NoMode)
2044 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
2045 else {
2046 auto entry(plist_new_dict());
2047 plist_dict_set_item(rules, rule->code_.c_str(), entry);
2048
2049 switch (rule->mode_) {
2050 case NoMode:
2051 break;
2052 case OmitMode:
2053 plist_dict_set_item(entry, "omit", plist_new_bool(true));
2054 break;
2055 case OptionalMode:
2056 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2057 break;
2058 case NestedMode:
2059 plist_dict_set_item(entry, "nested", plist_new_bool(true));
2060 break;
2061 case TopMode:
2062 plist_dict_set_item(entry, "top", plist_new_bool(true));
2063 break;
2064 }
2065
2066 if (rule->weight_ >= 10000)
2067 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
2068 else if (rule->weight_ != 1)
2069 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
2070 }
2071 }
2072
2073 folder.Save(signature, NULL, fun([&](std::streambuf &save) {
2074 HashProxy proxy(local[signature], save);
2075 char *xml(NULL);
2076 uint32_t size;
2077 plist_to_xml(plist, &xml, &size);
2078 _scope({ free(xml); });
2079 put(proxy, xml, size);
2080 }));
2081
2082 folder.Open(executable, fun([&](std::streambuf &buffer, const void *flag) {
2083 folder.Save(executable, flag, fun([&](std::streambuf &save) {
2084 Slots slots;
2085 slots[1] = local.at(info);
2086 slots[3] = local.at(signature);
2087 Sign(buffer, local[executable], save, identifier, entitlements, key, slots);
2088 }));
2089 }));
2090
2091 for (const auto &hash : local)
2092 remote[root + hash.first] = hash.second;
2093
2094 return executable;
2095 }
2096 #endif
2097
2098 #endif
2099 }
2100
2101 #ifndef LDID_NOTOOLS
2102 int main(int argc, char *argv[]) {
2103 #ifndef LDID_NOSMIME
2104 OpenSSL_add_all_algorithms();
2105 #endif
2106
2107 union {
2108 uint16_t word;
2109 uint8_t byte[2];
2110 } endian = {1};
2111
2112 little_ = endian.byte[0];
2113
2114 bool flag_r(false);
2115 bool flag_e(false);
2116
2117 #ifndef LDID_NOFLAGT
2118 bool flag_T(false);
2119 #endif
2120
2121 bool flag_S(false);
2122 bool flag_s(false);
2123
2124 bool flag_D(false);
2125
2126 bool flag_A(false);
2127 bool flag_a(false);
2128
2129 bool flag_u(false);
2130
2131 uint32_t flag_CPUType(_not(uint32_t));
2132 uint32_t flag_CPUSubtype(_not(uint32_t));
2133
2134 const char *flag_I(NULL);
2135
2136 #ifndef LDID_NOFLAGT
2137 bool timeh(false);
2138 uint32_t timev(0);
2139 #endif
2140
2141 Map entitlements;
2142 Map key;
2143 ldid::Slots slots;
2144
2145 std::vector<std::string> files;
2146
2147 if (argc == 1) {
2148 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
2149 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
2150 fprintf(stderr, " %s -S cat\n", argv[0]);
2151 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
2152 exit(0);
2153 }
2154
2155 for (int argi(1); argi != argc; ++argi)
2156 if (argv[argi][0] != '-')
2157 files.push_back(argv[argi]);
2158 else switch (argv[argi][1]) {
2159 case 'r':
2160 _assert(!flag_s);
2161 _assert(!flag_S);
2162 flag_r = true;
2163 break;
2164
2165 case 'e': flag_e = true; break;
2166
2167 case 'E': {
2168 const char *slot = argv[argi] + 2;
2169 const char *colon = strchr(slot, ':');
2170 _assert(colon != NULL);
2171 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
2172 char *arge;
2173 unsigned number(strtoul(slot, &arge, 0));
2174 _assert(arge == colon);
2175 sha1(slots[number], file.data(), file.size());
2176 } break;
2177
2178 case 'D': flag_D = true; break;
2179
2180 case 'a': flag_a = true; break;
2181
2182 case 'A':
2183 _assert(!flag_A);
2184 flag_A = true;
2185 if (argv[argi][2] != '\0') {
2186 const char *cpu = argv[argi] + 2;
2187 const char *colon = strchr(cpu, ':');
2188 _assert(colon != NULL);
2189 char *arge;
2190 flag_CPUType = strtoul(cpu, &arge, 0);
2191 _assert(arge == colon);
2192 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2193 _assert(arge == argv[argi] + strlen(argv[argi]));
2194 }
2195 break;
2196
2197 case 's':
2198 _assert(!flag_r);
2199 _assert(!flag_S);
2200 flag_s = true;
2201 break;
2202
2203 case 'S':
2204 _assert(!flag_r);
2205 _assert(!flag_s);
2206 flag_S = true;
2207 if (argv[argi][2] != '\0') {
2208 const char *xml = argv[argi] + 2;
2209 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2210 }
2211 break;
2212
2213 case 'K':
2214 if (argv[argi][2] != '\0')
2215 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
2216 break;
2217
2218 #ifndef LDID_NOFLAGT
2219 case 'T': {
2220 flag_T = true;
2221 if (argv[argi][2] == '-')
2222 timeh = true;
2223 else {
2224 char *arge;
2225 timev = strtoul(argv[argi] + 2, &arge, 0);
2226 _assert(arge == argv[argi] + strlen(argv[argi]));
2227 }
2228 } break;
2229 #endif
2230
2231 case 'u': {
2232 flag_u = true;
2233 } break;
2234
2235 case 'I': {
2236 flag_I = argv[argi] + 2;
2237 } break;
2238
2239 default:
2240 goto usage;
2241 break;
2242 }
2243
2244 _assert(flag_S || key.empty());
2245 _assert(flag_S || flag_I == NULL);
2246
2247 if (files.empty()) usage: {
2248 exit(0);
2249 }
2250
2251 size_t filei(0), filee(0);
2252 _foreach (file, files) try {
2253 std::string path(file);
2254
2255 struct stat info;
2256 _syscall(stat(path.c_str(), &info));
2257
2258 if (S_ISDIR(info.st_mode)) {
2259 #ifndef LDID_NOPLIST
2260 _assert(!flag_r);
2261 ldid::DiskFolder folder(path);
2262 std::map<std::string, std::vector<char>> hashes;
2263 path += "/" + Bundle("", folder, key, hashes, entitlements);
2264 #else
2265 _assert(false);
2266 #endif
2267 } else if (flag_S || flag_r) {
2268 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
2269
2270 std::filebuf output;
2271 Split split(path);
2272 auto temp(Temporary(output, split));
2273
2274 if (flag_r)
2275 ldid::Unsign(input.data(), input.size(), output);
2276 else {
2277 std::string identifier(flag_I ?: split.base.c_str());
2278 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
2279 }
2280
2281 Commit(path, temp);
2282 }
2283
2284 bool modify(false);
2285 #ifndef LDID_NOFLAGT
2286 if (flag_T)
2287 modify = true;
2288 #endif
2289 if (flag_s)
2290 modify = true;
2291
2292 Map mapping(path, modify);
2293 FatHeader fat_header(mapping.data(), mapping.size());
2294
2295 _foreach (mach_header, fat_header.GetMachHeaders()) {
2296 struct linkedit_data_command *signature(NULL);
2297 struct encryption_info_command *encryption(NULL);
2298
2299 if (flag_A) {
2300 if (mach_header.GetCPUType() != flag_CPUType)
2301 continue;
2302 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2303 continue;
2304 }
2305
2306 if (flag_a)
2307 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2308
2309 _foreach (load_command, mach_header.GetLoadCommands()) {
2310 uint32_t cmd(mach_header.Swap(load_command->cmd));
2311
2312 if (false);
2313 else if (cmd == LC_CODE_SIGNATURE)
2314 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
2315 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
2316 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
2317 else if (cmd == LC_LOAD_DYLIB) {
2318 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2319 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
2320
2321 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2322 if (flag_u) {
2323 Version version;
2324 version.value = mach_header.Swap(dylib_command->dylib.current_version);
2325 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
2326 }
2327 }
2328 }
2329 #ifndef LDID_NOFLAGT
2330 else if (cmd == LC_ID_DYLIB) {
2331 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2332
2333 if (flag_T) {
2334 uint32_t timed;
2335
2336 if (!timeh)
2337 timed = timev;
2338 else {
2339 dylib_command->dylib.timestamp = 0;
2340 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2341 }
2342
2343 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2344 }
2345 }
2346 #endif
2347 }
2348
2349 if (flag_D) {
2350 _assert(encryption != NULL);
2351 encryption->cryptid = mach_header.Swap(0);
2352 }
2353
2354 if (flag_e) {
2355 _assert(signature != NULL);
2356
2357 uint32_t data = mach_header.Swap(signature->dataoff);
2358
2359 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2360 uint8_t *blob = top + data;
2361 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2362
2363 for (size_t index(0); index != Swap(super->count); ++index)
2364 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2365 uint32_t begin = Swap(super->index[index].offset);
2366 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
2367 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
2368 }
2369 }
2370
2371 if (flag_s) {
2372 _assert(signature != NULL);
2373
2374 uint32_t data = mach_header.Swap(signature->dataoff);
2375
2376 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2377 uint8_t *blob = top + data;
2378 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2379
2380 for (size_t index(0); index != Swap(super->count); ++index)
2381 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2382 uint32_t begin = Swap(super->index[index].offset);
2383 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
2384
2385 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
2386 uint32_t pages = Swap(directory->nCodeSlots);
2387
2388 if (pages != 1)
2389 for (size_t i = 0; i != pages - 1; ++i)
2390 sha1(hashes[i], top + PageSize_ * i, PageSize_);
2391 if (pages != 0)
2392 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
2393 }
2394 }
2395 }
2396
2397 ++filei;
2398 } catch (const char *) {
2399 ++filee;
2400 ++filei;
2401 }
2402
2403 return filee;
2404 }
2405 #endif