Project

General

Profile

Download (64.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-2020 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
global $openvpn_exit_notify_server;
172
$openvpn_exit_notify_server = array(
173
	'none' => gettext("Disabled"),
174
	'1' => gettext("Reconnect to this server / Retry once"),
175
	'2' => gettext("Reconnect to next server / Retry twice"),
176
);
177

    
178
global $openvpn_exit_notify_client;
179
$openvpn_exit_notify_client = array(
180
	'none' => gettext("Disabled"),
181
);
182
for ($i=1; $i<=5; $i++) {
183
	$openvpn_exit_notify_client[$i] = sprintf(gettext("Retry %dx"), $i);
184
}
185

    
186
function openvpn_build_mode_list() {
187
	global $openvpn_server_modes;
188

    
189
	$list = array();
190

    
191
	foreach ($openvpn_server_modes as $name => $desc) {
192
		$list[$name] = $desc;
193
	}
194

    
195
	return($list);
196
}
197

    
198
global $openvpn_interfacenames;
199
function convert_openvpn_interface_to_friendly_descr($if) {
200
	global $openvpn_interfacenames;
201
	if (!is_array($openvpn_interfacenames)) {
202
		$openvpn_interfacenames = openvpn_build_if_list();
203
	}
204
	foreach($openvpn_interfacenames as $key => $value) {
205
		list($item_if, $item_ip) = explode("|", $key);
206
		if ($if == $item_if) {
207
			echo "$value";
208
		}
209
	}
210
}
211

    
212
function openvpn_build_if_list() {
213
	$list = array();
214

    
215
	$interfaces = get_configured_interface_with_descr();
216
	$viplist = get_configured_vip_list();
217
	foreach ($viplist as $vip => $address) {
218
		$interfaces[$vip.'|'.$address] = $address;
219
		if (get_vip_descr($address)) {
220
			$interfaces[$vip.'|'.$address] .= " (";
221
			$interfaces[$vip.'|'.$address] .= get_vip_descr($address);
222
			$interfaces[$vip.'|'.$address] .= ")";
223
		}
224
	}
225

    
226
	$grouplist = return_gateway_groups_array();
227
	foreach ($grouplist as $name => $group) {
228
		if ($group[0]['vip'] != "") {
229
			$vipif = $group[0]['vip'];
230
		} else {
231
			$vipif = $group[0]['int'];
232
		}
233

    
234
		$interfaces[$name] = "GW Group {$name}";
235
	}
236

    
237
	$interfaces['lo0'] = "Localhost";
238
	$interfaces['any'] = "any";
239

    
240
	foreach ($interfaces as $iface => $ifacename) {
241
	   $list[$iface] = $ifacename;
242
	}
243

    
244
	return($list);
245
}
246

    
247
function openvpn_build_crl_list() {
248
	global $a_crl;
249

    
250
	$list = array('' => 'None');
251

    
252
	foreach ($a_crl as $crl) {
253
		$caname = "";
254
		$ca = lookup_ca($crl['caref']);
255

    
256
		if ($ca) {
257
			$caname = " (CA: {$ca['descr']})";
258
		}
259

    
260
		$list[$crl['refid']] = $crl['descr'] . $caname;
261
	}
262

    
263
	return($list);
264
}
265

    
266
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
267
	global $a_cert;
268
	$openvpn_compatible_certs = cert_build_list('cert', 'OpenVPN');
269

    
270
	if ($include_none) {
271
		$list = array('' => gettext('None (Username and/or Password required)'));
272
	} else {
273
		$list = array();
274
	}
275

    
276
	$non_server_list = array();
277

    
278
	if ($prioritize_server_certs) {
279
		$list[' '] = gettext("===== Server Certificates =====");
280
		$non_server_list['  '] = gettext("===== Non-Server Certificates =====");
281
	}
282

    
283
	foreach ($a_cert as $cert) {
284
		if (!array_key_exists($cert['refid'], $openvpn_compatible_certs)) {
285
			continue;
286
		}
287
		$properties = array();
288
		$propstr = "";
289
		$ca = lookup_ca($cert['caref']);
290
		$purpose = cert_get_purpose($cert['crt'], true);
291

    
292
		if ($purpose['server'] == "Yes") {
293
			$properties[] = gettext("Server: Yes");
294
		} elseif ($prioritize_server_certs) {
295
			$properties[] = gettext("Server: NO");
296
		}
297
		if ($ca) {
298
			$properties[] = sprintf(gettext("CA: %s"), $ca['descr']);
299
		}
300
		if (cert_in_use($cert['refid'])) {
301
			$properties[] = gettext("In Use");
302
		}
303
		if (is_cert_revoked($cert)) {
304
			$properties[] = gettext("Revoked");
305
		}
306

    
307
		if (!empty($properties)) {
308
			$propstr = " (" . implode(", ", $properties) . ")";
309
		}
310

    
311
		if ($prioritize_server_certs) {
312
			if ($purpose['server'] == "Yes") {
313
				$list[$cert['refid']] = $cert['descr'] . $propstr;
314
			} else {
315
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
316
			}
317
		} else {
318
			$list[$cert['refid']] = $cert['descr'] . $propstr;
319
		}
320
	}
321

    
322
	return(array('server' => $list, 'non-server' => $non_server_list));
323
}
324

    
325
function openvpn_build_bridge_list() {
326
	$list = array();
327

    
328
	$serverbridge_interface['none'] = "none";
329
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
330
	$viplist = get_configured_vip_list();
331

    
332
	foreach ($viplist as $vip => $address) {
333
		$serverbridge_interface[$vip.'|'.$address] = $address;
334
		if (get_vip_descr($address)) {
335
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
336
		}
337
	}
338

    
339
	foreach ($serverbridge_interface as $iface => $ifacename) {
340
		$list[$iface] = htmlspecialchars($ifacename);
341
	}
342

    
343
	return($list);
344
}
345

    
346
function openvpn_create_key() {
347

    
348
	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
349
	if (!$fp) {
350
		return false;
351
	}
352

    
353
	$rslt = stream_get_contents($fp);
354
	pclose($fp);
355

    
356
	return $rslt;
357
}
358

    
359
function openvpn_create_dhparams($bits) {
360

    
361
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
362
	if (!$fp) {
363
		return false;
364
	}
365

    
366
	$rslt = stream_get_contents($fp);
367
	pclose($fp);
368

    
369
	return $rslt;
370
}
371

    
372
function openvpn_vpnid_used($vpnid) {
373
	global $config;
374

    
375
	if (is_array($config['openvpn']['openvpn-server'])) {
376
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
377
			if ($vpnid == $settings['vpnid']) {
378
				return true;
379
			}
380
		}
381
	}
382

    
383
	if (is_array($config['openvpn']['openvpn-client'])) {
384
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
385
			if ($vpnid == $settings['vpnid']) {
386
				return true;
387
			}
388
		}
389
	}
390

    
391
	return false;
392
}
393

    
394
function openvpn_vpnid_next() {
395

    
396
	$vpnid = 1;
397
	while (openvpn_vpnid_used($vpnid)) {
398
		$vpnid++;
399
	}
400

    
401
	return $vpnid;
402
}
403

    
404
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
405
	global $config;
406

    
407
	$ovpn_settings = array();
408
	if (is_array($config['openvpn']['openvpn-server'])) {
409
		$ovpn_settings = $config['openvpn']['openvpn-server'];
410
	}
411
	if (is_array($config['openvpn']['openvpn-client'])) {
412
		$ovpn_settings = array_merge($ovpn_settings,
413
		    $config['openvpn']['openvpn-client']);
414
	}
415

    
416
	foreach ($ovpn_settings as $settings) {
417
		if (isset($settings['disable'])) {
418
			continue;
419
		}
420

    
421
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
422
			continue;
423
		}
424

    
425
		/* (TCP|UDP)(4|6) does not conflict unless interface is any */
426
		if (($interface != "any" && $settings['interface'] != "any") &&
427
		    (strlen($prot) == 4) &&
428
		    (strlen($settings['protocol']) == 4) &&
429
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
430
		    substr($prot,3,1) != substr($settings['protocol'],3,1)) {
431
			continue;
432
		}
433

    
434
		if ($port == $settings['local_port'] &&
435
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
436
		    ($interface == $settings['interface'] ||
437
		    $interface == "any" || $settings['interface'] == "any")) {
438
			return $settings['vpnid'];
439
		}
440
	}
441

    
442
	return 0;
