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