diff --git a/components/SFTPModal.tsx b/components/SFTPModal.tsx index a91d7e2e9..9c7579b80 100644 --- a/components/SFTPModal.tsx +++ b/components/SFTPModal.tsx @@ -229,6 +229,15 @@ interface SFTPModalProps { port?: number; password?: string; privateKey?: string; + certificate?: string; + passphrase?: string; + // WebAuthn-backed keys (optional) + publicKey?: string; + credentialId?: string; + rpId?: string; + userVerification?: 'required' | 'preferred' | 'discouraged'; + keyId?: string; + keySource?: 'generated' | 'imported' | 'biometric' | 'fido2'; }; open: boolean; onClose: () => void; @@ -319,6 +328,14 @@ const SFTPModal: React.FC = ({ port: credentials.port || 22, password: credentials.password, privateKey: credentials.privateKey, + certificate: credentials.certificate, + passphrase: credentials.passphrase, + publicKey: credentials.publicKey, + credentialId: credentials.credentialId, + rpId: credentials.rpId, + userVerification: credentials.userVerification, + keyId: credentials.keyId, + keySource: credentials.keySource, }); sftpIdRef.current = sftpId; return sftpId; @@ -329,6 +346,14 @@ const SFTPModal: React.FC = ({ credentials.port, credentials.password, credentials.privateKey, + credentials.certificate, + credentials.passphrase, + credentials.publicKey, + credentials.credentialId, + credentials.rpId, + credentials.userVerification, + credentials.keyId, + credentials.keySource, openSftp, ]); diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 33fb04d7f..692153e32 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -194,10 +194,14 @@ const TerminalComponent: React.FC = ({ const [needsAuth, setNeedsAuth] = useState(false); const [authRetryMessage, setAuthRetryMessage] = useState(null); // Error message for auth retry const [authUsername, setAuthUsername] = useState(host.username || "root"); - const [authMethod, setAuthMethod] = useState<"password" | "key">("password"); + const [authMethod, setAuthMethod] = useState< + "password" | "key" | "certificate" + >("password"); const [authPassword, setAuthPassword] = useState(""); const [authKeyId, setAuthKeyId] = useState(null); + const [authPassphrase, setAuthPassphrase] = useState(""); const [showAuthPassword, setShowAuthPassword] = useState(false); + const [showAuthPassphrase, setShowAuthPassphrase] = useState(false); const [saveCredentials, setSaveCredentials] = useState(true); useEffect(() => { @@ -212,9 +216,11 @@ const TerminalComponent: React.FC = ({ // Pending connection credentials (set after auth dialog submit) const pendingAuthRef = useRef<{ + authMethod: "password" | "key"; username: string; password?: string; keyId?: string; + passphrase?: string; } | null>(null); // Known host verification state @@ -1078,6 +1084,7 @@ const TerminalComponent: React.FC = ({ // Always include password if available for fallback authentication const effectivePassword = pendingAuth?.password || host.password; const effectiveKeyId = pendingAuth?.keyId || host.identityFileId; + const effectivePassphrase = pendingAuth?.passphrase; const key = effectiveKeyId ? keys.find((k) => k.id === effectiveKeyId) @@ -1105,6 +1112,15 @@ const TerminalComponent: React.FC = ({ username: jumpHost.username || "root", password: jumpHost.password, // Always include for fallback privateKey: jumpKey?.privateKey, + certificate: jumpKey?.certificate, + passphrase: jumpKey?.passphrase, + publicKey: jumpKey?.publicKey, + credentialId: jumpKey?.credentialId, + rpId: jumpKey?.rpId, + keyId: jumpKey?.id, + keySource: jumpKey?.source, + userVerification: + jumpKey?.source === "biometric" ? "required" : "preferred", label: jumpHost.label, }; }); @@ -1186,6 +1202,7 @@ const TerminalComponent: React.FC = ({ keySource: key?.source, userVerification: key?.source === "biometric" ? "required" : "preferred", + passphrase: effectivePassphrase || key?.passphrase, agentForwarding: host.agentForwarding, cols: term.cols, rows: term.rows, @@ -1616,9 +1633,11 @@ const TerminalComponent: React.FC = ({ // Set pending auth credentials pendingAuthRef.current = { + authMethod, username: authUsername, password: authMethod === "password" ? authPassword : undefined, keyId: authMethod === "key" ? (authKeyId ?? undefined) : undefined, + passphrase: authMethod === "key" ? authPassphrase || undefined : undefined, }; // Save credentials to host if requested @@ -1628,8 +1647,7 @@ const TerminalComponent: React.FC = ({ username: authUsername, authMethod: authMethod, password: authMethod === "password" ? authPassword : undefined, - identityFileId: - authMethod === "key" ? (authKeyId ?? undefined) : undefined, + identityFileId: authMethod === "key" ? (authKeyId ?? undefined) : undefined, }; onUpdateHost(updatedHost); } @@ -1948,6 +1966,10 @@ const TerminalComponent: React.FC = ({ setAuthPassword, authKeyId, setAuthKeyId, + authPassphrase, + setAuthPassphrase, + showAuthPassphrase, + setShowAuthPassphrase, showAuthPassword, setShowAuthPassword, authRetryMessage, @@ -1981,6 +2003,31 @@ const TerminalComponent: React.FC = ({ privateKey: host.identityFileId ? keys.find((k) => k.id === host.identityFileId)?.privateKey : undefined, + certificate: host.identityFileId + ? keys.find((k) => k.id === host.identityFileId)?.certificate + : undefined, + passphrase: host.identityFileId + ? keys.find((k) => k.id === host.identityFileId)?.passphrase + : undefined, + publicKey: host.identityFileId + ? keys.find((k) => k.id === host.identityFileId)?.publicKey + : undefined, + credentialId: host.identityFileId + ? keys.find((k) => k.id === host.identityFileId)?.credentialId + : undefined, + rpId: host.identityFileId + ? keys.find((k) => k.id === host.identityFileId)?.rpId + : undefined, + keyId: host.identityFileId, + keySource: host.identityFileId + ? keys.find((k) => k.id === host.identityFileId)?.source + : undefined, + userVerification: host.identityFileId + ? keys.find((k) => k.id === host.identityFileId)?.source === + "biometric" + ? "required" + : "preferred" + : undefined, }} open={showSFTP && status === "connected"} onClose={() => setShowSFTP(false)} diff --git a/components/terminal/TerminalAuthDialog.tsx b/components/terminal/TerminalAuthDialog.tsx index 86f46e7c4..070e69f48 100644 --- a/components/terminal/TerminalAuthDialog.tsx +++ b/components/terminal/TerminalAuthDialog.tsx @@ -2,7 +2,7 @@ * Terminal Authentication Dialog * Displays auth form with password/key selection for SSH connection */ -import { AlertCircle,ChevronDown,Eye,EyeOff,Key,Lock } from 'lucide-react'; +import { AlertCircle, BadgeCheck, ChevronDown, Eye, EyeOff, Fingerprint, Key, Lock } from 'lucide-react'; import React from 'react'; import { cn } from '../../lib/utils'; import { SSHKey } from '../../types'; @@ -11,15 +11,21 @@ import { Input } from '../ui/input'; import { Label } from '../ui/label'; import { Popover,PopoverContent,PopoverTrigger } from '../ui/popover'; +export type TerminalAuthMethod = 'password' | 'key'; + export interface TerminalAuthDialogProps { - authMethod: 'password' | 'key'; - setAuthMethod: (method: 'password' | 'key') => void; + authMethod: TerminalAuthMethod; + setAuthMethod: (method: TerminalAuthMethod) => void; authUsername: string; setAuthUsername: (username: string) => void; authPassword: string; setAuthPassword: (password: string) => void; authKeyId: string | null; setAuthKeyId: (keyId: string | null) => void; + authPassphrase: string; + setAuthPassphrase: (passphrase: string) => void; + showAuthPassphrase: boolean; + setShowAuthPassphrase: (show: boolean) => void; showAuthPassword: boolean; setShowAuthPassword: (show: boolean) => void; authRetryMessage: string | null; @@ -39,6 +45,10 @@ export const TerminalAuthDialog: React.FC = ({ setAuthPassword, authKeyId, setAuthKeyId, + authPassphrase, + setAuthPassphrase, + showAuthPassphrase, + setShowAuthPassphrase, showAuthPassword, setShowAuthPassword, authRetryMessage, @@ -54,6 +64,13 @@ export const TerminalAuthDialog: React.FC = ({ } }; + // Show all keys (both regular keys and certificates) when in key mode + const selectableKeys = keys.filter((k) => k.category === 'key' || Boolean(k.certificate?.trim())); + + const [keyDropdownOpen, setKeyDropdownOpen] = React.useState(false); + + const selectedKey = authKeyId ? keys.find((k) => k.id === authKeyId) : null; + return ( <> {/* Auth method tabs */} @@ -80,7 +97,7 @@ export const TerminalAuthDialog: React.FC = ({ onClick={() => setAuthMethod('key')} > - Public Key + SSH Key @@ -127,40 +144,124 @@ export const TerminalAuthDialog: React.FC = ({ ) : ( -
- - {keys.filter(k => k.category === 'key').length === 0 ? ( -
- No keys available. Add keys in the Keychain section. -
- ) : ( -
- {keys.filter(k => k.category === 'key').map((key) => ( - + + +
+ {selectableKeys.map((key) => ( + + ))}
-
-
{key.label}
-
Type {key.type}
-
- - ))} +
+ + )} +
+ +
+ +
+ setAuthPassphrase(e.target.value)} + placeholder="Optional passphrase for the selected private key" + className="pr-10" + disabled={!selectedKey} + onKeyDown={handleKeyDown} + /> +
- )} -
+
+ )} diff --git a/electron/bridges/netcattyAgent.cjs b/electron/bridges/netcattyAgent.cjs index 87c3295ca..5379f4025 100644 --- a/electron/bridges/netcattyAgent.cjs +++ b/electron/bridges/netcattyAgent.cjs @@ -210,6 +210,7 @@ class NetcattyAgent extends BaseAgent { this._webContents = opts.webContents; this._key = null; this._meta = opts.meta; + this._advertisedType = null; if (this._mode === "certificate") { const { certificate, label } = opts.meta || {}; @@ -220,6 +221,7 @@ class NetcattyAgent extends BaseAgent { certBlob, comment: label || "", }); + this._advertisedType = certType; } else if (this._mode === "webauthn") { const { publicKey, label } = opts.meta || {}; if (!publicKey) throw new Error("Missing publicKey"); @@ -235,6 +237,7 @@ class NetcattyAgent extends BaseAgent { pubKeyBlob, comment: label || "", }); + this._advertisedType = WEBAUTHN_SK_ECDSA_ALGO; } else { throw new Error(`Unknown agent mode: ${opts.mode}`); } @@ -246,7 +249,12 @@ class NetcattyAgent extends BaseAgent { } sign(_pubKey, data, options, cb) { - log("sign called", { mode: this._mode, dataLength: data?.length }); + log("sign called", { + mode: this._mode, + dataLength: data?.length, + advertisedType: this._advertisedType, + options: options, + }); if (typeof options === "function") { cb = options; options = undefined; @@ -263,16 +271,33 @@ class NetcattyAgent extends BaseAgent { const key = Array.isArray(parsed) ? parsed[0] : parsed; const baseType = normalizeBaseTypeForConversion(key.type); - const hash = options && options.hash ? options.hash : undefined; + let hash = options && options.hash ? options.hash : undefined; + + // ssh2 does not currently infer hash algorithms for certificate types. + // For RSA cert algorithms, select the hash based on the *advertised* algorithm + // (e.g. rsa-sha2-256-cert-v01@openssh.com), not the private key type (ssh-rsa). + if (!hash) { + const advertisedBaseType = normalizeBaseTypeForConversion( + this._advertisedType || this._key?.type + ); + if (advertisedBaseType === "rsa-sha2-256") hash = "sha256"; + else if (advertisedBaseType === "rsa-sha2-512") hash = "sha512"; + else if (advertisedBaseType === "ssh-rsa") hash = "sha1"; + } + let sig = key.sign(data, hash); if (sig instanceof Error) throw sig; - // For ECDSA/DSS, convertSignature expects base (non-cert) key types. - if (baseType === "ssh-dss" || /^ecdsa-sha2-nistp\d+$/i.test(baseType)) { - sig = convertSignature(sig, baseType); - if (!sig) throw new Error("Failed to convert signature"); - } + log("certificate sign result", { + privateKeyType: key.type, + baseType, + advertisedType: this._advertisedType, + hash, + sigLength: sig?.length, + }); + // Return raw signature - ssh2SkPatch will handle format conversion + // for ECDSA/DSS types and proper signature field construction. return Buffer.from(sig); } diff --git a/electron/bridges/ssh2SkPatch.cjs b/electron/bridges/ssh2SkPatch.cjs index 361ea521d..7fbfbcea0 100644 --- a/electron/bridges/ssh2SkPatch.cjs +++ b/electron/bridges/ssh2SkPatch.cjs @@ -1,5 +1,7 @@ /** - * Patch ssh2's Protocol.authPK to support OpenSSH Security Key (sk-*) signature layouts. + * Patch ssh2's Protocol.authPK to support: + * 1. OpenSSH Security Key (sk-*) signature layouts + * 2. OpenSSH Certificate authentication with correct signature algorithm * * ssh2 assumes the SSH "signature" field is always: * string sig_alg, string sig_blob @@ -8,13 +10,29 @@ * 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". + * For certificate authentication, the signature algorithm in the signature + * field must be the BASE key type (e.g., "ssh-ed25519"), not the certificate + * type (e.g., "ssh-ed25519-cert-v01@openssh.com"). ssh2's original authPK + * incorrectly uses the certificate type, causing USERAUTH_FAILURE. + * + * Without this patch, sshd will reject with "parse packet: invalid format" + * or signature verification failure. */ 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 { sendPacket, writeUInt32BE, convertSignature } = require("ssh2/lib/protocol/utils.js"); + +// Simple logger for debugging +const fs = require("node:fs"); +const path = require("node:path"); +const logFile = path.join(require("os").tmpdir(), "netcatty-ssh2patch.log"); +const log = (msg, data) => { + const line = `[${new Date().toISOString()}] ${msg} ${data ? JSON.stringify(data) : ""}\n`; + try { fs.appendFileSync(logFile, line); } catch {} + console.log("[ssh2Patch]", msg, data || ""); +}; const PATCH_GUARD = "__netcattySsh2SkAuthPkPatchApplied"; if (!globalThis[PATCH_GUARD]) { @@ -28,6 +46,15 @@ if (!globalThis[PATCH_GUARD]) { "webauthn-sk-ecdsa-sha2-nistp256@openssh.com", ]); + // Certificate type regex - matches *-cert-v01@openssh.com + const CERT_TYPE_REGEX = /-cert-v0[01]@openssh\.com$/i; + + // Convert certificate type to base key type for signature algorithm + // e.g., "ssh-ed25519-cert-v01@openssh.com" -> "ssh-ed25519" + function certTypeToBaseType(certType) { + return certType.replace(CERT_TYPE_REGEX, ""); + } + Protocol.prototype.authPK = function authPK(username, pubKey, keyAlgo, cbSign) { if (this._server) throw new Error("Client-only method called in server mode"); @@ -36,7 +63,7 @@ if (!globalThis[PATCH_GUARD]) { keyAlgo = undefined; } - // Preserve original behavior for the "check" packet or non-SK algorithms. + // Preserve original behavior for the "check" packet if (!cbSign) return originalAuthPK.call(this, username, pubKey, keyAlgo); const parsedKey = parseKey(pubKey); @@ -46,10 +73,25 @@ if (!globalThis[PATCH_GUARD]) { const pubKeyBlob = parsedKey.getPublicSSH(); if (!keyAlgo) keyAlgo = keyType; - if (!SK_SIG_ALGOS.has(keyAlgo)) { + const isCertificate = CERT_TYPE_REGEX.test(keyAlgo); + const isSkAlgo = SK_SIG_ALGOS.has(keyAlgo); + + log("authPK called", { + keyAlgo, + keyType, + isCertificate, + isSkAlgo, + }); + + // Use original implementation for non-SK, non-certificate algorithms + if (!isSkAlgo && !isCertificate) { return originalAuthPK.call(this, username, parsedKey, keyAlgo, cbSign); } + // For certificates, the signature algorithm must be the base key type + const sigAlgo = isCertificate ? certTypeToBaseType(keyAlgo) : keyAlgo; + const sigAlgoLen = Buffer.byteLength(sigAlgo); + const userLen = Buffer.byteLength(username); const algoLen = Buffer.byteLength(keyAlgo); const pubKeyLen = pubKeyBlob.length; @@ -96,10 +138,30 @@ if (!globalThis[PATCH_GUARD]) { // string sig_alg || // where begins with string(ecdsa_signature) and includes extra fields // (flags/counter/origin/clientData/extensions). + // + // For certificate authentication: + // string sig_alg (BASE key type, not cert type) || string sig_blob if (!Buffer.isBuffer(signatureTail)) signatureTail = Buffer.from(signatureTail); - const tailLen = signatureTail.length; - const sigPayloadLen = 4 + algoLen + tailLen; + let sigBlob = signatureTail; + + // For certificate (non-SK) types, we need to convert the signature format + // and use the base key type's signature format + if (isCertificate && !isSkAlgo) { + // Convert signature for ECDSA/DSS types + const baseType = sigAlgo; + if (baseType === "ssh-dss" || /^ecdsa-sha2-nistp\d+$/i.test(baseType)) { + const converted = convertSignature(signatureTail, baseType); + if (converted) sigBlob = converted; + } + } + + const sigBlobLen = sigBlob.length; + // For SK algorithms, signatureTail contains the full signature tail (ecdsa_sig + flags + counter + ...) + // For certificates, sigBlob is just the signature bytes + const sigPayloadLen = isSkAlgo + ? 4 + sigAlgoLen + sigBlobLen // SK: string(sig_alg) || tail + : 4 + sigAlgoLen + 4 + sigBlobLen; // Cert: string(sig_alg) || string(sig_blob) const payloadLen = 1 + 4 + userLen @@ -135,10 +197,28 @@ if (!globalThis[PATCH_GUARD]) { // 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); + // sig_payload: string(sig_alg) || signature data + // Use sigAlgo (base type for certs) instead of keyAlgo (cert type) + log("Building signature field", { + keyAlgo, + sigAlgo, + sigAlgoLen, + sigBlobLen, + isSkAlgo, + isCertificate, + }); + + writeUInt32BE(packet, sigAlgoLen, p += 4); + packet.utf8Write(sigAlgo, p += 4, sigAlgoLen); + + if (isSkAlgo) { + // SK: signature tail directly follows sig_alg + packet.set(sigBlob, p += sigAlgoLen); + } else { + // Standard/Cert: string(sig_blob) - length-prefixed signature bytes + writeUInt32BE(packet, sigBlobLen, p += sigAlgoLen); + packet.set(sigBlob, p += 4); + } this._authsQueue.push("publickey"); this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (publickey)"); diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index 14c9a2ee5..20b4c5214 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -202,13 +202,55 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target }, }; - // Auth - support both key and password for fallback - if (jump.privateKey) { + // Auth - support agent (webauthn/certificate), key, and password fallback + const hasCertificate = + typeof jump.certificate === "string" && jump.certificate.trim().length > 0; + const hasWebAuthn = + typeof jump.credentialId === "string" + && typeof jump.rpId === "string" + && typeof jump.publicKey === "string" + && jump.publicKey.trim().length > 0; + + let authAgent = null; + if (hasWebAuthn) { + // Give users time to complete Touch ID / Passkey prompts + connOpts.readyTimeout = 240000; + authAgent = new NetcattyAgent({ + mode: "webauthn", + webContents: event.sender, + meta: { + label: jump.keyId || jump.username || "", + publicKey: jump.publicKey, + credentialId: jump.credentialId, + rpId: jump.rpId, + userVerification: jump.userVerification, + keySource: jump.keySource, + }, + }); + connOpts.agent = authAgent; + } else if (hasCertificate) { + authAgent = new NetcattyAgent({ + mode: "certificate", + webContents: event.sender, + meta: { + label: jump.keyId || jump.username || "", + certificate: jump.certificate, + privateKey: jump.privateKey, + passphrase: jump.passphrase, + }, + }); + connOpts.agent = authAgent; + } else if (jump.privateKey) { connOpts.privateKey = jump.privateKey; if (jump.passphrase) connOpts.passphrase = jump.passphrase; } - if (jump.password) { - connOpts.password = jump.password; + + if (jump.password) connOpts.password = jump.password; + + if (authAgent) { + const order = ["agent"]; + if (connOpts.password) order.push("password"); + connOpts.authHandler = order; } // If first hop and proxy is configured, connect through proxy diff --git a/global.d.ts b/global.d.ts index 1874e184c..f0744a798 100644 --- a/global.d.ts +++ b/global.d.ts @@ -17,6 +17,15 @@ interface NetcattyJumpHost { username: string; password?: string; privateKey?: string; + certificate?: string; + passphrase?: string; + // WebAuthn-backed keys (optional) + publicKey?: string; + credentialId?: string; + rpId?: string; + userVerification?: 'required' | 'preferred' | 'discouraged'; + keyId?: string; + keySource?: 'generated' | 'imported' | 'biometric' | 'fido2'; label?: string; // Display label for UI }