443
}
444

    
445
function openvpn_port_next($prot, $interface = "wan") {
446

    
447
	$port = 1194;
448
	while (openvpn_port_used($prot, $interface, $port)) {
449
		$port++;
450
	}
451
	while (openvpn_port_used($prot, "any", $port)) {
452
		$port++;
453
	}
454

    
455
	return $port;
456
}
457

    
458
function openvpn_get_cipherlist() {
459

    
460
	$ciphers = array();
461
	$cipher_out = shell_exec('/usr/local/sbin/openvpn --show-ciphers | /usr/bin/grep \'(.*key\' | sed \'s/, TLS client\/server mode only//\'');
462
	$cipher_lines = explode("\n", trim($cipher_out));
463
	sort($cipher_lines);
464
	foreach ($cipher_lines as $line) {
465
		$words = explode(' ', $line, 2);
466
		$ciphers[$words[0]] = "{$words[0]} {$words[1]}";
467
	}
468
	$ciphers["none"] = gettext("None (No Encryption)");
469
	return $ciphers;
470
}
471

    
472
function openvpn_get_curvelist() {
473
	global $cert_curve_compatible;
474
	$curves = array();
475
	$curves["none"] = gettext("Use Default");
476
	foreach ($cert_curve_compatible['OpenVPN'] as $curve) {
477
		$curves[$curve] = $curve;
478
	}
479
	return $curves;
480
}
481

    
482
function openvpn_validate_curve($curve) {
483
	$curves = openvpn_get_curvelist();
484
	return array_key_exists($curve, $curves);
485
}
486

    
487
/* Obtain the list of digest algorithms supported by openssl and their alternate names */
488
function openvpn_get_openssldigestmappings() {
489
	$digests = array();
490
	$digest_out = shell_exec('/usr/bin/openssl list-message-digest-algorithms | /usr/bin/grep "=>"');
491
	$digest_lines = explode("\n", trim($digest_out));
492
	sort($digest_lines);
493
	foreach ($digest_lines as $line) {
494
		$words = explode(' => ', $line, 2);
495
		$digests[$words[0]] = $words[1];
496
	}
497
	return $digests;
498
}
499

    
500
/* Obtain the list of digest algorithms supported by openvpn */
501
function openvpn_get_digestlist() {
502
	/* Grab the list from OpenSSL to check for duplicates or aliases */
503
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
504
	$digests = array();
505
	$digest_out = shell_exec('/usr/local/sbin/openvpn --show-digests | /usr/bin/grep "digest size" | /usr/bin/awk \'{print $1, "(" $2 "-" $3 ")";}\'');
506
	$digest_lines = explode("\n", trim($digest_out));
507
	sort($digest_lines);
508
	foreach ($digest_lines as $line) {
509
		$words = explode(' ', $line);
510
		/* Only add the entry if it is NOT also listed as being an alias/mapping by OpenSSL */
511
		if (!array_key_exists($words[0], $openssl_digest_mappings)) {
512
			$digests[$words[0]] = "{$words[0]} {$words[1]}";
513
		}
514
	}
515
	$digests["none"] = gettext("None (No Authentication)");
516
	return $digests;
517
}
518

    
519
/* Check to see if a digest name is an alias and if so, find the actual digest
520
 * algorithm instead. Useful for upgrade code that has to translate aliased
521
 * algorithms to their actual names.
522
 */
