Project

General

Profile

Download (64.4 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-2020 Rubicon Communications, LLC (Netgate)
8
 * All rights reserved.
9
 *
10
 * This file was rewritten from scratch by Fernando Lemos but
11
 * *MIGHT* contain code previously written by:
12
 *
13
 * Copyright (c) 2005 Peter Allgeyer <allgeyer_AT_web.de>
14
 * Copyright (c) 2004 Peter Curran (peter@closeconsultants.com).
15
 * All rights reserved.
16
 *
17
 * Licensed under the Apache License, Version 2.0 (the "License");
18
 * you may not use this file except in compliance with the License.
19
 * You may obtain a copy of the License at
20
 *
21
 * http://www.apache.org/licenses/LICENSE-2.0
22
 *
23
 * Unless required by applicable law or agreed to in writing, software
24
 * distributed under the License is distributed on an "AS IS" BASIS,
25
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26
 * See the License for the specific language governing permissions and
27
 * limitations under the License.
28
 */
29

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

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

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

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

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

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

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

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

    
116
global $openvpn_tls_server_modes;
117
$openvpn_tls_server_modes = array('p2p_tls', 'server_tls', 'server_user', 'server_tls_user');
118

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

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

    
139
global $openvpn_topologies;
140
$openvpn_topologies = array(
141
	'subnet' => gettext("Subnet -- One IP address per client in a common subnet"),
142
	'net30' => gettext("net30 -- Isolated /30 network per client")
143
//	'p2p => gettext("Peer to Peer -- One IP address per client peer-to-peer style. Does not work on Windows.")
144
);
145

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

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

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

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

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

    
170
global $openvpn_exit_notify_server;
171
$openvpn_exit_notify_server = array(
172
	'none' => gettext("Disabled"),
173
	'1' => gettext("Reconnect to this server / Retry once"),
174
	'2' => gettext("Reconnect to next server / Retry twice"),
175
);
176

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

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

    
188
	$list = array();
189

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

    
194
	return($list);
195
}
196

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

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

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

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

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

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

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

    
243
	return($list);
244
}
245

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

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

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

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

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

    
262
	return($list);
263
}
264

    
265
function openvpn_build_cert_list($include_none = false, $prioritize_server_certs = false) {
266
	global $a_cert;
267

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

    
274
	$non_server_list = array();
275

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

    
281
	foreach ($a_cert as $cert) {
282
		$properties = array();
283
		$propstr = "";
284
		$ca = lookup_ca($cert['caref']);
285
		$purpose = cert_get_purpose($cert['crt'], true);
286

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

    
302
		if (!empty($properties)) {
303
			$propstr = " (" . implode(", ", $properties) . ")";
304
		}
305

    
306
		if ($prioritize_server_certs) {
307
			if ($purpose['server'] == "Yes") {
308
				$list[$cert['refid']] = $cert['descr'] . $propstr;
309
			} else {
310
				$non_server_list[$cert['refid']] = $cert['descr'] . $propstr;
311
			}
312
		} else {
313
			$list[$cert['refid']] = $cert['descr'] . $propstr;
314
		}
315
	}
316

    
317
	return(array('server' => $list, 'non-server' => $non_server_list));
318
}
319

    
320
function openvpn_build_bridge_list() {
321
	$list = array();
322

    
323
	$serverbridge_interface['none'] = "none";
324
	$serverbridge_interface = array_merge($serverbridge_interface, get_configured_interface_with_descr());
325
	$viplist = get_configured_vip_list();
326

    
327
	foreach ($viplist as $vip => $address) {
328
		$serverbridge_interface[$vip.'|'.$address] = $address;
329
		if (get_vip_descr($address)) {
330
			$serverbridge_interface[$vip.'|'.$address] .= " (". get_vip_descr($address) .")";
331
		}
332
	}
333

    
334
	foreach ($serverbridge_interface as $iface => $ifacename) {
335
		$list[$iface] = htmlspecialchars($ifacename);
336
	}
337

    
338
	return($list);
339
}
340

    
341
function openvpn_create_key() {
342

    
343
	$fp = popen("/usr/local/sbin/openvpn --genkey --secret /dev/stdout 2>/dev/null", "r");
344
	if (!$fp) {
345
		return false;
346
	}
347

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

    
351
	return $rslt;
352
}
353

    
354
function openvpn_create_dhparams($bits) {
355

    
356
	$fp = popen("/usr/bin/openssl dhparam {$bits} 2>/dev/null", "r");
357
	if (!$fp) {
358
		return false;
359
	}
360

    
361
	$rslt = stream_get_contents($fp);
362
	pclose($fp);
363

    
364
	return $rslt;
365
}
366

    
367
function openvpn_vpnid_used($vpnid) {
368
	global $config;
369

    
370
	if (is_array($config['openvpn']['openvpn-server'])) {
371
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
372
			if ($vpnid == $settings['vpnid']) {
373
				return true;
374
			}
375
		}
376
	}
