Compare commits

..
4 Commits
Author SHA1 Message Date
lotherk 1202fe0090 0.1.1
ci / build (push) Successful in 52s
2026-11-21 19:04:03 +00:00
lotherk 577052decd 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.
2026-11-21 19:02:08 +00:00
lotherk 6851364ccb bound the public blob copied out of a key container
ci / build (push) Successful in 1m7s
Review found a stack-buffer-overflow in scr_openssh_load: the public blob
length came straight from the file and was memcpy'd into struct scr_priv's
4096-byte field. A crafted RSA key file (the ed25519 path cross-checks first)
overwrote the stack: ASan reported a 6000-byte write.

Also reject p or q <= 1 before BN_mod, arm the temp-file cleanup before the
write rather than after, clear the active flag on the conversion-failure path,
and block INT/TERM/HUP across ssh-keygen so a signalled child cannot rename a
fresh copy back after the handler unlinked it.

The new case crafts an oversized blob and asserts a clean exit 1, not a crash.
2026-11-21 18:38:46 +00:00
lotherk abdac42c83 README: name the tested OpenSSH and OpenSSL versions
ci / build (push) Successful in 34s
2026-11-21 17:13:12 +00:00
7 changed files with 240 additions and 75 deletions

No files matched your search

+17 -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: 25 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
@@ -58,12 +58,25 @@ you pass; do not remove that `override`.
* OpenSSL has no Ed25519→X25519 helper. `scr_ed25519_pk_to_x25519()` in
`keys.c` is the standard `u = (1+y)/(1-y)` map, cross-checked against
libcrypto X25519 in `tests/run.sh`. Do not replace it with an assumption.
* Lengths inside a key or message file are attacker-controlled. Every copy into
a fixed field must be bounded: the public blob from `openssh-key-v1` is
`memcpy`'d into `struct scr_priv.blob[4096]`, and it used to be copied at
whatever length the file claimed (stack overflow, caught in review). The
guard is the `publ > sizeof out->blob` check in `scr_openssh_load`.
* `memmem` is GNU, not POSIX. Use `find_bytes()` in `keys.c`.
* Terminal echo: save termios *before* clearing `ECHO` and restore that saved
copy. Re-reading with `tcgetattr` after disabling restores no-echo, and
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`.
+2 -1
View File
@@ -110,7 +110,8 @@ wrong key reports both fingerprints instead of a padding error:
present, `-lcrypto` otherwise.
* `ssh-keygen` at runtime, only for passphrase-protected OpenSSH keys.
Tested on Debian with OpenSSL 3.6.3 and OpenSSH 10.5p1.
Tested on Debian bookworm (OpenSSH 9.2, OpenSSL 3.0), Ubuntu 26.04 (OpenSSH
10.2, OpenSSL 3.5) and Debian testing (OpenSSH 10.5, OpenSSL 3.6).
## License
+1 -1
View File
@@ -1,4 +1,4 @@
.TH SSHCRYPT 1 "2026-11-21" "sshcrypt 0.1.0" "User Commands"
.TH SSHCRYPT 1 "2026-11-21" "sshcrypt 0.1.1" "User Commands"
.SH NAME
sshcrypt \- encrypt a file, a message, or stdin for an SSH public key
.SH SYNOPSIS
+138 -66
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,32 +603,62 @@ 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)
scr_die(SCR_EIO, "cannot create a temporary key file: %s",
strerror(errno));
(void)fchmod(fd, 0600);
scr_write_fd(fd, raw->data, raw->len);
close(fd);
/* 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);
if (run_ssh_keygen(tmp, pw) != 0) {
scr_secure_zero(pw, strlen(pw));
free(pw);
unlink(tmp);
free(tmp);
scr_die(SCR_EUSAGE,
"%s: wrong passphrase, or ssh-keygen could not read it",
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 has finished. */
sigset_t block, old;
int rc;
sigemptyset(&block);
sigaddset(&block, SIGINT);
sigaddset(&block, SIGTERM);
sigaddset(&block, SIGHUP);
sigprocmask(SIG_BLOCK, &block, &old);
rc = run_ssh_keygen(tmp, pw);
sigprocmask(SIG_SETMASK, &old, NULL);
if (rc != 0) {
scr_secure_zero(pw, strlen(pw));
free(pw);
unlink(tmp);
g_tmp_active = 0;
free(tmp);
scr_die(SCR_EUSAGE,
"%s: wrong passphrase, or ssh-keygen could not "
"read it", path);
}
}
scr_secure_zero(pw, strlen(pw));
free(pw);
+7
View File
@@ -120,6 +120,8 @@ static EVP_PKEY *rsa_from_parts(const unsigned char *nb, size_t nl,
goto done;
if (!BN_sub_word(pm1, 1) || !BN_sub_word(qm1, 1))
goto done;
if (BN_is_zero(pm1) || BN_is_zero(qm1))
goto done;
if (!BN_mod(dp, d, pm1, ctx) || !BN_mod(dq, d, qm1, ctx))
goto done;
@@ -273,6 +275,11 @@ int scr_openssh_load(const unsigned char *text, size_t n, struct scr_priv *out)
"supported\n", nkeys);
goto done;
}
if (publ == 0 || publ > sizeof out->blob) {
fprintf(stderr, "sshcrypt: the public key blob is %zu bytes; the "
"limit is %zu\n", publ, sizeof out->blob);
goto done;
}
if (parse_private(priv, privl, pub, publ, out) < 0)
goto done;
+1 -1
View File
@@ -4,7 +4,7 @@
#include <stddef.h>
#define SCR_VERSION 1
#define SCR_VERSION_STR "0.1.0"
#define SCR_VERSION_STR "0.1.1"
#define SCR_SUITE_X25519 1
#define SCR_SUITE_RSA 2
+74 -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"
@@ -98,12 +122,62 @@ else
ok
fi
# A public blob larger than the 4096-byte field must be rejected, not memcpy'd
# into struct scr_priv (this was a stack overflow in the container parser).
python3 - "$T/rsa" "$T/oversize" <<'EOF'
import base64, struct, sys
def rd(b, o):
n = struct.unpack('>I', b[o:o+4])[0]
return b[o+4:o+4+n], o+4+n
def put(s):
return struct.pack('>I', len(s)) + s
body = base64.b64decode(''.join(
l for l in open(sys.argv[1]).read().splitlines() if '---' not in l))
o = 15
cipher, o = rd(body, o)
kdf, o = rd(body, o)
ko, o = rd(body, o)
o += 4
_, o = rd(body, o)
priv, o = rd(body, o)
new = (body[:15] + put(cipher) + put(kdf) + put(ko) + struct.pack('>I', 1)
+ put(b'\x00' * 6000) + put(priv))
b64 = base64.b64encode(new).decode()
open(sys.argv[2], 'w').write(
'-----BEGIN OPENSSH PRIVATE KEY-----\n'
+ '\n'.join(b64[i:i + 70] for i in range(0, len(b64), 70))
+ '\n-----END OPENSSH PRIVATE KEY-----\n')
EOF
rc=0
"$BIN" -d -k "$T/oversize" -i "$T/msg.asc" -o /dev/null 2>"$T/over.err" ||
rc=$?
check "oversized key blob is rejected, not a crash" \
'[ "$rc" -eq 1 ] || [ "$rc" -eq 2 ]'
check "oversized key blob is named as such" \
'grep -q "public key blob is" "$T/over.err"'
# --- passphrase-protected OpenSSH key, and -r with a private key --------------
SSHCRYPT_PASSPHRASE=hunter2 "$BIN" -r "$T/pw.pub" -i "$T/msg" -o "$T/pw.asc"
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\"" \
@@ -119,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"