Files
sshcrypt/src/keys.c
T

651 lines
15 KiB
C

#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_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);
if (!priv) {
int rc = parse_pub_text((const char *)b.data, b.len, path, out);
free(b.data);
return rc;
}
free(b.data);
{
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);
}