377

    
378
	if (is_array($config['openvpn']['openvpn-client'])) {
379
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
380
			if ($vpnid == $settings['vpnid']) {
381
				return true;
382
			}
383
		}
384
	}
385

    
386
	return false;
387
}
388

    
389
function openvpn_vpnid_next() {
390

    
391
	$vpnid = 1;
392
	while (openvpn_vpnid_used($vpnid)) {
393
		$vpnid++;
394
	}
395

    
396
	return $vpnid;
397
}
398

    
399
function openvpn_port_used($prot, $interface, $port, $curvpnid = 0) {
400
	global $config;
401

    
402
	$ovpn_settings = array();
403
	if (is_array($config['openvpn']['openvpn-server'])) {
404
		$ovpn_settings = $config['openvpn']['openvpn-server'];
405
	}
406
	if (is_array($config['openvpn']['openvpn-client'])) {
407
		$ovpn_settings = array_merge($ovpn_settings,
408
		    $config['openvpn']['openvpn-client']);
409
	}
410

    
411
	foreach ($ovpn_settings as $settings) {
412
		if (isset($settings['disable'])) {
413
			continue;
414
		}
415

    
416
		if ($curvpnid != 0 && $curvpnid == $settings['vpnid']) {
417
			continue;
418
		}
419

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

    
429
		if ($port == $settings['local_port'] &&
430
		    substr($prot,0,3) == substr($settings['protocol'],0,3) &&
431
		    ($interface == $settings['interface'] ||
432
		    $interface == "any" || $settings['interface'] == "any")) {
433
			return $settings['vpnid'];
434
		}
435
	}
436

    
437
	return 0;
438
}
439

    
440
function openvpn_port_next($prot, $interface = "wan") {
441

    
442
	$port = 1194;
443
	while (openvpn_port_used($prot, $interface, $port)) {
444
		$port++;
445
	}
446
	while (openvpn_port_used($prot, "any", $port)) {
447
		$port++;
448
	}
449

    
450
	return $port;
451
}
452

    
453
function openvpn_get_cipherlist() {
454

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

    
467
function openvpn_get_curvelist() {
468

    
469
	$curves = array();
470
	$curves["none"] = gettext("Use Default");
471
	$curve_out = shell_exec('/usr/local/sbin/openvpn --show-curves | /usr/bin/grep -v \'Available Elliptic curves\'');
472
	$curve_lines = explode("\n", trim($curve_out));
473
	sort($curve_lines);
474
	foreach ($curve_lines as $line) {
475
		$line = trim($line);
476
		$curves[$line] = $line;
477
	}
478
	return $curves;
479
}
480

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
891
	$conf .= "ping-timer-rem\n";
892
	$conf .= "persist-tun\n";
893
	$conf .= "persist-key\n";
894
	$conf .= "proto {$proto}\n";
895
	$conf .= "cipher {$cipher}\n";
896
	$conf .= "auth {$digest}\n";
897
	$conf .= "up /usr/local/sbin/ovpn-linkup\n";
898
	$conf .= "down /usr/local/sbin/ovpn-linkdown\n";
899
	if (file_exists("/usr/local/sbin/openvpn.attributes.sh")) {
900
		switch ($settings['mode']) {
901
			case 'server_user':
902
			case 'server_tls_user':
903
				$conf .= "client-connect /usr/local/sbin/openvpn.attributes.sh\n";
904
				$conf .= "client-disconnect /usr/local/sbin/openvpn.attributes.sh\n";
905
				break;
906
		}
907
	}
908
	if ($settings['dev_mode'] === 'tun' && isset($config['unbound']['enable']) && isset($config['unbound']['regovpnclients'])) {
909
		switch($settings['mode']) {
910
			case 'server_tls':
911
			case 'server_tls_user':
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
				break;
917
		}
918
	}
919

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1113
	// client specific settings
1114

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

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

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

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

    
1140
		// The remote server
1141
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']}\n";
1142

    
1143
		if (!empty($settings['use_shaper'])) {
1144
			$conf .= "shaper {$settings['use_shaper']}\n";
1145
		}
1146

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

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

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

    
1189
		if ($settings['proxy_addr']) {
1190
			$conf .= "http-proxy {$settings['proxy_addr']} {$settings['proxy_port']}";
1191
			if ($settings['proxy_authtype'] != "none") {
1192
				$conf .= " {$g['varetc_path']}/openvpn/{$mode_id}.pas {$settings['proxy_authtype']}";
1193
				$proxypas = "{$settings['proxy_user']}\n";
1194
				$proxypas .= "{$settings['proxy_passwd']}\n";
1195
				file_put_contents("{$g['varetc_path']}/openvpn/{$mode_id}.pas", $proxypas);
1196
			}
1197
			$conf .= " \n";
1198
		}
1199
	}
