]> git.saurik.com Git - ldid.git/blob - ldid.cpp
02e2675df369fa76f8a601d1af0fcd50e0b22a8d
[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) {
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 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 &)> &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);
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 Functor<void (std::streambuf &)> &code) {
1719 return parent_.Save(path_ + path, code);
1720 }
1721
1722 bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &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 (std::streambuf &, const Functor<void (std::streambuf &, std::streambuf &)> &)> &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 parent_.Save(file, fun([&](std::streambuf &data) {
1741 save(data, code);
1742 }));
1743 }));
1744 }
1745
1746 UnionFolder::UnionFolder(Folder &parent) :
1747 parent_(parent)
1748 {
1749 }
1750
1751 void UnionFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1752 return parent_.Save(Map(path), code);
1753 }
1754
1755 bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1756 auto file(resets_.find(path));
1757 if (file == resets_.end())
1758 return parent_.Open(Map(path), code);
1759
1760 auto &data(file->second);
1761 data.pubseekpos(0, std::ios::in);
1762 code(data);
1763 return true;
1764 }
1765
1766 void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1767 parent_.Find(path, fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &save) {
1768 if (deletes_.find(path + name) == deletes_.end())
1769 code(name, save);
1770 }));
1771
1772 for (auto &reset : resets_)
1773 Map(path, code, reset.first, fun([&](std::streambuf &save, const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1774 reset.second.pubseekpos(0, std::ios::in);
1775 code(reset.second, save);
1776 }));
1777
1778 for (auto &remap : remaps_)
1779 Map(path, code, remap.first, fun([&](std::streambuf &save, const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1780 parent_.Open(remap.second, fun([&](std::streambuf &data) {
1781 code(data, save);
1782 }));
1783 }));
1784 }
1785
1786 #ifndef LDID_NOTOOLS
1787 static size_t copy(std::streambuf &source, std::streambuf &target) {
1788 size_t total(0);
1789 for (;;) {
1790 char data[4096];
1791 size_t writ(source.sgetn(data, sizeof(data)));
1792 if (writ == 0)
1793 break;
1794 _assert(target.sputn(data, writ) == writ);
1795 total += writ;
1796 }
1797 return total;
1798 }
1799
1800 #ifndef LDID_NOPLIST
1801 static plist_t plist(const std::string &data) {
1802 plist_t plist(NULL);
1803 if (Starts(data, "bplist00"))
1804 plist_from_bin(data.data(), data.size(), &plist);
1805 else
1806 plist_from_xml(data.data(), data.size(), &plist);
1807 _assert(plist != NULL);
1808 return plist;
1809 }
1810
1811 static void plist_d(std::streambuf &buffer, const Functor<void (plist_t)> &code) {
1812 std::stringbuf data;
1813 copy(buffer, data);
1814 auto node(plist(data.str()));
1815 _scope({ plist_free(node); });
1816 _assert(plist_get_node_type(node) == PLIST_DICT);
1817 code(node);
1818 }
1819
1820 static std::string plist_s(plist_t node) {
1821 _assert(node != NULL);
1822 _assert(plist_get_node_type(node) == PLIST_STRING);
1823 char *data;
1824 plist_get_string_val(node, &data);
1825 _scope({ free(data); });
1826 return data;
1827 }
1828 #endif
1829
1830 enum Mode {
1831 NoMode,
1832 OptionalMode,
1833 OmitMode,
1834 NestedMode,
1835 TopMode,
1836 };
1837
1838 class Expression {
1839 private:
1840 regex_t regex_;
1841
1842 public:
1843 Expression(const std::string &code) {
1844 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()");
1845 }
1846
1847 ~Expression() {
1848 regfree(&regex_);
1849 }
1850
1851 bool operator ()(const std::string &data) const {
1852 auto value(regexec(&regex_, data.c_str(), 0, NULL, 0));
1853 if (value == REG_NOMATCH)
1854 return false;
1855 _assert_(value == 0, "regexec()");
1856 return true;
1857 }
1858 };
1859
1860 struct Rule {
1861 unsigned weight_;
1862 Mode mode_;
1863 std::string code_;
1864
1865 mutable std::auto_ptr<Expression> regex_;
1866
1867 Rule(unsigned weight, Mode mode, const std::string &code) :
1868 weight_(weight),
1869 mode_(mode),
1870 code_(code)
1871 {
1872 }
1873
1874 Rule(const Rule &rhs) :
1875 weight_(rhs.weight_),
1876 mode_(rhs.mode_),
1877 code_(rhs.code_)
1878 {
1879 }
1880
1881 void Compile() const {
1882 regex_.reset(new Expression(code_));
1883 }
1884
1885 bool operator ()(const std::string &data) const {
1886 _assert(regex_.get() != NULL);
1887 return (*regex_)(data);
1888 }
1889
1890 bool operator <(const Rule &rhs) const {
1891 if (weight_ > rhs.weight_)
1892 return true;
1893 if (weight_ < rhs.weight_)
1894 return false;
1895 return mode_ > rhs.mode_;
1896 }
1897 };
1898
1899 struct RuleCode {
1900 bool operator ()(const Rule *lhs, const Rule *rhs) const {
1901 return lhs->code_ < rhs->code_;
1902 }
1903 };
1904
1905 #ifndef LDID_NOPLIST
1906 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) {
1907 // XXX: this is a miserable fail
1908 std::stringbuf temp;
1909 copy(buffer, temp);
1910 auto data(temp.str());
1911
1912 HashProxy proxy(hash, save);
1913 Sign(data.data(), data.size(), proxy, identifier, entitlements, key, slots);
1914 }
1915
1916 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) {
1917 std::string executable;
1918 std::string identifier;
1919
1920 static const std::string info("Info.plist");
1921
1922 _assert_(folder.Open(info, fun([&](std::streambuf &buffer) {
1923 plist_d(buffer, fun([&](plist_t node) {
1924 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
1925 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
1926 }));
1927 })), "open(): Info.plist");
1928
1929 static const std::string directory("_CodeSignature/");
1930 static const std::string signature(directory + "CodeResources");
1931
1932 std::map<std::string, std::multiset<Rule>> versions;
1933
1934 auto &rules1(versions[""]);
1935 auto &rules2(versions["2"]);
1936
1937 folder.Open(signature, fun([&](std::streambuf &buffer) {
1938 plist_d(buffer, fun([&](plist_t node) {
1939 // XXX: maybe attempt to preserve existing rules
1940 }));
1941 }));
1942
1943 if (true) {
1944 rules1.insert(Rule{1, NoMode, "^"});
1945 rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1946 rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1947 rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1948 rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1949 rules1.insert(Rule{1, NoMode, "^version.plist$"});
1950 }
1951
1952 if (true) {
1953 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
1954 rules2.insert(Rule{20, NoMode, "^"});
1955 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
1956 rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1957 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1958 rules2.insert(Rule{1, NoMode, "^.*"});
1959 rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1960 rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1961 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
1962 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
1963 rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1964 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
1965 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
1966 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
1967 }
1968
1969 std::map<std::string, std::vector<char>> local;
1970
1971 static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
1972 static Expression dylib("^[^/]*\\.dylib$");
1973
1974 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1975 if (!nested(name))
1976 return;
1977 auto bundle(root + Split(name).dir);
1978 SubFolder subfolder(folder, bundle);
1979 Bundle(bundle, subfolder, key, local, "");
1980 }));
1981
1982 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1983 // BundleDiskRep::adjustResources -> builder.addExclusion
1984 if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
1985 return;
1986
1987 auto &hash(local[name]);
1988 if (!hash.empty())
1989 return;
1990
1991 code(fun([&](std::streambuf &data, std::streambuf &save) {
1992 if (dylib(name)) {
1993 Slots slots;
1994 Sign(data, hash, save, identifier, "", key, slots);
1995 } else {
1996 HashProxy proxy(hash, save);
1997 copy(data, proxy);
1998 }
1999 }));
2000
2001 _assert(hash.size() == LDID_SHA1_DIGEST_LENGTH);
2002 }));
2003
2004 auto plist(plist_new_dict());
2005 _scope({ plist_free(plist); });
2006
2007 for (const auto &version : versions) {
2008 auto files(plist_new_dict());
2009 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
2010
2011 for (const auto &rule : version.second)
2012 rule.Compile();
2013
2014 for (const auto &hash : local)
2015 for (const auto &rule : version.second)
2016 if (rule(hash.first)) {
2017 if (rule.mode_ == NoMode)
2018 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(hash.second.data(), hash.second.size()));
2019 else if (rule.mode_ == OptionalMode) {
2020 auto entry(plist_new_dict());
2021 plist_dict_set_item(entry, "hash", plist_new_data(hash.second.data(), hash.second.size()));
2022 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2023 plist_dict_set_item(files, hash.first.c_str(), entry);
2024 }
2025
2026 break;
2027 }
2028 }
2029
2030 for (const auto &version : versions) {
2031 auto rules(plist_new_dict());
2032 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
2033
2034 std::multiset<const Rule *, RuleCode> ordered;
2035 for (const auto &rule : version.second)
2036 ordered.insert(&rule);
2037
2038 for (const auto &rule : ordered)
2039 if (rule->weight_ == 1 && rule->mode_ == NoMode)
2040 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
2041 else {
2042 auto entry(plist_new_dict());
2043 plist_dict_set_item(rules, rule->code_.c_str(), entry);
2044
2045 switch (rule->mode_) {
2046 case NoMode:
2047 break;
2048 case OmitMode:
2049 plist_dict_set_item(entry, "omit", plist_new_bool(true));
2050 break;
2051 case OptionalMode:
2052 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2053 break;
2054 case NestedMode:
2055 plist_dict_set_item(entry, "nested", plist_new_bool(true));
2056 break;
2057 case TopMode:
2058 plist_dict_set_item(entry, "top", plist_new_bool(true));
2059 break;
2060 }
2061
2062 if (rule->weight_ >= 10000)
2063 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
2064 else if (rule->weight_ != 1)
2065 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
2066 }
2067 }
2068
2069 folder.Save(signature, fun([&](std::streambuf &save) {
2070 HashProxy proxy(local[signature], save);
2071 char *xml(NULL);
2072 uint32_t size;
2073 plist_to_xml(plist, &xml, &size);
2074 _scope({ free(xml); });
2075 put(proxy, xml, size);
2076 }));
2077
2078 folder.Open(executable, fun([&](std::streambuf &buffer) {
2079 folder.Save(executable, fun([&](std::streambuf &save) {
2080 Slots slots;
2081 slots[1] = local.at(info);
2082 slots[3] = local.at(signature);
2083 Sign(buffer, local[executable], save, identifier, entitlements, key, slots);
2084 }));
2085 }));
2086
2087 for (const auto &hash : local)
2088 remote[root + hash.first] = hash.second;
2089
2090 return executable;
2091 }
2092 #endif
2093
2094 #endif
2095 }
2096
2097 #ifndef LDID_NOTOOLS
2098 int main(int argc, char *argv[]) {
2099 #ifndef LDID_NOSMIME
2100 OpenSSL_add_all_algorithms();
2101 #endif
2102
2103 union {
2104 uint16_t word;
2105 uint8_t byte[2];
2106 } endian = {1};
2107
2108 little_ = endian.byte[0];
2109
2110 bool flag_r(false);
2111 bool flag_e(false);
2112
2113 #ifndef LDID_NOFLAGT
2114 bool flag_T(false);
2115 #endif
2116
2117 bool flag_S(false);
2118 bool flag_s(false);
2119
2120 bool flag_D(false);
2121
2122 bool flag_A(false);
2123 bool flag_a(false);
2124
2125 bool flag_u(false);
2126
2127 uint32_t flag_CPUType(_not(uint32_t));
2128 uint32_t flag_CPUSubtype(_not(uint32_t));
2129
2130 const char *flag_I(NULL);
2131
2132 #ifndef LDID_NOFLAGT
2133 bool timeh(false);
2134 uint32_t timev(0);
2135 #endif
2136
2137 Map entitlements;
2138 Map key;
2139 ldid::Slots slots;
2140
2141 std::vector<std::string> files;
2142
2143 if (argc == 1) {
2144 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
2145 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
2146 fprintf(stderr, " %s -S cat\n", argv[0]);
2147 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
2148 exit(0);
2149 }
2150
2151 for (int argi(1); argi != argc; ++argi)
2152 if (argv[argi][0] != '-')
2153 files.push_back(argv[argi]);
2154 else switch (argv[argi][1]) {
2155 case 'r':
2156 _assert(!flag_s);
2157 _assert(!flag_S);
2158 flag_r = true;
2159 break;
2160
2161 case 'e': flag_e = true; break;
2162
2163 case 'E': {
2164 const char *slot = argv[argi] + 2;
2165 const char *colon = strchr(slot, ':');
2166 _assert(colon != NULL);
2167 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
2168 char *arge;
2169 unsigned number(strtoul(slot, &arge, 0));
2170 _assert(arge == colon);
2171 sha1(slots[number], file.data(), file.size());
2172 } break;
2173
2174 case 'D': flag_D = true; break;
2175
2176 case 'a': flag_a = true; break;
2177
2178 case 'A':
2179 _assert(!flag_A);
2180 flag_A = true;
2181 if (argv[argi][2] != '\0') {
2182 const char *cpu = argv[argi] + 2;
2183 const char *colon = strchr(cpu, ':');
2184 _assert(colon != NULL);
2185 char *arge;
2186 flag_CPUType = strtoul(cpu, &arge, 0);
2187 _assert(arge == colon);
2188 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2189 _assert(arge == argv[argi] + strlen(argv[argi]));
2190 }
2191 break;
2192
2193 case 's':
2194 _assert(!flag_r);
2195 _assert(!flag_S);
2196 flag_s = true;
2197 break;
2198
2199 case 'S':
2200 _assert(!flag_r);
2201 _assert(!flag_s);
2202 flag_S = true;
2203 if (argv[argi][2] != '\0') {
2204 const char *xml = argv[argi] + 2;
2205 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
2206 }
2207 break;
2208
2209 case 'K':
2210 if (argv[argi][2] != '\0')
2211 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
2212 break;
2213
2214 #ifndef LDID_NOFLAGT
2215 case 'T': {
2216 flag_T = true;
2217 if (argv[argi][2] == '-')
2218 timeh = true;
2219 else {
2220 char *arge;
2221 timev = strtoul(argv[argi] + 2, &arge, 0);
2222 _assert(arge == argv[argi] + strlen(argv[argi]));
2223 }
2224 } break;
2225 #endif
2226
2227 case 'u': {
2228 flag_u = true;
2229 } break;
2230
2231 case 'I': {
2232 flag_I = argv[argi] + 2;
2233 } break;
2234
2235 default:
2236 goto usage;
2237 break;
2238 }
2239
2240 _assert(flag_S || key.empty());
2241 _assert(flag_S || flag_I == NULL);
2242
2243 if (files.empty()) usage: {
2244 exit(0);
2245 }
2246
2247 size_t filei(0), filee(0);
2248 _foreach (file, files) try {
2249 std::string path(file);
2250
2251 struct stat info;
2252 _syscall(stat(path.c_str(), &info));
2253
2254 if (S_ISDIR(info.st_mode)) {
2255 #ifndef LDID_NOPLIST
2256 _assert(!flag_r);
2257 ldid::DiskFolder folder(path);
2258 std::map<std::string, std::vector<char>> hashes;
2259 path += "/" + Bundle("", folder, key, hashes, entitlements);
2260 #else
2261 _assert(false);
2262 #endif
2263 } else if (flag_S || flag_r) {
2264 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
2265
2266 std::filebuf output;
2267 Split split(path);
2268 auto temp(Temporary(output, split));
2269
2270 if (flag_r)
2271 ldid::Unsign(input.data(), input.size(), output);
2272 else {
2273 std::string identifier(flag_I ?: split.base.c_str());
2274 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
2275 }
2276
2277 Commit(path, temp);
2278 }
2279
2280 bool modify(false);
2281 #ifndef LDID_NOFLAGT
2282 if (flag_T)
2283 modify = true;
2284 #endif
2285 if (flag_s)
2286 modify = true;
2287
2288 Map mapping(path, modify);
2289 FatHeader fat_header(mapping.data(), mapping.size());
2290
2291 _foreach (mach_header, fat_header.GetMachHeaders()) {
2292 struct linkedit_data_command *signature(NULL);
2293 struct encryption_info_command *encryption(NULL);
2294
2295 if (flag_A) {
2296 if (mach_header.GetCPUType() != flag_CPUType)
2297 continue;
2298 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2299 continue;
2300 }
2301
2302 if (flag_a)
2303 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2304
2305 _foreach (load_command, mach_header.GetLoadCommands()) {
2306 uint32_t cmd(mach_header.Swap(load_command->cmd));
2307
2308 if (false);
2309 else if (cmd == LC_CODE_SIGNATURE)
2310 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
2311 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
2312 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
2313 else if (cmd == LC_LOAD_DYLIB) {
2314 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2315 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
2316
2317 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2318 if (flag_u) {
2319 Version version;
2320 version.value = mach_header.Swap(dylib_command->dylib.current_version);
2321 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
2322 }
2323 }
2324 }
2325 #ifndef LDID_NOFLAGT
2326 else if (cmd == LC_ID_DYLIB) {
2327 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2328
2329 if (flag_T) {
2330 uint32_t timed;
2331
2332 if (!timeh)
2333 timed = timev;
2334 else {
2335 dylib_command->dylib.timestamp = 0;
2336 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2337 }
2338
2339 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2340 }
2341 }
2342 #endif
2343 }
2344
2345 if (flag_D) {
2346 _assert(encryption != NULL);
2347 encryption->cryptid = mach_header.Swap(0);
2348 }
2349
2350 if (flag_e) {
2351 _assert(signature != NULL);
2352
2353 uint32_t data = mach_header.Swap(signature->dataoff);
2354
2355 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2356 uint8_t *blob = top + data;
2357 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2358
2359 for (size_t index(0); index != Swap(super->count); ++index)
2360 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2361 uint32_t begin = Swap(super->index[index].offset);
2362 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
2363 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
2364 }
2365 }
2366
2367 if (flag_s) {
2368 _assert(signature != NULL);
2369
2370 uint32_t data = mach_header.Swap(signature->dataoff);
2371
2372 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2373 uint8_t *blob = top + data;
2374 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
2375
2376 for (size_t index(0); index != Swap(super->count); ++index)
2377 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2378 uint32_t begin = Swap(super->index[index].offset);
2379 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
2380
2381 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
2382 uint32_t pages = Swap(directory->nCodeSlots);
2383
2384 if (pages != 1)
2385 for (size_t i = 0; i != pages - 1; ++i)
2386 sha1(hashes[i], top + PageSize_ * i, PageSize_);
2387 if (pages != 0)
2388 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
2389 }
2390 }
2391 }
2392
2393 ++filei;
2394 } catch (const char *) {
2395 ++filee;
2396 ++filei;
2397 }
2398
2399 return filee;
2400 }
2401 #endif