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