1200

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

    
1210
	// Write the settings for the keys
1211
	switch ($settings['mode']) {
1212
		case 'p2p_shared_key':
1213
			openvpn_add_keyfile($settings['shared_key'], $conf, $mode_id, "secret");
1214
			break;
1215
		case 'p2p_tls':
1216
		case 'server_tls':
1217
		case 'server_tls_user':
1218
		case 'server_user':
1219
			// ca_chain() expects parameter to be passed by reference.
1220
			// avoid passing the whole settings array, as param names or
1221
			// types might change in future releases.
1222
			$param = array('caref' => $settings['caref']);
1223
			$ca = ca_chain($param);
1224
			$ca = base64_encode($ca);
1225

    
1226
			openvpn_add_keyfile($ca, $conf, $mode_id, "ca");
1227

    
1228
			unset($ca, $param);
1229

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

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

    
1301
			break;
1302
	}
1303

    
1304
	$compression = "";
1305
	switch ($settings['compression']) {
1306
		case 'none':
1307
			$settings['compression'] = '';
1308
		case 'lz4':
1309
		case 'lz4-v2':
1310
		case 'lzo':
1311
		case 'stub':
1312
		case 'stub-v2':
1313
			$compression .= "compress {$settings['compression']}";
1314
			break;
1315
		case 'noadapt':
1316
			$compression .= "comp-noadapt";
1317
			break;
1318
		case 'adaptive':
1319
		case 'yes':
1320
		case 'no':
1321
			$compression .= "comp-lzo {$settings['compression']}";
1322
			break;
1323
		default:
1324
			/* Add nothing to the configuration */
1325
			break;
1326
	}
1327

    
1328
	if (!empty($compression)) {
1329
		$conf .= "{$compression}\n";
1330
		if ($settings['compression_push']) {
1331
			$conf .= "push \"{$compression}\"\n";
1332
		}
1333
	}
1334

    
1335
	if ($settings['passtos']) {
1336
		$conf .= "passtos\n";
1337
	}
1338

    
1339
	if ($mode == 'client') {
1340
		$conf .= "resolv-retry infinite\n";
1341
	}
1342

    
1343
	if ($settings['dynamic_ip']) {
1344
		$conf .= "persist-remote-ip\n";
1345
		$conf .= "float\n";
1346
	}
1347

    
1348
	// If the server is not a TLS server or it has a tunnel network CIDR less than a /30, skip this.
1349
	if (in_array($settings['mode'], $openvpn_tls_server_modes) && (!empty($ip) && !empty($mask) && ($cidr < 30)) && $settings['dev_mode'] != "tap") {
1350
		if (empty($settings['topology'])) {
1351
			$settings['topology'] = "subnet";
1352
		}
1353
		$conf .= "topology {$settings['topology']}\n";
1354
	}
1355

    
1356
	// New client features
1357
	if ($mode == "client") {
1358
		// Dont pull routes checkbox
1359
		if ($settings['route_no_pull']) {
1360
			$conf .= "route-nopull\n";
1361
		}
1362

    
1363
		// Dont add/remove routes checkbox
1364
		if ($settings['route_no_exec']) {
1365
			$conf .= "route-noexec\n";
1366
		}
1367
	}