523
function openvpn_remap_digest($digest) {
524
	$openssl_digest_mappings = openvpn_get_openssldigestmappings();
525
	if (array_key_exists($digest, $openssl_digest_mappings)) {
526
		/* Some mappings point to other mappings, keep going until we find the actual digest algorithm */
527
		if (array_key_exists($openssl_digest_mappings[$digest], $openssl_digest_mappings)) {
528
			return openvpn_remap_digest($openssl_digest_mappings[$digest]);
529
		} else {
530
			return $openssl_digest_mappings[$digest];
531
		}
532
	}
533
	return $digest;
534
}
535

    
536
function openvpn_get_keydirlist() {
537
	$keydirs = array(
538
		'default'  => gettext('Use default direction'),
539
		'0' => gettext('Direction 0'),
540
		'1' => gettext('Direction 1'),
541
		'2' => gettext('Both directions'),
542
	);
543
	return $keydirs;
544
}
545

    
546
function openvpn_get_engines() {
547
	$openssl_engines = array('none' => gettext('No Hardware Crypto Acceleration'));
548
	exec("/usr/bin/openssl engine -t -c", $openssl_engine_output);
549
	$openssl_engine_output = implode("\n", $openssl_engine_output);
550
	$openssl_engine_output = preg_replace("/\\n\\s+/", "|", $openssl_engine_output);
551
	$openssl_engine_output = explode("\n", $openssl_engine_output);
552

    
553
	foreach ($openssl_engine_output as $oeo) {
554
		$keep = true;
555
		$details = explode("|", $oeo);
556
		$engine = array_shift($details);
557
		$linematch = array();
558
		preg_match("/\((.*)\)\s(.*)/", $engine, $linematch);
559
		foreach ($details as $dt) {
560
			if (strpos($dt, "unavailable") !== FALSE) {
561
				$keep = false;
562
			}
563
			if (strpos($dt, "available") !== FALSE) {
564
				continue;
565
			}
566
			if (strpos($dt, "[") !== FALSE) {
567
				$ciphers = trim($dt, "[]");
568
			}
569
		}
570
		if (!empty($ciphers)) {
571
			$ciphers = " - " . $ciphers;
572
		}
573
		if (strlen($ciphers) > 60) {
574
			$ciphers = substr($ciphers, 0, 60) . " ... ";
575
		}
576
		if ($keep) {
577
			$openssl_engines[$linematch[1]] = $linematch[2] . $ciphers;
578
		}
579
	}
580
	return $openssl_engines;
581
}
582

    
583
function openvpn_get_buffer_values() {
584
	$sendbuf_max = get_single_sysctl('net.inet.tcp.sendbuf_max');
585
	$recvbuf_max = get_single_sysctl('net.inet.tcp.recvbuf_max');
586
	/* Usually these two are equal, but if they are not, take whichever one is lower. */
587
	$buffer_max = ($sendbuf_max <= $recvbuf_max) ? $sendbuf_max : $recvbuf_max;
588
	$buffer_values = array('' => gettext('Default'));
589
	for ($bs = 32; $bs >= 1; $bs /= 2) {
590
		$buffer_values[$buffer_max/$bs] = format_bytes($buffer_max/$bs);
591
	}
592
	return $buffer_values;
593
}
594

    
595
function openvpn_validate_engine($engine) {
596
	$engines = openvpn_get_engines();
597
	return array_key_exists($engine, $engines);
598
}
599

    
600
function openvpn_validate_host($value, $name) {
601
	$value = trim($value);
602
	if (empty($value) || (!is_domain($value) && !is_ipaddr($value))) {
603
		return sprintf(gettext("The field '%s' must contain a valid IP address or domain name."), $name);
604
	}
605
	return false;
606
}
607

    
608
function openvpn_validate_port($value, $name, $first_port = 0) {
609
	$value = trim($value);
610
	if (!is_numeric($first_port)) {
611
		$first_port = 0;
612
	}
613
	if (empty($value) || !is_numeric($value) || $value < $first_port || ($value > 65535)) {
614
		return sprintf(gettext("The field '%s' must contain a valid port, ranging from %s to 65535."), $name, $first_port);
615
	}
616
	return false;
617
}
618

    
619
function openvpn_validate_cidr($value, $name, $multiple = false, $ipproto = "ipv4") {
620
	$value = trim($value);
621
	$error = false;
622
	if (empty($value)) {
623
		return false;
624
	}
625
	$networks = explode(',', $value);
626

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

    
631
	foreach ($networks as $network) {
632
		if ($ipproto == "ipv4") {
633
			$error = !openvpn_validate_cidr_ipv4($network);
634
		} else {
635
			$error = !openvpn_validate_cidr_ipv6($network);
636
		}
637
		if ($error) {
638
			break;
639
		}
640
	}
641

    
642
	if ($error) {
643
		return sprintf(gettext("The field '%1\$s' must contain only valid %2\$s CIDR range(s) separated by commas."), $name, $ipproto);
644
	} else {
645
		return false;
646
	}
647
}
648

    
649
function openvpn_validate_cidr_ipv4($value) {
650
	$value = trim($value);
651
	if (!empty($value)) {
652
		list($ip, $mask) = explode('/', $value);
653
		if (!is_ipaddrv4($ip) or !is_numeric($mask) or ($mask > 32) or ($mask < 0)) {
654
			return false;
655
		}
656
	}
657
	return true;
658
}
659

    
660
function openvpn_validate_cidr_ipv6($value) {
661
	$value = trim($value);
662
	if (!empty($value)) {
663
		list($ipv6, $prefix) = explode('/', $value);
664
		if (empty($prefix)) {
665
			$prefix = "128";
666
		}
667
		if (!is_ipaddrv6($ipv6) or !is_numeric($prefix) or ($prefix > 128) or ($prefix < 0)) {
668
			return false;
669
		}
670
	}
671
	return true;
672
}
673

    
674
function openvpn_add_dhcpopts(& $settings, & $conf) {
675

    
676
	if (!empty($settings['dns_domain'])) {
677
		$conf .= "push \"dhcp-option DOMAIN {$settings['dns_domain']}\"\n";
678
	}
679

    
680
	if (!empty($settings['dns_server1'])) {
681
		$dnstype = (is_ipaddrv6($settings['dns_server1'])) ? "DNS6" : "DNS";
682
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server1']}\"\n";
683
	}
684
	if (!empty($settings['dns_server2'])) {
685
		$dnstype = (is_ipaddrv6($settings['dns_server2'])) ? "DNS6" : "DNS";
686
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server2']}\"\n";
687
	}
688
	if (!empty($settings['dns_server3'])) {
689
		$dnstype = (is_ipaddrv6($settings['dns_server3'])) ? "DNS6" : "DNS";
690
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server3']}\"\n";
691
	}
692
	if (!empty($settings['dns_server4'])) {
693
		$dnstype = (is_ipaddrv6($settings['dns_server4'])) ? "DNS6" : "DNS";
694
		$conf .= "push \"dhcp-option {$dnstype} {$settings['dns_server4']}\"\n";
695
	}
696

    
697
	if (!empty($settings['push_blockoutsidedns'])) {
698
		$conf .= "push \"block-outside-dns\"\n";
699
	}
700
	if (!empty($settings['push_register_dns'])) {
701
		$conf .= "push \"register-dns\"\n";
702
	}
703

    
704
	if (!empty($settings['ntp_server1'])) {
705
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server1']}\"\n";
706
	}
707
	if (!empty($settings['ntp_server2'])) {
708
		$conf .= "push \"dhcp-option NTP {$settings['ntp_server2']}\"\n";
709
	}
710

    
711
	if ($settings['netbios_enable']) {
712

    
713
		if (!empty($settings['dhcp_nbttype']) && ($settings['dhcp_nbttype'] != 0)) {
714
			$conf .= "push \"dhcp-option NBT {$settings['dhcp_nbttype']}\"\n";
715
		}
716
		if (!empty($settings['dhcp_nbtscope'])) {
717
			$conf .= "push \"dhcp-option NBS {$settings['dhcp_nbtscope']}\"\n";
718
		}
719

    
720
		if (!empty($settings['wins_server1'])) {
721
			$conf .= "push \"dhcp-option WINS {$settings['wins_server1']}\"\n";
722
		}
723
		if (!empty($settings['wins_server2'])) {
724
			$conf .= "push \"dhcp-option WINS {$settings['wins_server2']}\"\n";
725
		}
726

    
727
		if (!empty($settings['nbdd_server1'])) {
728
			$conf .= "push \"dhcp-option NBDD {$settings['nbdd_server1']}\"\n";
729
		}
730
	}
731

    
732
	if ($settings['gwredir']) {
733
		$conf .= "push \"redirect-gateway def1\"\n";
734
	}
735
	if ($settings['gwredir6']) {
736
		$conf .= "push \"redirect-gateway ipv6\"\n";
737
	}
738
}
739

    
740
function openvpn_add_custom(& $settings, & $conf) {
741

    
742
	if ($settings['custom_options']) {
743

    
744
		$options = explode(';', $settings['custom_options']);
745

    
746
		if (is_array($options)) {
747
			foreach ($options as $option) {
748
				$conf .= "$option\n";
749
			}
750
		} else {
751
			$conf .= "{$settings['custom_options']}\n";
752
		}
753
	}
754
}
755

    
756
function openvpn_add_keyfile(& $data, & $conf, $mode_id, $directive, $opt = "") {
757
	global $g;
758

    
759
	$fpath = "{$g['openvpn_base']}/{$mode_id}/{$directive}";
760
	openvpn_create_dirs();
761
	file_put_contents($fpath, base64_decode($data));
762
	//chown($fpath, 'nobody');
763
	//chgrp($fpath, 'nobody');
764
	@chmod($fpath, 0600);
765

    
766
	$conf .= "{$directive} {$fpath} {$opt}\n";
767
}
768

    
769
function openvpn_reconfigure($mode, $settings) {
770
	global $g, $config, $openvpn_tls_server_modes, $openvpn_dh_lengths, $openvpn_default_keepalive_interval, $openvpn_default_keepalive_timeout;
771

    
772
	if (empty($settings)) {
773
		return;
774
	}
775
	if (isset($settings['disable'])) {
776
		return;
777
	}
778
	openvpn_create_dirs();
779
	/*
780
	 * NOTE: Deleting tap devices causes spontaneous reboots. Instead,
781
	 * we use a vpnid number which is allocated for a particular client
782
	 * or server configuration. ( see openvpn_vpnid_next() )
783
	 */
784

    
785
	$vpnid = $settings['vpnid'];
786
	$mode_id = $mode.$vpnid;
787

    
788
	if (isset($settings['dev_mode'])) {
789
		$tunname = "{$settings['dev_mode']}{$vpnid}";
790
	} else {
791
		/* defaults to tun */
792
		$tunname = "tun{$vpnid}";
793
		$settings['dev_mode'] = "tun";
794
	}
795

    
796
	if ($mode == "server") {
797
		$devname = "ovpns{$vpnid}";
798
	} else {
799
		$devname = "ovpnc{$vpnid}";
800
	}
801

    
802
	/* is our device already configured */
803
	if (!does_interface_exist($devname)) {
804

    
805
		/* create the tap device if required */
806
		if (!file_exists("/dev/{$tunname}")) {
807
			exec("/sbin/ifconfig " . escapeshellarg($tunname) . " create");
808
		}
809

    
810
		/* rename the device */
811
		mwexec("/sbin/ifconfig " . escapeshellarg($tunname) . " name " . escapeshellarg($devname));
812

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

    
816
		$ifname = convert_real_interface_to_friendly_interface_name($devname);
817
		$grouptmp = link_interface_to_group($ifname);
818
		if (!empty($grouptmp)) {
819
			array_walk($grouptmp, 'interface_group_add_member');
820
		}
821
		unset($grouptmp, $ifname);
822
	}
823

    
824
	$pfile = $g['varrun_path'] . "/openvpn_{$mode_id}.pid";
825
	$proto = strtolower($settings['protocol']);
826
	if (substr($settings['protocol'], 0, 3) == "TCP") {
827
			$proto = "{$proto}-{$mode}";
828
	}
829
	$dev_mode = $settings['dev_mode'];
830
	$cipher = $settings['crypto'];
831
	// OpenVPN defaults to SHA1, so use it when unset to maintain compatibility.
832
	$digest = !empty($settings['digest']) ? $settings['digest'] : "SHA1";
833

    
834
	$interface = get_failover_interface($settings['interface']);
835
	// The IP address in the settings can be an IPv4 or IPv6 address associated with the interface
836
	$ipaddr = $settings['ipaddr'];
837

    
838
	// If a specific ip address (VIP) is requested, use it.
839
	// Otherwise, if a specific interface is requested, use it
840
	// If "any" interface was selected, local directive will be omitted.
841
	if (is_ipaddrv4($ipaddr)) {
842
		$iface_ip = $ipaddr;
843
	} elseif (!empty($interface) && strcmp($interface, "any")) {
844
		$iface_ip=get_interface_ip($interface);
845
	}
846
	if (is_ipaddrv6($ipaddr)) {
847
		$iface_ipv6 = $ipaddr;
848
	} elseif (!empty($interface) && strcmp($interface, "any")) {
849
		$iface_ipv6=get_interface_ipv6($interface);
850
	}
851

    
852
	$conf = "dev {$devname}\n";
853
	if (isset($settings['verbosity_level'])) {
854
		$conf .= "verb {$settings['verbosity_level']}\n";
855
	}
856

    
857
	$conf .= "dev-type {$settings['dev_mode']}\n";
858
	$conf .= "dev-node /dev/{$tunname}\n";
859
	$conf .= "writepid {$pfile}\n";
860
	$conf .= "#user nobody\n";
861
	$conf .= "#group nobody\n";
862
	$conf .= "script-security 3\n";
863
	$conf .= "daemon\n";
864

    
865
	if (!empty($settings['inactive_seconds'])) {
866
		$conf .= "inactive {$settings['inactive_seconds']}\n";
867
	}
868

    
869
	if (!empty($settings['ping_method']) &&
870
	    $settings['ping_method'] == 'ping') {
871
		$conf .= "ping {$settings['ping_seconds']}\n";
872

    
873
		if (!empty($settings['ping_push'])) {
874
			$conf .= "push \"ping {$settings['ping_seconds']}\"\n";
875
		}
876

    
877
		$action = str_replace("_", "-", $settings['ping_action']);
878
		$conf .= "{$action} {$settings['ping_action_seconds']}\n";
879

    
880
		if (!empty($settings['ping_action_push'])) {
881
			$conf .= "push \"{$action} " .
882
			    "{$settings['ping_action_seconds']}\"\n";
883
		}
884
	} else {
885
		$conf .= "keepalive " .
886
		    ($settings['keepalive_interval']
887
			?: $openvpn_default_keepalive_interval) . " " .
888
		    ($settings['keepalive_timeout']
889
			?: $openvpn_default_keepalive_timeout) . "\n";
890
	}
891

    
892
	$conf .= "ping-timer-rem\n";
893
	$conf .= "persist-tun\n";
894
	$conf .= "persist-key\n";
895
	$conf .= "proto {$proto}\n";
896
	$conf .= "cipher {$cipher}\n";
897
	$conf .= "auth {$digest}\n";
898
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
899
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
900
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
901
		switch ($settings['mode']) {
902
			case 'server_user':
903
			case 'server_tls_user':
904
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
905
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
906
				break;
907
		}
908
	}
