libastion 0.0.1 → 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -41,9 +41,18 @@ BASTION_PORT=2222
41
41
 
42
42
  # 日志级别
43
43
  BASTION_LOG_LEVEL=info
44
+
45
+ # 首次启动创建默认管理员时使用的密码(默认 admin123,生产环境务必设置)
46
+ # BASTION_ADMIN_PASSWORD=change-me-now
47
+ ```
48
+
49
+ ### 4. 生成 SSH 主机密钥
50
+
51
+ ```bash
52
+ ssh-keygen -t ed25519 -f host.key -N ""
44
53
  ```
45
54
 
46
- ### 3. 启动服务
55
+ ### 5. 启动服务
47
56
 
48
57
  ```bash
49
58
  npm start
@@ -51,7 +60,7 @@ npm start
51
60
  node bin/server.js
52
61
  ```
53
62
 
54
- ### 4. 使用 CLI 管理
63
+ ### 6. 使用 CLI 管理
55
64
 
56
65
  ```bash
57
66
  # 添加目标主机
@@ -73,7 +82,7 @@ node bin/cli.js list-sessions
73
82
  node bin/cli.js show-commands 1
74
83
  ```
75
84
 
76
- ### 5. 连接堡垒机
85
+ ### 7. 连接堡垒机
77
86
 
78
87
  ```bash
79
88
  ssh admin@localhost -p 2222
@@ -183,9 +192,9 @@ node bin/cli.js update-password admin new_password
183
192
 
184
193
  ## 技术栈
185
194
 
186
- - Node.js >= 18
195
+ - Node.js >= 22.5
187
196
  - ssh2 - SSH Server + Client
188
- - better-sqlite3 - 数据库
197
+ - node:sqlite - 数据库
189
198
  - bcryptjs - 密码哈希
190
199
  - winston - 日志
191
200
  - commander - CLI 工具
package/bin/server.js CHANGED
@@ -12,10 +12,19 @@ const sessionMod = require('../src/session');
12
12
  const logger = require('../src/logger');
13
13
  const svc = 'server';
14
14
 
15
+ if (!config.masterKey) {
16
+ logger.warn(`${svc}: BASTION_MASTER_KEY is not set, host credentials cannot be encrypted/decrypted`);
17
+ }
18
+
15
19
  logger.info(`${svc}: starting on port ${config.server.port}`);
16
20
  auth.initDefaults();
17
21
 
18
- const hostKey = fs.readFileSync(path.join(__dirname, '..', 'host.key'), 'utf8');
22
+ const hostKeyPath = path.join(__dirname, '..', 'host.key');
23
+ if (!fs.existsSync(hostKeyPath)) {
24
+ logger.error(`${svc}: host key not found at ${hostKeyPath}. Generate one with: ssh-keygen -t ed25519 -f host.key`);
25
+ process.exit(1);
26
+ }
27
+ const hostKey = fs.readFileSync(hostKeyPath, 'utf8');
19
28
  const server = new Server({ hostKeys: [hostKey] });
20
29
 
