From 089d9e3555a7e00102847944dfdadf6b64141be5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 15:40:10 +0000 Subject: [PATCH] SSH: PuTTY's .ppk keys, Pageant and OpenSSH's agent on Windows, an agent's socket chosen; the Linux app's login menu and PuTTY key import --- .github/workflows/build.yml | 14 +- linux/src/app.h | 4 + linux/src/config.c | 15 + linux/src/remote.c | 473 +++++++++++++- ssh/CMakeLists.txt | 6 +- ssh/include/dmodemssh.h | 21 +- ssh/src/agent.c | 397 ++++++++++++ ssh/src/agent.h | 30 + ssh/src/dmodemssh.c | 75 ++- ssh/src/ppk.c | 1169 +++++++++++++++++++++++++++++++++++ ssh/src/ppk.h | 38 ++ ssh/test/dmodemssh_test.c | 284 +++++++++ 12 files changed, 2501 insertions(+), 25 deletions(-) create mode 100644 ssh/src/agent.c create mode 100644 ssh/src/agent.h create mode 100644 ssh/src/ppk.c create mode 100644 ssh/src/ppk.h diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 28bb302..972d2d0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -36,15 +36,25 @@ jobs: ctest --test-dir build-asan --output-on-failure -R dmodemctl - name: SSH against a real sshd run: | - sudo apt-get install -y --no-install-recommends openssh-server + sudo apt-get install -y --no-install-recommends openssh-server putty-tools sudo useradd -m dmtest echo 'dmtest:Sesame-42' | sudo chpasswd + # a key in a file, one of PuTTY's (.ppk) and one in an agent ssh-keygen -q -t ed25519 -N '' -f "$RUNNER_TEMP/key" + : > "$RUNNER_TEMP/empty" + puttygen -t rsa -b 2048 -o "$RUNNER_TEMP/key.ppk" --new-passphrase "$RUNNER_TEMP/empty" + ssh-keygen -q -t ecdsa -N '' -f "$RUNNER_TEMP/agentkey" + eval "$(ssh-agent -a "$RUNNER_TEMP/agent.sock")" + ssh-add "$RUNNER_TEMP/agentkey" + unset SSH_AUTH_SOCK + puttygen "$RUNNER_TEMP/key.ppk" -O public-openssh -o "$RUNNER_TEMP/ppk.pub" + cat "$RUNNER_TEMP/key.pub" "$RUNNER_TEMP/agentkey.pub" "$RUNNER_TEMP/ppk.pub" > "$RUNNER_TEMP/authorized_keys" sudo install -d -m 700 -o dmtest ~dmtest/.ssh - sudo install -m 600 -o dmtest "$RUNNER_TEMP/key.pub" ~dmtest/.ssh/authorized_keys + sudo install -m 600 -o dmtest "$RUNNER_TEMP/authorized_keys" ~dmtest/.ssh/authorized_keys sudo mkdir -p /run/sshd sudo /usr/sbin/sshd -p 2222 -o ListenAddress=127.0.0.1 -o PasswordAuthentication=yes DMODEM_SSH_TEST=127.0.0.1:2222:dmtest:Sesame-42 DMODEM_SSH_TEST_KEY="$RUNNER_TEMP/key" \ + DMODEM_SSH_TEST_PPK="$RUNNER_TEMP/key.ppk" DMODEM_SSH_TEST_AGENT="$RUNNER_TEMP/agent.sock" \ build/ssh/dmodemssh_test windows-9x: diff --git a/linux/src/app.h b/linux/src/app.h index e8e1d71..79726ea 100644 --- a/linux/src/app.h +++ b/linux/src/app.h @@ -33,6 +33,10 @@ typedef struct Config { /* the Remote page's last login ([remote]): "SSH", "Telnet" or "rlogin", the server, its port (0: the protocol's), the user */ char *remote_proto, *remote_host, *remote_user; + /* how SSH logs in: "auto" (OpenSSH's keys and the agent), "agent" + or "key" (remote_key's file: OpenSSH's, PEM or PuTTY's .ppk); + the agent's socket ("": SSH_AUTH_SOCK's) */ + char *remote_auth, *remote_key, *remote_agent; /* the terminals' kinds (dmc_vt profiles' ids) */ char *term_type, *remote_term; int remote_port; diff --git a/linux/src/config.c b/linux/src/config.c index 044086f..aaddada 100644 --- a/linux/src/config.c +++ b/linux/src/config.c @@ -77,6 +77,15 @@ void config_load(Config *c) c->remote_user = g_key_file_get_string(k, "remote", "user", NULL); if (!c->remote_user) c->remote_user = g_strdup(""); + c->remote_auth = g_key_file_get_string(k, "remote", "login", NULL); + if (!c->remote_auth) + c->remote_auth = g_strdup("auto"); + c->remote_key = g_key_file_get_string(k, "remote", "key", NULL); + if (!c->remote_key) + c->remote_key = g_strdup(""); + c->remote_agent = g_key_file_get_string(k, "remote", "agent", NULL); + if (!c->remote_agent) + c->remote_agent = g_strdup(""); c->remote_term = g_key_file_get_string(k, "remote", "terminal", NULL); if (!c->remote_term) c->remote_term = g_strdup("xterm"); @@ -112,6 +121,9 @@ void config_save(const Config *c) g_key_file_set_string(k, "remote", "host", c->remote_host); g_key_file_set_integer(k, "remote", "port", c->remote_port); g_key_file_set_string(k, "remote", "user", c->remote_user); + g_key_file_set_string(k, "remote", "login", c->remote_auth); + g_key_file_set_string(k, "remote", "key", c->remote_key); + g_key_file_set_string(k, "remote", "agent", c->remote_agent); g_key_file_set_string(k, "remote", "terminal", c->remote_term); g_key_file_set_string(k, "terminal", "type", c->term_type); char *p = path(); @@ -145,6 +157,9 @@ void config_free(Config *c) g_free(c->remote_host); g_free(c->remote_user); g_free(c->remote_term); + g_free(c->remote_auth); + g_free(c->remote_key); + g_free(c->remote_agent); g_free(c->term_type); } diff --git a/linux/src/remote.c b/linux/src/remote.c index ec1ee5a..99a6660 100644 --- a/linux/src/remote.c +++ b/linux/src/remote.c @@ -9,8 +9,11 @@ * dmc_net for the protocol. SSH is libdmodemssh (the apps' own client, * on libssh) on a thread of its own, its events brought to the main * loop; it reads OpenSSH's config, known_hosts, keys and agent, so that - * they are the user's. Either way the terminal only shows bytes and - * gives what is typed. + * they are the user's. Its login may instead be by the agent alone (an + * ssh-agent's socket, SSH_AUTH_SOCK's or one given) or by a key file: + * OpenSSH's, PEM or PuTTY's .ppk, which can also be imported into + * ~/.ssh in OpenSSH's form. Either way the terminal only shows bytes + * and gives what is typed. */ #include #include @@ -30,6 +33,8 @@ static const int protos[] = { DMC_NET_SSH, DMC_NET_TELNET, DMC_NET_RLOGIN }; typedef struct Remote { App *a; GtkWidget *proto, *host, *port, *user, *go, *status; + /* how SSH logs in: its menu, the way, the key file, the agent */ + GtkWidget *login, *auth, *key_label, *agent, *agent_state; GtkWidget *term, *type; int cols, rows; /* what runs: its protocol (0: none) */ @@ -46,6 +51,10 @@ typedef struct Remote { the logins tried, a question's dialog */ struct Ssh *ssh; int shell, tried, asks, exit_status; + /* the methods the server last offered; the key file's text and the + passphrases tried for it */ + int methods, key_tries; + char *key_text; AdwDialog *dialog; guint size_tick; } Remote; @@ -64,6 +73,8 @@ static void controls(Remote *r) gtk_widget_set_sensitive(r->host, idle); gtk_widget_set_sensitive(r->port, idle); gtk_widget_set_sensitive(r->user, idle); + if (r->login) + gtk_widget_set_sensitive(r->login, idle); gtk_button_set_label(GTK_BUTTON(r->go), idle ? "Connect" : "Disconnect"); if (idle) { gtk_widget_add_css_class(r->go, "suggested-action"); @@ -79,6 +90,15 @@ static void show(Remote *r, const char *data, gssize n) termview_feed(r->term, data, n < 0 ? (int)strlen(data) : (int)n); } +/* the key file's text let go of (wiped) */ +static void key_forget(Remote *r) +{ + if (r->key_text) { + memset(r->key_text, 0, strlen(r->key_text)); + g_clear_pointer(&r->key_text, g_free); + } +} + static void ssh_disconnect(Remote *r); /* the connection over, with why (NULL: the user's doing) */ @@ -110,6 +130,7 @@ static void ended(Remote *r, const char *why) /* (the connection is freed once its thread has said it's closed) */ if (r->ssh) ssh_disconnect(r); + key_forget(r); r->shell = 0; if (r->size_tick) g_source_remove(r->size_tick); @@ -424,16 +445,133 @@ static void ask(Remote *r, const char *heading, const char *body, int prompts) gtk_widget_grab_focus(g_ptr_array_index(entries, 0)); } -/* what's tried, in OpenSSH's order: keys and the agent, then the - server's questions or a password (three times at most) */ -enum { TRIED_KEYS = 1 }; +/* a passphrase given (NULL: cancelled), to what asked for it */ +typedef void (*PassFn)(Remote *r, const char *pass, gpointer data); + +static void passphrase_given(AdwAlertDialog *d, const char *response, gpointer data) +{ + Remote *r = data; + PassFn fn = g_object_get_data(G_OBJECT(d), "fn"); + GtkWidget *e = g_object_get_data(G_OBJECT(d), "entry"); + if (r->dialog == ADW_DIALOG(d)) + r->dialog = NULL; + fn(r, strcmp(response, "ok") ? NULL : gtk_editable_get_text(GTK_EDITABLE(e)), + g_object_get_data(G_OBJECT(d), "arg")); +} + +/* a key's passphrase asked for (why: a try's failure, or NULL); fn + gets it with arg (freed with free_arg); login: the connection's + dialog, closed with it */ +static void ask_passphrase(Remote *r, const char *name, const char *why, + PassFn fn, gpointer arg, GDestroyNotify free_arg, + gboolean login) +{ + char *head = g_strdup_printf("Passphrase for %s", name); + AdwDialog *d = adw_alert_dialog_new(head, why); + g_free(head); + GtkWidget *e = gtk_password_entry_new(); + g_object_set(e, "placeholder-text", "Passphrase", "activates-default", TRUE, NULL); + adw_alert_dialog_set_extra_child(ADW_ALERT_DIALOG(d), e); + adw_alert_dialog_add_responses(ADW_ALERT_DIALOG(d), "cancel", "Cancel", + "ok", "Unlock", NULL); + adw_alert_dialog_set_response_appearance(ADW_ALERT_DIALOG(d), "ok", + ADW_RESPONSE_SUGGESTED); + adw_alert_dialog_set_default_response(ADW_ALERT_DIALOG(d), "ok"); + adw_alert_dialog_set_close_response(ADW_ALERT_DIALOG(d), "cancel"); + g_object_set_data(G_OBJECT(d), "fn", (gpointer)fn); + g_object_set_data(G_OBJECT(d), "entry", e); + g_object_set_data_full(G_OBJECT(d), "arg", arg, free_arg); + g_signal_connect(d, "response", G_CALLBACK(passphrase_given), r); + if (login) + r->dialog = d; + adw_dialog_present(d, GTK_WIDGET(r->a->window)); + gtk_widget_grab_focus(e); +} + +/* a path with ~/ at its start made the home folder's */ +static char *expand(const char *path) +{ + if (path[0] == '~' && path[1] == '/') + return g_build_filename(g_get_home_dir(), path + 2, NULL); + return g_strdup(path); +} + +/* what's tried, in OpenSSH's order: keys and the agent (or what was + chosen: the agent alone, or a key file), then the server's questions + or a password (three times at most) */ +enum { TRIED_KEYS = 1, TRIED_FILE = 2 }; + +static void ssh_auth(Remote *r, int methods, const char *why); + +/* the key file's passphrase given: the login by it, or another try */ +static void key_passphrase(Remote *r, const char *pass, gpointer data) +{ + Ssh *ssh = data; + if (ssh != r->ssh || !r->key_text) + return; + char *name = g_path_get_basename(r->a->cfg.remote_key); + if (pass && dmc_ssh_auth_key(ssh->s, r->key_text, pass) == 0) { + r->tried |= TRIED_FILE; + } else if (pass && ++r->key_tries < 3) { + ask_passphrase(r, name, "That passphrase does not open the key.", + key_passphrase, ssh, NULL, TRUE); + } else { + r->tried |= TRIED_FILE; + key_forget(r); + ssh_auth(r, r->methods, ""); + } + g_free(name); +} + +/* the login by the key file: its passphrase asked for if it has one; + FALSE when there's nothing to try */ +static gboolean key_login(Remote *r) +{ + char *path = expand(r->a->cfg.remote_key); + char *name = g_path_get_basename(path); + gboolean ok = FALSE; + + key_forget(r); + if (!g_file_get_contents(path, &r->key_text, NULL, NULL)) { + char *m = g_strdup_printf("\r\n[The key file %s can't be read]\r\n", path); + show(r, m, -1); + g_free(m); + r->tried |= TRIED_FILE; + } else if (dmc_ssh_key_encrypted(r->key_text)) { + r->key_tries = 0; + ask_passphrase(r, name, NULL, key_passphrase, r->ssh, NULL, TRUE); + ok = TRUE; + } else { + r->tried |= TRIED_FILE; + ok = dmc_ssh_auth_key(r->ssh->s, r->key_text, NULL) == 0; + if (!ok) { + char *m = g_strdup_printf("\r\n[%s is not a key that can be read]\r\n", path); + show(r, m, -1); + g_free(m); + } + } + g_free(name); + g_free(path); + return ok; +} static void ssh_auth(Remote *r, int methods, const char *why) { Ssh *ssh = r->ssh; - if ((methods & DMC_SSH_AUTH_PUBLICKEY) && !(r->tried & TRIED_KEYS)) { + const char *how = r->a->cfg.remote_auth; + gboolean file = !strcmp(how, "key") && *r->a->cfg.remote_key; + + r->methods = methods; + if ((methods & DMC_SSH_AUTH_PUBLICKEY) && file && !(r->tried & TRIED_FILE)) { + if (key_login(r)) + return; + } else if ((methods & DMC_SSH_AUTH_PUBLICKEY) && !file && + !(r->tried & TRIED_KEYS)) { r->tried |= TRIED_KEYS; - dmc_ssh_auth_auto(ssh->s); + if (!strcmp(how, "agent")) + dmc_ssh_auth_agent(ssh->s); + else + dmc_ssh_auth_auto(ssh->s); return; } if (r->asks++ >= 3) { @@ -547,12 +685,20 @@ static gboolean start_ssh(Remote *r, const char *host, int port, /* OpenSSH's own config and known hosts: the user's */ dmc_ssh_option(s, "config", ""); dmc_ssh_option(s, "knownhosts", ""); + /* the agent: the one given, else SSH_AUTH_SOCK's */ + const char *agent = r->a->cfg.remote_agent; + if (*agent) + dmc_ssh_option(s, "agent", agent); + if (!strcmp(r->a->cfg.remote_auth, "agent") && !dmc_ssh_agent_reachable(agent)) + show(r, *agent ? "[No agent answers at the socket given]\r\n" : + "[No agent answers: SSH_AUTH_SOCK names none]\r\n", -1); Ssh *ssh = g_new0(Ssh, 1); ssh->s = s; r->ssh = ssh; r->shell = 0; r->tried = 0; r->asks = 0; + key_forget(r); r->exit_status = 0; SshEv *start = g_new0(SshEv, 1); start->r = r; @@ -612,6 +758,8 @@ static void proto_changed(GObject *o, GParamSpec *p, gpointer data) char ps[16]; g_snprintf(ps, sizeof(ps), "%d", dmc_net_default_port(chosen_proto(r))); gtk_entry_set_placeholder_text(GTK_ENTRY(r->port), ps); + if (r->login) + gtk_widget_set_visible(r->login, chosen_proto(r) == DMC_NET_SSH); } static void connect_clicked(GtkWidget *w, gpointer data) @@ -702,6 +850,316 @@ static void type_changed(GObject *o, GParamSpec *p, gpointer data) config_save(&r->a->cfg); } +/* + * how SSH logs in: its menu + */ + +/* the ways in the drop-down's order, as the config has them */ +static const char *const hows[] = { "auto", "agent", "key" }; + +/* the key file shown (and its row's tooltip) */ +static void key_shown(Remote *r) +{ + const char *k = r->a->cfg.remote_key; + char *name = *k ? g_path_get_basename(k) : g_strdup("No key file chosen"); + gtk_label_set_text(GTK_LABEL(r->key_label), name); + gtk_widget_set_tooltip_text(r->key_label, *k ? k : NULL); + g_free(name); +} + +/* whether the agent answers, under its socket's entry */ +static void agent_shown(Remote *r) +{ + const char *a = r->a->cfg.remote_agent; + const char *m = dmc_ssh_agent_reachable(a) ? "An agent answers there" : + *a ? "No agent answers there" : + g_getenv("SSH_AUTH_SOCK") ? "No agent answers at SSH_AUTH_SOCK" : + "SSH_AUTH_SOCK is not set: give the agent's socket"; + gtk_label_set_text(GTK_LABEL(r->agent_state), m); +} + +/* the way chosen, kept */ +static void how_changed(GObject *o, GParamSpec *p, gpointer data) +{ + Remote *r = data; + (void)o; + (void)p; + guint i = gtk_drop_down_get_selected(GTK_DROP_DOWN(r->auth)); + g_free(r->a->cfg.remote_auth); + r->a->cfg.remote_auth = g_strdup(hows[i < G_N_ELEMENTS(hows) ? i : 0]); + config_save(&r->a->cfg); +} + +/* the key file set, and the login by it chosen */ +static void key_set(Remote *r, const char *path) +{ + g_free(r->a->cfg.remote_key); + r->a->cfg.remote_key = g_strdup(path); + gtk_drop_down_set_selected(GTK_DROP_DOWN(r->auth), 2); + config_save(&r->a->cfg); + key_shown(r); +} + +/* the agent's socket typed, kept */ +static void agent_changed(GtkEditable *e, gpointer data) +{ + Remote *r = data; + g_free(r->a->cfg.remote_agent); + r->a->cfg.remote_agent = g_strstrip(g_strdup(gtk_editable_get_text(e))); + config_save(&r->a->cfg); + agent_shown(r); +} + +/* a file dialog for keys, in ~/.ssh, *.ppk alone when ppk */ +static GtkFileDialog *key_dialog(const char *title, gboolean ppk) +{ + GtkFileDialog *d = gtk_file_dialog_new(); + gtk_file_dialog_set_title(d, title); + char *dir = g_build_filename(g_get_home_dir(), ".ssh", NULL); + GFile *f = g_file_new_for_path(dir); + if (g_file_test(dir, G_FILE_TEST_IS_DIR)) + gtk_file_dialog_set_initial_folder(d, f); + g_object_unref(f); + g_free(dir); + GListStore *filters = g_list_store_new(GTK_TYPE_FILE_FILTER); + GtkFileFilter *putty = gtk_file_filter_new(); + gtk_file_filter_set_name(putty, "PuTTY keys (.ppk)"); + gtk_file_filter_add_pattern(putty, "*.ppk"); + if (!ppk) { + GtkFileFilter *all = gtk_file_filter_new(); + gtk_file_filter_set_name(all, "All keys (OpenSSH's, PEM, PuTTY's)"); + gtk_file_filter_add_pattern(all, "*"); + g_list_store_append(filters, all); + g_object_unref(all); + } + g_list_store_append(filters, putty); + g_object_unref(putty); + gtk_file_dialog_set_filters(d, G_LIST_MODEL(filters)); + g_object_unref(filters); + return d; +} + +static void key_chosen(GObject *src, GAsyncResult *res, gpointer data) +{ + GFile *f = gtk_file_dialog_open_finish(GTK_FILE_DIALOG(src), res, NULL); + if (!f) + return; + char *p = g_file_get_path(f); + if (p) + key_set(data, p); + g_free(p); + g_object_unref(f); +} + +static void choose_key(GtkButton *b, gpointer data) +{ + Remote *r = data; + gtk_menu_button_popdown(GTK_MENU_BUTTON(r->login)); + (void)b; + GtkFileDialog *d = key_dialog("Choose a Private Key", FALSE); + gtk_file_dialog_open(d, r->a->window, NULL, key_chosen, r); + g_object_unref(d); +} + +/* where an imported key goes: ~/.ssh/, a name not yet taken */ +static char *import_path(const char *ppk) +{ + char *dir = g_build_filename(g_get_home_dir(), ".ssh", NULL); + char *base = g_path_get_basename(ppk); + char *dot = strrchr(base, '.'); + if (dot && !g_ascii_strcasecmp(dot, ".ppk")) + *dot = 0; + if (!*base) { + g_free(base); + base = g_strdup("putty-key"); + } + g_mkdir_with_parents(dir, 0700); + char *path = NULL; + for (int i = 1; i < 100; i++) { + char *name = i == 1 ? g_strdup(base) : g_strdup_printf("%s-%d", base, i); + path = g_build_filename(dir, name, NULL); + char *pub = g_strconcat(path, ".pub", NULL); + gboolean taken = g_file_test(path, G_FILE_TEST_EXISTS) || + g_file_test(pub, G_FILE_TEST_EXISTS); + g_free(pub); + g_free(name); + if (!taken) + break; + g_clear_pointer(&path, g_free); + } + g_free(base); + g_free(dir); + return path; +} + +/* a .ppk imported with its passphrase (NULL: cancelled): written to + ~/.ssh in OpenSSH's form, with the same passphrase, and chosen */ +static void import_with(Remote *r, const char *pass, gpointer data) +{ + const char *ppk = data; + char *text = NULL, *key = NULL, *pub = NULL; + char *name = g_path_get_basename(ppk); + + if (!g_file_get_contents(ppk, &text, NULL, NULL)) { + window_toast(r->a, "The PuTTY key can't be read"); + g_free(name); + return; + } + gboolean enc = dmc_ssh_key_encrypted(text); + if (enc && !pass) + goto done; + if (dmc_ssh_key_export(text, pass, pass, &key) || dmc_ssh_key_public(key, pass, &pub)) { + if (enc) + ask_passphrase(r, name, "That passphrase does not open the key.", + import_with, g_strdup(ppk), g_free, FALSE); + else + window_toast(r->a, "That file is not a PuTTY key that can be read"); + goto done; + } + char *path = import_path(ppk); + char *pubpath = path ? g_strconcat(path, ".pub", NULL) : NULL; + /* (the .pub line with the .ppk's comment, as OpenSSH's have theirs) */ + const char *c = strstr(text, "\nComment: "); + char *comment = c ? g_strndup(c + 10, strcspn(c + 10, "\r\n")) : g_strdup(""); + char *line = g_strdup_printf("%s%s%s\n", pub, *comment ? " " : "", comment); + GError *e = NULL; + if (path && g_file_set_contents_full(path, key, -1, G_FILE_SET_CONTENTS_CONSISTENT, 0600, &e) && + g_file_set_contents_full(pubpath, line, -1, G_FILE_SET_CONTENTS_CONSISTENT, 0644, &e)) { + key_set(r, path); + const char *home = g_get_home_dir(); + gsize hl = strlen(home); + char *m = !strncmp(path, home, hl) && path[hl] == '/' ? + g_strdup_printf("Imported as ~%s, and chosen for SSH logins", path + hl) : + g_strdup_printf("Imported as %s, and chosen for SSH logins", path); + window_toast(r->a, m); + g_free(m); + } else { + char *m = g_strdup_printf("The key could not be saved: %s", + e ? e->message : "no room in ~/.ssh"); + window_toast(r->a, m); + g_free(m); + } + g_clear_error(&e); + g_free(line); + g_free(comment); + g_free(pubpath); + g_free(path); +done: + if (key) { + memset(key, 0, strlen(key)); + dmc_ssh_free_string(key); + } + dmc_ssh_free_string(pub); + memset(text, 0, strlen(text)); + g_free(text); + g_free(name); +} + +static void ppk_chosen(GObject *src, GAsyncResult *res, gpointer data) +{ + Remote *r = data; + GFile *f = gtk_file_dialog_open_finish(GTK_FILE_DIALOG(src), res, NULL); + if (!f) + return; + char *p = g_file_get_path(f); + char *text = NULL; + if (p && g_file_get_contents(p, &text, NULL, NULL) && dmc_ssh_key_encrypted(text)) { + char *name = g_path_get_basename(p); + ask_passphrase(r, name, NULL, import_with, g_strdup(p), g_free, FALSE); + g_free(name); + } else if (p) { + import_with(r, NULL, p); + } + if (text) { + memset(text, 0, strlen(text)); + g_free(text); + } + g_free(p); + g_object_unref(f); +} + +static void import_clicked(GtkButton *b, gpointer data) +{ + Remote *r = data; + gtk_menu_button_popdown(GTK_MENU_BUTTON(r->login)); + (void)b; + GtkFileDialog *d = key_dialog("Import a PuTTY Key", TRUE); + gtk_file_dialog_open(d, r->a->window, NULL, ppk_chosen, r); + g_object_unref(d); +} + +/* the menu's button: the way to log in, the key file, the agent's + socket, and a .ppk's import */ +static GtkWidget *login_menu(Remote *r) +{ + App *a = r->a; + GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8); + gtk_widget_set_margin_start(box, 6); + gtk_widget_set_margin_end(box, 6); + gtk_widget_set_margin_top(box, 6); + gtk_widget_set_margin_bottom(box, 6); + + GtkWidget *l = gtk_label_new("Log in to SSH servers with"); + gtk_label_set_xalign(GTK_LABEL(l), 0); + gtk_widget_add_css_class(l, "heading"); + gtk_box_append(GTK_BOX(box), l); + const char *names[] = { "My keys and agent, as ssh does", + "The agent's keys only", "A key file", NULL }; + r->auth = gtk_drop_down_new_from_strings(names); + guint i; + for (i = 0; i < G_N_ELEMENTS(hows); i++) + if (!strcmp(a->cfg.remote_auth, hows[i])) + gtk_drop_down_set_selected(GTK_DROP_DOWN(r->auth), i); + g_signal_connect(r->auth, "notify::selected", G_CALLBACK(how_changed), r); + gtk_box_append(GTK_BOX(box), r->auth); + + l = gtk_label_new("Key file (OpenSSH's, PEM or PuTTY's .ppk)"); + gtk_label_set_xalign(GTK_LABEL(l), 0); + gtk_widget_add_css_class(l, "dim-label"); + gtk_box_append(GTK_BOX(box), l); + GtkWidget *row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6); + r->key_label = gtk_label_new(NULL); + gtk_label_set_xalign(GTK_LABEL(r->key_label), 0); + gtk_label_set_ellipsize(GTK_LABEL(r->key_label), PANGO_ELLIPSIZE_MIDDLE); + gtk_widget_set_hexpand(r->key_label, TRUE); + gtk_box_append(GTK_BOX(row), r->key_label); + GtkWidget *b = gtk_button_new_with_label("Choose…"); + g_signal_connect(b, "clicked", G_CALLBACK(choose_key), r); + gtk_box_append(GTK_BOX(row), b); + gtk_box_append(GTK_BOX(box), row); + key_shown(r); + + b = gtk_button_new_with_label("Import a PuTTY Key…"); + gtk_widget_set_tooltip_text(b, "A .ppk saved in ~/.ssh in OpenSSH's form, " + "with the same passphrase, and chosen"); + g_signal_connect(b, "clicked", G_CALLBACK(import_clicked), r); + gtk_box_append(GTK_BOX(box), b); + + l = gtk_label_new("Agent's socket"); + gtk_label_set_xalign(GTK_LABEL(l), 0); + gtk_widget_add_css_class(l, "dim-label"); + gtk_box_append(GTK_BOX(box), l); + r->agent = gtk_entry_new(); + gtk_entry_set_placeholder_text(GTK_ENTRY(r->agent), "Empty: SSH_AUTH_SOCK's"); + gtk_editable_set_text(GTK_EDITABLE(r->agent), a->cfg.remote_agent); + g_signal_connect(r->agent, "changed", G_CALLBACK(agent_changed), r); + gtk_box_append(GTK_BOX(box), r->agent); + r->agent_state = gtk_label_new(NULL); + gtk_label_set_xalign(GTK_LABEL(r->agent_state), 0); + gtk_widget_add_css_class(r->agent_state, "dim-label"); + gtk_widget_add_css_class(r->agent_state, "caption"); + gtk_box_append(GTK_BOX(box), r->agent_state); + agent_shown(r); + + GtkWidget *pop = gtk_popover_new(); + gtk_popover_set_child(GTK_POPOVER(pop), box); + r->login = gtk_menu_button_new(); + gtk_menu_button_set_icon_name(GTK_MENU_BUTTON(r->login), "dialog-password-symbolic"); + gtk_widget_set_tooltip_text(r->login, "How SSH logs in: keys, the agent, a PuTTY key"); + gtk_menu_button_set_popover(GTK_MENU_BUTTON(r->login), pop); + return r->login; +} + static int proto_index(const char *name) { guint i; @@ -746,6 +1204,7 @@ GtkWidget *remote_page_new(App *a) gtk_entry_set_placeholder_text(GTK_ENTRY(r->user), "User"); gtk_editable_set_width_chars(GTK_EDITABLE(r->user), 12); gtk_box_append(GTK_BOX(bar), r->user); + gtk_box_append(GTK_BOX(bar), login_menu(r)); r->go = gtk_button_new_with_label("Connect"); g_signal_connect(r->go, "clicked", G_CALLBACK(connect_clicked), r); diff --git a/ssh/CMakeLists.txt b/ssh/CMakeLists.txt index d35fa8d..4baeb9b 100644 --- a/ssh/CMakeLists.txt +++ b/ssh/CMakeLists.txt @@ -25,11 +25,11 @@ else() include(${CMAKE_CURRENT_LIST_DIR}/cmake/BundledLibssh.cmake) endif() -add_library(dmodemssh STATIC src/dmodemssh.c) +add_library(dmodemssh STATIC src/dmodemssh.c src/ppk.c src/agent.c) target_include_directories(dmodemssh PUBLIC include) target_link_libraries(dmodemssh PUBLIC dmodem_libssh) if(WIN32) - target_link_libraries(dmodemssh PUBLIC ws2_32) + target_link_libraries(dmodemssh PUBLIC ws2_32 user32 advapi32) elseif(UNIX) find_package(Threads REQUIRED) target_link_libraries(dmodemssh PUBLIC Threads::Threads) @@ -42,4 +42,6 @@ endif() add_executable(dmodemssh_test test/dmodemssh_test.c) target_link_libraries(dmodemssh_test PRIVATE dmodemssh) +# (Argon2 is tested too: ppk.h) +target_include_directories(dmodemssh_test PRIVATE src) add_test(NAME dmodemssh COMMAND dmodemssh_test) diff --git a/ssh/include/dmodemssh.h b/ssh/include/dmodemssh.h index a2694bb..b3ba666 100644 --- a/ssh/include/dmodemssh.h +++ b/ssh/include/dmodemssh.h @@ -15,8 +15,9 @@ * * What it has: host keys checked by the caller (and in OpenSSH's * known_hosts when asked); logins by password, keyboard-interactive, a - * private key (OpenSSH's, PEM), the system's agent, or OpenSSH's own - * keys and agent at once (ssh's default); ~/.ssh/config when asked; Ed25519, + * private key (OpenSSH's, PEM or PuTTY's .ppk), an agent (ssh-agent's + * socket; on Windows Pageant or OpenSSH's), or OpenSSH's own keys and + * agent at once (ssh's default); ~/.ssh/config when asked; Ed25519, * ECDSA and RSA keys; a shell on a pty, a command, direct TCP channels * (ssh -L and -D), remote listens (ssh -R) and the server's * agent channels (ssh -A) handed to the caller as channels. @@ -98,7 +99,10 @@ void dmc_ssh_free(dmc_ssh *s); "knownhosts" the host's key looked up there (a path; "" OpenSSH's) "hostkeys" the host key algorithms, in order (a list with commas) "timeout" seconds to connect in - "compression" "yes" or "no" */ + "compression" "yes" or "no" + "agent" the agent logged in with: a socket (Linux, macOS; "" + SSH_AUTH_SOCK's); on Windows "pageant", a named pipe, + or "" for Pageant and else OpenSSH's */ int dmc_ssh_option(dmc_ssh *s, const char *name, const char *value); /* the next event: 1 (in *ev), 0 when timeout_ms passed with none, -1 when the connection is over and its DMC_SSH_EV_CLOSED was handed back */ @@ -110,11 +114,15 @@ void dmc_ssh_disconnect(dmc_ssh *s); void dmc_ssh_trust(dmc_ssh *s, int ok, int remember); /* a login tried (an answer to DMC_SSH_EV_AUTH) */ void dmc_ssh_auth_password(dmc_ssh *s, const char *password); -/* by a private key's text (OpenSSH's, PEM): 0, or -1 when it can't be +/* by a private key's text (OpenSSH's, PEM or PuTTY's .ppk): 0, or -1 when it can't be read with that passphrase (nothing is tried: answer again) */ int dmc_ssh_auth_key(dmc_ssh *s, const char *key, const char *passphrase); -/* by the system's agent (SSH_AUTH_SOCK) */ +/* by the agent: the "agent" option's, else the system's (SSH_AUTH_SOCK; + on Windows Pageant, else OpenSSH's) */ void dmc_ssh_auth_agent(dmc_ssh *s); +/* whether that agent is there to answer (agent as the "agent" option): + 1 or 0 */ +int dmc_ssh_agent_reachable(const char *agent); /* as OpenSSH's ssh does: the agent, then ~/.ssh's keys with no passphrase */ void dmc_ssh_auth_auto(dmc_ssh *s); /* by the server's questions (keyboard-interactive) */ @@ -169,6 +177,9 @@ int dmc_ssh_keygen(const char *type, int bits, const char *passphrase, passphrase */ int dmc_ssh_key_public(const char *key, const char *passphrase, char **public_key); +/* whether a private key's text (OpenSSH's, PEM or PuTTY's .ppk) needs a + passphrase: 1 or 0 */ +int dmc_ssh_key_encrypted(const char *key); /* a private key written again (OpenSSH's form) with a new passphrase (NULL or "": none): 0, or -1 */ int dmc_ssh_key_export(const char *key, const char *passphrase, diff --git a/ssh/src/agent.c b/ssh/src/agent.c new file mode 100644 index 0000000..4bd7dce --- /dev/null +++ b/ssh/src/agent.c @@ -0,0 +1,397 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * agent.c - the agent libdmodemssh logs in with: on Linux and macOS an + * ssh-agent's socket (SSH_AUTH_SOCK, or one given); on + * Windows PuTTY's Pageant or OpenSSH's own agent. + * + * libssh talks to an agent over a socket it is given, so on Windows a + * pair of connected sockets stands between it and the agent: a thread + * reads each of libssh's requests from its end and hands it on, to + * Pageant by its WM_COPYDATA (a shared memory mapping, as PuTTY's own + * tools ask it) or down OpenSSH's named pipe, and writes the answer + * back. The thread ends when libssh closes its end. + * + * This file and agent.h are the same in D-Modem/gui (ssh/) and + * D-Modem/app (native-ssh/): change both. + */ +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#else +#include +#include +#include +#endif + +#include + +#include "agent.h" + +#ifdef _WIN32 + +/* Pageant's: its window, the WM_COPYDATA it answers, its longest message */ +#define PAGEANT_ID 0x804e50baUL +#define AGENT_MAX 262144 +/* OpenSSH's agent on Windows */ +#define OPENSSH_PIPE "\\\\.\\pipe\\openssh-ssh-agent" + +struct dmc_agent { + SOCKET sock; /* the thread's end */ + HANDLE thread; + HANDLE pipe; /* OpenSSH's, or a pipe given; else Pageant */ +}; + +/* a big-endian uint32 at b */ +static unsigned long be32(const unsigned char *b) +{ + return (unsigned long)b[0] << 24 | (unsigned long)b[1] << 16 | + (unsigned long)b[2] << 8 | b[3]; +} + +/* Pageant's window, if it's running */ +static HWND pageant(void) +{ + return FindWindowA("Pageant", "Pageant"); +} + +/* the user's SID (malloc'd), or NULL */ +static PSID user_sid(void) +{ + HANDLE tok; + DWORD n = 0; + TOKEN_USER *tu; + PSID sid = NULL; + + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tok)) + return NULL; + GetTokenInformation(tok, TokenUser, NULL, 0, &n); + tu = n ? malloc(n) : NULL; + if (tu && GetTokenInformation(tok, TokenUser, tu, n, &n)) { + DWORD l = GetLengthSid(tu->User.Sid); + sid = malloc(l); + if (sid && !CopySid(l, sid, tu->User.Sid)) { + free(sid); + sid = NULL; + } + } + free(tu); + CloseHandle(tok); + return sid; +} + +/* a request (its length first) asked of Pageant; the answer (its length + first) into rep, which holds AGENT_MAX: 0, or -1 */ +static int pageant_query(const unsigned char *req, unsigned long len, + unsigned char *rep) +{ + HWND w = pageant(); + char name[64]; + SECURITY_ATTRIBUTES sa, *psa = NULL; + PSECURITY_DESCRIPTOR sd = NULL; + PSID sid; + HANDLE fm; + unsigned char *p; + COPYDATASTRUCT cds; + int r = -1; + + if (!w || len > AGENT_MAX) + return -1; + snprintf(name, sizeof name, "PageantRequest%08lx", + (unsigned long)GetCurrentThreadId()); + /* (the mapping owned by the user: Pageant answers only its own) */ + sid = user_sid(); + if (sid) { + sd = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); + if (sd && InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION) && + SetSecurityDescriptorOwner(sd, sid, FALSE)) { + sa.nLength = sizeof sa; + sa.bInheritHandle = TRUE; + sa.lpSecurityDescriptor = sd; + psa = &sa; + } + } + fm = CreateFileMappingA(INVALID_HANDLE_VALUE, psa, PAGE_READWRITE, 0, + AGENT_MAX, name); + if (fm) { + p = MapViewOfFile(fm, FILE_MAP_WRITE, 0, 0, 0); + if (p) { + memcpy(p, req, len); + cds.dwData = PAGEANT_ID; + cds.cbData = (DWORD)strlen(name) + 1; + cds.lpData = name; + if (SendMessageA(w, WM_COPYDATA, 0, (LPARAM)&cds) > 0) { + unsigned long n = be32(p); + if (n <= AGENT_MAX - 4) { + memcpy(rep, p, n + 4); + r = 0; + } + } + UnmapViewOfFile(p); + } + CloseHandle(fm); + } + if (sd) + LocalFree(sd); + free(sid); + return r; +} + +/* n bytes read from the pipe: 0, or -1 */ +static int pipe_read(HANDLE h, unsigned char *b, unsigned long n) +{ + DWORD got; + while (n) { + if (!ReadFile(h, b, n, &got, NULL) || !got) + return -1; + b += got; + n -= got; + } + return 0; +} + +/* a request asked down the agent's pipe; the answer into rep: 0, or -1 */ +static int pipe_query(HANDLE h, const unsigned char *req, unsigned long len, + unsigned char *rep) +{ + DWORD put; + unsigned long n; + + while (len) { + if (!WriteFile(h, req, len, &put, NULL) || !put) + return -1; + req += put; + len -= put; + } + if (pipe_read(h, rep, 4)) + return -1; + n = be32(rep); + if (n > AGENT_MAX - 4) + return -1; + return pipe_read(h, rep + 4, n); +} + +/* n bytes from the socket: 0, or -1 at its end */ +static int sock_read(SOCKET s, unsigned char *b, unsigned long n) +{ + while (n) { + int got = recv(s, (char *)b, (int)n, 0); + if (got <= 0) + return -1; + b += got; + n -= (unsigned long)got; + } + return 0; +} + +/* the thread: libssh's requests to the agent, its answers back */ +static DWORD WINAPI bridge(void *p) +{ + struct dmc_agent *a = p; + unsigned char *req = malloc(AGENT_MAX), *rep = malloc(AGENT_MAX); + static const unsigned char failure[5] = { 0, 0, 0, 1, 5 }; + + while (req && rep) { + unsigned long n; + const unsigned char *out = rep; + int r, outlen; + + if (sock_read(a->sock, req, 4)) + break; + n = be32(req); + if (n > AGENT_MAX - 4 || sock_read(a->sock, req + 4, n)) + break; + r = a->pipe != INVALID_HANDLE_VALUE ? + pipe_query(a->pipe, req, n + 4, rep) : + pageant_query(req, n + 4, rep); + if (r) { + /* (SSH_AGENT_FAILURE: no agent, or it didn't answer) */ + out = failure; + outlen = 5; + } else { + outlen = (int)be32(rep) + 4; + } + if (send(a->sock, (const char *)out, outlen, 0) != outlen) + break; + } + free(req); + free(rep); + closesocket(a->sock); + a->sock = INVALID_SOCKET; + return 0; +} + +/* a pair of connected sockets, by the loopback: 0, or -1 */ +static int sock_pair(SOCKET pair[2]) +{ + SOCKET l = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP), c, a; + struct sockaddr_in at, mine, peer; + int n = sizeof at; + + if (l == INVALID_SOCKET) + return -1; + memset(&at, 0, sizeof at); + at.sin_family = AF_INET; + at.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (bind(l, (struct sockaddr *)&at, sizeof at) || listen(l, 1) || + getsockname(l, (struct sockaddr *)&at, &n)) { + closesocket(l); + return -1; + } + c = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (c == INVALID_SOCKET || connect(c, (struct sockaddr *)&at, sizeof at)) { + closesocket(l); + if (c != INVALID_SOCKET) + closesocket(c); + return -1; + } + n = sizeof peer; + a = accept(l, (struct sockaddr *)&peer, &n); + closesocket(l); + /* (only our own connection: the one from c's own port) */ + n = sizeof mine; + if (a == INVALID_SOCKET || getsockname(c, (struct sockaddr *)&mine, &n) || + peer.sin_port != mine.sin_port || peer.sin_addr.s_addr != mine.sin_addr.s_addr) { + if (a != INVALID_SOCKET) + closesocket(a); + closesocket(c); + return -1; + } + pair[0] = c; + pair[1] = a; + return 0; +} + +/* a named pipe opened, or INVALID_HANDLE_VALUE */ +static HANDLE pipe_open(const char *path) +{ + return CreateFileA(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, + OPEN_EXISTING, 0, NULL); +} + +/* the agent asked for: "" (Pageant, else OpenSSH's), "pageant", or a pipe */ +static int which_pipe(const char *which) +{ + return which && *which && _stricmp(which, "pageant") != 0; +} + +int dmc_agent_reachable(const char *which) +{ + HANDLE h; + + if (!which_pipe(which) && pageant()) + return 1; + if (which && !_stricmp(which, "pageant")) + return 0; + h = pipe_open(which_pipe(which) ? which : OPENSSH_PIPE); + if (h == INVALID_HANDLE_VALUE) + return 0; + CloseHandle(h); + return 1; +} + +int dmc_agent_attach(ssh_session ssh, const char *which, dmc_agent **out) +{ + struct dmc_agent *a; + SOCKET pair[2]; + HANDLE pipe = INVALID_HANDLE_VALUE; + DWORD id; + + *out = NULL; + if (which_pipe(which)) { + pipe = pipe_open(which); + } else if (!pageant()) { + if (which && *which) + return -1; + pipe = pipe_open(OPENSSH_PIPE); + } + if (pipe == INVALID_HANDLE_VALUE && (which_pipe(which) || !pageant())) + return -1; + a = calloc(1, sizeof *a); + if (!a || sock_pair(pair)) { + free(a); + if (pipe != INVALID_HANDLE_VALUE) + CloseHandle(pipe); + return -1; + } + a->sock = pair[1]; + a->pipe = pipe; + a->thread = CreateThread(NULL, 0, bridge, a, 0, &id); + if (!a->thread || ssh_set_agent_socket(ssh, pair[0]) != SSH_OK) { + closesocket(pair[0]); + if (a->thread) { + WaitForSingleObject(a->thread, INFINITE); + CloseHandle(a->thread); + } else { + closesocket(pair[1]); + } + if (pipe != INVALID_HANDLE_VALUE) + CloseHandle(pipe); + free(a); + return -1; + } + *out = a; + return 0; +} + +void dmc_agent_detach(dmc_agent *a) +{ + if (!a) + return; + /* (libssh closed its end with the session: the thread has ended or + ends now) */ + WaitForSingleObject(a->thread, INFINITE); + CloseHandle(a->thread); + if (a->pipe != INVALID_HANDLE_VALUE) + CloseHandle(a->pipe); + free(a); +} + +#else + +int dmc_agent_reachable(const char *which) +{ + const char *path = which && *which ? which : getenv("SSH_AUTH_SOCK"); + char full[sizeof(((struct sockaddr_un *)0)->sun_path)]; + struct sockaddr_un sun; + int fd, ok; + + if (!path || !*path) + return 0; + /* (~ the home folder, as OpenSSH's IdentityAgent has it) */ + if (path[0] == '~' && path[1] == '/' && getenv("HOME")) + snprintf(full, sizeof full, "%s%s", getenv("HOME"), path + 1); + else + snprintf(full, sizeof full, "%s", path); + memset(&sun, 0, sizeof sun); + sun.sun_family = AF_UNIX; + memcpy(sun.sun_path, full, sizeof sun.sun_path - 1); + fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) + return 0; + ok = connect(fd, (struct sockaddr *)&sun, sizeof sun) == 0; + close(fd); + return ok; +} + +int dmc_agent_attach(ssh_session ssh, const char *which, dmc_agent **out) +{ + *out = NULL; + /* (libssh connects to it itself; none given: SSH_AUTH_SOCK) */ + if (which && *which) + return ssh_options_set(ssh, SSH_OPTIONS_IDENTITY_AGENT, which) == SSH_OK ? 0 : -1; + return 0; +} + +void dmc_agent_detach(dmc_agent *a) +{ + (void)a; +} + +#endif diff --git a/ssh/src/agent.h b/ssh/src/agent.h new file mode 100644 index 0000000..f05695d --- /dev/null +++ b/ssh/src/agent.h @@ -0,0 +1,30 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * agent.h - the agent libdmodemssh logs in with (agent.c). + * + * This file and agent.c are the same in D-Modem/gui (ssh/) and + * D-Modem/app (native-ssh/): change both. + */ +#ifndef DMODEM_AGENT_H +#define DMODEM_AGENT_H + +#include + +typedef struct dmc_agent dmc_agent; + +/* whether the agent answers: which is its socket (Linux, macOS; NULL or + "": SSH_AUTH_SOCK's), or on Windows "pageant", a named pipe, or NULL + or "" for Pageant and else OpenSSH's agent */ +int dmc_agent_reachable(const char *which); + +/* the session's agent set to which (as above), before its login by the + agent: 0, or -1 when there's none; *out is freed by dmc_agent_detach() + once the session is */ +int dmc_agent_attach(ssh_session ssh, const char *which, dmc_agent **out); + +/* what dmc_agent_attach() made, freed after its session (NULL: none) */ +void dmc_agent_detach(dmc_agent *a); + +#endif diff --git a/ssh/src/dmodemssh.c b/ssh/src/dmodemssh.c index 4b4a330..09f837c 100644 --- a/ssh/src/dmodemssh.c +++ b/ssh/src/dmodemssh.c @@ -54,6 +54,10 @@ static void nap(int ms) #endif #include "dmodemssh.h" +#include "ppk.h" +#include "agent.h" + +static int import_key(const char *text, const char *passphrase, ssh_key *k); #define MAX_CHANNELS 64 #define MAX_EVENTS 256 @@ -128,6 +132,9 @@ struct dmc_ssh { int qhead, qlen; ev_t cur; /* the event last handed back */ int over; /* EV_CLOSED handed back */ + char *agent_which; /* the "agent" option */ + dmc_agent *agent; /* (Windows: what stands between) */ + int agent_set; /* the agent looked for */ }; /* -- small things -- */ @@ -343,6 +350,8 @@ void dmc_ssh_free(dmc_ssh *s) if (ssh_is_connected(s->ssh)) ssh_disconnect(s->ssh); ssh_free(s->ssh); + dmc_agent_detach(s->agent); + free(s->agent_which); if (s->key) ssh_key_free(s->key); while (s->qlen) { @@ -366,7 +375,8 @@ void dmc_ssh_free(dmc_ssh *s) OpenSSH's config read (a path; "" its own ~/.ssh/config) "knownhosts" the host's key looked up there (a path; "" OpenSSH's) "hostkeys" the host key algorithms, in order (a list with commas) - "timeout" seconds to connect in "compression" "yes" or "no" */ + "timeout" seconds to connect in "compression" "yes" or "no" + "agent" the agent logged in with (see dmc_ssh_agent_reachable) */ int dmc_ssh_option(dmc_ssh *s, const char *name, const char *value) { int r = -1; @@ -390,6 +400,10 @@ int dmc_ssh_option(dmc_ssh *s, const char *name, const char *value) r = ssh_options_set(s->ssh, SSH_OPTIONS_TIMEOUT, &t); } else if (!strcmp(name, "compression")) { r = ssh_options_set(s->ssh, SSH_OPTIONS_COMPRESSION, value); + } else if (!strcmp(name, "agent")) { + free(s->agent_which); + s->agent_which = copy(value); + r = s->agent_which ? 0 : -1; } UNLOCK(&s->lock); return r == 0 ? 0 : -1; @@ -495,6 +509,15 @@ static void login_result(dmc_ssh *s, int r) post(s, DMC_SSH_EV_AUTH, 0, s->methods, why, -1); } +/* the agent found, once, for the logins that use it */ +static void agent_setup(dmc_ssh *s) +{ + if (s->agent_set) + return; + s->agent_set = 1; + dmc_agent_attach(s->ssh, s->agent_which, &s->agent); +} + /* the login chosen, tried again until it's done */ static void login(dmc_ssh *s) { @@ -508,9 +531,11 @@ static void login(dmc_ssh *s) r = ssh_userauth_publickey(s->ssh, NULL, s->key); break; case L_AGENT: + agent_setup(s); r = ssh_userauth_agent(s->ssh, NULL); break; case L_AUTO: + agent_setup(s); r = ssh_userauth_publickey_auto(s->ssh, NULL, NULL); break; case L_INTERACTIVE: @@ -925,14 +950,13 @@ void dmc_ssh_auth_password(dmc_ssh *s, const char *password) UNLOCK(&s->lock); } -/* by a private key's text (OpenSSH's, PEM): 0, or -1 when it can't be +/* by a private key's text (OpenSSH's, PEM or PuTTY's .ppk): 0, or -1 when it can't be read with that passphrase (nothing is tried: answer again) */ int dmc_ssh_auth_key(dmc_ssh *s, const char *key, const char *passphrase) { ssh_key k = NULL; - if (ssh_pki_import_privkey_base64(key, passphrase && *passphrase ? passphrase : NULL, - NULL, NULL, &k) != SSH_OK) + if (import_key(key, passphrase, &k)) return -1; LOCK(&s->lock); if (s->step == S_CHOOSE && !s->login) { @@ -948,7 +972,8 @@ int dmc_ssh_auth_key(dmc_ssh *s, const char *key, const char *passphrase) return 0; } -/* by the system's agent (SSH_AUTH_SOCK) */ +/* by the agent: the "agent" option's, else the system's (SSH_AUTH_SOCK; + on Windows Pageant, else OpenSSH's) */ void dmc_ssh_auth_agent(dmc_ssh *s) { LOCK(&s->lock); @@ -956,6 +981,12 @@ void dmc_ssh_auth_agent(dmc_ssh *s) UNLOCK(&s->lock); } +/* whether the agent answers (see dmodemssh.h): 1 or 0 */ +int dmc_ssh_agent_reachable(const char *agent) +{ + return dmc_agent_reachable(agent); +} + /* as OpenSSH's ssh does: the agent, then ~/.ssh's keys with no passphrase */ void dmc_ssh_auth_auto(dmc_ssh *s) @@ -1201,6 +1232,27 @@ void dmc_ssh_resize(dmc_ssh *s, int channel, int cols, int rows) /* -- keys -- */ +/* a private key's text read: OpenSSH's, PEM or PuTTY's .ppk, with its + passphrase (NULL or "": none): 0, or -1 */ +static int import_key(const char *text, const char *passphrase, ssh_key *k) +{ + const char *pp = passphrase && *passphrase ? passphrase : NULL; + char *openssh = NULL; + int r; + + *k = NULL; + if (!text) + return -1; + if (!dmc_ppk_is(text)) + return ssh_pki_import_privkey_base64(text, pp, NULL, NULL, k) == SSH_OK ? 0 : -1; + if (dmc_ppk_to_openssh(text, pp, &openssh)) + return -1; + r = ssh_pki_import_privkey_base64(openssh, NULL, NULL, NULL, k) == SSH_OK ? 0 : -1; + memset(openssh, 0, strlen(openssh)); + free(openssh); + return r; +} + /* "type base64" of a public key, malloc'd, or NULL */ static char *pub_line(ssh_key k) { @@ -1318,8 +1370,7 @@ int dmc_ssh_key_public(const char *key, const char *passphrase, char **public_ke init_once(); *public_key = NULL; - if (ssh_pki_import_privkey_base64(key, passphrase && *passphrase ? passphrase : NULL, - NULL, NULL, &k) != SSH_OK) + if (import_key(key, passphrase, &k)) return -1; *public_key = pub_line(k); ssh_key_free(k); @@ -1336,14 +1387,20 @@ int dmc_ssh_key_export(const char *key, const char *passphrase, init_once(); *out = NULL; - if (ssh_pki_import_privkey_base64(key, passphrase && *passphrase ? passphrase : NULL, - NULL, NULL, &k) != SSH_OK) + if (import_key(key, passphrase, &k)) return -1; r = export_key(k, new_passphrase, out); ssh_key_free(k); return r; } +/* whether a private key's text needs a passphrase (OpenSSH's, PEM or + PuTTY's .ppk): 1 or 0 */ +int dmc_ssh_key_encrypted(const char *key) +{ + return dmc_key_text_encrypted(key); +} + /* a string these functions gave, freed */ void dmc_ssh_free_string(char *str) { diff --git a/ssh/src/ppk.c b/ssh/src/ppk.c new file mode 100644 index 0000000..b3e6501 --- /dev/null +++ b/ssh/src/ppk.c @@ -0,0 +1,1169 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * ppk.c - PuTTY's private key files (.ppk), versions 2 and 3, read and + * turned into OpenSSH's form, for libssh to load. + * + * A .ppk's public blob and private blob are SSH's own wire form, so the + * key is only rearranged into an OpenSSH private key (unencrypted: it is + * read straight back and never kept). An encrypted one is AES-256-CBC, + * its key from SHA-1 of the passphrase (version 2) or from Argon2 + * (version 3); either way a MAC over the whole file says whether the + * passphrase was right. The hashes and ciphers are here, small and + * plain, so that this reads the same whatever libssh was built on. + * + * This file and ppk.h are the same in D-Modem/gui (ssh/) and D-Modem/app + * (native-ssh/): change both. + */ +#include +#include +#include +#include + +#include "ppk.h" + +/* -- bytes -- */ + +typedef struct { + unsigned char *p; + size_t len, cap; + int bad; +} out_t; + +/* n bytes put at the end of o */ +static void put(out_t *o, const void *b, size_t n) +{ + if (o->bad) + return; + if (o->len + n > o->cap) { + size_t c = o->cap ? o->cap * 2 : 256; + unsigned char *q; + while (c < o->len + n) + c *= 2; + q = realloc(o->p, c); + if (!q) { + o->bad = 1; + return; + } + o->p = q; + o->cap = c; + } + memcpy(o->p + o->len, b, n); + o->len += n; +} + +/* a uint32, big-endian */ +static void put32(out_t *o, uint32_t v) +{ + unsigned char b[4]; + b[0] = (unsigned char)(v >> 24); + b[1] = (unsigned char)(v >> 16); + b[2] = (unsigned char)(v >> 8); + b[3] = (unsigned char)v; + put(o, b, 4); +} + +/* an SSH string: its length, then its bytes */ +static void put_str(out_t *o, const void *b, size_t n) +{ + put32(o, (uint32_t)n); + put(o, b, n); +} + +/* o's bytes wiped and freed */ +static void out_free(out_t *o) +{ + if (o->p) { + memset(o->p, 0, o->cap); + free(o->p); + } + memset(o, 0, sizeof *o); +} + +/* a big-endian uint32 at b */ +static uint32_t get32(const unsigned char *b) +{ + return (uint32_t)b[0] << 24 | (uint32_t)b[1] << 16 | + (uint32_t)b[2] << 8 | b[3]; +} + +/* a little-endian uint32 at b */ +static void le32(unsigned char *b, uint32_t v) +{ + b[0] = (unsigned char)v; + b[1] = (unsigned char)(v >> 8); + b[2] = (unsigned char)(v >> 16); + b[3] = (unsigned char)(v >> 24); +} + +/* an SSH string read from *b (left *n): its bytes and length, or -1 */ +static int get_str(const unsigned char **b, size_t *n, + const unsigned char **s, size_t *len) +{ + uint32_t l; + if (*n < 4) + return -1; + l = get32(*b); + if (l > *n - 4) + return -1; + *s = *b + 4; + *len = l; + *b += 4 + l; + *n -= 4 + l; + return 0; +} + +/* -- SHA-1 and SHA-256 -- */ + +typedef struct { + uint32_t h[8]; + uint64_t n; + unsigned char b[64]; + int big; /* SHA-256 */ +} sha_t; + +#define ROL(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) +#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) + +static const uint32_t K256[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, + 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, + 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, + 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, + 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +}; + +/* one 64-byte block into the state */ +static void sha_block(sha_t *c, const unsigned char *p) +{ + uint32_t w[80], a, b, d, e, f, g, h, cc, t1, t2; + int i; + + for (i = 0; i < 16; i++) + w[i] = get32(p + 4 * i); + a = c->h[0]; b = c->h[1]; cc = c->h[2]; d = c->h[3]; e = c->h[4]; + if (!c->big) { + for (i = 16; i < 80; i++) + w[i] = ROL(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1); + for (i = 0; i < 80; i++) { + if (i < 20) + t1 = ((b & cc) | (~b & d)) + 0x5a827999; + else if (i < 40) + t1 = (b ^ cc ^ d) + 0x6ed9eba1; + else if (i < 60) + t1 = ((b & cc) | (b & d) | (cc & d)) + 0x8f1bbcdc; + else + t1 = (b ^ cc ^ d) + 0xca62c1d6; + t1 += ROL(a, 5) + e + w[i]; + e = d; d = cc; cc = ROL(b, 30); b = a; a = t1; + } + c->h[0] += a; c->h[1] += b; c->h[2] += cc; c->h[3] += d; c->h[4] += e; + return; + } + f = c->h[5]; g = c->h[6]; h = c->h[7]; + for (i = 16; i < 64; i++) { + uint32_t s0 = ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3); + uint32_t s1 = ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + for (i = 0; i < 64; i++) { + t1 = h + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + ((e & f) ^ (~e & g)) + + K256[i] + w[i]; + t2 = (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) ^ (a & cc) ^ (b & cc)); + h = g; g = f; f = e; e = d + t1; d = cc; cc = b; b = a; a = t1 + t2; + } + c->h[0] += a; c->h[1] += b; c->h[2] += cc; c->h[3] += d; + c->h[4] += e; c->h[5] += f; c->h[6] += g; c->h[7] += h; +} + +/* a hash begun: SHA-256 when big, else SHA-1 */ +static void sha_init(sha_t *c, int big) +{ + static const uint32_t i1[5] = { + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 + }; + static const uint32_t i2[8] = { + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + }; + memset(c, 0, sizeof *c); + c->big = big; + memcpy(c->h, big ? i2 : i1, big ? sizeof i2 : sizeof i1); +} + +/* n bytes hashed */ +static void sha_add(sha_t *c, const void *data, size_t n) +{ + const unsigned char *p = data; + while (n) { + size_t at = (size_t)(c->n % 64), k = 64 - at; + if (k > n) + k = n; + memcpy(c->b + at, p, k); + c->n += k; + p += k; + n -= k; + if (c->n % 64 == 0) + sha_block(c, c->b); + } +} + +/* the digest (20 or 32 bytes) into out */ +static void sha_done(sha_t *c, unsigned char *out) +{ + uint64_t bits = c->n * 8; + unsigned char pad = 0x80, z = 0, l[8]; + int i; + + sha_add(c, &pad, 1); + while (c->n % 64 != 56) + sha_add(c, &z, 1); + for (i = 0; i < 8; i++) + l[i] = (unsigned char)(bits >> (56 - 8 * i)); + sha_add(c, l, 8); + for (i = 0; i < (c->big ? 8 : 5); i++) { + out[4 * i] = (unsigned char)(c->h[i] >> 24); + out[4 * i + 1] = (unsigned char)(c->h[i] >> 16); + out[4 * i + 2] = (unsigned char)(c->h[i] >> 8); + out[4 * i + 3] = (unsigned char)c->h[i]; + } + memset(c, 0, sizeof *c); +} + +/* HMAC-SHA-256 (big) or HMAC-SHA-1 of data with key, into out */ +static void hmac(int big, const unsigned char *key, size_t klen, + const unsigned char *data, size_t n, unsigned char *out) +{ + unsigned char k[64], pad[64], inner[32]; + sha_t c; + int i; + + memset(k, 0, sizeof k); + if (klen > 64) { + sha_init(&c, big); + sha_add(&c, key, klen); + sha_done(&c, k); + } else if (klen) { + memcpy(k, key, klen); + } + for (i = 0; i < 64; i++) + pad[i] = k[i] ^ 0x36; + sha_init(&c, big); + sha_add(&c, pad, 64); + sha_add(&c, data, n); + sha_done(&c, inner); + for (i = 0; i < 64; i++) + pad[i] = k[i] ^ 0x5c; + sha_init(&c, big); + sha_add(&c, pad, 64); + sha_add(&c, inner, big ? 32 : 20); + sha_done(&c, out); + memset(k, 0, sizeof k); + memset(pad, 0, sizeof pad); + memset(inner, 0, sizeof inner); +} + +/* -- AES-256, decryption, in CBC -- */ + +typedef struct { + unsigned char sbox[256], inv[256]; + unsigned char rk[240]; /* 15 round keys */ +} aes_t; + +/* x times 2 in GF(2^8) */ +static unsigned char xt(unsigned char x) +{ + return (unsigned char)((x << 1) ^ ((x & 0x80) ? 0x1b : 0)); +} + +/* a times b in GF(2^8) */ +static unsigned char gmul(unsigned char a, unsigned char b) +{ + unsigned char r = 0; + while (b) { + if (b & 1) + r ^= a; + a = xt(a); + b >>= 1; + } + return r; +} + +/* the S-boxes made, and the key's schedule */ +static void aes_init(aes_t *a, const unsigned char *key) +{ + unsigned char p = 1, q = 1, t[4], rcon = 1; + int i, j; + + /* (the S-box from the multiplicative inverse and its affine map) */ + do { + unsigned char x; + p = (unsigned char)(p ^ (p << 1) ^ ((p & 0x80) ? 0x1b : 0)); + q ^= q << 1; + q ^= q << 2; + q ^= q << 4; + if (q & 0x80) + q ^= 0x09; + x = (unsigned char)(q ^ (q << 1 | q >> 7) ^ (q << 2 | q >> 6) ^ + (q << 3 | q >> 5) ^ (q << 4 | q >> 4)); + a->sbox[p] = (unsigned char)(x ^ 0x63); + } while (p != 1); + a->sbox[0] = 0x63; + for (i = 0; i < 256; i++) + a->inv[a->sbox[i]] = (unsigned char)i; + + memcpy(a->rk, key, 32); + for (i = 32; i < 240; i += 4) { + memcpy(t, a->rk + i - 4, 4); + if (i % 32 == 0) { + unsigned char u = t[0]; + t[0] = (unsigned char)(a->sbox[t[1]] ^ rcon); + t[1] = a->sbox[t[2]]; + t[2] = a->sbox[t[3]]; + t[3] = a->sbox[u]; + rcon = xt(rcon); + } else if (i % 32 == 16) { + for (j = 0; j < 4; j++) + t[j] = a->sbox[t[j]]; + } + for (j = 0; j < 4; j++) + a->rk[i + j] = a->rk[i - 32 + j] ^ t[j]; + } +} + +/* one block decrypted in place */ +static void aes_decrypt(const aes_t *a, unsigned char *s) +{ + unsigned char t[16]; + int r, i, c; + + for (i = 0; i < 16; i++) + s[i] ^= a->rk[224 + i]; + for (r = 13; r >= 0; r--) { + /* inverse ShiftRows and SubBytes */ + for (c = 0; c < 4; c++) + for (i = 0; i < 4; i++) + t[4 * ((c + i) % 4) + i] = a->inv[s[4 * c + i]]; + for (i = 0; i < 16; i++) + s[i] = t[i] ^ a->rk[16 * r + i]; + if (r == 0) + break; + /* inverse MixColumns */ + for (c = 0; c < 4; c++) { + unsigned char *m = s + 4 * c, b0 = m[0], b1 = m[1], b2 = m[2], b3 = m[3]; + m[0] = gmul(b0, 14) ^ gmul(b1, 11) ^ gmul(b2, 13) ^ gmul(b3, 9); + m[1] = gmul(b0, 9) ^ gmul(b1, 14) ^ gmul(b2, 11) ^ gmul(b3, 13); + m[2] = gmul(b0, 13) ^ gmul(b1, 9) ^ gmul(b2, 14) ^ gmul(b3, 11); + m[3] = gmul(b0, 11) ^ gmul(b1, 13) ^ gmul(b2, 9) ^ gmul(b3, 14); + } + } + memset(t, 0, sizeof t); +} + +/* n bytes (whole blocks) decrypted in place, AES-256-CBC */ +static void cbc_decrypt(const unsigned char *key, const unsigned char *iv, + unsigned char *p, size_t n) +{ + aes_t *a = malloc(sizeof *a); + unsigned char prev[16], cur[16]; + size_t i; + int j; + + if (!a) + return; + aes_init(a, key); + memcpy(prev, iv, 16); + for (i = 0; i + 16 <= n; i += 16) { + memcpy(cur, p + i, 16); + aes_decrypt(a, p + i); + for (j = 0; j < 16; j++) + p[i + j] ^= prev[j]; + memcpy(prev, cur, 16); + } + memset(a, 0, sizeof *a); + free(a); +} + +/* -- BLAKE2b and Argon2 (RFC 9106) -- */ + +typedef struct { + uint64_t h[8], t; + unsigned char b[128]; + size_t at, outlen; +} b2_t; + +static const uint64_t B2IV[8] = { + 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, + 0xa54ff53a5f1d36f1ULL, 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, + 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL +}; + +static const unsigned char SIGMA[12][16] = { + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } +}; + +#define ROR64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) + +/* a little-endian uint64 at p */ +static uint64_t ld64(const unsigned char *p) +{ + uint64_t v = 0; + int i; + for (i = 7; i >= 0; i--) + v = v << 8 | p[i]; + return v; +} + +/* v put little-endian at p */ +static void st64(unsigned char *p, uint64_t v) +{ + int i; + for (i = 0; i < 8; i++) + p[i] = (unsigned char)(v >> (8 * i)); +} + +/* BLAKE2b's compression of the buffered block (last: the final one) */ +static void b2_compress(b2_t *c, int last) +{ + uint64_t v[16], m[16]; + int i, r; + + for (i = 0; i < 16; i++) + m[i] = ld64(c->b + 8 * i); + for (i = 0; i < 8; i++) { + v[i] = c->h[i]; + v[i + 8] = B2IV[i]; + } + v[12] ^= c->t; + if (last) + v[14] = ~v[14]; +#define B2G(a, b, cc, d, x, y) do { \ + v[a] = v[a] + v[b] + (x); v[d] = ROR64(v[d] ^ v[a], 32); \ + v[cc] = v[cc] + v[d]; v[b] = ROR64(v[b] ^ v[cc], 24); \ + v[a] = v[a] + v[b] + (y); v[d] = ROR64(v[d] ^ v[a], 16); \ + v[cc] = v[cc] + v[d]; v[b] = ROR64(v[b] ^ v[cc], 63); } while (0) + for (r = 0; r < 12; r++) { + const unsigned char *s = SIGMA[r]; + B2G(0, 4, 8, 12, m[s[0]], m[s[1]]); + B2G(1, 5, 9, 13, m[s[2]], m[s[3]]); + B2G(2, 6, 10, 14, m[s[4]], m[s[5]]); + B2G(3, 7, 11, 15, m[s[6]], m[s[7]]); + B2G(0, 5, 10, 15, m[s[8]], m[s[9]]); + B2G(1, 6, 11, 12, m[s[10]], m[s[11]]); + B2G(2, 7, 8, 13, m[s[12]], m[s[13]]); + B2G(3, 4, 9, 14, m[s[14]], m[s[15]]); + } +#undef B2G + for (i = 0; i < 8; i++) + c->h[i] ^= v[i] ^ v[i + 8]; +} + +/* BLAKE2b begun, outlen bytes (1 to 64) wanted, no key */ +static void b2_init(b2_t *c, size_t outlen) +{ + memset(c, 0, sizeof *c); + memcpy(c->h, B2IV, sizeof c->h); + c->h[0] ^= 0x01010000ULL ^ (uint64_t)outlen; + c->outlen = outlen; +} + +/* n bytes hashed */ +static void b2_add(b2_t *c, const void *data, size_t n) +{ + const unsigned char *p = data; + while (n) { + size_t k; + if (c->at == 128) { + c->t += 128; + b2_compress(c, 0); + c->at = 0; + } + k = 128 - c->at; + if (k > n) + k = n; + memcpy(c->b + c->at, p, k); + c->at += k; + p += k; + n -= k; + } +} + +/* the digest into out */ +static void b2_done(b2_t *c, unsigned char *out) +{ + unsigned char h[64]; + int i; + + c->t += c->at; + memset(c->b + c->at, 0, 128 - c->at); + b2_compress(c, 1); + for (i = 0; i < 8; i++) + st64(h + 8 * i, c->h[i]); + memcpy(out, h, c->outlen); + memset(c, 0, sizeof *c); +} + +/* Argon2's H': a hash of any length (n) of in, into out */ +static void hprime(unsigned char *out, uint32_t n, const unsigned char *in, + size_t inlen) +{ + unsigned char len[4], v[64]; + b2_t c; + + le32(len, n); + if (n <= 64) { + b2_init(&c, n); + b2_add(&c, len, 4); + b2_add(&c, in, inlen); + b2_done(&c, out); + return; + } + b2_init(&c, 64); + b2_add(&c, len, 4); + b2_add(&c, in, inlen); + b2_done(&c, v); + memcpy(out, v, 32); + out += 32; + n -= 32; + while (n > 64) { + b2_init(&c, 64); + b2_add(&c, v, 64); + b2_done(&c, v); + memcpy(out, v, 32); + out += 32; + n -= 32; + } + b2_init(&c, n); + b2_add(&c, v, 64); + b2_done(&c, out); + memset(v, 0, sizeof v); +} + +typedef struct { uint64_t v[128]; } block_t; + +/* the permutation's quarter: BLAKE2b's G, its sums with Argon2's products */ +#define FBLA(x, y) ((x) + (y) + 2 * ((x) & 0xffffffffULL) * ((y) & 0xffffffffULL)) +#define AG(a, b, c, d) do { \ + a = FBLA(a, b); d = ROR64(d ^ a, 32); c = FBLA(c, d); b = ROR64(b ^ c, 24); \ + a = FBLA(a, b); d = ROR64(d ^ a, 16); c = FBLA(c, d); b = ROR64(b ^ c, 63); } while (0) + +/* Argon2's P over 16 words, given by their indexes in the block */ +static void perm(uint64_t *v, const int *i) +{ + AG(v[i[0]], v[i[4]], v[i[8]], v[i[12]]); + AG(v[i[1]], v[i[5]], v[i[9]], v[i[13]]); + AG(v[i[2]], v[i[6]], v[i[10]], v[i[14]]); + AG(v[i[3]], v[i[7]], v[i[11]], v[i[15]]); + AG(v[i[0]], v[i[5]], v[i[10]], v[i[15]]); + AG(v[i[1]], v[i[6]], v[i[11]], v[i[12]]); + AG(v[i[2]], v[i[7]], v[i[8]], v[i[13]]); + AG(v[i[3]], v[i[4]], v[i[9]], v[i[14]]); +} + +/* Argon2's G: next = P(prev ^ ref) ^ prev ^ ref (^ next's old self when xor) */ +static void fill(const block_t *prev, const block_t *ref, block_t *next, int xor_) +{ + block_t r, t; + int i, j, idx[16]; + + for (i = 0; i < 128; i++) + r.v[i] = prev->v[i] ^ ref->v[i]; + t = r; + if (xor_) + for (i = 0; i < 128; i++) + t.v[i] ^= next->v[i]; + /* rows: 16 words each */ + for (i = 0; i < 8; i++) { + for (j = 0; j < 16; j++) + idx[j] = 16 * i + j; + perm(r.v, idx); + } + /* columns: pairs of words down the rows */ + for (i = 0; i < 8; i++) { + for (j = 0; j < 8; j++) { + idx[2 * j] = 2 * i + 16 * j; + idx[2 * j + 1] = 2 * i + 16 * j + 1; + } + perm(r.v, idx); + } + for (i = 0; i < 128; i++) + next->v[i] = t.v[i] ^ r.v[i]; +} + +/* a 1024-byte block from its bytes */ +static void block_load(block_t *b, const unsigned char *p) +{ + int i; + for (i = 0; i < 128; i++) + b->v[i] = ld64(p + 8 * i); +} + +/* Argon2 (type 0 d, 1 i, 2 id; version 0x13) of pwd and salt into out + (outlen bytes): 0, or -1 */ +int dmc_argon2(int type, uint32_t mem_kib, uint32_t passes, uint32_t lanes, + const unsigned char *pwd, size_t pwdlen, + const unsigned char *salt, size_t saltlen, + const unsigned char *secret, size_t secretlen, + const unsigned char *ad, size_t adlen, + unsigned char *out, uint32_t outlen) +{ + unsigned char h0[72], w[4], blk[1024]; + uint32_t m, q, seg, pass, slice, lane, i; + block_t *B, addr, input, zero; + b2_t c; + + if (lanes < 1 || lanes > 0xffffff || passes < 1 || outlen < 4 || + mem_kib < 8 * lanes || mem_kib > 4 * 1024 * 1024 || type < 0 || type > 2) + return -1; + m = mem_kib / (4 * lanes) * 4 * lanes; + q = m / lanes; + seg = q / 4; + B = calloc(m, sizeof *B); + if (!B) + return -1; + + b2_init(&c, 64); +#define W32(v) do { le32(w, (uint32_t)(v)); b2_add(&c, w, 4); } while (0) + W32(lanes); W32(outlen); W32(mem_kib); W32(passes); W32(0x13); W32(type); + W32(pwdlen); b2_add(&c, pwd, pwdlen); + W32(saltlen); b2_add(&c, salt, saltlen); + W32(secretlen); b2_add(&c, secret, secretlen); + W32(adlen); b2_add(&c, ad, adlen); +#undef W32 + b2_done(&c, h0); + + for (lane = 0; lane < lanes; lane++) { + le32(h0 + 64, 0); + le32(h0 + 68, lane); + hprime(blk, 1024, h0, 72); + block_load(&B[lane * q], blk); + le32(h0 + 64, 1); + hprime(blk, 1024, h0, 72); + block_load(&B[lane * q + 1], blk); + } + + memset(&zero, 0, sizeof zero); + for (pass = 0; pass < passes; pass++) { + for (slice = 0; slice < 4; slice++) { + for (lane = 0; lane < lanes; lane++) { + int indep = type == 1 || (type == 2 && pass == 0 && slice < 2); + uint32_t start = pass == 0 && slice == 0 ? 2 : 0; + uint32_t cur = lane * q + slice * seg + start; + + if (indep) { + memset(&input, 0, sizeof input); + input.v[0] = pass; + input.v[1] = lane; + input.v[2] = slice; + input.v[3] = m; + input.v[4] = passes; + input.v[5] = (uint64_t)type; + } + for (i = start; i < seg; i++, cur++) { + uint32_t prev = cur % q ? cur - 1 : cur + q - 1, ref; + uint64_t rnd, rel, area, startpos, ref_lane, x; + + if (indep) { + /* (a new block of addresses each 128) */ + if (i % 128 == 0 || (i == 2 && start == 2)) { + input.v[6]++; + fill(&zero, &input, &addr, 0); + fill(&zero, &addr, &addr, 0); + } + rnd = addr.v[i % 128]; + } else { + rnd = B[prev].v[0]; + } + ref_lane = (rnd >> 32) % lanes; + if (pass == 0 && slice == 0) + ref_lane = lane; + if (pass == 0) { + if (ref_lane == lane) + area = slice * seg + i - 1; + else + area = slice * seg - (i == 0 ? 1 : 0); + } else { + if (ref_lane == lane) + area = q - seg + i - 1; + else + area = q - seg - (i == 0 ? 1 : 0); + } + x = rnd & 0xffffffffULL; + x = x * x >> 32; + rel = area - 1 - (area * x >> 32); + startpos = pass != 0 && slice != 3 ? (uint64_t)(slice + 1) * seg : 0; + ref = (uint32_t)((startpos + rel) % q); + fill(&B[prev], &B[ref_lane * q + ref], &B[cur], pass != 0); + } + } + } + } + + addr = B[q - 1]; + for (lane = 1; lane < lanes; lane++) + for (i = 0; i < 128; i++) + addr.v[i] ^= B[lane * q + q - 1].v[i]; + for (i = 0; i < 128; i++) + st64(blk + 8 * i, addr.v[i]); + hprime(out, outlen, blk, 1024); + + memset(blk, 0, sizeof blk); + memset(h0, 0, sizeof h0); + memset(&addr, 0, sizeof addr); + memset(B, 0, (size_t)m * sizeof *B); + free(B); + return 0; +} + +/* -- the file -- */ + +/* a header's value (to the line's end) in text, or NULL */ +static const char *header(const char *text, const char *name, size_t *len) +{ + size_t n = strlen(name); + const char *p = text; + + while (p && *p) { + if (!strncmp(p, name, n) && p[n] == ':' && p[n + 1] == ' ') { + const char *v = p + n + 2; + *len = strcspn(v, "\r\n"); + while (*len && (v[*len - 1] == ' ' || v[*len - 1] == '\t')) + (*len)--; + return v; + } + p = strchr(p, '\n'); + if (p) + p++; + } + return NULL; +} + +/* a header's value as a number, or -1 */ +static long header_num(const char *text, const char *name) +{ + size_t n; + const char *v = header(text, name, &n); + long r = 0; + size_t i; + + if (!v || !n || n > 9) + return -1; + for (i = 0; i < n; i++) { + if (v[i] < '0' || v[i] > '9') + return -1; + r = r * 10 + (v[i] - '0'); + } + return r; +} + +/* base64's value of ch, or -1 */ +static int b64v(int ch) +{ + if (ch >= 'A' && ch <= 'Z') + return ch - 'A'; + if (ch >= 'a' && ch <= 'z') + return ch - 'a' + 26; + if (ch >= '0' && ch <= '9') + return ch - '0' + 52; + if (ch == '+') + return 62; + if (ch == '/') + return 63; + return -1; +} + +/* the lines-many lines of base64 after header name, decoded into o: + 0, or -1 */ +static int block(const char *text, const char *name, out_t *o) +{ + size_t n; + const char *p = header(text, name, &n); + long lines = header_num(text, name); + unsigned acc = 0; + int bits = 0; + + if (!p || lines < 0 || lines > 10000) + return -1; + p = strchr(p, '\n'); + while (lines-- > 0) { + if (!p) + return -1; + p++; + for (; *p && *p != '\n'; p++) { + int v; + if (*p == '\r' || *p == '=') + continue; + v = b64v((unsigned char)*p); + if (v < 0) + return -1; + acc = acc << 6 | (unsigned)v; + bits += 6; + if (bits >= 8) { + unsigned char b; + bits -= 8; + b = (unsigned char)(acc >> bits); + put(o, &b, 1); + } + } + } + acc = 0; + return o->bad ? -1 : 0; +} + +/* a hex header's bytes into out (at most max): their count, or -1 */ +static int hex_header(const char *text, const char *name, unsigned char *out, int max) +{ + size_t n, i; + const char *v = header(text, name, &n); + + if (!v || n % 2 || (int)(n / 2) > max) + return -1; + for (i = 0; i < n; i += 2) { + int d[2], k; + for (k = 0; k < 2; k++) { + char ch = v[i + (size_t)k]; + d[k] = ch >= '0' && ch <= '9' ? ch - '0' : + ch >= 'a' && ch <= 'f' ? ch - 'a' + 10 : + ch >= 'A' && ch <= 'F' ? ch - 'A' + 10 : -1; + if (d[k] < 0) + return -1; + } + out[i / 2] = (unsigned char)(d[0] << 4 | d[1]); + } + return (int)(n / 2); +} + +/* whether text is a .ppk */ +int dmc_ppk_is(const char *text) +{ + while (text && (*text == ' ' || *text == '\t' || *text == '\r' || *text == '\n')) + text++; + return text && !strncmp(text, "PuTTY-User-Key-File-", 20); +} + +/* the private key rearranged as OpenSSH's (its private section's key + fields) from PuTTY's public and private blobs: 0, or -1 */ +static int key_fields(out_t *o, const unsigned char *pub, size_t publen, + const unsigned char *priv, size_t privlen) +{ + const unsigned char *type, *a, *b, *c, *d, *e, *f; + size_t tl, al, bl, cl, dl, el, fl; + + if (get_str(&pub, &publen, &type, &tl)) + return -1; + put_str(o, type, tl); + if (tl == 7 && !memcmp(type, "ssh-rsa", 7)) { + /* PuTTY's e, n and d, p, q, iqmp; OpenSSH's n, e, d, iqmp, p, q */ + if (get_str(&pub, &publen, &a, &al) || get_str(&pub, &publen, &b, &bl) || + get_str(&priv, &privlen, &c, &cl) || get_str(&priv, &privlen, &d, &dl) || + get_str(&priv, &privlen, &e, &el) || get_str(&priv, &privlen, &f, &fl)) + return -1; + put_str(o, b, bl); + put_str(o, a, al); + put_str(o, c, cl); + put_str(o, f, fl); + put_str(o, d, dl); + put_str(o, e, el); + } else if (tl > 11 && !memcmp(type, "ecdsa-sha2-", 11)) { + /* the curve, the point; the private scalar */ + if (get_str(&pub, &publen, &a, &al) || get_str(&pub, &publen, &b, &bl) || + get_str(&priv, &privlen, &c, &cl)) + return -1; + put_str(o, a, al); + put_str(o, b, bl); + put_str(o, c, cl); + } else if (tl == 11 && !memcmp(type, "ssh-ed25519", 11)) { + /* the public 32 bytes; the private seed (32), and OpenSSH's + seed and public together */ + unsigned char both[64]; + if (get_str(&pub, &publen, &a, &al) || al != 32 || + get_str(&priv, &privlen, &c, &cl) || cl > 33 || cl < 1) + return -1; + /* (an mpint's leading zero, if PuTTY wrote one) */ + if (cl == 33) { + if (c[0]) + return -1; + c++; + cl--; + } + if (cl != 32) + return -1; + put_str(o, a, 32); + memcpy(both, c, 32); + memcpy(both + 32, a, 32); + put_str(o, both, 64); + memset(both, 0, sizeof both); + } else { + return -1; + } + return 0; +} + +/* OpenSSH's private key file, unencrypted, of the key in out (PEM text) */ +static char *openssh_text(const unsigned char *pub, size_t publen, + const unsigned char *priv, size_t privlen, + const char *comment, size_t commentlen) +{ + static const char b64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + out_t sec = { 0 }, all = { 0 }; + unsigned char pad = 1; + char *text = NULL, *t; + size_t i, n, col = 0; + + put32(&sec, 0x44536d21); + put32(&sec, 0x44536d21); + if (key_fields(&sec, pub, publen, priv, privlen)) { + out_free(&sec); + return NULL; + } + put_str(&sec, comment, commentlen); + while (sec.len % 8) + put(&sec, &pad, 1), pad++; + + put(&all, "openssh-key-v1", 15); + put_str(&all, "none", 4); + put_str(&all, "none", 4); + put_str(&all, "", 0); + put32(&all, 1); + put_str(&all, pub, publen); + put_str(&all, sec.p, sec.len); + out_free(&sec); + if (all.bad) { + out_free(&all); + return NULL; + } + + n = (all.len + 2) / 3 * 4; + text = malloc(n + n / 70 + 128); + if (text) { + t = text + sprintf(text, "-----BEGIN OPENSSH PRIVATE KEY-----\n"); + for (i = 0; i < all.len; i += 3) { + uint32_t v = (uint32_t)all.p[i] << 16; + if (i + 1 < all.len) + v |= (uint32_t)all.p[i + 1] << 8; + if (i + 2 < all.len) + v |= all.p[i + 2]; + *t++ = b64[v >> 18 & 63]; + *t++ = b64[v >> 12 & 63]; + *t++ = i + 1 < all.len ? b64[v >> 6 & 63] : '='; + *t++ = i + 2 < all.len ? b64[v & 63] : '='; + col += 4; + if (col == 68) { + *t++ = '\n'; + col = 0; + } + } + if (col) + *t++ = '\n'; + strcpy(t, "-----END OPENSSH PRIVATE KEY-----\n"); + } + out_free(&all); + return text; +} + +/* a .ppk (version 2 or 3) as OpenSSH's private key text, unencrypted + (malloc'd; wipe it before it's freed): 0; -1 it can't be read; -2 it + needs a passphrase, or the one given is wrong */ +int dmc_ppk_to_openssh(const char *text, const char *passphrase, char **out) +{ + out_t pub = { 0 }, priv = { 0 }, mac = { 0 }; + const char *first, *alg, *enc, *comment; + size_t alglen, enclen, commentlen, pl; + unsigned char want[32], got[32], keys[80], salt[64]; + int version, encrypted, r = -1, i, maclen; + + *out = NULL; + while (*text == ' ' || *text == '\t' || *text == '\r' || *text == '\n') + text++; + if (!strncmp(text, "PuTTY-User-Key-File-2:", 22)) + version = 2; + else if (!strncmp(text, "PuTTY-User-Key-File-3:", 22)) + version = 3; + else + return -1; + first = text + 23; + alg = first; + alglen = strcspn(alg, "\r\n"); + while (alglen && alg[alglen - 1] == ' ') + alglen--; + enc = header(text, "Encryption", &enclen); + comment = header(text, "Comment", &commentlen); + if (!comment) { + comment = ""; + commentlen = 0; + } + if (!enc) + return -1; + if (enclen == 4 && !memcmp(enc, "none", 4)) + encrypted = 0; + else if (enclen == 10 && !memcmp(enc, "aes256-cbc", 10)) + encrypted = 1; + else + return -1; + maclen = hex_header(text, "Private-MAC", want, sizeof want); + if (maclen != (version == 3 ? 32 : 20)) + return -1; + if (block(text, "Public-Lines", &pub) || block(text, "Private-Lines", &priv)) + goto done; + if (encrypted && (!passphrase || !*passphrase)) { + r = -2; + goto done; + } + pl = encrypted ? strlen(passphrase) : 0; + memset(keys, 0, sizeof keys); + + if (version == 3) { + if (encrypted) { + size_t kn; + const char *kdf = header(text, "Key-Derivation", &kn); + long mem = header_num(text, "Argon2-Memory"); + long passes = header_num(text, "Argon2-Passes"); + long par = header_num(text, "Argon2-Parallelism"); + int saltlen = hex_header(text, "Argon2-Salt", salt, sizeof salt); + int type; + if (!kdf || mem < 0 || passes < 0 || par < 0 || saltlen < 0) + goto done; + if (kn == 8 && !memcmp(kdf, "Argon2id", 8)) + type = 2; + else if (kn == 7 && !memcmp(kdf, "Argon2i", 7)) + type = 1; + else if (kn == 7 && !memcmp(kdf, "Argon2d", 7)) + type = 0; + else + goto done; + if (dmc_argon2(type, (uint32_t)mem, (uint32_t)passes, (uint32_t)par, + (const unsigned char *)passphrase, pl, + salt, (size_t)saltlen, NULL, 0, NULL, 0, keys, 80)) + goto done; + } + } else { + sha_t c; + static const unsigned char z[4] = { 0, 0, 0, 0 }, one[4] = { 0, 0, 0, 1 }; + unsigned char h[20]; + if (encrypted) { + sha_init(&c, 0); + sha_add(&c, z, 4); + sha_add(&c, passphrase, pl); + sha_done(&c, h); + memcpy(keys, h, 20); + sha_init(&c, 0); + sha_add(&c, one, 4); + sha_add(&c, passphrase, pl); + sha_done(&c, h); + memcpy(keys + 20, h, 12); + } + /* (the MAC's key: SHA-1 of a phrase and the passphrase) */ + sha_init(&c, 0); + sha_add(&c, "putty-private-key-file-mac-key", 30); + if (encrypted) + sha_add(&c, passphrase, pl); + sha_done(&c, keys + 48); + memset(h, 0, sizeof h); + } + + if (encrypted) { + if (priv.len % 16) + goto done; + { + /* (version 2's IV: zeros) */ + static const unsigned char zero_iv[16] = { 0 }; + cbc_decrypt(keys, version == 3 ? keys + 32 : zero_iv, priv.p, priv.len); + } + } + + put_str(&mac, alg, alglen); + put_str(&mac, enc, enclen); + put_str(&mac, comment, commentlen); + put_str(&mac, pub.p, pub.len); + put_str(&mac, priv.p, priv.len); + if (mac.bad) + goto done; + hmac(version == 3, keys + 48, version == 3 ? (encrypted ? 32 : 0) : 20, + mac.p, mac.len, got); + { + unsigned char diff = 0; + for (i = 0; i < maclen; i++) + diff |= (unsigned char)(got[i] ^ want[i]); + if (diff) { + r = encrypted ? -2 : -1; + goto done; + } + } + *out = openssh_text(pub.p, pub.len, priv.p, priv.len, comment, commentlen); + r = *out ? 0 : -1; +done: + memset(keys, 0, sizeof keys); + memset(got, 0, sizeof got); + out_free(&pub); + out_free(&priv); + out_free(&mac); + return r; +} + +/* whether a private key's text is encrypted (a passphrase needed): + PuTTY's .ppk, OpenSSH's own, or PEM's */ +int dmc_key_text_encrypted(const char *text) +{ + static const char begin[] = "-----BEGIN OPENSSH PRIVATE KEY-----"; + const char *p; + size_t n; + out_t o = { 0 }; + int r = 0; + + if (!text) + return 0; + if (dmc_ppk_is(text)) { + p = header(text, "Encryption", &n); + return p && !(n == 4 && !memcmp(p, "none", 4)); + } + if (strstr(text, "Proc-Type: 4,ENCRYPTED") || + strstr(text, "-----BEGIN ENCRYPTED PRIVATE KEY-----")) + return 1; + p = strstr(text, begin); + if (!p) + return 0; + /* "openssh-key-v1", then the cipher's name: "none" or another */ + p = strchr(p + sizeof begin - 1, '\n'); + if (p) { + unsigned acc = 0; + int bits = 0; + for (p++; *p && o.len < 64 && *p != '-'; p++) { + int v = b64v((unsigned char)*p); + if (v < 0) + continue; + acc = acc << 6 | (unsigned)v; + bits += 6; + if (bits >= 8) { + unsigned char b; + bits -= 8; + b = (unsigned char)(acc >> bits); + put(&o, &b, 1); + } + } + if (o.len >= 23 && !memcmp(o.p, "openssh-key-v1", 15)) { + uint32_t l = get32(o.p + 15); + r = !(l == 4 && !memcmp(o.p + 19, "none", 4)); + } + } + out_free(&o); + return r; +} diff --git a/ssh/src/ppk.h b/ssh/src/ppk.h new file mode 100644 index 0000000..faf1834 --- /dev/null +++ b/ssh/src/ppk.h @@ -0,0 +1,38 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * ppk.h - PuTTY's private key files (.ppk) read, for libdmodemssh. + * + * This file and ppk.c are the same in D-Modem/gui (ssh/) and D-Modem/app + * (native-ssh/): change both. + */ +#ifndef DMODEM_PPK_H +#define DMODEM_PPK_H + +#include +#include + +/* whether text is a .ppk (PuTTY-User-Key-File-...) */ +int dmc_ppk_is(const char *text); + +/* a .ppk (version 2 or 3) as OpenSSH's private key text, unencrypted + (malloc'd; wipe it before it's freed): 0; -1 it can't be read; -2 it + needs a passphrase, or the one given is wrong */ +int dmc_ppk_to_openssh(const char *text, const char *passphrase, char **out); + +/* whether a private key's text is encrypted (a passphrase needed): + PuTTY's .ppk, OpenSSH's own, or PEM's */ +int dmc_key_text_encrypted(const char *text); + +/* Argon2 (type 0 Argon2d, 1 Argon2i, 2 Argon2id; version 0x13) of pwd + and salt, with an optional secret and associated data, into out + (outlen bytes): 0, or -1 */ +int dmc_argon2(int type, uint32_t mem_kib, uint32_t passes, uint32_t lanes, + const unsigned char *pwd, size_t pwdlen, + const unsigned char *salt, size_t saltlen, + const unsigned char *secret, size_t secretlen, + const unsigned char *ad, size_t adlen, + unsigned char *out, uint32_t outlen); + +#endif diff --git a/ssh/test/dmodemssh_test.c b/ssh/test/dmodemssh_test.c index 66c9b03..a1597c4 100644 --- a/ssh/test/dmodemssh_test.c +++ b/ssh/test/dmodemssh_test.c @@ -24,6 +24,7 @@ #endif #include "dmodemssh.h" +#include "ppk.h" static int failures; @@ -50,7 +51,9 @@ static void test_keys(void) CHECK(pub2 && !strcmp(pub, pub2)); CHECK(dmc_ssh_fingerprint(pub, fp, sizeof fp) == 0); CHECK(!strncmp(fp, "SHA256:", 7) && strlen(fp) == 50); + CHECK(dmc_ssh_key_encrypted(priv) == 0); CHECK(dmc_ssh_key_export(priv, NULL, "sesame", &enc) == 0); + CHECK(enc && dmc_ssh_key_encrypted(enc) == 1); dmc_ssh_free_string(pub2); pub2 = NULL; CHECK(enc && dmc_ssh_key_public(enc, "wrong", &pub2) < 0); @@ -67,6 +70,110 @@ static void test_keys(void) } } +/* PuTTY's keys (made by PuTTYgen 0.81, for these tests only): version 3 + with Argon2id, version 2, and one with no passphrase */ +static const char ppk_v3[] = + "PuTTY-User-Key-File-3: ssh-ed25519\n" + "Encryption: aes256-cbc\n" + "Comment: dmodem test\n" + "Public-Lines: 2\n" + "AAAAC3NzaC1lZDI1NTE5AAAAIGaq1WGILuZaAUWi0Oj7RUOfHb2IdFdPFkpBvgmT\n" + "FNDY\n" + "Key-Derivation: Argon2id\n" + "Argon2-Memory: 1024\n" + "Argon2-Passes: 2\n" + "Argon2-Parallelism: 1\n" + "Argon2-Salt: 33f9ba393a4951fb796e2fbc41661b75\n" + "Private-Lines: 1\n" + "hM2XhuziydvZHlIY7Kv3LLpDLxZpyZRk0FUEdY9QffTXspVHngnD3kDEYfdjBqsL\n" + "Private-MAC: 335d60073336e5ef6af9660f801a38edc92fc04f52d7042d9a598a180787d6b6\n"; +static const char ppk_v3_pub[] = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGaq1WGILuZaAUWi0Oj7RUOfHb2IdFdPFkpBvgmTFNDY"; +static const char ppk_v2[] = + "PuTTY-User-Key-File-2: ecdsa-sha2-nistp256\n" + "Encryption: aes256-cbc\n" + "Comment: dmodem test\n" + "Public-Lines: 3\n" + "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBP8cgz/JGtuf\n" + "pTcbwYWaC5rRxEtd94wTxyYeZmpibjtHZs0xe5R/U0/gsjoYAZBqLsVAuw/m7PEH\n" + "owsid94C7vQ=\n" + "Private-Lines: 1\n" + "tXUEPEl6phjZUecV/5HDrEjp64lDdujz0/2vShR6B1ayoimLGtze26jtLPWczTOn\n" + "Private-MAC: 9ef17c9fa24457b60b4cc20f2f8e07925a9ec090\n"; +static const char ppk_v2_pub[] = + "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBP8cgz/JGtufpTcbwYWaC5rRxEtd94wTxyYeZmpibjtHZs0xe5R/U0/gsjoYAZBqLsVAuw/m7PEHowsid94C7vQ="; +static const char ppk_plain[] = + "PuTTY-User-Key-File-3: ssh-ed25519\n" + "Encryption: none\n" + "Comment: dmodem test\n" + "Public-Lines: 2\n" + "AAAAC3NzaC1lZDI1NTE5AAAAIJuvvweC5NNfYlxOXbIN7mOvU3s9uMr4WbpWTlzY\n" + "bOOZ\n" + "Private-Lines: 1\n" + "AAAAID9RN2flxRLWco4mJwxMJJQUNSmAEZ4ltTevZi+TSuxO\n" + "Private-MAC: c31121241789d04ca3e7e68d528a5c46a4309276510c45cdc6b4e0f501746f2f\n"; +static const char ppk_plain_pub[] = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJuvvweC5NNfYlxOXbIN7mOvU3s9uMr4WbpWTlzYbOOZ"; + +/* Argon2d, Argon2i and Argon2id: RFC 9106's test vectors */ +static void test_argon2(void) +{ + static const char *want[3] = { + "512b391b6f1162975371d30919734294f868e3be3984f3c1a13a4db9fabe4acb", + "c814d9d1dc7f37aa13f0d77f2494bda1c8de6b016dd388d29952a4c4672b6ce8", + "0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659", + }; + unsigned char pwd[32], salt[16], secret[8], ad[12], out[32]; + char hex[65]; + int t, i; + + memset(pwd, 1, sizeof pwd); + memset(salt, 2, sizeof salt); + memset(secret, 3, sizeof secret); + memset(ad, 4, sizeof ad); + for (t = 0; t < 3; t++) { + CHECK(dmc_argon2(t, 32, 3, 4, pwd, sizeof pwd, salt, sizeof salt, + secret, sizeof secret, ad, sizeof ad, out, 32) == 0); + for (i = 0; i < 32; i++) + snprintf(hex + 2 * i, 3, "%02x", out[i]); + CHECK(!strcmp(hex, want[t])); + } +} + +/* PuTTY's .ppk read: its public line, a wrong passphrase refused, and + OpenSSH's form written from it */ +static void test_ppk(void) +{ + static const struct { const char *ppk, *pub, *pass; } k[] = { + { ppk_v3, ppk_v3_pub, "sesame" }, + { ppk_v2, ppk_v2_pub, "sesame" }, + { ppk_plain, ppk_plain_pub, NULL }, + }; + int i; + + for (i = 0; i < 3; i++) { + char *pub = NULL, *out = NULL, *pub2 = NULL; + + CHECK(dmc_ssh_key_encrypted(k[i].ppk) == (k[i].pass != NULL)); + CHECK(dmc_ssh_key_public(k[i].ppk, k[i].pass, &pub) == 0); + CHECK(pub && !strcmp(pub, k[i].pub)); + if (k[i].pass) { + char *no = NULL; + CHECK(dmc_ssh_key_public(k[i].ppk, "wrong", &no) < 0); + CHECK(dmc_ssh_key_public(k[i].ppk, NULL, &no) < 0); + } + CHECK(dmc_ssh_key_export(k[i].ppk, k[i].pass, "new", &out) == 0); + CHECK(out && strstr(out, "BEGIN OPENSSH PRIVATE KEY") != NULL); + CHECK(out && dmc_ssh_key_encrypted(out) == 1); + CHECK(out && dmc_ssh_key_public(out, "new", &pub2) == 0); + CHECK(pub2 && !strcmp(pub2, k[i].pub)); + dmc_ssh_free_string(pub); + dmc_ssh_free_string(pub2); + dmc_ssh_free_string(out); + } + CHECK(dmc_ssh_key_encrypted("not a key") == 0); +} + static const char *host, *user, *password; static int port; @@ -261,6 +368,171 @@ static void test_key_login(const char *file) dmc_ssh_free(s); } +/* a login by the agent named (a socket, or on Windows Pageant or a + pipe) */ +static void test_agent_login(const char *agent) +{ + dmc_ssh *s; + dmc_ssh_event ev; + + CHECK(dmc_ssh_agent_reachable(agent) == 1); + s = dmc_ssh_new(host, port, user); + CHECK(dmc_ssh_option(s, "agent", agent) == 0); + CHECK(next(s, &ev) == DMC_SSH_EV_HOSTKEY); + dmc_ssh_trust(s, 1, 0); + CHECK(next(s, &ev) == DMC_SSH_EV_AUTH && (ev.value & DMC_SSH_AUTH_PUBLICKEY)); + dmc_ssh_auth_agent(s); + CHECK(next(s, &ev) == DMC_SSH_EV_READY); + dmc_ssh_free(s); +} + +#ifdef _WIN32 +/* + * A stand-in for Pageant: its window, answering by WM_COPYDATA as it + * does, with no keys (each request counted), so that the way to it is + * tested where PuTTY isn't. + */ +static int pageant_requests; + +/* the stand-in's window: a request in the named mapping, answered there */ +static LRESULT CALLBACK pageant_proc(HWND w, UINT msg, WPARAM wp, LPARAM lp) +{ + if (msg == WM_COPYDATA) { + COPYDATASTRUCT *cds = (COPYDATASTRUCT *)lp; + HANDLE fm; + unsigned char *p; + + if (cds->dwData != 0x804e50baUL) + return 0; + fm = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, (const char *)cds->lpData); + if (!fm) + return 0; + p = MapViewOfFile(fm, FILE_MAP_WRITE, 0, 0, 0); + if (p) { + pageant_requests++; + if (p[4] == 11) { + /* SSH2_AGENT_IDENTITIES_ANSWER, none */ + static const unsigned char none[9] = { 0, 0, 0, 5, 12, 0, 0, 0, 0 }; + memcpy(p, none, sizeof none); + } else { + /* SSH_AGENT_FAILURE */ + static const unsigned char fail[5] = { 0, 0, 0, 1, 5 }; + memcpy(p, fail, sizeof fail); + } + UnmapViewOfFile(p); + } + CloseHandle(fm); + return 1; + } + return DefWindowProcA(w, msg, wp, lp); +} + +/* the stand-in's thread: its window and their messages */ +static DWORD WINAPI pageant_run(void *ready) +{ + WNDCLASSA wc; + MSG m; + + memset(&wc, 0, sizeof wc); + wc.lpfnWndProc = pageant_proc; + wc.hInstance = GetModuleHandleA(NULL); + wc.lpszClassName = "Pageant"; + RegisterClassA(&wc); + CreateWindowA("Pageant", "Pageant", 0, 0, 0, 0, 0, NULL, NULL, wc.hInstance, NULL); + SetEvent((HANDLE)ready); + while (GetMessageA(&m, NULL, 0, 0) > 0) + DispatchMessageA(&m); + return 0; +} + +/* Pageant found, asked, and its "no keys" taken as a login refused */ +static void test_pageant(void) +{ + HANDLE ready = CreateEventA(NULL, TRUE, FALSE, NULL); + DWORD id; + dmc_ssh *s; + dmc_ssh_event ev; + + if (FindWindowA("Pageant", "Pageant")) { + printf("Pageant is running: its stand-in not tested\n"); + return; + } + CHECK(dmc_ssh_agent_reachable("pageant") == 0); + CreateThread(NULL, 0, pageant_run, ready, 0, &id); + WaitForSingleObject(ready, 5000); + if (!FindWindowA("Pageant", "Pageant")) { + printf("no window could be made: Pageant not tested\n"); + return; + } + CHECK(dmc_ssh_agent_reachable("pageant") == 1); + CHECK(dmc_ssh_agent_reachable("") == 1); + if (!host) + return; + s = dmc_ssh_new(host, port, user); + CHECK(dmc_ssh_option(s, "agent", "pageant") == 0); + CHECK(next(s, &ev) == DMC_SSH_EV_HOSTKEY); + dmc_ssh_trust(s, 1, 0); + CHECK(next(s, &ev) == DMC_SSH_EV_AUTH); + dmc_ssh_auth_agent(s); + CHECK(next(s, &ev) == DMC_SSH_EV_AUTH); + CHECK(pageant_requests >= 1); + dmc_ssh_free(s); +} +/* a stand-in for OpenSSH's agent on its named pipe: no keys, as above */ +#define TEST_PIPE "\\\\.\\pipe\\dmodem-test-agent" +static int pipe_requests; + +/* the pipe's one connection served, until it closes */ +static DWORD WINAPI pipe_run(void *h) +{ + unsigned char req[1024]; + DWORD n; + + if (!ConnectNamedPipe((HANDLE)h, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) + return 0; + while (ReadFile((HANDLE)h, req, sizeof req, &n, NULL) && n >= 5) { + static const unsigned char none[9] = { 0, 0, 0, 5, 12, 0, 0, 0, 0 }; + static const unsigned char fail[5] = { 0, 0, 0, 1, 5 }; + pipe_requests++; + if (req[4] == 11) + WriteFile((HANDLE)h, none, sizeof none, &n, NULL); + else + WriteFile((HANDLE)h, fail, sizeof fail, &n, NULL); + } + CloseHandle((HANDLE)h); + return 0; +} + +/* an agent on a named pipe found and asked */ +static void test_agent_pipe(void) +{ + HANDLE h; + DWORD id; + dmc_ssh *s; + dmc_ssh_event ev; + + CHECK(dmc_ssh_agent_reachable(TEST_PIPE) == 0); + if (!host) + return; + h = CreateNamedPipeA(TEST_PIPE, PIPE_ACCESS_DUPLEX, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, + 4096, 4096, 0, NULL); + CHECK(h != INVALID_HANDLE_VALUE); + if (h == INVALID_HANDLE_VALUE) + return; + CreateThread(NULL, 0, pipe_run, h, 0, &id); + s = dmc_ssh_new(host, port, user); + CHECK(dmc_ssh_option(s, "agent", TEST_PIPE) == 0); + CHECK(next(s, &ev) == DMC_SSH_EV_HOSTKEY); + dmc_ssh_trust(s, 1, 0); + CHECK(next(s, &ev) == DMC_SSH_EV_AUTH); + dmc_ssh_auth_agent(s); + CHECK(next(s, &ev) == DMC_SSH_EV_AUTH); + CHECK(pipe_requests >= 1); + dmc_ssh_free(s); +} +#endif + /* the logins and channels against DMODEM_SSH_TEST's sshd */ static void test_live(const char *spec) { @@ -269,6 +541,7 @@ static void test_live(const char *spec) int i; dmc_ssh *s; dmc_ssh_event ev; + /* (a key's file, OpenSSH's; a .ppk; an agent's socket) */ const char *key = getenv("DMODEM_SSH_TEST_KEY"); snprintf(buf, sizeof buf, "%s", spec); @@ -334,6 +607,11 @@ static void test_live(const char *spec) if (key) test_key_login(key); + if (getenv("DMODEM_SSH_TEST_PPK")) + test_key_login(getenv("DMODEM_SSH_TEST_PPK")); + if (getenv("DMODEM_SSH_TEST_AGENT")) + test_agent_login(getenv("DMODEM_SSH_TEST_AGENT")); + CHECK(dmc_ssh_agent_reachable("/nonexistent/agent.sock") == 0); } /* the key tests, then the live ones when DMODEM_SSH_TEST names a server */ @@ -346,10 +624,16 @@ int main(void) WSAStartup(MAKEWORD(2, 2), &w); #endif test_keys(); + test_argon2(); + test_ppk(); if (spec) test_live(spec); else printf("DMODEM_SSH_TEST is not set: no login tested\n"); +#ifdef _WIN32 + test_pageant(); + test_agent_pipe(); +#endif if (failures) { fprintf(stderr, "%d failed\n", failures); return 1;