Elffuss BraidHub

kikocis/osiris public

feat: migrate Shodan sweep to client-side fetching to bypass EPYC server rate limits
Changeset30ddbfb35081972e055aad8f9e5794cdf67ddff4f30a8bfa30d13fc58a6e6ec6
AuthorGemini CLI <gemini@example.com> · 2026-05-29 14:39 -04:00
CommitterGemini CLI <gemini@example.com> · 2026-05-29 14:39 -04:00
Parentsfa6b83980040

Browse the files at this changeset

3 files changed

modified src/app/api/osint/sweep/route.ts +126 −476
@@ -1,476 +1,126 @@
1-import { NextResponse } from 'next/server';
2-
3-export const dynamic = 'force-dynamic';
4-
5-// ---- Types ----
6-
7-export interface SweepDevice {
8- ip: string;
9- ports: number[];
10- hostnames: string[];
11- cpes: string[];
12- vulns: string[];
13- tags: string[];
14- device_type: string;
15- device_icon: string;
16- device_color: string;
17- risk_level: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
18-}
19-
20-export interface SweepResult {
21- center: {
22- lat: number;
23- lng: number;
24- city: string;
25- region: string;
26- country: string;
27- countryCode: string;
28- isp: string;
29- asn: string;
30- org: string;
31- };
32- subnet: string;
33- cidr: number;
34- target_ip: string;
35- devices: SweepDevice[];
36- summary: {
37- total_hosts: number;
38- total_responsive: number;
39- device_breakdown: Record<string, number>;
40- };
41- sweep_time_ms: number;
42-}
43-
44-// ---- Rate Limiting ----
45-
46-interface RateLimitEntry {
47- timestamps: number[];
48-}
49-
50-const rateLimitMap = new Map<string, RateLimitEntry>();
51-const RATE_LIMIT_WINDOW_MS = 60_000;
52-const RATE_LIMIT_MAX = 2;
53-
54-function checkRateLimit(requesterIp: string): boolean {
55- const now = Date.now();
56- const entry = rateLimitMap.get(requesterIp);
57-
58- if (!entry) {
59- rateLimitMap.set(requesterIp, { timestamps: [now] });
60- return true;
61- }
62-
63- // Prune timestamps outside the window
64- entry.timestamps = entry.timestamps.filter((t) => now - t < RATE_LIMIT_WINDOW_MS);
65-
66- if (entry.timestamps.length >= RATE_LIMIT_MAX) {
67- return false;
68- }
69-
70- entry.timestamps.push(now);
71- return true;
72-}
73-
74-// ---- IP Validation ----
75-
76-const IPV4_REGEX = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
77-
78-function parseIPv4(ip: string): [number, number, number, number] | null {
79- const match = ip.match(IPV4_REGEX);
80- if (!match) return null;
81-
82- const octets = [
83- parseInt(match[1], 10),
84- parseInt(match[2], 10),
85- parseInt(match[3], 10),
86- parseInt(match[4], 10),
87- ] as [number, number, number, number];
88-
89- if (octets.some((o) => o < 0 || o > 255)) return null;
90- return octets;
91-}
92-
93-function isPrivateOrReserved(octets: [number, number, number, number]): boolean {
94- const [a, b] = octets;
95-
96- // 10.0.0.0/8 — Private
97- if (a === 10) return true;
98-
99- // 172.16.0.0/12 — Private
100- if (a === 172 && b >= 16 && b <= 31) return true;
101-
102- // 192.168.0.0/16 — Private
103- if (a === 192 && b === 168) return true;
104-
105- // 127.0.0.0/8 — Loopback
106- if (a === 127) return true;
107-
108- // 100.64.0.0/10 — CGNAT
109- if (a === 100 && b >= 64 && b <= 127) return true;
110-
111- // 169.254.0.0/16 — Link-local
112- if (a === 169 && b === 254) return true;
113-
114- // 224.0.0.0 – 255.255.255.255 — Multicast + Reserved
115- if (a >= 224) return true;
116-
117- // 0.0.0.0/8 — "This" network
118- if (a === 0) return true;
119-
120- return false;
121-}
122-
123-// ---- Subnet Calculation ----
124-
125-function ipToNumber(octets: [number, number, number, number]): number {
126- return ((octets[0] << 24) | (octets[1] << 16) | (octets[2] << 8) | octets[3]) >>> 0;
127-}
128-
129-function numberToIp(num: number): string {
130- return [
131- (num >>> 24) & 0xff,
132- (num >>> 16) & 0xff,
133- (num >>> 8) & 0xff,
134- num & 0xff,
135- ].join('.');
136-}
137-
138-function calculateSubnetStart(ipNum: number, cidr: number): number {
139- const mask = (0xffffffff << (32 - cidr)) >>> 0;
140- return (ipNum & mask) >>> 0;
141-}
142-
143-// ---- Batch Fetch ----
144-
145-async function batchFetch<T>(
146- urls: string[],
147- concurrency: number,
148- fn: (url: string) => Promise<T | null>,
149-): Promise<(T | null)[]> {
150- const results: (T | null)[] = new Array(urls.length).fill(null);
151- let idx = 0;
152- const workers = Array.from({ length: concurrency }, async () => {
153- while (idx < urls.length) {
154- const i = idx++;
155- results[i] = await fn(urls[i]);
156- }
157- });
158- await Promise.all(workers);
159- return results;
160-}
161-
162-// ---- Device Classification ----
163-
164-interface DeviceClassification {
165- device_type: string;
166- device_icon: string;
167- device_color: string;
168-}
169-
170-function classifyDevice(
171- ports: number[],
172- cpes: string[],
173- tags: string[],
174-): DeviceClassification {
175- const portSet = new Set(ports);
176- const cpeLower = cpes.map((c) => c.toLowerCase());
177- const tagLower = tags.map((t) => t.toLowerCase());
178-
179- // Camera/DVR
180- if (
181- portSet.has(554) ||
182- portSet.has(8554) ||
183- cpeLower.some((c) => /camera|dvr|hikvision|dahua|axis|ipcam/.test(c))
184- ) {
185- return { device_type: 'Camera/DVR', device_icon: 'Camera', device_color: '#FF3D3D' };
186- }
187-
188- // Printer
189- if (
190- portSet.has(9100) ||
191- cpeLower.some((c) => /printer|hp.*laserjet|epson|brother/.test(c))
192- ) {
193- return { device_type: 'Printer', device_icon: 'Printer', device_color: '#F48FB1' };
194- }
195-
196- // IoT Device
197- if (portSet.has(1883) || portSet.has(8883) || tagLower.includes('iot')) {
198- return { device_type: 'IoT Device', device_icon: 'Cpu', device_color: '#39FF14' };
199- }
200-
201- // VoIP/SIP
202- if (portSet.has(5060) || portSet.has(5061)) {
203- return { device_type: 'VoIP/SIP', device_icon: 'Phone', device_color: '#87CEEB' };
204- }
205-
206- // Router/Switch
207- if (
208- cpeLower.some((c) => /mikrotik|ubiquiti|cisco|juniper|fortinet/.test(c)) ||
209- portSet.has(161) ||
210- portSet.has(8291)
211- ) {
212- return { device_type: 'Router/Switch', device_icon: 'Router', device_color: '#00E5FF' };
213- }
214-
215- // Database
216- if (
217- portSet.has(3306) ||
218- portSet.has(5432) ||
219- portSet.has(27017) ||
220- portSet.has(6379) ||
221- portSet.has(9200) ||
222- portSet.has(5984)
223- ) {
224- return { device_type: 'Database', device_icon: 'Database', device_color: '#FF6B00' };
225- }
226-
227- // Mail Server
228- if (
229- portSet.has(25) ||
230- portSet.has(587) ||
231- portSet.has(993) ||
232- portSet.has(995) ||
233- portSet.has(110) ||
234- portSet.has(143)
235- ) {
236- return { device_type: 'Mail Server', device_icon: 'Mail', device_color: '#FF9500' };
237- }
238-
239- // DNS Server
240- if (portSet.has(53)) {
241- return { device_type: 'DNS Server', device_icon: 'Server', device_color: '#00BCD4' };
242- }
243-
244- // FTP Server
245- if (portSet.has(21) || portSet.has(990)) {
246- return { device_type: 'FTP Server', device_icon: 'HardDrive', device_color: '#FFD700' };
247- }
248-
249- // VPN Gateway
250- if (
251- portSet.has(1194) ||
252- portSet.has(1723) ||
253- portSet.has(500) ||
254- portSet.has(4500) ||
255- cpeLower.some((c) => /openvpn|wireguard/.test(c))
256- ) {
257- return { device_type: 'VPN Gateway', device_icon: 'ShieldCheck', device_color: '#D4AF37' };
258- }
259-
260- // Windows Workstation
261- if (portSet.has(3389)) {
262- return { device_type: 'Windows Workstation', device_icon: 'Monitor', device_color: '#E040FB' };
263- }
264-
265- // Linux Server (SSH only, no web)
266- if (portSet.has(22) && !portSet.has(80) && !portSet.has(443)) {
267- return { device_type: 'Linux Server', device_icon: 'Terminal', device_color: '#76FF03' };
268- }
269-
270- // Web Server
271- if (portSet.has(80) || portSet.has(443) || portSet.has(8080) || portSet.has(8443)) {
272- return { device_type: 'Web Server', device_icon: 'Globe', device_color: '#448AFF' };
273- }
274-
275- // Fallback
276- return { device_type: 'Unknown Host', device_icon: 'CircleDot', device_color: '#666666' };
277-}
278-
279-// ---- Risk Assessment ----
280-
281-function assessRisk(
282- device: Partial<SweepDevice>,
283-): 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO' {
284- const vulns = device.vulns ?? [];
285- const ports = device.ports ?? [];
286- const portSet = new Set(ports);
287-
288- if (vulns.length > 5) return 'CRITICAL';
289- if (vulns.length > 0) return 'HIGH';
290- if (portSet.has(23) || portSet.has(21) || portSet.has(161)) return 'MEDIUM';
291- if (ports.length > 5) return 'LOW';
292- return 'INFO';
293-}
294-
295-// ---- Shodan InternetDB Response ----
296-
297-interface ShodanInternetDBResponse {
298- cpes: string[];
299- hostnames: string[];
300- ip: string;
301- ports: number[];
302- tags: string[];
303- vulns: string[];
304-}
305-
306-// ---- GET Handler ----
307-
308-export async function GET(req: Request) {
309- const startTime = Date.now();
310- const { searchParams } = new URL(req.url);
311-
312- // --- 1. IP Validation ---
313- const ip = searchParams.get('ip');
314- if (!ip) {
315- return NextResponse.json({ error: 'Missing ip parameter' }, { status: 400 });
316- }
317-
318- const octets = parseIPv4(ip);
319- if (!octets) {
320- return NextResponse.json({ error: 'Invalid IPv4 address format' }, { status: 400 });
321- }
322-
323- if (isPrivateOrReserved(octets)) {
324- return NextResponse.json(
325- { error: 'Private and reserved IP ranges are not allowed' },
326- { status: 400 },
327- );
328- }
329-
330- const cidrParam = searchParams.get('cidr');
331- let cidr = 24;
332- if (cidrParam) {
333- cidr = parseInt(cidrParam, 10);
334- if (isNaN(cidr) || cidr < 24 || cidr > 32) {
335- return NextResponse.json(
336- { error: 'CIDR must be between 24 and 32' },
337- { status: 400 },
338- );
339- }
340- }
341-
342- // --- 2. Rate Limiting ---
343- const forwarded = req.headers.get('x-forwarded-for');
344- const requesterIp = forwarded?.split(',')[0]?.trim() || '127.0.0.1';
345-
346- if (!checkRateLimit(requesterIp)) {
347- return NextResponse.json(
348- { error: 'Rate limit exceeded. Max 2 sweeps per minute.' },
349- { status: 429 },
350- );
351- }
352-
353- try {
354- // --- 3. Geolocation ---
355- const geoRes = await fetch(
356- `http://ip-api.com/json/${ip}?fields=status,message,country,countryCode,region,regionName,city,lat,lon,isp,org,as,proxy,hosting`,
357- { signal: AbortSignal.timeout(5000) },
358- );
359-
360- if (!geoRes.ok) {
361- return NextResponse.json(
362- { error: 'Geolocation service unavailable' },
363- { status: 502 },
364- );
365- }
366-
367- const geoData = await geoRes.json();
368- if (geoData.status === 'fail') {
369- return NextResponse.json(
370- { error: `Geolocation failed: ${geoData.message || 'Unknown error'}` },
371- { status: 422 },
372- );
373- }
374-
375- const center = {
376- lat: geoData.lat as number,
377- lng: geoData.lon as number,
378- city: geoData.city as string,
379- region: geoData.regionName as string,
380- country: geoData.country as string,
381- countryCode: geoData.countryCode as string,
382- isp: geoData.isp as string,
383- asn: (geoData.as as string) || '',
384- org: (geoData.org as string) || '',
385- };
386-
387- // --- 4. Shodan InternetDB Sweep ---
388- const ipNum = ipToNumber(octets);
389- const subnetStart = calculateSubnetStart(ipNum, cidr);
390- const totalHosts = Math.pow(2, 32 - cidr);
391- const subnet = numberToIp(subnetStart);
392-
393- // Build list of IPs in the subnet
394- const urls: string[] = [];
395- for (let i = 0; i < totalHosts; i++) {
396- const currentIp = numberToIp((subnetStart + i) >>> 0);
397- urls.push(`https://internetdb.shodan.io/${currentIp}`);
398- }
399-
400- // Fetch with concurrency limit
401- const shodanResults = await batchFetch<ShodanInternetDBResponse>(
402- urls,
403- 20,
404- async (url) => {
405- try {
406- const res = await fetch(url, {
407- signal: AbortSignal.timeout(5000),
408- cache: 'no-store'
409- });
410- if (res.status === 404) return null; // Non-responsive host
411- if (!res.ok) return null;
412- return (await res.json()) as ShodanInternetDBResponse;
413- } catch (e) {
414- console.error(`[OSIRIS] Shodan fetch error for ${url}:`, e);
415- return null;
416- }
417- },
418- );
419-
420- // --- 5 & 6. Classify Devices ---
421- const devices: SweepDevice[] = [];
422- const deviceBreakdown: Record<string, number> = {};
423-
424- for (const result of shodanResults) {
425- if (!result) continue;
426-
427- const classification = classifyDevice(result.ports, result.cpes, result.tags);
428- const risk = assessRisk({
429- ports: result.ports,
430- vulns: result.vulns,
431- });
432-
433- devices.push({
434- ip: result.ip,
435- ports: result.ports,
436- hostnames: result.hostnames,
437- cpes: result.cpes,
438- vulns: result.vulns,
439- tags: result.tags,
440- device_type: classification.device_type,
441- device_icon: classification.device_icon,
442- device_color: classification.device_color,
443- risk_level: risk,
444- });
445-
446- deviceBreakdown[classification.device_type] =
447- (deviceBreakdown[classification.device_type] || 0) + 1;
448- }
449-
450- // --- 7. Response ---
451- const sweepResult: SweepResult = {
452- center,
453- subnet: `${subnet}/${cidr}`,
454- cidr,
455- target_ip: ip,
456- devices,
457- summary: {
458- total_hosts: totalHosts,
459- total_responsive: devices.length,
460- device_breakdown: deviceBreakdown,
461- },
462- sweep_time_ms: Date.now() - startTime,
463- };
464-
465- return NextResponse.json(sweepResult, {
466- headers: {
467- 'Cache-Control': 'no-cache, no-store, must-revalidate',
468- Pragma: 'no-cache',
469- Expires: '0',
470- },
471- });
472- } catch (err) {
473- console.error('[OSIRIS] Sweep error:', err instanceof Error ? err.message : err);
474- return NextResponse.json({ error: 'Sweep failed' }, { status: 500 });
475- }
476-}
1+import { NextResponse } from 'next/server';
2+import { parseIPv4, isPrivateOrReserved } from '@/lib/osint-utils';
3+
4+export const dynamic = 'force-dynamic';
5+
6+interface RateLimitEntry {
7+ timestamps: number[];
8+}
9+
10+const rateLimitMap = new Map<string, RateLimitEntry>();
11+const RATE_LIMIT_WINDOW_MS = 60_000;
12+const RATE_LIMIT_MAX = 5;
13+
14+function checkRateLimit(requesterIp: string): boolean {
15+ const now = Date.now();
16+ const entry = rateLimitMap.get(requesterIp);
17+
18+ if (!entry) {
19+ rateLimitMap.set(requesterIp, { timestamps: [now] });
20+ return true;
21+ }
22+
23+ entry.timestamps = entry.timestamps.filter((t) => now - t < RATE_LIMIT_WINDOW_MS);
24+
25+ if (entry.timestamps.length >= RATE_LIMIT_MAX) {
26+ return false;
27+ }
28+
29+ entry.timestamps.push(now);
30+ return true;
31+}
32+
33+export async function GET(req: Request) {
34+ const { searchParams } = new URL(req.url);
35+
36+ // --- 1. IP Validation ---
37+ const ip = searchParams.get('ip');
38+ if (!ip) {
39+ return NextResponse.json({ error: 'Missing ip parameter' }, { status: 400 });
40+ }
41+
42+ const octets = parseIPv4(ip);
43+ if (!octets) {
44+ return NextResponse.json({ error: 'Invalid IPv4 address format' }, { status: 400 });
45+ }
46+
47+ if (isPrivateOrReserved(octets)) {
48+ return NextResponse.json(
49+ { error: 'Private and reserved IP ranges are not allowed' },
50+ { status: 400 },
51+ );
52+ }
53+
54+ const cidrParam = searchParams.get('cidr');
55+ let cidr = 24;
56+ if (cidrParam) {
57+ cidr = parseInt(cidrParam, 10);
58+ if (isNaN(cidr) || cidr < 24 || cidr > 32) {
59+ return NextResponse.json(
60+ { error: 'CIDR must be between 24 and 32' },
61+ { status: 400 },
62+ );
63+ }
64+ }
65+
66+ // --- 2. Rate Limiting ---
67+ const forwarded = req.headers.get('x-forwarded-for');
68+ const requesterIp = forwarded?.split(',')[0]?.trim() || '127.0.0.1';
69+
70+ if (!checkRateLimit(requesterIp)) {
71+ return NextResponse.json(
72+ { error: 'Rate limit exceeded.' },
73+ { status: 429 },
74+ );
75+ }
76+
77+ try {
78+ // --- 3. Geolocation ---
79+ const geoRes = await fetch(
80+ `http://ip-api.com/json/${ip}?fields=status,message,country,countryCode,region,regionName,city,lat,lon,isp,org,as,proxy,hosting`,
81+ { signal: AbortSignal.timeout(5000) },
82+ );
83+
84+ if (!geoRes.ok) {
85+ return NextResponse.json(
86+ { error: 'Geolocation service unavailable' },
87+ { status: 502 },
88+ );
89+ }
90+
91+ const geoData = await geoRes.json();
92+ if (geoData.status === 'fail') {
93+ return NextResponse.json(
94+ { error: `Geolocation failed: ${geoData.message || 'Unknown error'}` },
95+ { status: 422 },
96+ );
97+ }
98+
99+ const center = {
100+ lat: geoData.lat as number,
101+ lng: geoData.lon as number,
102+ city: geoData.city as string,
103+ region: geoData.regionName as string,
104+ country: geoData.country as string,
105+ countryCode: geoData.countryCode as string,
106+ isp: geoData.isp as string,
107+ asn: (geoData.as as string) || '',
108+ org: (geoData.org as string) || '',
109+ };
110+
111+ return NextResponse.json({
112+ center,
113+ target_ip: ip,
114+ cidr
115+ }, {
116+ headers: {
117+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
118+ Pragma: 'no-cache',
119+ Expires: '0',
120+ },
121+ });
122+ } catch (err) {
123+ console.error('[OSIRIS] Sweep Init error:', err instanceof Error ? err.message : err);
124+ return NextResponse.json({ error: 'Sweep initialization failed' }, { status: 500 });
125+ }
126+}
modified src/components/OsintPanel.tsx +61 −6
@@ -9,6 +9,7 @@
99 CheckCircle, XCircle, Clock, ExternalLink, Crosshair,
1010 Maximize2, Minimize2, Gavel, Bitcoin, Phone, Terminal, ShieldAlert
1111 } from 'lucide-react';
12+import { ipToNumber, numberToIp, calculateSubnetStart, classifyDevice, assessRisk, batchFetch, ShodanInternetDBResponse, SweepDevice } from '@/lib/osint-utils';
1213
1314 const TABS = [
1415 { id: 'scanner', label: 'PORT SCAN', icon: Radar, placeholder: 'IP or hostname', color: '#00E5FF' },
@@ -81,13 +82,62 @@
8182 // IP Sweep / Vuln Scan — separate flow
8283 if (activeTab === 'sweep' || activeTab === 'vuln') {
8384 setSweepResult(null);
84- setSweepProgress({ current: 0, total: Math.pow(2, 32 - sweepCidr) });
85+ const cidr = sweepCidr;
86+ const totalHosts = Math.pow(2, 32 - cidr);
87+ setSweepProgress({ current: 0, total: totalHosts });
8588 try {
86- const cidr = sweepCidr;
89+ const t0 = Date.now();
8790 const res = await fetch(`/api/osint/sweep?ip=${encodeURIComponent(query)}&cidr=${cidr}`);
8891 if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || `Sweep failed (${res.status})`); }
89- const data = await res.json();
90- setSweepResult(data);
92+ const initData = await res.json();
93+
94+ const ipParts = initData.target_ip.split('.').map(Number) as [number, number, number, number];
95+ const ipNum = ipToNumber(ipParts);
96+ const subnetStart = calculateSubnetStart(ipNum, cidr);
97+ const subnet = numberToIp(subnetStart);
98+
99+ const urls: string[] = [];
100+ for (let i = 0; i < totalHosts; i++) {
101+ urls.push(`https://internetdb.shodan.io/${numberToIp((subnetStart + i) >>> 0)}`);
102+ }
103+
104+ const shodanResults = await batchFetch<ShodanInternetDBResponse>(urls, 15, async (u) => {
105+ try {
106+ const r = await fetch(u, { cache: 'no-store' });
107+ if (r.status === 404) return null;
108+ if (!r.ok) return null;
109+ return await r.json();
110+ } catch {
111+ return null;
112+ }
113+ }, (done) => setSweepProgress({ current: done, total: totalHosts }));
114+
115+ const devices: SweepDevice[] = [];
116+ const deviceBreakdown: Record<string, number> = {};
117+ for (const sr of shodanResults) {
118+ if (!sr) continue;
119+ const classification = classifyDevice(sr.ports, sr.cpes, sr.tags);
120+ const risk = assessRisk({ ports: sr.ports, vulns: sr.vulns });
121+ devices.push({
122+ ip: sr.ip, ports: sr.ports, hostnames: sr.hostnames,
123+ cpes: sr.cpes, vulns: sr.vulns, tags: sr.tags,
124+ device_type: classification.device_type,
125+ device_icon: classification.device_icon,
126+ device_color: classification.device_color,
127+ risk_level: risk
128+ });
129+ deviceBreakdown[classification.device_type] = (deviceBreakdown[classification.device_type] || 0) + 1;
130+ }
131+
132+ setSweepResult({
133+ center: initData.center,
134+ subnet: `${subnet}/${cidr}`,
135+ cidr,
136+ target_ip: initData.target_ip,
137+ devices,
138+ summary: { total_hosts: totalHosts, total_responsive: devices.length, device_breakdown: deviceBreakdown },
139+ sweep_time_ms: Date.now() - t0
140+ });
91141 setSweepProgress(null);
92142 setHistory(prev => [{ tab: activeTab, query, time: new Date().toLocaleTimeString() }, ...prev.slice(0, 9)]);
93143 } catch (err: any) {
@@ -118,9 +168,14 @@
118168 case 'ssl': url = `/api/scanner?target=${encodeURIComponent(query)}&type=ssl`; break;
119169 case 'subdomains': url = `/api/scanner?target=${encodeURIComponent(query)}&type=subdomains`; break;
120170 case 'tech': url = `/api/scanner?target=${encodeURIComponent(query)}&type=tech`; break;
121- case 'shodan': url = `/api/osint/shodan?ip=${encodeURIComponent(query)}`; break;
171+ case 'shodan': url = `https://internetdb.shodan.io/${encodeURIComponent(query)}`; break;
172+ }
173+ const res = await fetch(url, activeTab === 'shodan' ? { cache: 'no-store' } : undefined);
174+ if (activeTab === 'shodan' && res.status === 404) {
175+ setResults({ ip: query, status: 'No Shodan InternetDB records found', ports: [], cpes: [], hostnames: [], tags: [], vulns: [] });
176+ setLoading(false);
177+ return;
122178 }
123- const res = await fetch(url);
124179 const data = await res.json();
125180 if (res.ok) {
126181 setResults(data);
added src/lib/osint-utils.ts +185 −0
@@ -0,0 +1,185 @@
1+export interface SweepDevice {
2+ ip: string;
3+ ports: number[];
4+ hostnames: string[];
5+ cpes: string[];
6+ vulns: string[];
7+ tags: string[];
8+ device_type: string;
9+ device_icon: string;
10+ device_color: string;
11+ risk_level: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
12+}
13+
14+export interface SweepResult {
15+ center: {
16+ lat: number;
17+ lng: number;
18+ city: string;
19+ region: string;
20+ country: string;
21+ countryCode: string;
22+ isp: string;
23+ asn: string;
24+ org: string;
25+ };
26+ subnet: string;
27+ cidr: number;
28+ target_ip: string;
29+ devices: SweepDevice[];
30+ summary: {
31+ total_hosts: number;
32+ total_responsive: number;
33+ device_breakdown: Record<string, number>;
34+ };
35+ sweep_time_ms: number;
36+}
37+
38+export interface ShodanInternetDBResponse {
39+ cpes: string[];
40+ hostnames: string[];
41+ ip: string;
42+ ports: number[];
43+ tags: string[];
44+ vulns: string[];
45+}
46+
47+const IPV4_REGEX = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
48+
49+export function parseIPv4(ip: string): [number, number, number, number] | null {
50+ const match = ip.match(IPV4_REGEX);
51+ if (!match) return null;
52+
53+ const octets = [
54+ parseInt(match[1], 10),
55+ parseInt(match[2], 10),
56+ parseInt(match[3], 10),
57+ parseInt(match[4], 10),
58+ ] as [number, number, number, number];
59+
60+ if (octets.some((o) => o < 0 || o > 255)) return null;
61+ return octets;
62+}
63+
64+export function isPrivateOrReserved(octets: [number, number, number, number]): boolean {
65+ const [a, b] = octets;
66+ if (a === 10) return true;
67+ if (a === 172 && b >= 16 && b <= 31) return true;
68+ if (a === 192 && b === 168) return true;
69+ if (a === 127) return true;
70+ if (a === 100 && b >= 64 && b <= 127) return true;
71+ if (a === 169 && b === 254) return true;
72+ if (a >= 224) return true;
73+ if (a === 0) return true;
74+ return false;
75+}
76+
77+export function ipToNumber(octets: [number, number, number, number]): number {
78+ return ((octets[0] << 24) | (octets[1] << 16) | (octets[2] << 8) | octets[3]) >>> 0;
79+}
80+
81+export function numberToIp(num: number): string {
82+ return [
83+ (num >>> 24) & 0xff,
84+ (num >>> 16) & 0xff,
85+ (num >>> 8) & 0xff,
86+ num & 0xff,
87+ ].join('.');
88+}
89+
90+export function calculateSubnetStart(ipNum: number, cidr: number): number {
91+ const mask = (0xffffffff << (32 - cidr)) >>> 0;
92+ return (ipNum & mask) >>> 0;
93+}
94+
95+export interface DeviceClassification {
96+ device_type: string;
97+ device_icon: string;
98+ device_color: string;
99+}
100+
101+export function classifyDevice(
102+ ports: number[],
103+ cpes: string[],
104+ tags: string[],
105+): DeviceClassification {
106+ const portSet = new Set(ports || []);
107+ const cpeLower = (cpes || []).map((c) => c.toLowerCase());
108+ const tagLower = (tags || []).map((t) => t.toLowerCase());
109+
110+ if (portSet.has(554) || portSet.has(8554) || cpeLower.some((c) => /camera|dvr|hikvision|dahua|axis|ipcam/.test(c))) {
111+ return { device_type: 'Camera/DVR', device_icon: 'Camera', device_color: '#FF3D3D' };
112+ }
113+ if (portSet.has(9100) || cpeLower.some((c) => /printer|hp.*laserjet|epson|brother/.test(c))) {
114+ return { device_type: 'Printer', device_icon: 'Printer', device_color: '#F48FB1' };
115+ }
116+ if (portSet.has(1883) || portSet.has(8883) || tagLower.includes('iot')) {
117+ return { device_type: 'IoT Device', device_icon: 'Cpu', device_color: '#39FF14' };
118+ }
119+ if (portSet.has(5060) || portSet.has(5061)) {
120+ return { device_type: 'VoIP/SIP', device_icon: 'Phone', device_color: '#87CEEB' };
121+ }
122+ if (cpeLower.some((c) => /mikrotik|ubiquiti|cisco|juniper|fortinet/.test(c)) || portSet.has(161) || portSet.has(8291)) {
123+ return { device_type: 'Router/Switch', device_icon: 'Router', device_color: '#00E5FF' };
124+ }
125+ if (portSet.has(3306) || portSet.has(5432) || portSet.has(27017) || portSet.has(6379) || portSet.has(9200) || portSet.has(5984)) {
126+ return { device_type: 'Database', device_icon: 'Database', device_color: '#FF6B00' };
127+ }
128+ if (portSet.has(25) || portSet.has(587) || portSet.has(993) || portSet.has(995) || portSet.has(110) || portSet.has(143)) {
129+ return { device_type: 'Mail Server', device_icon: 'Mail', device_color: '#FF9500' };
130+ }
131+ if (portSet.has(53)) {
132+ return { device_type: 'DNS Server', device_icon: 'Server', device_color: '#00BCD4' };
133+ }
134+ if (portSet.has(21) || portSet.has(990)) {
135+ return { device_type: 'FTP Server', device_icon: 'HardDrive', device_color: '#FFD700' };
136+ }
137+ if (portSet.has(1194) || portSet.has(1723) || portSet.has(500) || portSet.has(4500) || cpeLower.some((c) => /openvpn|wireguard/.test(c))) {
138+ return { device_type: 'VPN Gateway', device_icon: 'ShieldCheck', device_color: '#D4AF37' };
139+ }
140+ if (portSet.has(3389)) {
141+ return { device_type: 'Windows Workstation', device_icon: 'Monitor', device_color: '#E040FB' };
142+ }
143+ if (portSet.has(22) && !portSet.has(80) && !portSet.has(443)) {
144+ return { device_type: 'Linux Server', device_icon: 'Terminal', device_color: '#76FF03' };
145+ }
146+ if (portSet.has(80) || portSet.has(443) || portSet.has(8080) || portSet.has(8443)) {
147+ return { device_type: 'Web Server', device_icon: 'Globe', device_color: '#448AFF' };
148+ }
149+ return { device_type: 'Unknown Host', device_icon: 'CircleDot', device_color: '#666666' };
150+}
151+
152+export function assessRisk(
153+ device: Partial<SweepDevice>,
154+): 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO' {
155+ const vulns = device.vulns ?? [];
156+ const ports = device.ports ?? [];
157+ const portSet = new Set(ports);
158+
159+ if (vulns.length > 5) return 'CRITICAL';
160+ if (vulns.length > 0) return 'HIGH';
161+ if (portSet.has(23) || portSet.has(21) || portSet.has(161)) return 'MEDIUM';
162+ if (ports.length > 5) return 'LOW';
163+ return 'INFO';
164+}
165+
166+export async function batchFetch<T>(
167+ urls: string[],
168+ concurrency: number,
169+ fn: (url: string) => Promise<T | null>,
170+ onProgress?: (done: number) => void
171+): Promise<(T | null)[]> {
172+ const results: (T | null)[] = new Array(urls.length).fill(null);
173+ let idx = 0;
174+ let completed = 0;
175+ const workers = Array.from({ length: concurrency }, async () => {
176+ while (idx < urls.length) {
177+ const i = idx++;
178+ results[i] = await fn(urls[i]);
179+ completed++;
180+ if (onProgress) onProgress(completed);
181+ }
182+ });
183+ await Promise.all(workers);
184+ return results;
185+}