Enables OpenSSH WebAuthn SK signature compatibility

Updates WebAuthn signature handling to advertise and produce
the correct OpenSSH WebAuthn SK signature algorithm and format,
ensuring interoperability with sshd's verification process.
Removes unused file-based logging for cleaner output and
applies a required protocol patch at startup.
This commit is contained in:
bincxz committed 2025-12-13 23:32:27 +08:00
1 parent ef2b113472
commit 04e720dcd6
4 files changed
+177 -17

No files matched your search

+25 -11
View File
@@ -7,7 +7,6 @@
* OpenSSH's webauthn-sk-ecdsa-sha2-nistp256@openssh.com signature format.
*/
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const { BaseAgent } = require("ssh2/lib/agent.js");
@@ -26,6 +25,12 @@ const log = (msg, data) => {
const DUMMY_ED25519_PUB =
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB netcatty-agent-dummy";
// OpenSSH PROTOCOL.u2f defines a distinct signature algorithm for WebAuthn-backed ECDSA SK signatures.
// Public keys remain `sk-ecdsa-sha2-nistp256@openssh.com`, but signatures use:
// `webauthn-sk-ecdsa-sha2-nistp256@openssh.com`
const SK_ECDSA_ALGO = "sk-ecdsa-sha2-nistp256@openssh.com";
const WEBAUTHN_SK_ECDSA_ALGO = "webauthn-sk-ecdsa-sha2-nistp256@openssh.com";
function base64UrlToBuffer(b64url) {
const b64 = String(b64url).replace(/-/g, "+").replace(/_/g, "/");
const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
@@ -219,10 +224,14 @@ class NetcattyAgent extends BaseAgent {
const { publicKey, label } = opts.meta || {};
if (!publicKey) throw new Error("Missing publicKey");
const { type: pubKeyType, blob: pubKeyBlob } = parseOpenSshKeyLine(publicKey);
// Keep the original key type for identity (publickey check).
// The server matches sk-ecdsa-sha2-nistp256@openssh.com in authorized_keys.
if (pubKeyType !== SK_ECDSA_ALGO) {
throw new Error(`Unsupported WebAuthn publicKey type: ${pubKeyType}`);
}
// We must advertise the WebAuthn signature algorithm so sshd can verify using
// authenticatorData + SHA256(clientDataJSON) (OpenSSH PROTOCOL.u2f "webauthn signatures").
// The *public key blob* remains sk-ecdsa..., so authorized_keys still matches.
this._key = buildWebAuthnIdentityKey({
algoType: pubKeyType,
algoType: WEBAUTHN_SK_ECDSA_ALGO,
pubKeyBlob,
comment: label || "",
});
@@ -268,7 +277,7 @@ class NetcattyAgent extends BaseAgent {
}
if (this._mode === "webauthn") {
log("WebAuthn sign started", { keySource: this._meta?.keySource });
log("WebAuthn sign started", { keySource: this._meta?.keySource, algo: this._key?.type });
const { credentialId, rpId, userVerification } = this._meta || {};
if (!credentialId) throw new Error("Missing credentialId for WebAuthn auth");
if (!rpId) throw new Error("Missing rpId for WebAuthn auth");
@@ -277,24 +286,29 @@ class NetcattyAgent extends BaseAgent {
}
log("Calling requestWebAuthnAssertion", { rpId, hasCredentialId: !!credentialId });
const challenge = crypto.createHash("sha256").update(data).digest();
const assertion = await requestWebAuthnAssertion(this._webContents, {
credentialId,
rpId,
challenge: bufferToBase64Url(challenge),
// OpenSSH's WebAuthn SK verification expects the WebAuthn challenge to be the
// base64url-encoded SSH signature data (session_id || userauth request).
// See OpenSSH `ssh-ecdsa-sk.c` (webauthn_check_prepare_hash).
challenge: bufferToBase64Url(data),
userVerification: userVerification || "preferred",
keySource: this._meta?.keySource,
});
log("WebAuthn assertion received", { hasAssertion: !!assertion });
const origin = typeof assertion?.origin === "string" ? assertion.origin : "";
const authenticatorData = base64UrlToBuffer(assertion?.authenticatorData || "");
const clientDataJSON = base64UrlToBuffer(assertion?.clientDataJSON || "");
const signatureDer = base64UrlToBuffer(assertion?.signature || "");
// Use FIDO2 signature format (compatible with OpenSSH 8.2+)
// The WebAuthn API returns the same cryptographic signature as FIDO2,
// we just need to format it correctly without the WebAuthn-specific fields.
return buildFido2SkEcdsaSignatureBlob({
// WebAuthn signatures must include origin + clientDataJSON for sshd to verify
// against the challenge (OpenSSH PROTOCOL.u2f "webauthn signatures").
return buildWebAuthnSkEcdsaSignatureBlob({
origin,
authenticatorData,
clientDataJSON,
signatureDer,
});
}
+149
View File
@@ -0,0 +1,149 @@
/**
* Patch ssh2's Protocol.authPK to support OpenSSH Security Key (sk-*) signature layouts.
*
* ssh2 assumes the SSH "signature" field is always:
* string sig_alg, string sig_blob
*
* OpenSSH sk-ecdsa/webauthn-sk signatures include extra fields after the
* inner signature string, e.g.:
* string sig_alg, string ecdsa_sig, byte flags, uint32 counter, ...
*
* Without this patch, sshd will reject with "parse packet: invalid format".
*/
const Protocol = require("ssh2/lib/protocol/Protocol.js");
const { parseKey } = require("ssh2/lib/protocol/keyParser.js");
const { MESSAGE } = require("ssh2/lib/protocol/constants.js");
const { sendPacket, writeUInt32BE } = require("ssh2/lib/protocol/utils.js");
const PATCH_GUARD = "__netcattySsh2SkAuthPkPatchApplied";
if (!globalThis[PATCH_GUARD]) {
globalThis[PATCH_GUARD] = true;
const originalAuthPK = Protocol.prototype.authPK;
// Only patch algorithms we intentionally support (OpenSSH PROTOCOL.u2f).
const SK_SIG_ALGOS = new Set([
"sk-ecdsa-sha2-nistp256@openssh.com",
"webauthn-sk-ecdsa-sha2-nistp256@openssh.com",
]);
Protocol.prototype.authPK = function authPK(username, pubKey, keyAlgo, cbSign) {
if (this._server) throw new Error("Client-only method called in server mode");
if (typeof keyAlgo === "function") {
cbSign = keyAlgo;
keyAlgo = undefined;
}
// Preserve original behavior for the "check" packet or non-SK algorithms.
if (!cbSign) return originalAuthPK.call(this, username, pubKey, keyAlgo);
const parsedKey = parseKey(pubKey);
if (parsedKey instanceof Error) throw new Error("Invalid key");
const keyType = parsedKey.type;
const pubKeyBlob = parsedKey.getPublicSSH();
if (!keyAlgo) keyAlgo = keyType;
if (!SK_SIG_ALGOS.has(keyAlgo)) {
return originalAuthPK.call(this, username, parsedKey, keyAlgo, cbSign);
}
const userLen = Buffer.byteLength(username);
const algoLen = Buffer.byteLength(keyAlgo);
const pubKeyLen = pubKeyBlob.length;
const sessionID = this._kex.sessionID;
const sesLen = sessionID.length;
// Data to be signed = string(sessionID) || USERAUTH_REQUEST fields (up to pubkey).
const signData = Buffer.allocUnsafe(
4 + sesLen
+ 1 + 4 + userLen
+ 4 + 14
+ 4 + 9
+ 1
+ 4 + algoLen
+ 4 + pubKeyLen
);
let p = 0;
writeUInt32BE(signData, sesLen, p);
signData.set(sessionID, p += 4);
p += sesLen;
signData[p] = MESSAGE.USERAUTH_REQUEST;
writeUInt32BE(signData, userLen, ++p);
signData.utf8Write(username, p += 4, userLen);
writeUInt32BE(signData, 14, p += userLen);
signData.utf8Write("ssh-connection", p += 4, 14);
writeUInt32BE(signData, 9, p += 14);
signData.utf8Write("publickey", p += 4, 9);
signData[p += 9] = 1;
writeUInt32BE(signData, algoLen, ++p);
signData.utf8Write(keyAlgo, p += 4, algoLen);
writeUInt32BE(signData, pubKeyLen, p += algoLen);
signData.set(pubKeyBlob, p += 4);
cbSign(signData, (signatureTail) => {
// For OpenSSH SK signature algorithms, the signature field payload is:
// string sig_alg || <tail>
// where <tail> begins with string(ecdsa_signature) and includes extra fields
// (flags/counter/origin/clientData/extensions).
if (!Buffer.isBuffer(signatureTail)) signatureTail = Buffer.from(signatureTail);
const tailLen = signatureTail.length;
const sigPayloadLen = 4 + algoLen + tailLen;
const payloadLen =
1 + 4 + userLen
+ 4 + 14
+ 4 + 9
+ 1
+ 4 + algoLen
+ 4 + pubKeyLen
+ 4 + sigPayloadLen;
p = this._packetRW.write.allocStart;
const packet = this._packetRW.write.alloc(payloadLen);
packet[p] = MESSAGE.USERAUTH_REQUEST;
writeUInt32BE(packet, userLen, ++p);
packet.utf8Write(username, p += 4, userLen);
writeUInt32BE(packet, 14, p += userLen);
packet.utf8Write("ssh-connection", p += 4, 14);
writeUInt32BE(packet, 9, p += 14);
packet.utf8Write("publickey", p += 4, 9);
packet[p += 9] = 1;
writeUInt32BE(packet, algoLen, ++p);
packet.utf8Write(keyAlgo, p += 4, algoLen);
writeUInt32BE(packet, pubKeyLen, p += algoLen);
packet.set(pubKeyBlob, p += 4);
// signature: string(sig_payload)
writeUInt32BE(packet, sigPayloadLen, p += pubKeyLen);
// sig_payload: string(sig_alg) || signatureTail
writeUInt32BE(packet, algoLen, p += 4);
packet.utf8Write(keyAlgo, p += 4, algoLen);
packet.set(signatureTail, p += algoLen);
this._authsQueue.push("publickey");
this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (publickey)");
sendPacket(this, this._packetRW.write.finalize(packet));
});
};
}
-6
View File
@@ -6,14 +6,8 @@
*/
const { getAssertionInBrowser } = require("./webauthnBrowserBridge.cjs");
const fs = require("node:fs");
const path = require("node:path");
// Simple file logger for debugging WebAuthn issues
const logFile = path.join(require("os").tmpdir(), "netcatty-webauthn.log");
const log = (msg, data) => {
const line = `[${new Date().toISOString()}] ${msg} ${data ? JSON.stringify(data) : ""}\n`;
try { fs.appendFileSync(logFile, line); } catch {}
console.log("[WebAuthn]", msg, data || "");
};
+3
View File
@@ -61,6 +61,9 @@ protocol.registerSchemesAsPrivileged([
}
]);
// Apply ssh2 protocol patch needed for OpenSSH sk-* signature layouts.
require("./bridges/ssh2SkPatch.cjs");
// Import bridge modules
const sshBridge = require("./bridges/sshBridge.cjs");
const sftpBridge = require("./bridges/sftpBridge.cjs");