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