1368

    
1369
	/* UDP Fast I/O. Only compatible with UDP and also not compatible with OpenVPN's "shaper" directive. */
1370
	if ($settings['udp_fast_io']
1371
	    && (strtolower(substr($settings['protocol'], 0, 3)) == "udp")
1372
	    && (empty($settings['use_shaper']))) {
1373
		$conf .= "fast-io\n";
1374
	}
1375

    
1376
	/* Exit Notify. Only compatible with UDP. */
1377
	if (!empty($settings['exit_notify']) &&
1378
	    is_numericint($settings['exit_notify']) &&
1379
	    (strtolower(substr($settings['protocol'], 0, 3)) == "udp")) {
1380
		$conf .= "explicit-exit-notify {$settings['exit_notify']}\n";
1381
	}
1382

    
1383
	/* Send and Receive Buffer Settings */
1384
	if (is_numericint($settings['sndrcvbuf'])
1385
	    && ($settings['sndrcvbuf'] > 0)
1386
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.sendbuf_max'))
1387
	    && ($settings['sndrcvbuf'] <= get_single_sysctl('net.inet.tcp.recvbuf_max'))) {
1388
		$conf .= "sndbuf {$settings['sndrcvbuf']}\n";
1389
		$conf .= "rcvbuf {$settings['sndrcvbuf']}\n";
1390
	}
1391

    
1392
	openvpn_add_custom($settings, $conf);
1393

    
1394
	openvpn_create_dirs();
1395
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.conf";
1396
	file_put_contents($fpath, $conf);
1397
	unset($conf);
1398
	$fpath = "{$g['varetc_path']}/openvpn/{$mode_id}.interface";
1399
	file_put_contents($fpath, $interface);
1400
	//chown($fpath, 'nobody');
1401
	//chgrp($fpath, 'nobody');
1402
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1403
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.interface", 0600);
1404
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.key", 0600);
1405
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.tls-auth", 0600);
1406
	@chmod("{$g['varetc_path']}/openvpn/{$mode_id}.conf", 0600);
1407

    
1408
	if ($wait_tentative) {
1409
		interface_wait_tentative($interface);
1410
	}