909
	if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
910
		if (($settings['mode'] == 'server_tls') || ($settings['mode'] == 'server_tls_user') ||
911
		    (($settings['mode'] == 'server_user') && ($settings['username_as_common_name'] == 'enabled'))) {
912
			$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : $config['system']['domain'];
913
			if (is_domain($domain)) {
914
				$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
915
			}
916
		}
917
	}
918

    
919
	/*
920
	 * When binding specific address, wait cases where interface is in
921
	 * tentative state otherwise it will fail
922
	 */
923
	$wait_tentative = false;
924

    
925
	/* Determine the local IP to use - and make sure it matches with the selected protocol. */
926
	switch ($settings['protocol']) {
927
		case 'UDP':
928
		case 'TCP':
929
			$conf .= "multihome\n";
930
			break;
931
		case 'UDP4':
932
		case 'TCP4':
933
			if (is_ipaddrv4($iface_ip)) {
934
				$conf .= "local {$iface_ip}\n";
935
			}
936
			if ($settings['interface'] == "any") {
937
				$conf .= "multihome\n";
938
			}
939
			break;
940
		case 'UDP6':
941
		case 'TCP6':
942
			if (is_ipaddrv6($iface_ipv6)) {
943
				$conf .= "local {$iface_ipv6}\n";
944
				$wait_tentative = true;
945
			}
946
			if ($settings['interface'] == "any") {
947
				$conf .= "multihome\n";
948
			}
949
			break;
950
		default:
951
	}
952

    
953
	if (openvpn_validate_engine($settings['engine']) && ($settings['engine'] != "none")) {
954
		$conf .= "engine {$settings['engine']}\n";
955
	}
956

    
957
	// server specific settings
958
	if ($mode == 'server') {
959

    
960
		list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
961
		list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
962
		$mask = gen_subnet_mask($cidr);
963

    
964
		// configure tls modes
965
		switch ($settings['mode']) {
966
			case 'p2p_tls':
967
			case 'server_tls':
968
			case 'server_user':
969
			case 'server_tls_user':
970
				$conf .= "tls-server\n";
971
				break;
972
		}
973

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

    
1042
		// configure user auth modes
1043
		switch ($settings['mode']) {
1044
			case 'server_user':
1045
				$conf .= "verify-client-cert none\n";
1046
			case 'server_tls_user':
1047
				/* username-as-common-name is not compatible with server-bridge */
1048
				if ((stristr($conf, "server-bridge") === false) &&
1049
				    ($settings['username_as_common_name'] != 'disabled')) {
1050
					$conf .= "username-as-common-name\n";
1051
				}
1052
				if (!empty($settings['authmode'])) {
1053
					$strictusercn = "false";
1054
					if ($settings['strictusercn']) {
1055
						$strictusercn = "true";
1056
					}
1057
					$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";
1058
				}
1059
				break;
1060
		}
1061
		if (!isset($settings['cert_depth']) && (strstr($settings['mode'], 'tls'))) {
1062
			$settings['cert_depth'] = 1;
1063
		}
1064
		if (is_numeric($settings['cert_depth'])) {
1065
			if (($mode == 'client') && empty($settings['certref'])) {
1066
				$cert = "";
1067
			} else {
1068
				$cert = lookup_cert($settings['certref']);
1069
				/* XXX: Seems not used at all! */
1070
				$servercn = urlencode(cert_get_cn($cert['crt']));
1071
				$conf .= "tls-verify \"/usr/local/sbin/ovpn_auth_verify tls '{$servercn}' {$settings['cert_depth']}\"\n";
1072
			}
1073
		}
1074

    
1075
		// The local port to listen on
1076
		$conf .= "lport {$settings['local_port']}\n";
1077

    
1078
		// The management port to listen on
1079
		// Use unix socket to overcome the problem on any type of server
1080
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1081
		//$conf .= "management 127.0.0.1 {$settings['local_port']}\n";
1082

    
1083
		if ($settings['maxclients']) {
1084
			$conf .= "max-clients {$settings['maxclients']}\n";
1085
		}
1086

    
1087
		// Can we push routes, and should we?
1088
		if ($settings['local_network'] && !$settings['gwredir']) {
1089
			$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1090
		}
1091
		if ($settings['local_networkv6'] && !$settings['gwredir6']) {
1092
			$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1093
		}
1094

    
1095
		switch ($settings['mode']) {
1096
			case 'server_tls':
1097
			case 'server_user':
1098
			case 'server_tls_user':
1099
				// Configure client dhcp options
1100
				openvpn_add_dhcpopts($settings, $conf);
1101
				if ($settings['client2client']) {
1102
					$conf .= "client-to-client\n";
1103
				}
1104
				break;
1105
		}
1106
		if ($settings['mode'] != 'p2p_shared_key' &&
1107
		    isset($settings['duplicate_cn'])) {
1108
			$conf .= "duplicate-cn\n";
1109
		}
1110
	}
1111

    
1112
	// client specific settings
1113

    
1114
	if ($mode == 'client') {
1115

    
1116
		// configure p2p mode
1117
		switch ($settings['mode']) {
1118
			case 'p2p_tls':
1119
				$conf .= "tls-client\n";
1120
			case 'shared_key':
1121
				$conf .= "client\n";
1122
				break;
1123
		}
1124

    
1125
		// If there is no bind option at all (ip and/or port), add "nobind" directive
1126
		//  Otherwise, use the local port if defined, failing that, use lport 0 to
1127
		//  ensure a random source port.
1128
		if ((empty($iface_ip)) && empty($iface_ipv6) && (!$settings['local_port'])) {
1129
			$conf .= "nobind\n";
1130
		} elseif ($settings['local_port']) {
1131
			$conf .= "lport {$settings['local_port']}\n";
1132
		} else {
1133
			$conf .= "lport 0\n";
1134
		}
1135

    
1136
		// Use unix socket to overcome the problem on any type of server
1137
		$conf .= "management {$g['openvpn_base']}/{$mode_id}/sock unix\n";
1138

    
1139
		// The remote server
1140
		$remoteproto = strtolower($settings['protocol']);
1141
		if (substr($remoteproto, 0, 3) == "tcp") {
1142
			$remoteproto .= "-{$mode}";
1143
		}
1144
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1145

    
1146
		if (!empty($settings['use_shaper'])) {
1147
			$conf .= "shaper {$settings['use_shaper']}\n";
1148
		}
1149

    
1150
		if (!empty($settings['tunnel_network'])) {
1151
			list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
1152
			$mask = gen_subnet_mask($cidr);
1153
			list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
1154
			if ($settings['dev_mode'] == 'tun') {
1155
				$conf .= "ifconfig {$ip2} {$ip1}\n";
1156
			} else {
1157
				$conf .= "ifconfig {$ip2} {$mask}\n";
1158
			}
1159
		}
1160

    
1161
		if (!empty($settings['tunnel_networkv6'])) {
1162
			list($ipv6, $prefix) = explode('/', trim($settings['tunnel_networkv6']));
1163
			list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1164
			if ($settings['dev_mode'] == 'tun') {
1165
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$ipv6_1}\n";
1166
			} else {
1167
				$conf .= "ifconfig-ipv6 {$ipv6_2} {$prefix}\n";
1168
			}
1169
		}
1170

    
1171
		if (($settings['auth_user'] || $settings['auth_pass']) && $settings['mode'] == "p2p_tls") {
1172
			$up_file = "{$g['openvpn_base']}/{$mode_id}/up";
1173
			$conf .= "auth-user-pass {$up_file}\n";
1174
			if (!$settings['auth-retry-none']) {
1175
				$conf .= "auth-retry nointeract\n";
1176
			}
1177
			if ($settings['auth_user']) {
1178
				$userpass = "{$settings['auth_user']}\n";
1179
			} else {
1180
				$userpass = "";
1181
			}
1182
			if ($settings['auth_pass']) {
1183
				$userpass .= "{$settings['auth_pass']}\n";
1184
			}
1185
			// If only auth_pass is given, then it acts like a user name and we put a blank line where pass would normally go.
1186
			if (!($settings['auth_user'] && $settings['auth_pass'])) {
1187
				$userpass .= "\n";
1188
			}
1189
			file_put_contents($up_file, $userpass);
1190
		}
