From f8b876b2d5eda57eb066fbee0e630b91e28102cb Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 15:03:28 -0300 Subject: [PATCH] feat(network): add probe, wifi, reset, ssl, lan scan, and public IP commands --- app/Commands/Network/LanScanCommand.php | 75 ++++ app/Commands/Network/NetResetCommand.php | 63 ++++ app/Commands/Network/ProbeCommand.php | 114 ++++++ app/Commands/Network/PublicIpCommand.php | 48 +++ app/Commands/Network/SslCheckCommand.php | 63 ++++ app/Commands/Network/WifiCommand.php | 55 +++ app/Commands/ToolboxMenuCommand.php | 6 + app/Contracts/SystemDriverInterface.php | 48 +++ .../Concerns/InteractsWithNetworkSockets.php | 326 ++++++++++++++++++ app/Drivers/LinuxDriver.php | 209 +++++++++++ app/Drivers/WindowsDriver.php | 159 +++++++++ lang/en/messages.php | 70 ++++ lang/pt_BR/messages.php | 70 ++++ tests/Feature/ReportExporterTest.php | 30 ++ tests/Unit/HealthCheckServiceTest.php | 30 ++ tests/Unit/LinuxDriverTest.php | 62 ++++ tests/Unit/WindowsDriverTest.php | 78 +++++ 17 files changed, 1506 insertions(+) create mode 100644 app/Commands/Network/LanScanCommand.php create mode 100644 app/Commands/Network/NetResetCommand.php create mode 100644 app/Commands/Network/ProbeCommand.php create mode 100644 app/Commands/Network/PublicIpCommand.php create mode 100644 app/Commands/Network/SslCheckCommand.php create mode 100644 app/Commands/Network/WifiCommand.php create mode 100644 app/Drivers/Concerns/InteractsWithNetworkSockets.php diff --git a/app/Commands/Network/LanScanCommand.php b/app/Commands/Network/LanScanCommand.php new file mode 100644 index 0000000..e59736a --- /dev/null +++ b/app/Commands/Network/LanScanCommand.php @@ -0,0 +1,75 @@ +resolveLocale(); + + info((string) __('messages.network.scan_section')); + + /** @var array $devices */ + $devices = spin( + callback: fn (): array => $driver->scanLanDevices(), + message: (string) __('messages.spinners.network_scan'), + ); + + if ($devices === []) { + warning((string) __('messages.network.no_lan_devices')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.network.scan_headers.ip'), + (string) __('messages.network.scan_headers.mac'), + (string) __('messages.network.scan_headers.status'), + (string) __('messages.network.scan_headers.interface'), + ], + rows: array_map( + fn (array $device): array => [ + $device['ip'] ?? '-', + $device['mac'] ?? '-', + $device['status'] ?? '-', + $device['interface'] ?? '-', + ], + $devices + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Network/NetResetCommand.php b/app/Commands/Network/NetResetCommand.php new file mode 100644 index 0000000..afe4a51 --- /dev/null +++ b/app/Commands/Network/NetResetCommand.php @@ -0,0 +1,63 @@ +resolveLocale(); + + info((string) __('messages.network.reset_section')); + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.network.confirm_reset'), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $driver->resetNetworkStack(), + message: (string) __('messages.spinners.network_reset'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Network/ProbeCommand.php b/app/Commands/Network/ProbeCommand.php new file mode 100644 index 0000000..5ea4c00 --- /dev/null +++ b/app/Commands/Network/ProbeCommand.php @@ -0,0 +1,114 @@ +resolveLocale(); + + info((string) __('messages.network.probe_section')); + + $hostArg = $this->argument('host'); + $host = is_string($hostArg) && trim($hostArg) !== '' + ? trim($hostArg) + : text( + label: (string) __('messages.network.probe_host_prompt'), + default: '1.1.1.1', + required: true, + ); + + $portArg = $this->argument('port'); + $portStr = is_string($portArg) && trim($portArg) !== '' + ? trim($portArg) + : text( + label: (string) __('messages.network.probe_port_prompt'), + default: '443', + required: true, + validate: fn (string $val): ?string => (is_numeric($val) && (int) $val >= 1 && (int) $val <= 65535) + ? null + : (string) __('messages.network.probe_invalid_port'), + ); + + $port = max(1, min(65535, (int) $portStr)); + $timeout = max(1, (int) $this->option('timeout')); + + $result = spin( + callback: fn (): array => $driver->probePort($host, $port, $timeout), + message: (string) __('messages.spinners.network_probe', ['host' => $host, 'port' => $port]), + ); + + table( + headers: [ + (string) __('messages.network.probe_headers.host'), + (string) __('messages.network.probe_headers.port'), + (string) __('messages.network.probe_headers.status'), + (string) __('messages.network.probe_headers.latency'), + (string) __('messages.network.probe_headers.details'), + ], + rows: [ + [ + $result['host'], + (string) $result['port'], + $result['status'], + $result['latency'], + $result['error'], + ], + ], + ); + + if ($result['status'] === 'OPEN') { + info((string) __('messages.network.probe_open_success', [ + 'host' => $result['host'], + 'port' => $result['port'], + 'latency' => $result['latency'], + ])); + + return self::SUCCESS; + } + + error((string) __('messages.network.probe_failed', [ + 'host' => $result['host'], + 'port' => $result['port'], + 'status' => $result['status'], + ])); + + return self::FAILURE; + } +} diff --git a/app/Commands/Network/PublicIpCommand.php b/app/Commands/Network/PublicIpCommand.php new file mode 100644 index 0000000..8af796b --- /dev/null +++ b/app/Commands/Network/PublicIpCommand.php @@ -0,0 +1,48 @@ +resolveLocale(); + + info((string) __('messages.network.public_section')); + + $result = spin( + callback: fn () => $driver->getPublicIpInfo(), + message: (string) __('messages.spinners.network_public'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Network/SslCheckCommand.php b/app/Commands/Network/SslCheckCommand.php new file mode 100644 index 0000000..f7a0daf --- /dev/null +++ b/app/Commands/Network/SslCheckCommand.php @@ -0,0 +1,63 @@ +resolveLocale(); + + info((string) __('messages.network.ssl_section')); + + $domainArg = $this->argument('domain'); + $domain = is_string($domainArg) && trim($domainArg) !== '' + ? trim($domainArg) + : text( + label: (string) __('messages.network.ssl_domain_prompt'), + default: 'google.com', + required: true, + ); + + $port = max(1, min(65535, (int) $this->option('port'))); + + $result = spin( + callback: fn () => $driver->checkSslCertificate($domain, $port), + message: (string) __('messages.spinners.network_ssl', ['domain' => $domain]), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Network/WifiCommand.php b/app/Commands/Network/WifiCommand.php new file mode 100644 index 0000000..45d29e7 --- /dev/null +++ b/app/Commands/Network/WifiCommand.php @@ -0,0 +1,55 @@ +resolveLocale(); + + info((string) __('messages.network.wifi_section')); + + $result = spin( + callback: fn () => $driver->getWifiInfo(), + message: (string) __('messages.spinners.network_wifi'), + ); + + if (! $result->success) { + warning((string) __($result->message)); + + return self::SUCCESS; + } + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 912bc32..078bd04 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -169,6 +169,12 @@ protected function handleCategorySubmenu(string $category, string $locale): void '1' => ['label' => (string) __('messages.menu.actions.network_check'), 'command' => 'network:check'], '2' => ['label' => (string) __('messages.menu.actions.network_flush'), 'command' => 'network:flush'], '3' => ['label' => (string) __('messages.menu.actions.network_ports'), 'command' => 'network:ports'], + '4' => ['label' => (string) __('messages.menu.actions.network_probe'), 'command' => 'network:probe'], + '5' => ['label' => (string) __('messages.menu.actions.network_wifi'), 'command' => 'network:wifi'], + '6' => ['label' => (string) __('messages.menu.actions.network_reset'), 'command' => 'network:reset'], + '7' => ['label' => (string) __('messages.menu.actions.network_ssl'), 'command' => 'network:ssl'], + '8' => ['label' => (string) __('messages.menu.actions.network_scan'), 'command' => 'network:scan'], + '9' => ['label' => (string) __('messages.menu.actions.network_public'), 'command' => 'network:public'], ], 'maintenance' => [ '1' => ['label' => (string) __('messages.menu.actions.clean_temp'), 'command' => 'clean:temp'], diff --git a/app/Contracts/SystemDriverInterface.php b/app/Contracts/SystemDriverInterface.php index d74c41a..c16e1d7 100644 --- a/app/Contracts/SystemDriverInterface.php +++ b/app/Contracts/SystemDriverInterface.php @@ -95,6 +95,54 @@ public function flushDnsAndRenew(): ActionResult; */ public function getListeningPorts(): array; + /** + * Probe a remote TCP host and port and measure connection latency in milliseconds. + * + * @param string $host + * @param int $port + * @param int $timeout + * @return array{host: string, port: int, status: string, latency: string, error: string} + */ + public function probePort(string $host, int $port, int $timeout = 3): array; + + /** + * Retrieve wireless (Wi-Fi) adapter connection metrics (SSID, BSSID, Signal, Channel, Band, Rates). + * + * @return ActionResult + */ + public function getWifiInfo(): ActionResult; + + /** + * Perform a complete network stack reset (Winsock/IP reset on Windows; NetworkManager/DHCP on Linux). + * + * @return ActionResult + */ + public function resetNetworkStack(): ActionResult; + + /** + * Inspect an HTTPS domain's SSL/TLS certificate (CN, Issuer, Validity dates, Days remaining, SANs). + * + * @param string $domain + * @param int $port + * @param int $timeout + * @return ActionResult + */ + public function checkSslCertificate(string $domain, int $port = 443, int $timeout = 5): ActionResult; + + /** + * Discover active devices on the local area network (ARP cache + local subnet discovery). + * + * @return array + */ + public function scanLanDevices(): array; + + /** + * Retrieve external public IP address, geolocation, ISP/ASN, and reverse hostname. + * + * @return ActionResult + */ + public function getPublicIpInfo(): ActionResult; + /** * Clean system and user temporary directories safely. * diff --git a/app/Drivers/Concerns/InteractsWithNetworkSockets.php b/app/Drivers/Concerns/InteractsWithNetworkSockets.php new file mode 100644 index 0000000..413dd39 --- /dev/null +++ b/app/Drivers/Concerns/InteractsWithNetworkSockets.php @@ -0,0 +1,326 @@ +sanitizeHost($host); + $safePort = max(1, min(65535, $port)); + $safeTimeout = max(1, $timeout); + + $errno = 0; + $errstr = ''; + $startNs = hrtime(true); + + $socket = @stream_socket_client( + sprintf('tcp://%s:%d', $cleanHost, $safePort), + $errno, + $errstr, + $safeTimeout, + STREAM_CLIENT_CONNECT + ); + + $elapsedMs = round((hrtime(true) - $startNs) / 1_000_000, 2); + + if (is_resource($socket)) { + @fclose($socket); + + return [ + 'host' => $cleanHost, + 'port' => $safePort, + 'status' => 'OPEN', + 'latency' => sprintf('%.2f ms', $elapsedMs), + 'error' => '-', + ]; + } + + $lowerErr = strtolower($errstr); + $isTimeout = $errno === 110 + || $errno === 10060 + || str_contains($lowerErr, 'timed out') + || str_contains($lowerErr, 'timeout'); + + return [ + 'host' => $cleanHost, + 'port' => $safePort, + 'status' => $isTimeout ? 'TIMEOUT' : 'CLOSED', + 'latency' => '-', + 'error' => $errstr !== '' ? trim($errstr) : ($isTimeout ? 'Connection timed out' : 'Connection refused'), + ]; + } + + /** + * Inspect an HTTPS domain's SSL/TLS certificate (CN, Issuer, Validity dates, Days remaining, SANs). + */ + public function checkSslCertificate(string $domain, int $port = 443, int $timeout = 5): ActionResult + { + $cleanDomain = $this->sanitizeHost($domain); + $safePort = max(1, min(65535, $port)); + $safeTimeout = max(1, $timeout); + + $context = stream_context_create([ + 'ssl' => [ + 'capture_peer_cert' => true, + 'verify_peer' => false, + 'verify_peer_name' => false, + 'SNI_enabled' => true, + 'peer_name' => $cleanDomain, + ], + ]); + + $errno = 0; + $errstr = ''; + $client = @stream_socket_client( + sprintf('ssl://%s:%d', $cleanDomain, $safePort), + $errno, + $errstr, + $safeTimeout, + STREAM_CLIENT_CONNECT, + $context + ); + + if (! is_resource($client)) { + return new ActionResult( + success: false, + message: 'messages.network.ssl_connect_failed', + details: [ + 'domain' => $cleanDomain, + 'port' => $safePort, + 'error' => $errstr !== '' ? trim($errstr) : 'TLS handshake failed', + ], + ); + } + + $params = stream_context_get_params($client); + @fclose($client); + + $certResource = $params['options']['ssl']['peer_certificate'] ?? null; + if ($certResource === null) { + return new ActionResult( + success: false, + message: 'messages.network.ssl_connect_failed', + details: [ + 'domain' => $cleanDomain, + 'port' => $safePort, + 'error' => 'No peer certificate returned by server.', + ], + ); + } + + $parsed = @openssl_x509_parse($certResource); + if (! is_array($parsed)) { + return new ActionResult( + success: false, + message: 'messages.network.ssl_connect_failed', + details: [ + 'domain' => $cleanDomain, + 'port' => $safePort, + 'error' => 'Failed to parse X.509 certificate structure.', + ], + ); + } + + return $this->formatParsedSslCertificate($cleanDomain, $safePort, $parsed); + } + + /** + * Format a parsed openssl_x509_parse() array into a standardized ActionResult. + * + * @param array $parsed + */ + protected function formatParsedSslCertificate(string $domain, int $port, array $parsed): ActionResult + { + $subjectCn = (string) ($parsed['subject']['CN'] ?? $domain); + $issuerOrg = (string) ($parsed['issuer']['O'] ?? $parsed['issuer']['CN'] ?? 'Unknown Issuer'); + $issuerCn = (string) ($parsed['issuer']['CN'] ?? ''); + $issuer = ($issuerCn !== '' && $issuerCn !== $issuerOrg) + ? sprintf('%s (%s)', $issuerOrg, $issuerCn) + : $issuerOrg; + + $validFromTs = (int) ($parsed['validFrom_time_t'] ?? 0); + $validToTs = (int) ($parsed['validTo_time_t'] ?? 0); + + $validFrom = $validFromTs > 0 ? gmdate('Y-m-d H:i:s \U\T\C', $validFromTs) : 'N/A'; + $validTo = $validToTs > 0 ? gmdate('Y-m-d H:i:s \U\T\C', $validToTs) : 'N/A'; + + $daysRemaining = (int) floor(($validToTs - time()) / 86400); + if ($daysRemaining < 0) { + $daysLabel = sprintf('❌ %d (%s)', $daysRemaining, (string) __('messages.network.ssl_expired')); + } elseif ($daysRemaining < 30) { + $daysLabel = sprintf('⚠️ %d (%s)', $daysRemaining, (string) __('messages.network.ssl_expiring_soon')); + } else { + $daysLabel = sprintf('✅ %d', $daysRemaining); + } + + $rawSans = (string) ($parsed['extensions']['subjectAltName'] ?? ''); + $sansList = []; + foreach (explode(',', $rawSans) as $part) { + $part = trim($part); + if (str_starts_with($part, 'DNS:')) { + $sansList[] = substr($part, 4); + } + } + $sansFormatted = $sansList !== [] ? implode(', ', array_slice($sansList, 0, 8)) : $subjectCn; + + return new ActionResult( + success: true, + message: 'messages.network.ssl_valid_success', + details: [ + 'domain' => sprintf('%s:%d', $domain, $port), + 'subject_cn' => $subjectCn, + 'issuer' => $issuer, + 'valid_from' => $validFrom, + 'valid_to' => $validTo, + 'days_remaining' => $daysLabel, + 'sans' => $sansFormatted, + ], + ); + } + + /** + * Retrieve external public IP address, geolocation, ISP/ASN, and reverse hostname. + */ + public function getPublicIpInfo(): ActionResult + { + $endpoints = [ + 'https://ipinfo.io/json', + 'https://api.ipify.org?format=json', + ]; + + foreach ($endpoints as $url) { + $raw = $this->fetchPublicEndpoint($url, 4); + if ($raw === null || $raw === '') { + continue; + } + + $decoded = json_decode($raw, true); + if (! is_array($decoded) || empty($decoded['ip'])) { + continue; + } + + return $this->formatPublicIpPayload($decoded); + } + + return new ActionResult( + success: false, + message: 'messages.network.public_ip_failed', + details: [], + ); + } + + /** + * Format decoded JSON from ipinfo.io or ipify into a standardized ActionResult. + * + * @param array $decoded + */ + protected function formatPublicIpPayload(array $decoded): ActionResult + { + $ip = trim((string) ($decoded['ip'] ?? '-')); + $locationParts = array_filter([ + trim((string) ($decoded['city'] ?? '')), + trim((string) ($decoded['region'] ?? '')), + trim((string) ($decoded['country'] ?? '')), + ], fn (string $val): bool => $val !== ''); + + $location = $locationParts !== [] ? implode(', ', $locationParts) : 'N/A'; + $isp = trim((string) ($decoded['org'] ?? '')) ?: 'N/A'; + $hostname = trim((string) ($decoded['hostname'] ?? '')); + + if ($hostname === '' && filter_var($ip, FILTER_VALIDATE_IP) !== false) { + $resolved = @gethostbyaddr($ip); + $hostname = ($resolved !== false && $resolved !== $ip) ? $resolved : 'N/A'; + } + + return new ActionResult( + success: true, + message: 'messages.network.public_ip_success', + details: [ + 'public_ip' => $ip, + 'location' => $location, + 'isp' => $isp, + 'reverse_hostname' => $hostname !== '' ? $hostname : 'N/A', + ], + ); + } + + /** + * Perform a fast HTTPS GET request with a 4-second timeout. + */ + protected function fetchPublicEndpoint(string $url, int $timeout = 4): ?string + { + $context = stream_context_create([ + 'http' => [ + 'method' => 'GET', + 'header' => "User-Agent: it-toolbox-cli\r\nAccept: application/json\r\n", + 'timeout' => $timeout, + 'follow_location' => 1, + ], + 'ssl' => [ + 'verify_peer' => true, + 'verify_peer_name' => true, + ], + ]); + + try { + $result = @file_get_contents($url, false, $context); + + return $result === false ? null : $result; + } catch (Throwable) { + return null; + } + } + + /** + * Strip scheme, path, and port suffixes from a hostname or IP string. + */ + protected function sanitizeHost(string $host): string + { + $clean = trim($host); + $clean = (string) preg_replace('#^https?://#i', '', $clean); + $clean = explode('/', $clean)[0]; + + if (substr_count($clean, ':') === 1 && ! str_starts_with($clean, '[')) { + $clean = explode(':', $clean)[0]; + } + + return trim($clean, " \t\n\r\0\x0B[]"); + } + + /** + * Determine whether an IPv4 and MAC pair represents a real unicast LAN neighbor (excluding multicast/broadcast). + */ + protected function isUnicastLanNeighbor(string $ip, string $mac): bool + { + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { + return false; + } + + if (str_starts_with($ip, '127.') || str_ends_with($ip, '.255') || $ip === '255.255.255.255') { + return false; + } + + $firstOctet = (int) explode('.', $ip)[0]; + if ($firstOctet >= 224 && $firstOctet <= 239) { + return false; + } + + $normalizedMac = strtolower(str_replace('-', ':', trim($mac))); + if ($normalizedMac === '' || $normalizedMac === 'ff:ff:ff:ff:ff:ff' || $normalizedMac === '00:00:00:00:00:00' || str_starts_with($normalizedMac, '01:00:5e')) { + return false; + } + + return true; + } +} diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index 88ae3ec..5cc2d4f 100644 --- a/app/Drivers/LinuxDriver.php +++ b/app/Drivers/LinuxDriver.php @@ -6,6 +6,7 @@ use App\Contracts\ProcessExecutorInterface; use App\Contracts\SystemDriverInterface; +use App\Drivers\Concerns\InteractsWithNetworkSockets; use App\DTOs\ActionResult; use App\Services\SymfonyProcessExecutor; use Closure; @@ -15,6 +16,7 @@ class LinuxDriver implements SystemDriverInterface { + use InteractsWithNetworkSockets; /** * Real block/disk filesystem types to include in storage health checks. * @@ -677,6 +679,213 @@ public function getListeningPorts(): array return []; } + /** + * {@inheritDoc} + */ + public function getWifiInfo(): ActionResult + { + $nmcliResult = $this->processRunner->run([ + 'nmcli', + '-t', + '-f', + 'ACTIVE,SSID,BSSID,CHAN,FREQ,RATE,SIGNAL', + 'dev', + 'wifi', + ]); + + if ($nmcliResult->successful && $nmcliResult->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($nmcliResult->output)) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '') { + continue; + } + + // Split on unescaped colons (nmcli escapes colons inside BSSID as \:) + $parts = preg_split('/(? 'wlan0 (nmcli)', + 'state' => 'Connected', + 'ssid' => $ssid !== '' ? $ssid : '-', + 'bssid' => $bssid !== '' ? $bssid : '-', + 'signal' => $signal !== '' && ! str_ends_with($signal, '%') ? $signal . '%' : ($signal ?: '-'), + 'channel' => $chan !== '' ? $chan : '-', + 'band' => $freq !== '' ? $freq : '-', + 'rx_rate' => $rate !== '' ? $rate : '-', + 'tx_rate' => $rate !== '' ? $rate : '-', + 'driver' => 'Linux', + ], + ); + } + } + + // Fallback to `iw dev` + $iwResult = $this->processRunner->run(['iw', 'dev']); + if ($iwResult->successful && $iwResult->output !== '') { + if (preg_match('/Interface\s+(\S+)/', $iwResult->output, $ifaceMatch) === 1) { + $iface = $ifaceMatch[1]; + $ssid = preg_match('/ssid\s+(.+)$/m', $iwResult->output, $ssidMatch) === 1 ? trim($ssidMatch[1]) : '-'; + $chan = preg_match('/channel\s+(\d+)\s+\(([^)]+)\)/', $iwResult->output, $chanMatch) === 1 + ? $chanMatch[1] + : '-'; + $freq = isset($chanMatch[2]) ? trim($chanMatch[2]) : '-'; + + return new ActionResult( + success: true, + message: 'messages.network.wifi_fetched_success', + details: [ + 'interface' => $iface, + 'state' => $ssid !== '-' ? 'Connected' : 'Disconnected', + 'ssid' => $ssid, + 'bssid' => '-', + 'signal' => '-', + 'channel' => $chan, + 'band' => $freq, + 'rx_rate' => '-', + 'tx_rate' => '-', + 'driver' => 'Linux', + ], + ); + } + } + + return new ActionResult( + success: false, + message: 'messages.network.no_wifi', + details: ['driver' => 'Linux'], + ); + } + + /** + * {@inheritDoc} + */ + public function resetNetworkStack(): ActionResult + { + if (! $this->isRoot()) { + return new ActionResult( + success: false, + message: 'messages.common.permission_denied', + details: ['driver' => 'Linux'], + ); + } + + $executed = []; + + $nmRestart = $this->processRunner->run(['systemctl', 'restart', 'NetworkManager']); + if ($nmRestart->successful) { + $executed[] = 'systemctl restart NetworkManager'; + } else { + $networkdRestart = $this->processRunner->run(['systemctl', 'restart', 'systemd-networkd']); + if ($networkdRestart->successful) { + $executed[] = 'systemctl restart systemd-networkd'; + } + } + + if ($this->commandExists('dhclient')) { + $this->processRunner->run(['dhclient', '-r']); + $this->processRunner->run(['dhclient']); + $executed[] = 'dhclient -r && dhclient'; + } + + if ($executed === []) { + return new ActionResult( + success: false, + message: 'messages.network.reset_failed', + details: ['driver' => 'Linux'], + ); + } + + return new ActionResult( + success: true, + message: 'messages.network.reset_success', + details: [ + 'commands_executed' => $executed, + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function scanLanDevices(): array + { + $neighResult = $this->processRunner->run(['ip', 'neigh', 'show']); + if ($neighResult->successful && $neighResult->output !== '') { + $devices = []; + $lines = preg_split('/\r\n|\r|\n/', trim($neighResult->output)) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if (preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\s+dev\s+(\S+)\s+lladdr\s+([0-9a-fA-F:]{17})\s+(\S+)/', $line, $m) === 1) { + $ip = $m[1]; + $iface = $m[2]; + $mac = strtoupper($m[3]); + $state = strtoupper($m[4]); + + if (! $this->isUnicastLanNeighbor($ip, $mac)) { + continue; + } + + $devices[] = [ + 'ip' => $ip, + 'mac' => $mac, + 'status' => $state, + 'interface' => $iface, + ]; + } + } + + return $devices; + } + + $arpResult = $this->processRunner->run(['arp', '-n']); + if ($arpResult->successful && $arpResult->output !== '') { + $devices = []; + $lines = preg_split('/\r\n|\r|\n/', trim($arpResult->output)) ?: []; + foreach ($lines as $line) { + if (preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\s+\S+\s+([0-9a-fA-F:]{17})\s+\S+\s+(\S+)/', trim($line), $m) === 1) { + $ip = $m[1]; + $mac = strtoupper($m[2]); + $iface = $m[3]; + + if (! $this->isUnicastLanNeighbor($ip, $mac)) { + continue; + } + + $devices[] = [ + 'ip' => $ip, + 'mac' => $mac, + 'status' => 'REACHABLE', + 'interface' => $iface, + ]; + } + } + + return $devices; + } + + return []; + } + /** * {@inheritDoc} */ diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index 96eb920..f6a6a0d 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -6,12 +6,15 @@ use App\Contracts\ProcessExecutorInterface; use App\Contracts\SystemDriverInterface; +use App\Drivers\Concerns\InteractsWithNetworkSockets; use App\DTOs\ActionResult; use App\DTOs\ProcessResult; use App\Services\SymfonyProcessExecutor; class WindowsDriver implements SystemDriverInterface { + use InteractsWithNetworkSockets; + private const UTF8_PREAMBLE = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $OutputEncoding = [System.Text.Encoding]::UTF8; '; public function __construct( @@ -683,6 +686,162 @@ public function getListeningPorts(): array return $ports; } + /** + * {@inheritDoc} + */ + public function getWifiInfo(): ActionResult + { + $result = $this->runPowerShell('netsh wlan show interfaces'); + $output = trim($result->output); + + if (! $result->successful || $output === '') { + return new ActionResult( + success: false, + message: 'messages.network.no_wifi', + details: ['driver' => 'Windows'], + ); + } + + $lower = strtolower($output); + if (str_contains($lower, 'no wireless interface') + || str_contains($lower, 'não há interface sem fio') + || str_contains($lower, 'is not running') + || str_contains($lower, 'não está em execução')) { + return new ActionResult( + success: false, + message: 'messages.network.no_wifi', + details: ['driver' => 'Windows'], + ); + } + + $fields = []; + $lines = preg_split('/\r\n|\r|\n/', $output) ?: []; + foreach ($lines as $line) { + if (preg_match('/^\s*([^:]+?)\s*:\s*(.+)$/', $line, $matches) === 1) { + $key = strtolower(trim($matches[1])); + $val = trim($matches[2]); + $fields[$key] = $val; + } + } + + $ssid = $fields['ssid'] ?? ''; + $interface = $fields['name'] ?? $fields['nome'] ?? 'Wi-Fi'; + $state = $fields['state'] ?? $fields['estado'] ?? 'disconnected'; + + if ($ssid === '' && ! isset($fields['name']) && ! isset($fields['nome'])) { + return new ActionResult( + success: false, + message: 'messages.network.no_wifi', + details: ['driver' => 'Windows'], + ); + } + + $rxRate = $fields['receive rate (mbps)'] ?? $fields['taxa de recepção (mbps)'] ?? '-'; + $txRate = $fields['transmit rate (mbps)'] ?? $fields['taxa de transmissão (mbps)'] ?? '-'; + + return new ActionResult( + success: true, + message: 'messages.network.wifi_fetched_success', + details: [ + 'interface' => $interface, + 'state' => $state, + 'ssid' => $ssid !== '' ? $ssid : '-', + 'bssid' => $fields['bssid'] ?? '-', + 'signal' => $fields['signal'] ?? $fields['sinal'] ?? '-', + 'channel' => $fields['channel'] ?? $fields['canal'] ?? '-', + 'band' => $fields['band'] ?? $fields['banda'] ?? $fields['radio type'] ?? $fields['tipo de rádio'] ?? '-', + 'rx_rate' => $rxRate !== '-' && ! str_contains(strtolower($rxRate), 'mbps') ? $rxRate . ' Mbps' : $rxRate, + 'tx_rate' => $txRate !== '-' && ! str_contains(strtolower($txRate), 'mbps') ? $txRate . ' Mbps' : $txRate, + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function resetNetworkStack(): ActionResult + { + $adminCheck = $this->processRunner->run(['net', 'session'], 5); + if (! $adminCheck->successful) { + return new ActionResult( + success: false, + message: 'messages.common.permission_denied', + details: ['driver' => 'Windows'], + ); + } + + $steps = [ + ['cmd' => ['ipconfig', '/release'], 'label' => 'ipconfig /release'], + ['cmd' => ['ipconfig', '/flushdns'], 'label' => 'ipconfig /flushdns'], + ['cmd' => ['netsh', 'winsock', 'reset'], 'label' => 'netsh winsock reset'], + ['cmd' => ['netsh', 'int', 'ip', 'reset'], 'label' => 'netsh int ip reset'], + ['cmd' => ['ipconfig', '/renew'], 'label' => 'ipconfig /renew'], + ]; + + $executed = []; + foreach ($steps as $step) { + $this->processRunner->run($step['cmd'], 30); + $executed[] = $step['label']; + } + + return new ActionResult( + success: true, + message: 'messages.network.reset_success', + details: [ + 'commands_executed' => $executed, + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function scanLanDevices(): array + { + $arpResult = $this->processRunner->run(['arp', '-a']); + if (! $arpResult->successful || $arpResult->output === '') { + return []; + } + + $devices = []; + $currentInterface = 'LAN'; + $lines = preg_split('/\r\n|\r|\n/', $arpResult->output) ?: []; + + foreach ($lines as $line) { + $line = trim($line); + if ($line === '') { + continue; + } + + if (preg_match('/^Interface:\s+([0-9.]+)/i', $line, $ifaceMatch) === 1) { + $currentInterface = $ifaceMatch[1]; + + continue; + } + + if (preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\s+([0-9a-fA-F:-]{17})\s+(\S+)/', $line, $entryMatch) === 1) { + $ip = $entryMatch[1]; + $mac = strtoupper(str_replace('-', ':', $entryMatch[2])); + $type = ucfirst(strtolower($entryMatch[3])); + + if (! $this->isUnicastLanNeighbor($ip, $mac)) { + continue; + } + + $devices[] = [ + 'ip' => $ip, + 'mac' => $mac, + 'status' => $type, + 'interface' => $currentInterface, + ]; + } + } + + return $devices; + } + /** * {@inheritDoc} */ diff --git a/lang/en/messages.php b/lang/en/messages.php index c4377d3..7d62332 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -48,6 +48,12 @@ 'network_check' => 'Interfaces & Connectivity Health Check (network:check)', 'network_flush' => 'Flush DNS Cache & Renew IP Lease (network:flush)', 'network_ports' => 'Inspect Open Listening Ports (network:ports)', + 'network_probe' => 'Test Remote TCP Port & Measure Latency (network:probe)', + 'network_wifi' => 'Inspect Wi-Fi Signal, SSID, Channel & Speed (network:wifi)', + 'network_reset' => 'Full Network Stack Reset — Winsock/IP/DHCP (network:reset)', + 'network_ssl' => 'Inspect HTTPS SSL/TLS Certificate & Expiration (network:ssl)', + 'network_scan' => 'Discover Active Devices on Local Network (network:scan)', + 'network_public' => 'View External Public IP, Geolocation & ISP (network:public)', 'clean_temp' => 'Clean System & User Temporary Files (clean:temp)', 'report_export' => 'Export Full System Diagnostic Report (report:export)', ], @@ -76,6 +82,12 @@ 'network_check' => 'Inspecting network interfaces and testing connectivity...', 'network_flush' => 'Flushing DNS resolver cache and renewing network lease...', 'network_ports' => 'Scanning active listening TCP/UDP ports...', + 'network_probe' => 'Probing TCP connection to :host::port...', + 'network_wifi' => 'Querying wireless adapter signal and radio metrics...', + 'network_reset' => 'Resetting network stack, Winsock/IP configuration, and renewing DHCP lease...', + 'network_ssl' => 'Inspecting SSL/TLS certificate for :domain...', + 'network_scan' => 'Scanning local network ARP cache and active neighbors...', + 'network_public' => 'Querying external public IP address and ISP geolocation...', 'clean_temp' => 'Scanning and removing temporary files safely...', 'report_export' => 'Generating full diagnostic report...', 'self_update_check' => 'Checking GitHub Releases for newer versions...', @@ -230,6 +242,43 @@ 'confirm_flush' => 'This will flush the DNS cache and renew network configuration (may briefly interrupt active connections). Proceed?', 'flush_success' => 'DNS cache flushed and network configuration renewed successfully.', 'flush_failed' => 'Failed to flush DNS or renew network configuration.', + 'probe_section' => 'Remote TCP Port Probe & Latency Test', + 'probe_host_prompt' => 'Enter target hostname or IP address:', + 'probe_port_prompt' => 'Enter target TCP port (1-65535):', + 'probe_invalid_port' => 'Please enter a valid TCP port number between 1 and 65535.', + 'probe_headers' => [ + 'host' => 'Target Host', + 'port' => 'TCP Port', + 'status' => 'State', + 'latency' => 'Response Time', + 'details' => 'Details', + ], + 'probe_open_success' => 'TCP port :port on :host is OPEN (Latency: :latency).', + 'probe_failed' => 'TCP port :port on :host is :status.', + 'wifi_section' => 'Wireless (Wi-Fi) Adapter Diagnostics', + 'wifi_fetched_success' => 'Wireless adapter metrics retrieved successfully.', + 'no_wifi' => 'No active wireless (Wi-Fi) interface detected on this machine.', + 'reset_section' => 'Full Network Stack Reset', + 'confirm_reset' => 'WARNING: This will reset Winsock/IP stack and renew DHCP leases, temporarily disconnecting active network sessions. Proceed?', + 'reset_success' => 'Network stack reset and IP configuration renewed successfully. A system reboot is recommended on Windows.', + 'reset_failed' => 'Failed to reset the network stack. Verify administrator/sudo privileges.', + 'ssl_section' => 'HTTPS SSL/TLS Certificate Inspector', + 'ssl_domain_prompt' => 'Enter target HTTPS domain (e.g. google.com):', + 'ssl_valid_success' => 'SSL/TLS certificate retrieved and parsed successfully.', + 'ssl_connect_failed' => 'Failed to establish TLS connection or retrieve SSL certificate.', + 'ssl_expiring_soon' => 'EXPIRING SOON (< 30 days)', + 'ssl_expired' => 'EXPIRED', + 'scan_section' => 'Local Network (LAN) Active Devices Discovery', + 'no_lan_devices' => 'No active LAN neighbor devices found in the ARP table.', + 'scan_headers' => [ + 'ip' => 'IPv4 Address', + 'mac' => 'MAC Address', + 'status' => 'State / Type', + 'interface' => 'Interface', + ], + 'public_section' => 'External Public IP & ISP Geolocation', + 'public_ip_success' => 'External public IP information retrieved successfully.', + 'public_ip_failed' => 'Unable to query external public IP address. Check internet connectivity.', ], 'maintenance' => [ @@ -255,6 +304,27 @@ 'asset_name' => 'Release Artifact', 'download_url' => 'Download URL', 'count' => 'Event Count', + 'interface' => 'Interface', + 'state' => 'Connection State', + 'ssid' => 'Network SSID', + 'bssid' => 'Access Point BSSID', + 'signal' => 'Signal Quality', + 'channel' => 'Radio Channel', + 'band' => 'Frequency / Radio Band', + 'rx_rate' => 'Receive Rate (RX)', + 'tx_rate' => 'Transmit Rate (TX)', + 'domain' => 'Target Domain', + 'port' => 'Port', + 'subject_cn' => 'Subject (Common Name)', + 'issuer' => 'Certificate Issuer', + 'valid_from' => 'Issued On', + 'valid_to' => 'Expires On', + 'days_remaining' => 'Days Remaining', + 'sans' => 'Subject Alt Names (SANs)', + 'public_ip' => 'Public IP Address', + 'location' => 'City / Region / Country', + 'isp' => 'ISP / Organization (ASN)', + 'reverse_hostname' => 'Reverse Hostname', ], ], diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index 648a732..bc557b4 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -48,6 +48,12 @@ 'network_check' => 'Interfaces e Teste de Saúde de Conectividade (network:check)', 'network_flush' => 'Limpar Cache DNS e Renovar Concessão de IP (network:flush)', 'network_ports' => 'Inspecionar Portas Abertas em Escuta (network:ports)', + 'network_probe' => 'Testar Porta TCP Remota e Medir Latência (network:probe)', + 'network_wifi' => 'Diagnóstico de Wi-Fi — Sinal, SSID, Canal e Velocidade (network:wifi)', + 'network_reset' => 'Reset Completo da Pilha de Rede — Winsock/IP/DHCP (network:reset)', + 'network_ssl' => 'Inspecionar Certificado SSL/TLS HTTPS e Validade (network:ssl)', + 'network_scan' => 'Descobrir Dispositivos Ativos na Rede Local (network:scan)', + 'network_public' => 'Consultar IP Público Externo, Geolocalização e Provedor (network:public)', 'clean_temp' => 'Limpar Arquivos Temporários do Sistema e Usuário (clean:temp)', 'report_export' => 'Exportar Relatório Completo de Diagnóstico (report:export)', ], @@ -76,6 +82,12 @@ 'network_check' => 'Inspecionando interfaces de rede e testando conectividade...', 'network_flush' => 'Limpando cache de resolução DNS e renovando IP...', 'network_ports' => 'Escaneando portas TCP/UDP ativas em escuta...', + 'network_probe' => 'Testando conexão TCP em :host::port...', + 'network_wifi' => 'Consultando métricas do adaptador Wi-Fi e qualidade de sinal...', + 'network_reset' => 'Resetando pilha de rede, Winsock/IP e renovando concessão DHCP...', + 'network_ssl' => 'Inspecionando certificado SSL/TLS de :domain...', + 'network_scan' => 'Escaneando tabela ARP e dispositivos ativos na rede local...', + 'network_public' => 'Consultando endereço IP público externo e provedor (ISP)...', 'clean_temp' => 'Analisando e removendo arquivos temporários com segurança...', 'report_export' => 'Gerando relatório completo de diagnóstico...', 'self_update_check' => 'Consultando GitHub Releases por novas versões...', @@ -230,6 +242,43 @@ 'confirm_flush' => 'Isto limpará o cache DNS e renovará a configuração de rede (pode interromper conexões brevemente). Prosseguir?', 'flush_success' => 'Cache DNS limpo e configuração de rede renovada com sucesso.', 'flush_failed' => 'Falha ao limpar o DNS ou renovar a configuração de rede.', + 'probe_section' => 'Teste de Porta TCP Remota & Latência', + 'probe_host_prompt' => 'Informe o host ou endereço IP alvo:', + 'probe_port_prompt' => 'Informe a porta TCP alvo (1-65535):', + 'probe_invalid_port' => 'Informe um número de porta TCP válido entre 1 e 65535.', + 'probe_headers' => [ + 'host' => 'Host Alvo', + 'port' => 'Porta TCP', + 'status' => 'Estado', + 'latency' => 'Tempo de Resposta', + 'details' => 'Detalhes', + ], + 'probe_open_success' => 'A porta TCP :port em :host está ABERTA (Latência: :latency).', + 'probe_failed' => 'A porta TCP :port em :host retornou status :status.', + 'wifi_section' => 'Diagnóstico de Adaptador Sem Fio (Wi-Fi)', + 'wifi_fetched_success' => 'Métricas do adaptador Wi-Fi coletadas com sucesso.', + 'no_wifi' => 'Nenhuma interface sem fio (Wi-Fi) ativa detectada nesta máquina.', + 'reset_section' => 'Reset Completo da Pilha de Rede', + 'confirm_reset' => 'ATENÇÃO: Isto redefinirá a pilha Winsock/IP e renovará o DHCP, desconectando temporariamente as sessões de rede. Deseja prosseguir?', + 'reset_success' => 'Pilha de rede redefinida e configuração de IP renovada com sucesso. Recomenda-se reiniciar o sistema no Windows.', + 'reset_failed' => 'Falha ao redefinir a pilha de rede. Verifique privilégios de Administrador/sudo.', + 'ssl_section' => 'Inspetor de Certificado SSL/TLS HTTPS', + 'ssl_domain_prompt' => 'Informe o domínio HTTPS alvo (ex: google.com):', + 'ssl_valid_success' => 'Certificado SSL/TLS coletado e analisado com sucesso.', + 'ssl_connect_failed' => 'Falha ao estabelecer conexão TLS ou obter o certificado SSL.', + 'ssl_expiring_soon' => 'EXPIRA EM BREVE (< 30 dias)', + 'ssl_expired' => 'EXPIRADO', + 'scan_section' => 'Descoberta de Dispositivos Ativos na Rede Local (LAN)', + 'no_lan_devices' => 'Nenhum dispositivo vizinho ativo encontrado na tabela ARP.', + 'scan_headers' => [ + 'ip' => 'Endereço IPv4', + 'mac' => 'Endereço MAC', + 'status' => 'Estado / Tipo', + 'interface' => 'Interface', + ], + 'public_section' => 'IP Público Externo & Geolocalização do Provedor (ISP)', + 'public_ip_success' => 'Informações de IP público externo obtidas com sucesso.', + 'public_ip_failed' => 'Não foi possível consultar o IP público externo. Verifique a conexão com a internet.', ], 'maintenance' => [ @@ -255,6 +304,27 @@ 'asset_name' => 'Artefato da Release', 'download_url' => 'URL de Download', 'count' => 'Total de Eventos', + 'interface' => 'Interface', + 'state' => 'Estado da Conexão', + 'ssid' => 'SSID da Rede', + 'bssid' => 'BSSID do Ponto de Acesso', + 'signal' => 'Qualidade do Sinal', + 'channel' => 'Canal de Rádio', + 'band' => 'Frequência / Banda', + 'rx_rate' => 'Taxa de Recepção (RX)', + 'tx_rate' => 'Taxa de Transmissão (TX)', + 'domain' => 'Domínio Alvo', + 'port' => 'Porta', + 'subject_cn' => 'Sujeito (Common Name)', + 'issuer' => 'Emissor do Certificado', + 'valid_from' => 'Data de Emissão', + 'valid_to' => 'Data de Expiração', + 'days_remaining' => 'Dias Restantes', + 'sans' => 'Nomes Alternativos (SANs)', + 'public_ip' => 'Endereço IP Público', + 'location' => 'Cidade / Região / País', + 'isp' => 'Provedor / Organização (ASN)', + 'reverse_hostname' => 'Hostname Reverso', ], ], diff --git a/tests/Feature/ReportExporterTest.php b/tests/Feature/ReportExporterTest.php index f716249..cdc7ebc 100644 --- a/tests/Feature/ReportExporterTest.php +++ b/tests/Feature/ReportExporterTest.php @@ -117,6 +117,36 @@ public function getListeningPorts(): array return []; } + public function probePort(string $host, int $port, int $timeout = 3): array + { + return ['host' => $host, 'port' => $port, 'status' => 'OPEN', 'latency' => '1.00 ms', 'error' => '-']; + } + + public function getWifiInfo(): ActionResult + { + return new ActionResult(false, 'messages.network.no_wifi'); + } + + public function resetNetworkStack(): ActionResult + { + return new ActionResult(true, 'messages.network.reset_success'); + } + + public function checkSslCertificate(string $domain, int $port = 443, int $timeout = 5): ActionResult + { + return new ActionResult(true, 'messages.network.ssl_valid_success'); + } + + public function scanLanDevices(): array + { + return []; + } + + public function getPublicIpInfo(): ActionResult + { + return new ActionResult(true, 'messages.network.public_ip_success'); + } + public function cleanTempFiles(): ActionResult { return new ActionResult(true, 'messages.maintenance.clean_success'); diff --git a/tests/Unit/HealthCheckServiceTest.php b/tests/Unit/HealthCheckServiceTest.php index 67e2c25..fdc2676 100644 --- a/tests/Unit/HealthCheckServiceTest.php +++ b/tests/Unit/HealthCheckServiceTest.php @@ -109,6 +109,36 @@ public function getListeningPorts(): array return []; } + public function probePort(string $host, int $port, int $timeout = 3): array + { + return ['host' => $host, 'port' => $port, 'status' => 'OPEN', 'latency' => '1.00 ms', 'error' => '-']; + } + + public function getWifiInfo(): ActionResult + { + return new ActionResult(false, 'messages.network.no_wifi'); + } + + public function resetNetworkStack(): ActionResult + { + return new ActionResult(true, 'messages.network.reset_success'); + } + + public function checkSslCertificate(string $domain, int $port = 443, int $timeout = 5): ActionResult + { + return new ActionResult(true, 'messages.network.ssl_valid_success'); + } + + public function scanLanDevices(): array + { + return []; + } + + public function getPublicIpInfo(): ActionResult + { + return new ActionResult(true, 'messages.network.public_ip_success'); + } + public function cleanTempFiles(): ActionResult { return new ActionResult(true, 'ok'); diff --git a/tests/Unit/LinuxDriverTest.php b/tests/Unit/LinuxDriverTest.php index 3ab8db8..7732dc7 100644 --- a/tests/Unit/LinuxDriverTest.php +++ b/tests/Unit/LinuxDriverTest.php @@ -144,3 +144,65 @@ public function getEffectiveUid(): int ->and($emptyResult->details['count'])->toBe(0) ->and($emptyResult->details['events'])->toBeEmpty(); }); + +it('parses Linux nmcli Wi-Fi metrics, ip neigh LAN devices, and executes network stack reset as root', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $uid = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + return match ($command) { + ['nmcli', '-t', '-f', 'ACTIVE,SSID,BSSID,CHAN,FREQ,RATE,SIGNAL', 'dev', 'wifi'] => new ProcessResult( + 0, + "no:GuestNet:11\\:22\\:33\\:44\\:55\\:66:6:2437 MHz:130 Mbit/s:55\nyes:Office-WiFi6:AA\\:BB\\:CC\\:DD\\:EE\\:FF:44:5220 MHz:540 Mbit/s:88" + ), + ['systemctl', 'restart', 'NetworkManager'] => new ProcessResult(0, ''), + ['which', 'dhclient'] => new ProcessResult(0, '/usr/sbin/dhclient'), + ['dhclient', '-r'] => new ProcessResult(0, ''), + ['dhclient'] => new ProcessResult(0, ''), + ['ip', 'neigh', 'show'] => new ProcessResult(0, implode("\n", [ + '192.168.1.1 dev eth0 lladdr 00:1a:2b:3c:4d:5e REACHABLE', + '192.168.1.25 dev eth0 lladdr 10:20:30:40:50:60 STALE', + '192.168.1.99 dev eth0 FAILED', + ])), + default => new ProcessResult(1, '', 'Command failed', false), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return $this->uid; + } + }; + + $driver = new LinuxDriver($executor); + + $wifi = $driver->getWifiInfo(); + expect($wifi->success)->toBeTrue() + ->and($wifi->details['ssid'])->toBe('Office-WiFi6') + ->and($wifi->details['bssid'])->toBe('AA:BB:CC:DD:EE:FF') + ->and($wifi->details['signal'])->toBe('88%') + ->and($wifi->details['channel'])->toBe('44'); + + $resetRoot = $driver->resetNetworkStack(); + expect($resetRoot->success)->toBeTrue() + ->and($resetRoot->details['commands_executed'])->toContain('systemctl restart NetworkManager', 'dhclient -r && dhclient'); + + $executor->uid = 1000; + $resetNonRoot = $driver->resetNetworkStack(); + expect($resetNonRoot->success)->toBeFalse() + ->and($resetNonRoot->message)->toBe('messages.common.permission_denied'); + + $neighbors = $driver->scanLanDevices(); + expect($neighbors)->toHaveCount(2) + ->and($neighbors[0]['ip'])->toBe('192.168.1.1') + ->and($neighbors[0]['mac'])->toBe('00:1A:2B:3C:4D:5E') + ->and($neighbors[0]['status'])->toBe('REACHABLE') + ->and($neighbors[1]['ip'])->toBe('192.168.1.25'); +}); diff --git a/tests/Unit/WindowsDriverTest.php b/tests/Unit/WindowsDriverTest.php index 35aafcb..b7a0f92 100644 --- a/tests/Unit/WindowsDriverTest.php +++ b/tests/Unit/WindowsDriverTest.php @@ -217,3 +217,81 @@ public function getEffectiveUid(): int ->and($emptyResult->details['count'])->toBe(0) ->and($emptyResult->details['events'])->toBeEmpty(); }); + +it('parses Windows Wi-Fi metrics, ARP LAN devices, and executes network stack reset with Admin check', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $callIndex = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + $this->callIndex++; + + return match ($this->callIndex) { + 1 => new ProcessResult(0, implode("\r\n", [ + ' Name : Wi-Fi', + ' State : connected', + ' SSID : CorpNet-5G', + ' BSSID : aa:bb:cc:dd:ee:ff', + ' Radio type : 802.11ax', + ' Channel : 36', + ' Receive rate (Mbps) : 866.7', + ' Transmit rate (Mbps) : 866.7', + ' Signal : 92%', + ])), + 2 => new ProcessResult(0, 'There is no wireless interface on the system.'), + 3 => new ProcessResult(1, '', 'Access is denied.', false), // net session not admin + 4 => new ProcessResult(0, 'The command completed successfully.'), // net session admin + 5, 6, 7, 8, 9 => new ProcessResult(0, 'OK'), + 10 => new ProcessResult(0, implode("\r\n", [ + 'Interface: 192.168.1.105 --- 0xc', + ' Internet Address Physical Address Type', + ' 192.168.1.1 00-1a-2b-3c-4d-5e dynamic', + ' 192.168.1.50 11-22-33-44-55-66 dynamic', + ' 224.0.0.22 01-00-5e-00-00-16 static', + ' 255.255.255.255 ff-ff-ff-ff-ff-ff static', + ])), + default => new ProcessResult(0, ''), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new WindowsDriver($executor); + + $wifi = $driver->getWifiInfo(); + expect($wifi->success)->toBeTrue() + ->and($wifi->details['ssid'])->toBe('CorpNet-5G') + ->and($wifi->details['bssid'])->toBe('aa:bb:cc:dd:ee:ff') + ->and($wifi->details['signal'])->toBe('92%') + ->and($wifi->details['channel'])->toBe('36') + ->and($wifi->details['rx_rate'])->toBe('866.7 Mbps'); + + $noWifi = $driver->getWifiInfo(); + expect($noWifi->success)->toBeFalse() + ->and($noWifi->message)->toBe('messages.network.no_wifi'); + + $deniedReset = $driver->resetNetworkStack(); + expect($deniedReset->success)->toBeFalse() + ->and($deniedReset->message)->toBe('messages.common.permission_denied'); + + $adminReset = $driver->resetNetworkStack(); + expect($adminReset->success)->toBeTrue() + ->and($adminReset->message)->toBe('messages.network.reset_success') + ->and($adminReset->details['commands_executed'])->toHaveCount(5); + + $lanDevices = $driver->scanLanDevices(); + expect($lanDevices)->toHaveCount(2) + ->and($lanDevices[0]['ip'])->toBe('192.168.1.1') + ->and($lanDevices[0]['mac'])->toBe('00:1A:2B:3C:4D:5E') + ->and($lanDevices[1]['ip'])->toBe('192.168.1.50'); +});