firmware-utils: mktplinkfw: add option for endianness swap
[openwrt/openwrt.git] / tools / firmware-utils / src / jcgimage.c
1 /*
2 * jcgimage - Create a JCG firmware image
3 *
4 * Copyright (C) 2015 Reinhard Max <reinhard@m4x.de>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 *
20 */
21
22 /*
23 * JCG firmware update images consist of a 512 byte header and a
24 * modified uImage (details below) as the payload.
25 *
26 * The payload is obfuscated by XORing it with a key that is generated
27 * from parts of the header. Fortunately only non-essential parts of
28 * the header are used for this and zeroing them results in a zero
29 * key, effectively disabling the obfuscation and allowing us to use
30 * clear text payloads.
31 *
32 * The mandatory parts of the header are:
33 *
34 * - A magic string of "YSZJ" at offset 0.
35 * - A value of 1 at offset 39 (header format version?)
36 * - A CRC32 checksum of the payload at offset 504.
37 * - A CRC32 checksum of the header at offset 508.
38 *
39 * An image constructed by these rules will be accepted by JCG's
40 * U-Boot in resuce mode via TFTP and the payload will be written to
41 * the flash starting at offset 0x00050000.
42 *
43 * JCG's U-Boot does check the content or size of the payload
44 * image. If it is too large, it wraps around and overwrites U-Boot,
45 * requiring JTAG to revive the board. To prevent such bricking from
46 * happening, this tool refuses to build such overlong images.
47 *
48 * Two more conditions have to be met for a JCG image to be accepted
49 * as a valid update by the web interface of the stock firware:
50 *
51 * - The bytes at offsets 109 and 111 in the header must be a binary
52 * representation of the first two components of the firmware
53 * version as displayed in the update web form, or it will be
54 * rejected as "incorrect product".
55 *
56 * - The payload must start with a valid uImage header whose data
57 * CRC checksum matches the whole rest of the update file rather
58 * than just the number of bytes specified in the size field of the
59 * header.
60 *
61 * This last condition is met by JCG's original firmware images,
62 * because they have both, kernel and rootfs inside the uImage and
63 * abuse the last four bytes of the name field to record the offset of
64 * the file system from the start of the uImage header. This tool
65 * produces such images when called with -k and -r, which are meant to
66 * repack the original firmware after modifying the file systen,
67 * e.g. to add debugging tools and enable shell access.
68 *
69 * In contrast, OpenWrt sysupgrade images consist of a uImage that
70 * only contains the kernel and has the rootfs appended to it. Hence,
71 * the CRC over kernel and file system does not match the one in the
72 * uImage header. Fixing this by adjusting the uImage header is not
73 * possible, because it makes the uImage unusable for booting. Instead
74 * we append four "patch" bytes to the end of the file system, that
75 * are calculated to force the checksum of kernel+fs to be the same as
76 * for the kernel alone.
77 *
78 */
79
80 #include <zlib.h>
81 #include <stdio.h>
82 #include <string.h>
83 #include <sys/types.h>
84 #include <sys/stat.h>
85 #include <fcntl.h>
86 #include <unistd.h>
87 #include <libgen.h>
88 #include <stdlib.h>
89 #include <errno.h>
90 #include <err.h>
91 #include <time.h>
92 #include <sys/mman.h>
93 #include <arpa/inet.h>
94 #include <assert.h>
95
96 /*
97 * JCG Firmware image header
98 */
99 #define JH_MAGIC 0x59535a4a /* "YSZJ" */
100 struct jcg_header {
101 uint32_t jh_magic;
102 uint8_t jh_version[32]; /* Firmware version string.
103 Fill with zeros to avoid encryption */
104 uint32_t jh_type; /* must be 1 */
105 uint8_t jh_info[64]; /* Firmware info string. Fill with
106 zeros to avoid encryption */
107 uint32_t jh_time; /* Image creation time in seconds since
108 * the Epoch. Does not seem to be used
109 * by the stock firmware. */
110 uint16_t jh_major; /* Major fimware version */
111 uint16_t jh_minor; /* Minor fimrmware version */
112 uint8_t jh_unknown[392]; /* Apparently unused and all zeros */
113 uint32_t jh_dcrc; /* CRC checksum of the payload */
114 uint32_t jh_hcrc; /* CRC checksum of the header */
115 };
116
117 /*
118 * JCG uses a modified uImage header that replaces the last four bytes
119 * of the image name with the length of the kernel in the image.
120 */
121 #define IH_MAGIC 0x27051956 /* Image Magic Number */
122 #define IH_NMLEN 28 /* Image Name Length */
123
124 struct uimage_header {
125 uint32_t ih_magic; /* Image Header Magic Number */
126 uint32_t ih_hcrc; /* Image Header CRC Checksum */
127 uint32_t ih_time; /* Image Creation Timestamp */
128 uint32_t ih_size; /* Image Data Size */
129 uint32_t ih_load; /* Data Load Address */
130 uint32_t ih_ep; /* Entry Point Address */
131 uint32_t ih_dcrc; /* Image Data CRC Checksum */
132 uint8_t ih_os; /* Operating System */
133 uint8_t ih_arch; /* CPU architecture */
134 uint8_t ih_type; /* Image Type */
135 uint8_t ih_comp; /* Compression Type */
136 uint8_t ih_name[IH_NMLEN];/* Image Name */
137 uint32_t ih_fsoff; /* Offset of the file system
138 partition from the start of
139 the header */
140 };
141
142 /*
143 * Open the named file and return its size and file descriptor.
144 * Exit in case of errors.
145 */
146 int
147 opensize(char *name, size_t *size)
148 {
149 struct stat s;
150 int fd = open(name, O_RDONLY);
151 if (fd < 0) {
152 err(1, "cannot open \"%s\"", name);
153 }
154 if (fstat(fd, &s) == -1) {
155 err(1, "cannot stat \"%s\"", name);
156 }
157 *size = s.st_size;
158 return fd;
159 }
160
161 static time_t source_date_epoch = -1;
162 static void set_source_date_epoch() {
163 char *env = getenv("SOURCE_DATE_EPOCH");
164 char *endptr = env;
165 errno = 0;
166 if (env && *env) {
167 source_date_epoch = strtoull(env, &endptr, 10);
168 if (errno || (endptr && *endptr != '\0')) {
169 fprintf(stderr, "Invalid SOURCE_DATE_EPOCH");
170 exit(1);
171 }
172 }
173 }
174
175 /*
176 * Write the JCG header
177 */
178 void
179 mkjcgheader(struct jcg_header *h, size_t psize, char *version)
180 {
181 uLong crc;
182 uint16_t major = 0, minor = 0;
183 void *payload = (void *)h + sizeof(*h);
184 time_t t;
185
186 if (source_date_epoch != -1) {
187 t = source_date_epoch;
188 } else if ((time(&t) == (time_t)(-1))) {
189 err(1, "time call failed");
190 }
191
192 if (version != NULL) {
193 if (sscanf(version, "%hu.%hu", &major, &minor) != 2) {
194 err(1, "cannot parse version \"%s\"", version);
195 }
196 }
197
198 memset(h, 0, sizeof(*h));
199 h->jh_magic = htonl(JH_MAGIC);
200 h->jh_type = htonl(1);
201 h->jh_time = htonl(t);
202 h->jh_major = htons(major);
203 h->jh_minor = htons(minor);
204
205 /* CRC over JCG payload (uImage) */
206 crc = crc32(0L, Z_NULL, 0);
207 crc = crc32(crc, payload, psize);
208 h->jh_dcrc = htonl(crc);
209
210 /* CRC over JCG header */
211 crc = crc32(0L, Z_NULL, 0);
212 crc = crc32(crc, (void *)h, sizeof(*h));
213 h->jh_hcrc = htonl(crc);
214 }
215
216 /*
217 * Write the uImage header
218 */
219 void
220 mkuheader(struct uimage_header *h, size_t ksize, size_t fsize)
221 {
222 uLong crc;
223 void *payload = (void *)h + sizeof(*h);
224
225 // printf("mkuheader: %p, %zd, %zd\n", h, ksize, fsize);
226 memset(h, 0, sizeof(*h));
227 h->ih_magic = htonl(IH_MAGIC);
228 h->ih_time = htonl(time(NULL));
229 h->ih_size = htonl(ksize + fsize);
230 h->ih_load = htonl(0x80000000);
231 h->ih_ep = htonl(0x80292000);
232 h->ih_os = 0x05;
233 h->ih_arch = 0x05;
234 h->ih_type = 0x02;
235 h->ih_comp = 0x03;
236 h->ih_fsoff = htonl(sizeof(*h) + ksize);
237 strcpy((char *)h->ih_name, "Linux Kernel Image");
238
239 /* CRC over uImage payload (kernel and file system) */
240 crc = crc32(0L, Z_NULL, 0);
241 crc = crc32(crc, payload, ntohl(h->ih_size));
242 h->ih_dcrc = htonl(crc);
243 printf("CRC1: %08lx\n", crc);
244
245 /* CRC over uImage header */
246 crc = crc32(0L, Z_NULL, 0);
247 crc = crc32(crc, (void *)h, sizeof(*h));
248 h->ih_hcrc = htonl(crc);
249 printf("CRC2: %08lx\n", crc);
250 }
251
252 /*
253 * Calculate a "patch" value and write it into the last four bytes of
254 * buf, so that the CRC32 checksum of the whole buffer is dcrc.
255 *
256 * Based on: SAR-PR-2006-05: Reversing CRC – Theory and Practice.
257 * Martin Stigge, Henryk Plötz, Wolf Müller, Jens-Peter Redlich.
258 * http://sar.informatik.hu-berlin.de/research/publications/#SAR-PR-2006-05
259 */
260 void
261 craftcrc(uint32_t dcrc, uint8_t *buf, size_t len)
262 {
263 int i;
264 uint32_t a;
265 uint32_t patch = 0;
266 uint32_t crc = crc32(0L, Z_NULL, 0);
267
268 a = ~dcrc;
269 for (i = 0; i < 32; i++) {
270 if (patch & 1) {
271 patch = (patch >> 1) ^ 0xedb88320L;
272 } else {
273 patch >>= 1;
274 }
275 if (a & 1) {
276 patch ^= 0x5b358fd3L;
277 }
278 a >>= 1;
279 }
280 patch ^= ~crc32(crc, buf, len - 4);
281 for (i = 0; i < 4; i++) {
282 buf[len - 4 + i] = patch & 0xff;
283 patch >>= 8;
284 }
285 /* Verify that we actually get the desired result */
286 crc = crc32(0L, Z_NULL, 0);
287 crc = crc32(crc, buf, len);
288 if (crc != dcrc) {
289 errx(1, "CRC patching is broken: wanted %08x, but got %08x.",
290 dcrc, crc);
291 }
292 }
293
294 void
295 usage() {
296 fprintf(stderr, "Usage:\n"
297 "jcgimage -o outfile -u uImage [-v version]\n"
298 "jcgimage -o outfile -k kernel -f rootfs [-v version]\n");
299 exit(1);
300 }
301
302 #define MODE_UNKNOWN 0
303 #define MODE_UIMAGE 1
304 #define MODE_KR 2
305
306 /* The output image must not be larger than 4MiB - 5*64kiB */
307 #define MAXSIZE (size_t)(4 * 1024 * 1024 - 5 * 64 * 1024)
308
309 int
310 main(int argc, char **argv)
311 {
312 struct jcg_header *jh;
313 struct uimage_header *uh;
314 int c;
315 char *imagefile = NULL;
316 char *file1 = NULL;
317 char *file2 = NULL;
318 char *version = NULL;
319 int mode = MODE_UNKNOWN;
320 int fdo, fd1, fd2;
321 size_t size1, size2, sizeu, sizeo, off1, off2;
322 void *map;
323
324 /* Make sure the headers have the right size */
325 assert(sizeof(struct jcg_header) == 512);
326 assert(sizeof(struct uimage_header) == 64);
327 set_source_date_epoch();
328
329 while ((c = getopt(argc, argv, "o:k:f:u:v:h")) != -1) {
330 switch (c) {
331 case 'o':
332 imagefile = optarg;
333 break;
334 case 'k':
335 if (mode == MODE_UIMAGE) {
336 errx(1,"-k cannot be combined with -u");
337 }
338 mode = MODE_KR;
339 file1 = optarg;
340 break;
341 case 'f':
342 if (mode == MODE_UIMAGE) {
343 errx(1,"-f cannot be combined with -u");
344 }
345 mode = MODE_KR;
346 file2 = optarg;
347 break;
348 case 'u':
349 if (mode == MODE_KR) {
350 errx(1,"-u cannot be combined with -k and -r");
351 }
352 mode = MODE_UIMAGE;
353 file1 = optarg;
354 break;
355 case 'v':
356 version = optarg;
357 break;
358 case 'h':
359 default:
360 usage();
361 }
362 }
363 if (optind != argc) {
364 errx(1, "illegal arg \"%s\"", argv[optind]);
365 }
366 if (imagefile == NULL) {
367 errx(1, "no output file specified");
368 }
369 if (mode == MODE_UNKNOWN) {
370 errx(1, "specify either -u or -k and -r");
371 }
372 if (mode == MODE_KR) {
373 if (file1 == NULL || file2 == NULL) {
374 errx(1,"need -k and -r");
375 }
376 fd2 = opensize(file2, &size2);
377 }
378 fd1 = opensize(file1, &size1);
379 if (mode == MODE_UIMAGE) {
380 off1 = sizeof(*jh);
381 sizeu = size1 + 4;
382 sizeo = sizeof(*jh) + sizeu;
383 } else {
384 off1 = sizeof(*jh) + sizeof(*uh);
385 off2 = sizeof(*jh) + sizeof(*uh) + size1;
386 sizeu = sizeof(*uh) + size1 + size2;
387 sizeo = sizeof(*jh) + sizeu;
388 }
389
390 if (sizeo > MAXSIZE) {
391 errx(1,"payload too large: %zd > %zd\n", sizeo, MAXSIZE);
392 }
393
394 fdo = open(imagefile, O_RDWR | O_CREAT | O_TRUNC, 00644);
395 if (fdo < 0) {
396 err(1, "cannot open \"%s\"", imagefile);
397 }
398
399 if (ftruncate(fdo, sizeo) == -1) {
400 err(1, "cannot grow \"%s\" to %zd bytes", imagefile, sizeo);
401 }
402 map = mmap(NULL, sizeo, PROT_READ|PROT_WRITE, MAP_SHARED, fdo, 0);
403 uh = map + sizeof(*jh);
404 if (map == MAP_FAILED) {
405 err(1, "cannot mmap \"%s\"", imagefile);
406 }
407
408 if (read(fd1, map + off1, size1) != size1) {
409 err(1, "cannot copy %s", file1);
410 }
411
412 if (mode == MODE_KR) {
413 if (read(fd2, map+off2, size2) != size2) {
414 err(1, "cannot copy %s", file2);
415 }
416 mkuheader(uh, size1, size2);
417 } else if (mode == MODE_UIMAGE) {
418 craftcrc(ntohl(uh->ih_dcrc), (void*)uh + sizeof(*uh),
419 sizeu - sizeof(*uh));
420 }
421 mkjcgheader(map, sizeu, version);
422 munmap(map, sizeo);
423 close(fdo);
424 return 0;
425 }