forked from mscdex/ssh2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-integration-openssh.js
486 lines (445 loc) · 14.3 KB
/
test-integration-openssh.js
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// TODO: add more rekey tests that at least include switching from no
// compression to compression and vice versa
'use strict';
const assert = require('assert');
const { spawn, spawnSync } = require('child_process');
const { chmodSync, readdirSync } = require('fs');
const { join } = require('path');
const readline = require('readline');
const Server = require('../lib/server.js');
const {
fixture,
fixtureKey,
FIXTURES_DIR,
mustCall,
mustCallAtLeast,
} = require('./common.js');
const SPAWN_OPTS = { windowsHide: true };
const CLIENT_TIMEOUT = 5000;
const debug = false;
const opensshPath = 'ssh';
let opensshVer;
// TODO: figure out why this test is failing on Windows
if (process.platform === 'win32') {
console.log('Skipping OpenSSH integration tests on Windows');
process.exit(0);
}
// Fix file modes to avoid OpenSSH client complaints about keys' permissions
for (const file of readdirSync(FIXTURES_DIR, { withFileTypes: true })) {
if (file.isFile())
chmodSync(join(FIXTURES_DIR, file.name), 0o600);
}
{
// Get OpenSSH client version first
const {
error, stderr, stdout
} = spawnSync(opensshPath, ['-V'], SPAWN_OPTS);
if (error) {
console.error('OpenSSH client is required for these tests');
process.exitCode = 5;
return;
}
const re = /^OpenSSH_([\d.]+)/;
let m = re.exec(stdout.toString());
if (!m || !m[1]) {
m = re.exec(stderr.toString());
if (!m || !m[1]) {
console.error('OpenSSH client is required for these tests');
process.exitCode = 5;
return;
}
}
opensshVer = m[1];
console.log(`Testing with OpenSSH version: ${opensshVer}`);
}
// Key-based authentication
[
{ desc: 'RSA user key (old OpenSSH)',
clientKey: fixtureKey('id_rsa') },
{ desc: 'RSA user key (new OpenSSH)',
clientKey: fixtureKey('openssh_new_rsa') },
{ desc: 'DSA user key',
clientKey: fixtureKey('id_dsa') },
{ desc: 'ECDSA user key',
clientKey: fixtureKey('id_ecdsa') },
].forEach((test) => {
const { desc, clientKey } = test;
const username = 'KeyUser';
const { server } = setup(
desc,
{
client: {
username,
privateKeyPath: clientKey.fullPath,
},
server: { hostKeys: [ fixture('ssh_host_rsa_key') ] },
debug,
}
);
server.on('connection', mustCall((conn) => {
let authAttempt = 0;
conn.on('authentication', mustCallAtLeast((ctx) => {
assert(ctx.username === username,
`Wrong username: ${ctx.username}`);
switch (++authAttempt) {
case 1:
assert(ctx.method === 'none',
`Wrong auth method: ${ctx.method}`);
return ctx.reject();
case 2:
case 3:
if (authAttempt === 3)
assert(ctx.signature, 'Missing publickey signature');
assert(ctx.method === 'publickey',
`Wrong auth method: ${ctx.method}`);
assert(ctx.key.algo === clientKey.key.type,
`Wrong key algo: ${ctx.key.algo}`);
assert.deepStrictEqual(clientKey.key.getPublicSSH(),
ctx.key.data,
'Public key mismatch');
break;
default:
assert(false, 'Unexpected number of auth attempts');
}
if (ctx.signature) {
const result =
clientKey.key.verify(ctx.blob, ctx.signature, ctx.hashAlgo);
assert(result === true, 'Could not verify publickey signature');
// We should not expect any further auth attempts after we verify a
// signature
authAttempt = Infinity;
}
ctx.accept();
}, 2)).on('ready', mustCall(() => {
conn.on('session', mustCall((accept, reject) => {
accept().on('exec', mustCall((accept, reject) => {
const stream = accept();
stream.exit(0);
stream.end();
}));
}));
}));
}));
});
// Different host key types
[
{ desc: 'RSA host key (old OpenSSH)',
hostKey: fixture('id_rsa') },
{ desc: 'RSA host key (new OpenSSH)',
hostKey: fixture('openssh_new_rsa') },
{ desc: 'DSA host key',
hostKey: fixture('ssh_host_dsa_key') },
{ desc: 'ECDSA host key',
hostKey: fixture('ssh_host_ecdsa_key') },
{ desc: 'PPK',
hostKey: fixture('id_rsa.ppk') },
].forEach((test) => {
const { desc, hostKey } = test;
const clientKey = fixtureKey('openssh_new_rsa');
const username = 'KeyUser';
const { server } = setup(
desc,
{
client: {
username,
privateKeyPath: clientKey.fullPath,
},
server: { hostKeys: [ hostKey ] },
debug,
}
);
server.on('connection', mustCall((conn) => {
let authAttempt = 0;
conn.on('authentication', mustCallAtLeast((ctx) => {
assert(ctx.username === username,
`Wrong username: ${ctx.username}`);
switch (++authAttempt) {
case 1:
assert(ctx.method === 'none',
`Wrong auth method: ${ctx.method}`);
return ctx.reject();
case 2:
case 3:
if (authAttempt === 3)
assert(ctx.signature, 'Missing publickey signature');
assert(ctx.method === 'publickey',
`Wrong auth method: ${ctx.method}`);
assert(ctx.key.algo === clientKey.key.type,
`Wrong key algo: ${ctx.key.algo}`);
assert.deepStrictEqual(clientKey.key.getPublicSSH(),
ctx.key.data,
'Public key mismatch');
break;
default:
assert(false, 'Unexpected number of auth attempts');
}
if (ctx.signature) {
const result =
clientKey.key.verify(ctx.blob, ctx.signature, ctx.hashAlgo);
assert(result === true, 'Could not verify publickey signature');
// We should not expect any further auth attempts after we verify a
// signature
authAttempt = Infinity;
}
ctx.accept();
}, 2)).on('ready', mustCall(() => {
conn.on('session', mustCall((accept, reject) => {
accept().on('exec', mustCall((accept, reject) => {
const stream = accept();
stream.exit(0);
stream.end();
}));
}));
}));
}));
});
// Various edge cases
{
const clientKey = fixtureKey('openssh_new_rsa');
const username = 'KeyUser';
const { server } = setup(
'Server closes stdin too early',
{
client: {
username,
privateKeyPath: clientKey.fullPath,
},
server: { hostKeys: [ fixture('ssh_host_rsa_key') ] },
debug,
}
);
server.on('_child', mustCall((childProc) => {
childProc.stderr.once('data', mustCall((data) => {
childProc.stdin.end();
}));
childProc.stdin.write('ping');
})).on('connection', mustCall((conn) => {
let authAttempt = 0;
conn.on('authentication', mustCallAtLeast((ctx) => {
assert(ctx.username === username,
`Wrong username: ${ctx.username}`);
switch (++authAttempt) {
case 1:
assert(ctx.method === 'none',
`Wrong auth method: ${ctx.method}`);
return ctx.reject();
case 2:
case 3:
if (authAttempt === 3)
assert(ctx.signature, 'Missing publickey signature');
assert(ctx.method === 'publickey',
`Wrong auth method: ${ctx.method}`);
assert(ctx.key.algo === clientKey.key.type,
`Wrong key algo: ${ctx.key.algo}`);
assert.deepStrictEqual(clientKey.key.getPublicSSH(),
ctx.key.data,
'Public key mismatch');
break;
default:
assert(false, 'Unexpected number of auth attempts');
}
if (ctx.signature) {
const result =
clientKey.key.verify(ctx.blob, ctx.signature, ctx.hashAlgo);
assert(result === true, 'Could not verify publickey signature');
// We should not expect any further auth attempts after we verify a
// signature
authAttempt = Infinity;
}
ctx.accept();
}, 2)).on('ready', mustCall(() => {
conn.on('session', mustCall((accept, reject) => {
accept().on('exec', mustCall((accept, reject) => {
const stream = accept();
stream.stdin.on('data', mustCallAtLeast((data) => {
stream.stdout.write('pong on stdout');
stream.stderr.write('pong on stderr');
})).on('end', mustCall(() => {
stream.stdout.write('pong on stdout');
stream.stderr.write('pong on stderr');
stream.exit(0);
stream.close();
}));
}));
}));
}));
}));
}
{
const clientKey = fixtureKey('openssh_new_rsa');
const username = 'KeyUser';
const { server } = setup(
'Rekey',
{
client: {
username,
privateKeyPath: clientKey.fullPath,
},
server: { hostKeys: [ fixture('ssh_host_rsa_key') ] },
debug,
}
);
server.on('connection', mustCall((conn) => {
let authAttempt = 0;
conn.on('authentication', mustCallAtLeast((ctx) => {
assert(ctx.username === username,
`Wrong username: ${ctx.username}`);
switch (++authAttempt) {
case 1:
assert(ctx.method === 'none',
`Wrong auth method: ${ctx.method}`);
return ctx.reject();
case 2:
case 3:
if (authAttempt === 3)
assert(ctx.signature, 'Missing publickey signature');
assert(ctx.method === 'publickey',
`Wrong auth method: ${ctx.method}`);
assert(ctx.key.algo === clientKey.key.type,
`Wrong key algo: ${ctx.key.algo}`);
assert.deepStrictEqual(clientKey.key.getPublicSSH(),
ctx.key.data,
'Public key mismatch');
break;
default:
assert(false, 'Unexpected number of auth attempts');
}
if (ctx.signature) {
const result =
clientKey.key.verify(ctx.blob, ctx.signature, ctx.hashAlgo);
assert(result === true, 'Could not verify publickey signature');
// We should not expect any further auth attempts after we verify a
// signature
authAttempt = Infinity;
}
ctx.accept();
}, 2)).on('ready', mustCall(() => {
conn.on('session', mustCall((accept, reject) => {
const session = accept();
conn.rekey();
session.on('exec', mustCall((accept, reject) => {
const stream = accept();
stream.exit(0);
stream.end();
}));
}));
}));
}));
}
function setup(title, configs) {
const {
client: clientCfg,
server: serverCfg,
allReady: allReady_,
timeout: timeout_,
debug,
noForceServerReady,
} = configs;
let clientClose = false;
let serverClose = false;
let serverReady = false;
let client;
const msg = (text) => {
return `${title}: ${text}`;
};
const timeout = (typeof timeout_ === 'number'
? timeout_
: CLIENT_TIMEOUT);
const allReady = (typeof allReady_ === 'function' ? allReady_ : undefined);
if (debug) {
serverCfg.debug = (...args) => {
console.log(`[${title}][SERVER]`, ...args);
};
}
const serverReadyFn = (noForceServerReady ? onReady : mustCall(onReady));
const server = new Server(serverCfg);
server.on('error', onError)
.on('connection', mustCall((conn) => {
conn.on('error', onError)
.on('ready', serverReadyFn);
server.close();
}))
.on('close', mustCall(onClose));
function onError(err) {
const which = (arguments.length >= 3 ? 'client' : 'server');
assert(false, msg(`Unexpected ${which} error: ${err}`));
}
function onReady() {
assert(!serverReady, msg('Received multiple ready events for server'));
serverReady = true;
allReady && allReady();
}
function onClose() {
if (arguments.length >= 3) {
assert(!clientClose, msg('Received multiple close events for client'));
clientClose = true;
} else {
assert(!serverClose, msg('Received multiple close events for server'));
serverClose = true;
}
}
process.nextTick(mustCall(() => {
server.listen(0, 'localhost', mustCall(() => {
const args = [
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'StrictHostKeyChecking=no',
'-o', 'CheckHostIP=no',
'-o', 'ConnectTimeout=3',
'-o', 'GlobalKnownHostsFile=/dev/null',
'-o', 'GSSAPIAuthentication=no',
'-o', 'IdentitiesOnly=yes',
'-o', 'BatchMode=yes',
'-o', 'VerifyHostKeyDNS=no',
'-vvvvvv',
'-T',
'-o', 'KbdInteractiveAuthentication=no',
'-o', 'HostbasedAuthentication=no',
'-o', 'PasswordAuthentication=no',
'-o', 'PubkeyAuthentication=yes',
'-o', 'PreferredAuthentications=publickey'
];
if (clientCfg.privateKeyPath)
args.push('-o', `IdentityFile=${clientCfg.privateKeyPath}`);
if (!/^[0-6]\./.test(opensshVer)) {
// OpenSSH 7.0+ disables DSS/DSA host (and user) key support by
// default, so we explicitly enable it here
args.push('-o', 'HostKeyAlgorithms=+ssh-dss');
args.push('-o', 'PubkeyAcceptedKeyTypes=+ssh-dss');
args.push('-o', 'PubkeyAcceptedAlgorithms=+ssh-dss');
}
args.push('-p', server.address().port.toString(),
'-l', clientCfg.username,
'localhost',
'uptime');
client = spawn(opensshPath, args, SPAWN_OPTS);
server.emit('_child', client);
if (debug) {
readline.createInterface({
input: client.stdout
}).on('line', (line) => {
console.log(`[${title}][CLIENT][STDOUT]`, line);
});
readline.createInterface({
input: client.stderr
}).on('line', (line) => {
console.error(`[${title}][CLIENT][STDERR]`, line);
});
} else {
client.stdout.resume();
client.stderr.resume();
}
client.on('error', (err) => {
onError(err, null, null);
}).on('exit', (code) => {
clearTimeout(client.timer);
if (code !== 0)
return onError(new Error(`Non-zero exit code ${code}`), null, null);
onClose(null, null, null);
});
client.timer = setTimeout(() => {
assert(false, msg('Client timeout'));
}, timeout);
}));
}));
return { server };
}