1411
}
1412

    
1413
function openvpn_restart($mode, $settings) {
1414
	global $g, $config;
1415

    
1416
	$vpnid = $settings['vpnid'];
1417
	$mode_id = $mode.$vpnid;
1418
	$lockhandle = lock("openvpnservice{$mode_id}", LOCK_EX);
1419
	openvpn_reconfigure($mode, $settings);
1420
	/* kill the process if running */
1421
	$pfile = $g['varrun_path']."/openvpn_{$mode_id}.pid";
1422
	if (file_exists($pfile)) {
1423

    
1424
		/* read the pid file */
1425
		$pid = rtrim(file_get_contents($pfile));
1426
		unlink($pfile);
1427
		syslog(LOG_INFO, "OpenVPN terminate old pid: {$pid}");
1428

    
1429
		/* send a term signal to the process */
1430
		posix_kill($pid, SIGTERM);
1431

    
1432
		/* wait until the process exits, or timeout and kill it */
1433
		$i = 0;
1434
		while (posix_kill($pid, 0)) {
1435
			usleep(250000);
1436
			if ($i > 10) {
1437
				log_error(sprintf(gettext('OpenVPN ID %1$s PID %2$s still running, killing.'), $mode_id, $pid));
1438
				posix_kill($pid, SIGKILL);
1439
				usleep(500000);
1440
			}
1441
			$i++;
1442
		}
1443
	}
1444

    
1445
	if (isset($settings['disable'])) {
1446
		unlock($lockhandle);
1447
		return;
1448
	}
1449

    
1450
	/* Do not start an instance if we are not CARP master on this vip! */
1451
	if (strstr($settings['interface'], "_vip") && !in_array(get_carp_interface_status($settings['interface']), array("MASTER", ""))) {
1452
		unlock($lockhandle);
1453
		return;
1454
	}
1455

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

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

    
1491
function openvpn_delete($mode, $settings) {
1492
	global $g, $config;
1493

    
1494
	$vpnid = $settings['vpnid'];
1495
	$mode_id = $mode.$vpnid;
1496

    
1497
	if ($mode == "server") {
1498
		$devname = "ovpns{$vpnid}";
1499
	} else {
1500
		$devname = "ovpnc{$vpnid}";
1501
	}
1502

    
1503
	/* kill the process if running */
1504
	$pfile = "{$g['varrun_path']}/openvpn_{$mode_id}.pid";
1505
	if (file_exists($pfile)) {
1506

    
1507
		/* read the pid file */
1508
		$pid = trim(file_get_contents($pfile));
1509
		unlink($pfile);
1510

    
1511
		/* send a term signal to the process */
1512
		posix_kill($pid, SIGTERM);
1513
	}
1514

    
1515
	/* destroy the device */
1516
	pfSense_interface_destroy($devname);
1517

    
1518
	/* remove the configuration files */
1519
	@array_map('unlink', glob("{$g['varetc_path']}/openvpn/{$mode_id}.*"));
1520
}
1521

    
1522
function openvpn_resync_csc(& $settings) {
1523
	global $g, $config, $openvpn_tls_server_modes;
1524

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

    
1527
	if (isset($settings['disable'])) {
1528
		openvpn_delete_csc($settings);
1529
		return;
1530
	}
1531
	openvpn_create_dirs();
1532

    
1533
	if (empty($settings['server_list'])) {
1534
		$csc_server_list = array();
1535
	} else {
1536
		$csc_server_list = explode(",", $settings['server_list']);
1537
	}
1538

    
1539
	$conf = '';
1540
	if ($settings['block']) {
1541
		$conf .= "disable\n";
1542
	}
1543

    
1544
	if ($settings['push_reset']) {
1545
		$conf .= "push-reset\n";
1546
	}
1547

    
1548
	if ($settings['local_network']) {
1549
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1550
	}
1551
	if ($settings['local_networkv6']) {
1552
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1553
	}
1554

    
1555
	// Add a remote network iroute if set
1556
	if (openvpn_validate_cidr($settings['remote_network'], "", true, "ipv4") === FALSE) {
1557
		$conf .= openvpn_gen_routes($settings['remote_network'], "ipv4", false, true);
1558
	}
1559
	// Add a remote network iroute if set
1560
	if (openvpn_validate_cidr($settings['remote_networkv6'], "", true, "ipv6") === FALSE) {
1561
		$conf .= openvpn_gen_routes($settings['remote_networkv6'], "ipv6", false, true);
1562
	}
1563

    
1564
	openvpn_add_dhcpopts($settings, $conf);
1565

    
1566
	openvpn_add_custom($settings, $conf);
1567
	/* Loop through servers, find which ones can use this CSC */
1568
	if (is_array($config['openvpn']['openvpn-server'])) {
1569
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1570
			if (isset($serversettings['disable'])) {
1571
				continue;
1572
			}
1573
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1574
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1575
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1576
					$csc_conf = $conf;
1577

    
1578
					if (!empty($serversettings['tunnel_network']) && !empty($settings['tunnel_network'])) {
1579
						list($ip, $mask) = explode('/', trim($settings['tunnel_network']));
1580
						if (($serversettings['dev_mode'] == 'tap') || ($serversettings['topology'] == "subnet")) {
1581
							$csc_conf .= "ifconfig-push {$ip} " . gen_subnet_mask($mask) . "\n";
1582
						} else {
1583
							/* Because this is being pushed, the order from the client's point of view. */
1584
							$baselong = gen_subnetv4($ip, $mask);
1585
							$serverip = ip_after($baselong, 1);
1586
							$clientip = ip_after($baselong, 2);
1587
							$csc_conf .= "ifconfig-push {$clientip} {$serverip}\n";
1588
						}
1589
					}
1590

    
1591
					if (!empty($serversettings['tunnel_networkv6']) && !empty($settings['tunnel_networkv6'])) {
1592
						list($ipv6, $prefix) = explode('/', trim($serversettings['tunnel_networkv6']));
1593
						list($ipv6_1, $ipv6_2) = openvpn_get_interface_ipv6($ipv6, $prefix);
1594
						$csc_conf .= "ifconfig-ipv6-push {$settings['tunnel_networkv6']} {$ipv6_1}\n";
1595
					}
1596

    
1597
					file_put_contents($csc_path, $csc_conf);
1598
					chown($csc_path, 'nobody');
1599
					chgrp($csc_path, 'nobody');
1600
				}
1601
			}
1602
		}