1191

    
1192
		if ($settings['proxy_addr']) {
1193
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1194
			if ($settings['proxy_authtype'] != "none") {
1195
				$conf .= " {$g['openvpn_base']}/{$mode_id}/proxy_auth {$settings['proxy_authtype']}";
1196
				$proxypas = "{$settings['proxy_user']}\n";
1197
				$proxypas .= "{$settings['proxy_passwd']}\n";
1198
				file_put_contents("{$g['openvpn_base']}/{$mode_id}/proxy_auth", $proxypas);
1199
			}
1200
			$conf .= " \n";
1201
		}
1202
	}
1203

    
1204
	// Add a remote network route if set, and only for p2p modes.
1205
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE)) {
1206
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false);
1207
	}
1208
	// Add a remote network route if set, and only for p2p modes.
1209
	if ((substr($settings['mode'], 0, 3) == "p2p") && (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE)) {
1210
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false);
1211
	}
1212

    
1213
	// Write the settings for the keys
1214
	switch ($settings['mode']) {
1215
		case 'p2p_shared_key':
1216
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1217
			break;
1218
		case 'p2p_tls':
1219
		case 'server_tls':
1220
		case 'server_tls_user':
1221
		case 'server_user':
1222
			// ca_chain_array() expects parameter to be passed by reference.
1223
			// avoid passing the whole settings array, as param names or
1224
			// types might change in future releases.
1225
			$param = array('caref' => $settings['caref']);
1226
			$cas = ca_chain_array($param);
1227
			$capath = "{$g['openvpn_base']}/{$mode_id}/ca";
1228
			/* Cleanup old CA/CRL references */
1229
			@unlink_if_exists("{$capath}.*0");
1230
			/* Find the CRL listed in the settings */
1231
			if (!empty($settings['crlref'])) {
1232
				$crl = lookup_crl($settings['crlref']);
1233
				crl_update($crl);
1234
			}
1235
			/* For each CA in the chain, setup the CApath */
1236
			foreach ($cas as $ca) {
1237
				ca_setup_capath($ca, $capath, $crl);
1238
			}
1239
			$conf .= "capath {$capath}\n";
1240
			unset($cas, $param);
1241

    
1242
			if (!empty($settings['certref'])) {
1243
				$cert = lookup_cert($settings['certref']);
1244
				openvpn_add_keyfile($cert['crt'], $conf, $mode_id, "cert");
1245
				openvpn_add_keyfile($cert['prv'], $conf, $mode_id, "key");
1246
			}
1247
			if ($mode == 'server') {
1248
				if (is_numeric($settings['dh_length'])) {
1249
					if (!in_array($settings['dh_length'], array_keys($openvpn_dh_lengths))) {
1250
						/* The user selected a DH parameter length that does not have a corresponding file. */
1251
						log_error(gettext("Failed to construct OpenVPN server configuration. The selected DH Parameter length cannot be used."));
1252
						return;
1253
					}
1254
					$dh_file = "{$g['etc_path']}/dh-parameters.{$settings['dh_length']}";
1255
				} else {
1256
					$dh_file = $settings['dh_length'];
1257
				}
1258
				$conf .= "dh {$dh_file}\n";
1259
				if (!empty($settings['ecdh_curve']) && ($settings['ecdh_curve'] != "none") && openvpn_validate_curve($settings['ecdh_curve'])) {
1260
					$conf .= "ecdh-curve {$settings['ecdh_curve']}\n";
1261
				}
1262
			}
1263
			if ($settings['tls']) {
1264
				if ($settings['tls_type'] == "crypt") {
1265
					$tls_directive = "tls-crypt";
1266
					$tlsopt = "";
1267
				} else {
1268
					$tls_directive = "tls-auth";
1269
					if ($mode == "server") {
1270
						switch($settings['tlsauth_keydir']){
1271
							case '1':
1272
								$tlsopt = 1;
1273
								break;
1274
							case '2':
1275
								$tlsopt = '';
1276
								break;
1277
							default:
1278
								$tlsopt = 0;
1279
								break;
1280
						}
1281
					} else {
1282
						switch($settings['tlsauth_keydir']){
1283
							case '0':
1284
								$tlsopt = 0;
1285
								break;
1286
							case '2':
1287
								$tlsopt = '';
1288
								break;
1289
							default:
1290
								$tlsopt = 1;
1291
								break;
1292
						}
1293
					}
1294
				}
1295
				openvpn_add_keyfile($settings['tls'], $conf, $mode_id, $tls_directive, $tlsopt);
1296
			}
1297

    
1298
			/* NCP support. If it is not set, assume enabled since that is OpenVPN's default. */
1299
			if ($settings['ncp_enable'] == "disabled") {
1300
				$conf .= "ncp-disable\n";
1301
			} else {
1302
				/* If the ncp-ciphers list is empty, don't specify a list so OpenVPN's default will be used. */
1303
				if (!empty($settings['ncp-ciphers'])) {
1304
					$conf .= "ncp-ciphers " . str_replace(',', ':', $settings['ncp-ciphers']) . "\n";
1305
				}
1306
			}
1307

    
1308
			break;
1309
	}
1310

    
1311
	$compression = "";
1312
	switch ($settings['compression']) {
1313
		case 'none':
1314
			$settings['compression'] = '';
1315
		case 'lz4':
1316
		case 'lz4-v2':
1317
		case 'lzo':
1318
		case 'stub':
1319
		case 'stub-v2':
1320
			$compression .= "compress {$settings['compression']}";
1321
			break;
1322
		case 'noadapt':
1323
			$compression .= "comp-noadapt";
1324
			break;
1325
		case 'adaptive':
1326
		case 'yes':
1327
		case 'no':
1328
			$compression .= "comp-lzo {$settings['compression']}";
1329
			break;
1330
		default:
1331
			/* Add nothing to the configuration */
1332
			break;
1333
	}
1334

    
1335
	if (!empty($compression)) {
1336
		$conf .= "{$compression}\n";
1337
		if ($settings['compression_push']) {
1338
			$conf .= "push \"{$compression}\"\n";
1339
		}
1340
	}
1341

    
1342
	if ($settings['passtos']) {
1343
		$conf .= "passtos\n";
1344
	}
1345

    
1346
	if ($mode == 'client') {
1347
		$conf .= "resolv-retry infinite\n";
1348
	}
1349

    
1350
	if ($settings['dynamic_ip']) {
1351
		$conf .= "persist-remote-ip\n";
1352
		$conf .= "float\n";
1353
	}
1354

    
1355
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1356
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1357
		if (empty($settings['topology'])) {
1358
			$settings['topology'] = "subnet";
1359
		}
1360
		$conf .= "topology {$settings['topology']}\n";
1361
	}
1362

    
1363
	// New client features
1364
	if ($mode == "client") {
1365
		// Dont pull routes checkbox
1366
		if ($settings['route_no_pull']) {
1367
			$conf .= "route-nopull\n";
1368
		}
1369

    
1370
		// Dont add/remove routes checkbox
1371
		if ($settings['route_no_exec']) {
1372
			$conf .= "route-noexec\n";
1373
		}
1374
	}
1375

    
1376
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1377
	if ($settings['udp_fast_io']
1378
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1379
	    && (empty($settings['use_shaper']))) {
1380
		$conf .= "fast-io\n";
1381
	}
1382

    
1383
	/* Exit Notify. Only compatible with UDP. */
1384
	if (!empty($settings['exit_notify']) &&
1385
	    is_numericint($settings['exit_notify']) &&
1386
	    (strtolower(substr($settings['protocol'], 0, 3)) == "udp")) {
1387
		$conf .= "explicit-exit-notify {$settings['exit_notify']}\n";
1388
	}
1389

    
1390
	/* Send and Receive Buffer Settings */
1391
	if (is_numericint($settings['sndrcvbuf'])
1392
	    && ($settings['sndrcvbuf'] > 0)
1393
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1394
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1395
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1396
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1397
	}
1398

    
1399
	openvpn_add_custom($settings, $conf);
1400

    
1401
	openvpn_create_dirs();
1402
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1403
	file_put_contents($fpath, $conf);
1404
	unset($conf);
1405
	$fpath = "{$g['openvpn_base']}/{$mode_id}/interface";
1406
	file_put_contents($fpath, $interface);
1407
	//chown($fpath, 'nobody');
1408
	//chgrp($fpath, 'nobody');
1409
	@chmod("{$g['openvpn_base']}/{$mode_id}/config.ovpn", 0600);
1410
	@chmod("{$g['openvpn_base']}/{$mode_id}/interface", 0600);
1411
	@chmod("{$g['openvpn_base']}/{$mode_id}/key", 0600);
1412
	@chmod("{$g['openvpn_base']}/{$mode_id}/tls-auth", 0600);
