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