SSH engine: PuTTY's .ppk keys read natively, an agent chosen (Pageant and OpenSSH's on Windows), as in D-Modem/gui

This commit is contained in:
Claude committed 2026-11-12 15:46:58 +00:00
1 parent 48bf218a07
commit d9f3f8a731
10 files changed
+2020 -19

No files matched your search

+13 -3
View File
@@ -240,15 +240,25 @@ jobs:
run: |
cmake -S native-ssh -B build-ssh -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build-ssh
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"
puttygen "$RUNNER_TEMP/key.ppk" -O public-openssh -o "$RUNNER_TEMP/ppk.pub"
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
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_KEY="$RUNNER_TEMP/key" build-ssh/dmodemssh_test
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
swift test --package-path ios/DModemSSH
env:
DMODEM_SSH_TEST: 127.0.0.1:2222:dmtest:Sesame-42
+4 -1
View File
@@ -167,7 +167,10 @@
SHA-256). Android loads it through JNI (`NativeSsh.kt`), iOS as the
`DModemSSHNative` XCFramework (`ios/DModemSSH`). Ed25519, ECDSA and RSA
keys, the host's and the user's; password, keyboard-interactive and
key logins; on Android the app's own keys (made here, or OpenSSH's,
key logins, the key OpenSSH's, PEM or PuTTY's .ppk (read by the engine
itself, `native-ssh/src/ppk.c`); an agent's keys (on the desktops an
ssh-agent's socket, or on Windows Pageant or OpenSSH's agent:
`native-ssh/src/agent.c`); on Android the app's own keys (made here, or OpenSSH's,
PEM or PuTTY's .ppk imported), port forwards (-L, -R, -D: SOCKS 4/4a/5)
and agent forwarding (-A, each signature asked of the user when the
entry says). Its tests run against a real sshd: `native-ssh/test`,
+3 -1
View File
@@ -14,7 +14,7 @@ project(dmodemssh LANGUAGES C)
include(${CMAKE_CURRENT_LIST_DIR}/cmake/BundledLibssh.cmake)
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)
set_target_properties(dmodemssh PROPERTIES POSITION_INDEPENDENT_CODE ON)
@@ -49,5 +49,7 @@ if(NOT ANDROID AND NOT CMAKE_SYSTEM_NAME STREQUAL "iOS")
enable_testing()
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)
endif()
+16 -5
View File
@@ -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,
+397
View File
@@ -0,0 +1,397 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#else
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#endif
#include <libssh/libssh.h>
#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
+30
View File
@@ -0,0 +1,30 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* 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 <libssh/libssh.h>
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
+66 -9
View File
@@ -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)
{
+1169
View File
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* 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 <stddef.h>
#include <stdint.h>
/* 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
+284
View File
@@ -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;