From c13fbdd7279e1504b02216b447ad8ed5fcaebf7c Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 11 Dec 2025 02:03:22 +0800 Subject: [PATCH] Enables native SSH key generation and improves auth fallback Integrates real SSH keypair generation via Electron backend, replacing previous client-side mock generation for stronger security and reliability. Refines authentication logic to always provide password credentials for SSH and SFTP connections, ensuring fallback support when key-based authentication fails. Improves public key export flow with better host update handling and clearer error feedback. Updates host save logic to correctly update or insert records on key association. Fixes edge cases in SSH command execution status reporting for more robust error detection. --- components/KeychainManager.tsx | 85 ++++++++++++++++++++++------------ components/Terminal.tsx | 11 +++-- components/VaultView.tsx | 10 +++- electron/main.cjs | 78 +++++++++++++++++++++++++++---- electron/preload.cjs | 3 ++ global.d.ts | 5 ++ 6 files changed, 149 insertions(+), 43 deletions(-) diff --git a/components/KeychainManager.tsx b/components/KeychainManager.tsx index 4e9d5055a..80676d5ee 100644 --- a/components/KeychainManager.tsx +++ b/components/KeychainManager.tsx @@ -507,34 +507,40 @@ echo $3 >> "$FILE"`); setError(null); try { - // Simulate key generation delay - await new Promise(resolve => setTimeout(resolve, 500)); - const keyType = draftKey.type as KeyType || 'ED25519'; const keySize = draftKey.keySize; - const { privateKey, publicKey } = generateMockKeyPair( - keyType, - draftKey.label, - keySize - ); + // Use real key generation via Electron backend + if (window.nebula?.generateKeyPair) { + const result = await window.nebula.generateKeyPair({ + type: keyType, + bits: keySize, + comment: `${draftKey.label.trim()}@netcatty`, + }); - const newKey: SSHKey = { - id: crypto.randomUUID(), - label: draftKey.label.trim(), - type: keyType, - keySize: keyType !== 'ED25519' ? keySize : undefined, - privateKey, - publicKey, - passphrase: draftKey.passphrase, - savePassphrase: draftKey.savePassphrase, - source: 'generated', - category: 'key', - created: Date.now(), - }; + if (!result.success || !result.privateKey || !result.publicKey) { + throw new Error(result.error || 'Failed to generate key pair'); + } - onSave(newKey); - closePanel(); + const newKey: SSHKey = { + id: crypto.randomUUID(), + label: draftKey.label.trim(), + type: keyType, + keySize: keyType !== 'ED25519' ? keySize : undefined, + privateKey: result.privateKey, + publicKey: result.publicKey, + passphrase: draftKey.passphrase, + savePassphrase: draftKey.savePassphrase, + source: 'generated', + category: 'key', + created: Date.now(), + }; + + onSave(newKey); + closePanel(); + } else { + throw new Error('Key generation not available - please ensure the app is running in Electron'); + } } catch (err) { setError(err instanceof Error ? err.message : 'Failed to generate key'); } finally { @@ -1787,6 +1793,12 @@ echo $3 >> "$FILE"`); setError(''); try { + // Check for authentication method - prefer password for key export + // Since we're exporting a key to a host, we need password auth + if (!exportHost.password && !exportHost.identityFileId) { + throw new Error('Host has no saved password or key. Please add password credentials to the host first.'); + } + // Get private key for authentication if host uses key auth const hostPrivateKey = exportHost.identityFileId ? keys.find(k => k.id === exportHost.identityFileId)?.privateKey @@ -1796,11 +1808,14 @@ echo $3 >> "$FILE"`); const escapedPublicKey = panel.key.publicKey.replace(/'/g, "'\\''"); // Build the command by replacing $1, $2, $3 - const command = exportScript + const scriptWithVars = exportScript .replace(/\$1/g, exportLocation) .replace(/\$2/g, exportFilename) .replace(/\$3/g, `'${escapedPublicKey}'`); + // Execute the script directly - SSH exec handles multiline commands + const command = scriptWithVars; + // Execute via SSH const result = await window.nebula?.execCommand({ hostname: exportHost.hostname, @@ -1812,16 +1827,28 @@ echo $3 >> "$FILE"`); timeout: 30000, }); - if (result?.code === 0) { - toast.success(`Public key exported to ${exportHost.label}`, 'Export Successful'); + // Check result - code 0, null, or undefined with no stderr is success + const exitCode = result?.code; + const hasError = result?.stderr?.trim(); + if (exitCode === 0 || (exitCode == null && !hasError)) { + // Update host to use this key for authentication + if (onSaveHost) { + const updatedHost: Host = { + ...exportHost, + identityFileId: panel.key.id, + authMethod: 'key', + }; + onSaveHost(updatedHost); + } + toast.success(`Public key exported and attached to ${exportHost.label}`, 'Export Successful'); closePanel(); } else { - const errorMsg = result?.stderr || result?.stdout || 'Unknown error'; + const errorMsg = hasError || result?.stdout?.trim() || `Command exited with code ${exitCode}`; toast.error(`Failed to export key: ${errorMsg}`, 'Export Failed'); } } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - toast.error(message, 'Export Failed'); + const message = err instanceof Error ? err.message : String(err); + toast.error(`Export failed: ${message}`, 'Export Failed'); } finally { setIsExporting(false); } diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 39c78538c..fdbec00c5 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -162,7 +162,7 @@ const TerminalComponent: React.FC = ({ hostname: host.hostname, username: host.username || 'root', port: host.port || 22, - password: host.authMethod !== 'key' ? host.password : undefined, + password: host.password, // Always include for fallback privateKey: key?.privateKey, command: 'cat /etc/os-release 2>/dev/null || uname -a', timeout: 8000, @@ -503,7 +503,8 @@ const TerminalComponent: React.FC = ({ // Use pending auth if available, otherwise use host config const pendingAuth = pendingAuthRef.current; const effectiveUsername = pendingAuth?.username || host.username || 'root'; - const effectivePassword = pendingAuth?.password || (host.authMethod !== 'key' ? host.password : undefined); + // Always include password if available for fallback authentication + const effectivePassword = pendingAuth?.password || host.password; const effectiveKeyId = pendingAuth?.keyId || host.identityFileId; const key = effectiveKeyId @@ -528,7 +529,7 @@ const TerminalComponent: React.FC = ({ hostname: jumpHost.hostname, port: jumpHost.port || 22, username: jumpHost.username || 'root', - password: jumpHost.authMethod !== 'key' ? jumpHost.password : undefined, + password: jumpHost.password, // Always include for fallback privateKey: jumpKey?.privateKey, label: jumpHost.label, }; @@ -1288,8 +1289,8 @@ const TerminalComponent: React.FC = ({ username: host.username, hostname: host.hostname, port: host.port, - password: host.authMethod !== 'key' ? host.password : undefined, - privateKey: host.authMethod === 'key' + password: host.password, // Always include for fallback + privateKey: host.identityFileId ? keys.find(k => k.id === host.identityFileId)?.privateKey : undefined, }} diff --git a/components/VaultView.tsx b/components/VaultView.tsx index aa3fc247c..512011768 100644 --- a/components/VaultView.tsx +++ b/components/VaultView.tsx @@ -522,7 +522,15 @@ const VaultViewInner: React.FC = ({ onSave={k => onUpdateKeys([...keys, k])} onUpdate={k => onUpdateKeys(keys.map(existing => existing.id === k.id ? k : existing))} onDelete={id => onUpdateKeys(keys.filter(k => k.id !== id))} - onSaveHost={(host) => onUpdateHosts([...hosts, host])} + onSaveHost={(host) => { + // Update existing host or add new one + const existingIndex = hosts.findIndex(h => h.id === host.id); + if (existingIndex >= 0) { + onUpdateHosts(hosts.map(h => h.id === host.id ? host : h)); + } else { + onUpdateHosts([...hosts, host]); + } + }} onCreateGroup={(groupPath) => onUpdateCustomGroups(Array.from(new Set([...customGroups, groupPath])))} /> )} diff --git a/electron/main.cjs b/electron/main.cjs index 94f3137dc..4bcb9d246 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -25,7 +25,7 @@ const net = require("node:net"); const http = require("node:http"); const pty = require("node-pty"); const SftpClient = require("ssh2-sftp-client"); -const { Client: SSHClient } = require("ssh2"); +const { Client: SSHClient, utils: sshUtils } = require("ssh2"); // GPU: keep hardware acceleration enabled for smoother rendering // (If you hit GPU issues, you can restore these switches.) @@ -341,11 +341,12 @@ const registerSSHBridge = (win) => { }, }; - // Auth + // Auth - support both key and password for fallback if (jump.privateKey) { connOpts.privateKey = jump.privateKey; if (jump.passphrase) connOpts.passphrase = jump.passphrase; - } else if (jump.password) { + } + if (jump.password) { connOpts.password = jump.password; } @@ -468,13 +469,16 @@ const registerSSHBridge = (win) => { }, }; - // Authentication for final target + // Authentication for final target - support both key and password for fallback + // ssh2 will try methods in order: publickey first, then password if (options.privateKey) { connectOpts.privateKey = options.privateKey; if (options.passphrase) { connectOpts.passphrase = options.passphrase; } - } else if (options.password) { + } + // Always include password if available for fallback authentication + if (options.password) { connectOpts.password = options.password; } @@ -779,7 +783,8 @@ const registerSSHBridge = (win) => { clearTimeout(timer); settled = true; conn.end(); - resolve({ stdout, stderr, code }); + // code can be undefined in some cases, treat as 0 if no stderr + resolve({ stdout, stderr, code: code ?? (stderr ? 1 : 0) }); }); }); }) @@ -793,7 +798,13 @@ const registerSSHBridge = (win) => { if (settled) return; clearTimeout(timer); settled = true; - resolve({ stdout, stderr, code: null }); + // Connection ended before command close - likely an auth failure or connection issue + // If we have stderr output, use it; otherwise this is likely an error + if (stderr || stdout) { + resolve({ stdout, stderr, code: 0 }); + } else { + reject(new Error("SSH connection closed unexpectedly")); + } }); conn.connect({ @@ -810,6 +821,55 @@ const registerSSHBridge = (win) => { electronModule.ipcMain.handle("nebula:ssh:exec", execOnce); + // SSH Key Generation handler + electronModule.ipcMain.handle("nebula:key:generate", async (_event, options) => { + const { type, bits, comment } = options; + + try { + // Map key type to ssh2 format + let keyType; + let keyBits = bits; + + switch (type) { + case 'ED25519': + keyType = 'ed25519'; + keyBits = undefined; // ED25519 doesn't use bits + break; + case 'ECDSA': + keyType = 'ecdsa'; + keyBits = bits || 256; // 256, 384, or 521 + break; + case 'RSA': + default: + keyType = 'rsa'; + keyBits = bits || 4096; + break; + } + + // Generate key pair synchronously + const result = sshUtils.generateKeyPairSync(keyType, { + bits: keyBits, + comment: comment || 'netcatty-generated-key', + }); + + // Convert to OpenSSH format strings + const privateKey = result.private; + const publicKey = result.public; + + return { + success: true, + privateKey, + publicKey, + }; + } catch (err) { + console.error('Key generation failed:', err); + return { + success: false, + error: err.message || 'Key generation failed', + }; + } + }); + // SFTP handlers const openSftp = async (_event, options) => { const client = new SftpClient(); @@ -819,9 +879,11 @@ const registerSSHBridge = (win) => { port: options.port || 22, username: options.username || "root", }; + // Support both key and password for fallback authentication if (options.privateKey) { connectOpts.privateKey = options.privateKey; - } else if (options.password) { + } + if (options.password) { connectOpts.password = options.password; } await client.connect(connectOpts); diff --git a/electron/preload.cjs b/electron/preload.cjs index 6eaec1fdd..97cc15a4d 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -189,6 +189,9 @@ const api = { execCommand: async (options) => { return ipcRenderer.invoke("nebula:ssh:exec", options); }, + generateKeyPair: async (options) => { + return ipcRenderer.invoke("nebula:key:generate", options); + }, resizeSession: (sessionId, cols, rows) => { ipcRenderer.send("nebula:resize", { sessionId, cols, rows }); }, diff --git a/global.d.ts b/global.d.ts index 8b86e81c7..a73aa0b51 100644 --- a/global.d.ts +++ b/global.d.ts @@ -102,6 +102,11 @@ type PortForwardStatusCallback = (status: 'inactive' | 'connecting' | 'active' | interface NebulaBridge { startSSHSession(options: NebulaSSHOptions): Promise; startLocalSession?(options: { sessionId?: string; cols?: number; rows?: number; shell?: string; env?: Record }): Promise; + generateKeyPair?(options: { + type: 'RSA' | 'ECDSA' | 'ED25519'; + bits?: number; + comment?: string; + }): Promise<{ success: boolean; privateKey?: string; publicKey?: string; error?: string }>; execCommand(options: { hostname: string; username: string;