Project

General

Profile

Download (62.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * openvpn.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2006 Fernando Lemos
7
 * Copyright (c) 2006-2013 BSD Perimeter
8
 * Copyright (c) 2013-2016 Electric Sheep Fencing
9
 * Copyright (c) 2014-2019 Rubicon Communications, LLC (Netgate)
10
 * All rights reserved.
11
 *
12
 * This file was rewritten from scratch by Fernando Lemos but
13
 * *MIGHT* contain code previously written by:
14
 *
15
 * Copyright (c) 2005 Peter Allgeyer <allgeyer_AT_web.de>
16
 * Copyright (c) 2004 Peter Curran (peter@closeconsultants.com).
17
 * All rights reserved.
18
 *
19
 * Licensed under the Apache License, Version 2.0 (the "License");
20
 * you may not use this file except in compliance with the License.
21
 * You may obtain a copy of the License at
22
 *
23
 * http://www.apache.org/licenses/LICENSE-2.0
24
 *
25
 * Unless required by applicable law or agreed to in writing, software
26
 * distributed under the License is distributed on an "AS IS" BASIS,
27
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28
 * See the License for the specific language governing permissions and
29
 * limitations under the License.
30
 */
31

    
32
require_once('config.inc');
33
require_once("certs.inc");
34
require_once('pfsense-utils.inc');
35
require_once("auth.inc");
36

    
37
global $openvpn_prots;
38
$openvpn_prots = array(
39
	"UDP4" => "UDP on IPv4 only",
40
	"UDP6" => "UDP on IPv6 only",
41
	"TCP4" => "TCP on IPv4 only",
42
	"TCP6" => "TCP on IPv6 only",
43
	"UDP" => "UDP IPv4 and IPv6 on all interfaces (multihome)",
44
	"TCP" => "TCP IPv4 and IPv6 on all interfaces (multihome)"
45
);
46

    
47
global $openvpn_dev_mode;
48
$openvpn_dev_mode = array(
49
	"tun" => "tun - Layer 3 Tunnel Mode",
50
	"tap" => "tap - Layer 2 Tap Mode"
51
);
52

    
53
global $openvpn_verbosity_level;
54
$openvpn_verbosity_level = array(
55
	0 =>	gettext("none"),
56
	1 =>	gettext("default"),
57
	2 =>	"2",
58
	3 =>	gettext("3 (recommended)"),
59
	4 =>	"4",
60
	5 => 	"5",
61
	6 => 	"6",
62
	7 => 	"7",
63
	8 => 	"8",
64
	9 => 	"9",
65
	10 => 	"10",
66
	11 => 	"11"
67
);
68

    
69
/*
70
 * The User Auth mode below is disabled because
71
 * OpenVPN erroneously requires that we provide
72
 * a CA configuration parameter. In this mode,
73
 * clients don't send a certificate so there is
74
 * no need for a CA. If we require that admins
75
 * provide one in the pfSense UI due to a bogus
76
 * requirement imposed by OpenVPN, it could be
77
 * considered very confusing ( I know I was ).
78
 *
79
 * -mgrooms
80
 */
81

    
82
global $openvpn_dh_lengths;
83
$openvpn_dh_lengths = array(
84
	1024 => "1024 bit",
85
	2048 => "2048 bit",
86
	3072 => "3072 bit",
87
	4096 => "4096 bit",
88
	6144 => "6144 bit",
89
	7680 => "7680 bit",
90
	8192 => "8192 bit",
91
	15360 => "15360 bit",
92
	16384 => "16384 bit",
93
	"none" => "ECDH Only"
94
);
95
foreach ($openvpn_dh_lengths as $idx => $dhlen) {
96
	if (is_numeric($idx) && !file_exists("/etc/dh-parameters.{$idx}")) {
97
		unset($openvpn_dh_lengths[$idx]);
98
	}
99
}
100

    
101
global $openvpn_cert_depths;
102
$openvpn_cert_depths = array(
103
	1 => gettext("One (Client+Server)"),
104
	2 => gettext("Two (Client+Intermediate+Server)"),
105
	3 => gettext("Three (Client+2xIntermediate+Server)"),
106
	4 => gettext("Four (Client+3xIntermediate+Server)"),
107
	5 => gettext("Five (Client+4xIntermediate+Server)")
108
);
109

    
110
global $openvpn_server_modes;
111
$openvpn_server_modes = array(
112
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
113
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"),
114
	'server_tls' => gettext("Remote Access ( SSL/TLS )"),
115
	'server_user' => gettext("Remote Access ( User Auth )"),
116
	'server_tls_user' => gettext("Remote Access ( SSL/TLS + User Auth )"));
117

    
118
global $openvpn_tls_server_modes;
119
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
120

    
121
global $openvpn_client_modes;
122
$openvpn_client_modes = array(
123
	'p2p_tls' => gettext("Peer to Peer ( SSL/TLS )"),
124
	'p2p_shared_key' => gettext("Peer to Peer ( Shared Key )"));
125

    
126
global $openvpn_compression_modes;
127
$openvpn_compression_modes = array(
128
	'none' => gettext("Disable Compression, retain compression packet framing [compress]"),
129
	'lz4' => gettext("LZ4 Compression [compress lz4]"),
130
	'lz4-v2' => gettext("LZ4 Compression v2 [compress lz4-v2]"),
131
	'lzo' => gettext("LZO Compression [compress lzo, equivalent to comp-lzo yes for compatibility]"),
132
	'stub' => gettext("Enable Compression (stub) [compress stub]"),
133
	'stub-v2' => gettext("Enable Compression (stub v2) [compress stub-v2]"),
134
	'' => gettext("Omit Preference (Use OpenVPN Default)"),
135
	'noadapt' => gettext("Omit Preference, + Disable Adaptive LZO Compression [Legacy style, comp-noadapt]"),
136
	'adaptive' => gettext("Adaptive LZO Compression [Legacy style, comp-lzo adaptive]"),
137
	'yes' => gettext("LZO Compression [Legacy style, comp-lzo yes]"),
138
	'no' => gettext("No LZO Compression [Legacy style, comp-lzo no]"),
139
);
140

    
141
global $openvpn_topologies;
142
$openvpn_topologies = array(
143
	'subnet' => gettext("Subnet -- One IP address per client in a common subnet"),
144
	'net30' => gettext("net30 -- Isolated /30 network per client")
145
);
146

    
147
global $openvpn_tls_modes;
148
$openvpn_tls_modes = array(
149
	'auth' => gettext("TLS Authentication"),
150
	'crypt' => gettext("TLS Encryption and Authentication")
151
);
152

    
153
global $openvpn_ping_method;
154
$openvpn_ping_method = array(
155
	'keepalive' => gettext("keepalive -- Use keepalive helper to define ping configuration"),
156
	'ping' => gettext("ping -- Define ping/ping-exit/ping-restart manually")
157
);
158

    
159
global $openvpn_default_keepalive_interval;
160
$openvpn_default_keepalive_interval = 10;
161

    
162
global $openvpn_default_keepalive_timeout;
163
$openvpn_default_keepalive_timeout = 60;
164

    
165
global $openvpn_ping_action;
166
$openvpn_ping_action = array(
167
	'ping_restart' => gettext("ping-restart -- Restart OpenVPN after timeout"),
168
	'ping_exit' => gettext("ping-exit -- Exit OpenVPN after timeout")
169
);
170

    
171
function openvpn_build_mode_list() {
172
	global $openvpn_server_modes;
173

    
174
	$list = array();
175

    
176
	foreach ($openvpn_server_modes as $name => $desc) {
177
		$list[$name] = $desc;
178
	}
179

    
180
	return($list);
181
}
182

    
183
global $openvpn_interfacenames;
184
function convert_openvpn_interface_to_friendly_descr($if) {
185
	global $openvpn_interfacenames;
186
	if (!is_array($openvpn_interfacenames)) {
187
		$openvpn_interfacenames = openvpn_build_if_list();
188
	}
189
	foreach($openvpn_interfacenames as $key => $value) {
190
		list($item_if, $item_ip) = explode("|", $key);
191
		if ($if == $item_if) {
192
			echo "$value";
193
		}
194
	}
195
}
196

    
197
function openvpn_build_if_list() {
198
	$list = array();
199

    
200
	$interfaces = get_configured_interface_with_descr();
201
	$viplist = get_configured_vip_list();
202
	foreach ($viplist as $vip => $address) {
203
		$interfaces[$vip.'|'.$address] = $address;
204
		if (get_vip_descr($address)) {
205
			$interfaces[$vip.'|'.$address] .= " (";
206
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
207
			$interfaces[$vip.'|'.$address] .= ")";
208
		}
209
	}
210

    
211
	$grouplist = return_gateway_groups_array();
212
	foreach ($grouplist as $name => $group) {
213
		if ($group[0]['vip'] != "") {
214
			$vipif = $group[0]['vip'];
215
		} else {
216
			$vipif = $group[0]['int'];
217
		}
218

    
219
		$interfaces[$name] = "GW Group {$name}";
220
	}
221

    
222
	$interfaces['lo0'] = "Localhost";
223
	$interfaces['any'] = "any";
224

    
225
	foreach ($interfaces as $iface => $ifacename) {
226
	   $list[$iface] = $ifacename;
227
	}
228

    
229
	return($list);
230
}
231

    
232
function openvpn_build_crl_list() {
233
	global $a_crl;
234

    
235
	$list = array('' => 'None');
236

    
237
	foreach ($a_crl as $crl) {
238
		$caname = "";
239
		$ca = lookup_ca($crl['caref']);
240

    
241
		if ($ca) {
242
			$caname = " (CA: {$ca['descr']})";
243
		}
244

    
245
		$list[$crl['refid']] = $crl['descr'] . $caname;
246
	}
247

    
248
	return($list);
249
}
250

    
251
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
252
	global $a_cert;
253

    
254
	if ($include_none) {
255
		$list = array('' => gettext('None (Username and/or Password required)'));
256
	} else {
257
		$list = array();
258
	}
259

    
260
	$non_server_list = array();
261

    
262
	if ($prioritize_server_certs) {
263
		$list[' '] = gettext("===== Server Certificates =====");
264
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
265
	}
266

    
267
	foreach ($a_cert as $cert) {
268
		$properties = array();
269
		$propstr = "";
270
		$ca = lookup_ca($cert['caref']);
271
		$purpose = cert_get_purpose($cert['crt'], true);
272

    
273
		if ($purpose['server'] == "Yes") {
274
			$properties[] = gettext("Server: Yes");
275
		} elseif ($prioritize_server_certs) {
276
			$properties[] = gettext("Server: NO");
277
		}
278
		if ($ca) {
279
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
280
		}
281
		if (cert_in_use($cert['refid'])) {
282
			$properties[] = gettext("In Use");
283
		}
284
		if (is_cert_revoked($cert)) {
285
			$properties[] = gettext("Revoked");
286
		}
287

    
288
		if (!empty($properties)) {
289
			$propstr = " (" . implode(", ", $properties) . ")";
290
		}
291

    
292
		if ($prioritize_server_certs) {
293
			if ($purpose['server'] == "Yes") {
294
				$list[$cert['refid']] = $cert['descr'] . $propstr;
295
			} else {
296
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
297
			}
298
		} else {
299
			$list[$cert['refid']] = $cert['descr'] . $propstr;
300
		}
301
	}
302

    
303
	return(array('server' => $list, 'non-server' => $non_server_list));
304
}
305

    
306
function openvpn_build_bridge_list() {
307
	$list = array();
308

    
309
	$serverbridge_interface['none'] = "none";
310
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
311
	$viplist = get_configured_vip_list();
312

    
313
	foreach ($viplist as $vip => $address) {
314
		$serverbridge_interface[$vip.'|'.$address] = $address;
315
		if (get_vip_descr($address)) {
316
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
317
		}
318
	}
319

    
320
	foreach ($serverbridge_interface as $iface => $ifacename) {
321
		$list[$iface] = htmlspecialchars($ifacename);
322
	}
323

    
324
	return($list);
325
}
326

    
327
function openvpn_create_key() {
328

    
329
	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
330
	if (!$fp) {
331
		return false;
332
	}
333

    
334
	$rslt = stream_get_contents($fp);
335
	pclose($fp);
336

    
337
	return $rslt;
338
}
339

    
340
function openvpn_create_dhparams($bits) {
341

    
342
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
343
	if (!$fp) {
344
		return false;
345
	}
346

    
347
	$rslt = stream_get_contents($fp);
348
	pclose($fp);
349

    
350
	return $rslt;
351
}
352

    
353
function openvpn_vpnid_used($vpnid) {
354
	global $config;
355

    
356
	if (is_array($config['openvpn']['openvpn-server'])) {
357
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
358
			if ($vpnid == $settings['vpnid']) {
359
				return true;
360
			}
361
		}
362
	}
