Project

General

Profile

Download (63.9 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
		$conf .= "remote {$settings['server_addr']} {$settings['server_port']} {$remoteproto}\n";
1144

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

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

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

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

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

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

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

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

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

    
1307
			break;
1308
	}
1309

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

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

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

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

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

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

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

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

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

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

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

    
1398
	openvpn_add_custom($settings, $conf);
1399

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1524
	/* remove the configuration files */
1525
	@array_map('unlink', glob("{$g['openvpn_base']}/{$mode_id}/csc/*"));
1526
	@array_map('unlink', glob("{$g['openvpn_base']}/{$mode_id}/*"));
1527
}
1528

    
1529
function openvpn_resync_csc(& $settings) {
1530
	global $g, $config, $openvpn_tls_server_modes;
1531
	if (isset($settings['disable'])) {
1532
		openvpn_delete_csc($settings);
1533
		return;
1534
	}
1535
	openvpn_create_dirs();
1536

    
1537
	if (empty($settings['server_list'])) {
1538
		$csc_server_list = array();
1539
	} else {
1540
		$csc_server_list = explode(",", $settings['server_list']);
1541
	}
1542

    
1543
	$conf = '';
1544
	if ($settings['block']) {
1545
		$conf .= "disable\n";
1546
	}
1547

    
1548
	if ($settings['push_reset']) {
1549
		$conf .= "push-reset\n";
1550
	}
1551

    
1552
	if ($settings['local_network']) {
1553
		$conf .= openvpn_gen_routes($settings['local_network'], "ipv4", true);
1554
	}
1555
	if ($settings['local_networkv6']) {
1556
		$conf .= openvpn_gen_routes($settings['local_networkv6'], "ipv6", true);
1557
	}
1558

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

    
1568
	openvpn_add_dhcpopts($settings, $conf);
1569

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

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

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

    
1601
					file_put_contents($csc_path, $csc_conf);
1602
					chown($csc_path, 'nobody');
1603
					chgrp($csc_path, 'nobody');
1604
				}
1605
			}
1606
		}
1607
	}
