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