363

    
364
	if (is_array($config['openvpn']['openvpn-client'])) {
365
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
366
			if ($vpnid == $settings['vpnid']) {
367
				return true;
368
			}
369
		}
370
	}
371

    
372
	return false;
373
}
374

    
375
function openvpn_vpnid_next() {
376

    
377
	$vpnid = 1;
378
	while (openvpn_vpnid_used($vpnid)) {
379
		$vpnid++;
380
	}
381

    
382
	return $vpnid;
383
}
384

    
385
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
386
	global $config;
387

    
388
	$ovpn_settings = array();
389
	if (is_array($config['openvpn']['openvpn-server'])) {
390
		$ovpn_settings = $config['openvpn']['openvpn-server'];
391
	}
392
	if (is_array($config['openvpn']['openvpn-client'])) {
393
		$ovpn_settings = array_merge($ovpn_settings,
394
		    $config['openvpn']['openvpn-client']);
395
	}
396

    
397
	foreach ($ovpn_settings as $settings) {
398
		if (isset($settings['disable'])) {
399
			continue;
400
		}
401

    
402
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
403
			continue;
404
		}
405

    
406
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
407
		if (($interface != "any" && $settings['interface'] != "any") &&
408
		    (strlen($prot) == 4) &&
409
		    (strlen($settings['protocol']) == 4) &&
410
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
411
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
412
			continue;
413
		}
414

    
415
		if ($port == $settings['local_port'] &&
416
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
417
		    ($interface == $settings['interface'] ||
418
		    $interface == "any" || $settings['interface'] == "any")) {
419
			return $settings['vpnid'];
420
		}
421
	}
422

    
423
	return 0;
424
}
425

    
426
function openvpn_port_next($prot, $interface = "wan") {
427

    
428
	$port = 1194;
429
	while (openvpn_port_used($prot, $interface, $port)) {
430
		$port++;
431
	}
432
	while (openvpn_port_used($prot, "any", $port)) {
433
		$port++;
434
	}
435

    
436
	return $port;
437
}
438

    
439
function openvpn_get_cipherlist() {
440

    
441
	$ciphers = array();
442
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
443
	$cipher_lines = explode("\n", trim($cipher_out));
444
	sort($cipher_lines);
445
	foreach ($cipher_lines as $line) {
446
		$words = explode(' ', $line, 2);
447
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
448
	}
449
	$ciphers["none"] = gettext("None (No Encryption)");
450
	return $ciphers;
451
}
452

    
453
function openvpn_get_curvelist() {
454

    
455
	$curves = array();
456
	$curves["none"] = gettext("Use Default");
457
	$curve_out = shell_exec('/usr/local/sbin/openvpn --show-curves | /usr/bin/grep -v \'Available Elliptic curves\'');
458
	$curve_lines = explode("\n", trim($curve_out));
459
	sort($curve_lines);
460
	foreach ($curve_lines as $line) {
461
		$line = trim($line);
462
		$curves[$line] = $line;
463
	}
464
	return $curves;
465
}
466

    
467
function openvpn_validate_curve($curve) {
468
	$curves = openvpn_get_curvelist();
469
	return array_key_exists($curve, $curves);
470
}
471

    
472
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
473
function openvpn_get_openssldigestmappings() {
474
	$digests = array();
475
	$digest_out = shell_exec('/usr/bin/openssl list-message-digest-algorithms | /usr/bin/grep "=>"');
476
	$digest_lines = explode("\n", trim($digest_out));
477
	sort($digest_lines);
478
	foreach ($digest_lines as $line) {
479
		$words = explode(' => ', $line, 2);
480
		$digests[$words[0]] = $words[1];
481
	}
482
	return $digests;
483
}
484

    
485
/* Obtain the list of digest algorithms supported by openvpn */
486
function openvpn_get_digestlist() {
487
	/* Grab the list from OpenSSL to check for duplicates or aliases */
488
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
489
	$digests = array();
490
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
491
	$digest_lines = explode("\n", trim($digest_out));
492
	sort($digest_lines);
493
	foreach ($digest_lines as $line) {
494
		$words = explode(' ', $line);
495
		/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
496
		if (!array_key_exists($words[0], $openssl_digest_mappings)) {
497
			$digests[$words[0]] = "{$words[0]} {$words[1]}";
498
		}
499
	}
500
	$digests["none"] = gettext("None (No Authentication)");
501
	return $digests;
502
}
503

    
504
/* Check to see if a digest name is an alias and if so, find the actual digest
505
 * algorithm instead. Useful for upgrade code that has to translate aliased
506
 * algorithms to their actual names.
507
 */
