1#!/bin/bash 2 3# Copyright 2015 The Chromium OS Authors. All rights reserved. 4# Use of this source code is governed by a BSD-style license that can be 5# found in the LICENSE file. 6 7# Script to generate a Brillo update for use by the update engine. 8# 9# usage: brillo_update_payload COMMAND [ARGS] 10# The following commands are supported: 11# generate generate an unsigned payload 12# hash generate a payload or metadata hash 13# sign generate a signed payload 14# properties generate a properties file from a payload 15# 16# Generate command arguments: 17# --payload generated unsigned payload output file 18# --source_image if defined, generate a delta payload from the specified 19# image to the target_image 20# --target_image the target image that should be sent to clients 21# --metadata_size_file if defined, generate a file containing the size of the payload 22# metadata in bytes to the specified file 23# 24# Hash command arguments: 25# --unsigned_payload the input unsigned payload to generate the hash from 26# --signature_size signature sizes in bytes in the following format: 27# "size1:size2[:...]" 28# --payload_hash_file if defined, generate a payload hash and output to the 29# specified file 30# --metadata_hash_file if defined, generate a metadata hash and output to the 31# specified file 32# 33# Sign command arguments: 34# --unsigned_payload the input unsigned payload to insert the signatures 35# --payload the output signed payload 36# --signature_size signature sizes in bytes in the following format: 37# "size1:size2[:...]" 38# --payload_signature_file the payload signature files in the following 39# format: 40# "payload_signature1:payload_signature2[:...]" 41# --metadata_signature_file the metadata signature files in the following 42# format: 43# "metadata_signature1:metadata_signature2[:...]" 44# --metadata_size_file if defined, generate a file containing the size of 45# the signed payload metadata in bytes to the 46# specified file 47# Note that the number of signature sizes and payload signatures have to match. 48# 49# Properties command arguments: 50# --payload the input signed or unsigned payload 51# --properties_file the output path where to write the properties, or 52# '-' for stdout. 53 54 55# Exit codes: 56EX_UNSUPPORTED_DELTA=100 57 58warn() { 59 echo "brillo_update_payload: warning: $*" >&2 60} 61 62die() { 63 echo "brillo_update_payload: error: $*" >&2 64 exit 1 65} 66 67# Loads shflags. We first look at the default install location; then look for 68# crosutils (chroot); finally check our own directory (au-generator zipfile). 69load_shflags() { 70 local my_dir="$(dirname "$(readlink -f "$0")")" 71 local path 72 for path in /usr/share/misc {/usr/lib/crosutils,"${my_dir}"}/lib/shflags; do 73 if [[ -r "${path}/shflags" ]]; then 74 . "${path}/shflags" || die "Could not load ${path}/shflags." 75 return 76 fi 77 done 78 die "Could not find shflags." 79} 80 81load_shflags 82 83HELP_GENERATE="generate: Generate an unsigned update payload." 84HELP_HASH="hash: Generate the hashes of the unsigned payload and metadata used \ 85for signing." 86HELP_SIGN="sign: Insert the signatures into the unsigned payload." 87HELP_PROPERTIES="properties: Extract payload properties to a file." 88 89usage() { 90 echo "Supported commands:" 91 echo 92 echo "${HELP_GENERATE}" 93 echo "${HELP_HASH}" 94 echo "${HELP_SIGN}" 95 echo "${HELP_PROPERTIES}" 96 echo 97 echo "Use: \"$0 <command> --help\" for more options." 98} 99 100# Check that a command is specified. 101if [[ $# -lt 1 ]]; then 102 echo "Please specify a command [generate|hash|sign|properties]" 103 exit 1 104fi 105 106# Parse command. 107COMMAND="${1:-}" 108shift 109 110case "${COMMAND}" in 111 generate) 112 FLAGS_HELP="${HELP_GENERATE}" 113 ;; 114 115 hash) 116 FLAGS_HELP="${HELP_HASH}" 117 ;; 118 119 sign) 120 FLAGS_HELP="${HELP_SIGN}" 121 ;; 122 123 properties) 124 FLAGS_HELP="${HELP_PROPERTIES}" 125 ;; 126 *) 127 echo "Unrecognized command: \"${COMMAND}\"" >&2 128 usage >&2 129 exit 1 130 ;; 131esac 132 133# Flags 134FLAGS_HELP="Usage: $0 ${COMMAND} [flags] 135${FLAGS_HELP}" 136 137if [[ "${COMMAND}" == "generate" ]]; then 138 DEFINE_string payload "" \ 139 "Path to output the generated unsigned payload file." 140 DEFINE_string target_image "" \ 141 "Path to the target image that should be sent to clients." 142 DEFINE_string source_image "" \ 143 "Optional: Path to a source image. If specified, this makes a delta update." 144 DEFINE_string metadata_size_file "" \ 145 "Optional: Path to output metadata size." 146fi 147if [[ "${COMMAND}" == "hash" || "${COMMAND}" == "sign" ]]; then 148 DEFINE_string unsigned_payload "" "Path to the input unsigned payload." 149 DEFINE_string signature_size "" \ 150 "Signature sizes in bytes in the following format: size1:size2[:...]" 151fi 152if [[ "${COMMAND}" == "hash" ]]; then 153 DEFINE_string metadata_hash_file "" \ 154 "Optional: Path to output metadata hash file." 155 DEFINE_string payload_hash_file "" \ 156 "Optional: Path to output payload hash file." 157fi 158if [[ "${COMMAND}" == "sign" ]]; then 159 DEFINE_string payload "" \ 160 "Path to output the generated unsigned payload file." 161 DEFINE_string metadata_signature_file "" \ 162 "The metatada signatures in the following format: \ 163metadata_signature1:metadata_signature2[:...]" 164 DEFINE_string payload_signature_file "" \ 165 "The payload signatures in the following format: \ 166payload_signature1:payload_signature2[:...]" 167 DEFINE_string metadata_size_file "" \ 168 "Optional: Path to output metadata size." 169fi 170if [[ "${COMMAND}" == "properties" ]]; then 171 DEFINE_string payload "" \ 172 "Path to the input signed or unsigned payload file." 173 DEFINE_string properties_file "-" \ 174 "Path to output the extracted property files. If '-' is passed stdout will \ 175be used." 176fi 177 178DEFINE_string work_dir "/tmp" "Where to dump temporary files." 179 180# Parse command line flag arguments 181FLAGS "$@" || exit 1 182eval set -- "${FLAGS_ARGV}" 183set -e 184 185# Associative arrays from partition name to file in the source and target 186# images. The size of the updated area must be the size of the file. 187declare -A SRC_PARTITIONS 188declare -A DST_PARTITIONS 189 190# Associative arrays for the .map files associated with each src/dst partition 191# file in SRC_PARTITIONS and DST_PARTITIONS. 192declare -A SRC_PARTITIONS_MAP 193declare -A DST_PARTITIONS_MAP 194 195# A list of temporary files to remove during cleanup. 196CLEANUP_FILES=() 197 198# Global options to force the version of the payload. 199FORCE_MAJOR_VERSION="" 200FORCE_MINOR_VERSION="" 201 202# Path to the postinstall config file in target image if exists. 203POSTINSTALL_CONFIG_FILE="" 204 205# The fingerprint of zlib in the source image. 206ZLIB_FINGERPRINT="" 207 208# read_option_int <file.txt> <option_key> [default_value] 209# 210# Reads the unsigned integer value associated with |option_key| in a key=value 211# file |file.txt|. Prints the read value if found and valid, otherwise prints 212# the |default_value|. 213read_option_uint() { 214 local file_txt="$1" 215 local option_key="$2" 216 local default_value="${3:-}" 217 local value 218 if value=$(look "${option_key}=" "${file_txt}" | tail -n 1); then 219 if value=$(echo "${value}" | cut -f 2- -d "=" | grep -E "^[0-9]+$"); then 220 echo "${value}" 221 return 222 fi 223 fi 224 echo "${default_value}" 225} 226 227# truncate_file <file_path> <file_size> 228# 229# Truncate the given |file_path| to |file_size| using perl. 230# The truncate binary might not be available. 231truncate_file() { 232 local file_path="$1" 233 local file_size="$2" 234 perl -e "open(FILE, \"+<\", \$ARGV[0]); \ 235 truncate(FILE, ${file_size}); \ 236 close(FILE);" "${file_path}" 237} 238 239# Create a temporary file in the work_dir with an optional pattern name. 240# Prints the name of the newly created file. 241create_tempfile() { 242 local pattern="${1:-tempfile.XXXXXX}" 243 mktemp --tmpdir="${FLAGS_work_dir}" "${pattern}" 244} 245 246cleanup() { 247 local err="" 248 rm -f "${CLEANUP_FILES[@]}" || err=1 249 250 # If we are cleaning up after an error, or if we got an error during 251 # cleanup (even if we eventually succeeded) return a non-zero exit 252 # code. This triggers additional logging in most environments that call 253 # this script. 254 if [[ -n "${err}" ]]; then 255 die "Cleanup encountered an error." 256 fi 257} 258 259cleanup_on_error() { 260 trap - INT TERM ERR EXIT 261 cleanup 262 die "Cleanup success after an error." 263} 264 265cleanup_on_exit() { 266 trap - INT TERM ERR EXIT 267 cleanup 268} 269 270trap cleanup_on_error INT TERM ERR 271trap cleanup_on_exit EXIT 272 273 274# extract_image <image> <partitions_array> 275# 276# Detect the format of the |image| file and extract its updatable partitions 277# into new temporary files. Add the list of partition names and its files to the 278# associative array passed in |partitions_array|. 279extract_image() { 280 local image="$1" 281 282 # Brillo images are zip files. We detect the 4-byte magic header of the zip 283 # file. 284 local magic=$(head --bytes=4 "${image}" | hexdump -e '1/1 "%.2x"') 285 if [[ "${magic}" == "504b0304" ]]; then 286 echo "Detected .zip file, extracting Brillo image." 287 extract_image_brillo "$@" 288 return 289 fi 290 291 # Chrome OS images are GPT partitioned disks. We should have the cgpt binary 292 # bundled here and we will use it to extract the partitions, so the GPT 293 # headers must be valid. 294 if cgpt show -q -n "${image}" >/dev/null; then 295 echo "Detected GPT image, extracting Chrome OS image." 296 extract_image_cros "$@" 297 return 298 fi 299 300 die "Couldn't detect the image format of ${image}" 301} 302 303# extract_image_cros <image.bin> <partitions_array> 304# 305# Extract Chromium OS recovery images into new temporary files. 306extract_image_cros() { 307 local image="$1" 308 local partitions_array="$2" 309 310 local kernel root 311 kernel=$(create_tempfile "kernel.bin.XXXXXX") 312 CLEANUP_FILES+=("${kernel}") 313 root=$(create_tempfile "root.bin.XXXXXX") 314 CLEANUP_FILES+=("${root}") 315 316 cros_generate_update_payload --extract \ 317 --image "${image}" \ 318 --kern_path "${kernel}" --root_path "${root}" \ 319 --work_dir "${FLAGS_work_dir}" --outside_chroot 320 321 # Chrome OS uses major_version 1 payloads for all versions, even if the 322 # updater supports a newer major version. 323 FORCE_MAJOR_VERSION="1" 324 325 if [[ "${partitions_array}" == "SRC_PARTITIONS" ]]; then 326 # Copy from zlib_fingerprint in source image to stdout. 327 ZLIB_FINGERPRINT=$(e2cp "${root}":/etc/zlib_fingerprint -) 328 fi 329 330 # When generating legacy Chrome OS images, we need to use "boot" and "system" 331 # for the partition names to be compatible with updating Brillo devices with 332 # Chrome OS images. 333 eval ${partitions_array}[boot]=\""${kernel}"\" 334 eval ${partitions_array}[system]=\""${root}"\" 335 336 local part varname 337 for part in boot system; do 338 varname="${partitions_array}[${part}]" 339 printf "md5sum of %s: " "${varname}" 340 md5sum "${!varname}" 341 done 342} 343 344# extract_image_brillo <target_files.zip> <partitions_array> 345# 346# Extract the A/B updated partitions from a Brillo target_files zip file into 347# new temporary files. 348extract_image_brillo() { 349 local image="$1" 350 local partitions_array="$2" 351 352 local partitions=( "boot" "system" ) 353 local ab_partitions_list 354 ab_partitions_list=$(create_tempfile "ab_partitions_list.XXXXXX") 355 CLEANUP_FILES+=("${ab_partitions_list}") 356 if unzip -p "${image}" "META/ab_partitions.txt" >"${ab_partitions_list}"; then 357 if grep -v -E '^[a-zA-Z0-9_-]*$' "${ab_partitions_list}" >&2; then 358 die "Invalid partition names found in the partition list." 359 fi 360 partitions=($(cat "${ab_partitions_list}")) 361 if [[ ${#partitions[@]} -eq 0 ]]; then 362 die "The list of partitions is empty. Can't generate a payload." 363 fi 364 else 365 warn "No ab_partitions.txt found. Using default." 366 fi 367 echo "List of A/B partitions: ${partitions[@]}" 368 369 # All Brillo updaters support major version 2. 370 FORCE_MAJOR_VERSION="2" 371 372 if [[ "${partitions_array}" == "SRC_PARTITIONS" ]]; then 373 # Source image 374 local ue_config=$(create_tempfile "ue_config.XXXXXX") 375 CLEANUP_FILES+=("${ue_config}") 376 if ! unzip -p "${image}" "META/update_engine_config.txt" \ 377 >"${ue_config}"; then 378 warn "No update_engine_config.txt found. Assuming pre-release image, \ 379using payload minor version 2" 380 fi 381 # For delta payloads, we use the major and minor version supported by the 382 # old updater. 383 FORCE_MINOR_VERSION=$(read_option_uint "${ue_config}" \ 384 "PAYLOAD_MINOR_VERSION" 2) 385 FORCE_MAJOR_VERSION=$(read_option_uint "${ue_config}" \ 386 "PAYLOAD_MAJOR_VERSION" 2) 387 388 # Brillo support for deltas started with minor version 3. 389 if [[ "${FORCE_MINOR_VERSION}" -le 2 ]]; then 390 warn "No delta support from minor version ${FORCE_MINOR_VERSION}. \ 391Disabling deltas for this source version." 392 exit ${EX_UNSUPPORTED_DELTA} 393 fi 394 395 if [[ "${FORCE_MINOR_VERSION}" -ge 4 ]]; then 396 ZLIB_FINGERPRINT=$(unzip -p "${image}" "META/zlib_fingerprint.txt") 397 fi 398 else 399 # Target image 400 local postinstall_config=$(create_tempfile "postinstall_config.XXXXXX") 401 CLEANUP_FILES+=("${postinstall_config}") 402 if unzip -p "${image}" "META/postinstall_config.txt" \ 403 >"${postinstall_config}"; then 404 POSTINSTALL_CONFIG_FILE="${postinstall_config}" 405 fi 406 fi 407 408 local part part_file temp_raw filesize 409 for part in "${partitions[@]}"; do 410 part_file=$(create_tempfile "${part}.img.XXXXXX") 411 CLEANUP_FILES+=("${part_file}") 412 unzip -p "${image}" "IMAGES/${part}.img" >"${part_file}" 413 414 # If the partition is stored as an Android sparse image file, we need to 415 # convert them to a raw image for the update. 416 local magic=$(head --bytes=4 "${part_file}" | hexdump -e '1/1 "%.2x"') 417 if [[ "${magic}" == "3aff26ed" ]]; then 418 temp_raw=$(create_tempfile "${part}.raw.XXXXXX") 419 CLEANUP_FILES+=("${temp_raw}") 420 echo "Converting Android sparse image ${part}.img to RAW." 421 simg2img "${part_file}" "${temp_raw}" 422 # At this point, we can drop the contents of the old part_file file, but 423 # we can't delete the file because it will be deleted in cleanup. 424 true >"${part_file}" 425 part_file="${temp_raw}" 426 fi 427 428 # Extract the .map file (if one is available). 429 part_map_file=$(create_tempfile "${part}.map.XXXXXX") 430 CLEANUP_FILES+=("${part_map_file}") 431 unzip -p "${image}" "IMAGES/${part}.map" >"${part_map_file}" || \ 432 part_map_file="" 433 434 # delta_generator only supports images multiple of 4 KiB. For target images 435 # we pad the data with zeros if needed, but for source images we truncate 436 # down the data since the last block of the old image could be padded on 437 # disk with unknown data. 438 filesize=$(stat -c%s "${part_file}") 439 if [[ $(( filesize % 4096 )) -ne 0 ]]; then 440 if [[ "${partitions_array}" == "SRC_PARTITIONS" ]]; then 441 echo "Rounding DOWN partition ${part}.img to a multiple of 4 KiB." 442 : $(( filesize = filesize & -4096 )) 443 else 444 echo "Rounding UP partition ${part}.img to a multiple of 4 KiB." 445 : $(( filesize = (filesize + 4095) & -4096 )) 446 fi 447 truncate_file "${part_file}" "${filesize}" 448 fi 449 450 eval "${partitions_array}[\"${part}\"]=\"${part_file}\"" 451 eval "${partitions_array}_MAP[\"${part}\"]=\"${part_map_file}\"" 452 echo "Extracted ${partitions_array}[${part}]: ${filesize} bytes" 453 done 454} 455 456validate_generate() { 457 [[ -n "${FLAGS_payload}" ]] || 458 die "Error: you must specify an output filename with --payload FILENAME" 459 460 [[ -n "${FLAGS_target_image}" ]] || 461 die "Error: you must specify a target image with --target_image FILENAME" 462} 463 464cmd_generate() { 465 local payload_type="delta" 466 if [[ -z "${FLAGS_source_image}" ]]; then 467 payload_type="full" 468 fi 469 470 echo "Extracting images for ${payload_type} update." 471 472 extract_image "${FLAGS_target_image}" DST_PARTITIONS 473 if [[ "${payload_type}" == "delta" ]]; then 474 extract_image "${FLAGS_source_image}" SRC_PARTITIONS 475 fi 476 477 echo "Generating ${payload_type} update." 478 # Common payload args: 479 GENERATOR_ARGS=( -out_file="${FLAGS_payload}" ) 480 481 local part old_partitions="" new_partitions="" partition_names="" 482 local old_mapfiles="" new_mapfiles="" 483 for part in "${!DST_PARTITIONS[@]}"; do 484 if [[ -n "${partition_names}" ]]; then 485 partition_names+=":" 486 new_partitions+=":" 487 old_partitions+=":" 488 new_mapfiles+=":" 489 old_mapfiles+=":" 490 fi 491 partition_names+="${part}" 492 new_partitions+="${DST_PARTITIONS[${part}]}" 493 old_partitions+="${SRC_PARTITIONS[${part}]:-}" 494 new_mapfiles+="${DST_PARTITIONS_MAP[${part}]:-}" 495 old_mapfiles+="${SRC_PARTITIONS_MAP[${part}]:-}" 496 done 497 498 # Target image args: 499 GENERATOR_ARGS+=( 500 -partition_names="${partition_names}" 501 -new_partitions="${new_partitions}" 502 -new_mapfiles="${new_mapfiles}" 503 ) 504 505 if [[ "${payload_type}" == "delta" ]]; then 506 # Source image args: 507 GENERATOR_ARGS+=( 508 -old_partitions="${old_partitions}" 509 -old_mapfiles="${old_mapfiles}" 510 ) 511 if [[ -n "${FORCE_MINOR_VERSION}" ]]; then 512 GENERATOR_ARGS+=( --minor_version="${FORCE_MINOR_VERSION}" ) 513 fi 514 if [[ -n "${ZLIB_FINGERPRINT}" ]]; then 515 GENERATOR_ARGS+=( --zlib_fingerprint="${ZLIB_FINGERPRINT}" ) 516 fi 517 fi 518 519 if [[ -n "${FORCE_MAJOR_VERSION}" ]]; then 520 GENERATOR_ARGS+=( --major_version="${FORCE_MAJOR_VERSION}" ) 521 fi 522 523 if [[ -n "${FLAGS_metadata_size_file}" ]]; then 524 GENERATOR_ARGS+=( --out_metadata_size_file="${FLAGS_metadata_size_file}" ) 525 fi 526 527 if [[ -n "${POSTINSTALL_CONFIG_FILE}" ]]; then 528 GENERATOR_ARGS+=( 529 --new_postinstall_config_file="${POSTINSTALL_CONFIG_FILE}" 530 ) 531 fi 532 533 echo "Running delta_generator with args: ${GENERATOR_ARGS[@]}" 534 "${GENERATOR}" "${GENERATOR_ARGS[@]}" 535 536 echo "Done generating ${payload_type} update." 537} 538 539validate_hash() { 540 [[ -n "${FLAGS_signature_size}" ]] || 541 die "Error: you must specify signature size with --signature_size SIZES" 542 543 [[ -n "${FLAGS_unsigned_payload}" ]] || 544 die "Error: you must specify the input unsigned payload with \ 545--unsigned_payload FILENAME" 546 547 [[ -n "${FLAGS_payload_hash_file}" ]] || 548 die "Error: you must specify --payload_hash_file FILENAME" 549 550 [[ -n "${FLAGS_metadata_hash_file}" ]] || 551 die "Error: you must specify --metadata_hash_file FILENAME" 552} 553 554cmd_hash() { 555 "${GENERATOR}" \ 556 -in_file="${FLAGS_unsigned_payload}" \ 557 -signature_size="${FLAGS_signature_size}" \ 558 -out_hash_file="${FLAGS_payload_hash_file}" \ 559 -out_metadata_hash_file="${FLAGS_metadata_hash_file}" 560 561 echo "Done generating hash." 562} 563 564validate_sign() { 565 [[ -n "${FLAGS_signature_size}" ]] || 566 die "Error: you must specify signature size with --signature_size SIZES" 567 568 [[ -n "${FLAGS_unsigned_payload}" ]] || 569 die "Error: you must specify the input unsigned payload with \ 570--unsigned_payload FILENAME" 571 572 [[ -n "${FLAGS_payload}" ]] || 573 die "Error: you must specify the output signed payload with \ 574--payload FILENAME" 575 576 [[ -n "${FLAGS_payload_signature_file}" ]] || 577 die "Error: you must specify the payload signature file with \ 578--payload_signature_file SIGNATURES" 579 580 [[ -n "${FLAGS_metadata_signature_file}" ]] || 581 die "Error: you must specify the metadata signature file with \ 582--metadata_signature_file SIGNATURES" 583} 584 585cmd_sign() { 586 GENERATOR_ARGS=( 587 -in_file="${FLAGS_unsigned_payload}" 588 -signature_size="${FLAGS_signature_size}" 589 -signature_file="${FLAGS_payload_signature_file}" 590 -metadata_signature_file="${FLAGS_metadata_signature_file}" 591 -out_file="${FLAGS_payload}" 592 ) 593 594 if [[ -n "${FLAGS_metadata_size_file}" ]]; then 595 GENERATOR_ARGS+=( --out_metadata_size_file="${FLAGS_metadata_size_file}" ) 596 fi 597 598 "${GENERATOR}" "${GENERATOR_ARGS[@]}" 599 echo "Done signing payload." 600} 601 602validate_properties() { 603 [[ -n "${FLAGS_payload}" ]] || 604 die "Error: you must specify the payload file with --payload FILENAME" 605 606 [[ -n "${FLAGS_properties_file}" ]] || 607 die "Error: you must specify a non empty --properties_file FILENAME" 608} 609 610cmd_properties() { 611 "${GENERATOR}" \ 612 -in_file="${FLAGS_payload}" \ 613 -properties_file="${FLAGS_properties_file}" 614} 615 616# Sanity check that the real generator exists: 617GENERATOR="$(which delta_generator)" 618[[ -x "${GENERATOR}" ]] || die "can't find delta_generator" 619 620case "$COMMAND" in 621 generate) validate_generate 622 cmd_generate 623 ;; 624 hash) validate_hash 625 cmd_hash 626 ;; 627 sign) validate_sign 628 cmd_sign 629 ;; 630 properties) validate_properties 631 cmd_properties 632 ;; 633esac 634