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