508
function openvpn_remap_digest($digest) {
509
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
510
	if (array_key_exists($digest, $openssl_digest_mappings)) {
511
		/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
512
		if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
513
			return openvpn_remap_digest($openssl_digest_mappings[$digest]);
514
		} else {
515
			return $openssl_digest_mappings[$digest];
516
		}
517
	}
518
	return $digest;
519
}
520

    
521
function openvpn_get_keydirlist() {
522
	$keydirs = array(
523
		''  => gettext('Use default direction'),
524
		'0' => gettext('Direction 0'),
525
		'1' => gettext('Direction 1'),
526
		'2' => gettext('Both directions'),
527
	);
528
	return $keydirs;
529
}
530

    
531
function openvpn_get_engines() {
532
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
533
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
534
	$openssl_engine_output = implode("\n", $openssl_engine_output);
535
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
536
	$openssl_engine_output = explode("\n", $openssl_engine_output);
537

    
538
	foreach ($openssl_engine_output as $oeo) {
539
		$keep = true;
540
		$details = explode("|", $oeo);
541
		$engine = array_shift($details);
542
		$linematch = array();
543
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
544
		foreach ($details as $dt) {
545
			if (strpos($dt, "unavailable") !== FALSE) {
546
				$keep = false;
547
			}
548
			if (strpos($dt, "available") !== FALSE) {
549
				continue;
550
			}
551
			if (strpos($dt, "[") !== FALSE) {
552
				$ciphers = trim($dt, "[]");
553
			}
554
		}
555
		if (!empty($ciphers)) {
556
			$ciphers = " - " . $ciphers;
557
		}
558
		if (strlen($ciphers) > 60) {
559
			$ciphers = substr($ciphers, 0, 60) . " ... ";
560
		}
561
		if ($keep) {
562
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
563
		}
564
	}
565
	return $openssl_engines;
566
}
567

    
568
function openvpn_get_buffer_values() {
569
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
570
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
571
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
572
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
573
	$buffer_values = array('' => gettext('Default'));
574
	for ($bs = 32; $bs >= 1; $bs /= 2) {
575
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
576
	}
577
	return $buffer_values;
578
}
579

    
580
function openvpn_validate_engine($engine) {
581
	$engines = openvpn_get_engines();
582
	return array_key_exists($engine, $engines);
583
}
584

    
585
function openvpn_validate_host($value, $name) {
586
	$value = trim($value);
587
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
588
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
589
	}
590
	return false;
591
}
592

    
593
function openvpn_validate_port($value, $name, $first_port = 0) {
594
	$value = trim($value);
595
	if (!is_numeric($first_port)) {
596
		$first_port = 0;
597
	}
598
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
599
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
600
	}
601
	return false;
602
}
603

    
604
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
605
	$value = trim($value);
606
	$error = false;
607
	if (empty($value)) {
608
		return false;
609
	}
610
	$networks = explode(',', $value);
611

    
612
	if (!$multiple && (count($networks) > 1)) {
613
		return sprintf(gettext("The field '%1\$s' must contain a single valid %2\$s CIDR range."), $name, $ipproto);
614
	}
615

    
616
	foreach ($networks as $network) {
617
		if ($ipproto == "ipv4") {
618
			$error = !openvpn_validate_cidr_ipv4($network);
619
		} else {
620
			$error = !openvpn_validate_cidr_ipv6($network);
621
		}
622
		if ($error) {
623
			break;
624
		}
625
	}
626

    
627
	if ($error) {
628
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
629
	} else {
630
		return false;
631
	}
632
}
633

    
634
function openvpn_validate_cidr_ipv4($value) {
635
	$value = trim($value);
636
	if (!empty($value)) {
637
		list($ip, $mask) = explode('/', $value);
638
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
639
			return false;
640
		}
641
	}
642
	return true;
643
}
644

    
645
function openvpn_validate_cidr_ipv6($value) {
646
	$value = trim($value);
647
	if (!empty($value)) {
648
		list($ipv6, $prefix) = explode('/', $value);
649
		if (empty($prefix)) {
650
			$prefix = "128";
651
		}
652
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
653
			return false;
654
		}
655
	}
656
	return true;
657
}
658

    
659
function openvpn_add_dhcpopts(& $settings, & $conf) {
660

    
661
	if (!empty($settings['dns_domain'])) {
662
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
663
	}
664

    
665
	if (!empty($settings['dns_server1'])) {
666
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
667
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
668
	}
669
	if (!empty($settings['dns_server2'])) {
670
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
671
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
672
	}
673
	if (!empty($settings['dns_server3'])) {
674
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
675
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
676
	}
677
	if (!empty($settings['dns_server4'])) {
678
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
679
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
680
	}
681

    
682
	if (!empty($settings['push_blockoutsidedns'])) {
683
		$conf .= "push \"block-outside-dns\"\n";
684
	}
685
	if (!empty($settings['push_register_dns'])) {
686
		$conf .= "push \"register-dns\"\n";
687
	}
688

    
689
	if (!empty($settings['ntp_server1'])) {
690
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
691
	}
692
	if (!empty($settings['ntp_server2'])) {
693
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
694
	}
695

    
696
	if ($settings['netbios_enable']) {
697

    
698
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
699
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
700
		}
701
		if (!empty($settings['dhcp_nbtscope'])) {
702
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
703
		}
704

    
705
		if (!empty($settings['wins_server1'])) {
706
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
707
		}
708
		if (!empty($settings['wins_server2'])) {
709
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
710
		}
711

    
712
		if (!empty($settings['nbdd_server1'])) {
713
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
714
		}
715
	}
716

    
717
	if ($settings['gwredir']) {
718
		$conf .= "push \"redirect-gateway def1\"\n";
719
	}
720
	if ($settings['gwredir6']) {
721
		$conf .= "push \"redirect-gateway ipv6\"\n";
722
	}
723
}
724

    
725
function openvpn_add_custom(& $settings, & $conf) {
726

    
727
	if ($settings['custom_options']) {
728

    
729
		$options = explode(';', $settings['custom_options']);
730

    
731
		if (is_array($options)) {
732
			foreach ($options as $option) {
733
				$conf .= "$option\n";
734
			}
735
		} else {
736
			$conf .= "{$settings['custom_options']}\n";
737
		}
738
	}
739
}
740

    
741
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
742
	global $g;
743

    
744
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.{$directive}";
745
	openvpn_create_dirs();
746
	file_put_contents($fpath, base64_decode($data));
747
	//chown($fpath, 'nobody');
748
	//chgrp($fpath, 'nobody');
749
	@chmod($fpath, 0600);
750

    
751
	$conf .= "{$directive} {$fpath} {$opt}\n";