1413
	@chmod("{$g['openvpn_base']}/{$mode_id}/conf", 0600);
1414

    
1415
	if ($wait_tentative) {
1416
		interface_wait_tentative($interface);
1417
	}
1418
}
1419

    
1420
function openvpn_restart($mode, $settings) {
1421
	global $g, $config;
1422

    
1423
	$vpnid = $settings['vpnid'];
1424
	$mode_id = $mode.$vpnid;
1425
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1426
	openvpn_reconfigure($mode, $settings);
1427
	/* kill the process if running */
1428
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1429
	if (file_exists($pfile)) {
1430

    
1431
		/* read the pid file */
1432
		$pid = rtrim(file_get_contents($pfile));
1433
		unlink($pfile);
1434
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1435

    
1436
		/* send a term signal to the process */
1437
		posix_kill($pid, SIGTERM);
1438

    
1439
		/* wait until the process exits, or timeout and kill it */
1440
		$i = 0;
1441
		while (posix_kill($pid, 0)) {
1442
			usleep(250000);
1443
			if ($i > 10) {
1444
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1445
				posix_kill($pid, SIGKILL);
1446
				usleep(500000);
1447
			}
1448
			$i++;
1449
		}
1450
	}
1451

    
1452
	if (isset($settings['disable'])) {
1453
		unlock($lockhandle);
1454
		return;
1455
	}
1456

    
1457
	/* Do not start an instance if we are not CARP master on this vip! */
1458
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1459
		unlock($lockhandle);
1460
		return;
1461
	}
1462

    
1463
	/* Check if client is bound to a gateway group */
1464
	$a_groups = return_gateway_groups_array(true);
1465
	if (is_array($a_groups[$settings['interface']])) {
1466
		/* the interface is a gateway group. If a vip is defined and its a CARP backup then do not start */
1467
		if (($a_groups[$settings['interface']][0]['vip'] <> "") && (!in_array(get_carp_interface_status($a_groups[$settings['interface']][0]['vip']), array("MASTER", "")))) {
1468
			unlock($lockhandle);
1469
			return;
1470
		}
1471
	}
1472

    
1473
	/* start the new process */
1474
	$fpath = "{$g['openvpn_base']}/{$mode_id}/config.ovpn";
1475
	openvpn_clear_route($mode, $settings);
1476
	$res = mwexec("/usr/local/sbin/openvpn --config " . escapeshellarg($fpath));
1477
	if ($res == 0) {
1478
		$i = 0;
1479
		$pid = "--";
1480
		while ($i < 3000) {
1481
			if (isvalidpid($pfile)) {
1482
				$pid = rtrim(file_get_contents($pfile));
1483
				break;
1484
			}
1485
			usleep(1000);
1486
			$i++;
1487
		}
1488
		syslog(LOG_INFO, "OpenVPN PID written: {$pid}");
1489
	} else {
1490
		syslog(LOG_ERR, "OpenVPN failed to start");
1491
	}
1492
	if (!platform_booting()) {
1493
		send_event("filter reload");
1494
	}
1495
	unlock($lockhandle);
1496
}
1497

    
1498
function openvpn_delete($mode, $settings) {
1499
	global $g, $config;
1500

    
1501
	$vpnid = $settings['vpnid'];
1502
	$mode_id = $mode.$vpnid;
1503

    
1504
	if ($mode == "server") {
1505
		$devname = "ovpns{$vpnid}";
1506
	} else {
1507
		$devname = "ovpnc{$vpnid}";
1508
	}
1509

    
1510
	/* kill the process if running */
1511
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1512
	if (file_exists($pfile)) {
1513

    
1514
		/* read the pid file */
1515
		$pid = trim(file_get_contents($pfile));
1516
		unlink($pfile);
1517

    
1518
		/* send a term signal to the process */
1519
		posix_kill($pid, SIGTERM);
1520
	}
1521

    
1522
	/* destroy the device */
1523
	pfSense_interface_destroy($devname);
1524

    
1525
	/* Invalidate cache */
1526
	get_interface_arr(true);
1527

    
1528
	/* remove the configuration files */
1529
	@array_map('unlink', glob("{$g['openvpn_base']}/{$mode_id}/csc/*"));
1530
	@array_map('unlink', glob("{$g['openvpn_base']}/{$mode_id}/*"));
1531
}
1532

    
1533
function openvpn_resync_csc(& $settings) {
1534
	global $g, $config, $openvpn_tls_server_modes;
1535
	if (isset($settings['disable'])) {
1536
		openvpn_delete_csc($settings);
1537
		return;
1538
	}
1539
	openvpn_create_dirs();
1540

    
1541
	if (empty($settings['server_list'])) {
1542
		$csc_server_list = array();
1543
	} else {
1544
		$csc_server_list = explode(",", $settings['server_list']);
1545
	}
1546

    
1547
	$conf = '';
1548
	if ($settings['block']) {
1549
		$conf .= "disable\n";
1550
	}
1551

    
1552
	if ($settings['push_reset']) {
1553
		$conf .= "push-reset\n";
1554
	}
1555

    
1556
	if ($settings['remove_route']) {
1557
		$conf .= "push-remove route\n";
1558
	}
1559

    
1560
	if ($settings['local_network']) {
1561
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1562
	}
1563
	if ($settings['local_networkv6']) {
1564
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1565
	}
1566

    
1567
	// Add a remote network iroute if set
1568
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1569
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1570
	}
1571
	// Add a remote network iroute if set
1572
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1573
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1574
	}
1575

    
1576
	openvpn_add_dhcpopts($settings, $conf);
1577

    
1578
	openvpn_add_custom($settings, $conf);
1579
	/* Loop through servers, find which ones can use this CSC */
1580
	if (is_array($config['openvpn']['openvpn-server'])) {
1581
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1582
			if (isset($serversettings['disable'])) {
1583
				continue;
1584
			}
1585
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1586
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1587
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1588
					$csc_conf = $conf;
1589

    
1590
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1591
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1592
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1593
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1594
						} else {
1595
							/* Because this is being pushed, the order from the client's point of view. */
1596
							$baselong = gen_subnetv4($ip, $mask);
1597
							$serverip = ip_after($baselong, 1);
1598
							$clientip = ip_after($baselong, 2);
1599
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1600
						}
1601
					}
1602

    
1603
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1604
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1605
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1606
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1607
					}
1608

    
1609
					file_put_contents($csc_path, $csc_conf);
1610
					chown($csc_path, 'nobody');
1611
					chgrp($csc_path, 'nobody');
1612
				}
1613
			}
1614
		}
1615
	}
1616
}
1617

    
1618
function openvpn_resync_csc_all() {
1619
	global $config;
1620
	if (is_array($config['openvpn']['openvpn-csc'])) {
1621
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1622
			openvpn_resync_csc($settings);
1623
		}
1624
	}
1625
}
1626

    
1627
function openvpn_delete_csc(& $settings) {
1628
	global $g, $config, $openvpn_tls_server_modes;
1629
	if (empty($settings['server_list'])) {
1630
		$csc_server_list = array();
1631
	} else {
1632
		$csc_server_list = explode(",", $settings['server_list']);
1633
	}
1634

    
1635
	/* Loop through servers, find which ones used this CSC */
1636
	if (is_array($config['openvpn']['openvpn-server'])) {
1637
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1638
			if (isset($serversettings['disable'])) {
1639
				continue;
1640
			}
1641
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1642
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1643
					$csc_path = "{$g['openvpn_base']}/server{$serversettings['vpnid']}/csc/" . basename($settings['common_name']);
1644
					unlink_if_exists($csc_path);
1645
				}
1646
			}
1647
		}
1648
	}
1649
}
1650

    
1651
// Resync the configuration and restart the VPN
1652
function openvpn_resync($mode, $settings) {
1653
	openvpn_restart($mode, $settings);
1654
}
1655

    
1656
// Resync and restart all VPNs
1657
function openvpn_resync_all($interface = "") {
1658
	global $g, $config;
1659

    
1660
	openvpn_create_dirs();
1661

    
1662
	if (!is_array($config['openvpn'])) {
1663
		$config['openvpn'] = array();
1664
	}
1665

    
1666
	if ($interface <> "") {
1667
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1668
	} else {
1669
		log_error(gettext("Resyncing OpenVPN instances."));
1670
	}
1671

    
1672
	// Check if OpenVPN clients and servers require a resync.
1673
	foreach (array("server", "client") as $type) {
1674
		if (!is_array($config['openvpn']["openvpn-{$type}"])) {
1675
			continue;
1676
		}
1677
		foreach ($config['openvpn']["openvpn-{$type}"] as & $settings) {
1678
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1679
			$gw_group_change = FALSE;
1680
			$ip_change = ($interface === "") ||
1681
			    ($interface === $settings['interface']);
1682

    
1683
			if (!$ip_change && file_exists($fpath)) {
1684
				$gw_group_change =
1685
				    (trim(file_get_contents($fpath), " \t\n") !=
1686
				    get_failover_interface(
1687
					$settings['interface']));
1688
			}
1689

    
1690
			if ($ip_change || $gw_group_change) {
1691
				openvpn_resync($type, $settings);
1692
			}
1693
		}
1694
	}
1695

    
1696
	openvpn_resync_csc_all();
1697

    
1698
}
1699

    
1700
// Resync and restart all VPNs using a gateway group.
1701
function openvpn_resync_gwgroup($gwgroupname = "") {
1702
	global $g, $config;
1703

    
1704
	if ($gwgroupname <> "") {
1705
		if (is_array($config['openvpn']['openvpn-server'])) {
1706
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1707
				if ($gwgroupname == $settings['interface']) {
1708
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1709
					openvpn_resync('server', $settings);
1710
				}
1711
			}
1712
		}
1713

    
1714
		if (is_array($config['openvpn']['openvpn-client'])) {
1715
			foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1716
				if ($gwgroupname == $settings['interface']) {
1717
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s client %2$s.'), $gwgroupname, $settings["description"]));
1718
					openvpn_resync('client', $settings);
1719
				}
1720
			}
1721
		}
