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