From ba83dfa4897f36ef1506168d1c962e6f5c5f5a72 Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 15:40:49 -0300 Subject: [PATCH] feat(maintenance,security): add OS repair, large files, browser cache, updates, scheduler, and security audit suite --- .../Maintenance/CleanBrowsersCommand.php | 63 +++ .../Maintenance/LargeFilesCommand.php | 83 ++++ app/Commands/Maintenance/OsRepairCommand.php | 63 +++ app/Commands/Maintenance/OsUpdatesCommand.php | 74 +++ app/Commands/Maintenance/SchedulerCommand.php | 75 +++ app/Commands/Security/HostsFileCommand.php | 78 ++++ .../Security/SecurityAuditCommand.php | 66 +++ app/Commands/Security/SharesCommand.php | 74 +++ app/Commands/Security/UsersAuditCommand.php | 75 +++ app/Commands/ToolboxMenuCommand.php | 25 +- app/Contracts/SystemDriverInterface.php | 67 +++ .../InteractsWithMaintenanceAndSecurity.php | 320 +++++++++++++ app/Drivers/LinuxDriver.php | 441 ++++++++++++++++++ app/Drivers/WindowsDriver.php | 314 +++++++++++++ lang/en/messages.php | 90 +++- lang/pt_BR/messages.php | 90 +++- tests/Feature/ReportExporterTest.php | 45 ++ tests/Unit/HealthCheckServiceTest.php | 45 ++ tests/Unit/LinuxDriverTest.php | 83 ++++ tests/Unit/WindowsDriverTest.php | 127 +++++ 20 files changed, 2288 insertions(+), 10 deletions(-) create mode 100644 app/Commands/Maintenance/CleanBrowsersCommand.php create mode 100644 app/Commands/Maintenance/LargeFilesCommand.php create mode 100644 app/Commands/Maintenance/OsRepairCommand.php create mode 100644 app/Commands/Maintenance/OsUpdatesCommand.php create mode 100644 app/Commands/Maintenance/SchedulerCommand.php create mode 100644 app/Commands/Security/HostsFileCommand.php create mode 100644 app/Commands/Security/SecurityAuditCommand.php create mode 100644 app/Commands/Security/SharesCommand.php create mode 100644 app/Commands/Security/UsersAuditCommand.php create mode 100644 app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php diff --git a/app/Commands/Maintenance/CleanBrowsersCommand.php b/app/Commands/Maintenance/CleanBrowsersCommand.php new file mode 100644 index 0000000..7f59a18 --- /dev/null +++ b/app/Commands/Maintenance/CleanBrowsersCommand.php @@ -0,0 +1,63 @@ +resolveLocale(); + + info((string) __('messages.maintenance.browsers_section')); + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.maintenance.confirm_browsers_clean'), + default: true, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $driver->cleanBrowserCaches(), + message: (string) __('messages.spinners.maintenance_browsers'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Maintenance/LargeFilesCommand.php b/app/Commands/Maintenance/LargeFilesCommand.php new file mode 100644 index 0000000..c014c13 --- /dev/null +++ b/app/Commands/Maintenance/LargeFilesCommand.php @@ -0,0 +1,83 @@ +resolveLocale(); + + info((string) __('messages.maintenance.large_files_section')); + + $pathArg = $this->argument('path'); + $targetPath = is_string($pathArg) && trim($pathArg) !== '' ? trim($pathArg) : null; + $limit = max(1, (int) $this->option('limit')); + + /** @var array $files */ + $files = spin( + callback: fn (): array => $driver->findLargeFiles($targetPath, $limit), + message: (string) __('messages.spinners.maintenance_large_files'), + ); + + if ($files === []) { + warning((string) __('messages.maintenance.no_large_files')); + + return self::SUCCESS; + } + + table( + headers: [ + '#', + (string) __('messages.maintenance.large_files_headers.size'), + (string) __('messages.maintenance.large_files_headers.modified'), + (string) __('messages.maintenance.large_files_headers.path'), + ], + rows: array_map( + fn (array $file, int $idx): array => [ + (string) ($idx + 1), + $file['size_formatted'], + $file['modified_at'], + $file['path'], + ], + $files, + array_keys($files) + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Maintenance/OsRepairCommand.php b/app/Commands/Maintenance/OsRepairCommand.php new file mode 100644 index 0000000..15b065d --- /dev/null +++ b/app/Commands/Maintenance/OsRepairCommand.php @@ -0,0 +1,63 @@ +resolveLocale(); + + info((string) __('messages.maintenance.repair_section')); + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.maintenance.confirm_repair'), + 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->repairOsIntegrity(), + message: (string) __('messages.spinners.maintenance_repair'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Maintenance/OsUpdatesCommand.php b/app/Commands/Maintenance/OsUpdatesCommand.php new file mode 100644 index 0000000..4c36f8f --- /dev/null +++ b/app/Commands/Maintenance/OsUpdatesCommand.php @@ -0,0 +1,74 @@ +resolveLocale(); + + info((string) __('messages.maintenance.updates_section')); + + /** @var array $updates */ + $updates = spin( + callback: fn (): array => $driver->getPendingUpdates(), + message: (string) __('messages.spinners.maintenance_updates'), + ); + + if ($updates === []) { + info((string) __('messages.maintenance.no_pending_updates')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.maintenance.updates_headers.package'), + (string) __('messages.maintenance.updates_headers.version'), + (string) __('messages.maintenance.updates_headers.source'), + (string) __('messages.maintenance.updates_headers.status'), + ], + rows: array_map( + fn (array $upd): array => [ + $upd['package'] ?? '-', + $upd['version'] ?? '-', + $upd['source'] ?? '-', + $upd['status'] ?? '-', + ], + $updates + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Maintenance/SchedulerCommand.php b/app/Commands/Maintenance/SchedulerCommand.php new file mode 100644 index 0000000..d59d8f7 --- /dev/null +++ b/app/Commands/Maintenance/SchedulerCommand.php @@ -0,0 +1,75 @@ +resolveLocale(); + + info((string) __('messages.maintenance.scheduler_section')); + + /** @var array $tasks */ + $tasks = spin( + callback: fn (): array => $driver->getScheduledTasks(), + message: (string) __('messages.spinners.maintenance_scheduler'), + ); + + if ($tasks === []) { + warning((string) __('messages.maintenance.no_scheduled_tasks')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.maintenance.scheduler_headers.name'), + (string) __('messages.maintenance.scheduler_headers.schedule'), + (string) __('messages.maintenance.scheduler_headers.next_run'), + (string) __('messages.maintenance.scheduler_headers.status'), + ], + rows: array_map( + fn (array $task): array => [ + $task['name'] ?? '-', + $task['schedule'] ?? '-', + $task['next_run'] ?? '-', + $task['status'] ?? '-', + ], + $tasks + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Security/HostsFileCommand.php b/app/Commands/Security/HostsFileCommand.php new file mode 100644 index 0000000..0f2fee2 --- /dev/null +++ b/app/Commands/Security/HostsFileCommand.php @@ -0,0 +1,78 @@ +resolveLocale(); + + info((string) __('messages.security.hosts_section')); + + /** @var array $entries */ + $entries = spin( + callback: fn (): array => $driver->inspectHostsFile(), + message: (string) __('messages.spinners.security_hosts'), + ); + + if ($entries === []) { + info((string) __('messages.security.no_hosts_entries')); + + return self::SUCCESS; + } + + $statusLabels = [ + 'STANDARD' => (string) __('messages.security.hosts_states.standard'), + 'CUSTOM_LOCAL' => (string) __('messages.security.hosts_states.custom_local'), + 'EXTERNAL_REDIRECT' => (string) __('messages.security.hosts_states.external_redirect'), + ]; + + table( + headers: [ + (string) __('messages.security.hosts_headers.ip'), + (string) __('messages.security.hosts_headers.host'), + (string) __('messages.security.hosts_headers.status'), + ], + rows: array_map( + fn (array $item): array => [ + $item['ip'] ?? '-', + $item['host'] ?? '-', + sprintf('%s %s', $item['icon'] ?? '', $statusLabels[$item['status']] ?? $item['status']), + ], + $entries + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Security/SecurityAuditCommand.php b/app/Commands/Security/SecurityAuditCommand.php new file mode 100644 index 0000000..f70cf55 --- /dev/null +++ b/app/Commands/Security/SecurityAuditCommand.php @@ -0,0 +1,66 @@ +resolveLocale(); + + info((string) __('messages.security.audit_section')); + + /** @var array $checks */ + $checks = spin( + callback: fn (): array => $driver->runSecurityAudit(), + message: (string) __('messages.spinners.security_audit'), + ); + + table( + headers: [ + (string) __('messages.security.audit_headers.component'), + (string) __('messages.security.audit_headers.status'), + (string) __('messages.security.audit_headers.details'), + ], + rows: array_map( + fn (array $item): array => [ + $item['component'] ?? '-', + sprintf('%s %s', $item['icon'] ?? '', $item['status'] ?? '-'), + $item['details'] ?? '-', + ], + $checks + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Security/SharesCommand.php b/app/Commands/Security/SharesCommand.php new file mode 100644 index 0000000..1f3f2e2 --- /dev/null +++ b/app/Commands/Security/SharesCommand.php @@ -0,0 +1,74 @@ +resolveLocale(); + + info((string) __('messages.security.shares_section')); + + /** @var array $shares */ + $shares = spin( + callback: fn (): array => $driver->getNetworkShares(), + message: (string) __('messages.spinners.security_shares'), + ); + + if ($shares === []) { + info((string) __('messages.security.no_shares_found')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.security.shares_headers.name'), + (string) __('messages.security.shares_headers.path'), + (string) __('messages.security.shares_headers.type'), + (string) __('messages.security.shares_headers.description'), + ], + rows: array_map( + fn (array $share): array => [ + $share['name'] ?? '-', + $share['path'] ?? '-', + $share['type'] ?? '-', + $share['description'] ?? '-', + ], + $shares + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Security/UsersAuditCommand.php b/app/Commands/Security/UsersAuditCommand.php new file mode 100644 index 0000000..806b084 --- /dev/null +++ b/app/Commands/Security/UsersAuditCommand.php @@ -0,0 +1,75 @@ +resolveLocale(); + + info((string) __('messages.security.users_section')); + + /** @var array $users */ + $users = spin( + callback: fn (): array => $driver->getLocalUsersAudit(), + message: (string) __('messages.spinners.security_users'), + ); + + if ($users === []) { + warning((string) __('messages.security.no_users_found')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.security.users_headers.username'), + (string) __('messages.security.users_headers.status'), + (string) __('messages.security.users_headers.is_admin'), + (string) __('messages.security.users_headers.last_logon'), + ], + rows: array_map( + fn (array $user): array => [ + $user['username'] ?? '-', + $user['status'] ?? '-', + $user['is_admin'] ?? 'No', + $user['last_logon'] ?? '-', + ], + $users + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 9a0f94c..8bb361c 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -50,9 +50,10 @@ public function handle(): int '3' => (string) __('messages.menu.categories.printers'), '4' => (string) __('messages.menu.categories.network'), '5' => (string) __('messages.menu.categories.maintenance'), - '6' => (string) __('messages.menu.categories.reports'), - '7' => (string) __('messages.menu.categories.self_update'), - '8' => (string) __('messages.menu.categories.language'), + '6' => (string) __('messages.menu.categories.security'), + '7' => (string) __('messages.menu.categories.reports'), + '8' => (string) __('messages.menu.categories.self_update'), + '9' => (string) __('messages.menu.categories.language'), '0' => (string) __('messages.menu.exit'), ], defaultKey: '1', @@ -67,11 +68,11 @@ public function handle(): int if ($choice === '1') { $this->executeSubcommand('health:check', $locale); - } elseif ($choice === '6') { - $this->executeSubcommand('report:export', $locale); } elseif ($choice === '7') { - $this->executeSubcommand('self:update', $locale); + $this->executeSubcommand('report:export', $locale); } elseif ($choice === '8') { + $this->executeSubcommand('self:update', $locale); + } elseif ($choice === '9') { $locale = $this->promptNumericLanguageSwitch($locale); } else { $category = match ($choice) { @@ -79,6 +80,7 @@ public function handle(): int '3' => 'printers', '4' => 'network', '5' => 'maintenance', + '6' => 'security', default => 'system', }; @@ -184,6 +186,17 @@ protected function handleCategorySubmenu(string $category, string $locale): void ], 'maintenance' => [ '1' => ['label' => (string) __('messages.menu.actions.clean_temp'), 'command' => 'clean:temp'], + '2' => ['label' => (string) __('messages.menu.actions.maintenance_browsers'), 'command' => 'maintenance:browsers'], + '3' => ['label' => (string) __('messages.menu.actions.maintenance_large_files'), 'command' => 'maintenance:large-files'], + '4' => ['label' => (string) __('messages.menu.actions.maintenance_repair'), 'command' => 'maintenance:repair'], + '5' => ['label' => (string) __('messages.menu.actions.maintenance_updates'), 'command' => 'maintenance:updates'], + '6' => ['label' => (string) __('messages.menu.actions.maintenance_scheduler'), 'command' => 'maintenance:scheduler'], + ], + 'security' => [ + '1' => ['label' => (string) __('messages.menu.actions.security_audit'), 'command' => 'security:audit'], + '2' => ['label' => (string) __('messages.menu.actions.security_users'), 'command' => 'security:users'], + '3' => ['label' => (string) __('messages.menu.actions.security_shares'), 'command' => 'security:shares'], + '4' => ['label' => (string) __('messages.menu.actions.security_hosts'), 'command' => 'security:hosts'], ], default => [], }; diff --git a/app/Contracts/SystemDriverInterface.php b/app/Contracts/SystemDriverInterface.php index f9bfc03..3fc6522 100644 --- a/app/Contracts/SystemDriverInterface.php +++ b/app/Contracts/SystemDriverInterface.php @@ -205,4 +205,71 @@ public function getPublicIpInfo(): ActionResult; * @return ActionResult */ public function cleanTempFiles(): ActionResult; + + /** + * Run OS image and package integrity verification / repair (SFC & DISM on Windows; dpkg/apt/rpm/pacman audit on Linux). + * + * @return ActionResult + */ + public function repairOsIntegrity(): ActionResult; + + /** + * Scan a target directory recursively and return the largest files sorted by size descending. + * + * @param string|null $directory + * @param int $limit + * @return array + */ + public function findLargeFiles(?string $directory = null, int $limit = 15): array; + + /** + * Safely clean browser cache directories (Chrome, Edge, Firefox) without touching passwords, cookies, or history. + * + * @param array|null $customCachePaths Optional map of browser label => cache path for testing. + * @return ActionResult + */ + public function cleanBrowserCaches(?array $customCachePaths = null): ActionResult; + + /** + * Retrieve pending OS and package updates. + * + * @return array + */ + public function getPendingUpdates(): array; + + /** + * Retrieve active non-system scheduled tasks, cron jobs, and systemd timers. + * + * @return array + */ + public function getScheduledTasks(): array; + + /** + * Run a unified security posture audit (Firewall, Antivirus/Defender/MAC, and UAC/Sudo/SSH policy). + * + * @return array + */ + public function runSecurityAudit(): array; + + /** + * Audit local user accounts, active status, last logon, and Administrative / sudo membership. + * + * @return array + */ + public function getLocalUsersAudit(): array; + + /** + * Retrieve active SMB / Samba / NFS network shares. + * + * @return array + */ + public function getNetworkShares(): array; + + /** + * Inspect the system hosts file and highlight custom or suspicious domain redirections. + * + * @param string|null $customContent Optional raw hosts file content for testing. + * @return array + */ + public function inspectHostsFile(?string $customContent = null): array; } diff --git a/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php b/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php new file mode 100644 index 0000000..7b80bf4 --- /dev/null +++ b/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php @@ -0,0 +1,320 @@ + + */ + private const STANDARD_LOCAL_HOSTS = [ + 'localhost', + 'localhost.localdomain', + 'local', + 'ip6-localhost', + 'ip6-loopback', + 'ip6-localnet', + 'ip6-mcastprefix', + 'ip6-allnodes', + 'ip6-allrouters', + 'ip6-allhosts', + 'broadcasthost', + ]; + + /** + * Ignored virtual/system directory names when scanning for large files. + * + * @var array + */ + private const IGNORED_SCAN_DIRS = [ + 'proc', 'sys', 'dev', 'run', 'snap', 'winsxs', 'system volume information', '$recycle.bin', '.git', 'node_modules', + ]; + + /** + * Scan a target directory recursively and return the largest files sorted by size descending. + * + * @return array + */ + public function findLargeFiles(?string $directory = null, int $limit = 15): array + { + $safeLimit = max(1, $limit); + $targetDir = $directory !== null && trim($directory) !== '' + ? trim($directory) + : (string) (getenv('USERPROFILE') ?: getenv('HOME') ?: (getcwd() ?: base_path())); + + if (! is_dir($targetDir) || ! is_readable($targetDir)) { + return []; + } + + $collected = []; + + try { + $dirIterator = new RecursiveDirectoryIterator( + $targetDir, + FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_FILEINFO + ); + + $filterIterator = new \RecursiveCallbackFilterIterator( + $dirIterator, + function (SplFileInfo $current): bool { + if ($current->isLink()) { + return false; + } + if ($current->isDir()) { + $lowerName = strtolower($current->getFilename()); + + return ! in_array($lowerName, self::IGNORED_SCAN_DIRS, true); + } + + return true; + } + ); + + $iterator = new RecursiveIteratorIterator( + $filterIterator, + RecursiveIteratorIterator::LEAVES_ONLY, + RecursiveIteratorIterator::CATCH_GET_CHILD + ); + + /** @var SplFileInfo $file */ + foreach ($iterator as $file) { + if (! $file->isFile() || $file->isLink()) { + continue; + } + + $size = @$file->getSize(); + if ($size === false || $size <= 0) { + continue; + } + + $mtime = @$file->getMTime(); + $collected[] = [ + 'path' => $file->getPathname(), + 'size_bytes' => (float) $size, + 'size_formatted' => $this->formatBytes((float) $size), + 'modified_at' => $mtime !== false ? date('Y-m-d H:i', $mtime) : '-', + ]; + } + } catch (Throwable) { + // Ignore unreadable permission boundaries + } + + usort( + $collected, + fn (array $a, array $b): int => $b['size_bytes'] <=> $a['size_bytes'] + ); + + return array_slice($collected, 0, $safeLimit); + } + + /** + * Safely clean browser cache directories (Chrome, Edge, Firefox) without touching passwords, cookies, or history. + * + * @param array|null $customCachePaths + */ + public function cleanBrowserCaches(?array $customCachePaths = null): ActionResult + { + $targets = $customCachePaths ?? $this->getDefaultBrowserCachePaths(); + + $deletedFiles = 0; + $skippedFiles = 0; + $freedBytes = 0.0; + $cleanedBrowsers = []; + + foreach ($targets as $browserLabel => $cacheDir) { + if ($cacheDir === '' || ! is_dir($cacheDir) || ! is_readable($cacheDir)) { + continue; + } + + $browserFreed = 0.0; + try { + $iterator = new FilesystemIterator($cacheDir, FilesystemIterator::SKIP_DOTS); + /** @var SplFileInfo $entry */ + foreach ($iterator as $entry) { + $path = $entry->getPathname(); + $entrySize = $this->calculateCacheEntrySize($path); + + if ($this->deleteCacheEntrySafely($path)) { + $deletedFiles++; + $freedBytes += $entrySize; + $browserFreed += $entrySize; + } else { + $skippedFiles++; + } + } + } catch (Throwable) { + $skippedFiles++; + } + + if ($browserFreed > 0.0 || ! in_array($browserLabel, $cleanedBrowsers, true)) { + $cleanedBrowsers[] = (string) $browserLabel; + } + } + + return new ActionResult( + success: true, + message: 'messages.maintenance.browsers_clean_success', + details: [ + 'browsers_cleaned' => $cleanedBrowsers !== [] ? $cleanedBrowsers : ['None Detected'], + 'deleted_files' => $deletedFiles, + 'skipped_locked_files' => $skippedFiles, + 'freed_space' => $this->formatBytes($freedBytes), + 'driver' => $this->getDriverLabel(), + ], + ); + } + + /** + * Inspect the system hosts file and highlight custom or suspicious domain redirections. + * + * @return array + */ + public function inspectHostsFile(?string $customContent = null): array + { + $raw = $customContent ?? $this->readHostsFileContent(); + if ($raw === null || trim($raw) === '') { + return []; + } + + $entries = []; + $lines = preg_split('/\r\n|\r|\n/', $raw) ?: []; + $localHostname = strtolower((string) (gethostname() ?: '')); + + foreach ($lines as $line) { + // Strip inline comments + if (str_contains($line, '#')) { + $line = explode('#', $line, 2)[0]; + } + + $line = trim($line); + if ($line === '') { + continue; + } + + $parts = preg_split('/\s+/', $line); + if (! is_array($parts) || count($parts) < 2) { + continue; + } + + $ip = array_shift($parts); + $isLoopbackIp = in_array($ip, ['127.0.0.1', '127.0.1.1', '::1', '0.0.0.0', 'fe00::0', 'ff00::0', 'ff02::1', 'ff02::2', 'ff02::3'], true); + + foreach ($parts as $host) { + $lowerHost = strtolower(trim($host)); + if ($lowerHost === '') { + continue; + } + + $isStandardHost = in_array($lowerHost, self::STANDARD_LOCAL_HOSTS, true) + || ($localHostname !== '' && $lowerHost === $localHostname); + + if ($isLoopbackIp && $isStandardHost) { + $status = 'STANDARD'; + $icon = '✅'; + } elseif ($isLoopbackIp) { + $status = 'CUSTOM_LOCAL'; + $icon = '⚠️'; + } else { + $status = 'EXTERNAL_REDIRECT'; + $icon = '❌'; + } + + $entries[] = [ + 'ip' => $ip, + 'host' => $host, + 'status' => $status, + 'icon' => $icon, + ]; + } + } + + return $entries; + } + + /** + * Calculate byte size of a cache file or directory tree safely. + */ + protected function calculateCacheEntrySize(string $path): float + { + if (is_link($path)) { + return 0.0; + } + + if (is_file($path)) { + $size = @filesize($path); + + return $size !== false ? (float) $size : 0.0; + } + + if (! is_dir($path) || ! is_readable($path)) { + return 0.0; + } + + $total = 0.0; + try { + $iterator = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS); + /** @var SplFileInfo $item */ + foreach ($iterator as $item) { + $total += $this->calculateCacheEntrySize($item->getPathname()); + } + } catch (Throwable) { + // Ignore unreadable subtrees + } + + return $total; + } + + /** + * Delete a cache file or subdirectory safely. + */ + protected function deleteCacheEntrySafely(string $path): bool + { + if (is_link($path) || is_file($path)) { + return @unlink($path); + } + + if (! is_dir($path)) { + return false; + } + + try { + $iterator = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS); + /** @var SplFileInfo $item */ + foreach ($iterator as $item) { + $this->deleteCacheEntrySafely($item->getPathname()); + } + } catch (Throwable) { + return false; + } + + return @rmdir($path); + } + + /** + * Return default browser cache directories for the active OS driver. + * + * @return array + */ + abstract protected function getDefaultBrowserCachePaths(): array; + + /** + * Read the raw content of the system hosts file. + */ + abstract protected function readHostsFileContent(): ?string; + + /** + * Return the driver identifier ('Windows' or 'Linux'). + */ + abstract protected function getDriverLabel(): string; +} diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index 759dc0a..d700962 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\InteractsWithMaintenanceAndSecurity; use App\Drivers\Concerns\InteractsWithNetworkSockets; use App\DTOs\ActionResult; use App\Services\SymfonyProcessExecutor; @@ -16,6 +17,7 @@ class LinuxDriver implements SystemDriverInterface { + use InteractsWithMaintenanceAndSecurity; use InteractsWithNetworkSockets; /** * Real block/disk filesystem types to include in storage health checks. @@ -1272,6 +1274,445 @@ public function cleanTempFiles(): ActionResult ); } + /** + * {@inheritDoc} + */ + public function repairOsIntegrity(): ActionResult + { + $executed = []; + $outputs = []; + + if ($this->commandExists('dpkg')) { + $res = $this->processRunner->run(['dpkg', '--audit']); + $executed[] = 'dpkg --audit'; + $outputs[] = $res->output !== '' ? $res->output : 'dpkg: no broken packages found'; + } + + if ($this->commandExists('apt-get') && $this->isRoot()) { + $res = $this->processRunner->run(['apt-get', 'check']); + $executed[] = 'apt-get check'; + if ($res->output !== '') { + $outputs[] = $res->output; + } + } + + if ($executed === [] && $this->commandExists('rpm')) { + $res = $this->processRunner->run(['rpm', '-Va', '--nofiles', '--nodigest']); + $executed[] = 'rpm -Va --nofiles --nodigest'; + $outputs[] = $res->output !== '' ? $res->output : 'rpm: package database verified'; + } + + if ($executed === [] && $this->commandExists('pacman')) { + $res = $this->processRunner->run(['pacman', '-Qk']); + $executed[] = 'pacman -Qk'; + $outputs[] = $res->output !== '' ? $res->output : 'pacman: all packages intact'; + } + + if ($executed === []) { + return new ActionResult( + success: false, + message: 'messages.maintenance.repair_failed', + details: ['driver' => 'Linux'], + ); + } + + $summaryOutput = $this->truncateLogMessage(implode(' | ', $outputs), 110); + + return new ActionResult( + success: true, + message: 'messages.maintenance.repair_success', + details: [ + 'commands_executed' => $executed, + 'output' => $summaryOutput, + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getPendingUpdates(): array + { + $updates = []; + + if ($this->commandExists('apt')) { + $res = $this->processRunner->run(['apt', 'list', '--upgradable']); + if ($res->successful && $res->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($res->output)) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || str_starts_with(strtolower($line), 'listing')) { + continue; + } + // Format: "curl/noble-updates 8.5.0-2ubuntu10.4 amd64 [upgradable from: 8.5.0-2ubuntu10.1]" + if (preg_match('/^([^\/\s]+)\/(\S+)\s+(\S+)\s+\S+/', $line, $m) === 1) { + $updates[] = [ + 'package' => $m[1], + 'version' => $m[3], + 'source' => 'APT (' . $m[2] . ')', + 'status' => 'Upgradable', + ]; + } + } + + return array_slice($updates, 0, 30); + } + } + + if ($this->commandExists('dnf')) { + $res = $this->processRunner->run(['dnf', 'check-update', '--quiet']); + if ($res->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($res->output)) ?: []; + foreach ($lines as $line) { + $parts = preg_split('/\s+/', trim($line)); + if (is_array($parts) && count($parts) >= 3) { + $updates[] = [ + 'package' => $parts[0], + 'version' => $parts[1], + 'source' => 'DNF (' . $parts[2] . ')', + 'status' => 'Upgradable', + ]; + } + } + + return array_slice($updates, 0, 30); + } + } + + if ($this->commandExists('pacman')) { + $res = $this->processRunner->run(['pacman', '-Qu']); + if ($res->successful && $res->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($res->output)) ?: []; + foreach ($lines as $line) { + if (preg_match('/^(\S+)\s+(\S+)\s+->\s+(\S+)/', trim($line), $m) === 1) { + $updates[] = [ + 'package' => $m[1], + 'version' => $m[3], + 'source' => 'Pacman', + 'status' => 'Upgradable (from ' . $m[2] . ')', + ]; + } + } + } + } + + return array_slice($updates, 0, 30); + } + + /** + * {@inheritDoc} + */ + public function getScheduledTasks(): array + { + $tasks = []; + + $crontabRaw = $this->readFile('/etc/crontab') ?? ''; + if ($crontabRaw !== '') { + $lines = preg_split('/\r\n|\r|\n/', $crontabRaw) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || str_starts_with($line, '#') || preg_match('/^[A-Z_]+=/', $line) === 1) { + continue; + } + + $parts = preg_split('/\s+/', $line, 7); + if (is_array($parts) && count($parts) === 7) { + $scheduleExpr = implode(' ', array_slice($parts, 0, 5)); + $user = $parts[5]; + $command = $this->truncateLogMessage($parts[6], 55); + + $tasks[] = [ + 'name' => $command, + 'schedule' => 'cron (' . $scheduleExpr . ')', + 'next_run' => 'User: ' . $user, + 'status' => 'Active', + ]; + } + } + } + + $timersResult = $this->processRunner->run(['systemctl', 'list-timers', '--no-pager', '--no-legend']); + if ($timersResult->successful && $timersResult->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($timersResult->output)) ?: []; + foreach (array_slice($lines, 0, 20) as $line) { + $line = trim($line); + if ($line === '') { + continue; + } + if (preg_match('/^(.+?)\s+([A-Za-z0-9_.-]+\.timer)\s+([A-Za-z0-9_.-]+\.service)$/i', $line, $m) === 1) { + $tasks[] = [ + 'name' => $m[2], + 'schedule' => 'systemd timer -> ' . $m[3], + 'next_run' => $this->truncateLogMessage(trim($m[1]), 35), + 'status' => 'Active', + ]; + } + } + } + + return $tasks; + } + + /** + * {@inheritDoc} + */ + public function runSecurityAudit(): array + { + $audit = []; + + // 1. Firewall check (UFW / firewalld / nftables) + $fwActive = false; + $fwDetails = 'No active firewall service detected (ufw / firewalld / nftables)'; + + if ($this->commandExists('ufw')) { + $ufwRes = $this->processRunner->run(['ufw', 'status']); + if ($ufwRes->successful && str_contains(strtolower($ufwRes->output), 'status: active')) { + $fwActive = true; + $fwDetails = 'UFW Firewall is active'; + } + } + + if (! $fwActive) { + foreach (['firewalld', 'nftables'] as $fwDaemon) { + $res = $this->processRunner->run(['systemctl', 'is-active', $fwDaemon]); + if ($res->successful && trim($res->output) === 'active') { + $fwActive = true; + $fwDetails = $fwDaemon . ' daemon is active'; + break; + } + } + } + + $audit[] = [ + 'component' => 'Linux Host Firewall', + 'status' => $fwActive ? 'ENABLED' : 'WARNING', + 'icon' => $fwActive ? '✅' : '⚠️', + 'details' => $fwDetails, + ]; + + // 2. MAC / Antivirus check (AppArmor / SELinux / ClamAV) + $macActive = false; + $macDetails = []; + + $appArmorParam = trim((string) ($this->readFile('/sys/module/apparmor/parameters/enabled') ?? '')); + if (strtoupper($appArmorParam) === 'Y') { + $macActive = true; + $macDetails[] = 'AppArmor: Enabled'; + } + + if ($this->commandExists('getenforce')) { + $seRes = $this->processRunner->run(['getenforce']); + $seMode = trim($seRes->output); + if (in_array(strtolower($seMode), ['enforcing', 'permissive'], true)) { + $macActive = true; + $macDetails[] = 'SELinux: ' . $seMode; + } + } + + $audit[] = [ + 'component' => 'Mandatory Access Control (AppArmor / SELinux)', + 'status' => $macActive ? 'PROTECTED' : 'WARNING', + 'icon' => $macActive ? '✅' : '⚠️', + 'details' => $macDetails !== [] ? implode(' | ', $macDetails) : 'Neither AppArmor nor SELinux reported active', + ]; + + // 3. SSH Root Login & Sudo Policy + $sshdConfig = $this->readFile('/etc/ssh/sshd_config') ?? ''; + $rootLoginPermitted = preg_match('/^\s*PermitRootLogin\s+yes\b/im', $sshdConfig) === 1; + + $audit[] = [ + 'component' => 'SSH & Root Privilege Policy', + 'status' => $rootLoginPermitted ? 'WARNING' : 'HARDENED', + 'icon' => $rootLoginPermitted ? '⚠️' : '✅', + 'details' => $rootLoginPermitted + ? 'PermitRootLogin is set to "yes" in /etc/ssh/sshd_config' + : 'Direct SSH PermitRootLogin is restricted or disabled', + ]; + + return $audit; + } + + /** + * {@inheritDoc} + */ + public function getLocalUsersAudit(): array + { + $passwdRaw = $this->readFile('/etc/passwd') ?? ''; + $groupRaw = $this->readFile('/etc/group') ?? ''; + + if ($passwdRaw === '') { + return []; + } + + $adminUsers = ['root' => true]; + foreach (preg_split('/\r\n|\r|\n/', $groupRaw) ?: [] as $gLine) { + $gParts = explode(':', trim($gLine)); + if (count($gParts) >= 4 && in_array($gParts[0], ['sudo', 'wheel', 'admin', 'root'], true)) { + foreach (explode(',', $gParts[3]) as $member) { + $member = trim($member); + if ($member !== '') { + $adminUsers[$member] = true; + } + } + } + } + + $users = []; + foreach (preg_split('/\r\n|\r|\n/', $passwdRaw) ?: [] as $pLine) { + $pLine = trim($pLine); + if ($pLine === '' || str_starts_with($pLine, '#')) { + continue; + } + + $parts = explode(':', $pLine); + if (count($parts) < 7) { + continue; + } + + $username = $parts[0]; + $uid = (int) $parts[2]; + $shell = $parts[6]; + + $isLoginShell = ! str_ends_with($shell, 'nologin') && ! str_ends_with($shell, '/false') && ! str_ends_with($shell, '/sync'); + if ($uid !== 0 && $uid < 1000 && ! $isLoginShell) { + continue; + } + + $isAdmin = $uid === 0 || isset($adminUsers[$username]); + + $users[] = [ + 'username' => sprintf('%s (UID %d)', $username, $uid), + 'status' => $isLoginShell ? '✅ Active (' . basename($shell) . ')' : '⚪ System/Locked', + 'is_admin' => $isAdmin ? '⚠️ YES (sudo/root)' : 'No', + 'last_logon' => $shell, + ]; + } + + return $users; + } + + /** + * {@inheritDoc} + */ + public function getNetworkShares(): array + { + $shares = []; + + $smbConf = $this->readFile('/etc/samba/smb.conf') ?? ''; + if ($smbConf !== '') { + $currentSection = null; + $currentPath = '-'; + $currentComment = '-'; + + $lines = preg_split('/\r\n|\r|\n/', $smbConf) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || str_starts_with($line, '#') || str_starts_with($line, ';')) { + continue; + } + + if (preg_match('/^\[([^\]]+)\]$/', $line, $secMatch) === 1) { + if ($currentSection !== null && strtolower($currentSection) !== 'global') { + $shares[] = [ + 'name' => $currentSection, + 'path' => $currentPath, + 'type' => 'Samba (SMB)', + 'description' => $currentComment, + ]; + } + $currentSection = trim($secMatch[1]); + $currentPath = '-'; + $currentComment = '-'; + + continue; + } + + if ($currentSection !== null && str_contains($line, '=')) { + [$k, $v] = array_map('trim', explode('=', $line, 2)); + if (strtolower($k) === 'path') { + $currentPath = $v; + } elseif (strtolower($k) === 'comment') { + $currentComment = $v; + } + } + } + + if ($currentSection !== null && strtolower($currentSection) !== 'global') { + $shares[] = [ + 'name' => $currentSection, + 'path' => $currentPath, + 'type' => 'Samba (SMB)', + 'description' => $currentComment, + ]; + } + } + + $exportsRaw = $this->readFile('/etc/exports') ?? ''; + if ($exportsRaw !== '') { + $lines = preg_split('/\r\n|\r|\n/', $exportsRaw) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || str_starts_with($line, '#')) { + continue; + } + + $parts = preg_split('/\s+/', $line, 2); + if (is_array($parts) && count($parts) === 2) { + $shares[] = [ + 'name' => basename($parts[0]) ?: $parts[0], + 'path' => $parts[0], + 'type' => 'NFS Export', + 'description' => $this->truncateLogMessage($parts[1], 55), + ]; + } + } + } + + return $shares; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultBrowserCachePaths(): array + { + $home = (string) (getenv('HOME') ?: '/root'); + $cacheRoot = $home . '/.cache'; + + $paths = [ + 'Google Chrome (Cache)' => $cacheRoot . '/google-chrome/Default/Cache', + 'Google Chrome (Code Cache)' => $cacheRoot . '/google-chrome/Default/Code Cache', + 'Microsoft Edge (Cache)' => $cacheRoot . '/microsoft-edge/Default/Cache', + 'Microsoft Edge (Code Cache)' => $cacheRoot . '/microsoft-edge/Default/Code Cache', + ]; + + $firefoxCache = $cacheRoot . '/mozilla/firefox'; + if (is_dir($firefoxCache) && is_readable($firefoxCache)) { + foreach (glob($firefoxCache . '/*/cache2/entries') ?: [] as $idx => $ffDir) { + $paths['Mozilla Firefox (Profile ' . ($idx + 1) . ')'] = $ffDir; + } + } + + return $paths; + } + + /** + * {@inheritDoc} + */ + protected function readHostsFileContent(): ?string + { + return $this->readFile('/etc/hosts'); + } + + /** + * {@inheritDoc} + */ + protected function getDriverLabel(): string + { + return 'Linux'; + } + /** * Read a file from the filesystem or injected ProcessExecutorInterface / test reader. */ diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index 15f5791..73d5c6f 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -6,6 +6,7 @@ use App\Contracts\ProcessExecutorInterface; use App\Contracts\SystemDriverInterface; +use App\Drivers\Concerns\InteractsWithMaintenanceAndSecurity; use App\Drivers\Concerns\InteractsWithNetworkSockets; use App\DTOs\ActionResult; use App\DTOs\ProcessResult; @@ -13,6 +14,7 @@ class WindowsDriver implements SystemDriverInterface { + use InteractsWithMaintenanceAndSecurity; use InteractsWithNetworkSockets; private const UTF8_PREAMBLE = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $OutputEncoding = [System.Text.Encoding]::UTF8; '; @@ -1186,6 +1188,318 @@ public function cleanTempFiles(): ActionResult ); } + /** + * {@inheritDoc} + */ + public function repairOsIntegrity(): ActionResult + { + $adminCheck = $this->processRunner->run(['net', 'session'], 5); + if (! $adminCheck->successful) { + return new ActionResult( + success: false, + message: 'messages.common.permission_denied', + details: ['driver' => 'Windows'], + ); + } + + $sfcResult = $this->processRunner->run(['sfc', '/scannow'], 300); + $dismResult = $this->processRunner->run(['DISM', '/Online', '/Cleanup-Image', '/RestoreHealth'], 300); + + $combinedOutput = $this->normalizeConsoleOutput($sfcResult->output . ' ' . $dismResult->output); + $succeeded = $sfcResult->successful && $dismResult->successful; + + return new ActionResult( + success: $succeeded, + message: $succeeded ? 'messages.maintenance.repair_success' : 'messages.maintenance.repair_failed', + details: [ + 'commands_executed' => [ + 'sfc /scannow', + 'DISM /Online /Cleanup-Image /RestoreHealth', + ], + 'output' => $combinedOutput !== '' ? $this->truncateLogMessage($combinedOutput, 110) : 'Completed', + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getPendingUpdates(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$results = @(); +try { + $session = New-Object -ComObject Microsoft.Update.Session; + $searcher = $session.CreateUpdateSearcher(); + $searchResult = $searcher.Search("IsInstalled=0 and Type='Software'"); + foreach ($upd in $searchResult.Updates) { + $kb = if ($upd.KBArticleIDs.Count -gt 0) { "KB" + ($upd.KBArticleIDs | Select-Object -First 1) } else { "Update" }; + $results += [PSCustomObject]@{ + Package = [string]$upd.Title; + Version = [string]$kb; + Source = 'Windows Update'; + Status = if ($upd.IsDownloaded) { 'Downloaded (Pending Install)' } else { 'Available' } + }; + } +} catch {} + +if ($results.Count -eq 0) { + $hotfixes = @(Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 5); + foreach ($hf in $hotfixes) { + $installedDate = if ($hf.InstalledOn -is [DateTime]) { $hf.InstalledOn.ToString('yyyy-MM-dd') } else { 'Installed' }; + $results += [PSCustomObject]@{ + Package = [string]($hf.Description + ' (' + $hf.HotFixID + ')'); + Version = [string]$hf.HotFixID; + Source = 'Get-HotFix'; + Status = "Installed ($installedDate)" + }; + } +} +$results | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script, 45)); + + $updates = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['Package'])) { + continue; + } + + $updates[] = [ + 'package' => $this->truncateLogMessage((string) $item['Package'], 65), + 'version' => trim((string) ($item['Version'] ?? '-')), + 'source' => trim((string) ($item['Source'] ?? 'Windows Update')), + 'status' => trim((string) ($item['Status'] ?? 'Available')), + ]; + } + + return $updates; + } + + /** + * {@inheritDoc} + */ + public function getScheduledTasks(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +@(Get-ScheduledTask | Where-Object { $_.State -ne 'Disabled' -and $_.TaskPath -notlike '\Microsoft\*' } | Select-Object -First 25 | ForEach-Object { + $info = Get-ScheduledTaskInfo -TaskName $_.TaskName -TaskPath $_.TaskPath -ErrorAction SilentlyContinue; + $nextRun = if ($null -ne $info -and $info.NextRunTime -is [DateTime] -and $info.NextRunTime.Year -gt 2000) { $info.NextRunTime.ToString('yyyy-MM-dd HH:mm') } else { '-' }; + [PSCustomObject]@{ + TaskName = [string]$_.TaskName; + TaskPath = [string]$_.TaskPath; + NextRun = [string]$nextRun; + State = [string]$_.State + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $tasks = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['TaskName'])) { + continue; + } + + $tasks[] = [ + 'name' => trim((string) $item['TaskName']), + 'schedule' => trim((string) ($item['TaskPath'] ?? '\\')), + 'next_run' => trim((string) ($item['NextRun'] ?? '-')), + 'status' => trim((string) ($item['State'] ?? 'Ready')), + ]; + } + + return $tasks; + } + + /** + * {@inheritDoc} + */ + public function runSecurityAudit(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$fw = @(Get-NetFirewallProfile -ErrorAction SilentlyContinue | ForEach-Object { + "$($_.Name): " + ($(if ($_.Enabled) { 'ON' } else { 'OFF' })) +}); +$fwAllOn = @(Get-NetFirewallProfile -ErrorAction SilentlyContinue | Where-Object { -not $_.Enabled }).Count -eq 0 -and $fw.Count -gt 0; + +$mp = Get-MpComputerStatus -ErrorAction SilentlyContinue; +$avEnabled = if ($null -ne $mp) { [bool]$mp.AntivirusEnabled } else { $false }; +$rtpEnabled = if ($null -ne $mp) { [bool]$mp.RealTimeProtectionEnabled } else { $false }; + +$uac = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'EnableLUA' -ErrorAction SilentlyContinue).EnableLUA; +$uacEnabled = ($uac -eq 1); + +[PSCustomObject]@{ + FirewallAllOn = [bool]$fwAllOn; + FirewallSummary = [string]($fw -join ', '); + AvEnabled = [bool]$avEnabled; + RtpEnabled = [bool]$rtpEnabled; + UacEnabled = [bool]$uacEnabled +} | ConvertTo-Json -Compress +PS; + + $data = $this->runPowerShellJson($script); + + $fwOn = (bool) ($data['FirewallAllOn'] ?? false); + $avOn = (bool) ($data['AvEnabled'] ?? false) && (bool) ($data['RtpEnabled'] ?? false); + $uacOn = (bool) ($data['UacEnabled'] ?? false); + + return [ + [ + 'component' => 'Windows Defender Firewall', + 'status' => $fwOn ? 'ENABLED' : 'WARNING', + 'icon' => $fwOn ? '✅' : '⚠️', + 'details' => trim((string) ($data['FirewallSummary'] ?? '')) ?: ($fwOn ? 'All profiles active' : 'One or more profiles disabled'), + ], + [ + 'component' => 'Microsoft Defender Antivirus', + 'status' => $avOn ? 'PROTECTED' : 'WARNING', + 'icon' => $avOn ? '✅' : '⚠️', + 'details' => sprintf( + 'AV: %s | Real-Time Protection: %s', + ! empty($data['AvEnabled']) ? 'ON' : 'OFF', + ! empty($data['RtpEnabled']) ? 'ON' : 'OFF' + ), + ], + [ + 'component' => 'User Account Control (UAC)', + 'status' => $uacOn ? 'ENABLED' : 'DISABLED', + 'icon' => $uacOn ? '✅' : '❌', + 'details' => $uacOn ? 'EnableLUA = 1 (Active)' : 'EnableLUA = 0 (Disabled)', + ], + ]; + } + + /** + * {@inheritDoc} + */ + public function getLocalUsersAudit(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$admins = @(Get-LocalGroupMember -SID 'S-1-5-32-544' -ErrorAction SilentlyContinue | ForEach-Object { + ($_.Name -split '\\')[-1].ToLower() +}); +@(Get-LocalUser -ErrorAction SilentlyContinue | ForEach-Object { + $isAdm = $admins -contains $_.Name.ToLower(); + $lastLogon = if ($_.LastLogon -is [DateTime] -and $_.LastLogon.Year -gt 2000) { $_.LastLogon.ToString('yyyy-MM-dd HH:mm') } else { 'Never' }; + [PSCustomObject]@{ + Name = [string]$_.Name; + Enabled = [bool]$_.Enabled; + IsAdmin = [bool]$isAdm; + LastLogon = [string]$lastLogon + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $users = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['Name'])) { + continue; + } + + $enabled = ! empty($item['Enabled']); + $isAdmin = ! empty($item['IsAdmin']); + + $users[] = [ + 'username' => trim((string) $item['Name']), + 'status' => $enabled ? '✅ Enabled' : '⚪ Disabled', + 'is_admin' => $isAdmin ? '⚠️ YES (Administrator)' : 'No', + 'last_logon' => trim((string) ($item['LastLogon'] ?? '-')), + ]; + } + + return $users; + } + + /** + * {@inheritDoc} + */ + public function getNetworkShares(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +@(Get-SmbShare -ErrorAction SilentlyContinue | ForEach-Object { + [PSCustomObject]@{ + Name = [string]$_.Name; + Path = [string]$_.Path; + ShareType = [string]$_.ShareType; + Description = [string]$_.Description + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $shares = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['Name'])) { + continue; + } + + $shares[] = [ + 'name' => trim((string) $item['Name']), + 'path' => trim((string) ($item['Path'] ?? '-')) ?: '-', + 'type' => 'SMB (' . (trim((string) ($item['ShareType'] ?? 'FileSystemVolume')) ?: 'Disk') . ')', + 'description' => trim((string) ($item['Description'] ?? '-')) ?: '-', + ]; + } + + return $shares; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultBrowserCachePaths(): array + { + $localAppData = (string) (getenv('LOCALAPPDATA') ?: ((getenv('USERPROFILE') ?: 'C:\\Users\\Default') . '\\AppData\\Local')); + + $paths = [ + 'Google Chrome (Cache)' => $localAppData . '\\Google\\Chrome\\User Data\\Default\\Cache\\Cache_Data', + 'Google Chrome (Code Cache)' => $localAppData . '\\Google\\Chrome\\User Data\\Default\\Code Cache', + 'Microsoft Edge (Cache)' => $localAppData . '\\Microsoft\\Edge\\User Data\\Default\\Cache\\Cache_Data', + 'Microsoft Edge (Code Cache)' => $localAppData . '\\Microsoft\\Edge\\User Data\\Default\\Code Cache', + ]; + + $firefoxProfilesDir = $localAppData . '\\Mozilla\\Firefox\\Profiles'; + if (is_dir($firefoxProfilesDir) && is_readable($firefoxProfilesDir)) { + foreach (glob($firefoxProfilesDir . '\\*\\cache2\\entries') ?: [] as $idx => $ffCache) { + $paths['Mozilla Firefox (Profile ' . ($idx + 1) . ')'] = $ffCache; + } + } + + return $paths; + } + + /** + * {@inheritDoc} + */ + protected function readHostsFileContent(): ?string + { + $systemRoot = (string) (getenv('SystemRoot') ?: 'C:\\Windows'); + $hostsPath = $systemRoot . '\\System32\\drivers\\etc\\hosts'; + + return $this->processRunner->readFile($hostsPath); + } + + /** + * {@inheritDoc} + */ + protected function getDriverLabel(): string + { + return 'Windows'; + } + /** * Execute a PowerShell script safely with UTF-8 output encoding. */ diff --git a/lang/en/messages.php b/lang/en/messages.php index 16d8146..1901db8 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -35,6 +35,7 @@ 'printers' => '🖨 Printers & Spooler Management', 'network' => '🌐 Network & Connectivity Diagnostics', 'maintenance' => '🧹 System Maintenance & Cleanup', + 'security' => '🛡 Security & Access Auditing', 'reports' => '📄 Export Diagnostic Report', 'self_update' => '⬆️ Check for Updates (self:update)', 'language' => '🌍 Switch Language (EN / PT-BR)', @@ -61,6 +62,15 @@ '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)', + 'maintenance_browsers' => 'Clean Browser Caches — Chrome, Edge & Firefox (maintenance:browsers)', + 'maintenance_large_files' => 'Find Top 15 Largest Files on Disk (maintenance:large-files)', + 'maintenance_repair' => 'Verify & Repair OS System Integrity — SFC/DISM/Packages (maintenance:repair)', + 'maintenance_updates' => 'Inspect Pending OS Patches & Package Updates (maintenance:updates)', + 'maintenance_scheduler' => 'Inspect Active Scheduled Tasks, Cron & Timers (maintenance:scheduler)', + 'security_audit' => 'Unified Security Posture Audit — Firewall, AV & UAC/SSH (security:audit)', + 'security_users' => 'Audit Local User Accounts & Admin/Sudo Privileges (security:users)', + 'security_shares' => 'Inspect Active Network Shares — SMB, Samba & NFS (security:shares)', + 'security_hosts' => 'Audit System Hosts File & Custom Domain Redirects (security:hosts)', 'report_export' => 'Export Full System Diagnostic Report (report:export)', ], ], @@ -101,6 +111,15 @@ '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...', + 'maintenance_repair' => 'Running OS integrity verification and repair (this may take several minutes)...', + 'maintenance_large_files' => 'Scanning directory tree for the largest files...', + 'maintenance_browsers' => 'Cleaning Chrome, Edge, and Firefox cache directories safely...', + 'maintenance_updates' => 'Querying pending OS patches and package updates...', + 'maintenance_scheduler' => 'Enumerating active scheduled tasks, cron jobs, and systemd timers...', + 'security_audit' => 'Evaluating firewall, antivirus/MAC, and privilege elevation policies...', + 'security_users' => 'Auditing local user accounts and Administrator/sudo memberships...', + 'security_shares' => 'Querying active SMB, Samba, and NFS network shares...', + 'security_hosts' => 'Inspecting system hosts file for custom domain mappings...', 'report_export' => 'Generating full diagnostic report...', 'self_update_check' => 'Checking GitHub Releases for newer versions...', 'self_update_download' => 'Downloading and installing update v:version...', @@ -343,6 +362,36 @@ 'confirm_clean' => 'Are you sure you want to clean temporary directories (%TEMP%, /tmp, caches)? Locked files in use will be skipped.', 'clean_success' => 'Temporary directories cleaned and DNS cache flushed successfully.', 'clean_failed' => 'Failed to complete temporary files cleanup.', + 'repair_section' => 'OS System Files & Package Integrity Verification', + 'confirm_repair' => 'This will run OS integrity checks (SFC & DISM on Windows; dpkg/rpm/pacman audit on Linux). Proceed?', + 'repair_success' => 'OS integrity verification and package audit completed successfully.', + 'repair_failed' => 'OS integrity repair encountered errors or requires elevated privileges.', + 'large_files_section' => 'Top Largest Files Disk Space Analyzer', + 'no_large_files' => 'No readable files found in the target directory.', + 'large_files_headers' => [ + 'size' => 'File Size', + 'modified' => 'Last Modified', + 'path' => 'Full File Path', + ], + 'browsers_section' => 'Web Browser Cache Cleanup (Chrome, Edge, Firefox)', + 'confirm_browsers_clean' => 'This will clean ONLY temporary browser cache files (passwords, history, cookies, and bookmarks are preserved). Proceed?', + 'browsers_clean_success' => 'Browser cache directories cleaned safely.', + 'updates_section' => 'Pending OS & Package Updates', + 'no_pending_updates' => 'System is up to date. No pending updates found.', + 'updates_headers' => [ + 'package' => 'Package / Update Title', + 'version' => 'Version / KB', + 'source' => 'Provider / Repo', + 'status' => 'State', + ], + 'scheduler_section' => 'Active Scheduled Tasks, Cron Jobs & Systemd Timers', + 'no_scheduled_tasks' => 'No active non-system scheduled tasks or timers found.', + 'scheduler_headers' => [ + 'name' => 'Task / Timer Name', + 'schedule' => 'Trigger / Path', + 'next_run' => 'Next Run / Account', + 'status' => 'State', + ], 'details_labels' => [ 'deleted_files' => 'Deleted Items', 'skipped_locked_files' => 'Skipped (In Use / Locked)', @@ -365,7 +414,7 @@ 'state' => 'Connection State', 'ssid' => 'Network SSID', 'bssid' => 'Access Point BSSID', - 'signal' => 'Signal Quality', + 'signal' => 'Signal / Quality', 'channel' => 'Radio Channel', 'band' => 'Frequency / Radio Band', 'rx_rate' => 'Receive Rate (RX)', @@ -383,13 +432,50 @@ 'isp' => 'ISP / Organization (ASN)', 'reverse_hostname' => 'Reverse Hostname', 'process_name' => 'Process Name', - 'signal' => 'Signal / Quality', 'battery_status' => 'Power / Charging State', 'charge_percent' => 'Current Charge (%)', 'design_capacity' => 'Design Capacity', 'full_charge_capacity' => 'Full Charge Capacity', 'battery_health' => 'Battery Health & Wear', 'cycle_count' => 'Charge Cycle Count', + 'browsers_cleaned' => 'Browsers Processed', + ], + ], + + 'security' => [ + 'audit_section' => 'Unified Security Posture Audit (Firewall, Antivirus/MAC & Privilege Policy)', + 'audit_headers' => [ + 'component' => 'Security Component', + 'status' => 'Posture', + 'details' => 'Configuration Details', + ], + 'users_section' => 'Local User Accounts & Administrative Privilege Audit', + 'no_users_found' => 'No local user accounts returned by the system driver.', + 'users_headers' => [ + 'username' => 'Account / UID', + 'status' => 'Account State', + 'is_admin' => 'Admin / Sudoer', + 'last_logon' => 'Last Logon / Shell', + ], + 'shares_section' => 'Active Network Shares (SMB / Samba / NFS)', + 'no_shares_found' => 'No active network shares exposed on this system.', + 'shares_headers' => [ + 'name' => 'Share Name', + 'path' => 'Local Path', + 'type' => 'Protocol', + 'description' => 'Permissions / Comment', + ], + 'hosts_section' => 'System Hosts File Inspector (/etc/hosts)', + 'no_hosts_entries' => 'No active host mappings found in the system hosts file.', + 'hosts_headers' => [ + 'ip' => 'Target IP Address', + 'host' => 'Mapped Domain / Hostname', + 'status' => 'Classification', + ], + 'hosts_states' => [ + 'standard' => 'Standard Loopback', + 'custom_local' => 'Custom Local Override', + 'external_redirect' => 'Alert: Non-Standard External Redirect', ], ], diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index 7c6313e..84176b8 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -35,6 +35,7 @@ 'printers' => '🖨 Impressoras & Spooler', 'network' => '🌐 Rede & Conectividade', 'maintenance' => '🧹 Limpeza & Manutenção', + 'security' => '🛡 Segurança & Auditoria de Acesso', 'reports' => '📄 Exportar Relatório de Atendimento', 'self_update' => '⬆️ Verificar Atualizações (self:update)', 'language' => '🌍 Alterar Idioma (EN / PT-BR)', @@ -61,6 +62,15 @@ '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)', + 'maintenance_browsers' => 'Limpar Cache de Navegadores — Chrome, Edge e Firefox (maintenance:browsers)', + 'maintenance_large_files' => 'Localizar os 15 Maiores Arquivos no Disco (maintenance:large-files)', + 'maintenance_repair' => 'Verificar e Reparar Integridade do SO — SFC/DISM/Pacotes (maintenance:repair)', + 'maintenance_updates' => 'Inspecionar Atualizações Pendentes do SO e Pacotes (maintenance:updates)', + 'maintenance_scheduler' => 'Inspecionar Tarefas Agendadas, Cron e Timers (maintenance:scheduler)', + 'security_audit' => 'Auditoria Unificada de Segurança — Firewall, AV e UAC/SSH (security:audit)', + 'security_users' => 'Auditar Usuários Locais e Privilégios Admin/Sudo (security:users)', + 'security_shares' => 'Inspecionar Compartilhamentos Ativos — SMB, Samba e NFS (security:shares)', + 'security_hosts' => 'Auditar Arquivo Hosts e Redirecionamentos de Domínio (security:hosts)', 'report_export' => 'Exportar Relatório Completo de Diagnóstico (report:export)', ], ], @@ -101,6 +111,15 @@ '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...', + 'maintenance_repair' => 'Executando verificação e reparo de integridade do SO (pode levar alguns minutos)...', + 'maintenance_large_files' => 'Varrendo árvore de diretórios em busca dos maiores arquivos...', + 'maintenance_browsers' => 'Limpando diretórios de cache do Chrome, Edge e Firefox com segurança...', + 'maintenance_updates' => 'Consultando atualizações pendentes do SO e pacotes...', + 'maintenance_scheduler' => 'Enumerando tarefas agendadas ativas, cron jobs e systemd timers...', + 'security_audit' => 'Avaliando políticas de firewall, antivírus/MAC e elevação de privilégios...', + 'security_users' => 'Auditando contas de usuários locais e grupos Administradores/sudo...', + 'security_shares' => 'Consultando compartilhamentos de rede SMB, Samba e NFS ativos...', + 'security_hosts' => 'Inspecionando arquivo hosts do sistema por mapeamentos customizados...', 'report_export' => 'Gerando relatório completo de diagnóstico...', 'self_update_check' => 'Consultando GitHub Releases por novas versões...', 'self_update_download' => 'Baixando e instalando atualização v:version...', @@ -343,6 +362,36 @@ 'confirm_clean' => 'Tem certeza de que deseja limpar os diretórios temporários (%TEMP%, /tmp, caches)? Arquivos em uso serão ignorados com segurança.', 'clean_success' => 'Diretórios temporários limpos e cache DNS atualizado com sucesso.', 'clean_failed' => 'Falha ao concluir a limpeza de arquivos temporários.', + 'repair_section' => 'Verificação de Integridade de Arquivos e Pacotes do SO', + 'confirm_repair' => 'Isto executará verificações de integridade do SO (SFC & DISM no Windows; auditoria dpkg/rpm/pacman no Linux). Deseja prosseguir?', + 'repair_success' => 'Verificação de integridade do SO e auditoria de pacotes concluídas com sucesso.', + 'repair_failed' => 'O reparo de integridade encontrou erros ou requer privilégios elevados.', + 'large_files_section' => 'Analisador de Espaço dos Maiores Arquivos em Disco', + 'no_large_files' => 'Nenhum arquivo legível encontrado no diretório informado.', + 'large_files_headers' => [ + 'size' => 'Tamanho', + 'modified' => 'Última Modificação', + 'path' => 'Caminho Completo do Arquivo', + ], + 'browsers_section' => 'Limpeza de Cache de Navegadores Web (Chrome, Edge, Firefox)', + 'confirm_browsers_clean' => 'Isto limpará APENAS arquivos temporários de cache dos navegadores (senhas, histórico, cookies e favoritos serão preservados). Deseja prosseguir?', + 'browsers_clean_success' => 'Diretórios de cache dos navegadores limpos com segurança.', + 'updates_section' => 'Atualizações Pendentes do SO e Pacotes', + 'no_pending_updates' => 'O sistema está atualizado. Nenhuma atualização pendente encontrada.', + 'updates_headers' => [ + 'package' => 'Pacote / Atualização', + 'version' => 'Versão / KB', + 'source' => 'Origem / Repositório', + 'status' => 'Estado', + ], + 'scheduler_section' => 'Tarefas Agendadas Ativas, Cron Jobs & Systemd Timers', + 'no_scheduled_tasks' => 'Nenhuma tarefa agendada não-sistema ou timer ativo encontrado.', + 'scheduler_headers' => [ + 'name' => 'Nome da Tarefa / Timer', + 'schedule' => 'Gatilho / Caminho', + 'next_run' => 'Próxima Execução / Conta', + 'status' => 'Estado', + ], 'details_labels' => [ 'deleted_files' => 'Itens Removidos', 'skipped_locked_files' => 'Ignorados (Em Uso / Bloqueados)', @@ -365,7 +414,7 @@ 'state' => 'Estado da Conexão', 'ssid' => 'SSID da Rede', 'bssid' => 'BSSID do Ponto de Acesso', - 'signal' => 'Qualidade do Sinal', + 'signal' => 'Sinal / Qualidade', 'channel' => 'Canal de Rádio', 'band' => 'Frequência / Banda', 'rx_rate' => 'Taxa de Recepção (RX)', @@ -383,13 +432,50 @@ 'isp' => 'Provedor / Organização (ASN)', 'reverse_hostname' => 'Hostname Reverso', 'process_name' => 'Nome do Processo', - 'signal' => 'Sinal / Qualidade', 'battery_status' => 'Estado de Energia / Carga', 'charge_percent' => 'Carga Atual (%)', 'design_capacity' => 'Capacidade Projetada', 'full_charge_capacity' => 'Capacidade Total Atual', 'battery_health' => 'Saúde e Desgaste da Bateria', 'cycle_count' => 'Contagem de Ciclos', + 'browsers_cleaned' => 'Navegadores Processados', + ], + ], + + 'security' => [ + 'audit_section' => 'Auditoria Unificada de Segurança (Firewall, Antivírus/MAC & Política de Privilégios)', + 'audit_headers' => [ + 'component' => 'Componente de Segurança', + 'status' => 'Postura', + 'details' => 'Detalhes da Configuração', + ], + 'users_section' => 'Auditoria de Contas de Usuários Locais & Privilégios Administrativos', + 'no_users_found' => 'Nenhuma conta de usuário local retornada pelo driver do sistema.', + 'users_headers' => [ + 'username' => 'Conta / UID', + 'status' => 'Estado da Conta', + 'is_admin' => 'Admin / Sudoer', + 'last_logon' => 'Último Logon / Shell', + ], + 'shares_section' => 'Compartilhamentos de Rede Ativos (SMB / Samba / NFS)', + 'no_shares_found' => 'Nenhum compartilhamento de rede ativo exposto neste sistema.', + 'shares_headers' => [ + 'name' => 'Nome do Compartilhamento', + 'path' => 'Caminho Local', + 'type' => 'Protocolo', + 'description' => 'Permissões / Comentário', + ], + 'hosts_section' => 'Inspetor do Arquivo Hosts do Sistema (/etc/hosts)', + 'no_hosts_entries' => 'Nenhum mapeamento de host ativo encontrado no arquivo hosts.', + 'hosts_headers' => [ + 'ip' => 'Endereço IP Alvo', + 'host' => 'Domínio / Hostname Mapeado', + 'status' => 'Classificação', + ], + 'hosts_states' => [ + 'standard' => 'Loopback Padrão', + 'custom_local' => 'Redirecionamento Local Customizado', + 'external_redirect' => 'Alerta: Redirecionamento Externo Não-Padrão', ], ], diff --git a/tests/Feature/ReportExporterTest.php b/tests/Feature/ReportExporterTest.php index ad51d93..18805bd 100644 --- a/tests/Feature/ReportExporterTest.php +++ b/tests/Feature/ReportExporterTest.php @@ -186,6 +186,51 @@ public function cleanTempFiles(): ActionResult { return new ActionResult(true, 'messages.maintenance.clean_success'); } + + public function repairOsIntegrity(): ActionResult + { + return new ActionResult(true, 'messages.maintenance.repair_success'); + } + + public function findLargeFiles(?string $directory = null, int $limit = 15): array + { + return []; + } + + public function cleanBrowserCaches(?array $customCachePaths = null): ActionResult + { + return new ActionResult(true, 'messages.maintenance.browsers_clean_success'); + } + + public function getPendingUpdates(): array + { + return []; + } + + public function getScheduledTasks(): array + { + return []; + } + + public function runSecurityAudit(): array + { + return []; + } + + public function getLocalUsersAudit(): array + { + return []; + } + + public function getNetworkShares(): array + { + return []; + } + + public function inspectHostsFile(?string $customContent = null): array + { + return []; + } }; $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_test_' . uniqid(); diff --git a/tests/Unit/HealthCheckServiceTest.php b/tests/Unit/HealthCheckServiceTest.php index b03e74c..45012dd 100644 --- a/tests/Unit/HealthCheckServiceTest.php +++ b/tests/Unit/HealthCheckServiceTest.php @@ -178,6 +178,51 @@ public function cleanTempFiles(): ActionResult { return new ActionResult(true, 'ok'); } + + public function repairOsIntegrity(): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function findLargeFiles(?string $directory = null, int $limit = 15): array + { + return []; + } + + public function cleanBrowserCaches(?array $customCachePaths = null): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function getPendingUpdates(): array + { + return []; + } + + public function getScheduledTasks(): array + { + return []; + } + + public function runSecurityAudit(): array + { + return []; + } + + public function getLocalUsersAudit(): array + { + return []; + } + + public function getNetworkShares(): array + { + return []; + } + + public function inspectHostsFile(?string $customContent = null): array + { + return []; + } }; } diff --git a/tests/Unit/LinuxDriverTest.php b/tests/Unit/LinuxDriverTest.php index f34d8d2..a492779 100644 --- a/tests/Unit/LinuxDriverTest.php +++ b/tests/Unit/LinuxDriverTest.php @@ -296,3 +296,86 @@ public function getEffectiveUid(): int expect($killByName->success)->toBeTrue() ->and($killByName->details['process_name'])->toBe('firefox'); }); + +it('executes Linux package integrity audit, pending APT updates, cron/systemd scheduler, security posture audit, local users, and Samba/NFS shares', function (): void { + $executor = new class implements ProcessExecutorInterface + { + /** @var array */ + public array $files = [ + '/etc/crontab' => "0 3 * * * root /usr/local/bin/backup.sh\n", + '/sys/module/apparmor/parameters/enabled' => "Y\n", + '/etc/ssh/sshd_config' => "PermitRootLogin no\n", + '/etc/passwd' => "root:x:0:0:root:/root:/bin/bash\nadminuser:x:1000:1000:Admin:/home/adminuser:/bin/bash\nwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologin\n", + '/etc/group' => "sudo:x:27:adminuser\n", + '/etc/samba/smb.conf' => "[global]\nworkgroup = WORKGROUP\n[ projects ]\npath = /srv/samba/projects\ncomment = Engineering Files\n", + '/etc/exports' => "/srv/nfs/backups 192.168.1.0/24(rw,sync,no_subtree_check)\n", + ]; + + public function run(array $command, int $timeout = 30): ProcessResult + { + return match ($command) { + ['which', 'dpkg'] => new ProcessResult(0, '/usr/bin/dpkg'), + ['dpkg', '--audit'] => new ProcessResult(0, ''), + ['which', 'apt-get'] => new ProcessResult(0, '/usr/bin/apt-get'), + ['apt-get', 'check'] => new ProcessResult(0, ''), + ['which', 'apt'] => new ProcessResult(0, '/usr/bin/apt'), + ['apt', 'list', '--upgradable'] => new ProcessResult( + 0, + "Listing... Done\nopenssl/noble-security 3.0.13-0ubuntu3.4 amd64 [upgradable from: 3.0.13-0ubuntu3.1]\n" + ), + ['systemctl', 'list-timers', '--no-pager', '--no-legend'] => new ProcessResult( + 0, + "Thu 2026-11-19 06:00:00 UTC 14h left apt-daily.timer apt-daily.service\n" + ), + ['which', 'ufw'] => new ProcessResult(0, '/usr/sbin/ufw'), + ['ufw', 'status'] => new ProcessResult(0, "Status: active\n"), + ['which', 'getenforce'] => new ProcessResult(1, '', '', false), + default => new ProcessResult(1, '', '', false), + }; + } + + public function readFile(string $path): ?string + { + return $this->files[$path] ?? null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new LinuxDriver($executor); + + $repair = $driver->repairOsIntegrity(); + expect($repair->success)->toBeTrue() + ->and($repair->details['commands_executed'])->toContain('dpkg --audit', 'apt-get check'); + + $updates = $driver->getPendingUpdates(); + expect($updates)->toHaveCount(1) + ->and($updates[0]['package'])->toBe('openssl') + ->and($updates[0]['version'])->toBe('3.0.13-0ubuntu3.4'); + + $tasks = $driver->getScheduledTasks(); + expect($tasks)->toHaveCount(2) + ->and($tasks[0]['name'])->toBe('/usr/local/bin/backup.sh') + ->and($tasks[1]['name'])->toBe('apt-daily.timer'); + + $security = $driver->runSecurityAudit(); + expect($security)->toHaveCount(3) + ->and($security[0]['status'])->toBe('ENABLED') + ->and($security[1]['status'])->toBe('PROTECTED') + ->and($security[2]['status'])->toBe('HARDENED'); + + $users = $driver->getLocalUsersAudit(); + expect($users)->toHaveCount(2) + ->and($users[0]['username'])->toContain('root') + ->and($users[1]['username'])->toContain('adminuser') + ->and($users[1]['is_admin'])->toContain('YES'); + + $shares = $driver->getNetworkShares(); + expect($shares)->toHaveCount(2) + ->and($shares[0]['name'])->toBe('projects') + ->and($shares[0]['type'])->toBe('Samba (SMB)') + ->and($shares[1]['type'])->toBe('NFS Export'); +}); diff --git a/tests/Unit/WindowsDriverTest.php b/tests/Unit/WindowsDriverTest.php index 2094c0f..cf61795 100644 --- a/tests/Unit/WindowsDriverTest.php +++ b/tests/Unit/WindowsDriverTest.php @@ -398,3 +398,130 @@ public function getEffectiveUid(): int ->and($pathAudit['summary']['broken'])->toBe(1) ->and($pathAudit['summary']['duplicate'])->toBe(1); }); + +it('executes Windows OS repair, pending updates, scheduled tasks, security audit, users audit, SMB shares, large files, browser cache cleanup, and hosts inspection', 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, 'Admin OK'), // net session + 2 => new ProcessResult(0, 'Windows Resource Protection did not find any integrity violations.'), // sfc + 3 => new ProcessResult(0, 'The restore operation completed successfully.'), // DISM + 4 => new ProcessResult(0, (string) json_encode([ + [ + 'Package' => '2026-11 Cumulative Update for Windows 11 (KB5046617)', + 'Version' => 'KB5046617', + 'Source' => 'Windows Update', + 'Status' => 'Available', + ], + ])), + 5 => new ProcessResult(0, (string) json_encode([ + [ + 'TaskName' => 'GoogleUpdateTaskMachineCore', + 'TaskPath' => '\\GoogleSystem\\GoogleUpdater\\', + 'NextRun' => '2026-11-19 08:00', + 'State' => 'Ready', + ], + ])), + 6 => new ProcessResult(0, (string) json_encode([ + 'FirewallAllOn' => true, + 'FirewallSummary' => 'Domain: ON, Private: ON, Public: ON', + 'AvEnabled' => true, + 'RtpEnabled' => true, + 'UacEnabled' => true, + ])), + 7 => new ProcessResult(0, (string) json_encode([ + [ + 'Name' => 'Administrator', + 'Enabled' => true, + 'IsAdmin' => true, + 'LastLogon' => '2026-11-18 09:00', + ], + ])), + 8 => new ProcessResult(0, (string) json_encode([ + [ + 'Name' => 'PublicDocs', + 'Path' => 'C:\\Users\\Public\\Documents', + 'ShareType' => 'FileSystemVolume', + 'Description' => 'Shared Documents', + ], + ])), + default => new ProcessResult(0, '[]'), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new WindowsDriver($executor); + + $repair = $driver->repairOsIntegrity(); + expect($repair->success)->toBeTrue() + ->and($repair->details['commands_executed'])->toContain('sfc /scannow', 'DISM /Online /Cleanup-Image /RestoreHealth'); + + $updates = $driver->getPendingUpdates(); + expect($updates)->toHaveCount(1) + ->and($updates[0]['version'])->toBe('KB5046617'); + + $tasks = $driver->getScheduledTasks(); + expect($tasks)->toHaveCount(1) + ->and($tasks[0]['name'])->toBe('GoogleUpdateTaskMachineCore'); + + $security = $driver->runSecurityAudit(); + expect($security)->toHaveCount(3) + ->and($security[0]['status'])->toBe('ENABLED') + ->and($security[1]['status'])->toBe('PROTECTED') + ->and($security[2]['status'])->toBe('ENABLED'); + + $users = $driver->getLocalUsersAudit(); + expect($users)->toHaveCount(1) + ->and($users[0]['username'])->toBe('Administrator') + ->and($users[0]['is_admin'])->toContain('YES'); + + $shares = $driver->getNetworkShares(); + expect($shares)->toHaveCount(1) + ->and($shares[0]['name'])->toBe('PublicDocs'); + + $hosts = $driver->inspectHostsFile("# Comment line\n127.0.0.1 localhost\n127.0.0.1 myapp.local\n203.0.113.55 login.bank.com\n"); + expect($hosts)->toHaveCount(3) + ->and($hosts[0]['status'])->toBe('STANDARD') + ->and($hosts[1]['status'])->toBe('CUSTOM_LOCAL') + ->and($hosts[2]['status'])->toBe('EXTERNAL_REDIRECT'); + + $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_maint_' . uniqid(); + $cacheDir = $tempDir . DIRECTORY_SEPARATOR . 'chrome_cache'; + mkdir($cacheDir, 0777, true); + file_put_contents($tempDir . DIRECTORY_SEPARATOR . 'small.bin', str_repeat('A', 128)); + file_put_contents($tempDir . DIRECTORY_SEPARATOR . 'large.bin', str_repeat('B', 2048)); + file_put_contents($cacheDir . DIRECTORY_SEPARATOR . 'data_1', str_repeat('C', 1024)); + + try { + $largeFiles = $driver->findLargeFiles($tempDir, 5); + expect($largeFiles)->not->toBeEmpty() + ->and(basename($largeFiles[0]['path']))->toBe('large.bin'); + + $browserClean = $driver->cleanBrowserCaches(['Google Chrome' => $cacheDir]); + expect($browserClean->success)->toBeTrue() + ->and($browserClean->details['deleted_files'])->toBe(1) + ->and($browserClean->details['freed_space'])->toBe('1.00 KB'); + } finally { + @unlink($tempDir . DIRECTORY_SEPARATOR . 'small.bin'); + @unlink($tempDir . DIRECTORY_SEPARATOR . 'large.bin'); + @unlink($cacheDir . DIRECTORY_SEPARATOR . 'data_1'); + @rmdir($cacheDir); + @rmdir($tempDir); + } +});