1608
}
1609

    
1610
function openvpn_resync_csc_all() {
1611
	global $config;
1612
	if (is_array($config['openvpn']['openvpn-csc'])) {
1613
		foreach ($config['openvpn']['openvpn-csc'] as & $settings) {
1614
			openvpn_resync_csc($settings);
1615
		}
1616
	}
1617
}
1618

    
1619
function openvpn_delete_csc(& $settings) {
1620
	global $g, $config, $openvpn_tls_server_modes;
1621
	if (empty($settings['server_list'])) {
1622
		$csc_server_list = array();
1623
	} else {
1624
		$csc_server_list = explode(",", $settings['server_list']);
1625
	}
1626

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

    
1643
// Resync the configuration and restart the VPN
1644
function openvpn_resync($mode, $settings) {
1645
	openvpn_restart($mode, $settings);
1646
}
1647

    
1648
// Resync and restart all VPNs
1649
function openvpn_resync_all($interface = "") {
1650
	global $g, $config;
1651

    
1652
	openvpn_create_dirs();
1653

    
1654
	if (!is_array($config['openvpn'])) {
1655
		$config['openvpn'] = array();
1656
	}
1657

    
1658
	if ($interface <> "") {
1659
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1660
	} else {
1661
		log_error(gettext("Resyncing OpenVPN instances."));
1662
	}
1663

    
1664
	// Check if OpenVPN clients and servers require a resync.
1665
	foreach (array("server", "client") as $type) {
1666
		if (!is_array($config['openvpn']["openvpn-{$type}"])) {
1667
			continue;
1668
		}
1669
		foreach ($config['openvpn']["openvpn-{$type}"] as & $settings) {
1670
			$fpath = "{$g['openvpn_base']}/{$type}{$settings['vpnid']}/interface";
1671
			$gw_group_change = FALSE;
1672
			$ip_change = ($interface === "") ||
1673
			    ($interface === $settings['interface']);
1674

    
1675
			if (!$ip_change && file_exists($fpath)) {
1676
				$gw_group_change =
1677
				    (trim(file_get_contents($fpath), " \t\n") !=
1678
				    get_failover_interface(
1679
					$settings['interface']));
1680
			}
1681

    
1682
			if ($ip_change || $gw_group_change) {
1683
				openvpn_resync($type, $settings);
1684
			}
1685
		}
1686
	}
1687

    
1688
	openvpn_resync_csc_all();
1689

    
1690
}
1691

    
1692
// Resync and restart all VPNs using a gateway group.
1693
function openvpn_resync_gwgroup($gwgroupname = "") {
1694
	global $g, $config;
1695

    
1696
	if ($gwgroupname <> "") {
1697
		if (is_array($config['openvpn']['openvpn-server'])) {
1698
			foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1699
				if ($gwgroupname == $settings['interface']) {
1700
					log_error(sprintf(gettext('Resyncing OpenVPN for gateway group %1$s server %2$s.'), $gwgroupname, $settings["description"]));
1701
					openvpn_resync('server', $settings);
1702
				}
1703
			}
1704
		}
1705

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

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

    
1717
	} else {
1718
		log_error(gettext("openvpn_resync_gwgroup called with null gwgroup parameter."));
1719
	}
1720
}
1721

    
1722
function openvpn_get_active_servers($type="multipoint") {
1723
	global $config, $g;
1724

    
1725
	$servers = array();
1726
	if (is_array($config['openvpn']['openvpn-server'])) {
1727
		foreach ($config['openvpn']['openvpn-server'] as & $settings) {
1728
			if (empty($settings) || isset($settings['disable'])) {
1729
				continue;
1730
			}
1731

    
1732
			$prot = $settings['protocol'];
1733
			$port = $settings['local_port'];
1734

    
1735
			$server = array();
1736
			$server['port'] = ($settings['local_port']) ? $settings['local_port'] : 1194;
1737
			$server['mode'] = $settings['mode'];
1738
			if ($settings['description']) {
1739
				$server['name'] = "{$settings['description']} {$prot}:{$port}";
1740
			} else {
1741
				$server['name'] = "Server {$prot}:{$port}";
1742
			}
1743
			$server['conns'] = array();
1744
			$server['vpnid'] = $settings['vpnid'];
1745
			$server['mgmt'] = "server{$server['vpnid']}";
1746
			$socket = "unix://{$g['openvpn_base']}/{$server['mgmt']}/sock";
1747
			list($tn, $sm) = explode('/', trim($settings['tunnel_network']));
1748

    
1749
			if ((($server['mode'] == "p2p_shared_key") || ($sm >= 30)) && ($type == "p2p")) {
1750
				$servers[] = openvpn_get_client_status($server, $socket);
1751
			} elseif (($server['mode'] != "p2p_shared_key") && ($type == "multipoint") && ($sm < 30)) {
1752
				$servers[] = openvpn_get_server_status($server, $socket);
1753
			}
1754
		}
1755
	}
1756
	return $servers;
1757
}
1758

    
1759
function openvpn_get_server_status($server, $socket) {
1760
	$errval = null;
1761
	$errstr = null;
1762
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1763
	if ($fp) {
1764
		stream_set_timeout($fp, 1);
1765

    
1766
		/* send our status request */
1767
		fputs($fp, "status 2\n");
1768

    
1769
		/* recv all response lines */
1770
		while (!feof($fp)) {
1771

    
1772
			/* read the next line */
1773
			$line = fgets($fp, 1024);
1774

    
1775
			$info = stream_get_meta_data($fp);
1776
			if ($info['timed_out']) {
1777
				break;
1778
			}
1779

    
1780
			/* parse header list line */
1781
			if (strstr($line, "HEADER")) {
1782
				continue;
1783
			}
1784

    
1785
			/* parse end of output line */
1786
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1787
				break;
1788
			}
1789

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

    
1819
		/* cleanup */
1820
		fclose($fp);
1821
	} else {
1822
		$conn = array();
1823
		$conn['common_name'] = "[error]";
1824
		$conn['remote_host'] = gettext("Unable to contact daemon");
1825
		$conn['virtual_addr'] = gettext("Service not running?");
1826
		$conn['bytes_recv'] = 0;
1827
		$conn['bytes_sent'] = 0;
1828
		$conn['connect_time'] = 0;
1829
		$server['conns'][] = $conn;
1830
	}
1831
	return $server;
1832
}
1833

    
1834
function openvpn_get_active_clients() {
1835
	global $config, $g;
1836

    
1837
	$clients = array();
1838
	if (is_array($config['openvpn']['openvpn-client'])) {
1839
		foreach ($config['openvpn']['openvpn-client'] as & $settings) {
1840

    
1841
			if (empty($settings) || isset($settings['disable'])) {
1842
				continue;
1843
			}
1844

    
1845
			$prot = $settings['protocol'];
1846
			$port = ($settings['local_port']) ? ":{$settings['local_port']}" : "";
1847

    
1848
			$client = array();
1849
			$client['port'] = $settings['local_port'];
1850
			if ($settings['description']) {
1851
				$client['name'] = "{$settings['description']} {$prot}{$port}";
1852
			} else {
1853
				$client['name'] = "Client {$prot}{$port}";
1854
			}
1855

    
1856
			$client['vpnid'] = $settings['vpnid'];
1857
			$client['mgmt'] = "client{$client['vpnid']}";
1858
			$socket = "unix://{$g['openvpn_base']}/{$client['mgmt']}/sock";
1859
			$client['status']="down";
1860

    
1861
			$clients[] = openvpn_get_client_status($client, $socket);
1862
		}
1863
	}
1864
	return $clients;
1865
}
1866

    
1867
function openvpn_get_client_status($client, $socket) {
1868
	$errval = null;
1869
	$errstr = null;
1870
	$fp = @stream_socket_client($socket, $errval, $errstr, 1);
1871
	if ($fp) {
1872
		stream_set_timeout($fp, 1);
1873
		/* send our status request */
1874
		fputs($fp, "state 1\n");
1875

    
1876
		/* recv all response lines */
1877
		while (!feof($fp)) {
1878
			/* read the next line */
1879
			$line = fgets($fp, 1024);
1880

    
1881
			$info = stream_get_meta_data($fp);
1882
			if ($info['timed_out']) {
1883
				break;
1884
			}
1885

    
1886
			/* Get the client state */
1887
			if (strstr($line, "CONNECTED")) {
1888
				$client['status'] = "up";
1889
				$list = explode(",", $line);
1890

    
1891
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1892
				$client['virtual_addr'] = $list[3];
1893
				$client['remote_host'] = $list[4];
1894
				$client['remote_port'] = $list[5];
1895
				$client['local_host'] = $list[6];
1896
				$client['local_port'] = $list[7];
1897
				$client['virtual_addr6'] = $list[8];
1898
			}
1899
			if (strstr($line, "CONNECTING")) {
1900
				$client['status'] = "connecting";
1901
			}
1902
			if (strstr($line, "ASSIGN_IP")) {
1903
				$client['status'] = "waiting";
1904
				$list = explode(",", $line);
1905

    
1906
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1907
				$client['virtual_addr'] = $list[3];
1908
			}
1909
			if (strstr($line, "RECONNECTING")) {
1910
				$client['status'] = "reconnecting";
1911
				$list = explode(",", $line);
1912

    
1913
				$client['connect_time'] = date("D M j G:i:s Y", $list[0]);
1914
				$client['status'] .= "; " . $list[2];
1915
			}
1916
			/* parse end of output line */
1917
			if (strstr($line, "END") || strstr($line, "ERROR")) {
1918
				break;
1919
			}
1920
		}
1921

    
1922
		/* If up, get read/write stats */
1923
		if (strcmp($client['status'], "up") == 0) {
1924
			fputs($fp, "status 2\n");
1925
			/* recv all response lines */
1926
			while (!feof($fp)) {
1927
				/* read the next line */
1928
				$line = fgets($fp, 1024);
1929

    
1930
				$info = stream_get_meta_data($fp);
1931
				if ($info['timed_out']) {
1932
					break;
1933
				}
1934

    
1935
				if (strstr($line, "TCP/UDP read bytes")) {
1936
					$list = explode(",", $line);
1937
					$client['bytes_recv'] = $list[1];
1938
				}
1939

    
1940
				if (strstr($line, "TCP/UDP write bytes")) {
1941
					$list = explode(",", $line);
1942
					$client['bytes_sent'] = $list[1];
1943
				}
1944

    
1945
				/* parse end of output line */
1946
				if (strstr($line, "END")) {
1947
					break;
1948
				}
1949
			}
1950
		}
1951

    
1952
		fclose($fp);
1953

    
1954
	} else {
1955
		$client['remote_host'] = gettext("Unable to contact daemon");
1956
		$client['virtual_addr'] = gettext("Service not running?");
1957
		$client['bytes_recv'] = 0;
1958
		$client['bytes_sent'] = 0;
1959
		$client['connect_time'] = 0;
1960
	}
1961
	return $client;
1962
}
1963

    
1964
function openvpn_kill_client($port, $remipp) {
1965
	global $g;
1966

    
1967
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1968
	$tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";
1969
	$errval = null;
1970
	$errstr = null;
1971

    
1972
	/* open a tcp connection to the management port of each server */
1973
	$fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
1974
	$killed = -1;
1975
	if ($fp) {
1976
		stream_set_timeout($fp, 1);
1977
		fputs($fp, "kill {$remipp}\n");
1978
		while (!feof($fp)) {
1979
			$line = fgets($fp, 1024);
1980

    
1981
			$info = stream_get_meta_data($fp);
1982
			if ($info['timed_out']) {
1983
				break;
1984
			}
1985

    
1986
			/* parse header list line */
1987
			if (strpos($line, "INFO:") !== false) {
1988
				continue;
1989
			}
1990
			if (strpos($line, "SUCCESS") !== false) {
1991
				$killed = 0;
1992
			}
1993
			break;
1994
		}
1995
		fclose($fp);
1996
	}
1997
	return $killed;
1998
}
1999

    
2000
function openvpn_refresh_crls() {
2001
	global $g, $config;
2002

    
2003
	openvpn_create_dirs();
2004

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

    
2036
function openvpn_create_dirs() {
2037
	global $g, $config, $openvpn_tls_server_modes;
2038
	if (!is_dir($g['openvpn_base'])) {
2039
		safe_mkdir($g['openvpn_base'], 0750);
2040
	}
2041

    
2042
	init_config_arr(array('openvpn', 'openvpn-server'));
2043
	init_config_arr(array('openvpn', 'openvpn-client'));
2044
	foreach(array('server', 'client') as $mode) {
2045
		foreach ($config['openvpn']["openvpn-{$mode}"] as $settings) {
2046
			$target = "{$g['openvpn_base']}/{$mode}{$settings['vpnid']}";
2047
			@unlink_if_exists($csctarget);
2048
			@safe_mkdir($target);
2049
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2050
				if ($settings['vpnid']) {
2051
					$csctarget = "{$target}/csc/";
2052
					@unlink_if_exists($csctarget);
2053
					@safe_mkdir($csctarget);
2054
				}
2055
			}
2056
		}
2057
	}
2058
}
2059

    
2060
function openvpn_get_interface_ip($ip, $cidr) {
2061
	$subnet = gen_subnetv4($ip, $cidr);
2062
	if ($cidr == 31) {
2063
		$ip1 = $subnet;
2064
	} else {
2065
		$ip1 = ip_after($subnet);
2066
	}
2067
	$ip2 = ip_after($ip1);
2068
	return array($ip1, $ip2);
2069
}
2070

    
2071
function openvpn_get_interface_ipv6($ipv6, $prefix) {
2072
	$basev6 = gen_subnetv6($ipv6, $prefix);
2073
	// Is there a better way to do this math?
2074
	$ipv6_arr = explode(':', $basev6);
2075
	$last = hexdec(array_pop($ipv6_arr));
2076
	if ($prefix == 127) {
2077
		$last--;
2078
	}
2079
	$ipv6_1 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 1));
