Files
grpc-library/scripts/release/check-signing-key.sh
T
DongHyeonka a892a45073
pr / ci (pull_request) Successful in 3m34s
fix(release): 서명 진단이 비밀번호 모양을 알리고 Gradle 서명기로도 서명해 본다
signing-check(run 13)에서 base64를 푼 키는 맞았다. armor·CRC24·tag 5가
정상이고, 가져온 키 지문이 릴리스 키 92646CEA…F791F8AB였다. 남은 실패는
「SIGNING_PASSWORD로 서명이 안 된다」 하나인데, 비밀번호가 틀렸는지,
붙여 넣을 때 줄바꿈·공백이 섞였는지, gpg 쪽 문제인지 가를 수 없었다.
gpg는 비밀번호의 첫 줄만 읽고 Gradle은 값 전체를 쓰므로, gpg 판정이
Gradle 판정과 다를 수도 있었다.

- check-signing-key.sh: 비밀번호의 모양(글자 수, 줄바꿈·CR 수, 앞뒤 공백,
  비ASCII 수)과 서명 실패 때의 gpg 상태 키워드만 출력한다. 값은 출력하지
  않는다.
- verifySigningKey: 스크립트 뒤에 Gradle의 in-memory 서명기
  (signing.signatory)로 몇 바이트를 서명해 본다. Sign 태스크와 같은 판정이다.
  실패 문구는 BouncyCastle 예외 문장뿐이다. 둘 중 하나라도 실패하면
  태스크가 실패한다.

검증(로컬 gpg, 버리는 키): 맞는 비밀번호 ok, 틀린 비밀번호 「gpg status:
BEGIN_SIGNING FAILURE KEY_CONSIDERED」. 끝에 줄바꿈이 붙은 비밀번호는 gpg로
ok이고 모양 줄이 「line breaks 1」을 알린다(Gradle 판정은 desktop과 runner).
2026-11-08 15:21:16 +09:00

172 lines
8.3 KiB
Bash
Executable File

