]>
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 | #endif | |
89 | ||
90 | #include "ldid.hpp" | |
91 | ||
92 | #define _assert___(line) \ | |
93 | #line | |
94 | #define _assert__(line) \ | |
95 | _assert___(line) | |
96 | ||
97 | #ifdef __EXCEPTIONS | |
98 | #define _assert_(expr, format, ...) \ | |
99 | do if (!(expr)) { \ | |
100 | fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \ | |
101 | throw __FILE__ "(" _assert__(__LINE__) "): _assert(" #expr ")"; \ | |
102 | } while (false) | |
103 | #else | |
104 | // XXX: this is not acceptable | |
105 | #define _assert_(expr, format, ...) \ | |
106 | do if (!(expr)) { \ | |
107 | fprintf(stderr, "%s(%u): _assert(): " format "\n", __FILE__, __LINE__, ## __VA_ARGS__); \ | |
108 | exit(-1); \ | |
109 | } while (false) | |
110 | #endif | |
111 | ||
112 | #define _assert(expr) \ | |
113 | _assert_(expr, "%s", #expr) | |
114 | ||
115 | #define _syscall(expr, ...) [&] { for (;;) { \ | |
116 | auto _value(expr); \ | |
117 | if ((long) _value != -1) \ | |
118 | return _value; \ | |
119 | int error(errno); \ | |
120 | if (error == EINTR) \ | |
121 | continue; \ | |
122 | /* XXX: EINTR is included in this list to fix g++ */ \ | |
123 | for (auto success : (long[]) {EINTR, __VA_ARGS__}) \ | |
124 | if (error == success) \ | |
125 | return (decltype(expr)) -success; \ | |
126 | _assert_(false, "errno=%u", error); \ | |
127 | } }() | |
128 | ||
129 | #define _trace() \ | |
130 | fprintf(stderr, "_trace(%s:%u): %s\n", __FILE__, __LINE__, __FUNCTION__) | |
131 | ||
132 | #define _not(type) \ | |
133 | ((type) ~ (type) 0) | |
134 | ||
135 | #define _packed \ | |
136 | __attribute__((packed)) | |
137 | ||
138 | template <typename Type_> | |
139 | struct Iterator_ { | |
140 | typedef typename Type_::const_iterator Result; | |
141 | }; | |
142 | ||
143 | #define _foreach(item, list) \ | |
144 | for (bool _stop(true); _stop; ) \ | |
145 | for (const __typeof__(list) &_list = (list); _stop; _stop = false) \ | |
146 | for (Iterator_<__typeof__(list)>::Result _item = _list.begin(); _item != _list.end(); ++_item) \ | |
147 | for (bool _suck(true); _suck; _suck = false) \ | |
148 | for (const __typeof__(*_item) &item = *_item; _suck; _suck = false) | |
149 | ||
150 | class _Scope { | |
151 | }; | |
152 | ||
153 | template <typename Function_> | |
154 | class Scope : | |
155 | public _Scope | |
156 | { | |
157 | private: | |
158 | Function_ function_; | |
159 | ||
160 | public: | |
161 | Scope(const Function_ &function) : | |
162 | function_(function) | |
163 | { | |
164 | } | |
165 | ||
166 | ~Scope() { | |
167 | function_(); | |
168 | } | |
169 | }; | |
170 | ||
171 | template <typename Function_> | |
172 | Scope<Function_> _scope(const Function_ &function) { | |
173 | return Scope<Function_>(function); | |
174 | } | |
175 | ||
176 | #define _scope__(counter, function) \ | |
177 | __attribute__((__unused__)) \ | |
178 | const _Scope &_scope ## counter(_scope([&]function)) | |
179 | #define _scope_(counter, function) \ | |
180 | _scope__(counter, function) | |
181 | #define _scope(function) \ | |
182 | _scope_(__COUNTER__, function) | |
183 | ||
184 | #define CPU_ARCH_MASK uint32_t(0xff000000) | |
185 | #define CPU_ARCH_ABI64 uint32_t(0x01000000) | |
186 | ||
187 | #define CPU_TYPE_ANY uint32_t(-1) | |
188 | #define CPU_TYPE_VAX uint32_t( 1) | |
189 | #define CPU_TYPE_MC680x0 uint32_t( 6) | |
190 | #define CPU_TYPE_X86 uint32_t( 7) | |
191 | #define CPU_TYPE_MC98000 uint32_t(10) | |
192 | #define CPU_TYPE_HPPA uint32_t(11) | |
193 | #define CPU_TYPE_ARM uint32_t(12) | |
194 | #define CPU_TYPE_MC88000 uint32_t(13) | |
195 | #define CPU_TYPE_SPARC uint32_t(14) | |
196 | #define CPU_TYPE_I860 uint32_t(15) | |
197 | #define CPU_TYPE_POWERPC uint32_t(18) | |
198 | ||
199 | #define CPU_TYPE_I386 CPU_TYPE_X86 | |
200 | ||
201 | #define CPU_TYPE_ARM64 (CPU_ARCH_ABI64 | CPU_TYPE_ARM) | |
202 | #define CPU_TYPE_POWERPC64 (CPU_ARCH_ABI64 | CPU_TYPE_POWERPC) | |
203 | #define CPU_TYPE_X86_64 (CPU_ARCH_ABI64 | CPU_TYPE_X86) | |
204 | ||
205 | struct fat_header { | |
206 | uint32_t magic; | |
207 | uint32_t nfat_arch; | |
208 | } _packed; | |
209 | ||
210 | #define FAT_MAGIC 0xcafebabe | |
211 | #define FAT_CIGAM 0xbebafeca | |
212 | ||
213 | struct fat_arch { | |
214 | uint32_t cputype; | |
215 | uint32_t cpusubtype; | |
216 | uint32_t offset; | |
217 | uint32_t size; | |
218 | uint32_t align; | |
219 | } _packed; | |
220 | ||
221 | struct mach_header { | |
222 | uint32_t magic; | |
223 | uint32_t cputype; | |
224 | uint32_t cpusubtype; | |
225 | uint32_t filetype; | |
226 | uint32_t ncmds; | |
227 | uint32_t sizeofcmds; | |
228 | uint32_t flags; | |
229 | } _packed; | |
230 | ||
231 | #define MH_MAGIC 0xfeedface | |
232 | #define MH_CIGAM 0xcefaedfe | |
233 | ||
234 | #define MH_MAGIC_64 0xfeedfacf | |
235 | #define MH_CIGAM_64 0xcffaedfe | |
236 | ||
237 | #define MH_DYLDLINK 0x4 | |
238 | ||
239 | #define MH_OBJECT 0x1 | |
240 | #define MH_EXECUTE 0x2 | |
241 | #define MH_DYLIB 0x6 | |
242 | #define MH_BUNDLE 0x8 | |
243 | #define MH_DYLIB_STUB 0x9 | |
244 | ||
245 | struct load_command { | |
246 | uint32_t cmd; | |
247 | uint32_t cmdsize; | |
248 | } _packed; | |
249 | ||
250 | #define LC_REQ_DYLD uint32_t(0x80000000) | |
251 | ||
252 | #define LC_SEGMENT uint32_t(0x01) | |
253 | #define LC_SYMTAB uint32_t(0x02) | |
254 | #define LC_DYSYMTAB uint32_t(0x0b) | |
255 | #define LC_LOAD_DYLIB uint32_t(0x0c) | |
256 | #define LC_ID_DYLIB uint32_t(0x0d) | |
257 | #define LC_SEGMENT_64 uint32_t(0x19) | |
258 | #define LC_UUID uint32_t(0x1b) | |
259 | #define LC_CODE_SIGNATURE uint32_t(0x1d) | |
260 | #define LC_SEGMENT_SPLIT_INFO uint32_t(0x1e) | |
261 | #define LC_REEXPORT_DYLIB uint32_t(0x1f | LC_REQ_DYLD) | |
262 | #define LC_ENCRYPTION_INFO uint32_t(0x21) | |
263 | #define LC_DYLD_INFO uint32_t(0x22) | |
264 | #define LC_DYLD_INFO_ONLY uint32_t(0x22 | LC_REQ_DYLD) | |
265 | #define LC_ENCRYPTION_INFO_64 uint32_t(0x2c) | |
266 | ||
267 | union Version { | |
268 | struct { | |
269 | uint8_t patch; | |
270 | uint8_t minor; | |
271 | uint16_t major; | |
272 | } _packed; | |
273 | ||
274 | uint32_t value; | |
275 | }; | |
276 | ||
277 | struct dylib { | |
278 | uint32_t name; | |
279 | uint32_t timestamp; | |
280 | uint32_t current_version; | |
281 | uint32_t compatibility_version; | |
282 | } _packed; | |
283 | ||
284 | struct dylib_command { | |
285 | uint32_t cmd; | |
286 | uint32_t cmdsize; | |
287 | struct dylib dylib; | |
288 | } _packed; | |
289 | ||
290 | struct uuid_command { | |
291 | uint32_t cmd; | |
292 | uint32_t cmdsize; | |
293 | uint8_t uuid[16]; | |
294 | } _packed; | |
295 | ||
296 | struct symtab_command { | |
297 | uint32_t cmd; | |
298 | uint32_t cmdsize; | |
299 | uint32_t symoff; | |
300 | uint32_t nsyms; | |
301 | uint32_t stroff; | |
302 | uint32_t strsize; | |
303 | } _packed; | |
304 | ||
305 | struct dyld_info_command { | |
306 | uint32_t cmd; | |
307 | uint32_t cmdsize; | |
308 | uint32_t rebase_off; | |
309 | uint32_t rebase_size; | |
310 | uint32_t bind_off; | |
311 | uint32_t bind_size; | |
312 | uint32_t weak_bind_off; | |
313 | uint32_t weak_bind_size; | |
314 | uint32_t lazy_bind_off; | |
315 | uint32_t lazy_bind_size; | |
316 | uint32_t export_off; | |
317 | uint32_t export_size; | |
318 | } _packed; | |
319 | ||
320 | struct dysymtab_command { | |
321 | uint32_t cmd; | |
322 | uint32_t cmdsize; | |
323 | uint32_t ilocalsym; | |
324 | uint32_t nlocalsym; | |
325 | uint32_t iextdefsym; | |
326 | uint32_t nextdefsym; | |
327 | uint32_t iundefsym; | |
328 | uint32_t nundefsym; | |
329 | uint32_t tocoff; | |
330 | uint32_t ntoc; | |
331 | uint32_t modtaboff; | |
332 | uint32_t nmodtab; | |
333 | uint32_t extrefsymoff; | |
334 | uint32_t nextrefsyms; | |
335 | uint32_t indirectsymoff; | |
336 | uint32_t nindirectsyms; | |
337 | uint32_t extreloff; | |
338 | uint32_t nextrel; | |
339 | uint32_t locreloff; | |
340 | uint32_t nlocrel; | |
341 | } _packed; | |
342 | ||
343 | struct dylib_table_of_contents { | |
344 | uint32_t symbol_index; | |
345 | uint32_t module_index; | |
346 | } _packed; | |
347 | ||
348 | struct dylib_module { | |
349 | uint32_t module_name; | |
350 | uint32_t iextdefsym; | |
351 | uint32_t nextdefsym; | |
352 | uint32_t irefsym; | |
353 | uint32_t nrefsym; | |
354 | uint32_t ilocalsym; | |
355 | uint32_t nlocalsym; | |
356 | uint32_t iextrel; | |
357 | uint32_t nextrel; | |
358 | uint32_t iinit_iterm; | |
359 | uint32_t ninit_nterm; | |
360 | uint32_t objc_module_info_addr; | |
361 | uint32_t objc_module_info_size; | |
362 | } _packed; | |
363 | ||
364 | struct dylib_reference { | |
365 | uint32_t isym:24; | |
366 | uint32_t flags:8; | |
367 | } _packed; | |
368 | ||
369 | struct relocation_info { | |
370 | int32_t r_address; | |
371 | uint32_t r_symbolnum:24; | |
372 | uint32_t r_pcrel:1; | |
373 | uint32_t r_length:2; | |
374 | uint32_t r_extern:1; | |
375 | uint32_t r_type:4; | |
376 | } _packed; | |
377 | ||
378 | struct nlist { | |
379 | union { | |
380 | char *n_name; | |
381 | int32_t n_strx; | |
382 | } n_un; | |
383 | ||
384 | uint8_t n_type; | |
385 | uint8_t n_sect; | |
386 | uint8_t n_desc; | |
387 | uint32_t n_value; | |
388 | } _packed; | |
389 | ||
390 | struct segment_command { | |
391 | uint32_t cmd; | |
392 | uint32_t cmdsize; | |
393 | char segname[16]; | |
394 | uint32_t vmaddr; | |
395 | uint32_t vmsize; | |
396 | uint32_t fileoff; | |
397 | uint32_t filesize; | |
398 | uint32_t maxprot; | |
399 | uint32_t initprot; | |
400 | uint32_t nsects; | |
401 | uint32_t flags; | |
402 | } _packed; | |
403 | ||
404 | struct segment_command_64 { | |
405 | uint32_t cmd; | |
406 | uint32_t cmdsize; | |
407 | char segname[16]; | |
408 | uint64_t vmaddr; | |
409 | uint64_t vmsize; | |
410 | uint64_t fileoff; | |
411 | uint64_t filesize; | |
412 | uint32_t maxprot; | |
413 | uint32_t initprot; | |
414 | uint32_t nsects; | |
415 | uint32_t flags; | |
416 | } _packed; | |
417 | ||
418 | struct section { | |
419 | char sectname[16]; | |
420 | char segname[16]; | |
421 | uint32_t addr; | |
422 | uint32_t size; | |
423 | uint32_t offset; | |
424 | uint32_t align; | |
425 | uint32_t reloff; | |
426 | uint32_t nreloc; | |
427 | uint32_t flags; | |
428 | uint32_t reserved1; | |
429 | uint32_t reserved2; | |
430 | } _packed; | |
431 | ||
432 | struct section_64 { | |
433 | char sectname[16]; | |
434 | char segname[16]; | |
435 | uint64_t addr; | |
436 | uint64_t size; | |
437 | uint32_t offset; | |
438 | uint32_t align; | |
439 | uint32_t reloff; | |
440 | uint32_t nreloc; | |
441 | uint32_t flags; | |
442 | uint32_t reserved1; | |
443 | uint32_t reserved2; | |
444 | uint32_t reserved3; | |
445 | } _packed; | |
446 | ||
447 | struct linkedit_data_command { | |
448 | uint32_t cmd; | |
449 | uint32_t cmdsize; | |
450 | uint32_t dataoff; | |
451 | uint32_t datasize; | |
452 | } _packed; | |
453 | ||
454 | struct encryption_info_command { | |
455 | uint32_t cmd; | |
456 | uint32_t cmdsize; | |
457 | uint32_t cryptoff; | |
458 | uint32_t cryptsize; | |
459 | uint32_t cryptid; | |
460 | } _packed; | |
461 | ||
462 | #define BIND_OPCODE_MASK 0xf0 | |
463 | #define BIND_IMMEDIATE_MASK 0x0f | |
464 | #define BIND_OPCODE_DONE 0x00 | |
465 | #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10 | |
466 | #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20 | |
467 | #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30 | |
468 | #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40 | |
469 | #define BIND_OPCODE_SET_TYPE_IMM 0x50 | |
470 | #define BIND_OPCODE_SET_ADDEND_SLEB 0x60 | |
471 | #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70 | |
472 | #define BIND_OPCODE_ADD_ADDR_ULEB 0x80 | |
473 | #define BIND_OPCODE_DO_BIND 0x90 | |
474 | #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xa0 | |
475 | #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xb0 | |
476 | #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xc0 | |
477 | ||
478 | static std::streamsize read(std::streambuf &stream, void *data, size_t size) { | |
479 | auto writ(stream.sgetn(static_cast<char *>(data), size)); | |
480 | _assert(writ >= 0); | |
481 | return writ; | |
482 | } | |
483 | ||
484 | static inline void get(std::streambuf &stream, void *data, size_t size) { | |
485 | _assert(read(stream, data, size) == size); | |
486 | } | |
487 | ||
488 | static inline void put(std::streambuf &stream, const void *data, size_t size) { | |
489 | _assert(stream.sputn(static_cast<const char *>(data), size) == size); | |
490 | } | |
491 | ||
492 | static size_t most(std::streambuf &stream, void *data, size_t size) { | |
493 | size_t total(size); | |
494 | while (size > 0) | |
495 | if (auto writ = read(stream, data, size)) | |
496 | size -= writ; | |
497 | else break; | |
498 | return total - size; | |
499 | } | |
500 | ||
501 | static inline void pad(std::streambuf &stream, size_t size) { | |
502 | char padding[size]; | |
503 | memset(padding, 0, size); | |
504 | put(stream, padding, size); | |
505 | } | |
506 | ||
507 | template <typename Type_> | |
508 | Type_ Align(Type_ value, size_t align) { | |
509 | value += align - 1; | |
510 | value /= align; | |
511 | value *= align; | |
512 | return value; | |
513 | } | |
514 | ||
515 | static const uint8_t PageShift_(0x0c); | |
516 | static const uint32_t PageSize_(1 << PageShift_); | |
517 | ||
518 | static inline uint16_t Swap_(uint16_t value) { | |
519 | return | |
520 | ((value >> 8) & 0x00ff) | | |
521 | ((value << 8) & 0xff00); | |
522 | } | |
523 | ||
524 | static inline uint32_t Swap_(uint32_t value) { | |
525 | value = ((value >> 8) & 0x00ff00ff) | | |
526 | ((value << 8) & 0xff00ff00); | |
527 | value = ((value >> 16) & 0x0000ffff) | | |
528 | ((value << 16) & 0xffff0000); | |
529 | return value; | |
530 | } | |
531 | ||
532 | static inline uint64_t Swap_(uint64_t value) { | |
533 | value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32; | |
534 | value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16; | |
535 | value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8; | |
536 | return value; | |
537 | } | |
538 | ||
539 | static inline int16_t Swap_(int16_t value) { | |
540 | return Swap_(static_cast<uint16_t>(value)); | |
541 | } | |
542 | ||
543 | static inline int32_t Swap_(int32_t value) { | |
544 | return Swap_(static_cast<uint32_t>(value)); | |
545 | } | |
546 | ||
547 | static inline int64_t Swap_(int64_t value) { | |
548 | return Swap_(static_cast<uint64_t>(value)); | |
549 | } | |
550 | ||
551 | static bool little_(true); | |
552 | ||
553 | static inline uint16_t Swap(uint16_t value) { | |
554 | return little_ ? Swap_(value) : value; | |
555 | } | |
556 | ||
557 | static inline uint32_t Swap(uint32_t value) { | |
558 | return little_ ? Swap_(value) : value; | |
559 | } | |
560 | ||
561 | static inline uint64_t Swap(uint64_t value) { | |
562 | return little_ ? Swap_(value) : value; | |
563 | } | |
564 | ||
565 | static inline int16_t Swap(int16_t value) { | |
566 | return Swap(static_cast<uint16_t>(value)); | |
567 | } | |
568 | ||
569 | static inline int32_t Swap(int32_t value) { | |
570 | return Swap(static_cast<uint32_t>(value)); | |
571 | } | |
572 | ||
573 | static inline int64_t Swap(int64_t value) { | |
574 | return Swap(static_cast<uint64_t>(value)); | |
575 | } | |
576 | ||
577 | class Swapped { | |
578 | protected: | |
579 | bool swapped_; | |
580 | ||
581 | Swapped() : | |
582 | swapped_(false) | |
583 | { | |
584 | } | |
585 | ||
586 | public: | |
587 | Swapped(bool swapped) : | |
588 | swapped_(swapped) | |
589 | { | |
590 | } | |
591 | ||
592 | template <typename Type_> | |
593 | Type_ Swap(Type_ value) const { | |
594 | return swapped_ ? Swap_(value) : value; | |
595 | } | |
596 | }; | |
597 | ||
598 | class Data : | |
599 | public Swapped | |
600 | { | |
601 | private: | |
602 | void *base_; | |
603 | size_t size_; | |
604 | ||
605 | public: | |
606 | Data(void *base, size_t size) : | |
607 | base_(base), | |
608 | size_(size) | |
609 | { | |
610 | } | |
611 | ||
612 | void *GetBase() const { | |
613 | return base_; | |
614 | } | |
615 | ||
616 | size_t GetSize() const { | |
617 | return size_; | |
618 | } | |
619 | }; | |
620 | ||
621 | class MachHeader : | |
622 | public Data | |
623 | { | |
624 | private: | |
625 | bool bits64_; | |
626 | ||
627 | struct mach_header *mach_header_; | |
628 | struct load_command *load_command_; | |
629 | ||
630 | public: | |
631 | MachHeader(void *base, size_t size) : | |
632 | Data(base, size) | |
633 | { | |
634 | mach_header_ = (mach_header *) base; | |
635 | ||
636 | switch (Swap(mach_header_->magic)) { | |
637 | case MH_CIGAM: | |
638 | swapped_ = !swapped_; | |
639 | case MH_MAGIC: | |
640 | bits64_ = false; | |
641 | break; | |
642 | ||
643 | case MH_CIGAM_64: | |
644 | swapped_ = !swapped_; | |
645 | case MH_MAGIC_64: | |
646 | bits64_ = true; | |
647 | break; | |
648 | ||
649 | default: | |
650 | _assert(false); | |
651 | } | |
652 | ||
653 | void *post = mach_header_ + 1; | |
654 | if (bits64_) | |
655 | post = (uint32_t *) post + 1; | |
656 | load_command_ = (struct load_command *) post; | |
657 | ||
658 | _assert( | |
659 | Swap(mach_header_->filetype) == MH_EXECUTE || | |
660 | Swap(mach_header_->filetype) == MH_DYLIB || | |
661 | Swap(mach_header_->filetype) == MH_BUNDLE | |
662 | ); | |
663 | } | |
664 | ||
665 | bool Bits64() const { | |
666 | return bits64_; | |
667 | } | |
668 | ||
669 | struct mach_header *operator ->() const { | |
670 | return mach_header_; | |
671 | } | |
672 | ||
673 | operator struct mach_header *() const { | |
674 | return mach_header_; | |
675 | } | |
676 | ||
677 | uint32_t GetCPUType() const { | |
678 | return Swap(mach_header_->cputype); | |
679 | } | |
680 | ||
681 | uint32_t GetCPUSubtype() const { | |
682 | return Swap(mach_header_->cpusubtype) & 0xff; | |
683 | } | |
684 | ||
685 | struct load_command *GetLoadCommand() const { | |
686 | return load_command_; | |
687 | } | |
688 | ||
689 | std::vector<struct load_command *> GetLoadCommands() const { | |
690 | std::vector<struct load_command *> load_commands; | |
691 | ||
692 | struct load_command *load_command = load_command_; | |
693 | for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) { | |
694 | load_commands.push_back(load_command); | |
695 | load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize)); | |
696 | } | |
697 | ||
698 | return load_commands; | |
699 | } | |
700 | ||
701 | void ForSection(const ldid::Functor<void (const char *, const char *, void *, size_t)> &code) const { | |
702 | _foreach (load_command, GetLoadCommands()) | |
703 | switch (Swap(load_command->cmd)) { | |
704 | case LC_SEGMENT: { | |
705 | auto segment(reinterpret_cast<struct segment_command *>(load_command)); | |
706 | code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize); | |
707 | auto section(reinterpret_cast<struct section *>(segment + 1)); | |
708 | for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section) | |
709 | code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size); | |
710 | } break; | |
711 | ||
712 | case LC_SEGMENT_64: { | |
713 | auto segment(reinterpret_cast<struct segment_command_64 *>(load_command)); | |
714 | code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize); | |
715 | auto section(reinterpret_cast<struct section_64 *>(segment + 1)); | |
716 | for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section) | |
717 | code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size); | |
718 | } break; | |
719 | } | |
720 | } | |
721 | ||
722 | template <typename Target_> | |
723 | Target_ *GetOffset(uint32_t offset) const { | |
724 | return reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_); | |
725 | } | |
726 | }; | |
727 | ||
728 | class FatMachHeader : | |
729 | public MachHeader | |
730 | { | |
731 | private: | |
732 | fat_arch *fat_arch_; | |
733 | ||
734 | public: | |
735 | FatMachHeader(void *base, size_t size, fat_arch *fat_arch) : | |
736 | MachHeader(base, size), | |
737 | fat_arch_(fat_arch) | |
738 | { | |
739 | } | |
740 | ||
741 | fat_arch *GetFatArch() const { | |
742 | return fat_arch_; | |
743 | } | |
744 | }; | |
745 | ||
746 | class FatHeader : | |
747 | public Data | |
748 | { | |
749 | private: | |
750 | fat_header *fat_header_; | |
751 | std::vector<FatMachHeader> mach_headers_; | |
752 | ||
753 | public: | |
754 | FatHeader(void *base, size_t size) : | |
755 | Data(base, size) | |
756 | { | |
757 | fat_header_ = reinterpret_cast<struct fat_header *>(base); | |
758 | ||
759 | if (Swap(fat_header_->magic) == FAT_CIGAM) { | |
760 | swapped_ = !swapped_; | |
761 | goto fat; | |
762 | } else if (Swap(fat_header_->magic) != FAT_MAGIC) { | |
763 | fat_header_ = NULL; | |
764 | mach_headers_.push_back(FatMachHeader(base, size, NULL)); | |
765 | } else fat: { | |
766 | size_t fat_narch = Swap(fat_header_->nfat_arch); | |
767 | fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1); | |
768 | size_t arch; | |
769 | for (arch = 0; arch != fat_narch; ++arch) { | |
770 | uint32_t arch_offset = Swap(fat_arch->offset); | |
771 | uint32_t arch_size = Swap(fat_arch->size); | |
772 | mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch)); | |
773 | ++fat_arch; | |
774 | } | |
775 | } | |
776 | } | |
777 | ||
778 | std::vector<FatMachHeader> &GetMachHeaders() { | |
779 | return mach_headers_; | |
780 | } | |
781 | ||
782 | bool IsFat() const { | |
783 | return fat_header_ != NULL; | |
784 | } | |
785 | ||
786 | struct fat_header *operator ->() const { | |
787 | return fat_header_; | |
788 | } | |
789 | ||
790 | operator struct fat_header *() const { | |
791 | return fat_header_; | |
792 | } | |
793 | }; | |
794 | ||
795 | #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00) | |
796 | #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01) | |
797 | #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02) | |
798 | #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0) | |
799 | #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02) | |
800 | #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171) | |
801 | #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1) | |
802 | #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01) | |
803 | ||
804 | #define CSSLOT_CODEDIRECTORY uint32_t(0x00000) | |
805 | #define CSSLOT_INFOSLOT uint32_t(0x00001) | |
806 | #define CSSLOT_REQUIREMENTS uint32_t(0x00002) | |
807 | #define CSSLOT_RESOURCEDIR uint32_t(0x00003) | |
808 | #define CSSLOT_APPLICATION uint32_t(0x00004) | |
809 | #define CSSLOT_ENTITLEMENTS uint32_t(0x00005) | |
810 | ||
811 | #define CSSLOT_SIGNATURESLOT uint32_t(0x10000) | |
812 | ||
813 | #define CS_HASHTYPE_SHA1 1 | |
814 | ||
815 | struct BlobIndex { | |
816 | uint32_t type; | |
817 | uint32_t offset; | |
818 | } _packed; | |
819 | ||
820 | struct Blob { | |
821 | uint32_t magic; | |
822 | uint32_t length; | |
823 | } _packed; | |
824 | ||
825 | struct SuperBlob { | |
826 | struct Blob blob; | |
827 | uint32_t count; | |
828 | struct BlobIndex index[]; | |
829 | } _packed; | |
830 | ||
831 | struct CodeDirectory { | |
832 | uint32_t version; | |
833 | uint32_t flags; | |
834 | uint32_t hashOffset; | |
835 | uint32_t identOffset; | |
836 | uint32_t nSpecialSlots; | |
837 | uint32_t nCodeSlots; | |
838 | uint32_t codeLimit; | |
839 | uint8_t hashSize; | |
840 | uint8_t hashType; | |
841 | uint8_t spare1; | |
842 | uint8_t pageSize; | |
843 | uint32_t spare2; | |
844 | uint32_t scatterOffset; | |
845 | uint32_t teamIDOffset; | |
846 | uint32_t spare3; | |
847 | uint64_t codeLimit64; | |
848 | } _packed; | |
849 | ||
850 | #ifndef LDID_NOFLAGT | |
851 | extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval); | |
852 | #endif | |
853 | ||
854 | static void sha1(uint8_t *hash, const void *data, size_t size) { | |
855 | LDID_SHA1(static_cast<const uint8_t *>(data), size, hash); | |
856 | } | |
857 | ||
858 | static void sha1(std::vector<char> &hash, const void *data, size_t size) { | |
859 | hash.resize(LDID_SHA1_DIGEST_LENGTH); | |
860 | sha1(reinterpret_cast<uint8_t *>(hash.data()), data, size); | |
861 | } | |
862 | ||
863 | struct CodesignAllocation { | |
864 | FatMachHeader mach_header_; | |
865 | uint32_t offset_; | |
866 | uint32_t size_; | |
867 | uint32_t limit_; | |
868 | uint32_t alloc_; | |
869 | uint32_t align_; | |
870 | ||
871 | CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) : | |
872 | mach_header_(mach_header), | |
873 | offset_(offset), | |
874 | size_(size), | |
875 | limit_(limit), | |
876 | alloc_(alloc), | |
877 | align_(align) | |
878 | { | |
879 | } | |
880 | }; | |
881 | ||
882 | #ifndef LDID_NOTOOLS | |
883 | class File { | |
884 | private: | |
885 | int file_; | |
886 | ||
887 | public: | |
888 | File() : | |
889 | file_(-1) | |
890 | { | |
891 | } | |
892 | ||
893 | ~File() { | |
894 | if (file_ != -1) | |
895 | _syscall(close(file_)); | |
896 | } | |
897 | ||
898 | void open(const char *path, int flags) { | |
899 | _assert(file_ == -1); | |
900 | file_ = _syscall(::open(path, flags)); | |
901 | } | |
902 | ||
903 | int file() const { | |
904 | return file_; | |
905 | } | |
906 | }; | |
907 | ||
908 | class Map { | |
909 | private: | |
910 | File file_; | |
911 | void *data_; | |
912 | size_t size_; | |
913 | ||
914 | void clear() { | |
915 | if (data_ == NULL) | |
916 | return; | |
917 | _syscall(munmap(data_, size_)); | |
918 | data_ = NULL; | |
919 | size_ = 0; | |
920 | } | |
921 | ||
922 | public: | |
923 | Map() : | |
924 | data_(NULL), | |
925 | size_(0) | |
926 | { | |
927 | } | |
928 | ||
929 | Map(const std::string &path, int oflag, int pflag, int mflag) : | |
930 | Map() | |
931 | { | |
932 | open(path, oflag, pflag, mflag); | |
933 | } | |
934 | ||
935 | Map(const std::string &path, bool edit) : | |
936 | Map() | |
937 | { | |
938 | open(path, edit); | |
939 | } | |
940 | ||
941 | ~Map() { | |
942 | clear(); | |
943 | } | |
944 | ||
945 | bool empty() const { | |
946 | return data_ == NULL; | |
947 | } | |
948 | ||
949 | void open(const std::string &path, int oflag, int pflag, int mflag) { | |
950 | clear(); | |
951 | ||
952 | file_.open(path.c_str(), oflag); | |
953 | int file(file_.file()); | |
954 | ||
955 | struct stat stat; | |
956 | _syscall(fstat(file, &stat)); | |
957 | size_ = stat.st_size; | |
958 | ||
959 | data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0)); | |
960 | } | |
961 | ||
962 | void open(const std::string &path, bool edit) { | |
963 | if (edit) | |
964 | open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED); | |
965 | else | |
966 | open(path, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
967 | } | |
968 | ||
969 | void *data() const { | |
970 | return data_; | |
971 | } | |
972 | ||
973 | size_t size() const { | |
974 | return size_; | |
975 | } | |
976 | ||
977 | operator std::string() const { | |
978 | return std::string(static_cast<char *>(data_), size_); | |
979 | } | |
980 | }; | |
981 | #endif | |
982 | ||
983 | namespace ldid { | |
984 | ||
985 | static void Allocate(const void *idata, size_t isize, std::streambuf &output, const Functor<size_t (const MachHeader &, size_t)> &allocate, const Functor<size_t (const MachHeader &, std::streambuf &output, size_t, const std::string &, const char *)> &save) { | |
986 | FatHeader source(const_cast<void *>(idata), isize); | |
987 | ||
988 | size_t offset(0); | |
989 | if (source.IsFat()) | |
990 | offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch); | |
991 | ||
992 | std::vector<CodesignAllocation> allocations; | |
993 | _foreach (mach_header, source.GetMachHeaders()) { | |
994 | struct linkedit_data_command *signature(NULL); | |
995 | struct symtab_command *symtab(NULL); | |
996 | ||
997 | _foreach (load_command, mach_header.GetLoadCommands()) { | |
998 | uint32_t cmd(mach_header.Swap(load_command->cmd)); | |
999 | if (false); | |
1000 | else if (cmd == LC_CODE_SIGNATURE) | |
1001 | signature = reinterpret_cast<struct linkedit_data_command *>(load_command); | |
1002 | else if (cmd == LC_SYMTAB) | |
1003 | symtab = reinterpret_cast<struct symtab_command *>(load_command); | |
1004 | } | |
1005 | ||
1006 | size_t size; | |
1007 | if (signature == NULL) | |
1008 | size = mach_header.GetSize(); | |
1009 | else { | |
1010 | size = mach_header.Swap(signature->dataoff); | |
1011 | _assert(size <= mach_header.GetSize()); | |
1012 | } | |
1013 | ||
1014 | if (symtab != NULL) { | |
1015 | auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize)); | |
1016 | _assert(end <= size); | |
1017 | _assert(end >= size - 0x10); | |
1018 | size = end; | |
1019 | } | |
1020 | ||
1021 | size_t alloc(allocate(mach_header, size)); | |
1022 | ||
1023 | auto *fat_arch(mach_header.GetFatArch()); | |
1024 | uint32_t align; | |
1025 | ||
1026 | if (fat_arch != NULL) | |
1027 | align = source.Swap(fat_arch->align); | |
1028 | else switch (mach_header.GetCPUType()) { | |
1029 | case CPU_TYPE_POWERPC: | |
1030 | case CPU_TYPE_POWERPC64: | |
1031 | case CPU_TYPE_X86: | |
1032 | case CPU_TYPE_X86_64: | |
1033 | align = 0xc; | |
1034 | break; | |
1035 | case CPU_TYPE_ARM: | |
1036 | case CPU_TYPE_ARM64: | |
1037 | align = 0xe; | |
1038 | break; | |
1039 | default: | |
1040 | align = 0x0; | |
1041 | break; | |
1042 | } | |
1043 | ||
1044 | offset = Align(offset, 1 << align); | |
1045 | ||
1046 | uint32_t limit(size); | |
1047 | if (alloc != 0) | |
1048 | limit = Align(limit, 0x10); | |
1049 | ||
1050 | allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align)); | |
1051 | offset += size + alloc; | |
1052 | offset = Align(offset, 0x10); | |
1053 | } | |
1054 | ||
1055 | size_t position(0); | |
1056 | ||
1057 | if (source.IsFat()) { | |
1058 | fat_header fat_header; | |
1059 | fat_header.magic = Swap(FAT_MAGIC); | |
1060 | fat_header.nfat_arch = Swap(uint32_t(allocations.size())); | |
1061 | put(output, &fat_header, sizeof(fat_header)); | |
1062 | position += sizeof(fat_header); | |
1063 | ||
1064 | _foreach (allocation, allocations) { | |
1065 | auto &mach_header(allocation.mach_header_); | |
1066 | ||
1067 | fat_arch fat_arch; | |
1068 | fat_arch.cputype = Swap(mach_header->cputype); | |
1069 | fat_arch.cpusubtype = Swap(mach_header->cpusubtype); | |
1070 | fat_arch.offset = Swap(allocation.offset_); | |
1071 | fat_arch.size = Swap(allocation.limit_ + allocation.alloc_); | |
1072 | fat_arch.align = Swap(allocation.align_); | |
1073 | put(output, &fat_arch, sizeof(fat_arch)); | |
1074 | position += sizeof(fat_arch); | |
1075 | } | |
1076 | } | |
1077 | ||
1078 | _foreach (allocation, allocations) { | |
1079 | auto &mach_header(allocation.mach_header_); | |
1080 | ||
1081 | pad(output, allocation.offset_ - position); | |
1082 | position = allocation.offset_; | |
1083 | ||
1084 | std::vector<std::string> commands; | |
1085 | ||
1086 | _foreach (load_command, mach_header.GetLoadCommands()) { | |
1087 | std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize); | |
1088 | ||
1089 | switch (mach_header.Swap(load_command->cmd)) { | |
1090 | case LC_CODE_SIGNATURE: | |
1091 | continue; | |
1092 | break; | |
1093 | ||
1094 | case LC_SEGMENT: { | |
1095 | auto segment_command(reinterpret_cast<struct segment_command *>(©[0])); | |
1096 | if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0) | |
1097 | break; | |
1098 | size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff))); | |
1099 | segment_command->filesize = size; | |
1100 | segment_command->vmsize = Align(size, 1 << allocation.align_); | |
1101 | } break; | |
1102 | ||
1103 | case LC_SEGMENT_64: { | |
1104 | auto segment_command(reinterpret_cast<struct segment_command_64 *>(©[0])); | |
1105 | if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0) | |
1106 | break; | |
1107 | size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff))); | |
1108 | segment_command->filesize = size; | |
1109 | segment_command->vmsize = Align(size, 1 << allocation.align_); | |
1110 | } break; | |
1111 | } | |
1112 | ||
1113 | commands.push_back(copy); | |
1114 | } | |
1115 | ||
1116 | if (allocation.alloc_ != 0) { | |
1117 | linkedit_data_command signature; | |
1118 | signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE); | |
1119 | signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature))); | |
1120 | signature.dataoff = mach_header.Swap(allocation.limit_); | |
1121 | signature.datasize = mach_header.Swap(allocation.alloc_); | |
1122 | commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature))); | |
1123 | } | |
1124 | ||
1125 | size_t begin(position); | |
1126 | ||
1127 | uint32_t after(0); | |
1128 | _foreach(command, commands) | |
1129 | after += command.size(); | |
1130 | ||
1131 | std::stringbuf altern; | |
1132 | ||
1133 | struct mach_header header(*mach_header); | |
1134 | header.ncmds = mach_header.Swap(uint32_t(commands.size())); | |
1135 | header.sizeofcmds = mach_header.Swap(after); | |
1136 | put(output, &header, sizeof(header)); | |
1137 | put(altern, &header, sizeof(header)); | |
1138 | position += sizeof(header); | |
1139 | ||
1140 | if (mach_header.Bits64()) { | |
1141 | auto pad(mach_header.Swap(uint32_t(0))); | |
1142 | put(output, &pad, sizeof(pad)); | |
1143 | put(altern, &pad, sizeof(pad)); | |
1144 | position += sizeof(pad); | |
1145 | } | |
1146 | ||
1147 | _foreach(command, commands) { | |
1148 | put(output, command.data(), command.size()); | |
1149 | put(altern, command.data(), command.size()); | |
1150 | position += command.size(); | |
1151 | } | |
1152 | ||
1153 | uint32_t before(mach_header.Swap(mach_header->sizeofcmds)); | |
1154 | if (before > after) { | |
1155 | pad(output, before - after); | |
1156 | pad(altern, before - after); | |
1157 | position += before - after; | |
1158 | } | |
1159 | ||
1160 | auto top(reinterpret_cast<char *>(mach_header.GetBase())); | |
1161 | ||
1162 | std::string overlap(altern.str()); | |
1163 | overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size()); | |
1164 | ||
1165 | put(output, top + (position - begin), allocation.size_ - (position - begin)); | |
1166 | position = begin + allocation.size_; | |
1167 | ||
1168 | pad(output, allocation.limit_ - allocation.size_); | |
1169 | position += allocation.limit_ - allocation.size_; | |
1170 | ||
1171 | size_t saved(save(mach_header, output, allocation.limit_, overlap, top)); | |
1172 | if (allocation.alloc_ > saved) | |
1173 | pad(output, allocation.alloc_ - saved); | |
1174 | position += allocation.alloc_; | |
1175 | } | |
1176 | } | |
1177 | ||
1178 | } | |
1179 | ||
1180 | typedef std::map<uint32_t, std::string> Blobs; | |
1181 | ||
1182 | static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) { | |
1183 | auto value(buffer.str()); | |
1184 | std::swap(blobs[slot], value); | |
1185 | } | |
1186 | ||
1187 | static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) { | |
1188 | auto value(buffer.str()); | |
1189 | Blob blob; | |
1190 | blob.magic = Swap(magic); | |
1191 | blob.length = Swap(uint32_t(sizeof(blob) + value.size())); | |
1192 | value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob)); | |
1193 | std::swap(blobs[slot], value); | |
1194 | } | |
1195 | ||
1196 | static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) { | |
1197 | size_t total(0); | |
1198 | _foreach (blob, blobs) | |
1199 | total += blob.second.size(); | |
1200 | ||
1201 | struct SuperBlob super; | |
1202 | super.blob.magic = Swap(magic); | |
1203 | super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total)); | |
1204 | super.count = Swap(uint32_t(blobs.size())); | |
1205 | put(output, &super, sizeof(super)); | |
1206 | ||
1207 | size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size()); | |
1208 | ||
1209 | _foreach (blob, blobs) { | |
1210 | BlobIndex index; | |
1211 | index.type = Swap(blob.first); | |
1212 | index.offset = Swap(uint32_t(offset)); | |
1213 | put(output, &index, sizeof(index)); | |
1214 | offset += blob.second.size(); | |
1215 | } | |
1216 | ||
1217 | _foreach (blob, blobs) | |
1218 | put(output, blob.second.data(), blob.second.size()); | |
1219 | ||
1220 | return offset; | |
1221 | } | |
1222 | ||
1223 | #ifndef LDID_NOSMIME | |
1224 | class Buffer { | |
1225 | private: | |
1226 | BIO *bio_; | |
1227 | ||
1228 | public: | |
1229 | Buffer(BIO *bio) : | |
1230 | bio_(bio) | |
1231 | { | |
1232 | _assert(bio_ != NULL); | |
1233 | } | |
1234 | ||
1235 | Buffer() : | |
1236 | bio_(BIO_new(BIO_s_mem())) | |
1237 | { | |
1238 | } | |
1239 | ||
1240 | Buffer(const char *data, size_t size) : | |
1241 | Buffer(BIO_new_mem_buf(const_cast<char *>(data), size)) | |
1242 | { | |
1243 | } | |
1244 | ||
1245 | Buffer(const std::string &data) : | |
1246 | Buffer(data.data(), data.size()) | |
1247 | { | |
1248 | } | |
1249 | ||
1250 | Buffer(PKCS7 *pkcs) : | |
1251 | Buffer() | |
1252 | { | |
1253 | _assert(i2d_PKCS7_bio(bio_, pkcs) != 0); | |
1254 | } | |
1255 | ||
1256 | ~Buffer() { | |
1257 | BIO_free_all(bio_); | |
1258 | } | |
1259 | ||
1260 | operator BIO *() const { | |
1261 | return bio_; | |
1262 | } | |
1263 | ||
1264 | explicit operator std::string() const { | |
1265 | char *data; | |
1266 | auto size(BIO_get_mem_data(bio_, &data)); | |
1267 | return std::string(data, size); | |
1268 | } | |
1269 | }; | |
1270 | ||
1271 | class Stuff { | |
1272 | private: | |
1273 | PKCS12 *value_; | |
1274 | EVP_PKEY *key_; | |
1275 | X509 *cert_; | |
1276 | STACK_OF(X509) *ca_; | |
1277 | ||
1278 | public: | |
1279 | Stuff(BIO *bio) : | |
1280 | value_(d2i_PKCS12_bio(bio, NULL)), | |
1281 | ca_(NULL) | |
1282 | { | |
1283 | _assert(value_ != NULL); | |
1284 | _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0); | |
1285 | _assert(key_ != NULL); | |
1286 | _assert(cert_ != NULL); | |
1287 | } | |
1288 | ||
1289 | Stuff(const std::string &data) : | |
1290 | Stuff(Buffer(data)) | |
1291 | { | |
1292 | } | |
1293 | ||
1294 | ~Stuff() { | |
1295 | sk_X509_pop_free(ca_, X509_free); | |
1296 | X509_free(cert_); | |
1297 | EVP_PKEY_free(key_); | |
1298 | PKCS12_free(value_); | |
1299 | } | |
1300 | ||
1301 | operator PKCS12 *() const { | |
1302 | return value_; | |
1303 | } | |
1304 | ||
1305 | operator EVP_PKEY *() const { | |
1306 | return key_; | |
1307 | } | |
1308 | ||
1309 | operator X509 *() const { | |
1310 | return cert_; | |
1311 | } | |
1312 | ||
1313 | operator STACK_OF(X509) *() const { | |
1314 | return ca_; | |
1315 | } | |
1316 | }; | |
1317 | ||
1318 | class Signature { | |
1319 | private: | |
1320 | PKCS7 *value_; | |
1321 | ||
1322 | public: | |
1323 | Signature(const Stuff &stuff, const Buffer &data) : | |
1324 | value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED)) | |
1325 | { | |
1326 | _assert(value_ != NULL); | |
1327 | } | |
1328 | ||
1329 | ~Signature() { | |
1330 | PKCS7_free(value_); | |
1331 | } | |
1332 | ||
1333 | operator PKCS7 *() const { | |
1334 | return value_; | |
1335 | } | |
1336 | }; | |
1337 | #endif | |
1338 | ||
1339 | class NullBuffer : | |
1340 | public std::streambuf | |
1341 | { | |
1342 | public: | |
1343 | virtual std::streamsize xsputn(const char_type *data, std::streamsize size) { | |
1344 | return size; | |
1345 | } | |
1346 | ||
1347 | virtual int_type overflow(int_type next) { | |
1348 | return next; | |
1349 | } | |
1350 | }; | |
1351 | ||
1352 | class Hash { | |
1353 | public: | |
1354 | bool ready_; | |
1355 | char sha1_[LDID_SHA1_DIGEST_LENGTH]; | |
1356 | char sha256_[LDID_SHA256_DIGEST_LENGTH]; | |
1357 | ||
1358 | Hash() : | |
1359 | ready_(false) | |
1360 | { | |
1361 | } | |
1362 | ||
1363 | operator std::vector<char>() const { | |
1364 | return {sha1_, sha1_ + sizeof(sha1_)}; | |
1365 | } | |
1366 | }; | |
1367 | ||
1368 | class HashBuffer : | |
1369 | public std::streambuf | |
1370 | { | |
1371 | private: | |
1372 | Hash &hash_; | |
1373 | ||
1374 | LDID_SHA1_CTX sha1_; | |
1375 | LDID_SHA256_CTX sha256_; | |
1376 | ||
1377 | public: | |
1378 | HashBuffer(Hash &hash) : | |
1379 | hash_(hash) | |
1380 | { | |
1381 | LDID_SHA1_Init(&sha1_); | |
1382 | LDID_SHA256_Init(&sha256_); | |
1383 | } | |
1384 | ||
1385 | ~HashBuffer() { | |
1386 | LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.sha1_), &sha1_); | |
1387 | LDID_SHA256_Final(reinterpret_cast<uint8_t *>(hash_.sha256_), &sha256_); | |
1388 | hash_.ready_ = true; | |
1389 | } | |
1390 | ||
1391 | virtual std::streamsize xsputn(const char_type *data, std::streamsize size) { | |
1392 | LDID_SHA1_Update(&sha1_, data, size); | |
1393 | LDID_SHA256_Update(&sha256_, data, size); | |
1394 | return size; | |
1395 | } | |
1396 | ||
1397 | virtual int_type overflow(int_type next) { | |
1398 | if (next == traits_type::eof()) | |
1399 | return sync(); | |
1400 | char value(next); | |
1401 | xsputn(&value, 1); | |
1402 | return next; | |
1403 | } | |
1404 | }; | |
1405 | ||
1406 | class HashProxy : | |
1407 | public HashBuffer | |
1408 | { | |
1409 | private: | |
1410 | std::streambuf &buffer_; | |
1411 | ||
1412 | public: | |
1413 | HashProxy(Hash &hash, std::streambuf &buffer) : | |
1414 | HashBuffer(hash), | |
1415 | buffer_(buffer) | |
1416 | { | |
1417 | } | |
1418 | ||
1419 | virtual std::streamsize xsputn(const char_type *data, std::streamsize size) { | |
1420 | _assert(HashBuffer::xsputn(data, size) == size); | |
1421 | return buffer_.sputn(data, size); | |
1422 | } | |
1423 | }; | |
1424 | ||
1425 | #ifndef LDID_NOTOOLS | |
1426 | static bool Starts(const std::string &lhs, const std::string &rhs) { | |
1427 | return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0; | |
1428 | } | |
1429 | ||
1430 | class Split { | |
1431 | public: | |
1432 | std::string dir; | |
1433 | std::string base; | |
1434 | ||
1435 | Split(const std::string &path) { | |
1436 | size_t slash(path.rfind('/')); | |
1437 | if (slash == std::string::npos) | |
1438 | base = path; | |
1439 | else { | |
1440 | dir = path.substr(0, slash + 1); | |
1441 | base = path.substr(slash + 1); | |
1442 | } | |
1443 | } | |
1444 | }; | |
1445 | ||
1446 | static void mkdir_p(const std::string &path) { | |
1447 | if (path.empty()) | |
1448 | return; | |
1449 | #ifdef __WIN32__ | |
1450 | if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST) | |
1451 | return; | |
1452 | #else | |
1453 | if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST) | |
1454 | return; | |
1455 | #endif | |
1456 | auto slash(path.rfind('/', path.size() - 1)); | |
1457 | if (slash == std::string::npos) | |
1458 | return; | |
1459 | mkdir_p(path.substr(0, slash)); | |
1460 | } | |
1461 | ||
1462 | static std::string Temporary(std::filebuf &file, const Split &split) { | |
1463 | std::string temp(split.dir + ".ldid." + split.base); | |
1464 | mkdir_p(split.dir); | |
1465 | _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str()); | |
1466 | return temp; | |
1467 | } | |
1468 | ||
1469 | static void Commit(const std::string &path, const std::string &temp) { | |
1470 | struct stat info; | |
1471 | if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) { | |
1472 | #ifndef __WIN32__ | |
1473 | _syscall(chown(temp.c_str(), info.st_uid, info.st_gid)); | |
1474 | #endif | |
1475 | _syscall(chmod(temp.c_str(), info.st_mode)); | |
1476 | } | |
1477 | ||
1478 | _syscall(rename(temp.c_str(), path.c_str())); | |
1479 | } | |
1480 | #endif | |
1481 | ||
1482 | namespace ldid { | |
1483 | ||
1484 | void Sign(const void *idata, size_t isize, std::streambuf &output, const std::string &identifier, const std::string &entitlements, const std::string &requirement, const std::string &key, const Slots &slots) { | |
1485 | std::string team; | |
1486 | ||
1487 | #ifndef LDID_NOSMIME | |
1488 | if (!key.empty()) { | |
1489 | Stuff stuff(key); | |
1490 | auto name(X509_get_subject_name(stuff)); | |
1491 | _assert(name != NULL); | |
1492 | auto index(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, -1)); | |
1493 | _assert(index >= 0); | |
1494 | auto next(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, index)); | |
1495 | _assert(next == -1); | |
1496 | auto entry(X509_NAME_get_entry(name, index)); | |
1497 | _assert(entry != NULL); | |
1498 | auto asn(X509_NAME_ENTRY_get_data(entry)); | |
1499 | _assert(asn != NULL); | |
1500 | team.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn)), ASN1_STRING_length(asn)); | |
1501 | } | |
1502 | #endif | |
1503 | ||
1504 | Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, size_t size) -> size_t { | |
1505 | size_t alloc(sizeof(struct SuperBlob)); | |
1506 | ||
1507 | uint32_t special(0); | |
1508 | ||
1509 | special = std::max(special, CSSLOT_REQUIREMENTS); | |
1510 | alloc += sizeof(struct BlobIndex); | |
1511 | if (!requirement.empty()) | |
1512 | alloc += 0xc; | |
1513 | else | |
1514 | alloc += requirement.size(); | |
1515 | ||
1516 | if (!entitlements.empty()) { | |
1517 | special = std::max(special, CSSLOT_ENTITLEMENTS); | |
1518 | alloc += sizeof(struct BlobIndex); | |
1519 | alloc += sizeof(struct Blob); | |
1520 | alloc += entitlements.size(); | |
1521 | } | |
1522 | ||
1523 | special = std::max(special, CSSLOT_CODEDIRECTORY); | |
1524 | alloc += sizeof(struct BlobIndex); | |
1525 | alloc += sizeof(struct Blob); | |
1526 | alloc += sizeof(struct CodeDirectory); | |
1527 | alloc += identifier.size() + 1; | |
1528 | ||
1529 | if (!team.empty()) | |
1530 | alloc += team.size() + 1; | |
1531 | ||
1532 | if (!key.empty()) { | |
1533 | alloc += sizeof(struct BlobIndex); | |
1534 | alloc += sizeof(struct Blob); | |
1535 | // XXX: this is just a "sufficiently large number" | |
1536 | alloc += 0x3000; | |
1537 | } | |
1538 | ||
1539 | _foreach (slot, slots) | |
1540 | special = std::max(special, slot.first); | |
1541 | ||
1542 | mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) { | |
1543 | if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0) | |
1544 | special = std::max(special, CSSLOT_INFOSLOT); | |
1545 | })); | |
1546 | ||
1547 | uint32_t normal((size + PageSize_ - 1) / PageSize_); | |
1548 | alloc = Align(alloc + (special + normal) * LDID_SHA1_DIGEST_LENGTH, 16); | |
1549 | return alloc; | |
1550 | }), fun([&](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t { | |
1551 | Blobs blobs; | |
1552 | ||
1553 | if (true) { | |
1554 | std::stringbuf data; | |
1555 | ||
1556 | if (requirement.empty()) { | |
1557 | Blobs requirements; | |
1558 | put(data, CSMAGIC_REQUIREMENTS, requirements); | |
1559 | } else { | |
1560 | put(data, requirement.data(), requirement.size()); | |
1561 | } | |
1562 | ||
1563 | insert(blobs, CSSLOT_REQUIREMENTS, data); | |
1564 | } | |
1565 | ||
1566 | if (!entitlements.empty()) { | |
1567 | std::stringbuf data; | |
1568 | put(data, entitlements.data(), entitlements.size()); | |
1569 | insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data); | |
1570 | } | |
1571 | ||
1572 | if (true) { | |
1573 | std::stringbuf data; | |
1574 | ||
1575 | Slots posts(slots); | |
1576 | ||
1577 | mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) { | |
1578 | if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0) | |
1579 | sha1(posts[CSSLOT_INFOSLOT], data, size); | |
1580 | })); | |
1581 | ||
1582 | uint32_t special(0); | |
1583 | _foreach (blob, blobs) | |
1584 | special = std::max(special, blob.first); | |
1585 | _foreach (slot, posts) | |
1586 | special = std::max(special, slot.first); | |
1587 | uint32_t normal((limit + PageSize_ - 1) / PageSize_); | |
1588 | ||
1589 | CodeDirectory directory; | |
1590 | directory.version = Swap(uint32_t(0x00020200)); | |
1591 | directory.flags = Swap(uint32_t(0)); | |
1592 | directory.nSpecialSlots = Swap(special); | |
1593 | directory.codeLimit = Swap(uint32_t(limit)); | |
1594 | directory.nCodeSlots = Swap(normal); | |
1595 | directory.hashSize = LDID_SHA1_DIGEST_LENGTH; | |
1596 | directory.hashType = CS_HASHTYPE_SHA1; | |
1597 | directory.spare1 = 0x00; | |
1598 | directory.pageSize = PageShift_; | |
1599 | directory.spare2 = Swap(uint32_t(0)); | |
1600 | directory.scatterOffset = Swap(uint32_t(0)); | |
1601 | directory.spare3 = Swap(uint32_t(0)); | |
1602 | directory.codeLimit64 = Swap(uint64_t(0)); | |
1603 | ||
1604 | uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory)); | |
1605 | ||
1606 | directory.identOffset = Swap(uint32_t(offset)); | |
1607 | offset += identifier.size() + 1; | |
1608 | ||
1609 | if (team.empty()) | |
1610 | directory.teamIDOffset = Swap(uint32_t(0)); | |
1611 | else { | |
1612 | directory.teamIDOffset = Swap(uint32_t(offset)); | |
1613 | offset += team.size() + 1; | |
1614 | } | |
1615 | ||
1616 | offset += LDID_SHA1_DIGEST_LENGTH * special; | |
1617 | directory.hashOffset = Swap(uint32_t(offset)); | |
1618 | offset += LDID_SHA1_DIGEST_LENGTH * normal; | |
1619 | ||
1620 | put(data, &directory, sizeof(directory)); | |
1621 | ||
1622 | put(data, identifier.c_str(), identifier.size() + 1); | |
1623 | put(data, team.c_str(), team.size() + 1); | |
1624 | ||
1625 | uint8_t storage[special + normal][LDID_SHA1_DIGEST_LENGTH]; | |
1626 | uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = storage + special; | |
1627 | ||
1628 | memset(storage, 0, sizeof(*storage) * special); | |
1629 | ||
1630 | _foreach (blob, blobs) { | |
1631 | auto local(reinterpret_cast<const Blob *>(&blob.second[0])); | |
1632 | sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length)); | |
1633 | } | |
1634 | ||
1635 | _foreach (slot, posts) { | |
1636 | _assert(sizeof(*hashes) == slot.second.size()); | |
1637 | memcpy(hashes - slot.first, slot.second.data(), slot.second.size()); | |
1638 | } | |
1639 | ||
1640 | if (normal != 1) | |
1641 | for (size_t i = 0; i != normal - 1; ++i) | |
1642 | sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_); | |
1643 | if (normal != 0) | |
1644 | sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1); | |
1645 | ||
1646 | put(data, storage, sizeof(storage)); | |
1647 | ||
1648 | insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data); | |
1649 | } | |
1650 | ||
1651 | #ifndef LDID_NOSMIME | |
1652 | if (!key.empty()) { | |
1653 | std::stringbuf data; | |
1654 | const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]); | |
1655 | ||
1656 | Stuff stuff(key); | |
1657 | Buffer bio(sign); | |
1658 | ||
1659 | Signature signature(stuff, sign); | |
1660 | Buffer result(signature); | |
1661 | std::string value(result); | |
1662 | put(data, value.data(), value.size()); | |
1663 | ||
1664 | insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data); | |
1665 | } | |
1666 | #endif | |
1667 | ||
1668 | return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs); | |
1669 | })); | |
1670 | } | |
1671 | ||
1672 | #ifndef LDID_NOTOOLS | |
1673 | static void Unsign(void *idata, size_t isize, std::streambuf &output) { | |
1674 | Allocate(idata, isize, output, fun([](const MachHeader &mach_header, size_t size) -> size_t { | |
1675 | return 0; | |
1676 | }), fun([](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t { | |
1677 | return 0; | |
1678 | })); | |
1679 | } | |
1680 | ||
1681 | std::string DiskFolder::Path(const std::string &path) { | |
1682 | return path_ + "/" + path; | |
1683 | } | |
1684 | ||
1685 | DiskFolder::DiskFolder(const std::string &path) : | |
1686 | path_(path) | |
1687 | { | |
1688 | } | |
1689 | ||
1690 | DiskFolder::~DiskFolder() { | |
1691 | if (!std::uncaught_exception()) | |
1692 | for (const auto &commit : commit_) | |
1693 | Commit(commit.first, commit.second); | |
1694 | } | |
1695 | ||
1696 | void DiskFolder::Find(const std::string &root, const std::string &base, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) { | |
1697 | std::string path(Path(root) + base); | |
1698 | ||
1699 | DIR *dir(opendir(path.c_str())); | |
1700 | _assert(dir != NULL); | |
1701 | _scope({ _syscall(closedir(dir)); }); | |
1702 | ||
1703 | while (auto child = readdir(dir)) { | |
1704 | std::string name(child->d_name); | |
1705 | if (name == "." || name == "..") | |
1706 | continue; | |
1707 | if (Starts(name, ".ldid.")) | |
1708 | continue; | |
1709 | ||
1710 | bool directory; | |
1711 | ||
1712 | #ifdef __WIN32__ | |
1713 | struct stat info; | |
1714 | _syscall(stat((path + name).c_str(), &info)); | |
1715 | if (false); | |
1716 | else if (S_ISDIR(info.st_mode)) | |
1717 | directory = true; | |
1718 | else if (S_ISREG(info.st_mode)) | |
1719 | directory = false; | |
1720 | else | |
1721 | _assert_(false, "st_mode=%x", info.st_mode); | |
1722 | #else | |
1723 | switch (child->d_type) { | |
1724 | case DT_DIR: | |
1725 | directory = true; | |
1726 | break; | |
1727 | case DT_REG: | |
1728 | directory = false; | |
1729 | break; | |
1730 | default: | |
1731 | _assert_(false, "d_type=%u", child->d_type); | |
1732 | } | |
1733 | #endif | |
1734 | ||
1735 | if (directory) | |
1736 | Find(root, base + name + "/", code); | |
1737 | else | |
1738 | code(base + name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) { | |
1739 | std::string access(root + base + name); | |
1740 | _assert_(Open(access, fun([&](std::streambuf &data, const void *flag) { | |
1741 | auto from(path + name); | |
1742 | std::filebuf save; | |
1743 | commit_[from] = Temporary(save, from); | |
1744 | code(data, save); | |
1745 | })), "open(): %s", access.c_str()); | |
1746 | })); | |
1747 | } | |
1748 | } | |
1749 | ||
1750 | void DiskFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) { | |
1751 | std::filebuf save; | |
1752 | auto from(Path(path)); | |
1753 | commit_[from] = Temporary(save, from); | |
1754 | code(save); | |
1755 | } | |
1756 | ||
1757 | bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) { | |
1758 | std::filebuf data; | |
1759 | auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in)); | |
1760 | if (result == NULL) | |
1761 | return false; | |
1762 | _assert(result == &data); | |
1763 | code(data, NULL); | |
1764 | return true; | |
1765 | } | |
1766 | ||
1767 | void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) { | |
1768 | Find(path, "", code); | |
1769 | } | |
1770 | #endif | |
1771 | ||
1772 | SubFolder::SubFolder(Folder &parent, const std::string &path) : | |
1773 | parent_(parent), | |
1774 | path_(path) | |
1775 | { | |
1776 | } | |
1777 | ||
1778 | void SubFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) { | |
1779 | return parent_.Save(path_ + path, flag, code); | |
1780 | } | |
1781 | ||
1782 | bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) { | |
1783 | return parent_.Open(path_ + path, code); | |
1784 | } | |
1785 | ||
1786 | void SubFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) { | |
1787 | return parent_.Find(path_ + path, code); | |
1788 | } | |
1789 | ||
1790 | std::string UnionFolder::Map(const std::string &path) { | |
1791 | auto remap(remaps_.find(path)); | |
1792 | if (remap == remaps_.end()) | |
1793 | return path; | |
1794 | return remap->second; | |
1795 | } | |
1796 | ||
1797 | void UnionFolder::Map(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code, const std::string &file, const Functor<void (const Functor<void (std::streambuf &, const void *)> &)> &save) { | |
1798 | if (file.size() >= path.size() && file.substr(0, path.size()) == path) | |
1799 | code(file.substr(path.size()), fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) { | |
1800 | save(fun([&](std::streambuf &data, const void *flag) { | |
1801 | parent_.Save(file, flag, fun([&](std::streambuf &save) { | |
1802 | code(data, save); | |
1803 | })); | |
1804 | })); | |
1805 | })); | |
1806 | } | |
1807 | ||
1808 | UnionFolder::UnionFolder(Folder &parent) : | |
1809 | parent_(parent) | |
1810 | { | |
1811 | } | |
1812 | ||
1813 | void UnionFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) { | |
1814 | return parent_.Save(Map(path), flag, code); | |
1815 | } | |
1816 | ||
1817 | bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) { | |
1818 | auto file(resets_.find(path)); | |
1819 | if (file == resets_.end()) | |
1820 | return parent_.Open(Map(path), code); | |
1821 | auto &entry(file->second); | |
1822 | ||
1823 | auto &data(entry.first); | |
1824 | data.pubseekpos(0, std::ios::in); | |
1825 | code(data, entry.second); | |
1826 | return true; | |
1827 | } | |
1828 | ||
1829 | void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) { | |
1830 | parent_.Find(path, fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &save) { | |
1831 | if (deletes_.find(path + name) == deletes_.end()) | |
1832 | code(name, save); | |
1833 | })); | |
1834 | ||
1835 | for (auto &reset : resets_) | |
1836 | Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, const void *)> &code) { | |
1837 | auto &entry(reset.second); | |
1838 | entry.first.pubseekpos(0, std::ios::in); | |
1839 | code(entry.first, entry.second); | |
1840 | })); | |
1841 | ||
1842 | for (auto &remap : remaps_) | |
1843 | Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, const void *)> &code) { | |
1844 | parent_.Open(remap.second, fun([&](std::streambuf &data, const void *flag) { | |
1845 | code(data, flag); | |
1846 | })); | |
1847 | })); | |
1848 | } | |
1849 | ||
1850 | #ifndef LDID_NOTOOLS | |
1851 | static size_t copy(std::streambuf &source, std::streambuf &target) { | |
1852 | size_t total(0); | |
1853 | for (;;) { | |
1854 | char data[4096]; | |
1855 | size_t writ(source.sgetn(data, sizeof(data))); | |
1856 | if (writ == 0) | |
1857 | break; | |
1858 | _assert(target.sputn(data, writ) == writ); | |
1859 | total += writ; | |
1860 | } | |
1861 | return total; | |
1862 | } | |
1863 | ||
1864 | #ifndef LDID_NOPLIST | |
1865 | static plist_t plist(const std::string &data) { | |
1866 | plist_t plist(NULL); | |
1867 | if (Starts(data, "bplist00")) | |
1868 | plist_from_bin(data.data(), data.size(), &plist); | |
1869 | else | |
1870 | plist_from_xml(data.data(), data.size(), &plist); | |
1871 | _assert(plist != NULL); | |
1872 | return plist; | |
1873 | } | |
1874 | ||
1875 | static void plist_d(std::streambuf &buffer, const Functor<void (plist_t)> &code) { | |
1876 | std::stringbuf data; | |
1877 | copy(buffer, data); | |
1878 | auto node(plist(data.str())); | |
1879 | _scope({ plist_free(node); }); | |
1880 | _assert(plist_get_node_type(node) == PLIST_DICT); | |
1881 | code(node); | |
1882 | } | |
1883 | ||
1884 | static std::string plist_s(plist_t node) { | |
1885 | _assert(node != NULL); | |
1886 | _assert(plist_get_node_type(node) == PLIST_STRING); | |
1887 | char *data; | |
1888 | plist_get_string_val(node, &data); | |
1889 | _scope({ free(data); }); | |
1890 | return data; | |
1891 | } | |
1892 | #endif | |
1893 | ||
1894 | enum Mode { | |
1895 | NoMode, | |
1896 | OptionalMode, | |
1897 | OmitMode, | |
1898 | NestedMode, | |
1899 | TopMode, | |
1900 | }; | |
1901 | ||
1902 | class Expression { | |
1903 | private: | |
1904 | regex_t regex_; | |
1905 | ||
1906 | public: | |
1907 | Expression(const std::string &code) { | |
1908 | _assert_(regcomp(®ex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()"); | |
1909 | } | |
1910 | ||
1911 | ~Expression() { | |
1912 | regfree(®ex_); | |
1913 | } | |
1914 | ||
1915 | bool operator ()(const std::string &data) const { | |
1916 | auto value(regexec(®ex_, data.c_str(), 0, NULL, 0)); | |
1917 | if (value == REG_NOMATCH) | |
1918 | return false; | |
1919 | _assert_(value == 0, "regexec()"); | |
1920 | return true; | |
1921 | } | |
1922 | }; | |
1923 | ||
1924 | struct Rule { | |
1925 | unsigned weight_; | |
1926 | Mode mode_; | |
1927 | std::string code_; | |
1928 | ||
1929 | mutable std::auto_ptr<Expression> regex_; | |
1930 | ||
1931 | Rule(unsigned weight, Mode mode, const std::string &code) : | |
1932 | weight_(weight), | |
1933 | mode_(mode), | |
1934 | code_(code) | |
1935 | { | |
1936 | } | |
1937 | ||
1938 | Rule(const Rule &rhs) : | |
1939 | weight_(rhs.weight_), | |
1940 | mode_(rhs.mode_), | |
1941 | code_(rhs.code_) | |
1942 | { | |
1943 | } | |
1944 | ||
1945 | void Compile() const { | |
1946 | regex_.reset(new Expression(code_)); | |
1947 | } | |
1948 | ||
1949 | bool operator ()(const std::string &data) const { | |
1950 | _assert(regex_.get() != NULL); | |
1951 | return (*regex_)(data); | |
1952 | } | |
1953 | ||
1954 | bool operator <(const Rule &rhs) const { | |
1955 | if (weight_ > rhs.weight_) | |
1956 | return true; | |
1957 | if (weight_ < rhs.weight_) | |
1958 | return false; | |
1959 | return mode_ > rhs.mode_; | |
1960 | } | |
1961 | }; | |
1962 | ||
1963 | struct RuleCode { | |
1964 | bool operator ()(const Rule *lhs, const Rule *rhs) const { | |
1965 | return lhs->code_ < rhs->code_; | |
1966 | } | |
1967 | }; | |
1968 | ||
1969 | #ifndef LDID_NOPLIST | |
1970 | static void Sign(const uint8_t *prefix, size_t size, std::streambuf &buffer, Hash &hash, std::streambuf &save, const std::string &identifier, const std::string &entitlements, const std::string &requirement, const std::string &key, const Slots &slots) { | |
1971 | // XXX: this is a miserable fail | |
1972 | std::stringbuf temp; | |
1973 | put(temp, prefix, size); | |
1974 | copy(buffer, temp); | |
1975 | auto data(temp.str()); | |
1976 | ||
1977 | HashProxy proxy(hash, save); | |
1978 | Sign(data.data(), data.size(), proxy, identifier, entitlements, requirement, key, slots); | |
1979 | } | |
1980 | ||
1981 | std::string Bundle(const std::string &root, Folder &folder, const std::string &key, std::map<std::string, Hash> &remote, const std::string &entitlements, const std::string &requirement) { | |
1982 | std::string executable; | |
1983 | std::string identifier; | |
1984 | ||
1985 | static const std::string info("Info.plist"); | |
1986 | ||
1987 | _assert_(folder.Open(info, fun([&](std::streambuf &buffer, const void *flag) { | |
1988 | plist_d(buffer, fun([&](plist_t node) { | |
1989 | executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable")); | |
1990 | identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier")); | |
1991 | })); | |
1992 | })), "open(): Info.plist"); | |
1993 | ||
1994 | static const std::string directory("_CodeSignature/"); | |
1995 | static const std::string signature(directory + "CodeResources"); | |
1996 | ||
1997 | std::map<std::string, std::multiset<Rule>> versions; | |
1998 | ||
1999 | auto &rules1(versions[""]); | |
2000 | auto &rules2(versions["2"]); | |
2001 | ||
2002 | folder.Open(signature, fun([&](std::streambuf &buffer, const void *) { | |
2003 | plist_d(buffer, fun([&](plist_t node) { | |
2004 | // XXX: maybe attempt to preserve existing rules | |
2005 | })); | |
2006 | })); | |
2007 | ||
2008 | if (true) { | |
2009 | rules1.insert(Rule{1, NoMode, "^"}); | |
2010 | rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"}); | |
2011 | rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"}); | |
2012 | rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"}); | |
2013 | rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"}); | |
2014 | rules1.insert(Rule{1, NoMode, "^version.plist$"}); | |
2015 | } | |
2016 | ||
2017 | if (true) { | |
2018 | rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"}); | |
2019 | rules2.insert(Rule{20, NoMode, "^"}); | |
2020 | rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"}); | |
2021 | rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"}); | |
2022 | rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"}); | |
2023 | rules2.insert(Rule{1, NoMode, "^.*"}); | |
2024 | rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"}); | |
2025 | rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"}); | |
2026 | rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"}); | |
2027 | rules2.insert(Rule{20, OmitMode, "^PkgInfo$"}); | |
2028 | rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"}); | |
2029 | rules2.insert(Rule{10, NestedMode, "^[^/]+$"}); | |
2030 | rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"}); | |
2031 | rules2.insert(Rule{20, NoMode, "^version\\.plist$"}); | |
2032 | } | |
2033 | ||
2034 | std::map<std::string, Hash> local; | |
2035 | ||
2036 | static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$"); | |
2037 | ||
2038 | folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) { | |
2039 | if (!nested(name)) | |
2040 | return; | |
2041 | auto bundle(root + Split(name).dir); | |
2042 | SubFolder subfolder(folder, bundle); | |
2043 | Bundle(bundle, subfolder, key, local, "", ""); | |
2044 | })); | |
2045 | ||
2046 | folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) { | |
2047 | // BundleDiskRep::adjustResources -> builder.addExclusion | |
2048 | if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources") | |
2049 | return; | |
2050 | ||
2051 | auto &hash(local[name]); | |
2052 | if (hash.ready_) | |
2053 | return; | |
2054 | ||
2055 | code(fun([&](std::streambuf &data, std::streambuf &save) { | |
2056 | union { | |
2057 | struct { | |
2058 | uint32_t magic; | |
2059 | uint32_t count; | |
2060 | }; | |
2061 | ||
2062 | uint8_t bytes[8]; | |
2063 | } header; | |
2064 | ||
2065 | auto size(most(data, &header.bytes, sizeof(header.bytes))); | |
2066 | if (size == sizeof(header.bytes)) | |
2067 | switch (Swap(header.magic)) { | |
2068 | case FAT_MAGIC: | |
2069 | // Java class file format | |
2070 | if (Swap(header.count) >= 40) | |
2071 | break; | |
2072 | case FAT_CIGAM: | |
2073 | case MH_MAGIC: case MH_MAGIC_64: | |
2074 | case MH_CIGAM: case MH_CIGAM_64: | |
2075 | Slots slots; | |
2076 | Sign(header.bytes, size, data, hash, save, identifier, "", "", key, slots); | |
2077 | return; | |
2078 | } | |
2079 | ||
2080 | HashProxy proxy(hash, save); | |
2081 | put(proxy, header.bytes, size); | |
2082 | copy(data, proxy); | |
2083 | })); | |
2084 | ||
2085 | _assert(hash.ready_); | |
2086 | })); | |
2087 | ||
2088 | auto plist(plist_new_dict()); | |
2089 | _scope({ plist_free(plist); }); | |
2090 | ||
2091 | for (const auto &version : versions) { | |
2092 | auto files(plist_new_dict()); | |
2093 | plist_dict_set_item(plist, ("files" + version.first).c_str(), files); | |
2094 | ||
2095 | for (const auto &rule : version.second) | |
2096 | rule.Compile(); | |
2097 | ||
2098 | bool old(&version.second == &rules1); | |
2099 | ||
2100 | for (const auto &hash : local) | |
2101 | for (const auto &rule : version.second) | |
2102 | if (rule(hash.first)) { | |
2103 | if (rule.mode_ == NestedMode) { | |
2104 | // XXX: implement | |
2105 | } else if (rule.mode_ == NoMode && old) | |
2106 | plist_dict_set_item(files, hash.first.c_str(), plist_new_data(hash.second.sha1_, sizeof(hash.second.sha1_))); | |
2107 | else if (rule.mode_ != OmitMode) { | |
2108 | auto entry(plist_new_dict()); | |
2109 | plist_dict_set_item(entry, "hash", plist_new_data(hash.second.sha1_, sizeof(hash.second.sha1_))); | |
2110 | if (!old) | |
2111 | plist_dict_set_item(entry, "hash2", plist_new_data(hash.second.sha256_, sizeof(hash.second.sha256_))); | |
2112 | if (rule.mode_ == OptionalMode) | |
2113 | plist_dict_set_item(entry, "optional", plist_new_bool(true)); | |
2114 | plist_dict_set_item(files, hash.first.c_str(), entry); | |
2115 | } | |
2116 | ||
2117 | break; | |
2118 | } | |
2119 | } | |
2120 | ||
2121 | for (const auto &version : versions) { | |
2122 | auto rules(plist_new_dict()); | |
2123 | plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules); | |
2124 | ||
2125 | std::multiset<const Rule *, RuleCode> ordered; | |
2126 | for (const auto &rule : version.second) | |
2127 | ordered.insert(&rule); | |
2128 | ||
2129 | for (const auto &rule : ordered) | |
2130 | if (rule->weight_ == 1 && rule->mode_ == NoMode) | |
2131 | plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true)); | |
2132 | else { | |
2133 | auto entry(plist_new_dict()); | |
2134 | plist_dict_set_item(rules, rule->code_.c_str(), entry); | |
2135 | ||
2136 | switch (rule->mode_) { | |
2137 | case NoMode: | |
2138 | break; | |
2139 | case OmitMode: | |
2140 | plist_dict_set_item(entry, "omit", plist_new_bool(true)); | |
2141 | break; | |
2142 | case OptionalMode: | |
2143 | plist_dict_set_item(entry, "optional", plist_new_bool(true)); | |
2144 | break; | |
2145 | case NestedMode: | |
2146 | plist_dict_set_item(entry, "nested", plist_new_bool(true)); | |
2147 | break; | |
2148 | case TopMode: | |
2149 | plist_dict_set_item(entry, "top", plist_new_bool(true)); | |
2150 | break; | |
2151 | } | |
2152 | ||
2153 | if (rule->weight_ >= 10000) | |
2154 | plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_)); | |
2155 | else if (rule->weight_ != 1) | |
2156 | plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_)); | |
2157 | } | |
2158 | } | |
2159 | ||
2160 | folder.Save(signature, NULL, fun([&](std::streambuf &save) { | |
2161 | HashProxy proxy(local[signature], save); | |
2162 | char *xml(NULL); | |
2163 | uint32_t size; | |
2164 | plist_to_xml(plist, &xml, &size); | |
2165 | _scope({ free(xml); }); | |
2166 | put(proxy, xml, size); | |
2167 | })); | |
2168 | ||
2169 | folder.Open(executable, fun([&](std::streambuf &buffer, const void *flag) { | |
2170 | folder.Save(executable, flag, fun([&](std::streambuf &save) { | |
2171 | Slots slots; | |
2172 | slots[1] = local.at(info); | |
2173 | slots[3] = local.at(signature); | |
2174 | Sign(NULL, 0, buffer, local[executable], save, identifier, entitlements, requirement, key, slots); | |
2175 | })); | |
2176 | })); | |
2177 | ||
2178 | for (const auto &hash : local) | |
2179 | remote[root + hash.first] = hash.second; | |
2180 | ||
2181 | return executable; | |
2182 | } | |
2183 | ||
2184 | std::string Bundle(const std::string &root, Folder &folder, const std::string &key, const std::string &entitlements, const std::string &requirement) { | |
2185 | std::map<std::string, Hash> hashes; | |
2186 | return Bundle(root, folder, key, hashes, entitlements, requirement); | |
2187 | } | |
2188 | #endif | |
2189 | ||
2190 | #endif | |
2191 | } | |
2192 | ||
2193 | #ifndef LDID_NOTOOLS | |
2194 | int main(int argc, char *argv[]) { | |
2195 | #ifndef LDID_NOSMIME | |
2196 | OpenSSL_add_all_algorithms(); | |
2197 | #endif | |
2198 | ||
2199 | union { | |
2200 | uint16_t word; | |
2201 | uint8_t byte[2]; | |
2202 | } endian = {1}; | |
2203 | ||
2204 | little_ = endian.byte[0]; | |
2205 | ||
2206 | bool flag_r(false); | |
2207 | bool flag_e(false); | |
2208 | bool flag_q(false); | |
2209 | ||
2210 | #ifndef LDID_NOFLAGT | |
2211 | bool flag_T(false); | |
2212 | #endif | |
2213 | ||
2214 | bool flag_S(false); | |
2215 | bool flag_s(false); | |
2216 | ||
2217 | bool flag_D(false); | |
2218 | ||
2219 | bool flag_A(false); | |
2220 | bool flag_a(false); | |
2221 | ||
2222 | bool flag_u(false); | |
2223 | ||
2224 | uint32_t flag_CPUType(_not(uint32_t)); | |
2225 | uint32_t flag_CPUSubtype(_not(uint32_t)); | |
2226 | ||
2227 | const char *flag_I(NULL); | |
2228 | ||
2229 | #ifndef LDID_NOFLAGT | |
2230 | bool timeh(false); | |
2231 | uint32_t timev(0); | |
2232 | #endif | |
2233 | ||
2234 | Map entitlements; | |
2235 | Map requirement; | |
2236 | Map key; | |
2237 | ldid::Slots slots; | |
2238 | ||
2239 | std::vector<std::string> files; | |
2240 | ||
2241 | if (argc == 1) { | |
2242 | fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]); | |
2243 | fprintf(stderr, " %s -e MobileSafari\n", argv[0]); | |
2244 | fprintf(stderr, " %s -S cat\n", argv[0]); | |
2245 | fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]); | |
2246 | exit(0); | |
2247 | } | |
2248 | ||
2249 | for (int argi(1); argi != argc; ++argi) | |
2250 | if (argv[argi][0] != '-') | |
2251 | files.push_back(argv[argi]); | |
2252 | else switch (argv[argi][1]) { | |
2253 | case 'r': | |
2254 | _assert(!flag_s); | |
2255 | _assert(!flag_S); | |
2256 | flag_r = true; | |
2257 | break; | |
2258 | ||
2259 | case 'e': flag_e = true; break; | |
2260 | ||
2261 | case 'E': { | |
2262 | const char *slot = argv[argi] + 2; | |
2263 | const char *colon = strchr(slot, ':'); | |
2264 | _assert(colon != NULL); | |
2265 | Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
2266 | char *arge; | |
2267 | unsigned number(strtoul(slot, &arge, 0)); | |
2268 | _assert(arge == colon); | |
2269 | sha1(slots[number], file.data(), file.size()); | |
2270 | } break; | |
2271 | ||
2272 | case 'q': flag_q = true; break; | |
2273 | ||
2274 | case 'Q': { | |
2275 | const char *xml = argv[argi] + 2; | |
2276 | requirement.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
2277 | } break; | |
2278 | ||
2279 | case 'D': flag_D = true; break; | |
2280 | ||
2281 | case 'a': flag_a = true; break; | |
2282 | ||
2283 | case 'A': | |
2284 | _assert(!flag_A); | |
2285 | flag_A = true; | |
2286 | if (argv[argi][2] != '\0') { | |
2287 | const char *cpu = argv[argi] + 2; | |
2288 | const char *colon = strchr(cpu, ':'); | |
2289 | _assert(colon != NULL); | |
2290 | char *arge; | |
2291 | flag_CPUType = strtoul(cpu, &arge, 0); | |
2292 | _assert(arge == colon); | |
2293 | flag_CPUSubtype = strtoul(colon + 1, &arge, 0); | |
2294 | _assert(arge == argv[argi] + strlen(argv[argi])); | |
2295 | } | |
2296 | break; | |
2297 | ||
2298 | case 's': | |
2299 | _assert(!flag_r); | |
2300 | _assert(!flag_S); | |
2301 | flag_s = true; | |
2302 | break; | |
2303 | ||
2304 | case 'S': | |
2305 | _assert(!flag_r); | |
2306 | _assert(!flag_s); | |
2307 | flag_S = true; | |
2308 | if (argv[argi][2] != '\0') { | |
2309 | const char *xml = argv[argi] + 2; | |
2310 | entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
2311 | } | |
2312 | break; | |
2313 | ||
2314 | case 'K': | |
2315 | if (argv[argi][2] != '\0') | |
2316 | key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
2317 | break; | |
2318 | ||
2319 | #ifndef LDID_NOFLAGT | |
2320 | case 'T': { | |
2321 | flag_T = true; | |
2322 | if (argv[argi][2] == '-') | |
2323 | timeh = true; | |
2324 | else { | |
2325 | char *arge; | |
2326 | timev = strtoul(argv[argi] + 2, &arge, 0); | |
2327 | _assert(arge == argv[argi] + strlen(argv[argi])); | |
2328 | } | |
2329 | } break; | |
2330 | #endif | |
2331 | ||
2332 | case 'u': { | |
2333 | flag_u = true; | |
2334 | } break; | |
2335 | ||
2336 | case 'I': { | |
2337 | flag_I = argv[argi] + 2; | |
2338 | } break; | |
2339 | ||
2340 | default: | |
2341 | goto usage; | |
2342 | break; | |
2343 | } | |
2344 | ||
2345 | _assert(flag_S || key.empty()); | |
2346 | _assert(flag_S || flag_I == NULL); | |
2347 | ||
2348 | if (files.empty()) usage: { | |
2349 | exit(0); | |
2350 | } | |
2351 | ||
2352 | size_t filei(0), filee(0); | |
2353 | _foreach (file, files) try { | |
2354 | std::string path(file); | |
2355 | ||
2356 | struct stat info; | |
2357 | _syscall(stat(path.c_str(), &info)); | |
2358 | ||
2359 | if (S_ISDIR(info.st_mode)) { | |
2360 | #ifndef LDID_NOPLIST | |
2361 | _assert(!flag_r); | |
2362 | ldid::DiskFolder folder(path); | |
2363 | path += "/" + Bundle("", folder, key, entitlements, requirement); | |
2364 | #else | |
2365 | _assert(false); | |
2366 | #endif | |
2367 | } else if (flag_S || flag_r) { | |
2368 | Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
2369 | ||
2370 | std::filebuf output; | |
2371 | Split split(path); | |
2372 | auto temp(Temporary(output, split)); | |
2373 | ||
2374 | if (flag_r) | |
2375 | ldid::Unsign(input.data(), input.size(), output); | |
2376 | else { | |
2377 | std::string identifier(flag_I ?: split.base.c_str()); | |
2378 | ldid::Sign(input.data(), input.size(), output, identifier, entitlements, requirement, key, slots); | |
2379 | } | |
2380 | ||
2381 | Commit(path, temp); | |
2382 | } | |
2383 | ||
2384 | bool modify(false); | |
2385 | #ifndef LDID_NOFLAGT | |
2386 | if (flag_T) | |
2387 | modify = true; | |
2388 | #endif | |
2389 | if (flag_s) | |
2390 | modify = true; | |
2391 | ||
2392 | Map mapping(path, modify); | |
2393 | FatHeader fat_header(mapping.data(), mapping.size()); | |
2394 | ||
2395 | _foreach (mach_header, fat_header.GetMachHeaders()) { | |
2396 | struct linkedit_data_command *signature(NULL); | |
2397 | struct encryption_info_command *encryption(NULL); | |
2398 | ||
2399 | if (flag_A) { | |
2400 | if (mach_header.GetCPUType() != flag_CPUType) | |
2401 | continue; | |
2402 | if (mach_header.GetCPUSubtype() != flag_CPUSubtype) | |
2403 | continue; | |
2404 | } | |
2405 | ||
2406 | if (flag_a) | |
2407 | printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype()); | |
2408 | ||
2409 | _foreach (load_command, mach_header.GetLoadCommands()) { | |
2410 | uint32_t cmd(mach_header.Swap(load_command->cmd)); | |
2411 | ||
2412 | if (false); | |
2413 | else if (cmd == LC_CODE_SIGNATURE) | |
2414 | signature = reinterpret_cast<struct linkedit_data_command *>(load_command); | |
2415 | else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64) | |
2416 | encryption = reinterpret_cast<struct encryption_info_command *>(load_command); | |
2417 | else if (cmd == LC_LOAD_DYLIB) { | |
2418 | volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command)); | |
2419 | const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name)); | |
2420 | ||
2421 | if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) { | |
2422 | if (flag_u) { | |
2423 | Version version; | |
2424 | version.value = mach_header.Swap(dylib_command->dylib.current_version); | |
2425 | printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch); | |
2426 | } | |
2427 | } | |
2428 | } | |
2429 | #ifndef LDID_NOFLAGT | |
2430 | else if (cmd == LC_ID_DYLIB) { | |
2431 | volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command)); | |
2432 | ||
2433 | if (flag_T) { | |
2434 | uint32_t timed; | |
2435 | ||
2436 | if (!timeh) | |
2437 | timed = timev; | |
2438 | else { | |
2439 | dylib_command->dylib.timestamp = 0; | |
2440 | timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev); | |
2441 | } | |
2442 | ||
2443 | dylib_command->dylib.timestamp = mach_header.Swap(timed); | |
2444 | } | |
2445 | } | |
2446 | #endif | |
2447 | } | |
2448 | ||
2449 | if (flag_D) { | |
2450 | _assert(encryption != NULL); | |
2451 | encryption->cryptid = mach_header.Swap(0); | |
2452 | } | |
2453 | ||
2454 | if (flag_e) { | |
2455 | _assert(signature != NULL); | |
2456 | ||
2457 | uint32_t data = mach_header.Swap(signature->dataoff); | |
2458 | ||
2459 | uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase()); | |
2460 | uint8_t *blob = top + data; | |
2461 | struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob); | |
2462 | ||
2463 | for (size_t index(0); index != Swap(super->count); ++index) | |
2464 | if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) { | |
2465 | uint32_t begin = Swap(super->index[index].offset); | |
2466 | struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin); | |
2467 | fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout); | |
2468 | } | |
2469 | } | |
2470 | ||
2471 | if (flag_q) { | |
2472 | _assert(signature != NULL); | |
2473 | ||
2474 | uint32_t data = mach_header.Swap(signature->dataoff); | |
2475 | ||
2476 | uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase()); | |
2477 | uint8_t *blob = top + data; | |
2478 | struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob); | |
2479 | ||
2480 | for (size_t index(0); index != Swap(super->count); ++index) | |
2481 | if (Swap(super->index[index].type) == CSSLOT_REQUIREMENTS) { | |
2482 | uint32_t begin = Swap(super->index[index].offset); | |
2483 | struct Blob *requirement = reinterpret_cast<struct Blob *>(blob + begin); | |
2484 | fwrite(requirement, 1, Swap(requirement->length), stdout); | |
2485 | } | |
2486 | } | |
2487 | ||
2488 | if (flag_s) { | |
2489 | _assert(signature != NULL); | |
2490 | ||
2491 | uint32_t data = mach_header.Swap(signature->dataoff); | |
2492 | ||
2493 | uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase()); | |
2494 | uint8_t *blob = top + data; | |
2495 | struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob); | |
2496 | ||
2497 | for (size_t index(0); index != Swap(super->count); ++index) | |
2498 | if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) { | |
2499 | uint32_t begin = Swap(super->index[index].offset); | |
2500 | struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin + sizeof(Blob)); | |
2501 | ||
2502 | uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset)); | |
2503 | uint32_t pages = Swap(directory->nCodeSlots); | |
2504 | ||
2505 | if (pages != 1) | |
2506 | for (size_t i = 0; i != pages - 1; ++i) | |
2507 | sha1(hashes[i], top + PageSize_ * i, PageSize_); | |
2508 | if (pages != 0) | |
2509 | sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1); | |
2510 | } | |
2511 | } | |
2512 | } | |
2513 | ||
2514 | ++filei; | |
2515 | } catch (const char *) { | |
2516 | ++filee; | |
2517 | ++filei; | |
2518 | } | |
2519 | ||
2520 | return filee; | |
2521 | } | |
2522 | #endif |