752
}
753

    
754
function openvpn_reconfigure($mode, $settings) {
755
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
756

    
757
	if (empty($settings)) {
758
		return;
759
	}
760
	if (isset($settings['disable'])) {
761
		return;
762
	}
763
	openvpn_create_dirs();
764
	/*
765
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
766
	 * we use a vpnid number which is allocated for a particular client
767
	 * or server configuration. ( see openvpn_vpnid_next() )
768
	 */
769

    
770
	$vpnid = $settings['vpnid'];
771
	$mode_id = $mode.$vpnid;
772

    
773
	if (isset($settings['dev_mode'])) {
774
		$tunname = "{$settings['dev_mode']}{$vpnid}";
775
	} else {
776
		/* defaults to tun */
777
		$tunname = "tun{$vpnid}";
778
		$settings['dev_mode'] = "tun";
779
	}
780

    
781
	if ($mode == "server") {
782
		$devname = "ovpns{$vpnid}";
783
	} else {
784
		$devname = "ovpnc{$vpnid}";
785
	}
786

    
787
	/* is our device already configured */
788
	if (!does_interface_exist($devname)) {
789

    
790
		/* create the tap device if required */
791
		if (!file_exists("/dev/{$tunname}")) {
792
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
793
		}
794

    
795
		/* rename the device */
796
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
797

    
798
		/* add the device to the openvpn group and make sure it's UP*/
799
		mwexec("/sbin/ifconfig " . escapeshellarg($devname) . " group openvpn up");
800

    
801
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
802
		$grouptmp = link_interface_to_group($ifname);
803
		if (!empty($grouptmp)) {
804
			array_walk($grouptmp, 'interface_group_add_member');
805
		}
806
		unset($grouptmp, $ifname);
807
	}
808

    
809
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
810
	$proto = strtolower($settings['protocol']);
811
	if (substr($settings['protocol'], 0, 3) == "TCP") {
812
			$proto = "{$proto}-{$mode}";
813
	}
814
	$dev_mode = $settings['dev_mode'];
815
	$cipher = $settings['crypto'];
816
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
817
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
818

    
819
	$interface = get_failover_interface($settings['interface']);
820
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
821
	$ipaddr = $settings['ipaddr'];
822

    
823
	// If a specific ip address (VIP) is requested, use it.
824
	// Otherwise, if a specific interface is requested, use it
825
	// If "any" interface was selected, local directive will be omitted.
826
	if (is_ipaddrv4($ipaddr)) {
827
		$iface_ip = $ipaddr;
828
	} elseif (!empty($interface) && strcmp($interface, "any")) {
829
		$iface_ip=get_interface_ip($interface);
830
	}
831
	if (is_ipaddrv6($ipaddr)) {
832
		$iface_ipv6 = $ipaddr;
833
	} elseif (!empty($interface) && strcmp($interface, "any")) {
834
		$iface_ipv6=get_interface_ipv6($interface);
835
	}
836

    
837
	$conf = "dev {$devname}\n";
838
	if (isset($settings['verbosity_level'])) {
839
		$conf .= "verb {$settings['verbosity_level']}\n";
840
	}
841

    
842
	$conf .= "dev-type {$settings['dev_mode']}\n";
843
	$conf .= "dev-node /dev/{$tunname}\n";
844
	$conf .= "writepid {$pfile}\n";
845
	$conf .= "#user nobody\n";
846
	$conf .= "#group nobody\n";
847
	$conf .= "script-security 3\n";
848
	$conf .= "daemon\n";
849

    
850
	if (!empty($settings['inactive_seconds'])) {
851
		$conf .= "inactive {$settings['inactive_seconds']}\n";
852
	}
853

    
854
	if (!empty($settings['ping_method']) &&
855
	    $settings['ping_method'] == 'ping') {
856
		$conf .= "ping {$settings['ping_seconds']}\n";
857

    
858
		if (!empty($settings['ping_push'])) {
859
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
860
		}
861

    
862
		$action = str_replace("_", "-", $settings['ping_action']);
863
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
864

    
865
		if (!empty($settings['ping_action_push'])) {
866
			$conf .= "push \"{$action} " .
867
			    "{$settings['ping_action_seconds']}\"\n";
868
		}
869
	} else {
870
		$conf .= "keepalive " .
871
		    ($settings['keepalive_interval']
872
			?: $openvpn_default_keepalive_interval) . " " .
873
		    ($settings['keepalive_timeout']
874
			?: $openvpn_default_keepalive_timeout) . "\n";
875
	}
876

    
877
	$conf .= "ping-timer-rem\n";
878
	$conf .= "persist-tun\n";
879
	$conf .= "persist-key\n";
880
	$conf .= "proto {$proto}\n";
881
	$conf .= "cipher {$cipher}\n";
882
	$conf .= "auth {$digest}\n";
883
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
884
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
885
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
886
		switch ($settings['mode']) {
887
			case 'server_user':
888
			case 'server_tls_user':
889
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
890
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
891
				break;
892
		}
893
	}
894
	if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
895
		switch($settings['mode']) {
896
			case 'server_tls':
897
			case 'server_tls_user':
898
				$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : $config['system']['domain'];
899
				if (is_domain($domain)) {
900
					$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
901
				}
902
				break;
903
		}
904
	}
905

    
906
	/*
907
	 * When binding specific address, wait cases where interface is in
908
	 * tentative state otherwise it will fail
909
	 */
910
	$wait_tentative = false;
911

    
912
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
913
	switch ($settings['protocol']) {
914
		case 'UDP':
915
		case 'TCP':
916
			$conf .= "multihome\n";
917
			break;
918
		case 'UDP4':
919
		case 'TCP4':
920
			if (is_ipaddrv4($iface_ip)) {
921
				$conf .= "local {$iface_ip}\n";
922
			}
923
			if ($settings['interface'] == "any") {
924
				$conf .= "multihome\n";
925
			}
926
			break;
927
		case 'UDP6':
928
		case 'TCP6':
929
			if (is_ipaddrv6($iface_ipv6)) {
930
				$conf .= "local {$iface_ipv6}\n";
931
				$wait_tentative = true;
932
			}
933
			if ($settings['interface'] == "any") {
934
				$conf .= "multihome\n";
935
			}
936
			break;
937
		default:
938
	}
939

    
940
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
941
		$conf .= "engine {$settings['engine']}\n";
942
	}
943

    
944
	// server specific settings
945
	if ($mode == 'server') {
946

    
947
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
948
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
949
		$mask = gen_subnet_mask($cidr);
950

    
951
		// configure tls modes
952
		switch ($settings['mode']) {
953
			case 'p2p_tls':
954
			case 'server_tls':
955
			case 'server_user':
956
			case 'server_tls_user':
957
				$conf .= "tls-server\n";
958
				break;
959
		}
960

    
961
		// configure p2p/server modes
962
		switch ($settings['mode']) {
963
			case 'p2p_tls':
964
				// If the CIDR is less than a /30, OpenVPN will complain if you try to
965
				//  use the server directive. It works for a single client without it.
966
				//  See ticket #1417
967
				if (!empty($ip) && !empty($mask) && ($cidr < 30)) {
968
					$conf .= "server {$ip} {$mask}\n";
969
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
970
					if (is_ipaddr($ipv6)) {
971
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
972
					}
973
				}
974
			case 'p2p_shared_key':
975
				if (!empty($ip) && !empty($mask)) {
976
					list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
977
					if ($settings['dev_mode'] == 'tun') {
978
						$conf .= "ifconfig {$ip1} {$ip2}\n";
979
					} else {
980
						$conf .= "ifconfig {$ip1} {$mask}\n";
981
					}
982
				}
983
				if (!empty($ipv6) && !empty($prefix)) {
984
					list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
985
					if ($settings['dev_mode'] == 'tun') {
986
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$ipv6_2}\n";
987
					} else {
988
						$conf .= "ifconfig-ipv6 {$ipv6_1} {$prefix}\n";
989
					}
990
				}
991
				break;
992
			case 'server_tls':
993
			case 'server_user':
994
			case 'server_tls_user':
995
				if (!empty($ip) && !empty($mask)) {
996
					$conf .= "server {$ip} {$mask}\n";
997
					if (is_ipaddr($ipv6)) {
998
						$conf .= "server-ipv6 {$ipv6}/{$prefix}\n";
999
					}
1000
					$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
1001
				} else {
1002
					if ($settings['serverbridge_dhcp']) {
1003
						if ((!empty($settings['serverbridge_interface'])) && (strcmp($settings['serverbridge_interface'], "none"))) {
1004
							$biface_ip=get_interface_ip($settings['serverbridge_interface']);
1005
							$biface_sm=gen_subnet_mask(get_interface_subnet($settings['serverbridge_interface']));
1006
							if (is_ipaddrv4($biface_ip) && is_ipaddrv4($settings['serverbridge_dhcp_start']) && is_ipaddrv4($settings['serverbridge_dhcp_end'])) {
1007
								$conf .= "server-bridge {$biface_ip} {$biface_sm} {$settings['serverbridge_dhcp_start']} {$settings['serverbridge_dhcp_end']}\n";
1008
								$conf .= "client-config-dir {$g['varetc_path']}/openvpn-csc/server{$vpnid}\n";
1009
							} else {
1010
								$conf .= "mode server\n";
1011
							}
1012
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv4($biface_ip)) {
1013
								$conf .= "push \"route-gateway {$biface_ip}\"\n";
1014
							}
1015
							/* OpenVPN doesn't support this yet, clients do not recognize the option fully.
1016
							$biface_ip6=get_interface_ipv6($settings['serverbridge_interface']);
1017
							if (!empty($settings['serverbridge_routegateway']) && is_ipaddrv6($biface_ip6)) {
1018
								$conf .= "push \"route-ipv6-gateway {$biface_ip6}\"\n";
1019
							}
1020
							*/
1021
						} else {
1022
							$conf .= "mode server\n";
1023
						}
1024
					}
1025
				}
1026
				break;
1027
		}
1028

    
1029
		// configure user auth modes
1030
		switch ($settings['mode']) {
1031
			case 'server_user':
1032
				$conf .= "verify-client-cert none\n";
1033
			case 'server_tls_user':
1034
				/* username-as-common-name is not compatible with server-bridge */
1035
				if (stristr($conf, "server-bridge") === false) {
1036
					$conf .= "username-as-common-name\n";
1037
				}
1038
				if (!empty($settings['authmode'])) {
1039
					$strictusercn = "false";
1040
					if ($settings['strictusercn']) {
1041
						$strictusercn = "true";
1042
					}
1043
					$conf .= "plugin /usr/local/lib/openvpn/plugins/openvpn-plugin-auth-script.so /usr/local/sbin/ovpn_auth_verify_async user " . base64_encode($settings['authmode']) . " {$strictusercn} {$mode_id} {$settings['local_port']}\n";
1044
				}
1045
				break;
1046
		}