1722

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

    
1725
	} else {
1726
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1727
	}
1728
}
1729

    
1730
function openvpn_get_active_servers($type="multipoint") {
1731
	global $config, $g;
1732

    
1733
	$servers = array();
1734
	if (is_array($config['openvpn']['openvpn-server'])) {
1735
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1736
			if (empty($settings) || isset($settings['disable'])) {
1737
				continue;
1738
			}
1739

    
1740
			$prot = $settings['protocol'];
1741
			$port = $settings['local_port'];
1742

    
1743
			$server = array();
1744
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1745
			$server['mode'] = $settings['mode'];
1746
			if ($settings['description']) {
1747
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1748
			} else {
1749
				$server['name'] = "Server {$prot}:{$port}";
1750
			}
1751
			$server['conns'] = array();
1752
			$server['vpnid'] = $settings['vpnid'];
1753
			$server['mgmt'] = "server{$server['vpnid']}";
1754
			$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1755
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1756

    
1757
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1758
				$servers[] = openvpn_get_client_status($server, $socket);
1759
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1760
				$servers[] = openvpn_get_server_status($server, $socket);
1761
			}
1762
		}
1763
	}
1764
	return $servers;
1765
}
1766

    
1767
function openvpn_get_server_status($server, $socket) {
1768
	$errval = null;
1769
	$errstr = null;
1770
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1771
	if ($fp) {
1772
		stream_set_timeout($fp, 1);
1773

    
1774
		/* send our status request */
1775
		fputs($fp, "status 2\n");
1776

    
1777
		/* recv all response lines */
1778
		while (!feof($fp)) {
1779

    
1780
			/* read the next line */
1781
			$line = fgets($fp, 1024);
1782

    
1783
			$info = stream_get_meta_data($fp);
1784
			if ($info['timed_out']) {
1785
				break;
1786
			}
1787

    
1788
			/* parse header list line */
1789
			if (strstr($line, "HEADER")) {
1790
				continue;
1791
			}
1792

    
1793
			/* parse end of output line */
1794
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1795
				break;
1796
			}
1797

    
1798
			/* parse client list line */
1799
			if (strstr($line, "CLIENT_LIST")) {
1800
				$list = explode(",", $line);
1801
				$conn = array();
1802
				$conn['common_name'] = $list[1];
1803
				$conn['remote_host'] = $list[2];
1804
				$conn['virtual_addr'] = $list[3];
1805
				$conn['virtual_addr6'] = $list[4];
1806
				$conn['bytes_recv'] = $list[5];
1807
				$conn['bytes_sent'] = $list[6];
1808
				$conn['connect_time'] = $list[7];
1809
				$conn['connect_time_unix'] = $list[8];
1810
				$conn['user_name'] = $list[9];
1811
				$conn['client_id'] = $list[10];
1812
				$conn['peer_id'] = $list[11];
1813
				$server['conns'][] = $conn;
1814
			}
1815
			/* parse routing table lines */
1816
			if (strstr($line, "ROUTING_TABLE")) {
1817
				$list = explode(",", $line);
1818
				$conn = array();
1819
				$conn['virtual_addr'] = $list[1];
1820
				$conn['common_name'] = $list[2];
1821
				$conn['remote_host'] = $list[3];
1822
				$conn['last_time'] = $list[4];
1823
				$server['routes'][] = $conn;
1824
			}
1825
		}
1826

    
1827
		/* cleanup */
1828
		fclose($fp);
1829
	} else {
1830
		$conn = array();
1831
		$conn['common_name'] = "[error]";
1832
		$conn['remote_host'] = gettext("Unable to contact daemon");
1833
		$conn['virtual_addr'] = gettext("Service not running?");
1834
		$conn['bytes_recv'] = 0;
1835
		$conn['bytes_sent'] = 0;
1836
		$conn['connect_time'] = 0;
1837
		$server['conns'][] = $conn;
1838
	}
1839
	return $server;
1840
}
1841

    
1842
function openvpn_get_active_clients() {
1843
	global $config, $g;
1844

    
1845
	$clients = array();
1846
	if (is_array($config['openvpn']['openvpn-client'])) {
1847
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1848

    
1849
			if (empty($settings) || isset($settings['disable'])) {
1850
				continue;
1851
			}
1852

    
1853
			$prot = $settings['protocol'];
1854
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1855

    
1856
			$client = array();
1857
			$client['port'] = $settings['local_port'];
1858
			if ($settings['description']) {
1859
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1860
			} else {
1861
				$client['name'] = "Client {$prot}{$port}";
1862
			}
1863

    
1864
			$client['vpnid'] = $settings['vpnid'];
1865
			$client['mgmt'] = "client{$client['vpnid']}";
1866
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
1867
			$client['status']="down";
1868

    
1869
			$clients[] = openvpn_get_client_status($client, $socket);
1870
		}
1871
	}
1872
	return $clients;
1873
}
1874

    
1875
function openvpn_get_client_status($client, $socket) {
1876
	$errval = null;
1877
	$errstr = null;
1878
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1879
	if ($fp) {
1880
		stream_set_timeout($fp, 1);
1881
		/* send our status request */
1882
		fputs($fp, "state 1\n");
1883

    
1884
		/* recv all response lines */
1885
		while (!feof($fp)) {
1886
			/* read the next line */
1887
			$line = fgets($fp, 1024);
1888

    
1889
			$info = stream_get_meta_data($fp);
1890
			if ($info['timed_out']) {
1891
				break;
1892
			}
1893

    
1894
			/* Get the client state */
1895
			if (strstr($line, "CONNECTED")) {
1896
				$client['status'] = "up";
1897
				$list = explode(",", $line);
1898

    
1899
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1900
				$client['virtual_addr'] = $list[3];
1901
				$client['remote_host'] = $list[4];
1902
				$client['remote_port'] = $list[5];
1903
				$client['local_host'] = $list[6];
1904
				$client['local_port'] = $list[7];
1905
				$client['virtual_addr6'] = $list[8];
1906
			}
1907
			if (strstr($line, "CONNECTING")) {
1908
				$client['status'] = "connecting";
1909
			}
1910
			if (strstr($line, "ASSIGN_IP")) {
1911
				$client['status'] = "waiting";
1912
				$list = explode(",", $line);
1913

    
1914
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1915
				$client['virtual_addr'] = $list[3];
1916
			}
1917
			if (strstr($line, "RECONNECTING")) {
1918
				$client['status'] = "reconnecting";
1919
				$list = explode(",", $line);
1920

    
1921
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1922
				$client['status'] .= "; " . $list[2];
1923
			}
1924
			/* parse end of output line */
1925
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1926
				break;
1927
			}
1928
		}
1929

    
1930
		/* If up, get read/write stats */
1931
		if (strcmp($client['status'], "up") == 0) {
1932
			fputs($fp, "status 2\n");
1933
			/* recv all response lines */
1934
			while (!feof($fp)) {
1935
				/* read the next line */
1936
				$line = fgets($fp, 1024);
1937

    
1938
				$info = stream_get_meta_data($fp);
1939
				if ($info['timed_out']) {
1940
					break;
1941
				}
1942

    
1943
				if (strstr($line, "TCP/UDP read bytes")) {
1944
					$list = explode(",", $line);
1945
					$client['bytes_recv'] = $list[1];
1946
				}
1947

    
1948
				if (strstr($line, "TCP/UDP write bytes")) {
1949
					$list = explode(",", $line);
1950
					$client['bytes_sent'] = $list[1];
1951
				}
1952

    
1953
				/* parse end of output line */
1954
				if (strstr($line, "END")) {
1955
					break;
1956
				}
1957
			}
1958
		}
1959

    
1960
		fclose($fp);
1961

    
1962
	} else {
1963
		$client['remote_host'] = gettext("Unable to contact daemon");
1964
		$client['virtual_addr'] = gettext("Service not running?");
1965
		$client['bytes_recv'] = 0;
1966
		$client['bytes_sent'] = 0;
1967
		$client['connect_time'] = 0;
1968
	}
