]> git.saurik.com Git - ldid.git/blame - ldid.cpp
Embed team identifier of certificate in signature.
[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;
b73d2333
JF
813 uint32_t scatterOffset;
814 uint32_t teamIDOffset;
815 uint32_t spare3;
816 uint64_t codeLimit64;
c05d9758 817} _packed;
fdb119ef 818
fdbee693 819#ifndef LDID_NOFLAGT
a362a82f 820extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
fdbee693 821#endif
a362a82f 822
f65c321b 823static void sha1(uint8_t *hash, const void *data, size_t size) {
84d29a1c 824 LDID_SHA1(static_cast<const uint8_t *>(data), size, hash);
fdb119ef
JF
825}
826
707027e8
JF
827static void sha1(std::vector<char> &hash, const void *data, size_t size) {
828 hash.resize(LDID_SHA1_DIGEST_LENGTH);
829 sha1(reinterpret_cast<uint8_t *>(hash.data()), data, size);
830}
831
0a033524 832struct CodesignAllocation {
4374152f
JF
833 FatMachHeader mach_header_;
834 uint32_t offset_;
835 uint32_t size_;
4d4682ef 836 uint32_t limit_;
4374152f 837 uint32_t alloc_;
e4b7adc1 838 uint32_t align_;
4374152f 839
e0098838 840 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) :
4374152f
JF
841 mach_header_(mach_header),
842 offset_(offset),
843 size_(size),
4d4682ef 844 limit_(limit),
e4b7adc1
JF
845 alloc_(alloc),
846 align_(align)
0a033524
JF
847 {
848 }
849};
850
0326ab11 851#ifndef LDID_NOTOOLS
dede6121
JF
852class File {
853 private:
854 int file_;
855
856 public:
857 File() :
858 file_(-1)
859 {
860 }
861
862 ~File() {
863 if (file_ != -1)
864 _syscall(close(file_));
865 }
866
cad40c43 867 void open(const char *path, int flags) {
dede6121 868 _assert(file_ == -1);
fc7a76da 869 file_ = _syscall(::open(path, flags));
dede6121
JF
870 }
871
872 int file() const {
873 return file_;
874 }
875};
876
877class Map {
878 private:
879 File file_;
880 void *data_;
881 size_t size_;
882
883 void clear() {
884 if (data_ == NULL)
885 return;
886 _syscall(munmap(data_, size_));
887 data_ = NULL;
888 size_ = 0;
889 }
890
891 public:
892 Map() :
893 data_(NULL),
894 size_(0)
895 {
896 }
897
d4187e53 898 Map(const std::string &path, int oflag, int pflag, int mflag) :
cad40c43
JF
899 Map()
900 {
901 open(path, oflag, pflag, mflag);
902 }
903
d4187e53 904 Map(const std::string &path, bool edit) :
cad40c43
JF
905 Map()
906 {
907 open(path, edit);
dede6121
JF
908 }
909
910 ~Map() {
911 clear();
912 }
913
fac3d3e3
JF
914 bool empty() const {
915 return data_ == NULL;
916 }
917
d4187e53 918 void open(const std::string &path, int oflag, int pflag, int mflag) {
dede6121
JF
919 clear();
920
d4187e53 921 file_.open(path.c_str(), oflag);
dede6121
JF
922 int file(file_.file());
923
924 struct stat stat;
925 _syscall(fstat(file, &stat));
926 size_ = stat.st_size;
927
fc7a76da 928 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
cad40c43
JF
929 }
930
d4187e53 931 void open(const std::string &path, bool edit) {
cad40c43
JF
932 if (edit)
933 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
934 else
935 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
dede6121
JF
936 }
937
938 void *data() const {
939 return data_;
940 }
941
942 size_t size() const {
943 return size_;
944 }
f4b2df35
JF
945
946 operator std::string() const {
947 return std::string(static_cast<char *>(data_), size_);
948 }
dede6121 949};
0326ab11 950#endif
dede6121 951
a0c715e9
JF
952namespace ldid {
953
e4d33eec 954static 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 955 FatHeader source(const_cast<void *>(idata), isize);
f4b2df35
JF
956
957 size_t offset(0);
958 if (source.IsFat())
959 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
960
961 std::vector<CodesignAllocation> allocations;
962 _foreach (mach_header, source.GetMachHeaders()) {
963 struct linkedit_data_command *signature(NULL);
964 struct symtab_command *symtab(NULL);
965
966 _foreach (load_command, mach_header.GetLoadCommands()) {
967 uint32_t cmd(mach_header.Swap(load_command->cmd));
968 if (false);
969 else if (cmd == LC_CODE_SIGNATURE)
970 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
971 else if (cmd == LC_SYMTAB)
972 symtab = reinterpret_cast<struct symtab_command *>(load_command);
973 }
974
975 size_t size;
976 if (signature == NULL)
977 size = mach_header.GetSize();
978 else {
979 size = mach_header.Swap(signature->dataoff);
980 _assert(size <= mach_header.GetSize());
981 }
982
983 if (symtab != NULL) {
984 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
985 _assert(end <= size);
986 _assert(end >= size - 0x10);
987 size = end;
988 }
989
e4d33eec 990 size_t alloc(allocate(mach_header, size));
f4b2df35
JF
991
992 auto *fat_arch(mach_header.GetFatArch());
6f420711
JF
993 uint32_t align;
994
995 if (fat_arch != NULL)
996 align = source.Swap(fat_arch->align);
997 else switch (mach_header.GetCPUType()) {
998 case CPU_TYPE_POWERPC:
999 case CPU_TYPE_POWERPC64:
1000 case CPU_TYPE_X86:
1001 case CPU_TYPE_X86_64:
1002 align = 0xc;
1003 break;
1004 case CPU_TYPE_ARM:
1005 case CPU_TYPE_ARM64:
1006 align = 0xe;
1007 break;
1008 default:
1009 align = 0x0;
1010 break;
1011 }
1012
f4b2df35
JF
1013 offset = Align(offset, 1 << align);
1014
4d4682ef
JF
1015 uint32_t limit(size);
1016 if (alloc != 0)
1017 limit = Align(limit, 0x10);
1018
e0098838 1019 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
f4b2df35 1020 offset += size + alloc;
b9652d6e 1021 offset = Align(offset, 0x10);
f4b2df35
JF
1022 }
1023
4d4682ef
JF
1024 size_t position(0);
1025
1026 if (source.IsFat()) {
1027 fat_header fat_header;
1028 fat_header.magic = Swap(FAT_MAGIC);
1029 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1030 put(output, &fat_header, sizeof(fat_header));
1031 position += sizeof(fat_header);
1032
1033 _foreach (allocation, allocations) {
1034 auto &mach_header(allocation.mach_header_);
1035
1036 fat_arch fat_arch;
1037 fat_arch.cputype = Swap(mach_header->cputype);
1038 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
1039 fat_arch.offset = Swap(allocation.offset_);
1040 fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
1041 fat_arch.align = Swap(allocation.align_);
1042 put(output, &fat_arch, sizeof(fat_arch));
1043 position += sizeof(fat_arch);
1044 }
f4b2df35
JF
1045 }
1046
1047 _foreach (allocation, allocations) {
4d4682ef 1048 auto &mach_header(allocation.mach_header_);
f4b2df35 1049
4d4682ef
JF
1050 pad(output, allocation.offset_ - position);
1051 position = allocation.offset_;
f4b2df35 1052
4d4682ef 1053 std::vector<std::string> commands;
f4b2df35 1054
4d4682ef
JF
1055 _foreach (load_command, mach_header.GetLoadCommands()) {
1056 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
f4b2df35 1057
a7f01a65 1058 switch (mach_header.Swap(load_command->cmd)) {
4d4682ef
JF
1059 case LC_CODE_SIGNATURE:
1060 continue;
1061 break;
1062
1063 case LC_SEGMENT: {
1064 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
1065 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1066 break;
1067 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1068 segment_command->filesize = size;
6f420711 1069 segment_command->vmsize = Align(size, 1 << allocation.align_);
4d4682ef
JF
1070 } break;
1071
1072 case LC_SEGMENT_64: {
1073 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
1074 if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
1075 break;
1076 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1077 segment_command->filesize = size;
6f420711 1078 segment_command->vmsize = Align(size, 1 << allocation.align_);
4d4682ef
JF
1079 } break;
1080 }
f4b2df35 1081
4d4682ef 1082 commands.push_back(copy);
f4b2df35
JF
1083 }
1084
e0098838 1085 if (allocation.alloc_ != 0) {
4d4682ef
JF
1086 linkedit_data_command signature;
1087 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1088 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1089 signature.dataoff = mach_header.Swap(allocation.limit_);
1090 signature.datasize = mach_header.Swap(allocation.alloc_);
1091 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1092 }
f4b2df35 1093
4d4682ef 1094 size_t begin(position);
f4b2df35 1095
4d4682ef
JF
1096 uint32_t after(0);
1097 _foreach(command, commands)
1098 after += command.size();
f4b2df35 1099
4d4682ef 1100 std::stringbuf altern;
f4b2df35 1101
4d4682ef
JF
1102 struct mach_header header(*mach_header);
1103 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1104 header.sizeofcmds = mach_header.Swap(after);
1105 put(output, &header, sizeof(header));
1106 put(altern, &header, sizeof(header));
1107 position += sizeof(header);
f4b2df35 1108
4d4682ef
JF
1109 if (mach_header.Bits64()) {
1110 auto pad(mach_header.Swap(uint32_t(0)));
1111 put(output, &pad, sizeof(pad));
1112 put(altern, &pad, sizeof(pad));
1113 position += sizeof(pad);
1114 }
f4b2df35 1115
4d4682ef
JF
1116 _foreach(command, commands) {
1117 put(output, command.data(), command.size());
1118 put(altern, command.data(), command.size());
1119 position += command.size();
1120 }
f4b2df35 1121
4d4682ef
JF
1122 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1123 if (before > after) {
1124 pad(output, before - after);
1125 pad(altern, before - after);
1126 position += before - after;
1127 }
f4b2df35 1128
4d4682ef 1129 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
f4b2df35 1130
4d4682ef
JF
1131 std::string overlap(altern.str());
1132 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
f4b2df35 1133
4d4682ef
JF
1134 put(output, top + (position - begin), allocation.size_ - (position - begin));
1135 position = begin + allocation.size_;
f4b2df35 1136
4d4682ef
JF
1137 pad(output, allocation.limit_ - allocation.size_);
1138 position += allocation.limit_ - allocation.size_;
f4b2df35 1139
e4d33eec 1140 size_t saved(save(mach_header, output, allocation.limit_, overlap, top));
67205335
JF
1141 if (allocation.alloc_ > saved)
1142 pad(output, allocation.alloc_ - saved);
1143 position += allocation.alloc_;
e0098838
JF
1144 }
1145}
f4b2df35 1146
a0c715e9
JF
1147}
1148
efad8a44
JF
1149typedef std::map<uint32_t, std::string> Blobs;
1150
bb591e2b
JF
1151static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1152 auto value(buffer.str());
1153 std::swap(blobs[slot], value);
1154}
1155
8f310b91
JF
1156static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
1157 auto value(buffer.str());
1158 Blob blob;
1159 blob.magic = Swap(magic);
1160 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1161 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
1162 std::swap(blobs[slot], value);
efad8a44
JF
1163}
1164
1165static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1166 size_t total(0);
1167 _foreach (blob, blobs)
1168 total += blob.second.size();
1169
1170 struct SuperBlob super;
1171 super.blob.magic = Swap(magic);
1172 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1173 super.count = Swap(uint32_t(blobs.size()));
1174 put(output, &super, sizeof(super));
1175
1176 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1177
1178 _foreach (blob, blobs) {
1179 BlobIndex index;
1180 index.type = Swap(blob.first);
1181 index.offset = Swap(uint32_t(offset));
1182 put(output, &index, sizeof(index));
1183 offset += blob.second.size();
1184 }
1185
1186 _foreach (blob, blobs)
1187 put(output, blob.second.data(), blob.second.size());
1188
1189 return offset;
1190}
1191
489c97b8 1192#ifndef LDID_NOSMIME
30c64adb
JF
1193class Buffer {
1194 private:
1195 BIO *bio_;
1196
1197 public:
1198 Buffer(BIO *bio) :
1199 bio_(bio)
1200 {
1201 _assert(bio_ != NULL);
1202 }
1203
1204 Buffer() :
1205 bio_(BIO_new(BIO_s_mem()))
1206 {
1207 }
1208
1209 Buffer(const char *data, size_t size) :
1210 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1211 {
1212 }
1213
1214 Buffer(const std::string &data) :
1215 Buffer(data.data(), data.size())
1216 {
1217 }
1218
1219 Buffer(PKCS7 *pkcs) :
1220 Buffer()
1221 {
1222 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1223 }
1224
1225 ~Buffer() {
1226 BIO_free_all(bio_);
1227 }
1228
1229 operator BIO *() const {
1230 return bio_;
1231 }
1232
1233 explicit operator std::string() const {
1234 char *data;
1235 auto size(BIO_get_mem_data(bio_, &data));
1236 return std::string(data, size);
1237 }
1238};
1239
1240class Stuff {
1241 private:
1242 PKCS12 *value_;
1243 EVP_PKEY *key_;
1244 X509 *cert_;
1245 STACK_OF(X509) *ca_;
1246
1247 public:
1248 Stuff(BIO *bio) :
1249 value_(d2i_PKCS12_bio(bio, NULL)),
1250 ca_(NULL)
1251 {
1252 _assert(value_ != NULL);
1253 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
1254 _assert(key_ != NULL);
1255 _assert(cert_ != NULL);
1256 }
1257
1258 Stuff(const std::string &data) :
1259 Stuff(Buffer(data))
1260 {
1261 }
1262
1263 ~Stuff() {
1264 sk_X509_pop_free(ca_, X509_free);
1265 X509_free(cert_);
1266 EVP_PKEY_free(key_);
1267 PKCS12_free(value_);
1268 }
1269
1270 operator PKCS12 *() const {
1271 return value_;
1272 }
1273
1274 operator EVP_PKEY *() const {
1275 return key_;
1276 }
1277
1278 operator X509 *() const {
1279 return cert_;
1280 }
1281
1282 operator STACK_OF(X509) *() const {
1283 return ca_;
1284 }
1285};
1286
1287class Signature {
1288 private:
1289 PKCS7 *value_;
1290
1291 public:
1292 Signature(const Stuff &stuff, const Buffer &data) :
1293 value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
1294 {
1295 _assert(value_ != NULL);
1296 }
1297
1298 ~Signature() {
1299 PKCS7_free(value_);
1300 }
1301
1302 operator PKCS7 *() const {
1303 return value_;
1304 }
1305};
489c97b8 1306#endif
30c64adb 1307
23c11ee8
JF
1308class NullBuffer :
1309 public std::streambuf
1310{
1311 public:
1312 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1313 return size;
1314 }
1315
1316 virtual int_type overflow(int_type next) {
1317 return next;
1318 }
1319};
1320
1321class HashBuffer :
1322 public std::streambuf
1323{
1324 private:
1325 std::vector<char> &hash_;
84d29a1c 1326 LDID_SHA1_CTX context_;
23c11ee8
JF
1327
1328 public:
1329 HashBuffer(std::vector<char> &hash) :
1330 hash_(hash)
1331 {
84d29a1c 1332 LDID_SHA1_Init(&context_);
23c11ee8
JF
1333 }
1334
1335 ~HashBuffer() {
84d29a1c
JF
1336 hash_.resize(LDID_SHA1_DIGEST_LENGTH);
1337 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.data()), &context_);
23c11ee8
JF
1338 }
1339
1340 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
84d29a1c 1341 LDID_SHA1_Update(&context_, data, size);
23c11ee8
JF
1342 return size;
1343 }
1344
1345 virtual int_type overflow(int_type next) {
1346 if (next == traits_type::eof())
1347 return sync();
1348 char value(next);
1349 xsputn(&value, 1);
1350 return next;
1351 }
1352};
1353
1354class HashProxy :
1355 public HashBuffer
1356{
1357 private:
1358 std::streambuf &buffer_;
1359
1360 public:
1361 HashProxy(std::vector<char> &hash, std::streambuf &buffer) :
1362 HashBuffer(hash),
1363 buffer_(buffer)
1364 {
1365 }
1366
1367 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1368 _assert(HashBuffer::xsputn(data, size) == size);
1369 return buffer_.sputn(data, size);
1370 }
1371};
1372
0326ab11 1373#ifndef LDID_NOTOOLS
23c11ee8
JF
1374static bool Starts(const std::string &lhs, const std::string &rhs) {
1375 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1376}
1377
1378class Split {
1379 public:
1380 std::string dir;
1381 std::string base;
1382
1383 Split(const std::string &path) {
1384 size_t slash(path.rfind('/'));
1385 if (slash == std::string::npos)
1386 base = path;
1387 else {
1388 dir = path.substr(0, slash + 1);
1389 base = path.substr(slash + 1);
1390 }
1391 }
1392};
1393
1394static void mkdir_p(const std::string &path) {
1395 if (path.empty())
1396 return;
31cc0388
JF
1397#ifdef __WIN32__
1398 if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
1399 return;
1400#else
23c11ee8
JF
1401 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1402 return;
31cc0388 1403#endif
23c11ee8
JF
1404 auto slash(path.rfind('/', path.size() - 1));
1405 if (slash == std::string::npos)
1406 return;
1407 mkdir_p(path.substr(0, slash));
1408}
1409
1410static std::string Temporary(std::filebuf &file, const Split &split) {
1411 std::string temp(split.dir + ".ldid." + split.base);
1412 mkdir_p(split.dir);
1413 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1414 return temp;
1415}
1416
d4187e53
JF
1417static void Commit(const std::string &path, const std::string &temp) {
1418 struct stat info;
23c11ee8 1419 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
d4187e53 1420#ifndef __WIN32__
23c11ee8 1421 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
d4187e53 1422#endif
23c11ee8
JF
1423 _syscall(chmod(temp.c_str(), info.st_mode));
1424 }
1425
d4187e53
JF
1426 _syscall(rename(temp.c_str(), path.c_str()));
1427}
0326ab11 1428#endif
d4187e53 1429
a0c715e9 1430namespace ldid {
e57b1f91 1431
ffdd1183 1432void 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) {
b73d2333
JF
1433 std::string team;
1434
1435#ifndef LDID_NOSMIME
1436 if (!key.empty()) {
1437 std::stringbuf data;
1438 Stuff stuff(key);
1439 auto name(X509_get_subject_name(stuff));
1440 _assert(name != NULL);
1441 auto index(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, -1));
1442 _assert(index >= 0);
1443 auto next(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, index));
1444 _assert(next == -1);
1445 auto entry(X509_NAME_get_entry(name, index));
1446 _assert(entry != NULL);
1447 auto asn(X509_NAME_ENTRY_get_data(entry));
1448 _assert(asn != NULL);
1449 team.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn)), ASN1_STRING_length(asn));
1450 }
1451#endif
1452
e4d33eec 1453 Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, size_t size) -> size_t {
e0098838 1454 size_t alloc(sizeof(struct SuperBlob));
f4b2df35 1455
e0098838 1456 uint32_t special(0);
f4b2df35 1457
e0098838
JF
1458 special = std::max(special, CSSLOT_REQUIREMENTS);
1459 alloc += sizeof(struct BlobIndex);
1460 alloc += 0xc;
f4b2df35 1461
faa1b1f8 1462 if (!entitlements.empty()) {
e0098838
JF
1463 special = std::max(special, CSSLOT_ENTITLEMENTS);
1464 alloc += sizeof(struct BlobIndex);
1465 alloc += sizeof(struct Blob);
1466 alloc += entitlements.size();
1467 }
f4b2df35 1468
e0098838
JF
1469 special = std::max(special, CSSLOT_CODEDIRECTORY);
1470 alloc += sizeof(struct BlobIndex);
1471 alloc += sizeof(struct Blob);
1472 alloc += sizeof(struct CodeDirectory);
ffdd1183 1473 alloc += identifier.size() + 1;
f4b2df35 1474
b73d2333
JF
1475 if (!team.empty())
1476 alloc += team.size() + 1;
1477
30c64adb
JF
1478 if (!key.empty()) {
1479 alloc += sizeof(struct BlobIndex);
1480 alloc += sizeof(struct Blob);
1481 // XXX: this is just a "sufficiently large number"
1482 alloc += 0x3000;
1483 }
1484
e57b1f91
JF
1485 _foreach (slot, slots)
1486 special = std::max(special, slot.first);
1487
e4d33eec
JF
1488 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1489 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
1490 special = std::max(special, CSSLOT_INFOSLOT);
1491 }));
1492
b9652d6e 1493 uint32_t normal((size + PageSize_ - 1) / PageSize_);
84d29a1c 1494 alloc = Align(alloc + (special + normal) * LDID_SHA1_DIGEST_LENGTH, 16);
e0098838 1495 return alloc;
e4d33eec 1496 }), fun([&](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
efad8a44 1497 Blobs blobs;
f4b2df35 1498
e0098838
JF
1499 if (true) {
1500 std::stringbuf data;
f4b2df35 1501
bb591e2b
JF
1502 Blobs requirements;
1503 put(data, CSMAGIC_REQUIREMENTS, requirements);
4d4682ef 1504
bb591e2b 1505 insert(blobs, CSSLOT_REQUIREMENTS, data);
e0098838 1506 }
4d4682ef 1507
faa1b1f8 1508 if (!entitlements.empty()) {
e0098838 1509 std::stringbuf data;
e0098838 1510 put(data, entitlements.data(), entitlements.size());
8f310b91 1511 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
e0098838
JF
1512 }
1513
1514 if (true) {
1515 std::stringbuf data;
1516
e4d33eec
JF
1517 Slots posts(slots);
1518
1519 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1520 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
1521 sha1(posts[CSSLOT_INFOSLOT], data, size);
1522 }));
1523
e0098838
JF
1524 uint32_t special(0);
1525 _foreach (blob, blobs)
1526 special = std::max(special, blob.first);
e4d33eec 1527 _foreach (slot, posts)
e57b1f91 1528 special = std::max(special, slot.first);
b9652d6e 1529 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
e0098838 1530
e0098838 1531 CodeDirectory directory;
b73d2333 1532 directory.version = Swap(uint32_t(0x00020200));
e0098838 1533 directory.flags = Swap(uint32_t(0));
e0098838
JF
1534 directory.nSpecialSlots = Swap(special);
1535 directory.codeLimit = Swap(uint32_t(limit));
1536 directory.nCodeSlots = Swap(normal);
84d29a1c 1537 directory.hashSize = LDID_SHA1_DIGEST_LENGTH;
e0098838
JF
1538 directory.hashType = CS_HASHTYPE_SHA1;
1539 directory.spare1 = 0x00;
b9652d6e 1540 directory.pageSize = PageShift_;
e0098838 1541 directory.spare2 = Swap(uint32_t(0));
b73d2333
JF
1542 directory.scatterOffset = Swap(uint32_t(0));
1543 directory.spare3 = Swap(uint32_t(0));
1544 directory.codeLimit64 = Swap(uint64_t(0));
1545
1546 uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory));
1547
1548 directory.identOffset = Swap(uint32_t(offset));
1549 offset += identifier.size() + 1;
1550
1551 if (team.empty())
1552 directory.teamIDOffset = Swap(uint32_t(0));
1553 else {
1554 directory.teamIDOffset = Swap(uint32_t(offset));
1555 offset += team.size() + 1;
1556 }
1557
1558 offset += LDID_SHA1_DIGEST_LENGTH * special;
1559 directory.hashOffset = Swap(uint32_t(offset));
1560 offset += LDID_SHA1_DIGEST_LENGTH * normal;
1561
e0098838
JF
1562 put(data, &directory, sizeof(directory));
1563
ffdd1183 1564 put(data, identifier.c_str(), identifier.size() + 1);
b73d2333 1565 put(data, team.c_str(), team.size() + 1);
e0098838 1566
84d29a1c
JF
1567 uint8_t storage[special + normal][LDID_SHA1_DIGEST_LENGTH];
1568 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = storage + special;
e0098838
JF
1569
1570 memset(storage, 0, sizeof(*storage) * special);
4d4682ef
JF
1571
1572 _foreach (blob, blobs) {
e0098838
JF
1573 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
1574 sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
4d4682ef 1575 }
f4b2df35 1576
e4d33eec 1577 _foreach (slot, posts) {
e57b1f91
JF
1578 _assert(sizeof(*hashes) == slot.second.size());
1579 memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
1580 }
1581
e0098838
JF
1582 if (normal != 1)
1583 for (size_t i = 0; i != normal - 1; ++i)
b9652d6e 1584 sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
e0098838 1585 if (normal != 0)
b9652d6e 1586 sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
f4b2df35 1587
e0098838
JF
1588 put(data, storage, sizeof(storage));
1589
8f310b91 1590 insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
f4b2df35 1591 }
e0098838 1592
489c97b8 1593#ifndef LDID_NOSMIME
30c64adb
JF
1594 if (!key.empty()) {
1595 std::stringbuf data;
1596 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
1597
1598 Stuff stuff(key);
1599 Buffer bio(sign);
1600
1601 Signature signature(stuff, sign);
1602 Buffer result(signature);
1603 std::string value(result);
1604 put(data, value.data(), value.size());
1605
1606 insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
1607 }
489c97b8 1608#endif
30c64adb 1609
efad8a44 1610 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
e0098838
JF
1611 }));
1612}
1613
0326ab11 1614#ifndef LDID_NOTOOLS
a0c715e9 1615static void Unsign(void *idata, size_t isize, std::streambuf &output) {
e4d33eec 1616 Allocate(idata, isize, output, fun([](const MachHeader &mach_header, size_t size) -> size_t {
e0098838 1617 return 0;
e4d33eec 1618 }), fun([](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
e0098838
JF
1619 return 0;
1620 }));
f4b2df35
JF
1621}
1622
23c11ee8
JF
1623std::string DiskFolder::Path(const std::string &path) {
1624 return path_ + "/" + path;
1625}
1626
1627DiskFolder::DiskFolder(const std::string &path) :
1628 path_(path)
1629{
1630}
1631
1632DiskFolder::~DiskFolder() {
1633 if (!std::uncaught_exception())
1634 for (const auto &commit : commit_)
1635 Commit(commit.first, commit.second);
1636}
1637
54a0f854
JF
1638void DiskFolder::Find(const std::string &root, const std::string &base, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
1639 std::string path(Path(root) + base);
1640
1641 DIR *dir(opendir(path.c_str()));
1642 _assert(dir != NULL);
1643 _scope({ _syscall(closedir(dir)); });
1644
1645 while (auto child = readdir(dir)) {
261b9963 1646 std::string name(child->d_name);
54a0f854
JF
1647 if (name == "." || name == "..")
1648 continue;
1649 if (Starts(name, ".ldid."))
1650 continue;
1651
b6d8da4e
JF
1652 bool directory;
1653
1654#ifdef __WIN32__
1655 struct stat info;
1656 _syscall(stat(path.c_str(), &info));
1657 if (false);
1658 else if (S_ISDIR(info.st_mode))
1659 directory = true;
1660 else if (S_ISREG(info.st_mode))
1661 directory = false;
1662 else
1663 _assert_(false, "st_mode=%x", info.st_mode);
1664#else
54a0f854
JF
1665 switch (child->d_type) {
1666 case DT_DIR:
b6d8da4e
JF
1667 directory = true;
1668 break;
54a0f854 1669 case DT_REG:
b6d8da4e
JF
1670 directory = false;
1671 break;
54a0f854
JF
1672 default:
1673 _assert_(false, "d_type=%u", child->d_type);
54a0f854 1674 }
b6d8da4e
JF
1675#endif
1676
1677 if (directory)
1678 Find(root, base + name + "/", code);
1679 else
1680 code(base + name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1681 std::string access(root + base + name);
1682 _assert_(Open(access, fun([&](std::streambuf &data) {
1683 NullBuffer save;
1684 code(data, save);
1685 })), "open(): %s", access.c_str());
1686 }));
54a0f854
JF
1687 }
1688}
1689
23c11ee8
JF
1690void DiskFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1691 std::filebuf save;
1692 auto from(Path(path));
1693 commit_[from] = Temporary(save, from);
1694 code(save);
1695}
1696
1697bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1698 std::filebuf data;
1699 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
1700 if (result == NULL)
1701 return false;
1702 _assert(result == &data);
1703 code(data);
1704 return true;
1705}
1706
1707void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
54a0f854 1708 Find(path, "", code);
23c11ee8 1709}
0326ab11 1710#endif
23c11ee8 1711
2443500c 1712SubFolder::SubFolder(Folder &parent, const std::string &path) :
23c11ee8
JF
1713 parent_(parent),
1714 path_(path)
1715{
1716}
1717
1718void SubFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
2443500c 1719 return parent_.Save(path_ + path, code);
23c11ee8
JF
1720}
1721
1722bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
2443500c 1723 return parent_.Open(path_ + path, code);
23c11ee8
JF
1724}
1725
1726void SubFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
2443500c 1727 return parent_.Find(path_ + path, code);
23c11ee8
JF
1728}
1729
886cb3f1
JF
1730UnionFolder::UnionFolder(Folder &parent) :
1731 parent_(parent)
1732{
1733}
1734
1735void UnionFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1736 return parent_.Save(path, code);
1737}
1738
1739bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
1740 auto file(files_.find(path));
1741 if (file == files_.end())
1742 return parent_.Open(path, code);
1743
1744 auto &data(file->second);
1745 data.pubseekpos(0, std::ios::in);
1746 code(data);
1747 return true;
1748}
1749
1750void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
1751 parent_.Find(path, fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &save) {
35229d06 1752 if (files_.find(path + name) == files_.end())
886cb3f1
JF
1753 code(name, save);
1754 }));
1755
1756 for (auto &file : files_)
35229d06
JF
1757 if (file.first.size() >= path.size() && file.first.substr(0, path.size()) == path)
1758 code(file.first.substr(path.size()), fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
1759 parent_.Save(file.first, fun([&](std::streambuf &save) {
1760 file.second.pubseekpos(0, std::ios::in);
1761 code(file.second, save);
1762 }));
886cb3f1 1763 }));
886cb3f1
JF
1764}
1765
0326ab11 1766#ifndef LDID_NOTOOLS
23c11ee8
JF
1767static size_t copy(std::streambuf &source, std::streambuf &target) {
1768 size_t total(0);
1769 for (;;) {
1770 char data[4096];
1771 size_t writ(source.sgetn(data, sizeof(data)));
1772 if (writ == 0)
1773 break;
1774 _assert(target.sputn(data, writ) == writ);
1775 total += writ;
1776 }
1777 return total;
1778}
1779
489c97b8 1780#ifndef LDID_NOPLIST
8dfe0afc
JF
1781static plist_t plist(const std::string &data) {
1782 plist_t plist(NULL);
1783 if (Starts(data, "bplist00"))
1784 plist_from_bin(data.data(), data.size(), &plist);
1785 else
1786 plist_from_xml(data.data(), data.size(), &plist);
1787 _assert(plist != NULL);
1788 return plist;
23c11ee8
JF
1789}
1790
8dfe0afc 1791static void plist_d(std::streambuf &buffer, const Functor<void (plist_t)> &code) {
23c11ee8
JF
1792 std::stringbuf data;
1793 copy(buffer, data);
8dfe0afc
JF
1794 auto node(plist(data.str()));
1795 _scope({ plist_free(node); });
1796 _assert(plist_get_node_type(node) == PLIST_DICT);
1797 code(node);
23c11ee8
JF
1798}
1799
8dfe0afc
JF
1800static std::string plist_s(plist_t node) {
1801 _assert(node != NULL);
1802 _assert(plist_get_node_type(node) == PLIST_STRING);
1803 char *data;
1804 plist_get_string_val(node, &data);
1805 _scope({ free(data); });
1806 return data;
23c11ee8 1807}
489c97b8 1808#endif
23c11ee8
JF
1809
1810enum Mode {
1811 NoMode,
1812 OptionalMode,
1813 OmitMode,
1814 NestedMode,
1815 TopMode,
1816};
1817
1818class Expression {
1819 private:
1820 regex_t regex_;
1821
1822 public:
1823 Expression(const std::string &code) {
1824 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()");
1825 }
1826
1827 ~Expression() {
1828 regfree(&regex_);
1829 }
1830
1831 bool operator ()(const std::string &data) const {
1832 auto value(regexec(&regex_, data.c_str(), 0, NULL, 0));
1833 if (value == REG_NOMATCH)
1834 return false;
1835 _assert_(value == 0, "regexec()");
1836 return true;
1837 }
1838};
1839
1840struct Rule {
1841 unsigned weight_;
1842 Mode mode_;
1843 std::string code_;
1844
1845 mutable std::auto_ptr<Expression> regex_;
1846
1847 Rule(unsigned weight, Mode mode, const std::string &code) :
1848 weight_(weight),
1849 mode_(mode),
1850 code_(code)
1851 {
1852 }
1853
1854 Rule(const Rule &rhs) :
1855 weight_(rhs.weight_),
1856 mode_(rhs.mode_),
1857 code_(rhs.code_)
1858 {
1859 }
1860
1861 void Compile() const {
1862 regex_.reset(new Expression(code_));
1863 }
1864
1865 bool operator ()(const std::string &data) const {
1866 _assert(regex_.get() != NULL);
1867 return (*regex_)(data);
1868 }
1869
1870 bool operator <(const Rule &rhs) const {
1871 if (weight_ > rhs.weight_)
1872 return true;
1873 if (weight_ < rhs.weight_)
1874 return false;
1875 return mode_ > rhs.mode_;
1876 }
1877};
1878
1879struct RuleCode {
1880 bool operator ()(const Rule *lhs, const Rule *rhs) const {
1881 return lhs->code_ < rhs->code_;
1882 }
1883};
1884
489c97b8 1885#ifndef LDID_NOPLIST
7f5ad603
JF
1886void Sign(std::streambuf &buffer, std::vector<char> &hash, std::streambuf &save, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) {
1887 // XXX: this is a miserable fail
1888 std::stringbuf temp;
1889 copy(buffer, temp);
1890 auto data(temp.str());
1891
1892 HashProxy proxy(hash, save);
1893 Sign(data.data(), data.size(), proxy, identifier, entitlements, key, slots);
1894}
1895
4d03333f 1896std::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
1897 std::string executable;
1898 std::string identifier;
1899
1900 static const std::string info("Info.plist");
1901
1902 _assert_(folder.Open(info, fun([&](std::streambuf &buffer) {
8dfe0afc
JF
1903 plist_d(buffer, fun([&](plist_t node) {
1904 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
1905 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
23c11ee8
JF
1906 }));
1907 })), "open(): Info.plist");
1908
d9c2341d
JF
1909 static const std::string directory("_CodeSignature/");
1910 static const std::string signature(directory + "CodeResources");
1911
23c11ee8
JF
1912 std::map<std::string, std::multiset<Rule>> versions;
1913
1914 auto &rules1(versions[""]);
1915 auto &rules2(versions["2"]);
1916
23c11ee8 1917 folder.Open(signature, fun([&](std::streambuf &buffer) {
8dfe0afc 1918 plist_d(buffer, fun([&](plist_t node) {
23c11ee8
JF
1919 // XXX: maybe attempt to preserve existing rules
1920 }));
1921 }));
1922
1923 if (true) {
1924 rules1.insert(Rule{1, NoMode, "^"});
1925 rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1926 rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1927 rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1928 rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1929 rules1.insert(Rule{1, NoMode, "^version.plist$"});
1930 }
1931
1932 if (true) {
1933 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
1934 rules2.insert(Rule{20, NoMode, "^"});
1935 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
1936 rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1937 rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
1938 rules2.insert(Rule{1, NoMode, "^.*"});
1939 rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
1940 rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
1941 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
1942 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
1943 rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
1944 rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
1945 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
1946 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
1947 }
1948
1949 std::map<std::string, std::vector<char>> local;
1950
1951 static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
7f5ad603 1952 static Expression dylib("^[^/]*\\.dylib$");
23c11ee8
JF
1953
1954 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
1955 if (!nested(name))
1956 return;
1957 auto bundle(root + Split(name).dir);
2443500c 1958 SubFolder subfolder(folder, bundle);
4d03333f 1959 Bundle(bundle, subfolder, key, local, "");
23c11ee8
JF
1960 }));
1961
1962 folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
d9c2341d
JF
1963 // BundleDiskRep::adjustResources -> builder.addExclusion
1964 if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
23c11ee8
JF
1965 return;
1966
1967 auto &hash(local[name]);
1968 if (!hash.empty())
1969 return;
1970
1971 code(fun([&](std::streambuf &data, std::streambuf &save) {
7f5ad603
JF
1972 if (dylib(name)) {
1973 Slots slots;
1974 Sign(data, hash, save, identifier, "", key, slots);
1975 } else {
1976 HashProxy proxy(hash, save);
1977 copy(data, proxy);
1978 }
23c11ee8
JF
1979 }));
1980
84d29a1c 1981 _assert(hash.size() == LDID_SHA1_DIGEST_LENGTH);
23c11ee8
JF
1982 }));
1983
8dfe0afc
JF
1984 auto plist(plist_new_dict());
1985 _scope({ plist_free(plist); });
23c11ee8
JF
1986
1987 for (const auto &version : versions) {
8dfe0afc
JF
1988 auto files(plist_new_dict());
1989 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
23c11ee8
JF
1990
1991 for (const auto &rule : version.second)
1992 rule.Compile();
1993
1994 for (const auto &hash : local)
1995 for (const auto &rule : version.second)
1996 if (rule(hash.first)) {
1997 if (rule.mode_ == NoMode)
8dfe0afc 1998 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(hash.second.data(), hash.second.size()));
23c11ee8 1999 else if (rule.mode_ == OptionalMode) {
8dfe0afc
JF
2000 auto entry(plist_new_dict());
2001 plist_dict_set_item(entry, "hash", plist_new_data(hash.second.data(), hash.second.size()));
2002 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2003 plist_dict_set_item(files, hash.first.c_str(), entry);
23c11ee8
JF
2004 }
2005
2006 break;
2007 }
23c11ee8
JF
2008 }
2009
2010 for (const auto &version : versions) {
8dfe0afc
JF
2011 auto rules(plist_new_dict());
2012 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
23c11ee8
JF
2013
2014 std::multiset<const Rule *, RuleCode> ordered;
2015 for (const auto &rule : version.second)
2016 ordered.insert(&rule);
2017
2018 for (const auto &rule : ordered)
2019 if (rule->weight_ == 1 && rule->mode_ == NoMode)
8dfe0afc 2020 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
23c11ee8 2021 else {
8dfe0afc
JF
2022 auto entry(plist_new_dict());
2023 plist_dict_set_item(rules, rule->code_.c_str(), entry);
23c11ee8
JF
2024
2025 switch (rule->mode_) {
2026 case NoMode:
2027 break;
2028 case OmitMode:
8dfe0afc 2029 plist_dict_set_item(entry, "omit", plist_new_bool(true));
23c11ee8
JF
2030 break;
2031 case OptionalMode:
8dfe0afc 2032 plist_dict_set_item(entry, "optional", plist_new_bool(true));
23c11ee8
JF
2033 break;
2034 case NestedMode:
8dfe0afc 2035 plist_dict_set_item(entry, "nested", plist_new_bool(true));
23c11ee8
JF
2036 break;
2037 case TopMode:
8dfe0afc 2038 plist_dict_set_item(entry, "top", plist_new_bool(true));
23c11ee8
JF
2039 break;
2040 }
2041
2042 if (rule->weight_ >= 10000)
8dfe0afc 2043 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
23c11ee8 2044 else if (rule->weight_ != 1)
8dfe0afc 2045 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
23c11ee8 2046 }
23c11ee8
JF
2047 }
2048
2049 folder.Save(signature, fun([&](std::streambuf &save) {
2050 HashProxy proxy(local[signature], save);
8dfe0afc
JF
2051 char *xml(NULL);
2052 uint32_t size;
2053 plist_to_xml(plist, &xml, &size);
2054 _scope({ free(xml); });
2055 put(proxy, xml, size);
23c11ee8
JF
2056 }));
2057
2058 folder.Open(executable, fun([&](std::streambuf &buffer) {
23c11ee8
JF
2059 folder.Save(executable, fun([&](std::streambuf &save) {
2060 Slots slots;
2061 slots[1] = local.at(info);
2062 slots[3] = local.at(signature);
7f5ad603 2063 Sign(buffer, local[executable], save, identifier, entitlements, key, slots);
23c11ee8
JF
2064 }));
2065 }));
2066
2067 for (const auto &hash : local)
2068 remote[root + hash.first] = hash.second;
2069
2070 return executable;
2071}
489c97b8 2072#endif
23c11ee8 2073
0326ab11 2074#endif
a0c715e9
JF
2075}
2076
0326ab11 2077#ifndef LDID_NOTOOLS
a7f01a65 2078int main(int argc, char *argv[]) {
489c97b8 2079#ifndef LDID_NOSMIME
30c64adb 2080 OpenSSL_add_all_algorithms();
489c97b8 2081#endif
30c64adb 2082
5525a5a7
JF
2083 union {
2084 uint16_t word;
2085 uint8_t byte[2];
2086 } endian = {1};
2087
2088 little_ = endian.byte[0];
2089
20e7eb29 2090 bool flag_r(false);
9c83be90 2091 bool flag_e(false);
a362a82f 2092
fdbee693 2093#ifndef LDID_NOFLAGT
a362a82f 2094 bool flag_T(false);
fdbee693 2095#endif
20c5f1e8 2096
fdb119ef 2097 bool flag_S(false);
20c5f1e8 2098 bool flag_s(false);
a362a82f 2099
c0cc1574 2100 bool flag_D(false);
c0cc1574 2101
8c417842
JF
2102 bool flag_A(false);
2103 bool flag_a(false);
2104
56f0487d
JF
2105 bool flag_u(false);
2106
c0cc1574
JF
2107 uint32_t flag_CPUType(_not(uint32_t));
2108 uint32_t flag_CPUSubtype(_not(uint32_t));
2109
5d7ceb5d
JF
2110 const char *flag_I(NULL);
2111
fdbee693 2112#ifndef LDID_NOFLAGT
a362a82f
JF
2113 bool timeh(false);
2114 uint32_t timev(0);
fdbee693 2115#endif
a362a82f 2116
4d4682ef 2117 Map entitlements;
30c64adb 2118 Map key;
a0c715e9 2119 ldid::Slots slots;
c05d9758 2120
a362a82f
JF
2121 std::vector<std::string> files;
2122
a960f392
JF
2123 if (argc == 1) {
2124 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
9c83be90 2125 fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
a960f392
JF
2126 fprintf(stderr, " %s -S cat\n", argv[0]);
2127 fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
2128 exit(0);
2129 }
2130
a362a82f
JF
2131 for (int argi(1); argi != argc; ++argi)
2132 if (argv[argi][0] != '-')
2133 files.push_back(argv[argi]);
2134 else switch (argv[argi][1]) {
fac3d3e3
JF
2135 case 'r':
2136 _assert(!flag_s);
2137 _assert(!flag_S);
2138 flag_r = true;
2139 break;
2140
9c83be90 2141 case 'e': flag_e = true; break;
c05d9758 2142
e57b1f91
JF
2143 case 'E': {
2144 const char *slot = argv[argi] + 2;
2145 const char *colon = strchr(slot, ':');
2146 _assert(colon != NULL);
2147 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
2148 char *arge;
2149 unsigned number(strtoul(slot, &arge, 0));
2150 _assert(arge == colon);
707027e8 2151 sha1(slots[number], file.data(), file.size());
e57b1f91
JF
2152 } break;
2153
c0cc1574 2154 case 'D': flag_D = true; break;
c0cc1574 2155
8c417842
JF
2156 case 'a': flag_a = true; break;
2157
2158 case 'A':
fac3d3e3 2159 _assert(!flag_A);
8c417842
JF
2160 flag_A = true;
2161 if (argv[argi][2] != '\0') {
2162 const char *cpu = argv[argi] + 2;
2163 const char *colon = strchr(cpu, ':');
2164 _assert(colon != NULL);
2165 char *arge;
2166 flag_CPUType = strtoul(cpu, &arge, 0);
2167 _assert(arge == colon);
2168 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
2169 _assert(arge == argv[argi] + strlen(argv[argi]));
2170 }
2171 break;
2172
20c5f1e8 2173 case 's':
fac3d3e3 2174 _assert(!flag_r);
20c5f1e8
JF
2175 _assert(!flag_S);
2176 flag_s = true;
2177 break;
2178
c05d9758 2179 case 'S':
fac3d3e3 2180 _assert(!flag_r);
20c5f1e8 2181 _assert(!flag_s);
c05d9758
JF
2182 flag_S = true;
2183 if (argv[argi][2] != '\0') {
2184 const char *xml = argv[argi] + 2;
4d4682ef 2185 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
c05d9758
JF
2186 }
2187 break;
a362a82f 2188
30c64adb 2189 case 'K':
d73a3d58
JF
2190 if (argv[argi][2] != '\0')
2191 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
30c64adb
JF
2192 break;
2193
fdbee693 2194#ifndef LDID_NOFLAGT
a362a82f
JF
2195 case 'T': {
2196 flag_T = true;
2197 if (argv[argi][2] == '-')
2198 timeh = true;
2199 else {
2200 char *arge;
2201 timev = strtoul(argv[argi] + 2, &arge, 0);
2202 _assert(arge == argv[argi] + strlen(argv[argi]));
2203 }
2204 } break;
fdbee693 2205#endif
a362a82f 2206
56f0487d
JF
2207 case 'u': {
2208 flag_u = true;
2209 } break;
2210
5d7ceb5d
JF
2211 case 'I': {
2212 flag_I = argv[argi] + 2;
2213 } break;
2214
a362a82f
JF
2215 default:
2216 goto usage;
2217 break;
2218 }
2219
fac3d3e3
JF
2220 _assert(flag_S || key.empty());
2221 _assert(flag_S || flag_I == NULL);
f4b2df35 2222
a362a82f
JF
2223 if (files.empty()) usage: {
2224 exit(0);
2225 }
2226
2227 size_t filei(0), filee(0);
2228 _foreach (file, files) try {
d4187e53 2229 std::string path(file);
5d7ceb5d 2230
23c11ee8
JF
2231 struct stat info;
2232 _syscall(stat(path.c_str(), &info));
8762082f 2233
23c11ee8 2234 if (S_ISDIR(info.st_mode)) {
489c97b8 2235#ifndef LDID_NOPLIST
23c11ee8
JF
2236 _assert(!flag_r);
2237 ldid::DiskFolder folder(path);
2238 std::map<std::string, std::vector<char>> hashes;
4d03333f 2239 path += "/" + Bundle("", folder, key, hashes, entitlements);
489c97b8
JF
2240#else
2241 _assert(false);
2242#endif
23c11ee8
JF
2243 } else if (flag_S || flag_r) {
2244 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
8762082f 2245
4d4682ef 2246 std::filebuf output;
23c11ee8
JF
2247 Split split(path);
2248 auto temp(Temporary(output, split));
4d4682ef 2249
e0098838 2250 if (flag_r)
a0c715e9 2251 ldid::Unsign(input.data(), input.size(), output);
8762082f 2252 else {
23c11ee8 2253 std::string identifier(flag_I ?: split.base.c_str());
ffdd1183 2254 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
8762082f 2255 }
34f4c1d8 2256
d4187e53 2257 Commit(path, temp);
fdb119ef
JF
2258 }
2259
fdbee693
JF
2260 bool modify(false);
2261#ifndef LDID_NOFLAGT
2262 if (flag_T)
2263 modify = true;
2264#endif
2265 if (flag_s)
2266 modify = true;
2267
2268 Map mapping(path, modify);
dede6121 2269 FatHeader fat_header(mapping.data(), mapping.size());
a362a82f 2270
0a033524 2271 _foreach (mach_header, fat_header.GetMachHeaders()) {
d840a088 2272 struct linkedit_data_command *signature(NULL);
7b496abd
JF
2273 struct encryption_info_command *encryption(NULL);
2274
8c417842
JF
2275 if (flag_A) {
2276 if (mach_header.GetCPUType() != flag_CPUType)
2277 continue;
2278 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
2279 continue;
2280 }
2281
2282 if (flag_a)
2283 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
2284
0a033524
JF
2285 _foreach (load_command, mach_header.GetLoadCommands()) {
2286 uint32_t cmd(mach_header.Swap(load_command->cmd));
2287
cad40c43 2288 if (false);
0a033524
JF
2289 else if (cmd == LC_CODE_SIGNATURE)
2290 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
843aea8c 2291 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
7b496abd 2292 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
56f0487d
JF
2293 else if (cmd == LC_LOAD_DYLIB) {
2294 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
2295 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
2296
2297 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
2298 if (flag_u) {
2299 Version version;
2300 version.value = mach_header.Swap(dylib_command->dylib.current_version);
2301 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
2302 }
2303 }
2304 }
fdbee693 2305#ifndef LDID_NOFLAGT
cad40c43 2306 else if (cmd == LC_ID_DYLIB) {
0a033524 2307 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
a362a82f 2308
0a033524
JF
2309 if (flag_T) {
2310 uint32_t timed;
a362a82f 2311
0a033524
JF
2312 if (!timeh)
2313 timed = timev;
2314 else {
2315 dylib_command->dylib.timestamp = 0;
2316 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
2317 }
a362a82f 2318
0a033524
JF
2319 dylib_command->dylib.timestamp = mach_header.Swap(timed);
2320 }
7b496abd 2321 }
fdbee693 2322#endif
7b496abd
JF
2323 }
2324
7b496abd
JF
2325 if (flag_D) {
2326 _assert(encryption != NULL);
2327 encryption->cryptid = mach_header.Swap(0);
a362a82f 2328 }
a362a82f 2329
0a033524
JF
2330 if (flag_e) {
2331 _assert(signature != NULL);
9c83be90 2332
0a033524 2333 uint32_t data = mach_header.Swap(signature->dataoff);
9c83be90 2334
0a033524
JF
2335 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2336 uint8_t *blob = top + data;
2337 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
9c83be90 2338
0a033524
JF
2339 for (size_t index(0); index != Swap(super->count); ++index)
2340 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
2341 uint32_t begin = Swap(super->index[index].offset);
2342 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
b9652d6e 2343 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
0a033524
JF
2344 }
2345 }
9c83be90 2346
0a033524
JF
2347 if (flag_s) {
2348 _assert(signature != NULL);
20c5f1e8 2349
0a033524 2350 uint32_t data = mach_header.Swap(signature->dataoff);
20c5f1e8 2351
0a033524
JF
2352 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
2353 uint8_t *blob = top + data;
2354 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
20c5f1e8 2355
0a033524
JF
2356 for (size_t index(0); index != Swap(super->count); ++index)
2357 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
2358 uint32_t begin = Swap(super->index[index].offset);
2359 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
20c5f1e8 2360
84d29a1c 2361 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
0a033524 2362 uint32_t pages = Swap(directory->nCodeSlots);
20c5f1e8 2363
0a033524
JF
2364 if (pages != 1)
2365 for (size_t i = 0; i != pages - 1; ++i)
b9652d6e 2366 sha1(hashes[i], top + PageSize_ * i, PageSize_);
0a033524 2367 if (pages != 0)
b9652d6e 2368 sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1);
0a033524
JF
2369 }
2370 }
fdb119ef
JF
2371 }
2372
a362a82f
JF
2373 ++filei;
2374 } catch (const char *) {
2375 ++filee;
2376 ++filei;
2377 }
2378
2379 return filee;
2380}
0326ab11 2381#endif