]> git.saurik.com Git - ldid.git/blame - ldid.cpp
Fix regression on FAT files (from 64-bit support).
[ldid.git] / ldid.cpp
CommitLineData
ab113d22 1/* ldid - (Mach-O) Link-Loader Identity Editor
16efdde5 2 * Copyright (C) 2007-2015 Jay Freeman (saurik)
a362a82f
JF
3*/
4
dd6c06ed
JF
5/* GNU Affero General Public License, Version 3 {{{ */
6/*
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
e0524446
JF
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
dd6c06ed 11
e0524446
JF
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dd6c06ed
JF
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
e0524446
JF
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19**/
20/* }}} */
a362a82f 21
fa59c178
JF
22#include <cstdio>
23#include <cstdlib>
a362a82f 24#include <cstring>
4d4682ef 25#include <fstream>
23c11ee8 26#include <iostream>
4527f2af 27#include <memory>
23c11ee8 28#include <set>
4d4682ef 29#include <sstream>
a362a82f
JF
30#include <string>
31#include <vector>
32
54a0f854 33#include <dirent.h>
fa59c178 34#include <errno.h>
dede6121 35#include <fcntl.h>
23c11ee8 36#include <regex.h>
fa59c178
JF
37#include <stdbool.h>
38#include <stdint.h>
a7f01a65 39#include <unistd.h>
dede6121
JF
40
41#include <sys/mman.h>
42#include <sys/stat.h>
23c11ee8 43#include <sys/types.h>
dede6121 44
489c97b8 45#ifndef LDID_NOSMIME
30c64adb
JF
46#include <openssl/err.h>
47#include <openssl/pem.h>
48#include <openssl/pkcs7.h>
49#include <openssl/pkcs12.h>
489c97b8 50#endif
84d29a1c
JF
51
52#ifdef __APPLE__
53#include <CommonCrypto/CommonDigest.h>
9ec8439b 54
84d29a1c
JF
55#define LDID_SHA1_DIGEST_LENGTH CC_SHA1_DIGEST_LENGTH
56#define LDID_SHA1 CC_SHA1
57#define LDID_SHA1_CTX CC_SHA1_CTX
58#define LDID_SHA1_Init CC_SHA1_Init
59#define LDID_SHA1_Update CC_SHA1_Update
60#define LDID_SHA1_Final CC_SHA1_Final
9ec8439b
JF
61
62#define LDID_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
63#define LDID_SHA256 CC_SHA256
64#define LDID_SHA256_CTX CC_SHA256_CTX
65#define LDID_SHA256_Init CC_SHA256_Init
66#define LDID_SHA256_Update CC_SHA256_Update
67#define LDID_SHA256_Final CC_SHA256_Final
84d29a1c 68#else
a50bb1be 69#include <openssl/sha.h>
9ec8439b 70
84d29a1c
JF
71#define LDID_SHA1_DIGEST_LENGTH SHA_DIGEST_LENGTH
72#define LDID_SHA1 SHA1
73#define LDID_SHA1_CTX SHA_CTX
74#define LDID_SHA1_Init SHA1_Init
75#define LDID_SHA1_Update SHA1_Update
76#define LDID_SHA1_Final SHA1_Final
9ec8439b
JF
77
78#define LDID_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
79#define LDID_SHA256 SHA256
80#define LDID_SHA256_CTX SHA256_CTX
81#define LDID_SHA256_Init SHA256_Init
82#define LDID_SHA256_Update SHA256_Update
83#define LDID_SHA256_Final SHA256_Final
84d29a1c 84#endif
a50bb1be 85
489c97b8 86#ifndef LDID_NOPLIST
8dfe0afc 87#include <plist/plist.h>
1190f447
JF
88#elif __APPLE__
89#include <CoreFoundation/CoreFoundation.h>
489c97b8 90#endif
15babeef 91
a0c715e9
JF
92#include "ldid.hpp"
93
fa59c178
JF
94#define _assert___(line) \
95 #line
96#define _assert__(line) \
97 _assert___(line)
fa59c178 98
3736a011
JF
99#ifndef $
100#define $(value) value
101#endif
102
489c97b8 103#ifdef __EXCEPTIONS
eff987d2 104#define _assert_(expr, format, ...) \
fa59c178 105 do if (!(expr)) { \
3736a011
JF
106 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
107 throw $(__FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"); \
fa59c178 108 } while (false)
489c97b8
JF
109#else
110// XXX: this is not acceptable
111#define _assert_(expr, format, ...) \
112 do if (!(expr)) { \
3736a011 113 fprintf(stderr, $("%s(%u): _assert(): " format "\n"), __FILE__, __LINE__, ## __VA_ARGS__); \
489c97b8
JF
114 exit(-1); \
115 } while (false)
116#endif
fa59c178 117
eff987d2 118#define _assert(expr) \
3736a011 119 _assert_(expr, "%s", $(#expr))
eff987d2 120
23c11ee8
JF
121#define _syscall(expr, ...) [&] { for (;;) { \
122 auto _value(expr); \
123 if ((long) _value != -1) \
124 return _value; \
125 int error(errno); \
126 if (error == EINTR) \
127 continue; \
5c303467
JF
128 /* XXX: EINTR is included in this list to fix g++ */ \
129 for (auto success : (long[]) {EINTR, __VA_ARGS__}) \
23c11ee8
JF
130 if (error == success) \
131 return (decltype(expr)) -success; \
132 _assert_(false, "errno=%u", error); \
133} }()
fa59c178
JF
134
135#define _trace() \
3736a011 136 fprintf(stderr, $("_trace(%s:%u): %s\n"), __FILE__, __LINE__, $(__FUNCTION__))
fa59c178
JF
137
138#define _not(type) \
139 ((type) ~ (type) 0)
140
141#define _packed \
142 __attribute__((packed))
143
144template <typename Type_>
145struct Iterator_ {
146 typedef typename Type_::const_iterator Result;
147};
148
149#define _foreach(item, list) \
150 for (bool _stop(true); _stop; ) \
151 for (const __typeof__(list) &_list = (list); _stop; _stop = false) \
152 for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \
153 for (bool _suck(true); _suck; _suck = false) \
154 for (const __typeof__(*_item) &item = *_item; _suck; _suck = false)
155
23c11ee8
JF
156class _Scope {
157};
158
159template <typename Function_>
160class Scope :
161 public _Scope
162{
163 private:
164 Function_ function_;
165
166 public:
167 Scope(const Function_ &function) :
168 function_(function)
169 {
170 }
171
172 ~Scope() {
173 function_();
174 }
175};
176
177template <typename Function_>
178Scope<Function_> _scope(const Function_ &function) {
179 return Scope<Function_>(function);
180}
181
182#define _scope__(counter, function) \
183 __attribute__((__unused__)) \
184 const _Scope &_scope ## counter(_scope([&]function))
185#define _scope_(counter, function) \
186 _scope__(counter, function)
187#define _scope(function) \
188 _scope_(__COUNTER__, function)
189
6f420711
JF
190#define CPU_ARCH_MASK uint32_t(0xff000000)
191#define CPU_ARCH_ABI64 uint32_t(0x01000000)
192
193#define CPU_TYPE_ANY uint32_t(-1)
194#define CPU_TYPE_VAX uint32_t( 1)
195#define CPU_TYPE_MC680x0 uint32_t( 6)
196#define CPU_TYPE_X86 uint32_t( 7)
197#define CPU_TYPE_MC98000 uint32_t(10)
198#define CPU_TYPE_HPPA uint32_t(11)
199#define CPU_TYPE_ARM uint32_t(12)
200#define CPU_TYPE_MC88000 uint32_t(13)
201#define CPU_TYPE_SPARC uint32_t(14)
202#define CPU_TYPE_I860 uint32_t(15)
203#define CPU_TYPE_POWERPC uint32_t(18)
204
205#define CPU_TYPE_I386 CPU_TYPE_X86
206
207#define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM)
208#define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC)
209#define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86)
210
a362a82f
JF
211struct fat_header {
212 uint32_t magic;
213 uint32_t nfat_arch;
c05d9758 214} _packed;
a362a82f
JF
215
216#define FAT_MAGIC 0xcafebabe
217#define FAT_CIGAM 0xbebafeca
218
219struct fat_arch {
220 uint32_t cputype;
221 uint32_t cpusubtype;
222 uint32_t offset;
223 uint32_t size;
224 uint32_t align;
c05d9758 225} _packed;
a362a82f
JF
226
227struct mach_header {
228 uint32_t magic;
229 uint32_t cputype;
04802ab1 230 uint32_t cpusubtype;
a362a82f
JF
231 uint32_t filetype;
232 uint32_t ncmds;
233 uint32_t sizeofcmds;
234 uint32_t flags;
c05d9758 235} _packed;
a362a82f 236
fdb119ef 237#define MH_MAGIC 0xfeedface
a362a82f
JF
238#define MH_CIGAM 0xcefaedfe
239
3cbc6463
JF
240#define MH_MAGIC_64 0xfeedfacf
241#define MH_CIGAM_64 0xcffaedfe
242
82813bde
JF
243#define MH_DYLDLINK 0x4
244
4a864785 245#define MH_OBJECT 0x1
efd6cd4a
JF
246#define MH_EXECUTE 0x2
247#define MH_DYLIB 0x6
f4f5892d 248#define MH_DYLINKER 0x7
efd6cd4a
JF
249#define MH_BUNDLE 0x8
250#define MH_DYLIB_STUB 0x9
a362a82f
JF
251
252struct load_command {
253 uint32_t cmd;
254 uint32_t cmdsize;
c05d9758 255} _packed;
a362a82f 256
4a57e66c
JF
257#define LC_REQ_DYLD uint32_t(0x80000000)
258
259#define LC_SEGMENT uint32_t(0x01)
260#define LC_SYMTAB uint32_t(0x02)
261#define LC_DYSYMTAB uint32_t(0x0b)
262#define LC_LOAD_DYLIB uint32_t(0x0c)
263#define LC_ID_DYLIB uint32_t(0x0d)
289ccbbc 264#define LC_SEGMENT_64 uint32_t(0x19)
4a57e66c
JF
265#define LC_UUID uint32_t(0x1b)
266#define LC_CODE_SIGNATURE uint32_t(0x1d)
267#define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e)
268#define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD)
c0cc1574 269#define LC_ENCRYPTION_INFO uint32_t(0x21)
4a57e66c
JF
270#define LC_DYLD_INFO uint32_t(0x22)
271#define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD)
843aea8c 272#define LC_ENCRYPTION_INFO_64 uint32_t(0x2c)
a362a82f 273
56f0487d
JF
274union Version {
275 struct {
276 uint8_t patch;
277 uint8_t minor;
278 uint16_t major;
279 } _packed;
280
281 uint32_t value;
282};
283
a362a82f
JF
284struct dylib {
285 uint32_t name;
286 uint32_t timestamp;
287 uint32_t current_version;
288 uint32_t compatibility_version;
c05d9758 289} _packed;
a362a82f
JF
290
291struct dylib_command {
292 uint32_t cmd;
293 uint32_t cmdsize;
294 struct dylib dylib;
c05d9758 295} _packed;
a362a82f
JF
296
297struct uuid_command {
298 uint32_t cmd;
299 uint32_t cmdsize;
300 uint8_t uuid[16];
c05d9758 301} _packed;
a362a82f 302
20e7eb29
JF
303struct symtab_command {
304 uint32_t cmd;
305 uint32_t cmdsize;
306 uint32_t symoff;
307 uint32_t nsyms;
308 uint32_t stroff;
309 uint32_t strsize;
310} _packed;
311
4a57e66c
JF
312struct dyld_info_command {
313 uint32_t cmd;
314 uint32_t cmdsize;
315 uint32_t rebase_off;
316 uint32_t rebase_size;
317 uint32_t bind_off;
318 uint32_t bind_size;
319 uint32_t weak_bind_off;
320 uint32_t weak_bind_size;
321 uint32_t lazy_bind_off;
322 uint32_t lazy_bind_size;
323 uint32_t export_off;
324 uint32_t export_size;
325} _packed;
326
327struct dysymtab_command {
328 uint32_t cmd;
329 uint32_t cmdsize;
330 uint32_t ilocalsym;
331 uint32_t nlocalsym;
332 uint32_t iextdefsym;
333 uint32_t nextdefsym;
334 uint32_t iundefsym;
335 uint32_t nundefsym;
336 uint32_t tocoff;
337 uint32_t ntoc;
338 uint32_t modtaboff;
339 uint32_t nmodtab;
340 uint32_t extrefsymoff;
341 uint32_t nextrefsyms;
342 uint32_t indirectsymoff;
343 uint32_t nindirectsyms;
344 uint32_t extreloff;
345 uint32_t nextrel;
346 uint32_t locreloff;
347 uint32_t nlocrel;
348} _packed;
349
350struct dylib_table_of_contents {
351 uint32_t symbol_index;
352 uint32_t module_index;
353} _packed;
354
355struct dylib_module {
356 uint32_t module_name;
357 uint32_t iextdefsym;
358 uint32_t nextdefsym;
359 uint32_t irefsym;
360 uint32_t nrefsym;
361 uint32_t ilocalsym;
362 uint32_t nlocalsym;
363 uint32_t iextrel;
364 uint32_t nextrel;
365 uint32_t iinit_iterm;
366 uint32_t ninit_nterm;
367 uint32_t objc_module_info_addr;
368 uint32_t objc_module_info_size;
369} _packed;
370
371struct dylib_reference {
372 uint32_t isym:24;
373 uint32_t flags:8;
374} _packed;
375
376struct relocation_info {
377 int32_t r_address;
378 uint32_t r_symbolnum:24;
379 uint32_t r_pcrel:1;
380 uint32_t r_length:2;
381 uint32_t r_extern:1;
382 uint32_t r_type:4;
383} _packed;
384
385struct nlist {
386 union {
387 char *n_name;
388 int32_t n_strx;
389 } n_un;
390
391 uint8_t n_type;
392 uint8_t n_sect;
393 uint8_t n_desc;
394 uint32_t n_value;
395} _packed;
396
6e83315b
JF
397struct segment_command {
398 uint32_t cmd;
399 uint32_t cmdsize;
400 char segname[16];
401 uint32_t vmaddr;
402 uint32_t vmsize;
403 uint32_t fileoff;
404 uint32_t filesize;
405 uint32_t maxprot;
406 uint32_t initprot;
407 uint32_t nsects;
408 uint32_t flags;
429e34a5 409} _packed;
6e83315b 410
289ccbbc
JF
411struct segment_command_64 {
412 uint32_t cmd;
413 uint32_t cmdsize;
414 char segname[16];
415 uint64_t vmaddr;
416 uint64_t vmsize;
417 uint64_t fileoff;
418 uint64_t filesize;
419 uint32_t maxprot;
420 uint32_t initprot;
421 uint32_t nsects;
422 uint32_t flags;
429e34a5 423} _packed;
289ccbbc 424
6e83315b
JF
425struct section {
426 char sectname[16];
427 char segname[16];
428 uint32_t addr;
429 uint32_t size;
430 uint32_t offset;
431 uint32_t align;
432 uint32_t reloff;
433 uint32_t nreloc;
434 uint32_t flags;
435 uint32_t reserved1;
436 uint32_t reserved2;
429e34a5 437} _packed;
6e83315b 438
289ccbbc
JF
439struct section_64 {
440 char sectname[16];
441 char segname[16];
442 uint64_t addr;
443 uint64_t size;
444 uint32_t offset;
445 uint32_t align;
446 uint32_t reloff;
447 uint32_t nreloc;
448 uint32_t flags;
449 uint32_t reserved1;
450 uint32_t reserved2;
e4d33eec 451 uint32_t reserved3;
429e34a5 452} _packed;
289ccbbc 453
fdb119ef
JF
454struct linkedit_data_command {
455 uint32_t cmd;
456 uint32_t cmdsize;
457 uint32_t dataoff;
458 uint32_t datasize;
c05d9758 459} _packed;
fdb119ef 460
c0cc1574
JF
461struct encryption_info_command {
462 uint32_t cmd;
463 uint32_t cmdsize;
464 uint32_t cryptoff;
465 uint32_t cryptsize;
466 uint32_t cryptid;
467} _packed;
468
4a864785
JF
469#define BIND_OPCODE_MASK 0xf0
470#define BIND_IMMEDIATE_MASK 0x0f
471#define BIND_OPCODE_DONE 0x00
472#define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10
473#define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20
474#define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30
475#define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40
476#define BIND_OPCODE_SET_TYPE_IMM 0x50
477#define BIND_OPCODE_SET_ADDEND_SLEB 0x60
478#define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70
479#define BIND_OPCODE_ADD_ADDR_ULEB 0x80
480#define BIND_OPCODE_DO_BIND 0x90
481#define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0
482#define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0
483#define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0
484
b4b49374
JF
485struct : ldid::Progress {
486 virtual void operator()(const std::string &value) const {
487 }
488
489 virtual void operator()(double value) const {
490 }
491} dummy_;
492
493struct Progression : ldid::Progress {
494 const ldid::Progress &progress_;
495 std::string name_;
496
497 Progression(const ldid::Progress &progress, const std::string &name) :
498 progress_(progress),
499 name_(name)
500 {
501 }
502
503 virtual void operator()(const std::string &value) const {
504 return progress_(name_ + " (" + value + ")");
505 }
506
507 virtual void operator()(double value) const {
508 return progress_(value);
509 }
510};
e1d26767 511
f9cd1d1c
JF
512static std::streamsize read(std::streambuf &stream, void *data, size_t size) {
513 auto writ(stream.sgetn(static_cast<char *>(data), size));
514 _assert(writ >= 0);
515 return writ;
516}
517
ef3241bb 518static inline void get(std::streambuf &stream, void *data, size_t size) {
f9cd1d1c 519 _assert(read(stream, data, size) == size);
4d4682ef
JF
520}
521
ef3241bb 522static inline void put(std::streambuf &stream, const void *data, size_t size) {
4d4682ef
JF
523 _assert(stream.sputn(static_cast<const char *>(data), size) == size);
524}
525
b4b49374
JF
526static inline void put(std::streambuf &stream, const void *data, size_t size, const ldid::Progress &progress) {
527 progress(0);
e1d26767
JF
528 for (size_t total(0); total != size;) {
529 auto writ(std::min(size - total, size_t(4096 * 4)));
530 _assert(stream.sputn(static_cast<const char *>(data) + total, writ) == writ);
531 total += writ;
b4b49374 532 progress(double(total) / size);
e1d26767
JF
533 }
534}
535
f9cd1d1c
JF
536static size_t most(std::streambuf &stream, void *data, size_t size) {
537 size_t total(size);
538 while (size > 0)
539 if (auto writ = read(stream, data, size))
540 size -= writ;
541 else break;
542 return total - size;
543}
544
ef3241bb 545static inline void pad(std::streambuf &stream, size_t size) {
4d4682ef
JF
546 char padding[size];
547 memset(padding, 0, size);
548 put(stream, padding, size);
549}
550
4374152f
JF
551template <typename Type_>
552Type_ Align(Type_ value, size_t align) {
553 value += align - 1;
554 value /= align;
555 value *= align;
556 return value;
557}
558
b9652d6e
JF
559static const uint8_t PageShift_(0x0c);
560static const uint32_t PageSize_(1 << PageShift_);
561
f65c321b 562static inline uint16_t Swap_(uint16_t value) {
fdb119ef
JF
563 return
564 ((value >> 8) & 0x00ff) |
565 ((value << 8) & 0xff00);
566}
567
f65c321b 568static inline uint32_t Swap_(uint32_t value) {
fdb119ef
JF
569 value = ((value >> 8) & 0x00ff00ff) |
570 ((value << 8) & 0xff00ff00);
571 value = ((value >> 16) & 0x0000ffff) |
572 ((value << 16) & 0xffff0000);
573 return value;
574}
575
f65c321b 576static inline uint64_t Swap_(uint64_t value) {
4374152f
JF
577 value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32;
578 value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16;
579 value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8;
580 return value;
581}
582
f65c321b 583static inline int16_t Swap_(int16_t value) {
fdb119ef
JF
584 return Swap_(static_cast<uint16_t>(value));
585}
586
f65c321b 587static inline int32_t Swap_(int32_t value) {
fdb119ef
JF
588 return Swap_(static_cast<uint32_t>(value));
589}
590
f65c321b 591static inline int64_t Swap_(int64_t value) {
4374152f
JF
592 return Swap_(static_cast<uint64_t>(value));
593}
594
f65c321b 595static bool little_(true);
5525a5a7 596
f65c321b 597static inline uint16_t Swap(uint16_t value) {
5525a5a7 598 return little_ ? Swap_(value) : value;
fdb119ef
JF
599}
600
f65c321b 601static inline uint32_t Swap(uint32_t value) {
5525a5a7 602 return little_ ? Swap_(value) : value;
fdb119ef
JF
603}
604
f65c321b 605static inline uint64_t Swap(uint64_t value) {
4374152f
JF
606 return little_ ? Swap_(value) : value;
607}
608
f65c321b 609static inline int16_t Swap(int16_t value) {
fdb119ef
JF
610 return Swap(static_cast<uint16_t>(value));
611}
612
f65c321b 613static inline int32_t Swap(int32_t value) {
fdb119ef
JF
614 return Swap(static_cast<uint32_t>(value));
615}
616
f65c321b 617static inline int64_t Swap(int64_t value) {
4374152f
JF
618 return Swap(static_cast<uint64_t>(value));
619}
620
4d4682ef 621class Swapped {
0a033524 622 protected:
a362a82f
JF
623 bool swapped_;
624
4d4682ef 625 Swapped() :
0a033524
JF
626 swapped_(false)
627 {
628 }
629
4d4682ef
JF
630 public:
631 Swapped(bool swapped) :
632 swapped_(swapped)
633 {
a362a82f
JF
634 }
635
4d4682ef
JF
636 template <typename Type_>
637 Type_ Swap(Type_ value) const {
4374152f
JF
638 return swapped_ ? Swap_(value) : value;
639 }
4d4682ef 640};
4374152f 641
4d4682ef
JF
642class Data :
643 public Swapped
644{
645 private:
646 void *base_;
647 size_t size_;
a362a82f 648
4d4682ef
JF
649 public:
650 Data(void *base, size_t size) :
651 base_(base),
652 size_(size)
653 {
4374152f
JF
654 }
655
0a033524
JF
656 void *GetBase() const {
657 return base_;
658 }
a362a82f 659
0a033524
JF
660 size_t GetSize() const {
661 return size_;
662 }
663};
a362a82f 664
0a033524
JF
665class MachHeader :
666 public Data
667{
668 private:
669 bool bits64_;
670
671 struct mach_header *mach_header_;
672 struct load_command *load_command_;
673
674 public:
675 MachHeader(void *base, size_t size) :
676 Data(base, size)
677 {
678 mach_header_ = (mach_header *) base;
a362a82f 679
3cbc6463
JF
680 switch (Swap(mach_header_->magic)) {
681 case MH_CIGAM:
682 swapped_ = !swapped_;
683 case MH_MAGIC:
684 bits64_ = false;
685 break;
686
687 case MH_CIGAM_64:
688 swapped_ = !swapped_;
689 case MH_MAGIC_64:
690 bits64_ = true;
691 break;
692
693 default:
694 _assert(false);
695 }
696
697 void *post = mach_header_ + 1;
698 if (bits64_)
699 post = (uint32_t *) post + 1;
700 load_command_ = (struct load_command *) post;
a362a82f
JF
701
702 _assert(
703 Swap(mach_header_->filetype) == MH_EXECUTE ||
704 Swap(mach_header_->filetype) == MH_DYLIB ||
f4f5892d 705 Swap(mach_header_->filetype) == MH_DYLINKER ||
a362a82f
JF
706 Swap(mach_header_->filetype) == MH_BUNDLE
707 );
708 }
709
4d4682ef
JF
710 bool Bits64() const {
711 return bits64_;
712 }
713
afbb7c8e
JF
714 struct mach_header *operator ->() const {
715 return mach_header_;
716 }
717
4374152f
JF
718 operator struct mach_header *() const {
719 return mach_header_;
720 }
721
04802ab1
JF
722 uint32_t GetCPUType() const {
723 return Swap(mach_header_->cputype);
724 }
725
4374152f 726 uint32_t GetCPUSubtype() const {
04802ab1
JF
727 return Swap(mach_header_->cpusubtype) & 0xff;
728 }
729
4374152f
JF
730 struct load_command *GetLoadCommand() const {
731 return load_command_;
732 }
733
0a033524 734 std::vector<struct load_command *> GetLoadCommands() const {
a362a82f
JF
735 std::vector<struct load_command *> load_commands;
736
3cbc6463 737 struct load_command *load_command = load_command_;
a362a82f
JF
738 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
739 load_commands.push_back(load_command);
740 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
741 }
742
743 return load_commands;
744 }
6e83315b 745
e4d33eec
JF
746 void ForSection(const ldid::Functor<void (const char *, const char *, void *, size_t)> &code) const {
747 _foreach (load_command, GetLoadCommands())
748 switch (Swap(load_command->cmd)) {
749 case LC_SEGMENT: {
750 auto segment(reinterpret_cast<struct segment_command *>(load_command));
751 code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize);
752 auto section(reinterpret_cast<struct section *>(segment + 1));
753 for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section)
754 code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size);
755 } break;
756
757 case LC_SEGMENT_64: {
758 auto segment(reinterpret_cast<struct segment_command_64 *>(load_command));
759 code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize);
760 auto section(reinterpret_cast<struct section_64 *>(segment + 1));
761 for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section)
762 code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size);
763 } break;
764 }
765 }
766
6e83315b 767 template <typename Target_>
6e1a740e
JF
768 Target_ *GetOffset(uint32_t offset) const {
769 return reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_);
6e83315b
JF
770 }
771};
772
289ccbbc
JF
773class FatMachHeader :
774 public MachHeader
775{
776 private:
777 fat_arch *fat_arch_;
778
779 public:
780 FatMachHeader(void *base, size_t size, fat_arch *fat_arch) :
781 MachHeader(base, size),
782 fat_arch_(fat_arch)
783 {
784 }
785
786 fat_arch *GetFatArch() const {
787 return fat_arch_;
788 }
789};
790
0a033524
JF
791class FatHeader :
792 public Data
793{
794 private:
795 fat_header *fat_header_;
289ccbbc 796 std::vector<FatMachHeader> mach_headers_;
0a033524
JF
797
798 public:
799 FatHeader(void *base, size_t size) :
800 Data(base, size)
801 {
802 fat_header_ = reinterpret_cast<struct fat_header *>(base);
803
804 if (Swap(fat_header_->magic) == FAT_CIGAM) {
805 swapped_ = !swapped_;
806 goto fat;
807 } else if (Swap(fat_header_->magic) != FAT_MAGIC) {
808 fat_header_ = NULL;
289ccbbc 809 mach_headers_.push_back(FatMachHeader(base, size, NULL));
0a033524
JF
810 } else fat: {
811 size_t fat_narch = Swap(fat_header_->nfat_arch);
812 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1);
813 size_t arch;
814 for (arch = 0; arch != fat_narch; ++arch) {
815 uint32_t arch_offset = Swap(fat_arch->offset);
816 uint32_t arch_size = Swap(fat_arch->size);
289ccbbc 817 mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch));
0a033524
JF
818 ++fat_arch;
819 }
820 }
821 }
822
289ccbbc 823 std::vector<FatMachHeader> &GetMachHeaders() {
0a033524
JF
824 return mach_headers_;
825 }
20e7eb29
JF
826
827 bool IsFat() const {
828 return fat_header_ != NULL;
829 }
6b38c173
JF
830
831 struct fat_header *operator ->() const {
832 return fat_header_;
833 }
4374152f
JF
834
835 operator struct fat_header *() const {
836 return fat_header_;
837 }
0a033524
JF
838};
839
4d4682ef
JF
840#define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00)
841#define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01)
842#define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02)
843#define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0)
844#define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02)
845#define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171)
846#define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1)
847#define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01)
c05d9758 848
4d4682ef
JF
849#define CSSLOT_CODEDIRECTORY uint32_t(0x00000)
850#define CSSLOT_INFOSLOT uint32_t(0x00001)
851#define CSSLOT_REQUIREMENTS uint32_t(0x00002)
852#define CSSLOT_RESOURCEDIR uint32_t(0x00003)
853#define CSSLOT_APPLICATION uint32_t(0x00004)
854#define CSSLOT_ENTITLEMENTS uint32_t(0x00005)
f74652ab 855#define CSSLOT_ALTERNATE uint32_t(0x01000)
4d4682ef
JF
856
857#define CSSLOT_SIGNATURESLOT uint32_t(0x10000)
858
f74652ab
JF
859#define CS_HASHTYPE_SHA160_160 1
860#define CS_HASHTYPE_SHA256_256 2
861#define CS_HASHTYPE_SHA256_160 3
862#define CS_HASHTYPE_SHA386_386 4
fdb119ef 863
803b4bc9
JF
864#if 0
865#define CS_EXECSEG_MAIN_BINARY 0x001 /* executable segment denotes main binary */
866#define CS_EXECSEG_ALLOW_UNSIGNED 0x010 /* allow unsigned pages (for debugging) */
867#define CS_EXECSEG_DEBUGGER 0x020 /* main binary is debugger */
868#define CS_EXECSEG_JIT 0x040 /* JIT enabled */
869#define CS_EXECSEG_SKIP_LV 0x080 /* skip library validation */
870#define CS_EXECSEG_CAN_LOAD_CDHASH 0x100 /* can bless cdhash for execution */
871#define CS_EXECSEG_CAN_EXEC_CDHASH 0x200 /* can execute blessed cdhash */
872#else
873enum SecCodeExecSegFlags {
874 kSecCodeExecSegMainBinary = 0x001,
875 kSecCodeExecSegAllowUnsigned = 0x010,
876 kSecCodeExecSegDebugger = 0x020,
877 kSecCodeExecSegJit = 0x040,
878 kSecCodeExecSegSkipLibraryVal = 0x080,
879 kSecCodeExecSegCanLoadCdHash = 0x100,
880 kSecCodeExecSegCanExecCdHash = 0x100,
881};
882#endif
883
fdb119ef
JF
884struct BlobIndex {
885 uint32_t type;
886 uint32_t offset;
c05d9758 887} _packed;
fdb119ef 888
c05d9758 889struct Blob {
fdb119ef
JF
890 uint32_t magic;
891 uint32_t length;
c05d9758
JF
892} _packed;
893
894struct SuperBlob {
895 struct Blob blob;
fdb119ef
JF
896 uint32_t count;
897 struct BlobIndex index[];
c05d9758 898} _packed;
fdb119ef
JF
899
900struct CodeDirectory {
fdb119ef
JF
901 uint32_t version;
902 uint32_t flags;
903 uint32_t hashOffset;
904 uint32_t identOffset;
905 uint32_t nSpecialSlots;
906 uint32_t nCodeSlots;
907 uint32_t codeLimit;
908 uint8_t hashSize;
909 uint8_t hashType;
296fd38e 910 uint8_t platform;
fdb119ef
JF
911 uint8_t pageSize;
912 uint32_t spare2;
b73d2333
JF
913 uint32_t scatterOffset;
914 uint32_t teamIDOffset;
803b4bc9
JF
915 uint32_t spare3;
916 uint64_t codeLimit64;
917 uint64_t execSegBase;
918 uint64_t execSegLimit;
919 uint64_t execSegFlags;
920#if 0 // version = 0x20500
921 uint32_t runtime;
922 uint32_t preEncryptOffset;
923#endif
924#if 0 // version = 0x20600
925 uint8_t linkageHashType;
926 uint8_t linkageTruncated;
927 uint16_t spare4;
928 uint32_t linkageOffset;
929 uint32_t linkageSize;
930#endif
c05d9758 931} _packed;
fdb119ef 932
296fd38e
JF
933enum CodeSignatureFlags {
934 kSecCodeSignatureHost = 0x0001,
935 kSecCodeSignatureAdhoc = 0x0002,
936 kSecCodeSignatureForceHard = 0x0100,
937 kSecCodeSignatureForceKill = 0x0200,
938 kSecCodeSignatureForceExpiration = 0x0400,
939 kSecCodeSignatureRestrict = 0x0800,
940 kSecCodeSignatureEnforcement = 0x1000,
941 kSecCodeSignatureLibraryValidation = 0x2000,
c83a840d 942 kSecCodeSignatureRuntime = 0x10000,
296fd38e
JF
943};
944
7cb8c1fc
JF
945enum Kind : uint32_t {
946 exprForm = 1, // prefix expr form
947};
948
949enum ExprOp : uint32_t {
950 opFalse, // unconditionally false
951 opTrue, // unconditionally true
952 opIdent, // match canonical code [string]
953 opAppleAnchor, // signed by Apple as Apple's product
954 opAnchorHash, // match anchor [cert hash]
955 opInfoKeyValue, // *legacy* - use opInfoKeyField [key; value]
956 opAnd, // binary prefix expr AND expr [expr; expr]
957 opOr, // binary prefix expr OR expr [expr; expr]
958 opCDHash, // match hash of CodeDirectory directly [cd hash]
959 opNot, // logical inverse [expr]
960 opInfoKeyField, // Info.plist key field [string; match suffix]
961 opCertField, // Certificate field [cert index; field name; match suffix]
962 opTrustedCert, // require trust settings to approve one particular cert [cert index]
963 opTrustedCerts, // require trust settings to approve the cert chain
964 opCertGeneric, // Certificate component by OID [cert index; oid; match suffix]
965 opAppleGenericAnchor, // signed by Apple in any capacity
966 opEntitlementField, // entitlement dictionary field [string; match suffix]
967 opCertPolicy, // Certificate policy by OID [cert index; oid; match suffix]
968 opNamedAnchor, // named anchor type
969 opNamedCode, // named subroutine
970 opPlatform, // platform constraint [integer]
971 exprOpCount // (total opcode count in use)
972};
973
974enum MatchOperation {
975 matchExists, // anything but explicit "false" - no value stored
976 matchEqual, // equal (CFEqual)
977 matchContains, // partial match (substring)
978 matchBeginsWith, // partial match (initial substring)
979 matchEndsWith, // partial match (terminal substring)
980 matchLessThan, // less than (string with numeric comparison)
981 matchGreaterThan, // greater than (string with numeric comparison)
982 matchLessEqual, // less or equal (string with numeric comparison)
983 matchGreaterEqual, // greater or equal (string with numeric comparison)
984};
985
986#define OID_ISO_MEMBER 42
987#define OID_US OID_ISO_MEMBER, 134, 72
988#define APPLE_OID OID_US, 0x86, 0xf7, 0x63
989#define APPLE_ADS_OID APPLE_OID, 0x64
990#define APPLE_EXTENSION_OID APPLE_ADS_OID, 6
991
fdbee693 992#ifndef LDID_NOFLAGT
a362a82f 993extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
fdbee693 994#endif
a362a82f 995
f74652ab
JF
996struct Algorithm {
997 size_t size_;
998 uint8_t type_;
999
1000 Algorithm(size_t size, uint8_t type) :
1001 size_(size),
1002 type_(type)
1003 {
1004 }
1005
1006 virtual const uint8_t *operator [](const ldid::Hash &hash) const = 0;
1007
1008 virtual void operator ()(uint8_t *hash, const void *data, size_t size) const = 0;
1009 virtual void operator ()(ldid::Hash &hash, const void *data, size_t size) const = 0;
1010 virtual void operator ()(std::vector<char> &hash, const void *data, size_t size) const = 0;
2da83dea
JF
1011
1012 virtual const char *name() = 0;
f74652ab
JF
1013};
1014
1015struct AlgorithmSHA1 :
1016 Algorithm
1017{
1018 AlgorithmSHA1() :
1019 Algorithm(LDID_SHA1_DIGEST_LENGTH, CS_HASHTYPE_SHA160_160)
1020 {
1021 }
1022
1023 virtual const uint8_t *operator [](const ldid::Hash &hash) const {
1024 return hash.sha1_;
1025 }
1026
1027 void operator ()(uint8_t *hash, const void *data, size_t size) const {
1028 LDID_SHA1(static_cast<const uint8_t *>(data), size, hash);
1029 }
1030
1031 void operator ()(ldid::Hash &hash, const void *data, size_t size) const {
1032 return operator()(hash.sha1_, data, size);
1033 }
fdb119ef 1034
f74652ab
JF
1035 void operator ()(std::vector<char> &hash, const void *data, size_t size) const {
1036 hash.resize(LDID_SHA1_DIGEST_LENGTH);
1037 return operator ()(reinterpret_cast<uint8_t *>(hash.data()), data, size);
1038 }
2da83dea
JF
1039
1040 virtual const char *name() {
1041 return "sha1";
1042 }
f74652ab
JF
1043};
1044
1045struct AlgorithmSHA256 :
1046 Algorithm
1047{
1048 AlgorithmSHA256() :
1049 Algorithm(LDID_SHA256_DIGEST_LENGTH, CS_HASHTYPE_SHA256_256)
1050 {
1051 }
1052
1053 virtual const uint8_t *operator [](const ldid::Hash &hash) const {
1054 return hash.sha256_;
1055 }
1056
1057 void operator ()(uint8_t *hash, const void *data, size_t size) const {
1058 LDID_SHA256(static_cast<const uint8_t *>(data), size, hash);
1059 }
1060
1061 void operator ()(ldid::Hash &hash, const void *data, size_t size) const {
1062 return operator()(hash.sha256_, data, size);
1063 }
1064
1065 void operator ()(std::vector<char> &hash, const void *data, size_t size) const {
1066 hash.resize(LDID_SHA256_DIGEST_LENGTH);
1067 return operator ()(reinterpret_cast<uint8_t *>(hash.data()), data, size);
1068 }
2da83dea
JF
1069
1070 virtual const char *name() {
1071 return "sha256";
1072 }
f74652ab
JF
1073};
1074
f58c84b8
JF
1075static bool do_sha1(true);
1076static bool do_sha256(true);
1077
f74652ab
JF
1078static const std::vector<Algorithm *> &GetAlgorithms() {
1079 static AlgorithmSHA1 sha1;
1080 static AlgorithmSHA256 sha256;
1081
f58c84b8
JF
1082 static std::vector<Algorithm *> algorithms;
1083 if (algorithms.empty()) {
1084 if (do_sha1)
1085 algorithms.push_back(&sha1);
1086 if (do_sha256)
1087 algorithms.push_back(&sha256);
1088 }
f74652ab 1089
f74652ab 1090 return algorithms;
707027e8
JF
1091}
1092
ec3af45e
JF
1093struct Baton {
1094 std::string entitlements_;
1095};
1096
0a033524 1097struct CodesignAllocation {
4374152f 1098 FatMachHeader mach_header_;
2edb2a93 1099 uint64_t offset_;
4374152f 1100 uint32_t size_;
803b4bc9 1101 uint64_t limit_;
4374152f 1102 uint32_t alloc_;
e4b7adc1 1103 uint32_t align_;
b4b49374 1104 const char *arch_;
ec3af45e 1105 Baton baton_;
4374152f 1106
ec3af45e 1107 CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align, const char *arch, const Baton &baton) :
4374152f
JF
1108 mach_header_(mach_header),
1109 offset_(offset),
1110 size_(size),
4d4682ef 1111 limit_(limit),
e4b7adc1 1112 alloc_(alloc),
b4b49374 1113 align_(align),
ec3af45e
JF
1114 arch_(arch),
1115 baton_(baton)
0a033524
JF
1116 {
1117 }
1118};
1119
0326ab11 1120#ifndef LDID_NOTOOLS
dede6121
JF
1121class File {
1122 private:
1123 int file_;
1124
1125 public:
1126 File() :
1127 file_(-1)
1128 {
1129 }
1130
1131 ~File() {
1132 if (file_ != -1)
1133 _syscall(close(file_));
1134 }
1135
cad40c43 1136 void open(const char *path, int flags) {
dede6121 1137 _assert(file_ == -1);
fc7a76da 1138 file_ = _syscall(::open(path, flags));
dede6121
JF
1139 }
1140
1141 int file() const {
1142 return file_;
1143 }
1144};
1145
1146class Map {
1147 private:
1148 File file_;
1149 void *data_;
1150 size_t size_;
1151
1152 void clear() {
1153 if (data_ == NULL)
1154 return;
1155 _syscall(munmap(data_, size_));
1156 data_ = NULL;
1157 size_ = 0;
1158 }
1159
1160 public:
1161 Map() :
1162 data_(NULL),
1163 size_(0)
1164 {
1165 }
1166
d4187e53 1167 Map(const std::string &path, int oflag, int pflag, int mflag) :
cad40c43
JF
1168 Map()
1169 {
1170 open(path, oflag, pflag, mflag);
1171 }
1172
d4187e53 1173 Map(const std::string &path, bool edit) :
cad40c43
JF
1174 Map()
1175 {
1176 open(path, edit);
dede6121
JF
1177 }
1178
1179 ~Map() {
1180 clear();
1181 }
1182
fac3d3e3
JF
1183 bool empty() const {
1184 return data_ == NULL;
1185 }
1186
d4187e53 1187 void open(const std::string &path, int oflag, int pflag, int mflag) {
dede6121
JF
1188 clear();
1189
d4187e53 1190 file_.open(path.c_str(), oflag);
dede6121
JF
1191 int file(file_.file());
1192
1193 struct stat stat;
1194 _syscall(fstat(file, &stat));
1195 size_ = stat.st_size;
1196
fc7a76da 1197 data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0));
cad40c43
JF
1198 }
1199
d4187e53 1200 void open(const std::string &path, bool edit) {
cad40c43
JF
1201 if (edit)
1202 open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED);
1203 else
1204 open(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
dede6121
JF
1205 }
1206
1207 void *data() const {
1208 return data_;
1209 }
1210
1211 size_t size() const {
1212 return size_;
1213 }
f4b2df35
JF
1214
1215 operator std::string() const {
1216 return std::string(static_cast<char *>(data_), size_);
1217 }
dede6121 1218};
0326ab11 1219#endif
dede6121 1220
a0c715e9
JF
1221namespace ldid {
1222
ec3af45e
JF
1223#ifndef LDID_NOPLIST
1224static plist_t plist(const std::string &data);
1225#endif
1226
1227void Analyze(const MachHeader &mach_header, const Functor<void (const char *data, size_t size)> &entitle) {
1228 _foreach (load_command, mach_header.GetLoadCommands())
1229 if (mach_header.Swap(load_command->cmd) == LC_CODE_SIGNATURE) {
1230 auto signature(reinterpret_cast<struct linkedit_data_command *>(load_command));
1231 auto offset(mach_header.Swap(signature->dataoff));
1232 auto pointer(reinterpret_cast<uint8_t *>(mach_header.GetBase()) + offset);
1233 auto super(reinterpret_cast<struct SuperBlob *>(pointer));
1234
1235 for (size_t index(0); index != Swap(super->count); ++index)
1236 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
1237 auto begin(Swap(super->index[index].offset));
1238 auto blob(reinterpret_cast<struct Blob *>(pointer + begin));
1239 auto writ(Swap(blob->length) - sizeof(*blob));
1240 entitle(reinterpret_cast<char *>(blob + 1), writ);
1241 }
1242 }
1243}
1244
cdd9c0fd
JF
1245std::string Analyze(const void *data, size_t size) {
1246 std::string entitlements;
1247
1248 FatHeader fat_header(const_cast<void *>(data), size);
1249 _foreach (mach_header, fat_header.GetMachHeaders())
ec3af45e
JF
1250 Analyze(mach_header, fun([&](const char *data, size_t size) {
1251 if (entitlements.empty())
1252 entitlements.assign(data, size);
1253 else
1254 _assert(entitlements.compare(0, entitlements.size(), data, size) == 0);
1255 }));
cdd9c0fd
JF
1256
1257 return entitlements;
1258}
1259
803b4bc9 1260static void Allocate(const void *idata, size_t isize, std::streambuf &output, const Functor<size_t (const MachHeader &, Baton &, size_t)> &allocate, const Functor<size_t (const MachHeader &, const Baton &, std::streambuf &output, size_t, size_t, size_t, const std::string &, const char *, const Progress &)> &save, const Progress &progress) {
ffdd1183 1261 FatHeader source(const_cast<void *>(idata), isize);
f4b2df35
JF
1262
1263 size_t offset(0);
1264 if (source.IsFat())
1265 offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
1266
1267 std::vector<CodesignAllocation> allocations;
1268 _foreach (mach_header, source.GetMachHeaders()) {
1269 struct linkedit_data_command *signature(NULL);
1270 struct symtab_command *symtab(NULL);
1271
1272 _foreach (load_command, mach_header.GetLoadCommands()) {
1273 uint32_t cmd(mach_header.Swap(load_command->cmd));
1274 if (false);
1275 else if (cmd == LC_CODE_SIGNATURE)
1276 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
1277 else if (cmd == LC_SYMTAB)
1278 symtab = reinterpret_cast<struct symtab_command *>(load_command);
1279 }
1280
1281 size_t size;
1282 if (signature == NULL)
1283 size = mach_header.GetSize();
1284 else {
1285 size = mach_header.Swap(signature->dataoff);
1286 _assert(size <= mach_header.GetSize());
1287 }
1288
1289 if (symtab != NULL) {
1290 auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
422bad37
JF
1291 if (symtab->stroff != 0 || symtab->strsize != 0) {
1292 _assert(end <= size);
1293 _assert(end >= size - 0x10);
1294 size = end;
1295 }
f4b2df35
JF
1296 }
1297
ec3af45e
JF
1298 Baton baton;
1299 size_t alloc(allocate(mach_header, baton, size));
f4b2df35
JF
1300
1301 auto *fat_arch(mach_header.GetFatArch());
6f420711
JF
1302 uint32_t align;
1303
1304 if (fat_arch != NULL)
1305 align = source.Swap(fat_arch->align);
1306 else switch (mach_header.GetCPUType()) {
1307 case CPU_TYPE_POWERPC:
1308 case CPU_TYPE_POWERPC64:
1309 case CPU_TYPE_X86:
1310 case CPU_TYPE_X86_64:
1311 align = 0xc;
1312 break;
1313 case CPU_TYPE_ARM:
1314 case CPU_TYPE_ARM64:
1315 align = 0xe;
1316 break;
1317 default:
1318 align = 0x0;
1319 break;
1320 }
1321
b4b49374
JF
1322 const char *arch(NULL);
1323 switch (mach_header.GetCPUType()) {
1324 case CPU_TYPE_POWERPC:
1325 arch = "ppc";
1326 break;
1327 case CPU_TYPE_POWERPC64:
1328 arch = "ppc64";
1329 break;
1330 case CPU_TYPE_X86:
1331 arch = "i386";
1332 break;
1333 case CPU_TYPE_X86_64:
1334 arch = "x86_64";
1335 break;
1336 case CPU_TYPE_ARM:
1337 arch = "arm";
1338 break;
1339 case CPU_TYPE_ARM64:
1340 arch = "arm64";
1341 break;
1342 }
1343
f4b2df35
JF
1344 offset = Align(offset, 1 << align);
1345
4d4682ef
JF
1346 uint32_t limit(size);
1347 if (alloc != 0)
1348 limit = Align(limit, 0x10);
1349
ec3af45e 1350 allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align, arch, baton));
f4b2df35 1351 offset += size + alloc;
b9652d6e 1352 offset = Align(offset, 0x10);
f4b2df35
JF
1353 }
1354
4d4682ef
JF
1355 size_t position(0);
1356
1357 if (source.IsFat()) {
1358 fat_header fat_header;
1359 fat_header.magic = Swap(FAT_MAGIC);
1360 fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
1361 put(output, &fat_header, sizeof(fat_header));
1362 position += sizeof(fat_header);
1363
2edb2a93
JF
1364 // XXX: support fat_arch_64 (not in my toolchain)
1365 // probably use C++14 generic lambda (not in my toolchain)
1366
1367 _assert_(![&]() {
1368 _foreach (allocation, allocations) {
1369 const auto offset(allocation.offset_);
1370 const auto size(allocation.limit_ + allocation.alloc_);
1371 if (uint32_t(offset) != offset || uint32_t(size) != size)
1372 return true;
1373 }
1374 return false;
1375 }(), "FAT slice >=4GiB not currently supported");
1376
4d4682ef
JF
1377 _foreach (allocation, allocations) {
1378 auto &mach_header(allocation.mach_header_);
1379
1380 fat_arch fat_arch;
1381 fat_arch.cputype = Swap(mach_header->cputype);
1382 fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
2edb2a93
JF
1383 fat_arch.offset = Swap(uint32_t(allocation.offset_));
1384 fat_arch.size = Swap(uint32_t(allocation.limit_ + allocation.alloc_));
4d4682ef
JF
1385 fat_arch.align = Swap(allocation.align_);
1386 put(output, &fat_arch, sizeof(fat_arch));
1387 position += sizeof(fat_arch);
1388 }
f4b2df35
JF
1389 }
1390
1391 _foreach (allocation, allocations) {
b4b49374 1392 progress(allocation.arch_);
4d4682ef 1393 auto &mach_header(allocation.mach_header_);
f4b2df35 1394
4d4682ef
JF
1395 pad(output, allocation.offset_ - position);
1396 position = allocation.offset_;
f4b2df35 1397
803b4bc9
JF
1398 size_t left(-1);
1399 size_t right(0);
1400
4d4682ef 1401 std::vector<std::string> commands;
f4b2df35 1402
4d4682ef
JF
1403 _foreach (load_command, mach_header.GetLoadCommands()) {
1404 std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
f4b2df35 1405
a7f01a65 1406 switch (mach_header.Swap(load_command->cmd)) {
4d4682ef
JF
1407 case LC_CODE_SIGNATURE:
1408 continue;
1409 break;
1410
803b4bc9
JF
1411 // XXX: this is getting ridiculous: provide a better abstraction
1412
4d4682ef
JF
1413 case LC_SEGMENT: {
1414 auto segment_command(reinterpret_cast<struct segment_command *>(&copy[0]));
803b4bc9
JF
1415
1416 if ((segment_command->initprot & 04) != 0) {
1417 auto begin(mach_header.Swap(segment_command->fileoff));
1418 auto end(begin + mach_header.Swap(segment_command->filesize));
1419 if (left > begin)
1420 left = begin;
1421 if (right < end)
1422 right = end;
1423 }
1424
1425 if (strncmp(segment_command->segname, "__LINKEDIT", 16) == 0) {
1426 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1427 segment_command->filesize = size;
1428 segment_command->vmsize = Align(size, 1 << allocation.align_);
1429 }
4d4682ef
JF
1430 } break;
1431
1432 case LC_SEGMENT_64: {
1433 auto segment_command(reinterpret_cast<struct segment_command_64 *>(&copy[0]));
803b4bc9
JF
1434
1435 if ((segment_command->initprot & 04) != 0) {
1436 auto begin(mach_header.Swap(segment_command->fileoff));
1437 auto end(begin + mach_header.Swap(segment_command->filesize));
1438 if (left > begin)
1439 left = begin;
1440 if (right < end)
1441 right = end;
1442 }
1443
1444 if (strncmp(segment_command->segname, "__LINKEDIT", 16) == 0) {
1445 size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
1446 segment_command->filesize = size;
1447 segment_command->vmsize = Align(size, 1 << allocation.align_);
1448 }
4d4682ef
JF
1449 } break;
1450 }
f4b2df35 1451
4d4682ef 1452 commands.push_back(copy);
f4b2df35
JF
1453 }
1454
e0098838 1455 if (allocation.alloc_ != 0) {
4d4682ef
JF
1456 linkedit_data_command signature;
1457 signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
1458 signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
1459 signature.dataoff = mach_header.Swap(allocation.limit_);
1460 signature.datasize = mach_header.Swap(allocation.alloc_);
1461 commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
1462 }
f4b2df35 1463
4d4682ef 1464 size_t begin(position);
f4b2df35 1465
4d4682ef
JF
1466 uint32_t after(0);
1467 _foreach(command, commands)
1468 after += command.size();
f4b2df35 1469
4d4682ef 1470 std::stringbuf altern;
f4b2df35 1471
4d4682ef
JF
1472 struct mach_header header(*mach_header);
1473 header.ncmds = mach_header.Swap(uint32_t(commands.size()));
1474 header.sizeofcmds = mach_header.Swap(after);
1475 put(output, &header, sizeof(header));
1476 put(altern, &header, sizeof(header));
1477 position += sizeof(header);
f4b2df35 1478
4d4682ef
JF
1479 if (mach_header.Bits64()) {
1480 auto pad(mach_header.Swap(uint32_t(0)));
1481 put(output, &pad, sizeof(pad));
1482 put(altern, &pad, sizeof(pad));
1483 position += sizeof(pad);
1484 }
f4b2df35 1485
4d4682ef
JF
1486 _foreach(command, commands) {
1487 put(output, command.data(), command.size());
1488 put(altern, command.data(), command.size());
1489 position += command.size();
1490 }
f4b2df35 1491
4d4682ef
JF
1492 uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
1493 if (before > after) {
1494 pad(output, before - after);
1495 pad(altern, before - after);
1496 position += before - after;
1497 }
f4b2df35 1498
4d4682ef 1499 auto top(reinterpret_cast<char *>(mach_header.GetBase()));
f4b2df35 1500
4d4682ef
JF
1501 std::string overlap(altern.str());
1502 overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
f4b2df35 1503
b4b49374 1504 put(output, top + (position - begin), allocation.size_ - (position - begin), progress);
4d4682ef 1505 position = begin + allocation.size_;
f4b2df35 1506
4d4682ef
JF
1507 pad(output, allocation.limit_ - allocation.size_);
1508 position += allocation.limit_ - allocation.size_;
f4b2df35 1509
803b4bc9 1510 size_t saved(save(mach_header, allocation.baton_, output, allocation.limit_, left, right, overlap, top, progress));
67205335
JF
1511 if (allocation.alloc_ > saved)
1512 pad(output, allocation.alloc_ - saved);
4f63b590
JF
1513 else
1514 _assert(allocation.alloc_ == saved);
67205335 1515 position += allocation.alloc_;
e0098838
JF
1516 }
1517}
f4b2df35 1518
a0c715e9
JF
1519}
1520
efad8a44
JF
1521typedef std::map<uint32_t, std::string> Blobs;
1522
bb591e2b
JF
1523static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
1524 auto value(buffer.str());
1525 std::swap(blobs[slot], value);
1526}
1527
4ebf3494 1528static const std::string &insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
8f310b91
JF
1529 auto value(buffer.str());
1530 Blob blob;
1531 blob.magic = Swap(magic);
1532 blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
1533 value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
4ebf3494
JF
1534 auto &save(blobs[slot]);
1535 std::swap(save, value);
1536 return save;
efad8a44
JF
1537}
1538
1539static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
1540 size_t total(0);
1541 _foreach (blob, blobs)
1542 total += blob.second.size();
1543
1544 struct SuperBlob super;
1545 super.blob.magic = Swap(magic);
1546 super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
1547 super.count = Swap(uint32_t(blobs.size()));
1548 put(output, &super, sizeof(super));
1549
1550 size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
1551
1552 _foreach (blob, blobs) {
1553 BlobIndex index;
1554 index.type = Swap(blob.first);
1555 index.offset = Swap(uint32_t(offset));
1556 put(output, &index, sizeof(index));
1557 offset += blob.second.size();
1558 }
1559
1560 _foreach (blob, blobs)
1561 put(output, blob.second.data(), blob.second.size());
1562
1563 return offset;
1564}
1565
489c97b8 1566#ifndef LDID_NOSMIME
30c64adb
JF
1567class Buffer {
1568 private:
1569 BIO *bio_;
1570
1571 public:
1572 Buffer(BIO *bio) :
1573 bio_(bio)
1574 {
1575 _assert(bio_ != NULL);
1576 }
1577
1578 Buffer() :
1579 bio_(BIO_new(BIO_s_mem()))
1580 {
1581 }
1582
1583 Buffer(const char *data, size_t size) :
1584 Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
1585 {
1586 }
1587
1588 Buffer(const std::string &data) :
1589 Buffer(data.data(), data.size())
1590 {
1591 }
1592
1593 Buffer(PKCS7 *pkcs) :
1594 Buffer()
1595 {
1596 _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
1597 }
1598
1599 ~Buffer() {
1600 BIO_free_all(bio_);
1601 }
1602
1603 operator BIO *() const {
1604 return bio_;
1605 }
1606
1607 explicit operator std::string() const {
1608 char *data;
1609 auto size(BIO_get_mem_data(bio_, &data));
1610 return std::string(data, size);
1611 }
1612};
1613
1614class Stuff {
1615 private:
1616 PKCS12 *value_;
1617 EVP_PKEY *key_;
1618 X509 *cert_;
1619 STACK_OF(X509) *ca_;
1620
1621 public:
1622 Stuff(BIO *bio) :
1623 value_(d2i_PKCS12_bio(bio, NULL)),
1624 ca_(NULL)
1625 {
1626 _assert(value_ != NULL);
1627 _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
f1df4833 1628
30c64adb
JF
1629 _assert(key_ != NULL);
1630 _assert(cert_ != NULL);
f1df4833
JF
1631
1632 if (ca_ == NULL)
1633 ca_ = sk_X509_new_null();
1634 _assert(ca_ != NULL);
30c64adb
JF
1635 }
1636
1637 Stuff(const std::string &data) :
1638 Stuff(Buffer(data))
1639 {
1640 }
1641
1642 ~Stuff() {
1643 sk_X509_pop_free(ca_, X509_free);
1644 X509_free(cert_);
1645 EVP_PKEY_free(key_);
1646 PKCS12_free(value_);
1647 }
1648
1649 operator PKCS12 *() const {
1650 return value_;
1651 }
1652
1653 operator EVP_PKEY *() const {
1654 return key_;
1655 }
1656
1657 operator X509 *() const {
1658 return cert_;
1659 }
1660
1661 operator STACK_OF(X509) *() const {
1662 return ca_;
1663 }
1664};
1665
1666class Signature {
1667 private:
1668 PKCS7 *value_;
1669
1670 public:
fe54c5fb
JF
1671 Signature(const Stuff &stuff, const Buffer &data, const std::string &xml) {
1672 value_ = PKCS7_new();
30c64adb 1673 _assert(value_ != NULL);
fe54c5fb
JF
1674
1675 _assert(PKCS7_set_type(value_, NID_pkcs7_signed));
1676 _assert(PKCS7_content_new(value_, NID_pkcs7_data));
1677
1678 STACK_OF(X509) *certs(stuff);
1679 for (unsigned i(0), e(sk_X509_num(certs)); i != e; i++)
1680 _assert(PKCS7_add_certificate(value_, sk_X509_value(certs, e - i - 1)));
1681
7818dc9c
JF
1682 // XXX: this is the same as PKCS7_sign_add_signer(value_, stuff, stuff, NULL, PKCS7_NOSMIMECAP)
1683 _assert(X509_check_private_key(stuff, stuff));
1684 auto info(PKCS7_add_signature(value_, stuff, stuff, EVP_sha1()));
fe54c5fb 1685 _assert(info != NULL);
7818dc9c
JF
1686 _assert(PKCS7_add_certificate(value_, stuff));
1687 _assert(PKCS7_add_signed_attribute(info, NID_pkcs9_contentType, V_ASN1_OBJECT, OBJ_nid2obj(NID_pkcs7_data)));
fe54c5fb
JF
1688
1689 PKCS7_set_detached(value_, 1);
1690
1691 ASN1_OCTET_STRING *string(ASN1_OCTET_STRING_new());
1692 _assert(string != NULL);
1693 try {
1694 _assert(ASN1_STRING_set(string, xml.data(), xml.size()));
1695
1696 static auto nid(OBJ_create("1.2.840.113635.100.9.1", "", ""));
1697 _assert(PKCS7_add_signed_attribute(info, nid, V_ASN1_OCTET_STRING, string));
1698 } catch (...) {
1699 ASN1_OCTET_STRING_free(string);
1700 throw;
1701 }
1702
7818dc9c
JF
1703 // XXX: this is the same as PKCS7_final(value_, data, PKCS7_BINARY)
1704 BIO *bio(PKCS7_dataInit(value_, NULL));
1705 _assert(bio != NULL);
1706 _scope({ BIO_free_all(bio); });
1707 SMIME_crlf_copy(data, bio, PKCS7_BINARY);
1708 BIO_flush(bio);
1709 _assert(PKCS7_dataFinal(value_, bio));
30c64adb
JF
1710 }
1711
1712 ~Signature() {
1713 PKCS7_free(value_);
1714 }
1715
1716 operator PKCS7 *() const {
1717 return value_;
1718 }
1719};
489c97b8 1720#endif
30c64adb 1721
23c11ee8
JF
1722class NullBuffer :
1723 public std::streambuf
1724{
1725 public:
1726 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1727 return size;
1728 }
1729
1730 virtual int_type overflow(int_type next) {
1731 return next;
1732 }
1733};
1734
1735class HashBuffer :
1736 public std::streambuf
1737{
1738 private:
f74652ab 1739 ldid::Hash &hash_;
9ec8439b
JF
1740
1741 LDID_SHA1_CTX sha1_;
1742 LDID_SHA256_CTX sha256_;
23c11ee8
JF
1743
1744 public:
f74652ab 1745 HashBuffer(ldid::Hash &hash) :
23c11ee8
JF
1746 hash_(hash)
1747 {
9ec8439b
JF
1748 LDID_SHA1_Init(&sha1_);
1749 LDID_SHA256_Init(&sha256_);
23c11ee8
JF
1750 }
1751
1752 ~HashBuffer() {
9ec8439b
JF
1753 LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.sha1_), &sha1_);
1754 LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_.sha256_), &sha256_);
23c11ee8
JF
1755 }
1756
1757 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
9ec8439b
JF
1758 LDID_SHA1_Update(&sha1_, data, size);
1759 LDID_SHA256_Update(&sha256_, data, size);
23c11ee8
JF
1760 return size;
1761 }
1762
1763 virtual int_type overflow(int_type next) {
1764 if (next == traits_type::eof())
1765 return sync();
1766 char value(next);
1767 xsputn(&value, 1);
1768 return next;
1769 }
1770};
1771
1772class HashProxy :
1773 public HashBuffer
1774{
1775 private:
1776 std::streambuf &buffer_;
1777
1778 public:
f74652ab 1779 HashProxy(ldid::Hash &hash, std::streambuf &buffer) :
23c11ee8
JF
1780 HashBuffer(hash),
1781 buffer_(buffer)
1782 {
1783 }
1784
1785 virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
1786 _assert(HashBuffer::xsputn(data, size) == size);
1787 return buffer_.sputn(data, size);
1788 }
1789};
1790
0326ab11 1791#ifndef LDID_NOTOOLS
23c11ee8
JF
1792static bool Starts(const std::string &lhs, const std::string &rhs) {
1793 return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
1794}
1795
1796class Split {
1797 public:
1798 std::string dir;
1799 std::string base;
1800
1801 Split(const std::string &path) {
1802 size_t slash(path.rfind('/'));
1803 if (slash == std::string::npos)
1804 base = path;
1805 else {
1806 dir = path.substr(0, slash + 1);
1807 base = path.substr(slash + 1);
1808 }
1809 }
1810};
1811
1812static void mkdir_p(const std::string &path) {
1813 if (path.empty())
1814 return;
31cc0388
JF
1815#ifdef __WIN32__
1816 if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
1817 return;
1818#else
23c11ee8
JF
1819 if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
1820 return;
31cc0388 1821#endif
23c11ee8
JF
1822 auto slash(path.rfind('/', path.size() - 1));
1823 if (slash == std::string::npos)
1824 return;
1825 mkdir_p(path.substr(0, slash));
1826}
1827
1828static std::string Temporary(std::filebuf &file, const Split &split) {
1829 std::string temp(split.dir + ".ldid." + split.base);
1830 mkdir_p(split.dir);
1831 _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
1832 return temp;
1833}
1834
d4187e53
JF
1835static void Commit(const std::string &path, const std::string &temp) {
1836 struct stat info;
23c11ee8 1837 if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
d4187e53 1838#ifndef __WIN32__
23c11ee8 1839 _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
d4187e53 1840#endif
23c11ee8
JF
1841 _syscall(chmod(temp.c_str(), info.st_mode));
1842 }
1843
d4187e53
JF
1844 _syscall(rename(temp.c_str(), path.c_str()));
1845}
0326ab11 1846#endif
d4187e53 1847
a0c715e9 1848namespace ldid {
e57b1f91 1849
c1f70967 1850#ifndef LDID_NOSMIME
7cb8c1fc
JF
1851static void get(std::string &value, X509_NAME *name, int nid) {
1852 auto index(X509_NAME_get_index_by_NID(name, nid, -1));
1853 _assert(index >= 0);
1854 auto next(X509_NAME_get_index_by_NID(name, nid, index));
1855 _assert(next == -1);
1856 auto entry(X509_NAME_get_entry(name, index));
1857 _assert(entry != NULL);
1858 auto asn(X509_NAME_ENTRY_get_data(entry));
1859 _assert(asn != NULL);
1860 value.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn)), ASN1_STRING_length(asn));
1861}
c1f70967 1862#endif
7cb8c1fc
JF
1863
1864static void req(std::streambuf &buffer, uint32_t value) {
1865 value = Swap(value);
1866 put(buffer, &value, sizeof(value));
1867}
1868
1869static void req(std::streambuf &buffer, const std::string &value) {
1870 req(buffer, value.size());
1871 put(buffer, value.data(), value.size());
1872 static uint8_t zeros[] = {0,0,0,0};
1873 put(buffer, zeros, 3 - (value.size() + 3) % 4);
1874}
1875
1876template <size_t Size_>
1877static void req(std::streambuf &buffer, uint8_t (&&data)[Size_]) {
1878 req(buffer, Size_);
1879 put(buffer, data, Size_);
1880 static uint8_t zeros[] = {0,0,0,0};
1881 put(buffer, zeros, 3 - (Size_ + 3) % 4);
1882}
1883
ec3af45e 1884Hash Sign(const void *idata, size_t isize, std::streambuf &output, const std::string &identifier, const std::string &entitlements, bool merge, const std::string &requirements, const std::string &key, const Slots &slots, uint32_t flags, bool platform, const Progress &progress) {
f74652ab 1885 Hash hash;
4ebf3494 1886
7cb8c1fc 1887
b73d2333 1888 std::string team;
7cb8c1fc 1889 std::string common;
b73d2333
JF
1890
1891#ifndef LDID_NOSMIME
1892 if (!key.empty()) {
b73d2333
JF
1893 Stuff stuff(key);
1894 auto name(X509_get_subject_name(stuff));
1895 _assert(name != NULL);
7cb8c1fc
JF
1896 get(team, name, NID_organizationalUnitName);
1897 get(common, name, NID_commonName);
b73d2333
JF
1898 }
1899#endif
1900
7cb8c1fc
JF
1901
1902 std::stringbuf backing;
1903
1904 if (!requirements.empty()) {
1905 put(backing, requirements.data(), requirements.size());
1906 } else {
1907 Blobs blobs;
1908
1909 std::stringbuf requirement;
1910 req(requirement, exprForm);
1911 req(requirement, opAnd);
1912 req(requirement, opIdent);
1913 req(requirement, identifier);
1914 req(requirement, opAnd);
1915 req(requirement, opAppleGenericAnchor);
1916 req(requirement, opAnd);
1917 req(requirement, opCertField);
1918 req(requirement, 0);
1919 req(requirement, "subject.CN");
1920 req(requirement, matchEqual);
1921 req(requirement, common);
1922 req(requirement, opCertGeneric);
1923 req(requirement, 1);
1924 req(requirement, (uint8_t []) {APPLE_EXTENSION_OID, 2, 1});
1925 req(requirement, matchExists);
1926 insert(blobs, 3, CSMAGIC_REQUIREMENT, requirement);
1927
1928 put(backing, CSMAGIC_REQUIREMENTS, blobs);
1929 }
1930
1931
ee5f5556
JF
1932 // XXX: this is just a "sufficiently large number"
1933 size_t certificate(0x3000);
1934
ec3af45e 1935 Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, Baton &baton, size_t size) -> size_t {
e0098838 1936 size_t alloc(sizeof(struct SuperBlob));
f4b2df35 1937
f74652ab
JF
1938 uint32_t normal((size + PageSize_ - 1) / PageSize_);
1939
e0098838 1940 uint32_t special(0);
f4b2df35 1941
f74652ab
JF
1942 _foreach (slot, slots)
1943 special = std::max(special, slot.first);
1944
1945 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
1946 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
1947 special = std::max(special, CSSLOT_INFOSLOT);
1948 }));
1949
e0098838
JF
1950 special = std::max(special, CSSLOT_REQUIREMENTS);
1951 alloc += sizeof(struct BlobIndex);
7cb8c1fc 1952 alloc += backing.str().size();
f4b2df35 1953
ec3af45e
JF
1954 if (!merge)
1955 baton.entitlements_ = entitlements;
1956 else {
1957#ifndef LDID_NOPLIST
1958 Analyze(mach_header, fun([&](const char *data, size_t size) {
1959 baton.entitlements_.assign(data, size);
1960 }));
1961
f8e0d186
JF
1962 if (baton.entitlements_.empty())
1963 baton.entitlements_ = entitlements;
1964 else if (!entitlements.empty()) {
ec3af45e
JF
1965 auto combined(plist(baton.entitlements_));
1966 _scope({ plist_free(combined); });
1967 _assert(plist_get_node_type(combined) == PLIST_DICT);
1968
1969 auto merging(plist(entitlements));
1970 _scope({ plist_free(merging); });
1971 _assert(plist_get_node_type(merging) == PLIST_DICT);
1972
1973 plist_dict_iter iterator(NULL);
1974 plist_dict_new_iter(merging, &iterator);
1975 _scope({ free(iterator); });
1976
1977 for (;;) {
1978 char *key(NULL);
1979 plist_t value(NULL);
1980 plist_dict_next_item(merging, iterator, &key, &value);
1981 if (key == NULL)
1982 break;
1983 _scope({ free(key); });
1984 plist_dict_set_item(combined, key, plist_copy(value));
1985 }
1986
1987 char *xml(NULL);
1988 uint32_t size;
1989 plist_to_xml(combined, &xml, &size);
1990 _scope({ free(xml); });
1991
1992 baton.entitlements_.assign(xml, size);
1993 }
1994#else
1995 _assert(false);
1996#endif
1997 }
1998
1999 if (!baton.entitlements_.empty()) {
e0098838
JF
2000 special = std::max(special, CSSLOT_ENTITLEMENTS);
2001 alloc += sizeof(struct BlobIndex);
2002 alloc += sizeof(struct Blob);
ec3af45e 2003 alloc += baton.entitlements_.size();
e0098838 2004 }
f4b2df35 2005
f74652ab
JF
2006 size_t directory(0);
2007
2008 directory += sizeof(struct BlobIndex);
2009 directory += sizeof(struct Blob);
2010 directory += sizeof(struct CodeDirectory);
2011 directory += identifier.size() + 1;
f4b2df35 2012
b73d2333 2013 if (!team.empty())
f74652ab
JF
2014 directory += team.size() + 1;
2015
2016 for (Algorithm *algorithm : GetAlgorithms())
2017 alloc = Align(alloc + directory + (special + normal) * algorithm->size_, 16);
b73d2333 2018
fd50da22 2019#ifndef LDID_NOSMIME
30c64adb
JF
2020 if (!key.empty()) {
2021 alloc += sizeof(struct BlobIndex);
2022 alloc += sizeof(struct Blob);
ee5f5556 2023 alloc += certificate;
30c64adb 2024 }
fd50da22 2025#endif
30c64adb 2026
e0098838 2027 return alloc;
803b4bc9 2028 }), fun([&](const MachHeader &mach_header, const Baton &baton, std::streambuf &output, size_t limit, size_t left, size_t right, const std::string &overlap, const char *top, const Progress &progress) -> size_t {
efad8a44 2029 Blobs blobs;
f4b2df35 2030
e0098838 2031 if (true) {
7cb8c1fc 2032 insert(blobs, CSSLOT_REQUIREMENTS, backing);
e0098838 2033 }
4d4682ef 2034
803b4bc9
JF
2035 uint64_t execs(0);
2036 if (mach_header.Swap(mach_header->filetype) == MH_EXECUTE)
2037 execs |= kSecCodeExecSegMainBinary;
2038
ec3af45e 2039 if (!baton.entitlements_.empty()) {
e0098838 2040 std::stringbuf data;
ec3af45e 2041 put(data, baton.entitlements_.data(), baton.entitlements_.size());
8f310b91 2042 insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
803b4bc9
JF
2043
2044#ifndef LDID_NOPLIST
2045 auto entitlements(plist(baton.entitlements_));
2046 _scope({ plist_free(entitlements); });
2047 _assert(plist_get_node_type(entitlements) == PLIST_DICT);
2048
2049 const auto entitled([&](const char *key) {
2050 auto item(plist_dict_get_item(entitlements, key));
2051 if (plist_get_node_type(item) != PLIST_BOOLEAN)
2052 return false;
2053 uint8_t value(0);
2054 plist_get_bool_val(item, &value);
2055 return value != 0;
2056 });
2057
2058 if (entitled("get-task-allow"))
2059 execs |= kSecCodeExecSegAllowUnsigned;
2060 if (entitled("run-unsigned-code"))
2061 execs |= kSecCodeExecSegAllowUnsigned;
2062 if (entitled("com.apple.private.cs.debugger"))
2063 execs |= kSecCodeExecSegDebugger;
2064 if (entitled("dynamic-codesigning"))
2065 execs |= kSecCodeExecSegJit;
2066 if (entitled("com.apple.private.skip-library-validation"))
2067 execs |= kSecCodeExecSegSkipLibraryVal;
2068 if (entitled("com.apple.private.amfi.can-load-cdhash"))
2069 execs |= kSecCodeExecSegCanLoadCdHash;
2070 if (entitled("com.apple.private.amfi.can-execute-cdhash"))
2071 execs |= kSecCodeExecSegCanExecCdHash;
2072#endif
e0098838
JF
2073 }
2074
f74652ab 2075 Slots posts(slots);
e0098838 2076
f74652ab
JF
2077 mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
2078 if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0) {
2079 auto &slot(posts[CSSLOT_INFOSLOT]);
2080 for (Algorithm *algorithm : GetAlgorithms())
2081 (*algorithm)(slot, data, size);
2082 }
2083 }));
e4d33eec 2084
f74652ab
JF
2085 unsigned total(0);
2086 for (Algorithm *pointer : GetAlgorithms()) {
2087 Algorithm &algorithm(*pointer);
2088
2089 std::stringbuf data;
e4d33eec 2090
e0098838
JF
2091 uint32_t special(0);
2092 _foreach (blob, blobs)
2093 special = std::max(special, blob.first);
e4d33eec 2094 _foreach (slot, posts)
e57b1f91 2095 special = std::max(special, slot.first);
b9652d6e 2096 uint32_t normal((limit + PageSize_ - 1) / PageSize_);
e0098838 2097
e0098838 2098 CodeDirectory directory;
803b4bc9 2099 directory.version = Swap(uint32_t(0x00020400));
296fd38e 2100 directory.flags = Swap(uint32_t(flags));
e0098838 2101 directory.nSpecialSlots = Swap(special);
803b4bc9 2102 directory.codeLimit = Swap(uint32_t(limit > UINT32_MAX ? UINT32_MAX : limit));
e0098838 2103 directory.nCodeSlots = Swap(normal);
f74652ab
JF
2104 directory.hashSize = algorithm.size_;
2105 directory.hashType = algorithm.type_;
296fd38e 2106 directory.platform = platform ? 0x01 : 0x00;
b9652d6e 2107 directory.pageSize = PageShift_;
e0098838 2108 directory.spare2 = Swap(uint32_t(0));
b73d2333 2109 directory.scatterOffset = Swap(uint32_t(0));
803b4bc9
JF
2110 directory.spare3 = Swap(uint32_t(0));
2111 directory.codeLimit64 = Swap(uint64_t(limit > UINT32_MAX ? limit : 0));
2112 directory.execSegBase = Swap(uint64_t(left));
2113 directory.execSegLimit = Swap(uint64_t(right - left));
2114 directory.execSegFlags = Swap(execs);
b73d2333
JF
2115
2116 uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory));
2117
2118 directory.identOffset = Swap(uint32_t(offset));
2119 offset += identifier.size() + 1;
2120
2121 if (team.empty())
2122 directory.teamIDOffset = Swap(uint32_t(0));
2123 else {
2124 directory.teamIDOffset = Swap(uint32_t(offset));
2125 offset += team.size() + 1;
2126 }
2127
f74652ab 2128 offset += special * algorithm.size_;
b73d2333 2129 directory.hashOffset = Swap(uint32_t(offset));
f74652ab 2130 offset += normal * algorithm.size_;
b73d2333 2131
e0098838
JF
2132 put(data, &directory, sizeof(directory));
2133
ffdd1183 2134 put(data, identifier.c_str(), identifier.size() + 1);
d74ad7c4
JF
2135 if (!team.empty())
2136 put(data, team.c_str(), team.size() + 1);
e0098838 2137
f74652ab
JF
2138 std::vector<uint8_t> storage((special + normal) * algorithm.size_);
2139 auto *hashes(&storage[special * algorithm.size_]);
e0098838 2140
f74652ab 2141 memset(storage.data(), 0, special * algorithm.size_);
4d4682ef
JF
2142
2143 _foreach (blob, blobs) {
e0098838 2144 auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
f74652ab 2145 algorithm(hashes - blob.first * algorithm.size_, local, Swap(local->length));
4d4682ef 2146 }
f4b2df35 2147
f74652ab
JF
2148 _foreach (slot, posts)
2149 memcpy(hashes - slot.first * algorithm.size_, algorithm[slot.second], algorithm.size_);
e57b1f91 2150
b4b49374 2151 progress(0);
e0098838 2152 if (normal != 1)
e1d26767 2153 for (size_t i = 0; i != normal - 1; ++i) {
f74652ab 2154 algorithm(hashes + i * algorithm.size_, (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
b4b49374 2155 progress(double(i) / normal);
e1d26767 2156 }
e0098838 2157 if (normal != 0)
f74652ab 2158 algorithm(hashes + (normal - 1) * algorithm.size_, top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
b4b49374 2159 progress(1);
f4b2df35 2160
f74652ab
JF
2161 put(data, storage.data(), storage.size());
2162
2163 const auto &save(insert(blobs, total == 0 ? CSSLOT_CODEDIRECTORY : CSSLOT_ALTERNATE + total - 1, CSMAGIC_CODEDIRECTORY, data));
2164 algorithm(hash, save.data(), save.size());
e0098838 2165
f74652ab 2166 ++total;
f4b2df35 2167 }
e0098838 2168
489c97b8 2169#ifndef LDID_NOSMIME
30c64adb 2170 if (!key.empty()) {
1190f447
JF
2171#ifdef LDID_NOPLIST
2172 auto plist(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2173 _scope({ CFRelease(plist); });
2174
2175 auto cdhashes(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
2176 _scope({ CFRelease(cdhashes); });
2177
2178 CFDictionarySetValue(plist, CFSTR("cdhashes"), cdhashes);
2179#else
fe54c5fb
JF
2180 auto plist(plist_new_dict());
2181 _scope({ plist_free(plist); });
2182
2183 auto cdhashes(plist_new_array());
2184 plist_dict_set_item(plist, "cdhashes", cdhashes);
1190f447 2185#endif
fe54c5fb
JF
2186
2187 unsigned total(0);
2188 for (Algorithm *pointer : GetAlgorithms()) {
2189 Algorithm &algorithm(*pointer);
2190 (void) algorithm;
2191
2192 const auto &blob(blobs[total == 0 ? CSSLOT_CODEDIRECTORY : CSSLOT_ALTERNATE + total - 1]);
2193 ++total;
2194
2195 std::vector<char> hash;
2196 algorithm(hash, blob.data(), blob.size());
2197 hash.resize(20);
2198
1190f447
JF
2199#ifdef LDID_NOPLIST
2200 auto value(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(hash.data()), hash.size()));
2201 _scope({ CFRelease(value); });
2202 CFArrayAppendValue(cdhashes, value);
2203#else
fe54c5fb 2204 plist_array_append_item(cdhashes, plist_new_data(hash.data(), hash.size()));
1190f447 2205#endif
fe54c5fb
JF
2206 }
2207
1190f447
JF
2208#ifdef LDID_NOPLIST
2209 auto created(CFPropertyListCreateXMLData(kCFAllocatorDefault, plist));
2210 _scope({ CFRelease(created); });
2211 auto xml(reinterpret_cast<const char *>(CFDataGetBytePtr(created)));
2212 auto size(CFDataGetLength(created));
2213#else
fe54c5fb
JF
2214 char *xml(NULL);
2215 uint32_t size;
2216 plist_to_xml(plist, &xml, &size);
2217 _scope({ free(xml); });
1190f447 2218#endif
fe54c5fb 2219
30c64adb
JF
2220 std::stringbuf data;
2221 const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
2222
2223 Stuff stuff(key);
2224 Buffer bio(sign);
2225
fe54c5fb 2226 Signature signature(stuff, sign, std::string(xml, size));
30c64adb
JF
2227 Buffer result(signature);
2228 std::string value(result);
2229 put(data, value.data(), value.size());
2230
ee5f5556
JF
2231 const auto &save(insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data));
2232 _assert(save.size() <= certificate);
30c64adb 2233 }
489c97b8 2234#endif
30c64adb 2235
efad8a44 2236 return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
b4b49374 2237 }), progress);
4ebf3494
JF
2238
2239 return hash;
e0098838
JF
2240}
2241
0326ab11 2242#ifndef LDID_NOTOOLS
b4b49374 2243static void Unsign(void *idata, size_t isize, std::streambuf &output, const Progress &progress) {
ec3af45e 2244 Allocate(idata, isize, output, fun([](const MachHeader &mach_header, Baton &baton, size_t size) -> size_t {
e0098838 2245 return 0;
803b4bc9 2246 }), fun([](const MachHeader &mach_header, const Baton &baton, std::streambuf &output, size_t limit, size_t left, size_t right, const std::string &overlap, const char *top, const Progress &progress) -> size_t {
e0098838 2247 return 0;
b4b49374 2248 }), progress);
f4b2df35
JF
2249}
2250
addc31c5 2251std::string DiskFolder::Path(const std::string &path) const {
90c0c6ef 2252 return path_ + path;
23c11ee8
JF
2253}
2254
2255DiskFolder::DiskFolder(const std::string &path) :
2256 path_(path)
2257{
90c0c6ef 2258 _assert_(path_.size() != 0 && path_[path_.size() - 1] == '/', "missing / on %s", path_.c_str());
23c11ee8
JF
2259}
2260
2261DiskFolder::~DiskFolder() {
2262 if (!std::uncaught_exception())
2263 for (const auto &commit : commit_)
2264 Commit(commit.first, commit.second);
2265}
2266
51ced023
JF
2267#ifndef __WIN32__
2268std::string readlink(const std::string &path) {
2269 for (size_t size(1024); ; size *= 2) {
2270 std::string data;
2271 data.resize(size);
2272
2273 int writ(_syscall(::readlink(path.c_str(), &data[0], data.size())));
2274 if (size_t(writ) >= size)
2275 continue;
2276
2277 data.resize(writ);
2278 return data;
2279 }
2280}
2281#endif
2282
addc31c5 2283void DiskFolder::Find(const std::string &root, const std::string &base, const Functor<void (const std::string &)> &code, const Functor<void (const std::string &, const Functor<std::string ()> &)> &link) const {
54a0f854
JF
2284 std::string path(Path(root) + base);
2285
2286 DIR *dir(opendir(path.c_str()));
2287 _assert(dir != NULL);
2288 _scope({ _syscall(closedir(dir)); });
2289
2290 while (auto child = readdir(dir)) {
261b9963 2291 std::string name(child->d_name);
54a0f854
JF
2292 if (name == "." || name == "..")
2293 continue;
2294 if (Starts(name, ".ldid."))
2295 continue;
2296
b6d8da4e
JF
2297 bool directory;
2298
2299#ifdef __WIN32__
2300 struct stat info;
255e1652 2301 _syscall(stat((path + name).c_str(), &info));
b6d8da4e
JF
2302 if (false);
2303 else if (S_ISDIR(info.st_mode))
2304 directory = true;
2305 else if (S_ISREG(info.st_mode))
2306 directory = false;
2307 else
2308 _assert_(false, "st_mode=%x", info.st_mode);
2309#else
54a0f854
JF
2310 switch (child->d_type) {
2311 case DT_DIR:
b6d8da4e
JF
2312 directory = true;
2313 break;
54a0f854 2314 case DT_REG:
b6d8da4e
JF
2315 directory = false;
2316 break;
51ced023
JF
2317 case DT_LNK:
2318 link(base + name, fun([&]() { return readlink(path + name); }));
2319 continue;
54a0f854
JF
2320 default:
2321 _assert_(false, "d_type=%u", child->d_type);
54a0f854 2322 }
b6d8da4e
JF
2323#endif
2324
2325 if (directory)
51ced023 2326 Find(root, base + name + "/", code, link);
b6d8da4e 2327 else
addc31c5 2328 code(base + name);
54a0f854
JF
2329 }
2330}
2331
addc31c5
JF
2332void DiskFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2333 if (!edit) {
2334 // XXX: use nullbuf
2335 std::stringbuf save;
2336 code(save);
2337 } else {
2338 std::filebuf save;
2339 auto from(Path(path));
2340 commit_[from] = Temporary(save, from);
2341 code(save);
2342 }
23c11ee8
JF
2343}
2344
addc31c5 2345bool DiskFolder::Look(const std::string &path) const {
878260fc
JF
2346 return _syscall(access(Path(path).c_str(), R_OK), ENOENT) == 0;
2347}
2348
e1d26767 2349void DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
23c11ee8
JF
2350 std::filebuf data;
2351 auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
90c0c6ef 2352 _assert_(result == &data, "DiskFolder::Open(%s)", Path(path).c_str());
e1d26767
JF
2353
2354 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2355 data.pubseekpos(0, std::ios::in);
2356 code(data, length, NULL);
23c11ee8
JF
2357}
2358
addc31c5 2359void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &)> &code, const Functor<void (const std::string &, const Functor<std::string ()> &)> &link) const {
51ced023 2360 Find(path, "", code, link);
23c11ee8 2361}
0326ab11 2362#endif
23c11ee8 2363
2443500c 2364SubFolder::SubFolder(Folder &parent, const std::string &path) :
23c11ee8
JF
2365 parent_(parent),
2366 path_(path)
2367{
90c0c6ef
JF
2368 _assert_(path_.size() == 0 || path_[path_.size() - 1] == '/', "missing / on %s", path_.c_str());
2369}
2370
2371std::string SubFolder::Path(const std::string &path) const {
2372 return path_ + path;
23c11ee8
JF
2373}
2374
addc31c5 2375void SubFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
90c0c6ef 2376 return parent_.Save(Path(path), edit, flag, code);
23c11ee8
JF
2377}
2378
addc31c5 2379bool SubFolder::Look(const std::string &path) const {
90c0c6ef 2380 return parent_.Look(Path(path));
878260fc
JF
2381}
2382
e1d26767 2383void SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
90c0c6ef 2384 return parent_.Open(Path(path), code);
23c11ee8
JF
2385}
2386
addc31c5 2387void SubFolder::Find(const std::string &path, const Functor<void (const std::string &)> &code, const Functor<void (const std::string &, const Functor<std::string ()> &)> &link) const {
90c0c6ef 2388 return parent_.Find(Path(path), code, link);
23c11ee8
JF
2389}
2390
addc31c5 2391std::string UnionFolder::Map(const std::string &path) const {
7c49f771
JF
2392 auto remap(remaps_.find(path));
2393 if (remap == remaps_.end())
2394 return path;
2395 return remap->second;
2396}
2397
e1d26767 2398void UnionFolder::Map(const std::string &path, const Functor<void (const std::string &)> &code, const std::string &file, const Functor<void (const Functor<void (std::streambuf &, size_t, const void *)> &)> &save) const {
7c49f771 2399 if (file.size() >= path.size() && file.substr(0, path.size()) == path)
addc31c5 2400 code(file.substr(path.size()));
7c49f771
JF
2401}
2402
886cb3f1
JF
2403UnionFolder::UnionFolder(Folder &parent) :
2404 parent_(parent)
2405{
2406}
2407
addc31c5
JF
2408void UnionFolder::Save(const std::string &path, bool edit, const void *flag, const Functor<void (std::streambuf &)> &code) {
2409 return parent_.Save(Map(path), edit, flag, code);
886cb3f1
JF
2410}
2411
addc31c5 2412bool UnionFolder::Look(const std::string &path) const {
878260fc
JF
2413 auto file(resets_.find(path));
2414 if (file != resets_.end())
2415 return true;
2416 return parent_.Look(Map(path));
2417}
2418
e1d26767 2419void UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, size_t, const void *)> &code) const {
7c49f771
JF
2420 auto file(resets_.find(path));
2421 if (file == resets_.end())
2422 return parent_.Open(Map(path), code);
fefcecb0 2423 auto &entry(file->second);
886cb3f1 2424
4e6d856a 2425 auto &data(*entry.data_);
e1d26767 2426 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
886cb3f1 2427 data.pubseekpos(0, std::ios::in);
4e6d856a 2428 code(data, length, entry.flag_);
886cb3f1
JF
2429}
2430
addc31c5 2431void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &)> &code, const Functor<void (const std::string &, const Functor<std::string ()> &)> &link) const {
7c49f771 2432 for (auto &reset : resets_)
e1d26767 2433 Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
fefcecb0 2434 auto &entry(reset.second);
4e6d856a
JF
2435 auto &data(*entry.data_);
2436 auto length(data.pubseekoff(0, std::ios::end, std::ios::in));
2437 data.pubseekpos(0, std::ios::in);
2438 code(data, length, entry.flag_);
7c49f771
JF
2439 }));
2440
2441 for (auto &remap : remaps_)
e1d26767
JF
2442 Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, size_t, const void *)> &code) {
2443 parent_.Open(remap.second, fun([&](std::streambuf &data, size_t length, const void *flag) {
2444 code(data, length, flag);
886cb3f1 2445 }));
7c49f771 2446 }));
66f2305d
JF
2447
2448 parent_.Find(path, fun([&](const std::string &name) {
2449 if (deletes_.find(path + name) == deletes_.end())
2450 code(name);
2451 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
2452 if (deletes_.find(path + name) == deletes_.end())
2453 link(name, read);
2454 }));
886cb3f1
JF
2455}
2456
0326ab11 2457#ifndef LDID_NOTOOLS
b4b49374
JF
2458static void copy(std::streambuf &source, std::streambuf &target, size_t length, const Progress &progress) {
2459 progress(0);
23c11ee8
JF
2460 size_t total(0);
2461 for (;;) {
e1d26767 2462 char data[4096 * 4];
23c11ee8
JF
2463 size_t writ(source.sgetn(data, sizeof(data)));
2464 if (writ == 0)
2465 break;
2466 _assert(target.sputn(data, writ) == writ);
2467 total += writ;
b4b49374 2468 progress(double(total) / length);
23c11ee8 2469 }
23c11ee8
JF
2470}
2471
489c97b8 2472#ifndef LDID_NOPLIST
8dfe0afc
JF
2473static plist_t plist(const std::string &data) {
2474 plist_t plist(NULL);
2475 if (Starts(data, "bplist00"))
2476 plist_from_bin(data.data(), data.size(), &plist);
2477 else
2478 plist_from_xml(data.data(), data.size(), &plist);
2479 _assert(plist != NULL);
2480 return plist;
23c11ee8
JF
2481}
2482
e1d26767 2483static void plist_d(std::streambuf &buffer, size_t length, const Functor<void (plist_t)> &code) {
23c11ee8 2484 std::stringbuf data;
b4b49374 2485 copy(buffer, data, length, dummy_);
8dfe0afc
JF
2486 auto node(plist(data.str()));
2487 _scope({ plist_free(node); });
2488 _assert(plist_get_node_type(node) == PLIST_DICT);
2489 code(node);
23c11ee8
JF
2490}
2491
8dfe0afc
JF
2492static std::string plist_s(plist_t node) {
2493 _assert(node != NULL);
2494 _assert(plist_get_node_type(node) == PLIST_STRING);
2495 char *data;
2496 plist_get_string_val(node, &data);
2497 _scope({ free(data); });
2498 return data;
23c11ee8 2499}
489c97b8 2500#endif
23c11ee8
JF
2501
2502enum Mode {
2503 NoMode,
2504 OptionalMode,
2505 OmitMode,
2506 NestedMode,
2507 TopMode,
2508};
2509
2510class Expression {
2511 private:
2512 regex_t regex_;
4ebf3494 2513 std::vector<std::string> matches_;
23c11ee8
JF
2514
2515 public:
2516 Expression(const std::string &code) {
4ebf3494
JF
2517 _assert_(regcomp(&regex_, code.c_str(), REG_EXTENDED) == 0, "regcomp()");
2518 matches_.resize(regex_.re_nsub + 1);
23c11ee8
JF
2519 }
2520
2521 ~Expression() {
2522 regfree(&regex_);
2523 }
2524
4ebf3494
JF
2525 bool operator ()(const std::string &data) {
2526 regmatch_t matches[matches_.size()];
2527 auto value(regexec(&regex_, data.c_str(), matches_.size(), matches, 0));
23c11ee8
JF
2528 if (value == REG_NOMATCH)
2529 return false;
2530 _assert_(value == 0, "regexec()");
4ebf3494
JF
2531 for (size_t i(0); i != matches_.size(); ++i)
2532 matches_[i].assign(data.data() + matches[i].rm_so, matches[i].rm_eo - matches[i].rm_so);
23c11ee8
JF
2533 return true;
2534 }
4ebf3494
JF
2535
2536 const std::string &operator [](size_t index) const {
2537 return matches_[index];
2538 }
23c11ee8
JF
2539};
2540
2541struct Rule {
2542 unsigned weight_;
2543 Mode mode_;
2544 std::string code_;
2545
2546 mutable std::auto_ptr<Expression> regex_;
2547
2548 Rule(unsigned weight, Mode mode, const std::string &code) :
2549 weight_(weight),
2550 mode_(mode),
2551 code_(code)
2552 {
2553 }
2554
2555 Rule(const Rule &rhs) :
2556 weight_(rhs.weight_),
2557 mode_(rhs.mode_),
2558 code_(rhs.code_)
2559 {
2560 }
2561
2562 void Compile() const {
2563 regex_.reset(new Expression(code_));
2564 }
2565
2566 bool operator ()(const std::string &data) const {
2567 _assert(regex_.get() != NULL);
2568 return (*regex_)(data);
2569 }
2570
2571 bool operator <(const Rule &rhs) const {
2572 if (weight_ > rhs.weight_)
2573 return true;
2574 if (weight_ < rhs.weight_)
2575 return false;
2576 return mode_ > rhs.mode_;
2577 }
2578};
2579
2580struct RuleCode {
2581 bool operator ()(const Rule *lhs, const Rule *rhs) const {
2582 return lhs->code_ < rhs->code_;
2583 }
2584};
2585
489c97b8 2586#ifndef LDID_NOPLIST
ec3af45e 2587static Hash Sign(const uint8_t *prefix, size_t size, std::streambuf &buffer, Hash &hash, std::streambuf &save, const std::string &identifier, const std::string &entitlements, bool merge, const std::string &requirements, const std::string &key, const Slots &slots, size_t length, uint32_t flags, bool platform, const Progress &progress) {
7f5ad603
JF
2588 // XXX: this is a miserable fail
2589 std::stringbuf temp;
f9cd1d1c 2590 put(temp, prefix, size);
b4b49374 2591 copy(buffer, temp, length - size, progress);
c4f8d243 2592 // XXX: this is a stupid hack
e1d26767 2593 pad(temp, 0x10 - (length & 0xf));
7f5ad603
JF
2594 auto data(temp.str());
2595
2596 HashProxy proxy(hash, save);
ec3af45e 2597 return Sign(data.data(), data.size(), proxy, identifier, entitlements, merge, requirements, key, slots, flags, platform, progress);
7f5ad603
JF
2598}
2599
99a1dc0c
JF
2600struct State {
2601 std::map<std::string, Hash> files;
2602 std::map<std::string, std::string> links;
2603
2604 void Merge(const std::string &root, const State &state) {
2605 for (const auto &entry : state.files)
2606 files[root + entry.first] = entry.second;
2607 for (const auto &entry : state.links)
2608 links[root + entry.first] = entry.second;
2609 }
2610};
2611
90c0c6ef 2612Bundle Sign(const std::string &root, Folder &parent, const std::string &key, State &remote, const std::string &requirements, const Functor<std::string (const std::string &, const std::string &)> &alter, const Progress &progress) {
23c11ee8
JF
2613 std::string executable;
2614 std::string identifier;
2615
4ebf3494
JF
2616 bool mac(false);
2617
2618 std::string info("Info.plist");
90c0c6ef
JF
2619
2620 SubFolder folder(parent, [&]() {
2621 if (parent.Look(info))
2622 return "";
4ebf3494 2623 mac = true;
90c0c6ef
JF
2624 if (false);
2625 else if (parent.Look("Contents/" + info))
2626 return "Contents/";
2627 else if (parent.Look("Resources/" + info)) {
2628 info = "Resources/" + info;
2629 return "";
2630 } else _assert_(false, "cannot find Info.plist");
2631 }());
23c11ee8 2632
e1d26767
JF
2633 folder.Open(info, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2634 plist_d(buffer, length, fun([&](plist_t node) {
8dfe0afc
JF
2635 executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
2636 identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
23c11ee8 2637 }));
878260fc 2638 }));
23c11ee8 2639
90c0c6ef 2640 if (mac && info == "Info.plist")
4ebf3494 2641 executable = "MacOS/" + executable;
4ebf3494 2642
b4b49374
JF
2643 progress(root + "*");
2644
9b693b34 2645 std::string entitlements;
e1d26767 2646 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
9b693b34
JF
2647 // XXX: this is a miserable fail
2648 std::stringbuf temp;
b4b49374 2649 copy(buffer, temp, length, progress);
9b693b34 2650 // XXX: this is a stupid hack
e1d26767 2651 pad(temp, 0x10 - (length & 0xf));
9b693b34
JF
2652 auto data(temp.str());
2653 entitlements = alter(root, Analyze(data.data(), data.size()));
2654 }));
2655
d9c2341d
JF
2656 static const std::string directory("_CodeSignature/");
2657 static const std::string signature(directory + "CodeResources");
2658
23c11ee8
JF
2659 std::map<std::string, std::multiset<Rule>> versions;
2660
2661 auto &rules1(versions[""]);
2662 auto &rules2(versions["2"]);
2663
4ebf3494
JF
2664 const std::string resources(mac ? "Resources/" : "");
2665
23c11ee8 2666 if (true) {
90c0c6ef 2667 rules1.insert(Rule{1, NoMode, "^" + (resources == "" ? ".*" : resources)});
4ebf3494
JF
2668 rules1.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2669 rules1.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
90c0c6ef 2670 rules1.insert(Rule{1010, NoMode, "^" + resources + "Base\\.lproj/"});
23c11ee8
JF
2671 rules1.insert(Rule{1, NoMode, "^version.plist$"});
2672 }
2673
2674 if (true) {
2675 rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
90c0c6ef 2676 if (mac) rules2.insert(Rule{20, NoMode, "^" + resources});
23c11ee8 2677 rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
90c0c6ef 2678 if (mac) rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
23c11ee8 2679 rules2.insert(Rule{1, NoMode, "^.*"});
4ebf3494
JF
2680 rules2.insert(Rule{1000, OptionalMode, "^" + resources + ".*\\.lproj/"});
2681 rules2.insert(Rule{1100, OmitMode, "^" + resources + ".*\\.lproj/locversion.plist$"});
90c0c6ef 2682 if (!mac) rules2.insert(Rule{1010, NoMode, "^Base\\.lproj/"});
23c11ee8
JF
2683 rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
2684 rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
90c0c6ef 2685 if (mac) rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
23c11ee8 2686 rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
90c0c6ef 2687 if (mac) rules2.insert(Rule{1010, NoMode, "^" + resources + "Base\\.lproj/"});
23c11ee8
JF
2688 rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
2689 }
2690
99a1dc0c 2691 State local;
23c11ee8 2692
4ebf3494 2693 std::string failure(mac ? "Contents/|Versions/[^/]*/Resources/" : "");
7d19f8dd 2694 Expression nested("^(Frameworks/[^/]*\\.framework|PlugIns/[^/]*\\.appex(()|/[^/]*.app))/(" + failure + ")Info\\.plist$");
4ebf3494 2695 std::map<std::string, Bundle> bundles;
23c11ee8 2696
addc31c5 2697 folder.Find("", fun([&](const std::string &name) {
23c11ee8
JF
2698 if (!nested(name))
2699 return;
2700 auto bundle(root + Split(name).dir);
90c0c6ef
JF
2701 if (mac) {
2702 _assert(!bundle.empty());
2703 bundle = Split(bundle.substr(0, bundle.size() - 1)).dir;
2704 }
2443500c 2705 SubFolder subfolder(folder, bundle);
9b693b34
JF
2706
2707 bundles[nested[1]] = Sign(bundle, subfolder, key, local, "", Starts(name, "PlugIns/") ? alter :
4230d78b 2708 static_cast<const Functor<std::string (const std::string &, const std::string &)> &>(fun([&](const std::string &, const std::string &) -> std::string { return entitlements; }))
b4b49374 2709 , progress);
51ced023 2710 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
23c11ee8
JF
2711 }));
2712
1acc78fb 2713 std::set<std::string> excludes;
51ced023 2714
4ebf3494 2715 auto exclude([&](const std::string &name) {
d9c2341d
JF
2716 // BundleDiskRep::adjustResources -> builder.addExclusion
2717 if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
4ebf3494 2718 return true;
23c11ee8 2719
7d19f8dd 2720 for (const auto &bundle : bundles)
1acc78fb
JF
2721 if (Starts(name, bundle.first + "/")) {
2722 excludes.insert(name);
4ebf3494 2723 return true;
1acc78fb 2724 }
4ebf3494
JF
2725
2726 return false;
2727 });
2728
addc31c5 2729 folder.Find("", fun([&](const std::string &name) {
4ebf3494
JF
2730 if (exclude(name))
2731 return;
2732
99a1dc0c 2733 if (local.files.find(name) != local.files.end())
7d19f8dd 2734 return;
99a1dc0c 2735 auto &hash(local.files[name]);
23c11ee8 2736
e1d26767
JF
2737 folder.Open(name, fun([&](std::streambuf &data, size_t length, const void *flag) {
2738 progress(root + name);
2739
f9cd1d1c
JF
2740 union {
2741 struct {
2742 uint32_t magic;
2743 uint32_t count;
2744 };
2745
2746 uint8_t bytes[8];
2747 } header;
2748
2749 auto size(most(data, &header.bytes, sizeof(header.bytes)));
7d19f8dd
JF
2750
2751 if (name != "_WatchKitStub/WK" && size == sizeof(header.bytes))
f9cd1d1c
JF
2752 switch (Swap(header.magic)) {
2753 case FAT_MAGIC:
2754 // Java class file format
2755 if (Swap(header.count) >= 40)
2756 break;
2757 case FAT_CIGAM:
2758 case MH_MAGIC: case MH_MAGIC_64:
2759 case MH_CIGAM: case MH_CIGAM_64:
addc31c5
JF
2760 folder.Save(name, true, flag, fun([&](std::streambuf &save) {
2761 Slots slots;
ec3af45e 2762 Sign(header.bytes, size, data, hash, save, identifier, "", false, "", key, slots, length, 0, false, Progression(progress, root + name));
addc31c5 2763 }));
f9cd1d1c
JF
2764 return;
2765 }
2766
addc31c5
JF
2767 folder.Save(name, false, flag, fun([&](std::streambuf &save) {
2768 HashProxy proxy(hash, save);
2769 put(proxy, header.bytes, size);
b4b49374 2770 copy(data, proxy, length - size, progress);
addc31c5 2771 }));
23c11ee8 2772 }));
51ced023 2773 }), fun([&](const std::string &name, const Functor<std::string ()> &read) {
4ebf3494
JF
2774 if (exclude(name))
2775 return;
2776
99a1dc0c 2777 local.links[name] = read();
23c11ee8
JF
2778 }));
2779
8dfe0afc
JF
2780 auto plist(plist_new_dict());
2781 _scope({ plist_free(plist); });
23c11ee8
JF
2782
2783 for (const auto &version : versions) {
8dfe0afc
JF
2784 auto files(plist_new_dict());
2785 plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
23c11ee8
JF
2786
2787 for (const auto &rule : version.second)
2788 rule.Compile();
2789
9ec8439b
JF
2790 bool old(&version.second == &rules1);
2791
99a1dc0c 2792 for (const auto &hash : local.files)
23c11ee8
JF
2793 for (const auto &rule : version.second)
2794 if (rule(hash.first)) {
1acc78fb
JF
2795 if (!old && mac && excludes.find(hash.first) != excludes.end());
2796 else if (old && rule.mode_ == NoMode)
f74652ab 2797 plist_dict_set_item(files, hash.first.c_str(), plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
9ec8439b 2798 else if (rule.mode_ != OmitMode) {
8dfe0afc 2799 auto entry(plist_new_dict());
f74652ab 2800 plist_dict_set_item(entry, "hash", plist_new_data(reinterpret_cast<const char *>(hash.second.sha1_), sizeof(hash.second.sha1_)));
9ec8439b 2801 if (!old)
f74652ab 2802 plist_dict_set_item(entry, "hash2", plist_new_data(reinterpret_cast<const char *>(hash.second.sha256_), sizeof(hash.second.sha256_)));
9ec8439b
JF
2803 if (rule.mode_ == OptionalMode)
2804 plist_dict_set_item(entry, "optional", plist_new_bool(true));
8dfe0afc 2805 plist_dict_set_item(files, hash.first.c_str(), entry);
23c11ee8
JF
2806 }
2807
51ced023
JF
2808 break;
2809 }
2810
56459e57
JF
2811 if (!old)
2812 for (const auto &link : local.links)
2813 for (const auto &rule : version.second)
2814 if (rule(link.first)) {
2815 if (rule.mode_ != OmitMode) {
2816 auto entry(plist_new_dict());
2817 plist_dict_set_item(entry, "symlink", plist_new_string(link.second.c_str()));
2818 if (rule.mode_ == OptionalMode)
2819 plist_dict_set_item(entry, "optional", plist_new_bool(true));
2820 plist_dict_set_item(files, link.first.c_str(), entry);
2821 }
51ced023 2822
56459e57
JF
2823 break;
2824 }
4ebf3494 2825
7d19f8dd
JF
2826 if (!old && mac)
2827 for (const auto &bundle : bundles) {
2828 auto entry(plist_new_dict());
f74652ab 2829 plist_dict_set_item(entry, "cdhash", plist_new_data(reinterpret_cast<const char *>(bundle.second.hash.sha256_), sizeof(bundle.second.hash.sha256_)));
7d19f8dd
JF
2830 plist_dict_set_item(entry, "requirement", plist_new_string("anchor apple generic"));
2831 plist_dict_set_item(files, bundle.first.c_str(), entry);
2832 }
23c11ee8
JF
2833 }
2834
2835 for (const auto &version : versions) {
8dfe0afc
JF
2836 auto rules(plist_new_dict());
2837 plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
23c11ee8
JF
2838
2839 std::multiset<const Rule *, RuleCode> ordered;
2840 for (const auto &rule : version.second)
2841 ordered.insert(&rule);
2842
2843 for (const auto &rule : ordered)
2844 if (rule->weight_ == 1 && rule->mode_ == NoMode)
8dfe0afc 2845 plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
23c11ee8 2846 else {
8dfe0afc
JF
2847 auto entry(plist_new_dict());
2848 plist_dict_set_item(rules, rule->code_.c_str(), entry);
23c11ee8
JF
2849
2850 switch (rule->mode_) {
2851 case NoMode:
2852 break;
2853 case OmitMode:
8dfe0afc 2854 plist_dict_set_item(entry, "omit", plist_new_bool(true));
23c11ee8
JF
2855 break;
2856 case OptionalMode:
8dfe0afc 2857 plist_dict_set_item(entry, "optional", plist_new_bool(true));
23c11ee8
JF
2858 break;
2859 case NestedMode:
8dfe0afc 2860 plist_dict_set_item(entry, "nested", plist_new_bool(true));
23c11ee8
JF
2861 break;
2862 case TopMode:
8dfe0afc 2863 plist_dict_set_item(entry, "top", plist_new_bool(true));
23c11ee8
JF
2864 break;
2865 }
2866
2867 if (rule->weight_ >= 10000)
8dfe0afc 2868 plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
23c11ee8 2869 else if (rule->weight_ != 1)
8dfe0afc 2870 plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
23c11ee8 2871 }
23c11ee8
JF
2872 }
2873
addc31c5 2874 folder.Save(signature, true, NULL, fun([&](std::streambuf &save) {
99a1dc0c 2875 HashProxy proxy(local.files[signature], save);
8dfe0afc
JF
2876 char *xml(NULL);
2877 uint32_t size;
2878 plist_to_xml(plist, &xml, &size);
2879 _scope({ free(xml); });
2880 put(proxy, xml, size);
23c11ee8
JF
2881 }));
2882
4ebf3494 2883 Bundle bundle;
90c0c6ef 2884 bundle.path = folder.Path(executable);
4ebf3494 2885
e1d26767
JF
2886 folder.Open(executable, fun([&](std::streambuf &buffer, size_t length, const void *flag) {
2887 progress(root + executable);
addc31c5 2888 folder.Save(executable, true, flag, fun([&](std::streambuf &save) {
23c11ee8 2889 Slots slots;
99a1dc0c
JF
2890 slots[1] = local.files.at(info);
2891 slots[3] = local.files.at(signature);
2892 bundle.hash = Sign(NULL, 0, buffer, local.files[executable], save, identifier, entitlements, false, requirements, key, slots, length, 0, false, Progression(progress, root + executable));
23c11ee8
JF
2893 }));
2894 }));
2895
99a1dc0c 2896 remote.Merge(root, local);
4ebf3494 2897 return bundle;
23c11ee8 2898}
9ec8439b 2899
b4b49374 2900Bundle Sign(const std::string &root, Folder &folder, const std::string &key, const std::string &requirements, const Functor<std::string (const std::string &, const std::string &)> &alter, const Progress &progress) {
99a1dc0c 2901 State local;
b4b49374 2902 return Sign(root, folder, key, local, requirements, alter, progress);
9ec8439b 2903}
489c97b8 2904#endif
23c11ee8 2905
0326ab11 2906#endif
a0c715e9
JF
2907}
2908
c83a840d
JF
2909std::string Hex(const uint8_t *data, size_t size) {
2910 std::string hex;
2911 hex.reserve(size * 2);
2912 for (size_t i(0); i != size; ++i) {
2913 hex += "0123456789abcdef"[data[i] >> 4];
2914 hex += "0123456789abcdef"[data[i] & 0xf];
2915 }
2916 return hex;
2917}
2918
c2f8abf0
JF
2919static void usage(const char *argv0) {
2920 fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv0);
2921 fprintf(stderr, " %s -e MobileSafari\n", argv0);
2922 fprintf(stderr, " %s -S cat\n", argv0);
2923 fprintf(stderr, " %s -Stfp.xml gdb\n", argv0);
2924}
2925
0326ab11 2926#ifndef LDID_NOTOOLS
a7f01a65 2927int main(int argc, char *argv[]) {
489c97b8 2928#ifndef LDID_NOSMIME
30c64adb 2929 OpenSSL_add_all_algorithms();
489c97b8 2930#endif
30c64adb 2931
5525a5a7
JF
2932 union {
2933 uint16_t word;
2934 uint8_t byte[2];
2935 } endian = {1};
2936
2937 little_ = endian.byte[0];
2938
20e7eb29 2939 bool flag_r(false);
9c83be90 2940 bool flag_e(false);
9914b1b3 2941 bool flag_q(false);
a362a82f 2942
f58c84b8 2943 bool flag_H(false);
c83a840d 2944 bool flag_h(false);
f58c84b8 2945
fdbee693 2946#ifndef LDID_NOFLAGT
a362a82f 2947 bool flag_T(false);
fdbee693 2948#endif
20c5f1e8 2949
fdb119ef 2950 bool flag_S(false);
20c5f1e8 2951 bool flag_s(false);
a362a82f 2952
c0cc1574 2953 bool flag_D(false);
9dcaee40 2954 bool flag_d(false);
c0cc1574 2955
8c417842
JF
2956 bool flag_A(false);
2957 bool flag_a(false);
2958
56f0487d
JF
2959 bool flag_u(false);
2960
ec3af45e
JF
2961 bool flag_M(false);
2962
296fd38e
JF
2963 uint32_t flags(0);
2964 bool platform(false);
2965
c0cc1574
JF
2966 uint32_t flag_CPUType(_not(uint32_t));
2967 uint32_t flag_CPUSubtype(_not(uint32_t));
2968
5d7ceb5d
JF
2969 const char *flag_I(NULL);
2970
fdbee693 2971#ifndef LDID_NOFLAGT
a362a82f
JF
2972 bool timeh(false);
2973 uint32_t timev(0);
fdbee693 2974#endif
a362a82f 2975
4d4682ef 2976 Map entitlements;
8afb9766 2977 Map requirements;
30c64adb 2978 Map key;
a0c715e9 2979 ldid::Slots slots;
c05d9758 2980
a362a82f
JF
2981 std::vector<std::string> files;
2982
a960f392 2983 if (argc == 1) {
c2f8abf0
JF
2984 usage(argv[0]);
2985 return 0;
a960f392
JF
2986 }
2987
a362a82f
JF
2988 for (int argi(1); argi != argc; ++argi)
2989 if (argv[argi][0] != '-')
2990 files.push_back(argv[argi]);
2991 else switch (argv[argi][1]) {
fac3d3e3
JF
2992 case 'r':
2993 _assert(!flag_s);
2994 _assert(!flag_S);
2995 flag_r = true;
2996 break;
2997
9c83be90 2998 case 'e': flag_e = true; break;
c05d9758 2999
e57b1f91 3000 case 'E': {
f74652ab
JF
3001 const char *string = argv[argi] + 2;
3002 const char *colon = strchr(string, ':');
e57b1f91
JF
3003 _assert(colon != NULL);
3004 Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
3005 char *arge;
f74652ab 3006 unsigned number(strtoul(string, &arge, 0));
e57b1f91 3007 _assert(arge == colon);
f74652ab
JF
3008 auto &slot(slots[number]);
3009 for (Algorithm *algorithm : GetAlgorithms())
3010 (*algorithm)(slot, file.data(), file.size());
e57b1f91
JF
3011 } break;
3012
9914b1b3
JF
3013 case 'q': flag_q = true; break;
3014
f58c84b8
JF
3015 case 'H': {
3016 const char *hash = argv[argi] + 2;
3017
3018 if (!flag_H) {
3019 flag_H = true;
3020
3021 do_sha1 = false;
3022 do_sha256 = false;
3023
3024 fprintf(stderr, "WARNING: -H is only present for compatibility with a fork of ldid\n");
3025 fprintf(stderr, " you should NOT be manually specifying the hash algorithm\n");
3026 }
3027
3028 if (false);
3029 else if (strcmp(hash, "sha1") == 0)
3030 do_sha1 = true;
3031 else if (strcmp(hash, "sha256") == 0)
3032 do_sha256 = true;
3033 else _assert(false);
3034 } break;
3035
c83a840d
JF
3036 case 'h': flag_h = true; break;
3037
9914b1b3
JF
3038 case 'Q': {
3039 const char *xml = argv[argi] + 2;
8afb9766 3040 requirements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
9914b1b3
JF
3041 } break;
3042
c0cc1574 3043 case 'D': flag_D = true; break;
9dcaee40 3044 case 'd': flag_d = true; break;
c0cc1574 3045
8c417842
JF
3046 case 'a': flag_a = true; break;
3047
3048 case 'A':
fac3d3e3 3049 _assert(!flag_A);
8c417842
JF
3050 flag_A = true;
3051 if (argv[argi][2] != '\0') {
3052 const char *cpu = argv[argi] + 2;
3053 const char *colon = strchr(cpu, ':');
3054 _assert(colon != NULL);
3055 char *arge;
3056 flag_CPUType = strtoul(cpu, &arge, 0);
3057 _assert(arge == colon);
3058 flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
3059 _assert(arge == argv[argi] + strlen(argv[argi]));
3060 }
3061 break;
3062
296fd38e
JF
3063 case 'C': {
3064 const char *name = argv[argi] + 2;
3065 if (false);
3066 else if (strcmp(name, "host") == 0)
3067 flags |= kSecCodeSignatureHost;
3068 else if (strcmp(name, "adhoc") == 0)
3069 flags |= kSecCodeSignatureAdhoc;
3070 else if (strcmp(name, "hard") == 0)
3071 flags |= kSecCodeSignatureForceHard;
3072 else if (strcmp(name, "kill") == 0)
3073 flags |= kSecCodeSignatureForceKill;
3074 else if (strcmp(name, "expires") == 0)
3075 flags |= kSecCodeSignatureForceExpiration;
3076 else if (strcmp(name, "restrict") == 0)
3077 flags |= kSecCodeSignatureRestrict;
3078 else if (strcmp(name, "enforcement") == 0)
3079 flags |= kSecCodeSignatureEnforcement;
3080 else if (strcmp(name, "library-validation") == 0)
3081 flags |= kSecCodeSignatureLibraryValidation;
c83a840d
JF
3082 else if (strcmp(name, "runtime") == 0)
3083 flags |= kSecCodeSignatureRuntime;
296fd38e
JF
3084 else _assert(false);
3085 } break;
3086
3087 case 'P':
3088 platform = true;
3089 break;
3090
20c5f1e8 3091 case 's':
fac3d3e3 3092 _assert(!flag_r);
20c5f1e8
JF
3093 _assert(!flag_S);
3094 flag_s = true;
3095 break;
3096
c05d9758 3097 case 'S':
fac3d3e3 3098 _assert(!flag_r);
20c5f1e8 3099 _assert(!flag_s);
c05d9758
JF
3100 flag_S = true;
3101 if (argv[argi][2] != '\0') {
3102 const char *xml = argv[argi] + 2;
4d4682ef 3103 entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
c05d9758
JF
3104 }
3105 break;
a362a82f 3106
ec3af45e
JF
3107 case 'M':
3108 flag_M = true;
3109 break;
3110
30c64adb 3111 case 'K':
d73a3d58
JF
3112 if (argv[argi][2] != '\0')
3113 key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
30c64adb
JF
3114 break;
3115
fdbee693 3116#ifndef LDID_NOFLAGT
a362a82f
JF
3117 case 'T': {
3118 flag_T = true;
3119 if (argv[argi][2] == '-')
3120 timeh = true;
3121 else {
3122 char *arge;
3123 timev = strtoul(argv[argi] + 2, &arge, 0);
3124 _assert(arge == argv[argi] + strlen(argv[argi]));
3125 }
3126 } break;
fdbee693 3127#endif
a362a82f 3128
56f0487d
JF
3129 case 'u': {
3130 flag_u = true;
3131 } break;
3132
5d7ceb5d
JF
3133 case 'I': {
3134 flag_I = argv[argi] + 2;
3135 } break;
3136
a362a82f 3137 default:
c2f8abf0
JF
3138 usage(argv[0]);
3139 return 1;
a362a82f
JF
3140 break;
3141 }
3142
fac3d3e3
JF
3143 _assert(flag_S || key.empty());
3144 _assert(flag_S || flag_I == NULL);
f4b2df35 3145
9dcaee40
JF
3146 if (flag_d && !flag_h) {
3147 flag_h = true;
3148 fprintf(stderr, "WARNING: -d also (temporarily) does the behavior of -h for compatibility with a fork of ldid\n");
3149 }
3150
c2f8abf0
JF
3151 if (files.empty())
3152 return 0;
a362a82f
JF
3153
3154 size_t filei(0), filee(0);
3155 _foreach (file, files) try {
d4187e53 3156 std::string path(file);
5d7ceb5d 3157
23c11ee8
JF
3158 struct stat info;
3159 _syscall(stat(path.c_str(), &info));
8762082f 3160
d4a4dbe8
JF
3161 if (S_ISDIR(info.st_mode)) {
3162 _assert(flag_S);
489c97b8 3163#ifndef LDID_NOPLIST
90c0c6ef 3164 ldid::DiskFolder folder(path + "/");
b4b49374 3165 path += "/" + Sign("", folder, key, requirements, ldid::fun([&](const std::string &, const std::string &) -> std::string { return entitlements; }), dummy_).path;
489c97b8
JF
3166#else
3167 _assert(false);
3168#endif
23c11ee8
JF
3169 } else if (flag_S || flag_r) {
3170 Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
8762082f 3171
4d4682ef 3172 std::filebuf output;
23c11ee8
JF
3173 Split split(path);
3174 auto temp(Temporary(output, split));
4d4682ef 3175
e0098838 3176 if (flag_r)
b4b49374 3177 ldid::Unsign(input.data(), input.size(), output, dummy_);
8762082f 3178 else {
23c11ee8 3179 std::string identifier(flag_I ?: split.base.c_str());
ec3af45e 3180 ldid::Sign(input.data(), input.size(), output, identifier, entitlements, flag_M, requirements, key, slots, flags, platform, dummy_);
8762082f 3181 }
34f4c1d8 3182
d4187e53 3183 Commit(path, temp);
fdb119ef
JF
3184 }
3185
fdbee693
JF
3186 bool modify(false);
3187#ifndef LDID_NOFLAGT
3188 if (flag_T)
3189 modify = true;
3190#endif
3191 if (flag_s)
3192 modify = true;
3193
3194 Map mapping(path, modify);
dede6121 3195 FatHeader fat_header(mapping.data(), mapping.size());
a362a82f 3196
0a033524 3197 _foreach (mach_header, fat_header.GetMachHeaders()) {
d840a088 3198 struct linkedit_data_command *signature(NULL);
7b496abd
JF
3199 struct encryption_info_command *encryption(NULL);
3200
8c417842
JF
3201 if (flag_A) {
3202 if (mach_header.GetCPUType() != flag_CPUType)
3203 continue;
3204 if (mach_header.GetCPUSubtype() != flag_CPUSubtype)
3205 continue;
3206 }
3207
3208 if (flag_a)
3209 printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype());
3210
0a033524
JF
3211 _foreach (load_command, mach_header.GetLoadCommands()) {
3212 uint32_t cmd(mach_header.Swap(load_command->cmd));
3213
cad40c43 3214 if (false);
0a033524
JF
3215 else if (cmd == LC_CODE_SIGNATURE)
3216 signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
843aea8c 3217 else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64)
7b496abd 3218 encryption = reinterpret_cast<struct encryption_info_command *>(load_command);
56f0487d
JF
3219 else if (cmd == LC_LOAD_DYLIB) {
3220 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
3221 const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name));
3222
3223 if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) {
3224 if (flag_u) {
3225 Version version;
3226 version.value = mach_header.Swap(dylib_command->dylib.current_version);
3227 printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch);
3228 }
3229 }
3230 }
fdbee693 3231#ifndef LDID_NOFLAGT
cad40c43 3232 else if (cmd == LC_ID_DYLIB) {
0a033524 3233 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command));
a362a82f 3234
0a033524
JF
3235 if (flag_T) {
3236 uint32_t timed;
a362a82f 3237
0a033524
JF
3238 if (!timeh)
3239 timed = timev;
3240 else {
3241 dylib_command->dylib.timestamp = 0;
3242 timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev);
3243 }
a362a82f 3244
0a033524
JF
3245 dylib_command->dylib.timestamp = mach_header.Swap(timed);
3246 }
7b496abd 3247 }
fdbee693 3248#endif
7b496abd
JF
3249 }
3250
9dcaee40
JF
3251 if (flag_d && encryption != NULL) {
3252 printf("cryptid=%d\n", mach_header.Swap(encryption->cryptid));
3253 }
3254
7b496abd
JF
3255 if (flag_D) {
3256 _assert(encryption != NULL);
3257 encryption->cryptid = mach_header.Swap(0);
a362a82f 3258 }
a362a82f 3259
0a033524
JF
3260 if (flag_e) {
3261 _assert(signature != NULL);
9c83be90 3262
0a033524 3263 uint32_t data = mach_header.Swap(signature->dataoff);
9c83be90 3264
0a033524
JF
3265 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3266 uint8_t *blob = top + data;
3267 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
9c83be90 3268
0a033524
JF
3269 for (size_t index(0); index != Swap(super->count); ++index)
3270 if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) {
3271 uint32_t begin = Swap(super->index[index].offset);
3272 struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin);
b9652d6e 3273 fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout);
0a033524
JF
3274 }
3275 }
9c83be90 3276
9914b1b3
JF
3277 if (flag_q) {
3278 _assert(signature != NULL);
3279
3280 uint32_t data = mach_header.Swap(signature->dataoff);
3281
3282 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3283 uint8_t *blob = top + data;
3284 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3285
3286 for (size_t index(0); index != Swap(super->count); ++index)
3287 if (Swap(super->index[index].type) == CSSLOT_REQUIREMENTS) {
3288 uint32_t begin = Swap(super->index[index].offset);
3289 struct Blob *requirement = reinterpret_cast<struct Blob *>(blob + begin);
3290 fwrite(requirement, 1, Swap(requirement->length), stdout);
3291 }
3292 }
3293
0a033524
JF
3294 if (flag_s) {
3295 _assert(signature != NULL);
20c5f1e8 3296
0a033524 3297 uint32_t data = mach_header.Swap(signature->dataoff);
20c5f1e8 3298
0a033524
JF
3299 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3300 uint8_t *blob = top + data;
3301 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
20c5f1e8 3302
0a033524
JF
3303 for (size_t index(0); index != Swap(super->count); ++index)
3304 if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) {
3305 uint32_t begin = Swap(super->index[index].offset);
b2e6a299 3306 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob));
20c5f1e8 3307
84d29a1c 3308 uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset));
0a033524 3309 uint32_t pages = Swap(directory->nCodeSlots);
20c5f1e8 3310
0a033524
JF
3311 if (pages != 1)
3312 for (size_t i = 0; i != pages - 1; ++i)
f74652ab 3313 LDID_SHA1(top + PageSize_ * i, PageSize_, hashes[i]);
0a033524 3314 if (pages != 0)
f74652ab 3315 LDID_SHA1(top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1, hashes[pages - 1]);
0a033524
JF
3316 }
3317 }
c83a840d
JF
3318
3319 if (flag_h) {
3320 _assert(signature != NULL);
3321
3322 auto algorithms(GetAlgorithms());
3323
3324 uint32_t data = mach_header.Swap(signature->dataoff);
3325
3326 uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase());
3327 uint8_t *blob = top + data;
3328 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
3329
3330 struct Candidate {
3331 CodeDirectory *directory_;
3332 size_t size_;
3333 Algorithm &algorithm_;
3334 std::string hash_;
3335 };
3336
3337 std::map<uint8_t, Candidate> candidates;
3338
3339 for (size_t index(0); index != Swap(super->count); ++index) {
3340 auto type(Swap(super->index[index].type));
3341 if ((type == CSSLOT_CODEDIRECTORY || type >= CSSLOT_ALTERNATE) && type != CSSLOT_SIGNATURESLOT) {
3342 uint32_t begin = Swap(super->index[index].offset);
3343 uint32_t end = index + 1 == Swap(super->count) ? Swap(super->blob.length) : Swap(super->index[index + 1].offset);
3344 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob));
3345 auto type(directory->hashType);
3346 _assert(type > 0 && type <= algorithms.size());
3347 auto &algorithm(*algorithms[type - 1]);
3348 uint8_t hash[algorithm.size_];
3349 algorithm(hash, blob + begin, end - begin);
3350 candidates.insert({type, {directory, end - begin, algorithm, Hex(hash, 20)}});
3351 }
3352 }
3353
3354 _assert(!candidates.empty());
3355 auto best(candidates.end());
3356 --best;
3357
3358 const auto directory(best->second.directory_);
3359 const auto flags(Swap(directory->flags));
3360
3361 std::string names;
3362 if (flags & kSecCodeSignatureHost)
3363 names += ",host";
3364 if (flags & kSecCodeSignatureAdhoc)
3365 names += ",adhoc";
3366 if (flags & kSecCodeSignatureForceHard)
3367 names += ",hard";
3368 if (flags & kSecCodeSignatureForceKill)
3369 names += ",kill";
3370 if (flags & kSecCodeSignatureForceExpiration)
3371 names += ",expires";
3372 if (flags & kSecCodeSignatureRestrict)
3373 names += ",restrict";
3374 if (flags & kSecCodeSignatureEnforcement)
3375 names += ",enforcement";
3376 if (flags & kSecCodeSignatureLibraryValidation)
3377 names += ",library-validation";
3378 if (flags & kSecCodeSignatureRuntime)
3379 names += ",runtime";
3380
3381 printf("CodeDirectory v=%x size=%zd flags=0x%x(%s) hashes=%d+%d location=embedded\n",
3382 Swap(directory->version), best->second.size_, flags, names.empty() ? "none" : names.c_str() + 1, Swap(directory->nCodeSlots), Swap(directory->nSpecialSlots));
3383 printf("Hash type=%s size=%d\n", best->second.algorithm_.name(), directory->hashSize);
3384
3385 std::string choices;
3386 for (const auto &candidate : candidates) {
3387 auto choice(candidate.second.algorithm_.name());
3388 choices += ',';
3389 choices += choice;
3390 printf("CandidateCDHash %s=%s\n", choice, candidate.second.hash_.c_str());
3391 }
3392 printf("Hash choices=%s\n", choices.c_str() + 1);
3393
3394 printf("CDHash=%s\n", best->second.hash_.c_str());
3395 }
fdb119ef
JF
3396 }
3397
a362a82f
JF
3398 ++filei;
3399 } catch (const char *) {
3400 ++filee;
3401 ++filei;
3402 }
3403
3404 return filee;
3405}
0326ab11 3406#endif