sshcrypt: encrypt to an SSH public key, decrypt with the private key

C99/POSIX tool, one job: -r PUBKEY encrypts, -d -k PRIVKEY decrypts.
Ed25519 goes through X25519 + HKDF-SHA256 + ChaCha20-Poly1305, RSA through
RSA-OAEP-SHA256. Text armor by default so the message survives mail and chat.
OpenSSH private keys are converted through ssh-keygen; no other subprocess is
ever started.
This commit is contained in:
lotherk committed 2026-11-21 10:56:55 +00:00
commit 0afb114993
12 files changed
+2125

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
sshcrypt
src/*.o
*.o
core
+76
View File
@@ -0,0 +1,76 @@
# sshcrypt — notes for agents
One job: encrypt bytes for whoever holds an SSH keypair. `-r PUBKEY` encrypts,
`-d -k PRIVKEY` decrypts. Everything else is a non-goal on purpose: no signing,
no key discovery, no config file, no daemon, no chunked streaming. Adding one of
those is a design decision, not a commit.
## Build, test, install
make # -std=c99 -D_POSIX_C_SOURCE=200809L, links libcrypto
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: 20 end-to-end cases. It needs `ssh-keygen`, `cmp` and
`python3` (one tamper test). 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
The Makefile uses `override CFLAGS +=`, so the language flags survive any CFLAGS
you pass; do not remove that `override`.
## Layout
* `src/main.c` — CLI and mode dispatch, no crypto.
* `src/keys.c` — SSH wire parsing, public/private key loading, the ssh-keygen
conversion, Ed25519→X25519.
* `src/envelope.c` — KEM, AEAD, the wire format.
* `src/armor.c` — base64 armor.
* `src/util.c` — buffers, base64, zeroing.
* `tests/run.sh` — everything is tested through the binary, not unit tests.
## Traps that already cost time (all verified)
* `EVP_PKEY_decrypt` needs an output buffer at least as large as the RSA
modulus, even when the plaintext is 32 bytes. A 32-byte buffer fails with
`bad length` (providers/implementations/asymciphers/rsa_enc.c).
* `ssh-keygen -p -m PKCS8` only writes PKCS#8 when the **new** passphrase is
empty (`-N ''`). With a non-empty `-N` it silently keeps the OpenSSH
container. That is why the conversion always writes an unencrypted key into
the 0600 tmpfs file and unlinks it at once.
* libcrypto cannot read `-----BEGIN OPENSSH PRIVATE KEY-----` at all: no
openssh-key-v1, no bcrypt_pbkdf. Do not feed those bytes to
`PEM_read_PrivateKey`.
* `$SSH_ASKPASS` is exec'd with the prompt as `argv[1]`, so askpass mode cannot
be a command-line flag. It travels as `SSHCRYPT_ASKPASS_MODE` in the child's
environment, with the passphrase in `SSHCRYPT_ASKPASS` — never in argv.
* ssh-keygen only uses askpass when there is no controlling terminal, so the
child calls `setsid()` before `execvp`.
* 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.
* `memmem` is GNU, not POSIX. Use `find_bytes()` in `keys.c`.
* Every `.c` includes its own headers; missing `<stdio.h>` is a hard error under
`-std=c99 -Wpedantic`.
## Changing the format
The 40-byte header is AEAD additional data. Any layout change bumps
`SCR_VERSION` in `src/sshcrypt.h` and updates the table in `README.md`. Old
readers must fail closed, never guess. Keep the recipient fingerprint check
before key derivation: wrong keys must exit 3 and name both fingerprints.
## Invariants
* Exit codes are interface: 0 ok, 1 usage/I-O, 2 malformed input, 3 wrong key or
tampered message.
* Never put plaintext, key material or passphrases in argv, logs or temp files.
Prompt on `/dev/tty` with echo off. Zero secrets with `scr_secure_zero`.
* Encryption must stay subprocess-free; only OpenSSH private keys may call
`ssh-keygen`.
* Input is buffered whole, capped at 1 GiB. Do not silently raise the cap.
## Git
Remote `https://git.kropa.tech/hiddenbox/sshcrypt` (Gitea), default branch
`main`.
+83
View File
@@ -0,0 +1,83 @@
# CNCL — Could Not Care Less License
Version 1.1 (2026-11-19)
Version 1.1 adds the paragraph on military use; the grant is unchanged: 1.0 and
1.1 permit exactly the same things.
No rights reserved. No obligations imposed. Couldn't care less.
## Preamble
Software is the product of collective human knowledge.
Every idea builds upon ideas that came before. Every invention stands on the accumulated discoveries, mistakes, experiments, and imagination of generations.
We do not believe in artificial boundaries around creativity.
We do not believe that creating something grants us the moral authority to dictate what others may do with it.
We live in an age where knowledge, tools, and artificial intelligence make creation accessible to everyone. The distinction between author, user, modifier, and creator is becoming increasingly meaningless.
We are not here to control what happens next.
We are here to create.
## The License
This software is made available to the world.
Do whatever you want with it.
Use it. Copy it. Modify it. Break it. Fix it. Sell it. Give it away. Incorporate it into something else. Keep your modifications private. Publish them. Feed it to AI. Build something nobody has thought of yet.
Use it commercially or personally. Combine it with other software. Release it under another license.
You owe the original author nothing.
No attribution required. No royalties. No source disclosure. No reciprocal licensing. No contribution requirements. No permission needed.
There are no conditions attached to your use of this software.
There is no expectation that you will give anything back.
There is no expectation that you will even care.
## Military use
We have no illusions about armies, and no say over them either. If this software
ends up in a weapon, that is your business, not ours.
But since you asked: using it to defend people is not the same as using it to
attack them. Use it to protect. Do not use it to conquer.
There is nothing to enforce here either. This paragraph is the author's position,
not a term of the license: no condition, no revocation, no court. It does not add
an obligation to CNCL 1.0, and it is not a promise that the license is "ethical".
It is one sentence of opinion in a license that has no terms -- take it or leave
it, as with everything else here.
## Disclaimer
The software is provided "AS IS", without warranty of any kind.
The authors accept no responsibility for its use, misuse, modification, distribution, or consequences.
## The CNCL Principle
We acknowledge that everything we create is built upon something that existed before us.
We do not claim ownership over the collective intelligence of humanity.
We do not expect recognition, compensation, or control.
Take it. Change it. Make it better. Make it worse. Make something entirely different.
Or don't.
We Could Not Care Less.
---
CNCL — Could Not Care Less.
Created for everyone. Controlled by no one.
+32
View File
@@ -0,0 +1,32 @@
PREFIX ?= /usr/local
BINDIR ?= $(PREFIX)/bin
CC ?= cc
PKG_CONFIG ?= pkg-config
CFLAGS ?= -O2 -g
override CFLAGS += -std=c99 -D_POSIX_C_SOURCE=200809L -Wall -Wextra -Wpedantic
CPPFLAGS += $(shell $(PKG_CONFIG) --cflags libcrypto 2>/dev/null)
LDLIBS += $(shell $(PKG_CONFIG) --libs libcrypto 2>/dev/null || echo -lcrypto)
SRC = src/main.c src/util.c src/armor.c src/keys.c src/envelope.c
OBJ = $(SRC:.c=.o)
all: sshcrypt
sshcrypt: $(OBJ)
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJ) $(LDLIBS)
%.o: %.c src/sshcrypt.h
$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
check: sshcrypt
tests/run.sh
install: sshcrypt
install -d $(DESTDIR)$(BINDIR)
install -m 0755 sshcrypt $(DESTDIR)$(BINDIR)/sshcrypt
clean:
rm -f $(OBJ) sshcrypt
.PHONY: all check install clean
+112
View File
@@ -0,0 +1,112 @@
# sshcrypt
Encrypt a file, a message, or whatever comes down the pipe, for someone whose
SSH public key you already have. They decrypt it with the private key they
already use. No new identity system, no key server, no config file.
sshcrypt -r alice.pub -i report.pdf -o report.pdf.asc
# ...mail it...
sshcrypt -d -k ~/.ssh/id_ed25519 -i report.pdf.asc -o report.pdf
The output is ASCII armor, so it survives mail, chat, and copy-paste. `-b`
writes the raw binary envelope instead.
Code: https://git.kropa.tech/hiddenbox/sshcrypt
make # the binary, needs libcrypto headers
make check # end-to-end tests, no network
make install PREFIX=$HOME/.local # ~/.local/bin/sshcrypt
## The usual job
# encrypting needs only their public key
sshcrypt -r bob.pub < notes.txt > notes.txt.asc
# decrypting needs the matching private key
sshcrypt -d -k ~/.ssh/id_ed25519 < notes.txt.asc
# verify which key a message or a key file belongs to
sshcrypt -F bob.pub
sshcrypt -F ~/.ssh/id_ed25519
`-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.
Nothing is written to stdout except the payload. The one-line
`encrypted for SHA256:...` note goes to stderr, and only when stderr is a
terminal.
## Keys
* `ssh-ed25519` and `ssh-rsa` are accepted. ECDSA keys are not.
* A file with more than one supported key is rejected: put the one recipient's
key in its own file.
* Encryption never runs another program.
* Decryption reads PEM/PKCS#8 directly. An OpenSSH-format private key
(`-----BEGIN OPENSSH PRIVATE KEY-----`) is converted through `ssh-keygen`,
which therefore has to be installed. The conversion happens in a `0600`
file under `/dev/shm` (or `$TMPDIR`), and the file is unlinked immediately.
* A passphrase is asked for on `/dev/tty` with echo off, never on stdin (that
is the payload). `SSHCRYPT_PASSPHRASE` supplies it non-interactively.
## What this is not
* No signatures and no sender authentication. Anyone holding your public key
can encrypt to you; the message does not prove who sent it. Verify the
fingerprint out of band if that matters.
* No key discovery, no trust store, no revocation, no config file, no daemon.
* No forward secrecy. The envelope holds an ephemeral public key per message,
but whoever later obtains the recipient's private key can decrypt the
messages they kept.
* Not post-quantum.
* The whole input is held in memory, up to 1 GiB. There is no chunked or
streaming mode yet.
## Format
Binary envelope, version 1:
| bytes | field |
|---|---|
| 4 | `SSHC` |
| 1 | version, currently 1 |
| 1 | suite: 1 = ed25519/X25519, 2 = RSA |
| 2 | reserved, zero |
| 32 | SHA-256 of the recipient's SSH public key blob |
| 2 | KEM length, big endian |
| n | suite 1: ephemeral X25519 public key (32)<br>suite 2: 32 random bytes wrapped with RSA-OAEP-SHA256 |
| 12 | nonce |
| ... | ChaCha20-Poly1305 ciphertext, 16-byte tag at the end |
Suite 1 derives the message key with HKDF-SHA256 over the X25519 shared secret,
with the recipient fingerprint and the ephemeral public key as salt. Suite 2
derives it from the RSA-wrapped random key. The header, the KEM blob and the
nonce are authenticated as AEAD additional data, so a modified version, suite,
recipient, or ephemeral key fails the tag check.
An Ed25519 key is mapped to X25519 with the standard `u = (1+y)/(1-y)` birational
map; the private scalar is `clamp(SHA-512(seed)[0..31])`. This is the same
mapping libsodium uses, checked in `make check` against libcrypto's X25519
implementation.
Armor is base64 in 64-column lines between
`-----BEGIN SSHCRYPT MESSAGE-----` and `-----END SSHCRYPT MESSAGE-----`.
The decoder finds those markers inside surrounding text.
The fingerprint in the header is checked before any key derivation, so the
wrong key reports both fingerprints instead of a padding error:
sshcrypt: this message is for SHA256:9xQ... but your key is SHA256:2fA...
## Requirements
* C99 + POSIX.1-2008, `cc`, `make`.
* OpenSSL 3.x `libcrypto` (development headers). `pkg-config` is used when
present, `-lcrypto` otherwise.
* `ssh-keygen` at runtime, only for OpenSSH-format private keys.
Tested on Debian with OpenSSL 3.6.3 and OpenSSH 10.5p1.
## License
CNCL 1.1, the Could Not Care Less License. See `LICENSE`.
+84
View File
@@ -0,0 +1,84 @@
#include "sshcrypt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARMOR_BEGIN "-----BEGIN SSHCRYPT MESSAGE-----"
#define ARMOR_END "-----END SSHCRYPT MESSAGE-----"
#define ARMOR_WIDTH 64
static const char *find_sub(const char *hay, size_t n, const char *needle)
{
size_t nl = strlen(needle);
size_t i;
if (nl == 0 || n < nl)
return NULL;
for (i = 0; i + nl <= n; i++)
if (memcmp(hay + i, needle, nl) == 0)
return hay + i;
return NULL;
}
int scr_armor_wrap(const unsigned char *in, size_t n, char **out)
{
char *b64 = NULL;
size_t blen, lines, olen, i, o = 0;
char *s;
scr_b64_encode(in, n, &b64);
blen = strlen(b64);
lines = (blen + ARMOR_WIDTH - 1) / ARMOR_WIDTH;
olen = strlen(ARMOR_BEGIN) + 1 + blen + lines + strlen(ARMOR_END) + 2;
s = scr_xmalloc(olen);
memcpy(s + o, ARMOR_BEGIN, strlen(ARMOR_BEGIN));
o += strlen(ARMOR_BEGIN);
s[o++] = '\n';
for (i = 0; i < blen; i += ARMOR_WIDTH) {
size_t chunk = blen - i < ARMOR_WIDTH ? blen - i : ARMOR_WIDTH;
memcpy(s + o, b64 + i, chunk);
o += chunk;
s[o++] = '\n';
}
memcpy(s + o, ARMOR_END, strlen(ARMOR_END));
o += strlen(ARMOR_END);
s[o++] = '\n';
s[o] = '\0';
scr_secure_zero(b64, blen);
free(b64);
*out = s;
return 0;
}
int scr_armor_unwrap(const unsigned char *in, size_t n, struct buf *out)
{
const char *text = (const char *)in;
const char *begin, *end;
size_t bodylen;
int rc;
begin = find_sub(text, n, ARMOR_BEGIN);
if (!begin) {
fprintf(stderr,
"sshcrypt: no '%s' line found; this is not an armored message\n",
ARMOR_BEGIN);
return -1;
}
begin += strlen(ARMOR_BEGIN);
end = find_sub(begin, n - (size_t)(begin - text), ARMOR_END);
if (!end) {
fprintf(stderr, "sshcrypt: armored message is truncated (%s missing)\n",
ARMOR_END);
return -1;
}
bodylen = (size_t)(end - begin);
rc = scr_b64_decode(begin, bodylen, out);
if (rc < 0) {
fprintf(stderr, "sshcrypt: armored message is not valid base64\n");
return -1;
}
return 0;
}
+440
View File
@@ -0,0 +1,440 @@
#include "sshcrypt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/params.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>
#define MAGIC "SSHC"
#define INFO_X "sshcrypt v1 x25519 chacha20-poly1305"
#define INFO_R "sshcrypt v1 rsa-oaep-sha256 chacha20-poly1305"
static int hkdf_sha256(const unsigned char *salt, size_t saltlen,
const unsigned char *ikm, size_t ikmlen, const char *info,
unsigned char out[32])
{
EVP_KDF *kdf;
EVP_KDF_CTX *ctx;
OSSL_PARAM params[5];
int ok = -1;
kdf = EVP_KDF_fetch(NULL, "HKDF", NULL);
if (!kdf)
return -1;
ctx = EVP_KDF_CTX_new(kdf);
if (!ctx) {
EVP_KDF_free(kdf);
return -1;
}
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
(char *)"SHA256", 0);
params[1] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
(void *)ikm, ikmlen);
params[2] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
(void *)salt, saltlen);
params[3] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_INFO,
(void *)info, strlen(info));
params[4] = OSSL_PARAM_construct_end();
if (EVP_KDF_derive(ctx, out, 32, params) == 1)
ok = 0;
EVP_KDF_CTX_free(ctx);
EVP_KDF_free(kdf);
return ok;
}
static int x25519_shared(const unsigned char sk[32], const unsigned char pk[32],
unsigned char out[32])
{
EVP_PKEY *a = NULL, *b = NULL;
EVP_PKEY_CTX *ctx = NULL;
size_t len = 32;
int ok = -1;
a = EVP_PKEY_new_raw_private_key(EVP_PKEY_X25519, NULL, sk, 32);
b = EVP_PKEY_new_raw_public_key(EVP_PKEY_X25519, NULL, pk, 32);
if (!a || !b)
goto done;
ctx = EVP_PKEY_CTX_new(a, NULL);
if (!ctx)
goto done;
if (EVP_PKEY_derive_init(ctx) <= 0)
goto done;
if (EVP_PKEY_derive_set_peer(ctx, b) <= 0)
goto done;
if (EVP_PKEY_derive(ctx, out, &len) <= 0 || len != 32)
goto done;
ok = 0;
done:
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(a);
EVP_PKEY_free(b);
return ok;
}
/* returns plaintext length on success, -1 on failure */
static int aead_seal(const unsigned char key[32],
const unsigned char nonce[SCR_NONCE_LEN],
const unsigned char *aad, size_t aadlen,
const unsigned char *pt, size_t ptlen, unsigned char *out)
{
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
int n, total = 0, ok = -1;
if (!ctx)
return -1;
if (EVP_EncryptInit_ex(ctx, EVP_chacha20_poly1305(), NULL, NULL, NULL) != 1)
goto done;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, SCR_NONCE_LEN,
NULL) != 1)
goto done;
if (EVP_EncryptInit_ex(ctx, NULL, NULL, key, nonce) != 1)
goto done;
if (aadlen > 0 &&
EVP_EncryptUpdate(ctx, NULL, &n, aad, (int)aadlen) != 1)
goto done;
if (ptlen > 0 && EVP_EncryptUpdate(ctx, out, &n, pt, (int)ptlen) != 1)
goto done;
total = (int)ptlen;
if (EVP_EncryptFinal_ex(ctx, out + total, &n) != 1)
goto done;
total += n;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, SCR_TAG_LEN,
out + total) != 1)
goto done;
ok = total + SCR_TAG_LEN;
done:
EVP_CIPHER_CTX_free(ctx);
return ok;
}
static int aead_open(const unsigned char key[32],
const unsigned char nonce[SCR_NONCE_LEN],
const unsigned char *aad, size_t aadlen,
const unsigned char *ct, size_t ctlen, unsigned char *out)
{
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
int n, total = 0, ok = -1;
size_t bodylen = ctlen - SCR_TAG_LEN;
if (!ctx)
return -1;
if (EVP_DecryptInit_ex(ctx, EVP_chacha20_poly1305(), NULL, NULL, NULL) != 1)
goto done;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, SCR_NONCE_LEN,
NULL) != 1)
goto done;
if (EVP_DecryptInit_ex(ctx, NULL, NULL, key, nonce) != 1)
goto done;
if (aadlen > 0 &&
EVP_DecryptUpdate(ctx, NULL, &n, aad, (int)aadlen) != 1)
goto done;
if (bodylen > 0 &&
EVP_DecryptUpdate(ctx, out, &n, ct, (int)bodylen) != 1)
goto done;
total = (int)bodylen;
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, SCR_TAG_LEN,
(void *)(ct + bodylen)) != 1)
goto done;
if (EVP_DecryptFinal_ex(ctx, out + total, &n) != 1)
goto done;
total += n;
ok = total;
done:
EVP_CIPHER_CTX_free(ctx);
return ok;
}
static void key_id(const unsigned char *blob, size_t n, unsigned char out[32])
{
SHA256(blob, n, out);
}
static int rsa_wrap(const void *pkey, const unsigned char key[32],
unsigned char *out, size_t *outlen)
{
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new((EVP_PKEY *)pkey, NULL);
int ok = -1;
if (!ctx)
return -1;
if (EVP_PKEY_encrypt_init(ctx) <= 0)
goto done;
if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0)
goto done;
if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256()) <= 0)
goto done;
if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256()) <= 0)
goto done;
if (EVP_PKEY_encrypt(ctx, out, outlen, key, 32) <= 0)
goto done;
ok = 0;
done:
EVP_PKEY_CTX_free(ctx);
return ok;
}
static int rsa_unwrap(const void *pkey, const unsigned char *in, size_t inlen,
unsigned char key[32])
{
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new((EVP_PKEY *)pkey, NULL);
unsigned char out[1024];
/* libcrypto wants an output buffer as large as the modulus, even though
* the plaintext here is only 32 bytes: a smaller buffer is EINVAL. */
size_t len = (size_t)EVP_PKEY_get_size((EVP_PKEY *)pkey);
int ok = -1;
if (!ctx || len < 32 || len > sizeof out)
goto done;
if (EVP_PKEY_decrypt_init(ctx) <= 0)
goto done;
if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0)
goto done;
if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx, EVP_sha256()) <= 0)
goto done;
if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, EVP_sha256()) <= 0)
goto done;
if (EVP_PKEY_decrypt(ctx, out, &len, in, inlen) <= 0 || len != 32)
goto done;
memcpy(key, out, 32);
ok = 0;
done:
scr_secure_zero(out, sizeof out);
EVP_PKEY_CTX_free(ctx);
return ok;
}
int scr_encrypt(const struct scr_pub *to, const unsigned char *pt, size_t n,
struct buf *out)
{
unsigned char header[SCR_HDR_LEN];
unsigned char kid[32];
unsigned char nonce[SCR_NONCE_LEN];
unsigned char key[32];
unsigned char *kem = NULL;
size_t kemlen = 0;
size_t body;
unsigned char *env;
int rc = -1;
memset(out, 0, sizeof *out);
key_id(to->blob, to->bloblen, kid);
memset(header, 0, sizeof header);
memcpy(header, MAGIC, 4);
header[4] = SCR_VERSION;
header[5] = (unsigned char)to->suite;
memcpy(header + 8, kid, 32);
if (to->suite == SCR_SUITE_X25519) {
unsigned char esk[32], epk[32], shared[32], salt[64];
EVP_PKEY *eph;
if (RAND_bytes(esk, sizeof esk) != 1)
goto done;
eph = EVP_PKEY_new_raw_private_key(EVP_PKEY_X25519, NULL, esk,
sizeof esk);
if (!eph) {
scr_secure_zero(esk, sizeof esk);
goto done;
}
{
size_t len = sizeof epk;
if (EVP_PKEY_get_raw_public_key(eph, epk, &len) <= 0 ||
len != 32) {
EVP_PKEY_free(eph);
scr_secure_zero(esk, sizeof esk);
goto done;
}
}
EVP_PKEY_free(eph);
{
unsigned char xpk[32];
if (scr_ed25519_pk_to_x25519(to->ed, xpk) < 0 ||
x25519_shared(esk, xpk, shared) < 0) {
scr_secure_zero(esk, sizeof esk);
goto done;
}
memcpy(salt, kid, 32);
memcpy(salt + 32, epk, 32);
if (hkdf_sha256(salt, sizeof salt, shared, sizeof shared,
INFO_X, key) < 0) {
scr_secure_zero(esk, sizeof esk);
goto done;
}
scr_secure_zero(shared, sizeof shared);
scr_secure_zero(esk, sizeof esk);
}
kem = scr_xmalloc(32);
memcpy(kem, epk, 32);
kemlen = 32;
} else {
size_t wrapped = (size_t)EVP_PKEY_get_size((EVP_PKEY *)to->rsa);
unsigned char ikm[32];
if (wrapped == 0 || wrapped > 1024)
goto done;
kem = scr_xmalloc(wrapped);
kemlen = wrapped;
if (RAND_bytes(ikm, sizeof ikm) != 1 ||
rsa_wrap(to->rsa, ikm, kem, &kemlen) < 0) {
scr_secure_zero(ikm, sizeof ikm);
goto done;
}
if (hkdf_sha256(kid, 32, ikm, sizeof ikm, INFO_R, key) < 0) {
scr_secure_zero(ikm, sizeof ikm);
goto done;
}
scr_secure_zero(ikm, sizeof ikm);
}
if (RAND_bytes(nonce, sizeof nonce) != 1)
goto done;
body = SCR_HDR_LEN + 2 + kemlen + SCR_NONCE_LEN;
if (n > SCR_INPUT_MAX - body)
goto done;
env = scr_xmalloc(body + n + SCR_TAG_LEN);
memcpy(env, header, SCR_HDR_LEN);
env[SCR_HDR_LEN] = (unsigned char)(kemlen >> 8);
env[SCR_HDR_LEN + 1] = (unsigned char)(kemlen & 0xff);
memcpy(env + SCR_HDR_LEN + 2, kem, kemlen);
memcpy(env + SCR_HDR_LEN + 2 + kemlen, nonce, SCR_NONCE_LEN);
if (aead_seal(key, nonce, env, body, pt, n, env + body) < 0) {
free(env);
goto done;
}
out->data = env;
out->len = body + n + SCR_TAG_LEN;
rc = 0;
done:
scr_secure_zero(key, sizeof key);
if (kem)
free(kem);
return rc;
}
int scr_decrypt(const struct scr_priv *me, const unsigned char *env, size_t n,
struct buf *out)
{
unsigned char kid[32], key[32];
unsigned char nonce[SCR_NONCE_LEN];
const unsigned char *kem;
size_t kemlen, body, ctlen;
int suite;
memset(out, 0, sizeof *out);
if (n < SCR_HDR_LEN + 2 + SCR_NONCE_LEN + SCR_TAG_LEN) {
fprintf(stderr, "sshcrypt: message is too short to be valid\n");
return SCR_EDATA;
}
if (memcmp(env, MAGIC, 4) != 0) {
fprintf(stderr, "sshcrypt: bad magic; not an sshcrypt message\n");
return SCR_EDATA;
}
if (env[4] != SCR_VERSION) {
fprintf(stderr, "sshcrypt: unsupported version %u\n", env[4]);
return SCR_EDATA;
}
suite = env[5];
if (suite != SCR_SUITE_X25519 && suite != SCR_SUITE_RSA) {
fprintf(stderr, "sshcrypt: unsupported key type %d\n", suite);
return SCR_EDATA;
}
kemlen = ((size_t)env[SCR_HDR_LEN] << 8) | env[SCR_HDR_LEN + 1];
body = SCR_HDR_LEN + 2 + kemlen + SCR_NONCE_LEN;
if (kemlen == 0 || body + SCR_TAG_LEN > n) {
fprintf(stderr, "sshcrypt: truncated message\n");
return SCR_EDATA;
}
kem = env + SCR_HDR_LEN + 2;
memcpy(nonce, env + SCR_HDR_LEN + 2 + kemlen, SCR_NONCE_LEN);
ctlen = n - body;
key_id(me->blob, me->bloblen, kid);
if (CRYPTO_memcmp(env + 8, kid, 32) != 0) {
char stored[64] = "SHA256:";
char *b64 = NULL;
size_t i, j = 7;
scr_b64_encode(env + 8, 32, &b64);
for (i = 0; b64[i] && b64[i] != '=' && j < 63; i++)
stored[j++] = b64[i];
stored[j] = '\0';
free(b64);
fprintf(stderr,
"sshcrypt: this message is for %s, but your key is %s\n",
stored, me->fingerprint);
return SCR_EAUTH;
}
if (suite == SCR_SUITE_X25519) {
unsigned char xpk[32], shared[32], salt[64];
if (me->suite != SCR_SUITE_X25519) {
fprintf(stderr,
"sshcrypt: message needs an ed25519 key, yours is RSA\n");
return SCR_EAUTH;
}
if (kemlen != 32 || scr_ed25519_pk_to_x25519(me->ed_pub, xpk) < 0 ||
x25519_shared(me->ed_scalar, kem, shared) < 0) {
fprintf(stderr, "sshcrypt: malformed message\n");
return SCR_EDATA;
}
memcpy(salt, kid, 32);
memcpy(salt + 32, kem, 32);
if (hkdf_sha256(salt, sizeof salt, shared, sizeof shared, INFO_X,
key) < 0) {
scr_secure_zero(shared, sizeof shared);
return SCR_EDATA;
}
scr_secure_zero(shared, sizeof shared);
} else {
if (me->suite != SCR_SUITE_RSA) {
fprintf(stderr,
"sshcrypt: message needs an RSA key, yours is ed25519\n");
return SCR_EAUTH;
}
{
unsigned char ikm[32];
if (rsa_unwrap(me->rsa, kem, kemlen, ikm) < 0) {
scr_secure_zero(ikm, sizeof ikm);
fprintf(stderr, "sshcrypt: cannot unwrap the message key\n");
return SCR_EAUTH;
}
if (hkdf_sha256(kid, 32, ikm, sizeof ikm, INFO_R, key) < 0) {
scr_secure_zero(ikm, sizeof ikm);
return SCR_EDATA;
}
scr_secure_zero(ikm, sizeof ikm);
}
}
out->data = scr_xmalloc(ctlen ? ctlen : 1);
{
int plen = aead_open(key, nonce, env, body, env + body, ctlen,
out->data);
scr_secure_zero(key, sizeof key);
if (plen < 0) {
free(out->data);
out->data = NULL;
fprintf(stderr,
"sshcrypt: decryption failed: wrong key or the "
"message was modified\n");
return SCR_EAUTH;
}
out->len = (size_t)plen;
}
return SCR_OK;
}
+661
View File
@@ -0,0 +1,661 @@
#include "sshcrypt.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include <openssl/bn.h>
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/param_build.h>
#include <openssl/pem.h>
#include <openssl/sha.h>
extern char *scr_self_exe;
static char *g_pass;
static const char *g_pass_path;
static const char *passphrase_env(void)
{
const char *p = getenv("SSHCRYPT_PASSPHRASE");
return p && *p ? p : NULL;
}
/* Read a line from /dev/tty with echo off. Never from stdin: that is data. */
static char *prompt_passphrase(const char *path)
{
struct termios old, noecho;
char *line = NULL;
size_t cap = 0;
ssize_t n;
FILE *tty;
int fd = open("/dev/tty", O_RDWR);
if (fd < 0)
return NULL;
if (tcgetattr(fd, &old) == 0) {
noecho = old;
noecho.c_lflag &= ~(tcflag_t)ECHO;
tcsetattr(fd, TCSAFLUSH, &noecho);
}
fprintf(stderr, "passphrase for %s: ", path);
fflush(stderr);
tty = fdopen(fd, "r");
if (!tty) {
close(fd);
return NULL;
}
n = getline(&line, &cap, tty);
fputc('\n', stderr);
if (tcgetattr(fd, &old) == 0)
tcsetattr(fd, TCSAFLUSH, &old);
fclose(tty);
if (n <= 0) {
free(line);
return NULL;
}
if (line[n - 1] == '\n')
line[n - 1] = '\0';
return line;
}
static char *get_passphrase(const char *path)
{
const char *env = passphrase_env();
char *pw;
if (env)
return scr_xstrdup(env);
pw = prompt_passphrase(path);
if (!pw)
scr_die(SCR_EIO,
"no passphrase: cannot read /dev/tty and "
"SSHCRYPT_PASSPHRASE is unset");
return pw;
}
static int pass_cb(char *buf, int size, int rwflag, void *u)
{
size_t n;
(void)rwflag;
(void)u;
if (!g_pass)
g_pass = get_passphrase(g_pass_path ? g_pass_path : "private key");
n = strlen(g_pass);
if (n > (size_t)size)
return -1;
memcpy(buf, g_pass, n);
return (int)n;
}
/* ---------------- ssh wire encoding ---------------- */
static int rd_u32(const unsigned char **p, size_t *left, unsigned long *v)
{
if (*left < 4)
return -1;
*v = ((unsigned long)(*p)[0] << 24) | ((unsigned long)(*p)[1] << 16) |
((unsigned long)(*p)[2] << 8) | (unsigned long)(*p)[3];
*p += 4;
*left -= 4;
return 0;
}
static int rd_string(const unsigned char **p, size_t *left,
const unsigned char **s, size_t *len)
{
unsigned long l;
if (rd_u32(p, left, &l) < 0 || l > *left)
return -1;
*s = *p;
*len = l;
*p += l;
*left -= l;
return 0;
}
static int put_u32(unsigned char *p, size_t v)
{
p[0] = (unsigned char)(v >> 24);
p[1] = (unsigned char)(v >> 16);
p[2] = (unsigned char)(v >> 8);
p[3] = (unsigned char)v;
return 4;
}
static int put_string(unsigned char *p, const unsigned char *s, size_t n)
{
put_u32(p, n);
memcpy(p + 4, s, n);
return (int)n + 4;
}
static int put_mpint(unsigned char *p, const unsigned char *b, size_t n)
{
size_t len;
while (n > 0 && *b == 0) {
b++;
n--;
}
len = n == 0 ? 0 : ((b[0] & 0x80) ? n + 1 : n);
put_u32(p, len);
if (len == n) {
memcpy(p + 4, b, n);
} else if (len == n + 1) {
p[4] = 0;
memcpy(p + 5, b, n);
}
return (int)len + 4;
}
static int rsa_pub_blob(const BIGNUM *e, const BIGNUM *n, unsigned char *out,
size_t max, size_t *outlen)
{
int elen = BN_num_bytes(e), nlen = BN_num_bytes(n);
unsigned char *eb, *nb;
size_t o = 0;
int rc = -1;
if (elen <= 0 || nlen <= 0)
return -1;
eb = scr_xmalloc((size_t)elen);
nb = scr_xmalloc((size_t)nlen);
if (BN_bn2bin(e, eb) != elen || BN_bn2bin(n, nb) != nlen)
goto done;
if (4u + 7u + 4u + (size_t)elen + 4u + (size_t)nlen + 2u > max)
goto done;
o += (size_t)put_string(out + o, (const unsigned char *)"ssh-rsa", 7);
o += (size_t)put_mpint(out + o, eb, (size_t)elen);
o += (size_t)put_mpint(out + o, nb, (size_t)nlen);
*outlen = o;
rc = 0;
done:
scr_secure_zero(eb, (size_t)elen);
scr_secure_zero(nb, (size_t)nlen);
free(eb);
free(nb);
return rc;
}
void scr_fingerprint(const unsigned char *blob, size_t n, char out[64])
{
unsigned char md[SHA256_DIGEST_LENGTH];
char *b64 = NULL;
size_t i, j = 0;
SHA256(blob, n, md);
scr_b64_encode(md, sizeof md, &b64);
memcpy(out, "SHA256:", 7);
j = 7;
for (i = 0; b64[i] && b64[i] != '=' && j < 63; i++)
out[j++] = b64[i];
out[j] = '\0';
free(b64);
}
int scr_ed25519_pk_to_x25519(const unsigned char ed[32], unsigned char out[32])
{
BN_CTX *ctx = BN_CTX_new();
BIGNUM *p = NULL, *y = NULL, *one = NULL, *num = NULL, *den = NULL;
BIGNUM *inv = NULL, *u = NULL;
unsigned char tmp[32];
int ok = 0;
if (!ctx)
return -1;
memcpy(tmp, ed, 32);
tmp[31] &= 0x7f; /* the curve point's sign bit does not enter the map */
p = BN_new();
one = BN_new();
num = BN_new();
den = BN_new();
inv = BN_new();
u = BN_new();
y = BN_lebin2bn(tmp, 32, NULL);
if (!p || !one || !num || !den || !inv || !u || !y)
goto done;
if (!BN_one(one) || !BN_lshift(p, one, 255) || !BN_sub_word(p, 19))
goto done;
if (!BN_mod_add(num, one, y, p, ctx))
goto done;
if (!BN_mod_sub(den, one, y, p, ctx))
goto done;
if (!BN_mod_inverse(inv, den, p, ctx))
goto done;
if (!BN_mod_mul(u, num, inv, p, ctx))
goto done;
if (BN_bn2lebinpad(u, out, 32) != 32)
goto done;
ok = 1;
done:
BN_free(p);
BN_free(y);
BN_free(one);
BN_free(num);
BN_free(den);
BN_free(inv);
BN_free(u);
BN_CTX_free(ctx);
return ok ? 0 : -1;
}
/* ---------------- public keys ---------------- */
/* memmem is a GNU extension; keep the build on plain POSIX. */
static const void *find_bytes(const void *hay, size_t n, const char *needle,
size_t nl)
{
const unsigned char *h = hay;
size_t i;
if (nl == 0 || n < nl)
return NULL;
for (i = 0; i + nl <= n; i++)
if (memcmp(h + i, needle, nl) == 0)
return h + i;
return NULL;
}
static int is_private_blob(const struct buf *b, size_t limit)
{
size_t n = b->len < limit ? b->len : limit;
return find_bytes(b->data, n, "PRIVATE KEY-----", 16) != NULL;
}
static int rsa_from_mpints(const unsigned char *eb, size_t el,
const unsigned char *nb, size_t nl, EVP_PKEY **out)
{
BIGNUM *e = BN_bin2bn(eb, (int)el, NULL);
BIGNUM *n = BN_bin2bn(nb, (int)nl, NULL);
EVP_PKEY_CTX *ctx = NULL;
OSSL_PARAM_BLD *bld = NULL;
OSSL_PARAM *params = NULL;
EVP_PKEY *pkey = NULL;
int rc = -1;
if (!e || !n)
goto done;
ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL);
bld = OSSL_PARAM_BLD_new();
if (!ctx || !bld)
goto done;
if (!OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_N, n) ||
!OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_RSA_E, e))
goto done;
params = OSSL_PARAM_BLD_to_param(bld);
if (!params || EVP_PKEY_fromdata_init(ctx) <= 0)
goto done;
if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_PUBLIC_KEY, params) <= 0)
goto done;
*out = pkey;
pkey = NULL;
rc = 0;
done:
EVP_PKEY_free(pkey);
OSSL_PARAM_free(params);
OSSL_PARAM_BLD_free(bld);
EVP_PKEY_CTX_free(ctx);
BN_free(e);
BN_free(n);
return rc;
}
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;
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;
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);
}
p = eol ? eol + 1 : NULL;
}
if (!found) {
fprintf(stderr,
"sshcrypt: %s: no ssh-ed25519 or ssh-rsa public key found\n",
label);
return -1;
}
{
const unsigned char *q = blob, *type, *key;
size_t left = bloblen, typelen, keylen;
if (rd_string(&q, &left, &type, &typelen) < 0 ||
typelen != strlen(foundtype) ||
memcmp(type, foundtype, typelen) != 0 ||
rd_string(&q, &left, &key, &keylen) < 0) {
fprintf(stderr, "sshcrypt: %s: malformed key blob\n", label);
return -1;
}
if (strcmp(foundtype, "ssh-ed25519") == 0) {
if (keylen != 32) {
fprintf(stderr, "sshcrypt: %s: bad ed25519 key\n",
label);
return -1;
}
out->suite = SCR_SUITE_X25519;
memcpy(out->ed, key, 32);
} else {
const unsigned char *r = blob, *dummy, *eb, *nb;
size_t rl = bloblen, dl, el, nl;
EVP_PKEY *pkey = NULL;
if (rd_string(&r, &rl, &dummy, &dl) < 0 ||
rd_string(&r, &rl, &eb, &el) < 0 ||
rd_string(&r, &rl, &nb, &nl) < 0 ||
rsa_from_mpints(eb, el, nb, nl, &pkey) < 0) {
fprintf(stderr, "sshcrypt: %s: bad RSA key\n", label);
return -1;
}
out->suite = SCR_SUITE_RSA;
out->rsa = pkey;
}
}
memcpy(out->blob, blob, bloblen);
out->bloblen = bloblen;
scr_fingerprint(out->blob, out->bloblen, out->fingerprint);
return 0;
}
int scr_pub_load(const char *path, struct scr_pub *out)
{
struct buf b = scr_read_file(path, 4 * 1024 * 1024);
int rc;
if (is_private_blob(&b, 8192)) {
scr_die(SCR_EUSAGE,
"%s is a private key; pass the recipient's public key "
"(usually %s.pub)", path, path);
}
rc = parse_pub_text((const char *)b.data, b.len, path, out);
free(b.data);
return rc;
}
int scr_pub_load_any(const char *path, struct scr_pub *out)
{
struct buf b = scr_read_file(path, 4 * 1024 * 1024);
int priv;
priv = is_private_blob(&b, 8192);
free(b.data);
if (!priv)
return scr_pub_load(path, out);
{
struct scr_priv k;
if (scr_priv_load(path, &k) < 0)
return -1;
memset(out, 0, sizeof *out);
out->suite = k.suite;
out->bloblen = k.bloblen;
memcpy(out->blob, k.blob, k.bloblen);
memcpy(out->ed, k.ed_pub, 32);
memcpy(out->fingerprint, k.fingerprint, sizeof out->fingerprint);
if (k.rsa) {
EVP_PKEY_up_ref((EVP_PKEY *)k.rsa);
out->rsa = k.rsa;
}
scr_priv_free(&k);
}
return 0;
}
void scr_pub_free(struct scr_pub *k)
{
if (k->rsa)
EVP_PKEY_free((EVP_PKEY *)k->rsa);
memset(k, 0, sizeof *k);
}
/* ---------------- private keys ---------------- */
static int run_ssh_keygen(const char *path, const char *pass)
{
pid_t pid;
int status = -1;
char ap[64];
const char *prog = scr_self_exe;
if (!prog) {
snprintf(ap, sizeof ap, "/proc/%ld/exe", (long)getpid());
prog = ap;
}
pid = fork();
if (pid < 0)
return -1;
if (pid == 0) {
int fd;
char *const argv[] = {
(char *)"ssh-keygen", (char *)"-p", (char *)"-m",
(char *)"PKCS8", (char *)"-N", (char *)"", (char *)"-f",
(char *)path, NULL
};
setsid();
setenv("SSH_ASKPASS", prog, 1);
setenv("SSH_ASKPASS_REQUIRE", "force", 1);
setenv("SSHCRYPT_ASKPASS_MODE", "1", 1);
setenv("SSHCRYPT_ASKPASS", pass ? pass : "", 1);
fd = open("/dev/null", O_RDWR);
if (fd >= 0) {
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO)
close(fd);
}
execvp("ssh-keygen", argv);
_exit(127);
}
if (waitpid(pid, &status, 0) < 0)
return -1;
return WIFEXITED(status) && WEXITSTATUS(status) == 0 ? 0 : -1;
}
/* Convert an OpenSSH-container key to unencrypted PKCS#8 in a 0600 temp file.
* Returns the path; the caller must unlink it. */
static char *convert_openssh_key(const char *path, const struct buf *raw)
{
const char *t = getenv("TMPDIR");
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);
const char *env = passphrase_env();
int fd;
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);
if (!env && run_ssh_keygen(tmp, "") == 0)
return tmp;
{
char *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: ssh-keygen could not convert this key "
"(wrong passphrase?)", path);
}
scr_secure_zero(pw, strlen(pw));
free(pw);
}
return tmp;
}
int scr_priv_load(const char *path, struct scr_priv *out)
{
struct buf b = scr_read_file(path, 4 * 1024 * 1024);
char *tmp = NULL;
EVP_PKEY *pkey;
FILE *f;
const char *readpath;
memset(out, 0, sizeof *out);
if (!is_private_blob(&b, 8192))
scr_die(SCR_EUSAGE,
"%s does not look like a PEM or OpenSSH private key", path);
if (find_bytes(b.data, b.len < 8192 ? b.len : 8192,
"BEGIN OPENSSH PRIVATE KEY", 25))
tmp = convert_openssh_key(path, &b);
readpath = tmp ? tmp : path;
g_pass = NULL;
g_pass_path = path;
f = fopen(readpath, "r");
if (!f)
scr_die(SCR_EIO, "%s: %s", readpath, strerror(errno));
pkey = PEM_read_PrivateKey(f, NULL, pass_cb, NULL);
fclose(f);
if (g_pass) {
scr_secure_zero(g_pass, strlen(g_pass));
free(g_pass);
g_pass = NULL;
}
if (tmp) {
unlink(tmp);
free(tmp);
}
if (!pkey)
scr_die(SCR_EUSAGE, "%s: cannot read the private key "
"(wrong passphrase?)", path);
if (EVP_PKEY_is_a(pkey, "ED25519")) {
unsigned char seed[32], pub[32], h[SHA512_DIGEST_LENGTH];
size_t len = sizeof seed;
if (EVP_PKEY_get_raw_private_key(pkey, seed, &len) <= 0 ||
len != 32)
scr_die(SCR_EUSAGE, "%s: unsupported ed25519 key", path);
len = sizeof pub;
if (EVP_PKEY_get_raw_public_key(pkey, pub, &len) <= 0 || len != 32)
scr_die(SCR_EUSAGE, "%s: cannot read the ed25519 public "
"part", path);
SHA512(seed, sizeof seed, h);
memcpy(out->ed_scalar, h, 32);
out->ed_scalar[0] &= 248;
out->ed_scalar[31] &= 127;
out->ed_scalar[31] |= 64;
memcpy(out->ed_pub, pub, 32);
out->suite = SCR_SUITE_X25519;
out->bloblen = (size_t)put_string(out->blob,
(const unsigned char *)"ssh-ed25519", 11);
out->bloblen += (size_t)put_string(out->blob + out->bloblen, pub, 32);
scr_secure_zero(seed, sizeof seed);
scr_secure_zero(h, sizeof h);
} else if (EVP_PKEY_is_a(pkey, "RSA")) {
BIGNUM *e = NULL, *n = NULL;
if (!EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_E, &e) ||
!EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_N, &n) ||
rsa_pub_blob(e, n, out->blob, sizeof out->blob,
&out->bloblen) < 0)
scr_die(SCR_EUSAGE, "%s: cannot read the RSA public part",
path);
out->suite = SCR_SUITE_RSA;
out->rsa = pkey;
BN_free(e);
BN_free(n);
pkey = NULL;
} else {
scr_die(SCR_EUSAGE, "%s: unsupported key type (need ed25519 or "
"RSA)", path);
}
EVP_PKEY_free(pkey);
scr_secure_zero(b.data, b.len);
free(b.data);
scr_fingerprint(out->blob, out->bloblen, out->fingerprint);
return 0;
}
void scr_priv_free(struct scr_priv *k)
{
if (k->rsa)
EVP_PKEY_free((EVP_PKEY *)k->rsa);
scr_secure_zero(k, sizeof *k);
}
+240
View File
@@ -0,0 +1,240 @@
#include "sshcrypt.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *scr_self_exe = NULL;
static void usage(FILE *f)
{
fputs(
"usage: sshcrypt -r PUBKEY [-i IN] [-o OUT] [-b] encrypt (the default)\n"
" sshcrypt -d -k PRIVKEY [-i IN] [-o OUT] decrypt\n"
" sshcrypt -F KEY print a key's fingerprint\n"
"\n"
" -e, --encrypt encrypt (default)\n"
" -d, --decrypt decrypt\n"
" -r, --recipient FILE the recipient's public key (or their private key)\n"
" -k, --key FILE your private key, for -d\n"
" -i, --input FILE input file, - or absent means stdin\n"
" -o, --output FILE output file, absent means stdout\n"
" -b, --binary write the raw envelope, without the text armor\n"
" -q, --quiet no progress line on stderr\n"
" -F, --fingerprint KEY print SHA256:... for a key and exit\n"
" -h, --help this text\n"
" -V, --version version\n"
"\n"
"Encrypting needs only the recipient's public key. Decrypting needs their\n"
"private key; OpenSSH-format keys are converted through ssh-keygen, which must\n"
"be installed. A passphrase is asked on /dev/tty, or taken from\n"
"SSHCRYPT_PASSPHRASE.\n", f);
}
static void version(void)
{
printf("sshcrypt %s\n", "0.1.0");
}
static const char *need_arg(int argc, char **argv, int *i, const char *opt)
{
if (*i + 1 >= argc)
scr_die(SCR_EUSAGE, "%s needs an argument", opt);
return argv[++*i];
}
int main(int argc, char **argv)
{
int encrypt = 1, decrypt = 0, fingerprint = 0, binary = 0, quiet = 0;
const char *recipient = NULL, *key = NULL, *input = NULL, *output = NULL;
int i;
if (getenv("SSHCRYPT_ASKPASS_MODE")) {
/* internal: ssh-keygen runs us through $SSH_ASKPASS and passes the
* prompt as an argument, so the mode travels in the environment */
const char *p = getenv("SSHCRYPT_ASKPASS");
printf("%s\n", p ? p : "");
return 0;
}
for (i = 1; i < argc; i++) {
const char *a = argv[i];
if (strcmp(a, "--askpass") == 0) {
/* internal: ssh-keygen calls us back for the passphrase */
const char *p = getenv("SSHCRYPT_ASKPASS");
printf("%s\n", p ? p : "");
return 0;
}
if (strcmp(a, "-e") == 0 || strcmp(a, "--encrypt") == 0) {
encrypt = 1;
decrypt = 0;
} else if (strcmp(a, "-d") == 0 || strcmp(a, "--decrypt") == 0) {
decrypt = 1;
encrypt = 0;
} else if (strcmp(a, "-r") == 0 || strcmp(a, "--recipient") == 0) {
recipient = need_arg(argc, argv, &i, a);
} else if (strncmp(a, "--recipient=", 12) == 0) {
recipient = a + 12;
} else if (strcmp(a, "-k") == 0 || strcmp(a, "--key") == 0) {
key = need_arg(argc, argv, &i, a);
} else if (strncmp(a, "--key=", 6) == 0) {
key = a + 6;
} else if (strcmp(a, "-i") == 0 || strcmp(a, "--input") == 0) {
input = need_arg(argc, argv, &i, a);
} else if (strncmp(a, "--input=", 8) == 0) {
input = a + 8;
} else if (strcmp(a, "-o") == 0 || strcmp(a, "--output") == 0) {
output = need_arg(argc, argv, &i, a);
} else if (strncmp(a, "--output=", 9) == 0) {
output = a + 9;
} else if (strcmp(a, "-b") == 0 || strcmp(a, "--binary") == 0) {
binary = 1;
} else if (strcmp(a, "-q") == 0 || strcmp(a, "--quiet") == 0) {
quiet = 1;
} else if (strcmp(a, "-F") == 0 ||
strcmp(a, "--fingerprint") == 0) {
fingerprint = 1;
recipient = need_arg(argc, argv, &i, a);
} else if (strncmp(a, "--fingerprint=", 14) == 0) {
fingerprint = 1;
recipient = a + 14;
} else if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) {
usage(stdout);
return 0;
} else if (strcmp(a, "-V") == 0 || strcmp(a, "--version") == 0) {
version();
return 0;
} else if (strcmp(a, "--") == 0) {
if (i + 1 < argc)
scr_die(SCR_EUSAGE, "unexpected argument: %s",
argv[i + 1]);
break;
} else {
scr_die(SCR_EUSAGE, "unknown option: %s (try -h)", a);
}
}
{
char buf[4096];
ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1);
if (n > 0) {
buf[n] = '\0';
scr_self_exe = scr_xstrdup(buf);
} else if (argv[0] && strchr(argv[0], '/')) {
scr_self_exe = scr_xstrdup(argv[0]);
}
}
if (fingerprint) {
struct scr_pub k;
if (!recipient && !key)
scr_die(SCR_EUSAGE, "-F needs a key: -r FILE");
if (scr_pub_load_any(recipient ? recipient : key, &k) < 0)
return SCR_EUSAGE;
printf("%s\n", k.fingerprint);
scr_pub_free(&k);
return 0;
}
if (decrypt) {
struct scr_priv me;
struct buf in, plain, armored = { NULL, 0 };
int rc, fd = STDOUT_FILENO;
const unsigned char *env = NULL;
size_t envlen = 0;
if (!key)
scr_die(SCR_EUSAGE, "-d needs your private key: -k FILE");
in = scr_read_file(input ? input : "-", SCR_INPUT_MAX);
if (scr_priv_load(key, &me) < 0)
return SCR_EUSAGE;
if (in.len >= 4 && memcmp(in.data, "SSHC", 4) == 0) {
env = in.data;
envlen = in.len;
} else {
if (scr_armor_unwrap(in.data, in.len, &armored) < 0) {
free(in.data);
return SCR_EDATA;
}
env = armored.data;
envlen = armored.len;
}
rc = scr_decrypt(&me, env, envlen, &plain);
if (rc != SCR_OK) {
scr_priv_free(&me);
free(armored.data);
memset(in.data, 0, in.len);
free(in.data);
return rc;
}
if (output) {
fd = open(output, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0)
scr_die(SCR_EIO, "%s: %s", output,
strerror(errno));
}
scr_write_fd(fd, plain.data, plain.len);
if (output)
close(fd);
scr_secure_zero(plain.data, plain.len);
free(plain.data);
scr_priv_free(&me);
free(armored.data);
memset(in.data, 0, in.len);
free(in.data);
return rc;
}
(void)encrypt;
{
struct scr_pub to;
struct buf in, env;
int fd = STDOUT_FILENO;
if (!recipient)
scr_die(SCR_EUSAGE, "encrypting needs the recipient's "
"public key: -r FILE");
if (scr_pub_load_any(recipient, &to) < 0)
return SCR_EUSAGE;
in = scr_read_file(input ? input : "-", SCR_INPUT_MAX);
if (scr_encrypt(&to, in.data, in.len, &env) < 0)
scr_die(SCR_EIO, "encryption failed");
if (!quiet && isatty(STDERR_FILENO))
fprintf(stderr, "sshcrypt: encrypted for %s (%s)\n",
to.fingerprint,
to.suite == SCR_SUITE_X25519 ? "ssh-ed25519" :
"ssh-rsa");
if (output) {
fd = open(output, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0)
scr_die(SCR_EIO, "%s: %s", output,
strerror(errno));
}
if (binary) {
scr_write_fd(fd, env.data, env.len);
} else {
char *armor = NULL;
scr_armor_wrap(env.data, env.len, &armor);
scr_write_fd(fd, armor, strlen(armor));
scr_secure_zero(armor, strlen(armor));
free(armor);
}
if (output)
close(fd);
scr_secure_zero(env.data, env.len);
free(env.data);
memset(in.data, 0, in.len);
free(in.data);
scr_pub_free(&to);
}
return 0;
}
+78
View File
@@ -0,0 +1,78 @@
#ifndef SSHCRYPT_H
#define SSHCRYPT_H
#include <stddef.h>
#define SCR_VERSION 1
#define SCR_SUITE_X25519 1
#define SCR_SUITE_RSA 2
#define SCR_FP_LEN 32
#define SCR_NONCE_LEN 12
#define SCR_TAG_LEN 16
#define SCR_HDR_LEN 40 /* magic4 version1 suite1 reserved2 fingerprint32 */
#define SCR_PUB_MAX 4096
#define SCR_INPUT_MAX (1024u * 1024u * 1024u)
#define SCR_OK 0
#define SCR_EUSAGE 1
#define SCR_EIO 1
#define SCR_EDATA 2
#define SCR_EAUTH 3
struct buf {
unsigned char *data;
size_t len;
};
/* util.c */
void scr_die(int code, const char *fmt, ...);
void *scr_xmalloc(size_t n);
void *scr_xrealloc(void *p, size_t n);
char *scr_xstrdup(const char *s);
void scr_secure_zero(void *p, size_t n);
struct buf scr_read_fd(int fd, size_t max, const char *what);
struct buf scr_read_file(const char *path, size_t max);
void scr_write_fd(int fd, const void *p, size_t n);
int scr_b64_encode(const unsigned char *in, size_t n, char **out);
int scr_b64_decode(const char *in, size_t n, struct buf *out);
/* armor.c */
int scr_armor_wrap(const unsigned char *in, size_t n, char **out);
int scr_armor_unwrap(const unsigned char *in, size_t n, struct buf *out);
/* keys.c */
struct scr_pub {
int suite;
unsigned char blob[SCR_PUB_MAX];
size_t bloblen;
unsigned char ed[32];
void *rsa; /* EVP_PKEY * */
char fingerprint[64];
};
struct scr_priv {
int suite;
unsigned char ed_scalar[32]; /* x25519 scalar from the ed25519 seed */
unsigned char ed_pub[32];
void *rsa; /* EVP_PKEY * */
unsigned char blob[SCR_PUB_MAX];
size_t bloblen;
char fingerprint[64];
};
int scr_pub_load(const char *path, struct scr_pub *out);
int scr_pub_load_any(const char *path, struct scr_pub *out);
void scr_pub_free(struct scr_pub *k);
int scr_priv_load(const char *path, struct scr_priv *out);
void scr_priv_free(struct scr_priv *k);
void scr_fingerprint(const unsigned char *blob, size_t n, char out[64]);
int scr_ed25519_pk_to_x25519(const unsigned char ed[32], unsigned char out[32]);
/* envelope.c */
int scr_encrypt(const struct scr_pub *to, const unsigned char *pt, size_t n,
struct buf *out);
int scr_decrypt(const struct scr_priv *me, const unsigned char *env, size_t n,
struct buf *out);
#endif
+198
View File
@@ -0,0 +1,198 @@
#include "sshcrypt.h"
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void scr_die(int code, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fputs("sshcrypt: ", stderr);
vfprintf(stderr, fmt, ap);
fputc('\n', stderr);
va_end(ap);
exit(code);
}
void *scr_xmalloc(size_t n)
{
void *p = malloc(n ? n : 1);
if (!p)
scr_die(SCR_EIO, "out of memory (%zu bytes)", n);
return p;
}
void *scr_xrealloc(void *p, size_t n)
{
void *q = realloc(p, n ? n : 1);
if (!q)
scr_die(SCR_EIO, "out of memory (%zu bytes)", n);
return q;
}
char *scr_xstrdup(const char *s)
{
size_t n = strlen(s) + 1;
char *p = scr_xmalloc(n);
memcpy(p, s, n);
return p;
}
void scr_secure_zero(void *p, size_t n)
{
volatile unsigned char *v = (volatile unsigned char *)p;
while (n--)
*v++ = 0;
}
struct buf scr_read_fd(int fd, size_t max, const char *what)
{
struct buf b;
size_t cap = 64 * 1024;
b.data = scr_xmalloc(cap);
b.len = 0;
for (;;) {
ssize_t r;
if (b.len == cap) {
if (cap >= max)
scr_die(SCR_EDATA,
"%s: larger than the %zu byte limit",
what, max);
cap *= 2;
if (cap > max)
cap = max;
b.data = scr_xrealloc(b.data, cap);
}
r = read(fd, b.data + b.len, cap - b.len);
if (r < 0) {
if (errno == EINTR)
continue;
scr_die(SCR_EIO, "%s: %s", what, strerror(errno));
}
if (r == 0)
break;
b.len += (size_t)r;
}
return b;
}
struct buf scr_read_file(const char *path, size_t max)
{
struct buf b;
int fd;
if (strcmp(path, "-") == 0)
return scr_read_fd(STDIN_FILENO, max, "stdin");
fd = open(path, O_RDONLY);
if (fd < 0)
scr_die(SCR_EIO, "%s: %s", path, strerror(errno));
b = scr_read_fd(fd, max, path);
close(fd);
return b;
}
void scr_write_fd(int fd, const void *p, size_t n)
{
const unsigned char *q = p;
while (n > 0) {
ssize_t w = write(fd, q, n);
if (w < 0) {
if (errno == EINTR)
continue;
scr_die(SCR_EIO, "write: %s", strerror(errno));
}
q += w;
n -= (size_t)w;
}
}
static const char b64tab[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int scr_b64_encode(const unsigned char *in, size_t n, char **out)
{
size_t olen = 4 * ((n + 2) / 3);
char *s = scr_xmalloc(olen + 1);
size_t i, o = 0;
for (i = 0; i + 2 < n; i += 3) {
s[o++] = b64tab[in[i] >> 2];
s[o++] = b64tab[((in[i] & 3) << 4) | (in[i + 1] >> 4)];
s[o++] = b64tab[((in[i + 1] & 15) << 2) | (in[i + 2] >> 6)];
s[o++] = b64tab[in[i + 2] & 63];
}
if (i < n) {
s[o++] = b64tab[in[i] >> 2];
if (i + 1 < n) {
s[o++] = b64tab[((in[i] & 3) << 4) | (in[i + 1] >> 4)];
s[o++] = b64tab[(in[i + 1] & 15) << 2];
} else {
s[o++] = b64tab[(in[i] & 3) << 4];
s[o++] = '=';
}
s[o++] = '=';
}
s[o] = '\0';
*out = s;
return 0;
}
static int b64val(int c)
{
if (c >= 'A' && c <= 'Z')
return c - 'A';
if (c >= 'a' && c <= 'z')
return c - 'a' + 26;
if (c >= '0' && c <= '9')
return c - '0' + 52;
if (c == '+')
return 62;
if (c == '/')
return 63;
return -1;
}
int scr_b64_decode(const char *in, size_t n, struct buf *out)
{
unsigned char *o = scr_xmalloc(n / 4 * 3 + 4);
size_t i, len = 0;
unsigned acc = 0;
int bits = 0;
for (i = 0; i < n; i++) {
int c = (unsigned char)in[i];
int v;
if (c == '=' || c == '\n' || c == '\r' || c == ' ' || c == '\t')
continue;
v = b64val(c);
if (v < 0) {
free(o);
return -1;
}
acc = (acc << 6) | (unsigned)v;
bits += 6;
if (bits >= 8) {
bits -= 8;
o[len++] = (unsigned char)(acc >> bits);
acc &= (1u << bits) - 1;
}
}
out->data = o;
out->len = len;
return 0;
}
Executable
+117
View File
@@ -0,0 +1,117 @@
#!/bin/sh
# End-to-end tests. No network, no fixtures: keys are made in a temp dir.
set -eu
cd "$(dirname "$0")/.."
BIN=$PWD/sshcrypt
T=$(mktemp -d "${TMPDIR:-/tmp}/sshcrypt-test.XXXXXX")
trap 'rm -rf "$T"' EXIT INT TERM
pass=0
fail=0
ok() { pass=$((pass + 1)); }
bad() { fail=$((fail + 1)); printf 'FAIL: %s\n' "$*" >&2; }
check() { if eval "$2"; then ok; else bad "$1"; fi; }
ssh-keygen -q -t ed25519 -N '' -C t -f "$T/ed" >/dev/null
ssh-keygen -q -t rsa -b 3072 -N '' -C t -f "$T/rsa" >/dev/null
ssh-keygen -q -t ed25519 -N '' -C other -f "$T/other" >/dev/null
ssh-keygen -q -t ed25519 -N 'hunter2' -C pw -f "$T/pw" >/dev/null
# --- fingerprints agree with OpenSSH -----------------------------------------
check "fingerprint ed25519 matches ssh-keygen" \
'[ "$("$BIN" -F "$T/ed.pub")" = "$(ssh-keygen -lf "$T/ed.pub" | cut -d" " -f2)" ]'
check "fingerprint RSA matches ssh-keygen" \
'[ "$("$BIN" -F "$T/rsa.pub")" = "$(ssh-keygen -lf "$T/rsa.pub" | cut -d" " -f2)" ]'
# --- round trips --------------------------------------------------------------
printf 'hello, world\n' >"$T/msg"
"$BIN" -r "$T/ed.pub" -i "$T/msg" -o "$T/msg.asc"
check "armored output is text" 'grep -q "BEGIN SSHCRYPT MESSAGE" "$T/msg.asc"'
"$BIN" -d -k "$T/ed" -i "$T/msg.asc" -o "$T/msg.out"
check "ed25519 round trip" 'cmp -s "$T/msg" "$T/msg.out"'
"$BIN" -d -k "$T/ed" -i "$T/msg.asc" -o "$T/msg.same" -q
check "round trip is byte exact" 'cmp -s "$T/msg" "$T/msg.same"'
head -c 65536 /dev/urandom >"$T/blob"
"$BIN" -r "$T/ed.pub" -b -i "$T/blob" -o "$T/blob.bin"
check "binary envelope has the magic" 'head -c 4 "$T/blob.bin" | grep -q SSHC'
"$BIN" -d -k "$T/ed" -i "$T/blob.bin" -o "$T/blob.out"
check "64 KiB random binary round trip" 'cmp -s "$T/blob" "$T/blob.out"'
: >"$T/empty"
"$BIN" -r "$T/ed.pub" -i "$T/empty" -o "$T/empty.asc"
"$BIN" -d -k "$T/ed" -i "$T/empty.asc" -o "$T/empty.out"
check "empty input round trip" '[ ! -s "$T/empty.out" ]'
printf 'no trailing newline\000and a nul' >"$T/odd"
"$BIN" -r "$T/ed.pub" -i "$T/odd" -o "$T/odd.asc"
"$BIN" -d -k "$T/ed" -i "$T/odd.asc" -o "$T/odd.out"
check "NUL bytes and no trailing newline" 'cmp -s "$T/odd" "$T/odd.out"'
# --- pipes -------------------------------------------------------------------
cat "$T/msg" | "$BIN" -r "$T/ed.pub" | "$BIN" -d -k "$T/ed" >"$T/pipe.out"
check "stdin to stdout pipeline" 'cmp -s "$T/msg" "$T/pipe.out"'
# --- RSA ---------------------------------------------------------------------
"$BIN" -r "$T/rsa.pub" -i "$T/msg" -o "$T/rsa.asc"
"$BIN" -d -k "$T/rsa" -i "$T/rsa.asc" -o "$T/rsa.out"
check "RSA round trip" 'cmp -s "$T/msg" "$T/rsa.out"'
# --- armor survives being pasted into a mail ---------------------------------
{
printf 'Hi, here is the thing:\n\n'
cat "$T/msg.asc"
printf '\n-- \nsig\n'
} >"$T/mail.txt"
"$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"'
# --- 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"
else
ok
fi
check "wrong key names both fingerprints" \
'grep -q "but your key is SHA256:" "$T/err"'
check "wrong key writes nothing" '[ ! -e "$T/nope" ]'
cp "$T/blob.bin" "$T/tampered.bin"
python3 - "$T/tampered.bin" <<'EOF'
import sys
p = sys.argv[1]
b = bytearray(open(p, 'rb').read())
b[-1] ^= 0x01
open(p, 'wb').write(b)
EOF
if "$BIN" -d -k "$T/ed" -i "$T/tampered.bin" -o "$T/nope2" 2>"$T/err2"; then
bad "a modified message must fail"
else
ok
fi
if "$BIN" -r "$T/ed" -d -k "$T/ed" -i "$T/msg" -o "$T/nope3" 2>/dev/null; then
bad "garbage input must fail"
else
ok
fi
# --- 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"'
"$BIN" -r "$T/ed" -i "$T/msg" -o "$T/viapriv.asc"
"$BIN" -d -k "$T/ed" -i "$T/viapriv.asc" -o "$T/viapriv.out"
check "encrypting to a private-key path works" 'cmp -s "$T/msg" "$T/viapriv.out"'
# --- 1 MiB -------------------------------------------------------------------
head -c 1048576 /dev/urandom >"$T/big"
"$BIN" -r "$T/ed.pub" -i "$T/big" -o "$T/big.asc"
"$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"'
printf '%d passed, %d failed\n' "$pass" "$fail"
[ "$fail" -eq 0 ]