fix the remaining review findings in key handling
ci / build (push) Successful in 30s

- Parse public key lines field by field instead of searching for the type name
  anywhere. A commented-out key line is now ignored (it used to be accepted,
  so a secret could be encrypted to a key the user had disabled), and an
  authorized_keys option that contains the word ssh-rsa no longer aborts the
  parse. A candidate field only counts if its base64 decodes to that type.
- Bound the line loop by the buffer length, not by *p: the buffer is not NUL
  terminated, so a 64 KiB file ending in a newline made the loop look at
  uninitialised heap (valgrind). Reproduced on the old build, clean now.
- Ask for the passphrase before creating the temp file, and register an
  atexit cleanup, so a scr_die between mkstemp and the unlink cannot leave the
  key behind (no tty and no SSHCRYPT_PASSPHRASE used to leak one per run).
- Install the cleanup handler before the prompt again. A background job in a
  non-interactive shell inherits SIG_IGN for SIGINT, and ignored dispositions
  survive exec, so killing at the prompt is a no-op without a handler.

The suite is 31 cases and now covers each of these; five of them fail on the
previous build.
This commit is contained in:
lotherk committed 2026-11-21 19:02:08 +00:00
1 parent 6851364ccb
commit 577052decd
3 files changed
+163 -63

No files matched your search

