1#!/bin/bash
2set -eo pipefail
3
4help=$'Generate Tarball with PNOR image and MANIFEST Script
5
6Generates a PNOR SquashFS image from the PNOR image for VPNOR,
7Or use a static layout raw PNOR image,
8Creates a MANIFEST for image verification and recreation
9Packages the image and MANIFEST together in a tarball
10
11usage: generate-tar [OPTION] <PNOR FILE>...
12
13Options:
14-i, --image <squashfs|static>
15Generate SquashFS image or use static PNOR
16-f, --file <file>      Specify destination file. Defaults to
17$(pwd)/<PNOR FILE>.pnor.<image_type>.tar[.gz] if
18unspecified.
19(For example,
20    * "generate-tar -i squashfs my.pnor" would generate
21    $(pwd)/my.pnor.squashfs.tar
22    * "generate-tar -i static my.pnor" would generate
23$(pwd)/my.pnor.static.tar.gz)
24-s, --sign <path>      Sign the image. The optional path argument specifies
25the private key file. Defaults to the bash variable
26PRIVATE_KEY_PATH if available, or else uses the
27open-source private key in this script.
28-m, --machine <name>   Optionally specify the target machine name of this
29image.
30-h, --help             Display this help text and exit.
31'
32
33private_key=$'-----BEGIN PRIVATE KEY-----
34MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQDO7vWM6ZOylO6T
35lxDiRWgKCFauAxMVM4A7NmgZxfV73xqTzAtIzzF9CIKUEhqMT4LhNy1rU2oUUivH
364BZO2oC6yFafEPVla2oYAeWtXJmQTixYgJplKQCtLzFtb57DQJpl9Od0RVFC61yg
374LihsiENnRjncLPP7OkL68ssiELu+WxazDtewmVYQEHOMWQa2zDh9yrWsblLAyo4
38gsG9rdwWjqIUnZkoeJuT7zks4Jes4qAtQUuZhCxMcvwvOq8od3e4nLVFnyUOGMpE
39jdDDGddKh5e+9BJGqkfsLCT9UFTYi62Ifuxl1Gp963cZLapJS0CneHIrG3gapiCO
40ea4TH/xySfts2jpl7DnEIUo3Qs0rZrOLQDLVVXvRJvHdsVoZcSRCD8Jf0YTQ6tT7
41j3ejUOH8j3DGkgKRHGtH7yyCgmDyPYVQdEu3q4E1NBwODAyxppYGBqkwpSGRnf6q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/DERDnUR4/o8ZUJ6+2Bddn0
75xvUDPKX9UH+rGSx4tnscA5+CnYJsJeSdunvYONTRxBsn0l6iJhhn/gPOOpsHtKnL
76hS9y/vfd3GFDST33L23EsFa3a7xwgdY460D8AIgnGij7V9Lgel0AyYp0ovZc34uD
77z9yYWI32dbRWbMZ40RPKaudOeDSbjlMaH0A7ymfxjqwKxI9D2VscFWNs4hv8QErw
78Uc6NAoIBAQCmWWyARU/x4m7K4vNAWjD2Qx6R7PAdLs/6ZBqWw0RSpRHlYr73Qggw
79dCK+LrsR0O7y1KW2WUfrJmzHEdFQEYcZ1vZWeN85dMLVhYmazSXlaIegRE4FmMUa
80DbzViUJA60Y4D/l6QWqdhxdZZe81QgqyLPXAv/e5esxRIi8yvEYhCx4pq7QtWYBm
81tvQnPaZd8emlKARivF2ecGDlWzhf4NotDDtFRT4jOHZKUC58uVjbiXJ445Vimqlb
82Da7noVGwDQ93Ib1qyAilzFY5gWDeMyCnSQpnlVRHQ/8vlwLDsZs1kVau6k8WlcpM
83JbmuCRNy7YvALVTzyQsQ4yw87BoONt1L
84-----END PRIVATE KEY-----
85'
86
87# Reference the ffs structures at:
88# https://github.com/open-power/hostboot/blob/master/src/usr/pnor/common/ffs_hb.H
89# https://github.com/open-power/hostboot/blob/master/src/usr/pnor/ffs.h
90ffs_entry_size=128
91vercheck_offset=112
92do_sign=false
93PRIVATE_KEY_PATH=${PRIVATE_KEY_PATH:-}
94private_key_path="${PRIVATE_KEY_PATH}"
95image_type=""
96outfile=""
97declare -a partitions=()
98tocfile="pnor.toc"
99machine_name=""
100
101while [[ $# -gt 0 ]]; do
102  key="$1"
103  case $key in
104    -i|--image)
105      image_type="$2"
106      shift 2
107      ;;
108    -f|--file)
109      outfile="$2"
110      shift 2
111      ;;
112    -s|--sign)
113      do_sign=true
114      if [[ -n "${2}"  && "${2}" != -* ]]; then
115        private_key_path="$2"
116        shift 2
117      else
118        shift 1
119      fi
120      ;;
121    -m|--machine)
122      machine_name="$2"
123      shift 2
124      ;;
125    -h|--help)
126      echo "$help"
127      exit
128      ;;
129    *)
130      pnorfile="$1"
131      shift 1
132      ;;
133  esac
134done
135
136if [ ! -f "${pnorfile}" ]; then
137  echo "Please enter a valid PNOR file."
138  echo "$help"
139  exit 1
140fi
141
142if [[ "${image_type}" == "squashfs" ]]; then
143  echo "Will generate squashfs image for VPNOR"
144elif [[ "${image_type}" == "static" ]]; then
145  echo "Will use static image for PNOR"
146else
147  echo "Please specify the image type, \"squashfs\" or \"static\""
148  echo
149  echo "$help"
150  exit 1
151fi
152
153if [[ -z $outfile ]]; then
154    if [[ ${pnorfile##*.} == "pnor" ]]; then
155        outfile=$(pwd)/${pnorfile##*/}.$image_type.tar
156    else
157        outfile=$(pwd)/${pnorfile##*/}.pnor.$image_type.tar
158    fi
159    if [[ "${image_type}" == "static" ]]; then
160        # Append .gz so the tarball is compressed
161        outfile=$outfile.gz
162    fi
163else
164    if [[ $outfile != /* ]]; then
165        outfile=$(pwd)/$outfile
166    fi
167fi
168
169
170scratch_dir=$(mktemp -d)
171# Remove the temp directory on exit.
172# The files in the temp directory may contain read-only files, so add
173# --interactive=never to skip the prompt.
174trap '{ rm -r --interactive=never ${scratch_dir}; }' EXIT
175
176if [[ "${do_sign}" == true ]]; then
177  if [[ -z "${private_key_path}" ]]; then
178    private_key_path=${scratch_dir}/OpenBMC.priv
179    echo "${private_key}" > "${private_key_path}"
180    echo "Image is NOT secure!! Signing with the open private key!"
181  else
182    if [[ ! -f "${private_key_path}" ]]; then
183      echo "Couldn't find private key ${private_key_path}."
184      exit 1
185    fi
186
187    echo "Signing with ${private_key_path}."
188  fi
189
190  public_key_file=publickey
191  public_key_path=${scratch_dir}/$public_key_file
192  openssl pkey -in "${private_key_path}" -pubout -out "${public_key_path}"
193fi
194
195echo "Parsing PNOR TOC..."
196
197pnor_dir="${scratch_dir}/pnor"
198mkdir "${pnor_dir}"
199
200pflash --partition=part --read="${pnor_dir}"/part -F "${pnorfile}"
201pflash --partition=VERSION --read="${pnor_dir}"/VERSION -F "${pnorfile}"
202version_size=$(wc -c "${pnor_dir}"/VERSION | cut -d' ' -f 1)
203magic_number=$(xxd -p -l 4 "${pnor_dir}"/VERSION)
204# Check if VERSION is signed. A signed version partition will have an extra
205# 4K header starting with the magic number 0x17082011, see:
206# https://github.com/open-power/skiboot/blob/master/libstb/container.h#L47
207if [ "$version_size" == "8192" ] && [ "$magic_number" == "17082011" ]; then
208  # Advance past the STB header (4K, indexed from 1)
209  cp "${pnor_dir}"/VERSION "${pnor_dir}"/VERSION_FULL
210  tail --bytes=+4097 "${pnor_dir}"/VERSION_FULL > "${pnor_dir}"/VERSION
211fi
212{
213  version=$(head -n 1 "${pnor_dir}"/VERSION)
214  echo "version=$version"
215  # shellcheck disable=SC2005,SC2046 # Need the echo to remove new lines, same
216  # reason for not quoting the tail command
217  extended_version=$(echo $(tail -n +2 "${pnor_dir}"/VERSION)|tr ' ' ',')
218  echo "extended_version=$extended_version"
219  while read -r line; do
220    if [[ $line == "ID="* ]]; then
221        # This line looks like
222        # "ID=05 MVPD 000d9000..00169000 (actual=00090000) [ECC]"
223        read -r -a fields <<< "$line"
224
225        id=${fields[0]##*=}
226        offset=$((ffs_entry_size * 10#${id} + vercheck_offset))
227        vercheck=$(xxd -p -l  0x1 -seek ${offset} "${pnor_dir}"/part)
228        # shellcheck disable=SC2155 # Need the export in the same line to avoid
229        # pflash error
230        export flags=$(pflash --detail=$((10#$id)) -F "${pnorfile}" | grep "\[" |
231                sed 's/....$//' | tr '\n' ',' | sed 's/.$//')
232        if [[ $flags != "" ]]; then
233            flags=,$flags
234        fi
235
236        if [[ $(echo "$flags" | grep "READONLY") == "" &&
237              $(echo "$flags" | grep "PRESERVED") == "" ]]; then
238            flags=$flags,READWRITE
239        fi
240
241        # Need the partition ID, name, start location, end location, and flags
242        echo  "partition${id}=${fields[1]},${fields[2]/../,},${vercheck}${flags}"
243
244        # Save the partition name
245        partitions+=("${fields[1]}")
246    fi
247  # Don't need the BACKUP_PART partition
248  done < <(pflash --info -F "${pnorfile}" | grep -v "BACKUP")
249} > "${pnor_dir}"/${tocfile}
250
251for partition in "${partitions[@]}"; do
252  echo "Reading ${partition}..."
253  pflash --partition="${partition}" \
254    --read="${pnor_dir}"/"${partition}" \
255    -F "${pnorfile}"
256done
257
258manifest_location="MANIFEST"
259files_to_sign="$manifest_location $public_key_file"
260
261# Go to scratch_dir
262
263if [[ "${image_type}" == "squashfs" ]]; then
264  echo "Creating SquashFS image..."
265  # Prepare pnor file in ${pnor_dir}
266  cd "${pnor_dir}"
267  # Set permissions of partition files to read only
268  chmod 440 -- *
269  # shellcheck disable=SC2048,SC2086 # Do not quote partitions since it lists
270  # multiple files and mksquashfs would assume to be a single file name within
271  # quotes
272  mksquashfs ${tocfile} ${partitions[*]} "${scratch_dir}"/pnor.xz.squashfs -all-root
273  cd "${scratch_dir}"
274  files_to_sign+=" pnor.xz.squashfs"
275else
276  cp "${pnorfile}" "${scratch_dir}"
277  cd "${scratch_dir}"
278  files_to_sign+=" $(basename "${pnorfile}")"
279fi
280
281echo "Creating MANIFEST for the image"
282echo -e "purpose=xyz.openbmc_project.Software.Version.VersionPurpose.Host\nversion=$version\n\
283extended_version=$extended_version" >> $manifest_location
284
285if [[ -n "${machine_name}" ]]; then
286    echo -e "MachineName=${machine_name}" >> $manifest_location
287fi
288
289if [[ "${do_sign}" == true ]]; then
290  private_key_name=$(basename "${private_key_path}")
291  key_type="${private_key_name%.*}"
292  echo KeyType="${key_type}" >> $manifest_location
293  echo HashType="RSA-SHA256" >> $manifest_location
294
295  for file in $files_to_sign; do
296    openssl dgst -sha256 -sign "${private_key_path}" -out "${file}.sig" "$file"
297  done
298
299  additional_files="*.sig"
300fi
301
302if [[ "${image_type}" == "squashfs" ]]; then
303  echo "Generating tarball to contain the SquashFS image and its MANIFEST"
304  # shellcheck disable=SC2086 # Do not quote the files variables since they list
305  # multiple files and tar would assume to be a single file name within quotes
306  tar -cvf "$outfile" $files_to_sign $additional_files
307  echo "SquashFSTarball at ${outfile}"
308else
309  # shellcheck disable=SC2086 # Do not quote the files variables since they list
310  # multiple files and tar would assume to be a single file name within quotes
311  tar -czvf "$outfile" $files_to_sign $additional_files
312  echo "Static layout tarball at $outfile"
313fi
314