1047
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
1048
			$settings['cert_depth'] = 1;
1049
		}
1050
		if (is_numeric($settings['cert_depth'])) {
1051
			if (($mode == 'client') && empty($settings['certref'])) {
1052
				$cert = "";
1053
			} else {
1054
				$cert = lookup_cert($settings['certref']);
1055
				/* XXX: Seems not used at all! */
1056
				$servercn = urlencode(cert_get_cn($cert['crt']));
1057
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
1058
			}
1059
		}
1060

    
1061
		// The local port to listen on
1062
		$conf .= "lport {$settings['local_port']}\n";
1063

    
1064
		// The management port to listen on
1065
		// Use unix socket to overcome the problem on any type of server
1066
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
1067
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1068

    
1069
		if ($settings['maxclients']) {
1070
			$conf .= "max-clients {$settings['maxclients']}\n";
1071
		}
1072

    
1073
		// Can we push routes, and should we?
1074
		if ($settings['local_network'] && !$settings['gwredir']) {
1075
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1076
		}
1077
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1078
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1079
		}
1080

    
1081
		switch ($settings['mode']) {
1082
			case 'server_tls':
1083
			case 'server_user':
1084
			case 'server_tls_user':
1085
				// Configure client dhcp options
1086
				openvpn_add_dhcpopts($settings, $conf);
1087
				if ($settings['client2client']) {
1088
					$conf .= "client-to-client\n";
1089
				}
1090
				break;
1091
		}
1092
		if ($settings['mode'] != 'p2p_shared_key' &&
1093
		    isset($settings['duplicate_cn'])) {
1094
			$conf .= "duplicate-cn\n";
1095
		}
1096
	}
1097

    
1098
	// client specific settings
1099

    
1100
	if ($mode == 'client') {
1101

    
1102
		// configure p2p mode
1103
		switch ($settings['mode']) {
1104
			case 'p2p_tls':
1105
				$conf .= "tls-client\n";
1106
			case 'shared_key':
1107
				$conf .= "client\n";
1108
				break;
1109
		}
1110

    
1111
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1112
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1113
		//  ensure a random source port.
1114
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1115
			$conf .= "nobind\n";
1116
		} elseif ($settings['local_port']) {
1117
			$conf .= "lport {$settings['local_port']}\n";
1118
		} else {
1119
			$conf .= "lport 0\n";
1120
		}
1121

    
1122
		// Use unix socket to overcome the problem on any type of server
1123
		$conf .= "management {$g['varetc_path']}/openvpn/{$mode_id}.sock unix\n";
1124

    
1125
		// The remote server
1126
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
1127

    
1128
		if (!empty($settings['use_shaper'])) {
1129
			$conf .= "shaper {$settings['use_shaper']}\n";
1130
		}
1131

    
1132
		if (!empty($settings['tunnel_network'])) {
1133
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1134
			$mask = gen_subnet_mask($cidr);
1135
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1136
			if ($settings['dev_mode'] == 'tun') {
1137
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1138
			} else {
1139
				$conf .= "ifconfig {$ip2} {$mask}\n";
1140
			}
1141
		}
1142

    
1143
		if (!empty($settings['tunnel_networkv6'])) {
1144
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1145
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1146
			if ($settings['dev_mode'] == 'tun') {
1147
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1148
			} else {
1149
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
1150
			}
1151
		}
1152

    
1153
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1154
			$up_file = "{$g['varetc_path']}/openvpn/{$mode_id}.up";
1155
			$conf .= "auth-user-pass {$up_file}\n";
1156
			if (!$settings['auth-retry-none']) {
1157
				$conf .= "auth-retry nointeract\n";
1158
			}
1159
			if ($settings['auth_user']) {
1160
				$userpass = "{$settings['auth_user']}\n";
1161
			} else {
1162
				$userpass = "";
1163
			}
1164
			if ($settings['auth_pass']) {
1165
				$userpass .= "{$settings['auth_pass']}\n";
1166
			}
1167
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1168
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1169
				$userpass .= "\n";
1170
			}
1171
			file_put_contents($up_file, $userpass);
1172
		}
1173

    
1174
		if ($settings['proxy_addr']) {
1175
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1176
			if ($settings['proxy_authtype'] != "none") {
1177
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
1178
				$proxypas = "{$settings['proxy_user']}\n";
1179
				$proxypas .= "{$settings['proxy_passwd']}\n";
1180
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
1181
			}
1182
			$conf .= " \n";
1183
		}
1184
	}
1185

    
1186
	// Add a remote network route if set, and only for p2p modes.
1187
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
1188
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1189
	}
1190
	// Add a remote network route if set, and only for p2p modes.
1191
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1192
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1193
	}
1194

    
1195
	// Write the settings for the keys
1196
	switch ($settings['mode']) {
1197
		case 'p2p_shared_key':
1198
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1199
			break;
1200
		case 'p2p_tls':
1201
		case 'server_tls':
1202
		case 'server_tls_user':
1203
		case 'server_user':
1204
			// ca_chain() expects parameter to be passed by reference.
1205
			// avoid passing the whole settings array, as param names or
1206
			// types might change in future releases.
1207
			$param = array('caref' => $settings['caref']);
1208
			$ca = ca_chain($param);
1209
			$ca = base64_encode($ca);
1210

    
1211
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1212

    
1213
			unset($ca, $param);
1214

    
1215
			if (!empty($settings['certref'])) {
1216
				$cert = lookup_cert($settings['certref']);
1217
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1218
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1219
			}
1220
			if ($mode == 'server') {
1221
				if (is_numeric($settings['dh_length'])) {
1222
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1223
						/* The user selected a DH parameter length that does not have a corresponding file. */
1224
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1225
						return;
1226
					}
1227
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1228
				} else {
1229
					$dh_file = $settings['dh_length'];
1230
				}
1231
				$conf .= "dh {$dh_file}\n";
1232
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1233
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1234
				}
1235
			}
1236
			if (!empty($settings['crlref'])) {
1237
				$crl = lookup_crl($settings['crlref']);
1238
				crl_update($crl);
1239
				openvpn_add_keyfile($crl['text'], $conf, $mode_id, "crl-verify");
1240
			}
1241
			if ($settings['tls']) {
1242
				if ($settings['tls_type'] == "crypt") {
1243
					$tls_directive = "tls-crypt";
1244
					$tlsopt = "";
1245
				} else {
1246
					$tls_directive = "tls-auth";
1247
					if ($mode == "server") {
1248
						switch($settings['tlsauth_keydir']){
1249
							case '1':
1250
								$tlsopt = 1;
1251
								break;
1252
							case '2':
1253
								$tlsopt = '';
1254
								break;
1255
							default:
1256
								$tlsopt = 0;
1257
								break;
1258
						}
1259
					} else {
1260
						switch($settings['tlsauth_keydir']){
1261
							case '0':
1262
								$tlsopt = 0;
1263
								break;
1264
							case '2':
1265
								$tlsopt = '';
1266
								break;
1267
							default:
1268
								$tlsopt = 1;
1269
								break;
1270
						}
1271
					}
1272
				}
1273
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1274
			}
1275

    
1276
			/* NCP support. If it is not set, assume enabled since that is OpenVPN's default. */
1277
			if ($settings['ncp_enable'] == "disabled") {
1278
				$conf .= "ncp-disable\n";
1279
			} else {
1280
				/* If the ncp-ciphers list is empty, don't specify a list so OpenVPN's default will be used. */
1281
				if (!empty($settings['ncp-ciphers'])) {
1282
					$conf .= "ncp-ciphers " . str_replace(',', ':', $settings['ncp-ciphers']) . "\n";
1283
				}
1284
			}
1285

    
1286
			break;
1287
	}
1288

    
1289
	$compression = "";
1290
	switch ($settings['compression']) {
1291
		case 'none':
1292
			$settings['compression'] = '';
1293
		case 'lz4':
1294
		case 'lz4-v2':
1295
		case 'lzo':
1296
		case 'stub':
1297
		case 'stub-v2':
1298
			$compression .= "compress {$settings['compression']}";
1299
			break;
1300
		case 'noadapt':
1301
			$compression .= "comp-noadapt";
1302
			break;
1303
		case 'adaptive':
1304
		case 'yes':
1305
		case 'no':
1306
			$compression .= "comp-lzo {$settings['compression']}";
1307
			break;
1308
		default:
1309
			/* Add nothing to the configuration */
1310
			break;
1311
	}
