~fkooman/vpn-server-api

ref: 453cda58bae0131116fbab4e4fc686d867e87ade vpn-server-api/src/TlsCrypt.php -rw-r--r-- 1.7 KiB
453cda58François Kooman allow configuring the log format for log entries to syslog, also allow logging originating client IP 5 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
<?php

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

namespace LC\Server;

use LC\Common\FileIO;
use ParagonIE\ConstantTime\Hex;

class TlsCrypt
{
    /** @var string */
    private $keyDir;

    /**
     * @param string $keyDir
     */
    public function __construct($keyDir)
    {
        $this->keyDir = $keyDir;
    }

    /**
     * @param string $profileId
     *
     * @return string
     */
    public function get($profileId)
    {
        // check whether we still have global legacy "ta.key". Use it if we
        // find it...
        $globalTlsCryptKey = sprintf('%s/ta.key', $this->keyDir);
        if (@file_exists($globalTlsCryptKey)) {
            return FileIO::readFile($globalTlsCryptKey);
        }

        // check whether we already have profile tls-crypt key...
        $profileTlsCryptKey = sprintf('%s/tls-crypt-%s.key', $this->keyDir, $profileId);
        if (@file_exists($profileTlsCryptKey)) {
            return FileIO::readFile($profileTlsCryptKey);
        }

        // no key yet, create one
        $tlsCryptKey = self::generate();
        FileIO::writeFile($profileTlsCryptKey, $tlsCryptKey);

        return FileIO::readFile($profileTlsCryptKey);
    }

    /**
     * @return string
     */
    private static function generate()
    {
        // Same as $(openvpn --genkey --secret <file>)
        $randomData = wordwrap(Hex::encode(random_bytes(256)), 32, "\n", true);
        $tlsCrypt = <<< EOF
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
$randomData
-----END OpenVPN Static key V1-----
EOF;

        return $tlsCrypt;
    }
}