Compare commits

..
6 Commits
Author SHA1 Message Date
lotherk 154d25be91 accept input of exactly the documented size limit
ci / build (push) Successful in 28s
Review found the cap used as an output bound as well as an input bound: a file
of exactly 1 GiB, the documented maximum, was rejected twice. scr_read_fd could
not tell a full buffer from a larger input, and scr_encrypt refused anything
over SCR_INPUT_MAX minus the envelope overhead. The reader now probes a single
byte past a full buffer to distinguish the two, and the encrypt guard is a
plain size_t overflow check.

The suite builds a second binary with -DSCR_INPUT_MAX=65536 so both sides of the
boundary are tested without a 1 GiB file; the previous code fails the exact-cap
case. Also adds CRLF armor and 'a failed decrypt leaves the output file alone'
cases, and documents that -r on a protected key asks for its passphrase.
2026-11-21 20:07:04 +00:00
lotherk 2c381cbe75 mark scr_die noreturn so the error paths are provably dead ends
ci / build (push) Successful in 37s
gcc -fanalyzer and clang --analyze both reported findings that trace back to
scr_die() looking like an ordinary call: a possible NULL passphrase dereference
in strip_passphrase, and a double free of the temp key path (the analyzer
believed the conversion-failure branch returned and handed the freed pointer
back to the caller). exit() never returns, so say so with SCR_NORETURN.

Both analyzers are silent now; the suite is unchanged at 31/31.
2026-11-21 19:47:47 +00:00
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
9 changed files with 321 additions and 78 deletions

No files matched your search