1312

    
1313
	if (!empty($compression)) {
1314
		$conf .= "{$compression}\n";
1315
		if ($settings['compression_push']) {
1316
			$conf .= "push \"{$compression}\"\n";
1317
		}
1318
	}
1319

    
1320
	if ($settings['passtos']) {
1321
		$conf .= "passtos\n";
1322
	}
1323

    
1324
	if ($mode == 'client') {
1325
		$conf .= "resolv-retry infinite\n";
1326
	}
1327

    
1328
	if ($settings['dynamic_ip']) {
1329
		$conf .= "persist-remote-ip\n";
1330
		$conf .= "float\n";
1331
	}
1332

    
1333
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1334
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1335
		if (empty($settings['topology'])) {
1336
			$settings['topology'] = "subnet";
1337
		}
1338
		$conf .= "topology {$settings['topology']}\n";
1339
	}
1340

    
1341
	// New client features
1342
	if ($mode == "client") {
1343
		// Dont pull routes checkbox
1344
		if ($settings['route_no_pull']) {
1345
			$conf .= "route-nopull\n";
1346
		}
1347

    
1348
		// Dont add/remove routes checkbox
1349
		if ($settings['route_no_exec']) {
1350
			$conf .= "route-noexec\n";
1351
		}
1352
	}
1353

    
1354
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1355
	if ($settings['udp_fast_io']
1356
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1357
	    && (empty($settings['use_shaper']))) {
1358
		$conf .= "fast-io\n";
1359
	}
1360

    
1361
	/* Send and Receive Buffer Settings */
1362
	if (is_numericint($settings['sndrcvbuf'])
1363
	    && ($settings['sndrcvbuf'] > 0)
1364
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1365
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1366
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1367
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1368
	}
1369

    
1370
	openvpn_add_custom($settings, $conf);
1371

    
1372
	openvpn_create_dirs();
1373
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1374
	file_put_contents($fpath, $conf);
1375
	unset($conf);
1376
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1377
	file_put_contents($fpath, $interface);
1378
	//chown($fpath, 'nobody');
1379
	//chgrp($fpath, 'nobody');
1380
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1381
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1382
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1383
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1384
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1385

    
1386
	if ($wait_tentative) {
1387
		interface_wait_tentative($interface);
1388
	}
1389
}
1390

    
1391
function openvpn_restart($mode, $settings) {
1392
	global $g, $config;
1393

    
1394
	$vpnid = $settings['vpnid'];
1395
	$mode_id = $mode.$vpnid;
1396
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1397
	openvpn_reconfigure($mode, $settings);
1398
	/* kill the process if running */
1399
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1400
	if (file_exists($pfile)) {
1401

    
1402
		/* read the pid file */
1403
		$pid = rtrim(file_get_contents($pfile));
1404
		unlink($pfile);
1405
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1406

    
1407
		/* send a term signal to the process */
1408
		posix_kill($pid, SIGTERM);
1409

    
1410
		/* wait until the process exits, or timeout and kill it */
1411
		$i = 0;
1412
		while (posix_kill($pid, 0)) {
1413
			usleep(250000);
1414
			if ($i > 10) {
1415
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1416
				posix_kill($pid, SIGKILL);
1417
				usleep(500000);
1418
			}
1419
			$i++;
1420
		}
1421
	}
1422

    
1423
	if (isset($settings['disable'])) {
1424
		unlock($lockhandle);
1425
		return;
1426
	}
1427

    
1428
	/* Do not start an instance if we are not CARP master on this vip! */
1429
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1430
		unlock($lockhandle);
1431
		return;
1432
	}
1433

    
1434
	/* Check if client is bound to a gateway group */
1435
	$a_groups = return_gateway_groups_array(true);
1436
	if (is_array($a_groups[$settings['interface']])) {
1437
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1438
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1439
			unlock($lockhandle);
1440
			return;
1441
		}
1442
	}
1443

    
1444
	/* start the new process */
1445
	$fpath = $g['varetc_path']."/openvpn/{$mode_id}.conf";
1446
	openvpn_clear_route($mode, $settings);
1447
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1448
	if ($res == 0) {
1449
		$i = 0;
1450
		$pid = "--";
1451
		while ($i < 3000) {
1452
			if (isvalidpid($pfile)) {
1453
				$pid = rtrim(file_get_contents($pfile));
1454
				break;
1455
			}
1456
			usleep(1000);
1457
			$i++;
1458
		}
1459
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1460
	} else {
1461
		syslog(LOG_ERR, "OpenVPN failed to start");
1462
	}
1463
	if (!platform_booting()) {
1464
		send_event("filter reload");
1465
	}
1466
	unlock($lockhandle);
1467
}
1468

    
1469
function openvpn_delete($mode, $settings) {
1470
	global $g, $config;
1471

    
1472
	$vpnid = $settings['vpnid'];
1473
	$mode_id = $mode.$vpnid;
1474

    
1475
	if ($mode == "server") {
1476
		$devname = "ovpns{$vpnid}";
1477
	} else {
1478
		$devname = "ovpnc{$vpnid}";
1479
	}
1480

    
1481
	/* kill the process if running */
1482
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1483
	if (file_exists($pfile)) {
1484

    
1485
		/* read the pid file */
1486
		$pid = trim(file_get_contents($pfile));
1487
		unlink($pfile);
1488

    
1489
		/* send a term signal to the process */
1490
		posix_kill($pid, SIGTERM);
1491
	}
1492

    
1493
	/* destroy the device */
1494
	pfSense_interface_destroy($devname);
1495

    
1496
	/* remove the configuration files */
1497
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1498
}
1499

    
1500
function openvpn_resync_csc(& $settings) {
1501
	global $g, $config, $openvpn_tls_server_modes;
1502

    
1503
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1504

    
1505
	if (isset($settings['disable'])) {
1506
		openvpn_delete_csc($settings);
1507
		return;
1508
	}
1509
	openvpn_create_dirs();
1510

    
1511
	if (empty($settings['server_list'])) {
1512
		$csc_server_list = array();
1513
	} else {
1514
		$csc_server_list = explode(",", $settings['server_list']);
1515
	}
1516

    
1517
	$conf = '';
1518
	if ($settings['block']) {
1519
		$conf .= "disable\n";
1520
	}
1521

    
1522
	if ($settings['push_reset']) {
1523
		$conf .= "push-reset\n";
1524
	}
1525

    
1526
	if ($settings['local_network']) {
1527
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1528
	}
1529
	if ($settings['local_networkv6']) {
1530
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1531
	}
1532

    
1533
	// Add a remote network iroute if set
1534
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1535
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1536
	}
1537
	// Add a remote network iroute if set
1538
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1539
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1540
	}
1541

    
1542
	openvpn_add_dhcpopts($settings, $conf);
1543

    
1544
	openvpn_add_custom($settings, $conf);
1545
	/* Loop through servers, find which ones can use this CSC */
1546
	if (is_array($config['openvpn']['openvpn-server'])) {
1547
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1548
			if (isset($serversettings['disable'])) {
1549
				continue;
1550
			}
1551
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1552
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1553
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1554
					$csc_conf = $conf;
1555

    
1556
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1557
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1558
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1559
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1560
						} else {
1561
							/* Because this is being pushed, the order from the client's point of view. */
1562
							$baselong = gen_subnetv4($ip, $mask);
1563
							$serverip = ip_after($baselong, 1);
1564
							$clientip = ip_after($baselong, 2);
1565
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1566
						}
1567
					}
1568

    
1569
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1570
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1571
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1572
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1573
					}
1574

    
1575
					file_put_contents($csc_path, $csc_conf);
1576
					chown($csc_path, 'nobody');
1577
					chgrp($csc_path, 'nobody');
1578
				}
1579
			}
1580
		}
1581
	}
1582
}
1583

    
1584
function openvpn_resync_csc_all() {
1585
	global $config;
1586
	if (is_array($config['openvpn']['openvpn-csc'])) {
1587
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1588
			openvpn_resync_csc($settings);
1589
		}
1590
	}
1591
}
1592

    
1593
function openvpn_delete_csc(& $settings) {
1594
	global $g, $config, $openvpn_tls_server_modes;
1595
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1596
	if (empty($settings['server_list'])) {
1597
		$csc_server_list = array();
1598
	} else {
1599
		$csc_server_list = explode(",", $settings['server_list']);
1600
	}
1601

    
1602
	/* Loop through servers, find which ones used this CSC */
1603
	if (is_array($config['openvpn']['openvpn-server'])) {
1604
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1605
			if (isset($serversettings['disable'])) {
1606
				continue;
1607
			}
1608
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1609
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1610
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1611
					unlink_if_exists($csc_path);
1612
				}
1613
			}
1614
		}
1615
	}