+12 -4
View File
@@ -11,10 +11,10 @@ those is a design decision, not a commit.
make check # tests/run.sh, generates keys in a tmpdir, no network
make install PREFIX=$HOME/.local # installs bin/sshcrypt
`make check` is the gate: 27 end-to-end cases. It needs `ssh-keygen`, `cmp`,
`python3` (tamper test), `script(1)` (pty cases) and `pgrep` (SIGINT case);
those last ones skip themselves if the tool is missing. No network. After
touching parsing or the envelope, also run
`make check` is the gate: 31 end-to-end cases. It needs `ssh-keygen`, `cmp`,
`python3` (tamper and crafted-key cases), `script(1)` (pty cases), `pgrep`
(SIGINT case) and `setsid(1)` (no-tty case); those skip themselves if the tool
is missing. No network. After touching parsing or the envelope, also run
make clean && make CFLAGS="-O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer" LDFLAGS="-fsanitize=address,undefined" && make check
@@ -69,6 +69,14 @@ you pass; do not remove that `override`.
termios outlives the fd, so the user's shell is left mute. Use `TCSANOW`,
not `TCSAFLUSH`: the flush discards a passphrase that is already queued in
the tty. Both are covered by the `script(1)` cases in `make check`.
* A background job started by a non-interactive shell inherits SIGINT and
SIGQUIT set to `SIG_IGN`, and ignored dispositions survive `exec`. Installing
the cleanup handler is what makes Ctrl-C work in that case; do not move it
after the passphrase prompt (the pty test kills at the prompt).
* Public key lines are parsed field by field: a commented line is ignored, and
a field that merely contains a type name is skipped unless its base64 decodes
to that same type. A substring search accepts `# disabled: ssh-ed25519 ...`
and breaks on `command="echo ssh-rsa hi"`.
* Every `.c` includes its own headers; missing `<stdio.h>` is a hard error under
`-std=c99 -Wpedantic`.
+111 -57
View File
@@ -36,6 +36,13 @@ static void tmp_signal(int sig)
_exit(128 + sig);
}
/* Any scr_die between mkstemp and the caller's unlink goes through exit(). */
static void tmp_atexit(void)
{
if (g_tmp_active)
(void)unlink(g_tmp_path);
}
static void tmp_signals_install(void)
{
static int done;
@@ -349,72 +356,107 @@ done:
return rc;
}
/* Does this blob really begin with the advertised key type? An options value
* that merely contains the word "ssh-rsa" will not survive this. */
static int blob_has_type(const struct buf *raw, const char *type, size_t tl)
{
const unsigned char *p = raw->data, *s;
size_t left = raw->len, n;
if (rd_string(&p, &left, &s, &n) < 0)
return 0;
return n == tl && memcmp(s, type, tl) == 0;
}
static int parse_pub_text(const char *text, size_t n, const char *label,
struct scr_pub *out)
{
const char *types[2] = { "ssh-ed25519", "ssh-rsa" };
const char *p = text;
const char *end_all = text + n;
int found = 0;
char foundtype[32] = { 0 };
unsigned char blob[SCR_PUB_MAX];
size_t bloblen = 0;
memset(out, 0, sizeof *out);
while (p && *p) {
const char *eol = memchr(p, '\n', (size_t)((text + n) - p));
size_t linelen = eol ? (size_t)(eol - p) : (size_t)((text + n) - p);
int i;
while (p < end_all) {
const char *eol = memchr(p, '\n', (size_t)(end_all - p));
const char *line_end = eol ? eol : end_all;
const char *q = p;
for (i = 0; i < 2; i++) {
size_t tl = strlen(types[i]);
const char *tok = p, *end = p + linelen;
const char *b64;
size_t b64len;
struct buf raw;
while (tok < end) {
tok = find_bytes(tok, (size_t)(end - tok), types[i], tl);
if (!tok)
break;
if (tok + tl < end && tok[tl] == ' ')
break;
tok += tl;
}
if (!tok || tok >= end)
continue;
b64 = tok + tl + 1;
while (b64 < end && (*b64 == ' ' || *b64 == '\t'))
b64++;
b64len = 0;
while (b64 + b64len < end && b64[b64len] != ' ' &&
b64[b64len] != '\t' && b64[b64len] != '\r')
b64len++;
if (b64len == 0)
continue;
if (scr_b64_decode(b64, b64len, &raw) < 0) {
fprintf(stderr, "sshcrypt: %s: bad base64\n", label);
return -1;
}
if (found) {
fprintf(stderr,
"sshcrypt: %s holds more than one supported "
"key; use a file with just the recipient's "
"key\n", label);
free(raw.data);
return -1;
}
if (raw.len > sizeof blob) {
fprintf(stderr, "sshcrypt: %s: key too large\n", label);
free(raw.data);
return -1;
}
memcpy(blob, raw.data, raw.len);
bloblen = raw.len;
snprintf(foundtype, sizeof foundtype, "%s", types[i]);
found = 1;
free(raw.data);
/* a comment line is not a key, even when it names one */
while (q < line_end && (*q == ' ' || *q == '\t'))
q++;
if (q == line_end || *q == '#') {
p = eol ? eol + 1 : end_all;
continue;
}
p = eol ? eol + 1 : NULL;
/* Fields are whitespace separated: [options] keytype base64
* [comment]. Only a field that is exactly a key type counts, and
* it must be followed by something that decodes to that same
* type, so text inside an options value is skipped. */
while (q < line_end) {
const char *tok;
size_t toklen;
int i;
while (q < line_end &&
(*q == ' ' || *q == '\t' || *q == '\r'))
q++;
if (q == line_end)
break;
tok = q;
while (q < line_end && *q != ' ' && *q != '\t' &&
*q != '\r')
q++;
toklen = (size_t)(q - tok);
for (i = 0; i < 2; i++) {
const char *b64;
size_t b64len;
struct buf raw = { NULL, 0 };
if (toklen != strlen(types[i]) ||
memcmp(tok, types[i], toklen) != 0)
continue;
while (q < line_end &&
(*q == ' ' || *q == '\t'))
q++;
b64 = q;
while (q < line_end && *q != ' ' && *q != '\t' &&
*q != '\r')
q++;
b64len = (size_t)(q - b64);
if (b64len == 0 ||
scr_b64_decode(b64, b64len, &raw) < 0 ||
!blob_has_type(&raw, types[i], toklen)) {
free(raw.data);
continue;
}
if (found) {
fprintf(stderr, "sshcrypt: %s holds more "
"than one supported key; use a "
"file with just the recipient's "
"key\n", label);
free(raw.data);
return -1;
}
if (raw.len > sizeof blob) {
fprintf(stderr, "sshcrypt: %s: key too "
"large\n", label);
free(raw.data);
return -1;
}
memcpy(blob, raw.data, raw.len);
bloblen = raw.len;
snprintf(foundtype, sizeof foundtype, "%s", types[i]);
found = 1;
free(raw.data);
}
}
p = eol ? eol + 1 : end_all;
}
if (!found) {
fprintf(stderr,
@@ -561,11 +603,25 @@ static char *strip_passphrase(const char *path, const struct buf *raw)
const char *dir = access("/dev/shm", W_OK) == 0 ? "/dev/shm" :
(t && *t ? t : "/tmp");
size_t plen = strlen(dir) + 32;
char *tmp = scr_xmalloc(plen);
char *tmp;
const char *env = passphrase_env();
char *pw;
static int atexit_set;
int fd;
/* Arm cleanup before anything can fail or be interrupted. Installing the
* handler also overrides an inherited SIG_IGN, which a background job
* gets from a non-interactive shell. */
if (!atexit_set) {
(void)atexit(tmp_atexit);
atexit_set = 1;
}
tmp_signals_install();
/* Ask before the file exists: if this dies there is nothing to clean. */
pw = env ? scr_xstrdup(env) : get_passphrase(path);
tmp = scr_xmalloc(plen);
snprintf(tmp, plen, "%s/sshcrypt-XXXXXX", dir);
fd = mkstemp(tmp);
if (fd < 0)
@@ -575,16 +631,14 @@ static char *strip_passphrase(const char *path, const struct buf *raw)
/* arm the cleanup before writing, so a signal cannot leave a file */
snprintf(g_tmp_path, sizeof g_tmp_path, "%s", tmp);
g_tmp_active = 1;
tmp_signals_install();
scr_write_fd(fd, raw->data, raw->len);
close(fd);
pw = env ? scr_xstrdup(env) : get_passphrase(path);
{
/* Hold the cleanup signals across the child: if it were signalled
* mid-write it could rename a fresh copy back after the handler
* unlinked the path. A pending signal is delivered on unblock,
* when the conversion is finished. */
* when the conversion has finished. */
sigset_t block, old;
int rc;
+40 -2
View File
@@ -24,6 +24,30 @@ check "fingerprint ed25519 matches ssh-keygen" \
check "fingerprint RSA matches ssh-keygen" \
'[ "$("$BIN" -F "$T/rsa.pub")" = "$(ssh-keygen -lf "$T/rsa.pub" | cut -d" " -f2)" ]'
# A key line inside a comment is not a key: encrypting to a disabled key would
# be silent and wrong.
sed 's/^/# disabled: /' "$T/ed.pub" >"$T/comment.pub"
rc=0
"$BIN" -F "$T/comment.pub" >/dev/null 2>&1 || rc=$?
check "a commented-out key is ignored" '[ "$rc" -ne 0 ]'
# authorized_keys options may contain spaces and words that look like a key
# type; only a field that decodes to that type counts.
printf 'command="echo ssh-rsa hi" %s\n' "$(cat "$T/ed.pub")" >"$T/opts.pub"
check "options before the key are ignored" \
'[ "$("$BIN" -F "$T/opts.pub")" = "$(ssh-keygen -lf "$T/ed.pub" | cut -d" " -f2)" ]'
# Exactly one read-buffer boundary (64 KiB) ending in a newline: parse_pub_text
# used to look at text[n], which is uninitialised there.
python3 - "$T/ed.pub" "$T/big.pub" <<'EOF'
import sys
key = open(sys.argv[1]).read().strip()
pad = 65536 - len(key) - 2
open(sys.argv[2], 'w').write('#' + 'x' * (pad - 1) + '\n' + key + '\n')
EOF
check "a 64 KiB key file is read to its last byte" \
'[ "$("$BIN" -F "$T/big.pub")" = "$(ssh-keygen -lf "$T/ed.pub" | cut -d" " -f2)" ]'
# --- round trips --------------------------------------------------------------
printf 'hello, world\n' >"$T/msg"
"$BIN" -r "$T/ed.pub" -i "$T/msg" -o "$T/msg.asc"
@@ -138,6 +162,22 @@ SSHCRYPT_PASSPHRASE=hunter2 "$BIN" -d -k "$T/pw" -i "$T/pw.asc" -o "$T/pw.out"
check "passphrase-protected key round trip" 'cmp -s "$T/msg" "$T/pw.out"'
# --- the interactive prompt, on a real pty ------------------------------------
tmpd=/dev/shm
[ -w "$tmpd" ] || tmpd=${TMPDIR:-/tmp}
# No tty and no passphrase: fail before a temp file is created.
if command -v setsid >/dev/null 2>&1; then
before=$(ls "$tmpd" 2>/dev/null | grep -c '^sshcrypt-' || true)
rc=0
env -u SSHCRYPT_PASSPHRASE setsid -w "$BIN" -d -k "$T/pw" \
-i "$T/pw.asc" -o /dev/null </dev/null >/dev/null 2>&1 || rc=$?
after=$(ls "$tmpd" 2>/dev/null | grep -c '^sshcrypt-' || true)
check "no tty and no passphrase leaves no temp key" \
'[ "$rc" -eq 1 ] && [ "$after" -eq "$before" ]'
else
printf 'skip: setsid(1) missing, the no-tty case was not tested\n'
fi
if command -v script >/dev/null 2>&1; then
printf 'hunter2\n' | script -qec \
"\"$BIN\" -d -k \"$T/pw\" -i \"$T/pw.asc\" -o \"$T/pty.out\"" \
@@ -153,8 +193,6 @@ if command -v script >/dev/null 2>&1; then
# Interrupting the conversion must not leave key material behind.
if command -v pgrep >/dev/null 2>&1; then
tmpd=/dev/shm
[ -w "$tmpd" ] || tmpd=${TMPDIR:-/tmp}
before=$(ls "$tmpd" 2>/dev/null | grep -c '^sshcrypt-' || true)
mkfifo "$T/ttyin"
exec 9<>"$T/ttyin"