Passed
Push — master ( 176cfe...5723e1 )
by Nils
02:36
created

KnownHostsCollector::parseKnownHostsFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 22
rs 9.8666
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