1616
}
1617

    
1618
// Resync the configuration and restart the VPN
1619
function openvpn_resync($mode, $settings) {
1620
	openvpn_restart($mode, $settings);
1621
}
1622

    
1623
// Resync and restart all VPNs
1624
function openvpn_resync_all($interface = "") {
1625
	global $g, $config;
1626

    
1627
	openvpn_create_dirs();
1628

    
1629
	if (!is_array($config['openvpn'])) {
1630
		$config['openvpn'] = array();
1631
	}
1632

    
1633
	if ($interface <> "") {
1634
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1635
	} else {
1636
		log_error(gettext("Resyncing OpenVPN instances."));
1637
	}
1638

    
1639
	// Check if OpenVPN clients and servers require a resync.
1640
	foreach (array("server", "client") as $type) {
1641
		if (!is_array($config['openvpn']["openvpn-{$type}"])) {
1642
			continue;
1643
		}
1644
		foreach ($config['openvpn']["openvpn-{$type}"] as & $settings) {
1645
			$fpath = "{$g['varetc_path']}/openvpn/{$type}" .
1646
			    $settings['vpnid'] . ".interface";
1647
			$gw_group_change = FALSE;
1648
			$ip_change = ($interface === "") ||
1649
			    ($interface === $settings['interface']);
1650

    
1651
			if (!$ip_change && file_exists($fpath)) {
1652
				$gw_group_change =
1653
				    (trim(file_get_contents($fpath), " \t\n") !=
1654
				    get_failover_interface(
1655
					$settings['interface']));
1656
			}
1657

    
1658
			if ($ip_change || $gw_group_change) {
1659
				openvpn_resync($type, $settings);
1660
			}
1661
		}
1662
	}
1663

    
1664
	openvpn_resync_csc_all();
1665

    
1666
}
1667

    
1668
// Resync and restart all VPNs using a gateway group.
1669
function openvpn_resync_gwgroup($gwgroupname = "") {
1670
	global $g, $config;
1671

    
1672
	if ($gwgroupname <> "") {
1673
		if (is_array($config['openvpn']['openvpn-server'])) {
1674
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1675
				if ($gwgroupname == $settings['interface']) {
1676
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1677
					openvpn_resync('server', $settings);
1678
				}
1679
			}
1680
		}
1681

    
1682
		if (is_array($config['openvpn']['openvpn-client'])) {
1683
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1684
				if ($gwgroupname == $settings['interface']) {
1685
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1686
					openvpn_resync('client', $settings);
1687
				}
1688
			}
1689
		}
1690

    
1691
		// Note: no need to resysnc Client Specific (csc) here, as changes to the OpenVPN real interface do not effect these.
1692

    
1693
	} else {
1694
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1695
	}
1696
}
1697

    
1698
function openvpn_get_active_servers($type="multipoint") {
1699
	global $config, $g;
1700

    
1701
	$servers = array();
1702
	if (is_array($config['openvpn']['openvpn-server'])) {
1703
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1704
			if (empty($settings) || isset($settings['disable'])) {
1705
				continue;
1706
			}
1707

    
1708
			$prot = $settings['protocol'];
1709
			$port = $settings['local_port'];
1710

    
1711
			$server = array();
1712
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1713
			$server['mode'] = $settings['mode'];
1714
			if ($settings['description']) {
1715
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1716
			} else {
1717
				$server['name'] = "Server {$prot}:{$port}";
1718
			}
1719
			$server['conns'] = array();
1720
			$server['vpnid'] = $settings['vpnid'];
1721
			$server['mgmt'] = "server{$server['vpnid']}";
1722
			$socket = "unix://{$g['varetc_path']}/openvpn/{$server['mgmt']}.sock";
1723
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1724

    
1725
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1726
				$servers[] = openvpn_get_client_status($server, $socket);
1727
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1728
				$servers[] = openvpn_get_server_status($server, $socket);
1729
			}
1730
		}
1731
	}
1732
	return $servers;
1733
}
1734

    
1735
function openvpn_get_server_status($server, $socket) {
1736
	$errval = null;
1737
	$errstr = null;
1738
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1739
	if ($fp) {
1740
		stream_set_timeout($fp, 1);
1741

    
1742
		/* send our status request */
1743
		fputs($fp, "status 2\n");
1744

    
1745
		/* recv all response lines */
1746
		while (!feof($fp)) {
1747

    
1748
			/* read the next line */
1749
			$line = fgets($fp, 1024);
1750

    
1751
			$info = stream_get_meta_data($fp);
1752
			if ($info['timed_out']) {
1753
				break;
1754
			}
1755

    
1756
			/* parse header list line */
1757
			if (strstr($line, "HEADER")) {
1758
				continue;
1759
			}
1760

    
1761
			/* parse end of output line */
1762
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1763
				break;
1764
			}
1765

    
1766
			/* parse client list line */
1767
			if (strstr($line, "CLIENT_LIST")) {
1768
				$list = explode(",", $line);
1769
				$conn = array();
1770
				$conn['common_name'] = $list[1];
1771
				$conn['remote_host'] = $list[2];
1772
				$conn['virtual_addr'] = $list[3];
1773
				$conn['virtual_addr6'] = $list[4];
1774
				$conn['bytes_recv'] = $list[5];
1775
				$conn['bytes_sent'] = $list[6];
1776
				$conn['connect_time'] = $list[7];
1777
				$conn['connect_time_unix'] = $list[8];
1778
				$conn['user_name'] = $list[9];
1779
				$conn['client_id'] = $list[10];
1780
				$conn['peer_id'] = $list[11];
1781
				$server['conns'][] = $conn;
1782
			}
1783
			/* parse routing table lines */
1784
			if (strstr($line, "ROUTING_TABLE")) {
1785
				$list = explode(",", $line);
1786
				$conn = array();
1787
				$conn['virtual_addr'] = $list[1];
1788
				$conn['common_name'] = $list[2];
1789
				$conn['remote_host'] = $list[3];
1790
				$conn['last_time'] = $list[4];
1791
				$server['routes'][] = $conn;
1792
			}
1793
		}
1794

    
1795
		/* cleanup */
1796
		fclose($fp);
1797
	} else {
1798
		$conn = array();
1799
		$conn['common_name'] = "[error]";
1800
		$conn['remote_host'] = gettext("Unable to contact daemon");
1801
		$conn['virtual_addr'] = gettext("Service not running?");
1802
		$conn['bytes_recv'] = 0;
1803
		$conn['bytes_sent'] = 0;
1804
		$conn['connect_time'] = 0;
1805
		$server['conns'][] = $conn;
1806
	}
1807
	return $server;
1808
}
1809

    
1810
function openvpn_get_active_clients() {
1811
	global $config, $g;
1812

    
1813
	$clients = array();
1814
	if (is_array($config['openvpn']['openvpn-client'])) {
1815
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1816

    
1817
			if (empty($settings) || isset($settings['disable'])) {
1818
				continue;
1819
			}
1820

    
1821
			$prot = $settings['protocol'];
1822
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1823

    
1824
			$client = array();
1825
			$client['port'] = $settings['local_port'];
1826
			if ($settings['description']) {
1827
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1828
			} else {
1829
				$client['name'] = "Client {$prot}{$port}";
1830
			}
1831

    
1832
			$client['vpnid'] = $settings['vpnid'];
1833
			$client['mgmt'] = "client{$client['vpnid']}";
1834
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1835
			$client['status']="down";
1836

    
1837
			$clients[] = openvpn_get_client_status($client, $socket);
1838
		}
1839
	}
1840
	return $clients;