1969
	return $client;
1970
}
1971

    
1972
function openvpn_kill_client($port, $remipp) {
1973
	global $g;
1974

    
1975
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1976
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
1977
	$errval = null;
1978
	$errstr = null;
1979

    
1980
	/* open a tcp connection to the management port of each server */
1981
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1982
	$killed = -1;
1983
	if ($fp) {
1984
		stream_set_timeout($fp, 1);
1985
		fputs($fp, "kill {$remipp}\n");
1986
		while (!feof($fp)) {
1987
			$line = fgets($fp, 1024);
1988

    
1989
			$info = stream_get_meta_data($fp);
1990
			if ($info['timed_out']) {
1991
				break;
1992
			}
1993

    
1994
			/* parse header list line */
1995
			if (strpos($line, "INFO:") !== false) {
1996
				continue;
1997
			}
1998
			if (strpos($line, "SUCCESS") !== false) {
1999
				$killed = 0;
2000
			}
2001
			break;
2002
		}
2003
		fclose($fp);
2004
	}
2005
	return $killed;
2006
}
2007

    
2008
function openvpn_refresh_crls() {
2009
	global $g, $config;
2010

    
2011
	openvpn_create_dirs();
2012

    
2013
	if (is_array($config['openvpn']['openvpn-server'])) {
2014
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2015
			if (empty($settings)) {
2016
				continue;
2017
			}
2018
			if (isset($settings['disable'])) {
2019
				continue;
2020
			}
2021
			// Write the settings for the keys
2022
			switch ($settings['mode']) {
2023
				case 'p2p_tls':
2024
				case 'server_tls':
2025
				case 'server_tls_user':
2026
				case 'server_user':
2027
					$param = array('caref' => $settings['caref']);
2028
					$cas = ca_chain_array($param);
2029
					$capath = "{$g['openvpn_base']}/server{$settings['vpnid']}/ca";
2030
					if (!empty($settings['crlref'])) {
2031
						$crl = lookup_crl($settings['crlref']);
2032
						crl_update($crl);
2033
					}
2034
					foreach ($cas as $ca) {
2035
						ca_setup_capath($ca, $capath, $crl, true);
2036
					}
2037
					unset($cas, $param, $capath, $crl);
2038
					break;
2039
			}
2040
		}
2041
	}
2042
}
2043

    
2044
function openvpn_create_dirs() {
2045
	global $g, $config, $openvpn_tls_server_modes;
2046
	if (!is_dir($g['openvpn_base'])) {
2047
		safe_mkdir($g['openvpn_base'], 0750);
2048
	}
2049

    
2050
	init_config_arr(array('openvpn', 'openvpn-server'));
2051
	init_config_arr(array('openvpn', 'openvpn-client'));
2052
	foreach(array('server', 'client') as $mode) {
2053
		foreach ($config['openvpn']["openvpn-{$mode}"] as $settings) {
2054
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2055
			@unlink_if_exists($csctarget);
2056
			@safe_mkdir($target);
2057
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2058
				if ($settings['vpnid']) {
2059
					$csctarget = "{$target}/csc/";
2060
					@unlink_if_exists($csctarget);
2061
					@safe_mkdir($csctarget);
2062
				}
2063
			}
2064
		}
2065
	}
2066
}
2067

    
2068
function openvpn_get_interface_ip($ip, $cidr) {
2069
	$subnet = gen_subnetv4($ip, $cidr);
2070
	if ($cidr == 31) {
2071
		$ip1 = $subnet;
2072
	} else {
2073
		$ip1 = ip_after($subnet);
2074
	}
2075
	$ip2 = ip_after($ip1);
2076
	return array($ip1, $ip2);
2077
}
2078

    
2079
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2080
	$basev6 = gen_subnetv6($ipv6, $prefix);
2081
	// Is there a better way to do this math?
2082
	$ipv6_arr = explode(':', $basev6);
2083
	$last = hexdec(array_pop($ipv6_arr));
2084
	if ($prefix == 127) {
2085
		$last--;
2086
	}
2087
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2088
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2089
	return array($ipv6_1, $ipv6_2);
2090
}
2091

    
2092
function openvpn_clear_route($mode, $settings) {
2093
	if (empty($settings['tunnel_network'])) {
2094
		return;
2095
	}
2096
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
2097
	$mask = gen_subnet_mask($cidr);
2098
	$clear_route = false;
2099

    
2100
	switch ($settings['mode']) {
2101
		case 'shared_key':
2102
			$clear_route = true;
2103
			break;
2104
		case 'p2p_tls':
2105
		case 'p2p_shared_key':
2106
			if ($cidr >= 30) {
2107
				$clear_route = true;
2108
			}
2109
			break;
2110
	}
2111

    
2112
	if ($clear_route && !empty($ip) && !empty($mask)) {
2113
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2114
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2115
		/* XXX: Family for route? */
2116
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2117
	}
2118
}
2119

    
2120
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2121
	$routes = "";
2122
	if (empty($value)) {
2123
		return "";
2124
	}
2125
	$networks = explode(',', $value);
2126

    
2127
	foreach ($networks as $network) {
2128
		if ($ipproto == "ipv4") {
2129
			$route = openvpn_gen_route_ipv4($network, $iroute);
2130
		} else {
2131
			$route = openvpn_gen_route_ipv6($network, $iroute);
2132
		}
2133

    
2134
		if ($push) {
2135
			$routes .= "push \"{$route}\"\n";
2136
		} else {
2137
			$routes .= "{$route}\n";
2138
		}
2139
	}
2140
	return $routes;
2141
}
2142

    
2143
function openvpn_gen_route_ipv4($network, $iroute = false) {
2144
	$i = ($iroute) ? "i" : "";
2145
	list($ip, $mask) = explode('/', trim($network));
2146
	$mask = gen_subnet_mask($mask);
2147
	return "{$i}route $ip $mask";
2148
}
2149

    
2150
function openvpn_gen_route_ipv6($network, $iroute = false) {
2151
	$i = ($iroute) ? "i" : "";
2152
	list($ipv6, $prefix) = explode('/', trim($network));
2153
	if (empty($prefix) && !is_numeric($prefix)) {
2154
		$prefix = "128";
2155
	}
2156
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2157
}
2158

    
2159
function openvpn_get_settings($mode, $vpnid) {
2160
	global $config;
2161

    
2162
	if (is_array($config['openvpn']['openvpn-server'])) {
2163
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2164
			if (isset($settings['disable'])) {
2165
				continue;
2166
			}
2167

    
2168
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2169
				return $settings;
2170
			}
2171
		}
2172
	}
2173

    
2174
	if (is_array($config['openvpn']['openvpn-client'])) {
2175
		foreach ($config['openvpn']['openvpn-client'] as $settings) {
2176
			if (isset($settings['disable'])) {
2177
				continue;
2178
			}
2179

    
2180
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2181
				return $settings;
2182
			}
2183
		}
2184
	}
2185

    
2186
	return array();
2187
}
2188

    
2189
function openvpn_restart_by_vpnid($mode, $vpnid) {
2190
	$settings = openvpn_get_settings($mode, $vpnid);
2191
	openvpn_restart($mode, $settings);
2192
}
2193

    
2194
/****f* certs/openvpn_is_tunnel_network_in_use
2195
 * NAME
2196
 *   openvpn_is_tunnel_network_in_use
2197
 *     Check if the supplied network is in use as an OpenVPN server or client
2198
 *     tunnel network
2199
 * INPUTS
2200
 *   $net : The IPv4 or IPv6 network to check
2201
 * RESULT
2202
 *   boolean value: true if the network is in use, false otherwise.
2203
 ******/
2204

    
2205
function openvpn_is_tunnel_network_in_use($net) {
2206
	global $config;
2207
	init_config_arr(array('openvpn', 'openvpn-server'));
2208
	init_config_arr(array('openvpn', 'openvpn-client'));
2209
	/* Determine whether to check IPv4 or IPv6 tunnel networks */
2210
	$tocheck = 'tunnel_network';
2211
	if (is_v6($net)) {
2212
		$tocheck .= "v6";
2213
	}
2214
	/* Check all OpenVPN clients and servers for this tunnel network */
2215
	foreach(array('server', 'client') as $mode) {
2216
		foreach ($config['openvpn']["openvpn-{$mode}"] as $ovpn) {
2217
			if (!empty($ovpn[$tocheck]) &&
2218
			    ($ovpn[$tocheck] == $net)) {
2219
				return true;
2220
			}
2221
		}
2222
	}
2223
	return false;
2224
}
2225
?>
(33-33/61)