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-----
34MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAPvSDLu6slkP1gri
35PaeQXL9ysD69J/HjbBCIQ0RPfeWBb75US1tRTjPP0Ub8CtH8ExVf8iF1ulsZA78B
36zIjBYZVp9pyD6LbpZ/hjV7rIH6dTNhoVpdA+F8LzmQ7cyhHG8l2JMvdunwF2uX5k
37D4WDcZt/ITKZNQNavPtmIyD5HprdAgMBAAECgYEAuQkTSi5ZNpAoWz76xtGRFSwU
38zUT4wQi3Mz6tDtjKTYXasiQGa0dHC1M9F8fDu6BZ9W7W4Dc9hArRcdzEighuxoI/
39nZI/0uL89iUEywnDEIHuS6D5JlZaj86/nx9YvQnO8F/seM+MX0EAWVrd5wC7aAF1
40h6Fu7ykZB4ggUjQAWwECQQD+AUiDOEO+8btLJ135dQfSGc5VFcZiequnKWVm6uXt
41rX771hEYjYMjLqWGFg9G4gE3GuABM5chMINuQQUivy8tAkEA/cxfy19XkjtqcMgE
42x/UDt6Nr+Ky/tk+4Y65WxPRDas0uxFOPk/vEjgVmz1k/TAy9G4giisluTvtmltr5
43DCLocQJBAJnRHx9PiD7uVhRJz6/L/iNuOzPtTsi+Loq5F83+O6T15qsM1CeBMsOw
44cM5FN5UeMcwz+yjfHAsePMkcmMaU7jUCQHlg9+N8upXuIo7Dqj2zOU7nMmkgvSNE
455yuNImRZabC3ZolwaTdd7nf5r1y1Eyec5Ag5yENV6JKPe1Xkbb1XKJECQDngA0h4
466ATvfP1Vrx4CbP11eKXbCsZ9OGPHSgyvVjn68oY5ZP3uPsIattoN7dE2BRfuJm7m
47F0nIdUAhR0yTfKM=
48-----END PRIVATE KEY-----
49'
50
51# Reference the ffs structures at:
52# https://github.com/open-power/hostboot/blob/master/src/usr/pnor/common/ffs_hb.H
53# https://github.com/open-power/hostboot/blob/master/src/usr/pnor/ffs.h
54ffs_entry_size=128
55vercheck_offset=112
56do_sign=false
57PRIVATE_KEY_PATH=${PRIVATE_KEY_PATH:-}
58private_key_path="${PRIVATE_KEY_PATH}"
59image_type=""
60outfile=""
61declare -a partitions=()
62tocfile="pnor.toc"
63machine_name=""
64
65while [[ $# -gt 0 ]]; do
66  key="$1"
67  case $key in
68    -i|--image)
69      image_type="$2"
70      shift 2
71      ;;
72    -f|--file)
73      outfile="$2"
74      shift 2
75      ;;
76    -s|--sign)
77      do_sign=true
78      if [[ -n "${2}"  && "${2}" != -* ]]; then
79        private_key_path="$2"
80        shift 2
81      else
82        shift 1
83      fi
84      ;;
85    -m|--machine)
86      machine_name="$2"
87      shift 2
88      ;;
89    -h|--help)
90      echo "$help"
91      exit
92      ;;
93    *)
94      pnorfile="$1"
95      shift 1
96      ;;
97  esac
98done
99
100if [ ! -f "${pnorfile}" ]; then
101  echo "Please enter a valid PNOR file."
102  echo "$help"
103  exit 1
104fi
105
106if [[ "${image_type}" == "squashfs" ]]; then
107  echo "Will generate squashfs image for VPNOR"
108elif [[ "${image_type}" == "static" ]]; then
109  echo "Will use static image for PNOR"
110else
111  echo "Please specify the image type, \"squashfs\" or \"static\""
112  echo
113  echo "$help"
114  exit 1
115fi
116
117if [[ -z $outfile ]]; then
118    if [[ ${pnorfile##*.} == "pnor" ]]; then
119        outfile=$(pwd)/${pnorfile##*/}.$image_type.tar
120    else
121        outfile=$(pwd)/${pnorfile##*/}.pnor.$image_type.tar
122    fi
123    if [[ "${image_type}" == "static" ]]; then
124        # Append .gz so the tarball is compressed
125        outfile=$outfile.gz
126    fi
127else
128    if [[ $outfile != /* ]]; then
129        outfile=$(pwd)/$outfile
130    fi
131fi
132
133
134scratch_dir=$(mktemp -d)
135# Remove the temp directory on exit.
136# The files in the temp directory may contain read-only files, so add
137# --interactive=never to skip the prompt.
138trap '{ rm -r --interactive=never ${scratch_dir}; }' EXIT
139
140if [[ "${do_sign}" == true ]]; then
141  if [[ -z "${private_key_path}" ]]; then
142    private_key_path=${scratch_dir}/OpenBMC.priv
143    echo "${private_key}" > "${private_key_path}"
144    echo "Image is NOT secure!! Signing with the open private key!"
145  else
146    if [[ ! -f "${private_key_path}" ]]; then
147      echo "Couldn't find private key ${private_key_path}."
148      exit 1
149    fi
150
151    echo "Signing with ${private_key_path}."
152  fi
153
154  public_key_file=publickey
155  public_key_path=${scratch_dir}/$public_key_file
156  openssl pkey -in "${private_key_path}" -pubout -out "${public_key_path}"
157fi
158
159echo "Parsing PNOR TOC..."
160
161pnor_dir="${scratch_dir}/pnor"
162mkdir "${pnor_dir}"
163
164pflash --partition=part --read="${pnor_dir}"/part -F "${pnorfile}"
165pflash --partition=VERSION --read="${pnor_dir}"/VERSION -F "${pnorfile}"
166version_size=$(wc -c "${pnor_dir}"/VERSION | cut -d' ' -f 1)
167magic_number=$(xxd -p -l 4 "${pnor_dir}"/VERSION)
168# Check if VERSION is signed. A signed version partition will have an extra
169# 4K header starting with the magic number 0x17082011, see:
170# https://github.com/open-power/skiboot/blob/master/libstb/container.h#L47
171if [ "$version_size" == "8192" ] && [ "$magic_number" == "17082011" ]; then
172  # Advance past the STB header (4K, indexed from 1)
173  cp "${pnor_dir}"/VERSION "${pnor_dir}"/VERSION_FULL
174  tail --bytes=+4097 "${pnor_dir}"/VERSION_FULL > "${pnor_dir}"/VERSION
175fi
176{
177  version=$(head -n 1 "${pnor_dir}"/VERSION)
178  echo "version=$version"
179  # shellcheck disable=SC2005,SC2046 # Need the echo to remove new lines, same
180  # reason for not quoting the tail command
181  extended_version=$(echo $(tail -n +2 "${pnor_dir}"/VERSION)|tr ' ' ',')
182  echo "extended_version=$extended_version"
183  while read -r line; do
184    if [[ $line == "ID="* ]]; then
185        # This line looks like
186        # "ID=05 MVPD 000d9000..00169000 (actual=00090000) [ECC]"
187        read -r -a fields <<< "$line"
188
189        id=${fields[0]##*=}
190        offset=$((ffs_entry_size * 10#${id} + vercheck_offset))
191        vercheck=$(xxd -p -l  0x1 -seek ${offset} "${pnor_dir}"/part)
192        # shellcheck disable=SC2155 # Need the export in the same line to avoid
193        # pflash error
194        export flags=$(pflash --detail=$((10#$id)) -F "${pnorfile}" | grep "\[" |
195                sed 's/....$//' | tr '\n' ',' | sed 's/.$//')
196        if [[ $flags != "" ]]; then
197            flags=,$flags
198        fi
199
200        if [[ $(echo "$flags" | grep "READONLY") == "" &&
201              $(echo "$flags" | grep "PRESERVED") == "" ]]; then
202            flags=$flags,READWRITE
203        fi
204
205        # Need the partition ID, name, start location, end location, and flags
206        echo  "partition${id}=${fields[1]},${fields[2]/../,},${vercheck}${flags}"
207
208        # Save the partition name
209        partitions+=("${fields[1]}")
210    fi
211  # Don't need the BACKUP_PART partition
212  done < <(pflash --info -F "${pnorfile}" | grep -v "BACKUP")
213} > "${pnor_dir}"/${tocfile}
214
215for partition in "${partitions[@]}"; do
216  echo "Reading ${partition}..."
217  pflash --partition="${partition}" \
218    --read="${pnor_dir}"/"${partition}" \
219    -F "${pnorfile}"
220done
221
222manifest_location="MANIFEST"
223files_to_sign="$manifest_location $public_key_file"
224
225# Go to scratch_dir
226
227if [[ "${image_type}" == "squashfs" ]]; then
228  echo "Creating SquashFS image..."
229  # Prepare pnor file in ${pnor_dir}
230  cd "${pnor_dir}"
231  # Set permissions of partition files to read only
232  chmod 440 -- *
233  # shellcheck disable=SC2048,SC2086 # Do not quote partitions since it lists
234  # multiple files and mksquashfs would assume to be a single file name within
235  # quotes
236  mksquashfs ${tocfile} ${partitions[*]} "${scratch_dir}"/pnor.xz.squashfs -all-root
237  cd "${scratch_dir}"
238  files_to_sign+=" pnor.xz.squashfs"
239else
240  cp "${pnorfile}" "${scratch_dir}"
241  cd "${scratch_dir}"
242  files_to_sign+=" $(basename "${pnorfile}")"
243fi
244
245echo "Creating MANIFEST for the image"
246echo -e "purpose=xyz.openbmc_project.Software.Version.VersionPurpose.Host\nversion=$version\n\
247extended_version=$extended_version" >> $manifest_location
248
249if [[ -n "${machine_name}" ]]; then
250    echo -e "MachineName=${machine_name}" >> $manifest_location
251fi
252
253if [[ "${do_sign}" == true ]]; then
254  private_key_name=$(basename "${private_key_path}")
255  key_type="${private_key_name%.*}"
256  echo KeyType="${key_type}" >> $manifest_location
257  echo HashType="RSA-SHA256" >> $manifest_location
258
259  for file in $files_to_sign; do
260    openssl dgst -sha256 -sign "${private_key_path}" -out "${file}.sig" "$file"
261  done
262
263  additional_files="*.sig"
264fi
265
266if [[ "${image_type}" == "squashfs" ]]; then
267  echo "Generating tarball to contain the SquashFS image and its MANIFEST"
268  # shellcheck disable=SC2086 # Do not quote the files variables since they list
269  # multiple files and tar would assume to be a single file name within quotes
270  tar -cvf "$outfile" $files_to_sign $additional_files
271  echo "SquashFSTarball at ${outfile}"
272else
273  # shellcheck disable=SC2086 # Do not quote the files variables since they list
274  # multiple files and tar would assume to be a single file name within quotes
275  tar -czvf "$outfile" $files_to_sign $additional_files
276  echo "Static layout tarball at $outfile"
277fi
278