]> git.saurik.com Git - ldid.git/blame - ldid.cpp
Use std::string more often, and factor out Commit.
[ldid.git] / ldid.cpp
CommitLineData
ab113d22 1/* ldid - (Mach-O) Link-Loader Identity Editor
16efdde5 2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
a362a82f
JF
3*/
4
dd6c06ed
JF
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
e0524446
JF
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
dd6c06ed 11
e0524446
JF
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
dd6c06ed
JF
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
e0524446
JF
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19**/
20/* }}} */
a362a82f 21
fa59c178
JF
22#include <cstdio>
23#include <cstdlib>
a362a82f 24#include <cstring>
4d4682ef
JF
25#include <fstream>
26#include <map>
27#include <sstream>
a362a82f
JF
28#include <string>
29#include <vector>
30
fa59c178 31#include <errno.h>
dede6121 32#include <fcntl.h>
fa59c178
JF
33#include <stdbool.h>
34#include <stdint.h>
a7f01a65 35#include <unistd.h>
dede6121
JF
36
37#include <sys/mman.h>
38#include <sys/stat.h>
39
30c64adb
JF
40#include <openssl/err.h>
41#include <openssl/pem.h>
42#include <openssl/pkcs7.h>
43#include <openssl/pkcs12.h>
a50bb1be
JF
44#include <openssl/sha.h>
45
15babeef
JF
46#include <plist/plist.h>
47
a0c715e9
JF
48#include "ldid.hpp"
49
fa59c178
JF
50#define _assert___(line) \
51 #line
52#define _assert__(line) \
53 _assert___(line)
fa59c178 54
eff987d2 55#define _assert_(expr, format, ...) \
fa59c178 56 do if (!(expr)) { \
eff987d2
JF
57 fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \
58 throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \
fa59c178
JF
59 } while (false)
60
eff987d2
JF
61#define _assert(expr) \
62 _assert_(expr, "%s", #expr)
63
fa59c178
JF
64#define _syscall(expr) ({ \
65 __typeof__(expr) _value; \
66 do if ((long) (_value = (expr)) != -1) \
67 break; \
68 else switch (errno) { \
69 case EINTR: \
70 continue; \
71 default: \
eff987d2 72 _assert_(false, "errno=%u", errno); \
fa59c178
JF
73 } while (true); \
74 _value; \
75})
76
77#define _trace() \
78 fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__)
79
80#define _not(type) \
81 ((type) ~ (type) 0)
82
83#define _packed \
84 __attribute__((packed))
85
86template <typename Type_>
87struct Iterator_ {
88 typedef typename Type_::const_iterator Result;
89};
90
91#define _foreach(item, list) \
92 for (bool _stop(true); _stop; ) \
93 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
94 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
95 for (bool _suck(true); _suck; _suck = false) \
96 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
97
a362a82f
JF
98struct fat_header {
99 uint32_t magic;
100 uint32_t nfat_arch;
c05d9758 101} _packed;
a362a82f
JF
102
103#define FAT_MAGIC 0xcafebabe
104#define FAT_CIGAM 0xbebafeca
105
106struct fat_arch {
107 uint32_t cputype;
108 uint32_t cpusubtype;
109 uint32_t offset;
110 uint32_t size;
111 uint32_t align;
c05d9758 112} _packed;
a362a82f
JF
113
114struct mach_header {
115 uint32_t magic;
116 uint32_t cputype;
04802ab1 117 uint32_t cpusubtype;
a362a82f
JF
118 uint32_t filetype;
119 uint32_t ncmds;
120 uint32_t sizeofcmds;
121 uint32_t flags;
c05d9758 122} _packed;
a362a82f 123
fdb119ef 124#define MH_MAGIC 0xfeedface
a362a82f
JF
125#define MH_CIGAM 0xcefaedfe
126
3cbc6463
JF
127#define MH_MAGIC_64 0xfeedfacf
128#define MH_CIGAM_64 0xcffaedfe
129
82813bde
JF
130#define MH_DYLDLINK 0x4
131
4a864785 132#define MH_OBJECT 0x1
efd6cd4a
JF
133#define MH_EXECUTE 0x2
134#define MH_DYLIB 0x6
135#define MH_BUNDLE 0x8
136#define MH_DYLIB_STUB 0x9
a362a82f
JF
137
138struct load_command {
139 uint32_t cmd;
140 uint32_t cmdsize;
c05d9758 141} _packed;
a362a82f 142
4a57e66c
JF
143#define LC_REQ_DYLD uint32_t(0x80000000)
144
145#define LC_SEGMENT uint32_t(0x01)
146#define LC_SYMTAB uint32_t(0x02)
147#define LC_DYSYMTAB uint32_t(0x0b)
148#define LC_LOAD_DYLIB uint32_t(0x0c)
149#define LC_ID_DYLIB uint32_t(0x0d)
289ccbbc 150#define LC_SEGMENT_64 uint32_t(0x19)
4a57e66c
JF
151#define LC_UUID uint32_t(0x1b)
152#define LC_CODE_SIGNATURE uint32_t(0x1d)
153#define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
154#define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
c0cc1574 155#define LC_ENCRYPTION_INFO uint32_t(0x21)
4a57e66c
JF
156#define LC_DYLD_INFO uint32_t(0x22)
157#define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
843aea8c 158#define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
a362a82f
JF
159
160struct dylib {
161 uint32_t name;
162 uint32_t timestamp;
163 uint32_t current_version;
164 uint32_t compatibility_version;
c05d9758 165} _packed;
a362a82f
JF
166
167struct dylib_command {
168 uint32_t cmd;
169 uint32_t cmdsize;
170 struct dylib dylib;
c05d9758 171} _packed;
a362a82f
JF
172
173struct uuid_command {
174 uint32_t cmd;
175 uint32_t cmdsize;
176 uint8_t uuid[16];
c05d9758 177} _packed;
a362a82f 178
20e7eb29
JF
179struct symtab_command {
180 uint32_t cmd;
181 uint32_t cmdsize;
182 uint32_t symoff;
183 uint32_t nsyms;
184 uint32_t stroff;
185 uint32_t strsize;
186} _packed;
187
4a57e66c
JF
188struct dyld_info_command {
189 uint32_t cmd;
190 uint32_t cmdsize;
191 uint32_t rebase_off;
192 uint32_t rebase_size;
193 uint32_t bind_off;
194 uint32_t bind_size;
195 uint32_t weak_bind_off;
196 uint32_t weak_bind_size;
197 uint32_t lazy_bind_off;
198 uint32_t lazy_bind_size;
199 uint32_t export_off;
200 uint32_t export_size;
201} _packed;
202
203struct dysymtab_command {
204 uint32_t cmd;
205 uint32_t cmdsize;
206 uint32_t ilocalsym;
207 uint32_t nlocalsym;
208 uint32_t iextdefsym;
209 uint32_t nextdefsym;
210 uint32_t iundefsym;
211 uint32_t nundefsym;
212 uint32_t tocoff;
213 uint32_t ntoc;
214 uint32_t modtaboff;
215 uint32_t nmodtab;
216 uint32_t extrefsymoff;
217 uint32_t nextrefsyms;
218 uint32_t indirectsymoff;
219 uint32_t nindirectsyms;
220 uint32_t extreloff;
221 uint32_t nextrel;
222 uint32_t locreloff;
223 uint32_t nlocrel;
224} _packed;
225
226struct dylib_table_of_contents {
227 uint32_t symbol_index;
228 uint32_t module_index;
229} _packed;
230
231struct dylib_module {
232 uint32_t module_name;
233 uint32_t iextdefsym;
234 uint32_t nextdefsym;
235 uint32_t irefsym;
236 uint32_t nrefsym;
237 uint32_t ilocalsym;
238 uint32_t nlocalsym;
239 uint32_t iextrel;
240 uint32_t nextrel;
241 uint32_t iinit_iterm;
242 uint32_t ninit_nterm;
243 uint32_t objc_module_info_addr;
244 uint32_t objc_module_info_size;
245} _packed;
246
247struct dylib_reference {
248 uint32_t isym:24;
249 uint32_t flags:8;
250} _packed;
251
252struct relocation_info {
253 int32_t r_address;
254 uint32_t r_symbolnum:24;
255 uint32_t r_pcrel:1;
256 uint32_t r_length:2;
257 uint32_t r_extern:1;
258 uint32_t r_type:4;
259} _packed;
260
261struct nlist {
262 union {
263 char *n_name;
264 int32_t n_strx;
265 } n_un;
266
267 uint8_t n_type;
268 uint8_t n_sect;
269 uint8_t n_desc;
270 uint32_t n_value;
271} _packed;
272
6e83315b
JF
273struct segment_command {
274 uint32_t cmd;
275 uint32_t cmdsize;
276 char segname[16];
277 uint32_t vmaddr;
278 uint32_t vmsize;
279 uint32_t fileoff;
280 uint32_t filesize;
281 uint32_t maxprot;
282 uint32_t initprot;
283 uint32_t nsects;
284 uint32_t flags;
429e34a5 285} _packed;
6e83315b 286
289ccbbc
JF
287struct segment_command_64 {
288 uint32_t cmd;
289 uint32_t cmdsize;
290 char segname[16];
291 uint64_t vmaddr;
292 uint64_t vmsize;
293 uint64_t fileoff;
294 uint64_t filesize;
295 uint32_t maxprot;
296 uint32_t initprot;
297 uint32_t nsects;
298 uint32_t flags;
429e34a5 299} _packed;
289ccbbc 300
6e83315b
JF
301struct section {
302 char sectname[16];
303 char segname[16];
304 uint32_t addr;
305 uint32_t size;
306 uint32_t offset;
307 uint32_t align;
308 uint32_t reloff;
309 uint32_t nreloc;
310 uint32_t flags;
311 uint32_t reserved1;
312 uint32_t reserved2;
429e34a5 313} _packed;
6e83315b 314
289ccbbc
JF
315struct section_64 {
316 char sectname[16];
317 char segname[16];
318 uint64_t addr;
319 uint64_t size;
320 uint32_t offset;
321 uint32_t align;
322 uint32_t reloff;
323 uint32_t nreloc;
324 uint32_t flags;
325 uint32_t reserved1;
326 uint32_t reserved2;
429e34a5 327} _packed;
289ccbbc 328
fdb119ef
JF
329struct linkedit_data_command {
330 uint32_t cmd;
331 uint32_t cmdsize;
332 uint32_t dataoff;
333 uint32_t datasize;
c05d9758 334} _packed;
fdb119ef 335
c0cc1574
JF
336struct encryption_info_command {
337 uint32_t cmd;
338 uint32_t cmdsize;
339 uint32_t cryptoff;
340 uint32_t cryptsize;
341 uint32_t cryptid;
342} _packed;
343
4a864785
JF
344#define BIND_OPCODE_MASK 0xf0
345#define BIND_IMMEDIATE_MASK 0x0f
346#define BIND_OPCODE_DONE 0x00
347#define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
348#define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
349#define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
350#define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
351#define BIND_OPCODE_SET_TYPE_IMM 0x50
352#define BIND_OPCODE_SET_ADDEND_SLEB 0x60
353#define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
354#define BIND_OPCODE_ADD_ADDR_ULEB 0x80
355#define BIND_OPCODE_DO_BIND 0x90
356#define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
357#define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
358#define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
359
4d4682ef
JF
360inline void get(std::streambuf &stream, void *data, size_t size) {
361 _assert(stream.sgetn(static_cast<char *>(data), size) == size);
362}
363
364inline void put(std::streambuf &stream, const void *data, size_t size) {
365 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
366}
367
368inline void pad(std::streambuf &stream, size_t size) {
369 char padding[size];
370 memset(padding, 0, size);
371 put(stream, padding, size);
372}
373
4374152f
JF
374template <typename Type_>
375Type_ Align(Type_ value, size_t align) {
376 value += align - 1;
377 value /= align;
378 value *= align;
379 return value;
380}
381
b9652d6e
JF
382static const uint8_t PageShift_(0x0c);
383static const uint32_t PageSize_(1 << PageShift_);
384
f65c321b 385static inline uint16_t Swap_(uint16_t value) {
fdb119ef
JF
386 return
387 ((value >> 8) & 0x00ff) |
388 ((value << 8) & 0xff00);
389}
390
f65c321b 391static inline uint32_t Swap_(uint32_t value) {
fdb119ef
JF
392 value = ((value >> 8) & 0x00ff00ff) |
393 ((value << 8) & 0xff00ff00);
394 value = ((value >> 16) & 0x0000ffff) |
395 ((value << 16) & 0xffff0000);
396 return value;
397}
398
f65c321b 399static inline uint64_t Swap_(uint64_t value) {
4374152f
JF
400 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
401 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
402 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
403 return value;
404}
405
f65c321b 406static inline int16_t Swap_(int16_t value) {
fdb119ef
JF
407 return Swap_(static_cast<uint16_t>(value));
408}
409
f65c321b 410static inline int32_t Swap_(int32_t value) {
fdb119ef
JF
411 return Swap_(static_cast<uint32_t>(value));
412}
413
f65c321b 414static inline int64_t Swap_(int64_t value) {
4374152f
JF
415 return Swap_(static_cast<uint64_t>(value));
416}
417
f65c321b 418static bool little_(true);
5525a5a7 419
f65c321b 420static inline uint16_t Swap(uint16_t value) {
5525a5a7 421 return little_ ? Swap_(value) : value;
fdb119ef
JF
422}
423
f65c321b 424static inline uint32_t Swap(uint32_t value) {
5525a5a7 425 return little_ ? Swap_(value) : value;
fdb119ef
JF
426}
427
f65c321b 428static inline uint64_t Swap(uint64_t value) {
4374152f
JF
429 return little_ ? Swap_(value) : value;
430}
431
f65c321b 432static inline int16_t Swap(int16_t value) {
fdb119ef
JF
433 return Swap(static_cast<uint16_t>(value));
434}
435
f65c321b 436static inline int32_t Swap(int32_t value) {
fdb119ef
JF
437 return Swap(static_cast<uint32_t>(value));
438}
439
f65c321b 440static inline int64_t Swap(int64_t value) {
4374152f
JF
441 return Swap(static_cast<uint64_t>(value));
442}
443
6e83315b
JF
444template <typename Target_>
445class Pointer;
446
4d4682ef 447class Swapped {
0a033524 448 protected:
a362a82f
JF
449 bool swapped_;
450
4d4682ef 451 Swapped() :
0a033524
JF
452 swapped_(false)
453 {
454 }
455
4d4682ef
JF
456 public:
457 Swapped(bool swapped) :
458 swapped_(swapped)
459 {
a362a82f
JF
460 }
461
4d4682ef
JF
462 template <typename Type_>
463 Type_ Swap(Type_ value) const {
4374152f
JF
464 return swapped_ ? Swap_(value) : value;
465 }
4d4682ef 466};
4374152f 467
4d4682ef
JF
468class Data :
469 public Swapped
470{
471 private:
472 void *base_;
473 size_t size_;
a362a82f 474
4d4682ef
JF
475 public:
476 Data(void *base, size_t size) :
477 base_(base),
478 size_(size)
479 {
4374152f
JF
480 }
481
0a033524
JF
482 void *GetBase() const {
483 return base_;
484 }
a362a82f 485
0a033524
JF
486 size_t GetSize() const {
487 return size_;
488 }
489};
a362a82f 490
0a033524
JF
491class MachHeader :
492 public Data
493{
494 private:
495 bool bits64_;
496
497 struct mach_header *mach_header_;
498 struct load_command *load_command_;
499
500 public:
501 MachHeader(void *base, size_t size) :
502 Data(base, size)
503 {
504 mach_header_ = (mach_header *) base;
a362a82f 505
3cbc6463
JF
506 switch (Swap(mach_header_->magic)) {
507 case MH_CIGAM:
508 swapped_ = !swapped_;
509 case MH_MAGIC:
510 bits64_ = false;
511 break;
512
513 case MH_CIGAM_64:
514 swapped_ = !swapped_;
515 case MH_MAGIC_64:
516 bits64_ = true;
517 break;
518
519 default:
520 _assert(false);
521 }
522
523 void *post = mach_header_ + 1;
524 if (bits64_)
525 post = (uint32_t *) post + 1;
526 load_command_ = (struct load_command *) post;
a362a82f
JF
527
528 _assert(
529 Swap(mach_header_->filetype) == MH_EXECUTE ||
530 Swap(mach_header_->filetype) == MH_DYLIB ||
531 Swap(mach_header_->filetype) == MH_BUNDLE
532 );
533 }
534
4d4682ef
JF
535 bool Bits64() const {
536 return bits64_;
537 }
538
afbb7c8e
JF
539 struct mach_header *operator ->() const {
540 return mach_header_;
541 }
542
4374152f
JF
543 operator struct mach_header *() const {
544 return mach_header_;
545 }
546
04802ab1
JF
547 uint32_t GetCPUType() const {
548 return Swap(mach_header_->cputype);
549 }
550
4374152f 551 uint32_t GetCPUSubtype() const {
04802ab1
JF
552 return Swap(mach_header_->cpusubtype) & 0xff;
553 }
554
4374152f
JF
555 struct load_command *GetLoadCommand() const {
556 return load_command_;
557 }
558
0a033524 559 std::vector<struct load_command *> GetLoadCommands() const {
a362a82f
JF
560 std::vector<struct load_command *> load_commands;
561
3cbc6463 562 struct load_command *load_command = load_command_;
a362a82f
JF
563 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
564 load_commands.push_back(load_command);
565 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
566 }
567
568 return load_commands;
569 }
6e83315b 570
6f340f51 571 std::vector<segment_command *> GetSegments(const char *segment_name) const {
6e83315b
JF
572 std::vector<struct segment_command *> segment_commands;
573
289ccbbc 574 _foreach (load_command, GetLoadCommands()) {
0a033524
JF
575 if (Swap(load_command->cmd) == LC_SEGMENT) {
576 segment_command *segment_command = reinterpret_cast<struct segment_command *>(load_command);
6e83315b
JF
577 if (strncmp(segment_command->segname, segment_name, 16) == 0)
578 segment_commands.push_back(segment_command);
579 }
289ccbbc
JF
580 }
581
582 return segment_commands;
583 }
584
4374152f 585 std::vector<segment_command_64 *> GetSegments64(const char *segment_name) const {
289ccbbc
JF
586 std::vector<struct segment_command_64 *> segment_commands;
587
588 _foreach (load_command, GetLoadCommands()) {
589 if (Swap(load_command->cmd) == LC_SEGMENT_64) {
590 segment_command_64 *segment_command = reinterpret_cast<struct segment_command_64 *>(load_command);
591 if (strncmp(segment_command->segname, segment_name, 16) == 0)
592 segment_commands.push_back(segment_command);
593 }
594 }
6e83315b
JF
595
596 return segment_commands;
597 }
598
6f340f51 599 std::vector<section *> GetSections(const char *segment_name, const char *section_name) const {
6e83315b
JF
600 std::vector<section *> sections;
601
602 _foreach (segment, GetSegments(segment_name)) {
0a033524 603 section *section = (struct section *) (segment + 1);
6e83315b
JF
604
605 uint32_t sect;
0a033524 606 for (sect = 0; sect != Swap(segment->nsects); ++sect) {
6e83315b
JF
607 if (strncmp(section->sectname, section_name, 16) == 0)
608 sections.push_back(section);
609 ++section;
610 }
611 }
612
613 return sections;
614 }
615
616 template <typename Target_>
0a033524 617 Pointer<Target_> GetPointer(uint32_t address, const char *segment_name = NULL) const {
6e83315b
JF
618 load_command *load_command = (struct load_command *) (mach_header_ + 1);
619 uint32_t cmd;
620
621 for (cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
622 if (Swap(load_command->cmd) == LC_SEGMENT) {
623 segment_command *segment_command = (struct segment_command *) load_command;
624 if (segment_name != NULL && strncmp(segment_command->segname, segment_name, 16) != 0)
625 goto next_command;
626
627 section *sections = (struct section *) (segment_command + 1);
628
629 uint32_t sect;
630 for (sect = 0; sect != Swap(segment_command->nsects); ++sect) {
631 section *section = &sections[sect];
632 //printf("%s %u %p %p %u\n", segment_command->segname, sect, address, section->addr, section->size);
633 if (address >= Swap(section->addr) && address < Swap(section->addr) + Swap(section->size)) {
634 //printf("0x%.8x %s\n", address, segment_command->segname);
635 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(address - Swap(section->addr) + Swap(section->offset) + (char *) mach_header_));
636 }
637 }
638 }
639
640 next_command:
641 load_command = (struct load_command *) ((char *) load_command + Swap(load_command->cmdsize));
642 }
643
644 return Pointer<Target_>(this);
645 }
646
647 template <typename Target_>
648 Pointer<Target_> GetOffset(uint32_t offset) {
649 return Pointer<Target_>(this, reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_));
650 }
651};
652
289ccbbc
JF
653class FatMachHeader :
654 public MachHeader
655{
656 private:
657 fat_arch *fat_arch_;
658
659 public:
660 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
661 MachHeader(base, size),
662 fat_arch_(fat_arch)
663 {
664 }
665
666 fat_arch *GetFatArch() const {
667 return fat_arch_;
668 }
669};
670
0a033524
JF
671class FatHeader :
672 public Data
673{
674 private:
675 fat_header *fat_header_;
289ccbbc 676 std::vector<FatMachHeader> mach_headers_;
0a033524
JF
677
678 public:
679 FatHeader(void *base, size_t size) :
680 Data(base, size)
681 {
682 fat_header_ = reinterpret_cast<struct fat_header *>(base);
683
684 if (Swap(fat_header_->magic) == FAT_CIGAM) {
685 swapped_ = !swapped_;
686 goto fat;
687 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
688 fat_header_ = NULL;
289ccbbc 689 mach_headers_.push_back(FatMachHeader(base, size, NULL));
0a033524
JF
690 } else fat: {
691 size_t fat_narch = Swap(fat_header_->nfat_arch);
692 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
693 size_t arch;
694 for (arch = 0; arch != fat_narch; ++arch) {
695 uint32_t arch_offset = Swap(fat_arch->offset);
696 uint32_t arch_size = Swap(fat_arch->size);
289ccbbc 697 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
0a033524
JF
698 ++fat_arch;
699 }
700 }
701 }
702
289ccbbc 703 std::vector<FatMachHeader> &GetMachHeaders() {
0a033524
JF
704 return mach_headers_;
705 }
20e7eb29
JF
706
707 bool IsFat() const {
708 return fat_header_ != NULL;
709 }
6b38c173
JF
710
711 struct fat_header *operator ->() const {
712 return fat_header_;
713 }
4374152f
JF
714
715 operator struct fat_header *() const {
716 return fat_header_;
717 }
0a033524
JF
718};
719
6e83315b
JF
720template <typename Target_>
721class Pointer {
722 private:
0a033524 723 const MachHeader *framework_;
6e83315b
JF
724 const Target_ *pointer_;
725
726 public:
0a033524 727 Pointer(const MachHeader *framework = NULL, const Target_ *pointer = NULL) :
6e83315b
JF
728 framework_(framework),
729 pointer_(pointer)
730 {
731 }
732
733 operator const Target_ *() const {
734 return pointer_;
735 }
736
737 const Target_ *operator ->() const {
738 return pointer_;
739 }
740
741 Pointer<Target_> &operator ++() {
742 ++pointer_;
743 return *this;
744 }
745
746 template <typename Value_>
747 Value_ Swap(Value_ value) {
748 return framework_->Swap(value);
749 }
a362a82f
JF
750};
751
4d4682ef
JF
752#define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
753#define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
754#define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
755#define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
756#define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
757#define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
758#define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
759#define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
c05d9758 760
4d4682ef
JF
761#define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
762#define CSSLOT_INFOSLOT uint32_t(0x00001)
763#define CSSLOT_REQUIREMENTS uint32_t(0x00002)
764#define CSSLOT_RESOURCEDIR uint32_t(0x00003)
765#define CSSLOT_APPLICATION uint32_t(0x00004)
766#define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
767
768#define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
769
770#define CS_HASHTYPE_SHA1 1
fdb119ef
JF
771
772struct BlobIndex {
773 uint32_t type;
774 uint32_t offset;
c05d9758 775} _packed;
fdb119ef 776
c05d9758 777struct Blob {
fdb119ef
JF
778 uint32_t magic;
779 uint32_t length;
c05d9758
JF
780} _packed;
781
782struct SuperBlob {
783 struct Blob blob;
fdb119ef
JF
784 uint32_t count;
785 struct BlobIndex index[];
c05d9758 786} _packed;
fdb119ef
JF
787
788struct CodeDirectory {
fdb119ef
JF
789 uint32_t version;
790 uint32_t flags;
791 uint32_t hashOffset;
792 uint32_t identOffset;
793 uint32_t nSpecialSlots;
794 uint32_t nCodeSlots;
795 uint32_t codeLimit;
796 uint8_t hashSize;
797 uint8_t hashType;
798 uint8_t spare1;
799 uint8_t pageSize;
800 uint32_t spare2;
c05d9758 801} _packed;
fdb119ef 802
a362a82f
JF
803extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
804
f65c321b 805static void sha1(uint8_t *hash, const void *data, size_t size) {
4d4682ef 806 SHA1(static_cast<const uint8_t *>(data), size, hash);
fdb119ef
JF
807}
808
0a033524 809struct CodesignAllocation {
4374152f
JF
810 FatMachHeader mach_header_;
811 uint32_t offset_;
812 uint32_t size_;
4d4682ef 813 uint32_t limit_;
4374152f 814 uint32_t alloc_;
e4b7adc1 815 uint32_t align_;
4374152f 816
e0098838 817 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
4374152f
JF
818 mach_header_(mach_header),
819 offset_(offset),
820 size_(size),
4d4682ef 821 limit_(limit),
e4b7adc1
JF
822 alloc_(alloc),
823 align_(align)
0a033524
JF
824 {
825 }
826};
827
dede6121
JF
828class File {
829 private:
830 int file_;
831
832 public:
833 File() :
834 file_(-1)
835 {
836 }
837
838 ~File() {
839 if (file_ != -1)
840 _syscall(close(file_));
841 }
842
cad40c43 843 void open(const char *path, int flags) {
dede6121 844 _assert(file_ == -1);
fc7a76da 845 file_ = _syscall(::open(path, flags));
dede6121
JF
846 }
847
848 int file() const {
849 return file_;
850 }
851};
852
853class Map {
854 private:
855 File file_;
856 void *data_;
857 size_t size_;
858
859 void clear() {
860 if (data_ == NULL)
861 return;
862 _syscall(munmap(data_, size_));
863 data_ = NULL;
864 size_ = 0;
865 }
866
867 public:
868 Map() :
869 data_(NULL),
870 size_(0)
871 {
872 }
873
d4187e53 874 Map(const std::string &path, int oflag, int pflag, int mflag) :
cad40c43
JF
875 Map()
876 {
877 open(path, oflag, pflag, mflag);
878 }
879
d4187e53 880 Map(const std::string &path, bool edit) :
cad40c43
JF
881 Map()
882 {
883 open(path, edit);
dede6121
JF
884 }
885
886 ~Map() {
887 clear();
888 }
889
fac3d3e3
JF
890 bool empty() const {
891 return data_ == NULL;
892 }
893
d4187e53 894 void open(const std::string &path, int oflag, int pflag, int mflag) {
dede6121
JF
895 clear();
896
d4187e53 897 file_.open(path.c_str(), oflag);
dede6121
JF
898 int file(file_.file());
899
900 struct stat stat;
901 _syscall(fstat(file, &stat));
902 size_ = stat.st_size;
903
fc7a76da 904 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
cad40c43
JF
905 }
906
d4187e53 907 void open(const std::string &path, bool edit) {
cad40c43
JF
908 if (edit)
909 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
910 else
911 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
dede6121
JF
912 }
913
914 void *data() const {
915 return data_;
916 }
917
918 size_t size() const {
919 return size_;
920 }
f4b2df35
JF
921
922 operator std::string() const {
923 return std::string(static_cast<char *>(data_), size_);
924 }
dede6121
JF
925};
926
a0c715e9
JF
927namespace ldid {
928
ffdd1183
JF
929static 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) {
930 FatHeader source(const_cast<void *>(idata), isize);
f4b2df35
JF
931
932 size_t offset(0);
933 if (source.IsFat())
934 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
935
936 std::vector<CodesignAllocation> allocations;
937 _foreach (mach_header, source.GetMachHeaders()) {
938 struct linkedit_data_command *signature(NULL);
939 struct symtab_command *symtab(NULL);
940
941 _foreach (load_command, mach_header.GetLoadCommands()) {
942 uint32_t cmd(mach_header.Swap(load_command->cmd));
943 if (false);
944 else if (cmd == LC_CODE_SIGNATURE)
945 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
946 else if (cmd == LC_SYMTAB)
947 symtab = reinterpret_cast<struct symtab_command *>(load_command);
948 }
949
950 size_t size;
951 if (signature == NULL)
952 size = mach_header.GetSize();
953 else {
954 size = mach_header.Swap(signature->dataoff);
955 _assert(size <= mach_header.GetSize());
956 }
957
958 if (symtab != NULL) {
959 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
960 _assert(end <= size);
961 _assert(end >= size - 0x10);
962 size = end;
963 }
964
e0098838 965 size_t alloc(allocate(size));
f4b2df35
JF
966
967 auto *fat_arch(mach_header.GetFatArch());
968 uint32_t align(fat_arch == NULL ? 0 : source.Swap(fat_arch->align));
969 offset = Align(offset, 1 << align);
970
4d4682ef
JF
971 uint32_t limit(size);
972 if (alloc != 0)
973 limit = Align(limit, 0x10);
974
e0098838 975 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
f4b2df35 976 offset += size + alloc;
b9652d6e 977 offset = Align(offset, 0x10);
f4b2df35
JF
978 }
979
4d4682ef
JF
980 size_t position(0);
981
982 if (source.IsFat()) {
983 fat_header fat_header;
984 fat_header.magic = Swap(FAT_MAGIC);
985 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
986 put(output, &fat_header, sizeof(fat_header));
987 position += sizeof(fat_header);
988
989 _foreach (allocation, allocations) {
990 auto &mach_header(allocation.mach_header_);
991
992 fat_arch fat_arch;
993 fat_arch.cputype = Swap(mach_header->cputype);
994 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
995 fat_arch.offset = Swap(allocation.offset_);
996 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
997 fat_arch.align = Swap(allocation.align_);
998 put(output, &fat_arch, sizeof(fat_arch));
999 position += sizeof(fat_arch);
1000 }
f4b2df35
JF
1001 }
1002
1003 _foreach (allocation, allocations) {
4d4682ef 1004 auto &mach_header(allocation.mach_header_);
f4b2df35 1005
4d4682ef
JF
1006 pad(output, allocation.offset_ - position);
1007 position = allocation.offset_;
f4b2df35 1008
4d4682ef 1009 std::vector<std::string> commands;
f4b2df35 1010
4d4682ef
JF
1011 _foreach (load_command, mach_header.GetLoadCommands()) {
1012 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
f4b2df35 1013
a7f01a65 1014 switch (mach_header.Swap(load_command->cmd)) {
4d4682ef
JF
1015 case LC_CODE_SIGNATURE:
1016 continue;
1017 break;
1018
1019 case LC_SEGMENT: {
1020 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1021 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1022 break;
1023 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1024 segment_command->filesize = size;
b9652d6e 1025 segment_command->vmsize = Align(size, PageSize_);
4d4682ef
JF
1026 } break;
1027
1028 case LC_SEGMENT_64: {
1029 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1030 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1031 break;
1032 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1033 segment_command->filesize = size;
b9652d6e 1034 segment_command->vmsize = Align(size, PageSize_);
4d4682ef
JF
1035 } break;
1036 }
f4b2df35 1037
4d4682ef 1038 commands.push_back(copy);
f4b2df35
JF
1039 }
1040
e0098838 1041 if (allocation.alloc_ != 0) {
4d4682ef
JF
1042 linkedit_data_command signature;
1043 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1044 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1045 signature.dataoff = mach_header.Swap(allocation.limit_);
1046 signature.datasize = mach_header.Swap(allocation.alloc_);
1047 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1048 }
f4b2df35 1049
4d4682ef 1050 size_t begin(position);
f4b2df35 1051
4d4682ef
JF
1052 uint32_t after(0);
1053 _foreach(command, commands)
1054 after += command.size();
f4b2df35 1055
4d4682ef 1056 std::stringbuf altern;
f4b2df35 1057
4d4682ef
JF
1058 struct mach_header header(*mach_header);
1059 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1060 header.sizeofcmds = mach_header.Swap(after);
1061 put(output, &header, sizeof(header));
1062 put(altern, &header, sizeof(header));
1063 position += sizeof(header);
f4b2df35 1064
4d4682ef
JF
1065 if (mach_header.Bits64()) {
1066 auto pad(mach_header.Swap(uint32_t(0)));
1067 put(output, &pad, sizeof(pad));
1068 put(altern, &pad, sizeof(pad));
1069 position += sizeof(pad);
1070 }
f4b2df35 1071
4d4682ef
JF
1072 _foreach(command, commands) {
1073 put(output, command.data(), command.size());
1074 put(altern, command.data(), command.size());
1075 position += command.size();
1076 }
f4b2df35 1077
4d4682ef
JF
1078 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1079 if (before > after) {
1080 pad(output, before - after);
1081 pad(altern, before - after);
1082 position += before - after;
1083 }
f4b2df35 1084
4d4682ef 1085 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
f4b2df35 1086
4d4682ef
JF
1087 std::string overlap(altern.str());
1088 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
f4b2df35 1089
4d4682ef
JF
1090 put(output, top + (position - begin), allocation.size_ - (position - begin));
1091 position = begin + allocation.size_;
f4b2df35 1092
4d4682ef
JF
1093 pad(output, allocation.limit_ - allocation.size_);
1094 position += allocation.limit_ - allocation.size_;
f4b2df35 1095
67205335
JF
1096 size_t saved(save(output, allocation.limit_, overlap, top));
1097 if (allocation.alloc_ > saved)
1098 pad(output, allocation.alloc_ - saved);
1099 position += allocation.alloc_;
e0098838
JF
1100 }
1101}
f4b2df35 1102
a0c715e9
JF
1103}
1104
efad8a44
JF
1105typedef std::map<uint32_t, std::string> Blobs;
1106
bb591e2b
JF
1107static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1108 auto value(buffer.str());
1109 std::swap(blobs[slot], value);
1110}
1111
8f310b91
JF
1112static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1113 auto value(buffer.str());
1114 Blob blob;
1115 blob.magic = Swap(magic);
1116 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1117 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1118 std::swap(blobs[slot], value);
efad8a44
JF
1119}
1120
1121static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1122 size_t total(0);
1123 _foreach (blob, blobs)
1124 total += blob.second.size();
1125
1126 struct SuperBlob super;
1127 super.blob.magic = Swap(magic);
1128 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1129 super.count = Swap(uint32_t(blobs.size()));
1130 put(output, &super, sizeof(super));
1131
1132 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1133
1134 _foreach (blob, blobs) {
1135 BlobIndex index;
1136 index.type = Swap(blob.first);
1137 index.offset = Swap(uint32_t(offset));
1138 put(output, &index, sizeof(index));
1139 offset += blob.second.size();
1140 }
1141
1142 _foreach (blob, blobs)
1143 put(output, blob.second.data(), blob.second.size());
1144
1145 return offset;
1146}
1147
30c64adb
JF
1148class Buffer {
1149 private:
1150 BIO *bio_;
1151
1152 public:
1153 Buffer(BIO *bio) :
1154 bio_(bio)
1155 {
1156 _assert(bio_ != NULL);
1157 }
1158
1159 Buffer() :
1160 bio_(BIO_new(BIO_s_mem()))
1161 {
1162 }
1163
1164 Buffer(const char *data, size_t size) :
1165 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1166 {
1167 }
1168
1169 Buffer(const std::string &data) :
1170 Buffer(data.data(), data.size())
1171 {
1172 }
1173
1174 Buffer(PKCS7 *pkcs) :
1175 Buffer()
1176 {
1177 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1178 }
1179
1180 ~Buffer() {
1181 BIO_free_all(bio_);
1182 }
1183
1184 operator BIO *() const {
1185 return bio_;
1186 }
1187
1188 explicit operator std::string() const {
1189 char *data;
1190 auto size(BIO_get_mem_data(bio_, &data));
1191 return std::string(data, size);
1192 }
1193};
1194
1195class Stuff {
1196 private:
1197 PKCS12 *value_;
1198 EVP_PKEY *key_;
1199 X509 *cert_;
1200 STACK_OF(X509) *ca_;
1201
1202 public:
1203 Stuff(BIO *bio) :
1204 value_(d2i_PKCS12_bio(bio, NULL)),
1205 ca_(NULL)
1206 {
1207 _assert(value_ != NULL);
1208 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1209 _assert(key_ != NULL);
1210 _assert(cert_ != NULL);
1211 }
1212
1213 Stuff(const std::string &data) :
1214 Stuff(Buffer(data))
1215 {
1216 }
1217
1218 ~Stuff() {
1219 sk_X509_pop_free(ca_, X509_free);
1220 X509_free(cert_);
1221 EVP_PKEY_free(key_);
1222 PKCS12_free(value_);
1223 }
1224
1225 operator PKCS12 *() const {
1226 return value_;
1227 }
1228
1229 operator EVP_PKEY *() const {
1230 return key_;
1231 }
1232
1233 operator X509 *() const {
1234 return cert_;
1235 }
1236
1237 operator STACK_OF(X509) *() const {
1238 return ca_;
1239 }
1240};
1241
1242class Signature {
1243 private:
1244 PKCS7 *value_;
1245
1246 public:
1247 Signature(const Stuff &stuff, const Buffer &data) :
1248 value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
1249 {
1250 _assert(value_ != NULL);
1251 }
1252
1253 ~Signature() {
1254 PKCS7_free(value_);
1255 }
1256
1257 operator PKCS7 *() const {
1258 return value_;
1259 }
1260};
1261
d4187e53
JF
1262static void Commit(const std::string &path, const std::string &temp) {
1263 struct stat info;
1264 _syscall(stat(path.c_str(), &info));
1265#ifndef __WIN32__
1266 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
1267#endif
1268 _syscall(chmod(temp.c_str(), info.st_mode));
1269 _syscall(unlink(path.c_str()));
1270 _syscall(rename(temp.c_str(), path.c_str()));
1271}
1272
a0c715e9 1273namespace ldid {
e57b1f91 1274
ffdd1183 1275void 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) {
a0c715e9 1276 Allocate(idata, isize, output, fun([&](size_t size) -> size_t {
e0098838 1277 size_t alloc(sizeof(struct SuperBlob));
f4b2df35 1278
e0098838 1279 uint32_t special(0);
f4b2df35 1280
e0098838
JF
1281 special = std::max(special, CSSLOT_REQUIREMENTS);
1282 alloc += sizeof(struct BlobIndex);
1283 alloc += 0xc;
f4b2df35 1284
faa1b1f8 1285 if (!entitlements.empty()) {
e0098838
JF
1286 special = std::max(special, CSSLOT_ENTITLEMENTS);
1287 alloc += sizeof(struct BlobIndex);
1288 alloc += sizeof(struct Blob);
1289 alloc += entitlements.size();
1290 }
f4b2df35 1291
e0098838
JF
1292 special = std::max(special, CSSLOT_CODEDIRECTORY);
1293 alloc += sizeof(struct BlobIndex);
1294 alloc += sizeof(struct Blob);
1295 alloc += sizeof(struct CodeDirectory);
ffdd1183 1296 alloc += identifier.size() + 1;
f4b2df35 1297
30c64adb
JF
1298 if (!key.empty()) {
1299 alloc += sizeof(struct BlobIndex);
1300 alloc += sizeof(struct Blob);
1301 // XXX: this is just a "sufficiently large number"
1302 alloc += 0x3000;
1303 }
1304
e57b1f91
JF
1305 _foreach (slot, slots)
1306 special = std::max(special, slot.first);
1307
b9652d6e 1308 uint32_t normal((size + PageSize_ - 1) / PageSize_);
e0098838
JF
1309 alloc = Align(alloc + (special + normal) * SHA_DIGEST_LENGTH, 16);
1310 return alloc;
1311 }), fun([&](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
efad8a44 1312 Blobs blobs;
f4b2df35 1313
e0098838
JF
1314 if (true) {
1315 std::stringbuf data;
f4b2df35 1316
bb591e2b
JF
1317 Blobs requirements;
1318 put(data, CSMAGIC_REQUIREMENTS, requirements);
4d4682ef 1319
bb591e2b 1320 insert(blobs, CSSLOT_REQUIREMENTS, data);
e0098838 1321 }
4d4682ef 1322
faa1b1f8 1323 if (!entitlements.empty()) {
e0098838 1324 std::stringbuf data;
e0098838 1325 put(data, entitlements.data(), entitlements.size());
8f310b91 1326 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
e0098838
JF
1327 }
1328
1329 if (true) {
1330 std::stringbuf data;
1331
1332 uint32_t special(0);
1333 _foreach (blob, blobs)
1334 special = std::max(special, blob.first);
e57b1f91
JF
1335 _foreach (slot, slots)
1336 special = std::max(special, slot.first);
b9652d6e 1337 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
e0098838 1338
e0098838
JF
1339 CodeDirectory directory;
1340 directory.version = Swap(uint32_t(0x00020001));
1341 directory.flags = Swap(uint32_t(0));
ffdd1183 1342 directory.hashOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory) + identifier.size() + 1 + SHA_DIGEST_LENGTH * special));
8f310b91 1343 directory.identOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory)));
e0098838
JF
1344 directory.nSpecialSlots = Swap(special);
1345 directory.codeLimit = Swap(uint32_t(limit));
1346 directory.nCodeSlots = Swap(normal);
1347 directory.hashSize = SHA_DIGEST_LENGTH;
1348 directory.hashType = CS_HASHTYPE_SHA1;
1349 directory.spare1 = 0x00;
b9652d6e 1350 directory.pageSize = PageShift_;
e0098838
JF
1351 directory.spare2 = Swap(uint32_t(0));
1352 put(data, &directory, sizeof(directory));
1353
ffdd1183 1354 put(data, identifier.c_str(), identifier.size() + 1);
e0098838
JF
1355
1356 uint8_t storage[special + normal][SHA_DIGEST_LENGTH];
1357 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = storage + special;
1358
1359 memset(storage, 0, sizeof(*storage) * special);
4d4682ef
JF
1360
1361 _foreach (blob, blobs) {
e0098838
JF
1362 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1363 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
4d4682ef 1364 }
f4b2df35 1365
e57b1f91
JF
1366 _foreach (slot, slots) {
1367 _assert(sizeof(*hashes) == slot.second.size());
1368 memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
1369 }
1370
e0098838
JF
1371 if (normal != 1)
1372 for (size_t i = 0; i != normal - 1; ++i)
b9652d6e 1373 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
e0098838 1374 if (normal != 0)
b9652d6e 1375 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
f4b2df35 1376
e0098838
JF
1377 put(data, storage, sizeof(storage));
1378
8f310b91 1379 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
f4b2df35 1380 }
e0098838 1381
30c64adb
JF
1382 if (!key.empty()) {
1383 std::stringbuf data;
1384 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1385
1386 Stuff stuff(key);
1387 Buffer bio(sign);
1388
1389 Signature signature(stuff, sign);
1390 Buffer result(signature);
1391 std::string value(result);
1392 put(data, value.data(), value.size());
1393
1394 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1395 }
1396
efad8a44 1397 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
e0098838
JF
1398 }));
1399}
1400
a0c715e9
JF
1401static void Unsign(void *idata, size_t isize, std::streambuf &output) {
1402 Allocate(idata, isize, output, fun([](size_t size) -> size_t {
e0098838
JF
1403 return 0;
1404 }), fun([](std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
1405 return 0;
1406 }));
f4b2df35
JF
1407}
1408
a0c715e9
JF
1409}
1410
a7f01a65 1411int main(int argc, char *argv[]) {
30c64adb
JF
1412 OpenSSL_add_all_algorithms();
1413
5525a5a7
JF
1414 union {
1415 uint16_t word;
1416 uint8_t byte[2];
1417 } endian = {1};
1418
1419 little_ = endian.byte[0];
1420
20e7eb29 1421 bool flag_r(false);
9c83be90 1422 bool flag_e(false);
a362a82f
JF
1423
1424 bool flag_T(false);
20c5f1e8 1425
fdb119ef 1426 bool flag_S(false);
20c5f1e8 1427 bool flag_s(false);
a362a82f 1428
c0cc1574 1429 bool flag_D(false);
c0cc1574 1430
8c417842
JF
1431 bool flag_A(false);
1432 bool flag_a(false);
1433
c0cc1574
JF
1434 uint32_t flag_CPUType(_not(uint32_t));
1435 uint32_t flag_CPUSubtype(_not(uint32_t));
1436
5d7ceb5d
JF
1437 const char *flag_I(NULL);
1438
a362a82f
JF
1439 bool timeh(false);
1440 uint32_t timev(0);
1441
4d4682ef 1442 Map entitlements;
30c64adb 1443 Map key;
a0c715e9 1444 ldid::Slots slots;
c05d9758 1445
a362a82f
JF
1446 std::vector<std::string> files;
1447
a960f392
JF
1448 if (argc == 1) {
1449 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
9c83be90 1450 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
a960f392
JF
1451 fprintf(stderr, " %s -S cat\n", argv[0]);
1452 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
1453 exit(0);
1454 }
1455
a362a82f
JF
1456 for (int argi(1); argi != argc; ++argi)
1457 if (argv[argi][0] != '-')
1458 files.push_back(argv[argi]);
1459 else switch (argv[argi][1]) {
fac3d3e3
JF
1460 case 'r':
1461 _assert(!flag_s);
1462 _assert(!flag_S);
1463 flag_r = true;
1464 break;
1465
9c83be90 1466 case 'e': flag_e = true; break;
c05d9758 1467
e57b1f91
JF
1468 case 'E': {
1469 const char *slot = argv[argi] + 2;
1470 const char *colon = strchr(slot, ':');
1471 _assert(colon != NULL);
1472 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
1473 char *arge;
1474 unsigned number(strtoul(slot, &arge, 0));
1475 _assert(arge == colon);
1476 std::string &hash(slots[number]);
1477 hash.resize(SHA_DIGEST_LENGTH);
1478 sha1(reinterpret_cast<uint8_t *>(&hash[0]), file.data(), file.size());
1479 } break;
1480
c0cc1574 1481 case 'D': flag_D = true; break;
c0cc1574 1482
8c417842
JF
1483 case 'a': flag_a = true; break;
1484
1485 case 'A':
fac3d3e3 1486 _assert(!flag_A);
8c417842
JF
1487 flag_A = true;
1488 if (argv[argi][2] != '\0') {
1489 const char *cpu = argv[argi] + 2;
1490 const char *colon = strchr(cpu, ':');
1491 _assert(colon != NULL);
1492 char *arge;
1493 flag_CPUType = strtoul(cpu, &arge, 0);
1494 _assert(arge == colon);
1495 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
1496 _assert(arge == argv[argi] + strlen(argv[argi]));
1497 }
1498 break;
1499
20c5f1e8 1500 case 's':
fac3d3e3 1501 _assert(!flag_r);
20c5f1e8
JF
1502 _assert(!flag_S);
1503 flag_s = true;
1504 break;
1505
c05d9758 1506 case 'S':
fac3d3e3 1507 _assert(!flag_r);
20c5f1e8 1508 _assert(!flag_s);
c05d9758
JF
1509 flag_S = true;
1510 if (argv[argi][2] != '\0') {
1511 const char *xml = argv[argi] + 2;
4d4682ef 1512 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
c05d9758
JF
1513 }
1514 break;
a362a82f 1515
30c64adb
JF
1516 case 'K':
1517 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
1518 break;
1519
a362a82f
JF
1520 case 'T': {
1521 flag_T = true;
1522 if (argv[argi][2] == '-')
1523 timeh = true;
1524 else {
1525 char *arge;
1526 timev = strtoul(argv[argi] + 2, &arge, 0);
1527 _assert(arge == argv[argi] + strlen(argv[argi]));
1528 }
1529 } break;
1530
5d7ceb5d
JF
1531 case 'I': {
1532 flag_I = argv[argi] + 2;
1533 } break;
1534
a362a82f
JF
1535 default:
1536 goto usage;
1537 break;
1538 }
1539
fac3d3e3
JF
1540 _assert(flag_S || key.empty());
1541 _assert(flag_S || flag_I == NULL);
f4b2df35 1542
a362a82f
JF
1543 if (files.empty()) usage: {
1544 exit(0);
1545 }
1546
1547 size_t filei(0), filee(0);
1548 _foreach (file, files) try {
d4187e53 1549 std::string path(file);
5d7ceb5d 1550
cad40c43 1551 if (flag_S || flag_r) {
4d4682ef
JF
1552 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
1553
8762082f 1554 std::string dir;
d4187e53 1555 std::string base;
8762082f 1556
d4187e53
JF
1557 size_t slash(path.rfind('/'));
1558 if (slash == std::string::npos)
8762082f 1559 base = path;
d4187e53
JF
1560 else {
1561 dir = path.substr(0, slash + 1);
1562 base = path.substr(slash + 1);
1563 }
8762082f 1564
34f4c1d8 1565 std::string temp(dir + "." + base + ".cs");
4d4682ef 1566 std::filebuf output;
a7f01a65 1567 _assert(output.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &output);
4d4682ef 1568
e0098838 1569 if (flag_r)
a0c715e9 1570 ldid::Unsign(input.data(), input.size(), output);
8762082f 1571 else {
d4187e53 1572 std::string identifier(flag_I ?: base.c_str());
ffdd1183 1573 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
8762082f 1574 }
34f4c1d8 1575
d4187e53 1576 Commit(path, temp);
fdb119ef
JF
1577 }
1578
34f4c1d8 1579 Map mapping(path, flag_T || flag_s);
dede6121 1580 FatHeader fat_header(mapping.data(), mapping.size());
a362a82f 1581
0a033524 1582 _foreach (mach_header, fat_header.GetMachHeaders()) {
d840a088 1583 struct linkedit_data_command *signature(NULL);
7b496abd
JF
1584 struct encryption_info_command *encryption(NULL);
1585
8c417842
JF
1586 if (flag_A) {
1587 if (mach_header.GetCPUType() != flag_CPUType)
1588 continue;
1589 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
1590 continue;
1591 }
1592
1593 if (flag_a)
1594 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
1595
0a033524
JF
1596 _foreach (load_command, mach_header.GetLoadCommands()) {
1597 uint32_t cmd(mach_header.Swap(load_command->cmd));
1598
cad40c43 1599 if (false);
0a033524
JF
1600 else if (cmd == LC_CODE_SIGNATURE)
1601 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
843aea8c 1602 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
7b496abd 1603 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
cad40c43 1604 else if (cmd == LC_ID_DYLIB) {
0a033524 1605 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
a362a82f 1606
0a033524
JF
1607 if (flag_T) {
1608 uint32_t timed;
a362a82f 1609
0a033524
JF
1610 if (!timeh)
1611 timed = timev;
1612 else {
1613 dylib_command->dylib.timestamp = 0;
1614 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
1615 }
a362a82f 1616
0a033524
JF
1617 dylib_command->dylib.timestamp = mach_header.Swap(timed);
1618 }
7b496abd
JF
1619 }
1620 }
1621
7b496abd
JF
1622 if (flag_D) {
1623 _assert(encryption != NULL);
1624 encryption->cryptid = mach_header.Swap(0);
a362a82f 1625 }
a362a82f 1626
0a033524
JF
1627 if (flag_e) {
1628 _assert(signature != NULL);
9c83be90 1629
0a033524 1630 uint32_t data = mach_header.Swap(signature->dataoff);
9c83be90 1631
0a033524
JF
1632 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1633 uint8_t *blob = top + data;
1634 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
9c83be90 1635
0a033524
JF
1636 for (size_t index(0); index != Swap(super->count); ++index)
1637 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1638 uint32_t begin = Swap(super->index[index].offset);
1639 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
b9652d6e 1640 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
0a033524
JF
1641 }
1642 }
9c83be90 1643
0a033524
JF
1644 if (flag_s) {
1645 _assert(signature != NULL);
20c5f1e8 1646
0a033524 1647 uint32_t data = mach_header.Swap(signature->dataoff);
20c5f1e8 1648
0a033524
JF
1649 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
1650 uint8_t *blob = top + data;
1651 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
20c5f1e8 1652
0a033524
JF
1653 for (size_t index(0); index != Swap(super->count); ++index)
1654 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
1655 uint32_t begin = Swap(super->index[index].offset);
1656 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
20c5f1e8 1657
4d4682ef 1658 uint8_t (*hashes)[SHA_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[SHA_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
0a033524 1659 uint32_t pages = Swap(directory->nCodeSlots);
20c5f1e8 1660
0a033524
JF
1661 if (pages != 1)
1662 for (size_t i = 0; i != pages - 1; ++i)
b9652d6e 1663 sha1(hashes[i], top + PageSize_ * i, PageSize_);
0a033524 1664 if (pages != 0)
b9652d6e 1665 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
0a033524
JF
1666 }
1667 }
fdb119ef
JF
1668 }
1669
a362a82f
JF
1670 ++filei;
1671 } catch (const char *) {
1672 ++filee;
1673 ++filei;
1674 }
1675
1676 return filee;
1677}