Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
171
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
		''  => 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['varetc_path']."/openvpn/{$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['varetc_path']}/openvpn-csc/server{$vpnid}\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['varetc_path']}/openvpn-csc/server{$vpnid}\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['varetc_path']}/openvpn-csc/server{$vpnid}\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
					$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
	if ($interface <> "") {
1656
		log_error(sprintf(gettext("Resyncing OpenVPN instances for interface %s."), convert_friendly_interface_to_friendly_descr($interface)));
1657
	} else {
1658
		log_error(gettext("Resyncing OpenVPN instances."));
1659
	}
1660

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

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

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

    
1686
	openvpn_resync_csc_all();
1687

    
1688
}
1689

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

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

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

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

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

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

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

    
1730
			$prot = $settings['protocol'];
1731
			$port = $settings['local_port'];
1732

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

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

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

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

    
1767
		/* recv all response lines */
1768
		while (!feof($fp)) {
1769

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

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

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

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

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

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

    
1832
function openvpn_get_active_clients() {
1833
	global $config, $g;
1834

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

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

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

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

    
1854
			$client['vpnid'] = $settings['vpnid'];
1855
			$client['mgmt'] = "client{$client['vpnid']}";
1856
			$socket = "unix://{$g['varetc_path']}/openvpn/{$client['mgmt']}.sock";
1857
			$client['status']="down";
1858

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1950
		fclose($fp);
1951

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

    
1962
function openvpn_kill_client($port, $remipp) {
1963
	global $g;
1964

    
1965
	//$tcpsrv = "tcp://127.0.0.1:{$port}";
1966
	$tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
1967
	$errval = null;
1968
	$errstr = null;
1969

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

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

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

    
1998
function openvpn_refresh_crls() {
1999
	global $g, $config;
2000

    
2001
	openvpn_create_dirs();
2002

    
2003
	if (is_array($config['openvpn']['openvpn-server'])) {
2004
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2005
			if (empty($settings)) {
2006
				continue;
2007
			}
2008
			if (isset($settings['disable'])) {
2009
				continue;
2010
			}
2011
			// Write the settings for the keys
2012
			switch ($settings['mode']) {
2013
				case 'p2p_tls':
2014
				case 'server_tls':
2015
				case 'server_tls_user':
2016
				case 'server_user':
2017
					if (!empty($settings['crlref'])) {
2018
						$crl = lookup_crl($settings['crlref']);
2019
						crl_update($crl);
2020
						$fpath = $g['varetc_path']."/openvpn/server{$settings['vpnid']}.crl-verify";
2021
						file_put_contents($fpath, base64_decode($crl['text']));
2022
						@chmod($fpath, 0644);
2023
					}
2024
					break;
2025
			}
2026
		}
2027
	}
2028
}
2029

    
2030
function openvpn_create_dirs() {
2031
	global $g, $config, $openvpn_tls_server_modes;
2032
	if (!is_dir("{$g['varetc_path']}/openvpn")) {
2033
		safe_mkdir("{$g['varetc_path']}/openvpn", 0750);
2034
	}
2035
	if (!is_dir("{$g['varetc_path']}/openvpn-csc")) {
2036
		/* If it's a file, remove it */
2037
		if (file_exists("{$g['varetc_path']}/openvpn-csc")) {
2038
			unlink_if_exists("{$g['varetc_path']}/openvpn-csc");
2039
		}
2040
		safe_mkdir("{$g['varetc_path']}/openvpn-csc", 0750);
2041
	}
2042

    
2043
	/* Check for enabled servers and create server-specific CSC dirs */
2044
	if (is_array($config['openvpn']['openvpn-server'])) {
2045
		foreach ($config['openvpn']['openvpn-server'] as $settings) {
2046
			if (isset($settings['disable'])) {
2047
				continue;
2048
			}
2049
			if (in_array($settings['mode'], $openvpn_tls_server_modes)) {
2050
				if ($settings['vpnid']) {
2051
					safe_mkdir("{$g['varetc_path']}/openvpn-csc/server{$settings['vpnid']}");
2052
				}
2053
			}
2054
		}
2055
	}
2056
}
2057

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

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

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

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

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

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

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

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

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

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

    
2149
function openvpn_get_settings($mode, $vpnid) {
2150
	global $config;
2151

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

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

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

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

    
2176
	return array();
2177
}
2178

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

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

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