#!/usr/bin/env bash
# Checks the release signing secrets before anything is signed, without printing them.
#
# scripts/release/check-signing-key.sh [expected fingerprint]
#
# Reads SIGNING_KEY (an ASCII-armoured PGP secret key) and SIGNING_PASSWORD from the environment and
# prints only shapes and verdicts: line and character counts, whether the armour lines and the blank
# line after BEGIN are where OpenPGP puts them, whether the base64 body decodes and its CRC24 matches,
# the first packet's tag, whether gpg imports it, the imported key's fingerprint (public), and whether
# SIGNING_PASSWORD signs with it. No value, line or fragment of either secret is ever printed; do not
# add `set -x` here.
#
# Why it exists: Gradle's signing reports any of these problems as one "Could not read PGP secret
# key", and the cause sits in a secret nobody can look at in the job log (v1.0.0 release run 9).
# Exit codes: 0 = the key would sign, 1 = a check failed (the line says which), 2 = usage.
set -euo pipefail
expected=${1:-}
fail=0
if [ -z "${SIGNING_KEY:-}" ]; then
echo "check-signing-key: SIGNING_KEY is empty or not set"
exit 1
fi
[ -n "${SIGNING_PASSWORD:-}" ] || echo "check-signing-key: SIGNING_PASSWORD is empty (only right for a key without a passphrase)"
# The passphrase's shape only: a pasted value often carries a line break or spaces the key was not
# protected with, and Gradle uses the value as given.
python3 - <<'PY'
import os
p = os.environ.get("SIGNING_PASSWORD", "")
print(f"password shape: {len(p)} characters, line breaks {p.count(chr(10))}, CR {p.count(chr(13))},"
f" leading whitespace {'yes' if p[:1].isspace() else 'no'}, trailing whitespace {'yes' if p[-1:].isspace() else 'no'},"
f" non-ASCII characters {sum(1 for c in p if ord(c) > 127)}")
PY
home=$(mktemp -d)
trap 'rm -rf "$home"' EXIT
chmod 700 "$home"
KEY_OUT=$home/key.asc EXPECTED_FINGERPRINT=$expected python3 - <<'PY' || fail=1
import base64, os, re, sys
key = os.environ["SIGNING_KEY"]
BEGIN = "-----BEGIN PGP PRIVATE KEY BLOCK-----"
END = "-----END PGP PRIVATE KEY BLOCK-----"
problems = []
print(f"shape: {len(key)} characters, {key.count(chr(10)) + 1} lines,"
f" CR {'present' if chr(13) in key else 'absent'},"
f" literal backslash-n sequences {key.count(chr(92) + 'n')},"
f" non-ASCII characters {sum(1 for c in key if ord(c) > 127)},"
f" leading whitespace {'yes' if key[:1].isspace() else 'no'},"
f" trailing whitespace {'yes' if key[-1:].isspace() else 'no'}")
stripped = key.strip()
compact = re.sub(r"\s", "", key)
if "-----BEGIN" not in key and re.fullmatch(r"[A-Za-z0-9+/]+={0,2}", compact or "x"):
try:
unwrapped = base64.b64decode(compact).decode("utf-8")
except Exception:
unwrapped = ""
if unwrapped.strip().startswith("-----BEGIN PGP PRIVATE KEY BLOCK-----"):
print("form: base64 of an armoured key file on one value; the build unwraps it (SigningKeys), so the checks below read the unwrapped text")
key = unwrapped
stripped = key.strip()
print(f"unwrapped shape: {len(key)} characters, {key.count(chr(10)) + 1} lines")
if re.fullmatch(r"(0x)?[0-9A-Fa-f]{8}|(0x)?[0-9A-Fa-f]{16}|[0-9A-Fa-f]{40}", stripped):
expected = os.environ.get("EXPECTED_FINGERPRINT", "")
same = " (the release key's fingerprint)" if expected and stripped.upper() == expected.upper() else ""
print(f"PROBLEM: SIGNING_KEY holds a {len(stripped)}-hex-digit key ID or fingerprint{same}, not the key."
" Put in the output of `gpg --armor --export-secret-keys <fingerprint>` instead, BEGIN to END lines.")
sys.exit(1)
lines = key.replace("\r\n", "\n").replace("\r", "\n").split("\n")
while lines and lines[-1].strip() == "":
lines.pop()
if "\n" not in key.replace("\r", "\n"):
problems.append("the value is one line: the newlines were lost (paste the file as is, with its line breaks)")
first = lines[0].strip() if lines else ""
last = lines[-1].strip() if lines else ""
print(f"armour: first line is BEGIN {'yes' if first == BEGIN else 'no'}, last line is END {'yes' if last == END else 'no'}")
if first != BEGIN:
kind = "a PUBLIC key block" if "PUBLIC KEY BLOCK" in first else "something else"
problems.append(f"the value does not start with the BEGIN PGP PRIVATE KEY BLOCK line (it starts with {kind})")
if last != END:
problems.append("the value does not end with the END PGP PRIVATE KEY BLOCK line (cut short?)")
body = lines[1:-1] if first == BEGIN and last == END else lines
headers = []
while body and ":" in body[0] and body[0].strip():
headers.append(body.pop(0))
blank_after = bool(body) and body[0].strip() == ""
print(f"armour headers: {len(headers)}, blank line after them {'yes' if blank_after else 'no'}")
if not blank_after:
problems.append("no blank line between the BEGIN line (and its headers) and the base64 body")
data = [l.strip() for l in body if l.strip()]
checksum = data.pop() if data and data[-1].startswith("=") else None
lengths = [len(l) for l in data]
full = sum(1 for n in lengths[:-1] if n == lengths[0]) if lengths else 0
print(f"body: {len(data)} base64 lines, first {lengths[0] if lengths else 0} characters wide,"
f" {full + (1 if lengths else 0)} of {len(data)} lines that width or the last,"
f" checksum line {'present' if checksum else 'absent'}")
if lengths and any(n != lengths[0] for n in lengths[:-1]):
problems.append("base64 lines of different widths before the last one (lines joined, split or cut)")
joined = "".join(data)
bad = sum(1 for c in joined if not re.match(r"[A-Za-z0-9+/=]", c))
if bad:
problems.append(f"{bad} characters outside the base64 alphabet in the body")
try:
raw = base64.b64decode(joined, validate=False)
except Exception as error:
raw = b""
problems.append(f"the body does not decode as base64 ({type(error).__name__})")
if raw:
def crc24(data):
crc = 0xB704CE
for byte in data:
crc ^= byte << 16
for _ in range(8):
crc <<= 1
if crc & 0x1000000:
crc ^= 0x1864CFB
return crc & 0xFFFFFF
if checksum:
try:
stated = int.from_bytes(base64.b64decode(checksum[1:]), "big")
match = stated == crc24(raw)
except Exception:
match = False
print(f"CRC24 of the decoded body matches the checksum line: {'yes' if match else 'no'}")
if not match:
problems.append("the CRC24 checksum does not match: the base64 body was changed (a line lost, added or edited)")
header = raw[0]
tag = (header & 0x3F) if header & 0x40 else ((header & 0x3C) >> 2)
names = {5: "secret key", 6: "public key", 7: "secret subkey"}
print(f"first packet: tag {tag} ({names.get(tag, 'not a key packet')}), {len(raw)} bytes decoded")
if not header & 0x80 or tag != 5:
problems.append("the first packet is not a secret key packet (tag 5)")
for problem in problems:
print(f"PROBLEM: {problem}")
with open(os.environ["KEY_OUT"], "w", encoding="utf-8") as out:
out.write(key)
sys.exit(1 if problems else 0)
PY
if [ -s "$home/key.asc" ] && GNUPGHOME="$home" gpg --batch --quiet --import "$home/key.asc" >/dev/null 2>&1; then
fingerprint=$(GNUPGHOME="$home" gpg --batch --with-colons --list-secret-keys 2>/dev/null | awk -F: '/^fpr/{print $10; exit}')
echo "gpg import: ok, secret key fingerprint ${fingerprint:-none}"
if [ -n "$expected" ] && [ "${fingerprint:-}" != "$expected" ]; then
echo "PROBLEM: the imported key is not the release key ${expected}"
fail=1
fi
printf 'signing check\n' > "$home/message"
# gpg reads only the first line of the file; the shape line above says whether there is more.
printf '%s' "${SIGNING_PASSWORD:-}" > "$home/passphrase"
if GNUPGHOME="$home" gpg --batch --pinentry-mode loopback --passphrase-file "$home/passphrase" \
--status-fd 3 --local-user "${fingerprint:-none}" --detach-sign --output "$home/message.sig" \
"$home/message" >/dev/null 2>&1 3>"$home/status"; then
echo "signing with SIGNING_PASSWORD: ok"
else
# gpg's status keywords only (BAD_PASSPHRASE, MISSING_PASSPHRASE, ERROR …): no values.
status=$(awk '$1 == "[GNUPG:]" {print $2}' "$home/status" | sort -u | tr '\n' ' ')
echo "PROBLEM: SIGNING_PASSWORD does not unlock the key for signing (gpg status: ${status:-none})"
fail=1
fi
else
echo "PROBLEM: gpg cannot import SIGNING_KEY"
fail=1
fi
exit "$fail"