~fkooman/vpn-user-portal

ref: cc452cbd571f1e45ac50ffc38662dbd3fc6c3e8a vpn-user-portal/src/Http/VpnApiThreeModule.php -rw-r--r-- 9.1 KiB
cc452cbdFrançois Kooman update dependencies 2 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
<?php

declare(strict_types=1);

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

namespace LC\Portal\Http;

use DateTimeImmutable;
use fkooman\OAuth\Server\AccessToken;
use LC\Portal\CA\CaInterface;
use LC\Portal\ClientConfig;
use LC\Portal\Config;
use LC\Portal\Dt;
use LC\Portal\Http\Exception\InputValidationException;
use LC\Portal\LoggerInterface;
use LC\Portal\ProfileConfig;
use LC\Portal\RandomInterface;
use LC\Portal\Storage;
use LC\Portal\TlsCrypt;
use LC\Portal\WireGuard\Wg;

class VpnApiThreeModule implements ApiServiceModuleInterface
{
    private Config $config;
    private Storage $storage;
    private TlsCrypt $tlsCrypt;
    private RandomInterface $random;
    private CaInterface $ca;
    private Wg $wg;
    private DateTimeImmutable $dateTime;

    public function __construct(Config $config, Storage $storage, TlsCrypt $tlsCrypt, RandomInterface $random, CaInterface $ca, Wg $wg)
    {
        $this->config = $config;
        $this->storage = $storage;
        $this->tlsCrypt = $tlsCrypt;
        $this->random = $random;
        $this->ca = $ca;
        $this->wg = $wg;
        $this->dateTime = Dt::get();
    }

