]> git.saurik.com Git - ldid.git/blob - ldid.cpp
a95c8973a9c81e71fb8230990eaff2a555cdbc44
[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 } _packed;
429
430 struct linkedit_data_command {
431 uint32_t cmd;
432 uint32_t cmdsize;
433 uint32_t dataoff;
434 uint32_t datasize;
435 } _packed;
436
437 struct encryption_info_command {
438 uint32_t cmd;
439 uint32_t cmdsize;
440 uint32_t cryptoff;
441 uint32_t cryptsize;
442 uint32_t cryptid;
443 } _packed;
444
445 #define BIND_OPCODE_MASK 0xf0
446 #define BIND_IMMEDIATE_MASK 0x0f
447 #define BIND_OPCODE_DONE 0x00
448 #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
449 #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
450 #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
451 #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
452 #define BIND_OPCODE_SET_TYPE_IMM 0x50
453 #define BIND_OPCODE_SET_ADDEND_SLEB 0x60
454 #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
455 #define BIND_OPCODE_ADD_ADDR_ULEB 0x80
456 #define BIND_OPCODE_DO_BIND 0x90
457 #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
458 #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
459 #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
460
461 inline void get(std::streambuf &stream, void *data, size_t size) {
462 _assert(stream.sgetn(static_cast<char *>(data), size) == size);
463 }
464
465 inline void put(std::streambuf &stream, const void *data, size_t size) {
466 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
467 }
468
469 inline void pad(std::streambuf &stream, size_t size) {
470 char padding[size];
471 memset(padding, 0, size);
472 put(stream, padding, size);
473 }
474
475 template <typename Type_>
476 Type_ Align(Type_ value, size_t align) {
477 value += align - 1;
478 value /= align;
479 value *= align;
480 return value;
481 }
482
483 static const uint8_t PageShift_(0x0c);
484 static const uint32_t PageSize_(1 << PageShift_);
485
486 static inline uint16_t Swap_(uint16_t value) {
487 return
488 ((value >> 8) & 0x00ff) |
489 ((value << 8) & 0xff00);
490 }
491
492 static inline uint32_t Swap_(uint32_t value) {
493 value = ((value >> 8) & 0x00ff00ff) |
494 ((value << 8) & 0xff00ff00);
495 value = ((value >> 16) & 0x0000ffff) |
496 ((value << 16) & 0xffff0000);
497 return value;
498 }
499
500 static inline uint64_t Swap_(uint64_t value) {
501 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
502 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
503 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
504 return value;
505 }
506
507 static inline int16_t Swap_(int16_t value) {
508 return Swap_(static_cast<uint16_t>(value));
509 }
510
511 static inline int32_t Swap_(int32_t value) {
512 return Swap_(static_cast<uint32_t>(value));
513 }
514
515 static inline int64_t Swap_(int64_t value) {
516 return Swap_(static_cast<uint64_t>(value));
517 }
518
519 static bool little_(true);
520
521 static inline uint16_t Swap(uint16_t value) {
522 return little_ ? Swap_(value) : value;
523 }
524
525 static inline uint32_t Swap(uint32_t value) {
526 return little_ ? Swap_(value) : value;
527 }
528
529 static inline uint64_t Swap(uint64_t value) {
530 return little_ ? Swap_(value) : value;
531 }
532
533 static inline int16_t Swap(int16_t value) {
534 return Swap(static_cast<uint16_t>(value));
535 }
536
537 static inline int32_t Swap(int32_t value) {
538 return Swap(static_cast<uint32_t>(value));
539 }
540
541 static inline int64_t Swap(int64_t value) {
542 return Swap(static_cast<uint64_t>(value));
543 }
544
545 class Swapped {
546 protected:
547 bool swapped_;
548
549 Swapped() :
550 swapped_(false)
551 {
552 }
553
554 public:
555 Swapped(bool swapped) :
556 swapped_(swapped)
557 {
558 }
559
560 template <typename Type_>
561 Type_ Swap(Type_ value) const {
562 return swapped_ ? Swap_(value) : value;
563 }
564 };
565
566 class Data :
567 public Swapped
568 {
569 private:
570 void *base_;
571 size_t size_;
572
573 public:
574 Data(void *base, size_t size) :
575 base_(base),
576 size_(size)
577 {
578 }
579
580 void *GetBase() const {
581 return base_;
582 }
583
584 size_t GetSize() const {
585 return size_;
586 }
587 };
588
589 class MachHeader :
590 public Data
591 {
592 private:
593 bool bits64_;
594
595 struct mach_header *mach_header_;
596 struct load_command *load_command_;
597
598 public:
599 MachHeader(void *base, size_t size) :
600 Data(base, size)
601 {
602 mach_header_ = (mach_header *) base;
603
604 switch (Swap(mach_header_->magic)) {
605 case MH_CIGAM:
606 swapped_ = !swapped_;
607 case MH_MAGIC:
608 bits64_ = false;
609 break;
610
611 case MH_CIGAM_64:
612 swapped_ = !swapped_;
613 case MH_MAGIC_64:
614 bits64_ = true;
615 break;
616
617 default:
618 _assert(false);
619 }
620
621 void *post = mach_header_ + 1;
622 if (bits64_)
623 post = (uint32_t *) post + 1;
624 load_command_ = (struct load_command *) post;
625
626 _assert(
627 Swap(mach_header_->filetype) == MH_EXECUTE ||
628 Swap(mach_header_->filetype) == MH_DYLIB ||
629 Swap(mach_header_->filetype) == MH_BUNDLE
630 );
631 }
632
633 bool Bits64() const {
634 return bits64_;
635 }
636
637 struct mach_header *operator ->() const {
638 return mach_header_;
639 }
640
641 operator struct mach_header *() const {
642 return mach_header_;
643 }
644
645 uint32_t GetCPUType() const {
646 return Swap(mach_header_->cputype);
647 }
648
649 uint32_t GetCPUSubtype() const {
650 return Swap(mach_header_->cpusubtype) & 0xff;
651 }
652
653 struct load_command *GetLoadCommand() const {
654 return load_command_;
655 }
656
657 std::vector<struct load_command *> GetLoadCommands() const {
658 std::vector<struct load_command *> load_commands;
659
660 struct load_command *load_command = load_command_;
661 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
662 load_commands.push_back(load_command);
663 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
664 }
665
666 return load_commands;
667 }
668
669 template <typename Target_>
670 Target_ *GetOffset(uint32_t offset) const {
671 return reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_);
672 }
673 };
674
675 class FatMachHeader :
676 public MachHeader
677 {
678 private:
679 fat_arch *fat_arch_;
680
681 public:
682 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
683 MachHeader(base, size),
684 fat_arch_(fat_arch)
685 {
686 }
687
688 fat_arch *GetFatArch() const {
689 return fat_arch_;
690 }
691 };
692
693 class FatHeader :
694 public Data
695 {
696 private:
697 fat_header *fat_header_;
698 std::vector<FatMachHeader> mach_headers_;
699
700 public:
701 FatHeader(void *base, size_t size) :
702 Data(base, size)
703 {
704 fat_header_ = reinterpret_cast<struct fat_header *>(base);
705
706 if (Swap(fat_header_->magic) == FAT_CIGAM) {
707 swapped_ = !swapped_;
708 goto fat;
709 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
710 fat_header_ = NULL;
711 mach_headers_.push_back(FatMachHeader(base, size, NULL));
712 } else fat: {
713 size_t fat_narch = Swap(fat_header_->nfat_arch);
714 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
715 size_t arch;
716 for (arch = 0; arch != fat_narch; ++arch) {
717 uint32_t arch_offset = Swap(fat_arch->offset);
718 uint32_t arch_size = Swap(fat_arch->size);
719 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
720 ++fat_arch;
721 }
722 }
723 }
724
725 std::vector<FatMachHeader> &GetMachHeaders() {
726 return mach_headers_;
727 }
728
729 bool IsFat() const {
730 return fat_header_ != NULL;
731 }
732
733 struct fat_header *operator ->() const {
734 return fat_header_;
735 }
736
737 operator struct fat_header *() const {
738 return fat_header_;
739 }
740 };
741
742 #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
743 #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
744 #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
745 #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
746 #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
747 #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
748 #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
749 #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
750
751 #define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
752 #define CSSLOT_INFOSLOT uint32_t(0x00001)
753 #define CSSLOT_REQUIREMENTS uint32_t(0x00002)
754 #define CSSLOT_RESOURCEDIR uint32_t(0x00003)
755 #define CSSLOT_APPLICATION uint32_t(0x00004)
756 #define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
757
758 #define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
759
760 #define CS_HASHTYPE_SHA1 1
761
762 struct BlobIndex {
763 uint32_t type;
764 uint32_t offset;
765 } _packed;
766
767 struct Blob {
768 uint32_t magic;
769 uint32_t length;
770 } _packed;
771
772 struct SuperBlob {
773 struct Blob blob;
774 uint32_t count;
775 struct BlobIndex index[];
776 } _packed;
777
778 struct CodeDirectory {
779 uint32_t version;
780 uint32_t flags;
781 uint32_t hashOffset;
782 uint32_t identOffset;
783 uint32_t nSpecialSlots;
784 uint32_t nCodeSlots;
785 uint32_t codeLimit;
786 uint8_t hashSize;
787 uint8_t hashType;
788 uint8_t spare1;
789 uint8_t pageSize;
790 uint32_t spare2;
791 } _packed;
792
793 #ifndef LDID_NOFLAGT
794 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
795 #endif
796
797 static void sha1(uint8_t *hash, const void *data, size_t size) {
798 LDID_SHA1(static_cast<const uint8_t *>(data), size, hash);
799 }
800
801 static void sha1(std::vector<char> &hash, const void *data, size_t size) {
802 hash.resize(LDID_SHA1_DIGEST_LENGTH);
803 sha1(reinterpret_cast<uint8_t *>(hash.data()), data, size);
804 }
805
806 struct CodesignAllocation {
807 FatMachHeader mach_header_;
808 uint32_t offset_;
809 uint32_t size_;
810 uint32_t limit_;
811 uint32_t alloc_;
812 uint32_t align_;
813
814 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
815 mach_header_(mach_header),
816 offset_(offset),
817 size_(size),
818 limit_(limit),
819 alloc_(alloc),
820 align_(align)
821 {
822 }
823 };
824
825 #ifndef LDID_NOTOOLS
826 class File {
827 private:
828 int file_;
829
830 public:
831 File() :
832 file_(-1)
833 {
834 }
835
836 ~File() {
837 if (file_ != -1)
838 _syscall(close(file_));
839 }
840
841 void open(const char *path, int flags) {
842 _assert(file_ == -1);
843 file_ = _syscall(::open(path, flags));
844 }
845
846 int file() const {
847 return file_;
848 }
849 };
850
851 class Map {
852 private:
853 File file_;
854 void *data_;
855 size_t size_;
856
857 void clear() {
858 if (data_ == NULL)
859 return;
860 _syscall(munmap(data_, size_));
861 data_ = NULL;
862 size_ = 0;
863 }
864
865 public:
866 Map() :
867 data_(NULL),
868 size_(0)
869 {
870 }
871
872 Map(const std::string &path, int oflag, int pflag, int mflag) :
873 Map()
874 {
875 open(path, oflag, pflag, mflag);
876 }
877
878 Map(const std::string &path, bool edit) :
879 Map()
880 {
881 open(path, edit);
882 }
883
884 ~Map() {
885 clear();
886 }
887
888 bool empty() const {
889 return data_ == NULL;
890 }
891
892 void open(const std::string &path, int oflag, int pflag, int mflag) {
893 clear();
894
895 file_.open(path.c_str(), oflag);
896 int file(file_.file());
897
898 struct stat stat;
899 _syscall(fstat(file, &stat));
900 size_ = stat.st_size;
901
902 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
903 }
904
905 void open(const std::string &path, bool edit) {
906 if (edit)
907 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
908 else
909 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
910 }
911
912 void *data() const {
913 return data_;
914 }
915
916 size_t size() const {
917 return size_;
918 }
919
920 operator std::string() const {
921 return std::string(static_cast<char *>(data_), size_);
922 }
923 };
924 #endif
925
926 namespace ldid {
927
928 static void Allocate(const void *idata, size_t isize, std::streambuf &output, const Functor<size_t (size_t)> &allocate, const Functor<size_t (std::streambuf &output, size_t, const std::string &, const char *)> &save) {
929 FatHeader source(const_cast<void *>(idata), isize);
930
931 size_t offset(0);
932 if (source.IsFat())
933 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
934
935 std::vector<CodesignAllocation> allocations;
936 _foreach (mach_header, source.GetMachHeaders()) {
937 struct linkedit_data_command *signature(NULL);
938 struct symtab_command *symtab(NULL);
939
940 _foreach (load_command, mach_header.GetLoadCommands()) {
941 uint32_t cmd(mach_header.Swap(load_command->cmd));
942 if (false);
943 else if (cmd == LC_CODE_SIGNATURE)
944 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
945 else if (cmd == LC_SYMTAB)
946 symtab = reinterpret_cast<struct symtab_command *>(load_command);
947 }
948
949 size_t size;
950 if (signature == NULL)
951 size = mach_header.GetSize();
952 else {
953 size = mach_header.Swap(signature->dataoff);
954 _assert(size <= mach_header.GetSize());
955 }
956
957 if (symtab != NULL) {
958 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
959 _assert(end <= size);
960 _assert(end >= size - 0x10);
961 size = end;
962 }
963
964 size_t alloc(allocate(size));
965
966 auto *fat_arch(mach_header.GetFatArch());
967 uint32_t align;
968
969 if (fat_arch != NULL)
970 align = source.Swap(fat_arch->align);
971 else switch (mach_header.GetCPUType()) {
972 case CPU_TYPE_POWERPC:
973 case CPU_TYPE_POWERPC64:
974 case CPU_TYPE_X86:
975 case CPU_TYPE_X86_64:
976 align = 0xc;
977 break;
978 case CPU_TYPE_ARM:
979 case CPU_TYPE_ARM64:
980 align = 0xe;
981 break;
982 default:
983 align = 0x0;
984 break;
985 }
986
987 offset = Align(offset, 1 << align);
988
989 uint32_t limit(size);
990 if (alloc != 0)
991 limit = Align(limit, 0x10);
992
993 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
994 offset += size + alloc;
995 offset = Align(offset, 0x10);
996 }
997
998 size_t position(0);
999
1000 if (source.IsFat()) {
1001 fat_header fat_header;
1002 fat_header.magic = Swap(FAT_MAGIC);
1003 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1004 put(output, &fat_header, sizeof(fat_header));
1005 position += sizeof(fat_header);
1006
1007 _foreach (allocation, allocations) {
1008 auto &mach_header(allocation.mach_header_);
1009
1010 fat_arch fat_arch;
1011 fat_arch.cputype = Swap(mach_header->cputype);
1012 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1013 fat_arch.offset = Swap(allocation.offset_);
1014 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1015 fat_arch.align = Swap(allocation.align_);
1016 put(output, &fat_arch, sizeof(fat_arch));
1017 position += sizeof(fat_arch);
1018 }
1019 }
1020
1021 _foreach (allocation, allocations) {
1022 auto &mach_header(allocation.mach_header_);
1023
1024 pad(output, allocation.offset_ - position);
1025 position = allocation.offset_;
1026
1027 std::vector<std::string> commands;
1028
1029 _foreach (load_command, mach_header.GetLoadCommands()) {
1030 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
1031
1032 switch (mach_header.Swap(load_command->cmd)) {
1033 case LC_CODE_SIGNATURE:
1034 continue;
1035 break;
1036
1037 case LC_SEGMENT: {
1038 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1039 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1040 break;
1041 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1042 segment_command->filesize = size;
1043 segment_command->vmsize = Align(size, 1 << allocation.align_);
1044 } break;
1045
1046 case LC_SEGMENT_64: {
1047 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1048 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1049 break;
1050 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1051 segment_command->filesize = size;
1052 segment_command->vmsize = Align(size, 1 << allocation.align_);
1053 } break;
1054 }
1055
1056 commands.push_back(copy);
1057 }
1058
1059 if (allocation.alloc_ != 0) {
1060 linkedit_data_command signature;
1061 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1062 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1063 signature.dataoff = mach_header.Swap(allocation.limit_);
1064 signature.datasize = mach_header.Swap(allocation.alloc_);
1065 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1066 }
1067
1068 size_t begin(position);
1069
1070 uint32_t after(0);
1071 _foreach(command, commands)
1072 after += command.size();
1073
1074 std::stringbuf altern;
1075
1076 struct mach_header header(*mach_header);
1077 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1078 header.sizeofcmds = mach_header.Swap(after);
1079 put(output, &header, sizeof(header));
1080 put(altern, &header, sizeof(header));
1081 position += sizeof(header);
1082
1083 if (mach_header.Bits64()) {
1084 auto pad(mach_header.Swap(uint32_t(0)));
1085 put(output, &pad, sizeof(pad));
1086 put(altern, &pad, sizeof(pad));
1087 position += sizeof(pad);
1088 }
1089
1090 _foreach(command, commands) {
1091 put(output, command.data(), command.size());
1092 put(altern, command.data(), command.size());
1093 position += command.size();
1094 }
1095
1096 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1097 if (before > after) {
1098 pad(output, before - after);
1099 pad(altern, before - after);
1100 position += before - after;
1101 }
1102
1103 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
1104
1105 std::string overlap(altern.str());
1106 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
1107
1108 put(output, top + (position - begin), allocation.size_ - (position - begin));
1109 position = begin + allocation.size_;
1110
1111 pad(output, allocation.limit_ - allocation.size_);
1112 position += allocation.limit_ - allocation.size_;
1113
1114 size_t saved(save(output, allocation.limit_, overlap, top));
1115 if (allocation.alloc_ > saved)
1116 pad(output, allocation.alloc_ - saved);
1117 position += allocation.alloc_;
1118 }
1119 }
1120
1121 }
1122
1123 typedef std::map<uint32_t, std::string> Blobs;
1124
1125 static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1126 auto value(buffer.str());
1127 std::swap(blobs[slot], value);
1128 }
1129
1130 static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1131 auto value(buffer.str());
1132 Blob blob;
1133 blob.magic = Swap(magic);
1134 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1135 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1136 std::swap(blobs[slot], value);
1137 }
1138
1139 static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1140 size_t total(0);
1141 _foreach (blob, blobs)
1142 total += blob.second.size();
1143
1144 struct SuperBlob super;
1145 super.blob.magic = Swap(magic);
1146 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1147 super.count = Swap(uint32_t(blobs.size()));
1148 put(output, &super, sizeof(super));
1149
1150 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1151
1152 _foreach (blob, blobs) {
1153 BlobIndex index;
1154 index.type = Swap(blob.first);
1155 index.offset = Swap(uint32_t(offset));
1156 put(output, &index, sizeof(index));
1157 offset += blob.second.size();
1158 }
1159
1160 _foreach (blob, blobs)
1161 put(output, blob.second.data(), blob.second.size());
1162
1163 return offset;
1164 }
1165
1166 #ifndef LDID_NOSMIME
1167 class Buffer {
1168 private:
1169 BIO *bio_;
1170
1171 public:
1172 Buffer(BIO *bio) :
1173 bio_(bio)
1174 {
1175 _assert(bio_ != NULL);
1176 }
1177
1178 Buffer() :
1179 bio_(BIO_new(BIO_s_mem()))
1180 {
1181 }
1182
1183 Buffer(const char *data, size_t size) :
1184 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1185 {
1186 }
1187
1188 Buffer(const std::string &data) :
1189 Buffer(data.data(), data.size())
1190 {
1191 }
1192
1193 Buffer(PKCS7 *pkcs) :
1194 Buffer()
1195 {
1196 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1197 }
1198
1199 ~Buffer() {
1200 BIO_free_all(bio_);
1201 }
1202
1203 operator BIO *() const {
1204 return bio_;
1205 }
1206
1207 explicit operator std::string() const {
1208 char *data;
1209 auto size(BIO_get_mem_data(bio_, &data));
1210 return std::string(data, size);
1211 }
1212 };
1213
1214 class Stuff {
1215 private:
1216 PKCS12 *value_;
1217 EVP_PKEY *key_;
1218 X509 *cert_;
1219 STACK_OF(X509) *ca_;
1220
1221 public:
1222 Stuff(BIO *bio) :
1223 value_(d2i_PKCS12_bio(bio, NULL)),
1224 ca_(NULL)
1225 {
1226 _assert(value_ != NULL);
1227 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1228 _assert(key_ != NULL);
1229 _assert(cert_ != NULL);
1230 }
1231
1232 Stuff(const std::string &data) :
1233 Stuff(Buffer(data))
1234 {
1235 }
1236
1237 ~Stuff() {
1238 sk_X509_pop_free(ca_, X509_free);
1239 X509_free(cert_);
1240 EVP_PKEY_free(key_);
1241 PKCS12_free(value_);
1242 }
1243
1244 operator PKCS12 *() const {
1245 return value_;
1246 }
1247
1248 operator EVP_PKEY *() const {
1249 return key_;
1250 }
1251
1252 operator X509 *() const {
1253 return cert_;
1254 }
1255
1256 operator STACK_OF(X509) *() const {
1257 return ca_;
1258 }
1259 };
1260
1261 class Signature {
1262 private:
1263 PKCS7 *value_;
1264
1265 public:
1266 Signature(const Stuff &stuff, const Buffer &data) :
1267 value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
1268 {
1269 _assert(value_ != NULL);
1270 }
1271
1272 ~Signature() {
1273 PKCS7_free(value_);
1274 }
1275
1276 operator PKCS7 *() const {
1277 return value_;
1278 }
1279 };
1280 #endif
1281
1282 class NullBuffer :
1283 public std::streambuf
1284 {
1285 public:
1286 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1287 return size;
1288 }
1289
1290 virtual int_type overflow(int_type next) {
1291 return next;
1292 }
1293 };
1294
1295 class HashBuffer :
1296 public std::streambuf
1297 {
1298 private:
1299 std::vector<char> &hash_;
1300 LDID_SHA1_CTX context_;
1301
1302 public:
1303 HashBuffer(std::vector<char> &hash) :
1304 hash_(hash)
1305 {
1306 LDID_SHA1_Init(&context_);
1307 }
1308
1309 ~HashBuffer() {
1310 hash_.resize(LDID_SHA1_DIGEST_LENGTH);
1311 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.data()), &context_);
1312 }
1313
1314 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1315 LDID_SHA1_Update(&context_, data, size);
1316 return size;
1317 }
1318
1319 virtual int_type overflow(int_type next) {
1320 if (next == traits_type::eof())
1321 return sync();
1322 char value(next);
1323 xsputn(&value, 1);
1324 return next;
1325 }
1326 };
1327
1328 class HashProxy :
1329 public HashBuffer
1330 {
1331 private:
1332 std::streambuf &buffer_;
1333
1334 public:
1335 HashProxy(std::vector<char> &hash, std::streambuf &buffer) :
1336 HashBuffer(hash),
1337 buffer_(buffer)
1338 {
1339 }
1340
1341 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1342 _assert(HashBuffer::xsputn(data, size) == size);
1343 return buffer_.sputn(data, size);
1344 }
1345 };
1346
1347 #ifndef LDID_NOTOOLS
1348 static bool Starts(const std::string &lhs, const std::string &rhs) {
1349 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1350 }
1351
1352 class Split {
1353 public:
1354 std::string dir;
1355 std::string base;
1356
1357 Split(const std::string &path) {
1358 size_t slash(path.rfind('/'));
1359 if (slash == std::string::npos)
1360 base = path;
1361 else {
1362 dir = path.substr(0, slash + 1);
1363 base = path.substr(slash + 1);
1364 }
1365 }
1366 };
1367
1368 static void mkdir_p(const std::string &path) {
1369 if (path.empty())
1370 return;
1371 #ifdef __WIN32__
1372 if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
1373 return;
1374 #else
1375 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1376 return;
1377 #endif
1378 auto slash(path.rfind('/', path.size() - 1));
1379 if (slash == std::string::npos)
1380 return;
1381 mkdir_p(path.substr(0, slash));
1382 }
1383
1384 static std::string Temporary(std::filebuf &file, const Split &split) {
1385 std::string temp(split.dir + ".ldid." + split.base);
1386 mkdir_p(split.dir);
1387 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1388 return temp;
1389 }
1390
1391 static void Commit(const std::string &path, const std::string &temp) {
1392 struct stat info;
1393 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
1394 #ifndef __WIN32__
1395 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1396 #endif
1397 _syscall(chmod(temp.c_str(), info.st_mode));
1398 }
1399
1400 _syscall(rename(temp.c_str(), path.c_str()));
1401 }
1402 #endif
1403
1404 namespace ldid {
1405
1406 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) {
1407 Allocate(idata, isize, output, fun([&](size_t size) -> size_t {
1408 size_t alloc(sizeof(struct SuperBlob));
1409
1410 uint32_t special(0);
1411
1412 special = std::max(special, CSSLOT_REQUIREMENTS);
1413 alloc += sizeof(struct BlobIndex);
1414 alloc += 0xc;
1415
1416 if (!entitlements.empty()) {
1417 special = std::max(special, CSSLOT_ENTITLEMENTS);
1418 alloc += sizeof(struct BlobIndex);
1419 alloc += sizeof(struct Blob);
1420 alloc += entitlements.size();
1421 }
1422
1423 special = std::max(special, CSSLOT_CODEDIRECTORY);
1424 alloc += sizeof(struct BlobIndex);
1425 alloc += sizeof(struct Blob);
1426 alloc += sizeof(struct CodeDirectory);
1427 alloc += identifier.size() + 1;
1428
1429 if (!key.empty()) {
1430 alloc += sizeof(struct BlobIndex);
1431 alloc += sizeof(struct Blob);
1432 // XXX: this is just a "sufficiently large number"
1433 alloc += 0x3000;
1434 }
1435
1436 _foreach (slot, slots)
1437 special = std::max(special, slot.first);
1438
1439 uint32_t normal((size + PageSize_ - 1) / PageSize_);
1440 alloc = Align(alloc + (special + normal) * LDID_SHA1_DIGEST_LENGTH, 16);
1441 return alloc;
1442 }), fun([&](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1443 Blobs blobs;
1444
1445 if (true) {
1446 std::stringbuf data;
1447
1448 Blobs requirements;
1449 put(data, CSMAGIC_REQUIREMENTS, requirements);
1450
1451 insert(blobs, CSSLOT_REQUIREMENTS, data);
1452 }
1453
1454 if (!entitlements.empty()) {
1455 std::stringbuf data;
1456 put(data, entitlements.data(), entitlements.size());
1457 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
1458 }
1459
1460 if (true) {
1461 std::stringbuf data;
1462
1463 uint32_t special(0);
1464 _foreach (blob, blobs)
1465 special = std::max(special, blob.first);
1466 _foreach (slot, slots)
1467 special = std::max(special, slot.first);
1468 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
1469
1470 CodeDirectory directory;
1471 directory.version = Swap(uint32_t(0x00020001));
1472 directory.flags = Swap(uint32_t(0));
1473 directory.hashOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory) + identifier.size() + 1 + LDID_SHA1_DIGEST_LENGTH * special));
1474 directory.identOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory)));
1475 directory.nSpecialSlots = Swap(special);
1476 directory.codeLimit = Swap(uint32_t(limit));
1477 directory.nCodeSlots = Swap(normal);
1478 directory.hashSize = LDID_SHA1_DIGEST_LENGTH;
1479 directory.hashType = CS_HASHTYPE_SHA1;
1480 directory.spare1 = 0x00;
1481 directory.pageSize = PageShift_;
1482 directory.spare2 = Swap(uint32_t(0));
1483 put(data, &directory, sizeof(directory));
1484
1485 put(data, identifier.c_str(), identifier.size() + 1);
1486
1487 uint8_t storage[special + normal][LDID_SHA1_DIGEST_LENGTH];
1488 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = storage + special;
1489
1490 memset(storage, 0, sizeof(*storage) * special);
1491
1492 _foreach (blob, blobs) {
1493 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1494 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
1495 }
1496
1497 _foreach (slot, slots) {
1498 _assert(sizeof(*hashes) == slot.second.size());
1499 memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
1500 }
1501
1502 if (normal != 1)
1503 for (size_t i = 0; i != normal - 1; ++i)
1504 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
1505 if (normal != 0)
1506 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
1507
1508 put(data, storage, sizeof(storage));
1509
1510 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
1511 }
1512
1513 #ifndef LDID_NOSMIME
1514 if (!key.empty()) {
1515 std::stringbuf data;
1516 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1517
1518 Stuff stuff(key);
1519 Buffer bio(sign);
1520
1521 Signature signature(stuff, sign);
1522 Buffer result(signature);
1523 std::string value(result);
1524 put(data, value.data(), value.size());
1525
1526 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1527 }
1528 #endif
1529
1530 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
1531 }));
1532 }
1533
1534 #ifndef LDID_NOTOOLS
1535 static void Unsign(void *idata, size_t isize, std::streambuf &output) {
1536 Allocate(idata, isize, output, fun([](size_t size) -> size_t {
1537 return 0;
1538 }), fun([](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1539 return 0;
1540 }));
1541 }
1542
1543 std::string DiskFolder::Path(const std::string &path) {
1544 return path_ + "/" + path;
1545 }
1546
1547 DiskFolder::DiskFolder(const std::string &path) :
1548 path_(path)
1549 {
1550 }
1551
1552 DiskFolder::~DiskFolder() {
1553 if (!std::uncaught_exception())
1554 for (const auto &commit : commit_)
1555 Commit(commit.first, commit.second);
1556 }
1557
1558 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) {
1559 std::string path(Path(root) + base);
1560
1561 DIR *dir(opendir(path.c_str()));
1562 _assert(dir != NULL);
1563 _scope({ _syscall(closedir(dir)); });
1564
1565 while (auto child = readdir(dir)) {
1566 std::string name(child->d_name);
1567 if (name == "." || name == "..")
1568 continue;
1569 if (Starts(name, ".ldid."))
1570 continue;
1571
1572 bool directory;
1573
1574 #ifdef __WIN32__
1575 struct stat info;
1576 _syscall(stat(path.c_str(), &info));
1577 if (false);
1578 else if (S_ISDIR(info.st_mode))
1579 directory = true;
1580 else if (S_ISREG(info.st_mode))
1581 directory = false;
1582 else
1583 _assert_(false, "st_mode=%x", info.st_mode);
1584 #else
1585 switch (child->d_type) {
1586 case DT_DIR:
1587 directory = true;
1588 break;
1589 case DT_REG:
1590 directory = false;
1591 break;
1592 default:
1593 _assert_(false, "d_type=%u", child->d_type);
1594 }
1595 #endif
1596
1597 if (directory)
1598 Find(root, base + name + "/", code);
1599 else
1600 code(base + name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1601 std::string access(root + base + name);
1602 _assert_(Open(access, fun([&](std::streambuf &data) {
1603 NullBuffer save;
1604 code(data, save);
1605 })), "open(): %s", access.c_str());
1606 }));
1607 }
1608 }
1609
1610 void DiskFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1611 std::filebuf save;
1612 auto from(Path(path));
1613 commit_[from] = Temporary(save, from);
1614 code(save);
1615 }
1616
1617 bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1618 std::filebuf data;
1619 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
1620 if (result == NULL)
1621 return false;
1622 _assert(result == &data);
1623 code(data);
1624 return true;
1625 }
1626
1627 void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
1628 Find(path, "", code);
1629 }
1630 #endif
1631
1632 SubFolder::SubFolder(Folder &parent, const std::string &path) :
1633 parent_(parent),
1634 path_(path)
1635 {
1636 }
1637
1638 void SubFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1639 return parent_.Save(path_ + path, code);
1640 }
1641
1642 bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1643 return parent_.Open(path_ + path, code);
1644 }
1645
1646 void SubFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1647 return parent_.Find(path_ + path, code);
1648 }
1649
1650 UnionFolder::UnionFolder(Folder &parent) :
1651 parent_(parent)
1652 {
1653 }
1654
1655 void UnionFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1656 return parent_.Save(path, code);
1657 }
1658
1659 bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1660 auto file(files_.find(path));
1661 if (file == files_.end())
1662 return parent_.Open(path, code);
1663
1664 auto &data(file->second);
1665 data.pubseekpos(0, std::ios::in);
1666 code(data);
1667 return true;
1668 }
1669
1670 void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1671 parent_.Find(path, fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &save) {
1672 if (files_.find(name) == files_.end())
1673 code(name, save);
1674 }));
1675
1676 for (auto &file : files_)
1677 code(file.first, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1678 parent_.Save(file.first, fun([&](std::streambuf &save) {
1679 file.second.pubseekpos(0, std::ios::in);
1680 code(file.second, save);
1681 }));
1682 }));
1683 }
1684
1685 #ifndef LDID_NOTOOLS
1686 static size_t copy(std::streambuf &source, std::streambuf &target) {
1687 size_t total(0);
1688 for (;;) {
1689 char data[4096];
1690 size_t writ(source.sgetn(data, sizeof(data)));
1691 if (writ == 0)
1692 break;
1693 _assert(target.sputn(data, writ) == writ);
1694 total += writ;
1695 }
1696 return total;
1697 }
1698
1699 #ifndef LDID_NOPLIST
1700 static plist_t plist(const std::string &data) {
1701 plist_t plist(NULL);
1702 if (Starts(data, "bplist00"))
1703 plist_from_bin(data.data(), data.size(), &plist);
1704 else
1705 plist_from_xml(data.data(), data.size(), &plist);
1706 _assert(plist != NULL);
1707 return plist;
1708 }
1709
1710 static void plist_d(std::streambuf &buffer, const Functor<void (plist_t)> &code) {
1711 std::stringbuf data;
1712 copy(buffer, data);
1713 auto node(plist(data.str()));
1714 _scope({ plist_free(node); });
1715 _assert(plist_get_node_type(node) == PLIST_DICT);
1716 code(node);
1717 }
1718
1719 static std::string plist_s(plist_t node) {
1720 _assert(node != NULL);
1721 _assert(plist_get_node_type(node) == PLIST_STRING);
1722 char *data;
1723 plist_get_string_val(node, &data);
1724 _scope({ free(data); });
1725 return data;
1726 }
1727 #endif
1728
1729 enum Mode {
1730 NoMode,
1731 OptionalMode,
1732 OmitMode,
1733 NestedMode,
1734 TopMode,
1735 };
1736
1737 class Expression {
1738 private:
1739 regex_t regex_;
1740
1741 public:
1742 Expression(const std::string &code) {
1743 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()");
1744 }
1745
1746 ~Expression() {
1747 regfree(&regex_);
1748 }
1749
1750 bool operator ()(const std::string &data) const {
1751 auto value(regexec(&regex_, data.c_str(), 0, NULL, 0));
1752 if (value == REG_NOMATCH)
1753 return false;
1754 _assert_(value == 0, "regexec()");
1755 return true;
1756 }
1757 };
1758
1759 struct Rule {
1760 unsigned weight_;
1761 Mode mode_;
1762 std::string code_;
1763
1764 mutable std::auto_ptr<Expression> regex_;
1765
1766 Rule(unsigned weight, Mode mode, const std::string &code) :
1767 weight_(weight),
1768 mode_(mode),
1769 code_(code)
1770 {
1771 }
1772
1773 Rule(const Rule &rhs) :
1774 weight_(rhs.weight_),
1775 mode_(rhs.mode_),
1776 code_(rhs.code_)
1777 {
1778 }
1779
1780 void Compile() const {
1781 regex_.reset(new Expression(code_));
1782 }
1783
1784 bool operator ()(const std::string &data) const {
1785 _assert(regex_.get() != NULL);
1786 return (*regex_)(data);
1787 }
1788
1789 bool operator <(const Rule &rhs) const {
1790 if (weight_ > rhs.weight_)
1791 return true;
1792 if (weight_ < rhs.weight_)
1793 return false;
1794 return mode_ > rhs.mode_;
1795 }
1796 };
1797
1798 struct RuleCode {
1799 bool operator ()(const Rule *lhs, const Rule *rhs) const {
1800 return lhs->code_ < rhs->code_;
1801 }
1802 };
1803
1804 #ifndef LDID_NOPLIST
1805 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) {
1806 std::string executable;
1807 std::string identifier;
1808
1809 static const std::string info("Info.plist");
1810
1811 _assert_(folder.Open(info, fun([&](std::streambuf &buffer) {
1812 plist_d(buffer, fun([&](plist_t node) {
1813 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
1814 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
1815 }));
1816 })), "open(): Info.plist");
1817
1818 std::map<std::string, std::multiset<Rule>> versions;
1819
1820 auto &rules1(versions[""]);
1821 auto &rules2(versions["2"]);
1822
1823 static const std::string signature("_CodeSignature/CodeResources");
1824
1825 folder.Open(signature, fun([&](std::streambuf &buffer) {
1826 plist_d(buffer, fun([&](plist_t node) {
1827 // XXX: maybe attempt to preserve existing rules
1828 }));
1829 }));
1830
1831 if (true) {
1832 rules1.insert(Rule{1, NoMode, "^"});
1833 rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1834 rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1835 rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1836 rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1837 rules1.insert(Rule{1, NoMode, "^version.plist$"});
1838 }
1839
1840 if (true) {
1841 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
1842 rules2.insert(Rule{20, NoMode, "^"});
1843 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
1844 rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1845 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1846 rules2.insert(Rule{1, NoMode, "^.*"});
1847 rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1848 rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1849 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
1850 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
1851 rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1852 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
1853 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
1854 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
1855 }
1856
1857 std::map<std::string, std::vector<char>> local;
1858
1859 static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1860
1861 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1862 if (!nested(name))
1863 return;
1864 auto bundle(root + Split(name).dir);
1865 SubFolder subfolder(folder, bundle);
1866 Bundle(bundle, subfolder, key, local, "");
1867 }));
1868
1869 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1870 if (name == executable || name == signature)
1871 return;
1872
1873 auto &hash(local[name]);
1874 if (!hash.empty())
1875 return;
1876
1877 code(fun([&](std::streambuf &data, std::streambuf &save) {
1878 HashProxy proxy(hash, save);
1879 copy(data, proxy);
1880 }));
1881
1882 _assert(hash.size() == LDID_SHA1_DIGEST_LENGTH);
1883 }));
1884
1885 auto plist(plist_new_dict());
1886 _scope({ plist_free(plist); });
1887
1888 for (const auto &version : versions) {
1889 auto files(plist_new_dict());
1890 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
1891
1892 for (const auto &rule : version.second)
1893 rule.Compile();
1894
1895 for (const auto &hash : local)
1896 for (const auto &rule : version.second)
1897 if (rule(hash.first)) {
1898 if (rule.mode_ == NoMode)
1899 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(hash.second.data(), hash.second.size()));
1900 else if (rule.mode_ == OptionalMode) {
1901 auto entry(plist_new_dict());
1902 plist_dict_set_item(entry, "hash", plist_new_data(hash.second.data(), hash.second.size()));
1903 plist_dict_set_item(entry, "optional", plist_new_bool(true));
1904 plist_dict_set_item(files, hash.first.c_str(), entry);
1905 }
1906
1907 break;
1908 }
1909 }
1910
1911 for (const auto &version : versions) {
1912 auto rules(plist_new_dict());
1913 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
1914
1915 std::multiset<const Rule *, RuleCode> ordered;
1916 for (const auto &rule : version.second)
1917 ordered.insert(&rule);
1918
1919 for (const auto &rule : ordered)
1920 if (rule->weight_ == 1 && rule->mode_ == NoMode)
1921 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
1922 else {
1923 auto entry(plist_new_dict());
1924 plist_dict_set_item(rules, rule->code_.c_str(), entry);
1925
1926 switch (rule->mode_) {
1927 case NoMode:
1928 break;
1929 case OmitMode:
1930 plist_dict_set_item(entry, "omit", plist_new_bool(true));
1931 break;
1932 case OptionalMode:
1933 plist_dict_set_item(entry, "optional", plist_new_bool(true));
1934 break;
1935 case NestedMode:
1936 plist_dict_set_item(entry, "nested", plist_new_bool(true));
1937 break;
1938 case TopMode:
1939 plist_dict_set_item(entry, "top", plist_new_bool(true));
1940 break;
1941 }
1942
1943 if (rule->weight_ >= 10000)
1944 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
1945 else if (rule->weight_ != 1)
1946 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
1947 }
1948 }
1949
1950 folder.Save(signature, fun([&](std::streambuf &save) {
1951 HashProxy proxy(local[signature], save);
1952 char *xml(NULL);
1953 uint32_t size;
1954 plist_to_xml(plist, &xml, &size);
1955 _scope({ free(xml); });
1956 put(proxy, xml, size);
1957 }));
1958
1959 folder.Open(executable, fun([&](std::streambuf &buffer) {
1960 // XXX: this is a miserable fail
1961 std::stringbuf temp;
1962 copy(buffer, temp);
1963 auto data(temp.str());
1964
1965 folder.Save(executable, fun([&](std::streambuf &save) {
1966 Slots slots;
1967 slots[1] = local.at(info);
1968 slots[3] = local.at(signature);
1969
1970 HashProxy proxy(local[executable], save);
1971 Sign(data.data(), data.size(), proxy, identifier, entitlements, key, slots);
1972 }));
1973 }));
1974
1975 for (const auto &hash : local)
1976 remote[root + hash.first] = hash.second;
1977
1978 return executable;
1979 }
1980 #endif
1981
1982 #endif
1983 }
1984
1985 #ifndef LDID_NOTOOLS
1986 int main(int argc, char *argv[]) {
1987 #ifndef LDID_NOSMIME
1988 OpenSSL_add_all_algorithms();
1989 #endif
1990
1991 union {
1992 uint16_t word;
1993 uint8_t byte[2];
1994 } endian = {1};
1995
1996 little_ = endian.byte[0];
1997
1998 bool flag_r(false);
1999 bool flag_e(false);
2000
2001 #ifndef LDID_NOFLAGT
2002 bool flag_T(false);
2003 #endif
2004
2005 bool flag_S(false);
2006 bool flag_s(false);
2007
2008 bool flag_D(false);
2009
2010 bool flag_A(false);
2011 bool flag_a(false);
2012
2013 bool flag_u(false);
2014
2015 uint32_t flag_CPUType(_not(uint32_t));
2016 uint32_t flag_CPUSubtype(_not(uint32_t));
2017
2018 const char *flag_I(NULL);
2019
2020 #ifndef LDID_NOFLAGT
2021 bool timeh(false);
2022 uint32_t timev(0);
2023 #endif
2024
2025 Map entitlements;
2026 Map key;
2027 ldid::Slots slots;
2028
2029 std::vector<std::string> files;
2030
2031 if (argc == 1) {
2032 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
2033 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
2034 fprintf(stderr, " %s -S cat\n", argv[0]);
2035 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
2036 exit(0);
2037 }
2038
2039 for (int argi(1); argi != argc; ++argi)
2040 if (argv[argi][0] != '-')
2041 files.push_back(argv[argi]);
2042 else switch (argv[argi][1]) {
2043 case 'r':
2044 _assert(!flag_s);
2045 _assert(!flag_S);
2046 flag_r = true;
2047 break;
2048
2049 case 'e': flag_e = true; break;
2050
2051 case 'E': {
2052 const char *slot = argv[argi] + 2;
2053 const char *colon = strchr(slot, ':');
2054 _assert(colon != NULL);
2055 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
2056 char *arge;
2057 unsigned number(strtoul(slot, &arge, 0));
2058 _assert(arge == colon);
2059 sha1(slots[number], file.data(), file.size());
2060 } break;
2061
2062 case 'D': flag_D = true; break;
2063
2064 case 'a': flag_a = true; break;
2065
2066 case 'A':
2067 _assert(!flag_A);
2068 flag_A = true;
2069 if (argv[argi][2] != '\0') {
2070 const char *cpu = argv[argi] + 2;
2071 const char *colon = strchr(cpu, ':');
2072 _assert(colon != NULL);
2073 char *arge;
2074 flag_CPUType = strtoul(cpu, &arge, 0);
2075 _assert(arge == colon);
2076 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2077 _assert(arge == argv[argi] + strlen(argv[argi]));
2078 }
2079 break;
2080
2081 case 's':
2082 _assert(!flag_r);
2083 _assert(!flag_S);
2084 flag_s = true;
2085 break;
2086
2087 case 'S':
2088 _assert(!flag_r);
2089 _assert(!flag_s);
2090 flag_S = true;
2091 if (argv[argi][2] != '\0') {
2092 const char *xml = argv[argi] + 2;
2093 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2094 }
2095 break;
2096
2097 case 'K':
2098 if (argv[argi][2] != '\0')
2099 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
2100 break;
2101
2102 #ifndef LDID_NOFLAGT
2103 case 'T': {
2104 flag_T = true;
2105 if (argv[argi][2] == '-')
2106 timeh = true;
2107 else {
2108 char *arge;
2109 timev = strtoul(argv[argi] + 2, &arge, 0);
2110 _assert(arge == argv[argi] + strlen(argv[argi]));
2111 }
2112 } break;
2113 #endif
2114
2115 case 'u': {
2116 flag_u = true;
2117 } break;
2118
2119 case 'I': {
2120 flag_I = argv[argi] + 2;
2121 } break;
2122
2123 default:
2124 goto usage;
2125 break;
2126 }
2127
2128 _assert(flag_S || key.empty());
2129 _assert(flag_S || flag_I == NULL);
2130
2131 if (files.empty()) usage: {
2132 exit(0);
2133 }
2134
2135 size_t filei(0), filee(0);
2136 _foreach (file, files) try {
2137 std::string path(file);
2138
2139 struct stat info;
2140 _syscall(stat(path.c_str(), &info));
2141
2142 if (S_ISDIR(info.st_mode)) {
2143 #ifndef LDID_NOPLIST
2144 _assert(!flag_r);
2145 ldid::DiskFolder folder(path);
2146 std::map<std::string, std::vector<char>> hashes;
2147 path += "/" + Bundle("", folder, key, hashes, entitlements);
2148 #else
2149 _assert(false);
2150 #endif
2151 } else if (flag_S || flag_r) {
2152 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
2153
2154 std::filebuf output;
2155 Split split(path);
2156 auto temp(Temporary(output, split));
2157
2158 if (flag_r)
2159 ldid::Unsign(input.data(), input.size(), output);
2160 else {
2161 std::string identifier(flag_I ?: split.base.c_str());
2162 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
2163 }
2164
2165 Commit(path, temp);
2166 }
2167
2168 bool modify(false);
2169 #ifndef LDID_NOFLAGT
2170 if (flag_T)
2171 modify = true;
2172 #endif
2173 if (flag_s)
2174 modify = true;
2175
2176 Map mapping(path, modify);
2177 FatHeader fat_header(mapping.data(), mapping.size());
2178
2179 _foreach (mach_header, fat_header.GetMachHeaders()) {
2180 struct linkedit_data_command *signature(NULL);
2181 struct encryption_info_command *encryption(NULL);
2182
2183 if (flag_A) {
2184 if (mach_header.GetCPUType() != flag_CPUType)
2185 continue;
2186 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2187 continue;
2188 }
2189
2190 if (flag_a)
2191 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2192
2193 _foreach (load_command, mach_header.GetLoadCommands()) {
2194 uint32_t cmd(mach_header.Swap(load_command->cmd));
2195
2196 if (false);
2197 else if (cmd == LC_CODE_SIGNATURE)
2198 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
2199 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
2200 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
2201 else if (cmd == LC_LOAD_DYLIB) {
2202 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2203 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
2204
2205 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2206 if (flag_u) {
2207 Version version;
2208 version.value = mach_header.Swap(dylib_command->dylib.current_version);
2209 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
2210 }
2211 }
2212 }
2213 #ifndef LDID_NOFLAGT
2214 else if (cmd == LC_ID_DYLIB) {
2215 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2216
2217 if (flag_T) {
2218 uint32_t timed;
2219
2220 if (!timeh)
2221 timed = timev;
2222 else {
2223 dylib_command->dylib.timestamp = 0;
2224 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2225 }
2226
2227 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2228 }
2229 }
2230 #endif
2231 }
2232
2233 if (flag_D) {
2234 _assert(encryption != NULL);
2235 encryption->cryptid = mach_header.Swap(0);
2236 }
2237
2238 if (flag_e) {
2239 _assert(signature != NULL);
2240
2241 uint32_t data = mach_header.Swap(signature->dataoff);
2242
2243 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2244 uint8_t *blob = top + data;
2245 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2246
2247 for (size_t index(0); index != Swap(super->count); ++index)
2248 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2249 uint32_t begin = Swap(super->index[index].offset);
2250 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
2251 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
2252 }
2253 }
2254
2255 if (flag_s) {
2256 _assert(signature != NULL);
2257
2258 uint32_t data = mach_header.Swap(signature->dataoff);
2259
2260 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2261 uint8_t *blob = top + data;
2262 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2263
2264 for (size_t index(0); index != Swap(super->count); ++index)
2265 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2266 uint32_t begin = Swap(super->index[index].offset);
2267 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
2268
2269 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
2270 uint32_t pages = Swap(directory->nCodeSlots);
2271
2272 if (pages != 1)
2273 for (size_t i = 0; i != pages - 1; ++i)
2274 sha1(hashes[i], top + PageSize_ * i, PageSize_);
2275 if (pages != 0)
2276 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
2277 }
2278 }
2279 }
2280
2281 ++filei;
2282 } catch (const char *) {
2283 ++filee;
2284 ++filei;
2285 }
2286
2287 return filee;
2288 }
2289 #endif