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