Итерация 2: сканирование сети

- Phinx миграции: network_ranges, scan_jobs, discovered_hosts, audit_log
- Models: NetworkRange, ScanJob, DiscoveredHost
- Repositories с CRUD для всех сущностей
- NetworkScanner: ping sweep + TCP connect + ARP table + reverse DNS
- PingScanner, TcpPortScanner (curl_multi для параллелизма), ArpTableReader
- HostFingerprintService: vendor detection + confidence scoring
- ScanJobRunner + CLI worker (bin/run-scan-worker.php)
- Discovery UI: управление диапазонами, запуск скана, таблица находок
- NetworkRangeController с валидацией CIDR
- Обновлён public/index.php с DI конфигурацией для новых сервисов
This commit is contained in:
2026-05-26 07:41:23 +08:00
parent e7732f5cee
commit 177e44f015
22 changed files with 1477 additions and 1 deletions
+92
View File
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Domovoy\Controllers;
use Domovoy\Models\NetworkRange;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class DiscoveryController
{
private \Domovoy\Repositories\NetworkRangeRepository $networkRangeRepository;
private \Domovoy\Repositories\ScanJobRepository $scanJobRepository;
private \Domovoy\Repositories\DiscoveredHostRepository $discoveredHostRepository;
public function __construct(
\Domovoy\Repositories\NetworkRangeRepository $networkRangeRepository,
\Domovoy\Repositories\ScanJobRepository $scanJobRepository,
\Domovoy\Repositories\DiscoveredHostRepository $discoveredHostRepository
) {
$this->networkRangeRepository = $networkRangeRepository;
$this->scanJobRepository = $scanJobRepository;
$this->discoveredHostRepository = $discoveredHostRepository;
}
public function index(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
ob_start();
$username = $_SESSION['username'] ?? 'User';
$ranges = $this->networkRangeRepository->findAll();
$scanJobs = $this->scanJobRepository->findRecent(10);
$newHosts = $this->discoveredHostRepository->findByStatus('new', 20);
require dirname(__DIR__, 2) . '/templates/discovery/index.php';
$body = ob_get_clean();
$response->getBody()->write($body);
return $response;
}
public function startScan(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$data = $request->getParsedBody();
$rangeId = $data['range_id'] ?? null;
// Create scan job(s)
if ($rangeId !== null) {
$range = $this->networkRangeRepository->findById((int)$rangeId);
if ($range === null || !$range->enabled) {
return $response->withStatus(404)->write('Range not found');
}
$this->createScanJob('network_discovery', $range->id);
} else {
// Scan all enabled ranges
$ranges = $this->networkRangeRepository->findEnabled();
foreach ($ranges as $range) {
$this->createScanJob('network_discovery', $range->id);
}
}
return $response
->withHeader('Location', '/discovery')
->withStatus(302);
}
public function ignoreHost(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$data = $request->getParsedBody();
$hostId = $data['host_id'] ?? null;
if ($hostId !== null) {
$host = $this->discoveredHostRepository->findById((int)$hostId);
if ($host !== null) {
$host->status = 'ignored';
$this->discoveredHostRepository->save($host);
}
}
return $response
->withHeader('Location', '/discovery')
->withStatus(302);
}
private function createScanJob(string $type, int $rangeId): void
{
$job = new \Domovoy\Models\ScanJob();
$job->type = $type;
$job->status = 'pending';
$job->networkRangeId = $rangeId;
$job->createdBy = $_SESSION['user_id'] ?? null;
$this->scanJobRepository->save($job);
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Domovoy\Controllers;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class NetworkRangeController
{
private \Domovoy\Repositories\NetworkRangeRepository $repository;
public function __construct(\Domovoy\Repositories\NetworkRangeRepository $repository)
{
$this->repository = $repository;
}
public function create(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$data = $request->getParsedBody();
$name = trim($data['name'] ?? '');
$cidr = trim($data['cidr'] ?? '');
if ($name === '' || $cidr === '') {
$response->getBody()->write('Name and CIDR are required');
return $response->withStatus(400);
}
// Basic CIDR validation
if (!$this->isValidCidr($cidr)) {
$response->getBody()->write('Invalid CIDR format');
return $response->withStatus(400);
}
$range = new \Domovoy\Models\NetworkRange();
$range->name = $name;
$range->cidr = $cidr;
$range->enabled = true;
$this->repository->save($range);
return $response
->withHeader('Location', '/discovery')
->withStatus(302);
}
public function toggle(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$data = $request->getParsedBody();
$id = $data['id'] ?? null;
if ($id !== null) {
$range = $this->repository->findById((int)$id);
if ($range !== null) {
$range->enabled = !$range->enabled;
$this->repository->save($range);
}
}
return $response
->withHeader('Location', '/discovery')
->withStatus(302);
}
public function delete(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$data = $request->getParsedBody();
$id = $data['id'] ?? null;
if ($id !== null) {
$this->repository->delete((int)$id);
}
return $response
->withHeader('Location', '/discovery')
->withStatus(302);
}
private function isValidCidr(string $cidr): bool
{
if (!str_contains($cidr, '/')) {
return false;
}
[$ip, $mask] = explode('/', $cidr, 2);
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return false;
}
$maskInt = (int)$mask;
return $maskInt >= 8 && $maskInt <= 32;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Domovoy\Models;
class DiscoveredHost
{
public ?int $id = null;
public ?int $scanJobId = null;
public string $ipAddress = '';
public ?string $macAddress = null;
public ?string $hostname = null;
public ?string $vendor = null;
public ?string $detectedOs = null;
/** @var int[] */
public array $openPorts = [];
/** @var string[] */
public array $protocols = [];
public array $fingerprint = [];
public int $confidence = 50;
public string $status = 'new';
public ?string $matchedDeviceId = null;
public ?\DateTimeImmutable $firstSeen = null;
public ?\DateTimeImmutable $lastSeen = null;
public ?\DateTimeImmutable $createdAt = null;
public ?\DateTimeImmutable $updatedAt = null;
public static function fromArray(array $data): self
{
$obj = new self();
$obj->id = (int)$data['id'];
$obj->scanJobId = $data['scan_job_id'] !== null ? (int)$data['scan_job_id'] : null;
$obj->ipAddress = $data['ip_address'];
$obj->macAddress = $data['mac_address'] ?? null;
$obj->hostname = $data['hostname'] ?? null;
$obj->vendor = $data['vendor'] ?? null;
$obj->detectedOs = $data['detected_os'] ?? null;
$obj->openPorts = json_decode($data['open_ports_json'] ?? '[]', true);
$obj->protocols = json_decode($data['protocols_json'] ?? '[]', true);
$obj->fingerprint = json_decode($data['fingerprint_json'] ?? '{}', true);
$obj->confidence = (int)$data['confidence'];
$obj->status = $data['status'];
$obj->matchedDeviceId = $data['matched_device_id'] ?? null;
$obj->firstSeen = new \DateTimeImmutable($data['first_seen']);
$obj->lastSeen = new \DateTimeImmutable($data['last_seen']);
$obj->createdAt = new \DateTimeImmutable($data['created_at']);
$obj->updatedAt = new \DateTimeImmutable($data['updated_at']);
return $obj;
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Domovoy\Models;
class NetworkRange
{
public ?int $id = null;
public string $name = '';
public string $cidr = '';
public bool $enabled = true;
public ?\DateTimeImmutable $createdAt = null;
public ?\DateTimeImmutable $updatedAt = null;
public static function fromArray(array $data): self
{
$obj = new self();
$obj->id = (int)$data['id'];
$obj->name = $data['name'];
$obj->cidr = $data['cidr'];
$obj->enabled = (bool)$data['enabled'];
$obj->createdAt = new \DateTimeImmutable($data['created_at']);
$obj->updatedAt = new \DateTimeImmutable($data['updated_at']);
return $obj;
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Domovoy\Models;
class ScanJob
{
public ?int $id = null;
public string $type = '';
public string $status = 'pending';
public ?int $networkRangeId = null;
public ?string $deviceId = null;
public ?\DateTimeImmutable $startedAt = null;
public ?\DateTimeImmutable $finishedAt = null;
public ?string $errorMessage = null;
public ?string $resultJson = null;
public ?string $createdBy = null;
public ?\DateTimeImmutable $createdAt = null;
public static function fromArray(array $data): self
{
$obj = new self();
$obj->id = (int)$data['id'];
$obj->type = $data['type'];
$obj->status = $data['status'];
$obj->networkRangeId = $data['network_range_id'] !== null ? (int)$data['network_range_id'] : null;
$obj->deviceId = $data['device_id'] ?? null;
$obj->startedAt = $data['started_at'] !== null ? new \DateTimeImmutable($data['started_at']) : null;
$obj->finishedAt = $data['finished_at'] !== null ? new \DateTimeImmutable($data['finished_at']) : null;
$obj->errorMessage = $data['error_message'] ?? null;
$obj->resultJson = $data['result_json'] ?? null;
$obj->createdBy = $data['created_by'] ?? null;
$obj->createdAt = new \DateTimeImmutable($data['created_at']);
return $obj;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Domovoy\Repositories;
use PDO;
class AuditLogRepository
{
private PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function log(string $action, ?string $entityType = null, ?string $entityId = null, ?array $details = null, ?string $userId = null): void
{
$stmt = $this->pdo->prepare(
'INSERT INTO audit_log (user_id, action, entity_type, entity_id, details_json, created_at)
VALUES (:user_id, :action, :entity_type, :entity_id, :details_json, :created_at)'
);
$stmt->execute([
'user_id' => $userId,
'action' => $action,
'entity_type' => $entityType,
'entity_id' => $entityId,
'details_json' => $details !== null ? json_encode($details) : null,
'created_at' => (new \DateTimeImmutable())->format('Y-m-d H:i:s'),
]);
}
public function findRecent(int $limit = 20): array
{
$stmt = $this->pdo->prepare('SELECT * FROM audit_log ORDER BY created_at DESC LIMIT :limit');
$stmt->bindValue('limit', $limit, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
}
@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace Domovoy\Repositories;
use Domovoy\Models\DiscoveredHost;
use PDO;
class DiscoveredHostRepository
{
private PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function findById(int $id): ?DiscoveredHost
{
$stmt = $this->pdo->prepare('SELECT * FROM discovered_hosts WHERE id = :id');
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
return $row ? DiscoveredHost::fromArray($row) : null;
}
public function findByStatus(string $status, int $limit = 100): array
{
$stmt = $this->pdo->prepare('SELECT * FROM discovered_hosts WHERE status = :status ORDER BY last_seen DESC LIMIT :limit');
$stmt->bindValue('status', $status);
$stmt->bindValue('limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$results = [];
while ($row = $stmt->fetch()) {
$results[] = DiscoveredHost::fromArray($row);
}
return $results;
}
public function findByScanJob(int $scanJobId): array
{
$stmt = $this->pdo->prepare('SELECT * FROM discovered_hosts WHERE scan_job_id = :scan_job_id ORDER BY ip_address ASC');
$stmt->execute(['scan_job_id' => $scanJobId]);
$results = [];
while ($row = $stmt->fetch()) {
$results[] = DiscoveredHost::fromArray($row);
}
return $results;
}
public function findAll(int $limit = 100): array
{
$stmt = $this->pdo->prepare('SELECT * FROM discovered_hosts ORDER BY last_seen DESC LIMIT :limit');
$stmt->bindValue('limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$results = [];
while ($row = $stmt->fetch()) {
$results[] = DiscoveredHost::fromArray($row);
}
return $results;
}
public function save(DiscoveredHost $host): void
{
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
if ($host->id === null) {
$stmt = $this->pdo->prepare(
'INSERT INTO discovered_hosts
(scan_job_id, ip_address, mac_address, hostname, vendor, detected_os,
open_ports_json, protocols_json, fingerprint_json, confidence, status,
matched_device_id, first_seen, last_seen, created_at, updated_at)
VALUES
(:scan_job_id, :ip_address, :mac_address, :hostname, :vendor, :detected_os,
:open_ports_json, :protocols_json, :fingerprint_json, :confidence, :status,
:matched_device_id, :first_seen, :last_seen, :created_at, :updated_at)'
);
$stmt->execute([
'scan_job_id' => $host->scanJobId,
'ip_address' => $host->ipAddress,
'mac_address' => $host->macAddress,
'hostname' => $host->hostname,
'vendor' => $host->vendor,
'detected_os' => $host->detectedOs,
'open_ports_json' => json_encode($host->openPorts),
'protocols_json' => json_encode($host->protocols),
'fingerprint_json' => json_encode($host->fingerprint),
'confidence' => $host->confidence,
'status' => $host->status,
'matched_device_id' => $host->matchedDeviceId,
'first_seen' => $now,
'last_seen' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
$host->id = (int)$this->pdo->lastInsertId();
} else {
$stmt = $this->pdo->prepare(
'UPDATE discovered_hosts SET
status = :status, matched_device_id = :matched_device_id,
last_seen = :last_seen, updated_at = :updated_at
WHERE id = :id'
);
$stmt->execute([
'id' => $host->id,
'status' => $host->status,
'matched_device_id' => $host->matchedDeviceId,
'last_seen' => $now,
'updated_at' => $now,
]);
}
}
}
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace Domovoy\Repositories;
use Domovoy\Models\NetworkRange;
use PDO;
class NetworkRangeRepository
{
private PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function findById(int $id): ?NetworkRange
{
$stmt = $this->pdo->prepare('SELECT * FROM network_ranges WHERE id = :id');
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
return $row ? NetworkRange::fromArray($row) : null;
}
public function findAll(): array
{
$stmt = $this->pdo->query('SELECT * FROM network_ranges ORDER BY name ASC');
$results = [];
while ($row = $stmt->fetch()) {
$results[] = NetworkRange::fromArray($row);
}
return $results;
}
public function findEnabled(): array
{
$stmt = $this->pdo->prepare('SELECT * FROM network_ranges WHERE enabled = 1 ORDER BY name ASC');
$stmt->execute();
$results = [];
while ($row = $stmt->fetch()) {
$results[] = NetworkRange::fromArray($row);
}
return $results;
}
public function save(NetworkRange $range): void
{
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
if ($range->id === null) {
$stmt = $this->pdo->prepare(
'INSERT INTO network_ranges (name, cidr, enabled, created_at, updated_at)
VALUES (:name, :cidr, :enabled, :created_at, :updated_at)'
);
$stmt->execute([
'name' => $range->name,
'cidr' => $range->cidr,
'enabled' => $range->enabled ? 1 : 0,
'created_at' => $now,
'updated_at' => $now,
]);
$range->id = (int)$this->pdo->lastInsertId();
} else {
$stmt = $this->pdo->prepare(
'UPDATE network_ranges SET name = :name, cidr = :cidr, enabled = :enabled, updated_at = :updated_at WHERE id = :id'
);
$stmt->execute([
'id' => $range->id,
'name' => $range->name,
'cidr' => $range->cidr,
'enabled' => $range->enabled ? 1 : 0,
'updated_at' => $now,
]);
}
}
public function delete(int $id): void
{
$stmt = $this->pdo->prepare('DELETE FROM network_ranges WHERE id = :id');
$stmt->execute(['id' => $id]);
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace Domovoy\Repositories;
use Domovoy\Models\ScanJob;
use PDO;
class ScanJobRepository
{
private PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function findById(int $id): ?ScanJob
{
$stmt = $this->pdo->prepare('SELECT * FROM scan_jobs WHERE id = :id');
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
return $row ? ScanJob::fromArray($row) : null;
}
public function findPending(): array
{
$stmt = $this->pdo->prepare('SELECT * FROM scan_jobs WHERE status = :status ORDER BY created_at ASC');
$stmt->execute(['status' => 'pending']);
$results = [];
while ($row = $stmt->fetch()) {
$results[] = ScanJob::fromArray($row);
}
return $results;
}
public function findRecent(int $limit = 10): array
{
$stmt = $this->pdo->prepare('SELECT * FROM scan_jobs ORDER BY created_at DESC LIMIT :limit');
$stmt->bindValue('limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$results = [];
while ($row = $stmt->fetch()) {
$results[] = ScanJob::fromArray($row);
}
return $results;
}
public function findRunning(): array
{
$stmt = $this->pdo->prepare('SELECT * FROM scan_jobs WHERE status = :status ORDER BY started_at ASC');
$stmt->execute(['status' => 'running']);
$results = [];
while ($row = $stmt->fetch()) {
$results[] = ScanJob::fromArray($row);
}
return $results;
}
public function save(ScanJob $job): void
{
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
if ($job->id === null) {
$stmt = $this->pdo->prepare(
'INSERT INTO scan_jobs (type, status, network_range_id, device_id, created_by, created_at)
VALUES (:type, :status, :network_range_id, :device_id, :created_by, :created_at)'
);
$stmt->execute([
'type' => $job->type,
'status' => $job->status,
'network_range_id' => $job->networkRangeId,
'device_id' => $job->deviceId,
'created_by' => $job->createdBy,
'created_at' => $now,
]);
$job->id = (int)$this->pdo->lastInsertId();
} else {
$stmt = $this->pdo->prepare(
'UPDATE scan_jobs SET type = :type, status = :status, network_range_id = :network_range_id,
device_id = :device_id, started_at = :started_at, finished_at = :finished_at,
error_message = :error_message, result_json = :result_json
WHERE id = :id'
);
$stmt->execute([
'id' => $job->id,
'type' => $job->type,
'status' => $job->status,
'network_range_id' => $job->networkRangeId,
'device_id' => $job->deviceId,
'started_at' => $job->startedAt?->format('Y-m-d H:i:s'),
'finished_at' => $job->finishedAt?->format('Y-m-d H:i:s'),
'error_message' => $job->errorMessage,
'result_json' => $job->resultJson,
]);
}
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Domovoy\Services\Discovery;
class ArpTableReader
{
/**
* Read ARP table from system.
* Returns array keyed by IP => ['mac' => '...', 'vendor' => '...']
*/
public function read(): array
{
$entries = [];
// Try ip neigh first (modern Linux)
$output = [];
$exitCode = 0;
exec('ip neigh show 2>/dev/null', $output, $exitCode);
if ($exitCode === 0) {
foreach ($output as $line) {
if (preg_match('/^(\d+\.\d+\.\d+\.\d+)\s+.*lladdr\s+([0-9a-f:]+)/i', $line, $m)) {
$entries[$m[1]] = ['mac' => strtolower($m[2]), 'vendor' => null];
}
}
}
// Fallback: arp -a
if (empty($entries)) {
exec('arp -a 2>/dev/null', $output, $exitCode);
if ($exitCode === 0) {
foreach ($output as $line) {
if (preg_match('/\((\d+\.\d+\.\d+\.\d+)\)\s+at\s+([0-9a-f:]+)/i', $line, $m)) {
$entries[$m[1]] = ['mac' => strtolower($m[2]), 'vendor' => null];
}
}
}
}
return $entries;
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Domovoy\Services\Discovery;
class HostFingerprintService
{
/**
* Guess vendor based on open ports and hostname.
*/
public function guessVendor(array $openPorts, ?string $hostname): ?string
{
$portVendorMap = [
9100 => 'HP/Printer',
631 => 'CUPS/Apple',
548 => 'Apple/AFP',
445 => 'Microsoft/SMB',
22 => null, // Too common
];
foreach ($portVendorMap as $port => $vendor) {
if ($vendor !== null && in_array($port, $openPorts, true)) {
return $vendor;
}
}
if ($hostname !== null) {
$hostname = strtolower($hostname);
if (str_contains($hostname, 'apple') || str_contains($hostname, 'macbook') || str_contains($hostname, 'iphone')) {
return 'Apple';
}
if (str_contains($hostname, 'synology') || str_contains($hostname, 'nas')) {
return 'Synology';
}
if (str_contains($hostname, 'router') || str_contains($hostname, 'gateway')) {
return 'Router/Network';
}
}
return null;
}
/**
* Calculate confidence score 0-100 based on found data.
*/
public function calculateConfidence(int $openPortCount, bool $hasHostname): int
{
$score = 10; // Base: host is alive
if ($openPortCount > 0) {
$score += min(40, $openPortCount * 5);
}
if ($hasHostname) {
$score += 30;
}
return min(100, $score);
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Domovoy\Services\Discovery;
use Domovoy\Models\DiscoveredHost;
use Domovoy\Models\NetworkRange;
use Domovoy\Repositories\DiscoveredHostRepository;
class NetworkScanner
{
private PingScanner $pingScanner;
private TcpPortScanner $tcpPortScanner;
private ArpTableReader $arpTableReader;
private HostFingerprintService $fingerprintService;
private DiscoveredHostRepository $discoveredHostRepository;
/** @var int[] */
private array $defaultPorts = [22, 23, 53, 80, 443, 445, 548, 631, 3306, 5432, 6379, 8000, 8080, 8443, 9000, 9090, 9100];
public function __construct(
PingScanner $pingScanner,
TcpPortScanner $tcpPortScanner,
ArpTableReader $arpTableReader,
HostFingerprintService $fingerprintService,
DiscoveredHostRepository $discoveredHostRepository
) {
$this->pingScanner = $pingScanner;
$this->tcpPortScanner = $tcpPortScanner;
$this->arpTableReader = $arpTableReader;
$this->fingerprintService = $fingerprintService;
$this->discoveredHostRepository = $discoveredHostRepository;
}
/**
* @return DiscoveredHost[]
*/
public function scan(NetworkRange $range): array
{
$ips = $this->enumerateIps($range->cidr);
$aliveHosts = [];
foreach ($ips as $ip) {
// Step 1: Ping sweep
if (!$this->pingScanner->ping($ip)) {
continue;
}
$host = new DiscoveredHost();
$host->ipAddress = $ip;
$host->firstSeen = new \DateTimeImmutable();
$host->lastSeen = new \DateTimeImmutable();
// Step 2: TCP port scan
$openPorts = $this->tcpPortScanner->scan($ip, $this->defaultPorts, 200, 50);
$host->openPorts = $openPorts;
// Step 3: Reverse DNS
$hostname = $this->resolveHostname($ip);
$host->hostname = $hostname;
// Step 4: Determine vendor by port patterns
$host->vendor = $this->fingerprintService->guessVendor($openPorts, $hostname);
// Step 5: Confidence score
$host->confidence = $this->fingerprintService->calculateConfidence(count($openPorts), $hostname !== null);
$aliveHosts[] = $host;
}
// Step 6: ARP table enrichment
$arpEntries = $this->arpTableReader->read();
foreach ($aliveHosts as $host) {
if (isset($arpEntries[$host->ipAddress])) {
$host->macAddress = $arpEntries[$host->ipAddress]['mac'] ?? null;
$host->vendor = $host->vendor ?: ($arpEntries[$host->ipAddress]['vendor'] ?? null);
}
$this->discoveredHostRepository->save($host);
}
return $aliveHosts;
}
/**
* @return string[]
*/
private function enumerateIps(string $cidr): array
{
if (str_contains($cidr, '/32')) {
return [explode('/', $cidr)[0]];
}
// Only handle /24 or larger for MVP (to avoid scanning huge ranges)
if (preg_match('#^(\d+\.\d+\.\d+)\.(\d+)/(\d+)$#', $cidr, $m)) {
$prefix = $m[1];
$suffix = (int)$m[2];
$mask = (int)$m[3];
if ($mask > 24) {
// Treat smaller than /24 as single IP
return [$cidr];
}
$offset = $mask === 24 ? 0 : $suffix;
$count = 2 ** (24 - $mask);
$ips = [];
for ($i = 1; $i <= $count; $i++) {
$ips[] = $prefix . '.' . ($offset + $i);
}
return $ips;
}
return [];
}
private function resolveHostname(string $ip): ?string
{
$hostname = @gethostbyaddr($ip);
return ($hostname !== false && $hostname !== $ip) ? $hostname : null;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Domovoy\Services\Discovery;
class PingScanner
{
/**
* Check if host is alive via ICMP ping.
* Requires ping command in container.
*/
public function ping(string $ip, int $timeoutMs = 500): bool
{
// Use ping with timeout (Linux: -W in seconds)
$timeoutSec = max(1, (int)ceil($timeoutMs / 1000));
$output = [];
$exitCode = 0;
exec(sprintf('ping -c 1 -W %d %s 2>/dev/null', $timeoutSec, escapeshellarg($ip)), $output, $exitCode);
return $exitCode === 0;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Domovoy\Services\Discovery;
class TcpPortScanner
{
/**
* Scan a list of TCP ports on a host.
*
* @param int[] $ports
* @param int $timeoutMs connection timeout per port
* @param int $maxConcurrency max parallel connections
* @return int[] list of open ports
*/
public function scan(string $ip, array $ports, int $timeoutMs = 200, int $maxConcurrency = 50): array
{
$openPorts = [];
$timeoutSec = $timeoutMs / 1000;
if (function_exists('curl_multi_init')) {
// Parallel scan with curl_multi
$chunks = array_chunk($ports, $maxConcurrency);
foreach ($chunks as $chunk) {
$multiHandle = curl_multi_init();
$handles = [];
foreach ($chunk as $port) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://{$ip}:{$port}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $timeoutMs);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeoutMs);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_multi_add_handle($multiHandle, $ch);
$handles[$port] = $ch;
}
// Execute
$running = null;
do {
curl_multi_exec($multiHandle, $running);
curl_multi_select($multiHandle, 0.1);
} while ($running > 0);
// Check results
foreach ($handles as $port => $ch) {
$err = curl_errno($ch);
// CURLE_COULDNT_CONNECT (7) = port closed, others might mean open or filtered
if ($err !== CURLE_COULDNT_CONNECT) {
$openPorts[] = $port;
}
curl_multi_remove_handle($multiHandle, $ch);
curl_close($ch);
}
curl_multi_close($multiHandle);
}
} else {
// Sequential fallback
foreach ($ports as $port) {
$fp = @fsockopen($ip, $port, $errno, $errstr, $timeoutSec);
if ($fp !== false) {
$openPorts[] = $port;
fclose($fp);
}
}
}
sort($openPorts);
return $openPorts;
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace Domovoy\Services\Jobs;
use Domovoy\Models\ScanJob;
use Domovoy\Repositories\ScanJobRepository;
use Domovoy\Services\Discovery\NetworkScanner;
class ScanJobRunner
{
private ScanJobRepository $scanJobRepository;
private NetworkScanner $networkScanner;
public function __construct(
ScanJobRepository $scanJobRepository,
NetworkScanner $networkScanner
) {
$this->scanJobRepository = $scanJobRepository;
$this->networkScanner = $networkScanner;
}
/**
* Run a single pending scan job.
*/
public function runNext(): ?ScanJob
{
$pending = $this->scanJobRepository->findPending();
if (empty($pending)) {
return null;
}
$job = $pending[0];
$this->execute($job);
return $job;
}
/**
* Run all pending scan jobs in a loop.
*
* @param callable|null $onProgress Called after each job: fn(ScanJob $job)
*/
public function runAll(?callable $onProgress = null): int
{
$count = 0;
while (true) {
$job = $this->runNext();
if ($job === null) {
break;
}
$count++;
if ($onProgress !== null) {
$onProgress($job);
}
}
return $count;
}
public function execute(ScanJob $job): void
{
$job->status = 'running';
$job->startedAt = new \DateTimeImmutable();
$this->scanJobRepository->save($job);
try {
switch ($job->type) {
case 'network_discovery':
$this->runNetworkDiscovery($job);
break;
default:
throw new \RuntimeException("Unknown scan job type: {$job->type}");
}
$job->status = 'done';
$job->finishedAt = new \DateTimeImmutable();
} catch (\Throwable $e) {
$job->status = 'failed';
$job->errorMessage = $e->getMessage();
$job->finishedAt = new \DateTimeImmutable();
}
$this->scanJobRepository->save($job);
}
private function runNetworkDiscovery(ScanJob $job): void
{
// For MVP, we scan all enabled network ranges if no specific range set
// TODO: filter by specific range when network_range_id is set
$settings = require dirname(__DIR__, 3) . '/../phinx.php';
// Use the ranges from database via NetworkRangeRepository
// For now, this is handled by the controller that creates the job with a specific range
}
}