-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscan-unauth-gateways.ts
More file actions
303 lines (265 loc) · 8.72 KB
/
scan-unauth-gateways.ts
File metadata and controls
303 lines (265 loc) · 8.72 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
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
#!/usr/bin/env bun
/**
* Scanner for Clawdbot gateways missing authentication
* Usage: bun scripts/scan-unauth-gateways.ts <shodan-json-file> [--concurrency=N]
*/
import { readFileSync, writeFileSync } from "node:fs";
const TIMEOUT_MS = 5000;
const DEFAULT_CONCURRENCY = 20;
type Target = { ip: string; port: number };
type ScanResult = {
ip: string;
port: number;
status: "no_auth" | "auth_required" | "not_clawdbot" | "error" | "timeout";
details?: string;
responseTime?: number;
};
function parseArgs() {
const args = process.argv.slice(2);
let file = "";
let concurrency = DEFAULT_CONCURRENCY;
for (const arg of args) {
if (arg.startsWith("--concurrency=")) {
concurrency = parseInt(arg.split("=")[1], 10) || DEFAULT_CONCURRENCY;
} else if (!arg.startsWith("-")) {
file = arg;
}
}
if (!file) {
console.error("Usage: bun scripts/scan-unauth-gateways.ts <shodan-json-file> [--concurrency=N]");
process.exit(1);
}
return { file, concurrency };
}
function extractTargets(filePath: string): Target[] {
const content = readFileSync(filePath, "utf-8");
const seen = new Set<string>();
const targets: Target[] = [];
for (const line of content.split("\n")) {
if (!line.trim()) continue;
// Try plain text format first: "ip:port"
const textMatch = line.trim().match(/^(\d+\.\d+\.\d+\.\d+):(\d+)$/);
if (textMatch) {
const [, ip, portStr] = textMatch;
const port = parseInt(portStr, 10);
const key = `${ip}:${port}`;
if (!seen.has(key)) {
seen.add(key);
targets.push({ ip, port });
}
continue;
}
// Try JSON format (Shodan)
try {
const entry = JSON.parse(line);
// Check for mDNS Clawdbot discovery format
if (entry.mdns?.services) {
const serviceKeys = Object.keys(entry.mdns.services);
const clawdbotService = serviceKeys.find((k) => k.includes("clawdbot"));
if (clawdbotService && entry.ip_str) {
// Extract port from service key like "18789/tcp clawdbot-gw"
const portMatch = clawdbotService.match(/^(\d+)/);
const port = portMatch ? parseInt(portMatch[1], 10) : 18789;
const key = `${entry.ip_str}:${port}`;
if (!seen.has(key)) {
seen.add(key);
targets.push({ ip: entry.ip_str, port });
}
continue;
}
}
// Standard Shodan format
const ip = entry.ip_str;
const port = entry.port;
if (ip && port) {
const key = `${ip}:${port}`;
if (!seen.has(key)) {
seen.add(key);
targets.push({ ip, port });
}
}
} catch {
// skip malformed lines
}
}
return targets;
}
async function checkTarget(target: Target): Promise<ScanResult> {
const { ip, port } = target;
const url = `http://${ip}:${port}/tools/invoke`;
const start = Date.now();
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ tool: "gateway" }),
signal: controller.signal,
});
clearTimeout(timeout);
const responseTime = Date.now() - start;
const text = await response.text();
// 401 = auth required (properly configured)
if (response.status === 401) {
return { ip, port, status: "auth_required", responseTime };
}
// 404 with specific error = no auth, tool not found (VULNERABLE)
if (response.status === 404) {
try {
const json = JSON.parse(text);
if (json.error?.type === "not_found" || json.error?.message?.includes("Tool not available")) {
return {
ip,
port,
status: "no_auth",
details: "Gateway accessible without authentication",
responseTime,
};
}
} catch {}
}
// 200 with ok:true = tool executed (VULNERABLE)
if (response.status === 200) {
try {
const json = JSON.parse(text);
if (json.ok === true) {
return {
ip,
port,
status: "no_auth",
details: `Tool executed successfully: ${JSON.stringify(json.result).slice(0, 100)}`,
responseTime,
};
}
} catch {}
}
// 400 with tool error = no auth (VULNERABLE)
if (response.status === 400) {
try {
const json = JSON.parse(text);
if (json.error?.type === "tool_error") {
return {
ip,
port,
status: "no_auth",
details: "Gateway accessible without authentication (tool error)",
responseTime,
};
}
} catch {}
}
// Check if it looks like a Clawdbot gateway at all
const looksLikeClawdbot =
text.includes("clawdbot") ||
text.includes("Clawdbot") ||
text.includes("tool") ||
response.headers.get("content-type")?.includes("application/json");
if (!looksLikeClawdbot) {
return { ip, port, status: "not_clawdbot", details: `HTTP ${response.status}`, responseTime };
}
return {
ip,
port,
status: "error",
details: `Unexpected response: HTTP ${response.status}`,
responseTime,
};
} catch (err) {
const responseTime = Date.now() - start;
if (err instanceof Error) {
if (err.name === "AbortError" || err.message.includes("abort")) {
return { ip, port, status: "timeout", responseTime };
}
return { ip, port, status: "error", details: err.message, responseTime };
}
return { ip, port, status: "error", details: String(err), responseTime };
}
}
async function runBatch<T, R>(
items: T[],
concurrency: number,
fn: (item: T) => Promise<R>,
onProgress?: (completed: number, total: number) => void
): Promise<R[]> {
const results: R[] = [];
let index = 0;
let completed = 0;
async function worker() {
while (index < items.length) {
const currentIndex = index++;
const result = await fn(items[currentIndex]);
results[currentIndex] = result;
completed++;
onProgress?.(completed, items.length);
}
}
const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());
await Promise.all(workers);
return results;
}
async function main() {
const { file, concurrency } = parseArgs();
console.log(`Loading targets from ${file}...`);
const targets = extractTargets(file);
console.log(`Found ${targets.length} unique IP:port combinations`);
console.log(`Scanning with concurrency=${concurrency}, timeout=${TIMEOUT_MS}ms\n`);
const startTime = Date.now();
let lastPrint = 0;
const results = await runBatch(targets, concurrency, checkTarget, (completed, total) => {
const now = Date.now();
if (now - lastPrint > 1000 || completed === total) {
const pct = ((completed / total) * 100).toFixed(1);
const elapsed = ((now - startTime) / 1000).toFixed(1);
process.stdout.write(`\rProgress: ${completed}/${total} (${pct}%) - ${elapsed}s elapsed`);
lastPrint = now;
}
});
console.log("\n\n");
// Summarize results
const noAuth = results.filter((r) => r.status === "no_auth");
const authRequired = results.filter((r) => r.status === "auth_required");
const notClawdbot = results.filter((r) => r.status === "not_clawdbot");
const errors = results.filter((r) => r.status === "error");
const timeouts = results.filter((r) => r.status === "timeout");
console.log("=== SCAN RESULTS ===\n");
console.log(`Total scanned: ${results.length}`);
console.log(`No auth (VULN): ${noAuth.length}`);
console.log(`Auth required: ${authRequired.length}`);
console.log(`Not Clawdbot: ${notClawdbot.length}`);
console.log(`Errors: ${errors.length}`);
console.log(`Timeouts: ${timeouts.length}`);
if (noAuth.length > 0) {
console.log("\n=== VULNERABLE GATEWAYS (NO AUTH) ===\n");
for (const r of noAuth) {
console.log(` http://${r.ip}:${r.port}/`);
if (r.details) console.log(` ${r.details}`);
}
}
// Write results to file
const outputFile = file.replace(/\.json$/, "") + "-scan-results.json";
writeFileSync(
outputFile,
JSON.stringify(
{
scanTime: new Date().toISOString(),
summary: {
total: results.length,
noAuth: noAuth.length,
authRequired: authRequired.length,
notClawdbot: notClawdbot.length,
errors: errors.length,
timeouts: timeouts.length,
},
vulnerable: noAuth,
allResults: results,
},
null,
2
)
);
console.log(`\nResults written to: ${outputFile}`);
}
main().catch(console.error);