1603
	}
1604
}
1605

    
1606
function openvpn_resync_csc_all() {
1607
	global $config;
1608
	if (is_array($config['openvpn']['openvpn-csc'])) {
1609
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1610
			openvpn_resync_csc($settings);
1611
		}
1612
	}
1613
}
1614

    
1615
function openvpn_delete_csc(& $settings) {
1616
	global $g, $config, $openvpn_tls_server_modes;
1617
	$csc_base_path = "{$g['varetc_path']}/openvpn-csc";
1618
	if (empty($settings['server_list'])) {
1619
		$csc_server_list = array();
1620
	} else {
1621
		$csc_server_list = explode(",", $settings['server_list']);
1622
	}
1623

    
1624
	/* Loop through servers, find which ones used this CSC */
1625
	if (is_array($config['openvpn']['openvpn-server'])) {
1626
		foreach ($config['openvpn']['openvpn-server'] as $serversettings) {
1627
			if (isset($serversettings['disable'])) {
1628
				continue;
1629
			}
1630
			if (in_array($serversettings['mode'], $openvpn_tls_server_modes)) {
1631
				if ($serversettings['vpnid'] && (empty($csc_server_list) || in_array($serversettings['vpnid'], $csc_server_list))) {
1632
					$csc_path = "{$csc_base_path}/server{$serversettings['vpnid']}/" . basename($settings['common_name']);
1633
					unlink_if_exists($csc_path);
1634
				}
1635
			}
1636
		}
1637
	}
1638
}
1639

    
1640
// Resync the configuration and restart the VPN
1641
function openvpn_resync($mode, $settings) {
1642
	openvpn_restart($mode, $settings);
1643
}
1644

    
1645
// Resync and restart all VPNs
1646
function openvpn_resync_all($interface = "") {
1647
	global $g, $config;
1648

    
1649
	openvpn_create_dirs();
1650

    
1651
	if (!is_array($config['openvpn'])) {
1652
		$config['openvpn'] = array();
1653
	}
1654

    
1655
/*
1656
	if (!$config['openvpn']['dh-parameters']) {
1657
		echo "Configuring OpenVPN Parameters ...\n";
1658
		$dh_parameters = openvpn_create_dhparams(1024);
1659
		$dh_parameters = base64_encode($dh_parameters);
1660
		$config['openvpn']['dh-parameters'] = $dh_parameters;
1661
		write_config("OpenVPN DH parameters");
1662
	}
1663

    
1664
	$path_ovdh = $g['varetc_path']."/openvpn/dh-parameters";
1665
	if (!file_exists($path_ovdh)) {
1666
		$dh_parameters = $config['openvpn']['dh-parameters'];
1667
		$dh_parameters = base64_decode($dh_parameters);
1668
		file_put_contents($path_ovdh, $dh_parameters);
1669
	}
1670
*/
1671
	if ($interface <> "") {
1672
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1673
	} else {
1674
		log_error(gettext("Resyncing OpenVPN instances."));
1675
	}
1676

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

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

    
1696
			if ($ip_change || $gw_group_change) {
1697
				openvpn_resync($type, $settings);
1698
			}
1699
		}
1700
	}
1701

    
1702
	openvpn_resync_csc_all();
1703

    
1704
}
1705

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

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

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

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

    
1731
	} else {
1732
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1733
	}
