Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
188
	$list = array();
189

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

    
194
	return($list);
195
}
196

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

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

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

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

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

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

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

    
243
	return($list);
244
}
245

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

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

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

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

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

    
262
	return($list);
263
}
264

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

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

    
274
	$non_server_list = array();
275

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

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

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

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

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

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

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

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

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

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

    
338
	return($list);
339
}
340

    
341
function openvpn_create_key() {
342

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

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

    
351
	return $rslt;
352
}
353

    
354
function openvpn_create_dhparams($bits) {
355

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

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

    
364
	return $rslt;
365
}
366

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

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

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

    
386
	return false;
387
}
388

    
389
function openvpn_vpnid_next() {
390

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

    
396
	return $vpnid;
397
}
398

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

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

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

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

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

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

    
437
	return 0;
438
}
439

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

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

    
450
	return $port;
451
}
452

    
453
function openvpn_get_cipherlist() {
454

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

    
467
function openvpn_get_curvelist() {
468

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1112
	// client specific settings
1113

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1227
			unset($ca, $param);
1228

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

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

    
1300
			break;
1301
	}
1302

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

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

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

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

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

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

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

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

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

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

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

    
1391
	openvpn_add_custom($settings, $conf);
1392

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1563
	openvpn_add_dhcpopts($settings, $conf);
1564

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

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

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

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

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

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

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

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

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

    
1648
	openvpn_create_dirs();
1649

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

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

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

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

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

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

    
1701
	openvpn_resync_csc_all();
1702

    
1703
}
1704

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1899
			/* Get the client state */
1900
			if (strstr($line, "CONNECTED")) {
1901
				$client['status'] = "up";
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
				$client['remote_host'] = $list[4];
1907
				$client['remote_port'] = $list[5];
1908
				$client['local_host'] = $list[6];
1909
				$client['local_port'] = $list[7];
1910
				$client['virtual_addr6'] = $list[8];
1911
			}
1912
			if (strstr($line, "CONNECTING")) {
1913
				$client['status'] = "connecting";
1914
			}
1915
			if (strstr($line, "ASSIGN_IP")) {
1916
				$client['status'] = "waiting";
1917
				$list = explode(",", $line);
1918

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

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

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

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

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

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

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

    
1965
		fclose($fp);
1966

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

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

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

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

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

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

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

    
2016
	openvpn_create_dirs();
2017

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2191
	return array();
2192
}
2193

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

    
2199
?>
(34-34/60)