|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +# This script signs a given binary using GPG. |
| 4 | +# It expects the binary to be signed as the first argument. |
| 5 | +# |
| 6 | +# Usage: ./sign_with_gpg.sh path/to/binary |
| 7 | +# |
| 8 | +# On success, the input file will be signed using the GPG key and the signature output file will moved to /site/out/bin/ (happens in the Makefile) |
| 9 | +# |
| 10 | +# Depends on the GPG utility. Requires the following environment variables to be set: |
| 11 | +# - $CODER_GPG_RELEASE_KEY_BASE64: The base64 encoded private key to use. |
| 12 | + |
| 13 | +set -euo pipefail |
| 14 | +# shellcheck source=scripts/lib.sh |
| 15 | +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" |
| 16 | + |
| 17 | +requiredenvs CODER_GPG_RELEASE_KEY_BASE64 |
| 18 | + |
| 19 | +FILE_TO_SIGN="$1" |
| 20 | + |
| 21 | +if [[ -z "$FILE_TO_SIGN" ]]; then |
| 22 | + error "Usage: $0 <file_to_sign>" |
| 23 | +fi |
| 24 | + |
| 25 | +if [[ ! -f "$FILE_TO_SIGN" ]]; then |
| 26 | + error "File not found: $FILE_TO_SIGN" |
| 27 | +fi |
| 28 | + |
| 29 | +# Import the GPG key. |
| 30 | +old_gnupg_home="${GNUPGHOME:-}" |
| 31 | +gnupg_home_temp="$(mktemp -d)" |
| 32 | +export GNUPGHOME="$gnupg_home_temp" |
| 33 | + |
| 34 | +# Ensure GPG uses the temporary directory |
| 35 | +echo "$CODER_GPG_RELEASE_KEY_BASE64" | base64 -d | gpg --homedir "$gnupg_home_temp" --import 1>&2 |
| 36 | + |
| 37 | +# Sign the binary. This generates a file in the same directory and |
| 38 | +# with the same name as the binary but ending in ".asc". |
| 39 | +# |
| 40 | +# We pipe `true` into `gpg` so that it never tries to be interactive (i.e. |
| 41 | +# ask for a passphrase). The key we import above is not password protected. |
| 42 | +true | gpg --homedir "$gnupg_home_temp" --detach-sign --armor "$FILE_TO_SIGN" 1>&2 |
| 43 | + |
| 44 | +# Verify the signature and capture the exit status |
| 45 | +gpg --homedir "$gnupg_home_temp" --verify "${FILE_TO_SIGN}.asc" "$FILE_TO_SIGN" 1>&2 |
| 46 | +verification_result=$? |
| 47 | + |
| 48 | +# Clean up the temporary GPG home |
| 49 | +rm -rf "$gnupg_home_temp" |
| 50 | +unset GNUPGHOME |
| 51 | +if [[ "$old_gnupg_home" != "" ]]; then |
| 52 | + export GNUPGHOME="$old_gnupg_home" |
| 53 | +fi |
| 54 | + |
| 55 | +if [[ $verification_result -eq 0 ]]; then |
| 56 | + echo "${FILE_TO_SIGN}.asc" |
| 57 | +else |
| 58 | + error "Signature verification failed!" |
| 59 | +fi |
0 commit comments