@lethevimlet/sshift 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -7
- package/package.json +1 -2
- package/src/server/endpoints/rest/index.js +3 -0
- package/src/server/endpoints/rest/utils.js +36 -0
- package/src/server/index.js +49 -45
- package/src/server/services/sftp-manager.js +3 -1
- package/src/server/services/ssh-manager.js +3 -4
- package/src/server/utils/key-converter.js +363 -0
- package/src/webapp/css/style.css +83 -5
- package/src/webapp/index.html +22 -2
- package/src/webapp/js/app.js +368 -181
- package/src/webapp/js/mobile-terminal.js +65 -36
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ npm install -g @lethevimlet/sshift
|
|
|
35
35
|
sshift
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
The application will be available at `
|
|
38
|
+
The application will be available at `https://localhost:8022`
|
|
39
39
|
|
|
40
40
|
## 📖 Documentation
|
|
41
41
|
|
|
@@ -56,23 +56,25 @@ The recommended way to install sshift - automatically handles updates and autost
|
|
|
56
56
|
|
|
57
57
|
**Linux/macOS:**
|
|
58
58
|
```bash
|
|
59
|
-
curl -fsSL https://raw.githubusercontent.com/lethevimlet/sshift/main/install.sh | bash
|
|
59
|
+
curl -fsSL https://raw.githubusercontent.com/lethevimlet/sshift/main/sshift-install.sh | bash
|
|
60
60
|
```
|
|
61
61
|
|
|
62
62
|
**Windows (PowerShell):**
|
|
63
63
|
|
|
64
64
|
```powershell
|
|
65
65
|
Set-ExecutionPolicy Bypass -Scope Process
|
|
66
|
-
Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/lethevimlet/sshift/main/install.ps1" -UseBasicParsing).Content
|
|
66
|
+
Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/lethevimlet/sshift/main/sshift-install.ps1" -UseBasicParsing).Content
|
|
67
67
|
```
|
|
68
68
|
|
|
69
69
|
> **Note:** The Windows installer requires PowerShell to be run as Administrator for npm global installations.
|
|
70
70
|
|
|
71
71
|
The installer will:
|
|
72
|
-
- Install Node.js
|
|
73
|
-
- Install sshift globally
|
|
74
|
-
-
|
|
75
|
-
-
|
|
72
|
+
- Install Node.js 20+ if not present
|
|
73
|
+
- Install sshift globally via npm
|
|
74
|
+
- Start sshift after installation
|
|
75
|
+
- Configure autostart (optional, systemd on Linux, launchd on macOS, Task Scheduler on Windows)
|
|
76
|
+
- Create config at `~/.local/share/sshift/.env/config.json` with HTTPS enabled
|
|
77
|
+
- Print summary with HTTPS access links
|
|
76
78
|
|
|
77
79
|
### Docker
|
|
78
80
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lethevimlet/sshift",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
|
|
5
5
|
"main": "src/server/index.js",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,6 @@
|
|
|
24
24
|
"dotenv": "^17.4.0",
|
|
25
25
|
"express": "^4.18.2",
|
|
26
26
|
"lucide": "^1.7.0",
|
|
27
|
-
"pem": "^1.14.8",
|
|
28
27
|
"selfsigned": "^5.5.0",
|
|
29
28
|
"socket.io": "^4.7.2",
|
|
30
29
|
"ssh2": "^1.15.0",
|
|
@@ -8,6 +8,7 @@ const { registerConfigEndpoints } = require('./config');
|
|
|
8
8
|
const { registerFolderEndpoints } = require('./folders');
|
|
9
9
|
const { registerSessionsEndpoints } = require('./sessions');
|
|
10
10
|
const { registerSystemEndpoints } = require('./system');
|
|
11
|
+
const { registerUtilsEndpoints } = require('./utils');
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* Register all REST endpoints
|
|
@@ -20,6 +21,7 @@ function registerAllRestEndpoints(app, io) {
|
|
|
20
21
|
registerFolderEndpoints(app, io);
|
|
21
22
|
registerSessionsEndpoints(app, io);
|
|
22
23
|
registerSystemEndpoints(app, io);
|
|
24
|
+
registerUtilsEndpoints(app, io);
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
module.exports = {
|
|
@@ -28,5 +30,6 @@ module.exports = {
|
|
|
28
30
|
registerFolderEndpoints,
|
|
29
31
|
registerSessionsEndpoints,
|
|
30
32
|
registerSystemEndpoints,
|
|
33
|
+
registerUtilsEndpoints,
|
|
31
34
|
registerAllRestEndpoints
|
|
32
35
|
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const { detectKeyFormat, convertPPKToOpenSSH } = require('../../utils/key-converter');
|
|
2
|
+
|
|
3
|
+
function registerUtilsEndpoints(app, io) {
|
|
4
|
+
app.post('/api/utils/detect-key', (req, res) => {
|
|
5
|
+
const { content } = req.body;
|
|
6
|
+
if (!content || !content.trim()) {
|
|
7
|
+
return res.json({ format: 'unknown', type: 'unknown', encrypted: false });
|
|
8
|
+
}
|
|
9
|
+
try {
|
|
10
|
+
const info = detectKeyFormat(content);
|
|
11
|
+
res.json(info);
|
|
12
|
+
} catch (e) {
|
|
13
|
+
res.json({ format: 'unknown', type: 'unknown', encrypted: false, error: e.message });
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
app.post('/api/utils/convert-key', async (req, res) => {
|
|
18
|
+
const { content } = req.body;
|
|
19
|
+
if (!content || !content.trim()) {
|
|
20
|
+
return res.status(400).json({ error: 'No key content provided' });
|
|
21
|
+
}
|
|
22
|
+
const info = detectKeyFormat(content);
|
|
23
|
+
if (info.format === 'ppk') {
|
|
24
|
+
try {
|
|
25
|
+
const converted = await convertPPKToOpenSSH(content);
|
|
26
|
+
res.json({ success: true, key: converted, format: 'openssh' });
|
|
27
|
+
} catch (e) {
|
|
28
|
+
res.status(400).json({ error: e.message });
|
|
29
|
+
}
|
|
30
|
+
} else {
|
|
31
|
+
res.json({ success: true, key: content, format: info.format });
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { registerUtilsEndpoints };
|
package/src/server/index.js
CHANGED
|
@@ -15,7 +15,6 @@ const https = require('https');
|
|
|
15
15
|
const path = require('path');
|
|
16
16
|
const socketIO = require('socket.io');
|
|
17
17
|
const selfsigned = require('selfsigned');
|
|
18
|
-
const pem = require('pem');
|
|
19
18
|
|
|
20
19
|
// Import utilities
|
|
21
20
|
const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps } = require('./utils/config');
|
|
@@ -27,55 +26,60 @@ const { sshManager, sftpManager } = require('./services');
|
|
|
27
26
|
const { rest, ws } = require('./endpoints');
|
|
28
27
|
|
|
29
28
|
/**
|
|
30
|
-
* Generate self-signed SSL certificates in memory using
|
|
29
|
+
* Generate self-signed SSL certificates in memory using selfsigned package (pure JS, no OpenSSL dependency)
|
|
31
30
|
* @returns {Promise<Object>} Certificate and private key
|
|
32
31
|
*/
|
|
33
|
-
function generateSelfSignedCert() {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
localIPs.push(addr.address);
|
|
48
|
-
}
|
|
49
|
-
});
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
// Get hostname
|
|
53
|
-
const hostname = os.hostname();
|
|
54
|
-
|
|
55
|
-
console.log('[HTTPS] Certificate will be valid for:', localIPs.join(', '), 'and hostname:', hostname);
|
|
56
|
-
|
|
57
|
-
// Build alt names array
|
|
58
|
-
const altNames = ['localhost', hostname || 'localhost', ...localIPs];
|
|
59
|
-
|
|
60
|
-
pem.createCertificate({
|
|
61
|
-
days: 365,
|
|
62
|
-
selfSigned: true,
|
|
63
|
-
commonName: hostname || 'localhost',
|
|
64
|
-
altNames: altNames
|
|
65
|
-
}, (err, keys) => {
|
|
66
|
-
if (err) {
|
|
67
|
-
console.error('[HTTPS] Error generating certificate:', err);
|
|
68
|
-
reject(err);
|
|
69
|
-
return;
|
|
32
|
+
async function generateSelfSignedCert() {
|
|
33
|
+
console.log('[HTTPS] Generating self-signed certificate...');
|
|
34
|
+
|
|
35
|
+
const os = require('os');
|
|
36
|
+
|
|
37
|
+
// Get local IP addresses for SAN
|
|
38
|
+
const interfaces = os.networkInterfaces();
|
|
39
|
+
const localIPs = ['127.0.0.1'];
|
|
40
|
+
|
|
41
|
+
// Extract all IPv4 addresses from network interfaces
|
|
42
|
+
Object.values(interfaces).forEach(iface => {
|
|
43
|
+
iface.forEach(addr => {
|
|
44
|
+
if (addr.family === 'IPv4' && !addr.internal) {
|
|
45
|
+
localIPs.push(addr.address);
|
|
70
46
|
}
|
|
71
|
-
|
|
72
|
-
console.log('[HTTPS] Self-signed certificate generated successfully');
|
|
73
|
-
resolve({
|
|
74
|
-
cert: keys.certificate,
|
|
75
|
-
key: keys.serviceKey
|
|
76
|
-
});
|
|
77
47
|
});
|
|
78
48
|
});
|
|
49
|
+
|
|
50
|
+
// Get hostname
|
|
51
|
+
const hostname = os.hostname() || 'localhost';
|
|
52
|
+
|
|
53
|
+
console.log('[HTTPS] Certificate will be valid for:', localIPs.join(', '), 'and hostname:', hostname);
|
|
54
|
+
|
|
55
|
+
// Build Subject Alternative Names
|
|
56
|
+
const altNames = [
|
|
57
|
+
{ type: 2, value: 'localhost' },
|
|
58
|
+
{ type: 2, value: hostname },
|
|
59
|
+
...localIPs.map(ip => ({ type: 7, ip }))
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
const attrs = [{ name: 'commonName', value: hostname }];
|
|
64
|
+
const pems = await selfsigned.generate(attrs, {
|
|
65
|
+
days: 365,
|
|
66
|
+
keySize: 2048,
|
|
67
|
+
algorithm: 'sha256',
|
|
68
|
+
extensions: [{
|
|
69
|
+
name: 'subjectAltName',
|
|
70
|
+
altNames
|
|
71
|
+
}]
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
console.log('[HTTPS] Self-signed certificate generated successfully');
|
|
75
|
+
return {
|
|
76
|
+
cert: pems.cert,
|
|
77
|
+
key: pems.private
|
|
78
|
+
};
|
|
79
|
+
} catch (err) {
|
|
80
|
+
console.error('[HTTPS] Error generating certificate:', err);
|
|
81
|
+
throw err;
|
|
82
|
+
}
|
|
79
83
|
}
|
|
80
84
|
|
|
81
85
|
// Create Express app
|
|
@@ -28,11 +28,13 @@ class SFTPManager {
|
|
|
28
28
|
config.password = options.password;
|
|
29
29
|
console.log('[SFTP] Using password authentication');
|
|
30
30
|
} else if (options.privateKey && options.privateKey.length > 0) {
|
|
31
|
+
// Handle private key - supports OpenSSH, PEM, PKCS8, and base64-encoded formats
|
|
31
32
|
try {
|
|
32
33
|
if (options.privateKey.includes('BEGIN')) {
|
|
33
34
|
config.privateKey = options.privateKey;
|
|
34
35
|
} else {
|
|
35
|
-
|
|
36
|
+
const decoded = Buffer.from(options.privateKey, 'base64').toString('utf8');
|
|
37
|
+
config.privateKey = decoded;
|
|
36
38
|
}
|
|
37
39
|
} catch (e) {
|
|
38
40
|
config.privateKey = options.privateKey;
|
|
@@ -76,14 +76,13 @@ class SSHManager {
|
|
|
76
76
|
config.password = options.password;
|
|
77
77
|
console.log('[SSH] Using password authentication');
|
|
78
78
|
} else if (options.privateKey && options.privateKey.length > 0) {
|
|
79
|
-
// Handle private key -
|
|
79
|
+
// Handle private key - supports OpenSSH, PEM, PKCS8, and base64-encoded formats
|
|
80
80
|
try {
|
|
81
|
-
// If it's a base64 encoded key, decode it
|
|
82
81
|
if (options.privateKey.includes('BEGIN')) {
|
|
83
82
|
config.privateKey = options.privateKey;
|
|
84
83
|
} else {
|
|
85
|
-
|
|
86
|
-
config.privateKey =
|
|
84
|
+
const decoded = Buffer.from(options.privateKey, 'base64').toString('utf8');
|
|
85
|
+
config.privateKey = decoded;
|
|
87
86
|
}
|
|
88
87
|
} catch (e) {
|
|
89
88
|
config.privateKey = options.privateKey;
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
const { execFile } = require('child_process');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
|
|
7
|
+
function detectKeyFormat(keyContent) {
|
|
8
|
+
if (!keyContent || !keyContent.trim()) return { format: 'unknown', type: 'unknown' };
|
|
9
|
+
|
|
10
|
+
const trimmed = keyContent.trim();
|
|
11
|
+
|
|
12
|
+
if (/^PuTTY-User-Key-File-/im.test(trimmed)) {
|
|
13
|
+
const lines = trimmed.split('\n');
|
|
14
|
+
let type = 'ssh-rsa';
|
|
15
|
+
let isEncrypted = false;
|
|
16
|
+
for (const line of lines) {
|
|
17
|
+
const colonIdx = line.indexOf(':');
|
|
18
|
+
if (colonIdx !== -1) {
|
|
19
|
+
const key = line.substring(0, colonIdx).trim();
|
|
20
|
+
const value = line.substring(colonIdx + 1).trim();
|
|
21
|
+
if (key.match(/^PuTTY-User-Key-File-/i)) {
|
|
22
|
+
type = value;
|
|
23
|
+
}
|
|
24
|
+
if (key === 'Encryption') {
|
|
25
|
+
isEncrypted = value !== 'none';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return { format: 'ppk', type, encrypted: isEncrypted };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (trimmed.includes('-----BEGIN RSA PRIVATE KEY-----')) {
|
|
33
|
+
return { format: 'pem-rsa', type: 'ssh-rsa', encrypted: trimmed.includes('ENCRYPTED') };
|
|
34
|
+
}
|
|
35
|
+
if (trimmed.includes('-----BEGIN EC PRIVATE KEY-----')) {
|
|
36
|
+
return { format: 'pem-ec', type: 'ecdsa', encrypted: trimmed.includes('ENCRYPTED') };
|
|
37
|
+
}
|
|
38
|
+
if (trimmed.includes('-----BEGIN DSA PRIVATE KEY-----')) {
|
|
39
|
+
return { format: 'pem-dsa', type: 'ssh-dss', encrypted: trimmed.includes('ENCRYPTED') };
|
|
40
|
+
}
|
|
41
|
+
if (trimmed.includes('-----BEGIN PRIVATE KEY-----')) {
|
|
42
|
+
return { format: 'pkcs8', type: 'generic', encrypted: trimmed.includes('ENCRYPTED') };
|
|
43
|
+
}
|
|
44
|
+
if (trimmed.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {
|
|
45
|
+
return { format: 'pkcs8-encrypted', type: 'generic', encrypted: true };
|
|
46
|
+
}
|
|
47
|
+
if (trimmed.includes('-----BEGIN OPENSSH PRIVATE KEY-----')) {
|
|
48
|
+
return { format: 'openssh', type: 'openssh-generic', encrypted: false };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return { format: 'unknown', type: 'unknown' };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function convertPPKViaPuttygen(ppkContent) {
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
const tmpDir = os.tmpdir();
|
|
57
|
+
const inputFile = path.join(tmpDir, `sshift-ppk-${Date.now()}-${Math.random().toString(36).slice(2)}.ppk`);
|
|
58
|
+
const outputFile = inputFile + '.openssh';
|
|
59
|
+
|
|
60
|
+
fs.writeFile(inputFile, ppkContent, (writeErr) => {
|
|
61
|
+
if (writeErr) {
|
|
62
|
+
try { fs.unlinkSync(inputFile); } catch (e) { /* ignore */ }
|
|
63
|
+
return reject(new Error('Failed to write temporary PPK file: ' + writeErr.message));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
execFile('puttygen', [inputFile, '-O', 'private-openssh-new', '-o', outputFile], (err, stdout, stderr) => {
|
|
67
|
+
try { fs.unlinkSync(inputFile); } catch (e) { /* ignore */ }
|
|
68
|
+
|
|
69
|
+
if (err) {
|
|
70
|
+
try { fs.unlinkSync(outputFile); } catch (e) { /* ignore */ }
|
|
71
|
+
return reject(new Error(
|
|
72
|
+
'puttygen conversion failed: ' + (stderr || err.message) +
|
|
73
|
+
'. If the PPK file is encrypted, decrypt it first using PuTTYgen.'
|
|
74
|
+
));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
fs.readFile(outputFile, 'utf8', (readErr, data) => {
|
|
78
|
+
try { fs.unlinkSync(outputFile); } catch (e) { /* ignore */ }
|
|
79
|
+
if (readErr) {
|
|
80
|
+
return reject(new Error('Failed to read converted key: ' + readErr.message));
|
|
81
|
+
}
|
|
82
|
+
resolve(data);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function convertPPKV2ToOpenSSH(ppkContent) {
|
|
90
|
+
const lines = ppkContent.split('\n');
|
|
91
|
+
|
|
92
|
+
const headers = {};
|
|
93
|
+
const publicLines = [];
|
|
94
|
+
const privateLines = [];
|
|
95
|
+
let section = 'header';
|
|
96
|
+
|
|
97
|
+
for (const rawLine of lines) {
|
|
98
|
+
const line = rawLine.trim();
|
|
99
|
+
if (line === '') continue;
|
|
100
|
+
if (line.startsWith(':')) continue;
|
|
101
|
+
|
|
102
|
+
if (line.startsWith('Public-Lines:')) {
|
|
103
|
+
section = 'public';
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (line.startsWith('Private-Lines:')) {
|
|
107
|
+
section = 'private';
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (line.startsWith('Private-MAC:')) {
|
|
111
|
+
section = 'mac';
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (section === 'public') {
|
|
116
|
+
publicLines.push(line);
|
|
117
|
+
} else if (section === 'private') {
|
|
118
|
+
privateLines.push(line);
|
|
119
|
+
} else if (section === 'header') {
|
|
120
|
+
const colonIdx = line.indexOf(':');
|
|
121
|
+
if (colonIdx !== -1) {
|
|
122
|
+
headers[line.substring(0, colonIdx).trim()] = line.substring(colonIdx + 1).trim();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const encType = headers['Encryption'] || 'none';
|
|
128
|
+
if (encType !== 'none') {
|
|
129
|
+
throw new Error(
|
|
130
|
+
`PPK key is encrypted with "${encType}". Please decrypt it first using PuTTYgen: ` +
|
|
131
|
+
`load the PPK, enter the passphrase, then export as OpenSSH key.`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const ppkVersion = Object.keys(headers).find(k => k.match(/^PuTTY-User-Key-File-/i));
|
|
136
|
+
const keyType = ppkVersion ? headers[ppkVersion] : null;
|
|
137
|
+
if (!keyType) {
|
|
138
|
+
throw new Error('Could not determine PPK key type. Is this a valid PPK file?');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (ppkVersion && ppkVersion.match(/^PuTTY-User-Key-File-3$/i)) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
'PPK v3 format is not supported by the built-in converter. ' +
|
|
144
|
+
'The key will be converted using puttygen on the server instead.'
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const publicData = Buffer.from(publicLines.join(''), 'base64');
|
|
149
|
+
const privateData = Buffer.from(privateLines.join(''), 'base64');
|
|
150
|
+
|
|
151
|
+
if (privateData.length < 8) {
|
|
152
|
+
throw new Error('PPK private data is too short. The key file may be corrupt.');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const check1 = privateData.readUInt32BE(0);
|
|
156
|
+
const check2 = privateData.readUInt32BE(4);
|
|
157
|
+
if (check1 !== check2) {
|
|
158
|
+
throw new Error(
|
|
159
|
+
'PPK integrity check failed. The key may be encrypted or corrupted. ' +
|
|
160
|
+
'If it has a passphrase, convert using PuTTYgen first.'
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const privReader = new SSHBufferReader(privateData.slice(8));
|
|
165
|
+
const privKeyType = privReader.readString().toString('ascii');
|
|
166
|
+
|
|
167
|
+
if (privKeyType !== keyType) {
|
|
168
|
+
throw new Error(`PPK key type mismatch: expected ${keyType}, got ${privKeyType}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const keyParts = [Buffer.from(keyType)];
|
|
172
|
+
|
|
173
|
+
if (keyType === 'ssh-rsa') {
|
|
174
|
+
const n = privReader.readMPInt();
|
|
175
|
+
const e = privReader.readMPInt();
|
|
176
|
+
const d = privReader.readMPInt();
|
|
177
|
+
const iqmp = privReader.readMPInt();
|
|
178
|
+
const p = privReader.readMPInt();
|
|
179
|
+
const q = privReader.readMPInt();
|
|
180
|
+
|
|
181
|
+
keyParts.push(writeSSHString(n));
|
|
182
|
+
keyParts.push(writeSSHString(e));
|
|
183
|
+
keyParts.push(writeSSHString(d));
|
|
184
|
+
keyParts.push(writeSSHString(iqmp));
|
|
185
|
+
keyParts.push(writeSSHString(p));
|
|
186
|
+
keyParts.push(writeSSHString(q));
|
|
187
|
+
} else if (keyType === 'ssh-ed25519') {
|
|
188
|
+
const pubKeyBlob = privReader.readString();
|
|
189
|
+
const privKeyBlob = privReader.readString();
|
|
190
|
+
keyParts.push(pubKeyBlob);
|
|
191
|
+
keyParts.push(privKeyBlob);
|
|
192
|
+
} else if (keyType.startsWith('ecdsa-sha2-')) {
|
|
193
|
+
const curveName = privReader.readString();
|
|
194
|
+
const pubPoint = privReader.readString();
|
|
195
|
+
const privD = privReader.readMPInt();
|
|
196
|
+
keyParts.push(curveName);
|
|
197
|
+
keyParts.push(pubPoint);
|
|
198
|
+
keyParts.push(writeSSHString(privD));
|
|
199
|
+
} else if (keyType === 'ssh-dss') {
|
|
200
|
+
const p = privReader.readMPInt();
|
|
201
|
+
const q = privReader.readMPInt();
|
|
202
|
+
const g = privReader.readMPInt();
|
|
203
|
+
const y = privReader.readMPInt();
|
|
204
|
+
const x = privReader.readMPInt();
|
|
205
|
+
keyParts.push(writeSSHString(p));
|
|
206
|
+
keyParts.push(writeSSHString(q));
|
|
207
|
+
keyParts.push(writeSSHString(g));
|
|
208
|
+
keyParts.push(writeSSHString(y));
|
|
209
|
+
keyParts.push(writeSSHString(x));
|
|
210
|
+
} else {
|
|
211
|
+
throw new Error(`Unsupported PPK v2 key type: ${keyType}. Supported: ssh-rsa, ssh-ed25519, ecdsa-sha2-*, ssh-dss`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return encodeOpenSSHPrivateKey(keyParts);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
class SSHBufferReader {
|
|
218
|
+
constructor(buffer) {
|
|
219
|
+
this.buffer = buffer;
|
|
220
|
+
this.offset = 0;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
readString() {
|
|
224
|
+
if (this.offset + 4 > this.buffer.length) {
|
|
225
|
+
throw new Error('Buffer underflow reading string length');
|
|
226
|
+
}
|
|
227
|
+
const len = this.buffer.readUInt32BE(this.offset);
|
|
228
|
+
this.offset += 4;
|
|
229
|
+
if (this.offset + len > this.buffer.length) {
|
|
230
|
+
throw new Error('Buffer underflow reading string data');
|
|
231
|
+
}
|
|
232
|
+
const str = this.buffer.slice(this.offset, this.offset + len);
|
|
233
|
+
this.offset += len;
|
|
234
|
+
return str;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
readMPInt() {
|
|
238
|
+
if (this.offset + 4 > this.buffer.length) {
|
|
239
|
+
throw new Error('Buffer underflow reading MPInt length');
|
|
240
|
+
}
|
|
241
|
+
const len = this.buffer.readUInt32BE(this.offset);
|
|
242
|
+
this.offset += 4;
|
|
243
|
+
if (this.offset + len > this.buffer.length) {
|
|
244
|
+
throw new Error('Buffer underflow reading MPInt data');
|
|
245
|
+
}
|
|
246
|
+
const data = this.buffer.slice(this.offset, this.offset + len);
|
|
247
|
+
this.offset += len;
|
|
248
|
+
let start = 0;
|
|
249
|
+
while (start < data.length && data[start] === 0) start++;
|
|
250
|
+
return data.slice(start);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function writeSSHString(buf) {
|
|
255
|
+
let padded = buf;
|
|
256
|
+
if (buf.length > 0 && (buf[0] & 0x80)) {
|
|
257
|
+
padded = Buffer.concat([Buffer.alloc(1), buf]);
|
|
258
|
+
}
|
|
259
|
+
const lenBuf = Buffer.alloc(4);
|
|
260
|
+
lenBuf.writeUInt32BE(padded.length);
|
|
261
|
+
return Buffer.concat([lenBuf, padded]);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function encodeOpenSSHPrivateKey(keyParts) {
|
|
265
|
+
const prefix = Buffer.from('openssh-key-v1\0', 'binary');
|
|
266
|
+
|
|
267
|
+
const cipherName = Buffer.from('none');
|
|
268
|
+
const kdfName = Buffer.from('none');
|
|
269
|
+
const kdfOptions = Buffer.alloc(0);
|
|
270
|
+
|
|
271
|
+
const pubParts = [];
|
|
272
|
+
for (const part of keyParts) {
|
|
273
|
+
pubParts.push(writeSSHString(part));
|
|
274
|
+
}
|
|
275
|
+
const pubBlob = Buffer.concat(pubParts);
|
|
276
|
+
|
|
277
|
+
const checkVal = crypto.randomBytes(4).readUInt32BE(0);
|
|
278
|
+
const check1 = Buffer.alloc(4);
|
|
279
|
+
check1.writeUInt32BE(checkVal);
|
|
280
|
+
const check2 = Buffer.alloc(4);
|
|
281
|
+
check2.writeUInt32BE(checkVal);
|
|
282
|
+
|
|
283
|
+
const privParts = [check1, check2];
|
|
284
|
+
for (const part of keyParts) {
|
|
285
|
+
privParts.push(writeSSHString(part));
|
|
286
|
+
}
|
|
287
|
+
privParts.push(writeSSHString(Buffer.alloc(0)));
|
|
288
|
+
|
|
289
|
+
const currentLen = privParts.reduce((sum, p) => sum + p.length, 0);
|
|
290
|
+
const blockSize = 8;
|
|
291
|
+
const padLen = (blockSize - (currentLen % blockSize)) % blockSize;
|
|
292
|
+
if (padLen > 0) {
|
|
293
|
+
const padding = Buffer.alloc(padLen);
|
|
294
|
+
for (let i = 0; i < padLen; i++) {
|
|
295
|
+
padding[i] = (i + 1) & 0xff;
|
|
296
|
+
}
|
|
297
|
+
privParts.push(padding);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const privBlob = Buffer.concat(privParts);
|
|
301
|
+
|
|
302
|
+
const nKeys = Buffer.alloc(4);
|
|
303
|
+
nKeys.writeUInt32BE(1);
|
|
304
|
+
|
|
305
|
+
function sshBuf(buf) {
|
|
306
|
+
const len = Buffer.alloc(4);
|
|
307
|
+
len.writeUInt32BE(buf.length);
|
|
308
|
+
return Buffer.concat([len, buf]);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const serialized = Buffer.concat([
|
|
312
|
+
prefix,
|
|
313
|
+
sshBuf(cipherName),
|
|
314
|
+
sshBuf(kdfName),
|
|
315
|
+
sshBuf(kdfOptions),
|
|
316
|
+
nKeys,
|
|
317
|
+
sshBuf(pubBlob),
|
|
318
|
+
sshBuf(privBlob)
|
|
319
|
+
]);
|
|
320
|
+
|
|
321
|
+
const b64 = serialized.toString('base64');
|
|
322
|
+
const lines = b64.match(/.{1,70}/g) || [];
|
|
323
|
+
|
|
324
|
+
return `-----BEGIN OPENSSH PRIVATE KEY-----\n${lines.join('\n')}\n-----END OPENSSH PRIVATE KEY-----\n`;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function convertPPKToOpenSSH(ppkContent) {
|
|
328
|
+
const info = detectKeyFormat(ppkContent);
|
|
329
|
+
|
|
330
|
+
if (info.format !== 'ppk') {
|
|
331
|
+
throw new Error('Not a PPK key');
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (info.encrypted) {
|
|
335
|
+
throw new Error(
|
|
336
|
+
'This PPK key is encrypted. Please decrypt it first using PuTTYgen: ' +
|
|
337
|
+
'load the PPK, enter the passphrase, then export as OpenSSH key.'
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Try puttygen first (handles all PPK versions including v3)
|
|
342
|
+
try {
|
|
343
|
+
const result = await convertPPKViaPuttygen(ppkContent);
|
|
344
|
+
if (result && result.includes('BEGIN OPENSSH PRIVATE KEY')) {
|
|
345
|
+
return result;
|
|
346
|
+
}
|
|
347
|
+
} catch (e) {
|
|
348
|
+
// puttygen not available or failed, try built-in v2 parser
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Fall back to built-in PPK v2 converter
|
|
352
|
+
try {
|
|
353
|
+
return convertPPKV2ToOpenSSH(ppkContent);
|
|
354
|
+
} catch (e) {
|
|
355
|
+
throw new Error(
|
|
356
|
+
'Could not convert PPK key: ' + e.message +
|
|
357
|
+
'. Please convert the key manually using PuTTYgen: ' +
|
|
358
|
+
'load the PPK file, then export as OpenSSH key (Conversions > Export OpenSSH key).'
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
module.exports = { detectKeyFormat, convertPPKToOpenSSH };
|