-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh.tsx
More file actions
190 lines (171 loc) · 8.59 KB
/
ssh.tsx
File metadata and controls
190 lines (171 loc) · 8.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import { timingSafeEqual } from 'crypto';
import { Server, utils, ParsedKey } from 'ssh2';
import * as fs from 'fs';
import * as path from 'path';
import { homedir } from 'os';
import { activeConnections, activeSSHConnections, SSHConnection } from './state';
const SSH_PORT = 13336;
const dotssh = path.join(homedir(), '.ssh');
if (!fs.existsSync(dotssh)) fs.mkdirSync(dotssh);
const privateKeyPath = path.join(dotssh, 'id_rsa');
const publicKeyPath = path.join(dotssh, 'id_rsa.pub');
const authorizedKeysPath = path.join(dotssh, 'authorized_keys');
if (!fs.existsSync(privateKeyPath)) {
const { execSync } = require('child_process');
execSync(`ssh-keygen -t rsa -b 4096 -f ${privateKeyPath} -N ""`);
}
const authorizedKeys = fs.existsSync(authorizedKeysPath) ? fs.readFileSync(authorizedKeysPath, 'utf-8').split('\n').filter(i => i.trim()) : [];
const allowedPubKeys = authorizedKeys.map(i => utils.parseKey(i + '\n')).filter(i => i && !(i instanceof Error)) as ParsedKey[];
console.log(allowedPubKeys.length + ' keys loaded');
const eq = (a: Buffer, b: Buffer) => {
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
const sshServer = new Server({
hostKeys: [fs.readFileSync(privateKeyPath)],
}, (client) => {
const clientInfo = `SSH client`;
console.log(`[+] New admin connection from ${clientInfo}`);
const state = new SSHConnection(null);
activeSSHConnections.set(client, state);
client.on('authentication', (ctx) => {
if (!eq(Buffer.from(ctx.username), Buffer.from('user')))
return ctx.reject();
switch (ctx.method) {
case 'password':
return ctx.reject();
case 'publickey':
for (const allowedPubKey of allowedPubKeys) {
if (ctx.key.algo == allowedPubKey.type
&& eq(ctx.key.data, allowedPubKey.getPublicSSH())
&& (!ctx.signature || allowedPubKey.verify(ctx.blob!, ctx.signature, ctx.hashAlgo))) {
return ctx.accept();
}
}
return ctx.reject();
default:
return ctx.reject();
}
});
client.on('ready', () => {
client.on('session', (accept, reject) => {
const session = accept();
// 先处理PTY请求
session.on('pty', (accept, reject, info) => {
state.rows = info.rows;
state.cols = info.cols;
accept();
});
// 处理窗口大小变化
session.on('window-change', (accept, reject, info) => {
accept?.();
state.rows = info.rows;
state.cols = info.cols;
if (state.selectedId) {
const connInfo = activeConnections.get(state.selectedId);
if (connInfo && state.rows && state.cols) {
connInfo.resize(state.rows - 1, state.cols);
}
state.stream?.write(`\x1b[1;${info.rows - 1}r`);
} else {
state.stream?.write('\x1b[r');
}
state.drawBottomBar();
});
session.on('shell', (accept, reject) => {
const stream = accept();
state.stream = stream;
if (!state.rows) {
state.rows = 24;
state.cols = 80;
}
console.log('[*] Admin shell session started');
// 清屏并设置初始状态
stream.write('\x1b[2J\x1b[H');
stream.write('Command mode - Press number to switch tab, l to list, q to quit\r\n');
stream.write('\x1b[r'); // Initial full scroll region for command mode
state.drawBottomBar();
stream.on('data', (data) => {
const input = data.toString();
if (data[0] === 2) { // Ctrl+B
if (!state.commandMode) state.commandMode = true;
else if (state.selectedId) {
state.commandMode = false;
activeConnections.get(state.selectedId)?.socket.write(data);
}
state.drawBottomBar();
return;
}
if (state.commandMode) {
const char = input[0];
if (char === 'q' || char === 'd') stream.end();
else {
const num = parseInt(char);
if (!isNaN(num)) {
const connections = Array.from(activeConnections.entries());
if (num > 0 && num <= connections.length) {
const [id, info] = connections[num - 1];
state.selectedId = id;
state.commandMode = false;
if (state.rows && state.cols) {
info.terminal.resize(state.cols, state.rows - 1);
// Get cursor position before clearing
const buffer = info.terminal.buffer.active;
const cursorY = buffer.cursorY + 1; // 1-based
const cursorX = buffer.cursorX + 1; // 1-based
console.log('[-] Cursor position', cursorY, cursorX);
// Clear screen and set scroll region first
stream.write('\x1b[2J'); // Clear screen
stream.write(`\x1b[1;${state.rows - 1}r`); // Set scroll region to protect bottom line
stream.write('\x1b[H'); // Move cursor to home
// Write serialized content (remove cursor position from it if present)
const serialized = info.serializeAddon.serialize();
// Remove cursor position ANSI codes from serialized content
// const cleanedSerialized = serialized.replace(/\x1b\[\d+;\d+[Hf]/g, '');
stream.write(serialized);
// Restore cursor position after everything
stream.write(`\x1b[${cursorY};${cursorX}H`);
info.resize(state.rows - 1, state.cols);
}
state.drawBottomBar();
} else {
stream.write('\r\nInvalid connection number\r\n');
}
} else if (char === 'l') {
stream.write('\r\nActive connections:\r\n');
const conns = Array.from(activeConnections.entries());
conns.forEach(([id, info], idx) => {
const num = idx + 1;
stream.write(`${num}: ${info.user || 'unknown'}@${info.os || 'unknown'} (${id})\r\n`);
});
stream.write('\r\n');
}
}
} else if (state.selectedId) {
activeConnections.get(state.selectedId)?.socket.write(data);
}
});
// 处理会话结束
stream.on('close', () => {
state.stream = null;
state.selectedId = null;
console.log('[-] Admin shell session closed');
});
});
});
});
client.on('end', () => {
activeSSHConnections.delete(client);
console.log(`[-] Admin connection closed from ${clientInfo}`);
});
client.on('error', (err) => {
activeSSHConnections.delete(client);
console.error(`[-] Admin connection error: ${err.message}`);
})
});
// 启动SSH服务器
sshServer.listen(SSH_PORT, '0.0.0.0', () => {
console.log(`[*] SSH management server listening on port ${SSH_PORT}`);
console.log('[*] Waiting for admin connections...');
console.log(`[*] Public key for admin connection: ${fs.readFileSync(publicKeyPath, 'utf8')}`);
});