| 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, { signal: AbortSignal.timeout(5000) }); |
| 407 | if (res.status === 404) return null; // Non-responsive host |
| 408 | if (!res.ok) return null; |
| 409 | return (await res.json()) as ShodanInternetDBResponse; |
| 410 | } catch { |
| 411 | return null; |
| 412 | } |
| 413 | }, |
| 414 | ); |
| 415 | |
| 416 | // --- 5 & 6. Classify Devices --- |
| 417 | const devices: SweepDevice[] = []; |
| 418 | const deviceBreakdown: Record<string, number> = {}; |
| 419 | |
| 420 | for (const result of shodanResults) { |
| 421 | if (!result) continue; |
| 422 | |
| 423 | const classification = classifyDevice(result.ports, result.cpes, result.tags); |
| 424 | const risk = assessRisk({ |
| 425 | ports: result.ports, |
| 426 | vulns: result.vulns, |
| 427 | }); |
| 428 | |
| 429 | devices.push({ |
| 430 | ip: result.ip, |
| 431 | ports: result.ports, |
| 432 | hostnames: result.hostnames, |
| 433 | cpes: result.cpes, |
| 434 | vulns: result.vulns, |
| 435 | tags: result.tags, |
| 436 | device_type: classification.device_type, |
| 437 | device_icon: classification.device_icon, |
| 438 | device_color: classification.device_color, |
| 439 | risk_level: risk, |
| 440 | }); |
| 441 | |
| 442 | deviceBreakdown[classification.device_type] = |
| 443 | (deviceBreakdown[classification.device_type] || 0) + 1; |
| 444 | } |
| 445 | |
| 446 | // --- 7. Response --- |
| 447 | const sweepResult: SweepResult = { |
| 448 | center, |
| 449 | subnet: `${subnet}/${cidr}`, |
| 450 | cidr, |
| 451 | target_ip: ip, |
| 452 | devices, |
| 453 | summary: { |
| 454 | total_hosts: totalHosts, |
| 455 | total_responsive: devices.length, |
| 456 | device_breakdown: deviceBreakdown, |
| 457 | }, |
| 458 | sweep_time_ms: Date.now() - startTime, |
| 459 | }; |
| 460 | |
| 461 | return NextResponse.json(sweepResult, { |
| 462 | headers: { |
| 463 | 'Cache-Control': 'no-cache, no-store, must-revalidate', |
| 464 | Pragma: 'no-cache', |
| 465 | Expires: '0', |
| 466 | }, |
| 467 | }); |
| 468 | } catch (err) { |
| 469 | console.error('[OSIRIS] Sweep error:', err instanceof Error ? err.message : err); |
| 470 | return NextResponse.json({ error: 'Sweep failed' }, { status: 500 }); |
| 471 | } |
| 472 | } |