    public function init(ApiService $service): void
    {
        $service->get(
            '/v3/info',
            function (AccessToken $accessToken, Request $request): Response {
                $profileConfigList = $this->config->profileConfigList();
                // XXX really think about storing permissions in OAuth token!
                $userPermissions = $this->storage->getPermissionList($accessToken->userId());
                $userProfileList = [];
                foreach ($profileConfigList as $profileConfig) {
                    if ($profileConfig->hideProfile()) {
                        continue;
                    }
                    if ($profileConfig->enableAcl()) {
                        // is the user member of the aclPermissionList?
                        if (!VpnPortalModule::isMember($profileConfig->aclPermissionList(), $userPermissions)) {
                            continue;
                        }
                    }
                    $userProfileList[] = [
                        'profile_id' => $profileConfig->profileId(),
                        'display_name' => $profileConfig->displayName(),
                    ];
                }

                return new JsonResponse(
                    [
                        'info' => [
                            'profile_list' => $userProfileList,
                        ],
                    ]
                );
            }
        );

        $service->post(
            '/v3/connect',
            function (AccessToken $accessToken, Request $request): Response {
                // XXX catch InputValidationException
                $requestedProfileId = InputValidation::profileId($request->requirePostParameter('profile_id'));
                $profileConfigList = $this->config->profileConfigList();
                $userPermissions = $this->storage->getPermissionList($accessToken->userId());
                $availableProfiles = [];
                foreach ($profileConfigList as $profileConfig) {
                    if ($profileConfig->hideProfile()) {
                        continue;
                    }
                    if ($profileConfig->enableAcl()) {
                        // is the user member of the userPermissions?
                        if (!VpnPortalModule::isMember($profileConfig->aclPermissionList(), $userPermissions)) {
                            continue;
                        }
                    }

                    $availableProfiles[] = $profileConfig->profileId();
                }

                if (!\in_array($requestedProfileId, $availableProfiles, true)) {
                    return new JsonResponse(['error' => 'profile not available or no permission'], [], 400);
                }

                $profileConfig = $this->config->profileConfig($requestedProfileId);

                switch ($profileConfig->vpnType()) {
                    case 'openvpn':
                        return $this->getOpenVpnConfigResponse($profileConfig, $accessToken);
                    case 'wireguard':
                        $wgConfig = $this->wg->addPeer(
                            $profileConfig,
                            $accessToken->userId(),
                            $accessToken->clientId(),
                            $accessToken->authorizationExpiresAt(),
                            $accessToken,
                            self::validatePublicKey($request->requirePostParameter('public_key'))
                        );

                        return new Response(
                            (string) $wgConfig,
                            [
                                'Expires' => $accessToken->authorizationExpiresAt()->format(DateTimeImmutable::RFC7231),
                                'Content-Type' => 'application/x-wireguard-profile',
                            ]
                        );
                    default:
                        return new JsonResponse(['error' => 'invalid vpn_type'], [], 500);
                }
            }
        );

        $service->post(
            '/v3/disconnect',
            function (AccessToken $accessToken, Request $request): Response {
                // XXX duplicate from connect
                // XXX catch InputValidationException
                $requestedProfileId = InputValidation::profileId($request->requirePostParameter('profile_id'));
                $profileConfigList = $this->config->profileConfigList();
                $userPermissions = $this->storage->getPermissionList($accessToken->userId());
                $availableProfiles = [];
                foreach ($profileConfigList as $profileConfig) {
                    if ($profileConfig->hideProfile()) {
                        continue;
                    }
                    if ($profileConfig->enableAcl()) {
                        // is the user member of the userPermissions?
                        if (!VpnPortalModule::isMember($profileConfig->aclPermissionList(), $userPermissions)) {
                            continue;
                        }
                    }

                    $availableProfiles[] = $profileConfig->profileId();
                }

                if (!\in_array($requestedProfileId, $availableProfiles, true)) {
                    return new JsonResponse(['error' => 'profile not available or no permission'], [], 400);
                }

                $profileConfig = $this->config->profileConfig($requestedProfileId);

                if ('openvpn' === $profileConfig->vpnType()) {
                    // OpenVPN
                    $this->storage->deleteCertificatesWithAuthKey($accessToken->authKey());
                    // XXX do we also need to disconnect the client?

                    return new Response(null, [], 204);
                }

                // WireGuard
                $userId = $accessToken->userId();
                $authKey = $accessToken->authKey();
                // XXX move this to Wg class
                foreach ($this->storage->wgGetPeers($userId) as $wgPeer) {
                    if ($requestedProfileId !== $wgPeer['profile_id']) {
                        continue;
                    }
                    if ($authKey !== $wgPeer['auth_key']) {
                        continue;
                    }

                    $this->wg->removePeer(
                        $profileConfig,
                        $userId,
                        $wgPeer['public_key']
                    );
                }

                return new Response(null, [], 204);
            }
        );
    }

    /**
     * XXX want only 1 code path both for portal and for API.
     */
    private function getOpenVpnConfigResponse(ProfileConfig $profileConfig, AccessToken $accessToken): Response
    {
        $commonName = $this->random->get(16);
        $certInfo = $this->ca->clientCert($commonName, $profileConfig->profileId(), $accessToken->authorizationExpiresAt());
        $this->storage->addCertificate(
            $accessToken->userId(),
            $profileConfig->profileId(),
            $commonName,
            $accessToken->clientId(),
            $accessToken->authorizationExpiresAt(),
            $accessToken
        );

        $this->storage->addUserLog(
            $accessToken->userId(),
            LoggerInterface::NOTICE,
            sprintf('new certificate generated for "%s"', $accessToken->clientId()),
            $this->dateTime
        );

        $clientConfig = ClientConfig::get(
            $profileConfig,
            $this->ca->caCert(),
            $this->tlsCrypt,
            $certInfo,
            ClientConfig::STRATEGY_RANDOM
        );

        return new Response(
            $clientConfig,
            [
                'Expires' => $accessToken->authorizationExpiresAt()->format(DateTimeImmutable::RFC7231),
                'Content-Type' => 'application/x-openvpn-profile',
            ]
        );
    }

    private function validatePublicKey(string $publicKey): string
    {
        // XXX implement validation
        return $publicKey;
    }
}