typescript-virtual-container 1.1.4 → 1.1.5

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.
@@ -0,0 +1,180 @@
1
+ /**
2
+ * HoneyPot Auditing Example
3
+ *
4
+ * Demonstrates how to use the HoneyPot utility to track all activity
5
+ * in a virtual environment, collect statistics, and detect anomalies.
6
+ *
7
+ * Run with: bun run examples/honeypot-audit.ts
8
+ */
9
+
10
+ import {
11
+ HoneyPot,
12
+ SshClient,
13
+ VirtualShell,
14
+ VirtualSshServer,
15
+ } from "../src/index";
16
+
17
+ async function demonstrateHoneypot() {
18
+ console.log("🍯 HoneyPot Auditing Example\n");
19
+
20
+ // Initialize the virtual environment
21
+ const shell = new VirtualShell("security-lab");
22
+ const ssh = new VirtualSshServer({ port: 2222, shell });
23
+ await ssh.start();
24
+
25
+ const users = shell.getUsers()!;
26
+ const vfs = shell.getVfs()!;
27
+
28
+ // Create HoneyPot instance with 1000-entry log limit
29
+ const honeypot = new HoneyPot(1000);
30
+
31
+ // Attach HoneyPot to all components
32
+ honeypot.attach(shell, vfs, users, ssh);
33
+
34
+ console.log("✅ HoneyPot attached to all components\n");
35
+
36
+ // ------ Scenario 1: Normal user activity ------
37
+ console.log("--- Scenario 1: Normal User Activity ---\n");
38
+
39
+ await users.addUser("alice", "alice_pass123");
40
+ await users.addUser("bob", "bob_pass456");
41
+
42
+ const alice = new SshClient(shell, "alice");
43
+ await alice.mkdir("/home/alice/work", true);
44
+ await alice.writeFile("/home/alice/work/notes.txt", "Project notes");
45
+ await alice.ls("/home/alice/work");
46
+ await alice.cat("/home/alice/work/notes.txt");
47
+
48
+ console.log("✓ Alice performed normal operations\n");
49
+
50
+ // ------ Scenario 2: Bob attempts suspicious operations ------
51
+ console.log("--- Scenario 2: Suspicious Attempt ---\n");
52
+
53
+ const bob = new SshClient(shell, "bob");
54
+ // These will fail but are tracked
55
+ await bob.readFile("/etc/shadow");
56
+ await bob.readFile("/etc/passwd");
57
+ await bob.readFile("/root/.ssh/id_rsa");
58
+
59
+ console.log("✓ Bob attempted unauthorized file access\n");
60
+
61
+ // ------ Activity Summary ------
62
+ console.log("--- Activity Summary ---\n");
63
+
64
+ const stats = honeypot.getStats();
65
+ console.log("📊 Audit Statistics:");
66
+ console.log(` • Auth attempts: ${stats.authAttempts}`);
67
+ console.log(` • Auth successes: ${stats.authSuccesses}`);
68
+ console.log(` • Auth failures: ${stats.authFailures}`);
69
+ console.log(` • Commands executed: ${stats.commands}`);
70
+ console.log(` • File reads: ${stats.fileReads}`);
71
+ console.log(` • File writes: ${stats.fileWrites}`);
72
+ console.log(` • Users created: ${stats.userCreated}`);
73
+ console.log(` • Sessions started: ${stats.sessionStarts}\n`);
74
+
75
+ // ------ Recent Events ------
76
+ console.log("--- Most Recent Events ---\n");
77
+
78
+ const recent = honeypot.getRecent(10);
79
+ console.log(`📋 Last ${recent.length} events:\n`);
80
+ recent.forEach((entry) => {
81
+ console.log(` [${entry.timestamp}]`);
82
+ console.log(` Source: ${entry.source}`);
83
+ console.log(` Event: ${entry.type}`);
84
+ console.log(` Details: ${JSON.stringify(entry.details)}\n`);
85
+ });
86
+
87
+ // ------ Filtered Audit Log ------
88
+ console.log("--- Filtered Audit Log ---\n");
89
+
90
+ const authFailures = honeypot.getAuditLog("auth:failure");
91
+ console.log(`🚨 Auth Failures (${authFailures.length} total):\n`);
92
+ if (authFailures.length > 0) {
93
+ authFailures.forEach((entry) => {
94
+ console.log(
95
+ ` • User "${entry.details.username}" from ${entry.details.remoteAddress}`,
96
+ );
97
+ });
98
+ } else {
99
+ console.log(" • None detected");
100
+ }
101
+ console.log();
102
+
103
+ // ------ SSH-specific events ------
104
+ console.log("--- SSH-Specific Events ---\n");
105
+
106
+ const sshEvents = honeypot.getAuditLog(undefined, "SshMimic");
107
+ console.log(`🔗 SSH events (${sshEvents.length} total):\n`);
108
+ sshEvents.forEach((entry) => {
109
+ console.log(` • ${entry.type}: ${JSON.stringify(entry.details)}`);
110
+ });
111
+ console.log();
112
+
113
+ // ------ File System Activity ------
114
+ console.log("--- File System Activity ---\n");
115
+
116
+ const fileWrites = honeypot.getAuditLog("file:write", "VirtualFileSystem");
117
+ const fileReads = honeypot.getAuditLog("file:read", "VirtualFileSystem");
118
+
119
+ console.log(`📁 File Operations:`);
120
+ console.log(` • File writes: ${fileWrites.length}`);
121
+ fileWrites.forEach((entry) => {
122
+ console.log(` - ${entry.details.path} (${entry.details.size} bytes)`);
123
+ });
124
+ console.log(` • File reads: ${fileReads.length}`);
125
+ fileReads.forEach((entry) => {
126
+ console.log(` - ${entry.details.path} (${entry.details.size} bytes)`);
127
+ });
128
+ console.log();
129
+
130
+ // ------ Anomaly Detection ------
131
+ console.log("--- Security Analysis ---\n");
132
+
133
+ const anomalies = honeypot.detectAnomalies();
134
+ if (anomalies.length > 0) {
135
+ console.log("⚠️ Anomalies Detected:\n");
136
+ anomalies.forEach((anomaly) => {
137
+ const severity = {
138
+ low: "ℹ️ ",
139
+ medium: "⚠️ ",
140
+ high: "🚨",
141
+ }[anomaly.severity];
142
+ console.log(` ${severity} [${anomaly.type}]`);
143
+ console.log(` ${anomaly.message}\n`);
144
+ });
145
+ } else {
146
+ console.log("✅ No anomalies detected\n");
147
+ }
148
+
149
+ // ------ Export Audit Log ------
150
+ console.log("--- Full Audit Export ---\n");
151
+
152
+ const allAuditEntries = honeypot.getAuditLog();
153
+ console.log(`📊 Total audit entries: ${allAuditEntries.length}`);
154
+ console.log(`💾 Audit log is ready for export/storage\n`);
155
+
156
+ // Example export to JSON
157
+ const exportData = {
158
+ timestamp: new Date().toISOString(),
159
+ environment: "security-lab",
160
+ stats,
161
+ auditLog: allAuditEntries.slice(-50), // Last 50 entries
162
+ anomalies,
163
+ };
164
+
165
+ console.log("📄 Sample export structure:");
166
+ console.log(`${JSON.stringify(exportData, null, 2).substring(0, 300)}...\n`);
167
+
168
+ // Cleanup
169
+ ssh.stop();
170
+
171
+ console.log(
172
+ "✅ Example completed! HoneyPot auditing demonstration finished.\n",
173
+ );
174
+ }
175
+
176
+ // Run the example
177
+ demonstrateHoneypot().catch((error) => {
178
+ console.error("❌ Error:", error);
179
+ process.exit(1);
180
+ });
@@ -0,0 +1,253 @@
1
+ /**
2
+ * HoneyPot Advanced: Audit Export & Analysis
3
+ *
4
+ * Shows how to export audit data for external analysis, storage,
5
+ * or integration with security monitoring systems.
6
+ *
7
+ * Run with: bun run examples/honeypot-export.ts
8
+ */
9
+
10
+ import * as fs from "node:fs";
11
+ import {
12
+ HoneyPot,
13
+ SshClient,
14
+ VirtualShell,
15
+ VirtualSshServer,
16
+ } from "../src/index";
17
+
18
+ interface AuditReport {
19
+ timestamp: string;
20
+ environment: string;
21
+ durationMs: number;
22
+ summary: {
23
+ totalEvents: number;
24
+ totalUsers: number;
25
+ totalCommands: number;
26
+ failedAuthAttempts: number;
27
+ };
28
+ statistics: Record<string, number>;
29
+ anomalies: Array<{
30
+ type: string;
31
+ severity: string;
32
+ message: string;
33
+ }>;
34
+ timeline: Array<{
35
+ time: string;
36
+ event: string;
37
+ user?: string;
38
+ details: Record<string, unknown>;
39
+ }>;
40
+ }
41
+
42
+ async function generateAuditReport() {
43
+ const startTime = Date.now();
44
+
45
+ console.log("📊 HoneyPot Advanced: Generating Audit Report\n");
46
+
47
+ // Setup
48
+ const shell = new VirtualShell("audit-lab");
49
+ const ssh = new VirtualSshServer({ port: 2222, shell });
50
+ await ssh.start();
51
+
52
+ const users = shell.getUsers()!;
53
+ const vfs = shell.getVfs()!;
54
+
55
+ const honeypot = new HoneyPot(5000);
56
+ honeypot.attach(shell, vfs, users, ssh);
57
+
58
+ console.log("Running simulated workload...\n");
59
+
60
+ // Simulate various user activities
61
+ await users.addUser("analyst", "pass123");
62
+ await users.addUser("developer", "pass456");
63
+ await users.removeSudoer("developer");
64
+
65
+ // Analyst activities (authorized)
66
+ const analyst = new SshClient(shell, "analyst");
67
+ await analyst.mkdir("/data/reports", true);
68
+ await analyst.writeFile(
69
+ "/data/reports/analysis.txt",
70
+ "Security analysis report",
71
+ );
72
+ await analyst.ls("/data/reports");
73
+
74
+ // Developer activities
75
+ const dev = new SshClient(shell, "developer");
76
+ await dev.mkdir("/code/project", true);
77
+ await dev.writeFile("/code/project/main.ts", "export function main() {}");
78
+
79
+ // Some failed operations (tracked)
80
+ try {
81
+ await dev.readFile("/etc/shadow"); // Will fail
82
+ } catch {
83
+ // Ignored
84
+ }
85
+
86
+ try {
87
+ await dev.writeFile("/root/.bashrc", "malicious"); // Will fail
88
+ } catch {
89
+ // Ignored
90
+ }
91
+
92
+ // Get final duration
93
+ const duration = Date.now() - startTime;
94
+
95
+ console.log("Generating audit report...\n");
96
+
97
+ // Build comprehensive audit report
98
+ const stats = honeypot.getStats();
99
+ const anomalies = honeypot.detectAnomalies();
100
+ const auditLog = honeypot.getAuditLog();
101
+
102
+ const report: AuditReport = {
103
+ timestamp: new Date().toISOString(),
104
+ environment: "audit-lab",
105
+ durationMs: duration,
106
+
107
+ summary: {
108
+ totalEvents: auditLog.length,
109
+ totalUsers: stats.userCreated,
110
+ totalCommands: stats.commands,
111
+ failedAuthAttempts: stats.authFailures,
112
+ },
113
+
114
+ statistics: {
115
+ authAttempts: stats.authAttempts,
116
+ authSuccesses: stats.authSuccesses,
117
+ authFailures: stats.authFailures,
118
+ commandsExecuted: stats.commands,
119
+ fileReads: stats.fileReads,
120
+ fileWrites: stats.fileWrites,
121
+ sessionsStarted: stats.sessionStarts,
122
+ sessionsEnded: stats.sessionEnds,
123
+ usersCreated: stats.userCreated,
124
+ usersDeleted: stats.userDeleted,
125
+ clientConnects: stats.clientConnects,
126
+ clientDisconnects: stats.clientDisconnects,
127
+ },
128
+
129
+ anomalies: anomalies.map((a) => ({
130
+ type: a.type,
131
+ severity: a.severity,
132
+ message: a.message,
133
+ })),
134
+
135
+ timeline: auditLog.map((entry) => ({
136
+ time: entry.timestamp,
137
+ event: `${entry.source}:${entry.type}`,
138
+ user: (entry.details.username as string) || undefined,
139
+ details: entry.details,
140
+ })),
141
+ };
142
+
143
+ // Display summary
144
+ console.log("📋 Audit Report Summary\n");
145
+ console.log(` Environment: ${report.environment}`);
146
+ console.log(` Generated: ${report.timestamp}`);
147
+ console.log(` Duration: ${report.durationMs}ms\n`);
148
+
149
+ console.log("📊 Statistics:");
150
+ console.log(` • Total events: ${report.summary.totalEvents}`);
151
+ console.log(` • Total users: ${report.summary.totalUsers}`);
152
+ console.log(` • Commands executed: ${report.summary.totalCommands}`);
153
+ console.log(
154
+ ` • Failed auth attempts: ${report.summary.failedAuthAttempts}\n`,
155
+ );
156
+
157
+ // Display anomalies if any
158
+ if (report.anomalies.length > 0) {
159
+ console.log("⚠️ Anomalies:");
160
+ report.anomalies.forEach((a) => {
161
+ console.log(` • [${a.severity}] ${a.type}`);
162
+ console.log(` ${a.message}`);
163
+ });
164
+ console.log();
165
+ }
166
+
167
+ // Export to JSON file
168
+ const reportPath = "./audit_report.json";
169
+ fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
170
+ console.log(`✅ Report exported to: ${reportPath}\n`);
171
+
172
+ // Export CSV for spreadsheet analysis
173
+ const csvPath = "./audit_events.csv";
174
+ const csvHeader = "Timestamp,Source,Event,User,Details\n";
175
+ const csvRows = report.timeline
176
+ .map((entry) => {
177
+ const details = JSON.stringify(entry.details).replace(/"/g, '""');
178
+ return `"${entry.time}","${entry.event.split(":")[0]}","${
179
+ entry.event.split(":")[1]
180
+ }","${entry.user || ""}","${details}"`;
181
+ })
182
+ .join("\n");
183
+
184
+ fs.writeFileSync(csvPath, csvHeader + csvRows);
185
+ console.log(`✅ CSV export to: ${csvPath}\n`);
186
+
187
+ // Generate summary stats file
188
+ const statsPath = "./audit_stats.json";
189
+ fs.writeFileSync(
190
+ statsPath,
191
+ JSON.stringify(
192
+ {
193
+ summary: report.summary,
194
+ statistics: report.statistics,
195
+ anomalies: report.anomalies,
196
+ },
197
+ null,
198
+ 2,
199
+ ),
200
+ );
201
+ console.log(`✅ Stats export to: ${statsPath}\n`);
202
+
203
+ // Show sample data
204
+ console.log("📄 Sample Report Data:");
205
+ console.log(`${JSON.stringify(report, null, 2).substring(0, 500)}...\n`);
206
+
207
+ // Integration example: Send to external system
208
+ console.log("🔗 Integration Example:");
209
+ console.log("To send this data to external systems:");
210
+ console.log(" • Database: INSERT INTO audit_logs VALUES (...)");
211
+ console.log(" • API: POST /api/audit-reports (JSON payload)");
212
+ console.log(" • Message Queue: PUBLISH audit_report (for async processing)");
213
+ console.log(" • SIEM: Send via syslog or CEF format\n");
214
+
215
+ // Query examples
216
+ console.log("🔍 Query Examples:");
217
+
218
+ // Auth failures by user
219
+ const authFailures = honeypot.getAuditLog("auth:failure");
220
+ const failuresByUser = new Map<string, number>();
221
+ authFailures.forEach((entry) => {
222
+ const user = entry.details.username as string;
223
+ failuresByUser.set(user, (failuresByUser.get(user) || 0) + 1);
224
+ });
225
+
226
+ if (failuresByUser.size > 0) {
227
+ console.log("\n Auth Failures by User:");
228
+ failuresByUser.forEach((count, user) => {
229
+ console.log(` • ${user}: ${count} failures`);
230
+ });
231
+ }
232
+
233
+ // File operations
234
+ const fileWrites = honeypot.getAuditLog("file:write");
235
+ if (fileWrites.length > 0) {
236
+ console.log(`\n File Writes: ${fileWrites.length}`);
237
+ fileWrites.slice(-3).forEach((entry) => {
238
+ console.log(` • ${entry.details.path} (${entry.details.size} B)`);
239
+ });
240
+ }
241
+
242
+ console.log();
243
+
244
+ // Cleanup
245
+ ssh.stop();
246
+
247
+ console.log("✅ Audit report generation complete!");
248
+ console.log(
249
+ "💡 Tip: Open the generated .json files to view full audit trails.\n",
250
+ );
251
+ }
252
+
253
+ generateAuditReport().catch(console.error);
@@ -0,0 +1,110 @@
1
+ /**
2
+ * HoneyPot Quick Start Example
3
+ *
4
+ * A minimal, step-by-step introduction to HoneyPot auditing.
5
+ * Perfect for beginners.
6
+ *
7
+ * Run with: bun run examples/honeypot-quickstart.ts
8
+ */
9
+
10
+ import {
11
+ HoneyPot,
12
+ SshClient,
13
+ VirtualShell,
14
+ VirtualSshServer,
15
+ } from "../src/index";
16
+
17
+ async function quickStart() {
18
+ console.log("🍯 HoneyPot Quick Start\n");
19
+
20
+ // Step 1: Create virtual environment
21
+ console.log("Step 1️⃣ Creating virtual environment...");
22
+ const shell = new VirtualShell("my-lab");
23
+ const ssh = new VirtualSshServer({ port: 2222, shell });
24
+ await ssh.start();
25
+
26
+ const users = shell.getUsers()!;
27
+ const vfs = shell.getVfs()!;
28
+
29
+ console.log("✅ Environment ready\n");
30
+
31
+ // Step 2: Create HoneyPot instance
32
+ console.log("Step 2️⃣ Initializing HoneyPot...");
33
+ const honeypot = new HoneyPot();
34
+
35
+ // Step 3: Attach HoneyPot to all components
36
+ console.log("Step 3️⃣ Attaching HoneyPot to components...");
37
+ honeypot.attach(shell, vfs, users, ssh);
38
+
39
+ console.log("✅ HoneyPot is now tracking all activity\n");
40
+
41
+ // Step 4: Do some work (which will be audited)
42
+ console.log("Step 4️⃣ Performing some operations...\n");
43
+
44
+ // Create a user
45
+ await users.addUser("dev_user", "secure_pass");
46
+ console.log(" ✓ Created user 'dev_user'");
47
+
48
+ // Create a client
49
+ const client = new SshClient(shell, "dev_user");
50
+
51
+ // Create files
52
+ await client.mkdir("/app", true);
53
+ await client.writeFile("/app/config.json", '{"debug":true}');
54
+ await client.readFile("/app/config.json");
55
+
56
+ console.log(" ✓ Created /app directory and config.json");
57
+ console.log(" ✓ Read config.json\n");
58
+
59
+ // Step 5: Get statistics
60
+ console.log("Step 5️⃣ Viewing activity statistics...\n");
61
+ const stats = honeypot.getStats();
62
+ console.log(` 📊 Commands: ${stats.commands}`);
63
+ console.log(` 📝 File writes: ${stats.fileWrites}`);
64
+ console.log(` 📖 File reads: ${stats.fileReads}`);
65
+ console.log(` 👤 Users created: ${stats.userCreated}\n`);
66
+
67
+ // Step 6: Get recent events
68
+ console.log("Step 6️⃣ Last 5 events:\n");
69
+ honeypot.getRecent(5).forEach((entry, idx) => {
70
+ console.log(` ${idx + 1}. [${entry.source}] ${entry.type}`);
71
+ if (Object.keys(entry.details).length > 0) {
72
+ console.log(` └─ ${JSON.stringify(entry.details)}`);
73
+ }
74
+ });
75
+ console.log();
76
+
77
+ // Step 7: Query filtered logs
78
+ console.log("Step 7️⃣ Querying specific event types...\n");
79
+
80
+ const userEvents = honeypot.getAuditLog("user:add");
81
+ console.log(` 👤 User creation events: ${userEvents.length}`);
82
+
83
+ const fileEvents = honeypot.getAuditLog(undefined, "VirtualFileSystem");
84
+ console.log(` 📁 VirtualFileSystem events: ${fileEvents.length}\n`);
85
+
86
+ // Step 8: Detect anomalies
87
+ console.log("Step 8️⃣ Checking for anomalies...\n");
88
+ const anomalies = honeypot.detectAnomalies();
89
+ if (anomalies.length === 0) {
90
+ console.log(" ✅ No anomalies detected\n");
91
+ } else {
92
+ console.log(" ⚠️ Anomalies found:");
93
+ anomalies.forEach((a) => {
94
+ console.log(` • ${a.message}`);
95
+ });
96
+ console.log();
97
+ }
98
+
99
+ // Step 9: Export audit data (for storage/analysis)
100
+ console.log("Step 9️⃣ Exporting audit log...\n");
101
+ const fullLog = honeypot.getAuditLog();
102
+ console.log(` ✓ Exported ${fullLog.length} audit entries`);
103
+ console.log(` ✓ Ready to store in database, file, or monitoring system\n`);
104
+
105
+ // Cleanup
106
+ ssh.stop();
107
+ console.log("✅ Example complete!");
108
+ }
109
+
110
+ quickStart().catch(console.error);
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
7
- "version": "1.1.4",
7
+ "version": "1.1.5",
8
8
  "license": "MIT",
9
9
  "keywords": [
10
10
  "ssh",