forked from mdsummers/mock-ssh-responses
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
executable file
·184 lines (167 loc) · 6.06 KB
/
cli.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
#!/usr/local/bin/node
const YAML = require('yamljs');
const fs = require('fs');
const path = require('path');
const execFile = require('child_process').execFile;
const replace = require('replace-in-file');
const argv = require('minimist')(process.argv.slice(2), {
boolean: ['help', 'automate'],
string: ['command', 'generate-keypair'],
alias: {
command: ['cmd', 'c'],
'generate-keypair': ['generate', 'g'],
automate: ['auto','a'],
help: 'h'
}
});
function fatal () {
console.error.apply(null, arguments);
process.exit(255);
}
function debug () {
if (process.env.DEBUG) {
console.error.apply(null, ['DEBUG'].concat(Array.prototype.slice.call(arguments, 0)));
}
}
function generate (answerFile, privateKeyPath, cb) {
const basename = answerFile.replace(/^.*\//, '');
if (argv.auto) {
execFile('ssh-keygen', [
'-t', 'rsa',
'-b', '2048',
'-f', privateKeyPath,
'-N', '',
'-C', basename + '@mock-ssh-responses',
], cb);
} else {
execFile('ssh-keygen', [
'-t', 'rsa',
'-b', '2048',
'-f', privateKeyPath,
'-C', basename + '@mock-ssh-responses',
], cb);
}
}
if (argv.help) {
console.log('TODO: help');
process.exit(0);
}
let answerFile = argv._[0];
if (!answerFile) {
fatal('First argument should be the path to an answers file');
}
let answers;
try {
answers = YAML.load(answerFile);
} catch (err) {
fatal('Unable to parse answers file at %s', answerFile);
}
if (!Array.isArray(answers)) {
fatal('Answers are not in an array');
}
if (argv.generate) {
// File paths
const resolvedAnswerFile = path.resolve(answerFile);
const resolvedGeneratePath = path.resolve(argv.generate);
const authorizedKeysFile = resolvedGeneratePath.replace(/mocked-localhost/, 'authorized_keys');
const configFile = resolvedGeneratePath.replace(/mocked-localhost/, 'config');
const hostEntry = [ '',
'Host mock-' + answerFile.replace(/^.*\//, ''),
' HostName localhost',
' IdentityFile ' + resolvedGeneratePath
].join("\n")
if (!fs.existsSync(path)) {
// Do something
}
// Remove old private key
execFile('rm', ['-f', resolvedGeneratePath], (error, stdout, stderr) => { if (error) { throw error; } });
return generate(answerFile, argv.generate, function (error) {
if (error) {
fatal('Failed to generate key at %s', argv.generate, error);
}
fs.readFile(argv.generate + '.pub', 'utf-8', function (error, contents) {
// Generate new authorized key
const authorizedKey = 'command="' + process.argv[1] + ' ' + resolvedAnswerFile + '",no-port-forwarding,no-X11-forwarding,no-pty' + ' ' + contents.replace(/\n$/, '');
// Automate flag is present
if (argv.auto) {
if (fs.existsSync(authorizedKeysFile)) {
// Replace old key with new key if it exists. Otherwise append new key.
const options = {
files: authorizedKeysFile,
replace: /command.*mock-ssh-responses/g,
with: authorizedKey
};
replace(options, (error, changedFile) => {
if (error) { fatal('Error occurred while replacing key: ', error); }
// Append new key if old key did not exist and was not replaced
if (changedFile == '') {
// If authorized_keys file exists
fs.appendFile(authorizedKeysFile, authorizedKey, function (error) {
if (error) { fatal('Error occurred while appending key to authorized_keys file: ', error); }
});
}
});
} else {
// Create authorized_keys file
fs.openSync(authorizedKeysFile, 'w', function (error) {
if (error) { fatal('Error occurred while creating authorized_keys file: ', error); }
});
// Change permissions
fs.chmodSync(authorizedKeysFile, '600');
// Append to file
fs.appendFile(authorizedKeysFile, authorizedKey, function (error) {
if (error) { fatal('Error occurred while appending key to authorized_keys file: ', error); }
});
}
if (fs.existsSync(configFile)) {
// If host entry is not present append to config fle
fs.readFile(configFile, function (err, data) {
if (err) throw err;
if(data.indexOf(resolvedGeneratePath) < 0){
fs.appendFile(configFile, hostEntry, function (error) {
if (error) { fatal('Error occurred while appending host entry to config file: ', error); }
});
}
});
} else {
// Create authorized_keys file
fs.openSync(configFile, 'w', function (error) {
if (error) { fatal('Error occurred while creating config file: ', error); }
});
// Change permissions
fs.chmodSync(configFile, '644');
// Append to file
fs.appendFile(configFile, hostEntry, function (error) {
if (error) { fatal('Error occurred while appending host entry to new config file: ', error); }
});
}
// Automate flag is not present
} else {
// Print manual steps
console.log('Place the following line in your authorized_keys file:');
console.log(authorizedKey);
console.log();
console.log('Place the following lines in your ~/.ssh/config:');
console.log(hostEntry);
console.log();
console.log('Or use the --auto flag to apply the changes automatically');
}
});
});
}
const cmd = argv.command || process.env['SSH_ORIGINAL_COMMAND'];
debug('Command to match is', cmd);
if (!cmd) {
fatal('Command should be provided either as an argument or via env');
}
const filtered = answers.filter(function (answer) {
debug('Trying to match against', answer.cmd);
return answer.cmd === cmd;
});
if (!filtered.length) {
fatal('No matched answers');
}
const matched = filtered[0];
if (matched.stdout) console.log(matched.stdout.replace(/\n$/, ''));
if (matched.stderr) console.error(matched.stderr.replace(/\n$/, ''));
process.exit(matched.code || 0);