summaryrefslogtreecommitdiff
path: root/src/UfwModule.php
blob: 02be5158b4042c62d9f2c85c509e756b7d2c4289 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php

namespace PHPIAC\Modules;

use PHPIAC\Connection;
use PHPIAC\Module\Module;
use PHPIAC\Module\State;

class UfwModule extends Module
{
    protected string $rule;
    protected string $name;

    protected string $state = State::ENABLED;

    /**
     * @inheritDoc
     */
    public function checkState(): bool
    {
        $state = false;

        Connection::enablePty();

        Connection::exec('sudo ufw status');
        $status = Connection::read();

        if ($this->state === State::ENABLED) {
            $rule = strtoupper($this->rule);
            Connection::exec("sudo ufw status | grep '$this->name\|$rule'");
            $statusGrep = Connection::read();

            $state =
                str_contains($status, 'Status: active') &&
                str_contains($statusGrep, $this->name) && str_contains($statusGrep, $rule);
        }
        else if ($this->state === State::DISABLED) {
            $state = str_contains($status, 'Status: inactive');
        }

        Connection::disablePty();

        return $state;
    }

    /**
     * @inheritDoc
     */
    public function execute(): void
    {
        Connection::exec(implode(PHP_EOL, [
            "sudo ufw $this->rule $this->name",
            match ($this->state) {
                State::ENABLED => "sudo ufw --force enable",
                State::DISABLED => "sudo ufw disable",
            },
        ]));
    }
}