|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Startwind\Inventorio\Collector\System\Security; |
|
4
|
|
|
|
|
5
|
|
|
use Startwind\Inventorio\Collector\Collector; |
|
6
|
|
|
|
|
7
|
|
|
class KnownHostsCollector implements Collector |
|
8
|
|
|
{ |
|
9
|
|
|
public function getIdentifier(): string |
|
10
|
|
|
{ |
|
11
|
|
|
return 'known-hosts-all-users'; |
|
12
|
|
|
} |
|
13
|
|
|
|
|
14
|
|
|
public function collect(): array |
|
15
|
|
|
{ |
|
16
|
|
|
$results = []; |
|
17
|
|
|
|
|
18
|
|
|
// Read all user accounts from /etc/passwd |
|
19
|
|
|
$passwdLines = file('/etc/passwd', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); |
|
20
|
|
|
|
|
21
|
|
|
foreach ($passwdLines as $line) { |
|
22
|
|
|
$parts = explode(':', $line); |
|
23
|
|
|
if (count($parts) < 6) { |
|
24
|
|
|
continue; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
// Extract username, UID, and home directory |
|
28
|
|
|
[$username, , $uid, , , $homeDirectory] = array_slice($parts, 0, 6); |
|
29
|
|
|
|
|
30
|
|
|
// Only consider regular users (UID >= 1000) with a valid home directory |
|
31
|
|
|
if ((int)$uid < 1000 || !is_dir($homeDirectory)) { |
|
32
|
|
|
continue; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
$knownHostsPath = $homeDirectory . '/.ssh/known_hosts'; |
|
36
|
|
|
|
|
37
|
|
|
// If known_hosts exists, parse it |
|
38
|
|
|
if (!file_exists($knownHostsPath)) { |
|
39
|
|
|
continue; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$entries = $this->parseKnownHostsFile($knownHostsPath, $username); |
|
43
|
|
|
|
|
44
|
|
|
// Merge entries into the final result list |
|
45
|
|
|
$results = array_merge($results, $entries); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return $results; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Parse a known_hosts file and return structured entries including username. |
|
53
|
|
|
* |
|
54
|
|
|
* @param string $filePath Path to the known_hosts file |
|
55
|
|
|
* @param string $username The user who owns the file |
|
56
|
|
|
* @return array List of structured known host entries |
|
57
|
|
|
*/ |
|
58
|
|
|
private function parseKnownHostsFile(string $filePath, string $username): array |
|
59
|
|
|
{ |
|
60
|
|
|
$entries = []; |
|
61
|
|
|
|
|
62
|
|
|
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); |
|
63
|
|
|
|
|
64
|
|
|
foreach ($lines as $line) { |
|
65
|
|
|
$parts = preg_split('/\s+/', $line); |
|
66
|
|
|
|
|
67
|
|
|
// Process only lines with at least host, key type, and key |
|
68
|
|
|
if (count($parts) >= 3) { |
|
69
|
|
|
$entries[] = [ |
|
70
|
|
|
'user' => $username, |
|
71
|
|
|
'host' => $parts[0], |
|
72
|
|
|
'key_type' => $parts[1], |
|
73
|
|
|
'key' => $parts[2], |
|
74
|
|
|
'comment' => $parts[3] ?? null |
|
75
|
|
|
]; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
return $entries; |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|