2080
	$ipv6_2 = text_to_compressed_ip6(implode(':', $ipv6_arr) . ':' . dechex($last + 2));
2081
	return array($ipv6_1, $ipv6_2);
2082
}
2083

    
2084
function openvpn_clear_route($mode, $settings) {
2085
	if (empty($settings['tunnel_network'])) {
2086
		return;
2087
	}
2088
	list($ip, $cidr) = explode('/', trim($settings['tunnel_network']));
2089
	$mask = gen_subnet_mask($cidr);
2090
	$clear_route = false;
2091

    
2092
	switch ($settings['mode']) {
2093
		case 'shared_key':
2094
			$clear_route = true;
2095
			break;
2096
		case 'p2p_tls':
2097
		case 'p2p_shared_key':
2098
			if ($cidr >= 30) {
2099
				$clear_route = true;
2100
			}
2101
			break;
2102
	}
2103

    
2104
	if ($clear_route && !empty($ip) && !empty($mask)) {
2105
		list($ip1, $ip2) = openvpn_get_interface_ip($ip, $cidr);
2106
		$ip_to_clear = ($mode == "server") ? $ip1 : $ip2;
2107
		/* XXX: Family for route? */
2108
		mwexec("/sbin/route -q delete {$ip_to_clear}");
2109
	}
2110
}
2111

    
2112
function openvpn_gen_routes($value, $ipproto = "ipv4", $push = false, $iroute = false) {
2113
	$routes = "";
2114
	if (empty($value)) {
2115
		return "";
2116
	}
2117
	$networks = explode(',', $value);
2118

    
2119
	foreach ($networks as $network) {
2120
		if ($ipproto == "ipv4") {
2121
			$route = openvpn_gen_route_ipv4($network, $iroute);
2122
		} else {
2123
			$route = openvpn_gen_route_ipv6($network, $iroute);
2124
		}
2125

    
2126
		if ($push) {
2127
			$routes .= "push \"{$route}\"\n";
2128
		} else {
2129
			$routes .= "{$route}\n";
2130
		}
2131
	}
2132
	return $routes;
2133
}
2134

    
2135
function openvpn_gen_route_ipv4($network, $iroute = false) {
2136
	$i = ($iroute) ? "i" : "";
2137
	list($ip, $mask) = explode('/', trim($network));
2138
	$mask = gen_subnet_mask($mask);
2139
	return "{$i}route $ip $mask";
2140
}
2141

    
2142
function openvpn_gen_route_ipv6($network, $iroute = false) {
2143
	$i = ($iroute) ? "i" : "";
2144
	list($ipv6, $prefix) = explode('/', trim($network));
2145
	if (empty($prefix) && !is_numeric($prefix)) {
2146
		$prefix = "128";
2147
	}
2148
	return "{$i}route-ipv6 ${ipv6}/${prefix}";
2149
}
2150

    
2151
function openvpn_get_settings($mode, $vpnid) {
2152
	global $config;
2153

    
2154
	if (is_array($config['openvpn']['openvpn-server'])) {
2155
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2156
			if (isset($settings['disable'])) {
2157
				continue;
2158
			}
2159

    
2160
			if ($vpnid != 0 && $vpnid == $settings['vpnid']) {
2161
				return $settings;
2162
			}
2163
		}
2164
	}
2165

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

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

    
2178
	return array();
2179
}
2180

    
2181
function openvpn_restart_by_vpnid($mode, $vpnid) {
2182
	$settings = openvpn_get_settings($mode, $vpnid);
2183
	openvpn_restart($mode, $settings);
2184
}
2185

    
2186
/****f* certs/openvpn_is_tunnel_network_in_use
2187
 * NAME
2188
 *   openvpn_is_tunnel_network_in_use
2189
 *     Check if the supplied network is in use as an OpenVPN server or client
2190
 *     tunnel network
2191
 * INPUTS
2192
 *   $net : The IPv4 or IPv6 network to check
2193
 * RESULT
2194
 *   boolean value: true if the network is in use, false otherwise.
2195
 ******/
2196

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