firmware-utils: add NEXX factory image support
[openwrt.git] / tools / firmware-utils / src / mkporayfw.c
1 /*
2  * Builder/viewer/extractor utility for Poray firmware image files
3  *
4  * Copyright (C) 2013 Michel Stempin <michel.stempin@wanadoo.fr>
5  * Copyright (C) 2013 Felix Kaechele <felix@fetzig.org>
6  * Copyright (C) 2013 <admin@openschemes.com>
7  *
8  * This tool is based on:
9  *   TP-Link firmware upgrade tool.
10  *   Copyright (C) 2009 Gabor Juhos <juhosg@openwrt.org>
11  *
12  * Itself based on:
13  *   TP-Link WR941 V2 firmware checksum fixing tool.
14  *   Copyright (C) 2008,2009 Wang Jian <lark@linux.net.cn>
15  *
16  * This program is free software; you can redistribute it and/or modify it
17  * under the terms of the GNU General Public License version 2 as published
18  * by the Free Software Foundation.
19  *
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdint.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <libgen.h>
28 #include <getopt.h>
29 #include <stdarg.h>
30 #include <errno.h>
31 #include <sys/stat.h>
32 #include <arpa/inet.h>
33 #include <netinet/in.h>
34
35 #if (__BYTE_ORDER == __BIG_ENDIAN)
36 #  define HOST_TO_BE32(x)       (x)
37 #  define BE32_TO_HOST(x)       (x)
38 #  define HOST_TO_LE32(x)       bswap_32(x)
39 #  define LE32_TO_HOST(x)       bswap_32(x)
40 #else
41 #  define HOST_TO_BE32(x)       bswap_32(x)
42 #  define BE32_TO_HOST(x)       bswap_32(x)
43 #  define HOST_TO_LE32(x)       (x)
44 #  define LE32_TO_HOST(x)       (x)
45 #endif
46
47 /* Fixed header flags */
48 #define HEADER_FLAGS            0x020e0000
49
50 /* Recognized Hardware ID magic */
51 #define HWID_HAME_MPR_A1_L8     0x32473352
52 #define HWID_PORAY_R50B         0x31353033
53 #define HWID_PORAY_R50D         0x33353033
54 #define HWID_PORAY_R50E         0x34353033
55 #define HWID_PORAY_M3           0x31353335
56 #define HWID_PORAY_M4           0x32353335
57 #define HWID_PORAY_Q3           0x33353335
58 #define HWID_PORAY_X5_X6        0x35353335
59 #define HWID_PORAY_X8           0x36353335
60 #define HWID_PORAY_X1           0x38353335
61 #define HWID_NEXX_WT15XXX       0x30353332
62 #define HWID_NEXX_WT3020A       0x30323033
63
64 /* Recognized XOR obfuscation keys */
65 #define KEY_HAME                0
66 #define KEY_PORAY_1             1
67 #define KEY_PORAY_2             2
68 #define KEY_PORAY_3             3
69 #define KEY_PORAY_4             4
70 #define KEY_NEXX_1              5
71 #define KEY_NEXX_2              6
72
73 /* XOR key length */
74 #define KEY_LEN                 15
75
76 struct file_info {
77         char            *file_name;     /* Name of the file */
78         uint32_t        file_size;      /* Length of the file */
79 };
80
81 struct fw_header {
82         uint32_t        hw_id;          /* Hardware id */
83         uint32_t        firmware_len;   /* Firmware data length */
84         uint32_t        flags;          /* Header flags */
85         uint8_t         pad[16];
86 } __attribute__ ((packed));
87
88 struct flash_layout {
89         char            *id;
90         uint32_t        fw_max_len;
91 };
92
93 struct board_info {
94         char            *id;
95         uint32_t        hw_id;
96         char            *layout_id;
97         uint32_t        key;
98 };
99
100 /*
101  * Globals
102  */
103 static char *ofname;
104 static char *progname;
105
106 static char *board_id;
107 static struct board_info *board;
108 static char *layout_id;
109 static struct flash_layout *layout;
110 static char *opt_hw_id;
111 static uint32_t hw_id;
112 static struct file_info firmware_info;
113 static uint32_t firmware_len = 0;
114
115 static int inspect = 0;
116 static int extract = 0;
117
118 static uint8_t key[][KEY_LEN] = {
119   {0xC8, 0x3C, 0x3A, 0x93, 0xA2, 0x95, 0xC3, 0x63, 0x48, 0x45, 0x58, 0x09, 0x12, 0x03, 0x08},
120   {0x89, 0x6B, 0x5A, 0x93, 0x92, 0x95, 0xC3, 0x63, 0xD0, 0xA3, 0x9C, 0x92, 0x2E, 0xE6, 0xC7},
121   {0xC9, 0x1C, 0x3A, 0x93, 0x92, 0x95, 0xC3, 0x63, 0xD0, 0xA3, 0x9C, 0x92, 0x2E, 0xE6, 0xC7},
122   {0x19, 0x1B, 0x3A, 0x93, 0x92, 0x95, 0xC3, 0x63, 0xD0, 0xA3, 0x9C, 0x92, 0x2E, 0xE6, 0xC7},
123   {0x79, 0x7B, 0x7A, 0x93, 0x92, 0x95, 0xC3, 0x63, 0xD0, 0xA3, 0x9C, 0x92, 0x2E, 0xE6, 0xC7},
124   {0x19, 0x1C, 0x4A, 0x93, 0x96, 0x95, 0xC3, 0x63, 0xD0, 0xA3, 0x9C, 0x92, 0x2E, 0x16, 0xC6},
125   {0x39, 0x1C, 0x4A, 0x93, 0x96, 0x95, 0xC3, 0x63, 0xD0, 0xA3, 0x9C, 0x92, 0x2E, 0x16, 0xC6},
126 };
127
128 static struct flash_layout layouts[] = {
129         {
130                 .id             = "4M",
131                 .fw_max_len     = 0x3c0000,
132         }, {
133                 .id             = "8M",
134                 .fw_max_len     = 0x7c0000,
135         }, {
136                 /* terminating entry */
137         }
138 };
139
140 static struct board_info boards[] = {
141         {
142                 .id             = "MPR-A1",
143                 .hw_id          = HWID_HAME_MPR_A1_L8,
144                 .layout_id      = "4M",
145                 .key            = KEY_HAME,
146         }, {
147                 .id             = "MPR-L8",
148                 .hw_id          = HWID_HAME_MPR_A1_L8,
149                 .layout_id      = "4M",
150                 .key            = KEY_HAME,
151         }, {
152                 .id             = "R50B",
153                 .hw_id          = HWID_PORAY_R50B,
154                 .layout_id      = "4M",
155                 .key            = KEY_PORAY_2,
156         }, {
157                 .id             = "R50D",
158                 .hw_id          = HWID_PORAY_R50D,
159                 .layout_id      = "4M",
160                 .key            = KEY_PORAY_3,
161         }, {
162                 .id             = "R50E",
163                 .hw_id          = HWID_PORAY_R50E,
164                 .layout_id      = "4M",
165                 .key            = KEY_PORAY_4,
166         }, {
167                 .id             = "M3",
168                 .hw_id          = HWID_PORAY_M3,
169                 .layout_id      = "4M",
170                 .key            = KEY_PORAY_1,
171         }, {
172                 .id             = "M4",
173                 .hw_id          = HWID_PORAY_M4,
174                 .layout_id      = "4M",
175                 .key            = KEY_PORAY_1,
176         }, {
177                 .id             = "Q3",
178                 .hw_id          = HWID_PORAY_Q3,
179                 .layout_id      = "4M",
180                 .key            = KEY_PORAY_1,
181         }, {
182                 .id             = "X5 or X6",
183                 .hw_id          = HWID_PORAY_X5_X6,
184                 .layout_id      = "8M",
185                 .key            = KEY_PORAY_1,
186         }, {
187                 .id             = "X5",
188                 .hw_id          = HWID_PORAY_X5_X6,
189                 .layout_id      = "8M",
190                 .key            = KEY_PORAY_1,
191         }, {
192                 .id             = "X6",
193                 .hw_id          = HWID_PORAY_X5_X6,
194                 .layout_id      = "8M",
195                 .key            = KEY_PORAY_1,
196         }, {
197                 .id             = "X8",
198                 .hw_id          = HWID_PORAY_X8,
199                 .layout_id      = "8M",
200                 .key            = KEY_PORAY_1,
201         }, {
202                 .id             = "X1",
203                 .hw_id          = HWID_PORAY_X1,
204                 .layout_id      = "8M",
205                 .key            = KEY_PORAY_1,
206         }, {
207                 .id             = "WT15XXX",
208                 .hw_id          = HWID_NEXX_WT15XXX,
209                 .layout_id      = "4M",
210                 .key            = KEY_NEXX_1,
211         }, {
212                 .id             = "WT3020A",
213                 .hw_id          = HWID_NEXX_WT3020A,
214                 .layout_id      = "4M",
215                 .key            = KEY_NEXX_2,
216         }, {
217                 /* terminating entry */
218         }
219 };
220
221 /*
222  * Message macros
223  */
224 #define ERR(fmt, ...) do { \
225         fflush(0); \
226         fprintf(stderr, "[%s] *** error: " fmt "\n", \
227                         progname, ## __VA_ARGS__ ); \
228 } while (0)
229
230 #define ERRS(fmt, ...) do { \
231         int save = errno; \
232         fflush(0); \
233         fprintf(stderr, "[%s] *** error: " fmt ":%s\n", \
234                         progname, ## __VA_ARGS__, strerror(save)); \
235 } while (0)
236
237 #define DBG(fmt, ...) do { \
238         fprintf(stderr, "[%s] " fmt "\n", progname, ## __VA_ARGS__ ); \
239 } while (0)
240
241 /*
242  * Find a board by its name
243  */
244 static struct board_info *find_board(char *id)
245 {
246         struct board_info *ret;
247         struct board_info *board;
248
249         ret = NULL;
250         for (board = boards; board->id != NULL; board++){
251                 if (strcasecmp(id, board->id) == 0) {
252                         ret = board;
253                         break;
254                 }
255         };
256
257         return ret;
258 }
259
260 /*
261  * Find a board by its hardware ID
262  */
263 static struct board_info *find_board_by_hwid(uint32_t hw_id)
264 {
265         struct board_info *board;
266
267         for (board = boards; board->id != NULL; board++) {
268                 if (hw_id == board->hw_id)
269                         return board;
270         };
271
272         return NULL;
273 }
274
275 /*
276  * Find a Flash memory layout by its name
277  */
278 static struct flash_layout *find_layout(char *id)
279 {
280         struct flash_layout *ret;
281         struct flash_layout *l;
282
283         ret = NULL;
284         for (l = layouts; l->id != NULL; l++){
285                 if (strcasecmp(id, l->id) == 0) {
286                         ret = l;
287                         break;
288                 }
289         };
290
291         return ret;
292 }
293
294 /*
295  * Display usage
296  */
297 static void usage(int status)
298 {
299         FILE *stream = (status != EXIT_SUCCESS) ? stderr : stdout;
300
301         fprintf(stream, "Usage: %s [OPTIONS...]\n", progname);
302         fprintf(stream,
303 "\n"
304 "Options:\n"
305 "  -B <board>      create image for the board specified with <board>\n"
306 "  -H <hwid>       use hardware id specified with <hwid>\n"
307 "  -F <id>         use flash layout specified with <id>\n"
308 "  -f <file>       read firmware image from the file <file>\n"
309 "  -o <file>       write output to the file <file>\n"
310 "  -i              inspect given firmware file (requires -f)\n"
311 "  -x              extract combined kernel and rootfs while inspecting (implies -i)\n"
312 "  -h              show this screen\n"
313         );
314
315         exit(status);
316 }
317
318 /*
319  * Get file statistics
320  */
321 static int get_file_stat(struct file_info *fdata)
322 {
323         struct stat st;
324         int res;
325
326         if (fdata->file_name == NULL) {
327                 return 0;
328         }
329         res = stat(fdata->file_name, &st);
330         if (res){
331                 ERRS("stat failed on %s", fdata->file_name);
332                 return res;
333         }
334
335         fdata->file_size = st.st_size;
336         return 0;
337 }
338
339 /*
340  * Read file into buffer
341  */
342 static int read_to_buf(struct file_info *fdata, uint8_t *buf)
343 {
344         FILE *f;
345         int ret = EXIT_FAILURE;
346
347         f = fopen(fdata->file_name, "rb");
348         if (f == NULL) {
349                 ERRS("could not open \"%s\" for reading", fdata->file_name);
350                 goto out;
351         }
352
353         errno = 0;
354         fread(buf, fdata->file_size, 1, f);
355         if (errno != 0) {
356                 ERRS("unable to read from file \"%s\"", fdata->file_name);
357                 goto out_close;
358         }
359
360         ret = EXIT_SUCCESS;
361
362  out_close:
363         fclose(f);
364  out:
365         return ret;
366 }
367
368 /*
369  * Check command line options
370  */
371 static int check_options(void)
372 {
373         int ret;
374
375         if (firmware_info.file_name == NULL) {
376                 ERR("no firmware image specified");
377                 return -1;
378         }
379
380         ret = get_file_stat(&firmware_info);
381         if (ret)
382                 return ret;
383
384         if (inspect)
385                 return 0;
386
387         if (board_id == NULL && opt_hw_id == NULL) {
388                 ERR("either board or hardware id must be specified");
389                 return -1;
390         }
391
392         if (board_id) {
393                 board = find_board(board_id);
394                 if (board == NULL) {
395                         ERR("unknown/unsupported board id \"%s\"", board_id);
396                         return -1;
397                 }
398                 if (layout_id == NULL) {
399                         layout_id = board->layout_id;
400                 }
401                 hw_id = board->hw_id;
402         } else {
403                 hw_id = strtoul(opt_hw_id, NULL, 0);
404                 board = find_board_by_hwid(hw_id);
405                 if (layout_id == NULL) {
406                         layout_id = board->layout_id;
407                 }
408         }
409
410         layout = find_layout(layout_id);
411         if (layout == NULL) {
412                 ERR("unknown flash layout \"%s\"", layout_id);
413                 return -1;
414         }
415
416         firmware_len = firmware_info.file_size;
417
418         if (firmware_info.file_size >
419                 layout->fw_max_len - sizeof (struct fw_header)) {
420                 ERR("firmware image is too big");
421                 return -1;
422         }
423
424         if (ofname == NULL) {
425                 ERR("no output file specified");
426                 return -1;
427         }
428         return 0;
429 }
430
431 /*
432  * Fill in firmware header
433  */
434 static void fill_header(uint8_t *buf)
435 {
436         struct fw_header *hdr = (struct fw_header *) buf;
437
438         memset(hdr, 0, sizeof (struct fw_header));
439         hdr->hw_id = HOST_TO_LE32(hw_id);
440         hdr->firmware_len = HOST_TO_LE32(firmware_len);
441         hdr->flags = HOST_TO_LE32(HEADER_FLAGS);
442 }
443
444 /*
445  * Compute firmware checksum
446  */
447 static uint16_t checksum_fw(uint8_t *data, int len)
448 {
449         int i;
450         int32_t checksum = 0;
451
452         for (i = 0; i < len - 1; i += 2) {
453                 checksum += (data[i + 1] << 8) | data[i];
454         }
455         if (i < len) {
456                 checksum += data[i];
457         }
458         checksum = checksum + (checksum >> 16) + 0xffff;
459         checksum = ~(checksum + (checksum >> 16)) & 0xffff;
460         return (uint16_t) checksum;
461 }
462
463 /*
464  * (De)obfuscate firmware using an XOR operation with a fixed length key
465  */
466 static void xor_fw(uint8_t *data, int len)
467 {
468         int i;
469
470         for (i = 0; i <= len; i++) {
471                 data[i] ^= key[board->key][i % KEY_LEN];
472         }
473 }
474
475 /*
476  * Write firmware to file
477  */
478 static int write_fw(uint8_t *data, int len)
479 {
480         FILE *f;
481         int ret = EXIT_FAILURE;
482
483         f = fopen(ofname, "wb");
484         if (f == NULL) {
485                 ERRS("could not open \"%s\" for writing", ofname);
486                 goto out;
487         }
488
489         errno = 0;
490         fwrite(data, len, 1, f);
491         if (errno) {
492                 ERRS("unable to write output file");
493                 goto out_flush;
494         }
495
496         DBG("firmware file \"%s\" completed", ofname);
497
498         ret = EXIT_SUCCESS;
499
500  out_flush:
501         fflush(f);
502         fclose(f);
503         if (ret != EXIT_SUCCESS) {
504                 unlink(ofname);
505         }
506  out:
507         return ret;
508 }
509
510 /*
511  * Build firmware file
512  */
513 static int build_fw(void)
514 {
515         int buflen;
516         uint8_t *buf, *p;
517         int ret = EXIT_FAILURE;
518         int writelen = 0;
519         uint16_t checksum;
520
521         buflen = layout->fw_max_len;
522
523         buf = (uint8_t *) malloc(buflen);
524         if (!buf) {
525                 ERR("no memory for buffer\n");
526                 goto out;
527         }
528
529         memset(buf, 0xff, buflen);
530         p = buf + sizeof (struct fw_header);
531         ret = read_to_buf(&firmware_info, p);
532         if (ret) {
533                 goto out_free_buf;
534         }
535         writelen = sizeof (struct fw_header) + firmware_len + 2;
536
537         /* Fill in header */
538         fill_header(buf);
539
540         /* Compute firmware checksum */
541         checksum = checksum_fw(buf + sizeof (struct fw_header), firmware_len);
542
543         /* Cannot use network order function because checksum is not word-aligned */
544         buf[writelen - 1] = checksum >> 8;
545         buf[writelen - 2] = checksum & 0xff;
546
547         /* XOR obfuscate firmware */
548         xor_fw(buf + sizeof (struct fw_header), firmware_len + 2);
549
550         /* Write firmware file */
551         ret = write_fw(buf, writelen);
552         if (ret) {
553                 goto out_free_buf;
554         }
555         ret = EXIT_SUCCESS;
556
557  out_free_buf:
558         free(buf);
559  out:
560         return ret;
561 }
562
563 /* Helper functions to inspect_fw() representing different output formats */
564 static inline void inspect_fw_pstr(char *label, char *str)
565 {
566         printf("%-23s: %s\n", label, str);
567 }
568
569 static inline void inspect_fw_phex(char *label, uint32_t val)
570 {
571         printf("%-23s: 0x%08x\n", label, val);
572 }
573
574 static inline void inspect_fw_phexpost(char *label,
575                                        uint32_t val, char *post)
576 {
577         printf("%-23s: 0x%08x (%s)\n", label, val, post);
578 }
579
580 static inline void inspect_fw_phexdef(char *label,
581                                       uint32_t val, uint32_t defval)
582 {
583         printf("%-23s: 0x%08x                  ", label, val);
584
585         if (val == defval) {
586                 printf("(== OpenWrt default)\n");
587         } else {
588                 printf("(OpenWrt default: 0x%08x)\n", defval);
589         }
590 }
591
592 static inline void inspect_fw_phexexp(char *label,
593                                       uint32_t val, uint32_t expval)
594 {
595         printf("%-23s: 0x%08x ", label, val);
596
597         if (val == expval) {
598                 printf("(ok)\n");
599         } else {
600                 printf("(expected: 0x%08x)\n", expval);
601         }
602 }
603
604 static inline void inspect_fw_phexdec(char *label, uint32_t val)
605 {
606         printf("%-23s: 0x%08x / %8u bytes\n", label, val, val);
607 }
608
609 static inline void inspect_fw_pchecksum(char *label,
610                                         uint16_t val, uint16_t expval)
611 {
612         printf("%-23s: 0x%04x     ", label, val);
613         if (val == expval) {
614                 printf("(ok)\n");
615         } else {
616                 printf("(expected: 0x%04x)\n", expval);
617         }
618 }
619
620 static int inspect_fw(void)
621 {
622         uint8_t *buf;
623         struct fw_header *hdr;
624         int ret = EXIT_FAILURE;
625         uint16_t computed_checksum, file_checksum;
626
627         buf = (uint8_t *) malloc(firmware_info.file_size);
628         if (!buf) {
629                 ERR("no memory for buffer!\n");
630                 goto out;
631         }
632
633         ret = read_to_buf(&firmware_info, buf);
634         if (ret) {
635                 goto out_free_buf;
636         }
637         hdr = (struct fw_header *)buf;
638
639         inspect_fw_pstr("File name", firmware_info.file_name);
640         inspect_fw_phexdec("File size", firmware_info.file_size);
641
642         printf("\n");
643
644         inspect_fw_phexdec("Header size", sizeof (struct fw_header));
645         board = find_board_by_hwid(LE32_TO_HOST(hdr->hw_id));
646         if (board) {
647                 layout = find_layout(board->layout_id);
648                 inspect_fw_phexpost("Hardware ID",
649                                     LE32_TO_HOST( hdr->hw_id), board->id);
650         } else {
651                 inspect_fw_phexpost("Hardware ID",
652                                     LE32_TO_HOST(hdr->hw_id), "unknown");
653         }
654         inspect_fw_phexdec("Firmware data length",
655                            LE32_TO_HOST(hdr->firmware_len));
656
657         inspect_fw_phexexp("Flags",
658                            LE32_TO_HOST(hdr->flags), HEADER_FLAGS);
659         printf("\n");
660
661         /* XOR unobfuscate firmware */
662         xor_fw(buf + sizeof (struct fw_header), LE32_TO_HOST(hdr->firmware_len) + 2);
663
664         /* Compute firmware checksum */
665         computed_checksum = checksum_fw(buf + sizeof (struct fw_header), LE32_TO_HOST(hdr->firmware_len));
666
667         /* Cannot use network order function because checksum is not word-aligned */
668         file_checksum = (buf[firmware_info.file_size - 1] << 8) | buf[firmware_info.file_size - 2];
669         inspect_fw_pchecksum("Firmware checksum", computed_checksum, file_checksum);
670
671         /* Verify checksum */
672         if (computed_checksum != file_checksum) {
673                 ret = -1;
674                 ERR("checksums do not match");
675                 goto out_free_buf;
676         }
677
678         printf("\n");
679
680         if (extract) {
681                 FILE *fp;
682                 char *filename;
683
684                 if (ofname == NULL) {
685                         filename = malloc(strlen(firmware_info.file_name) + 10);
686                         sprintf(filename, "%s-firmware", firmware_info.file_name);
687                 } else {
688                         filename = ofname;
689                 }
690                 printf("Extracting firmware to \"%s\"...\n", filename);
691                 fp = fopen(filename, "wb");
692                 if (fp) {
693                   if (!fwrite(buf + sizeof (struct fw_header),
694                                     LE32_TO_HOST(hdr->firmware_len), 1, fp)) {
695                                 ERRS("error in fwrite(): %s", strerror(errno));
696                         }
697                         fclose(fp);
698                 } else {
699                         ERRS("error in fopen(): %s", strerror(errno));
700                 }
701                 if (ofname == NULL) {
702                         free(filename);
703                 }
704                 printf("\n");
705         }
706
707  out_free_buf:
708         free(buf);
709  out:
710         return ret;
711 }
712
713 /*
714  * Main entry point
715  */
716 int main(int argc, char *argv[])
717 {
718         int ret = EXIT_FAILURE;
719
720         progname = basename(argv[0]);
721
722         int c;
723
724         while ((c = getopt(argc, argv, "B:H:F:f:o:ixh")) != -1) {
725                 switch (c) {
726                 case 'B':
727                         board_id = optarg;
728                         break;
729                 case 'H':
730                         opt_hw_id = optarg;
731                         break;
732                 case 'F':
733                         layout_id = optarg;
734                         break;
735                 case 'f':
736                         firmware_info.file_name = optarg;
737                         break;
738                 case 'o':
739                         ofname = optarg;
740                         break;
741                 case 'i':
742                         inspect = 1;
743                         break;
744                 case 'x':
745                         inspect = 1;
746                         extract = 1;
747                         break;
748                 case 'h':
749                         usage(EXIT_SUCCESS);
750                         break;
751                 default:
752                         usage(EXIT_FAILURE);
753                         break;
754                 }
755         }
756
757         ret = check_options();
758         if (ret) {
759                 goto out;
760         }
761         if (!inspect) {
762                 ret = build_fw();
763         } else {
764                 ret = inspect_fw();
765         }
766
767  out:
768         return ret;
769 }