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