#!/usr/bin/env python3 """write-ssh-key.sh — normalize a pasted OpenSSH private key back to canonical PEM so ssh(1) accepts it, regardless of how a secrets UI stored it. Handles the realistic ways a web "secret" field can mangle a multiline key: * CRLF line endings (``\\r`` stripped) * missing trailing newline * the base64 body collapsed onto one line with spaces instead of newlines * leading/trailing whitespace Usage: write-ssh-key.sh (key content on stdin) Prints the number of bytes written; exits non-zero with a diagnostic if the result doesn't look like an OpenSSH private key. """ import base64 import re import sys KEY_RE = re.compile( r"-----BEGIN (?POPENSSH|PRIVATE|RSA|EC|DSA)[^-]*PRIVATE KEY-----" r"(?P.*?)" r"-----END (?P=kind)[^-]*PRIVATE KEY-----", re.DOTALL, ) def main() -> int: if len(sys.argv) != 2: print(__doc__) return 2 out = sys.argv[1] raw = sys.stdin.read() raw = raw.strip().replace("\r", "") m = KEY_RE.search(raw) if not m: print("write-ssh-key: no PEM block found in the secret", file=sys.stderr) return 1 header = m.group(0).split("-----", 4)[1] kind = m.group("kind") # re-wrap the base64 body at 70 chars/line (OpenSSH's native width) body = re.sub(r"[^A-Za-z0-9+/=]", "", m.group("body")) try: base64.b64decode(body, validate=True) except Exception as e: # noqa: BLE001 print(f"write-ssh-key: base64 body is invalid: {e}", file=sys.stderr) return 1 lines = [body[i : i + 70] for i in range(0, len(body), 70)] block = ( f"-----BEGIN {kind} PRIVATE KEY-----\n" + "\n".join(lines) + f"\n-----END {kind} PRIVATE KEY-----\n" ) with open(out, "w") as fh: fh.write(block) print(f"normalized {kind} private key -> {out} ({len(block)} bytes)") return 0 if __name__ == "__main__": sys.exit(main())