~fkooman/vpn-server-api

ref: 453cda58bae0131116fbab4e4fc686d867e87ade vpn-server-api/src/OpenVpn/DaemonSocket.php -rw-r--r-- 5.9 KiB
453cda58François Kooman allow configuring the log format for log entries to syslog, also allow logging originating client IP 9 months ago
                                                                                
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
<?php

/*
 * eduVPN - End-user friendly VPN.
 *
 * Copyright: 2016-2019, The Commons Conservancy eduVPN Programme
 * SPDX-License-Identifier: AGPL-3.0+
 */

namespace LC\Server\OpenVpn;

use RuntimeException;

class DaemonSocket
{
    /** @var resource|null */
    private $daemonSocket = null;

    /** @var string */
    private $certDir;

    /** @var bool */
    private $useTls;

    /**
     * @param string $certDir
     * @param bool   $useTls
     */
    public function __construct($certDir, $useTls)
    {
        $this->certDir = $certDir;
        $this->useTls = $useTls;
    }

    /**
     * @param string $managementIp
     *
     * @return void
     */
    public function open($managementIp)
    {
        $this->daemonSocket = self::getSocket($managementIp, $this->certDir, $this->useTls);
    }

    /**
     * @param array<int> $managementPortList
     *
     * @return void
     */
    public function setPorts(array $managementPortList)
    {
        $this->sendCommand(sprintf('SET_PORTS %s', implode(' ', $managementPortList)));
    }

    /**
     * @return array<array-key, array{common_name: string, virtual_address: array{0: string, 1: string}}>
     */
    public function connections()
    {
        $connectionList = self::parseConnectionList($this->sendCommand('LIST'));

        return $connectionList;
    }

    /**
     * @param array<string> $commonNameList
     *
     * @return void
     */
    public function disconnect(array $commonNameList)
    {
        $this->sendCommand(sprintf('DISCONNECT %s', implode(' ', $commonNameList)));
    }

    /**
     * @return void
     */
    public function close()
    {
        if (null !== $daemonSocket = $this->daemonSocket) {
            // we don't care if it fails, fail in silence...
            @fclose($daemonSocket);
        }
    }

    /**
     * @param string $managementIp
     * @param string $certDir
     * @param bool   $useTls
     *
     * @return resource
     */
    private static function getSocket($managementIp, $certDir, $useTls)
    {
        // never use TLS to connect to localhost, no matter whether useTls is
        // true...
        if (!\in_array($managementIp, ['127.0.0.1', '::1'], true) && $useTls) {
            // we MUST have a TLS cert
            // @see https://www.php.net/manual/en/context.ssl.php
            // @see https://www.php.net/manual/en/transports.inet.php
            $streamContext = stream_context_create(
                [
                    'ssl' => [
                        'verify_peer' => true,
                        'verify_peer_name' => true,
                        'peer_name' => 'vpn-daemon',
                        'cafile' => $certDir.'/ca.crt',
                        'local_cert' => $certDir.'/vpn-daemon-client.crt',
                        'local_pk' => $certDir.'/vpn-daemon-client.key',
                        'ciphers' => 'ECDHE-RSA-AES256-GCM-SHA384',
                        'disable_compression' => true,
                    ],
                ]
            );

            $socketAddress = sprintf('ssl://%s:41194', $managementIp);
            if (false === $daemonSocket = @stream_socket_client($socketAddress, $errno, $errstr, 5, STREAM_CLIENT_CONNECT, $streamContext)) {
                throw new RuntimeException(sprintf('unable to open socket to "%s": [%d]: %s', $socketAddress, $errno, $errstr));
            }

            return $daemonSocket;
        }

        $socketAddress = sprintf('tcp://%s:41194', $managementIp);
        if (false === $daemonSocket = @stream_socket_client($socketAddress, $errno, $errstr, 5, STREAM_CLIENT_CONNECT)) {
            throw new RuntimeException(sprintf('unable to open socket to "%s": [%d]: %s', $socketAddress, $errno, $errstr));
        }

        return $daemonSocket;
    }

    /**
     * @param string $socketCommand
     *
     * @return array<string>
     */
    private function sendCommand($socketCommand)
    {
        $this->writeLineToSocket(sprintf("%s\n", $socketCommand));

        return $this->handleResponse();
    }

    /**
     * @return array<string>
     */
    private function handleResponse()
    {
        $statusLine = $this->readLineFromSocket();
        if (0 !== strpos($statusLine, 'OK: ')) {
            throw new RuntimeException(sprintf('expected "OK <n>", got "%s"', $statusLine));
        }
        $resultLineCount = (int) substr($statusLine, 4);
        $resultData = [];
        for ($i = 0; $i < $resultLineCount; ++$i) {
            $resultData[] = trim($this->readLineFromSocket());
        }

        return $resultData;
    }

    /**
     * @param array<string> $connectionList
     *
     * @return array<array-key, array{management_port: int, common_name: string, virtual_address: array{0: string, 1: string}}>
     */
    private static function parseConnectionList(array $connectionList)
    {
        $clientInfoList = [];
        foreach ($connectionList as $connectionLine) {
            $clientInfo = explode(' ', $connectionLine);
            $clientInfoList[] = [
                'management_port' => (int) $clientInfo[0],
                'common_name' => $clientInfo[1],
                'virtual_address' => [$clientInfo[2], $clientInfo[3]],
            ];
        }

        return $clientInfoList;
    }

    /**
     * @param string $lineToWrite
     *
     * @return void
     */
    private function writeLineToSocket($lineToWrite)
    {
        if (null === $this->daemonSocket) {
            throw new RuntimeException('socket not open');
        }

        if (false === @fwrite($this->daemonSocket, $lineToWrite)) {
            throw new RuntimeException('unable to WRITE to socket');
        }
    }

    /**
     * @return string
     */
    private function readLineFromSocket()
    {
        if (null === $this->daemonSocket) {
            throw new RuntimeException('socket not open');
        }

        if (false === $responseData = @fgets($this->daemonSocket)) {
            throw new RuntimeException('unable to READ from socket');
        }

        return $responseData;
    }
}