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