+27 -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: 35 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,35 @@ 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"`.
* `SCR_INPUT_MAX` bounds the *input*, not the output. It used to guard the
envelope size too, so an input of exactly the documented cap was rejected by
the reader and again by `scr_encrypt`. The reader now probes one byte past a
full buffer to distinguish "full" from "too large", and `scr_encrypt` only
guards against `size_t` overflow. `tests/run.sh` rebuilds the tool with a
64 KiB cap so both sides of the boundary are covered without a 1 GiB file.
* `scr_die()` is declared `SCR_NORETURN`. Without the attribute both
`gcc -fanalyzer` and `clang --analyze` treat the code after a fatal call as
reachable and report a NULL dereference and a double free that cannot happen.
Keep it when touching the error paths.
* Every `.c` includes its own headers; missing `<stdio.h>` is a hard error under
`-std=c99 -Wpedantic`.
+4 -1
View File
@@ -34,6 +34,8 @@ Code: https://git.kropa.tech/hiddenbox/sshcrypt
`-r` also accepts a private key path: the public half is derived from it, so
`sshcrypt -r ~/.ssh/id_ed25519` works when you want to encrypt to yourself.
A passphrase-protected key asks for its passphrase first, because the public
half is read out of the key.
Nothing is written to stdout except the payload. The one-line
`encrypted for SHA256:...` note goes to stderr, and only when stderr is a
@@ -110,7 +112,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
+2 -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
@@ -63,6 +63,7 @@ The recipient's public key, in
.I authorized_keys
format.
A private key is accepted too: its public half is derived from it.
If that key has a passphrase, it is asked for first.
A file that holds more than one supported key is rejected.
.TP
.BR \-k ", " \-\-key " " \fIFILE\fP
+3 -1
View File
@@ -301,7 +301,9 @@ int scr_encrypt(const struct scr_pub *to, const unsigned char *pt, size_t n,
goto done;
body = SCR_HDR_LEN + 2 + kemlen + SCR_NONCE_LEN;
if (n > SCR_INPUT_MAX - body)
/* Overflow guard only: the reader already enforced the input cap, and
* refusing exactly-cap input here would contradict it. */
if (n > (size_t)-1 - body - SCR_TAG_LEN)
goto done;
env = scr_xmalloc(body + n + SCR_TAG_LEN);
memcpy(env, header, SCR_HDR_LEN);
+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;
+14 -2
View File
@@ -3,8 +3,18 @@
#include <stddef.h>
/* C99 has no _Noreturn; both compilers we target do have the attribute. It
* matters: without it a static analyzer cannot tell that an error path ends,
* and it reads the cleanup after scr_die() as a fall-through (it reported a
* double free of the temp path for exactly that reason). */
#if defined(__GNUC__) || defined(__clang__)
#define SCR_NORETURN __attribute__((__noreturn__))
#else
#define SCR_NORETURN
#endif
#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
@@ -13,7 +23,9 @@
#define SCR_TAG_LEN 16
#define SCR_HDR_LEN 40 /* magic4 version1 suite1 reserved2 fingerprint32 */
#define SCR_PUB_MAX 4096
#ifndef SCR_INPUT_MAX
#define SCR_INPUT_MAX (1024u * 1024u * 1024u)
#endif
#define SCR_OK 0
#define SCR_EUSAGE 1
@@ -27,7 +39,7 @@ struct buf {
};
/* util.c */
void scr_die(int code, const char *fmt, ...);
void scr_die(int code, const char *fmt, ...) SCR_NORETURN;
void *scr_xmalloc(size_t n);
void *scr_xrealloc(void *p, size_t n);
char *scr_xstrdup(const char *s);
+14 -1
View File
@@ -66,10 +66,23 @@ struct buf scr_read_fd(int fd, size_t max, const char *what)
ssize_t r;
if (b.len == cap) {
if (cap >= max)
if (cap >= max) {
/* A fill of exactly max bytes is allowed; only one
* more byte proves the input is too large. */
unsigned char extra;
do {
r = read(fd, &extra, 1);
} while (r < 0 && errno == EINTR);
if (r < 0)
scr_die(SCR_EIO, "%s: %s", what,
strerror(errno));
if (r == 0)
break;
scr_die(SCR_EDATA,
"%s: larger than the %zu byte limit",
what, max);
}
cap *= 2;
if (cap > max)
cap = max;
+112 -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"
@@ -68,6 +92,15 @@ check "RSA round trip" 'cmp -s "$T/msg" "$T/rsa.out"'
"$BIN" -d -k "$T/ed" -i "$T/mail.txt" -o "$T/mail.out"
check "armor inside surrounding text" 'cmp -s "$T/msg" "$T/mail.out"'
# Mail clients may have written CRLF line endings.
python3 - "$T/msg.asc" "$T/crlf.asc" <<'EOF'
import sys
open(sys.argv[2], 'wb').write(
open(sys.argv[1], 'rb').read().replace(b'\n', b'\r\n'))
EOF
"$BIN" -d -k "$T/ed" -i "$T/crlf.asc" -o "$T/crlf.out"
check "CRLF armor decrypts" 'cmp -s "$T/msg" "$T/crlf.out"'
# --- errors ------------------------------------------------------------------
if "$BIN" -d -k "$T/other" -i "$T/msg.asc" -o "$T/nope" 2>"$T/err"; then
bad "decrypting with the wrong key must fail"
@@ -78,6 +111,12 @@ check "wrong key names both fingerprints" \
'grep -q "but your key is SHA256:" "$T/err"'
check "wrong key writes nothing" '[ ! -e "$T/nope" ]'
# An existing output file must survive a failed decryption untouched.
printf 'keep me\n' >"$T/keep"
"$BIN" -d -k "$T/other" -i "$T/msg.asc" -o "$T/keep" 2>/dev/null || true
check "a failed decrypt leaves the output file alone" \
'[ "$(cat "$T/keep")" = "keep me" ]'
cp "$T/blob.bin" "$T/tampered.bin"
python3 - "$T/tampered.bin" <<'EOF'
import sys
@@ -98,12 +137,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 +208,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"
@@ -176,5 +263,28 @@ head -c 1048576 /dev/urandom >"$T/big"
"$BIN" -d -k "$T/ed" -i "$T/big.asc" -o "$T/big.out"
check "1 MiB round trip" 'cmp -s "$T/big" "$T/big.out"'
# --- the input cap boundary --------------------------------------------------
# Built with a 64 KiB cap so the exact boundary is testable without a 1 GiB
# file. A fill of exactly the cap must work; one byte more must not.
CAP_BIN=$T/sshcrypt-cap
if ${CC:-cc} -O1 -std=c99 -D_POSIX_C_SOURCE=200809L -DSCR_INPUT_MAX=65536 \
-I src -o "$CAP_BIN" src/*.c \
$(pkg-config --libs libcrypto 2>/dev/null || echo -lcrypto) 2>/dev/null
then
head -c 65536 /dev/urandom >"$T/exact"
rc=0
"$CAP_BIN" -r "$T/ed.pub" -b -i "$T/exact" -o "$T/exact.bin" \
2>/dev/null || rc=$?
check "exactly the input cap is accepted" \
'[ "$rc" -eq 0 ] && [ -s "$T/exact.bin" ]'
head -c 65537 /dev/urandom >"$T/over"
rc=0
"$CAP_BIN" -r "$T/ed.pub" -b -i "$T/over" -o "$T/over.bin" \
2>/dev/null || rc=$?
check "one byte over the cap is rejected" '[ "$rc" -eq 2 ]'
else
printf 'skip: could not build the small-cap binary\n'
fi
printf '%d passed, %d failed\n' "$pass" "$fail"
[ "$fail" -eq 0 ]