• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2018 The ChromiumOS Authors
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  *
5  * A reference implementation for AP (and supporting images) firmware updater.
6  */
7 
8 #include <assert.h>
9 #include <ctype.h>
10 #include <sys/stat.h>
11 
12 #include "2rsa.h"
13 #include "cbfstool.h"
14 #include "futility.h"
15 #include "host_misc.h"
16 #include "platform_csme.h"
17 #include "updater.h"
18 #include "util_misc.h"
19 
20 static const char ROOTKEY_HASH_DEV[] =
21 		"b11d74edd286c144e1135b49e7f0bc20cf041f10";
22 
23 enum target_type {
24 	TARGET_SELF,
25 	TARGET_UPDATE,
26 };
27 
28 enum rootkey_compat_result {
29 	ROOTKEY_COMPAT_OK,
30 	ROOTKEY_COMPAT_ERROR,
31 	ROOTKEY_COMPAT_REKEY,
32 	ROOTKEY_COMPAT_REKEY_TO_DEV,
33 };
34 
print_dut_properties(struct updater_config * cfg)35 static void print_dut_properties(struct updater_config *cfg)
36 {
37 	int i;
38 
39 	/*
40 	 * There may be error messages when fetching properties from active
41 	 * system, so we want to peek at them first and then print out.
42 	 */
43 	VB2_DEBUG("Scanning system properties...\n");
44 	for (i = 0; i < DUT_PROP_MAX; i++)
45 		dut_get_property((enum dut_property_type)i, cfg);
46 
47 	printf("System properties: [");
48 	for (i = 0; i < DUT_PROP_MAX; i++) {
49 		printf("%d,",
50 		       dut_get_property((enum dut_property_type)i, cfg));
51 	}
52 	printf("]\n");
53 }
54 
55 /*
56  * Overrides the return value of a system property.
57  * After invoked, next call to dut_get_property(type, cfg) will return
58  * the given value.
59  */
override_dut_property(enum dut_property_type property_type,struct updater_config * cfg,int value)60 static void override_dut_property(enum dut_property_type property_type,
61 				  struct updater_config *cfg, int value)
62 {
63 	struct dut_property *prop;
64 
65 	assert(property_type < DUT_PROP_MAX);
66 	prop = &cfg->dut_properties[property_type];
67 	prop->initialized = 1;
68 	prop->value = value;
69 }
70 
71 /*
72  * Overrides DUT properties with default values.
73  * With emulation, dut_get_property() calls would fail without specifying the
74  * fake DUT properties via --sys_props. Therefore, this function provides
75  * reasonable default values for emulation.
76  */
override_properties_with_default(struct updater_config * cfg)77 static void override_properties_with_default(struct updater_config *cfg)
78 {
79 	assert(cfg->emulation);
80 
81 	override_dut_property(DUT_PROP_MAINFW_ACT, cfg, SLOT_A);
82 	override_dut_property(DUT_PROP_TPM_FWVER, cfg, 0x10001);
83 	override_dut_property(DUT_PROP_PLATFORM_VER, cfg, 0);
84 	override_dut_property(DUT_PROP_WP_HW, cfg, 0);
85 	override_dut_property(DUT_PROP_WP_SW_AP, cfg, 0);
86 	override_dut_property(DUT_PROP_WP_SW_EC, cfg, 0);
87 }
88 
89 /*
90  * Overrides DUT properties from a given list.
91  * The list should be string of integers eliminated by comma and/or space.
92  * For example, "1 2 3" and "1,2,3" both overrides first 3 properties.
93  * To skip some properties you have to use comma, for example
94  * "1, , 3" will only override the first and 3rd properties.
95  * Invalid characters and fields will be ignored.
96  *
97  * The current implementation is only for unit testing.
98  * In future we may extend this with name=value so users can use it easily on
99  * actual systems.
100  */
override_properties_from_list(const char * override_list,struct updater_config * cfg)101 static void override_properties_from_list(const char *override_list,
102 					  struct updater_config *cfg)
103 {
104 	const char *s = override_list;
105 	char *e, c;
106 	int i = 0, wait_comma = 0;
107 	long int v;
108 
109 	VB2_DEBUG("Input is <%s>\n", override_list);
110 	for (c = *s; c; c = *++s) {
111 		if (c == ',') {
112 			if (!wait_comma)
113 				i++;
114 			wait_comma = 0;
115 		}
116 		if (!isascii(c) || !(isdigit(c) || c == '-'))
117 			continue;
118 		if (i >= DUT_PROP_MAX) {
119 			ERROR("Too many fields (max is %d): %s.\n",
120 			      DUT_PROP_MAX, override_list);
121 			return;
122 		}
123 		v = strtol(s, &e, 0);
124 		s = e - 1;
125 		VB2_DEBUG("property[%d].value = %ld\n", i, v);
126 		override_dut_property((enum dut_property_type)i, cfg, v);
127 		wait_comma = 1;
128 		i++;
129 	}
130 }
131 
get_config_quirk(enum quirk_types quirk,const struct updater_config * cfg)132 int get_config_quirk(enum quirk_types quirk, const struct updater_config *cfg)
133 {
134 	assert(quirk < QUIRK_MAX);
135 	return cfg->quirks[quirk].value;
136 }
137 
updater_list_config_quirks(const struct updater_config * cfg)138 void updater_list_config_quirks(const struct updater_config *cfg)
139 {
140 	const struct quirk_entry *entry = cfg->quirks;
141 	int i;
142 
143 	printf("Supported quirks:\n");
144 	for (i = 0; i < QUIRK_MAX; i++, entry++) {
145 		printf(" '%s': %s (default: %d)\n", entry->name,
146 		       entry->help ? entry->help : "(no description)",
147 		       get_config_quirk((enum quirk_types)i, cfg));
148 	}
149 }
150 
151 /*
152  * Applies a quirk if applicable (the value should be non-zero).
153  * Returns 0 on success, otherwise failure.
154  */
try_apply_quirk(enum quirk_types quirk,struct updater_config * cfg)155 static int try_apply_quirk(enum quirk_types quirk, struct updater_config *cfg)
156 {
157 	const struct quirk_entry *entry = cfg->quirks + quirk;
158 	assert(quirk < QUIRK_MAX);
159 
160 	if (!entry->value)
161 		return 0;
162 
163 	if (!entry->apply) {
164 		ERROR("<%s> not implemented.\n", entry->name);
165 		return -1;
166 	}
167 	VB2_DEBUG("Applying quirk <%s>.\n", entry->name);
168 	return entry->apply(cfg);
169 }
170 
171 /*
172  * Initialize the updater_config quirks from a list of settings.
173  * Returns 0 on success, otherwise failure.
174  */
setup_config_quirks(const char * quirks,struct updater_config * cfg)175 static int setup_config_quirks(const char *quirks, struct updater_config *cfg)
176 {
177 	/*
178 	 * The list should be in NAME[=VALUE],...
179 	 * Value defaults to 1 if not specified.
180 	 */
181 	int r = 0;
182 	char *buf = strdup(quirks);
183 	char *token;
184 	const char *delimiters = ", \n\r\t";
185 
186 	token = strtok(buf, delimiters);
187 	for (; token; token = strtok(NULL, delimiters)) {
188 		const char *name = token;
189 		char *equ = strchr(token, '=');
190 		int i, value = 1;
191 		struct quirk_entry *entry = cfg->quirks;
192 
193 		if (!*name)
194 			continue;
195 
196 		if (equ) {
197 			*equ = '\0';
198 			value = strtol(equ + 1, NULL, 0);
199 		}
200 
201 		VB2_DEBUG("Looking for quirk <%s=%d>.\n", name, value);
202 		for (i = 0; i < QUIRK_MAX; i++, entry++) {
203 			if (strcmp(name, entry->name))
204 				continue;
205 			entry->value = value;
206 			VB2_DEBUG("Set quirk %s to %d.\n", entry->name, value);
207 			break;
208 		}
209 		if (i >= QUIRK_MAX) {
210 			ERROR("Unknown quirk: %s\n", name);
211 			r++;
212 		}
213 	}
214 	free(buf);
215 	return r;
216 }
217 
218 /*
219  * Checks if the section is filled with given character.
220  * If section size is 0, return 0. If section is not empty, return non-zero if
221  * the section is filled with same character c, otherwise 0.
222  */
section_is_filled_with(const struct firmware_section * section,uint8_t c)223 static int section_is_filled_with(const struct firmware_section *section,
224 				  uint8_t c)
225 {
226 	uint32_t i;
227 	if (!section->size)
228 		return 0;
229 	for (i = 0; i < section->size; i++)
230 		if (section->data[i] != c)
231 			return 0;
232 	return 1;
233 }
234 
235 /*
236  * Decides which target in RW firmware to manipulate.
237  * The `target` argument specifies if we want to know "the section to be
238  * update" (TARGET_UPDATE), or "the (active) section * to check" (TARGET_SELF).
239  * Returns the section name if success, otherwise NULL.
240  */
decide_rw_target(struct updater_config * cfg,enum target_type target)241 static const char *decide_rw_target(struct updater_config *cfg,
242 				    enum target_type target)
243 {
244 	const char *a = FMAP_RW_SECTION_A, *b = FMAP_RW_SECTION_B;
245 	int slot = dut_get_property(DUT_PROP_MAINFW_ACT, cfg);
246 
247 	switch (slot) {
248 	case SLOT_A:
249 		return target == TARGET_UPDATE ? b : a;
250 
251 	case SLOT_B:
252 		return target == TARGET_UPDATE ? a : b;
253 	}
254 
255 	return NULL;
256 }
257 
258 /*
259  * Sets any needed DUT properties to indicate system should try the new
260  * firmware on next boot.
261  * The `target` argument is an FMAP section name indicating which to try.
262  * Returns 0 if success, non-zero if error.
263  */
set_try_cookies(struct updater_config * cfg,const char * target,int has_update)264 static int set_try_cookies(struct updater_config *cfg, const char *target,
265 			   int has_update)
266 {
267 	int tries = 17;
268 	const char *slot;
269 
270 	if (!has_update)
271 		tries = 0;
272 
273 	/* Find new slot according to target (section) name. */
274 	if (strcmp(target, FMAP_RW_SECTION_A) == 0)
275 		slot = FWACT_A;
276 	else if (strcmp(target, FMAP_RW_SECTION_B) == 0)
277 		slot = FWACT_B;
278 	else {
279 		ERROR("Unknown target: %s\n", target);
280 		return -1;
281 	}
282 
283 	if (cfg->emulation) {
284 		INFO("(emulation) %s slot %s on next boot, try_count=%d.\n",
285 		     has_update ? "Try" : "Keep", slot, tries);
286 		return 0;
287 	}
288 
289 	if (dut_set_property_string("fw_try_next", slot, cfg)) {
290 		ERROR("Failed to set fw_try_next to %s.\n", slot);
291 		return -1;
292 	}
293 	if (!has_update &&
294 	    dut_set_property_string("fw_result", "success", cfg)) {
295 		ERROR("Failed to set fw_result to success.\n");
296 		return -1;
297 	}
298 
299 	if (dut_set_property_int("fw_try_count", tries, cfg)) {
300 		ERROR("Failed to set fw_try_count to %d.\n", tries);
301 		return -1;
302 	}
303 
304 	return 0;
305 }
306 
307 /*
308  * Returns True if we should start the update process for given image.
309  */
has_valid_update(struct updater_config * cfg,const struct firmware_image * image,const char * section_name,int is_host)310 static int has_valid_update(struct updater_config *cfg,
311 			const struct firmware_image *image,
312 			const char *section_name,
313 			int is_host)
314 {
315 	if (!image->data) {
316 		VB2_DEBUG("No data in <%s> image.\n", image->programmer);
317 		return 0;
318 	}
319 	if (section_name && !firmware_section_exists(image, section_name)) {
320 		VB2_DEBUG("Image %s<%s> does not have section %s.\n",
321 			  image->file_name, image->programmer, section_name);
322 		return 0;
323 	}
324 	/* Currently only host emulation is supported. */
325 	if (cfg->emulation && !is_host) {
326 		INFO("(emulation) Update %s from %s to %s (%d bytes), "
327 		     "skipped for non-host targets in emulation.\n",
328 		     section_name ? section_name : "whole image",
329 		     image->file_name, image->programmer, image->size);
330 		return 0;
331 	}
332 	return 1;
333 }
334 
335 /*
336  * Preserve the GBB contents from image_from to image_to.
337  * HWID is always preserved, and flags are preserved only if preserve_flags set.
338  * Returns 0 if success, otherwise -1 if GBB header can't be found or if HWID is
339  * too large.
340  */
preserve_gbb(const struct firmware_image * image_from,struct firmware_image * image_to,int preserve_flags,int override_flags,uint64_t override_value)341 static int preserve_gbb(const struct firmware_image *image_from,
342 			struct firmware_image *image_to,
343 			int preserve_flags, int override_flags,
344 			uint64_t override_value)
345 {
346 	const struct vb2_gbb_header *gbb_from;
347 	struct vb2_gbb_header *gbb_to;
348 
349 	/* Cast to non-const because we do want to change GBB contents later. */
350 	gbb_to = (struct vb2_gbb_header *)find_gbb(image_to);
351 
352 	/*
353 	 * For all cases, we need a valid gbb_to. Note for 'override GBB flags
354 	 * on a erased device', we only need gbb_to, not gbb_from.
355 	 */
356 	if (!gbb_to)
357 		return -1;
358 
359 	gbb_from = find_gbb(image_from);
360 
361 	/* Preserve (for non-factory mode) or override flags. */
362 	if (override_flags)
363 		gbb_to->flags = override_value;
364 	else if (preserve_flags && gbb_from)
365 		gbb_to->flags = gbb_from->flags;
366 
367 	if (!gbb_from)
368 		return -1;
369 
370 	/* Preserve HWID. */
371 	return futil_set_gbb_hwid(
372 			gbb_to, (const char *)gbb_from + gbb_from->hwid_offset);
373 }
374 
375 /*
376  * Preserves the regions locked by Intel management engine.
377  */
preserve_management_engine(struct updater_config * cfg,const struct firmware_image * image_from,struct firmware_image * image_to)378 static int preserve_management_engine(struct updater_config *cfg,
379 				      const struct firmware_image *image_from,
380 				      struct firmware_image *image_to)
381 {
382 	struct firmware_section section;
383 
384 	find_firmware_section(&section, image_from, FMAP_SI_ME);
385 	if (!section.data) {
386 		VB2_DEBUG("Skipped because no section %s.\n", FMAP_SI_ME);
387 		return 0;
388 	}
389 	if (section_is_filled_with(&section, 0xFF)) {
390 		VB2_DEBUG("ME is probably locked - preserving %s.\n",
391 			  FMAP_SI_DESC);
392 		return preserve_firmware_section(
393 				image_from, image_to, FMAP_SI_DESC);
394 	}
395 
396 	if (!strcmp(cfg->original_programmer, FLASHROM_PROGRAMMER_INTERNAL_AP)) {
397 		if (try_apply_quirk(QUIRK_PRESERVE_ME, cfg) > 0) {
398 			VB2_DEBUG("ME needs to be preserved - preserving %s.\n",
399 				  FMAP_SI_ME);
400 			return preserve_firmware_section(image_from, image_to,
401 							 FMAP_SI_ME);
402 		}
403 	} else {
404 		VB2_DEBUG("Flashing via non-host programmer %s - no need to "
405 			  "preserve ME.\n", image_from->programmer);
406 	}
407 
408 	return 0;
409 }
410 
411 /* Preserve firmware sections by FMAP area flags. */
preserve_fmap_sections(struct firmware_image * from,struct firmware_image * to,int * count)412 static int preserve_fmap_sections(struct firmware_image *from,
413 				  struct firmware_image *to,
414 				  int *count)
415 {
416 	int i, errcnt = 0;
417 	FmapHeader *fmap = to->fmap_header;
418 	FmapAreaHeader *ah = (FmapAreaHeader*)(
419 			(uint8_t *)fmap + sizeof(FmapHeader));
420 	*count = 0;
421 
422 	for (i = 0; i < fmap->fmap_nareas; i++, ah++) {
423 		if (!(ah->area_flags & FMAP_AREA_PRESERVE))
424 			continue;
425 		/* Warning: area_name 'may' not end with NUL. */
426 		if (!firmware_section_exists(from, ah->area_name)) {
427 			VB2_DEBUG("FMAP area does not exist in source: %.*s\n",
428 				  FMAP_NAMELEN, ah->area_name);
429 			continue;
430 		}
431 		VB2_DEBUG("Preserve FMAP area: %.*s\n", FMAP_NAMELEN,
432 			  ah->area_name);
433 		errcnt += preserve_firmware_section(from, to, ah->area_name);
434 		(*count)++;
435 	}
436 
437 	return errcnt;
438 }
439 
440 /*
441  * Preserve old images without "preserve" information in FMAP.
442  * We have to use the legacy hard-coded list of names.
443  */
preserve_known_sections(struct firmware_image * from,struct firmware_image * to)444 static int preserve_known_sections(struct firmware_image *from,
445 				   struct firmware_image *to)
446 {
447 	int errcnt = 0, i;
448 	const char * const names[] = {
449 		"RW_PRESERVE",  /* Only octopus fw branch is using this. */
450 		FMAP_RO_VPD,
451 		FMAP_RW_VPD,
452 		"SMMSTORE",
453 		"RW_NVRAM",
454 		"RW_ELOG",
455 	};
456 
457 	for (i = 0; i < ARRAY_SIZE(names); i++) {
458 		if (!firmware_section_exists(from, names[i]))
459 			continue;
460 		VB2_DEBUG("Preserve firmware section: %s\n", names[i]);
461 		errcnt += preserve_firmware_section(from, to, names[i]);
462 	}
463 	return errcnt;
464 }
465 
466 /*
467  * Preserves the critical sections from the current (active) firmware.
468  * Currently preserved sections: GBB (HWID and flags), x86 ME, and any firmware
469  * sections with FMAP_AREA_PRESERVE flag set (or a list of known names).
470  * Returns 0 if success, non-zero if error.
471  */
preserve_images(struct updater_config * cfg)472 static int preserve_images(struct updater_config *cfg)
473 {
474 	int errcnt = 0, found;
475 	struct firmware_image *from = &cfg->image_current, *to = &cfg->image;
476 
477 	errcnt += preserve_gbb(from, to, !cfg->factory_update,
478 			       cfg->override_gbb_flags, cfg->gbb_flags);
479 	errcnt += preserve_management_engine(cfg, from, to);
480 	errcnt += preserve_fmap_sections(from, to, &found);
481 
482 	if (!found)
483 		errcnt += preserve_known_sections(from, to);
484 
485 	return errcnt;
486 }
487 
488 /*
489  * Compares if two sections have same size and data.
490  * Returns 0 if given sections are the same, otherwise non-zero.
491  */
compare_section(const struct firmware_section * a,const struct firmware_section * b)492 static int compare_section(const struct firmware_section *a,
493 			   const struct firmware_section *b)
494 {
495 	if (a->size != b->size)
496 		return a->size - b->size;
497 	return memcmp(a->data, b->data, a->size);
498 }
499 
500 /*
501  * Returns if the images are different (should be updated) in given section.
502  * If the section contents are the same or if the section does not exist on both
503  * images, return value is 0 (no need to update). Otherwise the return value is
504  * non-zero, indicating an update should be performed.
505  * If section_name is NULL, compare whole images.
506  */
section_needs_update(const struct firmware_image * image_from,const struct firmware_image * image_to,const char * section_name)507 static int section_needs_update(const struct firmware_image *image_from,
508 				const struct firmware_image *image_to,
509 				const char *section_name)
510 {
511 	struct firmware_section from, to;
512 
513 	if (!section_name) {
514 		if (image_from->size != image_to->size)
515 			return -1;
516 		return memcmp(image_from->data, image_to->data, image_to->size);
517 	}
518 
519 	find_firmware_section(&from, image_from, section_name);
520 	find_firmware_section(&to, image_to, section_name);
521 
522 	return compare_section(&from, &to);
523 }
524 
525 /*
526  * Checks if the system has locked AP RO (SI_DESC + Ti50 AP RO Verification).
527 
528  * b/284913015: When running on a DUT with SI_DESC, the SI_DESC may reject CPU
529  * (AP) from changing itself. And if we keep updating (and skipped SI_DESC and
530  * ME sections), the Ti50 AP RO verification via RO_GSCVD would fail because the
531  * hash was from a different SI_DESC (and not updated).
532  *
533  * As a result, we don't want to do full update in this case. However
534  * It is OK to do a full update if we are updating a remote DUT (via servo or
535  * other programmers).
536  *
537  * Returns:
538  *   True if AP is locked + verification enabled and we should skip updating RO.
539  *   Otherwise false.
540  */
is_ap_ro_locked_with_verification(struct updater_config * cfg)541 static bool is_ap_ro_locked_with_verification(struct updater_config *cfg)
542 {
543 	struct firmware_image *current = &cfg->image_current;
544 	VB2_DEBUG("Checking if the system has locked AP RO (+verif).\n");
545 
546 	if (cfg->dut_is_remote) {
547 		VB2_DEBUG("Remote DUT, assume the AP RO can be reflashed.\n");
548 		return false;
549 	}
550 	if (!firmware_section_exists(current, FMAP_RO_GSCVD)) {
551 		VB2_DEBUG("No %s, AP RO can be updated even if locked.\n", FMAP_RO_GSCVD);
552 		return false;
553 	}
554 	if (!firmware_section_exists(current, FMAP_SI_DESC)) {
555 		VB2_DEBUG("No %s, AP RO won't be locked.\n", FMAP_SI_DESC);
556 		return false;
557 	}
558 	if (!section_needs_update(&cfg->image, current, FMAP_SI_DESC)) {
559 		VB2_DEBUG("%s is exactly the same. RO update should be fine.\n", FMAP_SI_DESC);
560 		return false;
561 	}
562 	return is_flash_descriptor_locked(current);
563 }
564 
565 /* Returns true if the UNLOCK_CSME_* quirks were requested, otherwise false. */
is_unlock_csme_requested(struct updater_config * cfg)566 static bool is_unlock_csme_requested(struct updater_config *cfg)
567 {
568 	if (get_config_quirk(QUIRK_UNLOCK_CSME, cfg) ||
569 	    get_config_quirk(QUIRK_UNLOCK_CSME_EVE, cfg))
570 		return true;
571 	return false;
572 }
573 
574 /*
575  * Checks if the given firmware images are compatible with current platform.
576  * In current implementation (following Chrome OS style), we assume the platform
577  * is identical to the name before a dot (.) in firmware version.
578  * Returns 0 for success, otherwise failure.
579  */
check_compatible_platform(struct updater_config * cfg)580 static int check_compatible_platform(struct updater_config *cfg)
581 {
582 	int len;
583 	struct firmware_image *image_from = &cfg->image_current,
584 			      *image_to = &cfg->image;
585 	const char *from_dot = strchr(image_from->ro_version, '.'),
586 	           *to_dot = strchr(image_to->ro_version, '.');
587 
588 	if (!from_dot || !to_dot) {
589 		VB2_DEBUG("Missing dot (from=%p, to=%p)\n", from_dot, to_dot);
590 		return -1;
591 	}
592 	len = from_dot - image_from->ro_version + 1;
593 	VB2_DEBUG("Platform: %*.*s\n", len, len, image_from->ro_version);
594 	return strncasecmp(image_from->ro_version, image_to->ro_version, len);
595 }
596 
get_rootkey(const struct vb2_gbb_header * gbb)597 const struct vb2_packed_key *get_rootkey(
598 		const struct vb2_gbb_header *gbb)
599 {
600 	struct vb2_packed_key *key = NULL;
601 
602 	key = (struct vb2_packed_key *)((uint8_t *)gbb + gbb->rootkey_offset);
603 	if (vb2_packed_key_looks_ok(key, gbb->rootkey_size)) {
604 		ERROR("Invalid root key.\n");
605 		return NULL;
606 	}
607 	return key;
608 }
609 
610 /*
611  * Returns a keyblock key from given image section, or NULL on failure.
612  */
get_keyblock(const struct firmware_image * image,const char * section_name)613 static const struct vb2_keyblock *get_keyblock(
614 		const struct firmware_image *image,
615 		const char *section_name)
616 {
617 	struct firmware_section section;
618 
619 	if (find_firmware_section(&section, image, section_name) != 0) {
620 		ERROR("Section %s not found", section_name);
621 		return NULL;
622 	}
623 	const struct vb2_keyblock *block = (const struct vb2_keyblock *)section.data;
624 	if (vb2_check_keyblock(block, section.size, &block->keyblock_signature)) {
625 		ERROR("Invalid keyblock in %s\n", section_name);
626 		return NULL;
627 	}
628 	/* A keyblock must be followed by a vb2_fw_preamble. */
629 	if (section.size < block->keyblock_size + sizeof(struct vb2_fw_preamble)) {
630 		ERROR("Invalid section: %s\n", section_name);
631 		return NULL;
632 	}
633 	return block;
634 }
635 
636 /*
637  * Duplicates a keyblock and returns the duplicated block.
638  * The caller must free the returned keyblock after being used.
639  */
dupe_keyblock(const struct vb2_keyblock * block)640 static struct vb2_keyblock *dupe_keyblock(const struct vb2_keyblock *block)
641 {
642 	struct vb2_keyblock *new_block;
643 
644 	new_block = (struct vb2_keyblock *)malloc(block->keyblock_size);
645 	assert(new_block);
646 	memcpy(new_block, block, block->keyblock_size);
647 	return new_block;
648 }
649 
650 /*
651  * Verifies if keyblock is signed with given key.
652  * Returns 0 on success, otherwise failure.
653  */
verify_keyblock(const struct vb2_keyblock * block,const struct vb2_packed_key * sign_key)654 static int verify_keyblock(const struct vb2_keyblock *block,
655 			   const struct vb2_packed_key *sign_key) {
656 	int r;
657 	uint8_t workbuf[VB2_FIRMWARE_WORKBUF_RECOMMENDED_SIZE]
658 		__attribute__((aligned(VB2_WORKBUF_ALIGN)));
659 	struct vb2_workbuf wb;
660 	struct vb2_public_key key;
661 	struct vb2_keyblock *new_block;
662 
663 	if (block->keyblock_signature.sig_size == 0) {
664 		ERROR("Keyblock is not signed.\n");
665 		return -1;
666 	}
667 	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));
668 	if (VB2_SUCCESS != vb2_unpack_key(&key, sign_key)) {
669 		ERROR("Invalid signing key.\n");
670 		return -1;
671 	}
672 
673 	/*
674 	 * vb2_verify_keyblock will destroy the signature inside keyblock
675 	 * so we have to verify with a local copy.
676 	 */
677 	new_block = dupe_keyblock(block);
678 	r = vb2_verify_keyblock(new_block, new_block->keyblock_size, &key, &wb);
679 	free(new_block);
680 
681 	if (r != VB2_SUCCESS) {
682 		ERROR("Failed verifying keyblock.\n");
683 		return -1;
684 	}
685 	return 0;
686 }
687 
688 /*
689  * Gets the data key and firmware version from a section on firmware image.
690  * The section should contain a vb2_keyblock and a vb2_fw_preamble immediately
691  * after keyblock so we can decode and save the data key and firmware version
692  * into argument `data_key_version` and `firmware_version`.
693  * Returns 0 for success, otherwise failure.
694  */
get_key_versions(const struct firmware_image * image,const char * section_name,unsigned int * data_key_version,unsigned int * firmware_version)695 static int get_key_versions(const struct firmware_image *image,
696 			    const char *section_name,
697 			    unsigned int *data_key_version,
698 			    unsigned int *firmware_version)
699 {
700 	const struct vb2_keyblock *keyblock = get_keyblock(image, section_name);
701 	const struct vb2_fw_preamble *pre;
702 
703 	if (!keyblock)
704 		return -1;
705 	*data_key_version = keyblock->data_key.key_version;
706 	pre = (struct vb2_fw_preamble *)((uint8_t*)keyblock +
707 					 keyblock->keyblock_size);
708 	*firmware_version = pre->firmware_version;
709 	VB2_DEBUG("%s: data key version = %d, firmware version = %d\n",
710 		  image->file_name, *data_key_version, *firmware_version);
711 	return 0;
712 }
713 
714 /*
715  * Checks if the root key in ro_image can verify vblocks in rw_image.
716  * Returns 0 for success, otherwise failure.
717  */
check_compatible_root_key(const struct firmware_image * ro_image,const struct firmware_image * rw_image)718 static enum rootkey_compat_result check_compatible_root_key(
719 		const struct firmware_image *ro_image,
720 		const struct firmware_image *rw_image)
721 {
722 	const struct vb2_gbb_header *gbb = find_gbb(ro_image);
723 	const struct vb2_packed_key *rootkey;
724 	const struct vb2_keyblock *keyblock;
725 
726 	if (!gbb)
727 		return ROOTKEY_COMPAT_ERROR;
728 
729 	rootkey = get_rootkey(gbb);
730 	if (!rootkey)
731 		return ROOTKEY_COMPAT_ERROR;
732 
733 	/* Assume VBLOCK_A and VBLOCK_B are signed in same way. */
734 	keyblock = get_keyblock(rw_image, FMAP_RW_VBLOCK_A);
735 	if (!keyblock)
736 		return ROOTKEY_COMPAT_ERROR;
737 
738 	if (verify_keyblock(keyblock, rootkey) != 0) {
739 		const struct vb2_gbb_header *gbb_rw = find_gbb(rw_image);
740 		const struct vb2_packed_key *rootkey_rw = NULL;
741 		int is_same_key = 0, to_dev = 0;
742 		/*
743 		 * Try harder to provide more info.
744 		 * packed_key_sha1_string uses static buffer so don't call
745 		 * it twice in args list of one expression.
746 		 */
747 		if (gbb_rw)
748 			rootkey_rw = get_rootkey(gbb_rw);
749 		if (rootkey_rw) {
750 			if (rootkey->key_offset == rootkey_rw->key_offset &&
751 			    rootkey->key_size == rootkey_rw->key_size &&
752 			    memcmp(rootkey, rootkey_rw, rootkey->key_size +
753 				   rootkey->key_offset) == 0)
754 				is_same_key = 1;
755 			if (strcmp(packed_key_sha1_string(rootkey_rw),
756 				   ROOTKEY_HASH_DEV) == 0)
757 				to_dev = 1;
758 		}
759 		INFO("Current (RO) firmware image has root key: %s\n",
760 		     packed_key_sha1_string(rootkey));
761 		if (is_same_key) {
762 			ERROR("Rootkey is same as target (RW) image. \n"
763 			      "Maybe RW corrupted?");
764 			return ROOTKEY_COMPAT_ERROR;
765 		}
766 		WARN("Target (RW) image is signed by root key: %s%s\n",
767 		     rootkey_rw ? packed_key_sha1_string(rootkey_rw) :
768 		     "<invalid>", to_dev ? " (DEV/unsigned)" : "");
769 		return to_dev ? ROOTKEY_COMPAT_REKEY_TO_DEV :
770 				ROOTKEY_COMPAT_REKEY;
771 	}
772 	return ROOTKEY_COMPAT_OK;
773 }
774 
775 /*
776  * Returns non-zero if the RW_LEGACY needs to be updated, otherwise 0.
777  */
legacy_needs_update(struct updater_config * cfg)778 static int legacy_needs_update(struct updater_config *cfg)
779 {
780 	bool has_from, has_to;
781 	const char * const tag = "cros_allow_auto_update";
782 	const char *section = FMAP_RW_LEGACY;
783 	const char *tmp_to, *tmp_from;
784 
785 	VB2_DEBUG("Checking %s contents...\n", FMAP_RW_LEGACY);
786 
787 	tmp_to = get_firmware_image_temp_file(&cfg->image, &cfg->tempfiles);
788 	tmp_from = get_firmware_image_temp_file(&cfg->image_current,
789 						&cfg->tempfiles);
790 	if (!tmp_from || !tmp_to)
791 		return 0;
792 
793 	has_to = cbfstool_file_exists(tmp_to, section, tag);
794 	has_from = cbfstool_file_exists(tmp_from, section, tag);
795 
796 	if (!has_from || !has_to) {
797 		VB2_DEBUG("Current legacy firmware has%s updater tag (%s) and "
798 			  "target firmware has%s updater tag, won't update.\n",
799 			  has_from ? "" : " no", tag, has_to ? "" : " no");
800 		return 0;
801 	}
802 
803 	return section_needs_update(
804 			&cfg->image_current, &cfg->image, FMAP_RW_LEGACY);
805 }
806 
807 /*
808  * Checks if the given firmware image is signed with a key that won't be
809  * blocked by TPM's anti-rollback detection.
810  * Returns 0 for success, otherwise failure.
811  */
do_check_compatible_tpm_keys(struct updater_config * cfg,const struct firmware_image * rw_image)812 static int do_check_compatible_tpm_keys(struct updater_config *cfg,
813 					const struct firmware_image *rw_image)
814 {
815 	unsigned int data_key_version = 0, firmware_version = 0,
816 		     tpm_data_key_version = 0, tpm_firmware_version = 0;
817 	int tpm_fwver = 0;
818 
819 	/* Fail if the given image does not look good. */
820 	if (get_key_versions(rw_image, FMAP_RW_VBLOCK_A, &data_key_version,
821 			     &firmware_version) != 0)
822 		return -1;
823 
824 	/* The stored tpm_fwver can be 0 (b/116298359#comment3). */
825 	tpm_fwver = dut_get_property(DUT_PROP_TPM_FWVER, cfg);
826 	if (tpm_fwver < 0) {
827 		/*
828 		 * tpm_fwver is commonly misreported in --ccd mode, so allow
829 		 * force_update to ignore the reported value.
830 		 */
831 		if (!cfg->force_update)
832 			ERROR("Invalid tpm_fwver: %d.\n", tpm_fwver);
833 		return -1;
834 	}
835 
836 	tpm_data_key_version = tpm_fwver >> 16;
837 	tpm_firmware_version = tpm_fwver & 0xffff;
838 	VB2_DEBUG("TPM: data_key_version = %d, firmware_version = %d\n",
839 		  tpm_data_key_version, tpm_firmware_version);
840 
841 	if (tpm_data_key_version > data_key_version) {
842 		ERROR("Data key version rollback detected (%d->%d).\n",
843 		      tpm_data_key_version, data_key_version);
844 		return -1;
845 	}
846 	if (tpm_firmware_version > firmware_version) {
847 		ERROR("Firmware version rollback detected (%d->%d).\n",
848 		      tpm_firmware_version, firmware_version);
849 		return -1;
850 	}
851 	return 0;
852 }
853 
854 /*
855  * Wrapper for do_check_compatible_tpm_keys.
856  * Will return 0 if do_check_compatible_tpm_keys success or if cfg.force_update
857  * is set; otherwise non-zero.
858  */
check_compatible_tpm_keys(struct updater_config * cfg,const struct firmware_image * rw_image)859 static int check_compatible_tpm_keys(struct updater_config *cfg,
860 				     const struct firmware_image *rw_image)
861 {
862 	int r = do_check_compatible_tpm_keys(cfg, rw_image);
863 	if (!r)
864 		return r;
865 	if (!cfg->force_update) {
866 		ERROR("Add --force if you want to waive TPM checks.\n");
867 		return r;
868 	}
869 	WARN("TPM KEYS CHECK IS WAIVED BY --force. YOU ARE ON YOUR OWN.\n");
870 	return 0;
871 }
872 
873 
874 /*
875  * Update EC (RO+RW) firmware if possible.
876  * If the image has no data or if the section does not exist, ignore and return success.
877  * Returns 0 if success, non-zero if error.
878  */
update_ec_firmware(struct updater_config * cfg)879 static int update_ec_firmware(struct updater_config *cfg)
880 {
881 	struct firmware_image *ec_image = &cfg->ec_image;
882 	if (!has_valid_update(cfg, ec_image, NULL, 0))
883 		return 0;
884 
885 	const char *sections[] = {"WP_RO"};
886 	size_t num_sections = 0;
887 	int r = try_apply_quirk(QUIRK_EC_PARTIAL_RECOVERY, cfg);
888 	switch (r) {
889 	case EC_RECOVERY_FULL:
890 		break; /* 0 num_sections implies write whole image. */
891 
892 	case EC_RECOVERY_RO: {
893 		num_sections = ARRAY_SIZE(sections);
894 		break;
895 	}
896 
897 	case EC_RECOVERY_DONE:
898 		/* Done by some quirks, for example EC RO software sync. */
899 		return 0;
900 
901 	default:
902 		return r;
903 	}
904 
905 	if (is_ec_write_protection_enabled(cfg)) {
906 		ERROR("Target ec is write protected, skip updating.\n");
907 		return 0;
908 	}
909 
910 	/* TODO(quasisec): Uses cros_ec to program the EC. */
911 	return write_system_firmware(cfg, ec_image, sections, num_sections);
912 }
913 
914 const char * const updater_error_messages[] = {
915 	[UPDATE_ERR_DONE] = "Done (no error)",
916 	[UPDATE_ERR_NEED_RO_UPDATE] = "RO changed and no WP. Need full update.",
917 	[UPDATE_ERR_NO_IMAGE] = "No image to update; try specify with -i.",
918 	[UPDATE_ERR_SYSTEM_IMAGE] = "Cannot load system active firmware.",
919 	[UPDATE_ERR_INVALID_IMAGE] = "The given firmware image is not valid.",
920 	[UPDATE_ERR_SET_COOKIES] = "Failed writing system flags to try update.",
921 	[UPDATE_ERR_WRITE_FIRMWARE] = "Failed writing firmware.",
922 	[UPDATE_ERR_PLATFORM] = "Your system platform is not compatible.",
923 	[UPDATE_ERR_TARGET] = "No valid RW target to update. Abort.",
924 	[UPDATE_ERR_ROOT_KEY] = "RW signed by incompatible root key "
925 			        "(different from RO).",
926 	[UPDATE_ERR_TPM_ROLLBACK] = "RW not usable due to TPM anti-rollback.",
927 	[UPDATE_ERR_UNLOCK_CSME] = "The CSME was already locked (b/284913015).",
928 	[UPDATE_ERR_UNKNOWN] = "Unknown error.",
929 };
930 
931 /*
932  * The main updater for "Legacy update".
933  * This is equivalent to --mode=legacy.
934  * Returns UPDATE_ERR_DONE if success, otherwise error.
935  */
update_legacy_firmware(struct updater_config * cfg,struct firmware_image * image_to)936 static enum updater_error_codes update_legacy_firmware(
937 		struct updater_config *cfg,
938 		struct firmware_image *image_to)
939 {
940 	STATUS("LEGACY UPDATE: Updating firmware %s.\n", FMAP_RW_LEGACY);
941 
942 	const char *sections[] = {FMAP_RW_LEGACY};
943 	if (write_system_firmware(cfg, image_to, sections,
944 				  ARRAY_SIZE(sections)))
945 		return UPDATE_ERR_WRITE_FIRMWARE;
946 
947 	return UPDATE_ERR_DONE;
948 }
949 
950 /*
951  * The main updater for "Try-RW update", to update only one RW section
952  * and try if it can boot properly on reboot.
953  * This was also known as --mode=autoupdate,--wp=1 in legacy updater.
954  * Returns UPDATE_ERR_DONE if success, otherwise error.
955  */
update_try_rw_firmware(struct updater_config * cfg,struct firmware_image * image_from,struct firmware_image * image_to,bool wp_enabled)956 static enum updater_error_codes update_try_rw_firmware(
957 		struct updater_config *cfg,
958 		struct firmware_image *image_from,
959 		struct firmware_image *image_to,
960 		bool wp_enabled)
961 {
962 	const char *target, *self_target;
963 	int has_update = 1;
964 
965 	preserve_gbb(image_from, image_to, 1, 0, 0);
966 	if (!wp_enabled && section_needs_update(
967 			image_from, image_to, FMAP_RO_SECTION))
968 		return UPDATE_ERR_NEED_RO_UPDATE;
969 
970 	INFO("Checking compatibility...\n");
971 	if (check_compatible_root_key(image_from, image_to))
972 		return UPDATE_ERR_ROOT_KEY;
973 	if (check_compatible_tpm_keys(cfg, image_to))
974 		return UPDATE_ERR_TPM_ROLLBACK;
975 
976 	self_target = target = decide_rw_target(cfg, TARGET_SELF);
977 	if (target == NULL) {
978 		ERROR("TRY-RW update needs system to boot in RW firmware.\n");
979 		return UPDATE_ERR_TARGET;
980 	}
981 
982 	INFO("Checking %s contents...\n", target);
983 	if (!firmware_section_exists(image_to, target)) {
984 		ERROR("Cannot find section '%s' on firmware image: %s\n",
985 		      target, image_to->file_name);
986 		return UPDATE_ERR_INVALID_IMAGE;
987 	}
988 	if (!(cfg->force_update || cfg->try_update == TRY_UPDATE_DEFERRED_HOLD))
989 		has_update = section_needs_update(image_from, image_to, target);
990 
991 	if (has_update) {
992 		target = decide_rw_target(cfg, TARGET_UPDATE);
993 		STATUS("TRY-RW UPDATE: Updating %s to try on reboot.\n",
994 		       target);
995 
996 		const char *sections[] = {target};
997 		if (write_system_firmware(cfg, image_to, sections,
998 					  ARRAY_SIZE(sections)))
999 			return UPDATE_ERR_WRITE_FIRMWARE;
1000 
1001 		/*
1002 		 * If the firmware update requested is part of a deferred update
1003 		 * HOLD action, the autoupdater/postinstall will later call
1004 		 * defer update APPLY action to set the correct cookies. So here
1005 		 * it is valid to keep the self slot as the active firmware even
1006 		 * though the target slot is always updated (whether the current
1007 		 * active firmware is the same version or not).
1008 		 */
1009 		if (cfg->try_update == TRY_UPDATE_DEFERRED_HOLD) {
1010 			STATUS(
1011 			    "DEFERRED UPDATE: Defer setting cookies for %s\n",
1012 			    target);
1013 			target = self_target;
1014 			has_update = 0;
1015 		}
1016 	} else {
1017 		STATUS("NO RW UPDATE: No update for RW firmware.\n");
1018 	}
1019 
1020 	/* Always set right cookies for next boot. */
1021 	if (set_try_cookies(cfg, target, has_update))
1022 		return UPDATE_ERR_SET_COOKIES;
1023 
1024 	/* Do not fail on updating legacy. */
1025 	if (legacy_needs_update(cfg)) {
1026 		has_update = 1;
1027 		update_legacy_firmware(cfg, image_to);
1028 	}
1029 
1030 	return UPDATE_ERR_DONE;
1031 }
1032 
1033 /*
1034  * The main updater for "RW update".
1035  * This was also known as --mode=recovery, --wp=1 in legacy updater.
1036  * Returns UPDATE_ERR_DONE if success, otherwise error.
1037  */
update_rw_firmware(struct updater_config * cfg,struct firmware_image * image_from,struct firmware_image * image_to)1038 static enum updater_error_codes update_rw_firmware(
1039 		struct updater_config *cfg,
1040 		struct firmware_image *image_from,
1041 		struct firmware_image *image_to)
1042 {
1043 	int i, num = 0;
1044 	static const char * const required_sections[] = {
1045 		FMAP_RW_SECTION_A,
1046 		FMAP_RW_SECTION_B,
1047 	};
1048 	static const char * const optional_sections[] = {
1049 		FMAP_RW_LEGACY,
1050 		FMAP_RW_SHARED,
1051 	};
1052 	const char *sections[ARRAY_SIZE(required_sections) +
1053 			     ARRAY_SIZE(optional_sections)];
1054 
1055 	STATUS("RW UPDATE: Updating RW sections (%s, %s, %s, and %s).\n",
1056 	       FMAP_RW_SECTION_A, FMAP_RW_SECTION_B, FMAP_RW_SHARED,
1057 	       FMAP_RW_LEGACY);
1058 
1059 	INFO("Checking compatibility...\n");
1060 	if (check_compatible_root_key(image_from, image_to))
1061 		return UPDATE_ERR_ROOT_KEY;
1062 	if (check_compatible_tpm_keys(cfg, image_to))
1063 		return UPDATE_ERR_TPM_ROLLBACK;
1064 
1065 	for (i = 0; i < ARRAY_SIZE(required_sections); i++)
1066 		sections[num++] = required_sections[i];
1067 
1068 	/*
1069 	 * The FMAP_RW_LEGACY is a special optional section.
1070 	 * We may also consider only updating legacy if legacy_needs_update()
1071 	 * returns true. However, given this is for 'recovery', it is probably
1072 	 * better to restore everything to the default states. We may revisit
1073 	 * this if a new scenario is found.
1074 	 */
1075 	for (i = 0; i < ARRAY_SIZE(optional_sections); i++) {
1076 		const char *name = optional_sections[i];
1077 		if (!firmware_section_exists(image_from, name) ||
1078 		    !firmware_section_exists(image_to, name)) {
1079 			VB2_DEBUG("Skipped optional section: %s\n", name);
1080 			continue;
1081 		}
1082 		sections[num++] = name;
1083 	}
1084 	assert(num <= ARRAY_SIZE(sections));
1085 
1086 	if (write_system_firmware(cfg, image_to, sections, num))
1087 		return UPDATE_ERR_WRITE_FIRMWARE;
1088 
1089 	return UPDATE_ERR_DONE;
1090 }
1091 
1092 /*
1093  * The main updater for "Full update".
1094  * This was also known as "--mode=factory" or "--mode=recovery, --wp=0" in
1095  * legacy updater.
1096  * Returns UPDATE_ERR_DONE if success, otherwise error.
1097  */
update_whole_firmware(struct updater_config * cfg,struct firmware_image * image_to)1098 static enum updater_error_codes update_whole_firmware(
1099 		struct updater_config *cfg,
1100 		struct firmware_image *image_to)
1101 {
1102 	STATUS("FULL UPDATE: Updating whole firmware image(s), RO+RW.\n");
1103 
1104 	if (preserve_images(cfg))
1105 		VB2_DEBUG("Failed to preserve some sections - ignore.\n");
1106 
1107 	INFO("Checking compatibility...\n");
1108 	if (!cfg->force_update) {
1109 		/* Check if the image_to itself is broken */
1110 		enum rootkey_compat_result r = check_compatible_root_key(
1111 				image_to, image_to);
1112 		if (r != ROOTKEY_COMPAT_OK) {
1113 			ERROR("Target image does not look valid. \n"
1114 			      "Add --force if you really want to use it.");
1115 			return UPDATE_ERR_ROOT_KEY;
1116 		}
1117 
1118 		/* Check if the system is going to re-key. */
1119 		r = check_compatible_root_key(&cfg->image_current, image_to);
1120 		/* We only allow re-key to non-dev keys. */
1121 		switch (r) {
1122 		case ROOTKEY_COMPAT_OK:
1123 			break;
1124 		case ROOTKEY_COMPAT_REKEY:
1125 			INFO("Will change firmware signing key.\n");
1126 			break;
1127 		case ROOTKEY_COMPAT_REKEY_TO_DEV:
1128 			ERROR("Re-key to DEV is not allowed. \n"
1129 			      "Add --force if you really want to do that.");
1130 			return UPDATE_ERR_ROOT_KEY;
1131 		default:
1132 			return UPDATE_ERR_ROOT_KEY;
1133 		}
1134 	}
1135 	if (check_compatible_tpm_keys(cfg, image_to))
1136 		return UPDATE_ERR_TPM_ROLLBACK;
1137 
1138 	/* FMAP may be different so we should just update all. */
1139 	if (write_system_firmware(cfg, image_to, NULL, 0) ||
1140 	    update_ec_firmware(cfg))
1141 		return UPDATE_ERR_WRITE_FIRMWARE;
1142 
1143 	return UPDATE_ERR_DONE;
1144 }
1145 
update_firmware(struct updater_config * cfg)1146 enum updater_error_codes update_firmware(struct updater_config *cfg)
1147 {
1148 	bool done = false;
1149 	enum updater_error_codes r = UPDATE_ERR_UNKNOWN;
1150 
1151 	/*
1152 	 * For deferred update APPLY action, the only requirement is to set the
1153 	 * correct cookies to the update target slot.
1154 	 */
1155 	if (cfg->try_update == TRY_UPDATE_DEFERRED_APPLY) {
1156 		INFO("Apply deferred updates, only setting cookies for the "
1157 		     "next boot slot.\n");
1158 		if (set_try_cookies(cfg, decide_rw_target(cfg, TARGET_UPDATE),
1159 				    /*has_update=*/1))
1160 			return UPDATE_ERR_SET_COOKIES;
1161 		return UPDATE_ERR_DONE;
1162 	}
1163 
1164 	struct firmware_image *image_from = &cfg->image_current,
1165 			      *image_to = &cfg->image;
1166 	if (!image_to->data)
1167 		return UPDATE_ERR_NO_IMAGE;
1168 
1169 	STATUS("Target image: %s (RO:%s, RW/A:%s (w/ECRW:%s), RW/B:%s (w/ECRW:%s)).\n",
1170 	       image_to->file_name, image_to->ro_version,
1171 	       image_to->rw_version_a, image_to->ecrw_version_a,
1172 	       image_to->rw_version_b, image_to->ecrw_version_b);
1173 	check_firmware_versions(image_to);
1174 
1175 	try_apply_quirk(QUIRK_NO_VERIFY, cfg);
1176 	if (try_apply_quirk(QUIRK_MIN_PLATFORM_VERSION, cfg)) {
1177 		if (!cfg->force_update) {
1178 			ERROR("Add --force to waive checking the version.\n");
1179 			return UPDATE_ERR_PLATFORM;
1180 		}
1181 	}
1182 	if (!image_from->data) {
1183 		int ret;
1184 
1185 		INFO("Loading current system firmware...\n");
1186 		ret = load_system_firmware(cfg, image_from);
1187 		if (ret == IMAGE_PARSE_FAILURE && cfg->force_update) {
1188 			WARN("No compatible firmware in system.\n");
1189 			cfg->check_platform = 0;
1190 		} else if (ret)
1191 			return UPDATE_ERR_SYSTEM_IMAGE;
1192 	}
1193 	STATUS("Current system: %s (RO:%s, RW/A:%s (w/ECRW:%s), RW/B:%s (w/ECRW:%s)).\n",
1194 	       image_from->file_name, image_from->ro_version,
1195 	       image_from->rw_version_a, image_from->ecrw_version_a,
1196 	       image_from->rw_version_b, image_from->ecrw_version_b);
1197 
1198 	try_apply_quirk(QUIRK_NO_CHECK_PLATFORM, cfg);
1199 	if (cfg->check_platform && check_compatible_platform(cfg)) {
1200 		ERROR("The firmware image is not compatible with your system. "
1201 		      "If you really want to proceed, please run again with: "
1202 		      "--quirks=no_check_platform\n");
1203 		return UPDATE_ERR_PLATFORM;
1204 	}
1205 
1206 	bool wp_enabled = is_ap_write_protection_enabled(cfg);
1207 
1208 	if (try_apply_quirk(QUIRK_ENLARGE_IMAGE, cfg))
1209 		return UPDATE_ERR_SYSTEM_IMAGE;
1210 
1211 	if (try_apply_quirk(QUIRK_EVE_SMM_STORE, cfg))
1212 		return UPDATE_ERR_INVALID_IMAGE;
1213 
1214 	if (try_apply_quirk(QUIRK_CLEAR_MRC_DATA, cfg))
1215 		return UPDATE_ERR_SYSTEM_IMAGE;
1216 
1217 	if (debugging_enabled)
1218 		print_dut_properties(cfg);
1219 
1220 	if (cfg->legacy_update)
1221 		return update_legacy_firmware(cfg, image_to);
1222 
1223 	if (cfg->try_update) {
1224 		r = update_try_rw_firmware(cfg, image_from, image_to,
1225 					   wp_enabled);
1226 		if (r == UPDATE_ERR_NEED_RO_UPDATE)
1227 			WARN("%s\n", updater_error_messages[r]);
1228 		else
1229 			done = true;
1230 	}
1231 
1232 	if (!done) {
1233 		if (!wp_enabled && is_ap_ro_locked_with_verification(cfg)) {
1234 			if (is_unlock_csme_requested(cfg))
1235 				return UPDATE_ERR_UNLOCK_CSME;
1236 			WARN("The AP RO is locked with verification turned on so we can't do "
1237 			     "full update (b/284913015). Fall back to RW-only update.\n");
1238 			wp_enabled = 1;
1239 		}
1240 
1241 		r = wp_enabled ? update_rw_firmware(cfg, image_from, image_to) :
1242 				 update_whole_firmware(cfg, image_to);
1243 	}
1244 
1245 	/* Providing more hints for what to do on failure. */
1246 	if (r == UPDATE_ERR_ROOT_KEY && wp_enabled)
1247 		ERROR("To change keys in RO area, you must first remove "
1248 		      "write protection.\n");
1249 
1250 	return r;
1251 }
1252 
updater_new_config(void)1253 struct updater_config *updater_new_config(void)
1254 {
1255 	struct updater_config *cfg = (struct updater_config *)calloc(
1256 			1, sizeof(struct updater_config));
1257 	if (!cfg)
1258 		return cfg;
1259 	cfg->image.programmer = FLASHROM_PROGRAMMER_INTERNAL_AP;
1260 	cfg->image_current.programmer = FLASHROM_PROGRAMMER_INTERNAL_AP;
1261 	cfg->original_programmer = FLASHROM_PROGRAMMER_INTERNAL_AP;
1262 	cfg->ec_image.programmer = FLASHROM_PROGRAMMER_INTERNAL_EC;
1263 
1264 	cfg->check_platform = 1;
1265 	cfg->do_verify = 1;
1266 
1267 	dut_init_properties(&cfg->dut_properties[0],
1268 			    ARRAY_SIZE(cfg->dut_properties));
1269 	updater_register_quirks(cfg);
1270 	return cfg;
1271 }
1272 
1273 /*
1274  * Setup quirks for updating current image.
1275  *
1276  * Quirks must be loaded after image loaded because we use image contents to
1277  * decide default quirks to load. Also, we have to load default quirks first so
1278  * user can override them using command line.
1279  *
1280  * Returns 0 on success, otherwise number of failures.
1281  */
updater_setup_quirks(struct updater_config * cfg,const struct updater_config_arguments * arg)1282 static int updater_setup_quirks(struct updater_config *cfg,
1283 				const struct updater_config_arguments *arg)
1284 {
1285 	int errorcnt = 0;
1286 	const char *model_quirks = updater_get_model_quirks(cfg);
1287 	char *cbfs_quirks = updater_get_cbfs_quirks(cfg);
1288 
1289 	if (model_quirks)
1290 		errorcnt += !!setup_config_quirks(model_quirks, cfg);
1291 	if (cbfs_quirks) {
1292 		errorcnt += !!setup_config_quirks(cbfs_quirks, cfg);
1293 		free(cbfs_quirks);
1294 	}
1295 	if (arg->quirks)
1296 		errorcnt += !!setup_config_quirks(arg->quirks, cfg);
1297 	return errorcnt;
1298 }
1299 
1300 /*
1301  * Loads images into updater configuration.
1302  * Returns 0 on success, otherwise number of failures.
1303  */
updater_load_images(struct updater_config * cfg,const struct updater_config_arguments * arg,const char * image,const char * ec_image)1304 static int updater_load_images(struct updater_config *cfg,
1305 			       const struct updater_config_arguments *arg,
1306 			       const char *image,
1307 			       const char *ec_image)
1308 {
1309 	int errorcnt = 0;
1310 	struct u_archive *ar = cfg->archive;
1311 
1312 	if (!cfg->image.data && image) {
1313 		if (image && strcmp(image, "-") == 0) {
1314 			INFO("Reading image from stdin...\n");
1315 			image = create_temp_file(&cfg->tempfiles);
1316 			if (image)
1317 				errorcnt += !!save_file_from_stdin(image);
1318 		}
1319 		errorcnt += !!load_firmware_image(&cfg->image, image, ar);
1320 		if (!errorcnt)
1321 			errorcnt += updater_setup_quirks(cfg, arg);
1322 	}
1323 
1324 	/*
1325 	 * In emulation mode, we want to prevent unexpected writing to EC
1326 	 * so we should not load EC; however in output mode that is fine.
1327 	 */
1328 	if (arg->host_only || (arg->emulation && !cfg->output_only))
1329 		return errorcnt;
1330 
1331 	if (!cfg->ec_image.data && ec_image)
1332 		errorcnt += !!load_firmware_image(&cfg->ec_image, ec_image, ar);
1333 
1334 	return errorcnt;
1335 }
1336 
1337 /*
1338  * Writes a firmware image to specified file.
1339  * Returns 0 on success, otherwise failure.
1340  */
updater_output_image(const struct firmware_image * image,const char * fname,const char * root)1341 static int updater_output_image(const struct firmware_image *image,
1342 				const char *fname, const char *root)
1343 {
1344 	int r = 0;
1345 	char *fpath;
1346 
1347 	if (!image->data)
1348 		return 0;
1349 
1350 	ASPRINTF(&fpath, "%s/%s", root, fname);
1351 	r = vb2_write_file(fpath, image->data, image->size);
1352 	if (r)
1353 		ERROR("Failed writing firmware image to: %s\n", fpath);
1354 	else
1355 		printf("Firmware image saved in: %s\n", fpath);
1356 
1357 	free(fpath);
1358 	return !!r;
1359 }
1360 
1361 /*
1362  * Setup what the updater has to do against an archive.
1363  * Returns number of failures, or 0 on success.
1364  */
updater_setup_archive(struct updater_config * cfg,const struct updater_config_arguments * arg,struct manifest * manifest,int is_factory)1365 static int updater_setup_archive(
1366 		struct updater_config *cfg,
1367 		const struct updater_config_arguments *arg,
1368 		struct manifest *manifest,
1369 		int is_factory)
1370 {
1371 	int errorcnt = 0;
1372 	struct u_archive *ar = cfg->archive;
1373 	const struct model_config *model;
1374 
1375 	if (cfg->detect_model)
1376 		model = manifest_detect_model_from_frid(cfg, manifest);
1377 	else
1378 		model = manifest_find_model(cfg, manifest, arg->model);
1379 
1380 	if (!model)
1381 		return ++errorcnt;
1382 
1383 	if (arg->detect_model_only) {
1384 		puts(model->name);
1385 		/* No additional error. */
1386 		return errorcnt;
1387 	}
1388 
1389 	/* Load images now so we can get quirks in custom label checks. */
1390 	errorcnt += updater_load_images(
1391 			cfg, arg, model->image, model->ec_image);
1392 
1393 	/*
1394 	 * For custom label devices, we have to read the system firmware
1395 	 * (image_current) to get the tag from VPD. Some quirks may also need
1396 	 * the system firmware to identify if they should override the tags.
1397 	 *
1398 	 * The only exception is `--mode=output` (cfg->output_only), which we
1399 	 * usually add `--model=MODEL` to specify the target model (note some
1400 	 * people may still run without `--model` to get "the image to update
1401 	 * when running on this device"). The MODEL can be either the BASEMODEL
1402 	 * (has_custom_label=true) or BASEMODEL-TAG (has_custom_label=false).
1403 	 * So the only case we have to warn the user that they may forget to
1404 	 * provide the TAG is when has_custom_label=true (only BASEMODEL).
1405 	 */
1406 	if (cfg->output_only && arg->model && model->has_custom_label) {
1407 		printf(">> Generating output for a custom label device without tags (e.g., base model). "
1408 		       "The firmware images will be signed using the base model (or DEFAULT) keys. "
1409 		       "To get the images signed by the LOEM keys, "
1410 		       "add the corresponding tag from one of the following list: \n");
1411 
1412 		size_t len = strlen(arg->model);
1413 		bool printed = false;
1414 		int i;
1415 
1416 		for (i = 0; i < manifest->num; i++) {
1417 			const struct model_config *m = &manifest->models[i];
1418 			if (strncmp(m->name, arg->model, len) || m->name[len] != '-')
1419 				continue;
1420 			printf("%s `--model=%s`", printed ? "," : "", m->name);
1421 			printed = true;
1422 		}
1423 		printf("\n\n");
1424 	} else if (model->has_custom_label) {
1425 		if (!cfg->image_current.data) {
1426 			INFO("Loading system firmware for custom label...\n");
1427 			load_system_firmware(cfg, &cfg->image_current);
1428 		}
1429 
1430 		if (!cfg->image_current.data) {
1431 			ERROR("Cannot read the system firmware for tags.\n");
1432 			return ++errorcnt;
1433 		}
1434 		/*
1435 		 * For custom label devices, manifest_find_model may return the
1436 		 * base model instead of the custom label ones so we have to
1437 		 * look up again.
1438 		 */
1439 		const struct model_config *base_model = model;
1440 		model = manifest_find_custom_label_model(cfg, manifest, base_model);
1441 		if (!model)
1442 			return ++errorcnt;
1443 		/*
1444 		 * All custom label models should share the same image, so we
1445 		 * don't need to reload again - just pick up the new config and
1446 		 * patch later. We don't care about EC images because that will
1447 		 * be updated by software sync in the end.
1448 		 * Here we want to double check if that assumption is correct.
1449 		 */
1450 		if (base_model->image) {
1451 			if (!model->image ||
1452 			    strcmp(base_model->image, model->image)) {
1453 				ERROR("The firmware image for custom label [%s] "
1454 				      "does not match its base model [%s]\n",
1455 				      base_model->name, model->name);
1456 				return ++errorcnt;
1457 			}
1458 		}
1459 	}
1460 	errorcnt += patch_image_by_model(&cfg->image, model, ar);
1461 	return errorcnt;
1462 }
1463 
check_arg_compatibility(const struct updater_config_arguments * arg)1464 static int check_arg_compatibility(
1465 			 const struct updater_config_arguments *arg)
1466 {
1467 	/*
1468 	 * The following args are mutually exclusive:
1469 	 * - detect_model_only
1470 	 * - do_manifest
1471 	 * - repack
1472 	 * - unpack
1473 	 */
1474 	if (arg->detect_model_only) {
1475 		if (arg->do_manifest || arg->repack || arg->unpack) {
1476 			ERROR("--manifest/--parseable-manifest/--repack/--unpack"
1477 			      " is not compatible with --detect-model-only.\n");
1478 			return -1;
1479 		}
1480 		if (!arg->archive) {
1481 			ERROR("--detect-model-only needs --archive.\n");
1482 			return -1;
1483 		}
1484 	} else if (arg->do_manifest) {
1485 		if (arg->repack || arg->unpack) {
1486 			ERROR("--repack/--unpack"
1487 			      " is not compatible with --manifest/--parseable-manifest.\n");
1488 			return -1;
1489 		}
1490 		if (!arg->archive && !(arg->image || arg->ec_image)) {
1491 			ERROR("--manifest needs -a, -i or -e.\n");
1492 			return -1;
1493 		} else if (arg->archive && (arg->image || arg->ec_image)) {
1494 			ERROR("--manifest for archive (-a) does not accept"
1495 			      " additional images (--image, --ec_image).\n");
1496 			return -1;
1497 		}
1498 	} else if (arg->repack || arg->unpack) {
1499 		if (arg->repack && arg->unpack) {
1500 			ERROR("--unpack is incompatible with --repack.\n");
1501 			return -1;
1502 		}
1503 		if (!arg->archive) {
1504 			ERROR("--{re,un}pack needs --archive.\n");
1505 			return -1;
1506 		}
1507 	}
1508 
1509 	return 0;
1510 }
1511 
parse_arg_mode(struct updater_config * cfg,const struct updater_config_arguments * arg)1512 static int parse_arg_mode(struct updater_config *cfg,
1513 			  const struct updater_config_arguments *arg)
1514 {
1515 	if (!arg->mode)
1516 		return 0;
1517 
1518 	if (strcmp(arg->mode, "autoupdate") == 0) {
1519 		cfg->try_update = TRY_UPDATE_AUTO;
1520 	} else if (strcmp(arg->mode, "deferupdate_hold") == 0) {
1521 		cfg->try_update = TRY_UPDATE_DEFERRED_HOLD;
1522 	} else if (strcmp(arg->mode, "deferupdate_apply") == 0) {
1523 		cfg->try_update = TRY_UPDATE_DEFERRED_APPLY;
1524 	} else if (strcmp(arg->mode, "recovery") == 0) {
1525 		cfg->try_update = TRY_UPDATE_OFF;
1526 	} else if (strcmp(arg->mode, "legacy") == 0) {
1527 		cfg->legacy_update = 1;
1528 	} else if (strcmp(arg->mode, "factory") == 0 ||
1529 		   strcmp(arg->mode, "factory_install") == 0) {
1530 		cfg->factory_update = 1;
1531 	} else if (strcmp(arg->mode, "output") == 0) {
1532 		cfg->output_only = true;
1533 	} else {
1534 		ERROR("Invalid mode: %s\n", arg->mode);
1535 		return -1;
1536 	}
1537 
1538 	return 0;
1539 }
1540 
prog_arg_setup(struct updater_config * cfg,const struct updater_config_arguments * arg,bool * check_single_image)1541 static void prog_arg_setup(struct updater_config *cfg,
1542 			   const struct updater_config_arguments *arg,
1543 			   bool *check_single_image)
1544 {
1545 	if (!arg->programmer || !strcmp(arg->programmer, cfg->image.programmer))
1546 		return;
1547 
1548 	*check_single_image = true;
1549 	/* DUT should be remote if the programmer is changed. */
1550 	cfg->dut_is_remote = 1;
1551 	INFO("Configured to update a remote DUT%s.\n",
1552 	     arg->detect_servo ? " via Servo" : "");
1553 	cfg->image.programmer = arg->programmer;
1554 	cfg->image_current.programmer = arg->programmer;
1555 	cfg->original_programmer = arg->programmer;
1556 	VB2_DEBUG("AP (host) programmer changed to %s.\n",
1557 		  arg->programmer);
1558 
1559 	if (arg->archive && !arg->model)
1560 		cfg->detect_model = true;
1561 }
1562 
prog_arg_emulation(struct updater_config * cfg,const struct updater_config_arguments * arg,bool * check_single_image)1563 static int prog_arg_emulation(struct updater_config *cfg,
1564 			      const struct updater_config_arguments *arg,
1565 			      bool *check_single_image)
1566 {
1567 	if (!arg->emulation)
1568 		return 0;
1569 
1570 	VB2_DEBUG("Using file %s for emulation.\n", arg->emulation);
1571 	*check_single_image = true;
1572 	struct stat statbuf;
1573 	if (stat(arg->emulation, &statbuf)) {
1574 		ERROR("Failed to stat emulation file %s\n",
1575 		      arg->emulation);
1576 		return -1;
1577 	}
1578 
1579 	cfg->emulation = arg->emulation;
1580 	/* Store ownership of the dummy programmer string in
1581 	   cfg->emulation_programmer. */
1582 	ASPRINTF(&cfg->emulation_programmer,
1583 		 "dummy:emulate=VARIABLE_SIZE,size=%d,image=%s,bus=prog",
1584 		 (int)statbuf.st_size, arg->emulation);
1585 
1586 	cfg->image.programmer = cfg->emulation_programmer;
1587 	cfg->image_current.programmer = cfg->emulation_programmer;
1588 
1589 	return 0;
1590 }
1591 
updater_should_update(const struct updater_config_arguments * arg)1592 bool updater_should_update(const struct updater_config_arguments *arg)
1593 {
1594 	const bool do_output = arg->mode && !strcmp(arg->mode, "output");
1595 	if (arg->detect_model_only || arg->do_manifest
1596 		|| arg->repack || arg->unpack || do_output) {
1597 		return false;
1598 	}
1599 	return true;
1600 }
1601 
1602 /*
1603  * Prints manifest.
1604  *
1605  * Returns number of errors on failure, or zero on success.
1606  */
print_manifest(const struct updater_config_arguments * arg)1607 static int print_manifest(const struct updater_config_arguments *arg)
1608 {
1609 	assert(arg->do_manifest);
1610 
1611 	if (!arg->archive) {
1612 		char name[] = "default";
1613 		struct model_config model = {
1614 			.name = name,
1615 			.image = arg->image,
1616 			.ec_image = arg->ec_image,
1617 		};
1618 		struct manifest manifest = {
1619 			.num = 1,
1620 			.models = &model,
1621 		};
1622 		if (arg->manifest_format == MANIFEST_PRINT_FORMAT_JSON) {
1623 			print_json_manifest(&manifest);
1624 		} else if (arg->manifest_format == MANIFEST_PRINT_FORMAT_PARSEABLE) {
1625 			print_parseable_manifest(&manifest);
1626 		} else {
1627 			ERROR("Unknown manifest format requested: %d", arg->manifest_format);
1628 			return 1;
1629 		}
1630 		return 0;
1631 	}
1632 
1633 	struct u_archive *archive = archive_open(arg->archive);
1634 	if (!archive) {
1635 		ERROR("Failed to open archive: %s\n", arg->archive);
1636 		return 1;
1637 	}
1638 
1639 	if (arg->fast_update) {
1640 		/* Quickly load and dump the manifest file from the archive. */
1641 		const char *manifest_name = "manifest.json";
1642 		uint8_t *data = NULL;
1643 		uint32_t size = 0;
1644 
1645 		if (arg->manifest_format != MANIFEST_PRINT_FORMAT_JSON) {
1646 			ERROR("Only manifest format supported in fast mode is JSON.\n");
1647 			return 1;
1648 		}
1649 
1650 		if (!archive_has_entry(archive, manifest_name) ||
1651 		    archive_read_file(archive, manifest_name, &data, &size,
1652 				      NULL)) {
1653 			ERROR("Failed to read the cached manifest: %s\n",
1654 			      manifest_name);
1655 			return 1;
1656 		}
1657 		/* data is NUL-terminated. */
1658 		printf("%s\n", data);
1659 		free(data);
1660 	} else {
1661 		struct manifest *manifest =
1662 			new_manifest_from_archive(archive);
1663 		if (!manifest) {
1664 			ERROR("Failed to read manifest from archive: %s\n",
1665 			      arg->archive);
1666 			return 1;
1667 		}
1668 		if (arg->manifest_format == MANIFEST_PRINT_FORMAT_JSON) {
1669 			print_json_manifest(manifest);
1670 		} else if (arg->manifest_format == MANIFEST_PRINT_FORMAT_PARSEABLE) {
1671 			print_parseable_manifest(manifest);
1672 		} else {
1673 			ERROR("Unknown manifest format requested: %d", arg->manifest_format);
1674 			delete_manifest(manifest);
1675 			return 1;
1676 		}
1677 		delete_manifest(manifest);
1678 	}
1679 
1680 	return 0;
1681 }
1682 
updater_setup_config(struct updater_config * cfg,const struct updater_config_arguments * arg)1683 int updater_setup_config(struct updater_config *cfg,
1684 			 const struct updater_config_arguments *arg)
1685 {
1686 	int errorcnt = 0;
1687 	int check_wp_disabled = 0;
1688 	bool check_single_image = false;
1689 	const char *archive_path = arg->archive;
1690 
1691 	/* Setup values that may change output or decision of other argument. */
1692 	cfg->verbosity = arg->verbosity;
1693 	cfg->use_diff_image = arg->fast_update;
1694 	cfg->do_verify = !arg->fast_update;
1695 	cfg->factory_update = arg->is_factory;
1696 	if (arg->force_update)
1697 		cfg->force_update = 1;
1698 
1699 	/* Check incompatible options and return early. */
1700 	if (check_arg_compatibility(arg) < 0)
1701 		return 1;
1702 
1703 	if (arg->detect_model_only) {
1704 		cfg->detect_model = true;
1705 	}
1706 
1707 	/* Setup update mode. */
1708 	if (arg->try_update)
1709 		cfg->try_update = TRY_UPDATE_AUTO;
1710 
1711 	if (parse_arg_mode(cfg, arg) < 0)
1712 		return 1;
1713 
1714 	if (cfg->factory_update) {
1715 		/* factory_update must be processed after arg->mode. */
1716 		check_wp_disabled = 1;
1717 		cfg->try_update = TRY_UPDATE_OFF;
1718 	}
1719 	cfg->gbb_flags = arg->gbb_flags;
1720 	cfg->override_gbb_flags = arg->override_gbb_flags;
1721 
1722 	/* Setup properties and fields that do not have external dependency. */
1723 	prog_arg_setup(cfg, arg, &check_single_image);
1724 	if (prog_arg_emulation(cfg, arg, &check_single_image) < 0)
1725 		return 1;
1726 
1727 	if (arg->emulation)
1728 		override_properties_with_default(cfg);
1729 	if (arg->sys_props)
1730 		override_properties_from_list(arg->sys_props, cfg);
1731 	if (arg->write_protection) {
1732 		/* arg->write_protection must be done after arg->sys_props. */
1733 		int r = strtol(arg->write_protection, NULL, 0);
1734 		override_dut_property(DUT_PROP_WP_HW, cfg, r);
1735 		override_dut_property(DUT_PROP_WP_SW_AP, cfg, r);
1736 	}
1737 
1738 	/* Process the manifest. */
1739 	if (arg->do_manifest) {
1740 		errorcnt += print_manifest(arg);
1741 		return errorcnt;
1742 	}
1743 
1744 	/* Always load images specified from command line directly. */
1745 	errorcnt += updater_load_images(
1746 			cfg, arg, arg->image, arg->ec_image);
1747 
1748 	/* Set up archive. */
1749 	if (!archive_path)
1750 		archive_path = ".";
1751 	cfg->archive = archive_open(archive_path);
1752 	if (!cfg->archive) {
1753 		ERROR("Failed to open archive: %s\n", archive_path);
1754 		return ++errorcnt;
1755 	}
1756 
1757 	/* Process archives which may not have valid contents. */
1758 	if (arg->repack || arg->unpack) {
1759 		const char *work_name = arg->repack ? arg->repack : arg->unpack;
1760 		struct u_archive *from, *to, *work;
1761 
1762 		work = archive_open(work_name);
1763 		if (arg->repack) {
1764 			from = work;
1765 			to = cfg->archive;
1766 		} else {
1767 			to = work;
1768 			from = cfg->archive;
1769 		}
1770 		if (!work) {
1771 			ERROR("Failed to open: %s\n", work_name);
1772 			return ++errorcnt;
1773 		}
1774 		errorcnt += !!archive_copy(from, to);
1775 		/* TODO(hungte) Update manifest after copied. */
1776 		archive_close(work);
1777 		return errorcnt;
1778 	}
1779 
1780 	/* Load images from the archive. */
1781 	if (arg->archive) {
1782 		struct manifest *m = new_manifest_from_archive(cfg->archive);
1783 		if (m) {
1784 			errorcnt += updater_setup_archive(
1785 					cfg, arg, m, cfg->factory_update);
1786 			delete_manifest(m);
1787 		} else {
1788 			ERROR("Failure in archive: %s\n", arg->archive);
1789 			++errorcnt;
1790 		}
1791 	}
1792 
1793 	/*
1794 	 * Images should be loaded now (either in first updater_load_images or
1795 	 * second call from updater_setup_archive) and quirks should be loaded.
1796 	 * For invocation without image, we want to get quirks now.
1797 	 */
1798 	if (!cfg->image.data && arg->quirks)
1799 		errorcnt += !!setup_config_quirks(arg->quirks, cfg);
1800 
1801 	/* Additional checks. */
1802 	if (check_single_image && !cfg->output_only && cfg->ec_image.data) {
1803 		errorcnt++;
1804 		ERROR("EC/PD images are not supported in current mode.\n");
1805 	}
1806 	if (check_wp_disabled && is_ap_write_protection_enabled(cfg)) {
1807 		errorcnt++;
1808 		ERROR("Please remove write protection for factory mode\n");
1809 	}
1810 
1811 	if (cfg->image.data) {
1812 		/* Apply any quirks to modify the image before updating. */
1813 		if (arg->unlock_me)
1814 			cfg->quirks[QUIRK_UNLOCK_CSME].value = 1;
1815 		errorcnt += try_apply_quirk(QUIRK_UNLOCK_CSME_EVE, cfg);
1816 		errorcnt += try_apply_quirk(QUIRK_UNLOCK_CSME, cfg);
1817 	}
1818 
1819 	/* The images are ready for updating. Output if needed. */
1820 	if (!errorcnt && cfg->output_only) {
1821 		const char *r = arg->output_dir;
1822 		if (!r)
1823 			r = ".";
1824 
1825 		/* TODO(hungte) Remove bios.bin when migration is done. */
1826 		errorcnt += updater_output_image(&cfg->image, "bios.bin", r);
1827 		errorcnt += updater_output_image(&cfg->image, "image.bin", r);
1828 		errorcnt += updater_output_image(&cfg->ec_image, "ec.bin", r);
1829 	}
1830 	return errorcnt;
1831 }
1832 
1833 /* Enough to hold standard CCD programmer options plus serial number */
1834 static char ccd_programmer[128];
1835 
handle_flash_argument(struct updater_config_arguments * args,int opt,char * optarg)1836 int handle_flash_argument(struct updater_config_arguments *args, int opt,
1837 			  char *optarg)
1838 {
1839 	int ret;
1840 	switch (opt) {
1841 	case 'p':
1842 		args->use_flash = 1;
1843 		args->programmer = optarg;
1844 		break;
1845 	case OPT_CCD:
1846 		args->use_flash = 1;
1847 		args->fast_update = 1;
1848 		args->force_update = 1;
1849 		args->write_protection = "0";
1850 		ret = snprintf(ccd_programmer, sizeof(ccd_programmer),
1851 			       "raiden_debug_spi:target=AP%s%s",
1852 			       optarg ? ",serial=" : "", optarg ?: "");
1853 		if (ret >= sizeof(ccd_programmer)) {
1854 			ERROR("%s: CCD serial number was too long\n", __func__);
1855 			return 0;
1856 		}
1857 		args->programmer = ccd_programmer;
1858 		break;
1859 	case OPT_EMULATE:
1860 		args->use_flash = 1;
1861 		args->emulation = optarg;
1862 		break;
1863 	case OPT_SERVO:
1864 		args->use_flash = 1;
1865 		args->detect_servo = 1;
1866 		args->fast_update = 1;
1867 		args->force_update = 1;
1868 		args->write_protection = "0";
1869 		args->host_only = 1;
1870 		break;
1871 	case OPT_SERVO_PORT:
1872 		setenv(ENV_SERVOD_PORT, optarg, 1);
1873 		args->use_flash = 1;
1874 		args->detect_servo = 1;
1875 		args->fast_update = 1;
1876 		args->force_update = 1;
1877 		args->write_protection = "0";
1878 		args->host_only = 1;
1879 		break;
1880 	default:
1881 		return 0;
1882 	}
1883 	return 1;
1884 }
1885 
updater_delete_config(struct updater_config * cfg)1886 void updater_delete_config(struct updater_config *cfg)
1887 {
1888 	assert(cfg);
1889 	free_firmware_image(&cfg->image);
1890 	free_firmware_image(&cfg->image_current);
1891 	free_firmware_image(&cfg->ec_image);
1892 	cfg->image.programmer = cfg->original_programmer;
1893 	cfg->image_current.programmer = cfg->original_programmer;
1894 	free(cfg->emulation_programmer);
1895 	remove_all_temp_files(&cfg->tempfiles);
1896 	if (cfg->archive)
1897 		archive_close(cfg->archive);
1898 	free(cfg);
1899 }
1900