]> git.cameronkatri.com Git - ldid.git/blob - ldid.cpp
Maintain permissions during codehashing.
[ldid.git] / ldid.cpp
1 /* JocStrap - Java/Objective-C Bootstrap
2 * Copyright (C) 2007 Jay Freeman (saurik)
3 */
4
5 /*
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
9 *
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
17 * distribution.
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 */
37
38 #include "minimal/stdlib.h"
39 #include "minimal/mapping.h"
40
41 #include "sha1.h"
42
43 #include <cstring>
44 #include <string>
45 #include <vector>
46
47 #include <sys/wait.h>
48 #include <sys/types.h>
49 #include <sys/stat.h>
50
51 struct fat_header {
52 uint32_t magic;
53 uint32_t nfat_arch;
54 };
55
56 #define FAT_MAGIC 0xcafebabe
57 #define FAT_CIGAM 0xbebafeca
58
59 struct fat_arch {
60 uint32_t cputype;
61 uint32_t cpusubtype;
62 uint32_t offset;
63 uint32_t size;
64 uint32_t align;
65 };
66
67 struct mach_header {
68 uint32_t magic;
69 uint32_t cputype;
70 uint32_t cpusubtype;
71 uint32_t filetype;
72 uint32_t ncmds;
73 uint32_t sizeofcmds;
74 uint32_t flags;
75 };
76
77 #define MH_MAGIC 0xfeedface
78 #define MH_CIGAM 0xcefaedfe
79
80 #define MH_EXECUTE 0x2
81 #define MH_DYLIB 0x6
82 #define MH_BUNDLE 0x8
83
84 struct load_command {
85 uint32_t cmd;
86 uint32_t cmdsize;
87 };
88
89 #define LC_REQ_DYLD 0x80000000
90
91 #define LC_LOAD_DYLIB 0x0c
92 #define LC_ID_DYLIB 0x0d
93 #define LC_UUID 0x1b
94 #define LC_CODE_SIGNATURE 0x1d
95 #define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD)
96
97 struct dylib {
98 uint32_t name;
99 uint32_t timestamp;
100 uint32_t current_version;
101 uint32_t compatibility_version;
102 };
103
104 struct dylib_command {
105 uint32_t cmd;
106 uint32_t cmdsize;
107 struct dylib dylib;
108 };
109
110 struct uuid_command {
111 uint32_t cmd;
112 uint32_t cmdsize;
113 uint8_t uuid[16];
114 };
115
116 struct linkedit_data_command {
117 uint32_t cmd;
118 uint32_t cmdsize;
119 uint32_t dataoff;
120 uint32_t datasize;
121 };
122
123 uint16_t Swap_(uint16_t value) {
124 return
125 ((value >> 8) & 0x00ff) |
126 ((value << 8) & 0xff00);
127 }
128
129 uint32_t Swap_(uint32_t value) {
130 value = ((value >> 8) & 0x00ff00ff) |
131 ((value << 8) & 0xff00ff00);
132 value = ((value >> 16) & 0x0000ffff) |
133 ((value << 16) & 0xffff0000);
134 return value;
135 }
136
137 int16_t Swap_(int16_t value) {
138 return Swap_(static_cast<uint16_t>(value));
139 }
140
141 int32_t Swap_(int32_t value) {
142 return Swap_(static_cast<uint32_t>(value));
143 }
144
145 uint16_t Swap(uint16_t value) {
146 return true ? Swap_(value) : value;
147 }
148
149 uint32_t Swap(uint32_t value) {
150 return true ? Swap_(value) : value;
151 }
152
153 int16_t Swap(int16_t value) {
154 return Swap(static_cast<uint16_t>(value));
155 }
156
157 int32_t Swap(int32_t value) {
158 return Swap(static_cast<uint32_t>(value));
159 }
160
161 class Framework {
162 private:
163 void *base_;
164 size_t size_;
165 mach_header *mach_header_;
166 bool swapped_;
167
168 public:
169 uint16_t Swap(uint16_t value) const {
170 return swapped_ ? Swap_(value) : value;
171 }
172
173 uint32_t Swap(uint32_t value) const {
174 return swapped_ ? Swap_(value) : value;
175 }
176
177 int16_t Swap(int16_t value) const {
178 return Swap(static_cast<uint16_t>(value));
179 }
180
181 int32_t Swap(int32_t value) const {
182 return Swap(static_cast<uint32_t>(value));
183 }
184
185 Framework(const char *framework_path) :
186 swapped_(false)
187 {
188 base_ = map(framework_path, 0, _not(size_t), &size_, false);
189 fat_header *fat_header = reinterpret_cast<struct fat_header *>(base_);
190
191 if (Swap(fat_header->magic) == FAT_CIGAM) {
192 swapped_ = !swapped_;
193 goto fat;
194 } else if (Swap(fat_header->magic) != FAT_MAGIC)
195 mach_header_ = (mach_header *) base_;
196 else fat: {
197 size_t fat_narch = Swap(fat_header->nfat_arch);
198 fat_arch *fat_arch = reinterpret_cast<struct fat_arch *>(fat_header + 1);
199 size_t arch;
200 for (arch = 0; arch != fat_narch; ++arch) {
201 uint32_t arch_offset = Swap(fat_arch->offset);
202 mach_header_ = (mach_header *) ((uint8_t *) base_ + arch_offset);
203 goto found;
204 ++fat_arch;
205 }
206
207 _assert(false);
208 }
209
210 found:
211 if (Swap(mach_header_->magic) == MH_CIGAM)
212 swapped_ = !swapped_;
213 else _assert(Swap(mach_header_->magic) == MH_MAGIC);
214
215 _assert(
216 Swap(mach_header_->filetype) == MH_EXECUTE ||
217 Swap(mach_header_->filetype) == MH_DYLIB ||
218 Swap(mach_header_->filetype) == MH_BUNDLE
219 );
220 }
221
222 struct mach_header *operator ->() const {
223 return mach_header_;
224 }
225
226 void *GetBase() {
227 return base_;
228 }
229
230 size_t GetSize() {
231 return size_;
232 }
233
234 std::vector<struct load_command *> GetLoadCommands() {
235 std::vector<struct load_command *> load_commands;
236
237 struct load_command *load_command = reinterpret_cast<struct load_command *>(mach_header_ + 1);
238 for (uint32_t cmd = 0; cmd != Swap(mach_header_->ncmds); ++cmd) {
239 load_commands.push_back(load_command);
240 load_command = (struct load_command *) ((uint8_t *) load_command + Swap(load_command->cmdsize));
241 }
242
243 return load_commands;
244 }
245 };
246
247 #define CSMAGIC_CODEDIRECTORY 0xfade0c02
248 #define CSMAGIC_EMBEDDED_SIGNATURE 0xfade0cc0
249 #define CSSLOT_CODEDIRECTORY 0
250 #define CSSLOT_REQUIREMENTS 2
251
252 struct BlobIndex {
253 uint32_t type;
254 uint32_t offset;
255 };
256
257 struct SuperBlob {
258 uint32_t magic;
259 uint32_t length;
260 uint32_t count;
261 struct BlobIndex index[];
262 };
263
264 struct CodeDirectory {
265 uint32_t magic;
266 uint32_t length;
267 uint32_t version;
268 uint32_t flags;
269 uint32_t hashOffset;
270 uint32_t identOffset;
271 uint32_t nSpecialSlots;
272 uint32_t nCodeSlots;
273 uint32_t codeLimit;
274 uint8_t hashSize;
275 uint8_t hashType;
276 uint8_t spare1;
277 uint8_t pageSize;
278 uint32_t spare2;
279 };
280
281 extern "C" uint32_t hash(uint8_t *k, uint32_t length, uint32_t initval);
282
283 #define CODESIGN_ALLOCATE "arm-apple-darwin9-codesign_allocate"
284
285 void sha1(uint8_t *hash, uint8_t *data, size_t size) {
286 SHA1Context context;
287 SHA1Reset(&context);
288 SHA1Input(&context, data, size);
289 SHA1Result(&context, hash);
290 }
291
292 int main(int argc, const char *argv[]) {
293 bool flag_R(false);
294 bool flag_t(false);
295 bool flag_p(false);
296 bool flag_u(false);
297
298 bool flag_T(false);
299 bool flag_S(false);
300
301 bool timeh(false);
302 uint32_t timev(0);
303
304 std::vector<std::string> files;
305
306 _assert(argc != 0);
307 for (int argi(1); argi != argc; ++argi)
308 if (argv[argi][0] != '-')
309 files.push_back(argv[argi]);
310 else switch (argv[argi][1]) {
311 case 'R': flag_R = true; break;
312 case 't': flag_t = true; break;
313 case 'u': flag_u = true; break;
314 case 'p': flag_p = true; break;
315 case 'S': flag_S = true; break;
316
317 case 'T': {
318 flag_T = true;
319 if (argv[argi][2] == '-')
320 timeh = true;
321 else {
322 char *arge;
323 timev = strtoul(argv[argi] + 2, &arge, 0);
324 _assert(arge == argv[argi] + strlen(argv[argi]));
325 }
326 } break;
327
328 default:
329 goto usage;
330 break;
331 }
332
333 if (files.empty()) usage: {
334 exit(0);
335 }
336
337 size_t filei(0), filee(0);
338 _foreach (file, files) try {
339 const char *path(file->c_str());
340 const char *base = strrchr(path, '/');
341 char *temp(NULL), *dir;
342 mode_t mode = 0;
343
344 if (base != NULL)
345 dir = strndup(path, base++ - path + 1);
346 else {
347 dir = strdup("");
348 base = path;
349 }
350
351 if (flag_S) {
352 asprintf(&temp, "%s.%s.cs", dir, base);
353 const char *allocate = getenv("CODESIGN_ALLOCATE");
354 if (allocate == NULL)
355 allocate = "codesign_allocate";
356
357 size_t size = _not(size_t);
358 const char *arch; {
359 Framework framework(path);
360 _foreach (load_command, framework.GetLoadCommands()) {
361 uint32_t cmd(framework.Swap((*load_command)->cmd));
362 if (cmd == LC_CODE_SIGNATURE) {
363 struct linkedit_data_command *signature = reinterpret_cast<struct linkedit_data_command *>(*load_command);
364 size = framework.Swap(signature->dataoff);
365 _assert(size < framework.GetSize());
366 break;
367 }
368 }
369
370 if (size == _not(size_t))
371 size = framework.GetSize();
372
373 switch (framework->cputype) {
374 case 12: switch (framework->cpusubtype) {
375 case 0: arch = "arm"; break;
376 case 6: arch = "armv6"; break;
377 default: arch = NULL; break;
378 } break;
379
380 default: arch = NULL; break;
381 }
382 }
383
384 _assert(arch != NULL);
385
386 pid_t pid = fork();
387 _syscall(pid);
388 if (pid == 0) {
389 char *ssize;
390 asprintf(&ssize, "%u", (sizeof(struct SuperBlob) + 2 * sizeof(struct BlobIndex) + sizeof(struct CodeDirectory) + strlen(base) + 1 + (size + 0x1000 - 1) / 0x1000 * 0x14 + 0xc + 15) / 16 * 16);
391 execlp(allocate, allocate, "-i", path, "-a", arch, ssize, "-o", temp, NULL);
392 _assert(false);
393 }
394
395 int status;
396 _syscall(waitpid(pid, &status, 0));
397 _assert(WIFEXITED(status));
398 _assert(WEXITSTATUS(status) == 0);
399 }
400
401 Framework framework(temp == NULL ? path : temp);
402 struct linkedit_data_command *signature(NULL);
403
404 if (flag_p)
405 printf("path%zu='%s'\n", filei, file->c_str());
406
407 _foreach (load_command, framework.GetLoadCommands()) {
408 uint32_t cmd(framework.Swap((*load_command)->cmd));
409
410 if (flag_R && cmd == LC_REEXPORT_DYLIB)
411 (*load_command)->cmd = framework.Swap(LC_LOAD_DYLIB);
412 else if (cmd == LC_CODE_SIGNATURE)
413 signature = reinterpret_cast<struct linkedit_data_command *>(*load_command);
414 else if (cmd == LC_UUID) {
415 volatile struct uuid_command *uuid_command(reinterpret_cast<struct uuid_command *>(*load_command));
416
417 if (flag_u) {
418 printf("uuid%zu=%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x\n", filei,
419 uuid_command->uuid[ 0], uuid_command->uuid[ 1], uuid_command->uuid[ 2], uuid_command->uuid[ 3],
420 uuid_command->uuid[ 4], uuid_command->uuid[ 5], uuid_command->uuid[ 6], uuid_command->uuid[ 7],
421 uuid_command->uuid[ 8], uuid_command->uuid[ 9], uuid_command->uuid[10], uuid_command->uuid[11],
422 uuid_command->uuid[12], uuid_command->uuid[13], uuid_command->uuid[14], uuid_command->uuid[15]
423 );
424 }
425 } else if (cmd == LC_ID_DYLIB) {
426 volatile struct dylib_command *dylib_command(reinterpret_cast<struct dylib_command *>(*load_command));
427
428 if (flag_t)
429 printf("time%zu=0x%.8x\n", filei, framework.Swap(dylib_command->dylib.timestamp));
430
431 if (flag_T) {
432 uint32_t timed;
433
434 if (!timeh)
435 timed = timev;
436 else {
437 dylib_command->dylib.timestamp = 0;
438 timed = hash(reinterpret_cast<uint8_t *>(framework.GetBase()), framework.GetSize(), timev);
439 }
440
441 dylib_command->dylib.timestamp = framework.Swap(timed);
442 }
443 }
444 }
445
446 if (flag_S) {
447 _assert(signature != NULL);
448
449 uint32_t data = framework.Swap(signature->dataoff);
450 uint32_t size = framework.Swap(signature->datasize);
451
452 uint8_t *top = reinterpret_cast<uint8_t *>(framework.GetBase());
453 uint8_t *blob = top + data;
454 struct SuperBlob *super = reinterpret_cast<struct SuperBlob *>(blob);
455 super->magic = Swap(CSMAGIC_EMBEDDED_SIGNATURE);
456
457 uint32_t count = 2;
458 uint32_t offset = sizeof(struct SuperBlob) + count * sizeof(struct BlobIndex);
459
460 super->index[0].type = Swap(CSSLOT_CODEDIRECTORY);
461 super->index[0].offset = Swap(offset);
462
463 uint32_t begin = offset;
464 struct CodeDirectory *directory = reinterpret_cast<struct CodeDirectory *>(blob + begin);
465 offset += sizeof(struct CodeDirectory);
466
467 directory->magic = Swap(CSMAGIC_CODEDIRECTORY);
468 directory->version = Swap(0x00020001);
469 directory->flags = Swap(0);
470 directory->codeLimit = Swap(data);
471 directory->hashSize = 0x14;
472 directory->hashType = 0x01;
473 directory->spare1 = 0x00;
474 directory->pageSize = 0x0c;
475 directory->spare2 = Swap(0);
476
477 directory->identOffset = Swap(offset - begin);
478 strcpy(reinterpret_cast<char *>(blob + offset), base);
479 offset += strlen(base) + 1;
480
481 uint8_t (*hashes)[20] = reinterpret_cast<uint8_t (*)[20]>(blob + offset);
482 uint32_t special = 0;
483
484 uint32_t pages = (data + 0x1000 - 1) / 0x1000;
485 directory->nSpecialSlots = Swap(special);
486 directory->nCodeSlots = Swap(pages);
487
488 if (pages != 1)
489 for (size_t i = 0; i != pages - 1; ++i)
490 sha1(hashes[special + i], top + 0x1000 * i, 0x1000);
491 if (pages != 0)
492 sha1(hashes[special + pages - 1], top + 0x1000 * (pages - 1), data % 0x1000);
493
494 directory->hashOffset = Swap(offset - begin);
495 offset += sizeof(*hashes) * (special + pages);
496 directory->length = Swap(offset - begin);
497
498 super->index[1].type = Swap(CSSLOT_REQUIREMENTS);
499 super->index[1].offset = Swap(offset);
500
501 memcpy(blob + offset, "\xfa\xde\x0c\x01\x00\x00\x00\x0c\x00\x00\x00\x00", 0xc);
502 offset += 0xc;
503
504 super->count = Swap(count);
505 super->length = Swap(offset);
506
507 _assert(offset <= size);
508 memset(blob + offset, 0, size - offset);
509 }
510
511 if (temp) {
512 struct stat info;
513 _syscall(stat(path, &info));
514 _syscall(chown(temp, info.st_uid, info.st_gid));
515 _syscall(chmod(temp, info.st_mode));
516 _syscall(unlink(path));
517 _syscall(rename(temp, path));
518 free(temp);
519 }
520
521 free(dir);
522 ++filei;
523 } catch (const char *) {
524 ++filee;
525 ++filei;
526 }
527
528 return filee;
529 }