1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2013, Google Inc.
4  *
5  * (C) Copyright 2008 Semihalf
6  *
7  * (C) Copyright 2000-2006
8  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
9  */
10 
11 #include "mkimage.h"
12 #include <bootm.h>
13 #include <fdt_region.h>
14 #include <image.h>
15 #include <version.h>
16 
17 /**
18  * fit_set_hash_value - set hash value in requested has node
19  * @fit: pointer to the FIT format image header
20  * @noffset: hash node offset
21  * @value: hash value to be set
22  * @value_len: hash value length
23  *
24  * fit_set_hash_value() attempts to set hash value in a node at offset
25  * given and returns operation status to the caller.
26  *
27  * returns
28  *     0, on success
29  *     -1, on failure
30  */
fit_set_hash_value(void * fit,int noffset,uint8_t * value,int value_len)31 static int fit_set_hash_value(void *fit, int noffset, uint8_t *value,
32 				int value_len)
33 {
34 	int ret;
35 
36 	ret = fdt_setprop(fit, noffset, FIT_VALUE_PROP, value, value_len);
37 	if (ret) {
38 		printf("Can't set hash '%s' property for '%s' node(%s)\n",
39 		       FIT_VALUE_PROP, fit_get_name(fit, noffset, NULL),
40 		       fdt_strerror(ret));
41 		return ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO;
42 	}
43 
44 	return 0;
45 }
46 
47 /**
48  * fit_image_process_hash - Process a single subnode of the images/ node
49  *
50  * Check each subnode and process accordingly. For hash nodes we generate
51  * a hash of the supplised data and store it in the node.
52  *
53  * @fit:	pointer to the FIT format image header
54  * @image_name:	name of image being processes (used to display errors)
55  * @noffset:	subnode offset
56  * @data:	data to process
57  * @size:	size of data in bytes
58  * @return 0 if ok, -1 on error
59  */
fit_image_process_hash(void * fit,const char * image_name,int noffset,const void * data,size_t size)60 static int fit_image_process_hash(void *fit, const char *image_name,
61 		int noffset, const void *data, size_t size)
62 {
63 	uint8_t value[FIT_MAX_HASH_LEN];
64 	const char *node_name;
65 	int value_len;
66 	char *algo;
67 	int ret;
68 
69 	node_name = fit_get_name(fit, noffset, NULL);
70 
71 	if (fit_image_hash_get_algo(fit, noffset, &algo)) {
72 		printf("Can't get hash algo property for '%s' hash node in '%s' image node\n",
73 		       node_name, image_name);
74 		return -ENOENT;
75 	}
76 
77 	if (calculate_hash(data, size, algo, value, &value_len)) {
78 		printf("Unsupported hash algorithm (%s) for '%s' hash node in '%s' image node\n",
79 		       algo, node_name, image_name);
80 		return -EPROTONOSUPPORT;
81 	}
82 
83 	ret = fit_set_hash_value(fit, noffset, value, value_len);
84 	if (ret) {
85 		printf("Can't set hash value for '%s' hash node in '%s' image node\n",
86 		       node_name, image_name);
87 		return ret;
88 	}
89 
90 	return 0;
91 }
92 
93 /**
94  * fit_image_write_sig() - write the signature to a FIT
95  *
96  * This writes the signature and signer data to the FIT.
97  *
98  * @fit: pointer to the FIT format image header
99  * @noffset: hash node offset
100  * @value: signature value to be set
101  * @value_len: signature value length
102  * @comment: Text comment to write (NULL for none)
103  *
104  * returns
105  *     0, on success
106  *     -FDT_ERR_..., on failure
107  */
fit_image_write_sig(void * fit,int noffset,uint8_t * value,int value_len,const char * comment,const char * region_prop,int region_proplen,const char * cmdname)108 static int fit_image_write_sig(void *fit, int noffset, uint8_t *value,
109 		int value_len, const char *comment, const char *region_prop,
110 		int region_proplen, const char *cmdname)
111 {
112 	int string_size;
113 	int ret;
114 
115 	/*
116 	 * Get the current string size, before we update the FIT and add
117 	 * more
118 	 */
119 	string_size = fdt_size_dt_strings(fit);
120 
121 	ret = fdt_setprop(fit, noffset, FIT_VALUE_PROP, value, value_len);
122 	if (!ret) {
123 		ret = fdt_setprop_string(fit, noffset, "signer-name",
124 					 "mkimage");
125 	}
126 	if (!ret) {
127 		ret = fdt_setprop_string(fit, noffset, "signer-version",
128 				  PLAIN_VERSION);
129 	}
130 	if (comment && !ret)
131 		ret = fdt_setprop_string(fit, noffset, "comment", comment);
132 	if (!ret) {
133 		time_t timestamp = imagetool_get_source_date(cmdname,
134 							     time(NULL));
135 
136 		ret = fit_set_timestamp(fit, noffset, timestamp);
137 	}
138 	if (region_prop && !ret) {
139 		uint32_t strdata[2];
140 
141 		ret = fdt_setprop(fit, noffset, "hashed-nodes",
142 				   region_prop, region_proplen);
143 		/* This is a legacy offset, it is unused, and must remain 0. */
144 		strdata[0] = 0;
145 		strdata[1] = cpu_to_fdt32(string_size);
146 		if (!ret) {
147 			ret = fdt_setprop(fit, noffset, "hashed-strings",
148 					  strdata, sizeof(strdata));
149 		}
150 	}
151 
152 	return ret;
153 }
154 
fit_image_setup_sig(struct image_sign_info * info,const char * keydir,const char * keyfile,void * fit,const char * image_name,int noffset,const char * require_keys,const char * engine_id)155 static int fit_image_setup_sig(struct image_sign_info *info,
156 		const char *keydir, const char *keyfile, void *fit,
157 		const char *image_name, int noffset, const char *require_keys,
158 		const char *engine_id)
159 {
160 	const char *node_name;
161 	char *algo_name;
162 	const char *padding_name;
163 
164 	node_name = fit_get_name(fit, noffset, NULL);
165 	if (fit_image_hash_get_algo(fit, noffset, &algo_name)) {
166 		printf("Can't get algo property for '%s' signature node in '%s' image node\n",
167 		       node_name, image_name);
168 		return -1;
169 	}
170 
171 	padding_name = fdt_getprop(fit, noffset, "padding", NULL);
172 
173 	memset(info, '\0', sizeof(*info));
174 	info->keydir = keydir;
175 	info->keyfile = keyfile;
176 	info->keyname = fdt_getprop(fit, noffset, FIT_KEY_HINT, NULL);
177 	info->fit = fit;
178 	info->node_offset = noffset;
179 	info->name = strdup(algo_name);
180 	info->checksum = image_get_checksum_algo(algo_name);
181 	info->crypto = image_get_crypto_algo(algo_name);
182 	info->padding = image_get_padding_algo(padding_name);
183 	info->require_keys = require_keys;
184 	info->engine_id = engine_id;
185 	if (!info->checksum || !info->crypto) {
186 		printf("Unsupported signature algorithm (%s) for '%s' signature node in '%s' image node\n",
187 		       algo_name, node_name, image_name);
188 		return -1;
189 	}
190 
191 	return 0;
192 }
193 
194 /**
195  * fit_image_process_sig- Process a single subnode of the images/ node
196  *
197  * Check each subnode and process accordingly. For signature nodes we
198  * generate a signed hash of the supplised data and store it in the node.
199  *
200  * @keydir:	Directory containing keys to use for signing
201  * @keydest:	Destination FDT blob to write public keys into
202  * @fit:	pointer to the FIT format image header
203  * @image_name:	name of image being processes (used to display errors)
204  * @noffset:	subnode offset
205  * @data:	data to process
206  * @size:	size of data in bytes
207  * @comment:	Comment to add to signature nodes
208  * @require_keys: Mark all keys as 'required'
209  * @engine_id:	Engine to use for signing
210  * @return 0 if ok, -1 on error
211  */
fit_image_process_sig(const char * keydir,const char * keyfile,void * keydest,void * fit,const char * image_name,int noffset,const void * data,size_t size,const char * comment,int require_keys,const char * engine_id,const char * cmdname)212 static int fit_image_process_sig(const char *keydir, const char *keyfile,
213 		void *keydest, void *fit, const char *image_name,
214 		int noffset, const void *data, size_t size,
215 		const char *comment, int require_keys, const char *engine_id,
216 		const char *cmdname)
217 {
218 	struct image_sign_info info;
219 	struct image_region region;
220 	const char *node_name;
221 	uint8_t *value;
222 	uint value_len;
223 	int ret;
224 
225 	if (fit_image_setup_sig(&info, keydir, keyfile, fit, image_name,
226 				noffset, require_keys ? "image" : NULL,
227 				engine_id))
228 		return -1;
229 
230 	node_name = fit_get_name(fit, noffset, NULL);
231 	region.data = data;
232 	region.size = size;
233 	ret = info.crypto->sign(&info, &region, 1, &value, &value_len);
234 	if (ret) {
235 		printf("Failed to sign '%s' signature node in '%s' image node: %d\n",
236 		       node_name, image_name, ret);
237 
238 		/* We allow keys to be missing */
239 		if (ret == -ENOENT)
240 			return 0;
241 		return -1;
242 	}
243 
244 	ret = fit_image_write_sig(fit, noffset, value, value_len, comment,
245 			NULL, 0, cmdname);
246 	if (ret) {
247 		if (ret == -FDT_ERR_NOSPACE)
248 			return -ENOSPC;
249 		printf("Can't write signature for '%s' signature node in '%s' conf node: %s\n",
250 		       node_name, image_name, fdt_strerror(ret));
251 		return -1;
252 	}
253 	free(value);
254 
255 	/* Get keyname again, as FDT has changed and invalidated our pointer */
256 	info.keyname = fdt_getprop(fit, noffset, FIT_KEY_HINT, NULL);
257 
258 	/*
259 	 * Write the public key into the supplied FDT file; this might fail
260 	 * several times, since we try signing with successively increasing
261 	 * size values
262 	 */
263 	if (keydest) {
264 		ret = info.crypto->add_verify_data(&info, keydest);
265 		if (ret) {
266 			printf("Failed to add verification data for '%s' signature node in '%s' image node\n",
267 			       node_name, image_name);
268 			return ret;
269 		}
270 	}
271 
272 	return 0;
273 }
274 
fit_image_read_data(char * filename,unsigned char * data,int expected_size)275 static int fit_image_read_data(char *filename, unsigned char *data,
276 			       int expected_size)
277 {
278 	struct stat sbuf;
279 	int fd, ret = -1;
280 	ssize_t n;
281 
282 	/* Open file */
283 	fd = open(filename, O_RDONLY | O_BINARY);
284 	if (fd < 0) {
285 		printf("Can't open file %s (err=%d => %s)\n",
286 		       filename, errno, strerror(errno));
287 		return -1;
288 	}
289 
290 	/* Compute file size */
291 	if (fstat(fd, &sbuf) < 0) {
292 		printf("Can't fstat file %s (err=%d => %s)\n",
293 		       filename, errno, strerror(errno));
294 		goto err;
295 	}
296 
297 	/* Check file size */
298 	if (sbuf.st_size != expected_size) {
299 		printf("File %s don't have the expected size (size=%lld, expected=%d)\n",
300 		       filename, (long long)sbuf.st_size, expected_size);
301 		goto err;
302 	}
303 
304 	/* Read data */
305 	n = read(fd, data, sbuf.st_size);
306 	if (n < 0) {
307 		printf("Can't read file %s (err=%d => %s)\n",
308 		       filename, errno, strerror(errno));
309 		goto err;
310 	}
311 
312 	/* Check that we have read all the file */
313 	if (n != sbuf.st_size) {
314 		printf("Can't read all file %s (read %zd bytes, expexted %lld)\n",
315 		       filename, n, (long long)sbuf.st_size);
316 		goto err;
317 	}
318 
319 	ret = 0;
320 
321 err:
322 	close(fd);
323 	return ret;
324 }
325 
get_random_data(void * data,int size)326 static int get_random_data(void *data, int size)
327 {
328 	unsigned char *tmp = data;
329 	struct timespec date;
330 	int i, ret = 0;
331 
332 	if (!tmp) {
333 		printf("%s: pointer data is NULL\n", __func__);
334 		ret = -1;
335 		goto out;
336 	}
337 
338 	ret = clock_gettime(CLOCK_MONOTONIC, &date);
339 	if (ret < 0) {
340 		printf("%s: clock_gettime has failed (err=%d, str=%s)\n",
341 		       __func__, ret, strerror(errno));
342 		goto out;
343 	}
344 
345 	srandom(date.tv_nsec);
346 
347 	for (i = 0; i < size; i++) {
348 		*tmp = random() & 0xff;
349 		tmp++;
350 	}
351 
352  out:
353 	return ret;
354 }
355 
fit_image_setup_cipher(struct image_cipher_info * info,const char * keydir,void * fit,const char * image_name,int image_noffset,int noffset)356 static int fit_image_setup_cipher(struct image_cipher_info *info,
357 				  const char *keydir, void *fit,
358 				  const char *image_name, int image_noffset,
359 				  int noffset)
360 {
361 	char *algo_name;
362 	char filename[128];
363 	int ret = -1;
364 
365 	if (fit_image_cipher_get_algo(fit, noffset, &algo_name)) {
366 		printf("Can't get algo name for cipher in image '%s'\n",
367 		       image_name);
368 		goto out;
369 	}
370 
371 	info->keydir = keydir;
372 
373 	/* Read the key name */
374 	info->keyname = fdt_getprop(fit, noffset, FIT_KEY_HINT, NULL);
375 	if (!info->keyname) {
376 		printf("Can't get key name for cipher in image '%s'\n",
377 		       image_name);
378 		goto out;
379 	}
380 
381 	/*
382 	 * Read the IV name
383 	 *
384 	 * If this property is not provided then mkimage will generate
385 	 * a random IV and store it in the FIT image
386 	 */
387 	info->ivname = fdt_getprop(fit, noffset, "iv-name-hint", NULL);
388 
389 	info->fit = fit;
390 	info->node_noffset = noffset;
391 	info->name = algo_name;
392 
393 	info->cipher = image_get_cipher_algo(algo_name);
394 	if (!info->cipher) {
395 		printf("Can't get algo for cipher '%s'\n", image_name);
396 		goto out;
397 	}
398 
399 	/* Read the key in the file */
400 	snprintf(filename, sizeof(filename), "%s/%s%s",
401 		 info->keydir, info->keyname, ".bin");
402 	info->key = malloc(info->cipher->key_len);
403 	if (!info->key) {
404 		printf("Can't allocate memory for key\n");
405 		ret = -1;
406 		goto out;
407 	}
408 	ret = fit_image_read_data(filename, (unsigned char *)info->key,
409 				  info->cipher->key_len);
410 	if (ret < 0)
411 		goto out;
412 
413 	info->iv = malloc(info->cipher->iv_len);
414 	if (!info->iv) {
415 		printf("Can't allocate memory for iv\n");
416 		ret = -1;
417 		goto out;
418 	}
419 
420 	if (info->ivname) {
421 		/* Read the IV in the file */
422 		snprintf(filename, sizeof(filename), "%s/%s%s",
423 			 info->keydir, info->ivname, ".bin");
424 		ret = fit_image_read_data(filename, (unsigned char *)info->iv,
425 					  info->cipher->iv_len);
426 	} else {
427 		/* Generate an ramdom IV */
428 		ret = get_random_data((void *)info->iv, info->cipher->iv_len);
429 	}
430 
431  out:
432 	return ret;
433 }
434 
fit_image_write_cipher(void * fit,int image_noffset,int noffset,const void * data,size_t size,unsigned char * data_ciphered,int data_ciphered_len)435 int fit_image_write_cipher(void *fit, int image_noffset, int noffset,
436 			   const void *data, size_t size,
437 			   unsigned char *data_ciphered, int data_ciphered_len)
438 {
439 	int ret = -1;
440 
441 	/* Replace data with ciphered data */
442 	ret = fdt_setprop(fit, image_noffset, FIT_DATA_PROP,
443 			  data_ciphered, data_ciphered_len);
444 	if (ret == -FDT_ERR_NOSPACE) {
445 		ret = -ENOSPC;
446 		goto out;
447 	}
448 	if (ret) {
449 		printf("Can't replace data with ciphered data (err = %d)\n", ret);
450 		goto out;
451 	}
452 
453 	/* add non ciphered data size */
454 	ret = fdt_setprop_u32(fit, image_noffset, "data-size-unciphered", size);
455 	if (ret == -FDT_ERR_NOSPACE) {
456 		ret = -ENOSPC;
457 		goto out;
458 	}
459 	if (ret) {
460 		printf("Can't add unciphered data size (err = %d)\n", ret);
461 		goto out;
462 	}
463 
464  out:
465 	return ret;
466 }
467 
468 static int
fit_image_process_cipher(const char * keydir,void * keydest,void * fit,const char * image_name,int image_noffset,int node_noffset,const void * data,size_t size,const char * cmdname)469 fit_image_process_cipher(const char *keydir, void *keydest, void *fit,
470 			 const char *image_name, int image_noffset,
471 			 int node_noffset, const void *data, size_t size,
472 			 const char *cmdname)
473 {
474 	struct image_cipher_info info;
475 	unsigned char *data_ciphered = NULL;
476 	int data_ciphered_len;
477 	int ret;
478 
479 	memset(&info, 0, sizeof(info));
480 
481 	ret = fit_image_setup_cipher(&info, keydir, fit, image_name,
482 				     image_noffset, node_noffset);
483 	if (ret)
484 		goto out;
485 
486 	ret = info.cipher->encrypt(&info, data, size,
487 				    &data_ciphered, &data_ciphered_len);
488 	if (ret)
489 		goto out;
490 
491 	/*
492 	 * Write the public key into the supplied FDT file; this might fail
493 	 * several times, since we try signing with successively increasing
494 	 * size values
495 	 * And, if needed, write the iv in the FIT file
496 	 */
497 	if (keydest) {
498 		ret = info.cipher->add_cipher_data(&info, keydest, fit, node_noffset);
499 		if (ret) {
500 			printf("Failed to add verification data for cipher '%s' in image '%s'\n",
501 			       info.keyname, image_name);
502 			goto out;
503 		}
504 	}
505 
506 	ret = fit_image_write_cipher(fit, image_noffset, node_noffset,
507 				     data, size,
508 				     data_ciphered, data_ciphered_len);
509 
510  out:
511 	free(data_ciphered);
512 	free((void *)info.key);
513 	free((void *)info.iv);
514 	return ret;
515 }
516 
fit_image_cipher_data(const char * keydir,void * keydest,void * fit,int image_noffset,const char * comment,int require_keys,const char * engine_id,const char * cmdname)517 int fit_image_cipher_data(const char *keydir, void *keydest,
518 			  void *fit, int image_noffset, const char *comment,
519 			  int require_keys, const char *engine_id,
520 			  const char *cmdname)
521 {
522 	const char *image_name;
523 	const void *data;
524 	size_t size;
525 	int cipher_node_offset, len;
526 
527 	/* Get image name */
528 	image_name = fit_get_name(fit, image_noffset, NULL);
529 	if (!image_name) {
530 		printf("Can't get image name\n");
531 		return -1;
532 	}
533 
534 	/* Get image data and data length */
535 	if (fit_image_get_data(fit, image_noffset, &data, &size)) {
536 		printf("Can't get image data/size\n");
537 		return -1;
538 	}
539 
540 	/*
541 	 * Don't cipher ciphered data.
542 	 *
543 	 * If the data-size-unciphered property is present the data for this
544 	 * image is already encrypted. This is important as 'mkimage -F' can be
545 	 * run multiple times on a FIT image.
546 	 */
547 	if (fdt_getprop(fit, image_noffset, "data-size-unciphered", &len))
548 		return 0;
549 	if (len != -FDT_ERR_NOTFOUND) {
550 		printf("Failure testing for data-size-unciphered\n");
551 		return -1;
552 	}
553 
554 	/* Process cipher node if present */
555 	cipher_node_offset = fdt_subnode_offset(fit, image_noffset,
556 						FIT_CIPHER_NODENAME);
557 	if (cipher_node_offset == -FDT_ERR_NOTFOUND)
558 		return 0;
559 	if (cipher_node_offset < 0) {
560 		printf("Failure getting cipher node\n");
561 		return -1;
562 	}
563 	if (!IMAGE_ENABLE_ENCRYPT || !keydir)
564 		return 0;
565 	return fit_image_process_cipher(keydir, keydest, fit, image_name,
566 		image_noffset, cipher_node_offset, data, size, cmdname);
567 }
568 
569 /**
570  * fit_image_add_verification_data() - calculate/set verig. data for image node
571  *
572  * This adds hash and signature values for an component image node.
573  *
574  * All existing hash subnodes are checked, if algorithm property is set to
575  * one of the supported hash algorithms, hash value is computed and
576  * corresponding hash node property is set, for example:
577  *
578  * Input component image node structure:
579  *
580  * o image-1 (at image_noffset)
581  *   | - data = [binary data]
582  *   o hash-1
583  *     |- algo = "sha1"
584  *
585  * Output component image node structure:
586  *
587  * o image-1 (at image_noffset)
588  *   | - data = [binary data]
589  *   o hash-1
590  *     |- algo = "sha1"
591  *     |- value = sha1(data)
592  *
593  * For signature details, please see doc/uImage.FIT/signature.txt
594  *
595  * @keydir	Directory containing *.key and *.crt files (or NULL)
596  * @keydest	FDT Blob to write public keys into (NULL if none)
597  * @fit:	Pointer to the FIT format image header
598  * @image_noffset: Requested component image node
599  * @comment:	Comment to add to signature nodes
600  * @require_keys: Mark all keys as 'required'
601  * @engine_id:	Engine to use for signing
602  * @return: 0 on success, <0 on failure
603  */
fit_image_add_verification_data(const char * keydir,const char * keyfile,void * keydest,void * fit,int image_noffset,const char * comment,int require_keys,const char * engine_id,const char * cmdname)604 int fit_image_add_verification_data(const char *keydir, const char *keyfile,
605 		void *keydest, void *fit, int image_noffset,
606 		const char *comment, int require_keys, const char *engine_id,
607 		const char *cmdname)
608 {
609 	const char *image_name;
610 	const void *data;
611 	size_t size;
612 	int noffset;
613 
614 	/* Get image data and data length */
615 	if (fit_image_get_data(fit, image_noffset, &data, &size)) {
616 		printf("Can't get image data/size\n");
617 		return -1;
618 	}
619 
620 	image_name = fit_get_name(fit, image_noffset, NULL);
621 
622 	/* Process all hash subnodes of the component image node */
623 	for (noffset = fdt_first_subnode(fit, image_noffset);
624 	     noffset >= 0;
625 	     noffset = fdt_next_subnode(fit, noffset)) {
626 		const char *node_name;
627 		int ret = 0;
628 
629 		/*
630 		 * Check subnode name, must be equal to "hash" or "signature".
631 		 * Multiple hash nodes require unique unit node
632 		 * names, e.g. hash-1, hash-2, signature-1, etc.
633 		 */
634 		node_name = fit_get_name(fit, noffset, NULL);
635 		if (!strncmp(node_name, FIT_HASH_NODENAME,
636 			     strlen(FIT_HASH_NODENAME))) {
637 			ret = fit_image_process_hash(fit, image_name, noffset,
638 						data, size);
639 		} else if (IMAGE_ENABLE_SIGN && (keydir || keyfile) &&
640 			   !strncmp(node_name, FIT_SIG_NODENAME,
641 				strlen(FIT_SIG_NODENAME))) {
642 			ret = fit_image_process_sig(keydir, keyfile, keydest,
643 				fit, image_name, noffset, data, size,
644 				comment, require_keys, engine_id, cmdname);
645 		}
646 		if (ret)
647 			return ret;
648 	}
649 
650 	return 0;
651 }
652 
653 struct strlist {
654 	int count;
655 	char **strings;
656 };
657 
strlist_init(struct strlist * list)658 static void strlist_init(struct strlist *list)
659 {
660 	memset(list, '\0', sizeof(*list));
661 }
662 
strlist_free(struct strlist * list)663 static void strlist_free(struct strlist *list)
664 {
665 	int i;
666 
667 	for (i = 0; i < list->count; i++)
668 		free(list->strings[i]);
669 	free(list->strings);
670 }
671 
strlist_add(struct strlist * list,const char * str)672 static int strlist_add(struct strlist *list, const char *str)
673 {
674 	char *dup;
675 
676 	dup = strdup(str);
677 	list->strings = realloc(list->strings,
678 				(list->count + 1) * sizeof(char *));
679 	if (!list || !str)
680 		return -1;
681 	list->strings[list->count++] = dup;
682 
683 	return 0;
684 }
685 
fit_config_get_image_list(void * fit,int noffset,int * lenp,int * allow_missingp)686 static const char *fit_config_get_image_list(void *fit, int noffset,
687 		int *lenp, int *allow_missingp)
688 {
689 	static const char default_list[] = FIT_KERNEL_PROP "\0"
690 			FIT_FDT_PROP;
691 	const char *prop;
692 
693 	/* If there is an "image" property, use that */
694 	prop = fdt_getprop(fit, noffset, "sign-images", lenp);
695 	if (prop) {
696 		*allow_missingp = 0;
697 		return *lenp ? prop : NULL;
698 	}
699 
700 	/* Default image list */
701 	*allow_missingp = 1;
702 	*lenp = sizeof(default_list);
703 
704 	return default_list;
705 }
706 
fit_config_add_hash(void * fit,const char * conf_name,const char * sig_name,struct strlist * node_inc,const char * iname,int image_noffset)707 static int fit_config_add_hash(void *fit, const char *conf_name, const char *sig_name,
708 			       struct strlist *node_inc, const char *iname, int image_noffset)
709 {
710 	char name[200], path[200];
711 	int noffset;
712 	int hash_count;
713 	int ret;
714 
715 	ret = fdt_get_path(fit, image_noffset, path, sizeof(path));
716 	if (ret < 0)
717 		goto err_path;
718 	if (strlist_add(node_inc, path))
719 		goto err_mem;
720 
721 	snprintf(name, sizeof(name), "%s/%s", FIT_CONFS_PATH,
722 		 conf_name);
723 
724 	/* Add all this image's hashes */
725 	hash_count = 0;
726 	for (noffset = fdt_first_subnode(fit, image_noffset);
727 	     noffset >= 0;
728 	     noffset = fdt_next_subnode(fit, noffset)) {
729 		const char *name = fit_get_name(fit, noffset, NULL);
730 
731 		if (strncmp(name, FIT_HASH_NODENAME,
732 			    strlen(FIT_HASH_NODENAME)))
733 			continue;
734 		ret = fdt_get_path(fit, noffset, path, sizeof(path));
735 		if (ret < 0)
736 			goto err_path;
737 		if (strlist_add(node_inc, path))
738 			goto err_mem;
739 		hash_count++;
740 	}
741 
742 	if (!hash_count) {
743 		printf("Failed to find any hash nodes in configuration '%s/%s' image '%s' - without these it is not possible to verify this image\n",
744 		       conf_name, sig_name, iname);
745 		return -ENOMSG;
746 	}
747 
748 	/* Add this image's cipher node if present */
749 	noffset = fdt_subnode_offset(fit, image_noffset,
750 				     FIT_CIPHER_NODENAME);
751 	if (noffset != -FDT_ERR_NOTFOUND) {
752 		if (noffset < 0) {
753 			printf("Failed to get cipher node in configuration '%s/%s' image '%s': %s\n",
754 			       conf_name, sig_name, iname,
755 			       fdt_strerror(noffset));
756 			return -EIO;
757 		}
758 		ret = fdt_get_path(fit, noffset, path, sizeof(path));
759 		if (ret < 0)
760 			goto err_path;
761 		if (strlist_add(node_inc, path))
762 			goto err_mem;
763 	}
764 
765 	return 0;
766 
767 err_mem:
768 	printf("Out of memory processing configuration '%s/%s'\n", conf_name,
769 	       sig_name);
770 	return -ENOMEM;
771 
772 err_path:
773 	printf("Failed to get path for image '%s' in configuration '%s/%s': %s\n",
774 	       iname, conf_name, sig_name, fdt_strerror(ret));
775 	return -ENOENT;
776 }
777 
fit_config_get_hash_list(void * fit,int conf_noffset,int sig_offset,struct strlist * node_inc)778 static int fit_config_get_hash_list(void *fit, int conf_noffset,
779 				    int sig_offset, struct strlist *node_inc)
780 {
781 	int allow_missing;
782 	const char *prop, *iname, *end;
783 	const char *conf_name, *sig_name;
784 	char name[200];
785 	int image_count;
786 	int ret, len;
787 
788 	conf_name = fit_get_name(fit, conf_noffset, NULL);
789 	sig_name = fit_get_name(fit, sig_offset, NULL);
790 
791 	/*
792 	 * Build a list of nodes we need to hash. We always need the root
793 	 * node and the configuration.
794 	 */
795 	strlist_init(node_inc);
796 	snprintf(name, sizeof(name), "%s/%s", FIT_CONFS_PATH, conf_name);
797 	if (strlist_add(node_inc, "/") ||
798 	    strlist_add(node_inc, name))
799 		goto err_mem;
800 
801 	/* Get a list of images that we intend to sign */
802 	prop = fit_config_get_image_list(fit, sig_offset, &len,
803 					&allow_missing);
804 	if (!prop)
805 		return 0;
806 
807 	/* Locate the images */
808 	end = prop + len;
809 	image_count = 0;
810 	for (iname = prop; iname < end; iname += strlen(iname) + 1) {
811 		int image_noffset;
812 		int index, max_index;
813 
814 		max_index = fdt_stringlist_count(fit, conf_noffset, iname);
815 
816 		for (index = 0; index < max_index; index++) {
817 			image_noffset = fit_conf_get_prop_node_index(fit, conf_noffset,
818 								     iname, index);
819 
820 			if (image_noffset < 0) {
821 				printf("Failed to find image '%s' in  configuration '%s/%s'\n",
822 				       iname, conf_name, sig_name);
823 				if (allow_missing)
824 					continue;
825 
826 				return -ENOENT;
827 			}
828 
829 			ret = fit_config_add_hash(fit, conf_name,
830 						  sig_name, node_inc,
831 						  iname, image_noffset);
832 			if (ret < 0)
833 				return ret;
834 
835 			image_count++;
836 		}
837 	}
838 
839 	if (!image_count) {
840 		printf("Failed to find any images for configuration '%s/%s'\n",
841 		       conf_name, sig_name);
842 		return -ENOMSG;
843 	}
844 
845 	return 0;
846 
847 err_mem:
848 	printf("Out of memory processing configuration '%s/%s'\n", conf_name,
849 	       sig_name);
850 	return -ENOMEM;
851 }
852 
fit_config_get_data(void * fit,int conf_noffset,int noffset,struct image_region ** regionp,int * region_countp,char ** region_propp,int * region_proplen)853 static int fit_config_get_data(void *fit, int conf_noffset, int noffset,
854 		struct image_region **regionp, int *region_countp,
855 		char **region_propp, int *region_proplen)
856 {
857 	char * const exc_prop[] = {"data"};
858 	struct strlist node_inc;
859 	struct image_region *region;
860 	struct fdt_region fdt_regions[100];
861 	const char *conf_name, *sig_name;
862 	char path[200];
863 	int count, i;
864 	char *region_prop;
865 	int ret, len;
866 
867 	conf_name = fit_get_name(fit, conf_noffset, NULL);
868 	sig_name = fit_get_name(fit, noffset, NULL);
869 	debug("%s: conf='%s', sig='%s'\n", __func__, conf_name, sig_name);
870 
871 	/* Get a list of nodes we want to hash */
872 	ret = fit_config_get_hash_list(fit, conf_noffset, noffset, &node_inc);
873 	if (ret)
874 		return ret;
875 
876 	/* Get a list of regions to hash */
877 	count = fdt_find_regions(fit, node_inc.strings, node_inc.count,
878 			exc_prop, ARRAY_SIZE(exc_prop),
879 			fdt_regions, ARRAY_SIZE(fdt_regions),
880 			path, sizeof(path), 1);
881 	if (count < 0) {
882 		printf("Failed to hash configuration '%s/%s': %s\n", conf_name,
883 		       sig_name, fdt_strerror(ret));
884 		return -EIO;
885 	}
886 	if (count == 0) {
887 		printf("No data to hash for configuration '%s/%s': %s\n",
888 		       conf_name, sig_name, fdt_strerror(ret));
889 		return -EINVAL;
890 	}
891 
892 	/* Build our list of data blocks */
893 	region = fit_region_make_list(fit, fdt_regions, count, NULL);
894 	if (!region) {
895 		printf("Out of memory hashing configuration '%s/%s'\n",
896 		       conf_name, sig_name);
897 		return -ENOMEM;
898 	}
899 
900 	/* Create a list of all hashed properties */
901 	debug("Hash nodes:\n");
902 	for (i = len = 0; i < node_inc.count; i++) {
903 		debug("   %s\n", node_inc.strings[i]);
904 		len += strlen(node_inc.strings[i]) + 1;
905 	}
906 	region_prop = malloc(len);
907 	if (!region_prop) {
908 		printf("Out of memory setting up regions for configuration '%s/%s'\n",
909 		       conf_name, sig_name);
910 		return -ENOMEM;
911 	}
912 	for (i = len = 0; i < node_inc.count;
913 	     len += strlen(node_inc.strings[i]) + 1, i++)
914 		strcpy(region_prop + len, node_inc.strings[i]);
915 	strlist_free(&node_inc);
916 
917 	*region_countp = count;
918 	*regionp = region;
919 	*region_propp = region_prop;
920 	*region_proplen = len;
921 
922 	return 0;
923 }
924 
fit_config_process_sig(const char * keydir,const char * keyfile,void * keydest,void * fit,const char * conf_name,int conf_noffset,int noffset,const char * comment,int require_keys,const char * engine_id,const char * cmdname)925 static int fit_config_process_sig(const char *keydir, const char *keyfile,
926 		void *keydest,	void *fit, const char *conf_name,
927 		int conf_noffset, int noffset, const char *comment,
928 		int require_keys, const char *engine_id, const char *cmdname)
929 {
930 	struct image_sign_info info;
931 	const char *node_name;
932 	struct image_region *region;
933 	char *region_prop;
934 	int region_proplen;
935 	int region_count;
936 	uint8_t *value;
937 	uint value_len;
938 	int ret;
939 
940 	node_name = fit_get_name(fit, noffset, NULL);
941 	if (fit_config_get_data(fit, conf_noffset, noffset, &region,
942 				&region_count, &region_prop, &region_proplen))
943 		return -1;
944 
945 	if (fit_image_setup_sig(&info, keydir, keyfile, fit, conf_name, noffset,
946 				require_keys ? "conf" : NULL, engine_id))
947 		return -1;
948 
949 	ret = info.crypto->sign(&info, region, region_count, &value,
950 				&value_len);
951 	free(region);
952 	if (ret) {
953 		printf("Failed to sign '%s' signature node in '%s' conf node\n",
954 		       node_name, conf_name);
955 
956 		/* We allow keys to be missing */
957 		if (ret == -ENOENT)
958 			return 0;
959 		return -1;
960 	}
961 
962 	ret = fit_image_write_sig(fit, noffset, value, value_len, comment,
963 				region_prop, region_proplen, cmdname);
964 	if (ret) {
965 		if (ret == -FDT_ERR_NOSPACE)
966 			return -ENOSPC;
967 		printf("Can't write signature for '%s' signature node in '%s' conf node: %s\n",
968 		       node_name, conf_name, fdt_strerror(ret));
969 		return -1;
970 	}
971 	free(value);
972 	free(region_prop);
973 
974 	/* Get keyname again, as FDT has changed and invalidated our pointer */
975 	info.keyname = fdt_getprop(fit, noffset, FIT_KEY_HINT, NULL);
976 
977 	/* Write the public key into the supplied FDT file */
978 	if (keydest) {
979 		ret = info.crypto->add_verify_data(&info, keydest);
980 		if (ret) {
981 			printf("Failed to add verification data for '%s' signature node in '%s' configuration node\n",
982 			       node_name, conf_name);
983 		}
984 		return ret;
985 	}
986 
987 	return 0;
988 }
989 
fit_config_add_verification_data(const char * keydir,const char * keyfile,void * keydest,void * fit,int conf_noffset,const char * comment,int require_keys,const char * engine_id,const char * cmdname)990 static int fit_config_add_verification_data(const char *keydir,
991 		const char *keyfile, void *keydest, void *fit, int conf_noffset,
992 		const char *comment, int require_keys, const char *engine_id,
993 		const char *cmdname)
994 {
995 	const char *conf_name;
996 	int noffset;
997 
998 	conf_name = fit_get_name(fit, conf_noffset, NULL);
999 
1000 	/* Process all hash subnodes of the configuration node */
1001 	for (noffset = fdt_first_subnode(fit, conf_noffset);
1002 	     noffset >= 0;
1003 	     noffset = fdt_next_subnode(fit, noffset)) {
1004 		const char *node_name;
1005 		int ret = 0;
1006 
1007 		node_name = fit_get_name(fit, noffset, NULL);
1008 		if (!strncmp(node_name, FIT_SIG_NODENAME,
1009 			     strlen(FIT_SIG_NODENAME))) {
1010 			ret = fit_config_process_sig(keydir, keyfile, keydest,
1011 				fit, conf_name, conf_noffset, noffset, comment,
1012 				require_keys, engine_id, cmdname);
1013 		}
1014 		if (ret)
1015 			return ret;
1016 	}
1017 
1018 	return 0;
1019 }
1020 
fit_cipher_data(const char * keydir,void * keydest,void * fit,const char * comment,int require_keys,const char * engine_id,const char * cmdname)1021 int fit_cipher_data(const char *keydir, void *keydest, void *fit,
1022 		    const char *comment, int require_keys,
1023 		    const char *engine_id, const char *cmdname)
1024 {
1025 	int images_noffset;
1026 	int noffset;
1027 	int ret;
1028 
1029 	/* Find images parent node offset */
1030 	images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
1031 	if (images_noffset < 0) {
1032 		printf("Can't find images parent node '%s' (%s)\n",
1033 		       FIT_IMAGES_PATH, fdt_strerror(images_noffset));
1034 		return images_noffset;
1035 	}
1036 
1037 	/* Process its subnodes, print out component images details */
1038 	for (noffset = fdt_first_subnode(fit, images_noffset);
1039 	     noffset >= 0;
1040 	     noffset = fdt_next_subnode(fit, noffset)) {
1041 		/*
1042 		 * Direct child node of the images parent node,
1043 		 * i.e. component image node.
1044 		 */
1045 		ret = fit_image_cipher_data(keydir, keydest,
1046 					    fit, noffset, comment,
1047 					    require_keys, engine_id,
1048 					    cmdname);
1049 		if (ret)
1050 			return ret;
1051 	}
1052 
1053 	return 0;
1054 }
1055 
fit_add_verification_data(const char * keydir,const char * keyfile,void * keydest,void * fit,const char * comment,int require_keys,const char * engine_id,const char * cmdname)1056 int fit_add_verification_data(const char *keydir, const char *keyfile,
1057 			      void *keydest, void *fit, const char *comment,
1058 			      int require_keys, const char *engine_id,
1059 			      const char *cmdname)
1060 {
1061 	int images_noffset, confs_noffset;
1062 	int noffset;
1063 	int ret;
1064 
1065 	/* Find images parent node offset */
1066 	images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
1067 	if (images_noffset < 0) {
1068 		printf("Can't find images parent node '%s' (%s)\n",
1069 		       FIT_IMAGES_PATH, fdt_strerror(images_noffset));
1070 		return images_noffset;
1071 	}
1072 
1073 	/* Process its subnodes, print out component images details */
1074 	for (noffset = fdt_first_subnode(fit, images_noffset);
1075 	     noffset >= 0;
1076 	     noffset = fdt_next_subnode(fit, noffset)) {
1077 		/*
1078 		 * Direct child node of the images parent node,
1079 		 * i.e. component image node.
1080 		 */
1081 		ret = fit_image_add_verification_data(keydir, keyfile, keydest,
1082 				fit, noffset, comment, require_keys, engine_id,
1083 				cmdname);
1084 		if (ret)
1085 			return ret;
1086 	}
1087 
1088 	/* If there are no keys, we can't sign configurations */
1089 	if (!IMAGE_ENABLE_SIGN || !(keydir || keyfile))
1090 		return 0;
1091 
1092 	/* Find configurations parent node offset */
1093 	confs_noffset = fdt_path_offset(fit, FIT_CONFS_PATH);
1094 	if (confs_noffset < 0) {
1095 		printf("Can't find images parent node '%s' (%s)\n",
1096 		       FIT_CONFS_PATH, fdt_strerror(confs_noffset));
1097 		return -ENOENT;
1098 	}
1099 
1100 	/* Process its subnodes, print out component images details */
1101 	for (noffset = fdt_first_subnode(fit, confs_noffset);
1102 	     noffset >= 0;
1103 	     noffset = fdt_next_subnode(fit, noffset)) {
1104 		ret = fit_config_add_verification_data(keydir, keyfile, keydest,
1105 						       fit, noffset, comment,
1106 						       require_keys,
1107 						       engine_id, cmdname);
1108 		if (ret)
1109 			return ret;
1110 	}
1111 
1112 	return 0;
1113 }
1114 
1115 #ifdef CONFIG_FIT_SIGNATURE
fit_check_sign(const void * fit,const void * key,const char * fit_uname_config)1116 int fit_check_sign(const void *fit, const void *key,
1117 		   const char *fit_uname_config)
1118 {
1119 	int cfg_noffset;
1120 	int ret;
1121 
1122 	cfg_noffset = fit_conf_get_node(fit, fit_uname_config);
1123 	if (!cfg_noffset)
1124 		return -1;
1125 
1126 	printf("Verifying Hash Integrity for node '%s'... ",
1127 	       fdt_get_name(fit, cfg_noffset, NULL));
1128 	ret = fit_config_verify(fit, cfg_noffset);
1129 	if (ret)
1130 		return ret;
1131 	printf("Verified OK, loading images\n");
1132 	ret = bootm_host_load_images(fit, cfg_noffset);
1133 
1134 	return ret;
1135 }
1136 #endif
1137