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