21
30
  server.on('connection', (client, info) => {
@@ -26,13 +35,14 @@ server.on('connection', (client, info) => {
26
35
 
27
36
  client.on('authentication', (ctx) => {
28
37
  if (ctx.method !== 'password') return ctx.reject(['password']);
29
- if (sessionMod.getActiveSessions() >= sessionMod.getMaxSessions()) return ctx.reject();
38
+ if (sessionMod.getActiveSessions() >= sessionMod.getMaxSessions()) return ctx.reject(['password']);
30
39
  const u = auth.authenticate(ctx.username, ctx.password);
31
40
  if (!u) return ctx.reject(['password']);
32
41
  const hs = auth.getUserHosts(u.id);
33
42
  if (hs.length === 0) return ctx.reject(['password']);
34
43
  user = u;
35
44
  host = hosts.getHost(hs[0].id);
45
+ if (!host) return ctx.reject(['password']);
36
46
  ctx.accept();
37
47
  logger.info(`${svc}: auth ok ${u.username}`);
38
48
  });
@@ -49,24 +59,44 @@ server.on('connection', (client, info) => {
49
59
  const stream = acceptShell();
50
60
  const as = audit.createSession(user.id, host.id, connInfo.ip);
51
61
  let last = Date.now();
62
+ let timerCleared = false;
63
+ const stopTimer = () => {
64
+ if (!timerCleared) {
65
+ timerCleared = true;
66
+ clearInterval(t);
67
+ }
68
+ };
69
+
52
70
  const t = setInterval(() => {
53
71
  if (Date.now() - last > config.server.idleTimeoutSec * 1000) {
54
72
  stream.write('\r\n*** idle timeout ***\r\n');
55
73
  stream.end();
56
74
  client.end();
57
- clearInterval(t);
75
+ stopTimer();
58
76
  }
59
77
  }, 30000);
78
+
60
79
  sessionMod.createClientConnection(host, user.id, as.id, null).then((c) => {
61
80
  c.shell({ term: 'vt100' }, (err, rs) => {
62
- if (err) { stream.end(); return; }
81
+ if (err) {
82
+ stopTimer();
83
+ audit.endSession(as.id, 'error');
84
+ stream.end();
85
+ return;
86
+ }
63
87
  rs.on('data', (d) => { last = Date.now(); stream.write(d); });
64
88
  stream.on('data', (d) => { last = Date.now(); rs.write(d); });
65
- const close = () => { clearInterval(t); audit.endSession(as.id, 'closed'); client.end(); };
89
+ const close = () => {
90
+ stopTimer();
91
+ audit.endSession(as.id, 'closed');
92
+ c.end();
93
+ client.end();
94
+ };
66
95
  rs.on('close', close);
67
96
  stream.on('close', close);
68
97
  });
69
98
  }).catch((e) => {
99
+ stopTimer();
70
100
  logger.error(`${svc}: upstream connect failed: ${e.message}`);
71
101
  stream.write('\r\n*** upstream connect failed ***\r\n');
72
102
  stream.end();
@@ -74,7 +104,7 @@ server.on('connection', (client, info) => {
74
104
  });
75
105
 
76
106
  ch.on('exec', (acceptExec, rejectExec, info) => {
77
- if (!user || !host) { rejectExec && rejectExec(); return; }
107
+ if (!user || !host) { if (rejectExec) rejectExec(new Error('no target host')); return; }
78
108
  const as = audit.createSession(user.id, host.id, connInfo.ip);
79
109
  const bp = policy.checkCommand(info.command);
80
110
  if (bp.blocked) {
@@ -89,38 +119,123 @@ server.on('connection', (client, info) => {
89
119
  audit.recordCommand(as.id, info.command, false);
90
120
  sessionMod.createClientConnection(host, user.id, as.id, null).then((c) => {
91
121
  c.exec(info.command, (err, rs) => {
92
- if (err) { rejectExec && rejectExec(); return; }
122
+ if (err) {
123
+ audit.endSession(as.id, 'error');
124
+ if (rejectExec) rejectExec(err);
125
+ return;
126
+ }
93
127
  const s = acceptExec();
128
+ let exitCode = 0;
129
+ rs.on('exitStatus', (code) => { exitCode = code; });
94
130
  rs.on('data', (d) => s.write(d));
95
131
  rs.stderr.on('data', (d) => s.stderr && s.stderr.write(d));
96
- rs.on('close', () => { s.exit(0); s.end(); c.end(); audit.endSession(as.id, 'closed'); });
132
+ rs.on('close', () => {
133
+ s.exit(exitCode);
134
+ s.end();
135
+ c.end();
136
+ audit.endSession(as.id, 'closed');
137
+ });
97
138
  });
98
- }).catch((e) => { rejectExec && rejectExec(); });
139
+ }).catch((e) => {
140
+ audit.endSession(as.id, 'error');
141
+ if (rejectExec) rejectExec(e);
142
+ });
99
143
  });
100
144
 
101
- ch.on('sftp', (acceptSftp) => {
102
- if (!user || !host) { ch.close(); return; }
145
+ ch.on('subsystem', (accept, reject, info) => {
146
+ if (info.name !== 'sftp') {
147
+ if (reject) reject(new Error('unsupported subsystem'));
148
+ return;
149
+ }
150
+ if (!user || !host) {
151
+ if (reject) reject(new Error('no target host'));
152
+ return;
153
+ }
103
154
  const as = audit.createSession(user.id, host.id, connInfo.ip);
104
- const sc = acceptSftp();
105
- sc.on('OPEN', (reqid, filename, flags) => {
106
- const dir = (flags & 3) ? 'upload' : 'download';
107
- audit.recordTransfer(as.id, dir, filename, 0);
155
+ // accept() returns the raw channel (no SFTP parser attached), enabling
156
+ // protocol-level relaying to the target host
157
+ const sc = accept();
158
+
159
+ // Minimal SFTP packet parser to audit OPEN operations (upload/download)
160
+ let buf = Buffer.alloc(0);
161
+ const onClientData = (chunk) => {
162
+ buf = Buffer.concat([buf, chunk]);
163
+ while (buf.length >= 4) {
164
+ const len = buf.readUInt32BE(0);
165
+ if (buf.length < 4 + len) break;
166
+ const pkt = buf.subarray(4, 4 + len);
167
+ buf = buf.subarray(4 + len);
168
+ if (pkt.length < 13) continue;
169
+ const type = pkt[0];
170
+ if (type === 3) { // SSH_FXP_OPEN: type(1) reqid(4) filename(4+n) flags(4) attrs(4)
171
+ const nameLen = pkt.readUInt32BE(5);
172
+ if (13 + nameLen <= pkt.length) {
173
+ const filename = pkt.subarray(9, 9 + nameLen).toString('utf8');
174
+ const flags = pkt.readUInt32BE(9 + nameLen);
175
+ // SSH_FXF_WRITE (0x02) => upload, otherwise read => download
176
+ audit.recordTransfer(as.id, (flags & 0x02) ? 'upload' : 'download', filename, 0);
177
+ }
178
+ }
179
+ }
180
+ };
181
+
182
+ // Buffer client packets until the upstream SFTP channel is ready
183
+ let sftp = null;
184
+ const pending = [];
185
+ sc.on('data', (d) => {
186
+ if (sftp) {
187
+ onClientData(d);
188
+ sftp.write(d);
189
+ } else {
190
+ pending.push(d);
191
+ }
108
192
  });
193
+
109
194
  sessionMod.createClientConnection(host, user.id, as.id, null).then((c) => {
110
- c.sftp((err) => { if (err) { sc.close(); } });
195
+ // Open a raw sftp subsystem channel (no SFTP parser) so we can relay
196
+ // protocol packets byte-for-byte between client and target
197
+ c.subsys('sftp', (err, sftpChannel) => {
198
+ if (err) {
199
+ audit.endSession(as.id, 'error');
200
+ sc.close();
201
+ return;
202
+ }
203
+ sftp = sftpChannel;
204
+ // Flush packets received while the upstream channel was being established
205
+ for (const d of pending) {
206
+ onClientData(d);
207
+ sftp.write(d);
208
+ }
209
+ pending.length = 0;
210
+ // Relay raw SFTP protocol packets from target to client
211
+ sftp.on('data', (d) => sc.write(d));
212
+ const close = () => {
213
+ audit.endSession(as.id, 'closed');
214
+ sc.end();
215
+ sftp.end();
216
+ c.end();
217
+ };
218
+ sftp.on('close', close);
219
+ sc.on('close', close);
220
+ });
111
221
  }).catch(() => sc.close());
112
222
  });
113
223
 
114
224
  ch.on('direct-tcpip', (acceptDst, rejectDst, info) => {
115
- if (!user || !host) { rejectDst && rejectDst(new Error('unavailable')); return; }
225
+ if (!user || !host) {
226
+ if (rejectDst) rejectDst(new Error('no target host'));
227
+ return;
228
+ }
229
+ // Port forwarding is intentionally disabled; log the attempt for audit
116
230
  const as = audit.createSession(user.id, host.id, connInfo.ip);
117
231
  audit.recordForward(as.id, 'direct-tcpip', info.srcIP, info.srcPort, info.destIP, info.destPort);
118
- rejectDst ? rejectDst(new Error('port forwarding disabled')) : acceptDst().end();
119
232
  audit.endSession(as.id, 'closed');
233
+ if (rejectDst) return rejectDst(new Error('port forwarding disabled'));
234
+ acceptDst().end();
120
235
  });
121
236
  });
122
237
 
123
238
  client.on('close', () => logger.info(`${svc}: conn closed`));
124
239
  });
125
240
 
126
- server.listen(config.server.port, () => logger.info(`${svc}: ready on port ${config.server.port}`));
241
+ server.listen(config.server.port, () => logger.info(`${svc}: ready on port ${config.server.port}`));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libastion",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "A lightweight bastion host built with Node.js",
5
5
  "main": "bin/server.js",
6
6
  "bin": {
@@ -34,6 +34,6 @@
34
34
  "PLAN.md"
35
35
  ],
36
36
  "engines": {
37
- "node": ">=18"
37
+ "node": ">=22.5"
38
38
  }
39
39
  }
@@ -92,7 +92,7 @@ function queryCommands(sessionId, options = {}) {
92
92
  * Query sessions
93
93
  */
94
94
  function querySessions(options = {}) {
95
- let sql = 'SELECT s.*, u.username, h.name as host_name, h.host as host_addr FROM audit_sessions s JOIN users u ON u.id = s.user_id JOIN hosts h ON h.id = s.host_id WHERE 1=1';
95
+ let sql = 'SELECT s.*, u.username, h.name as host_name, h.host as host_addr, h.port as host_port FROM audit_sessions s JOIN users u ON u.id = s.user_id JOIN hosts h ON h.id = s.host_id WHERE 1=1';
96
96
  const params = [];
97
97
 
98
98
  if (options.userId) {
package/src/auth/index.js CHANGED
@@ -9,7 +9,11 @@ const service = 'auth';
9
9
  function initDefaults() {
10
10
  const user = db.prepare('SELECT id FROM users WHERE username = ?').get('admin');
11
11
  if (!user) {
12
- const hash = bcrypt.hashSync('admin123', 10);
12
+ const defaultPassword = process.env.BASTION_ADMIN_PASSWORD || 'admin123';
13
+ if (!process.env.BASTION_ADMIN_PASSWORD) {
14
+ logger.warn(`${service}: Using default admin password, set BASTION_ADMIN_PASSWORD and change it immediately after first login`);
15
+ }
16
+ const hash = bcrypt.hashSync(defaultPassword, 10);
13
17
  db.prepare(
14
18
  'INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)'
15
19
  ).run('admin', hash, 'admin');
@@ -22,6 +26,8 @@ function authenticate(username, password) {
22
26
  const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
23
27
  if (!user) {
24
28
  logger.warn(`${service}: User not found`, { username });
29
+ // Mitigate username enumeration via response timing
30
+ bcrypt.compareSync(password, '$2a$10$CwTycUXWue0Thq9StjUM0uJ8mRr5mN5H9vYjP9gK7q6kQbY3xXyWq');
25
31
  return null;
26
32
  }
27
33
 
package/src/cli/index.js CHANGED
@@ -11,7 +11,7 @@ const program = new Command();
11
11
  program
12
12
  .name('bastion')
13
13
  .description('CLI for bastion host management')
14
- .version('0.1.0');
14
+ .version('0.0.2');
15
15
 
16
16
  // User commands
17
17
  program
@@ -135,7 +135,7 @@ program
135
135
  sessions.forEach(s => {
136
136
  console.log(` ID: ${s.id}`);
137
137
  console.log(` User: ${s.username}`);
138
- console.log(` Host: ${s.host_name} (${s.host_addr}:${22})`);
138
+ console.log(` Host: ${s.host_name} (${s.host_addr}:${s.host_port})`);
139
139
  console.log(` Client IP: ${s.client_ip}`);
140
140
  console.log(` Status: ${s.status}`);
141
141
  console.log(` Started: ${s.start_time}`);
@@ -12,20 +12,28 @@ try {
12
12
  console.error('Failed to load config.json:', e.message);
13
13
  }
14
14
 
15
+ function toInt(value, fallback, min, max) {
16
+ const n = parseInt(value, 10);
17
+ if (Number.isNaN(n)) return fallback;
18
+ if (min !== undefined && n < min) return fallback;
19
+ if (max !== undefined && n > max) return fallback;
20
+ return n;
21
+ }
22
+
15
23
  module.exports = {
16
24
  server: {
17
- port: parseInt(process.env.BASTION_PORT || config.server?.port || 2222, 10),
18
- maxSessions: config.server?.maxSessions || 50,
19
- sessionTimeoutSec: config.server?.sessionTimeoutSec || 1800,
20
- idleTimeoutSec: config.server?.idleTimeoutSec || 900,
25
+ port: toInt(process.env.BASTION_PORT || config.server?.port || 2222, 2222, 1, 65535),
26
+ maxSessions: toInt(config.server?.maxSessions || 50, 50, 1, 10000),
27
+ sessionTimeoutSec: toInt(config.server?.sessionTimeoutSec || 1800, 1800, 0),
28
+ idleTimeoutSec: toInt(config.server?.idleTimeoutSec || 900, 900, 0),
21
29
  },
22
30
  auth: {
23
- maxFailedAttempts: config.auth?.maxFailedAttempts || 5,
24
- lockDurationSec: config.auth?.lockDurationSec || 900,
31
+ maxFailedAttempts: toInt(config.auth?.maxFailedAttempts || 5, 5, 1, 100),
32
+ lockDurationSec: toInt(config.auth?.lockDurationSec || 900, 900, 0),
25
33
  },
26
34
  policy: {
27
35
  blockedCommands: config.policy?.blockedCommands || [],
28
36
  },
29
37
  masterKey: process.env.BASTION_MASTER_KEY || '',
30
38
  logLevel: process.env.BASTION_LOG_LEVEL || config.logLevel || 'info',
31
- };
39
+ };
package/src/crypto.js CHANGED
@@ -1,14 +1,32 @@
1
1
  const crypto = require('crypto');
2
- const config = require('../config');
3
2
 
4
3
  const ALGORITHM = 'aes-256-gcm';
5
4
  const IV_LENGTH = 16;
6
- const SALT_LENGTH = 32;
5
+ const SALT_LENGTH = 16;
7
6
  const KEY_LENGTH = 32;
8
7
  const TAG_LENGTH = 16;
9
8
 
10
- function deriveKey(masterKey) {
11
- // Simple key derivation: hash master key
9
+ // scrypt parameters (16 MiB memory, ~50-100ms per derivation)
10
+ const SCRYPT_N = 16384;
11
+ const SCRYPT_R = 8;
12
+ const SCRYPT_P = 1;
13
+
14
+ // Current ciphertext format: v2:<salt>:<iv>:<tag>:<encrypted>
15
+ // Legacy format (no version prefix): <salt>:<iv>:<tag>:<encrypted> derived via sha256
16
+ const V2_PREFIX = 'v2:';
17
+ const LEGACY_PARTS = 4;
18
+
19
+ function deriveKeyV2(masterKey, salt) {
20
+ return crypto.scryptSync(masterKey, salt, KEY_LENGTH, {
21
+ N: SCRYPT_N,
22
+ r: SCRYPT_R,
23
+ p: SCRYPT_P,
24
+ maxmem: 64 * 1024 * 1024,
25
+ });
26
+ }
27
+
28
+ // Legacy derivation (sha256 without salt) kept for backward compatibility
29
+ function deriveKeyLegacy(masterKey) {
12
30
  return crypto.createHash('sha256').update(masterKey).digest();
13
31
  }
14
32
 
@@ -17,29 +35,37 @@ function encrypt(text, masterKey) {
17
35
 
18
36
  const salt = crypto.randomBytes(SALT_LENGTH);
19
37
  const iv = crypto.randomBytes(IV_LENGTH);
20
- const key = deriveKey(masterKey);
38
+ const key = deriveKeyV2(masterKey, salt);
21
39
 
22
40
  const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
23
41
  let encrypted = cipher.update(text, 'utf-8', 'hex');
24
42
  encrypted += cipher.final('hex');
25
43
  const tag = cipher.getAuthTag().toString('hex');
26
44
 
27
- // Format: salt:iv:tag:encrypted
28
- return [salt.toString('hex'), iv.toString('hex'), tag, encrypted].join(':');
45
+ return V2_PREFIX + [salt.toString('hex'), iv.toString('hex'), tag, encrypted].join(':');
29
46
  }
30
47
 
31
48
  function decrypt(encryptedText, masterKey) {
32
49
  if (!masterKey) throw new Error('Master key is not set');
50
+ if (typeof encryptedText !== 'string' || encryptedText.length === 0) {
51
+ throw new Error('Invalid encrypted format');
52
+ }
33
53
 
34
- const parts = encryptedText.split(':');
35
- if (parts.length !== 4) throw new Error('Invalid encrypted format');
54
+ const isV2 = encryptedText.startsWith(V2_PREFIX);
55
+ const payload = isV2 ? encryptedText.slice(V2_PREFIX.length) : encryptedText;
56
+ const parts = payload.split(':');
57
+ if (parts.length !== LEGACY_PARTS) throw new Error('Invalid encrypted format');
36
58
 
37
59
  const salt = Buffer.from(parts[0], 'hex');
38
60
  const iv = Buffer.from(parts[1], 'hex');
39
61
  const tag = Buffer.from(parts[2], 'hex');
40
62
  const encrypted = parts[3];
41
63
 
42
- const key = deriveKey(masterKey);
64
+ if (salt.length !== SALT_LENGTH || iv.length !== IV_LENGTH || tag.length !== TAG_LENGTH) {
65
+ throw new Error('Invalid encrypted format');
66
+ }
67
+
68
+ const key = isV2 ? deriveKeyV2(masterKey, salt) : deriveKeyLegacy(masterKey);
43
69
  const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
44
70
  decipher.setAuthTag(tag);
45
71
 
@@ -49,4 +75,4 @@ function decrypt(encryptedText, masterKey) {
49
75
  return decrypted;
50
76
  }
51
77
 
52
- module.exports = { encrypt, decrypt };
78
+ module.exports = { encrypt, decrypt };
package/src/logger.js CHANGED
@@ -1,6 +1,13 @@
1
1
  const winston = require('winston');
2
+ const fs = require('fs');
3
+ const path = require('path');
2
4
  const config = require('./config');
3
5
 
6
+ const LOG_DIR = path.join(__dirname, '..', 'logs');
7
+ if (!fs.existsSync(LOG_DIR)) {
8
+ fs.mkdirSync(LOG_DIR, { recursive: true });
9
+ }
10
+
4
11
  const logger = winston.createLogger({
5
12
  level: config.logLevel,
6
13
  format: winston.format.combine(
@@ -19,13 +26,13 @@ const logger = winston.createLogger({
19
26
  ),
20
27
  }),
21
28
  new winston.transports.File({
22
- filename: 'logs/error.log',
29
+ filename: path.join(LOG_DIR, 'error.log'),
23
30
  level: 'error',
24
31
  }),
25
32
  new winston.transports.File({
26
- filename: 'logs/combined.log',
33
+ filename: path.join(LOG_DIR, 'combined.log'),
27
34
  }),
28
35
  ],
29
36
  });
30
37
 
31
- module.exports = logger;
38
+ module.exports = logger;
@@ -3,11 +3,15 @@ const logger = require('../logger');
3
3
 
4
4
  const service = 'policy';
5
5
 
6
- // Pre-compile regex patterns
7
- const blockedPatterns = config.policy.blockedCommands.map(pattern => ({
8
- pattern: new RegExp(pattern, 'i'),
9
- original: pattern,
10
- }));
6
+ // Pre-compile regex patterns, skipping invalid ones instead of crashing the server
7
+ const blockedPatterns = [];
8
+ for (const pattern of config.policy.blockedCommands) {
9
+ try {
10
+ blockedPatterns.push({ pattern: new RegExp(pattern, 'i'), original: pattern });
11
+ } catch (e) {
12
+ logger.warn(`${service}: Skipping invalid blocked-command pattern "${pattern}": ${e.message}`);
13
+ }
14
+ }
11
15
 
12
16
  /**
13
17
  * Check if a command is blocked
@@ -29,4 +33,4 @@ function checkCommand(command) {
29
33
  return { blocked: false, reason: null };
30
34
  }
31
35
 
32
- module.exports = { checkCommand };
36
+ module.exports = { checkCommand };
@@ -14,8 +14,19 @@ let activeSessions = 0;
14
14
  function createClientConnection(hostInfo, userId, sessionId, serverStream) {
15
15
  return new Promise((resolve, reject) => {
16
16
  const client = new Client();
17
+ let connected = false;
18
+ let ended = false;
19
+
20
+ // End audit session exactly once, preserving the first (most specific) status
21
+ function markEnded(status) {
22
+ if (ended) return;
23
+ ended = true;
24
+ audit.endSession(sessionId, status);
25
+ }
17
26
 
18
27
  client.on('ready', () => {
28
+ connected = true;
29
+ activeSessions++;
19
30
  logger.info(`${service}: SSH client connected to target`, {
20
31
  host: hostInfo.host,
21
32
  port: hostInfo.port,
@@ -27,14 +38,17 @@ function createClientConnection(hostInfo, userId, sessionId, serverStream) {
27
38
 
28
39
  client.on('error', (err) => {
29
40
  logger.error(`${service}: SSH client error`, { error: err.message, host: hostInfo.host });
30
- audit.endSession(sessionId, 'error');
41
+ markEnded('error');
31
42
  reject(err);
32
43
  });
33
44
 
34
45
  client.on('close', () => {
46
+ if (connected) {
47
+ connected = false;
48
+ activeSessions--;
49
+ }
35
50
  logger.info(`${service}: SSH client closed`, { sessionId });
36
- audit.endSession(sessionId, 'closed');
37
- activeSessions--;
51
+ markEnded('closed');
38
52
  });
39
53
 
40
54
  // Connect to target host
@@ -53,6 +67,8 @@ function createClientConnection(hostInfo, userId, sessionId, serverStream) {
53
67
  */
54
68
  async function handleShell(client, sessionId) {
55
69
  return new Promise((resolve, reject) => {
70
+ let resolved = false;
71
+
56
72
  client.shell({
57
73
  term: 'xterm',
58
74
  cols: 80,
@@ -67,23 +83,31 @@ async function handleShell(client, sessionId) {
67
83
  logger.info(`${service}: Shell session started`, { sessionId });
68
84
  activeSessions++;
69
85
 
70
- // Set idle timeout
71
86
  let idleTimer = setTimeout(() => {
72
87
  logger.warn(`${service}: Session timed out (idle)`, { sessionId });
73
88
  stream.end();
74
- resolve();
89
+ if (!resolved) {
90
+ resolved = true;
91
+ resolve(stream);
92
+ }
75
93
  }, config.server.idleTimeoutSec * 1000);
76
94
 
77
- stream.on('data', (data) => {
95
+ stream.on('data', () => {
78
96
  clearTimeout(idleTimer);
79
97
  idleTimer = setTimeout(() => {
80
98
  logger.warn(`${service}: Session timed out (idle)`, { sessionId });
81
99
  stream.end();
82
- resolve();
100
+ if (!resolved) {
101
+ resolved = true;
102
+ resolve(stream);
103
+ }
83
104
  }, config.server.idleTimeoutSec * 1000);
84
105
  });
85
106
 
86
- resolve(stream);
107
+ if (!resolved) {
108
+ resolved = true;
109
+ resolve(stream);
110
+ }
87
111
  });
88
112
  });
89
113
  }
@@ -98,6 +122,7 @@ async function handleExec(client, command, sessionId) {
98
122
  client.exec(command, (err, stream) => {
99
123
  if (err) {
100
124
  logger.error(`${service}: Exec error`, { error: err.message });
125
+ activeSessions--;
101
126
  reject(err);
102
127
  return;
103
128
  }
@@ -137,4 +162,4 @@ module.exports = {
137
162
  bridgeStreams,
138
163
  getActiveSessions: () => activeSessions,
139
164
  getMaxSessions: () => config.server.maxSessions,
140
- };
165
+ };