1734
}
1735

    
1736
function openvpn_get_active_servers($type="multipoint") {
1737
	global $config, $g;
1738

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

    
1746
			$prot = $settings['protocol'];
1747
			$port = $settings['local_port'];
1748

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

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

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

    
1780
		/* send our status request */
1781
		fputs($fp, "status 2\n");
1782

    
1783
		/* recv all response lines */
1784
		while (!feof($fp)) {
1785

    
1786
			/* read the next line */
1787
			$line = fgets($fp, 1024);
1788

    
1789
			$info = stream_get_meta_data($fp);
1790
			if ($info['timed_out']) {
1791
				break;
1792
			}
1793

    
1794
			/* parse header list line */
1795
			if (strstr($line, "HEADER")) {
1796
				continue;
1797
			}
1798

    
1799
			/* parse end of output line */
1800
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1801
				break;
1802
			}
1803

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

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

    
1848
function openvpn_get_active_clients() {
1849
	global $config, $g;
1850

    
1851
	$clients = array();
1852
	if (is_array($config['openvpn']['openvpn-client'])) {
1853
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1854

    
1855
			if (empty($settings) || isset($settings['disable'])) {
1856
				continue;
1857
			}
1858

    
1859
			$prot = $settings['protocol'];
1860
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1861

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

    
1870
			$client['vpnid'] = $settings['vpnid'];
1871
			$client['mgmt'] = "client{$client['vpnid']}";
1872
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1873
			$client['status']="down";
1874

    
1875
			$clients[] = openvpn_get_client_status($client, $socket);
1876
		}
1877
	}
1878
	return $clients;
1879
}
1880

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

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

    
1895
			$info = stream_get_meta_data($fp);
1896
			if ($info['timed_out']) {
1897
				break;
1898
			}
1899

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

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

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

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

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

    
1944
				$info = stream_get_meta_data($fp);
1945
				if ($info['timed_out']) {
1946
					break;
1947
				}
1948

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

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

    
1959
				/* parse end of output line */
1960
				if (strstr($line, "END")) {
1961
					break;
1962
				}
1963
			}
1964
		}
1965

    
1966
		fclose($fp);
1967

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

    
1978
function openvpn_kill_client($port, $remipp) {
1979
	global $g;
1980

    
1981
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1982
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1983
	$errval = null;
1984
	$errstr = null;
1985

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

    
1995
			$info = stream_get_meta_data($fp);
1996
			if ($info['timed_out']) {
1997
				break;
1998
			}
1999

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

    
2014
function openvpn_refresh_crls() {
2015
	global $g, $config;
2016

    
2017
	openvpn_create_dirs();
2018

    
2019
	if (is_array($config['openvpn']['openvpn-server'])) {
2020
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2021
			if (empty($settings)) {
2022
				continue;
2023
			}
2024
			if (isset($settings['disable'])) {
2025
				continue;
2026
			}
2027
			// Write the settings for the keys
2028
			switch ($settings['mode']) {
2029
				case 'p2p_tls':
2030
				case 'server_tls':
2031
				case 'server_tls_user':
2032
				case 'server_user':
2033
					if (!empty($settings['crlref'])) {
2034
						$crl = lookup_crl($settings['crlref']);
2035
						crl_update($crl);
2036
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
2037
						file_put_contents($fpath, base64_decode($crl['text']));
2038
						@chmod($fpath, 0644);
2039
					}
2040
					break;
2041
			}
2042
		}
2043
	}
2044
}
2045

    
2046
function openvpn_create_dirs() {
2047
	global $g, $config, $openvpn_tls_server_modes;
2048
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
2049
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
2050
	}
2051
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
2052
		/* If it's a file, remove it */
2053
		if (file_exists("{$g['varetc_path']}/openvpn-csc")) {
2054
			unlink_if_exists("{$g['varetc_path']}/openvpn-csc");
2055
		}
2056
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
2057
	}
2058

    
2059
	/* Check for enabled servers and create server-specific CSC dirs */
2060
	if (is_array($config['openvpn']['openvpn-server'])) {
2061
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2062
			if (isset($settings['disable'])) {
2063
				continue;
2064
			}
2065
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2066
				if ($settings['vpnid']) {
2067
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
2068
				}
2069
			}
2070
		}
2071
	}
2072
}
2073

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

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

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

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

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

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

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

    
2140
		if ($push) {
2141
			$routes .= "push \"{$route}\"\n";
2142
		} else {
2143
			$routes .= "{$route}\n";
2144
		}
2145
	}
2146
	return $routes;
2147
}
2148

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

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

    
2165
function openvpn_get_settings($mode, $vpnid) {
2166
	global $config;
2167

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

    
2174
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2175
				return $settings;
2176
			}
2177
		}
2178
	}
2179

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

    
2186
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2187
				return $settings;
2188
			}
2189
		}
2190
	}
2191

    
2192
	return array();
2193
}
2194

    
2195
function openvpn_restart_by_vpnid($mode, $vpnid) {
2196
	$settings = openvpn_get_settings($mode, $vpnid);
2197
	openvpn_restart($mode, $settings);
2198
}
2199

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

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