common_minimal.sh 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. #!/bin/sh
  2. #
  3. # Copyright 2011 The ChromiumOS Authors
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. #
  7. # Note: This file must be written in dash compatible way as scripts that use
  8. # this may run in the Chrome OS client enviornment.
  9. # shellcheck disable=SC2039,SC2059,SC2155
  10. # Determine script directory
  11. SCRIPT_DIR=$(dirname "$0")
  12. PROG=$(basename "$0")
  13. : "${GPT:=cgpt}"
  14. : "${FUTILITY:=futility}"
  15. # The tag when the rootfs is changed.
  16. TAG_NEEDS_TO_BE_SIGNED="/root/.need_to_be_signed"
  17. # List of Temporary files and mount points.
  18. TEMP_FILE_LIST=$(mktemp)
  19. TEMP_DIR_LIST=$(mktemp)
  20. # Finds and loads the 'shflags' library, or return as failed.
  21. load_shflags() {
  22. # Load shflags
  23. if [ -f /usr/share/misc/shflags ]; then
  24. # shellcheck disable=SC1090,SC1091
  25. . /usr/share/misc/shflags
  26. elif [ -f "${SCRIPT_DIR}/lib/shflags/shflags" ]; then
  27. # shellcheck disable=SC1090
  28. . "${SCRIPT_DIR}/lib/shflags/shflags"
  29. else
  30. echo "ERROR: Cannot find the required shflags library."
  31. return 1
  32. fi
  33. # Add debug option for debug output below
  34. DEFINE_boolean debug $FLAGS_FALSE "Provide debug messages" "d"
  35. }
  36. # Functions for debug output
  37. # ----------------------------------------------------------------------------
  38. # These helpers are for runtime systems. For scripts using common.sh,
  39. # they'll get better definitions that will clobber these ones.
  40. info() {
  41. echo "${PROG}: INFO: $*" >&2
  42. }
  43. warn() {
  44. echo "${PROG}: WARN: $*" >&2
  45. }
  46. error() {
  47. echo "${PROG}: ERROR: $*" >&2
  48. }
  49. # Reports error message and exit(1)
  50. # Args: error message
  51. die() {
  52. error "$@"
  53. exit 1
  54. }
  55. # Returns true if we're running in debug mode.
  56. #
  57. # Note that if you don't set up shflags by calling load_shflags(), you
  58. # must set $FLAGS_debug and $FLAGS_TRUE yourself. The default
  59. # behavior is that debug will be off if you define neither $FLAGS_TRUE
  60. # nor $FLAGS_debug.
  61. is_debug_mode() {
  62. [ "${FLAGS_debug:-not$FLAGS_TRUE}" = "$FLAGS_TRUE" ]
  63. }
  64. # Prints messages (in parameters) in debug mode
  65. # Args: debug message
  66. debug_msg() {
  67. if is_debug_mode; then
  68. echo "DEBUG: $*" 1>&2
  69. fi
  70. }
  71. # Functions for temporary files and directories
  72. # ----------------------------------------------------------------------------
  73. # Create a new temporary file and return its name.
  74. # File is automatically cleaned when cleanup_temps_and_mounts() is called.
  75. make_temp_file() {
  76. local tempfile="$(mktemp)"
  77. echo "$tempfile" >> "$TEMP_FILE_LIST"
  78. echo "$tempfile"
  79. }
  80. # Create a new temporary directory and return its name.
  81. # Directory is automatically deleted and any filesystem mounted on it unmounted
  82. # when cleanup_temps_and_mounts() is called.
  83. make_temp_dir() {
  84. local tempdir=$(mktemp -d)
  85. echo "$tempdir" >> "$TEMP_DIR_LIST"
  86. echo "$tempdir"
  87. }
  88. cleanup_temps_and_mounts() {
  89. while read -r line; do
  90. rm -f "$line"
  91. done < "$TEMP_FILE_LIST"
  92. set +e # umount may fail for unmounted directories
  93. while read -r line; do
  94. if [ -n "$line" ]; then
  95. if has_needs_to_be_resigned_tag "$line"; then
  96. echo "Warning: image may be modified. Please resign image."
  97. fi
  98. sudo umount "$line" 2>/dev/null
  99. rm -rf "$line"
  100. fi
  101. done < "$TEMP_DIR_LIST"
  102. set -e
  103. rm -rf "$TEMP_DIR_LIST" "$TEMP_FILE_LIST"
  104. }
  105. trap "cleanup_temps_and_mounts" EXIT
  106. # Functions for partition management
  107. # ----------------------------------------------------------------------------
  108. # Construct a partition device name from a whole disk block device and a
  109. # partition number.
  110. # This works for [/dev/sda, 3] (-> /dev/sda3) as well as [/dev/mmcblk0, 2]
  111. # (-> /dev/mmcblk0p2).
  112. make_partition_dev() {
  113. local block="$1"
  114. local num="$2"
  115. # If the disk block device ends with a number, we add a 'p' before the
  116. # partition number.
  117. if [ "${block%[0-9]}" = "${block}" ]; then
  118. echo "${block}${num}"
  119. else
  120. echo "${block}p${num}"
  121. fi
  122. }
  123. # Find the block size of a device in bytes
  124. # Args: DEVICE (e.g. /dev/sda)
  125. # Return: block size in bytes
  126. blocksize() {
  127. local output=''
  128. local path="$1"
  129. if [ -b "${path}" ]; then
  130. local dev="${path##*/}"
  131. local sys="/sys/block/${dev}/queue/logical_block_size"
  132. output="$(cat "${sys}" 2>/dev/null)"
  133. fi
  134. echo "${output:-512}"
  135. }
  136. # Read GPT table to find the starting location of a specific partition.
  137. # Args: DEVICE PARTNUM
  138. # Returns: offset (in sectors) of partition PARTNUM
  139. partoffset() {
  140. sudo "$GPT" show -b -i "$2" "$1"
  141. }
  142. # Read GPT table to find the size of a specific partition.
  143. # Args: DEVICE PARTNUM
  144. # Returns: size (in sectors) of partition PARTNUM
  145. partsize() {
  146. sudo "$GPT" show -s -i "$2" "$1"
  147. }
  148. # Tags a file system as "needs to be resigned".
  149. # Args: MOUNTDIRECTORY
  150. tag_as_needs_to_be_resigned() {
  151. local mount_dir="$1"
  152. sudo touch "$mount_dir/$TAG_NEEDS_TO_BE_SIGNED"
  153. }
  154. # Determines if the target file system has the tag for resign
  155. # Args: MOUNTDIRECTORY
  156. # Returns: true if the tag is there otherwise false
  157. has_needs_to_be_resigned_tag() {
  158. local mount_dir="$1"
  159. [ -f "$mount_dir/$TAG_NEEDS_TO_BE_SIGNED" ]
  160. }
  161. # Determines if the target file system is a Chrome OS root fs
  162. # Args: MOUNTDIRECTORY
  163. # Returns: true if MOUNTDIRECTORY looks like root fs, otherwise false
  164. is_rootfs_partition() {
  165. local mount_dir="$1"
  166. [ -f "$mount_dir/$(dirname "$TAG_NEEDS_TO_BE_SIGNED")" ]
  167. }
  168. # If the kernel is buggy and is unable to loop+mount quickly,
  169. # retry the operation a few times.
  170. # Args: IMAGE PARTNUM MOUNTDIRECTORY [ro]
  171. #
  172. # This function does not check whether the partition is allowed to be mounted as
  173. # RW. Callers must ensure the partition can be mounted as RW before calling
  174. # this function without |ro| argument.
  175. _mount_image_partition_retry() {
  176. local image=$1
  177. local partnum=$2
  178. local mount_dir=$3
  179. local ro=$4
  180. local bs="$(blocksize "${image}")"
  181. local offset=$(( $(partoffset "${image}" "${partnum}") * bs ))
  182. local out try
  183. # shellcheck disable=SC2086
  184. set -- sudo LC_ALL=C mount -o loop,offset=${offset},${ro} \
  185. "${image}" "${mount_dir}"
  186. try=1
  187. while [ ${try} -le 5 ]; do
  188. if ! out=$("$@" 2>&1); then
  189. if [ "${out}" = "mount: you must specify the filesystem type" ]; then
  190. printf 'WARNING: mounting %s at %s failed (try %i); retrying\n' \
  191. "${image}" "${mount_dir}" "${try}"
  192. # Try to "quiet" the disks and sleep a little to reduce contention.
  193. sync
  194. sleep $(( try * 5 ))
  195. else
  196. # Failed for a different reason; abort!
  197. break
  198. fi
  199. else
  200. # It worked!
  201. return 0
  202. fi
  203. : $(( try += 1 ))
  204. done
  205. echo "ERROR: mounting ${image} at ${mount_dir} failed:"
  206. echo "${out}"
  207. # We don't preserve the exact exit code of `mount`, but since
  208. # no one in this code base seems to check it, it's a moot point.
  209. return 1
  210. }
  211. # If called without 'ro', make sure the partition is allowed to be mounted as
  212. # 'rw' before actually mounting it.
  213. # Args: IMAGE PARTNUM MOUNTDIRECTORY [ro]
  214. _mount_image_partition() {
  215. local image=$1
  216. local partnum=$2
  217. local mount_dir=$3
  218. local ro=$4
  219. local bs="$(blocksize "${image}")"
  220. local offset=$(( $(partoffset "${image}" "${partnum}") * bs ))
  221. if [ "$ro" != "ro" ]; then
  222. # Forcibly call enable_rw_mount. It should fail on unsupported
  223. # filesystems and be idempotent on ext*.
  224. enable_rw_mount "${image}" ${offset} 2> /dev/null
  225. fi
  226. _mount_image_partition_retry "$@"
  227. }
  228. # If called without 'ro', make sure the partition is allowed to be mounted as
  229. # 'rw' before actually mounting it.
  230. # Args: LOOPDEV PARTNUM MOUNTDIRECTORY [ro]
  231. _mount_loop_image_partition() {
  232. local loopdev=$1
  233. local partnum=$2
  234. local mount_dir=$3
  235. local ro=$4
  236. local loop_rootfs="${loopdev}p${partnum}"
  237. if [ "$ro" != "ro" ]; then
  238. # Forcibly call enable_rw_mount. It should fail on unsupported
  239. # filesystems and be idempotent on ext*.
  240. enable_rw_mount "${loop_rootfs}" 2>/dev/null
  241. fi
  242. sudo mount -o "${ro}" "${loop_rootfs}" "${mount_dir}"
  243. }
  244. # Mount a partition read-only from an image into a local directory
  245. # Args: IMAGE PARTNUM MOUNTDIRECTORY
  246. mount_image_partition_ro() {
  247. _mount_image_partition "$@" "ro"
  248. }
  249. # Mount a partition read-only from an image into a local directory
  250. # Args: LOOPDEV PARTNUM MOUNTDIRECTORY
  251. mount_loop_image_partition_ro() {
  252. _mount_loop_image_partition "$@" "ro"
  253. }
  254. # Mount a partition from an image into a local directory
  255. # Args: IMAGE PARTNUM MOUNTDIRECTORY
  256. mount_image_partition() {
  257. local mount_dir=$3
  258. _mount_image_partition "$@"
  259. if is_rootfs_partition "${mount_dir}"; then
  260. tag_as_needs_to_be_resigned "${mount_dir}"
  261. fi
  262. }
  263. # Mount a partition from an image into a local directory
  264. # Args: LOOPDEV PARTNUM MOUNTDIRECTORY
  265. mount_loop_image_partition() {
  266. local mount_dir=$3
  267. _mount_loop_image_partition "$@"
  268. if is_rootfs_partition "${mount_dir}"; then
  269. tag_as_needs_to_be_resigned "${mount_dir}"
  270. fi
  271. }
  272. # Mount the image's ESP (EFI System Partition) on a newly created temporary
  273. # directory.
  274. # Prints out the newly created temporary directory path if succeeded.
  275. # If the image doens't have an ESP partition, returns 0 without print anything.
  276. # Args: LOOPDEV
  277. # Returns: 0 if succeeded, 1 otherwise.
  278. mount_image_esp() {
  279. local loopdev="$1"
  280. local ESP_PARTNUM=12
  281. local loop_esp="${loopdev}p${ESP_PARTNUM}"
  282. local esp_offset=$(( $(partoffset "${loopdev}" "${ESP_PARTNUM}") ))
  283. # Check if the image has an ESP partition.
  284. if [[ "${esp_offset}" == "0" ]]; then
  285. return 0
  286. fi
  287. local esp_dir="$(make_temp_dir)"
  288. if ! sudo mount -o "${ro}" "${loop_esp}" "${esp_dir}"; then
  289. return 1
  290. fi
  291. echo "${esp_dir}"
  292. return 0
  293. }
  294. # Extract a partition to a file
  295. # Args: IMAGE PARTNUM OUTPUTFILE
  296. extract_image_partition() {
  297. local image=$1
  298. local partnum=$2
  299. local output_file=$3
  300. local offset=$(partoffset "$image" "$partnum")
  301. local size=$(partsize "$image" "$partnum")
  302. # shellcheck disable=SC2086
  303. dd if="$image" of="$output_file" bs=512 skip=$offset count=$size \
  304. conv=notrunc 2>/dev/null
  305. }
  306. # Replace a partition in an image from file
  307. # Args: IMAGE PARTNUM INPUTFILE
  308. replace_image_partition() {
  309. local image=$1
  310. local partnum=$2
  311. local input_file=$3
  312. local offset=$(partoffset "$image" "$partnum")
  313. local size=$(partsize "$image" "$partnum")
  314. # shellcheck disable=SC2086
  315. dd if="$input_file" of="$image" bs=512 seek=$offset count=$size \
  316. conv=notrunc 2>/dev/null
  317. }
  318. # For details, see crosutils.git/common.sh
  319. enable_rw_mount() {
  320. local rootfs="$1"
  321. local offset="${2-0}"
  322. # Make sure we're checking an ext2 image
  323. # shellcheck disable=SC2086
  324. if ! is_ext2 "$rootfs" $offset; then
  325. echo "enable_rw_mount called on non-ext2 filesystem: $rootfs $offset" 1>&2
  326. return 1
  327. fi
  328. local ro_compat_offset=$((0x464 + 3)) # Set 'highest' byte
  329. # Dash can't do echo -ne, but it can do printf "\NNN"
  330. # We could use /dev/zero here, but this matches what would be
  331. # needed for disable_rw_mount (printf '\377').
  332. printf '\000' |
  333. sudo dd of="$rootfs" seek=$((offset + ro_compat_offset)) \
  334. conv=notrunc count=1 bs=1 2>/dev/null
  335. }
  336. # For details, see crosutils.git/common.sh
  337. is_ext2() {
  338. local rootfs="$1"
  339. local offset="${2-0}"
  340. # Make sure we're checking an ext2 image
  341. local sb_magic_offset=$((0x438))
  342. local sb_value=$(sudo dd if="$rootfs" skip=$((offset + sb_magic_offset)) \
  343. count=2 bs=1 2>/dev/null)
  344. local expected_sb_value=$(printf '\123\357')
  345. if [ "$sb_value" = "$expected_sb_value" ]; then
  346. return 0
  347. fi
  348. return 1
  349. }
  350. disable_rw_mount() {
  351. local rootfs="$1"
  352. local offset="${2-0}"
  353. # Make sure we're checking an ext2 image
  354. # shellcheck disable=SC2086
  355. if ! is_ext2 "$rootfs" $offset; then
  356. echo "disable_rw_mount called on non-ext2 filesystem: $rootfs $offset" 1>&2
  357. return 1
  358. fi
  359. local ro_compat_offset=$((0x464 + 3)) # Set 'highest' byte
  360. # Dash can't do echo -ne, but it can do printf "\NNN"
  361. # We could use /dev/zero here, but this matches what would be
  362. # needed for disable_rw_mount (printf '\377').
  363. printf '\377' |
  364. sudo dd of="$rootfs" seek=$((offset + ro_compat_offset)) \
  365. conv=notrunc count=1 bs=1 2>/dev/null
  366. }
  367. rw_mount_disabled() {
  368. local rootfs="$1"
  369. local offset="${2-0}"
  370. # Make sure we're checking an ext2 image
  371. # shellcheck disable=SC2086
  372. if ! is_ext2 "$rootfs" $offset; then
  373. return 2
  374. fi
  375. local ro_compat_offset=$((0x464 + 3)) # Set 'highest' byte
  376. local ro_value=$(sudo dd if="$rootfs" skip=$((offset + ro_compat_offset)) \
  377. count=1 bs=1 2>/dev/null)
  378. local expected_ro_value=$(printf '\377')
  379. if [ "$ro_value" = "$expected_ro_value" ]; then
  380. return 0
  381. fi
  382. return 1
  383. }
  384. # Functions for CBFS management
  385. # ----------------------------------------------------------------------------
  386. # Get the compression algorithm used for the given CBFS file.
  387. # Args: INPUT_CBFS_IMAGE CBFS_FILE_NAME
  388. get_cbfs_compression() {
  389. cbfstool "$1" print -r "FW_MAIN_A" | awk -vname="$2" '$1 == name {print $5}'
  390. }
  391. # Store a file in CBFS.
  392. # Args: INPUT_CBFS_IMAGE INPUT_FILE CBFS_FILE_NAME
  393. store_file_in_cbfs() {
  394. local image="$1"
  395. local file="$2"
  396. local name="$3"
  397. local compression=$(get_cbfs_compression "$1" "${name}")
  398. # Don't re-add a file to a section if it's unchanged. Otherwise this seems
  399. # to break signature of existing contents. https://crbug.com/889716
  400. if cbfstool "${image}" extract -r "FW_MAIN_A,FW_MAIN_B" \
  401. -f "${file}.orig" -n "${name}"; then
  402. if cmp -s "${file}" "${file}.orig"; then
  403. rm -f "${file}.orig"
  404. return
  405. fi
  406. rm -f "${file}.orig"
  407. fi
  408. cbfstool "${image}" remove -r "FW_MAIN_A,FW_MAIN_B" -n "${name}" || return
  409. # This add can fail if
  410. # 1. Size of a signature after compression is larger
  411. # 2. CBFS is full
  412. # These conditions extremely unlikely become true at the same time.
  413. cbfstool "${image}" add -r "FW_MAIN_A,FW_MAIN_B" -t "raw" \
  414. -c "${compression}" -f "${file}" -n "${name}" || return
  415. }
  416. # Misc functions
  417. # ----------------------------------------------------------------------------
  418. # Parses the version file containing key=value lines
  419. # Args: key file
  420. # Returns: value
  421. get_version() {
  422. local key="$1"
  423. local file="$2"
  424. awk -F= -vkey="${key}" '$1 == key { print $NF }' "${file}"
  425. }
  426. # Returns true if all files in parameters exist.
  427. # Args: List of files
  428. ensure_files_exist() {
  429. local filename return_value=0
  430. for filename in "$@"; do
  431. if [ ! -f "$filename" ] && [ ! -b "$filename" ]; then
  432. echo "ERROR: Cannot find required file: $filename"
  433. return_value=1
  434. fi
  435. done
  436. return $return_value
  437. }
  438. # Check if the 'chronos' user already has a password
  439. # Args: rootfs
  440. no_chronos_password() {
  441. local rootfs=$1
  442. # Make sure the chronos user actually exists.
  443. if grep -qs '^chronos:' "${rootfs}/etc/passwd"; then
  444. sudo grep -q '^chronos:\*:' "${rootfs}/etc/shadow"
  445. fi
  446. }
  447. # Returns true if given ec.bin is signed or false if not.
  448. is_ec_rw_signed() {
  449. ${FUTILITY} dump_fmap "$1" | grep -q KEY_RO
  450. }