-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetscanner.js
More file actions
246 lines (198 loc) · 7.17 KB
/
netscanner.js
File metadata and controls
246 lines (198 loc) · 7.17 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
#!/usr/bin/env node
import net from require("net");
import dns from require("dns").promises;
import fs from require("fs");
import readline from require("readline");
const args = process.argv.slice(2);
if (args.length < 2) {
console.log("Usage: netscanner <target> <ports|auto|file.txt> [--open-only] [--json out.json]");
process.exit(1);
}
const target = args[0];
let portsSpec = args[1];
const OPEN_ONLY = args.includes("--open-only");
const jsonOut = args.includes("--json") ? args[args.indexOf("--json") + 1] : null;
const TIMEOUT = 300;
const CONCURRENCY = 300; // sehr schnell, aber stabil
const CSV_FILE = "results.csv";
////////////////////////////////////////////////////////////////////////////////
// PORTS PARSING
////////////////////////////////////////////////////////////////////////////////
function parsePorts(str) {
const ports = new Set();
if (str === "auto") {
[22,23,53,80,443,3306,3389,8080,8443,9000].forEach(p => ports.add(p));
return [...ports];
}
if (fs.existsSync(str)) {
const lines = fs.readFileSync(str, "utf8").split(/\r?\n/);
lines.forEach(l => {
if (/^\d+$/.test(l.trim())) ports.add(parseInt(l.trim()));
});
return [...ports];
}
for (const part of str.split(",")) {
if (part.includes("-")) {
const [a, b] = part.split("-").map(n => parseInt(n, 10));
for (let p = a; p <= b; p++) ports.add(p);
} else ports.add(parseInt(part, 10));
}
return [...ports].sort((a, b) => a - b);
}
////////////////////////////////////////////////////////////////////////////////
// CIDR + IP Range
////////////////////////////////////////////////////////////////////////////////
function isCidr(s) {
return /^\d{1,3}(\.\d{1,3}){3}\/\d{1,2}$/.test(s);
}
function ipToInt(ip) {
return ip.split(".").reduce((acc, part) => (acc << 8) + (parseInt(part) & 255), 0) >>> 0;
}
function intToIp(int) {
return [
(int >>> 24) & 255,
(int >>> 16) & 255,
(int >>> 8) & 255,
int & 255
].join(".");
}
function expandCidr(cidr) {
const [addr, prefixStr] = cidr.split("/");
const prefix = parseInt(prefixStr);
const base = ipToInt(addr);
const mask = prefix === 0 ? 0 : (~0 << (32 - prefix)) >>> 0;
const start = (base & mask) + 1;
const end = (base | (~mask >>> 0)) - 1;
const ips = [];
for (let i = start; i <= end; i++) ips.push(intToIp(i));
return ips;
}
////////////////////////////////////////////////////////////////////////////////
// Resolve + Warnings
////////////////////////////////////////////////////////////////////////////////
async function resolveTarget(t) {
if (isCidr(t)) {
const ips = expandCidr(t);
if (ips.length > 4096) {
await confirmLargeScan(ips.length);
}
return ips;
}
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(t)) return [t];
return dns.resolve4(t);
}
function confirmLargeScan(count) {
return new Promise((resolve) => {
const r = readline.createInterface({ input: process.stdin, output: process.stdout });
r.question(`Scan of ${count} hosts. Continue? (y/N): `, (ans) => {
r.close();
if (ans.toLowerCase() !== "y") {
console.log("Aborted.");
process.exit(0);
}
resolve();
});
});
}
////////////////////////////////////////////////////////////////////////////////
// Reverse DNS
////////////////////////////////////////////////////////////////////////////////
async function reverseDns(ip) {
try {
const res = await dns.reverse(ip);
return res[0] || null;
} catch {
return null;
}
}
////////////////////////////////////////////////////////////////////////////////
// TCP Port Scan
////////////////////////////////////////////////////////////////////////////////
function scanPort(ip, port) {
return new Promise(resolve => {
const socket = new net.Socket();
let done = false;
const finish = (open) => {
if (!done) {
done = true;
socket.destroy();
resolve({ ip, port, open });
}
};
socket.setTimeout(TIMEOUT);
socket.once("timeout", () => finish(false));
socket.once("error", () => finish(false));
socket.connect(port, ip, () => finish(true));
});
}
////////////////////////////////////////////////////////////////////////////////
// Concurrency Control
////////////////////////////////////////////////////////////////////////////////
async function runPool(items, fn, limit) {
const results = [];
let i = 0;
async function worker() {
while (i < items.length) {
const idx = i++;
results[idx] = await fn(items[idx]);
}
}
const workers = [];
for (let w = 0; w < limit; w++) workers.push(worker());
await Promise.all(workers);
return results;
}
////////////////////////////////////////////////////////////////////////////////
// Output Formatting
////////////////////////////////////////////////////////////////////////////////
const color = {
green: (s) => `\x1b[32m${s}\x1b[0m`,
gray: (s) => `\x1b[90m${s}\x1b[0m`,
yellow:(s) => `\x1b[33m${s}\x1b[0m`
};
////////////////////////////////////////////////////////////////////////////////
// CSV + JSON
////////////////////////////////////////////////////////////////////////////////
function saveCsv(results) {
const ts = new Date().toISOString();
const header = "timestamp,ip,port,status\n";
const rows = results.map(r => `${ts},${r.ip},${r.port},${r.open ? "open" : "closed"}`).join("\n");
fs.writeFileSync(CSV_FILE, header + rows);
}
function saveJson(results) {
fs.writeFileSync(jsonOut, JSON.stringify(results, null, 2));
}
////////////////////////////////////////////////////////////////////////////////
// MAIN
////////////////////////////////////////////////////////////////////////////////
(async () => {
const startTime = Date.now();
const ports = parsePorts(portsSpec);
const ips = await resolveTarget(target);
const allTasks = [];
for (const ip of ips) {
const hostTask = reverseDns(ip).then(host => ({ ip, host }));
const scans = ports.map(port => ({ ip, port }));
allTasks.push({ ip, scans, hostTask });
}
let finalResults = [];
for (const t of allTasks) {
const host = await t.hostTask;
console.log(color.yellow(`\nTarget: ${t.ip}`) + (host.host ? ` (${host.host})` : ""));
const scans = await runPool(t.scans, async p => scanPort(p.ip, p.port), CONCURRENCY);
for (const r of scans) {
if (r.open) {
console.log(color.green(`[OPEN ] ${r.ip}:${r.port}`));
} else if (!OPEN_ONLY) {
console.log(color.gray(`[closed] ${r.ip}:${r.port}`));
}
}
finalResults.push(...scans);
}
saveCsv(finalResults);
if (jsonOut) saveJson(finalResults);
const duration = ((Date.now() - startTime) / 1000).toFixed(2);
console.log(`\nCompleted in ${duration}s`);
console.log(`CSV: ${CSV_FILE}`);
if (jsonOut) console.log(`JSON: ${jsonOut}`);
})();