GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( eac3b8...08138e )
by François
02:37
created

ServerConfig::get()   D

Complexity

Conditions 13
Paths 65

Size

Total Lines 184
Code Lines 92

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 184
rs 4.9922
cc 13
eloc 92
nc 65
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Copyright 2015 François Kooman <[email protected]>.
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 * http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
namespace fkooman\VPN\Server;
19
20
use RuntimeException;
21
22
class ServerConfig
23
{
24
    public function get(array $serverConfig)
25
    {
26
        $requiredParameters = [
27
            'cn',
28
            'valid_from',
29
            'valid_to',
30
            'dev',          // tun-udp, tun-tcp, tun0, tun1, ...
31
            'proto',        // udp6, tcp-server
32
            'port',         // 1194, 443, ...
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
33
            'v4_prefix',    // 10.42.42.0/24, ...
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
34
            'v6_prefix',
35
            'dns',
36
            'management_port',  // 7505, 7506, ...
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
37
            'ca',
38
            'cert',
39
            'key',
40
            'dh',
41
            'ta',
42
            'listen',
43
            '2fa',
44
            'routes',
45
            'c2c',
46
        ];
47
48
        // XXX verify the parameters and types
49
50
        foreach ($requiredParameters as $p) {
51
            if (!array_key_exists($p, $serverConfig)) {
52
                throw new RuntimeException(sprintf('missing parameter "%s"', $p));
53
            }
54
        }
55
56
        $routeConfig = [];
57
        if (0 === count($serverConfig['routes'])) {
58
            $routeConfig[] = 'push "redirect-gateway def1 bypass-dhcp"';
59
60
            # for Windows clients we need this extra route to mark the TAP adapter as 
61
            # trusted and as having "Internet" access to allow the user to set it to 
62
            # "Home" or "Work" to allow accessing file shares and printers  
63
            #$routeConfig[] = 'push "route 0.0.0.0 0.0.0.0"';
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
64
65
            # for iOS we need this OpenVPN 2.4 "ipv6" flag to redirect-gateway
66
            # See https://docs.openvpn.net/docs/openvpn-connect/openvpn-connect-ios-faq.html
67
            $routeConfig[] = 'push "redirect-gateway ipv6"';
68
69
            # we use 2000::/3 instead of ::/0 because it seems to break on native IPv6 
70
            # networks where the ::/0 default route already exists
71
            $routeConfig[] = 'push "route-ipv6 2000::/3"';
72
        } else {
73
            // there are some routes specified, push those, and not the default 
74
            foreach ($serverConfig['routes'] as $r) {
75
                if (false !== strpos($r, ':')) {
76
                    // IPv6
77
                    $routeConfig[] = sprintf('push "route-ipv6 %s"', $r);
78
                } else {
79
                    // IPv4
80
                    $routeConfig[] = sprintf('push "route %s"', $r);
81
                }
82
            }
83
        }
84
85
        $v4 = new IPv4($serverConfig['v4_prefix']);
86
87
        $dnsEntries = [];
88
        if (0 === count($serverConfig['routes'])) {
89
            // only push DNS when we are the default route
90
            foreach ($serverConfig['dns'] as $dnsAddress) {
91
                $dnsEntries[] = sprintf('push "dhcp-option DNS %s"', $dnsAddress);
92
            }
93
        }
94
95
        $tfaEntries = [];
96
        if ($serverConfig['2fa']) {
97
            $tfaEntries[] = 'auth-user-pass-verify /usr/bin/vpn-server-api-verify-otp via-env';
98
99
            # increase the renegotiation time to 8h from the default of 1h when
100
            # using 2FA, otherwise the user will be asked for the 2FA key every
101
            # hour
102
            $tfaEntries[] = 'reneg-sec 28800';
103
        }
104
105
        $tcpOptions = [];
106
        if ('tcp-server' === $serverConfig['proto'] || 'tcp6-server' === $serverConfig['proto']) {
107
            $tcpOptions[] = 'socket-flags TCP_NODELAY';
108
            $tcpOptions[] = 'push "socket-flags TCP_NODELAY"';
109
        }
110
111
        if ($serverConfig['c2c']) {
112
            $clientToClient[] = 'client-to-client';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$clientToClient was never initialized. Although not strictly required by PHP, it is generally a good practice to add $clientToClient = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
113
        }
114
115
        return [
116
            sprintf('# OpenVPN Server Configuration for %s', $serverConfig['cn']),
117
118
            sprintf('# Valid From: %s', date('c', $serverConfig['valid_from'])),
119
            sprintf('# Valid To: %s', date('c', $serverConfig['valid_to'])),
120
121
            sprintf('dev %s', $serverConfig['dev']),
122
123
            sprintf('local %s', $serverConfig['listen']),
124
125
            # UDP6 (works also for UDP)
126
            sprintf('proto %s', $serverConfig['proto']),
127
            sprintf('port %d', $serverConfig['port']),
128
129
            # IPv4
130
            sprintf('server %s %s', $v4->getNetwork(), $v4->getNetmask()),
131
132
            # IPv6
133
            sprintf('server-ipv6 %s', $serverConfig['v6_prefix']),
134
135
            implode(PHP_EOL, $routeConfig),
136
137
            implode(PHP_EOL, $clientToClient),
0 ignored issues
show
Bug introduced by
The variable $clientToClient does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
138
139
            'topology subnet',
140
            # disable compression
141
            'comp-lzo no',
142
            'push "comp-lzo no"',
143
            'persist-key',
144
            'persist-tun',
145
            'verb 3',
146
            sprintf('max-clients %d', $v4->getNumberOfHosts() - 1),
147
            'keepalive 10 60',
148
            'user openvpn',
149
            'group openvpn',
150
            'remote-cert-tls client',
151
152
            # when using TCP, we want to reduce the latency of the TCP tunnel
153
            implode(PHP_EOL, $tcpOptions),
154
155
            # CRYPTO (DATA CHANNEL)
156
            'auth SHA256',
157
            'cipher AES-256-CBC',
158
159
            # CRYPTO (CONTROL CHANNEL)
160
            # @see RFC 7525  
161
            # @see https://bettercrypto.org
162
            # @see https://community.openvpn.net/openvpn/wiki/Hardening
163
            'tls-version-min 1.2',
164
165
            # To work with default configuration in iOS OpenVPN with
166
            # "Force AES-CBC ciphersuites" enabled, we need to accept an 
167
            # additional cipher "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
168
            'tls-cipher TLS-DHE-RSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-GCM-SHA384:TLS-DHE-RSA-WITH-AES-256-CBC-SHA',
169
170
            sprintf('script-security %d', $serverConfig['2fa'] ? 3 : 2),
171
            'client-connect /usr/bin/vpn-server-api-client-connect',
172
            'client-disconnect /usr/bin/vpn-server-api-client-disconnect',
173
174
            # 2FA
175
            implode(PHP_EOL, $tfaEntries),
176
177
            # Certificate Revocation List
178
            'crl-verify /var/lib/vpn-server-api/ca.crl',
179
180
            # ask client to tell us on disconnect
181
            'push "explicit-exit-notify 3"',
182
183
            # DNS
184
            implode(PHP_EOL, $dnsEntries),
185
186
            # disable "netbios", i.e. Windows file sharing over TCP/IP
187
            #push "dhcp-option DISABLE-NBT"
188
189
            # also send a NTP server
190
            #push "dhcp-option NTP time.example.org"
191
192
            # allow client-to-client communication, see openvpn(8)
193
            #client-to-client
194
195
            # need to allow 7505 also with SELinux
196
            sprintf('management localhost %d', $serverConfig['management_port']),
197
198
            sprintf('<ca>%s</ca>', PHP_EOL.$serverConfig['ca'].PHP_EOL),
199
            sprintf('<cert>%s</cert>', PHP_EOL.$serverConfig['cert'].PHP_EOL),
200
            sprintf('<key>%s</key>', PHP_EOL.$serverConfig['key'].PHP_EOL),
201
            sprintf('<dh>%s</dh>', PHP_EOL.$serverConfig['dh'].PHP_EOL),
202
203
            'key-direction 0',
204
205
            sprintf('<tls-auth>%s</tls-auth>', PHP_EOL.$serverConfig['ta'].PHP_EOL),
206
        ];
207
    }
208
}
209