update Chinese(Simplified) translation
[maemo-rb.git] / utils / imxtools / sbtools / sbtoelf.c
blobe68f5e6e0618cd4f201f59596106333b174482e1
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2010 Bertrik Sikken
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
23 * .sb file parser and chunk extractor
25 * Based on amsinfo, which is
26 * Copyright © 2008 Rafaël Carré <rafael.carre@gmail.com>
29 #define _ISOC99_SOURCE /* snprintf() */
30 #include <stdio.h>
31 #include <errno.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <time.h>
36 #include <stdarg.h>
37 #include <strings.h>
38 #include <getopt.h>
40 #include "crypto.h"
41 #include "elf.h"
42 #include "sb.h"
43 #include "sb1.h"
44 #include "misc.h"
46 /* all blocks are sized as a multiple of 0x1ff */
47 #define PAD_TO_BOUNDARY(x) (((x) + 0x1ff) & ~0x1ff)
49 /* If you find a firmware that breaks the known format ^^ */
50 #define assert(a) do { if(!(a)) { fprintf(stderr,"Assertion \"%s\" failed in %s() line %d!\n\nPlease send us your firmware!\n",#a,__func__,__LINE__); exit(1); } } while(0)
52 #define crypto_cbc(...) \
53 do { int ret = crypto_cbc(__VA_ARGS__); \
54 if(ret != CRYPTO_ERROR_SUCCESS) \
55 bug("crypto_cbc error: %d\n", ret); \
56 }while(0)
58 /* globals */
60 static char *g_out_prefix;
61 static bool g_elf_simplify = true;
63 static void elf_printf(void *user, bool error, const char *fmt, ...)
65 if(!g_debug && !error)
66 return;
67 (void) user;
68 va_list args;
69 va_start(args, fmt);
70 vprintf(fmt, args);
71 va_end(args);
74 static void elf_write(void *user, uint32_t addr, const void *buf, size_t count)
76 FILE *f = user;
77 fseek(f, addr, SEEK_SET);
78 fwrite(buf, count, 1, f);
81 static void extract_elf_section(struct elf_params_t *elf, int count, uint32_t id)
83 char name[5];
84 char *filename = xmalloc(strlen(g_out_prefix) + 32);
85 sb_fill_section_name(name, id);
86 sprintf(filename, "%s%s.%d.elf", g_out_prefix, name, count);
87 if(g_debug)
88 printf("Write boot section %s to %s\n", name, filename);
90 FILE *fd = fopen(filename, "wb");
91 free(filename);
93 if(fd == NULL)
94 return;
95 if(g_elf_simplify)
96 elf_simplify(elf);
97 elf_write_file(elf, elf_write, elf_printf, fd);
98 fclose(fd);
101 static void extract_sb_section(struct sb_section_t *sec)
103 if(sec->is_data)
105 char sec_name[5];
106 char *filename = xmalloc(strlen(g_out_prefix) + 32);
107 sb_fill_section_name(sec_name, sec->identifier);
108 sprintf(filename, "%s%s.bin", g_out_prefix, sec_name);
109 FILE *fd = fopen(filename, "wb");
110 if(fd == NULL)
111 bugp("Cannot open %s for writing\n", filename);
112 if(g_debug)
113 printf("Write data section %s to %s\n", sec_name, filename);
114 free(filename);
116 for(int j = 0; j < sec->nr_insts; j++)
118 assert(sec->insts[j].inst == SB_INST_DATA);
119 fwrite(sec->insts[j].data, sec->insts[j].size, 1, fd);
121 fclose(fd);
124 int elf_count = 0;
125 struct elf_params_t elf;
126 elf_init(&elf);
128 for(int i = 0; i < sec->nr_insts; i++)
130 struct sb_inst_t *inst = &sec->insts[i];
131 switch(inst->inst)
133 case SB_INST_LOAD:
134 elf_add_load_section(&elf, inst->addr, inst->size, inst->data);
135 break;
136 case SB_INST_FILL:
137 elf_add_fill_section(&elf, inst->addr, inst->size, inst->pattern);
138 break;
139 case SB_INST_CALL:
140 case SB_INST_JUMP:
141 elf_set_start_addr(&elf, inst->addr);
142 extract_elf_section(&elf, elf_count++, sec->identifier);
143 elf_release(&elf);
144 elf_init(&elf);
145 break;
146 default:
147 /* ignore mode and nop */
148 break;
152 if(!elf_is_empty(&elf))
153 extract_elf_section(&elf, elf_count, sec->identifier);
154 elf_release(&elf);
157 static void extract_sb_file(struct sb_file_t *file)
159 for(int i = 0; i < file->nr_sections; i++)
160 extract_sb_section(&file->sections[i]);
163 static void extract_elf(struct elf_params_t *elf, int count)
165 char *filename = xmalloc(strlen(g_out_prefix) + 32);
166 sprintf(filename, "%s.%d.elf", g_out_prefix, count);
167 if(g_debug)
168 printf("Write boot content to %s\n", filename);
170 FILE *fd = fopen(filename, "wb");
171 free(filename);
173 if(fd == NULL)
174 return;
175 if(g_elf_simplify)
176 elf_simplify(elf);
177 elf_write_file(elf, elf_write, elf_printf, fd);
178 fclose(fd);
181 static void extract_sb1_file(struct sb1_file_t *file)
183 int elf_count = 0;
184 struct elf_params_t elf;
185 elf_init(&elf);
187 for(int i = 0; i < file->nr_insts; i++)
189 struct sb1_inst_t *inst = &file->insts[i];
190 switch(inst->cmd)
192 case SB1_INST_LOAD:
193 elf_add_load_section(&elf, inst->addr, inst->size, inst->data);
194 break;
195 case SB1_INST_FILL:
196 elf_add_fill_section(&elf, inst->addr, inst->size, inst->pattern);
197 break;
198 case SB1_INST_CALL:
199 case SB1_INST_JUMP:
200 elf_set_start_addr(&elf, inst->addr);
201 extract_elf(&elf, elf_count++);
202 elf_release(&elf);
203 elf_init(&elf);
204 break;
205 default:
206 /* ignore mode and nop */
207 break;
211 if(!elf_is_empty(&elf))
212 extract_elf(&elf, elf_count);
213 elf_release(&elf);
216 static void usage(void)
218 printf("Usage: sbtoelf [options] sb-file\n");
219 printf("Options:\n");
220 printf(" -?/--help\tDisplay this message\n");
221 printf(" -o <prefix>\tEnable output and set prefix\n");
222 printf(" -d/--debug\tEnable debug output*\n");
223 printf(" -k <file>\tAdd key file\n");
224 printf(" -z\t\tAdd zero key\n");
225 printf(" -r\t\tUse raw command mode\n");
226 printf(" -a/--add-key <key>\tAdd single key (hex or usbotp)\n");
227 printf(" -n/--no-color\tDisable output colors\n");
228 printf(" -l/--loopback <file>\tProduce sb file out of extracted description*\n");
229 printf(" -f/--force\tForce reading even without a key*\n");
230 printf(" -1/--v1\tForce to read file as a version 1 file\n");
231 printf(" -2/--v2\tForce to read file as a version 2 file\n");
232 printf(" -s/--no-simpl\tPrevent elf files from being simplified*\n");
233 printf(" -x\t\tUse default sb1 key\n");
234 printf(" -b\tBrute force key\n");
235 printf("Options marked with a * are for debug purpose only\n");
236 exit(1);
239 static void sb_printf(void *user, bool error, color_t c, const char *fmt, ...)
241 (void) user;
242 (void) error;
243 va_list args;
244 va_start(args, fmt);
245 color(c);
246 vprintf(fmt, args);
247 va_end(args);
250 static struct crypto_key_t g_zero_key =
252 .method = CRYPTO_KEY,
253 .u.key = {0}
258 enum sb_version_guess_t
260 SB_VERSION_1,
261 SB_VERSION_2,
262 SB_VERSION_UNK,
265 enum sb_version_guess_t guess_sb_version(const char *filename)
267 #define ret(x) do { fclose(f); return x; } while(0)
268 FILE *f = fopen(filename, "rb");
269 if(f == NULL)
270 bugp("Cannot open file for reading\n");
271 // check signature
272 uint8_t sig[4];
273 if(fseek(f, 20, SEEK_SET))
274 ret(SB_VERSION_UNK);
275 if(fread(sig, 4, 1, f) != 1)
276 ret(SB_VERSION_UNK);
277 if(memcmp(sig, "STMP", 4) != 0)
278 ret(SB_VERSION_UNK);
279 // check header size (v1)
280 uint32_t hdr_size;
281 if(fseek(f, 8, SEEK_SET))
282 ret(SB_VERSION_UNK);
283 if(fread(&hdr_size, 4, 1, f) != 1)
284 ret(SB_VERSION_UNK);
285 if(hdr_size == 0x34)
286 ret(SB_VERSION_1);
287 // check header params relationship
288 struct
290 uint16_t nr_keys; /* Number of encryption keys */
291 uint16_t key_dict_off; /* Offset to key dictionary (in blocks) */
292 uint16_t header_size; /* In blocks */
293 uint16_t nr_sections; /* Number of sections */
294 uint16_t sec_hdr_size; /* Section header size (in blocks) */
295 } __attribute__((packed)) u;
296 if(fseek(f, 0x28, SEEK_SET))
297 ret(SB_VERSION_UNK);
298 if(fread(&u, sizeof(u), 1, f) != 1)
299 ret(SB_VERSION_UNK);
300 if(u.sec_hdr_size == 1 && u.header_size == 6 && u.key_dict_off == u.header_size + u.nr_sections)
301 ret(SB_VERSION_2);
302 ret(SB_VERSION_UNK);
303 #undef ret
306 int main(int argc, char **argv)
308 bool raw_mode = false;
309 const char *loopback = NULL;
310 bool force_sb1 = false;
311 bool force_sb2 = false;
312 bool brute_force = false;
314 while(1)
316 static struct option long_options[] =
318 {"help", no_argument, 0, '?'},
319 {"debug", no_argument, 0, 'd'},
320 {"add-key", required_argument, 0, 'a'},
321 {"no-color", no_argument, 0, 'n'},
322 {"loopback", required_argument, 0, 'l'},
323 {"force", no_argument, 0, 'f'},
324 {"v1", no_argument, 0, '1'},
325 {"v2", no_argument, 0, '2'},
326 {"no-simpl", no_argument, 0, 's'},
327 {0, 0, 0, 0}
330 int c = getopt_long(argc, argv, "?do:k:zra:nl:f12xsb", long_options, NULL);
331 if(c == -1)
332 break;
333 switch(c)
335 case -1:
336 break;
337 case 'l':
338 if(loopback)
339 bug("Only one loopback file can be specified !\n");
340 loopback = optarg;
341 break;
342 case 'n':
343 enable_color(false);
344 break;
345 case 'd':
346 g_debug = true;
347 break;
348 case '?':
349 usage();
350 break;
351 case 'o':
352 g_out_prefix = optarg;
353 break;
354 case 'f':
355 g_force = true;
356 break;
357 case 'k':
359 if(!add_keys_from_file(optarg))
360 bug("Cannot add keys from %s\n", optarg);
361 break;
363 case 'z':
364 add_keys(&g_zero_key, 1);
365 break;
366 case 'x':
368 struct crypto_key_t key;
369 sb1_get_default_key(&key);
370 add_keys(&key, 1);
371 break;
373 case 'r':
374 raw_mode = true;
375 break;
376 case 'a':
378 struct crypto_key_t key;
379 char *s = optarg;
380 if(!parse_key(&s, &key))
381 bug("Invalid key specified as argument\n");
382 if(*s != 0)
383 bug("Trailing characters after key specified as argument\n");
384 add_keys(&key, 1);
385 break;
387 case '1':
388 force_sb1 = true;
389 break;
390 case '2':
391 force_sb2 = true;
392 break;
393 case 's':
394 g_elf_simplify = false;
395 break;
396 case 'b':
397 brute_force = true;
398 break;
399 default:
400 abort();
404 if(force_sb1 && force_sb2)
405 bug("You cannot force both version 1 and 2\n");
407 if(argc - optind != 1)
409 usage();
410 return 1;
413 const char *sb_filename = argv[optind];
415 enum sb_version_guess_t ver = guess_sb_version(sb_filename);
417 if(force_sb2 || ver == SB_VERSION_2)
419 enum sb_error_t err;
420 struct sb_file_t *file = sb_read_file(sb_filename, raw_mode, NULL, sb_printf, &err);
421 if(file == NULL)
423 color(OFF);
424 printf("SB read failed: %d\n", err);
425 return 1;
428 color(OFF);
429 if(g_out_prefix)
430 extract_sb_file(file);
431 if(g_debug)
433 color(GREY);
434 printf("[Debug output]\n");
435 sb_dump(file, NULL, sb_printf);
437 if(loopback)
439 /* sb_read_file will fill real key and IV but we don't want to override
440 * them when looping back otherwise the output will be inconsistent and
441 * garbage */
442 file->override_real_key = false;
443 file->override_crypto_iv = false;
444 sb_write_file(file, loopback);
446 sb_free(file);
448 else if(force_sb1 || ver == SB_VERSION_1)
450 if(brute_force)
452 struct crypto_key_t key;
453 enum sb1_error_t err;
454 if(!sb1_brute_force(sb_filename, NULL, sb_printf, &err, &key))
456 color(OFF);
457 printf("Brute force failed: %d\n", err);
458 return 1;
460 color(RED);
461 printf("Key found:");
462 color(YELLOW);
463 for(int i = 0; i < 32; i++)
464 printf(" %08x", key.u.xor_key[i / 16].k[i % 16]);
465 color(OFF);
466 printf("\n");
467 color(RED);
468 printf("Key: ");
469 color(YELLOW);
470 for(int i = 0; i < 128; i++)
471 printf("%02x", key.u.xor_key[i / 64].key[i % 64]);
472 color(OFF);
473 printf("\n");
474 add_keys(&key, 1);
477 enum sb1_error_t err;
478 struct sb1_file_t *file = sb1_read_file(sb_filename, NULL, sb_printf, &err);
479 if(file == NULL)
481 color(OFF);
482 printf("SB read failed: %d\n", err);
483 return 1;
486 color(OFF);
487 if(g_out_prefix)
488 extract_sb1_file(file);
489 if(g_debug)
491 color(GREY);
492 printf("[Debug output]\n");
493 sb1_dump(file, NULL, sb_printf);
495 if(loopback)
496 sb1_write_file(file, loopback);
498 sb1_free(file);
500 else
502 color(OFF);
503 printf("Cannot guess file type, are you sure it's a valid image ?\n");
504 return 1;
506 clear_keys();
508 return 0;