DatabaseCredentialCollector::extractCredentials()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 3
b 0
f 0
nc 8
nop 1
dl 0
loc 20
rs 9.6111
1
<?php
2
3
namespace Startwind\Inventorio\Collector\Website\WordPress;
4
5
use Startwind\Inventorio\Collector\BasicCollector;
6
use Startwind\Inventorio\Collector\InventoryAwareCollector;
7
use Startwind\Inventorio\Exec\File;
8
use Startwind\Inventorio\Util\PasswordUtil;
9
10
class DatabaseCredentialCollector extends BasicCollector implements InventoryAwareCollector
11
{
12
    private array $inventory;
13
14
    protected string $identifier = "WordPressDatabaseCredential";
15
16
    public function setInventory(array $inventory): void
17
    {
18
        $this->inventory = $inventory;
19
    }
20
21
    public function collect(): array
22
    {
23
        if (!array_key_exists(WordPressCollector::COLLECTOR_IDENTIFIER, $this->inventory)
24
            || !is_array($this->inventory[WordPressCollector::COLLECTOR_IDENTIFIER])
25
        ) return [];
26
27
        $credentials = [];
28
29
        $wordpressSites = $this->inventory[WordPressCollector::COLLECTOR_IDENTIFIER];
30
31
        foreach ($wordpressSites as $domain => $site) {
32
            $configFile = File::getInstance()->getContents($site['path'] . 'wp-config.php');
33
34
            $credentialArray = $this->extractCredentials($configFile);
35
36
            if ($credentialArray) {
37
                $credentials[$domain] = [
38
                    'passwordStrength' => PasswordUtil::evaluateStrength($credentialArray['password']),
39
                    'user' => $credentialArray['user'],
40
                ];
41
            }
42
        }
43
44
        return $credentials;
45
    }
46
47
    private function extractCredentials(string $wpConfigContent): ?array
48
    {
49
        $user = $pass = null;
50
51
        if (preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"](.*?)['\"]\s*\)/", $wpConfigContent, $matches)) {
52
            $user = $matches[1];
53
        }
54
55
        if (preg_match("/define\s*\(\s*['\"]DB_PASSWORD['\"]\s*,\s*['\"](.*?)['\"]\s*\)/", $wpConfigContent, $matches)) {
56
            $pass = $matches[1];
57
        }
58
59
        if ($user !== null && $pass !== null) {
60
            return [
61
                'user' => $user,
62
                'password' => $pass
63
            ];
64
        }
65
66
        return null;
67
    }
68
}