]>
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 | ||
ef3241bb | 462 | static inline void get(std::streambuf &stream, void *data, size_t size) { |
4d4682ef JF |
463 | _assert(stream.sgetn(static_cast<char *>(data), size) == size); |
464 | } | |
465 | ||
ef3241bb | 466 | static inline void put(std::streambuf &stream, const void *data, size_t size) { |
4d4682ef JF |
467 | _assert(stream.sputn(static_cast<const char *>(data), size) == size); |
468 | } | |
469 | ||
ef3241bb | 470 | static inline void pad(std::streambuf &stream, size_t size) { |
4d4682ef JF |
471 | char padding[size]; |
472 | memset(padding, 0, size); | |
473 | put(stream, padding, size); | |
474 | } | |
475 | ||
4374152f JF |
476 | template <typename Type_> |
477 | Type_ Align(Type_ value, size_t align) { | |
478 | value += align - 1; | |
479 | value /= align; | |
480 | value *= align; | |
481 | return value; | |
482 | } | |
483 | ||
b9652d6e JF |
484 | static const uint8_t PageShift_(0x0c); |
485 | static const uint32_t PageSize_(1 << PageShift_); | |
486 | ||
f65c321b | 487 | static inline uint16_t Swap_(uint16_t value) { |
fdb119ef JF |
488 | return |
489 | ((value >> 8) & 0x00ff) | | |
490 | ((value << 8) & 0xff00); | |
491 | } | |
492 | ||
f65c321b | 493 | static inline uint32_t Swap_(uint32_t value) { |
fdb119ef JF |
494 | value = ((value >> 8) & 0x00ff00ff) | |
495 | ((value << 8) & 0xff00ff00); | |
496 | value = ((value >> 16) & 0x0000ffff) | | |
497 | ((value << 16) & 0xffff0000); | |
498 | return value; | |
499 | } | |
500 | ||
f65c321b | 501 | static inline uint64_t Swap_(uint64_t value) { |
4374152f JF |
502 | value = (value & 0x00000000ffffffff) << 32 | (value & 0xffffffff00000000) >> 32; |
503 | value = (value & 0x0000ffff0000ffff) << 16 | (value & 0xffff0000ffff0000) >> 16; | |
504 | value = (value & 0x00ff00ff00ff00ff) << 8 | (value & 0xff00ff00ff00ff00) >> 8; | |
505 | return value; | |
506 | } | |
507 | ||
f65c321b | 508 | static inline int16_t Swap_(int16_t value) { |
fdb119ef JF |
509 | return Swap_(static_cast<uint16_t>(value)); |
510 | } | |
511 | ||
f65c321b | 512 | static inline int32_t Swap_(int32_t value) { |
fdb119ef JF |
513 | return Swap_(static_cast<uint32_t>(value)); |
514 | } | |
515 | ||
f65c321b | 516 | static inline int64_t Swap_(int64_t value) { |
4374152f JF |
517 | return Swap_(static_cast<uint64_t>(value)); |
518 | } | |
519 | ||
f65c321b | 520 | static bool little_(true); |
5525a5a7 | 521 | |
f65c321b | 522 | static inline uint16_t Swap(uint16_t value) { |
5525a5a7 | 523 | return little_ ? Swap_(value) : value; |
fdb119ef JF |
524 | } |
525 | ||
f65c321b | 526 | static inline uint32_t Swap(uint32_t value) { |
5525a5a7 | 527 | return little_ ? Swap_(value) : value; |
fdb119ef JF |
528 | } |
529 | ||
f65c321b | 530 | static inline uint64_t Swap(uint64_t value) { |
4374152f JF |
531 | return little_ ? Swap_(value) : value; |
532 | } | |
533 | ||
f65c321b | 534 | static inline int16_t Swap(int16_t value) { |
fdb119ef JF |
535 | return Swap(static_cast<uint16_t>(value)); |
536 | } | |
537 | ||
f65c321b | 538 | static inline int32_t Swap(int32_t value) { |
fdb119ef JF |
539 | return Swap(static_cast<uint32_t>(value)); |
540 | } | |
541 | ||
f65c321b | 542 | static inline int64_t Swap(int64_t value) { |
4374152f JF |
543 | return Swap(static_cast<uint64_t>(value)); |
544 | } | |
545 | ||
4d4682ef | 546 | class Swapped { |
0a033524 | 547 | protected: |
a362a82f JF |
548 | bool swapped_; |
549 | ||
4d4682ef | 550 | Swapped() : |
0a033524 JF |
551 | swapped_(false) |
552 | { | |
553 | } | |
554 | ||
4d4682ef JF |
555 | public: |
556 | Swapped(bool swapped) : | |
557 | swapped_(swapped) | |
558 | { | |
a362a82f JF |
559 | } |
560 | ||
4d4682ef JF |
561 | template <typename Type_> |
562 | Type_ Swap(Type_ value) const { | |
4374152f JF |
563 | return swapped_ ? Swap_(value) : value; |
564 | } | |
4d4682ef | 565 | }; |
4374152f | 566 | |
4d4682ef JF |
567 | class Data : |
568 | public Swapped | |
569 | { | |
570 | private: | |
571 | void *base_; | |
572 | size_t size_; | |
a362a82f | 573 | |
4d4682ef JF |
574 | public: |
575 | Data(void *base, size_t size) : | |
576 | base_(base), | |
577 | size_(size) | |
578 | { | |
4374152f JF |
579 | } |
580 | ||
0a033524 JF |
581 | void *GetBase() const { |
582 | return base_; | |
583 | } | |
a362a82f | 584 | |
0a033524 JF |
585 | size_t GetSize() const { |
586 | return size_; | |
587 | } | |
588 | }; | |
a362a82f | 589 | |
0a033524 JF |
590 | class MachHeader : |
591 | public Data | |
592 | { | |
593 | private: | |
594 | bool bits64_; | |
595 | ||
596 | struct mach_header *mach_header_; | |
597 | struct load_command *load_command_; | |
598 | ||
599 | public: | |
600 | MachHeader(void *base, size_t size) : | |
601 | Data(base, size) | |
602 | { | |
603 | mach_header_ = (mach_header *) base; | |
a362a82f | 604 | |
3cbc6463 JF |
605 | switch (Swap(mach_header_->magic)) { |
606 | case MH_CIGAM: | |
607 | swapped_ = !swapped_; | |
608 | case MH_MAGIC: | |
609 | bits64_ = false; | |
610 | break; | |
611 | ||
612 | case MH_CIGAM_64: | |
613 | swapped_ = !swapped_; | |
614 | case MH_MAGIC_64: | |
615 | bits64_ = true; | |
616 | break; | |
617 | ||
618 | default: | |
619 | _assert(false); | |
620 | } | |
621 | ||
622 | void *post = mach_header_ + 1; | |
623 | if (bits64_) | |
624 | post = (uint32_t *) post + 1; | |
625 | load_command_ = (struct load_command *) post; | |
a362a82f JF |
626 | |
627 | _assert( | |
628 | Swap(mach_header_->filetype) == MH_EXECUTE || | |
629 | Swap(mach_header_->filetype) == MH_DYLIB || | |
630 | Swap(mach_header_->filetype) == MH_BUNDLE | |
631 | ); | |
632 | } | |
633 | ||
4d4682ef JF |
634 | bool Bits64() const { |
635 | return bits64_; | |
636 | } | |
637 | ||
afbb7c8e JF |
638 | struct mach_header *operator ->() const { |
639 | return mach_header_; | |
640 | } | |
641 | ||
4374152f JF |
642 | operator struct mach_header *() const { |
643 | return mach_header_; | |
644 | } | |
645 | ||
04802ab1 JF |
646 | uint32_t GetCPUType() const { |
647 | return Swap(mach_header_->cputype); | |
648 | } | |
649 | ||
4374152f | 650 | uint32_t GetCPUSubtype() const { |
04802ab1 JF |
651 | return Swap(mach_header_->cpusubtype) & 0xff; |
652 | } | |
653 | ||
4374152f JF |
654 | struct load_command *GetLoadCommand() const { |
655 | return load_command_; | |
656 | } | |
657 | ||
0a033524 | 658 | std::vector<struct load_command *> GetLoadCommands() const { |
a362a82f JF |
659 | std::vector<struct load_command *> load_commands; |
660 | ||
3cbc6463 | 661 | struct load_command *load_command = load_command_; |
a362a82f JF |
662 | for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) { |
663 | load_commands.push_back(load_command); | |
664 | load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize)); | |
665 | } | |
666 | ||
667 | return load_commands; | |
668 | } | |
6e83315b | 669 | |
e4d33eec JF |
670 | void ForSection(const ldid::Functor<void (const char *, const char *, void *, size_t)> &code) const { |
671 | _foreach (load_command, GetLoadCommands()) | |
672 | switch (Swap(load_command->cmd)) { | |
673 | case LC_SEGMENT: { | |
674 | auto segment(reinterpret_cast<struct segment_command *>(load_command)); | |
675 | code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize); | |
676 | auto section(reinterpret_cast<struct section *>(segment + 1)); | |
677 | for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section) | |
678 | code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size); | |
679 | } break; | |
680 | ||
681 | case LC_SEGMENT_64: { | |
682 | auto segment(reinterpret_cast<struct segment_command_64 *>(load_command)); | |
683 | code(segment->segname, NULL, GetOffset<void>(segment->fileoff), segment->filesize); | |
684 | auto section(reinterpret_cast<struct section_64 *>(segment + 1)); | |
685 | for (uint32_t i(0), e(Swap(segment->nsects)); i != e; ++i, ++section) | |
686 | code(segment->segname, section->sectname, GetOffset<void>(segment->fileoff + section->offset), section->size); | |
687 | } break; | |
688 | } | |
689 | } | |
690 | ||
6e83315b | 691 | template <typename Target_> |
6e1a740e JF |
692 | Target_ *GetOffset(uint32_t offset) const { |
693 | return reinterpret_cast<Target_ *>(offset + (uint8_t *) mach_header_); | |
6e83315b JF |
694 | } |
695 | }; | |
696 | ||
289ccbbc JF |
697 | class FatMachHeader : |
698 | public MachHeader | |
699 | { | |
700 | private: | |
701 | fat_arch *fat_arch_; | |
702 | ||
703 | public: | |
704 | FatMachHeader(void *base, size_t size, fat_arch *fat_arch) : | |
705 | MachHeader(base, size), | |
706 | fat_arch_(fat_arch) | |
707 | { | |
708 | } | |
709 | ||
710 | fat_arch *GetFatArch() const { | |
711 | return fat_arch_; | |
712 | } | |
713 | }; | |
714 | ||
0a033524 JF |
715 | class FatHeader : |
716 | public Data | |
717 | { | |
718 | private: | |
719 | fat_header *fat_header_; | |
289ccbbc | 720 | std::vector<FatMachHeader> mach_headers_; |
0a033524 JF |
721 | |
722 | public: | |
723 | FatHeader(void *base, size_t size) : | |
724 | Data(base, size) | |
725 | { | |
726 | fat_header_ = reinterpret_cast<struct fat_header *>(base); | |
727 | ||
728 | if (Swap(fat_header_->magic) == FAT_CIGAM) { | |
729 | swapped_ = !swapped_; | |
730 | goto fat; | |
731 | } else if (Swap(fat_header_->magic) != FAT_MAGIC) { | |
732 | fat_header_ = NULL; | |
289ccbbc | 733 | mach_headers_.push_back(FatMachHeader(base, size, NULL)); |
0a033524 JF |
734 | } else fat: { |
735 | size_t fat_narch = Swap(fat_header_->nfat_arch); | |
736 | fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header_ + 1); | |
737 | size_t arch; | |
738 | for (arch = 0; arch != fat_narch; ++arch) { | |
739 | uint32_t arch_offset = Swap(fat_arch->offset); | |
740 | uint32_t arch_size = Swap(fat_arch->size); | |
289ccbbc | 741 | mach_headers_.push_back(FatMachHeader((uint8_t *) base + arch_offset, arch_size, fat_arch)); |
0a033524 JF |
742 | ++fat_arch; |
743 | } | |
744 | } | |
745 | } | |
746 | ||
289ccbbc | 747 | std::vector<FatMachHeader> &GetMachHeaders() { |
0a033524 JF |
748 | return mach_headers_; |
749 | } | |
20e7eb29 JF |
750 | |
751 | bool IsFat() const { | |
752 | return fat_header_ != NULL; | |
753 | } | |
6b38c173 JF |
754 | |
755 | struct fat_header *operator ->() const { | |
756 | return fat_header_; | |
757 | } | |
4374152f JF |
758 | |
759 | operator struct fat_header *() const { | |
760 | return fat_header_; | |
761 | } | |
0a033524 JF |
762 | }; |
763 | ||
4d4682ef JF |
764 | #define CSMAGIC_REQUIREMENT uint32_t(0xfade0c00) |
765 | #define CSMAGIC_REQUIREMENTS uint32_t(0xfade0c01) | |
766 | #define CSMAGIC_CODEDIRECTORY uint32_t(0xfade0c02) | |
767 | #define CSMAGIC_EMBEDDED_SIGNATURE uint32_t(0xfade0cc0) | |
768 | #define CSMAGIC_EMBEDDED_SIGNATURE_OLD uint32_t(0xfade0b02) | |
769 | #define CSMAGIC_EMBEDDED_ENTITLEMENTS uint32_t(0xfade7171) | |
770 | #define CSMAGIC_DETACHED_SIGNATURE uint32_t(0xfade0cc1) | |
771 | #define CSMAGIC_BLOBWRAPPER uint32_t(0xfade0b01) | |
c05d9758 | 772 | |
4d4682ef JF |
773 | #define CSSLOT_CODEDIRECTORY uint32_t(0x00000) |
774 | #define CSSLOT_INFOSLOT uint32_t(0x00001) | |
775 | #define CSSLOT_REQUIREMENTS uint32_t(0x00002) | |
776 | #define CSSLOT_RESOURCEDIR uint32_t(0x00003) | |
777 | #define CSSLOT_APPLICATION uint32_t(0x00004) | |
778 | #define CSSLOT_ENTITLEMENTS uint32_t(0x00005) | |
779 | ||
780 | #define CSSLOT_SIGNATURESLOT uint32_t(0x10000) | |
781 | ||
782 | #define CS_HASHTYPE_SHA1 1 | |
fdb119ef JF |
783 | |
784 | struct BlobIndex { | |
785 | uint32_t type; | |
786 | uint32_t offset; | |
c05d9758 | 787 | } _packed; |
fdb119ef | 788 | |
c05d9758 | 789 | struct Blob { |
fdb119ef JF |
790 | uint32_t magic; |
791 | uint32_t length; | |
c05d9758 JF |
792 | } _packed; |
793 | ||
794 | struct SuperBlob { | |
795 | struct Blob blob; | |
fdb119ef JF |
796 | uint32_t count; |
797 | struct BlobIndex index[]; | |
c05d9758 | 798 | } _packed; |
fdb119ef JF |
799 | |
800 | struct CodeDirectory { | |
fdb119ef JF |
801 | uint32_t version; |
802 | uint32_t flags; | |
803 | uint32_t hashOffset; | |
804 | uint32_t identOffset; | |
805 | uint32_t nSpecialSlots; | |
806 | uint32_t nCodeSlots; | |
807 | uint32_t codeLimit; | |
808 | uint8_t hashSize; | |
809 | uint8_t hashType; | |
810 | uint8_t spare1; | |
811 | uint8_t pageSize; | |
812 | uint32_t spare2; | |
b73d2333 JF |
813 | uint32_t scatterOffset; |
814 | uint32_t teamIDOffset; | |
815 | uint32_t spare3; | |
816 | uint64_t codeLimit64; | |
c05d9758 | 817 | } _packed; |
fdb119ef | 818 | |
fdbee693 | 819 | #ifndef LDID_NOFLAGT |
a362a82f | 820 | extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval); |
fdbee693 | 821 | #endif |
a362a82f | 822 | |
f65c321b | 823 | static void sha1(uint8_t *hash, const void *data, size_t size) { |
84d29a1c | 824 | LDID_SHA1(static_cast<const uint8_t *>(data), size, hash); |
fdb119ef JF |
825 | } |
826 | ||
707027e8 JF |
827 | static void sha1(std::vector<char> &hash, const void *data, size_t size) { |
828 | hash.resize(LDID_SHA1_DIGEST_LENGTH); | |
829 | sha1(reinterpret_cast<uint8_t *>(hash.data()), data, size); | |
830 | } | |
831 | ||
0a033524 | 832 | struct CodesignAllocation { |
4374152f JF |
833 | FatMachHeader mach_header_; |
834 | uint32_t offset_; | |
835 | uint32_t size_; | |
4d4682ef | 836 | uint32_t limit_; |
4374152f | 837 | uint32_t alloc_; |
e4b7adc1 | 838 | uint32_t align_; |
4374152f | 839 | |
e0098838 | 840 | CodesignAllocation(FatMachHeader mach_header, size_t offset, size_t size, size_t limit, size_t alloc, size_t align) : |
4374152f JF |
841 | mach_header_(mach_header), |
842 | offset_(offset), | |
843 | size_(size), | |
4d4682ef | 844 | limit_(limit), |
e4b7adc1 JF |
845 | alloc_(alloc), |
846 | align_(align) | |
0a033524 JF |
847 | { |
848 | } | |
849 | }; | |
850 | ||
0326ab11 | 851 | #ifndef LDID_NOTOOLS |
dede6121 JF |
852 | class File { |
853 | private: | |
854 | int file_; | |
855 | ||
856 | public: | |
857 | File() : | |
858 | file_(-1) | |
859 | { | |
860 | } | |
861 | ||
862 | ~File() { | |
863 | if (file_ != -1) | |
864 | _syscall(close(file_)); | |
865 | } | |
866 | ||
cad40c43 | 867 | void open(const char *path, int flags) { |
dede6121 | 868 | _assert(file_ == -1); |
fc7a76da | 869 | file_ = _syscall(::open(path, flags)); |
dede6121 JF |
870 | } |
871 | ||
872 | int file() const { | |
873 | return file_; | |
874 | } | |
875 | }; | |
876 | ||
877 | class Map { | |
878 | private: | |
879 | File file_; | |
880 | void *data_; | |
881 | size_t size_; | |
882 | ||
883 | void clear() { | |
884 | if (data_ == NULL) | |
885 | return; | |
886 | _syscall(munmap(data_, size_)); | |
887 | data_ = NULL; | |
888 | size_ = 0; | |
889 | } | |
890 | ||
891 | public: | |
892 | Map() : | |
893 | data_(NULL), | |
894 | size_(0) | |
895 | { | |
896 | } | |
897 | ||
d4187e53 | 898 | Map(const std::string &path, int oflag, int pflag, int mflag) : |
cad40c43 JF |
899 | Map() |
900 | { | |
901 | open(path, oflag, pflag, mflag); | |
902 | } | |
903 | ||
d4187e53 | 904 | Map(const std::string &path, bool edit) : |
cad40c43 JF |
905 | Map() |
906 | { | |
907 | open(path, edit); | |
dede6121 JF |
908 | } |
909 | ||
910 | ~Map() { | |
911 | clear(); | |
912 | } | |
913 | ||
fac3d3e3 JF |
914 | bool empty() const { |
915 | return data_ == NULL; | |
916 | } | |
917 | ||
d4187e53 | 918 | void open(const std::string &path, int oflag, int pflag, int mflag) { |
dede6121 JF |
919 | clear(); |
920 | ||
d4187e53 | 921 | file_.open(path.c_str(), oflag); |
dede6121 JF |
922 | int file(file_.file()); |
923 | ||
924 | struct stat stat; | |
925 | _syscall(fstat(file, &stat)); | |
926 | size_ = stat.st_size; | |
927 | ||
fc7a76da | 928 | data_ = _syscall(mmap(NULL, size_, pflag, mflag, file, 0)); |
cad40c43 JF |
929 | } |
930 | ||
d4187e53 | 931 | void open(const std::string &path, bool edit) { |
cad40c43 JF |
932 | if (edit) |
933 | open(path, O_RDWR, PROT_READ | PROT_WRITE, MAP_SHARED); | |
934 | else | |
935 | open(path, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
dede6121 JF |
936 | } |
937 | ||
938 | void *data() const { | |
939 | return data_; | |
940 | } | |
941 | ||
942 | size_t size() const { | |
943 | return size_; | |
944 | } | |
f4b2df35 JF |
945 | |
946 | operator std::string() const { | |
947 | return std::string(static_cast<char *>(data_), size_); | |
948 | } | |
dede6121 | 949 | }; |
0326ab11 | 950 | #endif |
dede6121 | 951 | |
a0c715e9 JF |
952 | namespace ldid { |
953 | ||
e4d33eec | 954 | 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 | 955 | FatHeader source(const_cast<void *>(idata), isize); |
f4b2df35 JF |
956 | |
957 | size_t offset(0); | |
958 | if (source.IsFat()) | |
959 | offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch); | |
960 | ||
961 | std::vector<CodesignAllocation> allocations; | |
962 | _foreach (mach_header, source.GetMachHeaders()) { | |
963 | struct linkedit_data_command *signature(NULL); | |
964 | struct symtab_command *symtab(NULL); | |
965 | ||
966 | _foreach (load_command, mach_header.GetLoadCommands()) { | |
967 | uint32_t cmd(mach_header.Swap(load_command->cmd)); | |
968 | if (false); | |
969 | else if (cmd == LC_CODE_SIGNATURE) | |
970 | signature = reinterpret_cast<struct linkedit_data_command *>(load_command); | |
971 | else if (cmd == LC_SYMTAB) | |
972 | symtab = reinterpret_cast<struct symtab_command *>(load_command); | |
973 | } | |
974 | ||
975 | size_t size; | |
976 | if (signature == NULL) | |
977 | size = mach_header.GetSize(); | |
978 | else { | |
979 | size = mach_header.Swap(signature->dataoff); | |
980 | _assert(size <= mach_header.GetSize()); | |
981 | } | |
982 | ||
983 | if (symtab != NULL) { | |
984 | auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize)); | |
985 | _assert(end <= size); | |
986 | _assert(end >= size - 0x10); | |
987 | size = end; | |
988 | } | |
989 | ||
e4d33eec | 990 | size_t alloc(allocate(mach_header, size)); |
f4b2df35 JF |
991 | |
992 | auto *fat_arch(mach_header.GetFatArch()); | |
6f420711 JF |
993 | uint32_t align; |
994 | ||
995 | if (fat_arch != NULL) | |
996 | align = source.Swap(fat_arch->align); | |
997 | else switch (mach_header.GetCPUType()) { | |
998 | case CPU_TYPE_POWERPC: | |
999 | case CPU_TYPE_POWERPC64: | |
1000 | case CPU_TYPE_X86: | |
1001 | case CPU_TYPE_X86_64: | |
1002 | align = 0xc; | |
1003 | break; | |
1004 | case CPU_TYPE_ARM: | |
1005 | case CPU_TYPE_ARM64: | |
1006 | align = 0xe; | |
1007 | break; | |
1008 | default: | |
1009 | align = 0x0; | |
1010 | break; | |
1011 | } | |
1012 | ||
f4b2df35 JF |
1013 | offset = Align(offset, 1 << align); |
1014 | ||
4d4682ef JF |
1015 | uint32_t limit(size); |
1016 | if (alloc != 0) | |
1017 | limit = Align(limit, 0x10); | |
1018 | ||
e0098838 | 1019 | allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align)); |
f4b2df35 | 1020 | offset += size + alloc; |
b9652d6e | 1021 | offset = Align(offset, 0x10); |
f4b2df35 JF |
1022 | } |
1023 | ||
4d4682ef JF |
1024 | size_t position(0); |
1025 | ||
1026 | if (source.IsFat()) { | |
1027 | fat_header fat_header; | |
1028 | fat_header.magic = Swap(FAT_MAGIC); | |
1029 | fat_header.nfat_arch = Swap(uint32_t(allocations.size())); | |
1030 | put(output, &fat_header, sizeof(fat_header)); | |
1031 | position += sizeof(fat_header); | |
1032 | ||
1033 | _foreach (allocation, allocations) { | |
1034 | auto &mach_header(allocation.mach_header_); | |
1035 | ||
1036 | fat_arch fat_arch; | |
1037 | fat_arch.cputype = Swap(mach_header->cputype); | |
1038 | fat_arch.cpusubtype = Swap(mach_header->cpusubtype); | |
1039 | fat_arch.offset = Swap(allocation.offset_); | |
1040 | fat_arch.size = Swap(allocation.limit_ + allocation.alloc_); | |
1041 | fat_arch.align = Swap(allocation.align_); | |
1042 | put(output, &fat_arch, sizeof(fat_arch)); | |
1043 | position += sizeof(fat_arch); | |
1044 | } | |
f4b2df35 JF |
1045 | } |
1046 | ||
1047 | _foreach (allocation, allocations) { | |
4d4682ef | 1048 | auto &mach_header(allocation.mach_header_); |
f4b2df35 | 1049 | |
4d4682ef JF |
1050 | pad(output, allocation.offset_ - position); |
1051 | position = allocation.offset_; | |
f4b2df35 | 1052 | |
4d4682ef | 1053 | std::vector<std::string> commands; |
f4b2df35 | 1054 | |
4d4682ef JF |
1055 | _foreach (load_command, mach_header.GetLoadCommands()) { |
1056 | std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize); | |
f4b2df35 | 1057 | |
a7f01a65 | 1058 | switch (mach_header.Swap(load_command->cmd)) { |
4d4682ef JF |
1059 | case LC_CODE_SIGNATURE: |
1060 | continue; | |
1061 | break; | |
1062 | ||
1063 | case LC_SEGMENT: { | |
1064 | auto segment_command(reinterpret_cast<struct segment_command *>(©[0])); | |
1065 | if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0) | |
1066 | break; | |
1067 | size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff))); | |
1068 | segment_command->filesize = size; | |
6f420711 | 1069 | segment_command->vmsize = Align(size, 1 << allocation.align_); |
4d4682ef JF |
1070 | } break; |
1071 | ||
1072 | case LC_SEGMENT_64: { | |
1073 | auto segment_command(reinterpret_cast<struct segment_command_64 *>(©[0])); | |
1074 | if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0) | |
1075 | break; | |
1076 | size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff))); | |
1077 | segment_command->filesize = size; | |
6f420711 | 1078 | segment_command->vmsize = Align(size, 1 << allocation.align_); |
4d4682ef JF |
1079 | } break; |
1080 | } | |
f4b2df35 | 1081 | |
4d4682ef | 1082 | commands.push_back(copy); |
f4b2df35 JF |
1083 | } |
1084 | ||
e0098838 | 1085 | if (allocation.alloc_ != 0) { |
4d4682ef JF |
1086 | linkedit_data_command signature; |
1087 | signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE); | |
1088 | signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature))); | |
1089 | signature.dataoff = mach_header.Swap(allocation.limit_); | |
1090 | signature.datasize = mach_header.Swap(allocation.alloc_); | |
1091 | commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature))); | |
1092 | } | |
f4b2df35 | 1093 | |
4d4682ef | 1094 | size_t begin(position); |
f4b2df35 | 1095 | |
4d4682ef JF |
1096 | uint32_t after(0); |
1097 | _foreach(command, commands) | |
1098 | after += command.size(); | |
f4b2df35 | 1099 | |
4d4682ef | 1100 | std::stringbuf altern; |
f4b2df35 | 1101 | |
4d4682ef JF |
1102 | struct mach_header header(*mach_header); |
1103 | header.ncmds = mach_header.Swap(uint32_t(commands.size())); | |
1104 | header.sizeofcmds = mach_header.Swap(after); | |
1105 | put(output, &header, sizeof(header)); | |
1106 | put(altern, &header, sizeof(header)); | |
1107 | position += sizeof(header); | |
f4b2df35 | 1108 | |
4d4682ef JF |
1109 | if (mach_header.Bits64()) { |
1110 | auto pad(mach_header.Swap(uint32_t(0))); | |
1111 | put(output, &pad, sizeof(pad)); | |
1112 | put(altern, &pad, sizeof(pad)); | |
1113 | position += sizeof(pad); | |
1114 | } | |
f4b2df35 | 1115 | |
4d4682ef JF |
1116 | _foreach(command, commands) { |
1117 | put(output, command.data(), command.size()); | |
1118 | put(altern, command.data(), command.size()); | |
1119 | position += command.size(); | |
1120 | } | |
f4b2df35 | 1121 | |
4d4682ef JF |
1122 | uint32_t before(mach_header.Swap(mach_header->sizeofcmds)); |
1123 | if (before > after) { | |
1124 | pad(output, before - after); | |
1125 | pad(altern, before - after); | |
1126 | position += before - after; | |
1127 | } | |
f4b2df35 | 1128 | |
4d4682ef | 1129 | auto top(reinterpret_cast<char *>(mach_header.GetBase())); |
f4b2df35 | 1130 | |
4d4682ef JF |
1131 | std::string overlap(altern.str()); |
1132 | overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size()); | |
f4b2df35 | 1133 | |
4d4682ef JF |
1134 | put(output, top + (position - begin), allocation.size_ - (position - begin)); |
1135 | position = begin + allocation.size_; | |
f4b2df35 | 1136 | |
4d4682ef JF |
1137 | pad(output, allocation.limit_ - allocation.size_); |
1138 | position += allocation.limit_ - allocation.size_; | |
f4b2df35 | 1139 | |
e4d33eec | 1140 | size_t saved(save(mach_header, output, allocation.limit_, overlap, top)); |
67205335 JF |
1141 | if (allocation.alloc_ > saved) |
1142 | pad(output, allocation.alloc_ - saved); | |
1143 | position += allocation.alloc_; | |
e0098838 JF |
1144 | } |
1145 | } | |
f4b2df35 | 1146 | |
a0c715e9 JF |
1147 | } |
1148 | ||
efad8a44 JF |
1149 | typedef std::map<uint32_t, std::string> Blobs; |
1150 | ||
bb591e2b JF |
1151 | static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) { |
1152 | auto value(buffer.str()); | |
1153 | std::swap(blobs[slot], value); | |
1154 | } | |
1155 | ||
8f310b91 JF |
1156 | static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) { |
1157 | auto value(buffer.str()); | |
1158 | Blob blob; | |
1159 | blob.magic = Swap(magic); | |
1160 | blob.length = Swap(uint32_t(sizeof(blob) + value.size())); | |
1161 | value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob)); | |
1162 | std::swap(blobs[slot], value); | |
efad8a44 JF |
1163 | } |
1164 | ||
1165 | static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) { | |
1166 | size_t total(0); | |
1167 | _foreach (blob, blobs) | |
1168 | total += blob.second.size(); | |
1169 | ||
1170 | struct SuperBlob super; | |
1171 | super.blob.magic = Swap(magic); | |
1172 | super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total)); | |
1173 | super.count = Swap(uint32_t(blobs.size())); | |
1174 | put(output, &super, sizeof(super)); | |
1175 | ||
1176 | size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size()); | |
1177 | ||
1178 | _foreach (blob, blobs) { | |
1179 | BlobIndex index; | |
1180 | index.type = Swap(blob.first); | |
1181 | index.offset = Swap(uint32_t(offset)); | |
1182 | put(output, &index, sizeof(index)); | |
1183 | offset += blob.second.size(); | |
1184 | } | |
1185 | ||
1186 | _foreach (blob, blobs) | |
1187 | put(output, blob.second.data(), blob.second.size()); | |
1188 | ||
1189 | return offset; | |
1190 | } | |
1191 | ||
489c97b8 | 1192 | #ifndef LDID_NOSMIME |
30c64adb JF |
1193 | class Buffer { |
1194 | private: | |
1195 | BIO *bio_; | |
1196 | ||
1197 | public: | |
1198 | Buffer(BIO *bio) : | |
1199 | bio_(bio) | |
1200 | { | |
1201 | _assert(bio_ != NULL); | |
1202 | } | |
1203 | ||
1204 | Buffer() : | |
1205 | bio_(BIO_new(BIO_s_mem())) | |
1206 | { | |
1207 | } | |
1208 | ||
1209 | Buffer(const char *data, size_t size) : | |
1210 | Buffer(BIO_new_mem_buf(const_cast<char *>(data), size)) | |
1211 | { | |
1212 | } | |
1213 | ||
1214 | Buffer(const std::string &data) : | |
1215 | Buffer(data.data(), data.size()) | |
1216 | { | |
1217 | } | |
1218 | ||
1219 | Buffer(PKCS7 *pkcs) : | |
1220 | Buffer() | |
1221 | { | |
1222 | _assert(i2d_PKCS7_bio(bio_, pkcs) != 0); | |
1223 | } | |
1224 | ||
1225 | ~Buffer() { | |
1226 | BIO_free_all(bio_); | |
1227 | } | |
1228 | ||
1229 | operator BIO *() const { | |
1230 | return bio_; | |
1231 | } | |
1232 | ||
1233 | explicit operator std::string() const { | |
1234 | char *data; | |
1235 | auto size(BIO_get_mem_data(bio_, &data)); | |
1236 | return std::string(data, size); | |
1237 | } | |
1238 | }; | |
1239 | ||
1240 | class Stuff { | |
1241 | private: | |
1242 | PKCS12 *value_; | |
1243 | EVP_PKEY *key_; | |
1244 | X509 *cert_; | |
1245 | STACK_OF(X509) *ca_; | |
1246 | ||
1247 | public: | |
1248 | Stuff(BIO *bio) : | |
1249 | value_(d2i_PKCS12_bio(bio, NULL)), | |
1250 | ca_(NULL) | |
1251 | { | |
1252 | _assert(value_ != NULL); | |
1253 | _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0); | |
1254 | _assert(key_ != NULL); | |
1255 | _assert(cert_ != NULL); | |
1256 | } | |
1257 | ||
1258 | Stuff(const std::string &data) : | |
1259 | Stuff(Buffer(data)) | |
1260 | { | |
1261 | } | |
1262 | ||
1263 | ~Stuff() { | |
1264 | sk_X509_pop_free(ca_, X509_free); | |
1265 | X509_free(cert_); | |
1266 | EVP_PKEY_free(key_); | |
1267 | PKCS12_free(value_); | |
1268 | } | |
1269 | ||
1270 | operator PKCS12 *() const { | |
1271 | return value_; | |
1272 | } | |
1273 | ||
1274 | operator EVP_PKEY *() const { | |
1275 | return key_; | |
1276 | } | |
1277 | ||
1278 | operator X509 *() const { | |
1279 | return cert_; | |
1280 | } | |
1281 | ||
1282 | operator STACK_OF(X509) *() const { | |
1283 | return ca_; | |
1284 | } | |
1285 | }; | |
1286 | ||
1287 | class Signature { | |
1288 | private: | |
1289 | PKCS7 *value_; | |
1290 | ||
1291 | public: | |
1292 | Signature(const Stuff &stuff, const Buffer &data) : | |
1293 | value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED)) | |
1294 | { | |
1295 | _assert(value_ != NULL); | |
1296 | } | |
1297 | ||
1298 | ~Signature() { | |
1299 | PKCS7_free(value_); | |
1300 | } | |
1301 | ||
1302 | operator PKCS7 *() const { | |
1303 | return value_; | |
1304 | } | |
1305 | }; | |
489c97b8 | 1306 | #endif |
30c64adb | 1307 | |
23c11ee8 JF |
1308 | class NullBuffer : |
1309 | public std::streambuf | |
1310 | { | |
1311 | public: | |
1312 | virtual std::streamsize xsputn(const char_type *data, std::streamsize size) { | |
1313 | return size; | |
1314 | } | |
1315 | ||
1316 | virtual int_type overflow(int_type next) { | |
1317 | return next; | |
1318 | } | |
1319 | }; | |
1320 | ||
1321 | class HashBuffer : | |
1322 | public std::streambuf | |
1323 | { | |
1324 | private: | |
1325 | std::vector<char> &hash_; | |
84d29a1c | 1326 | LDID_SHA1_CTX context_; |
23c11ee8 JF |
1327 | |
1328 | public: | |
1329 | HashBuffer(std::vector<char> &hash) : | |
1330 | hash_(hash) | |
1331 | { | |
84d29a1c | 1332 | LDID_SHA1_Init(&context_); |
23c11ee8 JF |
1333 | } |
1334 | ||
1335 | ~HashBuffer() { | |
84d29a1c JF |
1336 | hash_.resize(LDID_SHA1_DIGEST_LENGTH); |
1337 | LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.data()), &context_); | |
23c11ee8 JF |
1338 | } |
1339 | ||
1340 | virtual std::streamsize xsputn(const char_type *data, std::streamsize size) { | |
84d29a1c | 1341 | LDID_SHA1_Update(&context_, data, size); |
23c11ee8 JF |
1342 | return size; |
1343 | } | |
1344 | ||
1345 | virtual int_type overflow(int_type next) { | |
1346 | if (next == traits_type::eof()) | |
1347 | return sync(); | |
1348 | char value(next); | |
1349 | xsputn(&value, 1); | |
1350 | return next; | |
1351 | } | |
1352 | }; | |
1353 | ||
1354 | class HashProxy : | |
1355 | public HashBuffer | |
1356 | { | |
1357 | private: | |
1358 | std::streambuf &buffer_; | |
1359 | ||
1360 | public: | |
1361 | HashProxy(std::vector<char> &hash, std::streambuf &buffer) : | |
1362 | HashBuffer(hash), | |
1363 | buffer_(buffer) | |
1364 | { | |
1365 | } | |
1366 | ||
1367 | virtual std::streamsize xsputn(const char_type *data, std::streamsize size) { | |
1368 | _assert(HashBuffer::xsputn(data, size) == size); | |
1369 | return buffer_.sputn(data, size); | |
1370 | } | |
1371 | }; | |
1372 | ||
0326ab11 | 1373 | #ifndef LDID_NOTOOLS |
23c11ee8 JF |
1374 | static bool Starts(const std::string &lhs, const std::string &rhs) { |
1375 | return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0; | |
1376 | } | |
1377 | ||
1378 | class Split { | |
1379 | public: | |
1380 | std::string dir; | |
1381 | std::string base; | |
1382 | ||
1383 | Split(const std::string &path) { | |
1384 | size_t slash(path.rfind('/')); | |
1385 | if (slash == std::string::npos) | |
1386 | base = path; | |
1387 | else { | |
1388 | dir = path.substr(0, slash + 1); | |
1389 | base = path.substr(slash + 1); | |
1390 | } | |
1391 | } | |
1392 | }; | |
1393 | ||
1394 | static void mkdir_p(const std::string &path) { | |
1395 | if (path.empty()) | |
1396 | return; | |
31cc0388 JF |
1397 | #ifdef __WIN32__ |
1398 | if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST) | |
1399 | return; | |
1400 | #else | |
23c11ee8 JF |
1401 | if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST) |
1402 | return; | |
31cc0388 | 1403 | #endif |
23c11ee8 JF |
1404 | auto slash(path.rfind('/', path.size() - 1)); |
1405 | if (slash == std::string::npos) | |
1406 | return; | |
1407 | mkdir_p(path.substr(0, slash)); | |
1408 | } | |
1409 | ||
1410 | static std::string Temporary(std::filebuf &file, const Split &split) { | |
1411 | std::string temp(split.dir + ".ldid." + split.base); | |
1412 | mkdir_p(split.dir); | |
1413 | _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str()); | |
1414 | return temp; | |
1415 | } | |
1416 | ||
d4187e53 JF |
1417 | static void Commit(const std::string &path, const std::string &temp) { |
1418 | struct stat info; | |
23c11ee8 | 1419 | if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) { |
d4187e53 | 1420 | #ifndef __WIN32__ |
23c11ee8 | 1421 | _syscall(chown(temp.c_str(), info.st_uid, info.st_gid)); |
d4187e53 | 1422 | #endif |
23c11ee8 JF |
1423 | _syscall(chmod(temp.c_str(), info.st_mode)); |
1424 | } | |
1425 | ||
d4187e53 JF |
1426 | _syscall(rename(temp.c_str(), path.c_str())); |
1427 | } | |
0326ab11 | 1428 | #endif |
d4187e53 | 1429 | |
a0c715e9 | 1430 | namespace ldid { |
e57b1f91 | 1431 | |
ffdd1183 | 1432 | void Sign(const void *idata, size_t isize, std::streambuf &output, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) { |
b73d2333 JF |
1433 | std::string team; |
1434 | ||
1435 | #ifndef LDID_NOSMIME | |
1436 | if (!key.empty()) { | |
1437 | std::stringbuf data; | |
1438 | Stuff stuff(key); | |
1439 | auto name(X509_get_subject_name(stuff)); | |
1440 | _assert(name != NULL); | |
1441 | auto index(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, -1)); | |
1442 | _assert(index >= 0); | |
1443 | auto next(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, index)); | |
1444 | _assert(next == -1); | |
1445 | auto entry(X509_NAME_get_entry(name, index)); | |
1446 | _assert(entry != NULL); | |
1447 | auto asn(X509_NAME_ENTRY_get_data(entry)); | |
1448 | _assert(asn != NULL); | |
1449 | team.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn)), ASN1_STRING_length(asn)); | |
1450 | } | |
1451 | #endif | |
1452 | ||
e4d33eec | 1453 | Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, size_t size) -> size_t { |
e0098838 | 1454 | size_t alloc(sizeof(struct SuperBlob)); |
f4b2df35 | 1455 | |
e0098838 | 1456 | uint32_t special(0); |
f4b2df35 | 1457 | |
e0098838 JF |
1458 | special = std::max(special, CSSLOT_REQUIREMENTS); |
1459 | alloc += sizeof(struct BlobIndex); | |
1460 | alloc += 0xc; | |
f4b2df35 | 1461 | |
faa1b1f8 | 1462 | if (!entitlements.empty()) { |
e0098838 JF |
1463 | special = std::max(special, CSSLOT_ENTITLEMENTS); |
1464 | alloc += sizeof(struct BlobIndex); | |
1465 | alloc += sizeof(struct Blob); | |
1466 | alloc += entitlements.size(); | |
1467 | } | |
f4b2df35 | 1468 | |
e0098838 JF |
1469 | special = std::max(special, CSSLOT_CODEDIRECTORY); |
1470 | alloc += sizeof(struct BlobIndex); | |
1471 | alloc += sizeof(struct Blob); | |
1472 | alloc += sizeof(struct CodeDirectory); | |
ffdd1183 | 1473 | alloc += identifier.size() + 1; |
f4b2df35 | 1474 | |
b73d2333 JF |
1475 | if (!team.empty()) |
1476 | alloc += team.size() + 1; | |
1477 | ||
30c64adb JF |
1478 | if (!key.empty()) { |
1479 | alloc += sizeof(struct BlobIndex); | |
1480 | alloc += sizeof(struct Blob); | |
1481 | // XXX: this is just a "sufficiently large number" | |
1482 | alloc += 0x3000; | |
1483 | } | |
1484 | ||
e57b1f91 JF |
1485 | _foreach (slot, slots) |
1486 | special = std::max(special, slot.first); | |
1487 | ||
e4d33eec JF |
1488 | mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) { |
1489 | if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0) | |
1490 | special = std::max(special, CSSLOT_INFOSLOT); | |
1491 | })); | |
1492 | ||
b9652d6e | 1493 | uint32_t normal((size + PageSize_ - 1) / PageSize_); |
84d29a1c | 1494 | alloc = Align(alloc + (special + normal) * LDID_SHA1_DIGEST_LENGTH, 16); |
e0098838 | 1495 | return alloc; |
e4d33eec | 1496 | }), fun([&](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t { |
efad8a44 | 1497 | Blobs blobs; |
f4b2df35 | 1498 | |
e0098838 JF |
1499 | if (true) { |
1500 | std::stringbuf data; | |
f4b2df35 | 1501 | |
bb591e2b JF |
1502 | Blobs requirements; |
1503 | put(data, CSMAGIC_REQUIREMENTS, requirements); | |
4d4682ef | 1504 | |
bb591e2b | 1505 | insert(blobs, CSSLOT_REQUIREMENTS, data); |
e0098838 | 1506 | } |
4d4682ef | 1507 | |
faa1b1f8 | 1508 | if (!entitlements.empty()) { |
e0098838 | 1509 | std::stringbuf data; |
e0098838 | 1510 | put(data, entitlements.data(), entitlements.size()); |
8f310b91 | 1511 | insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data); |
e0098838 JF |
1512 | } |
1513 | ||
1514 | if (true) { | |
1515 | std::stringbuf data; | |
1516 | ||
e4d33eec JF |
1517 | Slots posts(slots); |
1518 | ||
1519 | mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) { | |
1520 | if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0) | |
1521 | sha1(posts[CSSLOT_INFOSLOT], data, size); | |
1522 | })); | |
1523 | ||
e0098838 JF |
1524 | uint32_t special(0); |
1525 | _foreach (blob, blobs) | |
1526 | special = std::max(special, blob.first); | |
e4d33eec | 1527 | _foreach (slot, posts) |
e57b1f91 | 1528 | special = std::max(special, slot.first); |
b9652d6e | 1529 | uint32_t normal((limit + PageSize_ - 1) / PageSize_); |
e0098838 | 1530 | |
e0098838 | 1531 | CodeDirectory directory; |
b73d2333 | 1532 | directory.version = Swap(uint32_t(0x00020200)); |
e0098838 | 1533 | directory.flags = Swap(uint32_t(0)); |
e0098838 JF |
1534 | directory.nSpecialSlots = Swap(special); |
1535 | directory.codeLimit = Swap(uint32_t(limit)); | |
1536 | directory.nCodeSlots = Swap(normal); | |
84d29a1c | 1537 | directory.hashSize = LDID_SHA1_DIGEST_LENGTH; |
e0098838 JF |
1538 | directory.hashType = CS_HASHTYPE_SHA1; |
1539 | directory.spare1 = 0x00; | |
b9652d6e | 1540 | directory.pageSize = PageShift_; |
e0098838 | 1541 | directory.spare2 = Swap(uint32_t(0)); |
b73d2333 JF |
1542 | directory.scatterOffset = Swap(uint32_t(0)); |
1543 | directory.spare3 = Swap(uint32_t(0)); | |
1544 | directory.codeLimit64 = Swap(uint64_t(0)); | |
1545 | ||
1546 | uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory)); | |
1547 | ||
1548 | directory.identOffset = Swap(uint32_t(offset)); | |
1549 | offset += identifier.size() + 1; | |
1550 | ||
1551 | if (team.empty()) | |
1552 | directory.teamIDOffset = Swap(uint32_t(0)); | |
1553 | else { | |
1554 | directory.teamIDOffset = Swap(uint32_t(offset)); | |
1555 | offset += team.size() + 1; | |
1556 | } | |
1557 | ||
1558 | offset += LDID_SHA1_DIGEST_LENGTH * special; | |
1559 | directory.hashOffset = Swap(uint32_t(offset)); | |
1560 | offset += LDID_SHA1_DIGEST_LENGTH * normal; | |
1561 | ||
e0098838 JF |
1562 | put(data, &directory, sizeof(directory)); |
1563 | ||
ffdd1183 | 1564 | put(data, identifier.c_str(), identifier.size() + 1); |
b73d2333 | 1565 | put(data, team.c_str(), team.size() + 1); |
e0098838 | 1566 | |
84d29a1c JF |
1567 | uint8_t storage[special + normal][LDID_SHA1_DIGEST_LENGTH]; |
1568 | uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = storage + special; | |
e0098838 JF |
1569 | |
1570 | memset(storage, 0, sizeof(*storage) * special); | |
4d4682ef JF |
1571 | |
1572 | _foreach (blob, blobs) { | |
e0098838 JF |
1573 | auto local(reinterpret_cast<const Blob *>(&blob.second[0])); |
1574 | sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length)); | |
4d4682ef | 1575 | } |
f4b2df35 | 1576 | |
e4d33eec | 1577 | _foreach (slot, posts) { |
e57b1f91 JF |
1578 | _assert(sizeof(*hashes) == slot.second.size()); |
1579 | memcpy(hashes - slot.first, slot.second.data(), slot.second.size()); | |
1580 | } | |
1581 | ||
e0098838 JF |
1582 | if (normal != 1) |
1583 | for (size_t i = 0; i != normal - 1; ++i) | |
b9652d6e | 1584 | sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_); |
e0098838 | 1585 | if (normal != 0) |
b9652d6e | 1586 | sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1); |
f4b2df35 | 1587 | |
e0098838 JF |
1588 | put(data, storage, sizeof(storage)); |
1589 | ||
8f310b91 | 1590 | insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data); |
f4b2df35 | 1591 | } |
e0098838 | 1592 | |
489c97b8 | 1593 | #ifndef LDID_NOSMIME |
30c64adb JF |
1594 | if (!key.empty()) { |
1595 | std::stringbuf data; | |
1596 | const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]); | |
1597 | ||
1598 | Stuff stuff(key); | |
1599 | Buffer bio(sign); | |
1600 | ||
1601 | Signature signature(stuff, sign); | |
1602 | Buffer result(signature); | |
1603 | std::string value(result); | |
1604 | put(data, value.data(), value.size()); | |
1605 | ||
1606 | insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data); | |
1607 | } | |
489c97b8 | 1608 | #endif |
30c64adb | 1609 | |
efad8a44 | 1610 | return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs); |
e0098838 JF |
1611 | })); |
1612 | } | |
1613 | ||
0326ab11 | 1614 | #ifndef LDID_NOTOOLS |
a0c715e9 | 1615 | static void Unsign(void *idata, size_t isize, std::streambuf &output) { |
e4d33eec | 1616 | Allocate(idata, isize, output, fun([](const MachHeader &mach_header, size_t size) -> size_t { |
e0098838 | 1617 | return 0; |
e4d33eec | 1618 | }), fun([](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t { |
e0098838 JF |
1619 | return 0; |
1620 | })); | |
f4b2df35 JF |
1621 | } |
1622 | ||
23c11ee8 JF |
1623 | std::string DiskFolder::Path(const std::string &path) { |
1624 | return path_ + "/" + path; | |
1625 | } | |
1626 | ||
1627 | DiskFolder::DiskFolder(const std::string &path) : | |
1628 | path_(path) | |
1629 | { | |
1630 | } | |
1631 | ||
1632 | DiskFolder::~DiskFolder() { | |
1633 | if (!std::uncaught_exception()) | |
1634 | for (const auto &commit : commit_) | |
1635 | Commit(commit.first, commit.second); | |
1636 | } | |
1637 | ||
54a0f854 JF |
1638 | 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) { |
1639 | std::string path(Path(root) + base); | |
1640 | ||
1641 | DIR *dir(opendir(path.c_str())); | |
1642 | _assert(dir != NULL); | |
1643 | _scope({ _syscall(closedir(dir)); }); | |
1644 | ||
1645 | while (auto child = readdir(dir)) { | |
261b9963 | 1646 | std::string name(child->d_name); |
54a0f854 JF |
1647 | if (name == "." || name == "..") |
1648 | continue; | |
1649 | if (Starts(name, ".ldid.")) | |
1650 | continue; | |
1651 | ||
b6d8da4e JF |
1652 | bool directory; |
1653 | ||
1654 | #ifdef __WIN32__ | |
1655 | struct stat info; | |
1656 | _syscall(stat(path.c_str(), &info)); | |
1657 | if (false); | |
1658 | else if (S_ISDIR(info.st_mode)) | |
1659 | directory = true; | |
1660 | else if (S_ISREG(info.st_mode)) | |
1661 | directory = false; | |
1662 | else | |
1663 | _assert_(false, "st_mode=%x", info.st_mode); | |
1664 | #else | |
54a0f854 JF |
1665 | switch (child->d_type) { |
1666 | case DT_DIR: | |
b6d8da4e JF |
1667 | directory = true; |
1668 | break; | |
54a0f854 | 1669 | case DT_REG: |
b6d8da4e JF |
1670 | directory = false; |
1671 | break; | |
54a0f854 JF |
1672 | default: |
1673 | _assert_(false, "d_type=%u", child->d_type); | |
54a0f854 | 1674 | } |
b6d8da4e JF |
1675 | #endif |
1676 | ||
1677 | if (directory) | |
1678 | Find(root, base + name + "/", code); | |
1679 | else | |
1680 | code(base + name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) { | |
1681 | std::string access(root + base + name); | |
fefcecb0 | 1682 | _assert_(Open(access, fun([&](std::streambuf &data, const void *flag) { |
b6d8da4e JF |
1683 | NullBuffer save; |
1684 | code(data, save); | |
1685 | })), "open(): %s", access.c_str()); | |
1686 | })); | |
54a0f854 JF |
1687 | } |
1688 | } | |
1689 | ||
fefcecb0 | 1690 | void DiskFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) { |
23c11ee8 JF |
1691 | std::filebuf save; |
1692 | auto from(Path(path)); | |
1693 | commit_[from] = Temporary(save, from); | |
1694 | code(save); | |
1695 | } | |
1696 | ||
fefcecb0 | 1697 | bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) { |
23c11ee8 JF |
1698 | std::filebuf data; |
1699 | auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in)); | |
1700 | if (result == NULL) | |
1701 | return false; | |
1702 | _assert(result == &data); | |
fefcecb0 | 1703 | code(data, NULL); |
23c11ee8 JF |
1704 | return true; |
1705 | } | |
1706 | ||
1707 | 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 | 1708 | Find(path, "", code); |
23c11ee8 | 1709 | } |
0326ab11 | 1710 | #endif |
23c11ee8 | 1711 | |
2443500c | 1712 | SubFolder::SubFolder(Folder &parent, const std::string &path) : |
23c11ee8 JF |
1713 | parent_(parent), |
1714 | path_(path) | |
1715 | { | |
1716 | } | |
1717 | ||
fefcecb0 JF |
1718 | void SubFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) { |
1719 | return parent_.Save(path_ + path, flag, code); | |
23c11ee8 JF |
1720 | } |
1721 | ||
fefcecb0 | 1722 | bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) { |
2443500c | 1723 | return parent_.Open(path_ + path, code); |
23c11ee8 JF |
1724 | } |
1725 | ||
1726 | 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 | 1727 | return parent_.Find(path_ + path, code); |
23c11ee8 JF |
1728 | } |
1729 | ||
7c49f771 JF |
1730 | std::string UnionFolder::Map(const std::string &path) { |
1731 | auto remap(remaps_.find(path)); | |
1732 | if (remap == remaps_.end()) | |
1733 | return path; | |
1734 | return remap->second; | |
1735 | } | |
1736 | ||
fefcecb0 | 1737 | 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 |
1738 | if (file.size() >= path.size() && file.substr(0, path.size()) == path) |
1739 | code(file.substr(path.size()), fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) { | |
fefcecb0 JF |
1740 | save(fun([&](std::streambuf &data, const void *flag) { |
1741 | parent_.Save(file, flag, fun([&](std::streambuf &save) { | |
1742 | code(data, save); | |
1743 | })); | |
7c49f771 JF |
1744 | })); |
1745 | })); | |
1746 | } | |
1747 | ||
886cb3f1 JF |
1748 | UnionFolder::UnionFolder(Folder &parent) : |
1749 | parent_(parent) | |
1750 | { | |
1751 | } | |
1752 | ||
fefcecb0 JF |
1753 | void UnionFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) { |
1754 | return parent_.Save(Map(path), flag, code); | |
886cb3f1 JF |
1755 | } |
1756 | ||
fefcecb0 | 1757 | bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) { |
7c49f771 JF |
1758 | auto file(resets_.find(path)); |
1759 | if (file == resets_.end()) | |
1760 | return parent_.Open(Map(path), code); | |
fefcecb0 | 1761 | auto &entry(file->second); |
886cb3f1 | 1762 | |
fefcecb0 | 1763 | auto &data(entry.first); |
886cb3f1 | 1764 | data.pubseekpos(0, std::ios::in); |
fefcecb0 | 1765 | code(data, entry.second); |
886cb3f1 JF |
1766 | return true; |
1767 | } | |
1768 | ||
1769 | void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) { | |
1770 | parent_.Find(path, fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &save) { | |
7c49f771 | 1771 | if (deletes_.find(path + name) == deletes_.end()) |
886cb3f1 JF |
1772 | code(name, save); |
1773 | })); | |
1774 | ||
7c49f771 | 1775 | for (auto &reset : resets_) |
fefcecb0 JF |
1776 | Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, const void *)> &code) { |
1777 | auto &entry(reset.second); | |
1778 | entry.first.pubseekpos(0, std::ios::in); | |
1779 | code(entry.first, entry.second); | |
7c49f771 JF |
1780 | })); |
1781 | ||
1782 | for (auto &remap : remaps_) | |
fefcecb0 JF |
1783 | Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, const void *)> &code) { |
1784 | parent_.Open(remap.second, fun([&](std::streambuf &data, const void *flag) { | |
1785 | code(data, flag); | |
886cb3f1 | 1786 | })); |
7c49f771 | 1787 | })); |
886cb3f1 JF |
1788 | } |
1789 | ||
0326ab11 | 1790 | #ifndef LDID_NOTOOLS |
23c11ee8 JF |
1791 | static size_t copy(std::streambuf &source, std::streambuf &target) { |
1792 | size_t total(0); | |
1793 | for (;;) { | |
1794 | char data[4096]; | |
1795 | size_t writ(source.sgetn(data, sizeof(data))); | |
1796 | if (writ == 0) | |
1797 | break; | |
1798 | _assert(target.sputn(data, writ) == writ); | |
1799 | total += writ; | |
1800 | } | |
1801 | return total; | |
1802 | } | |
1803 | ||
489c97b8 | 1804 | #ifndef LDID_NOPLIST |
8dfe0afc JF |
1805 | static plist_t plist(const std::string &data) { |
1806 | plist_t plist(NULL); | |
1807 | if (Starts(data, "bplist00")) | |
1808 | plist_from_bin(data.data(), data.size(), &plist); | |
1809 | else | |
1810 | plist_from_xml(data.data(), data.size(), &plist); | |
1811 | _assert(plist != NULL); | |
1812 | return plist; | |
23c11ee8 JF |
1813 | } |
1814 | ||
8dfe0afc | 1815 | static void plist_d(std::streambuf &buffer, const Functor<void (plist_t)> &code) { |
23c11ee8 JF |
1816 | std::stringbuf data; |
1817 | copy(buffer, data); | |
8dfe0afc JF |
1818 | auto node(plist(data.str())); |
1819 | _scope({ plist_free(node); }); | |
1820 | _assert(plist_get_node_type(node) == PLIST_DICT); | |
1821 | code(node); | |
23c11ee8 JF |
1822 | } |
1823 | ||
8dfe0afc JF |
1824 | static std::string plist_s(plist_t node) { |
1825 | _assert(node != NULL); | |
1826 | _assert(plist_get_node_type(node) == PLIST_STRING); | |
1827 | char *data; | |
1828 | plist_get_string_val(node, &data); | |
1829 | _scope({ free(data); }); | |
1830 | return data; | |
23c11ee8 | 1831 | } |
489c97b8 | 1832 | #endif |
23c11ee8 JF |
1833 | |
1834 | enum Mode { | |
1835 | NoMode, | |
1836 | OptionalMode, | |
1837 | OmitMode, | |
1838 | NestedMode, | |
1839 | TopMode, | |
1840 | }; | |
1841 | ||
1842 | class Expression { | |
1843 | private: | |
1844 | regex_t regex_; | |
1845 | ||
1846 | public: | |
1847 | Expression(const std::string &code) { | |
1848 | _assert_(regcomp(®ex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()"); | |
1849 | } | |
1850 | ||
1851 | ~Expression() { | |
1852 | regfree(®ex_); | |
1853 | } | |
1854 | ||
1855 | bool operator ()(const std::string &data) const { | |
1856 | auto value(regexec(®ex_, data.c_str(), 0, NULL, 0)); | |
1857 | if (value == REG_NOMATCH) | |
1858 | return false; | |
1859 | _assert_(value == 0, "regexec()"); | |
1860 | return true; | |
1861 | } | |
1862 | }; | |
1863 | ||
1864 | struct Rule { | |
1865 | unsigned weight_; | |
1866 | Mode mode_; | |
1867 | std::string code_; | |
1868 | ||
1869 | mutable std::auto_ptr<Expression> regex_; | |
1870 | ||
1871 | Rule(unsigned weight, Mode mode, const std::string &code) : | |
1872 | weight_(weight), | |
1873 | mode_(mode), | |
1874 | code_(code) | |
1875 | { | |
1876 | } | |
1877 | ||
1878 | Rule(const Rule &rhs) : | |
1879 | weight_(rhs.weight_), | |
1880 | mode_(rhs.mode_), | |
1881 | code_(rhs.code_) | |
1882 | { | |
1883 | } | |
1884 | ||
1885 | void Compile() const { | |
1886 | regex_.reset(new Expression(code_)); | |
1887 | } | |
1888 | ||
1889 | bool operator ()(const std::string &data) const { | |
1890 | _assert(regex_.get() != NULL); | |
1891 | return (*regex_)(data); | |
1892 | } | |
1893 | ||
1894 | bool operator <(const Rule &rhs) const { | |
1895 | if (weight_ > rhs.weight_) | |
1896 | return true; | |
1897 | if (weight_ < rhs.weight_) | |
1898 | return false; | |
1899 | return mode_ > rhs.mode_; | |
1900 | } | |
1901 | }; | |
1902 | ||
1903 | struct RuleCode { | |
1904 | bool operator ()(const Rule *lhs, const Rule *rhs) const { | |
1905 | return lhs->code_ < rhs->code_; | |
1906 | } | |
1907 | }; | |
1908 | ||
489c97b8 | 1909 | #ifndef LDID_NOPLIST |
ef3241bb | 1910 | static void Sign(std::streambuf &buffer, std::vector<char> &hash, std::streambuf &save, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) { |
7f5ad603 JF |
1911 | // XXX: this is a miserable fail |
1912 | std::stringbuf temp; | |
1913 | copy(buffer, temp); | |
1914 | auto data(temp.str()); | |
1915 | ||
1916 | HashProxy proxy(hash, save); | |
1917 | Sign(data.data(), data.size(), proxy, identifier, entitlements, key, slots); | |
1918 | } | |
1919 | ||
4d03333f | 1920 | 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) { |
23c11ee8 JF |
1921 | std::string executable; |
1922 | std::string identifier; | |
1923 | ||
1924 | static const std::string info("Info.plist"); | |
1925 | ||
fefcecb0 | 1926 | _assert_(folder.Open(info, fun([&](std::streambuf &buffer, const void *flag) { |
8dfe0afc JF |
1927 | plist_d(buffer, fun([&](plist_t node) { |
1928 | executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable")); | |
1929 | identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier")); | |
23c11ee8 JF |
1930 | })); |
1931 | })), "open(): Info.plist"); | |
1932 | ||
d9c2341d JF |
1933 | static const std::string directory("_CodeSignature/"); |
1934 | static const std::string signature(directory + "CodeResources"); | |
1935 | ||
23c11ee8 JF |
1936 | std::map<std::string, std::multiset<Rule>> versions; |
1937 | ||
1938 | auto &rules1(versions[""]); | |
1939 | auto &rules2(versions["2"]); | |
1940 | ||
fefcecb0 | 1941 | folder.Open(signature, fun([&](std::streambuf &buffer, const void *) { |
8dfe0afc | 1942 | plist_d(buffer, fun([&](plist_t node) { |
23c11ee8 JF |
1943 | // XXX: maybe attempt to preserve existing rules |
1944 | })); | |
1945 | })); | |
1946 | ||
1947 | if (true) { | |
1948 | rules1.insert(Rule{1, NoMode, "^"}); | |
1949 | rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"}); | |
1950 | rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"}); | |
1951 | rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"}); | |
1952 | rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"}); | |
1953 | rules1.insert(Rule{1, NoMode, "^version.plist$"}); | |
1954 | } | |
1955 | ||
1956 | if (true) { | |
1957 | rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"}); | |
1958 | rules2.insert(Rule{20, NoMode, "^"}); | |
1959 | rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"}); | |
1960 | rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"}); | |
1961 | rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"}); | |
1962 | rules2.insert(Rule{1, NoMode, "^.*"}); | |
1963 | rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"}); | |
1964 | rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"}); | |
1965 | rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"}); | |
1966 | rules2.insert(Rule{20, OmitMode, "^PkgInfo$"}); | |
1967 | rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"}); | |
1968 | rules2.insert(Rule{10, NestedMode, "^[^/]+$"}); | |
1969 | rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"}); | |
1970 | rules2.insert(Rule{20, NoMode, "^version\\.plist$"}); | |
1971 | } | |
1972 | ||
1973 | std::map<std::string, std::vector<char>> local; | |
1974 | ||
1975 | static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$"); | |
7f5ad603 | 1976 | static Expression dylib("^[^/]*\\.dylib$"); |
23c11ee8 JF |
1977 | |
1978 | folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) { | |
1979 | if (!nested(name)) | |
1980 | return; | |
1981 | auto bundle(root + Split(name).dir); | |
2443500c | 1982 | SubFolder subfolder(folder, bundle); |
4d03333f | 1983 | Bundle(bundle, subfolder, key, local, ""); |
23c11ee8 JF |
1984 | })); |
1985 | ||
1986 | folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) { | |
d9c2341d JF |
1987 | // BundleDiskRep::adjustResources -> builder.addExclusion |
1988 | if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources") | |
23c11ee8 JF |
1989 | return; |
1990 | ||
1991 | auto &hash(local[name]); | |
1992 | if (!hash.empty()) | |
1993 | return; | |
1994 | ||
1995 | code(fun([&](std::streambuf &data, std::streambuf &save) { | |
7f5ad603 JF |
1996 | if (dylib(name)) { |
1997 | Slots slots; | |
1998 | Sign(data, hash, save, identifier, "", key, slots); | |
1999 | } else { | |
2000 | HashProxy proxy(hash, save); | |
2001 | copy(data, proxy); | |
2002 | } | |
23c11ee8 JF |
2003 | })); |
2004 | ||
84d29a1c | 2005 | _assert(hash.size() == LDID_SHA1_DIGEST_LENGTH); |
23c11ee8 JF |
2006 | })); |
2007 | ||
8dfe0afc JF |
2008 | auto plist(plist_new_dict()); |
2009 | _scope({ plist_free(plist); }); | |
23c11ee8 JF |
2010 | |
2011 | for (const auto &version : versions) { | |
8dfe0afc JF |
2012 | auto files(plist_new_dict()); |
2013 | plist_dict_set_item(plist, ("files" + version.first).c_str(), files); | |
23c11ee8 JF |
2014 | |
2015 | for (const auto &rule : version.second) | |
2016 | rule.Compile(); | |
2017 | ||
2018 | for (const auto &hash : local) | |
2019 | for (const auto &rule : version.second) | |
2020 | if (rule(hash.first)) { | |
2021 | if (rule.mode_ == NoMode) | |
8dfe0afc | 2022 | plist_dict_set_item(files, hash.first.c_str(), plist_new_data(hash.second.data(), hash.second.size())); |
23c11ee8 | 2023 | else if (rule.mode_ == OptionalMode) { |
8dfe0afc JF |
2024 | auto entry(plist_new_dict()); |
2025 | plist_dict_set_item(entry, "hash", plist_new_data(hash.second.data(), hash.second.size())); | |
2026 | plist_dict_set_item(entry, "optional", plist_new_bool(true)); | |
2027 | plist_dict_set_item(files, hash.first.c_str(), entry); | |
23c11ee8 JF |
2028 | } |
2029 | ||
2030 | break; | |
2031 | } | |
23c11ee8 JF |
2032 | } |
2033 | ||
2034 | for (const auto &version : versions) { | |
8dfe0afc JF |
2035 | auto rules(plist_new_dict()); |
2036 | plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules); | |
23c11ee8 JF |
2037 | |
2038 | std::multiset<const Rule *, RuleCode> ordered; | |
2039 | for (const auto &rule : version.second) | |
2040 | ordered.insert(&rule); | |
2041 | ||
2042 | for (const auto &rule : ordered) | |
2043 | if (rule->weight_ == 1 && rule->mode_ == NoMode) | |
8dfe0afc | 2044 | plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true)); |
23c11ee8 | 2045 | else { |
8dfe0afc JF |
2046 | auto entry(plist_new_dict()); |
2047 | plist_dict_set_item(rules, rule->code_.c_str(), entry); | |
23c11ee8 JF |
2048 | |
2049 | switch (rule->mode_) { | |
2050 | case NoMode: | |
2051 | break; | |
2052 | case OmitMode: | |
8dfe0afc | 2053 | plist_dict_set_item(entry, "omit", plist_new_bool(true)); |
23c11ee8 JF |
2054 | break; |
2055 | case OptionalMode: | |
8dfe0afc | 2056 | plist_dict_set_item(entry, "optional", plist_new_bool(true)); |
23c11ee8 JF |
2057 | break; |
2058 | case NestedMode: | |
8dfe0afc | 2059 | plist_dict_set_item(entry, "nested", plist_new_bool(true)); |
23c11ee8 JF |
2060 | break; |
2061 | case TopMode: | |
8dfe0afc | 2062 | plist_dict_set_item(entry, "top", plist_new_bool(true)); |
23c11ee8 JF |
2063 | break; |
2064 | } | |
2065 | ||
2066 | if (rule->weight_ >= 10000) | |
8dfe0afc | 2067 | plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_)); |
23c11ee8 | 2068 | else if (rule->weight_ != 1) |
8dfe0afc | 2069 | plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_)); |
23c11ee8 | 2070 | } |
23c11ee8 JF |
2071 | } |
2072 | ||
fefcecb0 | 2073 | folder.Save(signature, NULL, fun([&](std::streambuf &save) { |
23c11ee8 | 2074 | HashProxy proxy(local[signature], save); |
8dfe0afc JF |
2075 | char *xml(NULL); |
2076 | uint32_t size; | |
2077 | plist_to_xml(plist, &xml, &size); | |
2078 | _scope({ free(xml); }); | |
2079 | put(proxy, xml, size); | |
23c11ee8 JF |
2080 | })); |
2081 | ||
fefcecb0 JF |
2082 | folder.Open(executable, fun([&](std::streambuf &buffer, const void *flag) { |
2083 | folder.Save(executable, flag, fun([&](std::streambuf &save) { | |
23c11ee8 JF |
2084 | Slots slots; |
2085 | slots[1] = local.at(info); | |
2086 | slots[3] = local.at(signature); | |
7f5ad603 | 2087 | Sign(buffer, local[executable], save, identifier, entitlements, key, slots); |
23c11ee8 JF |
2088 | })); |
2089 | })); | |
2090 | ||
2091 | for (const auto &hash : local) | |
2092 | remote[root + hash.first] = hash.second; | |
2093 | ||
2094 | return executable; | |
2095 | } | |
489c97b8 | 2096 | #endif |
23c11ee8 | 2097 | |
0326ab11 | 2098 | #endif |
a0c715e9 JF |
2099 | } |
2100 | ||
0326ab11 | 2101 | #ifndef LDID_NOTOOLS |
a7f01a65 | 2102 | int main(int argc, char *argv[]) { |
489c97b8 | 2103 | #ifndef LDID_NOSMIME |
30c64adb | 2104 | OpenSSL_add_all_algorithms(); |
489c97b8 | 2105 | #endif |
30c64adb | 2106 | |
5525a5a7 JF |
2107 | union { |
2108 | uint16_t word; | |
2109 | uint8_t byte[2]; | |
2110 | } endian = {1}; | |
2111 | ||
2112 | little_ = endian.byte[0]; | |
2113 | ||
20e7eb29 | 2114 | bool flag_r(false); |
9c83be90 | 2115 | bool flag_e(false); |
a362a82f | 2116 | |
fdbee693 | 2117 | #ifndef LDID_NOFLAGT |
a362a82f | 2118 | bool flag_T(false); |
fdbee693 | 2119 | #endif |
20c5f1e8 | 2120 | |
fdb119ef | 2121 | bool flag_S(false); |
20c5f1e8 | 2122 | bool flag_s(false); |
a362a82f | 2123 | |
c0cc1574 | 2124 | bool flag_D(false); |
c0cc1574 | 2125 | |
8c417842 JF |
2126 | bool flag_A(false); |
2127 | bool flag_a(false); | |
2128 | ||
56f0487d JF |
2129 | bool flag_u(false); |
2130 | ||
c0cc1574 JF |
2131 | uint32_t flag_CPUType(_not(uint32_t)); |
2132 | uint32_t flag_CPUSubtype(_not(uint32_t)); | |
2133 | ||
5d7ceb5d JF |
2134 | const char *flag_I(NULL); |
2135 | ||
fdbee693 | 2136 | #ifndef LDID_NOFLAGT |
a362a82f JF |
2137 | bool timeh(false); |
2138 | uint32_t timev(0); | |
fdbee693 | 2139 | #endif |
a362a82f | 2140 | |
4d4682ef | 2141 | Map entitlements; |
30c64adb | 2142 | Map key; |
a0c715e9 | 2143 | ldid::Slots slots; |
c05d9758 | 2144 | |
a362a82f JF |
2145 | std::vector<std::string> files; |
2146 | ||
a960f392 JF |
2147 | if (argc == 1) { |
2148 | fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]); | |
9c83be90 | 2149 | fprintf(stderr, " %s -e MobileSafari\n", argv[0]); |
a960f392 JF |
2150 | fprintf(stderr, " %s -S cat\n", argv[0]); |
2151 | fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]); | |
2152 | exit(0); | |
2153 | } | |
2154 | ||
a362a82f JF |
2155 | for (int argi(1); argi != argc; ++argi) |
2156 | if (argv[argi][0] != '-') | |
2157 | files.push_back(argv[argi]); | |
2158 | else switch (argv[argi][1]) { | |
fac3d3e3 JF |
2159 | case 'r': |
2160 | _assert(!flag_s); | |
2161 | _assert(!flag_S); | |
2162 | flag_r = true; | |
2163 | break; | |
2164 | ||
9c83be90 | 2165 | case 'e': flag_e = true; break; |
c05d9758 | 2166 | |
e57b1f91 JF |
2167 | case 'E': { |
2168 | const char *slot = argv[argi] + 2; | |
2169 | const char *colon = strchr(slot, ':'); | |
2170 | _assert(colon != NULL); | |
2171 | Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
2172 | char *arge; | |
2173 | unsigned number(strtoul(slot, &arge, 0)); | |
2174 | _assert(arge == colon); | |
707027e8 | 2175 | sha1(slots[number], file.data(), file.size()); |
e57b1f91 JF |
2176 | } break; |
2177 | ||
c0cc1574 | 2178 | case 'D': flag_D = true; break; |
c0cc1574 | 2179 | |
8c417842 JF |
2180 | case 'a': flag_a = true; break; |
2181 | ||
2182 | case 'A': | |
fac3d3e3 | 2183 | _assert(!flag_A); |
8c417842 JF |
2184 | flag_A = true; |
2185 | if (argv[argi][2] != '\0') { | |
2186 | const char *cpu = argv[argi] + 2; | |
2187 | const char *colon = strchr(cpu, ':'); | |
2188 | _assert(colon != NULL); | |
2189 | char *arge; | |
2190 | flag_CPUType = strtoul(cpu, &arge, 0); | |
2191 | _assert(arge == colon); | |
2192 | flag_CPUSubtype = strtoul(colon + 1, &arge, 0); | |
2193 | _assert(arge == argv[argi] + strlen(argv[argi])); | |
2194 | } | |
2195 | break; | |
2196 | ||
20c5f1e8 | 2197 | case 's': |
fac3d3e3 | 2198 | _assert(!flag_r); |
20c5f1e8 JF |
2199 | _assert(!flag_S); |
2200 | flag_s = true; | |
2201 | break; | |
2202 | ||
c05d9758 | 2203 | case 'S': |
fac3d3e3 | 2204 | _assert(!flag_r); |
20c5f1e8 | 2205 | _assert(!flag_s); |
c05d9758 JF |
2206 | flag_S = true; |
2207 | if (argv[argi][2] != '\0') { | |
2208 | const char *xml = argv[argi] + 2; | |
4d4682ef | 2209 | entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE); |
c05d9758 JF |
2210 | } |
2211 | break; | |
a362a82f | 2212 | |
30c64adb | 2213 | case 'K': |
d73a3d58 JF |
2214 | if (argv[argi][2] != '\0') |
2215 | key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
30c64adb JF |
2216 | break; |
2217 | ||
fdbee693 | 2218 | #ifndef LDID_NOFLAGT |
a362a82f JF |
2219 | case 'T': { |
2220 | flag_T = true; | |
2221 | if (argv[argi][2] == '-') | |
2222 | timeh = true; | |
2223 | else { | |
2224 | char *arge; | |
2225 | timev = strtoul(argv[argi] + 2, &arge, 0); | |
2226 | _assert(arge == argv[argi] + strlen(argv[argi])); | |
2227 | } | |
2228 | } break; | |
fdbee693 | 2229 | #endif |
a362a82f | 2230 | |
56f0487d JF |
2231 | case 'u': { |
2232 | flag_u = true; | |
2233 | } break; | |
2234 | ||
5d7ceb5d JF |
2235 | case 'I': { |
2236 | flag_I = argv[argi] + 2; | |
2237 | } break; | |
2238 | ||
a362a82f JF |
2239 | default: |
2240 | goto usage; | |
2241 | break; | |
2242 | } | |
2243 | ||
fac3d3e3 JF |
2244 | _assert(flag_S || key.empty()); |
2245 | _assert(flag_S || flag_I == NULL); | |
f4b2df35 | 2246 | |
a362a82f JF |
2247 | if (files.empty()) usage: { |
2248 | exit(0); | |
2249 | } | |
2250 | ||
2251 | size_t filei(0), filee(0); | |
2252 | _foreach (file, files) try { | |
d4187e53 | 2253 | std::string path(file); |
5d7ceb5d | 2254 | |
23c11ee8 JF |
2255 | struct stat info; |
2256 | _syscall(stat(path.c_str(), &info)); | |
8762082f | 2257 | |
23c11ee8 | 2258 | if (S_ISDIR(info.st_mode)) { |
489c97b8 | 2259 | #ifndef LDID_NOPLIST |
23c11ee8 JF |
2260 | _assert(!flag_r); |
2261 | ldid::DiskFolder folder(path); | |
2262 | std::map<std::string, std::vector<char>> hashes; | |
4d03333f | 2263 | path += "/" + Bundle("", folder, key, hashes, entitlements); |
489c97b8 JF |
2264 | #else |
2265 | _assert(false); | |
2266 | #endif | |
23c11ee8 JF |
2267 | } else if (flag_S || flag_r) { |
2268 | Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE); | |
8762082f | 2269 | |
4d4682ef | 2270 | std::filebuf output; |
23c11ee8 JF |
2271 | Split split(path); |
2272 | auto temp(Temporary(output, split)); | |
4d4682ef | 2273 | |
e0098838 | 2274 | if (flag_r) |
a0c715e9 | 2275 | ldid::Unsign(input.data(), input.size(), output); |
8762082f | 2276 | else { |
23c11ee8 | 2277 | std::string identifier(flag_I ?: split.base.c_str()); |
ffdd1183 | 2278 | ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots); |
8762082f | 2279 | } |
34f4c1d8 | 2280 | |
d4187e53 | 2281 | Commit(path, temp); |
fdb119ef JF |
2282 | } |
2283 | ||
fdbee693 JF |
2284 | bool modify(false); |
2285 | #ifndef LDID_NOFLAGT | |
2286 | if (flag_T) | |
2287 | modify = true; | |
2288 | #endif | |
2289 | if (flag_s) | |
2290 | modify = true; | |
2291 | ||
2292 | Map mapping(path, modify); | |
dede6121 | 2293 | FatHeader fat_header(mapping.data(), mapping.size()); |
a362a82f | 2294 | |
0a033524 | 2295 | _foreach (mach_header, fat_header.GetMachHeaders()) { |
d840a088 | 2296 | struct linkedit_data_command *signature(NULL); |
7b496abd JF |
2297 | struct encryption_info_command *encryption(NULL); |
2298 | ||
8c417842 JF |
2299 | if (flag_A) { |
2300 | if (mach_header.GetCPUType() != flag_CPUType) | |
2301 | continue; | |
2302 | if (mach_header.GetCPUSubtype() != flag_CPUSubtype) | |
2303 | continue; | |
2304 | } | |
2305 | ||
2306 | if (flag_a) | |
2307 | printf("cpu=0x%x:0x%x\n", mach_header.GetCPUType(), mach_header.GetCPUSubtype()); | |
2308 | ||
0a033524 JF |
2309 | _foreach (load_command, mach_header.GetLoadCommands()) { |
2310 | uint32_t cmd(mach_header.Swap(load_command->cmd)); | |
2311 | ||
cad40c43 | 2312 | if (false); |
0a033524 JF |
2313 | else if (cmd == LC_CODE_SIGNATURE) |
2314 | signature = reinterpret_cast<struct linkedit_data_command *>(load_command); | |
843aea8c | 2315 | else if (cmd == LC_ENCRYPTION_INFO || cmd == LC_ENCRYPTION_INFO_64) |
7b496abd | 2316 | encryption = reinterpret_cast<struct encryption_info_command *>(load_command); |
56f0487d JF |
2317 | else if (cmd == LC_LOAD_DYLIB) { |
2318 | volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command)); | |
2319 | const char *name(reinterpret_cast<const char *>(load_command) + mach_header.Swap(dylib_command->dylib.name)); | |
2320 | ||
2321 | if (strcmp(name, "/System/Library/Frameworks/UIKit.framework/UIKit") == 0) { | |
2322 | if (flag_u) { | |
2323 | Version version; | |
2324 | version.value = mach_header.Swap(dylib_command->dylib.current_version); | |
2325 | printf("uikit=%u.%u.%u\n", version.major, version.minor, version.patch); | |
2326 | } | |
2327 | } | |
2328 | } | |
fdbee693 | 2329 | #ifndef LDID_NOFLAGT |
cad40c43 | 2330 | else if (cmd == LC_ID_DYLIB) { |
0a033524 | 2331 | volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(load_command)); |
a362a82f | 2332 | |
0a033524 JF |
2333 | if (flag_T) { |
2334 | uint32_t timed; | |
a362a82f | 2335 | |
0a033524 JF |
2336 | if (!timeh) |
2337 | timed = timev; | |
2338 | else { | |
2339 | dylib_command->dylib.timestamp = 0; | |
2340 | timed = hash(reinterpret_cast<uint8_t *>(mach_header.GetBase()), mach_header.GetSize(), timev); | |
2341 | } | |
a362a82f | 2342 | |
0a033524 JF |
2343 | dylib_command->dylib.timestamp = mach_header.Swap(timed); |
2344 | } | |
7b496abd | 2345 | } |
fdbee693 | 2346 | #endif |
7b496abd JF |
2347 | } |
2348 | ||
7b496abd JF |
2349 | if (flag_D) { |
2350 | _assert(encryption != NULL); | |
2351 | encryption->cryptid = mach_header.Swap(0); | |
a362a82f | 2352 | } |
a362a82f | 2353 | |
0a033524 JF |
2354 | if (flag_e) { |
2355 | _assert(signature != NULL); | |
9c83be90 | 2356 | |
0a033524 | 2357 | uint32_t data = mach_header.Swap(signature->dataoff); |
9c83be90 | 2358 | |
0a033524 JF |
2359 | uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase()); |
2360 | uint8_t *blob = top + data; | |
2361 | struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob); | |
9c83be90 | 2362 | |
0a033524 JF |
2363 | for (size_t index(0); index != Swap(super->count); ++index) |
2364 | if (Swap(super->index[index].type) == CSSLOT_ENTITLEMENTS) { | |
2365 | uint32_t begin = Swap(super->index[index].offset); | |
2366 | struct Blob *entitlements = reinterpret_cast<struct Blob *>(blob + begin); | |
b9652d6e | 2367 | fwrite(entitlements + 1, 1, Swap(entitlements->length) - sizeof(*entitlements), stdout); |
0a033524 JF |
2368 | } |
2369 | } | |
9c83be90 | 2370 | |
0a033524 JF |
2371 | if (flag_s) { |
2372 | _assert(signature != NULL); | |
20c5f1e8 | 2373 | |
0a033524 | 2374 | uint32_t data = mach_header.Swap(signature->dataoff); |
20c5f1e8 | 2375 | |
0a033524 JF |
2376 | uint8_t *top = reinterpret_cast<uint8_t *>(mach_header.GetBase()); |
2377 | uint8_t *blob = top + data; | |
2378 | struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob); | |
20c5f1e8 | 2379 | |
0a033524 JF |
2380 | for (size_t index(0); index != Swap(super->count); ++index) |
2381 | if (Swap(super->index[index].type) == CSSLOT_CODEDIRECTORY) { | |
2382 | uint32_t begin = Swap(super->index[index].offset); | |
2383 | struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin); | |
20c5f1e8 | 2384 | |
84d29a1c | 2385 | uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = reinterpret_cast<uint8_t (*)[LDID_SHA1_DIGEST_LENGTH]>(blob + begin + Swap(directory->hashOffset)); |
0a033524 | 2386 | uint32_t pages = Swap(directory->nCodeSlots); |
20c5f1e8 | 2387 | |
0a033524 JF |
2388 | if (pages != 1) |
2389 | for (size_t i = 0; i != pages - 1; ++i) | |
b9652d6e | 2390 | sha1(hashes[i], top + PageSize_ * i, PageSize_); |
0a033524 | 2391 | if (pages != 0) |
b9652d6e | 2392 | sha1(hashes[pages - 1], top + PageSize_ * (pages - 1), ((data - 1) % PageSize_) + 1); |
0a033524 JF |
2393 | } |
2394 | } | |
fdb119ef JF |
2395 | } |
2396 | ||
a362a82f JF |
2397 | ++filei; |
2398 | } catch (const char *) { | |
2399 | ++filee; | |
2400 | ++filei; | |
2401 | } | |
2402 | ||
2403 | return filee; | |
2404 | } | |
0326ab11 | 2405 | #endif |