1841
}
1842

    
1843
function openvpn_get_client_status($client, $socket) {
1844
	$errval = null;
1845
	$errstr = null;
1846
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1847
	if ($fp) {
1848
		stream_set_timeout($fp, 1);
1849
		/* send our status request */
1850
		fputs($fp, "state 1\n");
1851

    
1852
		/* recv all response lines */
1853
		while (!feof($fp)) {
1854
			/* read the next line */
1855
			$line = fgets($fp, 1024);
1856

    
1857
			$info = stream_get_meta_data($fp);
1858
			if ($info['timed_out']) {
1859
				break;
1860
			}
1861

    
1862
			/* Get the client state */
1863
			if (strstr($line, "CONNECTED")) {
1864
				$client['status'] = "up";
1865
				$list = explode(",", $line);
1866

    
1867
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1868
				$client['virtual_addr'] = $list[3];
1869
				$client['remote_host'] = $list[4];
1870
				$client['remote_port'] = $list[5];
1871
				$client['local_host'] = $list[6];
1872
				$client['local_port'] = $list[7];
1873
				$client['virtual_addr6'] = $list[8];
1874
			}
1875
			if (strstr($line, "CONNECTING")) {
1876
				$client['status'] = "connecting";
1877
			}
1878
			if (strstr($line, "ASSIGN_IP")) {
1879
				$client['status'] = "waiting";
1880
				$list = explode(",", $line);
1881

    
1882
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1883
				$client['virtual_addr'] = $list[3];
1884
			}
1885
			if (strstr($line, "RECONNECTING")) {
1886
				$client['status'] = "reconnecting";
1887
				$list = explode(",", $line);
1888

    
1889
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1890
				$client['status'] .= "; " . $list[2];
1891
			}
1892
			/* parse end of output line */
1893
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1894
				break;
1895
			}
1896
		}
1897

    
1898
		/* If up, get read/write stats */
1899
		if (strcmp($client['status'], "up") == 0) {
1900
			fputs($fp, "status 2\n");
1901
			/* recv all response lines */
1902
			while (!feof($fp)) {
1903
				/* read the next line */
1904
				$line = fgets($fp, 1024);
1905

    
1906
				$info = stream_get_meta_data($fp);
1907
				if ($info['timed_out']) {
1908
					break;
1909
				}
1910

    
1911
				if (strstr($line, "TCP/UDP read bytes")) {
1912
					$list = explode(",", $line);
1913
					$client['bytes_recv'] = $list[1];
1914
				}
1915

    
1916
				if (strstr($line, "TCP/UDP write bytes")) {
1917
					$list = explode(",", $line);
1918
					$client['bytes_sent'] = $list[1];
1919
				}
1920

    
1921
				/* parse end of output line */
1922
				if (strstr($line, "END")) {
1923
					break;
1924
				}
1925
			}
1926
		}
1927

    
1928
		fclose($fp);
1929

    
1930
	} else {
1931
		$client['remote_host'] = gettext("Unable to contact daemon");
1932
		$client['virtual_addr'] = gettext("Service not running?");
1933
		$client['bytes_recv'] = 0;
1934
		$client['bytes_sent'] = 0;
1935
		$client['connect_time'] = 0;
1936
	}
1937
	return $client;
1938
}
1939

    
1940
function openvpn_kill_client($port, $remipp) {
1941
	global $g;
1942

    
1943
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1944
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1945
	$errval = null;
1946
	$errstr = null;
1947

    
1948
	/* open a tcp connection to the management port of each server */
1949
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1950
	$killed = -1;
1951
	if ($fp) {
1952
		stream_set_timeout($fp, 1);
1953
		fputs($fp, "kill {$remipp}\n");
1954
		while (!feof($fp)) {
1955
			$line = fgets($fp, 1024);
1956

    
1957
			$info = stream_get_meta_data($fp);
1958
			if ($info['timed_out']) {
1959
				break;
1960
			}
1961

    
1962
			/* parse header list line */
1963
			if (strpos($line, "INFO:") !== false) {
1964
				continue;
1965
			}
1966
			if (strpos($line, "SUCCESS") !== false) {
1967
				$killed = 0;
1968
			}
1969
			break;
1970
		}
1971
		fclose($fp);
1972
	}
1973
	return $killed;
1974
}
1975

    
1976
function openvpn_refresh_crls() {
1977
	global $g, $config;
1978

    
1979
	openvpn_create_dirs();
1980

    
1981
	if (is_array($config['openvpn']['openvpn-server'])) {
1982
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
1983
			if (empty($settings)) {
1984
				continue;
1985
			}
1986
			if (isset($settings['disable'])) {
1987
				continue;
1988
			}
1989
			// Write the settings for the keys
1990
			switch ($settings['mode']) {
1991
				case 'p2p_tls':
1992
				case 'server_tls':
1993
				case 'server_tls_user':
1994
				case 'server_user':
1995
					if (!empty($settings['crlref'])) {
1996
						$crl = lookup_crl($settings['crlref']);
1997
						crl_update($crl);
1998
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
1999
						file_put_contents($fpath, base64_decode($crl['text']));
2000
						@chmod($fpath, 0644);
2001
					}
2002
					break;
2003
			}
2004
		}
2005
	}
2006
}
2007

    
2008
function openvpn_create_dirs() {
2009
	global $g, $config, $openvpn_tls_server_modes;
2010
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
2011
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
2012
	}
2013
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
2014
		/* If it's a file, remove it */
2015
		if (file_exists("{$g['varetc_path']}/openvpn-csc")) {
2016
			unlink_if_exists("{$g['varetc_path']}/openvpn-csc");
2017
		}
2018
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
2019
	}
2020

    
2021
	/* Check for enabled servers and create server-specific CSC dirs */
2022
	if (is_array($config['openvpn']['openvpn-server'])) {
2023
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2024
			if (isset($settings['disable'])) {
2025
				continue;
2026
			}
2027
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2028
				if ($settings['vpnid']) {
2029
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
2030
				}
2031
			}
2032
		}
2033
	}
2034
}
2035

    
2036
function openvpn_get_interface_ip($ip, $cidr) {
2037
	$subnet = gen_subnetv4($ip, $cidr);
2038
	if ($cidr == 31) {
2039
		$ip1 = $subnet;
2040
	} else {
2041
		$ip1 = ip_after($subnet);
2042
	}
2043
	$ip2 = ip_after($ip1);
2044
	return array($ip1, $ip2);
2045
}
2046

    
2047
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2048
	$basev6 = gen_subnetv6($ipv6, $prefix);
2049
	// Is there a better way to do this math?
2050
	$ipv6_arr = explode(':', $basev6);
2051
	$last = hexdec(array_pop($ipv6_arr));
2052
	if ($prefix == 127) {
2053
		$last--;
2054
	}
2055
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2056
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2057
	return array($ipv6_1, $ipv6_2);
2058
}
2059

    
2060
function openvpn_clear_route($mode, $settings) {
2061
	if (empty($settings['tunnel_network'])) {
2062
		return;
2063
	}
2064
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
2065
	$mask = gen_subnet_mask($cidr);
2066
	$clear_route = false;
2067

    
2068
	switch ($settings['mode']) {
2069
		case 'shared_key':
2070
			$clear_route = true;
2071
			break;
2072
		case 'p2p_tls':
2073
		case 'p2p_shared_key':
2074
			if ($cidr >= 30) {
2075
				$clear_route = true;
2076
			}
2077
			break;
2078
	}
2079

    
2080
	if ($clear_route && !empty($ip) && !empty($mask)) {
2081
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2082
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2083
		/* XXX: Family for route? */
2084
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2085
	}
2086
}
2087

    
2088
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2089
	$routes = "";
2090
	if (empty($value)) {
2091
		return "";
2092
	}
2093
	$networks = explode(',', $value);
2094

    
2095
	foreach ($networks as $network) {
2096
		if ($ipproto == "ipv4") {
2097
			$route = openvpn_gen_route_ipv4($network, $iroute);
2098
		} else {
2099
			$route = openvpn_gen_route_ipv6($network, $iroute);
2100
		}
2101

    
2102
		if ($push) {
2103
			$routes .= "push \"{$route}\"\n";
2104
		} else {
2105
			$routes .= "{$route}\n";
2106
		}
2107
	}
2108
	return $routes;
2109
}
2110

    
2111
function openvpn_gen_route_ipv4($network, $iroute = false) {
2112
	$i = ($iroute) ? "i" : "";
2113
	list($ip, $mask) = explode('/', trim($network));
2114
	$mask = gen_subnet_mask($mask);
2115
	return "{$i}route $ip $mask";
2116
}
2117

    
2118
function openvpn_gen_route_ipv6($network, $iroute = false) {
2119
	$i = ($iroute) ? "i" : "";
2120
	list($ipv6, $prefix) = explode('/', trim($network));
2121
	if (empty($prefix) && !is_numeric($prefix)) {
2122
		$prefix = "128";
2123
	}
2124
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2125
}
2126

    
2127
function openvpn_get_settings($mode, $vpnid) {
2128
	global $config;
2129

    
2130
	if (is_array($config['openvpn']['openvpn-server'])) {
2131
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2132
			if (isset($settings['disable'])) {
2133
				continue;
2134
			}
2135

    
2136
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2137
				return $settings;
2138
			}
2139
		}
2140
	}
2141

    
2142
	if (is_array($config['openvpn']['openvpn-client'])) {
2143
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2144
			if (isset($settings['disable'])) {
2145
				continue;
2146
			}
2147

    
2148
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2149
				return $settings;
2150
			}
2151
		}
2152
	}
2153

    
2154
	return array();
2155
}
2156

    
2157
function openvpn_restart_by_vpnid($mode, $vpnid) {
2158
	$settings = openvpn_get_settings($mode, $vpnid);
2159
	openvpn_restart($mode, $settings);
2160
}
2161

    
2162
?>
(33-33/59)