Project

General

Profile

Download (64.1 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
		switch($settings['mode']) {
911
			case 'server_tls':
912
			case 'server_tls_user':
913
				$domain = !empty($settings['dns_domain']) ? $settings['dns_domain'] : $config['system']['domain'];
914
				if (is_domain($domain)) {
915
					$conf .= "learn-address \"/usr/local/sbin/openvpn.learn-address.sh $domain\"\n";
916
				}
917
				break;
918
		}
919
	}
920

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

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

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

    
959
	// server specific settings
960
	if ($mode == 'server') {
961

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

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

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

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

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

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

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

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

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

    
1114
	// client specific settings
1115

    
1116
	if ($mode == 'client') {
1117

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1310
			break;
1311
	}
1312

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

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

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

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

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

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

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

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

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

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

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

    
1401
	openvpn_add_custom($settings, $conf);
1402

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

    
1417
	if ($wait_tentative) {
1418
		interface_wait_tentative($interface);
1419
	}
1420
}
1421

    
1422
function openvpn_restart($mode, $settings) {
1423
	global $g, $config;
1424

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

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

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

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

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

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

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

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

    
1500
function openvpn_delete($mode, $settings) {
1501
	global $g, $config;
1502

    
1503
	$vpnid = $settings['vpnid'];
1504
	$mode_id = $mode.$vpnid;
1505

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

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

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

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

    
1524
	/* destroy the device */
1525
	pfSense_interface_destroy($devname);
1526

    
1527
	/* Invalidate cache */
1528
	get_interface_arr(true);
1529

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

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

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

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

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

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

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

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

    
1578
	openvpn_add_dhcpopts($settings, $conf);
1579

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

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

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

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

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

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

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

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

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

    
1662
	openvpn_create_dirs();
1663

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

    
1668
	openlog("", LOG_PID, LOG_LOCAL0);
1669
	if ($interface <> "") {
1670
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1671
	} else {
1672
		log_error(gettext("Resyncing OpenVPN instances."));
1673
	}
1674

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

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

    
1693
			if ($ip_change || $gw_group_change) {
1694
				openvpn_resync($type, $settings);
1695
			}
1696
		}
1697
	}
1698

    
1699
	openvpn_resync_csc_all();
1700

    
1701
}
1702

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

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

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

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

    
1728
	} else {
1729
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1730
	}
1731
}
1732

    
1733
function openvpn_get_active_servers($type="multipoint") {
1734
	global $config, $g;
1735

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

    
1743
			$prot = $settings['protocol'];
1744
			$port = $settings['local_port'];
1745

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

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

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

    
1777
		/* send our status request */
1778
		fputs($fp, "status 2\n");
1779

    
1780
		/* recv all response lines */
1781
		while (!feof($fp)) {
1782

    
1783
			/* read the next line */
1784
			$line = fgets($fp, 1024);
1785

    
1786
			$info = stream_get_meta_data($fp);
1787
			if ($info['timed_out']) {
1788
				break;
1789
			}
1790

    
1791
			/* parse header list line */
1792
			if (strstr($line, "HEADER")) {
1793
				continue;
1794
			}
1795

    
1796
			/* parse end of output line */
1797
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1798
				break;
1799
			}
1800

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

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

    
1845
function openvpn_get_active_clients() {
1846
	global $config, $g;
1847

    
1848
	$clients = array();
1849
	if (is_array($config['openvpn']['openvpn-client'])) {
1850
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1851

    
1852
			if (empty($settings) || isset($settings['disable'])) {
1853
				continue;
1854
			}
1855

    
1856
			$prot = $settings['protocol'];
1857
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1858

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

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

    
1872
			$clients[] = openvpn_get_client_status($client, $socket);
1873
		}
1874
	}
1875
	return $clients;
1876
}
1877

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

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

    
1892
			$info = stream_get_meta_data($fp);
1893
			if ($info['timed_out']) {
1894
				break;
1895
			}
1896

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

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

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

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

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

    
1941
				$info = stream_get_meta_data($fp);
1942
				if ($info['timed_out']) {
1943
					break;
1944
				}
1945

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

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

    
1956
				/* parse end of output line */
1957
				if (strstr($line, "END")) {
1958
					break;
1959
				}
1960
			}
1961
		}
1962

    
1963
		fclose($fp);
1964

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

    
1975
function openvpn_kill_client($port, $remipp) {
1976
	global $g;
1977

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

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

    
1992
			$info = stream_get_meta_data($fp);
1993
			if ($info['timed_out']) {
1994
				break;
1995
			}
1996

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

    
2011
function openvpn_refresh_crls() {
2012
	global $g, $config;
2013

    
2014
	openvpn_create_dirs();
2015

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

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

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

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

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

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

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

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

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

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

    
2137
		if ($push) {
2138
			$routes .= "push \"{$route}\"\n";
2139
		} else {
2140
			$routes .= "{$route}\n";
2141
		}
2142
	}
2143
	return $routes;
2144
}
2145

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

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

    
2162
function openvpn_get_settings($mode, $vpnid) {
2163
	global $config;
2164

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

    
2171
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2172
				return $settings;
2173
			}
2174
		}
2175
	}
2176

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

    
2183
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2184
				return $settings;
2185
			}
2186
		}
2187
	}
2188

    
2189
	return array();
2190
}
2191

    
2192
function openvpn_restart_by_vpnid($mode, $vpnid) {
2193
	$settings = openvpn_get_settings($mode, $vpnid);
2194
	openvpn_restart($mode, $settings);
2195
}
2196

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

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